diff --git a/cdn/RUNTIMES.json b/cdn/RUNTIMES.json index e19de61..633c534 100644 --- a/cdn/RUNTIMES.json +++ b/cdn/RUNTIMES.json @@ -44,5 +44,14 @@ "detectorSha256": "54882ff7faebb854f79505b4f00313ea9a8ef927741c1501ac60d98022fe356e", "recognizerSha256": "0722ca4a2b9e76b37f3e0d32b78bb1d9afd5d040d219de3560a322c98a966d79" } + }, + "0.8.0": { + "vendoredCommit": "77dcac029e1e351df2d3add687e647463f4b0ce2", + "ortWeb": "1.29.0", + "bundledRelease": { + "id": "862aec0f937da326", + "detectorSha256": "54882ff7faebb854f79505b4f00313ea9a8ef927741c1501ac60d98022fe356e", + "recognizerSha256": "0722ca4a2b9e76b37f3e0d32b78bb1d9afd5d040d219de3560a322c98a966d79" + } } } diff --git a/cdn/requirements.txt b/cdn/requirements.txt index c8c8b6a..7b04b39 100644 --- a/cdn/requirements.txt +++ b/cdn/requirements.txt @@ -1,2 +1,2 @@ # The publishing tool, `cardvision cdn` (the toolkit's docs/cdn.md), with boto3 for the uploads. -cardvision[cdn]==0.10.1 +cardvision[cdn]==0.11.0 diff --git a/docs/store-listing.md b/docs/store-listing.md index 077a614..2639508 100644 --- a/docs/store-listing.md +++ b/docs/store-listing.md @@ -21,6 +21,7 @@ anything. Read the store's current policies before each submission: they change. | 0.5.0 | release `387bdfb29b4b050f` bundled; card details in French, German, Italian, Spanish and Portuguese (the browser's language); the paused-video fix; runtime cardvision 0.5.0rc2 | Public | Chrome: submitted 2026-10-29, replaced by 0.6.0; Firefox: skipped (0.4.0 went straight to 0.6.0) | | 0.6.0 | release `387bdfb29b4b050f` bundled; the session on the toolkit's two-frame contract (pictures stop 60 s after the pointer last moved; a tap opens 10 s); the "Ancient eye" icon and new store images; runtime cardvision 0.6.0rc2 | Public | Chrome: submitted 2026-10-30, live 2026-10-31, replaced by 0.7.0; Firefox: public 2026-10-31, replaced by 0.7.0 | | 0.7.0 | release `387bdfb29b4b050f` bundled; the Card language menu in the popup; the tooltip keeps its picture through a settings refresh and retries a details file that failed; runtime cardvision 0.6.0rc2 (unchanged) | Public | Chrome: submitted 2026-11-09, live 2026-11-09; Firefox: submitted 2026-11-09, public 2026-11-09 | +| 0.8.0 | release `862aec0f937da326` bundled (the 2026-11-10 card update `f3ed25290dde66e9`, converted to a binary bank); a card lying at an angle is outlined and hovered along its own edges; analysis paced from what it costs on the computer, so a slower computer is not kept busy; runtime cardvision 0.11.0 (toolkit main 77dcac0) | Public | Chrome: not yet submitted; Firefox: not yet submitted | Update this table with each submission (date submitted, date approved, store item ID). Chrome's item is `okngcckiafmekbmdgoakggfbicgoagnc`; Firefox's add-on is `duelsight@duelsight.com` diff --git a/package-lock.json b/package-lock.json index ea4ae89..bad4148 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "duelsight", - "version": "0.7.0", + "version": "0.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "duelsight", - "version": "0.7.0", + "version": "0.8.0", "license": "Apache-2.0", "dependencies": { "onnxruntime-web": "1.29.0" diff --git a/package.json b/package.json index e3f05ee..fbaab56 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "duelsight", - "version": "0.7.0", + "version": "0.8.0", "description": "Hover a Yu-Gi-Oh! card in a YouTube or Twitch video to see which card it is. Unofficial fan project, not affiliated with or endorsed by Konami.", "license": "Apache-2.0", "private": true, diff --git a/release-legal/NOTICE b/release-legal/NOTICE index 86af704..99e54a4 100644 --- a/release-legal/NOTICE +++ b/release-legal/NOTICE @@ -1,4 +1,4 @@ -DuelSight Yu-Gi-Oh! models, release T2 (id 387bdfb29b4b050f), converted losslessly from 0927859c6f18302f +DuelSight Yu-Gi-Oh! models, release T2 + cards to 2026-11-10 (id 862aec0f937da326), converted losslessly from f3ed25290dde66e9 Copyright 2026 The DuelSight authors and the cardvision authors The files in the release folder (release.json, detector.onnx, recognizer.onnx, bank.json, diff --git a/release-legal/PROVENANCE.md b/release-legal/PROVENANCE.md index 6171604..cabb570 100644 --- a/release-legal/PROVENANCE.md +++ b/release-legal/PROVENANCE.md @@ -2,7 +2,7 @@ | | | | --- | --- | -| Release | T2, release document id `387bdfb29b4b050f`: T2 (`0927859c6f18302f`) converted with `cardvision convert-release` (toolkit 0.4.0rc2) to a binary bank and a compact catalog. The models, the vectors and the catalog's values are unchanged, so it scores exactly as T2. Game `yugioh`, 14,636 entries in the bank, 14,639 in the catalog | +| Release | T2 + cards to 2026-11-10, release document id `862aec0f937da326`: release `f3ed25290dde66e9` (T2 with the card updates to 2026-11-10, below) converted with `cardvision convert-release` (toolkit 0.11.0) to a binary bank and a compact catalog. The models, the vectors and the catalog's values are unchanged, so it scores exactly as `f3ed25290dde66e9`. Game `yugioh`, 14,636 entries in the bank, 14,639 in the catalog | | Status | Measured on a held-out test before release (docs/accuracy.md). Replaces the early preview release T (`6666477f410559ac`). | | License | Apache-2.0 (LICENSE beside this file); NOTICE says what it does not cover | | Trained by | the DuelSight project, with the open-source cardvision toolkit 0.2.0rc4 (https://github.com/ryangswe/riftsight-vision) | @@ -38,3 +38,7 @@ ## Not included No card art, no video frames, no labels. The card art and the videos belong to their owners. + +## 2026-11-10 (release f3ed25290dde66e9) + +Cards added: 0. Card names updated: 15, to the official English names in YGOPRODeck's card list pulled on 2026-11-10 (11 announced for the TCG, 4 released in Master Duel). Detector, recognizer, accept rule and every bank row are unchanged. diff --git a/src/compute/frame.ts b/src/compute/frame.ts index 2814be4..85a5b63 100644 --- a/src/compute/frame.ts +++ b/src/compute/frame.ts @@ -5,7 +5,8 @@ // pictures it closes. What is DuelSight's own: // - the options it starts with: its message tag, the pages it serves (`allowedParentOrigin`), // the shown card held through short gaps (`SHOWN_HOLD`), turned cards' outlines -// (`rotatedOutlines`), the release it loads; +// (`rotatedOutlines`), analysis paced from its measured cost (`measuredPacing`), the release +// it loads; // - the card facts channel. A card of a remote release goes to the tooltip frame with its facts // over an extension-only channel (`postFacts`), never through the page, and they leave before // the card does. A tooltip frame that lacks a card's facts asks on that channel, and is @@ -67,7 +68,7 @@ export function createFactsChannel(postFacts: (message: CardFactsMessage) => voi } /** What DuelSight's compute frame starts from: the toolkit's options, less the ones it sets. */ -export type DuelSightFrameEnv = Omit & { +export type DuelSightFrameEnv = Omit & { /** `location.ancestorOrigins[0]`: missing, or the string "null" when a referrer policy hides it. */ parentOrigin: string | null | undefined; dev: boolean; @@ -90,6 +91,9 @@ export function computeFrameEnv(env: DuelSightFrameEnv, facts: FactsChannel): Co // A card lying at an angle is hovered and outlined along its own edges, not its upright box // (the shown card then carries `rotation`, `localWidth`, `localHeight`; outline.ts draws them). rotatedOutlines: true, + // Analyses are spaced from what they cost on this computer (a quarter of the time at most by + // default), never faster than the fixed rates: a slow computer is not kept busy analyzing. + measuredPacing: true, onShown: facts.onShown, }; } diff --git a/test/compute-frame.test.ts b/test/compute-frame.test.ts index cf6e0b1..52e1e1d 100644 --- a/test/compute-frame.test.ts +++ b/test/compute-frame.test.ts @@ -65,6 +65,10 @@ describe("compute frame: the pages it serves", () => { }); describe("compute frame: the shown card", () => { + it("paces analysis from its measured cost (measuredPacing is on)", () => { + expect(computeFrameEnv({ ...computeHarness().env }, createFactsChannel(() => undefined)).measuredPacing).toBe(true); + }); + it("asks for turned cards' outlines (rotatedOutlines is on)", () => { expect(computeFrameEnv({ ...computeHarness().env }, createFactsChannel(() => undefined)).rotatedOutlines).toBe(true); }); diff --git a/vendor/cardvision-browser/VENDOR.json b/vendor/cardvision-browser/VENDOR.json index 6dc2f8b..4602fa3 100644 --- a/vendor/cardvision-browser/VENDOR.json +++ b/vendor/cardvision-browser/VENDOR.json @@ -3,8 +3,8 @@ "version": "0.1.0", "license": "Apache-2.0", "source": "cardvision-browser, the browser runtime of the cardvision toolkit (source published with the toolkit release)", - "commit": "8a0f2c269b9df699c38928d9d4da745111469bd7", - "toolkitRelease": "cardvision 0.10.1", + "commit": "77dcac029e1e351df2d3add687e647463f4b0ce2", + "toolkitRelease": "cardvision 0.11.0", "onnxruntimeWeb": "1.29.0", "ortFiles": [ "ort-wasm-simd-threaded.jsep.mjs", diff --git a/vendor/cardvision-browser/cardvision.js b/vendor/cardvision-browser/cardvision.js index 51ed90e..27e639a 100644 --- a/vendor/cardvision-browser/cardvision.js +++ b/vendor/cardvision-browser/cardvision.js @@ -1,4 +1,4 @@ -var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var m3=Object.create,Jo=Object.defineProperty,g3=Object.getOwnPropertyDescriptor,b3=Object.getOwnPropertyNames,y3=Object.getPrototypeOf,w3=Object.prototype.hasOwnProperty,Bu=(e=>typeof jr<"u"?jr:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof jr<"u"?jr:t)[n]}):e)(function(e){if(typeof jr<"u")return jr.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),D=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(i){throw n=[i],i}},ae=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},wn=(e,t)=>{for(var n in t)Jo(e,n,{get:t[n],enumerable:!0})},l0=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of b3(t))!w3.call(e,u)&&u!==n&&Jo(e,u,{get:()=>t[u],enumerable:!(i=g3(t,u))||i.enumerable});return e},be=(e,t,n)=>(n=e!=null?m3(y3(e)):{},l0(t||!e||!e.__esModule?Jo(n,"default",{value:e,enumerable:!0}):n,e)),Nn=e=>l0(Jo({},"__esModule",{value:!0}),e),ri,br,pn,oh,d0,c0=D(()=>{"use strict";ri=new Map,br=[],pn=(e,t,n)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=ri.get(e);if(i===void 0)ri.set(e,{backend:t,priority:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let u=br.indexOf(e);u!==-1&&br.splice(u,1);for(let l=0;l{let t=ri.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return n||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},d0=async e=>{let t=e.executionProviders||[],n=t.map(s=>typeof s=="string"?s:s.name),i=n.length===0?br:n,u,l=[],d=new Set;for(let s of i){let r=await oh(s);typeof r=="string"?l.push({name:s,err:r}):(u||(u=r),u===r&&d.add(s))}if(!u)throw new Error(`no available backend found. ERR: ${l.map(s=>`[${s.name}] ${s.err}`).join(", ")}`);for(let{name:s,err:r}of l)n.includes(s)&&console.warn(`removing requested execution provider "${s}" from session options because it is not available: ${r}`);let c=t.filter(s=>d.has(typeof s=="string"?s:s.name));return[u,new Proxy(e,{get:(s,r)=>r==="executionProviders"?c:Reflect.get(s,r)})]}}),_3=D(()=>{"use strict";c0()}),p0,v3=D(()=>{"use strict";p0="1.29.0"}),aa,st,h0=D(()=>{"use strict";v3(),aa="warning",st={wasm:{},webgl:{},webgpu:{},versions:{common:p0},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);aa=e}},get logLevel(){return aa}},Object.defineProperty(st,"logLevel",{enumerable:!0})}),me,x3=D(()=>{"use strict";h0(),me=st}),f0,m0,$3=D(()=>{"use strict";f0=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let i=n.getContext("2d");if(i!=null){let u,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(u=e.dims[2],l=e.dims[3]):(u=e.dims[3],l=e.dims[2]);let d=t?.format!==void 0?t.format:"RGB",c=t?.norm,s,r;c===void 0||c.mean===void 0?s=[255,255,255,255]:typeof c.mean=="number"?s=[c.mean,c.mean,c.mean,c.mean]:(s=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(s[3]=c.mean[3])),c===void 0||c.bias===void 0?r=[0,0,0,0]:typeof c.bias=="number"?r=[c.bias,c.bias,c.bias,c.bias]:(r=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(r[3]=c.bias[3]));let o=l*u,a=0,p=o,h=o*2,m=-1;d==="RGBA"?(a=0,p=o,h=o*2,m=o*3):d==="RGB"?(a=0,p=o,h=o*2):d==="RBG"&&(a=0,h=o,p=o*2);for(let g=0;g{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(n!=null){let u,l,d;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(u=e.dims[2],l=e.dims[1],d=e.dims[3]):(u=e.dims[3],l=e.dims[2],d=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",s=t?.norm,r,o;s===void 0||s.mean===void 0?r=[255,255,255,255]:typeof s.mean=="number"?r=[s.mean,s.mean,s.mean,s.mean]:(r=[s.mean[0],s.mean[1],s.mean[2],255],s.mean[3]!==void 0&&(r[3]=s.mean[3])),s===void 0||s.bias===void 0?o=[0,0,0,0]:typeof s.bias=="number"?o=[s.bias,s.bias,s.bias,s.bias]:(o=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(o[3]=s.bias[3]));let a=l*u;if(t!==void 0&&(t.format!==void 0&&d===4&&t.format!=="RGBA"||d===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let p=4,h=0,m=1,g=2,_=3,w=0,y=a,T=a*2,S=-1;c==="RGBA"?(w=0,y=a,T=a*2,S=a*3):c==="RGB"?(w=0,y=a,T=a*2):c==="RBG"&&(w=0,T=a,y=a*2),i=n.createImageData(u,l);for(let O=0;O{"use strict";ql(),yo=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:n,width:i}=t,u=t.norm??{mean:255,bias:0},l,d;typeof u.mean=="number"?l=[u.mean,u.mean,u.mean,u.mean]:l=[u.mean[0],u.mean[1],u.mean[2],u.mean[3]??255],typeof u.bias=="number"?d=[u.bias,u.bias,u.bias,u.bias]:d=[u.bias[0],u.bias[1],u.bias[2],u.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",s=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",r=n*i,o=s==="RGBA"?new Float32Array(r*4):new Float32Array(r*3),a=4,p=0,h=1,m=2,g=3,_=0,w=r,y=r*2,T=-1;c==="RGB"&&(a=3,p=0,h=1,m=2,g=-1),s==="RGBA"?T=r*3:s==="RBG"?(_=0,y=r,w=r*2):s==="BGR"&&(y=0,w=r,_=r*2);for(let S=0;S{let n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,u=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string",d,c=t??{},s=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},r=o=>typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas?o.getContext("2d"):null;if(n){let o=s();o.width=e.width,o.height=e.height;let a=r(o);if(a!=null){let p=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(p=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=p,c.width=h}else c.tensorFormat="RGBA",c.height=p,c.width=h;a.drawImage(e,0,0),d=a.getImageData(0,0,h,p).data}else throw new Error("Can not access image data")}else if(i){let o,a;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(o=t.resizedHeight,a=t.resizedWidth):(o=e.height,a=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=o,c.width=a,t!==void 0){let p=s();p.width=a,p.height=o;let h=r(p);if(h!=null)h.putImageData(e,0,0),d=h.getImageData(0,0,a,o).data;else throw new Error("Can not access image data")}else d=e.data}else if(u){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let o=s();o.width=e.width,o.height=e.height;let a=r(o);if(a!=null){let p=e.height,h=e.width;return a.drawImage(e,0,0,h,p),d=a.getImageData(0,0,h,p).data,c.height=p,c.width=h,yo(d,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((o,a)=>{let p=s(),h=r(p);if(!e||!h)return a();let m=new Image;m.crossOrigin="Anonymous",m.src=e,m.onload=()=>{p.width=m.width,p.height=m.height,h.drawImage(m,0,0,p.width,p.height);let g=h.getImageData(0,0,p.width,p.height);c.height=p.height,c.width=p.width,o(yo(g.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(d!==void 0)return yo(d,c);throw new Error("Input data provided is not supported - aborted tensor creation")},b0=(e,t)=>{let{width:n,height:i,download:u,dispose:l}=t,d=[1,i,n,4];return new _t({location:"texture",type:"float32",texture:e,dims:d,download:u,dispose:l})},y0=(e,t)=>{let{dataType:n,dims:i,download:u,dispose:l}=t;return new _t({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:i,download:u,dispose:l})},w0=(e,t)=>{let{dataType:n,dims:i,download:u,dispose:l}=t;return new _t({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:i,download:u,dispose:l})},_0=(e,t,n)=>new _t({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),an,wi,ua,v0,S3=D(()=>{"use strict";an=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),wi=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ua=!1,v0=()=>{if(!ua){ua=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;e&&(an.set("int64",BigInt64Array),wi.set(BigInt64Array,"int64")),t&&(an.set("uint64",BigUint64Array),wi.set(BigUint64Array,"uint64")),i?(an.set("float16",n),wi.set(n,"float16")):an.set("float16",Uint16Array)}}}),x0,$0,I3=D(()=>{"use strict";ql(),x0=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new _t(e.type,e.data,t);case"cpu-pinned":return new _t({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new _t({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new _t({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new _t({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),_t,ql=D(()=>{"use strict";$3(),T3(),S3(),I3(),_t=class{constructor(e,t,n){v0();let i,u;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,u=e.dims,e.location){case"cpu-pinned":{let d=an.get(i);if(!d)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=e.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,c;if(typeof e=="string")if(i=e,c=n,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");d=t}else{let s=an.get(e);if(s===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&s===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${s.name} as data.`);e==="uint64"||e==="int64"?d=s.from(t,BigInt):d=s.from(t)}else if(t instanceof s)d=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")d=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&s!==Uint16Array)d=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${s}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let s=typeof e[0];if(s==="string")i="string",d=e;else if(s==="boolean")i="bool",d=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${s}.`)}else if(e instanceof Uint8ClampedArray)i="uint8",d=Uint8Array.from(e);else{let s=wi.get(e.constructor);if(s===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=s,d=e}if(c===void 0)c=[d.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");u=c,this.cpuData=d,this.dataLocation="cpu"}let l=x0(u);if(this.cpuData&&l!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(l/2)===this.cpuData.length))throw new Error(`Tensor's size(${l}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=u,this.size=l}static async fromImage(e,t){return g0(e,t)}static fromTexture(e,t){return b0(e,t)}static fromGpuBuffer(e,t){return y0(e,t)}static fromMLTensor(e,t){return w0(e,t)}static fromPinnedBuffer(e,t,n){return _0(e,t,n)}toDataURL(e){return f0(this,e)}toImageData(e){return m0(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return $0(this,e)}}}),vt,T0=D(()=>{"use strict";ql(),vt=_t}),Lo,la,Jt,Vt,hn,fn,S0=D(()=>{"use strict";h0(),Lo=(e,t)=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.timeStamp(`${e}::ORT::${t}`)},la=(e,t)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let u=0;u{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||la("BEGIN",e)},Vt=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||la("END",e)},hn=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.time(`ORT::${e}`)},fn=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.timeEnd(`ORT::${e}`)}}),I0,O3=D(()=>{"use strict";c0(),T0(),S0(),I0=class O0{constructor(t){this.handler=t}async run(t,n,i){Jt(),hn("InferenceSession.run");let u={},l={};if(typeof t!="object"||t===null||t instanceof vt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof vt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let r of n){if(typeof r!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(r)===-1)throw new RangeError(`'fetches' contains invalid output name: ${r}.`);u[r]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let r=!1,o=Object.getOwnPropertyNames(n);for(let a of this.outputNames)if(o.indexOf(a)!==-1){let p=n[a];(p===null||p instanceof vt)&&(r=!0,d=!1,u[a]=p)}if(r){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let r of this.inputNames)if(typeof t[r]>"u")throw new Error(`input '${r}' is missing in 'feeds'.`);if(d)for(let r of this.outputNames)u[r]=null;let c=await this.handler.run(t,u,l),s={};for(let r in c)if(Object.hasOwnProperty.call(c,r)){let o=c[r];o instanceof vt?s[r]=o:s[r]=new vt(o.type,o.data,o.dims)}return fn("InferenceSession.run"),Vt(),s}async release(){return this.handler.dispose()}static async create(t,n,i,u){Jt(),hn("InferenceSession.create");let l,d={};if(typeof t=="string"){if(l=t,typeof n=="object"&&n!==null)d=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof n=="object"&&n!==null)d=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let o=t,a=0,p=t.byteLength;if(typeof n=="object"&&n!==null)d=n;else if(typeof n=="number"){if(a=n,!Number.isSafeInteger(a))throw new RangeError("'byteOffset' must be an integer.");if(a<0||a>=o.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${o.byteLength}).`);if(p=t.byteLength-a,typeof i=="number"){if(p=i,!Number.isSafeInteger(p))throw new RangeError("'byteLength' must be an integer.");if(p<=0||a+p>o.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${o.byteLength-a}].`);if(typeof u=="object"&&u!==null)d=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");l=new Uint8Array(o,a,p)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,s]=await d0(d),r=await c.createInferenceSessionHandler(l,s);return fn("InferenceSession.create"),Vt(),new O0(r)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Qo,E3=D(()=>{"use strict";O3(),Qo=I0}),A3=D(()=>{"use strict"}),k3=D(()=>{"use strict"}),P3=D(()=>{"use strict"}),C3=D(()=>{"use strict"}),R3={};wn(R3,{InferenceSession:()=>Qo,TRACE:()=>Lo,TRACE_EVENT_BEGIN:()=>hn,TRACE_EVENT_END:()=>fn,TRACE_FUNC_BEGIN:()=>Jt,TRACE_FUNC_END:()=>Vt,Tensor:()=>vt,env:()=>me,registerBackend:()=>pn});var dt=D(()=>{"use strict";_3(),x3(),E3(),T0(),A3(),k3(),S0(),P3(),C3()});function un(e,t,n,i){if(t===void 0)return D3(e);if(n===void 0)wo(e,t,1);else if(typeof n=="number"&&i===void 0)wo(e,t,n);else if(typeof n=="string"&&i===void 0)wo(e,n,1,t);else if(typeof n=="string"&&typeof i=="number")wo(e,n,i,t);else throw new TypeError("input is valid")}function D3(e){return{verbose:un.verbose.bind(null,e),info:un.info.bind(null,e),warning:un.warning.bind(null,e),error:un.error.bind(null,e),fatal:un.fatal.bind(null,e)}}function wo(e,t,n,i){let u=Dn[i||""]||Dn[""];Fu[e]{"use strict";sh=class{log(e,t,n){}},ah=class{log(e,t,n){console.log(`${this.color(e)} ${n?"\x1B[35m"+n+"\x1B[0m ":""}${t}`)}color(e){switch(e){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${e}`)}}},Fu={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},E0={none:new sh,console:new ah},da={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1},Dn={"":da},(e=>{function t(r,o){e("verbose",r,o)}e.verbose=t;function n(r,o){e("info",r,o)}e.info=n;function i(r,o){e("warning",r,o)}e.warning=i;function u(r,o){e("error",r,o)}e.error=u;function l(r,o){e("fatal",r,o)}e.fatal=l;function d(r){Dn={},c("",r||{})}e.reset=d;function c(r,o){if(r==="*")d(o);else{let a=Dn[r]||da;Dn[r]={provider:o.provider||a.provider,minimalSeverity:o.minimalSeverity||a.minimalSeverity,logDateTime:o.logDateTime===void 0?a.logDateTime:o.logDateTime,logSourceLocation:o.logSourceLocation===void 0?a.logSourceLocation:o.logSourceLocation}}}e.set=c;function s(r){let o={};r.logLevel&&(o.minimalSeverity=r.logLevel),c("",o)}e.setWithEnv=s})(un||={}),Je=un,ca=class{constructor(e,t,n,i,u,l){this.category=e,this.name=t,this.startTime=n,this.endCallback=i,this.timer=u,this.ctx=l}async end(){return this.endCallback(this)}async checkTimer(){if(this.ctx===void 0||this.timer===void 0)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}},pa=class{constructor(e,t,n,i){this.category=e,this.name=t,this.startTime=n,this.endTime=i}},A0=class{constructor(e,t,n){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=e===void 0?1e4:e,this._flushBatchSize=t===void 0?10:t,this._flushIntervalInMilliseconds=n===void 0?5e3:n}static create(e){return e===void 0?new this:new this(e.maxNumberEvents,e.flushBatchSize,e.flushIntervalInMilliseconds)}start(){this._started=!0,this._timingEvents=[],this._flushTime=ni(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer{d.then(async r=>{u&&await u.end(),c(r)},async r=>{u&&await u.end(),s(r)})});if(!l&&u){let c=u.end();if(c&&typeof c.then=="function")return new Promise((s,r)=>{c.then(()=>{s(d)},o=>{r(o)})})}return d}begin(e,t,n){if(!this._started)throw new Error("profiler is not started yet");if(n===void 0){let i=ni();return this.flush(i),new ca(e,t,i,u=>this.endSync(u))}else{let i=n.beginTimer();return new ca(e,t,0,async u=>this.end(u),i,n)}}async end(e){let t=await e.checkTimer();this._timingEvents.length=this._flushBatchSize||e-this._flushTime>=this._flushIntervalInMilliseconds){for(let t=this._flushPointer;this._flushPointerperformance.now():Date.now});function M3(e,t,n){for(let i of n){let u=i[0],l=i[1],d=i[2],c=i[3],s=i[4];if(e.opType===u){for(let r of t)if((r.domain===l||r.domain==="ai.onnx"&&l==="")&&N3(r.version,d))return{opImpl:c,opInit:s}}}throw new TypeError(`cannot resolve operator '${e.opType}' with opsets: ${t.map(i=>`${i.domain||"ai.onnx"} v${i.version}`).join(", ")}`)}function N3(e,t){if(t.endsWith("+")){let n=Number.parseInt(t.substring(0,t.length-1),10);return!isNaN(n)&&n<=e}else if(t.split("-").length===2){let n=t.split("-"),i=Number.parseInt(n[0],10),u=Number.parseInt(n[1],10);return!isNaN(i)&&!isNaN(u)&&i<=e&&e<=u}else return Number.parseInt(t,10)===e}var z3=D(()=>{"use strict"}),B3=ae(e=>{"use strict";e.__esModule=!0;var t=(function(){function n(i){if(!i)throw new TypeError("Invalid argument; `value` has no value.");this.value=n.EMPTY,i&&n.isGuid(i)&&(this.value=i)}return n.isGuid=function(i){var u=i.toString();return i&&(i instanceof n||n.validator.test(u))},n.create=function(){return new n([n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-"))},n.createEmpty=function(){return new n("emptyguid")},n.parse=function(i){return new n(i)},n.raw=function(){return[n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-")},n.gen=function(i){for(var u="",l=0;l>>=0,(u=0<=e&&e<256)&&(i=ju[e],i)?i:(n=Ce(e,0,!0),u&&(ju[e]=n),n)):(e|=0,(u=-128<=e&&e<128)&&(i=Lu[e],i)?i:(n=Ce(e,e<0?-1:0,!1),u&&(Lu[e]=n),n))}function Rt(e,t){if(isNaN(e))return t?Zt:Ct;if(t){if(e<0)return Zt;if(e>=Uu)return Gu}else{if(e<=-Vu)return pt;if(e+1>=Vu)return qu}return e<0?Rt(-e,t).neg():Ce(e%ln|0,e/ln|0,t)}function Ce(e,t,n){return new ze(e,t,n)}function Gl(e,t,n){if(e.length===0)throw Error("empty string");if(typeof t=="number"?(n=t,t=!1):t=!!t,e==="NaN"||e==="Infinity"||e==="+Infinity"||e==="-Infinity")return t?Zt:Ct;if(n=n||10,n<2||360)throw Error("interior hyphen");if(i===0)return Gl(e.substring(1),t,n).neg();for(var u=Rt(Oi(n,8)),l=Ct,d=0;d{gt=null;try{gt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}ze.prototype.__isLong__,Object.defineProperty(ze.prototype,"__isLong__",{value:!0}),ze.isLong=lt,Lu={},ju={},ze.fromInt=Ur,ze.fromNumber=Rt,ze.fromBits=Ce,Oi=Math.pow,ze.fromString=Gl,ze.fromValue=Et,ha=65536,lh=1<<24,ln=ha*ha,Uu=ln*ln,Vu=Uu/2,fa=Ur(lh),Ct=Ur(0),ze.ZERO=Ct,Zt=Ur(0,!0),ze.UZERO=Zt,Vr=Ur(1),ze.ONE=Vr,ma=Ur(1,!0),ze.UONE=ma,_o=Ur(-1),ze.NEG_ONE=_o,qu=Ce(-1,2147483647,!1),ze.MAX_VALUE=qu,Gu=Ce(-1,-1,!0),ze.MAX_UNSIGNED_VALUE=Gu,pt=Ce(0,-2147483648,!1),ze.MIN_VALUE=pt,Z=ze.prototype,Z.toInt=function(){return this.unsigned?this.low>>>0:this.low},Z.toNumber=function(){return this.unsigned?(this.high>>>0)*ln+(this.low>>>0):this.high*ln+(this.low>>>0)},Z.toString=function(e){if(e=e||10,e<2||36>>0,r=s.toString(e);if(l=c,l.isZero())return r+d;for(;r.length<6;)r="0"+r;d=""+r+d}},Z.getHighBits=function(){return this.high},Z.getHighBitsUnsigned=function(){return this.high>>>0},Z.getLowBits=function(){return this.low},Z.getLowBitsUnsigned=function(){return this.low>>>0},Z.getNumBitsAbs=function(){if(this.isNegative())return this.eq(pt)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&(e&1<>21;return e?this.unsigned?!1:e===-1&&!(this.low===0&&this.high===-2097152):!0},Z.isZero=function(){return this.high===0&&this.low===0},Z.eqz=Z.isZero,Z.isNegative=function(){return!this.unsigned&&this.high<0},Z.isPositive=function(){return this.unsigned||this.high>=0},Z.isOdd=function(){return(this.low&1)===1},Z.isEven=function(){return(this.low&1)===0},Z.equals=function(e){return lt(e)||(e=Et(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low},Z.eq=Z.equals,Z.notEquals=function(e){return!this.eq(e)},Z.neq=Z.notEquals,Z.ne=Z.notEquals,Z.lessThan=function(e){return this.comp(e)<0},Z.lt=Z.lessThan,Z.lessThanOrEqual=function(e){return this.comp(e)<=0},Z.lte=Z.lessThanOrEqual,Z.le=Z.lessThanOrEqual,Z.greaterThan=function(e){return this.comp(e)>0},Z.gt=Z.greaterThan,Z.greaterThanOrEqual=function(e){return this.comp(e)>=0},Z.gte=Z.greaterThanOrEqual,Z.ge=Z.greaterThanOrEqual,Z.compare=function(e){if(lt(e)||(e=Et(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},Z.comp=Z.compare,Z.negate=function(){return!this.unsigned&&this.eq(pt)?pt:this.not().add(Vr)},Z.neg=Z.negate,Z.add=function(e){lt(e)||(e=Et(e));var t=this.high>>>16,n=this.high&65535,i=this.low>>>16,u=this.low&65535,l=e.high>>>16,d=e.high&65535,c=e.low>>>16,s=e.low&65535,r=0,o=0,a=0,p=0;return p+=u+s,a+=p>>>16,p&=65535,a+=i+c,o+=a>>>16,a&=65535,o+=n+d,r+=o>>>16,o&=65535,r+=t+l,r&=65535,Ce(a<<16|p,r<<16|o,this.unsigned)},Z.subtract=function(e){return lt(e)||(e=Et(e)),this.add(e.neg())},Z.sub=Z.subtract,Z.multiply=function(e){if(this.isZero())return this;if(lt(e)||(e=Et(e)),gt){var t=gt.mul(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Zt:Ct;if(this.eq(pt))return e.isOdd()?pt:Ct;if(e.eq(pt))return this.isOdd()?pt:Ct;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(fa)&&e.lt(fa))return Rt(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,i=this.high&65535,u=this.low>>>16,l=this.low&65535,d=e.high>>>16,c=e.high&65535,s=e.low>>>16,r=e.low&65535,o=0,a=0,p=0,h=0;return h+=l*r,p+=h>>>16,h&=65535,p+=u*r,a+=p>>>16,p&=65535,p+=l*s,a+=p>>>16,p&=65535,a+=i*r,o+=a>>>16,a&=65535,a+=u*s,o+=a>>>16,a&=65535,a+=l*c,o+=a>>>16,a&=65535,o+=n*r+i*s+u*c+l*d,o&=65535,Ce(p<<16|h,o<<16|a,this.unsigned)},Z.mul=Z.multiply,Z.divide=function(e){if(lt(e)||(e=Et(e)),e.isZero())throw Error("division by zero");if(gt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?gt.div_u:gt.div_s)(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Zt:Ct;var n,i,u;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Zt;if(e.gt(this.shru(1)))return ma;u=Zt}else{if(this.eq(pt)){if(e.eq(Vr)||e.eq(_o))return pt;if(e.eq(pt))return Vr;var l=this.shr(1);return n=l.div(e).shl(1),n.eq(Ct)?e.isNegative()?Vr:_o:(i=this.sub(e.mul(n)),u=n.add(i.div(e)),u)}else if(e.eq(pt))return this.unsigned?Zt:Ct;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();u=Ct}for(i=this;i.gte(e);){n=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var d=Math.ceil(Math.log(n)/Math.LN2),c=d<=48?1:Oi(2,d-48),s=Rt(n),r=s.mul(e);r.isNegative()||r.gt(i);)n-=c,s=Rt(n,this.unsigned),r=s.mul(e);s.isZero()&&(s=Vr),u=u.add(s),i=i.sub(r)}return u},Z.div=Z.divide,Z.modulo=function(e){if(lt(e)||(e=Et(e)),gt){var t=(this.unsigned?gt.rem_u:gt.rem_s)(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))},Z.mod=Z.modulo,Z.rem=Z.modulo,Z.not=function(){return Ce(~this.low,~this.high,this.unsigned)},Z.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},Z.clz=Z.countLeadingZeros,Z.countTrailingZeros=function(){return this.low?uh(this.low):uh(this.high)+32},Z.ctz=Z.countTrailingZeros,Z.and=function(e){return lt(e)||(e=Et(e)),Ce(this.low&e.low,this.high&e.high,this.unsigned)},Z.or=function(e){return lt(e)||(e=Et(e)),Ce(this.low|e.low,this.high|e.high,this.unsigned)},Z.xor=function(e){return lt(e)||(e=Et(e)),Ce(this.low^e.low,this.high^e.high,this.unsigned)},Z.shiftLeft=function(e){return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Ce(this.low<>>32-e,this.unsigned):Ce(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Ce(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Z.shr=Z.shiftRight,Z.shiftRightUnsigned=function(e){return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Ce(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?Ce(this.high,0,this.unsigned):Ce(this.high>>>e-32,0,this.unsigned)},Z.shru=Z.shiftRightUnsigned,Z.shr_u=Z.shiftRightUnsigned,Z.rotateLeft=function(e){var t;return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Ce(this.high,this.low,this.unsigned):e<32?(t=32-e,Ce(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,Ce(this.high<>>t,this.low<>>t,this.unsigned))},Z.rotl=Z.rotateLeft,Z.rotateRight=function(e){var t;return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Ce(this.high,this.low,this.unsigned):e<32?(t=32-e,Ce(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,Ce(this.low<>>e,this.high<>>e,this.unsigned))},Z.rotr=Z.rotateRight,Z.toSigned=function(){return this.unsigned?Ce(this.low,this.high,!1):this},Z.toUnsigned=function(){return this.unsigned?this:Ce(this.low,this.high,!0)},Z.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Z.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]},Z.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]},ze.fromBytes=function(e,t,n){return n?ze.fromBytesLE(e,t):ze.fromBytesBE(e,t)},ze.fromBytesLE=function(e,t){return new ze(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},ze.fromBytesBE=function(e,t){return new ze(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},typeof BigInt=="function"&&(ze.fromBigInt=function(e,t){var n=Number(BigInt.asIntN(32,e)),i=Number(BigInt.asIntN(32,e>>BigInt(32)));return Ce(n,i,t)},ze.fromValue=function(e,t){return typeof e=="bigint"?ze.fromBigInt(e,t):Et(e,t)},Z.toBigInt=function(){var e=BigInt(this.low>>>0),t=BigInt(this.unsigned?this.high>>>0:this.high);return t<{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ArgType=void 0;var t;(function(n){n[n.INPUT=0]="INPUT",n[n.OUTPUT=1]="OUTPUT"})(t||(e.ArgType=t={}))}),Hl=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SIZE_PREFIX_LENGTH=e.FILE_IDENTIFIER_LENGTH=e.SIZEOF_INT=e.SIZEOF_SHORT=void 0,e.SIZEOF_SHORT=2,e.SIZEOF_INT=4,e.FILE_IDENTIFIER_LENGTH=4,e.SIZE_PREFIX_LENGTH=4}),C0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isLittleEndian=e.float64=e.float32=e.int32=void 0,e.int32=new Int32Array(2),e.float32=new Float32Array(e.int32.buffer),e.float64=new Float64Array(e.int32.buffer),e.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1}),R0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Encoding=void 0;var t;(function(n){n[n.UTF8_BYTES=1]="UTF8_BYTES",n[n.UTF16_STRING=2]="UTF16_STRING"})(t||(e.Encoding=t={}))}),D0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ByteBuffer=void 0;var t=Hl(),n=R0(),i=C0(),u=class M0{constructor(d){this.bytes_=d,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(d){return new M0(new Uint8Array(d))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(d){this.position_=d}capacity(){return this.bytes_.length}readInt8(d){return this.readUint8(d)<<24>>24}readUint8(d){return this.bytes_[d]}readInt16(d){return this.readUint16(d)<<16>>16}readUint16(d){return this.bytes_[d]|this.bytes_[d+1]<<8}readInt32(d){return this.bytes_[d]|this.bytes_[d+1]<<8|this.bytes_[d+2]<<16|this.bytes_[d+3]<<24}readUint32(d){return this.readInt32(d)>>>0}readInt64(d){return BigInt.asIntN(64,BigInt(this.readUint32(d))+(BigInt(this.readUint32(d+4))<>8}writeUint16(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8}writeInt32(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8,this.bytes_[d+2]=c>>16,this.bytes_[d+3]=c>>24}writeUint32(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8,this.bytes_[d+2]=c>>16,this.bytes_[d+3]=c>>24}writeInt64(d,c){this.writeInt32(d,Number(BigInt.asIntN(32,c))),this.writeInt32(d+4,Number(BigInt.asIntN(32,c>>BigInt(32))))}writeUint64(d,c){this.writeUint32(d,Number(BigInt.asUintN(32,c))),this.writeUint32(d+4,Number(BigInt.asUintN(32,c>>BigInt(32))))}writeFloat32(d,c){i.float32[0]=c,this.writeInt32(d,i.int32[0])}writeFloat64(d,c){i.float64[0]=c,this.writeInt32(d,i.int32[i.isLittleEndian?0:1]),this.writeInt32(d+4,i.int32[i.isLittleEndian?1:0])}getBufferIdentifier(){if(this.bytes_.length{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Builder=void 0;var t=D0(),n=Hl(),i=class N0{constructor(l){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null,this.text_encoder=new TextEncoder;let d;l?d=l:d=1024,this.bb=t.ByteBuffer.allocate(d),this.space=d}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(l){this.force_defaults=l}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(l,d){l>this.minalign&&(this.minalign=l);let c=~(this.bb.capacity()-this.space+d)+1&l-1;for(;this.space=0&&this.vtable[d]==0;d--);let c=d+1;for(;d>=0;d--)this.addInt16(this.vtable[d]!=0?l-this.vtable[d]:0);let s=2;this.addInt16(l-this.object_start);let r=(c+s)*n.SIZEOF_SHORT;this.addInt16(r);let o=0,a=this.space;e:for(d=0;d=0;o--)this.writeInt8(r.charCodeAt(o))}this.prep(this.minalign,n.SIZEOF_INT+s),this.addOffset(l),s&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(l,d){this.finish(l,d,!0)}requiredField(l,d){let c=this.bb.capacity()-l,s=c-this.bb.readInt32(c);if(!(d{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Encoding=e.ByteBuffer=e.Builder=e.isLittleEndian=e.int32=e.float64=e.float32=e.SIZE_PREFIX_LENGTH=e.SIZEOF_SHORT=e.SIZEOF_INT=e.FILE_IDENTIFIER_LENGTH=void 0;var t=Hl();Object.defineProperty(e,"FILE_IDENTIFIER_LENGTH",{enumerable:!0,get:function(){return t.FILE_IDENTIFIER_LENGTH}}),Object.defineProperty(e,"SIZEOF_INT",{enumerable:!0,get:function(){return t.SIZEOF_INT}}),Object.defineProperty(e,"SIZEOF_SHORT",{enumerable:!0,get:function(){return t.SIZEOF_SHORT}}),Object.defineProperty(e,"SIZE_PREFIX_LENGTH",{enumerable:!0,get:function(){return t.SIZE_PREFIX_LENGTH}});var n=C0();Object.defineProperty(e,"float32",{enumerable:!0,get:function(){return n.float32}}),Object.defineProperty(e,"float64",{enumerable:!0,get:function(){return n.float64}}),Object.defineProperty(e,"int32",{enumerable:!0,get:function(){return n.int32}}),Object.defineProperty(e,"isLittleEndian",{enumerable:!0,get:function(){return n.isLittleEndian}});var i=F3();Object.defineProperty(e,"Builder",{enumerable:!0,get:function(){return i.Builder}});var u=D0();Object.defineProperty(e,"ByteBuffer",{enumerable:!0,get:function(){return u.ByteBuffer}});var l=R0();Object.defineProperty(e,"Encoding",{enumerable:!0,get:function(){return l.Encoding}})}),z0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AttributeType=void 0;var t;(function(n){n[n.UNDEFINED=0]="UNDEFINED",n[n.FLOAT=1]="FLOAT",n[n.INT=2]="INT",n[n.STRING=3]="STRING",n[n.TENSOR=4]="TENSOR",n[n.GRAPH=5]="GRAPH",n[n.FLOATS=6]="FLOATS",n[n.INTS=7]="INTS",n[n.STRINGS=8]="STRINGS",n[n.TENSORS=9]="TENSORS",n[n.GRAPHS=10]="GRAPHS",n[n.SPARSE_TENSOR=11]="SPARSE_TENSOR",n[n.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(t||(e.AttributeType=t={}))}),F0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.NodeType=void 0;var t;(function(n){n[n.Primitive=0]="Primitive",n[n.Fused=1]="Fused"})(t||(e.NodeType=t={}))}),L0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p=0;a--)r.addOffset(o[a]);return r.endVector()}static startInputsVector(r,o){r.startVector(4,o,4)}static addOutputs(r,o){r.addFieldOffset(9,o,0)}static createOutputsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startOutputsVector(r,o){r.startVector(4,o,4)}static addAttributes(r,o){r.addFieldOffset(10,o,0)}static createAttributesVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startAttributesVector(r,o){r.startVector(4,o,4)}static addInputArgCounts(r,o){r.addFieldOffset(11,o,0)}static createInputArgCountsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addInt32(o[a]);return r.endVector()}static startInputArgCountsVector(r,o){r.startVector(4,o,4)}static addImplicitInputs(r,o){r.addFieldOffset(12,o,0)}static createImplicitInputsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startImplicitInputsVector(r,o){r.startVector(4,o,4)}static endNode(r){return r.endObject()}static createNode(r,o,a,p,h,m,g,_,w,y,T,S,O,A){return ot.startNode(r),ot.addName(r,o),ot.addDocString(r,a),ot.addDomain(r,p),ot.addSinceVersion(r,h),ot.addIndex(r,m),ot.addOpType(r,g),ot.addType(r,_),ot.addExecutionProviderType(r,w),ot.addInputs(r,y),ot.addOutputs(r,T),ot.addAttributes(r,S),ot.addInputArgCounts(r,O),ot.addImplicitInputs(r,A),ot.endNode(r)}};e.Node=c}),j0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.EdgeEnd=void 0;var t=class{constructor(){this.bb=null,this.bb_pos=0}__init(n,i){return this.bb_pos=n,this.bb=i,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static sizeOf(){return 12}static createEdgeEnd(n,i,u,l){return n.prep(4,12),n.writeInt32(l),n.writeInt32(u),n.writeInt32(i),n.offset()}};e.EdgeEnd=t}),U0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o=0;r--)c.addInt32(s[r]);return c.endVector()}static startNodeIndicesVector(c,s){c.startVector(4,s,4)}static addNumInputs(c,s){c.addFieldInt32(1,s,0)}static addNumOutputs(c,s){c.addFieldInt32(2,s,0)}static addHasVariadicInput(c,s){c.addFieldInt8(3,+s,0)}static addHasVariadicOutput(c,s){c.addFieldInt8(4,+s,0)}static addNumVariadicInputs(c,s){c.addFieldInt32(5,s,0)}static addNumVariadicOutputs(c,s){c.addFieldInt32(6,s,0)}static endNodesToOptimizeIndices(c){return c.endObject()}static createNodesToOptimizeIndices(c,s,r,o,a,p,h,m){return kt.startNodesToOptimizeIndices(c),kt.addNodeIndices(c,s),kt.addNumInputs(c,r),kt.addNumOutputs(c,o),kt.addHasVariadicInput(c,a),kt.addHasVariadicOutput(c,p),kt.addNumVariadicInputs(c,h),kt.addNumVariadicOutputs(c,m),kt.endNodesToOptimizeIndices(c)}};e.NodesToOptimizeIndices=l}),q0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startProducedOpIdsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizationRecord(s){return s.endObject()}};e.RuntimeOptimizationRecord=d}),G0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startRuntimeOptimizationRecordsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizationRecordContainerEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createRuntimeOptimizationRecordContainerEntry(s,r,o){return Zr.startRuntimeOptimizationRecordContainerEntry(s),Zr.addOptimizerName(s,r),Zr.addRuntimeOptimizationRecords(s,o),Zr.endRuntimeOptimizationRecordContainerEntry(s)}};e.RuntimeOptimizationRecordContainerEntry=d}),H0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startRecordsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizations(s){return s.endObject()}static createRuntimeOptimizations(s,r){return kn.startRuntimeOptimizations(s),kn.addRecords(s,r),kn.endRuntimeOptimizations(s)}};e.RuntimeOptimizations=d}),es=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TensorDataType=void 0;var t;(function(n){n[n.UNDEFINED=0]="UNDEFINED",n[n.FLOAT=1]="FLOAT",n[n.UINT8=2]="UINT8",n[n.INT8=3]="INT8",n[n.UINT16=4]="UINT16",n[n.INT16=5]="INT16",n[n.INT32=6]="INT32",n[n.INT64=7]="INT64",n[n.STRING=8]="STRING",n[n.BOOL=9]="BOOL",n[n.FLOAT16=10]="FLOAT16",n[n.DOUBLE=11]="DOUBLE",n[n.UINT32=12]="UINT32",n[n.UINT64=13]="UINT64",n[n.COMPLEX64=14]="COMPLEX64",n[n.COMPLEX128=15]="COMPLEX128",n[n.BFLOAT16=16]="BFLOAT16",n[n.FLOAT8E4M3FN=17]="FLOAT8E4M3FN",n[n.FLOAT8E4M3FNUZ=18]="FLOAT8E4M3FNUZ",n[n.FLOAT8E5M2=19]="FLOAT8E5M2",n[n.FLOAT8E5M2FNUZ=20]="FLOAT8E5M2FNUZ"})(t||(e.TensorDataType=t={}))}),ts=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addInt64(r[o]);return s.endVector()}static startDimsVector(s,r){s.startVector(8,r,8)}static addDataType(s,r){s.addFieldInt32(3,r,l.TensorDataType.UNDEFINED)}static addRawData(s,r){s.addFieldOffset(4,r,0)}static createRawDataVector(s,r){s.startVector(1,r.length,1);for(let o=r.length-1;o>=0;o--)s.addInt8(r[o]);return s.endVector()}static startRawDataVector(s,r){s.startVector(1,r,1)}static addStringData(s,r){s.addFieldOffset(5,r,0)}static createStringDataVector(s,r){s.startVector(4,r.length,4);for(let o=r.length-1;o>=0;o--)s.addOffset(r[o]);return s.endVector()}static startStringDataVector(s,r){s.startVector(4,r,4)}static addExternalDataOffset(s,r){s.addFieldInt64(6,r,BigInt("-1"))}static endTensor(s){return s.endObject()}static createTensor(s,r,o,a,p,h,m,g){return Pt.startTensor(s),Pt.addName(s,r),Pt.addDocString(s,o),Pt.addDims(s,a),Pt.addDataType(s,p),Pt.addRawData(s,h),Pt.addStringData(s,m),Pt.addExternalDataOffset(s,g),Pt.endTensor(s)}};e.Tensor=d}),W0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addInt64(r[o]);return s.endVector()}static startDimsVector(s,r){s.startVector(8,r,8)}static endSparseTensor(s){return s.endObject()}};e.SparseTensor=d}),K0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DimensionValueType=void 0;var t;(function(n){n[n.UNKNOWN=0]="UNKNOWN",n[n.VALUE=1]="VALUE",n[n.PARAM=2]="PARAM"})(t||(e.DimensionValueType=t={}))}),Y0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startDimVector(s,r){s.startVector(4,r,4)}static endShape(s){return s.endObject()}static createShape(s,r){return Cn.startShape(s),Cn.addDim(s,r),Cn.endShape(s)}};e.Shape=d}),ew=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TypeInfoValue=void 0,e.unionToTypeInfoValue=l,e.unionListToTypeInfoValue=d;var t=K0(),n=X0(),i=ew(),u;(function(c){c[c.NONE=0]="NONE",c[c.tensor_type=1]="tensor_type",c[c.sequence_type=2]="sequence_type",c[c.map_type=3]="map_type"})(u||(e.TypeInfoValue=u={}));function l(c,s){switch(u[c]){case"NONE":return null;case"tensor_type":return s(new i.TensorTypeAndShape);case"sequence_type":return s(new n.SequenceType);case"map_type":return s(new t.MapType);default:return null}}function d(c,s,r){switch(u[c]){case"NONE":return null;case"tensor_type":return s(r,new i.TensorTypeAndShape);case"sequence_type":return s(r,new n.SequenceType);case"map_type":return s(r,new t.MapType);default:return null}}}),rs=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(p,h,m,g){g===void 0&&(g=m);var _=Object.getOwnPropertyDescriptor(h,m);(!_||("get"in _?!h.__esModule:_.writable||_.configurable))&&(_={enumerable:!0,get:function(){return h[m]}}),Object.defineProperty(p,g,_)}:function(p,h,m,g){g===void 0&&(g=m),p[g]=h[m]}),n=e&&e.__setModuleDefault||(Object.create?function(p,h){Object.defineProperty(p,"default",{enumerable:!0,value:h})}:function(p,h){p.default=h}),i=e&&e.__importStar||(function(){var p=function(h){return p=Object.getOwnPropertyNames||function(m){var g=[];for(var _ in m)Object.prototype.hasOwnProperty.call(m,_)&&(g[g.length]=_);return g},p(h)};return function(h){if(h&&h.__esModule)return h;var m={};if(h!=null)for(var g=p(h),_=0;_=0;g--)h.addOffset(m[g]);return h.endVector()}static startInitializersVector(h,m){h.startVector(4,m,4)}static addNodeArgs(h,m){h.addFieldOffset(1,m,0)}static createNodeArgsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodeArgsVector(h,m){h.startVector(4,m,4)}static addNodes(h,m){h.addFieldOffset(2,m,0)}static createNodesVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodesVector(h,m){h.startVector(4,m,4)}static addMaxNodeIndex(h,m){h.addFieldInt32(3,m,0)}static addNodeEdges(h,m){h.addFieldOffset(4,m,0)}static createNodeEdgesVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodeEdgesVector(h,m){h.startVector(4,m,4)}static addInputs(h,m){h.addFieldOffset(5,m,0)}static createInputsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startInputsVector(h,m){h.startVector(4,m,4)}static addOutputs(h,m){h.addFieldOffset(6,m,0)}static createOutputsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startOutputsVector(h,m){h.startVector(4,m,4)}static addSparseInitializers(h,m){h.addFieldOffset(7,m,0)}static createSparseInitializersVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startSparseInitializersVector(h,m){h.startVector(4,m,4)}static addRuntimeOptimizations(h,m){h.addFieldOffset(8,m,0)}static endGraph(h){return h.endObject()}};e.Graph=a}),nw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(r,o,a,p){p===void 0&&(p=a);var h=Object.getOwnPropertyDescriptor(o,a);(!h||("get"in h?!o.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(r,p,h)}:function(r,o,a,p){p===void 0&&(p=a),r[p]=o[a]}),n=e&&e.__setModuleDefault||(Object.create?function(r,o){Object.defineProperty(r,"default",{enumerable:!0,value:o})}:function(r,o){r.default=o}),i=e&&e.__importStar||(function(){var r=function(o){return r=Object.getOwnPropertyNames||function(a){var p=[];for(var h in a)Object.prototype.hasOwnProperty.call(a,h)&&(p[p.length]=h);return p},r(o)};return function(o){if(o&&o.__esModule)return o;var a={};if(o!=null)for(var p=r(o),h=0;h=0;p--)o.addFloat32(a[p]);return o.endVector()}static startFloatsVector(o,a){o.startVector(4,a,4)}static addInts(o,a){o.addFieldOffset(9,a,0)}static createIntsVector(o,a){o.startVector(8,a.length,8);for(let p=a.length-1;p>=0;p--)o.addInt64(a[p]);return o.endVector()}static startIntsVector(o,a){o.startVector(8,a,8)}static addStrings(o,a){o.addFieldOffset(10,a,0)}static createStringsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startStringsVector(o,a){o.startVector(4,a,4)}static addTensors(o,a){o.addFieldOffset(11,a,0)}static createTensorsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startTensorsVector(o,a){o.startVector(4,a,4)}static addGraphs(o,a){o.addFieldOffset(12,a,0)}static createGraphsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startGraphsVector(o,a){o.startVector(4,a,4)}static endAttribute(o){return o.endObject()}};e.Attribute=s}),iw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o=0;r--)c.addInt32(s[r]);return c.endVector()}static startNodeIndicesVector(c,s){c.startVector(4,s,4)}static addKernelDefHashes(c,s){c.addFieldOffset(1,s,0)}static createKernelDefHashesVector(c,s){c.startVector(8,s.length,8);for(let r=s.length-1;r>=0;r--)c.addInt64(s[r]);return c.endVector()}static startKernelDefHashesVector(c,s){c.startVector(8,s,8)}static endDeprecatedKernelCreateInfos(c){return c.endObject()}static createDeprecatedKernelCreateInfos(c,s,r){return Jr.startDeprecatedKernelCreateInfos(c),Jr.addNodeIndices(c,s),Jr.addKernelDefHashes(c,r),Jr.endDeprecatedKernelCreateInfos(c)}};e.DeprecatedKernelCreateInfos=l}),L3=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p=0;a--)r.addOffset(o[a]);return r.endVector()}static startSubGraphSessionStatesVector(r,o){r.startVector(4,o,4)}static endDeprecatedSessionState(r){return r.endObject()}static createDeprecatedSessionState(r,o,a){return en.startDeprecatedSessionState(r),en.addKernels(r,o),en.addSubGraphSessionStates(r,a),en.endDeprecatedSessionState(r)}};e.DeprecatedSessionState=c}),aw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startArgsVector(s,r){s.startVector(4,r,4)}static endKernelTypeStrArgsEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createKernelTypeStrArgsEntry(s,r,o){return tn.startKernelTypeStrArgsEntry(s),tn.addKernelTypeStr(s,r),tn.addArgs(s,o),tn.endKernelTypeStrArgsEntry(s)}};e.KernelTypeStrArgsEntry=d}),uw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startKernelTypeStrArgsVector(s,r){s.startVector(4,r,4)}static endOpIdKernelTypeStrArgsEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createOpIdKernelTypeStrArgsEntry(s,r,o){return rn.startOpIdKernelTypeStrArgsEntry(s),rn.addOpId(s,r),rn.addKernelTypeStrArgs(s,o),rn.endOpIdKernelTypeStrArgsEntry(s)}};e.OpIdKernelTypeStrArgsEntry=d}),lw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startOpKernelTypeStrArgsVector(s,r){s.startVector(4,r,4)}static endKernelTypeStrResolver(s){return s.endObject()}static createKernelTypeStrResolver(s,r){return Rn.startKernelTypeStrResolver(s),Rn.addOpKernelTypeStrArgs(s,r),Rn.endKernelTypeStrResolver(s)}};e.KernelTypeStrResolver=d}),dw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(r,o,a,p){p===void 0&&(p=a);var h=Object.getOwnPropertyDescriptor(o,a);(!h||("get"in h?!o.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(r,p,h)}:function(r,o,a,p){p===void 0&&(p=a),r[p]=o[a]}),n=e&&e.__setModuleDefault||(Object.create?function(r,o){Object.defineProperty(r,"default",{enumerable:!0,value:o})}:function(r,o){r.default=o}),i=e&&e.__importStar||(function(){var r=function(o){return r=Object.getOwnPropertyNames||function(a){var p=[];for(var h in a)Object.prototype.hasOwnProperty.call(a,h)&&(p[p.length]=h);return p},r(o)};return function(o){if(o&&o.__esModule)return o;var a={};if(o!=null)for(var p=r(o),h=0;h=0;p--)o.addOffset(a[p]);return o.endVector()}static startOpsetImportVector(o,a){o.startVector(4,a,4)}static addProducerName(o,a){o.addFieldOffset(2,a,0)}static addProducerVersion(o,a){o.addFieldOffset(3,a,0)}static addDomain(o,a){o.addFieldOffset(4,a,0)}static addModelVersion(o,a){o.addFieldInt64(5,a,BigInt("0"))}static addDocString(o,a){o.addFieldOffset(6,a,0)}static addGraph(o,a){o.addFieldOffset(7,a,0)}static addGraphDocString(o,a){o.addFieldOffset(8,a,0)}static addMetadataProps(o,a){o.addFieldOffset(9,a,0)}static createMetadataPropsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startMetadataPropsVector(o,a){o.startVector(4,a,4)}static endModel(o){return o.endObject()}};e.Model=s}),j3=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";U3=be(P0()),V3=be(z0()),rl=be(nw()),jt=be(B0()),q3=be(iw()),G3=be(L3()),H3=be(sw()),W3=be(ow()),K3=be(J0()),X3=be(Y0()),Z3=be(Z0()),Y3=be(j0()),hw=be(Wl()),fw=be(j3()),J3=be(aw()),Q3=be(lw()),eO=be(K0()),tO=be(pw()),mw=be(L0()),rO=be(U0()),nO=be(F0()),iO=be(V0()),oO=be(uw()),sO=be(dw()),aO=be(q0()),uO=be(G0()),lO=be(H0()),dO=be(X0()),cO=be(Q0()),pO=be(W0()),hO=be(cw()),fO=be(ts()),No=be(es()),gw=be(ew()),mO=be(rs()),bw=be(tw()),gO=be(rw())}),ns=D(()=>{"use strict";bO()}),yO=ae((e,t)=>{"use strict";t.exports=n;function n(i,u){for(var l=new Array(arguments.length-1),d=0,c=2,s=!0;c{"use strict";var t=e;t.length=function(d){var c=d.length;if(!c)return 0;for(var s=0;--c%4>1&&d.charAt(c)==="=";)++s;return Math.ceil(d.length*3)/4-s};var n=new Array(64),i=new Array(123);for(u=0;u<64;)i[n[u]=u<26?u+65:u<52?u+71:u<62?u-4:u-59|43]=u++;var u;t.encode=function(d,c,s){for(var r=null,o=[],a=0,p=0,h;c>2],h=(m&3)<<4,p=1;break;case 1:o[a++]=n[h|m>>4],h=(m&15)<<2,p=2;break;case 2:o[a++]=n[h|m>>6],o[a++]=n[m&63],p=0;break}a>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,o)),a=0)}return p&&(o[a++]=n[h],o[a++]=61,p===1&&(o[a++]=61)),r?(a&&r.push(String.fromCharCode.apply(String,o.slice(0,a))),r.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var l="invalid encoding";t.decode=function(d,c,s){for(var r=s,o=0,a,p=0;p1)break;if((h=i[h])===void 0)throw Error(l);switch(o){case 0:a=h,o=1;break;case 1:c[s++]=a<<2|(h&48)>>4,a=h,o=2;break;case 2:c[s++]=(a&15)<<4|(h&60)>>2,a=h,o=3;break;case 3:c[s++]=(a&3)<<6|h,o=0;break}}if(o===1)throw Error(l);return s-r},t.test=function(d){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(d)}}),_O=ae((e,t)=>{"use strict";t.exports=n;function n(){this._listeners=Object.create(null)}n.prototype.on=function(i,u,l){return(this._listeners[i]||(this._listeners[i]=[])).push({fn:u,ctx:l||this}),this},n.prototype.off=function(i,u){if(i===void 0)this._listeners=Object.create(null);else if(u===void 0)this._listeners[i]=[];else{var l=this._listeners[i];if(!l)return this;for(var d=0;d{"use strict";t.exports=n(n);function n(c){return typeof Float32Array<"u"?(function(){var s=new Float32Array([-0]),r=new Uint8Array(s.buffer),o=r[3]===128;function a(g,_,w){s[0]=g,_[w]=r[0],_[w+1]=r[1],_[w+2]=r[2],_[w+3]=r[3]}function p(g,_,w){s[0]=g,_[w]=r[3],_[w+1]=r[2],_[w+2]=r[1],_[w+3]=r[0]}c.writeFloatLE=o?a:p,c.writeFloatBE=o?p:a;function h(g,_){return r[0]=g[_],r[1]=g[_+1],r[2]=g[_+2],r[3]=g[_+3],s[0]}function m(g,_){return r[3]=g[_],r[2]=g[_+1],r[1]=g[_+2],r[0]=g[_+3],s[0]}c.readFloatLE=o?h:m,c.readFloatBE=o?m:h})():(function(){function s(o,a,p,h){var m=a<0?1:0;if(m&&(a=-a),a===0)o(1/a>0?0:2147483648,p,h);else if(isNaN(a))o(2143289344,p,h);else if(a>34028234663852886e22)o((m<<31|2139095040)>>>0,p,h);else if(a<11754943508222875e-54)o((m<<31|Math.round(a/1401298464324817e-60))>>>0,p,h);else{var g=Math.floor(Math.log(a)/Math.LN2),_=Math.round(a*Math.pow(2,-g)*8388608)&8388607;o((m<<31|g+127<<23|_)>>>0,p,h)}}c.writeFloatLE=s.bind(null,i),c.writeFloatBE=s.bind(null,u);function r(o,a,p){var h=o(a,p),m=(h>>31)*2+1,g=h>>>23&255,_=h&8388607;return g===255?_?NaN:m*(1/0):g===0?m*1401298464324817e-60*_:m*Math.pow(2,g-150)*(_+8388608)}c.readFloatLE=r.bind(null,l),c.readFloatBE=r.bind(null,d)})(),typeof Float64Array<"u"?(function(){var s=new Float64Array([-0]),r=new Uint8Array(s.buffer),o=r[7]===128;function a(g,_,w){s[0]=g,_[w]=r[0],_[w+1]=r[1],_[w+2]=r[2],_[w+3]=r[3],_[w+4]=r[4],_[w+5]=r[5],_[w+6]=r[6],_[w+7]=r[7]}function p(g,_,w){s[0]=g,_[w]=r[7],_[w+1]=r[6],_[w+2]=r[5],_[w+3]=r[4],_[w+4]=r[3],_[w+5]=r[2],_[w+6]=r[1],_[w+7]=r[0]}c.writeDoubleLE=o?a:p,c.writeDoubleBE=o?p:a;function h(g,_){return r[0]=g[_],r[1]=g[_+1],r[2]=g[_+2],r[3]=g[_+3],r[4]=g[_+4],r[5]=g[_+5],r[6]=g[_+6],r[7]=g[_+7],s[0]}function m(g,_){return r[7]=g[_],r[6]=g[_+1],r[5]=g[_+2],r[4]=g[_+3],r[3]=g[_+4],r[2]=g[_+5],r[1]=g[_+6],r[0]=g[_+7],s[0]}c.readDoubleLE=o?h:m,c.readDoubleBE=o?m:h})():(function(){function s(o,a,p,h,m,g){var _=h<0?1:0;if(_&&(h=-h),h===0)o(0,m,g+a),o(1/h>0?0:2147483648,m,g+p);else if(isNaN(h))o(0,m,g+a),o(2146959360,m,g+p);else if(h>17976931348623157e292)o(0,m,g+a),o((_<<31|2146435072)>>>0,m,g+p);else{var w;if(h<22250738585072014e-324)w=h/5e-324,o(w>>>0,m,g+a),o((_<<31|w/4294967296)>>>0,m,g+p);else{var y=Math.floor(Math.log(h)/Math.LN2);y===1024&&(y=1023),w=h*Math.pow(2,-y),o(w*4503599627370496>>>0,m,g+a),o((_<<31|y+1023<<20|w*1048576&1048575)>>>0,m,g+p)}}}c.writeDoubleLE=s.bind(null,i,0,4),c.writeDoubleBE=s.bind(null,u,4,0);function r(o,a,p,h,m){var g=o(h,m+a),_=o(h,m+p),w=(_>>31)*2+1,y=_>>>20&2047,T=4294967296*(_&1048575)+g;return y===2047?T?NaN:w*(1/0):y===0?w*5e-324*T:w*Math.pow(2,y-1075)*(T+4503599627370496)}c.readDoubleLE=r.bind(null,l,0,4),c.readDoubleBE=r.bind(null,d,4,0)})(),c}function i(c,s,r){s[r]=c&255,s[r+1]=c>>>8&255,s[r+2]=c>>>16&255,s[r+3]=c>>>24}function u(c,s,r){s[r]=c>>>24,s[r+1]=c>>>16&255,s[r+2]=c>>>8&255,s[r+3]=c&255}function l(c,s){return(c[s]|c[s+1]<<8|c[s+2]<<16|c[s+3]<<24)>>>0}function d(c,s){return(c[s]<<24|c[s+1]<<16|c[s+2]<<8|c[s+3])>>>0}}),xO=ae((e,t)=>{"use strict";t.exports=n;function n(i){try{if(typeof Bu!="function")return null;var u=Bu(i);return u&&(u.length||Object.keys(u).length)?u:null}catch{return null}}}),$O=ae(e=>{"use strict";var t=e,n="\uFFFD";t.length=function(i){for(var u=0,l=0,d=0;d=192&&s<224){var r=(s&31)<<6|i[c++]&63;d+=r>=128?String.fromCharCode(r):n}else if(s>=224&&s<240){var o=(s&15)<<12|(i[c++]&63)<<6|i[c++]&63;d+=o>=2048?String.fromCharCode(o):n}else if(s>=240){var a=(s&7)<<18|(i[c++]&63)<<12|(i[c++]&63)<<6|i[c++]&63;a<65536||a>1114111?d+=n:(a-=65536,d+=String.fromCharCode(55296+(a>>10)),d+=String.fromCharCode(56320+(a&1023)))}}return d},t.write=function(i,u,l){for(var d=l,c,s,r=0;r>6|192,u[l++]=c&63|128):(c&64512)===55296&&((s=i.charCodeAt(r+1))&64512)===56320?(c=65536+((c&1023)<<10)+(s&1023),++r,u[l++]=c>>18|240,u[l++]=c>>12&63|128,u[l++]=c>>6&63|128,u[l++]=c&63|128):(u[l++]=c>>12|224,u[l++]=c>>6&63|128,u[l++]=c&63|128);return l-d}}),TO=ae((e,t)=>{"use strict";t.exports=n;function n(i,u,l){var d=l||8192,c=d>>>1,s=null,r=d;return function(o){if(o<1||o>c)return i(o);r+o>d&&(s=i(d),r=0);var a=u.call(s,r,r+=o);return r&7&&(r=(r|7)+1),a}}}),SO=ae((e,t)=>{"use strict";t.exports=i;var n=_n();function i(c,s){this.lo=c>>>0,this.hi=s>>>0}var u=i.zero=new i(0,0);u.toNumber=function(){return 0},u.zzEncode=u.zzDecode=function(){return this},u.length=function(){return 1};var l=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(c){if(c===0)return u;var s=c<0;s&&(c=-c);var r=c>>>0,o=(c-r)/4294967296>>>0;return s&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new i(r,o)},i.from=function(c){if(typeof c=="number")return i.fromNumber(c);if(n.isString(c))if(n.Long)c=n.Long.fromString(c);else return i.fromNumber(parseInt(c,10));return c.low||c.high?new i(c.low>>>0,c.high>>>0):u},i.prototype.toNumber=function(c){if(!c&&this.hi>>>31){var s=~this.lo+1>>>0,r=~this.hi>>>0;return s||(r=r+1>>>0),-(s+r*4294967296)}return this.lo+this.hi*4294967296},i.prototype.toLong=function(c){return n.Long?new n.Long(this.lo|0,this.hi|0,!!c):{low:this.lo|0,high:this.hi|0,unsigned:!!c}};var d=String.prototype.charCodeAt;i.fromHash=function(c){return c===l?u:new i((d.call(c,0)|d.call(c,1)<<8|d.call(c,2)<<16|d.call(c,3)<<24)>>>0,(d.call(c,4)|d.call(c,5)<<8|d.call(c,6)<<16|d.call(c,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var c=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^c)>>>0,this.lo=(this.lo<<1^c)>>>0,this},i.prototype.zzDecode=function(){var c=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^c)>>>0,this.hi=(this.hi>>>1^c)>>>0,this},i.prototype.length=function(){var c=this.lo,s=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?s===0?c<16384?c<128?1:2:c<2097152?3:4:s<16384?s<128?5:6:s<2097152?7:8:r<128?9:10}}),IO=ae((e,t)=>{(function(n,i){function u(l){return l.default||l}typeof define=="function"&&define.amd?define([],function(){var l={};return i(l),u(l)}):typeof e=="object"?(i(e),typeof t=="object"&&(t.exports=u(e))):(function(){var l={};i(l),n.Long=u(l)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:e,function(n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=null;try{i=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function u(v,R,H){this.low=v|0,this.high=R|0,this.unsigned=!!H}u.prototype.__isLong__,Object.defineProperty(u.prototype,"__isLong__",{value:!0});function l(v){return(v&&v.__isLong__)===!0}function d(v){var R=Math.clz32(v&-v);return v?31-R:R}u.isLong=l;var c={},s={};function r(v,R){var H,L,V;return R?(v>>>=0,(V=0<=v&&v<256)&&(L=s[v],L)?L:(H=a(v,0,!0),V&&(s[v]=H),H)):(v|=0,(V=-128<=v&&v<128)&&(L=c[v],L)?L:(H=a(v,v<0?-1:0,!1),V&&(c[v]=H),H))}u.fromInt=r;function o(v,R){if(isNaN(v))return R?A:O;if(R){if(v<0)return A;if(v>=y)return J}else{if(v<=-T)return q;if(v+1>=T)return G}return v<0?o(-v,R).neg():a(v%w|0,v/w|0,R)}u.fromNumber=o;function a(v,R,H){return new u(v,R,H)}u.fromBits=a;var p=Math.pow;function h(v,R,H){if(v.length===0)throw Error("empty string");if(typeof R=="number"?(H=R,R=!1):R=!!R,v==="NaN"||v==="Infinity"||v==="+Infinity"||v==="-Infinity")return R?A:O;if(H=H||10,H<2||360)throw Error("interior hyphen");if(L===0)return h(v.substring(1),R,H).neg();for(var V=o(p(H,8)),K=O,B=0;B>>0:this.low},C.toNumber=function(){return this.unsigned?(this.high>>>0)*w+(this.low>>>0):this.high*w+(this.low>>>0)},C.toString=function(v){if(v=v||10,v<2||36>>0,N=Y.toString(v);if(K=te,K.isZero())return N+B;for(;N.length<6;)N="0"+N;B=""+N+B}},C.getHighBits=function(){return this.high},C.getHighBitsUnsigned=function(){return this.high>>>0},C.getLowBits=function(){return this.low},C.getLowBitsUnsigned=function(){return this.low>>>0},C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(q)?64:this.neg().getNumBitsAbs();for(var v=this.high!=0?this.high:this.low,R=31;R>0&&(v&1<>21;return v?this.unsigned?!1:v===-1&&!(this.low===0&&this.high===-2097152):!0},C.isZero=function(){return this.high===0&&this.low===0},C.eqz=C.isZero,C.isNegative=function(){return!this.unsigned&&this.high<0},C.isPositive=function(){return this.unsigned||this.high>=0},C.isOdd=function(){return(this.low&1)===1},C.isEven=function(){return(this.low&1)===0},C.equals=function(v){return l(v)||(v=m(v)),this.unsigned!==v.unsigned&&this.high>>>31===1&&v.high>>>31===1?!1:this.high===v.high&&this.low===v.low},C.eq=C.equals,C.notEquals=function(v){return!this.eq(v)},C.neq=C.notEquals,C.ne=C.notEquals,C.lessThan=function(v){return this.comp(v)<0},C.lt=C.lessThan,C.lessThanOrEqual=function(v){return this.comp(v)<=0},C.lte=C.lessThanOrEqual,C.le=C.lessThanOrEqual,C.greaterThan=function(v){return this.comp(v)>0},C.gt=C.greaterThan,C.greaterThanOrEqual=function(v){return this.comp(v)>=0},C.gte=C.greaterThanOrEqual,C.ge=C.greaterThanOrEqual,C.compare=function(v){if(l(v)||(v=m(v)),this.eq(v))return 0;var R=this.isNegative(),H=v.isNegative();return R&&!H?-1:!R&&H?1:this.unsigned?v.high>>>0>this.high>>>0||v.high===this.high&&v.low>>>0>this.low>>>0?-1:1:this.sub(v).isNegative()?-1:1},C.comp=C.compare,C.negate=function(){return!this.unsigned&&this.eq(q)?q:this.not().add(P)},C.neg=C.negate,C.add=function(v){l(v)||(v=m(v));var R=this.high>>>16,H=this.high&65535,L=this.low>>>16,V=this.low&65535,K=v.high>>>16,B=v.high&65535,te=v.low>>>16,Y=v.low&65535,N=0,X=0,W=0,re=0;return re+=V+Y,W+=re>>>16,re&=65535,W+=L+te,X+=W>>>16,W&=65535,X+=H+B,N+=X>>>16,X&=65535,N+=R+K,N&=65535,a(W<<16|re,N<<16|X,this.unsigned)},C.subtract=function(v){return l(v)||(v=m(v)),this.add(v.neg())},C.sub=C.subtract,C.multiply=function(v){if(this.isZero())return this;if(l(v)||(v=m(v)),i){var R=i.mul(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}if(v.isZero())return this.unsigned?A:O;if(this.eq(q))return v.isOdd()?q:O;if(v.eq(q))return this.isOdd()?q:O;if(this.isNegative())return v.isNegative()?this.neg().mul(v.neg()):this.neg().mul(v).neg();if(v.isNegative())return this.mul(v.neg()).neg();if(this.lt(S)&&v.lt(S))return o(this.toNumber()*v.toNumber(),this.unsigned);var H=this.high>>>16,L=this.high&65535,V=this.low>>>16,K=this.low&65535,B=v.high>>>16,te=v.high&65535,Y=v.low>>>16,N=v.low&65535,X=0,W=0,re=0,le=0;return le+=K*N,re+=le>>>16,le&=65535,re+=V*N,W+=re>>>16,re&=65535,re+=K*Y,W+=re>>>16,re&=65535,W+=L*N,X+=W>>>16,W&=65535,W+=V*Y,X+=W>>>16,W&=65535,W+=K*te,X+=W>>>16,W&=65535,X+=H*N+L*Y+V*te+K*B,X&=65535,a(re<<16|le,X<<16|W,this.unsigned)},C.mul=C.multiply,C.divide=function(v){if(l(v)||(v=m(v)),v.isZero())throw Error("division by zero");if(i){if(!this.unsigned&&this.high===-2147483648&&v.low===-1&&v.high===-1)return this;var R=(this.unsigned?i.div_u:i.div_s)(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?A:O;var H,L,V;if(this.unsigned){if(v.unsigned||(v=v.toUnsigned()),v.gt(this))return A;if(v.gt(this.shru(1)))return I;V=A}else{if(this.eq(q)){if(v.eq(P)||v.eq(z))return q;if(v.eq(q))return P;var K=this.shr(1);return H=K.div(v).shl(1),H.eq(O)?v.isNegative()?P:z:(L=this.sub(v.mul(H)),V=H.add(L.div(v)),V)}else if(v.eq(q))return this.unsigned?A:O;if(this.isNegative())return v.isNegative()?this.neg().div(v.neg()):this.neg().div(v).neg();if(v.isNegative())return this.div(v.neg()).neg();V=O}for(L=this;L.gte(v);){H=Math.max(1,Math.floor(L.toNumber()/v.toNumber()));for(var B=Math.ceil(Math.log(H)/Math.LN2),te=B<=48?1:p(2,B-48),Y=o(H),N=Y.mul(v);N.isNegative()||N.gt(L);)H-=te,Y=o(H,this.unsigned),N=Y.mul(v);Y.isZero()&&(Y=P),V=V.add(Y),L=L.sub(N)}return V},C.div=C.divide,C.modulo=function(v){if(l(v)||(v=m(v)),i){var R=(this.unsigned?i.rem_u:i.rem_s)(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}return this.sub(this.div(v).mul(v))},C.mod=C.modulo,C.rem=C.modulo,C.not=function(){return a(~this.low,~this.high,this.unsigned)},C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},C.clz=C.countLeadingZeros,C.countTrailingZeros=function(){return this.low?d(this.low):d(this.high)+32},C.ctz=C.countTrailingZeros,C.and=function(v){return l(v)||(v=m(v)),a(this.low&v.low,this.high&v.high,this.unsigned)},C.or=function(v){return l(v)||(v=m(v)),a(this.low|v.low,this.high|v.high,this.unsigned)},C.xor=function(v){return l(v)||(v=m(v)),a(this.low^v.low,this.high^v.high,this.unsigned)},C.shiftLeft=function(v){return l(v)&&(v=v.toInt()),(v&=63)===0?this:v<32?a(this.low<>>32-v,this.unsigned):a(0,this.low<>>v|this.high<<32-v,this.high>>v,this.unsigned):a(this.high>>v-32,this.high>=0?0:-1,this.unsigned)},C.shr=C.shiftRight,C.shiftRightUnsigned=function(v){return l(v)&&(v=v.toInt()),(v&=63)===0?this:v<32?a(this.low>>>v|this.high<<32-v,this.high>>>v,this.unsigned):v===32?a(this.high,0,this.unsigned):a(this.high>>>v-32,0,this.unsigned)},C.shru=C.shiftRightUnsigned,C.shr_u=C.shiftRightUnsigned,C.rotateLeft=function(v){var R;return l(v)&&(v=v.toInt()),(v&=63)===0?this:v===32?a(this.high,this.low,this.unsigned):v<32?(R=32-v,a(this.low<>>R,this.high<>>R,this.unsigned)):(v-=32,R=32-v,a(this.high<>>R,this.low<>>R,this.unsigned))},C.rotl=C.rotateLeft,C.rotateRight=function(v){var R;return l(v)&&(v=v.toInt()),(v&=63)===0?this:v===32?a(this.high,this.low,this.unsigned):v<32?(R=32-v,a(this.high<>>v,this.low<>>v,this.unsigned)):(v-=32,R=32-v,a(this.low<>>v,this.high<>>v,this.unsigned))},C.rotr=C.rotateRight,C.toSigned=function(){return this.unsigned?a(this.low,this.high,!1):this},C.toUnsigned=function(){return this.unsigned?this:a(this.low,this.high,!0)},C.toBytes=function(v){return v?this.toBytesLE():this.toBytesBE()},C.toBytesLE=function(){var v=this.high,R=this.low;return[R&255,R>>>8&255,R>>>16&255,R>>>24,v&255,v>>>8&255,v>>>16&255,v>>>24]},C.toBytesBE=function(){var v=this.high,R=this.low;return[v>>>24,v>>>16&255,v>>>8&255,v&255,R>>>24,R>>>16&255,R>>>8&255,R&255]},u.fromBytes=function(v,R,H){return H?u.fromBytesLE(v,R):u.fromBytesBE(v,R)},u.fromBytesLE=function(v,R){return new u(v[0]|v[1]<<8|v[2]<<16|v[3]<<24,v[4]|v[5]<<8|v[6]<<16|v[7]<<24,R)},u.fromBytesBE=function(v,R){return new u(v[4]<<24|v[5]<<16|v[6]<<8|v[7],v[0]<<24|v[1]<<16|v[2]<<8|v[3],R)},typeof BigInt=="function"&&(u.fromBigInt=function(v,R){var H=Number(BigInt.asIntN(32,v)),L=Number(BigInt.asIntN(32,v>>BigInt(32)));return a(H,L,R)},u.fromValue=function(v,R){return typeof v=="bigint"?u.fromBigInt(v,R):m(v,R)},C.toBigInt=function(){var v=BigInt(this.low>>>0),R=BigInt(this.unsigned?this.high>>>0:this.high);return R<{"use strict";var t=e;t.asPromise=yO(),t.base64=wO(),t.EventEmitter=_O(),t.float=vO(),t.inquire=xO(),t.utf8=$O(),t.pool=TO(),t.LongBits=SO();function n(l){return l==="__proto__"||l==="prototype"||l==="constructor"}t.isUnsafeProperty=n,t.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node),t.global=t.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||e,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(l){return typeof l=="number"&&isFinite(l)&&Math.floor(l)===l},t.isString=function(l){return typeof l=="string"||l instanceof String},t.isObject=function(l){return l&&typeof l=="object"},t.isset=t.isSet=function(l,d){var c=l[d];return c!=null&&Object.hasOwnProperty.call(l,d)?typeof c!="object"||(Array.isArray(c)?c.length:Object.keys(c).length)>0:!1},t.Buffer=(function(){try{var l=t.global.Buffer;return l.prototype.utf8Write?l:null}catch{return null}})(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(l){return typeof l=="number"?t.Buffer?t._Buffer_allocUnsafe(l):new t.Array(l):t.Buffer?t._Buffer_from(l):typeof Uint8Array>"u"?l:new Uint8Array(l)},t.Array=typeof Uint8Array<"u"?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||(function(){try{var l=IO();return l&&l.isLong?l:null}catch{return null}})(),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(l){return l?t.LongBits.from(l).toHash():t.LongBits.zeroHash},t.longFromHash=function(l,d){var c=t.LongBits.fromHash(l);return t.Long?t.Long.fromBits(c.lo,c.hi,d):c.toNumber(!!d)};function i(l){var d=typeof arguments[arguments.length-1]=="boolean",c=d?arguments.length-1:arguments.length;d=d&&arguments[arguments.length-1];for(var s=1;s-1;--r)if(d[s[r]]===1&&this[s[r]]!==void 0&&this[s[r]]!==null)return s[r]}},t.oneOfSetter=function(l){return function(d){for(var c=0;c{"use strict";t.exports=o;var n=_n(),i,u=n.LongBits,l=n.base64,d=n.utf8;function c(y,T,S){this.fn=y,this.len=T,this.next=void 0,this.val=S}function s(){}function r(y){this.head=y.head,this.tail=y.tail,this.len=y.len,this.next=y.states}function o(){this.len=0,this.head=new c(s,0,0),this.tail=this.head,this.states=null}var a=function(){return n.Buffer?function(){return(o.create=function(){return new i})()}:function(){return new o}};o.create=a(),o.alloc=function(y){return new n.Array(y)},n.Array!==Array&&(o.alloc=n.pool(o.alloc,n.Array.prototype.subarray)),o.prototype._push=function(y,T,S){return this.tail=this.tail.next=new c(y,T,S),this.len+=T,this};function p(y,T,S){T[S]=y&255}function h(y,T,S){for(;y>127;)T[S++]=y&127|128,y>>>=7;T[S]=y}function m(y,T){this.len=y,this.next=void 0,this.val=T}m.prototype=Object.create(c.prototype),m.prototype.fn=h,o.prototype.uint32=function(y){return this.len+=(this.tail=this.tail.next=new m((y=y>>>0)<128?1:y<16384?2:y<2097152?3:y<268435456?4:5,y)).len,this},o.prototype.int32=function(y){return(y|=0)<0?this._push(g,10,u.fromNumber(y)):this.uint32(y)},o.prototype.sint32=function(y){return this.uint32((y<<1^y>>31)>>>0)};function g(y,T,S){for(var O=y.lo,A=y.hi;A;)T[S++]=O&127|128,O=(O>>>7|A<<25)>>>0,A>>>=7;for(;O>127;)T[S++]=O&127|128,O=O>>>7;T[S++]=O}o.prototype.uint64=function(y){var T=u.from(y);return this._push(g,T.length(),T)},o.prototype.int64=o.prototype.uint64,o.prototype.sint64=function(y){var T=u.from(y).zzEncode();return this._push(g,T.length(),T)},o.prototype.bool=function(y){return this._push(p,1,y?1:0)};function _(y,T,S){T[S]=y&255,T[S+1]=y>>>8&255,T[S+2]=y>>>16&255,T[S+3]=y>>>24}o.prototype.fixed32=function(y){return this._push(_,4,y>>>0)},o.prototype.sfixed32=o.prototype.fixed32,o.prototype.fixed64=function(y){var T=u.from(y);return this._push(_,4,T.lo)._push(_,4,T.hi)},o.prototype.sfixed64=o.prototype.fixed64,o.prototype.float=function(y){return this._push(n.float.writeFloatLE,4,y)},o.prototype.double=function(y){return this._push(n.float.writeDoubleLE,8,y)};var w=n.Array.prototype.set?function(y,T,S){T.set(y,S)}:function(y,T,S){for(var O=0;O>>0;if(!T)return this._push(p,1,0);if(n.isString(y)){var S=o.alloc(T=l.length(y));l.decode(y,S,0),y=S}return this.uint32(T)._push(w,T,y)},o.prototype.string=function(y){var T=d.length(y);return T?this.uint32(T)._push(d.write,T,y):this._push(p,1,0)},o.prototype.fork=function(){return this.states=new r(this),this.head=this.tail=new c(s,0,0),this.len=0,this},o.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(s,0,0),this.len=0),this},o.prototype.ldelim=function(){var y=this.head,T=this.tail,S=this.len;return this.reset().uint32(S),S&&(this.tail.next=y.next,this.tail=T,this.len+=S),this},o.prototype.finish=function(){for(var y=this.head.next,T=this.constructor.alloc(this.len),S=0;y;)y.fn(y.val,T,S),S+=y.len,y=y.next;return T},o._configure=function(y){i=y,o.create=a(),i._configure()}}),OO=ae((e,t)=>{"use strict";t.exports=u;var n=yw();(u.prototype=Object.create(n.prototype)).constructor=u;var i=_n();function u(){n.call(this)}u._configure=function(){u.alloc=i._Buffer_allocUnsafe,u.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&i.Buffer.prototype.set.name==="set"?function(d,c,s){c.set(d,s)}:function(d,c,s){if(d.copy)d.copy(c,s,0,d.length);else for(var r=0;r>>0;return this.uint32(c),c&&this._push(u.writeBytesBuffer,c,d),this};function l(d,c,s){d.length<40?i.utf8.write(d,c,s):c.utf8Write?c.utf8Write(d,s):c.write(d,s)}u.prototype.string=function(d){var c=i.Buffer.byteLength(d);return this.uint32(c),c&&this._push(l,c,d),this},u._configure()}),ww=ae((e,t)=>{"use strict";t.exports=c;var n=_n(),i,u=n.LongBits,l=n.utf8;function d(h,m){return RangeError("index out of range: "+h.pos+" + "+(m||1)+" > "+h.len)}function c(h){this.buf=h,this.pos=0,this.len=h.length}var s=typeof Uint8Array<"u"?function(h){if(h instanceof Uint8Array||Array.isArray(h))return new c(h);throw Error("illegal buffer")}:function(h){if(Array.isArray(h))return new c(h);throw Error("illegal buffer")},r=function(){return n.Buffer?function(h){return(c.create=function(m){return n.Buffer.isBuffer(m)?new i(m):s(m)})(h)}:s};c.create=r(),c.prototype._slice=n.Array.prototype.subarray||n.Array.prototype.slice,c.prototype.uint32=(function(){var h=4294967295;return function(){if(h=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(h=(h|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return h;if((this.pos+=5)>this.len)throw this.pos=this.len,d(this,10);return h}})(),c.prototype.int32=function(){return this.uint32()|0},c.prototype.sint32=function(){var h=this.uint32();return h>>>1^-(h&1)|0};function o(){var h=new u(0,0),m=0;if(this.len-this.pos>4){for(;m<4;++m)if(h.lo=(h.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h;if(h.lo=(h.lo|(this.buf[this.pos]&127)<<28)>>>0,h.hi=(h.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return h;m=0}else{for(;m<3;++m){if(this.pos>=this.len)throw d(this);if(h.lo=(h.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}return h.lo=(h.lo|(this.buf[this.pos++]&127)<>>0,h}if(this.len-this.pos>4){for(;m<5;++m)if(h.hi=(h.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}else for(;m<5;++m){if(this.pos>=this.len)throw d(this);if(h.hi=(h.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}throw Error("invalid varint encoding")}c.prototype.bool=function(){return this.uint32()!==0};function a(h,m){return(h[m-4]|h[m-3]<<8|h[m-2]<<16|h[m-1]<<24)>>>0}c.prototype.fixed32=function(){if(this.pos+4>this.len)throw d(this,4);return a(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw d(this,4);return a(this.buf,this.pos+=4)|0};function p(){if(this.pos+8>this.len)throw d(this,8);return new u(a(this.buf,this.pos+=4),a(this.buf,this.pos+=4))}c.prototype.float=function(){if(this.pos+4>this.len)throw d(this,4);var h=n.float.readFloatLE(this.buf,this.pos);return this.pos+=4,h},c.prototype.double=function(){if(this.pos+8>this.len)throw d(this,4);var h=n.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,h},c.prototype.bytes=function(){var h=this.uint32(),m=this.pos,g=this.pos+h;if(g>this.len)throw d(this,h);if(this.pos+=h,Array.isArray(this.buf))return this.buf.slice(m,g);if(m===g){var _=n.Buffer;return _?_.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,m,g)},c.prototype.string=function(){var h=this.bytes();return l.read(h,0,h.length)},c.prototype.skip=function(h){if(typeof h=="number"){if(this.pos+h>this.len)throw d(this,h);this.pos+=h}else do if(this.pos>=this.len)throw d(this);while(this.buf[this.pos++]&128);return this},c.recursionLimit=n.recursionLimit,c.prototype.skipType=function(h,m){if(m===void 0&&(m=0),m>c.recursionLimit)throw Error("maximum nesting depth exceeded");switch(h){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(h=this.uint32()&7)!==4;)this.skipType(h,m+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+h+" at offset "+this.pos)}return this},c._configure=function(h){i=h,c.create=r(),i._configure();var m=n.Long?"toLong":"toNumber";n.merge(c.prototype,{int64:function(){return o.call(this)[m](!1)},uint64:function(){return o.call(this)[m](!0)},sint64:function(){return o.call(this).zzDecode()[m](!1)},fixed64:function(){return p.call(this)[m](!0)},sfixed64:function(){return p.call(this)[m](!1)}})}}),EO=ae((e,t)=>{"use strict";t.exports=u;var n=ww();(u.prototype=Object.create(n.prototype)).constructor=u;var i=_n();function u(l){n.call(this,l)}u._configure=function(){i.Buffer&&(u.prototype._slice=i.Buffer.prototype.slice)},u.prototype.string=function(){var l=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+l,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+l,this.len))},u._configure()}),AO=ae((e,t)=>{"use strict";t.exports=i;var n=_n();(i.prototype=Object.create(n.EventEmitter.prototype)).constructor=i;function i(u,l,d){if(typeof u!="function")throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=u,this.requestDelimited=!!l,this.responseDelimited=!!d}i.prototype.rpcCall=function u(l,d,c,s,r){if(!s)throw TypeError("request must be specified");var o=this;if(!r)return n.asPromise(u,o,l,d,c,s);if(!o.rpcImpl){setTimeout(function(){r(Error("already ended"))},0);return}try{return o.rpcImpl(l,d[o.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(a,p){if(a)return o.emit("error",a,l),r(a);if(p===null){o.end(!0);return}if(!(p instanceof c))try{p=c[o.responseDelimited?"decodeDelimited":"decode"](p)}catch(h){return o.emit("error",h,l),r(h)}return o.emit("data",p,l),r(null,p)})}catch(a){o.emit("error",a,l),setTimeout(function(){r(a)},0);return}},i.prototype.end=function(u){return this.rpcImpl&&(u||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}}),kO=ae(e=>{"use strict";var t=e;t.Service=AO()}),PO=ae((e,t)=>{"use strict";t.exports=Object.create(null)}),CO=ae(e=>{"use strict";var t=e;t.build="minimal",t.Writer=yw(),t.BufferWriter=OO(),t.Reader=ww(),t.BufferReader=EO(),t.util=_n(),t.rpc=kO(),t.roots=PO(),t.configure=n;function n(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}n()}),RO=ae((e,t)=>{"use strict";t.exports=CO()}),Ni=ae((e,t)=>{"use strict";var n=RO(),i=n.Reader,u=n.Writer,l=n.util,d=n.roots.default||(n.roots.default={});d.onnx=(function(){var c={};return c.Version=(function(){var s={},r=Object.create(s);return r[s[0]="_START_VERSION"]=0,r[s[1]="IR_VERSION_2017_10_10"]=1,r[s[2]="IR_VERSION_2017_10_30"]=2,r[s[3]="IR_VERSION_2017_11_3"]=3,r[s[4]="IR_VERSION_2019_1_22"]=4,r[s[5]="IR_VERSION_2019_3_18"]=5,r[s[6]="IR_VERSION_2019_9_19"]=6,r[s[7]="IR_VERSION_2020_5_8"]=7,r[s[8]="IR_VERSION_2021_7_30"]=8,r[s[9]="IR_VERSION"]=9,r})(),c.AttributeProto=(function(){function s(r){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],this.sparseTensors=[],this.typeProtos=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.name=r.string();break}case 21:{p.refAttrName=r.string();break}case 13:{p.docString=r.string();break}case 20:{p.type=r.int32();break}case 2:{p.f=r.float();break}case 3:{p.i=r.int64();break}case 4:{p.s=r.bytes();break}case 5:{p.t=d.onnx.TensorProto.decode(r,r.uint32());break}case 6:{p.g=d.onnx.GraphProto.decode(r,r.uint32());break}case 22:{p.sparseTensor=d.onnx.SparseTensorProto.decode(r,r.uint32());break}case 14:{p.tp=d.onnx.TypeProto.decode(r,r.uint32());break}case 7:{if(p.floats&&p.floats.length||(p.floats=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.i.high>>>0).toNumber())),r.s!=null&&(typeof r.s=="string"?l.base64.decode(r.s,o.s=l.newBuffer(l.base64.length(r.s)),0):r.s.length>=0&&(o.s=r.s)),r.t!=null){if(typeof r.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");o.t=d.onnx.TensorProto.fromObject(r.t)}if(r.g!=null){if(typeof r.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");o.g=d.onnx.GraphProto.fromObject(r.g)}if(r.sparseTensor!=null){if(typeof r.sparseTensor!="object")throw TypeError(".onnx.AttributeProto.sparseTensor: object expected");o.sparseTensor=d.onnx.SparseTensorProto.fromObject(r.sparseTensor)}if(r.tp!=null){if(typeof r.tp!="object")throw TypeError(".onnx.AttributeProto.tp: object expected");o.tp=d.onnx.TypeProto.fromObject(r.tp)}if(r.floats){if(!Array.isArray(r.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");o.floats=[];for(var a=0;a>>0,r.ints[a].high>>>0).toNumber())}if(r.strings){if(!Array.isArray(r.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");o.strings=[];for(var a=0;a=0&&(o.strings[a]=r.strings[a])}if(r.tensors){if(!Array.isArray(r.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");o.tensors=[];for(var a=0;a>>0,r.i.high>>>0).toNumber():r.i),r.s!=null&&r.hasOwnProperty("s")&&(a.s=o.bytes===String?l.base64.encode(r.s,0,r.s.length):o.bytes===Array?Array.prototype.slice.call(r.s):r.s),r.t!=null&&r.hasOwnProperty("t")&&(a.t=d.onnx.TensorProto.toObject(r.t,o)),r.g!=null&&r.hasOwnProperty("g")&&(a.g=d.onnx.GraphProto.toObject(r.g,o)),r.floats&&r.floats.length){a.floats=[];for(var h=0;h>>0,r.ints[h].high>>>0).toNumber():r.ints[h]}if(r.strings&&r.strings.length){a.strings=[];for(var h=0;h>>3){case 1:{p.name=r.string();break}case 2:{p.type=d.onnx.TypeProto.decode(r,r.uint32());break}case 3:{p.docString=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.name!=null&&r.hasOwnProperty("name")&&!l.isString(r.name))return"name: string expected";if(r.type!=null&&r.hasOwnProperty("type")){var o=d.onnx.TypeProto.verify(r.type);if(o)return"type."+o}return r.docString!=null&&r.hasOwnProperty("docString")&&!l.isString(r.docString)?"docString: string expected":null},s.fromObject=function(r){if(r instanceof d.onnx.ValueInfoProto)return r;var o=new d.onnx.ValueInfoProto;if(r.name!=null&&(o.name=String(r.name)),r.type!=null){if(typeof r.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");o.type=d.onnx.TypeProto.fromObject(r.type)}return r.docString!=null&&(o.docString=String(r.docString)),o},s.toObject=function(r,o){o||(o={});var a={};return o.defaults&&(a.name="",a.type=null,a.docString=""),r.name!=null&&r.hasOwnProperty("name")&&(a.name=r.name),r.type!=null&&r.hasOwnProperty("type")&&(a.type=d.onnx.TypeProto.toObject(r.type,o)),r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.ValueInfoProto"},s})(),c.NodeProto=(function(){function s(r){if(this.input=[],this.output=[],this.attribute=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.input&&p.input.length||(p.input=[]),p.input.push(r.string());break}case 2:{p.output&&p.output.length||(p.output=[]),p.output.push(r.string());break}case 3:{p.name=r.string();break}case 4:{p.opType=r.string();break}case 7:{p.domain=r.string();break}case 5:{p.attribute&&p.attribute.length||(p.attribute=[]),p.attribute.push(d.onnx.AttributeProto.decode(r,r.uint32()));break}case 6:{p.docString=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.input!=null&&r.hasOwnProperty("input")){if(!Array.isArray(r.input))return"input: array expected";for(var o=0;o>>3){case 1:{p.initialization=d.onnx.GraphProto.decode(r,r.uint32());break}case 2:{p.algorithm=d.onnx.GraphProto.decode(r,r.uint32());break}case 3:{p.initializationBinding&&p.initializationBinding.length||(p.initializationBinding=[]),p.initializationBinding.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}case 4:{p.updateBinding&&p.updateBinding.length||(p.updateBinding=[]),p.updateBinding.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.initialization!=null&&r.hasOwnProperty("initialization")){var o=d.onnx.GraphProto.verify(r.initialization);if(o)return"initialization."+o}if(r.algorithm!=null&&r.hasOwnProperty("algorithm")){var o=d.onnx.GraphProto.verify(r.algorithm);if(o)return"algorithm."+o}if(r.initializationBinding!=null&&r.hasOwnProperty("initializationBinding")){if(!Array.isArray(r.initializationBinding))return"initializationBinding: array expected";for(var a=0;a>>3){case 1:{p.irVersion=r.int64();break}case 8:{p.opsetImport&&p.opsetImport.length||(p.opsetImport=[]),p.opsetImport.push(d.onnx.OperatorSetIdProto.decode(r,r.uint32()));break}case 2:{p.producerName=r.string();break}case 3:{p.producerVersion=r.string();break}case 4:{p.domain=r.string();break}case 5:{p.modelVersion=r.int64();break}case 6:{p.docString=r.string();break}case 7:{p.graph=d.onnx.GraphProto.decode(r,r.uint32());break}case 14:{p.metadataProps&&p.metadataProps.length||(p.metadataProps=[]),p.metadataProps.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}case 20:{p.trainingInfo&&p.trainingInfo.length||(p.trainingInfo=[]),p.trainingInfo.push(d.onnx.TrainingInfoProto.decode(r,r.uint32()));break}case 25:{p.functions&&p.functions.length||(p.functions=[]),p.functions.push(d.onnx.FunctionProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.irVersion!=null&&r.hasOwnProperty("irVersion")&&!l.isInteger(r.irVersion)&&!(r.irVersion&&l.isInteger(r.irVersion.low)&&l.isInteger(r.irVersion.high)))return"irVersion: integer|Long expected";if(r.opsetImport!=null&&r.hasOwnProperty("opsetImport")){if(!Array.isArray(r.opsetImport))return"opsetImport: array expected";for(var o=0;o>>0,r.irVersion.high>>>0).toNumber())),r.opsetImport){if(!Array.isArray(r.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");o.opsetImport=[];for(var a=0;a>>0,r.modelVersion.high>>>0).toNumber())),r.docString!=null&&(o.docString=String(r.docString)),r.graph!=null){if(typeof r.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");o.graph=d.onnx.GraphProto.fromObject(r.graph)}if(r.metadataProps){if(!Array.isArray(r.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");o.metadataProps=[];for(var a=0;a>>0,r.irVersion.high>>>0).toNumber():r.irVersion),r.producerName!=null&&r.hasOwnProperty("producerName")&&(a.producerName=r.producerName),r.producerVersion!=null&&r.hasOwnProperty("producerVersion")&&(a.producerVersion=r.producerVersion),r.domain!=null&&r.hasOwnProperty("domain")&&(a.domain=r.domain),r.modelVersion!=null&&r.hasOwnProperty("modelVersion")&&(typeof r.modelVersion=="number"?a.modelVersion=o.longs===String?String(r.modelVersion):r.modelVersion:a.modelVersion=o.longs===String?l.Long.prototype.toString.call(r.modelVersion):o.longs===Number?new l.LongBits(r.modelVersion.low>>>0,r.modelVersion.high>>>0).toNumber():r.modelVersion),r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),r.graph!=null&&r.hasOwnProperty("graph")&&(a.graph=d.onnx.GraphProto.toObject(r.graph,o)),r.opsetImport&&r.opsetImport.length){a.opsetImport=[];for(var h=0;h>>3){case 1:{p.key=r.string();break}case 2:{p.value=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){return typeof r!="object"||r===null?"object expected":r.key!=null&&r.hasOwnProperty("key")&&!l.isString(r.key)?"key: string expected":r.value!=null&&r.hasOwnProperty("value")&&!l.isString(r.value)?"value: string expected":null},s.fromObject=function(r){if(r instanceof d.onnx.StringStringEntryProto)return r;var o=new d.onnx.StringStringEntryProto;return r.key!=null&&(o.key=String(r.key)),r.value!=null&&(o.value=String(r.value)),o},s.toObject=function(r,o){o||(o={});var a={};return o.defaults&&(a.key="",a.value=""),r.key!=null&&r.hasOwnProperty("key")&&(a.key=r.key),r.value!=null&&r.hasOwnProperty("value")&&(a.value=r.value),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.StringStringEntryProto"},s})(),c.TensorAnnotation=(function(){function s(r){if(this.quantParameterTensorNames=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.tensorName=r.string();break}case 2:{p.quantParameterTensorNames&&p.quantParameterTensorNames.length||(p.quantParameterTensorNames=[]),p.quantParameterTensorNames.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.tensorName!=null&&r.hasOwnProperty("tensorName")&&!l.isString(r.tensorName))return"tensorName: string expected";if(r.quantParameterTensorNames!=null&&r.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(r.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var o=0;o>>3){case 1:{p.node&&p.node.length||(p.node=[]),p.node.push(d.onnx.NodeProto.decode(r,r.uint32()));break}case 2:{p.name=r.string();break}case 5:{p.initializer&&p.initializer.length||(p.initializer=[]),p.initializer.push(d.onnx.TensorProto.decode(r,r.uint32()));break}case 15:{p.sparseInitializer&&p.sparseInitializer.length||(p.sparseInitializer=[]),p.sparseInitializer.push(d.onnx.SparseTensorProto.decode(r,r.uint32()));break}case 10:{p.docString=r.string();break}case 11:{p.input&&p.input.length||(p.input=[]),p.input.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 12:{p.output&&p.output.length||(p.output=[]),p.output.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 13:{p.valueInfo&&p.valueInfo.length||(p.valueInfo=[]),p.valueInfo.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 14:{p.quantizationAnnotation&&p.quantizationAnnotation.length||(p.quantizationAnnotation=[]),p.quantizationAnnotation.push(d.onnx.TensorAnnotation.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.node!=null&&r.hasOwnProperty("node")){if(!Array.isArray(r.node))return"node: array expected";for(var o=0;o>>3){case 1:{if(p.dims&&p.dims.length||(p.dims=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.dims[a].high>>>0).toNumber())}if(r.dataType!=null&&(o.dataType=r.dataType|0),r.segment!=null){if(typeof r.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");o.segment=d.onnx.TensorProto.Segment.fromObject(r.segment)}if(r.floatData){if(!Array.isArray(r.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");o.floatData=[];for(var a=0;a=0&&(o.stringData[a]=r.stringData[a])}if(r.int64Data){if(!Array.isArray(r.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");o.int64Data=[];for(var a=0;a>>0,r.int64Data[a].high>>>0).toNumber())}if(r.name!=null&&(o.name=String(r.name)),r.docString!=null&&(o.docString=String(r.docString)),r.rawData!=null&&(typeof r.rawData=="string"?l.base64.decode(r.rawData,o.rawData=l.newBuffer(l.base64.length(r.rawData)),0):r.rawData.length>=0&&(o.rawData=r.rawData)),r.externalData){if(!Array.isArray(r.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");o.externalData=[];for(var a=0;a>>0,r.uint64Data[a].high>>>0).toNumber(!0))}return o},s.toObject=function(r,o){o||(o={});var a={};if((o.arrays||o.defaults)&&(a.dims=[],a.floatData=[],a.int32Data=[],a.stringData=[],a.int64Data=[],a.doubleData=[],a.uint64Data=[],a.externalData=[]),o.defaults&&(a.dataType=0,a.segment=null,a.name="",o.bytes===String?a.rawData="":(a.rawData=[],o.bytes!==Array&&(a.rawData=l.newBuffer(a.rawData))),a.docString="",a.dataLocation=o.enums===String?"DEFAULT":0),r.dims&&r.dims.length){a.dims=[];for(var p=0;p>>0,r.dims[p].high>>>0).toNumber():r.dims[p]}if(r.dataType!=null&&r.hasOwnProperty("dataType")&&(a.dataType=r.dataType),r.segment!=null&&r.hasOwnProperty("segment")&&(a.segment=d.onnx.TensorProto.Segment.toObject(r.segment,o)),r.floatData&&r.floatData.length){a.floatData=[];for(var p=0;p>>0,r.int64Data[p].high>>>0).toNumber():r.int64Data[p]}if(r.name!=null&&r.hasOwnProperty("name")&&(a.name=r.name),r.rawData!=null&&r.hasOwnProperty("rawData")&&(a.rawData=o.bytes===String?l.base64.encode(r.rawData,0,r.rawData.length):o.bytes===Array?Array.prototype.slice.call(r.rawData):r.rawData),r.doubleData&&r.doubleData.length){a.doubleData=[];for(var p=0;p>>0,r.uint64Data[p].high>>>0).toNumber(!0):r.uint64Data[p]}if(r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),r.externalData&&r.externalData.length){a.externalData=[];for(var p=0;p>>3){case 1:{h.begin=o.int64();break}case 2:{h.end=o.int64();break}default:o.skipType(m&7);break}}return h},r.decodeDelimited=function(o){return o instanceof i||(o=new i(o)),this.decode(o,o.uint32())},r.verify=function(o){return typeof o!="object"||o===null?"object expected":o.begin!=null&&o.hasOwnProperty("begin")&&!l.isInteger(o.begin)&&!(o.begin&&l.isInteger(o.begin.low)&&l.isInteger(o.begin.high))?"begin: integer|Long expected":o.end!=null&&o.hasOwnProperty("end")&&!l.isInteger(o.end)&&!(o.end&&l.isInteger(o.end.low)&&l.isInteger(o.end.high))?"end: integer|Long expected":null},r.fromObject=function(o){if(o instanceof d.onnx.TensorProto.Segment)return o;var a=new d.onnx.TensorProto.Segment;return o.begin!=null&&(l.Long?(a.begin=l.Long.fromValue(o.begin)).unsigned=!1:typeof o.begin=="string"?a.begin=parseInt(o.begin,10):typeof o.begin=="number"?a.begin=o.begin:typeof o.begin=="object"&&(a.begin=new l.LongBits(o.begin.low>>>0,o.begin.high>>>0).toNumber())),o.end!=null&&(l.Long?(a.end=l.Long.fromValue(o.end)).unsigned=!1:typeof o.end=="string"?a.end=parseInt(o.end,10):typeof o.end=="number"?a.end=o.end:typeof o.end=="object"&&(a.end=new l.LongBits(o.end.low>>>0,o.end.high>>>0).toNumber())),a},r.toObject=function(o,a){a||(a={});var p={};if(a.defaults){if(l.Long){var h=new l.Long(0,0,!1);p.begin=a.longs===String?h.toString():a.longs===Number?h.toNumber():h}else p.begin=a.longs===String?"0":0;if(l.Long){var h=new l.Long(0,0,!1);p.end=a.longs===String?h.toString():a.longs===Number?h.toNumber():h}else p.end=a.longs===String?"0":0}return o.begin!=null&&o.hasOwnProperty("begin")&&(typeof o.begin=="number"?p.begin=a.longs===String?String(o.begin):o.begin:p.begin=a.longs===String?l.Long.prototype.toString.call(o.begin):a.longs===Number?new l.LongBits(o.begin.low>>>0,o.begin.high>>>0).toNumber():o.begin),o.end!=null&&o.hasOwnProperty("end")&&(typeof o.end=="number"?p.end=a.longs===String?String(o.end):o.end:p.end=a.longs===String?l.Long.prototype.toString.call(o.end):a.longs===Number?new l.LongBits(o.end.low>>>0,o.end.high>>>0).toNumber():o.end),p},r.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},r.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TensorProto.Segment"},r})(),s.DataLocation=(function(){var r={},o=Object.create(r);return o[r[0]="DEFAULT"]=0,o[r[1]="EXTERNAL"]=1,o})(),s})(),c.SparseTensorProto=(function(){function s(r){if(this.dims=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.values=d.onnx.TensorProto.decode(r,r.uint32());break}case 2:{p.indices=d.onnx.TensorProto.decode(r,r.uint32());break}case 3:{if(p.dims&&p.dims.length||(p.dims=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.dims[a].high>>>0).toNumber())}return o},s.toObject=function(r,o){o||(o={});var a={};if((o.arrays||o.defaults)&&(a.dims=[]),o.defaults&&(a.values=null,a.indices=null),r.values!=null&&r.hasOwnProperty("values")&&(a.values=d.onnx.TensorProto.toObject(r.values,o)),r.indices!=null&&r.hasOwnProperty("indices")&&(a.indices=d.onnx.TensorProto.toObject(r.indices,o)),r.dims&&r.dims.length){a.dims=[];for(var p=0;p>>0,r.dims[p].high>>>0).toNumber():r.dims[p]}return a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.SparseTensorProto"},s})(),c.TensorShapeProto=(function(){function s(r){if(this.dim=[],r)for(var o=Object.keys(r),a=0;a>>3===1?(p.dim&&p.dim.length||(p.dim=[]),p.dim.push(d.onnx.TensorShapeProto.Dimension.decode(r,r.uint32()))):r.skipType(h&7)}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.dim!=null&&r.hasOwnProperty("dim")){if(!Array.isArray(r.dim))return"dim: array expected";for(var o=0;o>>3){case 1:{m.dimValue=a.int64();break}case 2:{m.dimParam=a.string();break}case 3:{m.denotation=a.string();break}default:a.skipType(g&7);break}}return m},r.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},r.verify=function(a){if(typeof a!="object"||a===null)return"object expected";var p={};if(a.dimValue!=null&&a.hasOwnProperty("dimValue")&&(p.value=1,!l.isInteger(a.dimValue)&&!(a.dimValue&&l.isInteger(a.dimValue.low)&&l.isInteger(a.dimValue.high))))return"dimValue: integer|Long expected";if(a.dimParam!=null&&a.hasOwnProperty("dimParam")){if(p.value===1)return"value: multiple values";if(p.value=1,!l.isString(a.dimParam))return"dimParam: string expected"}return a.denotation!=null&&a.hasOwnProperty("denotation")&&!l.isString(a.denotation)?"denotation: string expected":null},r.fromObject=function(a){if(a instanceof d.onnx.TensorShapeProto.Dimension)return a;var p=new d.onnx.TensorShapeProto.Dimension;return a.dimValue!=null&&(l.Long?(p.dimValue=l.Long.fromValue(a.dimValue)).unsigned=!1:typeof a.dimValue=="string"?p.dimValue=parseInt(a.dimValue,10):typeof a.dimValue=="number"?p.dimValue=a.dimValue:typeof a.dimValue=="object"&&(p.dimValue=new l.LongBits(a.dimValue.low>>>0,a.dimValue.high>>>0).toNumber())),a.dimParam!=null&&(p.dimParam=String(a.dimParam)),a.denotation!=null&&(p.denotation=String(a.denotation)),p},r.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.denotation=""),a.dimValue!=null&&a.hasOwnProperty("dimValue")&&(typeof a.dimValue=="number"?h.dimValue=p.longs===String?String(a.dimValue):a.dimValue:h.dimValue=p.longs===String?l.Long.prototype.toString.call(a.dimValue):p.longs===Number?new l.LongBits(a.dimValue.low>>>0,a.dimValue.high>>>0).toNumber():a.dimValue,p.oneofs&&(h.value="dimValue")),a.dimParam!=null&&a.hasOwnProperty("dimParam")&&(h.dimParam=a.dimParam,p.oneofs&&(h.value="dimParam")),a.denotation!=null&&a.hasOwnProperty("denotation")&&(h.denotation=a.denotation),h},r.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},r.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TensorShapeProto.Dimension"},r})(),s})(),c.TypeProto=(function(){function s(o){if(o)for(var a=Object.keys(o),p=0;p>>3){case 1:{h.tensorType=d.onnx.TypeProto.Tensor.decode(o,o.uint32());break}case 4:{h.sequenceType=d.onnx.TypeProto.Sequence.decode(o,o.uint32());break}case 5:{h.mapType=d.onnx.TypeProto.Map.decode(o,o.uint32());break}case 9:{h.optionalType=d.onnx.TypeProto.Optional.decode(o,o.uint32());break}case 8:{h.sparseTensorType=d.onnx.TypeProto.SparseTensor.decode(o,o.uint32());break}case 6:{h.denotation=o.string();break}default:o.skipType(m&7);break}}return h},s.decodeDelimited=function(o){return o instanceof i||(o=new i(o)),this.decode(o,o.uint32())},s.verify=function(o){if(typeof o!="object"||o===null)return"object expected";var a={};if(o.tensorType!=null&&o.hasOwnProperty("tensorType")){a.value=1;{var p=d.onnx.TypeProto.Tensor.verify(o.tensorType);if(p)return"tensorType."+p}}if(o.sequenceType!=null&&o.hasOwnProperty("sequenceType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Sequence.verify(o.sequenceType);if(p)return"sequenceType."+p}}if(o.mapType!=null&&o.hasOwnProperty("mapType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Map.verify(o.mapType);if(p)return"mapType."+p}}if(o.optionalType!=null&&o.hasOwnProperty("optionalType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Optional.verify(o.optionalType);if(p)return"optionalType."+p}}if(o.sparseTensorType!=null&&o.hasOwnProperty("sparseTensorType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.SparseTensor.verify(o.sparseTensorType);if(p)return"sparseTensorType."+p}}return o.denotation!=null&&o.hasOwnProperty("denotation")&&!l.isString(o.denotation)?"denotation: string expected":null},s.fromObject=function(o){if(o instanceof d.onnx.TypeProto)return o;var a=new d.onnx.TypeProto;if(o.tensorType!=null){if(typeof o.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");a.tensorType=d.onnx.TypeProto.Tensor.fromObject(o.tensorType)}if(o.sequenceType!=null){if(typeof o.sequenceType!="object")throw TypeError(".onnx.TypeProto.sequenceType: object expected");a.sequenceType=d.onnx.TypeProto.Sequence.fromObject(o.sequenceType)}if(o.mapType!=null){if(typeof o.mapType!="object")throw TypeError(".onnx.TypeProto.mapType: object expected");a.mapType=d.onnx.TypeProto.Map.fromObject(o.mapType)}if(o.optionalType!=null){if(typeof o.optionalType!="object")throw TypeError(".onnx.TypeProto.optionalType: object expected");a.optionalType=d.onnx.TypeProto.Optional.fromObject(o.optionalType)}if(o.sparseTensorType!=null){if(typeof o.sparseTensorType!="object")throw TypeError(".onnx.TypeProto.sparseTensorType: object expected");a.sparseTensorType=d.onnx.TypeProto.SparseTensor.fromObject(o.sparseTensorType)}return o.denotation!=null&&(a.denotation=String(o.denotation)),a},s.toObject=function(o,a){a||(a={});var p={};return a.defaults&&(p.denotation=""),o.tensorType!=null&&o.hasOwnProperty("tensorType")&&(p.tensorType=d.onnx.TypeProto.Tensor.toObject(o.tensorType,a),a.oneofs&&(p.value="tensorType")),o.sequenceType!=null&&o.hasOwnProperty("sequenceType")&&(p.sequenceType=d.onnx.TypeProto.Sequence.toObject(o.sequenceType,a),a.oneofs&&(p.value="sequenceType")),o.mapType!=null&&o.hasOwnProperty("mapType")&&(p.mapType=d.onnx.TypeProto.Map.toObject(o.mapType,a),a.oneofs&&(p.value="mapType")),o.denotation!=null&&o.hasOwnProperty("denotation")&&(p.denotation=o.denotation),o.sparseTensorType!=null&&o.hasOwnProperty("sparseTensorType")&&(p.sparseTensorType=d.onnx.TypeProto.SparseTensor.toObject(o.sparseTensorType,a),a.oneofs&&(p.value="sparseTensorType")),o.optionalType!=null&&o.hasOwnProperty("optionalType")&&(p.optionalType=d.onnx.TypeProto.Optional.toObject(o.optionalType,a),a.oneofs&&(p.value="optionalType")),p},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TypeProto"},s.Tensor=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.elemType=a.int32();break}case 2:{m.shape=d.onnx.TensorShapeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")&&!l.isInteger(a.elemType))return"elemType: integer expected";if(a.shape!=null&&a.hasOwnProperty("shape")){var p=d.onnx.TensorShapeProto.verify(a.shape);if(p)return"shape."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Tensor)return a;var p=new d.onnx.TypeProto.Tensor;if(a.elemType!=null&&(p.elemType=a.elemType|0),a.shape!=null){if(typeof a.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");p.shape=d.onnx.TensorShapeProto.fromObject(a.shape)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=0,h.shape=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=a.elemType),a.shape!=null&&a.hasOwnProperty("shape")&&(h.shape=d.onnx.TensorShapeProto.toObject(a.shape,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Tensor"},o})(),s.Sequence=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3===1?m.elemType=d.onnx.TypeProto.decode(a,a.uint32()):a.skipType(g&7)}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")){var p=d.onnx.TypeProto.verify(a.elemType);if(p)return"elemType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Sequence)return a;var p=new d.onnx.TypeProto.Sequence;if(a.elemType!=null){if(typeof a.elemType!="object")throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected");p.elemType=d.onnx.TypeProto.fromObject(a.elemType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=d.onnx.TypeProto.toObject(a.elemType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Sequence"},o})(),s.Map=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.keyType=a.int32();break}case 2:{m.valueType=d.onnx.TypeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.keyType!=null&&a.hasOwnProperty("keyType")&&!l.isInteger(a.keyType))return"keyType: integer expected";if(a.valueType!=null&&a.hasOwnProperty("valueType")){var p=d.onnx.TypeProto.verify(a.valueType);if(p)return"valueType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Map)return a;var p=new d.onnx.TypeProto.Map;if(a.keyType!=null&&(p.keyType=a.keyType|0),a.valueType!=null){if(typeof a.valueType!="object")throw TypeError(".onnx.TypeProto.Map.valueType: object expected");p.valueType=d.onnx.TypeProto.fromObject(a.valueType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.keyType=0,h.valueType=null),a.keyType!=null&&a.hasOwnProperty("keyType")&&(h.keyType=a.keyType),a.valueType!=null&&a.hasOwnProperty("valueType")&&(h.valueType=d.onnx.TypeProto.toObject(a.valueType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Map"},o})(),s.Optional=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3===1?m.elemType=d.onnx.TypeProto.decode(a,a.uint32()):a.skipType(g&7)}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")){var p=d.onnx.TypeProto.verify(a.elemType);if(p)return"elemType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Optional)return a;var p=new d.onnx.TypeProto.Optional;if(a.elemType!=null){if(typeof a.elemType!="object")throw TypeError(".onnx.TypeProto.Optional.elemType: object expected");p.elemType=d.onnx.TypeProto.fromObject(a.elemType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=d.onnx.TypeProto.toObject(a.elemType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Optional"},o})(),s.SparseTensor=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.elemType=a.int32();break}case 2:{m.shape=d.onnx.TensorShapeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")&&!l.isInteger(a.elemType))return"elemType: integer expected";if(a.shape!=null&&a.hasOwnProperty("shape")){var p=d.onnx.TensorShapeProto.verify(a.shape);if(p)return"shape."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.SparseTensor)return a;var p=new d.onnx.TypeProto.SparseTensor;if(a.elemType!=null&&(p.elemType=a.elemType|0),a.shape!=null){if(typeof a.shape!="object")throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected");p.shape=d.onnx.TensorShapeProto.fromObject(a.shape)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=0,h.shape=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=a.elemType),a.shape!=null&&a.hasOwnProperty("shape")&&(h.shape=d.onnx.TensorShapeProto.toObject(a.shape,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.SparseTensor"},o})(),s})(),c.OperatorSetIdProto=(function(){function s(r){if(r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.domain=r.string();break}case 2:{p.version=r.int64();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){return typeof r!="object"||r===null?"object expected":r.domain!=null&&r.hasOwnProperty("domain")&&!l.isString(r.domain)?"domain: string expected":r.version!=null&&r.hasOwnProperty("version")&&!l.isInteger(r.version)&&!(r.version&&l.isInteger(r.version.low)&&l.isInteger(r.version.high))?"version: integer|Long expected":null},s.fromObject=function(r){if(r instanceof d.onnx.OperatorSetIdProto)return r;var o=new d.onnx.OperatorSetIdProto;return r.domain!=null&&(o.domain=String(r.domain)),r.version!=null&&(l.Long?(o.version=l.Long.fromValue(r.version)).unsigned=!1:typeof r.version=="string"?o.version=parseInt(r.version,10):typeof r.version=="number"?o.version=r.version:typeof r.version=="object"&&(o.version=new l.LongBits(r.version.low>>>0,r.version.high>>>0).toNumber())),o},s.toObject=function(r,o){o||(o={});var a={};if(o.defaults)if(a.domain="",l.Long){var p=new l.Long(0,0,!1);a.version=o.longs===String?p.toString():o.longs===Number?p.toNumber():p}else a.version=o.longs===String?"0":0;return r.domain!=null&&r.hasOwnProperty("domain")&&(a.domain=r.domain),r.version!=null&&r.hasOwnProperty("version")&&(typeof r.version=="number"?a.version=o.longs===String?String(r.version):r.version:a.version=o.longs===String?l.Long.prototype.toString.call(r.version):o.longs===Number?new l.LongBits(r.version.low>>>0,r.version.high>>>0).toNumber():r.version),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.OperatorSetIdProto"},s})(),c.OperatorStatus=(function(){var s={},r=Object.create(s);return r[s[0]="EXPERIMENTAL"]=0,r[s[1]="STABLE"]=1,r})(),c.FunctionProto=(function(){function s(r){if(this.input=[],this.output=[],this.attribute=[],this.attributeProto=[],this.node=[],this.opsetImport=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.name=r.string();break}case 4:{p.input&&p.input.length||(p.input=[]),p.input.push(r.string());break}case 5:{p.output&&p.output.length||(p.output=[]),p.output.push(r.string());break}case 6:{p.attribute&&p.attribute.length||(p.attribute=[]),p.attribute.push(r.string());break}case 11:{p.attributeProto&&p.attributeProto.length||(p.attributeProto=[]),p.attributeProto.push(d.onnx.AttributeProto.decode(r,r.uint32()));break}case 7:{p.node&&p.node.length||(p.node=[]),p.node.push(d.onnx.NodeProto.decode(r,r.uint32()));break}case 8:{p.docString=r.string();break}case 9:{p.opsetImport&&p.opsetImport.length||(p.opsetImport=[]),p.opsetImport.push(d.onnx.OperatorSetIdProto.decode(r,r.uint32()));break}case 10:{p.domain=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.name!=null&&r.hasOwnProperty("name")&&!l.isString(r.name))return"name: string expected";if(r.input!=null&&r.hasOwnProperty("input")){if(!Array.isArray(r.input))return"input: array expected";for(var o=0;o{"use strict";k0(),Le=be(Ni()),Ln(),_i=class{static arraysEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n1&&o>1)return;c[d-s]=Math.max(r,o)}return c}static index(t,n){let i=new Array(n.length);return vi.fillIndex(t,n,i),i}static fillIndex(t,n,i){let u=t.length-n.length;for(let l=0;l=0;y--)r[y]=_%d[y],_=Math.floor(_/d[y]);m||(vi.fillIndex(r,t.dims,o),p=t.get(o)),g||(vi.fillIndex(r,n.dims,a),h=n.get(a)),s.set(r,i(p,h))}}return s}}static isValidBroadcast(t,n){let i=t.length,u=n.length;if(i>u)return!1;for(let l=1;l<=i;l++)if(t[i-l]!==1&&t[i-l]!==n[u-l])return!1;return!0}static getBroadcastDims(t,n){let i=t.length,u=[];for(let l=0;l1&&c===1&&u.unshift(d)}return u}},_w=class{static getShapeOfGemmResult(e,t,n,i,u){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,d,c;t?(l=e[1],d=e[0]):(l=e[0],d=e[1]);let s=-1;if(i?(c=n[0],s=1):(c=n[1],s=0),n[s]!==d)throw new Error("dimension mismatch");if(l<=0||c<=0||d<=0)throw new Error("invalid shape specified");if(u&&!Qt.isValidBroadcast(u,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,d]}},wt=class ol{static tensorDataTypeFromProto(t){switch(t){case Le.onnx.TensorProto.DataType.INT8:return"int8";case Le.onnx.TensorProto.DataType.UINT8:return"uint8";case Le.onnx.TensorProto.DataType.BOOL:return"bool";case Le.onnx.TensorProto.DataType.INT16:return"int16";case Le.onnx.TensorProto.DataType.UINT16:return"uint16";case Le.onnx.TensorProto.DataType.INT32:return"int32";case Le.onnx.TensorProto.DataType.UINT32:return"uint32";case Le.onnx.TensorProto.DataType.FLOAT:return"float32";case Le.onnx.TensorProto.DataType.DOUBLE:return"float64";case Le.onnx.TensorProto.DataType.STRING:return"string";case Le.onnx.TensorProto.DataType.INT64:return"int32";case Le.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${Le.onnx.TensorProto.DataType[t]}`)}}static tensorDataTypeStringToEnum(t){switch(t){case"int8":return Le.onnx.TensorProto.DataType.INT8;case"uint8":return Le.onnx.TensorProto.DataType.UINT8;case"bool":return Le.onnx.TensorProto.DataType.BOOL;case"int16":return Le.onnx.TensorProto.DataType.INT16;case"uint16":return Le.onnx.TensorProto.DataType.UINT16;case"int32":return Le.onnx.TensorProto.DataType.INT32;case"uint32":return Le.onnx.TensorProto.DataType.UINT32;case"float32":return Le.onnx.TensorProto.DataType.FLOAT;case"float64":return Le.onnx.TensorProto.DataType.DOUBLE;case"string":return Le.onnx.TensorProto.DataType.STRING;case"int64":return Le.onnx.TensorProto.DataType.INT64;case"uint64":return Le.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${t}`)}}static tensorDimsFromProto(t){return t.map(n=>mn.isLong(n)?n.toNumber():n)}static tensorValueTypeFromProto(t){return{tensorType:ol.tensorDataTypeFromProto(t.elemType),shape:{dims:ol.tensorDimsFromProto(t.shape.dim.map(n=>n.dimValue))}}}static tensorDimsFromORTFormat(t){let n=[];for(let i=0;it.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Sr.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Sr.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let u=1;for(let l=n;l=0;--u)i[u]=i[u+1]*t[u+1];return i}static transpose(t){return t.slice().reverse()}static indicesToOffset(t,n,i){i===void 0&&(i=t.length);let u=0;for(let l=0;l=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n))}static incrementIndex(t,n,i){if(n.length===0||t.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(i===void 0)i=n.length;else if(i<=0||i>n.length)throw new Error("Incorrect axis to increment on");for(let u=i-1;u>=0&&(t[u]++,!(t[u]=t.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");u[s]=t[s]}else u[s]=n[s];d*=u[s]}}let c=Sr.size(t);if(l!==-1){if(c%d!==0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t}] Output shape: [${n}]`);u[l]=c/d}else if(d!==c)throw new Error("reshapedDims and originalDims don't have matching sizes");return u}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((u,l)=>u+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,u)=>i===n[u])}static validateDimsAndCalcSize(t){if(t.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let n=1;for(let i of t){if(!Number.isInteger(i))throw new TypeError(`Invalid shape: ${i} is not an integer`);if(i<0||i>2147483647)throw new TypeError(`Invalid shape: length ${i} is not allowed`);n*=i}return n}static flattenShape(t,n){n<0&&(n+=t.length);let i=t.reduce((l,d)=>l*d,1),u=t.slice(n).reduce((l,d)=>l*d,1);return[i/u,u]}static squeezeShape(t,n){let i=new Array;n=Sr.normalizeAxes(n,t.length);for(let u=0;u=0;if(l&&t[u]!==1)throw new Error("squeeze an axis of size different than 1");(n.length===0&&t[u]>1||n.length>0&&!l)&&i.push(t[u])}return i}static unsqueezeShape(t,n){let i=new Array(t.length+n.length);i.fill(0);for(let l=0;l=i.length)throw new Error("'axes' has an out of range axis");if(i[d]!==0)throw new Error("'axes' has a duplicate axis");i[d]=1}let u=0;for(let l=0;l=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c=i[c]||d[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,u,l,d){if(d){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let c=0;c=i+u&&(d-=1)),d}static adjustPadAndReturnShape(t,n,i,u,l,d,c,s,r=0){let o=i*(u-1)+1;if(s&&s!=="NOTSET")switch(s){case"VALID":return l[d]=0,l[c]=0,Ir.computeOutputSize(t-o,n,t,0,r);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let a=(Math.floor((t+n-1)/n)-1)*n+u-t;return l[d]=Math.floor(s==="SAME_LOWER"?(a+1)/2:a/2),l[c]=a-l[d],Ir.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}default:throw new Error("Unsupported AutoPad type")}else return Ir.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}},Ci=-34028234663852886e22,Ri=34028234663852886e22});function DO(e){switch(e){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${e}`)}}function ch(e){switch(e){case ve.onnx.TensorProto.DataType.UINT8:case ve.onnx.TensorProto.DataType.INT8:case ve.onnx.TensorProto.DataType.BOOL:return 1;case ve.onnx.TensorProto.DataType.UINT16:case ve.onnx.TensorProto.DataType.INT16:return 2;case ve.onnx.TensorProto.DataType.FLOAT:case ve.onnx.TensorProto.DataType.INT32:case ve.onnx.TensorProto.DataType.UINT32:return 4;case ve.onnx.TensorProto.DataType.INT64:case ve.onnx.TensorProto.DataType.DOUBLE:case ve.onnx.TensorProto.DataType.UINT64:return 8;default:throw new Error(`cannot calculate sizeof() on type ${ve.onnx.TensorProto.DataType[e]}`)}}function MO(e,t){return new(xw(t))(e)}function xw(e){switch(e){case"bool":case"uint8":return Uint8Array;case"int8":return Int8Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"float32":return Float32Array;case"float64":return Float64Array;default:throw new Error("unspecified error")}}function sl(e,t){if(t===ve.onnx.TensorProto.DataType.INT64||t===No.TensorDataType.INT64){if(e.greaterThanOrEqual(2147483648)||e.lessThan(-2147483648))throw new TypeError("int64 is not supported")}else if(t===ve.onnx.TensorProto.DataType.UINT32||t===No.TensorDataType.UINT32||t===ve.onnx.TensorProto.DataType.UINT64||t===No.TensorDataType.UINT64){if(e.greaterThanOrEqual(4294967296)||e.lessThan(0))throw new TypeError("uint64 is not supported")}else throw new TypeError(`not a LONG type: ${ve.onnx.TensorProto.DataType[t]}`);return e.toNumber()}function ph(e,t,n){switch(t){case ve.onnx.TensorProto.DataType.BOOL:case ve.onnx.TensorProto.DataType.UINT8:return e.getUint8(n);case ve.onnx.TensorProto.DataType.INT8:return e.getInt8(n);case ve.onnx.TensorProto.DataType.UINT16:return e.getUint16(n,!0);case ve.onnx.TensorProto.DataType.INT16:return e.getInt16(n,!0);case ve.onnx.TensorProto.DataType.FLOAT:return e.getFloat32(n,!0);case ve.onnx.TensorProto.DataType.INT32:return e.getInt32(n,!0);case ve.onnx.TensorProto.DataType.UINT32:return e.getUint32(n,!0);case ve.onnx.TensorProto.DataType.INT64:return sl(mn.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!1),t);case ve.onnx.TensorProto.DataType.DOUBLE:return e.getFloat64(n,!0);case ve.onnx.TensorProto.DataType.UINT64:return sl(mn.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!0),t);default:throw new Error(`cannot read from DataView for type ${ve.onnx.TensorProto.DataType[t]}`)}}var hh,ve,xt,Ln=D(()=>{"use strict";hh=be(B3()),k0(),ns(),ve=be(Ni()),Me(),xt=class zo{constructor(t,n,i,u,l,d=hh.Guid.create()){this.dims=t,this.type=n,this.dataProvider=i,this.asyncDataProvider=u,this.cache=l,this.dataId=d,this.size=ye.validateDimsAndCalcSize(t);let c=this.size,s=i===void 0&&u===void 0&&l===void 0;if(l!==void 0&&l.length!==c)throw new RangeError("Input dims doesn't match data length.");if(n==="string"){if(l!==void 0&&(!Array.isArray(l)||!l.every(r=>typeof r=="string")))throw new TypeError("cache should be a string array");s&&(this.cache=new Array(c))}else{if(l!==void 0){let r=xw(n);if(!(l instanceof r))throw new TypeError(`cache should be type ${r.name}`)}if(s){let r=new ArrayBuffer(c*DO(n));this.cache=MO(r,n)}}}get data(){if(this.cache===void 0){let t=this.dataProvider(this.dataId);if(t.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=t}return this.cache}get stringData(){if(this.type!=="string")throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if(this.type!=="string")return this.data;throw new TypeError("type cannot be non-number (string)")}get(t){return this.data[ye.indicesToOffset(t,this.strides)]}set(t,n){this.data[ye.indicesToOffset(t,this.strides)]=n}async getData(){return this.cache===void 0&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=ye.computeStrides(this.dims)),this._strides}static fromProto(t){if(!t)throw new Error("cannot construct Value from an empty tensor");let n=wt.tensorDataTypeFromProto(t.dataType),i=wt.tensorDimsFromProto(t.dims),u=new zo(i,n);if(n==="string")t.stringData.forEach((l,d)=>{u.data[d]=nl(l)});else if(t.rawData&&typeof t.rawData.byteLength=="number"&&t.rawData.byteLength>0){let l=u.data,d=new DataView(t.rawData.buffer,t.rawData.byteOffset,t.rawData.byteLength),c=ch(t.dataType),s=t.rawData.byteLength/c;if(t.rawData.byteLength%c!==0)throw new Error("invalid buffer length");if(l.length!==s)throw new Error("buffer length mismatch");for(let r=0;r0){let l=u.data,d=new DataView(t.rawDataArray().buffer,t.rawDataArray().byteOffset,t.rawDataLength()),c=ch(t.dataType()),s=t.rawDataLength()/c;if(t.rawDataLength()%c!==0)throw new Error("invalid buffer length");if(l.length!==s)throw new Error("buffer length mismatch");for(let r=0;rtypeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var x3=Object.create,es=Object.defineProperty,$3=Object.getOwnPropertyDescriptor,T3=Object.getOwnPropertyNames,S3=Object.getPrototypeOf,I3=Object.prototype.hasOwnProperty,ju=(e=>typeof jr<"u"?jr:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof jr<"u"?jr:t)[n]}):e)(function(e){if(typeof jr<"u")return jr.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')}),D=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(i){throw n=[i],i}},ae=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},wn=(e,t)=>{for(var n in t)es(e,n,{get:t[n],enumerable:!0})},f0=(e,t,n,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of T3(t))!I3.call(e,u)&&u!==n&&es(e,u,{get:()=>t[u],enumerable:!(i=$3(t,u))||i.enumerable});return e},be=(e,t,n)=>(n=e!=null?x3(S3(e)):{},f0(t||!e||!e.__esModule?es(n,"default",{value:e,enumerable:!0}):n,e)),Nn=e=>f0(es({},"__esModule",{value:!0}),e),ii,br,pn,dh,m0,g0=D(()=>{"use strict";ii=new Map,br=[],pn=(e,t,n)=>{if(t&&typeof t.init=="function"&&typeof t.createInferenceSessionHandler=="function"){let i=ii.get(e);if(i===void 0)ii.set(e,{backend:t,priority:n});else{if(i.priority>n)return;if(i.priority===n&&i.backend!==t)throw new Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let u=br.indexOf(e);u!==-1&&br.splice(u,1);for(let l=0;l{let t=ii.get(e);if(!t)return"backend not found.";if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(i){return n||(t.error=`${i}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},m0=async e=>{let t=e.executionProviders||[],n=t.map(s=>typeof s=="string"?s:s.name),i=n.length===0?br:n,u,l=[],d=new Set;for(let s of i){let r=await dh(s);typeof r=="string"?l.push({name:s,err:r}):(u||(u=r),u===r&&d.add(s))}if(!u)throw new Error(`no available backend found. ERR: ${l.map(s=>`[${s.name}] ${s.err}`).join(", ")}`);for(let{name:s,err:r}of l)n.includes(s)&&console.warn(`removing requested execution provider "${s}" from session options because it is not available: ${r}`);let c=t.filter(s=>d.has(typeof s=="string"?s:s.name));return[u,new Proxy(e,{get:(s,r)=>r==="executionProviders"?c:Reflect.get(s,r)})]}}),O3=D(()=>{"use strict";g0()}),b0,E3=D(()=>{"use strict";b0="1.29.0"}),da,st,y0=D(()=>{"use strict";E3(),da="warning",st={wasm:{},webgl:{},webgpu:{},versions:{common:b0},set logLevel(e){if(e!==void 0){if(typeof e!="string"||["verbose","info","warning","error","fatal"].indexOf(e)===-1)throw new Error(`Unsupported logging level: ${e}`);da=e}},get logLevel(){return da}},Object.defineProperty(st,"logLevel",{enumerable:!0})}),me,A3=D(()=>{"use strict";y0(),me=st}),w0,_0,k3=D(()=>{"use strict";w0=(e,t)=>{let n=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let i=n.getContext("2d");if(i!=null){let u,l;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(u=e.dims[2],l=e.dims[3]):(u=e.dims[3],l=e.dims[2]);let d=t?.format!==void 0?t.format:"RGB",c=t?.norm,s,r;c===void 0||c.mean===void 0?s=[255,255,255,255]:typeof c.mean=="number"?s=[c.mean,c.mean,c.mean,c.mean]:(s=[c.mean[0],c.mean[1],c.mean[2],0],c.mean[3]!==void 0&&(s[3]=c.mean[3])),c===void 0||c.bias===void 0?r=[0,0,0,0]:typeof c.bias=="number"?r=[c.bias,c.bias,c.bias,c.bias]:(r=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(r[3]=c.bias[3]));let o=l*u,a=0,p=o,h=o*2,m=-1;d==="RGBA"?(a=0,p=o,h=o*2,m=o*3):d==="RGB"?(a=0,p=o,h=o*2):d==="RBG"&&(a=0,h=o,p=o*2);for(let g=0;g{let n=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),i;if(n!=null){let u,l,d;t?.tensorLayout!==void 0&&t.tensorLayout==="NHWC"?(u=e.dims[2],l=e.dims[1],d=e.dims[3]):(u=e.dims[3],l=e.dims[2],d=e.dims[1]);let c=t!==void 0&&t.format!==void 0?t.format:"RGB",s=t?.norm,r,o;s===void 0||s.mean===void 0?r=[255,255,255,255]:typeof s.mean=="number"?r=[s.mean,s.mean,s.mean,s.mean]:(r=[s.mean[0],s.mean[1],s.mean[2],255],s.mean[3]!==void 0&&(r[3]=s.mean[3])),s===void 0||s.bias===void 0?o=[0,0,0,0]:typeof s.bias=="number"?o=[s.bias,s.bias,s.bias,s.bias]:(o=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(o[3]=s.bias[3]));let a=l*u;if(t!==void 0&&(t.format!==void 0&&d===4&&t.format!=="RGBA"||d===3&&t.format!=="RGB"&&t.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let p=4,h=0,m=1,g=2,_=3,w=0,y=a,T=a*2,S=-1;c==="RGBA"?(w=0,y=a,T=a*2,S=a*3):c==="RGB"?(w=0,y=a,T=a*2):c==="RBG"&&(w=0,T=a,y=a*2),i=n.createImageData(u,l);for(let O=0;O{"use strict";Wl(),_o=(e,t)=>{if(e===void 0)throw new Error("Image buffer must be defined");if(t.height===void 0||t.width===void 0)throw new Error("Image height and width must be defined");if(t.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:n,width:i}=t,u=t.norm??{mean:255,bias:0},l,d;typeof u.mean=="number"?l=[u.mean,u.mean,u.mean,u.mean]:l=[u.mean[0],u.mean[1],u.mean[2],u.mean[3]??255],typeof u.bias=="number"?d=[u.bias,u.bias,u.bias,u.bias]:d=[u.bias[0],u.bias[1],u.bias[2],u.bias[3]??0];let c=t.format!==void 0?t.format:"RGBA",s=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:"RGB",r=n*i,o=s==="RGBA"?new Float32Array(r*4):new Float32Array(r*3),a=4,p=0,h=1,m=2,g=3,_=0,w=r,y=r*2,T=-1;c==="RGB"&&(a=3,p=0,h=1,m=2,g=-1),s==="RGBA"?T=r*3:s==="RBG"?(_=0,y=r,w=r*2):s==="BGR"&&(y=0,w=r,_=r*2);for(let S=0;S{let n=typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement,i=typeof ImageData<"u"&&e instanceof ImageData,u=typeof ImageBitmap<"u"&&e instanceof ImageBitmap,l=typeof e=="string",d,c=t??{},s=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},r=o=>typeof HTMLCanvasElement<"u"&&o instanceof HTMLCanvasElement||o instanceof OffscreenCanvas?o.getContext("2d"):null;if(n){let o=s();o.width=e.width,o.height=e.height;let a=r(o);if(a!=null){let p=e.height,h=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(p=t.resizedHeight,h=t.resizedWidth),t!==void 0){if(c=t,t.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");c.tensorFormat="RGBA",c.height=p,c.width=h}else c.tensorFormat="RGBA",c.height=p,c.width=h;a.drawImage(e,0,0),d=a.getImageData(0,0,h,p).data}else throw new Error("Can not access image data")}else if(i){let o,a;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(o=t.resizedHeight,a=t.resizedWidth):(o=e.height,a=e.width),t!==void 0&&(c=t),c.format="RGBA",c.height=o,c.width=a,t!==void 0){let p=s();p.width=a,p.height=o;let h=r(p);if(h!=null)h.putImageData(e,0,0),d=h.getImageData(0,0,a,o).data;else throw new Error("Can not access image data")}else d=e.data}else if(u){if(t===void 0)throw new Error("Please provide image config with format for Imagebitmap");let o=s();o.width=e.width,o.height=e.height;let a=r(o);if(a!=null){let p=e.height,h=e.width;return a.drawImage(e,0,0,h,p),d=a.getImageData(0,0,h,p).data,c.height=p,c.width=h,_o(d,c)}else throw new Error("Can not access image data")}else{if(l)return new Promise((o,a)=>{let p=s(),h=r(p);if(!e||!h)return a();let m=new Image;m.crossOrigin="Anonymous",m.src=e,m.onload=()=>{p.width=m.width,p.height=m.height,h.drawImage(m,0,0,p.width,p.height);let g=h.getImageData(0,0,p.width,p.height);c.height=p.height,c.width=p.width,o(_o(g.data,c))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(d!==void 0)return _o(d,c);throw new Error("Input data provided is not supported - aborted tensor creation")},x0=(e,t)=>{let{width:n,height:i,download:u,dispose:l}=t,d=[1,i,n,4];return new _t({location:"texture",type:"float32",texture:e,dims:d,download:u,dispose:l})},$0=(e,t)=>{let{dataType:n,dims:i,download:u,dispose:l}=t;return new _t({location:"gpu-buffer",type:n??"float32",gpuBuffer:e,dims:i,download:u,dispose:l})},T0=(e,t)=>{let{dataType:n,dims:i,download:u,dispose:l}=t;return new _t({location:"ml-tensor",type:n??"float32",mlTensor:e,dims:i,download:u,dispose:l})},S0=(e,t,n)=>new _t({location:"cpu-pinned",type:e,data:t,dims:n??[t.length]})}),an,vi,ca,I0,C3=D(()=>{"use strict";an=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),vi=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ca=!1,I0=()=>{if(!ca){ca=!0;let e=typeof BigInt64Array<"u"&&BigInt64Array.from,t=typeof BigUint64Array<"u"&&BigUint64Array.from,n=globalThis.Float16Array,i=typeof n<"u"&&n.from;e&&(an.set("int64",BigInt64Array),vi.set(BigInt64Array,"int64")),t&&(an.set("uint64",BigUint64Array),vi.set(BigUint64Array,"uint64")),i?(an.set("float16",n),vi.set(n,"float16")):an.set("float16",Uint16Array)}}}),O0,E0,R3=D(()=>{"use strict";Wl(),O0=e=>{let t=1;for(let n=0;n{switch(e.location){case"cpu":return new _t(e.type,e.data,t);case"cpu-pinned":return new _t({location:"cpu-pinned",data:e.data,type:e.type,dims:t});case"texture":return new _t({location:"texture",texture:e.texture,type:e.type,dims:t});case"gpu-buffer":return new _t({location:"gpu-buffer",gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case"ml-tensor":return new _t({location:"ml-tensor",mlTensor:e.mlTensor,type:e.type,dims:t});default:throw new Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),_t,Wl=D(()=>{"use strict";k3(),P3(),C3(),R3(),_t=class{constructor(e,t,n){I0();let i,u;if(typeof e=="object"&&"location"in e)switch(this.dataLocation=e.location,i=e.type,u=e.dims,e.location){case"cpu-pinned":{let d=an.get(i);if(!d)throw new TypeError(`unsupported type "${i}" to create tensor from pinned buffer`);if(!(e.data instanceof d))throw new TypeError(`buffer should be of type ${d.name}`);this.cpuData=e.data;break}case"texture":{if(i!=="float32")throw new TypeError(`unsupported type "${i}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break}case"gpu-buffer":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break}case"ml-tensor":{if(i!=="float32"&&i!=="float16"&&i!=="int32"&&i!=="int64"&&i!=="uint32"&&i!=="uint64"&&i!=="int8"&&i!=="uint8"&&i!=="bool"&&i!=="uint4"&&i!=="int4")throw new TypeError(`unsupported type "${i}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let d,c;if(typeof e=="string")if(i=e,c=n,e==="string"){if(!Array.isArray(t))throw new TypeError("A string tensor's data must be a string array.");d=t}else{let s=an.get(e);if(s===void 0)throw new TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e==="float16"&&s===Uint16Array||e==="uint4"||e==="int4")throw new TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${s.name} as data.`);e==="uint64"||e==="int64"?d=s.from(t,BigInt):d=s.from(t)}else if(t instanceof s)d=t;else if(t instanceof Uint8ClampedArray)if(e==="uint8")d=Uint8Array.from(t);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(e==="float16"&&t instanceof Uint16Array&&s!==Uint16Array)d=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw new TypeError(`A ${i} tensor's data must be type of ${s}`)}else if(c=t,Array.isArray(e)){if(e.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let s=typeof e[0];if(s==="string")i="string",d=e;else if(s==="boolean")i="bool",d=Uint8Array.from(e);else throw new TypeError(`Invalid element type of data array: ${s}.`)}else if(e instanceof Uint8ClampedArray)i="uint8",d=Uint8Array.from(e);else{let s=vi.get(e.constructor);if(s===void 0)throw new TypeError(`Unsupported type for tensor data: ${e.constructor}.`);i=s,d=e}if(c===void 0)c=[d.length];else if(!Array.isArray(c))throw new TypeError("A tensor's dims must be a number array");u=c,this.cpuData=d,this.dataLocation="cpu"}let l=O0(u);if(this.cpuData&&l!==this.cpuData.length&&!((i==="uint4"||i==="int4")&&Math.ceil(l/2)===this.cpuData.length))throw new Error(`Tensor's size(${l}) does not match data length(${this.cpuData.length}).`);this.type=i,this.dims=u,this.size=l}static async fromImage(e,t){return v0(e,t)}static fromTexture(e,t){return x0(e,t)}static fromGpuBuffer(e,t){return $0(e,t)}static fromMLTensor(e,t){return T0(e,t)}static fromPinnedBuffer(e,t,n){return S0(e,t,n)}toDataURL(e){return w0(this,e)}toImageData(e){return _0(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return E0(this,e)}}}),vt,A0=D(()=>{"use strict";Wl(),vt=_t}),Uo,pa,Jt,Vt,hn,fn,k0=D(()=>{"use strict";y0(),Uo=(e,t)=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.timeStamp(`${e}::ORT::${t}`)},pa=(e,t)=>{let n=new Error().stack?.split(/\r\n|\r|\n/g)||[],i=!1;for(let u=0;u{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||pa("BEGIN",e)},Vt=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||pa("END",e)},hn=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.time(`ORT::${e}`)},fn=e=>{(typeof st.trace>"u"?!st.wasm.trace:!st.trace)||console.timeEnd(`ORT::${e}`)}}),P0,D3=D(()=>{"use strict";g0(),A0(),k0(),P0=class C0{constructor(t){this.handler=t}async run(t,n,i){Jt(),hn("InferenceSession.run");let u={},l={};if(typeof t!="object"||t===null||t instanceof vt||Array.isArray(t))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let d=!0;if(typeof n=="object"){if(n===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(n instanceof vt)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(n)){if(n.length===0)throw new TypeError("'fetches' cannot be an empty array.");d=!1;for(let r of n){if(typeof r!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(r)===-1)throw new RangeError(`'fetches' contains invalid output name: ${r}.`);u[r]=null}if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else{let r=!1,o=Object.getOwnPropertyNames(n);for(let a of this.outputNames)if(o.indexOf(a)!==-1){let p=n[a];(p===null||p instanceof vt)&&(r=!0,d=!1,u[a]=p)}if(r){if(typeof i=="object"&&i!==null)l=i;else if(typeof i<"u")throw new TypeError("'options' must be an object.")}else l=n}}else if(typeof n<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let r of this.inputNames)if(typeof t[r]>"u")throw new Error(`input '${r}' is missing in 'feeds'.`);if(d)for(let r of this.outputNames)u[r]=null;let c=await this.handler.run(t,u,l),s={};for(let r in c)if(Object.hasOwnProperty.call(c,r)){let o=c[r];o instanceof vt?s[r]=o:s[r]=new vt(o.type,o.data,o.dims)}return fn("InferenceSession.run"),Vt(),s}async release(){return this.handler.dispose()}static async create(t,n,i,u){Jt(),hn("InferenceSession.create");let l,d={};if(typeof t=="string"){if(l=t,typeof n=="object"&&n!==null)d=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof Uint8Array){if(l=t,typeof n=="object"&&n!==null)d=n;else if(typeof n<"u")throw new TypeError("'options' must be an object.")}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer){let o=t,a=0,p=t.byteLength;if(typeof n=="object"&&n!==null)d=n;else if(typeof n=="number"){if(a=n,!Number.isSafeInteger(a))throw new RangeError("'byteOffset' must be an integer.");if(a<0||a>=o.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${o.byteLength}).`);if(p=t.byteLength-a,typeof i=="number"){if(p=i,!Number.isSafeInteger(p))throw new RangeError("'byteLength' must be an integer.");if(p<=0||a+p>o.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${o.byteLength-a}].`);if(typeof u=="object"&&u!==null)d=u;else if(typeof u<"u")throw new TypeError("'options' must be an object.")}else if(typeof i<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof n<"u")throw new TypeError("'options' must be an object.");l=new Uint8Array(o,a,p)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[c,s]=await m0(d),r=await c.createInferenceSessionHandler(l,s);return fn("InferenceSession.create"),Vt(),new C0(r)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),ts,M3=D(()=>{"use strict";D3(),ts=P0}),N3=D(()=>{"use strict"}),z3=D(()=>{"use strict"}),B3=D(()=>{"use strict"}),F3=D(()=>{"use strict"}),L3={};wn(L3,{InferenceSession:()=>ts,TRACE:()=>Uo,TRACE_EVENT_BEGIN:()=>hn,TRACE_EVENT_END:()=>fn,TRACE_FUNC_BEGIN:()=>Jt,TRACE_FUNC_END:()=>Vt,Tensor:()=>vt,env:()=>me,registerBackend:()=>pn});var dt=D(()=>{"use strict";O3(),A3(),M3(),A0(),N3(),z3(),k0(),B3(),F3()});function un(e,t,n,i){if(t===void 0)return j3(e);if(n===void 0)vo(e,t,1);else if(typeof n=="number"&&i===void 0)vo(e,t,n);else if(typeof n=="string"&&i===void 0)vo(e,n,1,t);else if(typeof n=="string"&&typeof i=="number")vo(e,n,i,t);else throw new TypeError("input is valid")}function j3(e){return{verbose:un.verbose.bind(null,e),info:un.info.bind(null,e),warning:un.warning.bind(null,e),error:un.error.bind(null,e),fatal:un.fatal.bind(null,e)}}function vo(e,t,n,i){let u=Dn[i||""]||Dn[""];Uu[e]{"use strict";ch=class{log(e,t,n){}},ph=class{log(e,t,n){console.log(`${this.color(e)} ${n?"\x1B[35m"+n+"\x1B[0m ":""}${t}`)}color(e){switch(e){case"verbose":return"\x1B[34;40mv\x1B[0m";case"info":return"\x1B[32mi\x1B[0m";case"warning":return"\x1B[30;43mw\x1B[0m";case"error":return"\x1B[31;40me\x1B[0m";case"fatal":return"\x1B[101mf\x1B[0m";default:throw new Error(`unsupported severity: ${e}`)}}},Uu={verbose:1e3,info:2e3,warning:4e3,error:5e3,fatal:6e3},R0={none:new ch,console:new ph},ha={provider:"console",minimalSeverity:"warning",logDateTime:!0,logSourceLocation:!1},Dn={"":ha},(e=>{function t(r,o){e("verbose",r,o)}e.verbose=t;function n(r,o){e("info",r,o)}e.info=n;function i(r,o){e("warning",r,o)}e.warning=i;function u(r,o){e("error",r,o)}e.error=u;function l(r,o){e("fatal",r,o)}e.fatal=l;function d(r){Dn={},c("",r||{})}e.reset=d;function c(r,o){if(r==="*")d(o);else{let a=Dn[r]||ha;Dn[r]={provider:o.provider||a.provider,minimalSeverity:o.minimalSeverity||a.minimalSeverity,logDateTime:o.logDateTime===void 0?a.logDateTime:o.logDateTime,logSourceLocation:o.logSourceLocation===void 0?a.logSourceLocation:o.logSourceLocation}}}e.set=c;function s(r){let o={};r.logLevel&&(o.minimalSeverity=r.logLevel),c("",o)}e.setWithEnv=s})(un||={}),Je=un,fa=class{constructor(e,t,n,i,u,l){this.category=e,this.name=t,this.startTime=n,this.endCallback=i,this.timer=u,this.ctx=l}async end(){return this.endCallback(this)}async checkTimer(){if(this.ctx===void 0||this.timer===void 0)throw new Error("No webgl timer found");return this.ctx.endTimer(),this.ctx.waitForQueryAndGetTime(this.timer)}},ma=class{constructor(e,t,n,i){this.category=e,this.name=t,this.startTime=n,this.endTime=i}},D0=class{constructor(e,t,n){this._started=!1,this._flushPointer=0,this._started=!1,this._maxNumberEvents=e===void 0?1e4:e,this._flushBatchSize=t===void 0?10:t,this._flushIntervalInMilliseconds=n===void 0?5e3:n}static create(e){return e===void 0?new this:new this(e.maxNumberEvents,e.flushBatchSize,e.flushIntervalInMilliseconds)}start(){this._started=!0,this._timingEvents=[],this._flushTime=oi(),this._flushPointer=0}stop(){for(this._started=!1;this._flushPointer{d.then(async r=>{u&&await u.end(),c(r)},async r=>{u&&await u.end(),s(r)})});if(!l&&u){let c=u.end();if(c&&typeof c.then=="function")return new Promise((s,r)=>{c.then(()=>{s(d)},o=>{r(o)})})}return d}begin(e,t,n){if(!this._started)throw new Error("profiler is not started yet");if(n===void 0){let i=oi();return this.flush(i),new fa(e,t,i,u=>this.endSync(u))}else{let i=n.beginTimer();return new fa(e,t,0,async u=>this.end(u),i,n)}}async end(e){let t=await e.checkTimer();this._timingEvents.length=this._flushBatchSize||e-this._flushTime>=this._flushIntervalInMilliseconds){for(let t=this._flushPointer;this._flushPointerperformance.now():Date.now});function U3(e,t,n){for(let i of n){let u=i[0],l=i[1],d=i[2],c=i[3],s=i[4];if(e.opType===u){for(let r of t)if((r.domain===l||r.domain==="ai.onnx"&&l==="")&&V3(r.version,d))return{opImpl:c,opInit:s}}}throw new TypeError(`cannot resolve operator '${e.opType}' with opsets: ${t.map(i=>`${i.domain||"ai.onnx"} v${i.version}`).join(", ")}`)}function V3(e,t){if(t.endsWith("+")){let n=Number.parseInt(t.substring(0,t.length-1),10);return!isNaN(n)&&n<=e}else if(t.split("-").length===2){let n=t.split("-"),i=Number.parseInt(n[0],10),u=Number.parseInt(n[1],10);return!isNaN(i)&&!isNaN(u)&&i<=e&&e<=u}else return Number.parseInt(t,10)===e}var G3=D(()=>{"use strict"}),q3=ae(e=>{"use strict";e.__esModule=!0;var t=(function(){function n(i){if(!i)throw new TypeError("Invalid argument; `value` has no value.");this.value=n.EMPTY,i&&n.isGuid(i)&&(this.value=i)}return n.isGuid=function(i){var u=i.toString();return i&&(i instanceof n||n.validator.test(u))},n.create=function(){return new n([n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-"))},n.createEmpty=function(){return new n("emptyguid")},n.parse=function(i){return new n(i)},n.raw=function(){return[n.gen(2),n.gen(1),n.gen(1),n.gen(1),n.gen(3)].join("-")},n.gen=function(i){for(var u="",l=0;l>>=0,(u=0<=e&&e<256)&&(i=Gu[e],i)?i:(n=Ce(e,0,!0),u&&(Gu[e]=n),n)):(e|=0,(u=-128<=e&&e<128)&&(i=Vu[e],i)?i:(n=Ce(e,e<0?-1:0,!1),u&&(Vu[e]=n),n))}function Rt(e,t){if(isNaN(e))return t?Zt:Ct;if(t){if(e<0)return Zt;if(e>=qu)return Ku}else{if(e<=-Hu)return pt;if(e+1>=Hu)return Wu}return e<0?Rt(-e,t).neg():Ce(e%ln|0,e/ln|0,t)}function Ce(e,t,n){return new ze(e,t,n)}function Kl(e,t,n){if(e.length===0)throw Error("empty string");if(typeof t=="number"?(n=t,t=!1):t=!!t,e==="NaN"||e==="Infinity"||e==="+Infinity"||e==="-Infinity")return t?Zt:Ct;if(n=n||10,n<2||360)throw Error("interior hyphen");if(i===0)return Kl(e.substring(1),t,n).neg();for(var u=Rt(Ai(n,8)),l=Ct,d=0;d{gt=null;try{gt=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}ze.prototype.__isLong__,Object.defineProperty(ze.prototype,"__isLong__",{value:!0}),ze.isLong=lt,Vu={},Gu={},ze.fromInt=Ur,ze.fromNumber=Rt,ze.fromBits=Ce,Ai=Math.pow,ze.fromString=Kl,ze.fromValue=Et,ga=65536,fh=1<<24,ln=ga*ga,qu=ln*ln,Hu=qu/2,ba=Ur(fh),Ct=Ur(0),ze.ZERO=Ct,Zt=Ur(0,!0),ze.UZERO=Zt,Vr=Ur(1),ze.ONE=Vr,ya=Ur(1,!0),ze.UONE=ya,xo=Ur(-1),ze.NEG_ONE=xo,Wu=Ce(-1,2147483647,!1),ze.MAX_VALUE=Wu,Ku=Ce(-1,-1,!0),ze.MAX_UNSIGNED_VALUE=Ku,pt=Ce(0,-2147483648,!1),ze.MIN_VALUE=pt,Z=ze.prototype,Z.toInt=function(){return this.unsigned?this.low>>>0:this.low},Z.toNumber=function(){return this.unsigned?(this.high>>>0)*ln+(this.low>>>0):this.high*ln+(this.low>>>0)},Z.toString=function(e){if(e=e||10,e<2||36>>0,r=s.toString(e);if(l=c,l.isZero())return r+d;for(;r.length<6;)r="0"+r;d=""+r+d}},Z.getHighBits=function(){return this.high},Z.getHighBitsUnsigned=function(){return this.high>>>0},Z.getLowBits=function(){return this.low},Z.getLowBitsUnsigned=function(){return this.low>>>0},Z.getNumBitsAbs=function(){if(this.isNegative())return this.eq(pt)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&(e&1<>21;return e?this.unsigned?!1:e===-1&&!(this.low===0&&this.high===-2097152):!0},Z.isZero=function(){return this.high===0&&this.low===0},Z.eqz=Z.isZero,Z.isNegative=function(){return!this.unsigned&&this.high<0},Z.isPositive=function(){return this.unsigned||this.high>=0},Z.isOdd=function(){return(this.low&1)===1},Z.isEven=function(){return(this.low&1)===0},Z.equals=function(e){return lt(e)||(e=Et(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low},Z.eq=Z.equals,Z.notEquals=function(e){return!this.eq(e)},Z.neq=Z.notEquals,Z.ne=Z.notEquals,Z.lessThan=function(e){return this.comp(e)<0},Z.lt=Z.lessThan,Z.lessThanOrEqual=function(e){return this.comp(e)<=0},Z.lte=Z.lessThanOrEqual,Z.le=Z.lessThanOrEqual,Z.greaterThan=function(e){return this.comp(e)>0},Z.gt=Z.greaterThan,Z.greaterThanOrEqual=function(e){return this.comp(e)>=0},Z.gte=Z.greaterThanOrEqual,Z.ge=Z.greaterThanOrEqual,Z.compare=function(e){if(lt(e)||(e=Et(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},Z.comp=Z.compare,Z.negate=function(){return!this.unsigned&&this.eq(pt)?pt:this.not().add(Vr)},Z.neg=Z.negate,Z.add=function(e){lt(e)||(e=Et(e));var t=this.high>>>16,n=this.high&65535,i=this.low>>>16,u=this.low&65535,l=e.high>>>16,d=e.high&65535,c=e.low>>>16,s=e.low&65535,r=0,o=0,a=0,p=0;return p+=u+s,a+=p>>>16,p&=65535,a+=i+c,o+=a>>>16,a&=65535,o+=n+d,r+=o>>>16,o&=65535,r+=t+l,r&=65535,Ce(a<<16|p,r<<16|o,this.unsigned)},Z.subtract=function(e){return lt(e)||(e=Et(e)),this.add(e.neg())},Z.sub=Z.subtract,Z.multiply=function(e){if(this.isZero())return this;if(lt(e)||(e=Et(e)),gt){var t=gt.mul(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}if(e.isZero())return this.unsigned?Zt:Ct;if(this.eq(pt))return e.isOdd()?pt:Ct;if(e.eq(pt))return this.isOdd()?pt:Ct;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(ba)&&e.lt(ba))return Rt(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,i=this.high&65535,u=this.low>>>16,l=this.low&65535,d=e.high>>>16,c=e.high&65535,s=e.low>>>16,r=e.low&65535,o=0,a=0,p=0,h=0;return h+=l*r,p+=h>>>16,h&=65535,p+=u*r,a+=p>>>16,p&=65535,p+=l*s,a+=p>>>16,p&=65535,a+=i*r,o+=a>>>16,a&=65535,a+=u*s,o+=a>>>16,a&=65535,a+=l*c,o+=a>>>16,a&=65535,o+=n*r+i*s+u*c+l*d,o&=65535,Ce(p<<16|h,o<<16|a,this.unsigned)},Z.mul=Z.multiply,Z.divide=function(e){if(lt(e)||(e=Et(e)),e.isZero())throw Error("division by zero");if(gt){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?gt.div_u:gt.div_s)(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Zt:Ct;var n,i,u;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Zt;if(e.gt(this.shru(1)))return ya;u=Zt}else{if(this.eq(pt)){if(e.eq(Vr)||e.eq(xo))return pt;if(e.eq(pt))return Vr;var l=this.shr(1);return n=l.div(e).shl(1),n.eq(Ct)?e.isNegative()?Vr:xo:(i=this.sub(e.mul(n)),u=n.add(i.div(e)),u)}else if(e.eq(pt))return this.unsigned?Zt:Ct;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();u=Ct}for(i=this;i.gte(e);){n=Math.max(1,Math.floor(i.toNumber()/e.toNumber()));for(var d=Math.ceil(Math.log(n)/Math.LN2),c=d<=48?1:Ai(2,d-48),s=Rt(n),r=s.mul(e);r.isNegative()||r.gt(i);)n-=c,s=Rt(n,this.unsigned),r=s.mul(e);s.isZero()&&(s=Vr),u=u.add(s),i=i.sub(r)}return u},Z.div=Z.divide,Z.modulo=function(e){if(lt(e)||(e=Et(e)),gt){var t=(this.unsigned?gt.rem_u:gt.rem_s)(this.low,this.high,e.low,e.high);return Ce(t,gt.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))},Z.mod=Z.modulo,Z.rem=Z.modulo,Z.not=function(){return Ce(~this.low,~this.high,this.unsigned)},Z.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},Z.clz=Z.countLeadingZeros,Z.countTrailingZeros=function(){return this.low?hh(this.low):hh(this.high)+32},Z.ctz=Z.countTrailingZeros,Z.and=function(e){return lt(e)||(e=Et(e)),Ce(this.low&e.low,this.high&e.high,this.unsigned)},Z.or=function(e){return lt(e)||(e=Et(e)),Ce(this.low|e.low,this.high|e.high,this.unsigned)},Z.xor=function(e){return lt(e)||(e=Et(e)),Ce(this.low^e.low,this.high^e.high,this.unsigned)},Z.shiftLeft=function(e){return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Ce(this.low<>>32-e,this.unsigned):Ce(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Ce(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Z.shr=Z.shiftRight,Z.shiftRightUnsigned=function(e){return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Ce(this.low>>>e|this.high<<32-e,this.high>>>e,this.unsigned):e===32?Ce(this.high,0,this.unsigned):Ce(this.high>>>e-32,0,this.unsigned)},Z.shru=Z.shiftRightUnsigned,Z.shr_u=Z.shiftRightUnsigned,Z.rotateLeft=function(e){var t;return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Ce(this.high,this.low,this.unsigned):e<32?(t=32-e,Ce(this.low<>>t,this.high<>>t,this.unsigned)):(e-=32,t=32-e,Ce(this.high<>>t,this.low<>>t,this.unsigned))},Z.rotl=Z.rotateLeft,Z.rotateRight=function(e){var t;return lt(e)&&(e=e.toInt()),(e&=63)===0?this:e===32?Ce(this.high,this.low,this.unsigned):e<32?(t=32-e,Ce(this.high<>>e,this.low<>>e,this.unsigned)):(e-=32,t=32-e,Ce(this.low<>>e,this.high<>>e,this.unsigned))},Z.rotr=Z.rotateRight,Z.toSigned=function(){return this.unsigned?Ce(this.low,this.high,!1):this},Z.toUnsigned=function(){return this.unsigned?this:Ce(this.low,this.high,!0)},Z.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Z.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]},Z.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]},ze.fromBytes=function(e,t,n){return n?ze.fromBytesLE(e,t):ze.fromBytesBE(e,t)},ze.fromBytesLE=function(e,t){return new ze(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},ze.fromBytesBE=function(e,t){return new ze(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)},typeof BigInt=="function"&&(ze.fromBigInt=function(e,t){var n=Number(BigInt.asIntN(32,e)),i=Number(BigInt.asIntN(32,e>>BigInt(32)));return Ce(n,i,t)},ze.fromValue=function(e,t){return typeof e=="bigint"?ze.fromBigInt(e,t):Et(e,t)},Z.toBigInt=function(){var e=BigInt(this.low>>>0),t=BigInt(this.unsigned?this.high>>>0:this.high);return t<{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ArgType=void 0;var t;(function(n){n[n.INPUT=0]="INPUT",n[n.OUTPUT=1]="OUTPUT"})(t||(e.ArgType=t={}))}),Xl=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.SIZE_PREFIX_LENGTH=e.FILE_IDENTIFIER_LENGTH=e.SIZEOF_INT=e.SIZEOF_SHORT=void 0,e.SIZEOF_SHORT=2,e.SIZEOF_INT=4,e.FILE_IDENTIFIER_LENGTH=4,e.SIZE_PREFIX_LENGTH=4}),z0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isLittleEndian=e.float64=e.float32=e.int32=void 0,e.int32=new Int32Array(2),e.float32=new Float32Array(e.int32.buffer),e.float64=new Float64Array(e.int32.buffer),e.isLittleEndian=new Uint16Array(new Uint8Array([1,0]).buffer)[0]===1}),B0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Encoding=void 0;var t;(function(n){n[n.UTF8_BYTES=1]="UTF8_BYTES",n[n.UTF16_STRING=2]="UTF16_STRING"})(t||(e.Encoding=t={}))}),F0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ByteBuffer=void 0;var t=Xl(),n=B0(),i=z0(),u=class L0{constructor(d){this.bytes_=d,this.position_=0,this.text_decoder_=new TextDecoder}static allocate(d){return new L0(new Uint8Array(d))}clear(){this.position_=0}bytes(){return this.bytes_}position(){return this.position_}setPosition(d){this.position_=d}capacity(){return this.bytes_.length}readInt8(d){return this.readUint8(d)<<24>>24}readUint8(d){return this.bytes_[d]}readInt16(d){return this.readUint16(d)<<16>>16}readUint16(d){return this.bytes_[d]|this.bytes_[d+1]<<8}readInt32(d){return this.bytes_[d]|this.bytes_[d+1]<<8|this.bytes_[d+2]<<16|this.bytes_[d+3]<<24}readUint32(d){return this.readInt32(d)>>>0}readInt64(d){return BigInt.asIntN(64,BigInt(this.readUint32(d))+(BigInt(this.readUint32(d+4))<>8}writeUint16(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8}writeInt32(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8,this.bytes_[d+2]=c>>16,this.bytes_[d+3]=c>>24}writeUint32(d,c){this.bytes_[d]=c,this.bytes_[d+1]=c>>8,this.bytes_[d+2]=c>>16,this.bytes_[d+3]=c>>24}writeInt64(d,c){this.writeInt32(d,Number(BigInt.asIntN(32,c))),this.writeInt32(d+4,Number(BigInt.asIntN(32,c>>BigInt(32))))}writeUint64(d,c){this.writeUint32(d,Number(BigInt.asUintN(32,c))),this.writeUint32(d+4,Number(BigInt.asUintN(32,c>>BigInt(32))))}writeFloat32(d,c){i.float32[0]=c,this.writeInt32(d,i.int32[0])}writeFloat64(d,c){i.float64[0]=c,this.writeInt32(d,i.int32[i.isLittleEndian?0:1]),this.writeInt32(d+4,i.int32[i.isLittleEndian?1:0])}getBufferIdentifier(){if(this.bytes_.length{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Builder=void 0;var t=F0(),n=Xl(),i=class j0{constructor(l){this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null,this.text_encoder=new TextEncoder;let d;l?d=l:d=1024,this.bb=t.ByteBuffer.allocate(d),this.space=d}clear(){this.bb.clear(),this.space=this.bb.capacity(),this.minalign=1,this.vtable=null,this.vtable_in_use=0,this.isNested=!1,this.object_start=0,this.vtables=[],this.vector_num_elems=0,this.force_defaults=!1,this.string_maps=null}forceDefaults(l){this.force_defaults=l}dataBuffer(){return this.bb}asUint8Array(){return this.bb.bytes().subarray(this.bb.position(),this.bb.position()+this.offset())}prep(l,d){l>this.minalign&&(this.minalign=l);let c=~(this.bb.capacity()-this.space+d)+1&l-1;for(;this.space=0&&this.vtable[d]==0;d--);let c=d+1;for(;d>=0;d--)this.addInt16(this.vtable[d]!=0?l-this.vtable[d]:0);let s=2;this.addInt16(l-this.object_start);let r=(c+s)*n.SIZEOF_SHORT;this.addInt16(r);let o=0,a=this.space;e:for(d=0;d=0;o--)this.writeInt8(r.charCodeAt(o))}this.prep(this.minalign,n.SIZEOF_INT+s),this.addOffset(l),s&&this.addInt32(this.bb.capacity()-this.space),this.bb.setPosition(this.space)}finishSizePrefixed(l,d){this.finish(l,d,!0)}requiredField(l,d){let c=this.bb.capacity()-l,s=c-this.bb.readInt32(c);if(!(d{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Encoding=e.ByteBuffer=e.Builder=e.isLittleEndian=e.int32=e.float64=e.float32=e.SIZE_PREFIX_LENGTH=e.SIZEOF_SHORT=e.SIZEOF_INT=e.FILE_IDENTIFIER_LENGTH=void 0;var t=Xl();Object.defineProperty(e,"FILE_IDENTIFIER_LENGTH",{enumerable:!0,get:function(){return t.FILE_IDENTIFIER_LENGTH}}),Object.defineProperty(e,"SIZEOF_INT",{enumerable:!0,get:function(){return t.SIZEOF_INT}}),Object.defineProperty(e,"SIZEOF_SHORT",{enumerable:!0,get:function(){return t.SIZEOF_SHORT}}),Object.defineProperty(e,"SIZE_PREFIX_LENGTH",{enumerable:!0,get:function(){return t.SIZE_PREFIX_LENGTH}});var n=z0();Object.defineProperty(e,"float32",{enumerable:!0,get:function(){return n.float32}}),Object.defineProperty(e,"float64",{enumerable:!0,get:function(){return n.float64}}),Object.defineProperty(e,"int32",{enumerable:!0,get:function(){return n.int32}}),Object.defineProperty(e,"isLittleEndian",{enumerable:!0,get:function(){return n.isLittleEndian}});var i=H3();Object.defineProperty(e,"Builder",{enumerable:!0,get:function(){return i.Builder}});var u=F0();Object.defineProperty(e,"ByteBuffer",{enumerable:!0,get:function(){return u.ByteBuffer}});var l=B0();Object.defineProperty(e,"Encoding",{enumerable:!0,get:function(){return l.Encoding}})}),U0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.AttributeType=void 0;var t;(function(n){n[n.UNDEFINED=0]="UNDEFINED",n[n.FLOAT=1]="FLOAT",n[n.INT=2]="INT",n[n.STRING=3]="STRING",n[n.TENSOR=4]="TENSOR",n[n.GRAPH=5]="GRAPH",n[n.FLOATS=6]="FLOATS",n[n.INTS=7]="INTS",n[n.STRINGS=8]="STRINGS",n[n.TENSORS=9]="TENSORS",n[n.GRAPHS=10]="GRAPHS",n[n.SPARSE_TENSOR=11]="SPARSE_TENSOR",n[n.SPARSE_TENSORS=12]="SPARSE_TENSORS"})(t||(e.AttributeType=t={}))}),G0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.NodeType=void 0;var t;(function(n){n[n.Primitive=0]="Primitive",n[n.Fused=1]="Fused"})(t||(e.NodeType=t={}))}),q0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p=0;a--)r.addOffset(o[a]);return r.endVector()}static startInputsVector(r,o){r.startVector(4,o,4)}static addOutputs(r,o){r.addFieldOffset(9,o,0)}static createOutputsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startOutputsVector(r,o){r.startVector(4,o,4)}static addAttributes(r,o){r.addFieldOffset(10,o,0)}static createAttributesVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startAttributesVector(r,o){r.startVector(4,o,4)}static addInputArgCounts(r,o){r.addFieldOffset(11,o,0)}static createInputArgCountsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addInt32(o[a]);return r.endVector()}static startInputArgCountsVector(r,o){r.startVector(4,o,4)}static addImplicitInputs(r,o){r.addFieldOffset(12,o,0)}static createImplicitInputsVector(r,o){r.startVector(4,o.length,4);for(let a=o.length-1;a>=0;a--)r.addOffset(o[a]);return r.endVector()}static startImplicitInputsVector(r,o){r.startVector(4,o,4)}static endNode(r){return r.endObject()}static createNode(r,o,a,p,h,m,g,_,w,y,T,S,O,A){return ot.startNode(r),ot.addName(r,o),ot.addDocString(r,a),ot.addDomain(r,p),ot.addSinceVersion(r,h),ot.addIndex(r,m),ot.addOpType(r,g),ot.addType(r,_),ot.addExecutionProviderType(r,w),ot.addInputs(r,y),ot.addOutputs(r,T),ot.addAttributes(r,S),ot.addInputArgCounts(r,O),ot.addImplicitInputs(r,A),ot.endNode(r)}};e.Node=c}),H0=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.EdgeEnd=void 0;var t=class{constructor(){this.bb=null,this.bb_pos=0}__init(n,i){return this.bb_pos=n,this.bb=i,this}nodeIndex(){return this.bb.readUint32(this.bb_pos)}srcArgIndex(){return this.bb.readInt32(this.bb_pos+4)}dstArgIndex(){return this.bb.readInt32(this.bb_pos+8)}static sizeOf(){return 12}static createEdgeEnd(n,i,u,l){return n.prep(4,12),n.writeInt32(l),n.writeInt32(u),n.writeInt32(i),n.offset()}};e.EdgeEnd=t}),W0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o=0;r--)c.addInt32(s[r]);return c.endVector()}static startNodeIndicesVector(c,s){c.startVector(4,s,4)}static addNumInputs(c,s){c.addFieldInt32(1,s,0)}static addNumOutputs(c,s){c.addFieldInt32(2,s,0)}static addHasVariadicInput(c,s){c.addFieldInt8(3,+s,0)}static addHasVariadicOutput(c,s){c.addFieldInt8(4,+s,0)}static addNumVariadicInputs(c,s){c.addFieldInt32(5,s,0)}static addNumVariadicOutputs(c,s){c.addFieldInt32(6,s,0)}static endNodesToOptimizeIndices(c){return c.endObject()}static createNodesToOptimizeIndices(c,s,r,o,a,p,h,m){return kt.startNodesToOptimizeIndices(c),kt.addNodeIndices(c,s),kt.addNumInputs(c,r),kt.addNumOutputs(c,o),kt.addHasVariadicInput(c,a),kt.addHasVariadicOutput(c,p),kt.addNumVariadicInputs(c,h),kt.addNumVariadicOutputs(c,m),kt.endNodesToOptimizeIndices(c)}};e.NodesToOptimizeIndices=l}),X0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startProducedOpIdsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizationRecord(s){return s.endObject()}};e.RuntimeOptimizationRecord=d}),Z0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startRuntimeOptimizationRecordsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizationRecordContainerEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createRuntimeOptimizationRecordContainerEntry(s,r,o){return Zr.startRuntimeOptimizationRecordContainerEntry(s),Zr.addOptimizerName(s,r),Zr.addRuntimeOptimizationRecords(s,o),Zr.endRuntimeOptimizationRecordContainerEntry(s)}};e.RuntimeOptimizationRecordContainerEntry=d}),Y0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startRecordsVector(s,r){s.startVector(4,r,4)}static endRuntimeOptimizations(s){return s.endObject()}static createRuntimeOptimizations(s,r){return kn.startRuntimeOptimizations(s),kn.addRecords(s,r),kn.endRuntimeOptimizations(s)}};e.RuntimeOptimizations=d}),rs=ae(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TensorDataType=void 0;var t;(function(n){n[n.UNDEFINED=0]="UNDEFINED",n[n.FLOAT=1]="FLOAT",n[n.UINT8=2]="UINT8",n[n.INT8=3]="INT8",n[n.UINT16=4]="UINT16",n[n.INT16=5]="INT16",n[n.INT32=6]="INT32",n[n.INT64=7]="INT64",n[n.STRING=8]="STRING",n[n.BOOL=9]="BOOL",n[n.FLOAT16=10]="FLOAT16",n[n.DOUBLE=11]="DOUBLE",n[n.UINT32=12]="UINT32",n[n.UINT64=13]="UINT64",n[n.COMPLEX64=14]="COMPLEX64",n[n.COMPLEX128=15]="COMPLEX128",n[n.BFLOAT16=16]="BFLOAT16",n[n.FLOAT8E4M3FN=17]="FLOAT8E4M3FN",n[n.FLOAT8E4M3FNUZ=18]="FLOAT8E4M3FNUZ",n[n.FLOAT8E5M2=19]="FLOAT8E5M2",n[n.FLOAT8E5M2FNUZ=20]="FLOAT8E5M2FNUZ"})(t||(e.TensorDataType=t={}))}),ns=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addInt64(r[o]);return s.endVector()}static startDimsVector(s,r){s.startVector(8,r,8)}static addDataType(s,r){s.addFieldInt32(3,r,l.TensorDataType.UNDEFINED)}static addRawData(s,r){s.addFieldOffset(4,r,0)}static createRawDataVector(s,r){s.startVector(1,r.length,1);for(let o=r.length-1;o>=0;o--)s.addInt8(r[o]);return s.endVector()}static startRawDataVector(s,r){s.startVector(1,r,1)}static addStringData(s,r){s.addFieldOffset(5,r,0)}static createStringDataVector(s,r){s.startVector(4,r.length,4);for(let o=r.length-1;o>=0;o--)s.addOffset(r[o]);return s.endVector()}static startStringDataVector(s,r){s.startVector(4,r,4)}static addExternalDataOffset(s,r){s.addFieldInt64(6,r,BigInt("-1"))}static endTensor(s){return s.endObject()}static createTensor(s,r,o,a,p,h,m,g){return Pt.startTensor(s),Pt.addName(s,r),Pt.addDocString(s,o),Pt.addDims(s,a),Pt.addDataType(s,p),Pt.addRawData(s,h),Pt.addStringData(s,m),Pt.addExternalDataOffset(s,g),Pt.endTensor(s)}};e.Tensor=d}),J0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addInt64(r[o]);return s.endVector()}static startDimsVector(s,r){s.startVector(8,r,8)}static endSparseTensor(s){return s.endObject()}};e.SparseTensor=d}),Q0=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.DimensionValueType=void 0;var t;(function(n){n[n.UNKNOWN=0]="UNKNOWN",n[n.VALUE=1]="VALUE",n[n.PARAM=2]="PARAM"})(t||(e.DimensionValueType=t={}))}),rw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startDimVector(s,r){s.startVector(4,r,4)}static endShape(s){return s.endObject()}static createShape(s,r){return Cn.startShape(s),Cn.addDim(s,r),Cn.endShape(s)}};e.Shape=d}),ow=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TypeInfoValue=void 0,e.unionToTypeInfoValue=l,e.unionListToTypeInfoValue=d;var t=Q0(),n=ew(),i=ow(),u;(function(c){c[c.NONE=0]="NONE",c[c.tensor_type=1]="tensor_type",c[c.sequence_type=2]="sequence_type",c[c.map_type=3]="map_type"})(u||(e.TypeInfoValue=u={}));function l(c,s){switch(u[c]){case"NONE":return null;case"tensor_type":return s(new i.TensorTypeAndShape);case"sequence_type":return s(new n.SequenceType);case"map_type":return s(new t.MapType);default:return null}}function d(c,s,r){switch(u[c]){case"NONE":return null;case"tensor_type":return s(r,new i.TensorTypeAndShape);case"sequence_type":return s(r,new n.SequenceType);case"map_type":return s(r,new t.MapType);default:return null}}}),is=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(p,h,m,g){g===void 0&&(g=m);var _=Object.getOwnPropertyDescriptor(h,m);(!_||("get"in _?!h.__esModule:_.writable||_.configurable))&&(_={enumerable:!0,get:function(){return h[m]}}),Object.defineProperty(p,g,_)}:function(p,h,m,g){g===void 0&&(g=m),p[g]=h[m]}),n=e&&e.__setModuleDefault||(Object.create?function(p,h){Object.defineProperty(p,"default",{enumerable:!0,value:h})}:function(p,h){p.default=h}),i=e&&e.__importStar||(function(){var p=function(h){return p=Object.getOwnPropertyNames||function(m){var g=[];for(var _ in m)Object.prototype.hasOwnProperty.call(m,_)&&(g[g.length]=_);return g},p(h)};return function(h){if(h&&h.__esModule)return h;var m={};if(h!=null)for(var g=p(h),_=0;_=0;g--)h.addOffset(m[g]);return h.endVector()}static startInitializersVector(h,m){h.startVector(4,m,4)}static addNodeArgs(h,m){h.addFieldOffset(1,m,0)}static createNodeArgsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodeArgsVector(h,m){h.startVector(4,m,4)}static addNodes(h,m){h.addFieldOffset(2,m,0)}static createNodesVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodesVector(h,m){h.startVector(4,m,4)}static addMaxNodeIndex(h,m){h.addFieldInt32(3,m,0)}static addNodeEdges(h,m){h.addFieldOffset(4,m,0)}static createNodeEdgesVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startNodeEdgesVector(h,m){h.startVector(4,m,4)}static addInputs(h,m){h.addFieldOffset(5,m,0)}static createInputsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startInputsVector(h,m){h.startVector(4,m,4)}static addOutputs(h,m){h.addFieldOffset(6,m,0)}static createOutputsVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startOutputsVector(h,m){h.startVector(4,m,4)}static addSparseInitializers(h,m){h.addFieldOffset(7,m,0)}static createSparseInitializersVector(h,m){h.startVector(4,m.length,4);for(let g=m.length-1;g>=0;g--)h.addOffset(m[g]);return h.endVector()}static startSparseInitializersVector(h,m){h.startVector(4,m,4)}static addRuntimeOptimizations(h,m){h.addFieldOffset(8,m,0)}static endGraph(h){return h.endObject()}};e.Graph=a}),uw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(r,o,a,p){p===void 0&&(p=a);var h=Object.getOwnPropertyDescriptor(o,a);(!h||("get"in h?!o.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(r,p,h)}:function(r,o,a,p){p===void 0&&(p=a),r[p]=o[a]}),n=e&&e.__setModuleDefault||(Object.create?function(r,o){Object.defineProperty(r,"default",{enumerable:!0,value:o})}:function(r,o){r.default=o}),i=e&&e.__importStar||(function(){var r=function(o){return r=Object.getOwnPropertyNames||function(a){var p=[];for(var h in a)Object.prototype.hasOwnProperty.call(a,h)&&(p[p.length]=h);return p},r(o)};return function(o){if(o&&o.__esModule)return o;var a={};if(o!=null)for(var p=r(o),h=0;h=0;p--)o.addFloat32(a[p]);return o.endVector()}static startFloatsVector(o,a){o.startVector(4,a,4)}static addInts(o,a){o.addFieldOffset(9,a,0)}static createIntsVector(o,a){o.startVector(8,a.length,8);for(let p=a.length-1;p>=0;p--)o.addInt64(a[p]);return o.endVector()}static startIntsVector(o,a){o.startVector(8,a,8)}static addStrings(o,a){o.addFieldOffset(10,a,0)}static createStringsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startStringsVector(o,a){o.startVector(4,a,4)}static addTensors(o,a){o.addFieldOffset(11,a,0)}static createTensorsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startTensorsVector(o,a){o.startVector(4,a,4)}static addGraphs(o,a){o.addFieldOffset(12,a,0)}static createGraphsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startGraphsVector(o,a){o.startVector(4,a,4)}static endAttribute(o){return o.endObject()}};e.Attribute=s}),lw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o=0;r--)c.addInt32(s[r]);return c.endVector()}static startNodeIndicesVector(c,s){c.startVector(4,s,4)}static addKernelDefHashes(c,s){c.addFieldOffset(1,s,0)}static createKernelDefHashesVector(c,s){c.startVector(8,s.length,8);for(let r=s.length-1;r>=0;r--)c.addInt64(s[r]);return c.endVector()}static startKernelDefHashesVector(c,s){c.startVector(8,s,8)}static endDeprecatedKernelCreateInfos(c){return c.endObject()}static createDeprecatedKernelCreateInfos(c,s,r){return Jr.startDeprecatedKernelCreateInfos(c),Jr.addNodeIndices(c,s),Jr.addKernelDefHashes(c,r),Jr.endDeprecatedKernelCreateInfos(c)}};e.DeprecatedKernelCreateInfos=l}),W3=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p=0;a--)r.addOffset(o[a]);return r.endVector()}static startSubGraphSessionStatesVector(r,o){r.startVector(4,o,4)}static endDeprecatedSessionState(r){return r.endObject()}static createDeprecatedSessionState(r,o,a){return en.startDeprecatedSessionState(r),en.addKernels(r,o),en.addSubGraphSessionStates(r,a),en.endDeprecatedSessionState(r)}};e.DeprecatedSessionState=c}),pw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startArgsVector(s,r){s.startVector(4,r,4)}static endKernelTypeStrArgsEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createKernelTypeStrArgsEntry(s,r,o){return tn.startKernelTypeStrArgsEntry(s),tn.addKernelTypeStr(s,r),tn.addArgs(s,o),tn.endKernelTypeStrArgsEntry(s)}};e.KernelTypeStrArgsEntry=d}),hw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startKernelTypeStrArgsVector(s,r){s.startVector(4,r,4)}static endOpIdKernelTypeStrArgsEntry(s){let r=s.endObject();return s.requiredField(r,4),r}static createOpIdKernelTypeStrArgsEntry(s,r,o){return rn.startOpIdKernelTypeStrArgsEntry(s),rn.addOpId(s,r),rn.addKernelTypeStrArgs(s,o),rn.endOpIdKernelTypeStrArgsEntry(s)}};e.OpIdKernelTypeStrArgsEntry=d}),fw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(c,s,r,o){o===void 0&&(o=r);var a=Object.getOwnPropertyDescriptor(s,r);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[r]}}),Object.defineProperty(c,o,a)}:function(c,s,r,o){o===void 0&&(o=r),c[o]=s[r]}),n=e&&e.__setModuleDefault||(Object.create?function(c,s){Object.defineProperty(c,"default",{enumerable:!0,value:s})}:function(c,s){c.default=s}),i=e&&e.__importStar||(function(){var c=function(s){return c=Object.getOwnPropertyNames||function(r){var o=[];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(o[o.length]=a);return o},c(s)};return function(s){if(s&&s.__esModule)return s;var r={};if(s!=null)for(var o=c(s),a=0;a=0;o--)s.addOffset(r[o]);return s.endVector()}static startOpKernelTypeStrArgsVector(s,r){s.startVector(4,r,4)}static endKernelTypeStrResolver(s){return s.endObject()}static createKernelTypeStrResolver(s,r){return Rn.startKernelTypeStrResolver(s),Rn.addOpKernelTypeStrArgs(s,r),Rn.endKernelTypeStrResolver(s)}};e.KernelTypeStrResolver=d}),mw=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(d,c,s,r){r===void 0&&(r=s);var o=Object.getOwnPropertyDescriptor(c,s);(!o||("get"in o?!c.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return c[s]}}),Object.defineProperty(d,r,o)}:function(d,c,s,r){r===void 0&&(r=s),d[r]=c[s]}),n=e&&e.__setModuleDefault||(Object.create?function(d,c){Object.defineProperty(d,"default",{enumerable:!0,value:c})}:function(d,c){d.default=c}),i=e&&e.__importStar||(function(){var d=function(c){return d=Object.getOwnPropertyNames||function(s){var r=[];for(var o in s)Object.prototype.hasOwnProperty.call(s,o)&&(r[r.length]=o);return r},d(c)};return function(c){if(c&&c.__esModule)return c;var s={};if(c!=null)for(var r=d(c),o=0;o{"use strict";var t=e&&e.__createBinding||(Object.create?function(r,o,a,p){p===void 0&&(p=a);var h=Object.getOwnPropertyDescriptor(o,a);(!h||("get"in h?!o.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return o[a]}}),Object.defineProperty(r,p,h)}:function(r,o,a,p){p===void 0&&(p=a),r[p]=o[a]}),n=e&&e.__setModuleDefault||(Object.create?function(r,o){Object.defineProperty(r,"default",{enumerable:!0,value:o})}:function(r,o){r.default=o}),i=e&&e.__importStar||(function(){var r=function(o){return r=Object.getOwnPropertyNames||function(a){var p=[];for(var h in a)Object.prototype.hasOwnProperty.call(a,h)&&(p[p.length]=h);return p},r(o)};return function(o){if(o&&o.__esModule)return o;var a={};if(o!=null)for(var p=r(o),h=0;h=0;p--)o.addOffset(a[p]);return o.endVector()}static startOpsetImportVector(o,a){o.startVector(4,a,4)}static addProducerName(o,a){o.addFieldOffset(2,a,0)}static addProducerVersion(o,a){o.addFieldOffset(3,a,0)}static addDomain(o,a){o.addFieldOffset(4,a,0)}static addModelVersion(o,a){o.addFieldInt64(5,a,BigInt("0"))}static addDocString(o,a){o.addFieldOffset(6,a,0)}static addGraph(o,a){o.addFieldOffset(7,a,0)}static addGraphDocString(o,a){o.addFieldOffset(8,a,0)}static addMetadataProps(o,a){o.addFieldOffset(9,a,0)}static createMetadataPropsVector(o,a){o.startVector(4,a.length,4);for(let p=a.length-1;p>=0;p--)o.addOffset(a[p]);return o.endVector()}static startMetadataPropsVector(o,a){o.startVector(4,a,4)}static endModel(o){return o.endObject()}};e.Model=s}),K3=ae(e=>{"use strict";var t=e&&e.__createBinding||(Object.create?function(s,r,o,a){a===void 0&&(a=o);var p=Object.getOwnPropertyDescriptor(r,o);(!p||("get"in p?!r.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return r[o]}}),Object.defineProperty(s,a,p)}:function(s,r,o,a){a===void 0&&(a=o),s[a]=r[o]}),n=e&&e.__setModuleDefault||(Object.create?function(s,r){Object.defineProperty(s,"default",{enumerable:!0,value:r})}:function(s,r){s.default=r}),i=e&&e.__importStar||(function(){var s=function(r){return s=Object.getOwnPropertyNames||function(o){var a=[];for(var p in o)Object.prototype.hasOwnProperty.call(o,p)&&(a[a.length]=p);return a},s(r)};return function(r){if(r&&r.__esModule)return r;var o={};if(r!=null)for(var a=s(r),p=0;p{"use strict";X3=be(N0()),Z3=be(U0()),ol=be(uw()),jt=be(V0()),Y3=be(lw()),J3=be(W3()),Q3=be(cw()),eO=be(dw()),tO=be(nw()),rO=be(rw()),nO=be(tw()),iO=be(H0()),yw=be(Zl()),ww=be(K3()),oO=be(pw()),sO=be(fw()),aO=be(Q0()),uO=be(bw()),_w=be(q0()),lO=be(W0()),dO=be(G0()),cO=be(K0()),pO=be(hw()),hO=be(mw()),fO=be(X0()),mO=be(Z0()),gO=be(Y0()),bO=be(ew()),yO=be(iw()),wO=be(J0()),_O=be(gw()),vO=be(ns()),Bo=be(rs()),vw=be(ow()),xO=be(is()),xw=be(sw()),$O=be(aw())}),os=D(()=>{"use strict";TO()}),SO=ae((e,t)=>{"use strict";t.exports=n;function n(i,u){for(var l=new Array(arguments.length-1),d=0,c=2,s=!0;c{"use strict";var t=e;t.length=function(d){var c=d.length;if(!c)return 0;for(var s=0;--c%4>1&&d.charAt(c)==="=";)++s;return Math.ceil(d.length*3)/4-s};var n=new Array(64),i=new Array(123);for(u=0;u<64;)i[n[u]=u<26?u+65:u<52?u+71:u<62?u-4:u-59|43]=u++;var u;t.encode=function(d,c,s){for(var r=null,o=[],a=0,p=0,h;c>2],h=(m&3)<<4,p=1;break;case 1:o[a++]=n[h|m>>4],h=(m&15)<<2,p=2;break;case 2:o[a++]=n[h|m>>6],o[a++]=n[m&63],p=0;break}a>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,o)),a=0)}return p&&(o[a++]=n[h],o[a++]=61,p===1&&(o[a++]=61)),r?(a&&r.push(String.fromCharCode.apply(String,o.slice(0,a))),r.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var l="invalid encoding";t.decode=function(d,c,s){for(var r=s,o=0,a,p=0;p1)break;if((h=i[h])===void 0)throw Error(l);switch(o){case 0:a=h,o=1;break;case 1:c[s++]=a<<2|(h&48)>>4,a=h,o=2;break;case 2:c[s++]=(a&15)<<4|(h&60)>>2,a=h,o=3;break;case 3:c[s++]=(a&3)<<6|h,o=0;break}}if(o===1)throw Error(l);return s-r},t.test=function(d){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(d)}}),OO=ae((e,t)=>{"use strict";t.exports=n;function n(){this._listeners=Object.create(null)}n.prototype.on=function(i,u,l){return(this._listeners[i]||(this._listeners[i]=[])).push({fn:u,ctx:l||this}),this},n.prototype.off=function(i,u){if(i===void 0)this._listeners=Object.create(null);else if(u===void 0)this._listeners[i]=[];else{var l=this._listeners[i];if(!l)return this;for(var d=0;d{"use strict";t.exports=n(n);function n(c){return typeof Float32Array<"u"?(function(){var s=new Float32Array([-0]),r=new Uint8Array(s.buffer),o=r[3]===128;function a(g,_,w){s[0]=g,_[w]=r[0],_[w+1]=r[1],_[w+2]=r[2],_[w+3]=r[3]}function p(g,_,w){s[0]=g,_[w]=r[3],_[w+1]=r[2],_[w+2]=r[1],_[w+3]=r[0]}c.writeFloatLE=o?a:p,c.writeFloatBE=o?p:a;function h(g,_){return r[0]=g[_],r[1]=g[_+1],r[2]=g[_+2],r[3]=g[_+3],s[0]}function m(g,_){return r[3]=g[_],r[2]=g[_+1],r[1]=g[_+2],r[0]=g[_+3],s[0]}c.readFloatLE=o?h:m,c.readFloatBE=o?m:h})():(function(){function s(o,a,p,h){var m=a<0?1:0;if(m&&(a=-a),a===0)o(1/a>0?0:2147483648,p,h);else if(isNaN(a))o(2143289344,p,h);else if(a>34028234663852886e22)o((m<<31|2139095040)>>>0,p,h);else if(a<11754943508222875e-54)o((m<<31|Math.round(a/1401298464324817e-60))>>>0,p,h);else{var g=Math.floor(Math.log(a)/Math.LN2),_=Math.round(a*Math.pow(2,-g)*8388608)&8388607;o((m<<31|g+127<<23|_)>>>0,p,h)}}c.writeFloatLE=s.bind(null,i),c.writeFloatBE=s.bind(null,u);function r(o,a,p){var h=o(a,p),m=(h>>31)*2+1,g=h>>>23&255,_=h&8388607;return g===255?_?NaN:m*(1/0):g===0?m*1401298464324817e-60*_:m*Math.pow(2,g-150)*(_+8388608)}c.readFloatLE=r.bind(null,l),c.readFloatBE=r.bind(null,d)})(),typeof Float64Array<"u"?(function(){var s=new Float64Array([-0]),r=new Uint8Array(s.buffer),o=r[7]===128;function a(g,_,w){s[0]=g,_[w]=r[0],_[w+1]=r[1],_[w+2]=r[2],_[w+3]=r[3],_[w+4]=r[4],_[w+5]=r[5],_[w+6]=r[6],_[w+7]=r[7]}function p(g,_,w){s[0]=g,_[w]=r[7],_[w+1]=r[6],_[w+2]=r[5],_[w+3]=r[4],_[w+4]=r[3],_[w+5]=r[2],_[w+6]=r[1],_[w+7]=r[0]}c.writeDoubleLE=o?a:p,c.writeDoubleBE=o?p:a;function h(g,_){return r[0]=g[_],r[1]=g[_+1],r[2]=g[_+2],r[3]=g[_+3],r[4]=g[_+4],r[5]=g[_+5],r[6]=g[_+6],r[7]=g[_+7],s[0]}function m(g,_){return r[7]=g[_],r[6]=g[_+1],r[5]=g[_+2],r[4]=g[_+3],r[3]=g[_+4],r[2]=g[_+5],r[1]=g[_+6],r[0]=g[_+7],s[0]}c.readDoubleLE=o?h:m,c.readDoubleBE=o?m:h})():(function(){function s(o,a,p,h,m,g){var _=h<0?1:0;if(_&&(h=-h),h===0)o(0,m,g+a),o(1/h>0?0:2147483648,m,g+p);else if(isNaN(h))o(0,m,g+a),o(2146959360,m,g+p);else if(h>17976931348623157e292)o(0,m,g+a),o((_<<31|2146435072)>>>0,m,g+p);else{var w;if(h<22250738585072014e-324)w=h/5e-324,o(w>>>0,m,g+a),o((_<<31|w/4294967296)>>>0,m,g+p);else{var y=Math.floor(Math.log(h)/Math.LN2);y===1024&&(y=1023),w=h*Math.pow(2,-y),o(w*4503599627370496>>>0,m,g+a),o((_<<31|y+1023<<20|w*1048576&1048575)>>>0,m,g+p)}}}c.writeDoubleLE=s.bind(null,i,0,4),c.writeDoubleBE=s.bind(null,u,4,0);function r(o,a,p,h,m){var g=o(h,m+a),_=o(h,m+p),w=(_>>31)*2+1,y=_>>>20&2047,T=4294967296*(_&1048575)+g;return y===2047?T?NaN:w*(1/0):y===0?w*5e-324*T:w*Math.pow(2,y-1075)*(T+4503599627370496)}c.readDoubleLE=r.bind(null,l,0,4),c.readDoubleBE=r.bind(null,d,4,0)})(),c}function i(c,s,r){s[r]=c&255,s[r+1]=c>>>8&255,s[r+2]=c>>>16&255,s[r+3]=c>>>24}function u(c,s,r){s[r]=c>>>24,s[r+1]=c>>>16&255,s[r+2]=c>>>8&255,s[r+3]=c&255}function l(c,s){return(c[s]|c[s+1]<<8|c[s+2]<<16|c[s+3]<<24)>>>0}function d(c,s){return(c[s]<<24|c[s+1]<<16|c[s+2]<<8|c[s+3])>>>0}}),AO=ae((e,t)=>{"use strict";t.exports=n;function n(i){try{if(typeof ju!="function")return null;var u=ju(i);return u&&(u.length||Object.keys(u).length)?u:null}catch{return null}}}),kO=ae(e=>{"use strict";var t=e,n="\uFFFD";t.length=function(i){for(var u=0,l=0,d=0;d=192&&s<224){var r=(s&31)<<6|i[c++]&63;d+=r>=128?String.fromCharCode(r):n}else if(s>=224&&s<240){var o=(s&15)<<12|(i[c++]&63)<<6|i[c++]&63;d+=o>=2048?String.fromCharCode(o):n}else if(s>=240){var a=(s&7)<<18|(i[c++]&63)<<12|(i[c++]&63)<<6|i[c++]&63;a<65536||a>1114111?d+=n:(a-=65536,d+=String.fromCharCode(55296+(a>>10)),d+=String.fromCharCode(56320+(a&1023)))}}return d},t.write=function(i,u,l){for(var d=l,c,s,r=0;r>6|192,u[l++]=c&63|128):(c&64512)===55296&&((s=i.charCodeAt(r+1))&64512)===56320?(c=65536+((c&1023)<<10)+(s&1023),++r,u[l++]=c>>18|240,u[l++]=c>>12&63|128,u[l++]=c>>6&63|128,u[l++]=c&63|128):(u[l++]=c>>12|224,u[l++]=c>>6&63|128,u[l++]=c&63|128);return l-d}}),PO=ae((e,t)=>{"use strict";t.exports=n;function n(i,u,l){var d=l||8192,c=d>>>1,s=null,r=d;return function(o){if(o<1||o>c)return i(o);r+o>d&&(s=i(d),r=0);var a=u.call(s,r,r+=o);return r&7&&(r=(r|7)+1),a}}}),CO=ae((e,t)=>{"use strict";t.exports=i;var n=_n();function i(c,s){this.lo=c>>>0,this.hi=s>>>0}var u=i.zero=new i(0,0);u.toNumber=function(){return 0},u.zzEncode=u.zzDecode=function(){return this},u.length=function(){return 1};var l=i.zeroHash="\0\0\0\0\0\0\0\0";i.fromNumber=function(c){if(c===0)return u;var s=c<0;s&&(c=-c);var r=c>>>0,o=(c-r)/4294967296>>>0;return s&&(o=~o>>>0,r=~r>>>0,++r>4294967295&&(r=0,++o>4294967295&&(o=0))),new i(r,o)},i.from=function(c){if(typeof c=="number")return i.fromNumber(c);if(n.isString(c))if(n.Long)c=n.Long.fromString(c);else return i.fromNumber(parseInt(c,10));return c.low||c.high?new i(c.low>>>0,c.high>>>0):u},i.prototype.toNumber=function(c){if(!c&&this.hi>>>31){var s=~this.lo+1>>>0,r=~this.hi>>>0;return s||(r=r+1>>>0),-(s+r*4294967296)}return this.lo+this.hi*4294967296},i.prototype.toLong=function(c){return n.Long?new n.Long(this.lo|0,this.hi|0,!!c):{low:this.lo|0,high:this.hi|0,unsigned:!!c}};var d=String.prototype.charCodeAt;i.fromHash=function(c){return c===l?u:new i((d.call(c,0)|d.call(c,1)<<8|d.call(c,2)<<16|d.call(c,3)<<24)>>>0,(d.call(c,4)|d.call(c,5)<<8|d.call(c,6)<<16|d.call(c,7)<<24)>>>0)},i.prototype.toHash=function(){return String.fromCharCode(this.lo&255,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,this.hi&255,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},i.prototype.zzEncode=function(){var c=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^c)>>>0,this.lo=(this.lo<<1^c)>>>0,this},i.prototype.zzDecode=function(){var c=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^c)>>>0,this.hi=(this.hi>>>1^c)>>>0,this},i.prototype.length=function(){var c=this.lo,s=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return r===0?s===0?c<16384?c<128?1:2:c<2097152?3:4:s<16384?s<128?5:6:s<2097152?7:8:r<128?9:10}}),RO=ae((e,t)=>{(function(n,i){function u(l){return l.default||l}typeof define=="function"&&define.amd?define([],function(){var l={};return i(l),u(l)}):typeof e=="object"?(i(e),typeof t=="object"&&(t.exports=u(e))):(function(){var l={};i(l),n.Long=u(l)})()})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:e,function(n){"use strict";Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var i=null;try{i=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch{}function u(v,R,H){this.low=v|0,this.high=R|0,this.unsigned=!!H}u.prototype.__isLong__,Object.defineProperty(u.prototype,"__isLong__",{value:!0});function l(v){return(v&&v.__isLong__)===!0}function d(v){var R=Math.clz32(v&-v);return v?31-R:R}u.isLong=l;var c={},s={};function r(v,R){var H,L,V;return R?(v>>>=0,(V=0<=v&&v<256)&&(L=s[v],L)?L:(H=a(v,0,!0),V&&(s[v]=H),H)):(v|=0,(V=-128<=v&&v<128)&&(L=c[v],L)?L:(H=a(v,v<0?-1:0,!1),V&&(c[v]=H),H))}u.fromInt=r;function o(v,R){if(isNaN(v))return R?A:O;if(R){if(v<0)return A;if(v>=y)return J}else{if(v<=-T)return G;if(v+1>=T)return q}return v<0?o(-v,R).neg():a(v%w|0,v/w|0,R)}u.fromNumber=o;function a(v,R,H){return new u(v,R,H)}u.fromBits=a;var p=Math.pow;function h(v,R,H){if(v.length===0)throw Error("empty string");if(typeof R=="number"?(H=R,R=!1):R=!!R,v==="NaN"||v==="Infinity"||v==="+Infinity"||v==="-Infinity")return R?A:O;if(H=H||10,H<2||360)throw Error("interior hyphen");if(L===0)return h(v.substring(1),R,H).neg();for(var V=o(p(H,8)),K=O,B=0;B>>0:this.low},C.toNumber=function(){return this.unsigned?(this.high>>>0)*w+(this.low>>>0):this.high*w+(this.low>>>0)},C.toString=function(v){if(v=v||10,v<2||36>>0,N=Y.toString(v);if(K=te,K.isZero())return N+B;for(;N.length<6;)N="0"+N;B=""+N+B}},C.getHighBits=function(){return this.high},C.getHighBitsUnsigned=function(){return this.high>>>0},C.getLowBits=function(){return this.low},C.getLowBitsUnsigned=function(){return this.low>>>0},C.getNumBitsAbs=function(){if(this.isNegative())return this.eq(G)?64:this.neg().getNumBitsAbs();for(var v=this.high!=0?this.high:this.low,R=31;R>0&&(v&1<>21;return v?this.unsigned?!1:v===-1&&!(this.low===0&&this.high===-2097152):!0},C.isZero=function(){return this.high===0&&this.low===0},C.eqz=C.isZero,C.isNegative=function(){return!this.unsigned&&this.high<0},C.isPositive=function(){return this.unsigned||this.high>=0},C.isOdd=function(){return(this.low&1)===1},C.isEven=function(){return(this.low&1)===0},C.equals=function(v){return l(v)||(v=m(v)),this.unsigned!==v.unsigned&&this.high>>>31===1&&v.high>>>31===1?!1:this.high===v.high&&this.low===v.low},C.eq=C.equals,C.notEquals=function(v){return!this.eq(v)},C.neq=C.notEquals,C.ne=C.notEquals,C.lessThan=function(v){return this.comp(v)<0},C.lt=C.lessThan,C.lessThanOrEqual=function(v){return this.comp(v)<=0},C.lte=C.lessThanOrEqual,C.le=C.lessThanOrEqual,C.greaterThan=function(v){return this.comp(v)>0},C.gt=C.greaterThan,C.greaterThanOrEqual=function(v){return this.comp(v)>=0},C.gte=C.greaterThanOrEqual,C.ge=C.greaterThanOrEqual,C.compare=function(v){if(l(v)||(v=m(v)),this.eq(v))return 0;var R=this.isNegative(),H=v.isNegative();return R&&!H?-1:!R&&H?1:this.unsigned?v.high>>>0>this.high>>>0||v.high===this.high&&v.low>>>0>this.low>>>0?-1:1:this.sub(v).isNegative()?-1:1},C.comp=C.compare,C.negate=function(){return!this.unsigned&&this.eq(G)?G:this.not().add(P)},C.neg=C.negate,C.add=function(v){l(v)||(v=m(v));var R=this.high>>>16,H=this.high&65535,L=this.low>>>16,V=this.low&65535,K=v.high>>>16,B=v.high&65535,te=v.low>>>16,Y=v.low&65535,N=0,X=0,W=0,re=0;return re+=V+Y,W+=re>>>16,re&=65535,W+=L+te,X+=W>>>16,W&=65535,X+=H+B,N+=X>>>16,X&=65535,N+=R+K,N&=65535,a(W<<16|re,N<<16|X,this.unsigned)},C.subtract=function(v){return l(v)||(v=m(v)),this.add(v.neg())},C.sub=C.subtract,C.multiply=function(v){if(this.isZero())return this;if(l(v)||(v=m(v)),i){var R=i.mul(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}if(v.isZero())return this.unsigned?A:O;if(this.eq(G))return v.isOdd()?G:O;if(v.eq(G))return this.isOdd()?G:O;if(this.isNegative())return v.isNegative()?this.neg().mul(v.neg()):this.neg().mul(v).neg();if(v.isNegative())return this.mul(v.neg()).neg();if(this.lt(S)&&v.lt(S))return o(this.toNumber()*v.toNumber(),this.unsigned);var H=this.high>>>16,L=this.high&65535,V=this.low>>>16,K=this.low&65535,B=v.high>>>16,te=v.high&65535,Y=v.low>>>16,N=v.low&65535,X=0,W=0,re=0,le=0;return le+=K*N,re+=le>>>16,le&=65535,re+=V*N,W+=re>>>16,re&=65535,re+=K*Y,W+=re>>>16,re&=65535,W+=L*N,X+=W>>>16,W&=65535,W+=V*Y,X+=W>>>16,W&=65535,W+=K*te,X+=W>>>16,W&=65535,X+=H*N+L*Y+V*te+K*B,X&=65535,a(re<<16|le,X<<16|W,this.unsigned)},C.mul=C.multiply,C.divide=function(v){if(l(v)||(v=m(v)),v.isZero())throw Error("division by zero");if(i){if(!this.unsigned&&this.high===-2147483648&&v.low===-1&&v.high===-1)return this;var R=(this.unsigned?i.div_u:i.div_s)(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?A:O;var H,L,V;if(this.unsigned){if(v.unsigned||(v=v.toUnsigned()),v.gt(this))return A;if(v.gt(this.shru(1)))return I;V=A}else{if(this.eq(G)){if(v.eq(P)||v.eq(z))return G;if(v.eq(G))return P;var K=this.shr(1);return H=K.div(v).shl(1),H.eq(O)?v.isNegative()?P:z:(L=this.sub(v.mul(H)),V=H.add(L.div(v)),V)}else if(v.eq(G))return this.unsigned?A:O;if(this.isNegative())return v.isNegative()?this.neg().div(v.neg()):this.neg().div(v).neg();if(v.isNegative())return this.div(v.neg()).neg();V=O}for(L=this;L.gte(v);){H=Math.max(1,Math.floor(L.toNumber()/v.toNumber()));for(var B=Math.ceil(Math.log(H)/Math.LN2),te=B<=48?1:p(2,B-48),Y=o(H),N=Y.mul(v);N.isNegative()||N.gt(L);)H-=te,Y=o(H,this.unsigned),N=Y.mul(v);Y.isZero()&&(Y=P),V=V.add(Y),L=L.sub(N)}return V},C.div=C.divide,C.modulo=function(v){if(l(v)||(v=m(v)),i){var R=(this.unsigned?i.rem_u:i.rem_s)(this.low,this.high,v.low,v.high);return a(R,i.get_high(),this.unsigned)}return this.sub(this.div(v).mul(v))},C.mod=C.modulo,C.rem=C.modulo,C.not=function(){return a(~this.low,~this.high,this.unsigned)},C.countLeadingZeros=function(){return this.high?Math.clz32(this.high):Math.clz32(this.low)+32},C.clz=C.countLeadingZeros,C.countTrailingZeros=function(){return this.low?d(this.low):d(this.high)+32},C.ctz=C.countTrailingZeros,C.and=function(v){return l(v)||(v=m(v)),a(this.low&v.low,this.high&v.high,this.unsigned)},C.or=function(v){return l(v)||(v=m(v)),a(this.low|v.low,this.high|v.high,this.unsigned)},C.xor=function(v){return l(v)||(v=m(v)),a(this.low^v.low,this.high^v.high,this.unsigned)},C.shiftLeft=function(v){return l(v)&&(v=v.toInt()),(v&=63)===0?this:v<32?a(this.low<>>32-v,this.unsigned):a(0,this.low<>>v|this.high<<32-v,this.high>>v,this.unsigned):a(this.high>>v-32,this.high>=0?0:-1,this.unsigned)},C.shr=C.shiftRight,C.shiftRightUnsigned=function(v){return l(v)&&(v=v.toInt()),(v&=63)===0?this:v<32?a(this.low>>>v|this.high<<32-v,this.high>>>v,this.unsigned):v===32?a(this.high,0,this.unsigned):a(this.high>>>v-32,0,this.unsigned)},C.shru=C.shiftRightUnsigned,C.shr_u=C.shiftRightUnsigned,C.rotateLeft=function(v){var R;return l(v)&&(v=v.toInt()),(v&=63)===0?this:v===32?a(this.high,this.low,this.unsigned):v<32?(R=32-v,a(this.low<>>R,this.high<>>R,this.unsigned)):(v-=32,R=32-v,a(this.high<>>R,this.low<>>R,this.unsigned))},C.rotl=C.rotateLeft,C.rotateRight=function(v){var R;return l(v)&&(v=v.toInt()),(v&=63)===0?this:v===32?a(this.high,this.low,this.unsigned):v<32?(R=32-v,a(this.high<>>v,this.low<>>v,this.unsigned)):(v-=32,R=32-v,a(this.low<>>v,this.high<>>v,this.unsigned))},C.rotr=C.rotateRight,C.toSigned=function(){return this.unsigned?a(this.low,this.high,!1):this},C.toUnsigned=function(){return this.unsigned?this:a(this.low,this.high,!0)},C.toBytes=function(v){return v?this.toBytesLE():this.toBytesBE()},C.toBytesLE=function(){var v=this.high,R=this.low;return[R&255,R>>>8&255,R>>>16&255,R>>>24,v&255,v>>>8&255,v>>>16&255,v>>>24]},C.toBytesBE=function(){var v=this.high,R=this.low;return[v>>>24,v>>>16&255,v>>>8&255,v&255,R>>>24,R>>>16&255,R>>>8&255,R&255]},u.fromBytes=function(v,R,H){return H?u.fromBytesLE(v,R):u.fromBytesBE(v,R)},u.fromBytesLE=function(v,R){return new u(v[0]|v[1]<<8|v[2]<<16|v[3]<<24,v[4]|v[5]<<8|v[6]<<16|v[7]<<24,R)},u.fromBytesBE=function(v,R){return new u(v[4]<<24|v[5]<<16|v[6]<<8|v[7],v[0]<<24|v[1]<<16|v[2]<<8|v[3],R)},typeof BigInt=="function"&&(u.fromBigInt=function(v,R){var H=Number(BigInt.asIntN(32,v)),L=Number(BigInt.asIntN(32,v>>BigInt(32)));return a(H,L,R)},u.fromValue=function(v,R){return typeof v=="bigint"?u.fromBigInt(v,R):m(v,R)},C.toBigInt=function(){var v=BigInt(this.low>>>0),R=BigInt(this.unsigned?this.high>>>0:this.high);return R<{"use strict";var t=e;t.asPromise=SO(),t.base64=IO(),t.EventEmitter=OO(),t.float=EO(),t.inquire=AO(),t.utf8=kO(),t.pool=PO(),t.LongBits=CO();function n(l){return l==="__proto__"||l==="prototype"||l==="constructor"}t.isUnsafeProperty=n,t.isNode=!!(typeof global<"u"&&global&&global.process&&global.process.versions&&global.process.versions.node),t.global=t.isNode&&global||typeof window<"u"&&window||typeof self<"u"&&self||e,t.emptyArray=Object.freeze?Object.freeze([]):[],t.emptyObject=Object.freeze?Object.freeze({}):{},t.isInteger=Number.isInteger||function(l){return typeof l=="number"&&isFinite(l)&&Math.floor(l)===l},t.isString=function(l){return typeof l=="string"||l instanceof String},t.isObject=function(l){return l&&typeof l=="object"},t.isset=t.isSet=function(l,d){var c=l[d];return c!=null&&Object.hasOwnProperty.call(l,d)?typeof c!="object"||(Array.isArray(c)?c.length:Object.keys(c).length)>0:!1},t.Buffer=(function(){try{var l=t.global.Buffer;return l.prototype.utf8Write?l:null}catch{return null}})(),t._Buffer_from=null,t._Buffer_allocUnsafe=null,t.newBuffer=function(l){return typeof l=="number"?t.Buffer?t._Buffer_allocUnsafe(l):new t.Array(l):t.Buffer?t._Buffer_from(l):typeof Uint8Array>"u"?l:new Uint8Array(l)},t.Array=typeof Uint8Array<"u"?Uint8Array:Array,t.Long=t.global.dcodeIO&&t.global.dcodeIO.Long||t.global.Long||(function(){try{var l=RO();return l&&l.isLong?l:null}catch{return null}})(),t.key2Re=/^true|false|0|1$/,t.key32Re=/^-?(?:0|[1-9][0-9]*)$/,t.key64Re=/^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/,t.longToHash=function(l){return l?t.LongBits.from(l).toHash():t.LongBits.zeroHash},t.longFromHash=function(l,d){var c=t.LongBits.fromHash(l);return t.Long?t.Long.fromBits(c.lo,c.hi,d):c.toNumber(!!d)};function i(l){var d=typeof arguments[arguments.length-1]=="boolean",c=d?arguments.length-1:arguments.length;d=d&&arguments[arguments.length-1];for(var s=1;s-1;--r)if(d[s[r]]===1&&this[s[r]]!==void 0&&this[s[r]]!==null)return s[r]}},t.oneOfSetter=function(l){return function(d){for(var c=0;c{"use strict";t.exports=o;var n=_n(),i,u=n.LongBits,l=n.base64,d=n.utf8;function c(y,T,S){this.fn=y,this.len=T,this.next=void 0,this.val=S}function s(){}function r(y){this.head=y.head,this.tail=y.tail,this.len=y.len,this.next=y.states}function o(){this.len=0,this.head=new c(s,0,0),this.tail=this.head,this.states=null}var a=function(){return n.Buffer?function(){return(o.create=function(){return new i})()}:function(){return new o}};o.create=a(),o.alloc=function(y){return new n.Array(y)},n.Array!==Array&&(o.alloc=n.pool(o.alloc,n.Array.prototype.subarray)),o.prototype._push=function(y,T,S){return this.tail=this.tail.next=new c(y,T,S),this.len+=T,this};function p(y,T,S){T[S]=y&255}function h(y,T,S){for(;y>127;)T[S++]=y&127|128,y>>>=7;T[S]=y}function m(y,T){this.len=y,this.next=void 0,this.val=T}m.prototype=Object.create(c.prototype),m.prototype.fn=h,o.prototype.uint32=function(y){return this.len+=(this.tail=this.tail.next=new m((y=y>>>0)<128?1:y<16384?2:y<2097152?3:y<268435456?4:5,y)).len,this},o.prototype.int32=function(y){return(y|=0)<0?this._push(g,10,u.fromNumber(y)):this.uint32(y)},o.prototype.sint32=function(y){return this.uint32((y<<1^y>>31)>>>0)};function g(y,T,S){for(var O=y.lo,A=y.hi;A;)T[S++]=O&127|128,O=(O>>>7|A<<25)>>>0,A>>>=7;for(;O>127;)T[S++]=O&127|128,O=O>>>7;T[S++]=O}o.prototype.uint64=function(y){var T=u.from(y);return this._push(g,T.length(),T)},o.prototype.int64=o.prototype.uint64,o.prototype.sint64=function(y){var T=u.from(y).zzEncode();return this._push(g,T.length(),T)},o.prototype.bool=function(y){return this._push(p,1,y?1:0)};function _(y,T,S){T[S]=y&255,T[S+1]=y>>>8&255,T[S+2]=y>>>16&255,T[S+3]=y>>>24}o.prototype.fixed32=function(y){return this._push(_,4,y>>>0)},o.prototype.sfixed32=o.prototype.fixed32,o.prototype.fixed64=function(y){var T=u.from(y);return this._push(_,4,T.lo)._push(_,4,T.hi)},o.prototype.sfixed64=o.prototype.fixed64,o.prototype.float=function(y){return this._push(n.float.writeFloatLE,4,y)},o.prototype.double=function(y){return this._push(n.float.writeDoubleLE,8,y)};var w=n.Array.prototype.set?function(y,T,S){T.set(y,S)}:function(y,T,S){for(var O=0;O>>0;if(!T)return this._push(p,1,0);if(n.isString(y)){var S=o.alloc(T=l.length(y));l.decode(y,S,0),y=S}return this.uint32(T)._push(w,T,y)},o.prototype.string=function(y){var T=d.length(y);return T?this.uint32(T)._push(d.write,T,y):this._push(p,1,0)},o.prototype.fork=function(){return this.states=new r(this),this.head=this.tail=new c(s,0,0),this.len=0,this},o.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new c(s,0,0),this.len=0),this},o.prototype.ldelim=function(){var y=this.head,T=this.tail,S=this.len;return this.reset().uint32(S),S&&(this.tail.next=y.next,this.tail=T,this.len+=S),this},o.prototype.finish=function(){for(var y=this.head.next,T=this.constructor.alloc(this.len),S=0;y;)y.fn(y.val,T,S),S+=y.len,y=y.next;return T},o._configure=function(y){i=y,o.create=a(),i._configure()}}),DO=ae((e,t)=>{"use strict";t.exports=u;var n=$w();(u.prototype=Object.create(n.prototype)).constructor=u;var i=_n();function u(){n.call(this)}u._configure=function(){u.alloc=i._Buffer_allocUnsafe,u.writeBytesBuffer=i.Buffer&&i.Buffer.prototype instanceof Uint8Array&&i.Buffer.prototype.set.name==="set"?function(d,c,s){c.set(d,s)}:function(d,c,s){if(d.copy)d.copy(c,s,0,d.length);else for(var r=0;r>>0;return this.uint32(c),c&&this._push(u.writeBytesBuffer,c,d),this};function l(d,c,s){d.length<40?i.utf8.write(d,c,s):c.utf8Write?c.utf8Write(d,s):c.write(d,s)}u.prototype.string=function(d){var c=i.Buffer.byteLength(d);return this.uint32(c),c&&this._push(l,c,d),this},u._configure()}),Tw=ae((e,t)=>{"use strict";t.exports=c;var n=_n(),i,u=n.LongBits,l=n.utf8;function d(h,m){return RangeError("index out of range: "+h.pos+" + "+(m||1)+" > "+h.len)}function c(h){this.buf=h,this.pos=0,this.len=h.length}var s=typeof Uint8Array<"u"?function(h){if(h instanceof Uint8Array||Array.isArray(h))return new c(h);throw Error("illegal buffer")}:function(h){if(Array.isArray(h))return new c(h);throw Error("illegal buffer")},r=function(){return n.Buffer?function(h){return(c.create=function(m){return n.Buffer.isBuffer(m)?new i(m):s(m)})(h)}:s};c.create=r(),c.prototype._slice=n.Array.prototype.subarray||n.Array.prototype.slice,c.prototype.uint32=(function(){var h=4294967295;return function(){if(h=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(h=(h|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(h=(h|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return h;if((this.pos+=5)>this.len)throw this.pos=this.len,d(this,10);return h}})(),c.prototype.int32=function(){return this.uint32()|0},c.prototype.sint32=function(){var h=this.uint32();return h>>>1^-(h&1)|0};function o(){var h=new u(0,0),m=0;if(this.len-this.pos>4){for(;m<4;++m)if(h.lo=(h.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h;if(h.lo=(h.lo|(this.buf[this.pos]&127)<<28)>>>0,h.hi=(h.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return h;m=0}else{for(;m<3;++m){if(this.pos>=this.len)throw d(this);if(h.lo=(h.lo|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}return h.lo=(h.lo|(this.buf[this.pos++]&127)<>>0,h}if(this.len-this.pos>4){for(;m<5;++m)if(h.hi=(h.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}else for(;m<5;++m){if(this.pos>=this.len)throw d(this);if(h.hi=(h.hi|(this.buf[this.pos]&127)<>>0,this.buf[this.pos++]<128)return h}throw Error("invalid varint encoding")}c.prototype.bool=function(){return this.uint32()!==0};function a(h,m){return(h[m-4]|h[m-3]<<8|h[m-2]<<16|h[m-1]<<24)>>>0}c.prototype.fixed32=function(){if(this.pos+4>this.len)throw d(this,4);return a(this.buf,this.pos+=4)},c.prototype.sfixed32=function(){if(this.pos+4>this.len)throw d(this,4);return a(this.buf,this.pos+=4)|0};function p(){if(this.pos+8>this.len)throw d(this,8);return new u(a(this.buf,this.pos+=4),a(this.buf,this.pos+=4))}c.prototype.float=function(){if(this.pos+4>this.len)throw d(this,4);var h=n.float.readFloatLE(this.buf,this.pos);return this.pos+=4,h},c.prototype.double=function(){if(this.pos+8>this.len)throw d(this,4);var h=n.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,h},c.prototype.bytes=function(){var h=this.uint32(),m=this.pos,g=this.pos+h;if(g>this.len)throw d(this,h);if(this.pos+=h,Array.isArray(this.buf))return this.buf.slice(m,g);if(m===g){var _=n.Buffer;return _?_.alloc(0):new this.buf.constructor(0)}return this._slice.call(this.buf,m,g)},c.prototype.string=function(){var h=this.bytes();return l.read(h,0,h.length)},c.prototype.skip=function(h){if(typeof h=="number"){if(this.pos+h>this.len)throw d(this,h);this.pos+=h}else do if(this.pos>=this.len)throw d(this);while(this.buf[this.pos++]&128);return this},c.recursionLimit=n.recursionLimit,c.prototype.skipType=function(h,m){if(m===void 0&&(m=0),m>c.recursionLimit)throw Error("maximum nesting depth exceeded");switch(h){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(h=this.uint32()&7)!==4;)this.skipType(h,m+1);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+h+" at offset "+this.pos)}return this},c._configure=function(h){i=h,c.create=r(),i._configure();var m=n.Long?"toLong":"toNumber";n.merge(c.prototype,{int64:function(){return o.call(this)[m](!1)},uint64:function(){return o.call(this)[m](!0)},sint64:function(){return o.call(this).zzDecode()[m](!1)},fixed64:function(){return p.call(this)[m](!0)},sfixed64:function(){return p.call(this)[m](!1)}})}}),MO=ae((e,t)=>{"use strict";t.exports=u;var n=Tw();(u.prototype=Object.create(n.prototype)).constructor=u;var i=_n();function u(l){n.call(this,l)}u._configure=function(){i.Buffer&&(u.prototype._slice=i.Buffer.prototype.slice)},u.prototype.string=function(){var l=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+l,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+l,this.len))},u._configure()}),NO=ae((e,t)=>{"use strict";t.exports=i;var n=_n();(i.prototype=Object.create(n.EventEmitter.prototype)).constructor=i;function i(u,l,d){if(typeof u!="function")throw TypeError("rpcImpl must be a function");n.EventEmitter.call(this),this.rpcImpl=u,this.requestDelimited=!!l,this.responseDelimited=!!d}i.prototype.rpcCall=function u(l,d,c,s,r){if(!s)throw TypeError("request must be specified");var o=this;if(!r)return n.asPromise(u,o,l,d,c,s);if(!o.rpcImpl){setTimeout(function(){r(Error("already ended"))},0);return}try{return o.rpcImpl(l,d[o.requestDelimited?"encodeDelimited":"encode"](s).finish(),function(a,p){if(a)return o.emit("error",a,l),r(a);if(p===null){o.end(!0);return}if(!(p instanceof c))try{p=c[o.responseDelimited?"decodeDelimited":"decode"](p)}catch(h){return o.emit("error",h,l),r(h)}return o.emit("data",p,l),r(null,p)})}catch(a){o.emit("error",a,l),setTimeout(function(){r(a)},0);return}},i.prototype.end=function(u){return this.rpcImpl&&(u||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}}),zO=ae(e=>{"use strict";var t=e;t.Service=NO()}),BO=ae((e,t)=>{"use strict";t.exports=Object.create(null)}),FO=ae(e=>{"use strict";var t=e;t.build="minimal",t.Writer=$w(),t.BufferWriter=DO(),t.Reader=Tw(),t.BufferReader=MO(),t.util=_n(),t.rpc=zO(),t.roots=BO(),t.configure=n;function n(){t.util._configure(),t.Writer._configure(t.BufferWriter),t.Reader._configure(t.BufferReader)}n()}),LO=ae((e,t)=>{"use strict";t.exports=FO()}),Bi=ae((e,t)=>{"use strict";var n=LO(),i=n.Reader,u=n.Writer,l=n.util,d=n.roots.default||(n.roots.default={});d.onnx=(function(){var c={};return c.Version=(function(){var s={},r=Object.create(s);return r[s[0]="_START_VERSION"]=0,r[s[1]="IR_VERSION_2017_10_10"]=1,r[s[2]="IR_VERSION_2017_10_30"]=2,r[s[3]="IR_VERSION_2017_11_3"]=3,r[s[4]="IR_VERSION_2019_1_22"]=4,r[s[5]="IR_VERSION_2019_3_18"]=5,r[s[6]="IR_VERSION_2019_9_19"]=6,r[s[7]="IR_VERSION_2020_5_8"]=7,r[s[8]="IR_VERSION_2021_7_30"]=8,r[s[9]="IR_VERSION"]=9,r})(),c.AttributeProto=(function(){function s(r){if(this.floats=[],this.ints=[],this.strings=[],this.tensors=[],this.graphs=[],this.sparseTensors=[],this.typeProtos=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.name=r.string();break}case 21:{p.refAttrName=r.string();break}case 13:{p.docString=r.string();break}case 20:{p.type=r.int32();break}case 2:{p.f=r.float();break}case 3:{p.i=r.int64();break}case 4:{p.s=r.bytes();break}case 5:{p.t=d.onnx.TensorProto.decode(r,r.uint32());break}case 6:{p.g=d.onnx.GraphProto.decode(r,r.uint32());break}case 22:{p.sparseTensor=d.onnx.SparseTensorProto.decode(r,r.uint32());break}case 14:{p.tp=d.onnx.TypeProto.decode(r,r.uint32());break}case 7:{if(p.floats&&p.floats.length||(p.floats=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.i.high>>>0).toNumber())),r.s!=null&&(typeof r.s=="string"?l.base64.decode(r.s,o.s=l.newBuffer(l.base64.length(r.s)),0):r.s.length>=0&&(o.s=r.s)),r.t!=null){if(typeof r.t!="object")throw TypeError(".onnx.AttributeProto.t: object expected");o.t=d.onnx.TensorProto.fromObject(r.t)}if(r.g!=null){if(typeof r.g!="object")throw TypeError(".onnx.AttributeProto.g: object expected");o.g=d.onnx.GraphProto.fromObject(r.g)}if(r.sparseTensor!=null){if(typeof r.sparseTensor!="object")throw TypeError(".onnx.AttributeProto.sparseTensor: object expected");o.sparseTensor=d.onnx.SparseTensorProto.fromObject(r.sparseTensor)}if(r.tp!=null){if(typeof r.tp!="object")throw TypeError(".onnx.AttributeProto.tp: object expected");o.tp=d.onnx.TypeProto.fromObject(r.tp)}if(r.floats){if(!Array.isArray(r.floats))throw TypeError(".onnx.AttributeProto.floats: array expected");o.floats=[];for(var a=0;a>>0,r.ints[a].high>>>0).toNumber())}if(r.strings){if(!Array.isArray(r.strings))throw TypeError(".onnx.AttributeProto.strings: array expected");o.strings=[];for(var a=0;a=0&&(o.strings[a]=r.strings[a])}if(r.tensors){if(!Array.isArray(r.tensors))throw TypeError(".onnx.AttributeProto.tensors: array expected");o.tensors=[];for(var a=0;a>>0,r.i.high>>>0).toNumber():r.i),r.s!=null&&r.hasOwnProperty("s")&&(a.s=o.bytes===String?l.base64.encode(r.s,0,r.s.length):o.bytes===Array?Array.prototype.slice.call(r.s):r.s),r.t!=null&&r.hasOwnProperty("t")&&(a.t=d.onnx.TensorProto.toObject(r.t,o)),r.g!=null&&r.hasOwnProperty("g")&&(a.g=d.onnx.GraphProto.toObject(r.g,o)),r.floats&&r.floats.length){a.floats=[];for(var h=0;h>>0,r.ints[h].high>>>0).toNumber():r.ints[h]}if(r.strings&&r.strings.length){a.strings=[];for(var h=0;h>>3){case 1:{p.name=r.string();break}case 2:{p.type=d.onnx.TypeProto.decode(r,r.uint32());break}case 3:{p.docString=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.name!=null&&r.hasOwnProperty("name")&&!l.isString(r.name))return"name: string expected";if(r.type!=null&&r.hasOwnProperty("type")){var o=d.onnx.TypeProto.verify(r.type);if(o)return"type."+o}return r.docString!=null&&r.hasOwnProperty("docString")&&!l.isString(r.docString)?"docString: string expected":null},s.fromObject=function(r){if(r instanceof d.onnx.ValueInfoProto)return r;var o=new d.onnx.ValueInfoProto;if(r.name!=null&&(o.name=String(r.name)),r.type!=null){if(typeof r.type!="object")throw TypeError(".onnx.ValueInfoProto.type: object expected");o.type=d.onnx.TypeProto.fromObject(r.type)}return r.docString!=null&&(o.docString=String(r.docString)),o},s.toObject=function(r,o){o||(o={});var a={};return o.defaults&&(a.name="",a.type=null,a.docString=""),r.name!=null&&r.hasOwnProperty("name")&&(a.name=r.name),r.type!=null&&r.hasOwnProperty("type")&&(a.type=d.onnx.TypeProto.toObject(r.type,o)),r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.ValueInfoProto"},s})(),c.NodeProto=(function(){function s(r){if(this.input=[],this.output=[],this.attribute=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.input&&p.input.length||(p.input=[]),p.input.push(r.string());break}case 2:{p.output&&p.output.length||(p.output=[]),p.output.push(r.string());break}case 3:{p.name=r.string();break}case 4:{p.opType=r.string();break}case 7:{p.domain=r.string();break}case 5:{p.attribute&&p.attribute.length||(p.attribute=[]),p.attribute.push(d.onnx.AttributeProto.decode(r,r.uint32()));break}case 6:{p.docString=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.input!=null&&r.hasOwnProperty("input")){if(!Array.isArray(r.input))return"input: array expected";for(var o=0;o>>3){case 1:{p.initialization=d.onnx.GraphProto.decode(r,r.uint32());break}case 2:{p.algorithm=d.onnx.GraphProto.decode(r,r.uint32());break}case 3:{p.initializationBinding&&p.initializationBinding.length||(p.initializationBinding=[]),p.initializationBinding.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}case 4:{p.updateBinding&&p.updateBinding.length||(p.updateBinding=[]),p.updateBinding.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.initialization!=null&&r.hasOwnProperty("initialization")){var o=d.onnx.GraphProto.verify(r.initialization);if(o)return"initialization."+o}if(r.algorithm!=null&&r.hasOwnProperty("algorithm")){var o=d.onnx.GraphProto.verify(r.algorithm);if(o)return"algorithm."+o}if(r.initializationBinding!=null&&r.hasOwnProperty("initializationBinding")){if(!Array.isArray(r.initializationBinding))return"initializationBinding: array expected";for(var a=0;a>>3){case 1:{p.irVersion=r.int64();break}case 8:{p.opsetImport&&p.opsetImport.length||(p.opsetImport=[]),p.opsetImport.push(d.onnx.OperatorSetIdProto.decode(r,r.uint32()));break}case 2:{p.producerName=r.string();break}case 3:{p.producerVersion=r.string();break}case 4:{p.domain=r.string();break}case 5:{p.modelVersion=r.int64();break}case 6:{p.docString=r.string();break}case 7:{p.graph=d.onnx.GraphProto.decode(r,r.uint32());break}case 14:{p.metadataProps&&p.metadataProps.length||(p.metadataProps=[]),p.metadataProps.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}case 20:{p.trainingInfo&&p.trainingInfo.length||(p.trainingInfo=[]),p.trainingInfo.push(d.onnx.TrainingInfoProto.decode(r,r.uint32()));break}case 25:{p.functions&&p.functions.length||(p.functions=[]),p.functions.push(d.onnx.FunctionProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.irVersion!=null&&r.hasOwnProperty("irVersion")&&!l.isInteger(r.irVersion)&&!(r.irVersion&&l.isInteger(r.irVersion.low)&&l.isInteger(r.irVersion.high)))return"irVersion: integer|Long expected";if(r.opsetImport!=null&&r.hasOwnProperty("opsetImport")){if(!Array.isArray(r.opsetImport))return"opsetImport: array expected";for(var o=0;o>>0,r.irVersion.high>>>0).toNumber())),r.opsetImport){if(!Array.isArray(r.opsetImport))throw TypeError(".onnx.ModelProto.opsetImport: array expected");o.opsetImport=[];for(var a=0;a>>0,r.modelVersion.high>>>0).toNumber())),r.docString!=null&&(o.docString=String(r.docString)),r.graph!=null){if(typeof r.graph!="object")throw TypeError(".onnx.ModelProto.graph: object expected");o.graph=d.onnx.GraphProto.fromObject(r.graph)}if(r.metadataProps){if(!Array.isArray(r.metadataProps))throw TypeError(".onnx.ModelProto.metadataProps: array expected");o.metadataProps=[];for(var a=0;a>>0,r.irVersion.high>>>0).toNumber():r.irVersion),r.producerName!=null&&r.hasOwnProperty("producerName")&&(a.producerName=r.producerName),r.producerVersion!=null&&r.hasOwnProperty("producerVersion")&&(a.producerVersion=r.producerVersion),r.domain!=null&&r.hasOwnProperty("domain")&&(a.domain=r.domain),r.modelVersion!=null&&r.hasOwnProperty("modelVersion")&&(typeof r.modelVersion=="number"?a.modelVersion=o.longs===String?String(r.modelVersion):r.modelVersion:a.modelVersion=o.longs===String?l.Long.prototype.toString.call(r.modelVersion):o.longs===Number?new l.LongBits(r.modelVersion.low>>>0,r.modelVersion.high>>>0).toNumber():r.modelVersion),r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),r.graph!=null&&r.hasOwnProperty("graph")&&(a.graph=d.onnx.GraphProto.toObject(r.graph,o)),r.opsetImport&&r.opsetImport.length){a.opsetImport=[];for(var h=0;h>>3){case 1:{p.key=r.string();break}case 2:{p.value=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){return typeof r!="object"||r===null?"object expected":r.key!=null&&r.hasOwnProperty("key")&&!l.isString(r.key)?"key: string expected":r.value!=null&&r.hasOwnProperty("value")&&!l.isString(r.value)?"value: string expected":null},s.fromObject=function(r){if(r instanceof d.onnx.StringStringEntryProto)return r;var o=new d.onnx.StringStringEntryProto;return r.key!=null&&(o.key=String(r.key)),r.value!=null&&(o.value=String(r.value)),o},s.toObject=function(r,o){o||(o={});var a={};return o.defaults&&(a.key="",a.value=""),r.key!=null&&r.hasOwnProperty("key")&&(a.key=r.key),r.value!=null&&r.hasOwnProperty("value")&&(a.value=r.value),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.StringStringEntryProto"},s})(),c.TensorAnnotation=(function(){function s(r){if(this.quantParameterTensorNames=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.tensorName=r.string();break}case 2:{p.quantParameterTensorNames&&p.quantParameterTensorNames.length||(p.quantParameterTensorNames=[]),p.quantParameterTensorNames.push(d.onnx.StringStringEntryProto.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.tensorName!=null&&r.hasOwnProperty("tensorName")&&!l.isString(r.tensorName))return"tensorName: string expected";if(r.quantParameterTensorNames!=null&&r.hasOwnProperty("quantParameterTensorNames")){if(!Array.isArray(r.quantParameterTensorNames))return"quantParameterTensorNames: array expected";for(var o=0;o>>3){case 1:{p.node&&p.node.length||(p.node=[]),p.node.push(d.onnx.NodeProto.decode(r,r.uint32()));break}case 2:{p.name=r.string();break}case 5:{p.initializer&&p.initializer.length||(p.initializer=[]),p.initializer.push(d.onnx.TensorProto.decode(r,r.uint32()));break}case 15:{p.sparseInitializer&&p.sparseInitializer.length||(p.sparseInitializer=[]),p.sparseInitializer.push(d.onnx.SparseTensorProto.decode(r,r.uint32()));break}case 10:{p.docString=r.string();break}case 11:{p.input&&p.input.length||(p.input=[]),p.input.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 12:{p.output&&p.output.length||(p.output=[]),p.output.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 13:{p.valueInfo&&p.valueInfo.length||(p.valueInfo=[]),p.valueInfo.push(d.onnx.ValueInfoProto.decode(r,r.uint32()));break}case 14:{p.quantizationAnnotation&&p.quantizationAnnotation.length||(p.quantizationAnnotation=[]),p.quantizationAnnotation.push(d.onnx.TensorAnnotation.decode(r,r.uint32()));break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.node!=null&&r.hasOwnProperty("node")){if(!Array.isArray(r.node))return"node: array expected";for(var o=0;o>>3){case 1:{if(p.dims&&p.dims.length||(p.dims=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.dims[a].high>>>0).toNumber())}if(r.dataType!=null&&(o.dataType=r.dataType|0),r.segment!=null){if(typeof r.segment!="object")throw TypeError(".onnx.TensorProto.segment: object expected");o.segment=d.onnx.TensorProto.Segment.fromObject(r.segment)}if(r.floatData){if(!Array.isArray(r.floatData))throw TypeError(".onnx.TensorProto.floatData: array expected");o.floatData=[];for(var a=0;a=0&&(o.stringData[a]=r.stringData[a])}if(r.int64Data){if(!Array.isArray(r.int64Data))throw TypeError(".onnx.TensorProto.int64Data: array expected");o.int64Data=[];for(var a=0;a>>0,r.int64Data[a].high>>>0).toNumber())}if(r.name!=null&&(o.name=String(r.name)),r.docString!=null&&(o.docString=String(r.docString)),r.rawData!=null&&(typeof r.rawData=="string"?l.base64.decode(r.rawData,o.rawData=l.newBuffer(l.base64.length(r.rawData)),0):r.rawData.length>=0&&(o.rawData=r.rawData)),r.externalData){if(!Array.isArray(r.externalData))throw TypeError(".onnx.TensorProto.externalData: array expected");o.externalData=[];for(var a=0;a>>0,r.uint64Data[a].high>>>0).toNumber(!0))}return o},s.toObject=function(r,o){o||(o={});var a={};if((o.arrays||o.defaults)&&(a.dims=[],a.floatData=[],a.int32Data=[],a.stringData=[],a.int64Data=[],a.doubleData=[],a.uint64Data=[],a.externalData=[]),o.defaults&&(a.dataType=0,a.segment=null,a.name="",o.bytes===String?a.rawData="":(a.rawData=[],o.bytes!==Array&&(a.rawData=l.newBuffer(a.rawData))),a.docString="",a.dataLocation=o.enums===String?"DEFAULT":0),r.dims&&r.dims.length){a.dims=[];for(var p=0;p>>0,r.dims[p].high>>>0).toNumber():r.dims[p]}if(r.dataType!=null&&r.hasOwnProperty("dataType")&&(a.dataType=r.dataType),r.segment!=null&&r.hasOwnProperty("segment")&&(a.segment=d.onnx.TensorProto.Segment.toObject(r.segment,o)),r.floatData&&r.floatData.length){a.floatData=[];for(var p=0;p>>0,r.int64Data[p].high>>>0).toNumber():r.int64Data[p]}if(r.name!=null&&r.hasOwnProperty("name")&&(a.name=r.name),r.rawData!=null&&r.hasOwnProperty("rawData")&&(a.rawData=o.bytes===String?l.base64.encode(r.rawData,0,r.rawData.length):o.bytes===Array?Array.prototype.slice.call(r.rawData):r.rawData),r.doubleData&&r.doubleData.length){a.doubleData=[];for(var p=0;p>>0,r.uint64Data[p].high>>>0).toNumber(!0):r.uint64Data[p]}if(r.docString!=null&&r.hasOwnProperty("docString")&&(a.docString=r.docString),r.externalData&&r.externalData.length){a.externalData=[];for(var p=0;p>>3){case 1:{h.begin=o.int64();break}case 2:{h.end=o.int64();break}default:o.skipType(m&7);break}}return h},r.decodeDelimited=function(o){return o instanceof i||(o=new i(o)),this.decode(o,o.uint32())},r.verify=function(o){return typeof o!="object"||o===null?"object expected":o.begin!=null&&o.hasOwnProperty("begin")&&!l.isInteger(o.begin)&&!(o.begin&&l.isInteger(o.begin.low)&&l.isInteger(o.begin.high))?"begin: integer|Long expected":o.end!=null&&o.hasOwnProperty("end")&&!l.isInteger(o.end)&&!(o.end&&l.isInteger(o.end.low)&&l.isInteger(o.end.high))?"end: integer|Long expected":null},r.fromObject=function(o){if(o instanceof d.onnx.TensorProto.Segment)return o;var a=new d.onnx.TensorProto.Segment;return o.begin!=null&&(l.Long?(a.begin=l.Long.fromValue(o.begin)).unsigned=!1:typeof o.begin=="string"?a.begin=parseInt(o.begin,10):typeof o.begin=="number"?a.begin=o.begin:typeof o.begin=="object"&&(a.begin=new l.LongBits(o.begin.low>>>0,o.begin.high>>>0).toNumber())),o.end!=null&&(l.Long?(a.end=l.Long.fromValue(o.end)).unsigned=!1:typeof o.end=="string"?a.end=parseInt(o.end,10):typeof o.end=="number"?a.end=o.end:typeof o.end=="object"&&(a.end=new l.LongBits(o.end.low>>>0,o.end.high>>>0).toNumber())),a},r.toObject=function(o,a){a||(a={});var p={};if(a.defaults){if(l.Long){var h=new l.Long(0,0,!1);p.begin=a.longs===String?h.toString():a.longs===Number?h.toNumber():h}else p.begin=a.longs===String?"0":0;if(l.Long){var h=new l.Long(0,0,!1);p.end=a.longs===String?h.toString():a.longs===Number?h.toNumber():h}else p.end=a.longs===String?"0":0}return o.begin!=null&&o.hasOwnProperty("begin")&&(typeof o.begin=="number"?p.begin=a.longs===String?String(o.begin):o.begin:p.begin=a.longs===String?l.Long.prototype.toString.call(o.begin):a.longs===Number?new l.LongBits(o.begin.low>>>0,o.begin.high>>>0).toNumber():o.begin),o.end!=null&&o.hasOwnProperty("end")&&(typeof o.end=="number"?p.end=a.longs===String?String(o.end):o.end:p.end=a.longs===String?l.Long.prototype.toString.call(o.end):a.longs===Number?new l.LongBits(o.end.low>>>0,o.end.high>>>0).toNumber():o.end),p},r.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},r.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TensorProto.Segment"},r})(),s.DataLocation=(function(){var r={},o=Object.create(r);return o[r[0]="DEFAULT"]=0,o[r[1]="EXTERNAL"]=1,o})(),s})(),c.SparseTensorProto=(function(){function s(r){if(this.dims=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.values=d.onnx.TensorProto.decode(r,r.uint32());break}case 2:{p.indices=d.onnx.TensorProto.decode(r,r.uint32());break}case 3:{if(p.dims&&p.dims.length||(p.dims=[]),(h&7)===2)for(var m=r.uint32()+r.pos;r.pos>>0,r.dims[a].high>>>0).toNumber())}return o},s.toObject=function(r,o){o||(o={});var a={};if((o.arrays||o.defaults)&&(a.dims=[]),o.defaults&&(a.values=null,a.indices=null),r.values!=null&&r.hasOwnProperty("values")&&(a.values=d.onnx.TensorProto.toObject(r.values,o)),r.indices!=null&&r.hasOwnProperty("indices")&&(a.indices=d.onnx.TensorProto.toObject(r.indices,o)),r.dims&&r.dims.length){a.dims=[];for(var p=0;p>>0,r.dims[p].high>>>0).toNumber():r.dims[p]}return a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.SparseTensorProto"},s})(),c.TensorShapeProto=(function(){function s(r){if(this.dim=[],r)for(var o=Object.keys(r),a=0;a>>3===1?(p.dim&&p.dim.length||(p.dim=[]),p.dim.push(d.onnx.TensorShapeProto.Dimension.decode(r,r.uint32()))):r.skipType(h&7)}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.dim!=null&&r.hasOwnProperty("dim")){if(!Array.isArray(r.dim))return"dim: array expected";for(var o=0;o>>3){case 1:{m.dimValue=a.int64();break}case 2:{m.dimParam=a.string();break}case 3:{m.denotation=a.string();break}default:a.skipType(g&7);break}}return m},r.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},r.verify=function(a){if(typeof a!="object"||a===null)return"object expected";var p={};if(a.dimValue!=null&&a.hasOwnProperty("dimValue")&&(p.value=1,!l.isInteger(a.dimValue)&&!(a.dimValue&&l.isInteger(a.dimValue.low)&&l.isInteger(a.dimValue.high))))return"dimValue: integer|Long expected";if(a.dimParam!=null&&a.hasOwnProperty("dimParam")){if(p.value===1)return"value: multiple values";if(p.value=1,!l.isString(a.dimParam))return"dimParam: string expected"}return a.denotation!=null&&a.hasOwnProperty("denotation")&&!l.isString(a.denotation)?"denotation: string expected":null},r.fromObject=function(a){if(a instanceof d.onnx.TensorShapeProto.Dimension)return a;var p=new d.onnx.TensorShapeProto.Dimension;return a.dimValue!=null&&(l.Long?(p.dimValue=l.Long.fromValue(a.dimValue)).unsigned=!1:typeof a.dimValue=="string"?p.dimValue=parseInt(a.dimValue,10):typeof a.dimValue=="number"?p.dimValue=a.dimValue:typeof a.dimValue=="object"&&(p.dimValue=new l.LongBits(a.dimValue.low>>>0,a.dimValue.high>>>0).toNumber())),a.dimParam!=null&&(p.dimParam=String(a.dimParam)),a.denotation!=null&&(p.denotation=String(a.denotation)),p},r.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.denotation=""),a.dimValue!=null&&a.hasOwnProperty("dimValue")&&(typeof a.dimValue=="number"?h.dimValue=p.longs===String?String(a.dimValue):a.dimValue:h.dimValue=p.longs===String?l.Long.prototype.toString.call(a.dimValue):p.longs===Number?new l.LongBits(a.dimValue.low>>>0,a.dimValue.high>>>0).toNumber():a.dimValue,p.oneofs&&(h.value="dimValue")),a.dimParam!=null&&a.hasOwnProperty("dimParam")&&(h.dimParam=a.dimParam,p.oneofs&&(h.value="dimParam")),a.denotation!=null&&a.hasOwnProperty("denotation")&&(h.denotation=a.denotation),h},r.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},r.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TensorShapeProto.Dimension"},r})(),s})(),c.TypeProto=(function(){function s(o){if(o)for(var a=Object.keys(o),p=0;p>>3){case 1:{h.tensorType=d.onnx.TypeProto.Tensor.decode(o,o.uint32());break}case 4:{h.sequenceType=d.onnx.TypeProto.Sequence.decode(o,o.uint32());break}case 5:{h.mapType=d.onnx.TypeProto.Map.decode(o,o.uint32());break}case 9:{h.optionalType=d.onnx.TypeProto.Optional.decode(o,o.uint32());break}case 8:{h.sparseTensorType=d.onnx.TypeProto.SparseTensor.decode(o,o.uint32());break}case 6:{h.denotation=o.string();break}default:o.skipType(m&7);break}}return h},s.decodeDelimited=function(o){return o instanceof i||(o=new i(o)),this.decode(o,o.uint32())},s.verify=function(o){if(typeof o!="object"||o===null)return"object expected";var a={};if(o.tensorType!=null&&o.hasOwnProperty("tensorType")){a.value=1;{var p=d.onnx.TypeProto.Tensor.verify(o.tensorType);if(p)return"tensorType."+p}}if(o.sequenceType!=null&&o.hasOwnProperty("sequenceType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Sequence.verify(o.sequenceType);if(p)return"sequenceType."+p}}if(o.mapType!=null&&o.hasOwnProperty("mapType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Map.verify(o.mapType);if(p)return"mapType."+p}}if(o.optionalType!=null&&o.hasOwnProperty("optionalType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.Optional.verify(o.optionalType);if(p)return"optionalType."+p}}if(o.sparseTensorType!=null&&o.hasOwnProperty("sparseTensorType")){if(a.value===1)return"value: multiple values";a.value=1;{var p=d.onnx.TypeProto.SparseTensor.verify(o.sparseTensorType);if(p)return"sparseTensorType."+p}}return o.denotation!=null&&o.hasOwnProperty("denotation")&&!l.isString(o.denotation)?"denotation: string expected":null},s.fromObject=function(o){if(o instanceof d.onnx.TypeProto)return o;var a=new d.onnx.TypeProto;if(o.tensorType!=null){if(typeof o.tensorType!="object")throw TypeError(".onnx.TypeProto.tensorType: object expected");a.tensorType=d.onnx.TypeProto.Tensor.fromObject(o.tensorType)}if(o.sequenceType!=null){if(typeof o.sequenceType!="object")throw TypeError(".onnx.TypeProto.sequenceType: object expected");a.sequenceType=d.onnx.TypeProto.Sequence.fromObject(o.sequenceType)}if(o.mapType!=null){if(typeof o.mapType!="object")throw TypeError(".onnx.TypeProto.mapType: object expected");a.mapType=d.onnx.TypeProto.Map.fromObject(o.mapType)}if(o.optionalType!=null){if(typeof o.optionalType!="object")throw TypeError(".onnx.TypeProto.optionalType: object expected");a.optionalType=d.onnx.TypeProto.Optional.fromObject(o.optionalType)}if(o.sparseTensorType!=null){if(typeof o.sparseTensorType!="object")throw TypeError(".onnx.TypeProto.sparseTensorType: object expected");a.sparseTensorType=d.onnx.TypeProto.SparseTensor.fromObject(o.sparseTensorType)}return o.denotation!=null&&(a.denotation=String(o.denotation)),a},s.toObject=function(o,a){a||(a={});var p={};return a.defaults&&(p.denotation=""),o.tensorType!=null&&o.hasOwnProperty("tensorType")&&(p.tensorType=d.onnx.TypeProto.Tensor.toObject(o.tensorType,a),a.oneofs&&(p.value="tensorType")),o.sequenceType!=null&&o.hasOwnProperty("sequenceType")&&(p.sequenceType=d.onnx.TypeProto.Sequence.toObject(o.sequenceType,a),a.oneofs&&(p.value="sequenceType")),o.mapType!=null&&o.hasOwnProperty("mapType")&&(p.mapType=d.onnx.TypeProto.Map.toObject(o.mapType,a),a.oneofs&&(p.value="mapType")),o.denotation!=null&&o.hasOwnProperty("denotation")&&(p.denotation=o.denotation),o.sparseTensorType!=null&&o.hasOwnProperty("sparseTensorType")&&(p.sparseTensorType=d.onnx.TypeProto.SparseTensor.toObject(o.sparseTensorType,a),a.oneofs&&(p.value="sparseTensorType")),o.optionalType!=null&&o.hasOwnProperty("optionalType")&&(p.optionalType=d.onnx.TypeProto.Optional.toObject(o.optionalType,a),a.oneofs&&(p.value="optionalType")),p},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(o){return o===void 0&&(o="type.googleapis.com"),o+"/onnx.TypeProto"},s.Tensor=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.elemType=a.int32();break}case 2:{m.shape=d.onnx.TensorShapeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")&&!l.isInteger(a.elemType))return"elemType: integer expected";if(a.shape!=null&&a.hasOwnProperty("shape")){var p=d.onnx.TensorShapeProto.verify(a.shape);if(p)return"shape."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Tensor)return a;var p=new d.onnx.TypeProto.Tensor;if(a.elemType!=null&&(p.elemType=a.elemType|0),a.shape!=null){if(typeof a.shape!="object")throw TypeError(".onnx.TypeProto.Tensor.shape: object expected");p.shape=d.onnx.TensorShapeProto.fromObject(a.shape)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=0,h.shape=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=a.elemType),a.shape!=null&&a.hasOwnProperty("shape")&&(h.shape=d.onnx.TensorShapeProto.toObject(a.shape,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Tensor"},o})(),s.Sequence=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3===1?m.elemType=d.onnx.TypeProto.decode(a,a.uint32()):a.skipType(g&7)}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")){var p=d.onnx.TypeProto.verify(a.elemType);if(p)return"elemType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Sequence)return a;var p=new d.onnx.TypeProto.Sequence;if(a.elemType!=null){if(typeof a.elemType!="object")throw TypeError(".onnx.TypeProto.Sequence.elemType: object expected");p.elemType=d.onnx.TypeProto.fromObject(a.elemType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=d.onnx.TypeProto.toObject(a.elemType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Sequence"},o})(),s.Map=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.keyType=a.int32();break}case 2:{m.valueType=d.onnx.TypeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.keyType!=null&&a.hasOwnProperty("keyType")&&!l.isInteger(a.keyType))return"keyType: integer expected";if(a.valueType!=null&&a.hasOwnProperty("valueType")){var p=d.onnx.TypeProto.verify(a.valueType);if(p)return"valueType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Map)return a;var p=new d.onnx.TypeProto.Map;if(a.keyType!=null&&(p.keyType=a.keyType|0),a.valueType!=null){if(typeof a.valueType!="object")throw TypeError(".onnx.TypeProto.Map.valueType: object expected");p.valueType=d.onnx.TypeProto.fromObject(a.valueType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.keyType=0,h.valueType=null),a.keyType!=null&&a.hasOwnProperty("keyType")&&(h.keyType=a.keyType),a.valueType!=null&&a.hasOwnProperty("valueType")&&(h.valueType=d.onnx.TypeProto.toObject(a.valueType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Map"},o})(),s.Optional=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3===1?m.elemType=d.onnx.TypeProto.decode(a,a.uint32()):a.skipType(g&7)}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")){var p=d.onnx.TypeProto.verify(a.elemType);if(p)return"elemType."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.Optional)return a;var p=new d.onnx.TypeProto.Optional;if(a.elemType!=null){if(typeof a.elemType!="object")throw TypeError(".onnx.TypeProto.Optional.elemType: object expected");p.elemType=d.onnx.TypeProto.fromObject(a.elemType)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=d.onnx.TypeProto.toObject(a.elemType,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.Optional"},o})(),s.SparseTensor=(function(){function o(a){if(a)for(var p=Object.keys(a),h=0;h>>3){case 1:{m.elemType=a.int32();break}case 2:{m.shape=d.onnx.TensorShapeProto.decode(a,a.uint32());break}default:a.skipType(g&7);break}}return m},o.decodeDelimited=function(a){return a instanceof i||(a=new i(a)),this.decode(a,a.uint32())},o.verify=function(a){if(typeof a!="object"||a===null)return"object expected";if(a.elemType!=null&&a.hasOwnProperty("elemType")&&!l.isInteger(a.elemType))return"elemType: integer expected";if(a.shape!=null&&a.hasOwnProperty("shape")){var p=d.onnx.TensorShapeProto.verify(a.shape);if(p)return"shape."+p}return null},o.fromObject=function(a){if(a instanceof d.onnx.TypeProto.SparseTensor)return a;var p=new d.onnx.TypeProto.SparseTensor;if(a.elemType!=null&&(p.elemType=a.elemType|0),a.shape!=null){if(typeof a.shape!="object")throw TypeError(".onnx.TypeProto.SparseTensor.shape: object expected");p.shape=d.onnx.TensorShapeProto.fromObject(a.shape)}return p},o.toObject=function(a,p){p||(p={});var h={};return p.defaults&&(h.elemType=0,h.shape=null),a.elemType!=null&&a.hasOwnProperty("elemType")&&(h.elemType=a.elemType),a.shape!=null&&a.hasOwnProperty("shape")&&(h.shape=d.onnx.TensorShapeProto.toObject(a.shape,p)),h},o.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},o.getTypeUrl=function(a){return a===void 0&&(a="type.googleapis.com"),a+"/onnx.TypeProto.SparseTensor"},o})(),s})(),c.OperatorSetIdProto=(function(){function s(r){if(r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.domain=r.string();break}case 2:{p.version=r.int64();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){return typeof r!="object"||r===null?"object expected":r.domain!=null&&r.hasOwnProperty("domain")&&!l.isString(r.domain)?"domain: string expected":r.version!=null&&r.hasOwnProperty("version")&&!l.isInteger(r.version)&&!(r.version&&l.isInteger(r.version.low)&&l.isInteger(r.version.high))?"version: integer|Long expected":null},s.fromObject=function(r){if(r instanceof d.onnx.OperatorSetIdProto)return r;var o=new d.onnx.OperatorSetIdProto;return r.domain!=null&&(o.domain=String(r.domain)),r.version!=null&&(l.Long?(o.version=l.Long.fromValue(r.version)).unsigned=!1:typeof r.version=="string"?o.version=parseInt(r.version,10):typeof r.version=="number"?o.version=r.version:typeof r.version=="object"&&(o.version=new l.LongBits(r.version.low>>>0,r.version.high>>>0).toNumber())),o},s.toObject=function(r,o){o||(o={});var a={};if(o.defaults)if(a.domain="",l.Long){var p=new l.Long(0,0,!1);a.version=o.longs===String?p.toString():o.longs===Number?p.toNumber():p}else a.version=o.longs===String?"0":0;return r.domain!=null&&r.hasOwnProperty("domain")&&(a.domain=r.domain),r.version!=null&&r.hasOwnProperty("version")&&(typeof r.version=="number"?a.version=o.longs===String?String(r.version):r.version:a.version=o.longs===String?l.Long.prototype.toString.call(r.version):o.longs===Number?new l.LongBits(r.version.low>>>0,r.version.high>>>0).toNumber():r.version),a},s.prototype.toJSON=function(){return this.constructor.toObject(this,n.util.toJSONOptions)},s.getTypeUrl=function(r){return r===void 0&&(r="type.googleapis.com"),r+"/onnx.OperatorSetIdProto"},s})(),c.OperatorStatus=(function(){var s={},r=Object.create(s);return r[s[0]="EXPERIMENTAL"]=0,r[s[1]="STABLE"]=1,r})(),c.FunctionProto=(function(){function s(r){if(this.input=[],this.output=[],this.attribute=[],this.attributeProto=[],this.node=[],this.opsetImport=[],r)for(var o=Object.keys(r),a=0;a>>3){case 1:{p.name=r.string();break}case 4:{p.input&&p.input.length||(p.input=[]),p.input.push(r.string());break}case 5:{p.output&&p.output.length||(p.output=[]),p.output.push(r.string());break}case 6:{p.attribute&&p.attribute.length||(p.attribute=[]),p.attribute.push(r.string());break}case 11:{p.attributeProto&&p.attributeProto.length||(p.attributeProto=[]),p.attributeProto.push(d.onnx.AttributeProto.decode(r,r.uint32()));break}case 7:{p.node&&p.node.length||(p.node=[]),p.node.push(d.onnx.NodeProto.decode(r,r.uint32()));break}case 8:{p.docString=r.string();break}case 9:{p.opsetImport&&p.opsetImport.length||(p.opsetImport=[]),p.opsetImport.push(d.onnx.OperatorSetIdProto.decode(r,r.uint32()));break}case 10:{p.domain=r.string();break}default:r.skipType(h&7);break}}return p},s.decodeDelimited=function(r){return r instanceof i||(r=new i(r)),this.decode(r,r.uint32())},s.verify=function(r){if(typeof r!="object"||r===null)return"object expected";if(r.name!=null&&r.hasOwnProperty("name")&&!l.isString(r.name))return"name: string expected";if(r.input!=null&&r.hasOwnProperty("input")){if(!Array.isArray(r.input))return"input: array expected";for(var o=0;o{"use strict";M0(),Le=be(Bi()),Ln(),xi=class{static arraysEqual(e,t){if(e.length!==t.length)return!1;for(let n=0;n1&&o>1)return;c[d-s]=Math.max(r,o)}return c}static index(t,n){let i=new Array(n.length);return $i.fillIndex(t,n,i),i}static fillIndex(t,n,i){let u=t.length-n.length;for(let l=0;l=0;y--)r[y]=_%d[y],_=Math.floor(_/d[y]);m||($i.fillIndex(r,t.dims,o),p=t.get(o)),g||($i.fillIndex(r,n.dims,a),h=n.get(a)),s.set(r,i(p,h))}}return s}}static isValidBroadcast(t,n){let i=t.length,u=n.length;if(i>u)return!1;for(let l=1;l<=i;l++)if(t[i-l]!==1&&t[i-l]!==n[u-l])return!1;return!0}static getBroadcastDims(t,n){let i=t.length,u=[];for(let l=0;l1&&c===1&&u.unshift(d)}return u}},Sw=class{static getShapeOfGemmResult(e,t,n,i,u){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,d,c;t?(l=e[1],d=e[0]):(l=e[0],d=e[1]);let s=-1;if(i?(c=n[0],s=1):(c=n[1],s=0),n[s]!==d)throw new Error("dimension mismatch");if(l<=0||c<=0||d<=0)throw new Error("invalid shape specified");if(u&&!Qt.isValidBroadcast(u,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,d]}},wt=class ul{static tensorDataTypeFromProto(t){switch(t){case Le.onnx.TensorProto.DataType.INT8:return"int8";case Le.onnx.TensorProto.DataType.UINT8:return"uint8";case Le.onnx.TensorProto.DataType.BOOL:return"bool";case Le.onnx.TensorProto.DataType.INT16:return"int16";case Le.onnx.TensorProto.DataType.UINT16:return"uint16";case Le.onnx.TensorProto.DataType.INT32:return"int32";case Le.onnx.TensorProto.DataType.UINT32:return"uint32";case Le.onnx.TensorProto.DataType.FLOAT:return"float32";case Le.onnx.TensorProto.DataType.DOUBLE:return"float64";case Le.onnx.TensorProto.DataType.STRING:return"string";case Le.onnx.TensorProto.DataType.INT64:return"int32";case Le.onnx.TensorProto.DataType.UINT64:return"uint32";default:throw new Error(`unsupported data type: ${Le.onnx.TensorProto.DataType[t]}`)}}static tensorDataTypeStringToEnum(t){switch(t){case"int8":return Le.onnx.TensorProto.DataType.INT8;case"uint8":return Le.onnx.TensorProto.DataType.UINT8;case"bool":return Le.onnx.TensorProto.DataType.BOOL;case"int16":return Le.onnx.TensorProto.DataType.INT16;case"uint16":return Le.onnx.TensorProto.DataType.UINT16;case"int32":return Le.onnx.TensorProto.DataType.INT32;case"uint32":return Le.onnx.TensorProto.DataType.UINT32;case"float32":return Le.onnx.TensorProto.DataType.FLOAT;case"float64":return Le.onnx.TensorProto.DataType.DOUBLE;case"string":return Le.onnx.TensorProto.DataType.STRING;case"int64":return Le.onnx.TensorProto.DataType.INT64;case"uint64":return Le.onnx.TensorProto.DataType.UINT64;default:throw new Error(`unsupported data type: ${t}`)}}static tensorDimsFromProto(t){return t.map(n=>mn.isLong(n)?n.toNumber():n)}static tensorValueTypeFromProto(t){return{tensorType:ul.tensorDataTypeFromProto(t.elemType),shape:{dims:ul.tensorDimsFromProto(t.shape.dim.map(n=>n.dimValue))}}}static tensorDimsFromORTFormat(t){let n=[];for(let i=0;it.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Sr.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Sr.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let u=1;for(let l=n;l=0;--u)i[u]=i[u+1]*t[u+1];return i}static transpose(t){return t.slice().reverse()}static indicesToOffset(t,n,i){i===void 0&&(i=t.length);let u=0;for(let l=0;l=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n))}static incrementIndex(t,n,i){if(n.length===0||t.length===0)throw new Error("Index incrementing unsupported for scalar Tensor");if(i===void 0)i=n.length;else if(i<=0||i>n.length)throw new Error("Incorrect axis to increment on");for(let u=i-1;u>=0&&(t[u]++,!(t[u]=t.length)throw new Error("the dimension with value zero exceeds the dimension size of the input tensor");u[s]=t[s]}else u[s]=n[s];d*=u[s]}}let c=Sr.size(t);if(l!==-1){if(c%d!==0)throw new Error(`the input tensor cannot be reshaped to the requested shape. Input shape: [${t}] Output shape: [${n}]`);u[l]=c/d}else if(d!==c)throw new Error("reshapedDims and originalDims don't have matching sizes");return u}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((u,l)=>u+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,u)=>i===n[u])}static validateDimsAndCalcSize(t){if(t.length>6)throw new TypeError("Only rank 0 to 6 is supported for tensor shape.");let n=1;for(let i of t){if(!Number.isInteger(i))throw new TypeError(`Invalid shape: ${i} is not an integer`);if(i<0||i>2147483647)throw new TypeError(`Invalid shape: length ${i} is not allowed`);n*=i}return n}static flattenShape(t,n){n<0&&(n+=t.length);let i=t.reduce((l,d)=>l*d,1),u=t.slice(n).reduce((l,d)=>l*d,1);return[i/u,u]}static squeezeShape(t,n){let i=new Array;n=Sr.normalizeAxes(n,t.length);for(let u=0;u=0;if(l&&t[u]!==1)throw new Error("squeeze an axis of size different than 1");(n.length===0&&t[u]>1||n.length>0&&!l)&&i.push(t[u])}return i}static unsqueezeShape(t,n){let i=new Array(t.length+n.length);i.fill(0);for(let l=0;l=i.length)throw new Error("'axes' has an out of range axis");if(i[d]!==0)throw new Error("'axes' has a duplicate axis");i[d]=1}let u=0;for(let l=0;l=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c=i[c]||d[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,u,l,d){if(d){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let c=0;c=i+u&&(d-=1)),d}static adjustPadAndReturnShape(t,n,i,u,l,d,c,s,r=0){let o=i*(u-1)+1;if(s&&s!=="NOTSET")switch(s){case"VALID":return l[d]=0,l[c]=0,Ir.computeOutputSize(t-o,n,t,0,r);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let a=(Math.floor((t+n-1)/n)-1)*n+u-t;return l[d]=Math.floor(s==="SAME_LOWER"?(a+1)/2:a/2),l[c]=a-l[d],Ir.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}default:throw new Error("Unsupported AutoPad type")}else return Ir.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}},Di=-34028234663852886e22,Mi=34028234663852886e22});function jO(e){switch(e){case"bool":case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;case"float64":return 8;default:throw new Error(`cannot calculate sizeof() on type ${e}`)}}function gh(e){switch(e){case ve.onnx.TensorProto.DataType.UINT8:case ve.onnx.TensorProto.DataType.INT8:case ve.onnx.TensorProto.DataType.BOOL:return 1;case ve.onnx.TensorProto.DataType.UINT16:case ve.onnx.TensorProto.DataType.INT16:return 2;case ve.onnx.TensorProto.DataType.FLOAT:case ve.onnx.TensorProto.DataType.INT32:case ve.onnx.TensorProto.DataType.UINT32:return 4;case ve.onnx.TensorProto.DataType.INT64:case ve.onnx.TensorProto.DataType.DOUBLE:case ve.onnx.TensorProto.DataType.UINT64:return 8;default:throw new Error(`cannot calculate sizeof() on type ${ve.onnx.TensorProto.DataType[e]}`)}}function UO(e,t){return new(Ow(t))(e)}function Ow(e){switch(e){case"bool":case"uint8":return Uint8Array;case"int8":return Int8Array;case"int16":return Int16Array;case"uint16":return Uint16Array;case"int32":return Int32Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"float32":return Float32Array;case"float64":return Float64Array;default:throw new Error("unspecified error")}}function ll(e,t){if(t===ve.onnx.TensorProto.DataType.INT64||t===Bo.TensorDataType.INT64){if(e.greaterThanOrEqual(2147483648)||e.lessThan(-2147483648))throw new TypeError("int64 is not supported")}else if(t===ve.onnx.TensorProto.DataType.UINT32||t===Bo.TensorDataType.UINT32||t===ve.onnx.TensorProto.DataType.UINT64||t===Bo.TensorDataType.UINT64){if(e.greaterThanOrEqual(4294967296)||e.lessThan(0))throw new TypeError("uint64 is not supported")}else throw new TypeError(`not a LONG type: ${ve.onnx.TensorProto.DataType[t]}`);return e.toNumber()}function bh(e,t,n){switch(t){case ve.onnx.TensorProto.DataType.BOOL:case ve.onnx.TensorProto.DataType.UINT8:return e.getUint8(n);case ve.onnx.TensorProto.DataType.INT8:return e.getInt8(n);case ve.onnx.TensorProto.DataType.UINT16:return e.getUint16(n,!0);case ve.onnx.TensorProto.DataType.INT16:return e.getInt16(n,!0);case ve.onnx.TensorProto.DataType.FLOAT:return e.getFloat32(n,!0);case ve.onnx.TensorProto.DataType.INT32:return e.getInt32(n,!0);case ve.onnx.TensorProto.DataType.UINT32:return e.getUint32(n,!0);case ve.onnx.TensorProto.DataType.INT64:return ll(mn.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!1),t);case ve.onnx.TensorProto.DataType.DOUBLE:return e.getFloat64(n,!0);case ve.onnx.TensorProto.DataType.UINT64:return ll(mn.fromBits(e.getUint32(n,!0),e.getUint32(n+4,!0),!0),t);default:throw new Error(`cannot read from DataView for type ${ve.onnx.TensorProto.DataType[t]}`)}}var yh,ve,xt,Ln=D(()=>{"use strict";yh=be(q3()),M0(),os(),ve=be(Bi()),Me(),xt=class Fo{constructor(t,n,i,u,l,d=yh.Guid.create()){this.dims=t,this.type=n,this.dataProvider=i,this.asyncDataProvider=u,this.cache=l,this.dataId=d,this.size=ye.validateDimsAndCalcSize(t);let c=this.size,s=i===void 0&&u===void 0&&l===void 0;if(l!==void 0&&l.length!==c)throw new RangeError("Input dims doesn't match data length.");if(n==="string"){if(l!==void 0&&(!Array.isArray(l)||!l.every(r=>typeof r=="string")))throw new TypeError("cache should be a string array");s&&(this.cache=new Array(c))}else{if(l!==void 0){let r=Ow(n);if(!(l instanceof r))throw new TypeError(`cache should be type ${r.name}`)}if(s){let r=new ArrayBuffer(c*jO(n));this.cache=UO(r,n)}}}get data(){if(this.cache===void 0){let t=this.dataProvider(this.dataId);if(t.length!==this.size)throw new Error("Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.");this.cache=t}return this.cache}get stringData(){if(this.type!=="string")throw new TypeError("data type is not string");return this.data}get integerData(){switch(this.type){case"uint8":case"int8":case"uint16":case"int16":case"int32":case"uint32":case"bool":return this.data;default:throw new TypeError("data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)")}}get floatData(){switch(this.type){case"float32":case"float64":return this.data;default:throw new TypeError("data type is not float (float32, float64)")}}get numberData(){if(this.type!=="string")return this.data;throw new TypeError("type cannot be non-number (string)")}get(t){return this.data[ye.indicesToOffset(t,this.strides)]}set(t,n){this.data[ye.indicesToOffset(t,this.strides)]=n}async getData(){return this.cache===void 0&&(this.cache=await this.asyncDataProvider(this.dataId)),this.cache}get strides(){return this._strides||(this._strides=ye.computeStrides(this.dims)),this._strides}static fromProto(t){if(!t)throw new Error("cannot construct Value from an empty tensor");let n=wt.tensorDataTypeFromProto(t.dataType),i=wt.tensorDimsFromProto(t.dims),u=new Fo(i,n);if(n==="string")t.stringData.forEach((l,d)=>{u.data[d]=sl(l)});else if(t.rawData&&typeof t.rawData.byteLength=="number"&&t.rawData.byteLength>0){let l=u.data,d=new DataView(t.rawData.buffer,t.rawData.byteOffset,t.rawData.byteLength),c=gh(t.dataType),s=t.rawData.byteLength/c;if(t.rawData.byteLength%c!==0)throw new Error("invalid buffer length");if(l.length!==s)throw new Error("buffer length mismatch");for(let r=0;r0){let l=u.data,d=new DataView(t.rawDataArray().buffer,t.rawDataArray().byteOffset,t.rawDataLength()),c=gh(t.dataType()),s=t.rawDataLength()/c;if(t.rawDataLength()%c!==0)throw new Error("invalid buffer length");if(l.length!==s)throw new Error("buffer length mismatch");for(let r=0;rtypeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( { gl_Position = vec4(position, 1.0); TexCoords = textureCoord; - }`}function zO(e){let t=Ae(e);return`${t.version} + }`}function GO(e){let t=Ae(e);return`${t.version} precision highp float; precision highp int; precision highp sampler2D; @@ -41,14 +41,14 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( return x - y * (x / y); } - `}function BO(e,t){let n=Ae(e);return` + `}function qO(e,t){let n=Ae(e);return` void main() { int indices[${t}]; toVec(TexCoords, indices); vec4 result = vec4(process(indices)); ${n.output} = result; } - `}var $w,Tw,Ke=D(()=>{"use strict";$w={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},Tw={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"}}),Pe=D(()=>{"use strict"});async function fh(e,t=i=>0,n){return new Promise((i,u)=>{let l=0,d=()=>{if(e()){i();return}l++;let c=t(l);if(n!=null&&l>=n){u();return}setTimeout(d,c)};d()})}function ga(e){return jo(typeof e<"u"&&e.length!==0,()=>"empty string found for sampler name"),"get"+e.charAt(0).toUpperCase()+e.slice(1)}function FO(e){return jo(typeof e<"u"&&e.length!==0,()=>"empty string found for sampler name"),"get"+e.charAt(0).toUpperCase()+e.slice(1)+"AtOutCoords"}function ii(e,t){let n=JSON.parse(JSON.stringify(e));return n=t,n}function oi(e,t){return t.map(n=>e[n]).join(", ")}function Ar(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function zn(e=6){return["x","y","z","w","u","v"].slice(0,e)}var ar=D(()=>{"use strict";Me()});function LO(e,t){return zn(t).map(n=>`${e}.${n}`)}function Kl(e,t){return t===1?[e]:LO(e,t)}function zi(){return` + `}var Ew,Aw,Ke=D(()=>{"use strict";Ew={version:"",attribute:"attribute",varyingVertex:"varying",varyingFrag:"varying",texture2D:"texture2D",output:"gl_FragColor",outputDeclaration:""},Aw={version:"#version 300 es",attribute:"in",varyingVertex:"out",varyingFrag:"in",texture2D:"texture",output:"outputColor",outputDeclaration:"out vec4 outputColor;"}}),Pe=D(()=>{"use strict"});async function wh(e,t=i=>0,n){return new Promise((i,u)=>{let l=0,d=()=>{if(e()){i();return}l++;let c=t(l);if(n!=null&&l>=n){u();return}setTimeout(d,c)};d()})}function wa(e){return Vo(typeof e<"u"&&e.length!==0,()=>"empty string found for sampler name"),"get"+e.charAt(0).toUpperCase()+e.slice(1)}function HO(e){return Vo(typeof e<"u"&&e.length!==0,()=>"empty string found for sampler name"),"get"+e.charAt(0).toUpperCase()+e.slice(1)+"AtOutCoords"}function si(e,t){let n=JSON.parse(JSON.stringify(e));return n=t,n}function ai(e,t){return t.map(n=>e[n]).join(", ")}function Ar(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function zn(e=6){return["x","y","z","w","u","v"].slice(0,e)}var ar=D(()=>{"use strict";Me()});function WO(e,t){return zn(t).map(n=>`${e}.${n}`)}function Yl(e,t){return t===1?[e]:WO(e,t)}function Fi(){return` float getChannel(vec4 frag, int dim) { int modCoord = imod(dim, 2); return modCoord == 0 ? frag.r : frag.g; @@ -60,19 +60,19 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( (modCoord.y == 0. ? frag.r : frag.g) : (modCoord.y == 0. ? frag.b : frag.a); } - `}var jn=D(()=>{"use strict";ar()});function jO(e,t,n){if(e===0)return"false";if(e===1)return`rc > ${t[0]}`;let i="";for(let u=e-2;u= ${t[u-e+2]}`,u{"use strict";ar()});function KO(e,t,n){if(e===0)return"false";if(e===1)return`rc > ${t[0]}`;let i="";for(let u=e-2;u= ${t[u-e+2]}`,u= ${e[0]} ? 0. : getA(rc + 1), 0, 0`;let i="r, c",u="r, cp1",l="rp1, c",d="rp1, cp1",c="";if(n>2)for(let s=0;s= ${i}; bool cEdge = cp1 >= ${n}; - `}var ba,mh,Sw,qO=D(()=>{"use strict";Ke(),Pe(),ar(),jn(),ba={name:"pack",inputNames:["A"],inputTypes:[1]},mh=(e,t)=>{let n=Ae(e.session.backend.glContext.version),i=t.dims,u=i.length,l=t.dims.length,d=Ar(l),c=Kl("rc",l),s=VO(l,c,i[i.length-2],i[i.length-1]),r;u===0?r=[1,1]:u===1?r=[i[0],1]:r=[i[l-1],i[l-2]];let o=jO(l,r,c),a=UO(i,c),p=` + `}var _a,_h,kw,YO=D(()=>{"use strict";Ke(),Pe(),ar(),jn(),_a={name:"pack",inputNames:["A"],inputTypes:[1]},_h=(e,t)=>{let n=Ae(e.session.backend.glContext.version),i=t.dims,u=i.length,l=t.dims.length,d=Ar(l),c=Yl("rc",l),s=ZO(l,c,i[i.length-2],i[i.length-1]),r;u===0?r=[1,1]:u===1?r=[i[0],1]:r=[i[l-1],i[l-2]];let o=KO(l,r,c),a=XO(i,c),p=` void main() { ${d} rc = getOutputCoords(); @@ -84,17 +84,17 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( ${n.output} = vec4(${a}); } } - `;return{...ba,hasMain:!0,output:{dims:t.dims,type:t.type,textureType:2},shaderSource:p}},Sw=(e,t)=>({...ba,get:()=>mh(e,t)})});function gh(e){if(e.length===0)return[1,1,1];let t=1;for(let n=0;n1?e[e.length-2]:1,e[e.length-1]]}function GO(e,t){let n=!1;return e.length===0||t.length===0?n=!0:e.length<2||t.length<2?n=e[e.length-1]===t[t.length-1]:n=e[e.length-1]===t[t.length-1]&&e[e.length-2]===t[t.length-2],n}function HO(e){let t=ye.computeStrides(e),n=["b","r","c"],i="index";return` + `;return{..._a,hasMain:!0,output:{dims:t.dims,type:t.type,textureType:2},shaderSource:p}},kw=(e,t)=>({..._a,get:()=>_h(e,t)})});function vh(e){if(e.length===0)return[1,1,1];let t=1;for(let n=0;n1?e[e.length-2]:1,e[e.length-1]]}function JO(e,t){let n=!1;return e.length===0||t.length===0?n=!0:e.length<2||t.length<2?n=e[e.length-1]===t[t.length-1]:n=e[e.length-1]===t[t.length-1]&&e[e.length-2]===t[t.length-2],n}function QO(e){let t=ye.computeStrides(e),n=["b","r","c"],i="index";return` ivec3 inputCoordsFromReshapedOutCoords(int index) { ${t.map((u,l)=>{let d=`int ${n[l]} = ${i} / ${u}`,c=l===t.length-1?`int ${n[l+1]} = ${i} - ${n[l]} * ${u}`:`index -= ${n[l]} * ${u}`;return`${d}; ${c};`}).join("")} return ivec3(b, r, c); } - `}function WO(e){let t=ye.computeStrides(e);return` + `}function eE(e){let t=ye.computeStrides(e);return` int getFlattenedIndex(ivec3 coords) { // reverse y, z order return coords.x * ${t[0]} + coords.z * ${t[1]} + coords.y; } -`}var bh,yh,Iw,KO=D(()=>{"use strict";Me(),Ke(),Pe(),jn(),bh=e=>({name:"Reshape (packed)",inputTypes:[2],inputNames:["A"],cacheHint:`${e}`}),yh=(e,t,n,i)=>{let u=t.dims,l=i,d="";for(let r=0;r<4;r++){let o="";switch(r){case 0:o="outputCoords = rc;";break;case 1:o="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:o="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:o="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}d+=` +`}var xh,$h,Pw,tE=D(()=>{"use strict";Me(),Ke(),Pe(),jn(),xh=e=>({name:"Reshape (packed)",inputTypes:[2],inputNames:["A"],cacheHint:`${e}`}),$h=(e,t,n,i)=>{let u=t.dims,l=i,d="";for(let r=0;r<4;r++){let o="";switch(r){case 0:o="outputCoords = rc;";break;case 1:o="outputCoords = ivec3(rc.x, rc.y+1, rc.z);";break;case 2:o="outputCoords = ivec3(rc.x, rc.y, rc.z+1);";break;case 3:o="outputCoords = ivec3(rc.x, rc.y+1, rc.z+1);";break;default:throw new Error}d+=` ${o} ${r>0?"if(outputCoords.y < rows && outputCoords.z < cols){":""} int flattenedIndex = getFlattenedIndex(outputCoords); @@ -106,9 +106,9 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( ${r>0?"}":""} `}let c=Ae(e.session.backend.glContext.version),s=` - ${HO(u)} - ${WO(l)} - ${zi()} + ${QO(u)} + ${eE(l)} + ${Fi()} void main() { ivec3 rc = getOutputCoords(); @@ -122,7 +122,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( ${d} ${c.output} = result; } - `;return{...n,output:{dims:l,type:t.type,textureType:2},shaderSource:s,hasMain:!0}},Iw=(e,t,n)=>{let i=bh(n);return{...i,get:()=>yh(e,t,i,n)}}}),al,XO=D(()=>{"use strict";Ke(),Pe(),al=(e,t)=>{let n=t.shape,i=Ae(e.session.backend.glContext.version),u=` + `;return{...n,output:{dims:l,type:t.type,textureType:2},shaderSource:s,hasMain:!0}},Pw=(e,t,n)=>{let i=xh(n);return{...i,get:()=>$h(e,t,i,n)}}}),dl,rE=D(()=>{"use strict";Ke(),Pe(),dl=(e,t)=>{let n=t.shape,i=Ae(e.session.backend.glContext.version),u=` const float FLOAT_MAX = 1.70141184e38; const float FLOAT_MIN = 1.17549435e-38; @@ -169,7 +169,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( void main() { float value = ${i.texture2D}(X,TexCoords).r; ${i.output} = encodeAsUint8(value); - }`,l={name:"Uint8Encode",inputTypes:[0],inputNames:["X"],output:{dims:n,type:t.tensor.type,textureType:3},shaderSource:u,hasMain:!0};return e.executeProgram(l,[t.tensor])}});function ZO(e,t){if(e===1)return"rc";let n="";for(let i=0;i{"use strict";Ke(),Pe(),ar(),jn(),ya={name:"unpack",inputNames:["A"],inputTypes:[2]},wh=(e,t)=>{let n=t.dims.length,i=Kl("rc",n),u=i.slice(-2),l=Ar(n),d=zi(),c=t.dims.length===0?"":ZO(n,i),s=n<=1?"rc":`vec2(${u.join(",")})`,r=Ae(e.session.backend.glContext.version),o=` + }`,l={name:"Uint8Encode",inputTypes:[0],inputNames:["X"],output:{dims:n,type:t.tensor.type,textureType:3},shaderSource:u,hasMain:!0};return e.executeProgram(l,[t.tensor])}});function nE(e,t){if(e===1)return"rc";let n="";for(let i=0;i{"use strict";Ke(),Pe(),ar(),jn(),va={name:"unpack",inputNames:["A"],inputTypes:[2]},Th=(e,t)=>{let n=t.dims.length,i=Yl("rc",n),u=i.slice(-2),l=Ar(n),d=Fi(),c=t.dims.length===0?"":nE(n,i),s=n<=1?"rc":`vec2(${u.join(",")})`,r=Ae(e.session.backend.glContext.version),o=` ${d} void main() { ${l} rc = getOutputCoords(); @@ -179,7 +179,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( ${r.output} = vec4(getChannel(packedInput, ${s}), 0, 0, 0); } - `;return{...ya,hasMain:!0,output:{dims:t.dims,type:t.type,textureType:0},shaderSource:o}},Ow=(e,t)=>({...ya,get:()=>wh(e,t)})}),Ew,ul,Aw,Vo=D(()=>{"use strict";qt(),Ew=class{constructor(e,t=1){if(t===1)this.internalFormat=e.R32F,this.format=e.RED,this.textureType=e.FLOAT,this.channelSize=t;else if(t===4)this.internalFormat=e.RGBA32F,this.format=e.RGBA,this.textureType=e.FLOAT,this.channelSize=t;else throw new Error(`Invalid number of channels: ${t}`)}encode(e,t){let n,i;return e.constructor!==Float32Array&&(Je.warning("Encoder","data was not of type Float32; creating new Float32Array"),i=new Float32Array(e)),t*this.channelSize>e.length?(Je.warning("Encoder","Source data too small. Allocating larger array"),i=e,n=this.allocate(t*this.channelSize),i.forEach((u,l)=>n[l]=u)):(i=e,n=i),n}allocate(e){return new Float32Array(e*4)}decode(e,t){return this.channelSize===1?e.filter((n,i)=>i%4===0).subarray(0,t):e.subarray(0,t)}},ul=class{constructor(e,t=1,n){if(t!==1&&t!==4)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA,this.format=e.RGBA,this.channelSize=t,this.textureType=n||e.FLOAT}encode(e,t){let n=e;return this.channelSize===1&&(Je.verbose("Encoder","Exploding into a larger array"),n=this.allocate(t),e.forEach((i,u)=>n[u*4]=i)),n}allocate(e){return new Float32Array(e*4)}decode(e,t){return this.channelSize===1?e.filter((n,i)=>i%4===0).subarray(0,t):e.subarray(0,t)}},Aw=class{constructor(e,t=1){if(this.channelSize=4,t===1)this.internalFormat=e.ALPHA,this.format=e.ALPHA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=t;else if(t===4)this.internalFormat=e.RGBA,this.format=e.RGBA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=t;else throw new Error(`Invalid number of channels: ${t}`)}encode(e,t){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}allocate(e){return new Uint8Array(e*this.channelSize)}decode(e,t){if(e instanceof Uint8Array)return e.subarray(0,t);throw new Error(`Invalid array type: ${e.constructor}`)}}}),Ei,kw,ll,JO=D(()=>{"use strict";Me(),Pe(),Ei=(e,t,n)=>{let i=n===0||n===1?1:4,u=n===2,l=n===1||n===2,d=n===4?t.length-1:void 0,c=n===4?t.map((s,r)=>r===t.length-1?s*4:s):void 0;return ll(e,t,i,c,{isPacked:u,reverseWH:l,breakAxis:d})},kw=(e,t,n)=>{let i=Ei(e,t,n);return[i.width,i.height]},ll=(e,t,n=1,i,u)=>{let l=!!(u&&u.isPacked),[d,c]=e.computeTextureWH(l&&i||t,u),s=t.length,r=t.slice(0);if(s===0&&(r=[1]),n===1)i=t;else if(l){if(n!==4)throw new Error("a packed texture must be 4-channel");i=t,s>0&&(r[s-1]=Math.ceil(r[s-1]/2)),s>1&&(r[s-2]=Math.ceil(r[s-2]/2))}else if(!i)throw new Error("Unpacked shape is needed when using channels > 1");return{width:d,height:c,channels:n,isPacked:l,shape:r,strides:ye.computeStrides(r),unpackedShape:i,reversedWH:u&&u.reverseWH}}}),_h,Pw,QO=D(()=>{"use strict";qt(),Ln(),Me(),qO(),KO(),XO(),YO(),Vo(),JO(),Pe(),_h=(e,t)=>{let n=t.map(u=>`${u.unpackedShape.join(",")};${u.width}x${u.height}`).join("_"),i=e.name;return e.cacheHint&&(i+="["+e.cacheHint+"]"),i+=":"+n,i},Pw=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,t){return kw(this.session.layoutStrategy,e,t)}executeProgram(e,t){if(t.lengththis.readTexture(l),async d=>this.readTextureAsync(l),void 0,u),texture:n};return this.setTextureData(l.tensor.dataId,l,e.isPacked),l}getTextureData(e,t=!1){return this.session.isInitializer(e)?this.session.getTextureData(e,t):t?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,t,n=!1){this.session.isInitializer(e)?this.session.setTextureData(e,t,n):(n?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,t)}isTextureLayoutCached(e,t=!1){return!!this.getTextureData(e.dataId,t)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat(al(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat(al(this,e))}pack(e){return this.executeProgram(Sw(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram(Ow(this,e.tensor),[e.tensor])}}}),vh,je,ut=D(()=>{"use strict";vh=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},je=e=>new vh(e)}),wa,Cw,Rw,xh,$h,eE=D(()=>{"use strict";ut(),Ke(),Pe(),wa={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[0,0,0,0,0]},Cw=(e,t,n)=>($h(t),[e.run({...wa,cacheHint:n.cacheKey,get:()=>xh(e,t,n)},t)]),Rw=e=>{let t=e.attributes.getFloat("epsilon",1e-5),n=e.attributes.getFloat("momentum",.9),i=e.attributes.getInt("spatial",1);return je({epsilon:t,momentum:n,spatial:i})},xh=(e,t,n)=>{let i=Ae(e.session.backend.glContext.version),u=t[0].dims.length,[l,d]=e.calculateTextureWidthAndHeight(t[1].dims,0),c=` + `;return{...va,hasMain:!0,output:{dims:t.dims,type:t.type,textureType:0},shaderSource:o}},Cw=(e,t)=>({...va,get:()=>Th(e,t)})}),Rw,cl,Dw,qo=D(()=>{"use strict";Gt(),Rw=class{constructor(e,t=1){if(t===1)this.internalFormat=e.R32F,this.format=e.RED,this.textureType=e.FLOAT,this.channelSize=t;else if(t===4)this.internalFormat=e.RGBA32F,this.format=e.RGBA,this.textureType=e.FLOAT,this.channelSize=t;else throw new Error(`Invalid number of channels: ${t}`)}encode(e,t){let n,i;return e.constructor!==Float32Array&&(Je.warning("Encoder","data was not of type Float32; creating new Float32Array"),i=new Float32Array(e)),t*this.channelSize>e.length?(Je.warning("Encoder","Source data too small. Allocating larger array"),i=e,n=this.allocate(t*this.channelSize),i.forEach((u,l)=>n[l]=u)):(i=e,n=i),n}allocate(e){return new Float32Array(e*4)}decode(e,t){return this.channelSize===1?e.filter((n,i)=>i%4===0).subarray(0,t):e.subarray(0,t)}},cl=class{constructor(e,t=1,n){if(t!==1&&t!==4)throw new Error(`Invalid number of channels: ${t}`);this.internalFormat=e.RGBA,this.format=e.RGBA,this.channelSize=t,this.textureType=n||e.FLOAT}encode(e,t){let n=e;return this.channelSize===1&&(Je.verbose("Encoder","Exploding into a larger array"),n=this.allocate(t),e.forEach((i,u)=>n[u*4]=i)),n}allocate(e){return new Float32Array(e*4)}decode(e,t){return this.channelSize===1?e.filter((n,i)=>i%4===0).subarray(0,t):e.subarray(0,t)}},Dw=class{constructor(e,t=1){if(this.channelSize=4,t===1)this.internalFormat=e.ALPHA,this.format=e.ALPHA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=t;else if(t===4)this.internalFormat=e.RGBA,this.format=e.RGBA,this.textureType=e.UNSIGNED_BYTE,this.channelSize=t;else throw new Error(`Invalid number of channels: ${t}`)}encode(e,t){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}allocate(e){return new Uint8Array(e*this.channelSize)}decode(e,t){if(e instanceof Uint8Array)return e.subarray(0,t);throw new Error(`Invalid array type: ${e.constructor}`)}}}),ki,Mw,pl,oE=D(()=>{"use strict";Me(),Pe(),ki=(e,t,n)=>{let i=n===0||n===1?1:4,u=n===2,l=n===1||n===2,d=n===4?t.length-1:void 0,c=n===4?t.map((s,r)=>r===t.length-1?s*4:s):void 0;return pl(e,t,i,c,{isPacked:u,reverseWH:l,breakAxis:d})},Mw=(e,t,n)=>{let i=ki(e,t,n);return[i.width,i.height]},pl=(e,t,n=1,i,u)=>{let l=!!(u&&u.isPacked),[d,c]=e.computeTextureWH(l&&i||t,u),s=t.length,r=t.slice(0);if(s===0&&(r=[1]),n===1)i=t;else if(l){if(n!==4)throw new Error("a packed texture must be 4-channel");i=t,s>0&&(r[s-1]=Math.ceil(r[s-1]/2)),s>1&&(r[s-2]=Math.ceil(r[s-2]/2))}else if(!i)throw new Error("Unpacked shape is needed when using channels > 1");return{width:d,height:c,channels:n,isPacked:l,shape:r,strides:ye.computeStrides(r),unpackedShape:i,reversedWH:u&&u.reverseWH}}}),Sh,Nw,sE=D(()=>{"use strict";Gt(),Ln(),Me(),YO(),tE(),rE(),iE(),qo(),oE(),Pe(),Sh=(e,t)=>{let n=t.map(u=>`${u.unpackedShape.join(",")};${u.width}x${u.height}`).join("_"),i=e.name;return e.cacheHint&&(i+="["+e.cacheHint+"]"),i+=":"+n,i},Nw=class{constructor(e){this.session=e,this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map}calculateTextureWidthAndHeight(e,t){return Mw(this.session.layoutStrategy,e,t)}executeProgram(e,t){if(t.lengththis.readTexture(l),async d=>this.readTextureAsync(l),void 0,u),texture:n};return this.setTextureData(l.tensor.dataId,l,e.isPacked),l}getTextureData(e,t=!1){return this.session.isInitializer(e)?this.session.getTextureData(e,t):t?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,t,n=!1){this.session.isInitializer(e)?this.session.setTextureData(e,t,n):(n?this.packedTextureDataCache:this.unpackedTextureDataCache).set(e,t)}isTextureLayoutCached(e,t=!1){return!!this.getTextureData(e.dataId,t)}dispose(){this.session.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.session.textureManager.releaseTexture(e)),this.unpackedTextureDataCache=new Map}readTexture(e){return e.isPacked?this.readTexture(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTexture(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat(dl(this,e))}async readTextureAsync(e){return e.isPacked?this.readTextureAsync(this.unpack(e)):this.session.backend.glContext.isFloat32DownloadSupported?this.session.textureManager.readTextureAsync(e,e.tensor.type,e.channels):this.session.textureManager.readUint8TextureAsFloat(dl(this,e))}pack(e){return this.executeProgram(kw(this,e.tensor),[e.tensor])}unpack(e){return this.executeProgram(Cw(this,e.tensor),[e.tensor])}}}),Ih,je,ut=D(()=>{"use strict";Ih=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},je=e=>new Ih(e)}),xa,zw,Bw,Oh,Eh,aE=D(()=>{"use strict";ut(),Ke(),Pe(),xa={name:"BatchNormalization",inputNames:["A","Scale","B","Mean","Variance"],inputTypes:[0,0,0,0,0]},zw=(e,t,n)=>(Eh(t),[e.run({...xa,cacheHint:n.cacheKey,get:()=>Oh(e,t,n)},t)]),Bw=e=>{let t=e.attributes.getFloat("epsilon",1e-5),n=e.attributes.getFloat("momentum",.9),i=e.attributes.getInt("spatial",1);return je({epsilon:t,momentum:n,spatial:i})},Oh=(e,t,n)=>{let i=Ae(e.session.backend.glContext.version),u=t[0].dims.length,[l,d]=e.calculateTextureWidthAndHeight(t[1].dims,0),c=` float process(int[${u}] indices) { vec2 position = offsetToCoords(indices[1], ${l}, ${d}); float scale = getColorAsFloat(${i.texture2D}(Scale, position)); @@ -188,42 +188,42 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( float b = getColorAsFloat(${i.texture2D}(B, position)); return scale * ( (_A(indices) - mean) / sqrt(variance + float(${n.epsilon})) ) + b; - }`;return{...wa,output:{dims:t[0].dims,type:t[0].type,textureType:0},shaderSource:c}},$h=e=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs.");let t=e[0],n=e[1],i=e[2],u=e[3],l=e[4];if(t.dims.length<3||n.dims.length!==1||i.dims.length!==1||u.dims.length!==1||l.dims.length!==1)throw new Error("invalid input shape.");if(n.dims[0]!==t.dims[1]||i.dims[0]!==t.dims[1]||u.dims[0]!==t.dims[1]||l.dims[0]!==t.dims[1])throw new Error("invalid input shape.");if(t.type!=="float32"&&t.type!=="float64"||n.type!=="float32"&&n.type!=="float64"||i.type!=="float32"&&i.type!=="float64"||u.type!=="float32"&&u.type!=="float64"||l.type!=="float32"&&l.type!=="float64")throw new Error("invalid input tensor types.")}}),Dw,Un,ie,dl,Mw,Pr=D(()=>{"use strict";Dw=class{constructor(e,t,n,i){this.glContext=e,this.programInfo=t,this.inputTextureLayouts=n,this.outputTextureLayout=i}},Un=class{constructor(e){this.context=e}},ie=class{constructor(e,t){this.routineBody=e,this.dependencies=t}},dl=class{constructor(e,t,n){this.name=e,n?this.dependencies=n:this.dependencies=[],t&&(this.routineBody=t)}addDependency(e){e&&this.dependencies.push(e)}},Mw=class{static returnOrderedNodes(e){if(!e||e.length===0)return[];if(e.length===1)return e;let t=new Set,n=new Set,i=new Array;return this.createOrderedNodes(e,t,n,i),i}static createOrderedNodes(e,t,n,i){for(let u=0;u0)for(let l=0;l{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs.");let t=e[0],n=e[1],i=e[2],u=e[3],l=e[4];if(t.dims.length<3||n.dims.length!==1||i.dims.length!==1||u.dims.length!==1||l.dims.length!==1)throw new Error("invalid input shape.");if(n.dims[0]!==t.dims[1]||i.dims[0]!==t.dims[1]||u.dims[0]!==t.dims[1]||l.dims[0]!==t.dims[1])throw new Error("invalid input shape.");if(t.type!=="float32"&&t.type!=="float64"||n.type!=="float32"&&n.type!=="float64"||i.type!=="float32"&&i.type!=="float64"||u.type!=="float32"&&u.type!=="float64"||l.type!=="float32"&&l.type!=="float64")throw new Error("invalid input tensor types.")}}),Fw,Un,ie,hl,Lw,Pr=D(()=>{"use strict";Fw=class{constructor(e,t,n,i){this.glContext=e,this.programInfo=t,this.inputTextureLayouts=n,this.outputTextureLayout=i}},Un=class{constructor(e){this.context=e}},ie=class{constructor(e,t){this.routineBody=e,this.dependencies=t}},hl=class{constructor(e,t,n){this.name=e,n?this.dependencies=n:this.dependencies=[],t&&(this.routineBody=t)}addDependency(e){e&&this.dependencies.push(e)}},Lw=class{static returnOrderedNodes(e){if(!e||e.length===0)return[];if(e.length===1)return e;let t=new Set,n=new Set,i=new Array;return this.createOrderedNodes(e,t,n,i),i}static createOrderedNodes(e,t,n,i){for(let u=0;u0)for(let l=0;l b); } @@ -233,7 +233,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( v1.b > v2.b, v1.a > v2.a ); } - `,name:e,type:0}}function aE(){let e="less_";return{body:` + `,name:e,type:0}}function fE(){let e="less_";return{body:` float ${e}(float a, float b) { return float(a < b); } @@ -243,7 +243,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( v1.b < v2.b, v1.a < v2.a ); } - `,name:e,type:0}}function uE(){let e="and_";return{body:` + `,name:e,type:0}}function mE(){let e="and_";return{body:` float ${e}(float a, float b) { return float( bool(a) && bool(b) ); } @@ -255,7 +255,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( b1.b && b2.b, b1.a && b2.a ); } - `,name:e,type:0}}function lE(){return{body:` + `,name:e,type:0}}function gE(){return{body:` float or_(float a, float b) { return float( bool(a) || bool(b) ); } @@ -267,7 +267,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( b1.b || b2.b, b1.a || b2.a ); } - `,name:"or_",type:0}}function dE(){let e="xor_";return{body:` + `,name:"or_",type:0}}function bE(){let e="xor_";return{body:` float ${e}(float a, float b) { return float( bool(a) ^^ bool(b) ); } @@ -279,7 +279,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( b1.b ^^ b2.b, b1.a ^^ b2.a ); } - `,name:e,type:0}}function cE(){return hE("pow")}function pE(){let e="prelu_";return{body:` + `,name:e,type:0}}function yE(){return _E("pow")}function wE(){let e="prelu_";return{body:` float ${e}(float a, float b) { return a < 0.0 ? a * b: a; } @@ -291,14 +291,14 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( v1.a < 0.0 ? v1.a * v2.a: v1.a ); } - `,name:e,type:0}}function hE(e){let t=`${e}_`;return{body:` + `,name:e,type:0}}function _E(e){let t=`${e}_`;return{body:` float ${t}(float a, float b) { return ${e}(a, b); } vec4 ${t}(vec4 v1, vec4 v2) { return ${e}(v1, v2); } - `,name:t,type:0}}var bt,Th,Nw,zw,Bw,Fw,Lw,jw,Uw,Vw,qw,Gw,Hw,Ww,fE=D(()=>{"use strict";Me(),Pr(),Ke(),Pe(),bt=(e,t,n,i=t[0].type,u)=>{let l=e.session.pack?2:0;return{name:n.name,inputNames:["A","B"],inputTypes:[l,l],cacheHint:u,get:()=>Th(e,t,n,i)}},Th=(e,t,n,i=t[0].type)=>{let u=e.session.pack?2:0,l=!ye.areEqual(t[0].dims,t[1].dims),d=t[0].dims,c=e.session.pack;if(l){let o=Qt.calcShape(t[0].dims,t[1].dims,!1);if(!o)throw new Error("Can't perform binary op on the given tensors");d=o;let a=d.length,p=t[0].dims.length!==0?t[0].dims.length:1,h=t[1].dims.length!==0?t[1].dims.length:1,m=t[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",g=t[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",_=Ae(e.session.backend.glContext.version),w=c?` + `,name:t,type:0}}var bt,Ah,jw,Uw,Vw,Gw,qw,Hw,Ww,Kw,Xw,Zw,Yw,Jw,vE=D(()=>{"use strict";Me(),Pr(),Ke(),Pe(),bt=(e,t,n,i=t[0].type,u)=>{let l=e.session.pack?2:0;return{name:n.name,inputNames:["A","B"],inputTypes:[l,l],cacheHint:u,get:()=>Ah(e,t,n,i)}},Ah=(e,t,n,i=t[0].type)=>{let u=e.session.pack?2:0,l=!ye.areEqual(t[0].dims,t[1].dims),d=t[0].dims,c=e.session.pack;if(l){let o=Qt.calcShape(t[0].dims,t[1].dims,!1);if(!o)throw new Error("Can't perform binary op on the given tensors");d=o;let a=d.length,p=t[0].dims.length!==0?t[0].dims.length:1,h=t[1].dims.length!==0?t[1].dims.length:1,m=t[0].dims.length!==0?"bcastIndices_A(indices, aindices);":"aindices[0] = 0;",g=t[1].dims.length!==0?"bcastIndices_B(indices, bindices);":"bindices[0] = 0;",_=Ae(e.session.backend.glContext.version),w=c?` ${n.body} void main() { vec4 a = getAAtOutCoords(); @@ -321,18 +321,18 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( vec4 result = ${n.name}(v1, v2); ${s.output} = result; } - `;return{name:n.name,inputNames:["A","B"],inputTypes:[u,u],output:{dims:t[0].dims,type:i,textureType:u},shaderSource:r,hasMain:!0}},Nw=(e,t)=>[e.run(bt(e,t,tE()),t)],zw=(e,t)=>[e.run(bt(e,t,uE(),"bool"),t)],Bw=(e,t)=>[e.run(bt(e,t,rE()),t)],Fw=(e,t)=>[e.run(bt(e,t,oE(),"bool"),t)],Lw=(e,t)=>[e.run(bt(e,t,sE(),"bool"),t)],jw=(e,t)=>[e.run(bt(e,t,aE(),"bool"),t)],Uw=(e,t)=>[e.run(bt(e,t,nE()),t)],Vw=(e,t)=>[e.run(bt(e,t,lE(),"bool"),t)],qw=(e,t)=>[e.run(bt(e,t,cE()),t)],Gw=(e,t)=>[e.run(bt(e,t,pE()),t)],Hw=(e,t)=>[e.run(bt(e,t,iE()),t)],Ww=(e,t)=>[e.run(bt(e,t,dE(),"bool"),t)]}),Kw,Xw,Sh,mE=D(()=>{"use strict";Me(),Kw=(e,t,n)=>(Sh(t),[e.cast(t[0],n)]),Xw=e=>wt.tensorDataTypeFromProto(e.attributes.getInt("to")),Sh=e=>{if(!e||e.length!==1)throw new Error("Cast requires 1 input.");if(e[0].type==="string")throw new Error("Invalid input type.")}}),Ih,Oh,Zw,si,gE=D(()=>{"use strict";Ke(),Pe(),ar(),jn(),Ih=(e,t)=>({name:"Concat (packed)",inputNames:Array.from({length:e},(n,i)=>`X${i}`),inputTypes:Array(e).fill(2),cacheHint:t}),Oh=(e,t,n,i)=>{let u=n[0].dims.slice();if(i>=u.length||i<-1*u.length)throw new Error("axis specified for concat doesn't match input dimensionality");i<0&&(i=u.length+i);let l=u.slice(0);for(let O=1;OO.dims),a=zn(d),p=new Array(o.length-1);p[0]=o[0][i];for(let O=1;O[e.run(bt(e,t,uE()),t)],Uw=(e,t)=>[e.run(bt(e,t,mE(),"bool"),t)],Vw=(e,t)=>[e.run(bt(e,t,lE()),t)],Gw=(e,t)=>[e.run(bt(e,t,pE(),"bool"),t)],qw=(e,t)=>[e.run(bt(e,t,hE(),"bool"),t)],Hw=(e,t)=>[e.run(bt(e,t,fE(),"bool"),t)],Ww=(e,t)=>[e.run(bt(e,t,dE()),t)],Kw=(e,t)=>[e.run(bt(e,t,gE(),"bool"),t)],Xw=(e,t)=>[e.run(bt(e,t,yE()),t)],Zw=(e,t)=>[e.run(bt(e,t,wE()),t)],Yw=(e,t)=>[e.run(bt(e,t,cE()),t)],Jw=(e,t)=>[e.run(bt(e,t,bE(),"bool"),t)]}),Qw,e_,kh,xE=D(()=>{"use strict";Me(),Qw=(e,t,n)=>(kh(t),[e.cast(t[0],n)]),e_=e=>wt.tensorDataTypeFromProto(e.attributes.getInt("to")),kh=e=>{if(!e||e.length!==1)throw new Error("Cast requires 1 input.");if(e[0].type==="string")throw new Error("Invalid input type.")}}),Ph,Ch,t_,ui,$E=D(()=>{"use strict";Ke(),Pe(),ar(),jn(),Ph=(e,t)=>({name:"Concat (packed)",inputNames:Array.from({length:e},(n,i)=>`X${i}`),inputTypes:Array(e).fill(2),cacheHint:t}),Ch=(e,t,n,i)=>{let u=n[0].dims.slice();if(i>=u.length||i<-1*u.length)throw new Error("axis specified for concat doesn't match input dimensionality");i<0&&(i=u.length+i);let l=u.slice(0);for(let O=1;OO.dims),a=zn(d),p=new Array(o.length-1);p[0]=o[0][i];for(let O=1;O= ${p[O-1]}) { return getChannel( - getX${O}(${si(a,h,A)}), - vec2(${si(m,h,A)})); + getX${O}(${ui(a,h,A)}), + vec2(${ui(m,h,A)})); }`}let w=p.length,y=p[p.length-1];_+=` return getChannel( - getX${w}(${si(a,h,y)}), - vec2(${si(m,h,y)}));`;let T=Ae(e.session.backend.glContext.version),S=` + getX${w}(${ui(a,h,y)}), + vec2(${ui(m,h,y)}));`;let T=Ae(e.session.backend.glContext.version),S=` ${r} float getValue(${a.map(O=>"int "+O)}) { ${_} @@ -363,7 +363,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( } ${T.output} = result; } - `;return{...t,output:{dims:l,type:n[0].type,textureType:2},shaderSource:S,hasMain:!0}},Zw=(e,t,n)=>{let i=Ih(t.length,n.cacheKey);return{...i,get:()=>Oh(e,i,t,n.axis)}},si=(e,t,n)=>{let i=e.indexOf(t);return e.map((u,l)=>l===i?`${u} - ${n}`:u).join()}}),Yw,Eh,Ah,kh,_a,Ph,Ch,Rh,Jw,Dh,bE=D(()=>{"use strict";ut(),Pe(),gE(),Yw=(e,t,n)=>(Dh(t),e.session.pack&&t[0].dims.length>1?[e.run(Zw(e,t,n),t)]:[e.run(kh(e,t,n),t)]),Eh=(e,t)=>({name:"Concat",inputNames:Array.from({length:e},(n,i)=>`X${i}`),inputTypes:Array(e).fill(0),cacheHint:t}),Ah=(e,t,n,i)=>{let u=n[0].dims.slice();if(i>=u.length||i<-1*u.length)throw new Error("axis specified for concat doesn't match input dimensionality");i<0&&(i=u.length+i);let l=u.slice(0);for(let h=1;h{let i=Ph(t.length,n.cacheKey);return{...i,get:()=>Ch(e,i,t,n.axis)}},ui=(e,t,n)=>{let i=e.indexOf(t);return e.map((u,l)=>l===i?`${u} - ${n}`:u).join()}}),r_,Rh,Dh,Mh,$a,Nh,zh,Bh,n_,Fh,TE=D(()=>{"use strict";ut(),Pe(),$E(),r_=(e,t,n)=>(Fh(t),e.session.pack&&t[0].dims.length>1?[e.run(t_(e,t,n),t)]:[e.run(Mh(e,t,n),t)]),Rh=(e,t)=>({name:"Concat",inputNames:Array.from({length:e},(n,i)=>`X${i}`),inputTypes:Array(e).fill(0),cacheHint:t}),Dh=(e,t,n,i)=>{let u=n[0].dims.slice();if(i>=u.length||i<-1*u.length)throw new Error("axis specified for concat doesn't match input dimensionality");i<0&&(i=u.length+i);let l=u.slice(0);for(let h=1;htypeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( } return fetchDataFromCorrectTexture(textureIndex, indices); - }`;return{...t,output:{dims:l,type:n[0].type,textureType:0},shaderSource:p}},kh=(e,t,n)=>{let i=Eh(t.length,n.cacheKey);return{...i,get:()=>Ah(e,i,t,n.axis)}},_a=e=>`int getTextureWhereDataResides(int index) { + }`;return{...t,output:{dims:l,type:n[0].type,textureType:0},shaderSource:p}},Mh=(e,t,n)=>{let i=Rh(t.length,n.cacheKey);return{...i,get:()=>Dh(e,i,t,n.axis)}},$a=e=>`int getTextureWhereDataResides(int index) { ${e.map((t,n)=>`if(index<${t}) {return ${n};} `).join("")} - }`,Ph=e=>_a(e),Ch=(e,t)=>{let n=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${t}]) {`];for(let i=0;i{let t=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let n=0;nje({axis:e.attributes.getInt("axis")}),Dh=e=>{if(!e||e.length<1)throw new Error("too few inputs");let t=e[0].type,n=e[0].dims.length;if(t==="string")throw new Error("string tensor is not supported yet");for(let i of e){if(i.type!==t)throw new Error("input tensors should be one type");if(i.dims.length!==n)throw new Error("input tensors should have the same shape")}}});function yE(){return Dt("abs")}function wE(){return Dt("acos")}function _E(){return Dt("asin")}function vE(){return Dt("atan")}function xE(){return Dt("ceil")}function $E(){return Dt("cos")}function TE(e){return{body:` + }`,Nh=e=>$a(e),zh=(e,t)=>{let n=[`float fetchDataFromCorrectTexture(int textureIndex, int indices[${t}]) {`];for(let i=0;i{let t=["int getSizeInConcatAxisValueFromIndex(int index) {"];for(let n=0;nje({axis:e.attributes.getInt("axis")}),Fh=e=>{if(!e||e.length<1)throw new Error("too few inputs");let t=e[0].type,n=e[0].dims.length;if(t==="string")throw new Error("string tensor is not supported yet");for(let i of e){if(i.type!==t)throw new Error("input tensors should be one type");if(i.dims.length!==n)throw new Error("input tensors should have the same shape")}}});function SE(){return Dt("abs")}function IE(){return Dt("acos")}function OE(){return Dt("asin")}function EE(){return Dt("atan")}function AE(){return Dt("ceil")}function kE(){return Dt("cos")}function PE(e){return{body:` const float alpha = float(${e}); float elu_(float a) { @@ -389,7 +389,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( vec4 elu_(vec4 v) { return vec4(elu_(v.x), elu_(v.y), elu_(v.z), elu_(v.w)); } - `,name:"elu",type:0}}function SE(){return Dt("exp")}function IE(){return Dt("floor")}function Qw(e,t){let n="clip";return{body:` + `,name:"elu",type:0}}function CE(){return Dt("exp")}function RE(){return Dt("floor")}function i_(e,t){let n="clip";return{body:` const float min = float(${e}); const float max = float(${t}); @@ -399,14 +399,14 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( vec4 ${n}_(vec4 v) { return clamp(v, min, max); } - `,name:n,type:0}}function OE(){let e="indentity";return{body:` + `,name:n,type:0}}function DE(){let e="indentity";return{body:` float ${e}_(float a) { return a; } vec4 ${e}_(vec4 v) { return v; } - `,name:e,type:0}}function EE(e){let t="leakyRelu";return{body:` + `,name:e,type:0}}function ME(e){let t="leakyRelu";return{body:` const float alpha = float(${e}); float ${t}_(float a) { @@ -415,14 +415,14 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( vec4 ${t}_(vec4 v) { return vec4(${t}_(v.x), ${t}_(v.y), ${t}_(v.z), ${t}_(v.w)); } - `,name:t,type:0}}function AE(){return Dt("log")}function kE(){return{body:` + `,name:t,type:0}}function NE(){return Dt("log")}function zE(){return{body:` float neg_(float a) { return -a; } vec4 neg_(vec4 v) { return -v; } - `,name:"neg",type:0}}function PE(){return{body:` + `,name:"neg",type:0}}function BE(){return{body:` float not_(float a) { return float( ! bool(a) ); } @@ -435,21 +435,21 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( bvec4 not_(bvec4 v) { return bvec4(!v.x, !v.y, !v.z, !v.w); } - `,name:"not",type:0}}function CE(){return Dt("sin")}function e_(){let e="relu";return{body:` + `,name:"not",type:0}}function FE(){return Dt("sin")}function o_(){let e="relu";return{body:` float ${e}_(float a) { return max( a, 0.0 ); } vec4 ${e}_(vec4 v) { return max( v, 0.0 ); } - `,name:e,type:0}}function t_(){let e="sigmoid";return{body:` + `,name:e,type:0}}function s_(){let e="sigmoid";return{body:` float ${e}_(float a) { return 1.0 / (1.0 + exp(-a)); } vec4 ${e}_(vec4 v) { return 1.0 / (1.0 + exp(-v)); } - `,name:e,type:0}}function RE(){return Dt("sqrt")}function DE(){return Dt("tan")}function ME(){let e="tanh";return{body:` + `,name:e,type:0}}function LE(){return Dt("sqrt")}function jE(){return Dt("tan")}function UE(){let e="tanh";return{body:` float ${e}_(float a) { a = clamp(a, -10., 10.); a = exp(2.*a); @@ -467,14 +467,14 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( vec4 ${e}_(vec4 v) { return ${e}(v); } - `,name:e,type:0}}var Mh,Ye,r_,n_,i_,o_,cl,s_,a_,Nh,u_,l_,d_,c_,p_,h_,pl,f_,m_,g_,b_,y_,w_,__,v_,x_,$_,T_,S_=D(()=>{"use strict";ut(),Me(),Pr(),Ke(),Pe(),Mh=(e,t,n,i)=>{let u=e.session.pack?2:0,l=Ae(e.session.backend.glContext.version);return{...t,output:{dims:n.dims,type:n.type,textureType:u},shaderSource:` + `,name:e,type:0}}var Lh,Ye,a_,u_,l_,d_,fl,c_,p_,jh,h_,f_,m_,g_,b_,y_,ml,w_,__,v_,x_,$_,T_,S_,I_,O_,E_,A_,k_=D(()=>{"use strict";ut(),Me(),Pr(),Ke(),Pe(),Lh=(e,t,n,i)=>{let u=e.session.pack?2:0,l=Ae(e.session.backend.glContext.version);return{...t,output:{dims:n.dims,type:n.type,textureType:u},shaderSource:` ${i.body} void main() { vec4 v = ${l.texture2D}(A, TexCoords); v = ${i.name}_(v); ${l.output} = v; } - `,hasMain:!0}},Ye=(e,t,n,i)=>{let u=e.session.pack?2:0,l={name:n.name,inputTypes:[u],inputNames:["A"],cacheHint:i};return{...l,get:()=>Mh(e,l,t,n)}},r_=(e,t)=>[e.run(Ye(e,t[0],yE()),t)],n_=(e,t)=>[e.run(Ye(e,t[0],wE()),t)],i_=(e,t)=>[e.run(Ye(e,t[0],_E()),t)],o_=(e,t)=>[e.run(Ye(e,t[0],vE()),t)],cl=(e,t,n)=>[e.run(Ye(e,t[0],Qw(n.min,n.max),n.cacheKey),t)],s_=e=>je({min:e.attributes.getFloat("min",Ci),max:e.attributes.getFloat("max",Ri)}),a_=(e,t)=>{let n=Nh(e,t);return cl(e,[t[0]],n)},Nh=(e,t)=>{if(t.length>=3&&(!e.session.isInitializer(t[1].dataId)||!e.session.isInitializer(t[2].dataId)))throw new Error("dynamic clip attributes are not allowed");let n=t.length>=3?t[1].numberData[0]:Ci,i=t.length>=3?t[2].numberData[0]:Ri;return je({min:n,max:i})},u_=(e,t)=>[e.run(Ye(e,t[0],xE()),t)],l_=(e,t)=>[e.run(Ye(e,t[0],$E()),t)],d_=(e,t,n)=>[e.run(Ye(e,t[0],TE(n.alpha),n.cacheKey),t)],c_=e=>je({alpha:e.attributes.getFloat("alpha",1)}),p_=(e,t)=>[e.run(Ye(e,t[0],SE()),t)],h_=(e,t)=>[e.run(Ye(e,t[0],IE()),t)],pl=(e,t)=>[e.run(Ye(e,t[0],OE()),t)],f_=(e,t,n)=>[e.run(Ye(e,t[0],EE(n.alpha),n.cacheKey),t)],m_=e=>je({alpha:e.attributes.getFloat("alpha",.01)}),g_=(e,t)=>[e.run(Ye(e,t[0],AE()),t)],b_=(e,t)=>[e.run(Ye(e,t[0],kE()),t)],y_=(e,t)=>[e.run(Ye(e,t[0],PE()),t)],w_=(e,t)=>[e.run(Ye(e,t[0],e_()),t)],__=(e,t)=>[e.run(Ye(e,t[0],t_()),t)],v_=(e,t)=>[e.run(Ye(e,t[0],CE()),t)],x_=(e,t)=>[e.run(Ye(e,t[0],RE()),t)],$_=(e,t)=>[e.run(Ye(e,t[0],DE()),t)],T_=(e,t)=>[e.run(Ye(e,t[0],ME()),t)]});function Bi(e){let t;switch(e.activation){case"Relu":t=e_();break;case"Sigmoid":t=t_();break;case"Clip":t=Qw(e.clipMin,e.clipMax);break;default:return{activationFunction:"",applyActivation:""}}let n=t.name,i=t.body,u=`value = ${n}_(value);`;return{activationFunction:i,applyActivation:u}}var is,Vn=D(()=>{"use strict";Me(),S_(),is=e=>{let t=e.getString("activation","");if(t==="Clip"){let[n,i]=e.getFloats("activation_params",[Ci,Ri]);return{activation:t,clipMax:i,clipMin:n,activationCacheKey:`${t}:${n},${i}`}}return{activation:t,activationCacheKey:t}}}),zh,Bh,I_,NE=D(()=>{"use strict";qt(),Ke(),Pe(),Yl(),Vn(),zh=(e,t)=>({name:"GroupedConv",inputNames:e?["X","W","Bias"]:["X","W"],inputTypes:e?[0,0,0]:[0,0],cacheHint:t}),Bh=(e,t,n,i)=>{let u=t.length>2?"value += getBias(output_channel);":"",l=t[0].dims.slice(),d=t[1].dims.slice(),c=d[0]/i.group;Je.verbose("GroupedConv",`autpPad:${i.autoPad}, dilations:${i.dilations}, group:${i.group}, kernelShape:${i.kernelShape}, pads:${i.pads}, strides:${i.strides}`);let s=Ai(l,d,i.dilations,i.pads,i.strides),r=Ae(e.session.backend.glContext.version),{activationFunction:o,applyActivation:a}=Bi(i),p=` + `,hasMain:!0}},Ye=(e,t,n,i)=>{let u=e.session.pack?2:0,l={name:n.name,inputTypes:[u],inputNames:["A"],cacheHint:i};return{...l,get:()=>Lh(e,l,t,n)}},a_=(e,t)=>[e.run(Ye(e,t[0],SE()),t)],u_=(e,t)=>[e.run(Ye(e,t[0],IE()),t)],l_=(e,t)=>[e.run(Ye(e,t[0],OE()),t)],d_=(e,t)=>[e.run(Ye(e,t[0],EE()),t)],fl=(e,t,n)=>[e.run(Ye(e,t[0],i_(n.min,n.max),n.cacheKey),t)],c_=e=>je({min:e.attributes.getFloat("min",Di),max:e.attributes.getFloat("max",Mi)}),p_=(e,t)=>{let n=jh(e,t);return fl(e,[t[0]],n)},jh=(e,t)=>{if(t.length>=3&&(!e.session.isInitializer(t[1].dataId)||!e.session.isInitializer(t[2].dataId)))throw new Error("dynamic clip attributes are not allowed");let n=t.length>=3?t[1].numberData[0]:Di,i=t.length>=3?t[2].numberData[0]:Mi;return je({min:n,max:i})},h_=(e,t)=>[e.run(Ye(e,t[0],AE()),t)],f_=(e,t)=>[e.run(Ye(e,t[0],kE()),t)],m_=(e,t,n)=>[e.run(Ye(e,t[0],PE(n.alpha),n.cacheKey),t)],g_=e=>je({alpha:e.attributes.getFloat("alpha",1)}),b_=(e,t)=>[e.run(Ye(e,t[0],CE()),t)],y_=(e,t)=>[e.run(Ye(e,t[0],RE()),t)],ml=(e,t)=>[e.run(Ye(e,t[0],DE()),t)],w_=(e,t,n)=>[e.run(Ye(e,t[0],ME(n.alpha),n.cacheKey),t)],__=e=>je({alpha:e.attributes.getFloat("alpha",.01)}),v_=(e,t)=>[e.run(Ye(e,t[0],NE()),t)],x_=(e,t)=>[e.run(Ye(e,t[0],zE()),t)],$_=(e,t)=>[e.run(Ye(e,t[0],BE()),t)],T_=(e,t)=>[e.run(Ye(e,t[0],o_()),t)],S_=(e,t)=>[e.run(Ye(e,t[0],s_()),t)],I_=(e,t)=>[e.run(Ye(e,t[0],FE()),t)],O_=(e,t)=>[e.run(Ye(e,t[0],LE()),t)],E_=(e,t)=>[e.run(Ye(e,t[0],jE()),t)],A_=(e,t)=>[e.run(Ye(e,t[0],UE()),t)]});function Li(e){let t;switch(e.activation){case"Relu":t=o_();break;case"Sigmoid":t=s_();break;case"Clip":t=i_(e.clipMin,e.clipMax);break;default:return{activationFunction:"",applyActivation:""}}let n=t.name,i=t.body,u=`value = ${n}_(value);`;return{activationFunction:i,applyActivation:u}}var ss,Vn=D(()=>{"use strict";Me(),k_(),ss=e=>{let t=e.getString("activation","");if(t==="Clip"){let[n,i]=e.getFloats("activation_params",[Di,Mi]);return{activation:t,clipMax:i,clipMin:n,activationCacheKey:`${t}:${n},${i}`}}return{activation:t,activationCacheKey:t}}}),Uh,Vh,P_,VE=D(()=>{"use strict";Gt(),Ke(),Pe(),ed(),Vn(),Uh=(e,t)=>({name:"GroupedConv",inputNames:e?["X","W","Bias"]:["X","W"],inputTypes:e?[0,0,0]:[0,0],cacheHint:t}),Vh=(e,t,n,i)=>{let u=t.length>2?"value += getBias(output_channel);":"",l=t[0].dims.slice(),d=t[1].dims.slice(),c=d[0]/i.group;Je.verbose("GroupedConv",`autpPad:${i.autoPad}, dilations:${i.dilations}, group:${i.group}, kernelShape:${i.kernelShape}, pads:${i.pads}, strides:${i.strides}`);let s=Pi(l,d,i.dilations,i.pads,i.strides),r=Ae(e.session.backend.glContext.version),{activationFunction:o,applyActivation:a}=Li(i),p=` const ivec2 strides = ivec2(${i.strides[0]}, ${i.strides[1]}); const ivec2 pads = ivec2(${i.pads[0]}, ${i.pads[1]}); ${o} @@ -511,7 +511,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( ${a} ${r.output} = vec4(value, .0, .0, .0); } -`;return{...n,output:{dims:s,type:t[0].type,textureType:0},shaderSource:p,hasMain:!0}},I_=(e,t,n)=>{let i=zh(t.length>2,n.cacheKey);return{...i,get:()=>Bh(e,t,i,n)}}}),Fh,Lh,O_,zE=D(()=>{"use strict";Ke(),Pe(),jn(),Fh=e=>({name:"Im2Col (packed)",inputNames:["A"],inputTypes:[2],cacheHint:e}),Lh=(e,t,n,i,u,l)=>{let d=n.dims,c=i.dims,s=2,r=3,o=u.length,a=[c[1]*c[2]*c[3],u[2]*u[3]],p=c[2]*c[3],h=zi(),m=Ae(e.session.backend.glContext.version),g="";for(let w=0;w<=1;w++)for(let y=0;y<=1;y++)g+=` +`;return{...n,output:{dims:s,type:t[0].type,textureType:0},shaderSource:p,hasMain:!0}},P_=(e,t,n)=>{let i=Uh(t.length>2,n.cacheKey);return{...i,get:()=>Vh(e,t,i,n)}}}),Gh,qh,C_,GE=D(()=>{"use strict";Ke(),Pe(),jn(),Gh=e=>({name:"Im2Col (packed)",inputNames:["A"],inputTypes:[2],cacheHint:e}),qh=(e,t,n,i,u,l)=>{let d=n.dims,c=i.dims,s=2,r=3,o=u.length,a=[c[1]*c[2]*c[3],u[2]*u[3]],p=c[2]*c[3],h=Fi(),m=Ae(e.session.backend.glContext.version),g="";for(let w=0;w<=1;w++)for(let y=0;y<=1;y++)g+=` blockIndex = rc.x + ${y}; pos = rc.y + ${w}; @@ -547,7 +547,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( ${g} ${m.output} = result; } - `;return{...t,output:{dims:a,type:n.type,textureType:2},shaderSource:_,hasMain:!0}},O_=(e,t,n,i,u)=>{let l=Fh(u.cacheKey);return{...l,get:()=>Lh(e,l,t,n,i,u)}}});function BE(e,t,n){let i=t[0].dims,u=t[1].dims,l=Qt.calcShape(i,u,!0);if(!l)throw new Error("Can't use matmul on the given tensors");let d=Ar(l.length),c=zn(),{activationFunction:s,applyActivation:r}=Bi(n),o=t.length>2,a=o?"value += getBiasForMatmul();":"",p=o?`${A_(d,c,t[2].dims,l,!1)}`:"",h=l.length,m=i.length,g=u.length,_=i[i.length-1],w=` + `;return{...t,output:{dims:a,type:n.type,textureType:2},shaderSource:_,hasMain:!0}},C_=(e,t,n,i,u)=>{let l=Gh(u.cacheKey);return{...l,get:()=>qh(e,l,t,n,i,u)}}});function qE(e,t,n){let i=t[0].dims,u=t[1].dims,l=Qt.calcShape(i,u,!0);if(!l)throw new Error("Can't use matmul on the given tensors");let d=Ar(l.length),c=zn(),{activationFunction:s,applyActivation:r}=Li(n),o=t.length>2,a=o?"value += getBiasForMatmul();":"",p=o?`${D_(d,c,t[2].dims,l,!1)}`:"",h=l.length,m=i.length,g=u.length,_=i[i.length-1],w=` ${s} ${p} float process(int indices[${h}]) { @@ -565,7 +565,7 @@ var jr=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>( ${a} ${r} return value; - }`;return{...e,output:{dims:l,type:t[0].type,textureType:0},shaderSource:w}}function E_(e,t){let n=C_(e.length>2,t.activationCacheKey);return{...n,get:()=>BE(n,e,t)}}function A_(e,t,n,i,u){let l="",d=n.length,c=i.length,s=c-d;c<2&&d>0?l="coords":l=n.map((p,h)=>`coords.${t[h+s]}`).join(", ");let r=Qt.getBroadcastDims(n,i).map(p=>`coords.${t[p+s]} = 0;`).join(` + }`;return{...e,output:{dims:l,type:t[0].type,textureType:0},shaderSource:w}}function R_(e,t){let n=z_(e.length>2,t.activationCacheKey);return{...n,get:()=>qE(n,e,t)}}function D_(e,t,n,i,u){let l="",d=n.length,c=i.length,s=c-d;c<2&&d>0?l="coords":l=n.map((p,h)=>`coords.${t[h+s]}`).join(", ");let r=Qt.getBroadcastDims(n,i).map(p=>`coords.${t[p+s]} = 0;`).join(` `),o=ye.size(n)===1,a="vec4(outputValue.xx, outputValue.yy)";return o&&(a="vec4(outputValue.x)"),u?` vec4 getBiasForMatmul() { ${e} coords = getOutputCoords(); @@ -577,7 +577,7 @@ float getBiasForMatmul() { ${e} coords = getOutputCoords(); ${r} return getBias(coords.x); -}`}var k_,P_,C_,jh,Xl=D(()=>{"use strict";Me(),Pe(),ar(),Vn(),R_(),k_=(e,t,n)=>(jh(t),e.session.pack?[e.run(Zl(e,t,n),t)]:[e.run(E_(t,n),t)]),P_=e=>is(e.attributes),C_=(e,t)=>({name:"MatMul",inputNames:e?["A","B","Bias"]:["A","B"],inputTypes:e?[0,0,0]:[0,0],cacheHint:t}),jh=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.");if(e[0].type!=="float32"&&e[0].type!=="float64"||e[1].type!=="float32"&&e[1].type!=="float64")throw new Error("inputs should be float type");if(e[0].type!==e[1].type)throw new Error("inputs types should match")}});function FE(e,t,n,i){let u=[],l=[],d=n[0].dims,c=n[1].dims,s=d.length,r=c.length,o=i.length,a=o-s,p=o-r;u=d.map((y,T)=>`coords.${t[T+a]}`),u[s-1]="i*2",u.join(", "),l=c.map((y,T)=>`coords.${t[T+p]}`),l[r-2]="i*2",l.join(", ");let h=Qt.getBroadcastDims(d,i),m=Qt.getBroadcastDims(c,i),g=h.map(y=>`coords.${t[y+a]} = 0;`).join(` +}`}var M_,N_,z_,Hh,Jl=D(()=>{"use strict";Me(),Pe(),ar(),Vn(),B_(),M_=(e,t,n)=>(Hh(t),e.session.pack?[e.run(Ql(e,t,n),t)]:[e.run(R_(t,n),t)]),N_=e=>ss(e.attributes),z_=(e,t)=>({name:"MatMul",inputNames:e?["A","B","Bias"]:["A","B"],inputTypes:e?[0,0,0]:[0,0],cacheHint:t}),Hh=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.");if(e[0].type!=="float32"&&e[0].type!=="float64"||e[1].type!=="float32"&&e[1].type!=="float64")throw new Error("inputs should be float type");if(e[0].type!==e[1].type)throw new Error("inputs types should match")}});function HE(e,t,n,i){let u=[],l=[],d=n[0].dims,c=n[1].dims,s=d.length,r=c.length,o=i.length,a=o-s,p=o-r;u=d.map((y,T)=>`coords.${t[T+a]}`),u[s-1]="i*2",u.join(", "),l=c.map((y,T)=>`coords.${t[T+p]}`),l[r-2]="i*2",l.join(", ");let h=Qt.getBroadcastDims(d,i),m=Qt.getBroadcastDims(c,i),g=h.map(y=>`coords.${t[y+a]} = 0;`).join(` `),_=m.map(y=>`coords.${t[y+p]} = 0;`).join(` `),w=`int lastDim = coords.${t[o-1]}; coords.${t[o-1]} = coords.${t[o-2]}; @@ -596,7 +596,7 @@ vec4 getBAtOutCoordsMatmul(int i) { ${_} vec4 outputValue = getB(${l}); return outputValue; -}`}function LE(e,t){let n="";for(let i=0;i{"use strict";Me(),Ke(),Pe(),ar(),Vn(),Xl(),Uh=(e,t)=>({name:"MatMul (packed)",inputNames:e?["A","B","Bias"]:["A","B"],inputTypes:e?[2,2,2]:[2,2],cacheHint:t}),Vh=(e,t,n,i)=>{let u=n.length>2,l=u?"value += getBiasForMatmul();":"",d=n[0].dims,c=n[1].dims,s=Qt.calcShape(d,c,!0),r=!ye.areEqual(n[0].dims,n[1].dims);if(!s)throw new Error("Can't use matmul on the given tensors");let o=d[d.length-1],a=Math.ceil(o/2),p=d.length,h=c.length,m=Ae(e.session.backend.glContext.version),g=Ar(s.length),_=s.length,w=zn(),{activationFunction:y,applyActivation:T}=Bi(i),S=u?`${A_(g,w,n[2].dims,s,!0)}`:"",O=r?`${FE(g,w,n,s)}`:"",A=r?"getAAtOutCoordsMatmul(i)":`getA(${LE(w,p)})`,P=r?"getBAtOutCoordsMatmul(i)":`getB(${jE(w,h)})`,I=r?"":`${g} rc = +}`}function WE(e,t){let n="";for(let i=0;i{"use strict";Me(),Ke(),Pe(),ar(),Vn(),Jl(),Wh=(e,t)=>({name:"MatMul (packed)",inputNames:e?["A","B","Bias"]:["A","B"],inputTypes:e?[2,2,2]:[2,2],cacheHint:t}),Kh=(e,t,n,i)=>{let u=n.length>2,l=u?"value += getBiasForMatmul();":"",d=n[0].dims,c=n[1].dims,s=Qt.calcShape(d,c,!0),r=!ye.areEqual(n[0].dims,n[1].dims);if(!s)throw new Error("Can't use matmul on the given tensors");let o=d[d.length-1],a=Math.ceil(o/2),p=d.length,h=c.length,m=Ae(e.session.backend.glContext.version),g=Ar(s.length),_=s.length,w=zn(),{activationFunction:y,applyActivation:T}=Li(i),S=u?`${D_(g,w,n[2].dims,s,!0)}`:"",O=r?`${HE(g,w,n,s)}`:"",A=r?"getAAtOutCoordsMatmul(i)":`getA(${WE(w,p)})`,P=r?"getBAtOutCoordsMatmul(i)":`getB(${KE(w,h)})`,I=r?"":`${g} rc = getOutputCoords(); int lastDim = rc.${w[_-1]}; rc.${w[_-1]} = rc.${w[_-2]}; rc.${w[_-2]} = lastDim; `,z=` @@ -617,7 +617,7 @@ vec4 getBAtOutCoordsMatmul(int i) { ${l} ${T} ${m.output} = value; - }`;return{...t,output:{dims:s,type:n[0].type,textureType:2},shaderSource:z,hasMain:!0}},Zl=(e,t,n)=>{let i=Uh(t.length>2,n.activationCacheKey);return{...i,get:()=>Vh(e,i,t,n)}}}),D_,UE=D(()=>{"use strict";Yl(),zE(),R_(),D_=(e,t,n)=>{let i=t[0].dims,u=t[1].dims,l=Ai(i,u,n.dilations,n.pads,n.strides),d=e.run(O_(e,t[0],t[1],l,n),[t[0]]),c=e.reshapePacked(t[1],[u[0],u[1]*u[2]*u[3]]),s=t.length===3?[c,d,t[2]]:[c,d],r=e.run(Zl(e,s,n),s);return e.reshapePacked(r,l)}}),qh,Gh,M_,hl,N_=D(()=>{"use strict";Pe(),qh=e=>({name:"Im2Col",inputNames:["X"],inputTypes:[0],cacheHint:e}),Gh=(e,t,n,i,u,l)=>{let d=n.dims,c=i.dims,s=u.length,r=hl(d,c,u,4),o=` + }`;return{...t,output:{dims:s,type:n[0].type,textureType:2},shaderSource:z,hasMain:!0}},Ql=(e,t,n)=>{let i=Wh(t.length>2,n.activationCacheKey);return{...i,get:()=>Kh(e,i,t,n)}}}),F_,XE=D(()=>{"use strict";ed(),GE(),B_(),F_=(e,t,n)=>{let i=t[0].dims,u=t[1].dims,l=Pi(i,u,n.dilations,n.pads,n.strides),d=e.run(C_(e,t[0],t[1],l,n),[t[0]]),c=e.reshapePacked(t[1],[u[0],u[1]*u[2]*u[3]]),s=t.length===3?[c,d,t[2]]:[c,d],r=e.run(Ql(e,s,n),s);return e.reshapePacked(r,l)}}),Xh,Zh,L_,gl,j_=D(()=>{"use strict";Pe(),Xh=e=>({name:"Im2Col",inputNames:["X"],inputTypes:[0],cacheHint:e}),Zh=(e,t,n,i,u,l)=>{let d=n.dims,c=i.dims,s=u.length,r=gl(d,c,u,4),o=` const int XC = ${d[1]}; const int XH = ${d[2]}; const int XW = ${d[3]}; @@ -661,7 +661,7 @@ vec4 getBAtOutCoordsMatmul(int i) { } return value; } - `;return{...t,output:{dims:r,type:n.type,textureType:4},shaderSource:o}},M_=(e,t,n,i,u)=>{let l=qh(u.cacheKey);return{...l,get:()=>Gh(e,l,t,n,i,u)}},hl=(e,t,n,i=4)=>[n[0],n[2],n[3],Math.ceil(e[1]*t[2]*t[3]/i)]}),Hh,Wh,z_,VE=D(()=>{"use strict";Me(),Ke(),Pe(),Vn(),N_(),Hh=(e,t)=>({name:"ConvDotProduct",inputNames:e?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:e?[0,4,0]:[0,4],cacheKey:t.activationCacheKey}),Wh=(e,t,n,i,u)=>{let l=n[0].dims,d=n[1].dims,c=[d[0],Math.ceil(l[1]*d[2]*d[3]/4)],s=hl(l,d,i),[r,o]=e.calculateTextureWidthAndHeight(c,4),a=ye.computeStrides(s),[p,h]=e.calculateTextureWidthAndHeight(s,4),m=i.length,g=n.length<3?"0.0":"_B(b)",_=Math.ceil(l[1]*d[2]*d[3]/4),{activationFunction:w,applyActivation:y}=Bi(u),T=Ae(e.session.backend.glContext.version),S=` + `;return{...t,output:{dims:r,type:n.type,textureType:4},shaderSource:o}},L_=(e,t,n,i,u)=>{let l=Xh(u.cacheKey);return{...l,get:()=>Zh(e,l,t,n,i,u)}},gl=(e,t,n,i=4)=>[n[0],n[2],n[3],Math.ceil(e[1]*t[2]*t[3]/i)]}),Yh,Jh,U_,ZE=D(()=>{"use strict";Me(),Ke(),Pe(),Vn(),j_(),Yh=(e,t)=>({name:"ConvDotProduct",inputNames:e?["Im2Col","K","B"]:["Im2Col","K"],inputTypes:e?[0,4,0]:[0,4],cacheKey:t.activationCacheKey}),Jh=(e,t,n,i,u)=>{let l=n[0].dims,d=n[1].dims,c=[d[0],Math.ceil(l[1]*d[2]*d[3]/4)],s=gl(l,d,i),[r,o]=e.calculateTextureWidthAndHeight(c,4),a=ye.computeStrides(s),[p,h]=e.calculateTextureWidthAndHeight(s,4),m=i.length,g=n.length<3?"0.0":"_B(b)",_=Math.ceil(l[1]*d[2]*d[3]/4),{activationFunction:w,applyActivation:y}=Li(u),T=Ae(e.session.backend.glContext.version),S=` ${w} float process(int indices[${m}]) { int b[1]; @@ -682,7 +682,7 @@ float process(int indices[${m}]) { } ${y} return value; -}`;return{...t,output:{dims:i,type:n[0].type,textureType:0},shaderSource:S}},z_=(e,t,n,i)=>{let u=Hh(t.length>2,i);return{...u,get:()=>Wh(e,u,t,n,i)}}}),Ai,fl,Kh,Xh,Zh,Yh,ml,Jh,Yl=D(()=>{"use strict";ut(),Me(),NE(),UE(),VE(),Vn(),N_(),Xl(),Ai=(e,t,n,i,u)=>{let l=e[0],d=e.slice(2),c=d.length,s=t[0],r=t.slice(2).map((a,p)=>a+(a-1)*(n[p]-1)),o=d.map((a,p)=>a+i[p]+i[p+c]).map((a,p)=>Math.floor((a-r[p]+u[p])/u[p]));return[l,s].concat(...o)},fl=(e,t,n)=>(Jh(t,n),Kh(e,t,n)),Kh=(e,t,n)=>{let i=Yh(n,t),u=e.session.pack,l=i.kernelShape[0]===1&&i.kernelShape[1]===1;return i.group>1?[e.run(I_(e,t,i),t)]:l&&u?[Xh(e,t,i)]:u&&t[0].dims.length===4&&t[0].dims[0]===1&&!l?[D_(e,t,i)]:[Zh(e,t,i)]},Xh=(e,t,n)=>{let i=t[0].dims,u=t[1].dims,l=Ai(i,u,n.dilations,n.pads,n.strides),d=e.reshapeUnpacked(t[0],[i[1],i[2]*i[3]]),c=e.reshapeUnpacked(t[1],[u[0],u[1]]),s=t.length>2?[c,d,t[2]]:[c,d],r=e.run(E_(s,n),s);return e.reshapeUnpacked(r,l)},Zh=(e,t,n)=>{let i=t[0].dims,u=t[1].dims,l=Ai(i,u,n.dilations,n.pads,n.strides),d=e.run(M_(e,t[0],t[1],l,n),[t[0]]),c=t.length===3?[d,t[1],t[2]]:[d,t[1]];return e.run(z_(e,t,l,n),c)},Yh=(e,t)=>{let n=e.kernelShape.slice();if(e.kernelShape.length===0)for(let l=2;l{let t=e.attributes,n=is(t),i=t.getString("auto_pad","NOTSET"),u=t.getInts("dilations",[1,1]),l=t.getInt("group",1),d=t.getInts("kernel_shape",[]),c=t.getInts("pads",[0,0,0,0]),s=t.getInts("strides",[1,1]);return je({autoPad:i,dilations:u,group:l,kernelShape:d,pads:c,strides:s,...n})},Jh=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4||e[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");let n=e[0].dims[1],i=e[1].dims[1]*t.group;if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let u=e[0].dims.length-2;if(t.dilations.length!==u)throw new Error(`dilations should be ${u}D`);if(t.strides.length!==u)throw new Error(`strides should be ${u}D`);if(t.pads.length!==u*2)throw new Error(`pads should be ${u*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(e[0].type!=="float32"||e[1].type!=="float32")throw new Error("Conv input(X,W) should be float tensor");if(e.length===3&&e[2].type!=="float32")throw new Error("Conv input(bias) should be float tensor")}}),Qh,ef,tf,B_,rf,nf,of,sf,af,uf,F_,lf,qE=D(()=>{"use strict";ut(),Ke(),Pe(),Vn(),Qh=(e,t,n,i,u,l)=>(e-1)*t+n+(i-1)*u+1-l,ef=(e,t,n,i,u)=>{let l=Math.floor(e/2);t==="SAME_UPPER"?(n[i]=l,n[u]=e-l):t==="SAME_LOWER"&&(n[i]=e-l,n[u]=l)},tf=(e,t,n,i,u,l,d,c)=>{let s=e.length-2,r=c.length===0;for(let o=0;o(lf(t,n),rf(e,t,n)),rf=(e,t,n)=>{let i=uf(n,t);return[af(e,t,i)]},nf=(e,t)=>({name:"ConvTranspose",inputNames:e?["X","W","B"]:["X","W"],inputTypes:e?[0,0,0]:[0,0],cacheHint:t}),of=(e,t,n,i)=>{let u=t.length>2?"getB(output_channel)":"0.0",l=t[0].dims,d=t[1].dims,c=d[1],s=d[0]/i.group,r=[t[0].dims[0],t[1].dims[1]*i.group,...i.outputShape],o=Ae(e.session.backend.glContext.version),{activationFunction:a,applyActivation:p}=Bi(i),h=` +}`;return{...t,output:{dims:i,type:n[0].type,textureType:0},shaderSource:S}},U_=(e,t,n,i)=>{let u=Yh(t.length>2,i);return{...u,get:()=>Jh(e,u,t,n,i)}}}),Pi,bl,Qh,ef,tf,rf,yl,nf,ed=D(()=>{"use strict";ut(),Me(),VE(),XE(),ZE(),Vn(),j_(),Jl(),Pi=(e,t,n,i,u)=>{let l=e[0],d=e.slice(2),c=d.length,s=t[0],r=t.slice(2).map((a,p)=>a+(a-1)*(n[p]-1)),o=d.map((a,p)=>a+i[p]+i[p+c]).map((a,p)=>Math.floor((a-r[p]+u[p])/u[p]));return[l,s].concat(...o)},bl=(e,t,n)=>(nf(t,n),Qh(e,t,n)),Qh=(e,t,n)=>{let i=rf(n,t),u=e.session.pack,l=i.kernelShape[0]===1&&i.kernelShape[1]===1;return i.group>1?[e.run(P_(e,t,i),t)]:l&&u?[ef(e,t,i)]:u&&t[0].dims.length===4&&t[0].dims[0]===1&&!l?[F_(e,t,i)]:[tf(e,t,i)]},ef=(e,t,n)=>{let i=t[0].dims,u=t[1].dims,l=Pi(i,u,n.dilations,n.pads,n.strides),d=e.reshapeUnpacked(t[0],[i[1],i[2]*i[3]]),c=e.reshapeUnpacked(t[1],[u[0],u[1]]),s=t.length>2?[c,d,t[2]]:[c,d],r=e.run(R_(s,n),s);return e.reshapeUnpacked(r,l)},tf=(e,t,n)=>{let i=t[0].dims,u=t[1].dims,l=Pi(i,u,n.dilations,n.pads,n.strides),d=e.run(L_(e,t[0],t[1],l,n),[t[0]]),c=t.length===3?[d,t[1],t[2]]:[d,t[1]];return e.run(U_(e,t,l,n),c)},rf=(e,t)=>{let n=e.kernelShape.slice();if(e.kernelShape.length===0)for(let l=2;l{let t=e.attributes,n=ss(t),i=t.getString("auto_pad","NOTSET"),u=t.getInts("dilations",[1,1]),l=t.getInt("group",1),d=t.getInts("kernel_shape",[]),c=t.getInts("pads",[0,0,0,0]),s=t.getInts("strides",[1,1]);return je({autoPad:i,dilations:u,group:l,kernelShape:d,pads:c,strides:s,...n})},nf=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4||e[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");let n=e[0].dims[1],i=e[1].dims[1]*t.group;if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let u=e[0].dims.length-2;if(t.dilations.length!==u)throw new Error(`dilations should be ${u}D`);if(t.strides.length!==u)throw new Error(`strides should be ${u}D`);if(t.pads.length!==u*2)throw new Error(`pads should be ${u*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(e[0].type!=="float32"||e[1].type!=="float32")throw new Error("Conv input(X,W) should be float tensor");if(e.length===3&&e[2].type!=="float32")throw new Error("Conv input(bias) should be float tensor")}}),of,sf,af,V_,uf,lf,df,cf,pf,hf,G_,ff,YE=D(()=>{"use strict";ut(),Ke(),Pe(),Vn(),of=(e,t,n,i,u,l)=>(e-1)*t+n+(i-1)*u+1-l,sf=(e,t,n,i,u)=>{let l=Math.floor(e/2);t==="SAME_UPPER"?(n[i]=l,n[u]=e-l):t==="SAME_LOWER"&&(n[i]=e-l,n[u]=l)},af=(e,t,n,i,u,l,d,c)=>{let s=e.length-2,r=c.length===0;for(let o=0;o(ff(t,n),uf(e,t,n)),uf=(e,t,n)=>{let i=hf(n,t);return[pf(e,t,i)]},lf=(e,t)=>({name:"ConvTranspose",inputNames:e?["X","W","B"]:["X","W"],inputTypes:e?[0,0,0]:[0,0],cacheHint:t}),df=(e,t,n,i)=>{let u=t.length>2?"getB(output_channel)":"0.0",l=t[0].dims,d=t[1].dims,c=d[1],s=d[0]/i.group,r=[t[0].dims[0],t[1].dims[1]*i.group,...i.outputShape],o=Ae(e.session.backend.glContext.version),{activationFunction:a,applyActivation:p}=Li(i),h=` const ivec2 strides = ivec2(${i.strides[0]}, ${i.strides[1]}); const ivec2 pads = ivec2(${i.pads[0]}, ${i.pads[1]}); ${a} @@ -719,14 +719,14 @@ float process(int indices[${m}]) { ${p} ${o.output} = vec4(value, .0, .0, .0); } -`;return{...n,output:{dims:r,type:t[0].type,textureType:0},shaderSource:h,hasMain:!0}},sf=(e,t,n)=>{let i=nf(t.length>2,n.cacheKey);return{...i,get:()=>of(e,t,i,n)}},af=(e,t,n)=>e.run(sf(e,t,n),t),uf=(e,t)=>{let n=e.kernelShape.slice();if(e.kernelShape.length===0)for(let c=2;c{let t=e.attributes,n=is(t),i=t.getString("auto_pad","NOTSET"),u=t.getInts("dilations",[1,1]),l=t.getInt("group",1),d=t.getInts("kernel_shape",[]),c=t.getInts("output_padding",[0,0]),s=t.getInts("output_shape",[]),r=t.getInts("pads",[0,0,0,0]),o=t.getInts("strides",[1,1]);return je({autoPad:i,dilations:u,group:l,kernelShape:d,outputPadding:c,outputShape:s,pads:r,strides:o,...n})},lf=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4||e[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");let n=e[0].dims[1],i=e[1].dims[0];if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let u=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==u))throw new Error("invalid bias");let l=e[0].dims.length-2;if(t.dilations.length!==l)throw new Error(`dilations should be ${l}D`);if(t.strides.length!==l)throw new Error(`strides should be ${l}D`);if(t.pads.length!==l*2)throw new Error(`pads should be ${l*2}D`);if(t.outputPadding.length!==l)throw new Error(`output_padding should be ${l}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape");if(e[0].type!=="float32"||e[1].type!=="float32")throw new Error("ConvTranspose input(X,W) should be float tensor");if(e.length===3&&e[2].type!=="float32")throw new Error("ConvTranspose input(bias) should be float tensor")}}),va,Di,L_,df,xa,cf,pf,hf,Jl=D(()=>{"use strict";ut(),Me(),Pe(),va={name:"Transpose",inputNames:["A"],inputTypes:[0]},Di=(e,t,n)=>(hf(t),[e.run({...va,cacheHint:n.cacheKey,get:()=>df(e,t[0],n.perm)},t)]),L_=e=>je({perm:e.attributes.getInts("perm",[])}),df=(e,t,n)=>{let i=t.dims;n=xa(i,n);let u=cf(i,n),l=i.length,d=` - ${pf("perm",n,l)} +`;return{...n,output:{dims:r,type:t[0].type,textureType:0},shaderSource:h,hasMain:!0}},cf=(e,t,n)=>{let i=lf(t.length>2,n.cacheKey);return{...i,get:()=>df(e,t,i,n)}},pf=(e,t,n)=>e.run(cf(e,t,n),t),hf=(e,t)=>{let n=e.kernelShape.slice();if(e.kernelShape.length===0)for(let c=2;c{let t=e.attributes,n=ss(t),i=t.getString("auto_pad","NOTSET"),u=t.getInts("dilations",[1,1]),l=t.getInt("group",1),d=t.getInts("kernel_shape",[]),c=t.getInts("output_padding",[0,0]),s=t.getInts("output_shape",[]),r=t.getInts("pads",[0,0,0,0]),o=t.getInts("strides",[1,1]);return je({autoPad:i,dilations:u,group:l,kernelShape:d,outputPadding:c,outputShape:s,pads:r,strides:o,...n})},ff=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4||e[1].dims.length!==4)throw new Error("currently only support 2-dimensional conv");let n=e[0].dims[1],i=e[1].dims[0];if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let u=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==u))throw new Error("invalid bias");let l=e[0].dims.length-2;if(t.dilations.length!==l)throw new Error(`dilations should be ${l}D`);if(t.strides.length!==l)throw new Error(`strides should be ${l}D`);if(t.pads.length!==l*2)throw new Error(`pads should be ${l*2}D`);if(t.outputPadding.length!==l)throw new Error(`output_padding should be ${l}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape");if(e[0].type!=="float32"||e[1].type!=="float32")throw new Error("ConvTranspose input(X,W) should be float tensor");if(e.length===3&&e[2].type!=="float32")throw new Error("ConvTranspose input(bias) should be float tensor")}}),Ta,Ni,q_,mf,Sa,gf,bf,yf,td=D(()=>{"use strict";ut(),Me(),Pe(),Ta={name:"Transpose",inputNames:["A"],inputTypes:[0]},Ni=(e,t,n)=>(yf(t),[e.run({...Ta,cacheHint:n.cacheKey,get:()=>mf(e,t[0],n.perm)},t)]),q_=e=>je({perm:e.attributes.getInts("perm",[])}),mf=(e,t,n)=>{let i=t.dims;n=Sa(i,n);let u=gf(i,n),l=i.length,d=` + ${bf("perm",n,l)} float process(int indices[${l}]) { int a[${l}]; perm(a, indices); return _A(a); - }`;return{...va,output:{dims:u,type:t.type,textureType:0},shaderSource:d}},xa=(e,t)=>(t&&t.length!==e.length&&(t=[...e.keys()].reverse()),t),cf=(e,t)=>(t=xa(e,t),ye.sortBasedOnPerm(e,t)),pf=(e,t,n)=>{let i=[];i.push(`void ${e}(out int a[${n}], int src[${n}]) {`);for(let u=0;u{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("input should be float tensor")}}),j_,U_,ff,GE=D(()=>{"use strict";Jl(),j_=(e,t,n)=>{ff(t);let i=n.blocksize,u=i*i,l=n.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],d=n.mode==="DCR"?[t[0].dims[0],i,i,t[0].dims[1]/u,t[0].dims[2],t[0].dims[3]]:[t[0].dims[0],t[0].dims[1]/u,i,i,t[0].dims[2],t[0].dims[3]],c=e.reshapeUnpacked(t[0],d),s={perm:l,cacheKey:`${l}`},[r]=Di(e,[c],s),o=[t[0].dims[0],t[0].dims[1]/u,t[0].dims[2]*i,t[0].dims[3]*i];return[e.reshapeUnpacked(r,o)]},U_=e=>{let t=e.attributes.getInt("blocksize");if(t<1)throw new Error(`blocksize must be >= 1, but got : ${t} for DepthToSpace`);let n=e.attributes.getString("mode","DCR");if(n!=="DCR"&&n!=="CRD")throw new Error(`unrecognized mode: ${n} for DepthToSpace`);return{mode:n,blocksize:t}},ff=e=>{if(e.length!==1)throw new Error(`DepthToSpace expect 1 inputs, but got ${e.length}`);if(e[0].type==="string"||e[0].dims.length!==4)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}}),V_,q_,mf,HE=D(()=>{"use strict";Me(),V_=(e,t,n)=>{mf(t,n);let i=ye.flattenShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],i)]},q_=e=>e.attributes.getInt("axis",1),mf=(e,t)=>{if(!e||e.length!==1)throw new Error("Flatten requires 1 input.");let n=e[0].dims.length;if(n===0)throw new Error("scalar tensor is not supported.");if(t<-n||t>n)throw new Error("Invalid axis");if(e[0].type==="string")throw new Error("string tensor is not supported.")}}),Fi,os=D(()=>{"use strict";Fi=["float32","float64","int32","int16","int8","uint16","uint32","uint8"]}),G_,H_,gf,bf,yf,wf,WE=D(()=>{"use strict";ut(),os(),Me(),Pe(),G_=(e,t,n)=>(wf(t,n.axis),[e.run(yf(e,t,n),t)]),H_=e=>je({axis:e.attributes.getInt("axis",0)}),gf={name:"Gather",inputNames:["A","B"],inputTypes:[0,0]},bf=(e,t,n,i)=>{let u=n[0].dims.slice(),l=n[1].dims.slice(),d=new Array(u.length+l.length-1);i=ye.normalizeAxis(i,u.length);let c=[];for(let p=0;p(t&&t.length!==e.length&&(t=[...e.keys()].reverse()),t),gf=(e,t)=>(t=Sa(e,t),ye.sortBasedOnPerm(e,t)),bf=(e,t,n)=>{let i=[];i.push(`void ${e}(out int a[${n}], int src[${n}]) {`);for(let u=0;u{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("input should be float tensor")}}),H_,W_,wf,JE=D(()=>{"use strict";td(),H_=(e,t,n)=>{wf(t);let i=n.blocksize,u=i*i,l=n.mode==="DCR"?[0,3,4,1,5,2]:[0,1,4,2,5,3],d=n.mode==="DCR"?[t[0].dims[0],i,i,t[0].dims[1]/u,t[0].dims[2],t[0].dims[3]]:[t[0].dims[0],t[0].dims[1]/u,i,i,t[0].dims[2],t[0].dims[3]],c=e.reshapeUnpacked(t[0],d),s={perm:l,cacheKey:`${l}`},[r]=Ni(e,[c],s),o=[t[0].dims[0],t[0].dims[1]/u,t[0].dims[2]*i,t[0].dims[3]*i];return[e.reshapeUnpacked(r,o)]},W_=e=>{let t=e.attributes.getInt("blocksize");if(t<1)throw new Error(`blocksize must be >= 1, but got : ${t} for DepthToSpace`);let n=e.attributes.getString("mode","DCR");if(n!=="DCR"&&n!=="CRD")throw new Error(`unrecognized mode: ${n} for DepthToSpace`);return{mode:n,blocksize:t}},wf=e=>{if(e.length!==1)throw new Error(`DepthToSpace expect 1 inputs, but got ${e.length}`);if(e[0].type==="string"||e[0].dims.length!==4)throw new TypeError("DepthToSpace input should be a 4-D numeric tensor")}}),K_,X_,_f,QE=D(()=>{"use strict";Me(),K_=(e,t,n)=>{_f(t,n);let i=ye.flattenShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],i)]},X_=e=>e.attributes.getInt("axis",1),_f=(e,t)=>{if(!e||e.length!==1)throw new Error("Flatten requires 1 input.");let n=e[0].dims.length;if(n===0)throw new Error("scalar tensor is not supported.");if(t<-n||t>n)throw new Error("Invalid axis");if(e[0].type==="string")throw new Error("string tensor is not supported.")}}),ji,as=D(()=>{"use strict";ji=["float32","float64","int32","int16","int8","uint16","uint32","uint8"]}),Z_,Y_,vf,xf,$f,Tf,eA=D(()=>{"use strict";ut(),as(),Me(),Pe(),Z_=(e,t,n)=>(Tf(t,n.axis),[e.run($f(e,t,n),t)]),Y_=e=>je({axis:e.attributes.getInt("axis",0)}),vf={name:"Gather",inputNames:["A","B"],inputTypes:[0,0]},xf=(e,t,n,i)=>{let u=n[0].dims.slice(),l=n[1].dims.slice(),d=new Array(u.length+l.length-1);i=ye.normalizeAxis(i,u.length);let c=[];for(let p=0;p{let i={...gf,cacheHint:n.cacheKey};return{...i,get:()=>bf(e,i,t,n.axis)}},wf=(e,t)=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.");let n=e[0].dims.length;if(n<1)throw new Error("Invalid input shape.");if(t<-n||t>n-1)throw new Error("Invalid axis.");if(Fi.indexOf(e[0].type)===-1)throw new Error("Invaid input type.");if(e[1].type!=="int32"&&e[1].type!=="int16")throw new Error("Invaid input type.")}}),gl,$a,W_,K_,_f,vf,xf,KE=D(()=>{"use strict";ut(),Me(),Pe(),gl=(e,t,n)=>(xf(t,n),[e.run(_f(t,n),t)]),$a=(e,t)=>{let n=e.attributes.getInt("transA",0)!==0,i=e.attributes.getInt("transB",0)!==0,u=e.attributes.getFloat("alpha",1),l=e.attributes.getFloat("beta",1);return je({transA:n,transB:i,alpha:u,beta:l,isOptionalC:t})},W_=e=>$a(e,!1),K_=e=>$a(e,!0),_f=(e,t)=>{let n={name:"Gemm",inputNames:e.length===3?["A","B","C"]:["A","B"],inputTypes:e.length===3?[0,0,0]:[0,0],key:t.cacheKey};return{...n,get:()=>vf(n,e,t)}},vf=(e,t,n)=>{let i=t[0].dims.slice(),u=t[1].dims.slice(),[l,d]=_w.getShapeOfGemmResult(i,n.transA,u,n.transB,t.length===3?t[2].dims:void 0),c=[l,d];if(!c)throw new Error("Can't use gemm on the given tensors");let s=i[i.length-1],r="";n.transA&&(s=i[0]),n.transA&&n.transB?r="value += _A_T(a) * _B_T(b);":n.transA&&!n.transB?r="value += _A_T(a) * _B(b);":!n.transA&&n.transB?r="value += _A(a) * _B_T(b);":!n.transA&&!n.transB&&(r="value += _A(a) * _B(b);");let o=c.length,a=t.length===3?`int c[${t[2].dims.length}];`:"",p=t.length===3?"bcastIndices_C(indices, c);":"",h=t.length===3?"value += beta * _C(c);":"",m=` + }`;return{...t,output:{dims:d,type:n[0].type,textureType:0},shaderSource:a}},$f=(e,t,n)=>{let i={...vf,cacheHint:n.cacheKey};return{...i,get:()=>xf(e,i,t,n.axis)}},Tf=(e,t)=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.");let n=e[0].dims.length;if(n<1)throw new Error("Invalid input shape.");if(t<-n||t>n-1)throw new Error("Invalid axis.");if(ji.indexOf(e[0].type)===-1)throw new Error("Invaid input type.");if(e[1].type!=="int32"&&e[1].type!=="int16")throw new Error("Invaid input type.")}}),wl,Ia,J_,Q_,Sf,If,Of,tA=D(()=>{"use strict";ut(),Me(),Pe(),wl=(e,t,n)=>(Of(t,n),[e.run(Sf(t,n),t)]),Ia=(e,t)=>{let n=e.attributes.getInt("transA",0)!==0,i=e.attributes.getInt("transB",0)!==0,u=e.attributes.getFloat("alpha",1),l=e.attributes.getFloat("beta",1);return je({transA:n,transB:i,alpha:u,beta:l,isOptionalC:t})},J_=e=>Ia(e,!1),Q_=e=>Ia(e,!0),Sf=(e,t)=>{let n={name:"Gemm",inputNames:e.length===3?["A","B","C"]:["A","B"],inputTypes:e.length===3?[0,0,0]:[0,0],key:t.cacheKey};return{...n,get:()=>If(n,e,t)}},If=(e,t,n)=>{let i=t[0].dims.slice(),u=t[1].dims.slice(),[l,d]=Sw.getShapeOfGemmResult(i,n.transA,u,n.transB,t.length===3?t[2].dims:void 0),c=[l,d];if(!c)throw new Error("Can't use gemm on the given tensors");let s=i[i.length-1],r="";n.transA&&(s=i[0]),n.transA&&n.transB?r="value += _A_T(a) * _B_T(b);":n.transA&&!n.transB?r="value += _A_T(a) * _B(b);":!n.transA&&n.transB?r="value += _A(a) * _B_T(b);":!n.transA&&!n.transB&&(r="value += _A(a) * _B(b);");let o=c.length,a=t.length===3?`int c[${t[2].dims.length}];`:"",p=t.length===3?"bcastIndices_C(indices, c);":"",h=t.length===3?"value += beta * _C(c);":"",m=` float process(int indices[${o}]) { int a[${o}]; int b[${o}]; @@ -756,12 +756,12 @@ float process(int indices[${m}]) { value = value * alpha; ${h} return value; - }`;return{...e,output:{dims:c,type:t[0].type,textureType:0},variables:[{name:"alpha",type:"float",data:n.alpha},{name:"beta",type:"float",data:n.beta}],shaderSource:m}},xf=(e,t)=>{if(!e)throw new Error("Input is missing");if(t.isOptionalC&&(e.length<2||e.length>3))throw new Error("Invaid input shape.");if(!t.isOptionalC&&e.length!==3)throw new Error("Gemm requires 3 inputs");if(e.length===3&&e[2].dims.length!==1&&e[2].dims.length!==2)throw new Error("Invalid input shape of C");if(e[0].type!=="float32"&&e[0].type!=="float64"||e[1].type!=="float32"&&e[1].type!=="float64"||e.length===3&&e[2].type!=="float32"&&e[2].type!=="float64")throw new Error("Invalid input type.");if(e[0].type!==e[1].type||e.length===3&&e[0].type!==e[2].type)throw new Error("Input types are mismatched")}}),X_,Z_,$f,Tf,Sf,If,Of,XE=D(()=>{"use strict";ut(),Pe(),X_=(e,t,n)=>(Of(t),[e.run(Sf(e,t,n),t)]),Z_=e=>{let t=e.attributes.getFloat("scale"),n=e.attributes.getFloats("bias");return je({scale:t,bias:n})},$f={name:"ImageScaler",inputNames:["X"],inputTypes:[0]},Tf=(e,t,n,i)=>{let u=n[0].dims.slice(),l=u.length,d=` - ${If(i.bias.length)} + }`;return{...e,output:{dims:c,type:t[0].type,textureType:0},variables:[{name:"alpha",type:"float",data:n.alpha},{name:"beta",type:"float",data:n.beta}],shaderSource:m}},Of=(e,t)=>{if(!e)throw new Error("Input is missing");if(t.isOptionalC&&(e.length<2||e.length>3))throw new Error("Invaid input shape.");if(!t.isOptionalC&&e.length!==3)throw new Error("Gemm requires 3 inputs");if(e.length===3&&e[2].dims.length!==1&&e[2].dims.length!==2)throw new Error("Invalid input shape of C");if(e[0].type!=="float32"&&e[0].type!=="float64"||e[1].type!=="float32"&&e[1].type!=="float64"||e.length===3&&e[2].type!=="float32"&&e[2].type!=="float64")throw new Error("Invalid input type.");if(e[0].type!==e[1].type||e.length===3&&e[0].type!==e[2].type)throw new Error("Input types are mismatched")}}),ev,tv,Ef,Af,kf,Pf,Cf,rA=D(()=>{"use strict";ut(),Pe(),ev=(e,t,n)=>(Cf(t),[e.run(kf(e,t,n),t)]),tv=e=>{let t=e.attributes.getFloat("scale"),n=e.attributes.getFloats("bias");return je({scale:t,bias:n})},Ef={name:"ImageScaler",inputNames:["X"],inputTypes:[0]},Af=(e,t,n,i)=>{let u=n[0].dims.slice(),l=u.length,d=` + ${Pf(i.bias.length)} float process(int indices[${l}]) { return _X(indices) * scale + getBias(bias, indices[1]); - }`;return{...t,output:{dims:u,type:n[0].type,textureType:0},variables:[{name:"bias",type:"float",arrayLength:i.bias.length,data:i.bias},{name:"scale",type:"float",data:i.scale}],shaderSource:d}},Sf=(e,t,n)=>{let i={...$f,cacheHint:n.cacheKey};return{...i,get:()=>Tf(e,i,t,n)}},If=e=>{let t=[`float getBias(float bias[${e}], int channel) {`];for(let n=0;n{if(!e||e.length!==1)throw new Error("ImageScaler requires 1 input.");if(e[0].dims.length!==4)throw new Error("Invalid input shape.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("Invalid input type.")}}),Y_,J_,Ta,Ef,Af,kf,Pf,Cf,Rf,ZE=D(()=>{"use strict";Ke(),Pe(),Y_=(e,t,n)=>{Rf(t);let i=e.run(Af(t[0]),t);return[e.run(Cf(e,t[0],n,i.dims),[t[0],i,t[1],t[2]])]},J_=e=>e.attributes.getFloat("epsilon",1e-5),Ta={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[0]},Ef=(e,t)=>{let n=t.dims.slice(),i=n[1],u=n[2]*n[3],l=[n[0],i],d=` + }`;return{...t,output:{dims:u,type:n[0].type,textureType:0},variables:[{name:"bias",type:"float",arrayLength:i.bias.length,data:i.bias},{name:"scale",type:"float",data:i.scale}],shaderSource:d}},kf=(e,t,n)=>{let i={...Ef,cacheHint:n.cacheKey};return{...i,get:()=>Af(e,i,t,n)}},Pf=e=>{let t=[`float getBias(float bias[${e}], int channel) {`];for(let n=0;n{if(!e||e.length!==1)throw new Error("ImageScaler requires 1 input.");if(e[0].dims.length!==4)throw new Error("Invalid input shape.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("Invalid input type.")}}),rv,nv,Oa,Rf,Df,Mf,Nf,zf,Bf,nA=D(()=>{"use strict";Ke(),Pe(),rv=(e,t,n)=>{Bf(t);let i=e.run(Df(t[0]),t);return[e.run(zf(e,t[0],n,i.dims),[t[0],i,t[1],t[2]])]},nv=e=>e.attributes.getFloat("epsilon",1e-5),Oa={name:"InstanceNormalization_MeanAndVariance",inputNames:["X"],inputTypes:[0]},Rf=(e,t)=>{let n=t.dims.slice(),i=n[1],u=n[2]*n[3],l=[n[0],i],d=` vec4 process(int[2] indices) { vec4 v = vec4(0.0); int a[4]; @@ -790,7 +790,7 @@ float process(int indices[${m}]) { v.g = temp / float(${u}); return v; - }`;return{...e,output:{dims:l,type:t.type,textureType:4},shaderSource:d}},Af=e=>({...Ta,get:()=>Ef(Ta,e)}),kf={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[0,4,0,0]},Pf=(e,t,n,i,u)=>{let l=Ae(e.session.backend.glContext.version),[d,c]=e.calculateTextureWidthAndHeight(u,4),[s,r]=[d/4,c],o=` + }`;return{...e,output:{dims:l,type:t.type,textureType:4},shaderSource:d}},Df=e=>({...Oa,get:()=>Rf(Oa,e)}),Mf={name:"InstanceNormalization_ComputeOutput",inputNames:["X","MeanAndVariance","Scale","B"],inputTypes:[0,4,0,0]},Nf=(e,t,n,i,u)=>{let l=Ae(e.session.backend.glContext.version),[d,c]=e.calculateTextureWidthAndHeight(u,4),[s,r]=[d/4,c],o=` vec4 get_MeanAndVariance(int[2] mv) { int offset = indicesToOffset_MeanAndVariance(mv); vec2 coords = offsetToCoords(offset, ${s}, ${r}); @@ -811,7 +811,7 @@ float process(int indices[${m}]) { float b = _B(sb); return scale * (_X(indices) - mean) / sqrt(variance + epsilon) + b; - }`;return{...t,output:{dims:n.dims,type:n.type,textureType:0},variables:[{name:"epsilon",type:"float",data:i}],shaderSource:o}},Cf=(e,t,n,i)=>{let u={...kf,cacheHint:`${n}`};return{...u,get:()=>Pf(e,u,t,n,i)}},Rf=e=>{if(!e||e.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");let t=e[0],n=e[1],i=e[2];if(t.dims.length<3||n.dims.length!==1||i.dims.length!==1)throw new Error("Invalid input shape.");if(n.dims[0]!==t.dims[1]||i.dims[0]!==t.dims[1])throw new Error("Input shapes are mismatched.");if(t.type!=="float32"&&t.type!=="float64"||n.type!=="float32"&&n.type!=="float64"||i.type!=="float32"&&i.type!=="float64")throw new Error("Invalid input type.");if(e[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}});function YE(e,t){let n=e[0].dims[1],i=e[0].dims.length,u=-Math.floor((t.size-1)/2),l=Math.ceil((t.size-1)/2),d=`float(${t.alpha}) / float(${t.size})`,c=`float(${t.bias})`,s=`float(${t.beta})`,r=` + }`;return{...t,output:{dims:n.dims,type:n.type,textureType:0},variables:[{name:"epsilon",type:"float",data:i}],shaderSource:o}},zf=(e,t,n,i)=>{let u={...Mf,cacheHint:`${n}`};return{...u,get:()=>Nf(e,u,t,n,i)}},Bf=e=>{if(!e||e.length!==3)throw new Error("InstanceNormalization requires 3 inputs.");let t=e[0],n=e[1],i=e[2];if(t.dims.length<3||n.dims.length!==1||i.dims.length!==1)throw new Error("Invalid input shape.");if(n.dims[0]!==t.dims[1]||i.dims[0]!==t.dims[1])throw new Error("Input shapes are mismatched.");if(t.type!=="float32"&&t.type!=="float64"||n.type!=="float32"&&n.type!=="float64"||i.type!=="float32"&&i.type!=="float64")throw new Error("Invalid input type.");if(e[0].dims.length!==4)throw new Error("Only support 4-D input shape.")}});function iA(e,t){let n=e[0].dims[1],i=e[0].dims.length,u=-Math.floor((t.size-1)/2),l=Math.ceil((t.size-1)/2),d=`float(${t.alpha}) / float(${t.size})`,c=`float(${t.bias})`,s=`float(${t.beta})`,r=` float process(int indices[${i}]) { int c = indices[1]; float x = _X(indices); @@ -826,11 +826,11 @@ float process(int indices[${m}]) { } } return x / pow(${c} + ${d} * square_sum, ${s}); - }`;return{...Ql,cacheHint:t.cacheKey,output:{dims:e[0].dims,type:e[0].type,textureType:0},shaderSource:r}}function JE(e,t){return{...Ql,cacheHint:t.cacheKey,get:()=>YE(e,t)}}var Q_,ev,Ql,Df,QE=D(()=>{"use strict";ut(),Pe(),Q_=(e,t,n)=>(Df(t),[e.run(JE(t,n),t)]),ev=e=>{let t=e.attributes.getFloat("alpha",1e-4),n=e.attributes.getFloat("beta",.75),i=e.attributes.getFloat("bias",1),u=e.attributes.getInt("size");return je({alpha:t,beta:n,bias:i,size:u})},Ql={name:"LRN",inputNames:["X"],inputTypes:[0]},Df=e=>{if(!e||e.length!==1)throw new Error("LRN requires 1 input.");if(e[0].dims.length!==4)throw new Error('currently only support LRN for input with "NCHW" format');if(e[0].type!=="float32")throw new Error("input should be float type")}}),Mf,bl,tv,rv,nv,Nf,zf,Bf,Ff,Lf,jf,Uf,Vf,eA=D(()=>{"use strict";ut(),Me(),Ke(),Pe(),Mf={name:"Pad",inputNames:["A"],inputTypes:[0]},bl=(e,t,n)=>(Bf(t),[e.run({...Mf,cacheHint:n.cacheKey,get:()=>zf(e,t[0],n)},t)]),tv=e=>{let t=e.attributes.getString("mode","constant"),n=e.attributes.getFloat("value",0),i=e.attributes.getInts("pads");return je({mode:t,value:n,pads:i})},rv=(e,t,n)=>{Ff(t);let i=Nf(e,t,n);return bl(e,[t[0]],i)},nv=e=>e.attributes.getString("mode","constant"),Nf=(e,t,n)=>{if(!e.session.isInitializer(t[1].dataId)||t.length>=3&&!e.session.isInitializer(t[2].dataId))throw new Error("dynamic pad attributes are not allowed");let i=Array.from(t[1].integerData),u=t.length>=3?t[2].floatData[0]:0;return je({mode:n,pads:i,value:u})},zf=(e,t,n)=>{let i=ye.padShape(t.dims.slice(),n.pads),u=i.length,l=` - ${Lf(e,t,n)} + }`;return{...rd,cacheHint:t.cacheKey,output:{dims:e[0].dims,type:e[0].type,textureType:0},shaderSource:r}}function oA(e,t){return{...rd,cacheHint:t.cacheKey,get:()=>iA(e,t)}}var iv,ov,rd,Ff,sA=D(()=>{"use strict";ut(),Pe(),iv=(e,t,n)=>(Ff(t),[e.run(oA(t,n),t)]),ov=e=>{let t=e.attributes.getFloat("alpha",1e-4),n=e.attributes.getFloat("beta",.75),i=e.attributes.getFloat("bias",1),u=e.attributes.getInt("size");return je({alpha:t,beta:n,bias:i,size:u})},rd={name:"LRN",inputNames:["X"],inputTypes:[0]},Ff=e=>{if(!e||e.length!==1)throw new Error("LRN requires 1 input.");if(e[0].dims.length!==4)throw new Error('currently only support LRN for input with "NCHW" format');if(e[0].type!=="float32")throw new Error("input should be float type")}}),Lf,_l,sv,av,uv,jf,Uf,Vf,Gf,qf,Hf,Wf,Kf,aA=D(()=>{"use strict";ut(),Me(),Ke(),Pe(),Lf={name:"Pad",inputNames:["A"],inputTypes:[0]},_l=(e,t,n)=>(Vf(t),[e.run({...Lf,cacheHint:n.cacheKey,get:()=>Uf(e,t[0],n)},t)]),sv=e=>{let t=e.attributes.getString("mode","constant"),n=e.attributes.getFloat("value",0),i=e.attributes.getInts("pads");return je({mode:t,value:n,pads:i})},av=(e,t,n)=>{Gf(t);let i=jf(e,t,n);return _l(e,[t[0]],i)},uv=e=>e.attributes.getString("mode","constant"),jf=(e,t,n)=>{if(!e.session.isInitializer(t[1].dataId)||t.length>=3&&!e.session.isInitializer(t[2].dataId))throw new Error("dynamic pad attributes are not allowed");let i=Array.from(t[1].integerData),u=t.length>=3?t[2].floatData[0]:0;return je({mode:n,pads:i,value:u})},Uf=(e,t,n)=>{let i=ye.padShape(t.dims.slice(),n.pads),u=i.length,l=` + ${qf(e,t,n)} float process(int[${u}] indices) { return padA(indices); - }`;return{name:"Pad",inputNames:["A"],inputTypes:[0],output:{dims:i,type:t.type,textureType:0},shaderSource:l}},Bf=e=>{if(!e||e.length!==1)throw new Error("Pad requires 1 input");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("Invalid input type.")},Ff=e=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Pad requires 2 or 3 inputs");if(e[1].type!=="int32")throw new Error("Invalid input type.");if(e.length>=3&&e[2].type==="string")throw new Error("Invalid input type.")},Lf=(e,t,n)=>{let i=Ae(e.session.backend.glContext.version),[u,l]=e.calculateTextureWidthAndHeight(t.dims,0),d=ye.computeStrides(t.dims);switch(n.mode){case"constant":return jf(i,t.dims,d,u,l,n.pads,n.value);case"reflect":return Uf(i,t.dims,d,u,l,n.pads);case"edge":return Vf(i,t.dims,d,u,l,n.pads);default:throw new Error("Invalid mode")}},jf=(e,t,n,i,u,l,d)=>{let c=t.length,s="";for(let r=c-1;r>=0;--r)s+=` + }`;return{name:"Pad",inputNames:["A"],inputTypes:[0],output:{dims:i,type:t.type,textureType:0},shaderSource:l}},Vf=e=>{if(!e||e.length!==1)throw new Error("Pad requires 1 input");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("Invalid input type.")},Gf=e=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Pad requires 2 or 3 inputs");if(e[1].type!=="int32")throw new Error("Invalid input type.");if(e.length>=3&&e[2].type==="string")throw new Error("Invalid input type.")},qf=(e,t,n)=>{let i=Ae(e.session.backend.glContext.version),[u,l]=e.calculateTextureWidthAndHeight(t.dims,0),d=ye.computeStrides(t.dims);switch(n.mode){case"constant":return Hf(i,t.dims,d,u,l,n.pads,n.value);case"reflect":return Wf(i,t.dims,d,u,l,n.pads);case"edge":return Kf(i,t.dims,d,u,l,n.pads);default:throw new Error("Invalid mode")}},Hf=(e,t,n,i,u,l,d)=>{let c=t.length,s="";for(let r=c-1;r>=0;--r)s+=` k = m[${r}] - ${l[r]}; if (k < 0) return constant; if (k >= ${t[r]}) return constant; @@ -845,7 +845,7 @@ float process(int indices[${m}]) { float value = getColorAsFloat(${e.texture2D}(A, coords)); return value; } - `},Uf=(e,t,n,i,u,l)=>{let d=t.length,c="";for(let s=d-1;s>=0;--s)c+=` + `},Wf=(e,t,n,i,u,l)=>{let d=t.length,c="";for(let s=d-1;s>=0;--s)c+=` k = m[${s}] - ${l[s]}; if (k < 0) { k = -k; } { @@ -863,7 +863,7 @@ float process(int indices[${m}]) { float value = getColorAsFloat(${e.texture2D}(A, coords)); return value; } - `},Vf=(e,t,n,i,u,l)=>{let d=t.length,c="";for(let s=d-1;s>=0;--s)c+=` + `},Kf=(e,t,n,i,u,l)=>{let d=t.length,c="";for(let s=d-1;s>=0;--s)c+=` k = m[${s}] - ${l[s]}; if (k < 0) k = 0; if (k >= ${t[s]}) k = ${t[s]-1}; @@ -877,13 +877,13 @@ float process(int indices[${m}]) { float value = getColorAsFloat(${e.texture2D}(A, coords)); return value; } - `}}),iv,ov,Sa,sv,av,uv,lv,Ia,Oa,qf,Ea,dv,ai,Aa,ui,Gf,tA=D(()=>{"use strict";ut(),Me(),Pe(),iv=(e,t,n)=>{ai(t);let i={name:"AveragePool",inputNames:["X"],inputTypes:[0],cacheHint:n.cacheKey};return[e.run({...i,get:()=>Sa(t,i,!1,n)},t)]},ov=e=>{let t=e.attributes.getString("auto_pad","NOTSET"),n=e.attributes.getInt("ceil_mode",0),i=e.attributes.getInt("count_include_pad",0)!==0,u=e.attributes.getInts("kernel_shape"),l=e.attributes.getInts("strides",[]),d=e.attributes.getInts("pads",[]);if(n!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return je({autoPad:t,ceilMode:n,countIncludePad:i,kernelShape:u,strides:l,pads:d})},Sa=(e,t,n,i)=>{let[u,l]=Oa(e,i,n),d=ye.size(u.kernelShape),c="value += _X(x);",s="";u.countIncludePad?s+=`value /= float(${d});`:s+=`value /= float(${d} - pad);`;let r=` - ${Aa(e[0].dims,u,c,s,"0.0")} - `;return{...t,output:{dims:l,type:e[0].type,textureType:0},shaderSource:r}},sv=(e,t,n)=>{ai(t);let i={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[0],cacheHint:`${n.countIncludePad}`};return[e.run({...i,get:()=>Sa(t,i,!0,n)},t)]},av=e=>{let t=e.attributes.getInt("count_include_pad",0)!==0;return je({autoPad:"",ceilMode:0,countIncludePad:t,kernelShape:[],strides:[],pads:[]})},uv=(e,t,n)=>{ai(t);let i={name:"MaxPool",inputNames:["X"],inputTypes:[0],cacheHint:n.cacheKey};return[e.run({...i,get:()=>Ia(t,i,!1,n)},t)]},lv=e=>{let t=e.attributes.getString("auto_pad","NOTSET"),n=e.attributes.getInt("ceil_mode",0),i=e.attributes.getInts("kernel_shape"),u=e.attributes.getInts("strides",[]),l=e.attributes.getInts("pads",[]),d=e.attributes.getInt("storage_order",0),c=e.attributes.getInts("dilations",[]);if(d!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return je({autoPad:t,ceilMode:n,countIncludePad:!1,kernelShape:i,strides:u,pads:l,storageOrder:d,dilations:c})},Ia=(e,t,n,i)=>{let[u,l]=Oa(e,i,n),d=` - ${Aa(e[0].dims,u,` + `}}),lv,dv,Ea,cv,pv,hv,fv,Aa,ka,Xf,Pa,mv,li,Ca,di,Zf,uA=D(()=>{"use strict";ut(),Me(),Pe(),lv=(e,t,n)=>{li(t);let i={name:"AveragePool",inputNames:["X"],inputTypes:[0],cacheHint:n.cacheKey};return[e.run({...i,get:()=>Ea(t,i,!1,n)},t)]},dv=e=>{let t=e.attributes.getString("auto_pad","NOTSET"),n=e.attributes.getInt("ceil_mode",0),i=e.attributes.getInt("count_include_pad",0)!==0,u=e.attributes.getInts("kernel_shape"),l=e.attributes.getInts("strides",[]),d=e.attributes.getInts("pads",[]);if(n!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");return je({autoPad:t,ceilMode:n,countIncludePad:i,kernelShape:u,strides:l,pads:d})},Ea=(e,t,n,i)=>{let[u,l]=ka(e,i,n),d=ye.size(u.kernelShape),c="value += _X(x);",s="";u.countIncludePad?s+=`value /= float(${d});`:s+=`value /= float(${d} - pad);`;let r=` + ${Ca(e[0].dims,u,c,s,"0.0")} + `;return{...t,output:{dims:l,type:e[0].type,textureType:0},shaderSource:r}},cv=(e,t,n)=>{li(t);let i={name:"GlobalAveragePool",inputNames:["X"],inputTypes:[0],cacheHint:`${n.countIncludePad}`};return[e.run({...i,get:()=>Ea(t,i,!0,n)},t)]},pv=e=>{let t=e.attributes.getInt("count_include_pad",0)!==0;return je({autoPad:"",ceilMode:0,countIncludePad:t,kernelShape:[],strides:[],pads:[]})},hv=(e,t,n)=>{li(t);let i={name:"MaxPool",inputNames:["X"],inputTypes:[0],cacheHint:n.cacheKey};return[e.run({...i,get:()=>Aa(t,i,!1,n)},t)]},fv=e=>{let t=e.attributes.getString("auto_pad","NOTSET"),n=e.attributes.getInt("ceil_mode",0),i=e.attributes.getInts("kernel_shape"),u=e.attributes.getInts("strides",[]),l=e.attributes.getInts("pads",[]),d=e.attributes.getInt("storage_order",0),c=e.attributes.getInts("dilations",[]);if(d!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(n!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");return je({autoPad:t,ceilMode:n,countIncludePad:!1,kernelShape:i,strides:u,pads:l,storageOrder:d,dilations:c})},Aa=(e,t,n,i)=>{let[u,l]=ka(e,i,n),d=` + ${Ca(e[0].dims,u,` value = max(_X(x), value); `,"","-1e5")} - `;return{...t,output:{dims:l,type:e[0].type,textureType:0},shaderSource:d}},Oa=(e,t,n)=>{let i=e[0].dims.slice(),u=Object.hasOwnProperty.call(t,"dilations"),l=t.kernelShape.slice(),d=t.strides.slice(),c=u?t.dilations.slice():[],s=t.pads.slice();Uo.adjustPoolAttributes(n,i,l,d,c,s);let r=Uo.computePoolOutputShape(n,i,d,c,l,s,t.autoPad),o=Object.assign({},t);return u?Object.assign(o,{kernelShape:l,strides:d,pads:s,dilations:c,cacheKey:t.cacheKey}):Object.assign(o,{kernelShape:l,strides:d,pads:s,cacheKey:t.cacheKey}),[o,r]},qf={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},Ea={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[0]},dv=(e,t)=>(ai(t),[e.run({...Ea,get:()=>Ia(t,Ea,!0,qf)},t)]),ai=e=>{if(!e||e.length!==1)throw new Error("Pool ops requires 1 input.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("Invalid input type.")},Aa=(e,t,n,i,u)=>{let l=e.length;if(t.kernelShape.length<=2){let d=t.kernelShape[t.kernelShape.length-1],c=t.strides[t.strides.length-1],s=t.pads[t.pads.length/2-1],r=t.pads[t.pads.length-1],o=e[l-1],a="",p="",h="";if(s+r!==0?a=` + `;return{...t,output:{dims:l,type:e[0].type,textureType:0},shaderSource:d}},ka=(e,t,n)=>{let i=e[0].dims.slice(),u=Object.hasOwnProperty.call(t,"dilations"),l=t.kernelShape.slice(),d=t.strides.slice(),c=u?t.dilations.slice():[],s=t.pads.slice();Go.adjustPoolAttributes(n,i,l,d,c,s);let r=Go.computePoolOutputShape(n,i,d,c,l,s,t.autoPad),o=Object.assign({},t);return u?Object.assign(o,{kernelShape:l,strides:d,pads:s,dilations:c,cacheKey:t.cacheKey}):Object.assign(o,{kernelShape:l,strides:d,pads:s,cacheKey:t.cacheKey}),[o,r]},Xf={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[],cacheKey:""},Pa={name:"GlobalMaxPool",inputNames:["X"],inputTypes:[0]},mv=(e,t)=>(li(t),[e.run({...Pa,get:()=>Aa(t,Pa,!0,Xf)},t)]),li=e=>{if(!e||e.length!==1)throw new Error("Pool ops requires 1 input.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("Invalid input type.")},Ca=(e,t,n,i,u)=>{let l=e.length;if(t.kernelShape.length<=2){let d=t.kernelShape[t.kernelShape.length-1],c=t.strides[t.strides.length-1],s=t.pads[t.pads.length/2-1],r=t.pads[t.pads.length-1],o=e[l-1],a="",p="",h="";if(s+r!==0?a=` for (int i = 0; i < ${d}; i++) { x[${l} - 1] = indices[${l} - 1] * ${c} - ${s} + i; if (x[${l} - 1] < 0 || x[${l} - 1] >= ${o}) { @@ -920,7 +920,7 @@ float process(int indices[${m}]) { ${i} return value; } - `}else{let d=ye.size(t.kernelShape),c=ye.computeStrides(t.kernelShape),s=c.length,r=t.pads.length,o=Gf(s),a=ui(e,"inputDims"),p=ui(t.pads,"pads"),h=ui(c,"kernelStrides"),m=ui(t.strides,"strides"),g=t.pads.reduce((w,y)=>w+y),_="";return g?_=` + `}else{let d=ye.size(t.kernelShape),c=ye.computeStrides(t.kernelShape),s=c.length,r=t.pads.length,o=Zf(s),a=di(e,"inputDims"),p=di(t.pads,"pads"),h=di(c,"kernelStrides"),m=di(t.strides,"strides"),g=t.pads.reduce((w,y)=>w+y),_="";return g?_=` if (x[j] >= inputDims[j] || x[j] < 0) { pad++; isPad = true; @@ -962,9 +962,9 @@ float process(int indices[${m}]) { return value; } - `}},ui=(e,t)=>{let n="";for(let i=0;i{let n="";for(let i=0;i` + `;return n},Zf=e=>` void offsetToIndices(int offset, int[${e}] strides, out int[${e}] indices) { if (${e} == 0) { return; @@ -974,7 +974,7 @@ float process(int indices[${m}]) { offset -= indices[i] * strides[i]; } indices[${e} - 1] = offset; - }`}),yr,Or,Hf,Wf,cv,pv,hv,fv,mv,gv,bv,rA=D(()=>{"use strict";ut(),os(),Me(),Pe(),yr=(e,t,n,i,u)=>{Wf(t);let l={name:i,inputNames:["A"],inputTypes:[0]};return[e.run({...l,cacheHint:n.cacheKey,get:()=>Hf(e,t,n,i,u,l)},t)]},Or=e=>{let t=e.attributes.getInts("axes",[]),n=e.attributes.getInt("keepdims",1)===1;return je({axes:t,keepDims:n})},Hf=(e,t,n,i,u,l)=>{let d=[],c=t[0].dims.length||1,s=[],r=ye.normalizeAxes(n.axes,t[0].dims.length),o=u(t,r),a=o[1];for(let h=0;h=0||r.length===0?(n.keepDims&&d.push(1),a=` + }`}),yr,Or,Yf,Jf,gv,bv,yv,wv,_v,vv,xv,lA=D(()=>{"use strict";ut(),as(),Me(),Pe(),yr=(e,t,n,i,u)=>{Jf(t);let l={name:i,inputNames:["A"],inputTypes:[0]};return[e.run({...l,cacheHint:n.cacheKey,get:()=>Yf(e,t,n,i,u,l)},t)]},Or=e=>{let t=e.attributes.getInts("axes",[]),n=e.attributes.getInt("keepdims",1)===1;return je({axes:t,keepDims:n})},Yf=(e,t,n,i,u,l)=>{let d=[],c=t[0].dims.length||1,s=[],r=ye.normalizeAxes(n.axes,t[0].dims.length),o=u(t,r),a=o[1];for(let h=0;h=0||r.length===0?(n.keepDims&&d.push(1),a=` for(int j${h} = 0; j${h} < ${t[0].dims[h]}; j${h}++) { inputIdx[${h}] = j${h}; ${a} @@ -988,11 +988,11 @@ float process(int indices[${m}]) { ${a} ${o[2]} // final computation for reduce mean return value; - }`;return{...l,output:{dims:d,type:t[0].type,textureType:0},shaderSource:p}},Wf=e=>{if(!e||e.length!==1)throw new Error("Reduce op requires 1 input.");if(Fi.indexOf(e[0].type)===-1)throw new Error("Invalid input type.")},cv=(e,t,n)=>yr(e,t,n,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),pv=(e,t,n)=>yr(e,t,n,"ReduceMean",(i,u)=>{let l=1;for(let d=0;d=0||u.length===0)&&(l*=i[0].dims[d]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${l}.;`]}),hv=(e,t,n)=>yr(e,t,n,"ReduceMax",(i,u)=>{let l=[];for(let d=0;d=0||u.length===0)&&l.push(`inputIdx[${d}] = 0;`);return[`${l.join(` + }`;return{...l,output:{dims:d,type:t[0].type,textureType:0},shaderSource:p}},Jf=e=>{if(!e||e.length!==1)throw new Error("Reduce op requires 1 input.");if(ji.indexOf(e[0].type)===-1)throw new Error("Invalid input type.")},gv=(e,t,n)=>yr(e,t,n,"ReduceSum",()=>["value = 0.0;","value += _A(inputIdx);",""]),bv=(e,t,n)=>yr(e,t,n,"ReduceMean",(i,u)=>{let l=1;for(let d=0;d=0||u.length===0)&&(l*=i[0].dims[d]);return["value = 0.0;","value += _A(inputIdx);",`value /= ${l}.;`]}),yv=(e,t,n)=>yr(e,t,n,"ReduceMax",(i,u)=>{let l=[];for(let d=0;d=0||u.length===0)&&l.push(`inputIdx[${d}] = 0;`);return[`${l.join(` `)} -value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),fv=(e,t,n)=>yr(e,t,n,"ReduceMin",(i,u)=>{let l=[];for(let d=0;d=0||u.length===0)&&l.push(`inputIdx[${d}] = 0;`);return[`${l.join(` +value = _A(inputIdx);`,"value = max(value, _A(inputIdx));",""]}),wv=(e,t,n)=>yr(e,t,n,"ReduceMin",(i,u)=>{let l=[];for(let d=0;d=0||u.length===0)&&l.push(`inputIdx[${d}] = 0;`);return[`${l.join(` `)} -value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr(e,t,n,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),gv=(e,t,n)=>yr(e,t,n,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),bv=(e,t,n)=>yr(e,t,n,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])}),yv,nA=D(()=>{"use strict";Me(),yv=(e,t)=>{let n=ye.calculateReshapedDims(t[0].dims,t[1].integerData);return e.session.pack?[e.reshapePacked(t[0],n)]:[e.reshapeUnpacked(t[0],n)]}}),ka,yl,wv,_v,ki,Kf,wl,qo,vv=D(()=>{"use strict";ut(),Ke(),Pe(),ka={name:"Upsample",inputNames:["X"],inputTypes:[0]},yl=(e,t,n)=>(wl(t,n),[e.run({...ka,cacheHint:n.cacheKey,get:()=>Kf(e,t,n)},t)]),wv=e=>ki(e,7),_v=e=>ki(e,9),ki=(e,t)=>{let n=t>=10,i=e.attributes.getString("mode","nearest");if(i!=="nearest"&&i!=="linear"&&(t<11||i!=="cubic"))throw new Error(`unrecognized mode: ${i}`);let u=[];t<9&&(u=e.attributes.getFloats("scales"),qo(u,i,n));let l=e.attributes.getFloat("extrapolation_value",0),d=t>10?e.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(d)===-1)throw new Error(`coordinate_transform_mode '${d}' is not supported`);let c=d==="tf_crop_and_resize",s=c,r=i==="nearest"&&t>=11?e.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(r)===-1)throw new Error(`nearest_mode '${r}' is not supported`);let o=e.attributes.getFloat("cubic_coeff_a",-.75),a=e.attributes.getInt("exclude_outside",0)!==0;if(a&&i!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");let p=t<11?!0:i==="nearest"&&d==="asymmetric"&&r==="floor",h=0,m=0,g=0;return t>10?e.inputs.length>2?(h=1,m=2,g=3):(m=1,g=2):t===9&&(m=1),je({opset:t,isResize:n,mode:i,scales:u,extrapolationValue:l,coordinateTransformMode:d,useExtrapolation:s,needRoiInput:c,nearestMode:r,cubicCoefficientA:o,excludeOutside:a,useNearest2xOptimization:p,roiInputIdx:h,scalesInputIdx:m,sizesInputIdx:g})},Kf=(e,t,n)=>{let i=Ae(e.session.backend.glContext.version),[u,l]=e.calculateTextureWidthAndHeight(t[0].dims,0),d=t[0].dims.map((g,_)=>Math.floor(g*n.scales[_])),[c,s]=e.calculateTextureWidthAndHeight(d,0),r=d.length,o=new Array(r),a=new Array(r),p=` +value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),_v=(e,t,n)=>yr(e,t,n,"ReduceProd",()=>["value = 1.0;","value *= _A(inputIdx);",""]),vv=(e,t,n)=>yr(e,t,n,"ReduceLogSum",()=>["value = 0.0;","value += _A(inputIdx);","value = log(value);"]),xv=(e,t,n)=>yr(e,t,n,"ReduceLogSumSquare",()=>["float t; value = 0.0;","t = _A(inputIdx); value += t * t;",""])}),$v,dA=D(()=>{"use strict";Me(),$v=(e,t)=>{let n=ye.calculateReshapedDims(t[0].dims,t[1].integerData);return e.session.pack?[e.reshapePacked(t[0],n)]:[e.reshapeUnpacked(t[0],n)]}}),Ra,vl,Tv,Sv,Ci,Qf,xl,Ho,Iv=D(()=>{"use strict";ut(),Ke(),Pe(),Ra={name:"Upsample",inputNames:["X"],inputTypes:[0]},vl=(e,t,n)=>(xl(t,n),[e.run({...Ra,cacheHint:n.cacheKey,get:()=>Qf(e,t,n)},t)]),Tv=e=>Ci(e,7),Sv=e=>Ci(e,9),Ci=(e,t)=>{let n=t>=10,i=e.attributes.getString("mode","nearest");if(i!=="nearest"&&i!=="linear"&&(t<11||i!=="cubic"))throw new Error(`unrecognized mode: ${i}`);let u=[];t<9&&(u=e.attributes.getFloats("scales"),Ho(u,i,n));let l=e.attributes.getFloat("extrapolation_value",0),d=t>10?e.attributes.getString("coordinate_transformation_mode","half_pixel"):"asymmetric";if(["asymmetric","pytorch_half_pixel","tf_half_pixel_for_nn","align_corners","tf_crop_and_resize","half_pixel"].indexOf(d)===-1)throw new Error(`coordinate_transform_mode '${d}' is not supported`);let c=d==="tf_crop_and_resize",s=c,r=i==="nearest"&&t>=11?e.attributes.getString("nearest_mode","round_prefer_floor"):"";if(["round_prefer_floor","round_prefer_ceil","floor","ceil",""].indexOf(r)===-1)throw new Error(`nearest_mode '${r}' is not supported`);let o=e.attributes.getFloat("cubic_coeff_a",-.75),a=e.attributes.getInt("exclude_outside",0)!==0;if(a&&i!=="cubic")throw new Error("exclude_outside can be set to 1 only when mode is CUBIC.");let p=t<11?!0:i==="nearest"&&d==="asymmetric"&&r==="floor",h=0,m=0,g=0;return t>10?e.inputs.length>2?(h=1,m=2,g=3):(m=1,g=2):t===9&&(m=1),je({opset:t,isResize:n,mode:i,scales:u,extrapolationValue:l,coordinateTransformMode:d,useExtrapolation:s,needRoiInput:c,nearestMode:r,cubicCoefficientA:o,excludeOutside:a,useNearest2xOptimization:p,roiInputIdx:h,scalesInputIdx:m,sizesInputIdx:g})},Qf=(e,t,n)=>{let i=Ae(e.session.backend.glContext.version),[u,l]=e.calculateTextureWidthAndHeight(t[0].dims,0),d=t[0].dims.map((g,_)=>Math.floor(g*n.scales[_])),[c,s]=e.calculateTextureWidthAndHeight(d,0),r=d.length,o=new Array(r),a=new Array(r),p=` int output_pitches[${r}]; int input_pitches[${r}]; `;for(let g=r-1;g>=0;g--)o[g]=g===r-1?1:o[g+1]*d[g+1],a[g]=g===r-1?1:a[g+1]*t[0].dims[g+1],p+=` @@ -1128,7 +1128,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]); float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]); return y0 + float(x_offset) * (y1 - y0) / float(scales[1]); - }`;return{...ka,output:{dims:d,type:t[0].type,textureType:0},shaderSource:m,variables:[{name:"scales",type:"int",arrayLength:n.scales.length,data:n.scales.map(g=>Math.ceil(g))}]}},wl=(e,t)=>{if(!e||t.opset<9&&e.length!==1||t.opset>=9&&t.opset<11&&e.length!==2||t.opset>=11&&e.length<2)throw new Error("invalid inputs.");if(t.scales.length>0&&e[0].dims.length!==t.scales.length)throw new Error("Invalid input shape.");if(e[0].type==="string")throw new Error("Invalid input tensor types.")},qo=(e,t,n)=>{if(n){for(let i of e)if(i<=0)throw new Error("Scale value should be greater than 0.")}else for(let i of e)if(i<1)throw new Error("Scale value should be greater than or equal to 1.");if((t==="linear"||t==="cubic")&&e.length!==2&&(e.length!==4||e[0]!==1||e[1]!==1))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n?"Resize":"Upsample"} opeartor.`)}}),vo,_l,xv,$v,Xf,Zf,Yf,Jf,iA=D(()=>{"use strict";Ke(),Pe(),ar(),jn(),vv(),vo={name:"Resize",inputNames:["A"],inputTypes:[2]},_l=(e,t,n)=>(wl(t,n),[e.run({...vo,cacheHint:n.cacheKey,get:()=>Xf(e,t,n)},t)]),xv=e=>ki(e,10),$v=e=>ki(e,11),Xf=(e,t,n)=>{let i=Ae(e.session.backend.glContext.version),[u,l]=Zf(t,n);if(u.every(y=>y===1)&&n.coordinateTransformMode!=="tf_crop_and_resize")return{...vo,output:{dims:l,type:t[0].type,textureType:2},hasMain:!0,shaderSource:`void main() { + }`;return{...Ra,output:{dims:d,type:t[0].type,textureType:0},shaderSource:m,variables:[{name:"scales",type:"int",arrayLength:n.scales.length,data:n.scales.map(g=>Math.ceil(g))}]}},xl=(e,t)=>{if(!e||t.opset<9&&e.length!==1||t.opset>=9&&t.opset<11&&e.length!==2||t.opset>=11&&e.length<2)throw new Error("invalid inputs.");if(t.scales.length>0&&e[0].dims.length!==t.scales.length)throw new Error("Invalid input shape.");if(e[0].type==="string")throw new Error("Invalid input tensor types.")},Ho=(e,t,n)=>{if(n){for(let i of e)if(i<=0)throw new Error("Scale value should be greater than 0.")}else for(let i of e)if(i<1)throw new Error("Scale value should be greater than or equal to 1.");if((t==="linear"||t==="cubic")&&e.length!==2&&(e.length!==4||e[0]!==1||e[1]!==1))throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') or 4-D inputs with the corresponding outermost 2 scale values being 1 in the ${n?"Resize":"Upsample"} opeartor.`)}}),$o,$l,Ov,Ev,em,tm,rm,nm,cA=D(()=>{"use strict";Ke(),Pe(),ar(),jn(),Iv(),$o={name:"Resize",inputNames:["A"],inputTypes:[2]},$l=(e,t,n)=>(xl(t,n),[e.run({...$o,cacheHint:n.cacheKey,get:()=>em(e,t,n)},t)]),Ov=e=>Ci(e,10),Ev=e=>Ci(e,11),em=(e,t,n)=>{let i=Ae(e.session.backend.glContext.version),[u,l]=tm(t,n);if(u.every(y=>y===1)&&n.coordinateTransformMode!=="tf_crop_and_resize")return{...$o,output:{dims:l,type:t[0].type,textureType:2},hasMain:!0,shaderSource:`void main() { vec4 v = ${i.texture2D}(X, TexCoords); ${i.output} = v; }`};let d=l.length;if(d<2)throw new Error(`output dimension should be at least 2, but got ${d}`);let c=l[d-2],s=l[d-1],r=t[0].dims;if(d!==r.length)throw new Error(`output dimension should match input ${r.length}, but got ${d}`);let o=r[d-2],a=r[d-1],p=u[d-2],h=u[d-1],m="";if(n.mode!=="linear")throw new Error(`resize (packed) does not support mode: '${n.mode}'`);switch(n.coordinateTransformMode){case"asymmetric":m=` @@ -1158,7 +1158,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( vec4 new_scale = original / resized; return vec4(coords) * new_scale; } - `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${n.coordinateTransformMode}'`)}let g=Ar(d),_=zi(),w=` + `;break;default:throw new Error(`resize (packed) does not support coordinateTransformMode: '${n.coordinateTransformMode}'`)}let g=Ar(d),_=Fi(),w=` const vec2 inputWH = vec2(${o}.0, ${a}.0); const vec4 scaleWHWH = vec4(float(${p}), float(${h}), float(${p}), float(${h})); ${_} @@ -1225,12 +1225,12 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( ${i.output} = vec4(newValue); } - `;return{...vo,output:{dims:l,type:t[0].type,textureType:2},hasMain:!0,shaderSource:w}},Zf=(e,t)=>{let n=e[0].dims,i=t.scales,u;if(i.length===0){let d=e[t.scalesInputIdx];if(d&&d.size!==0){if(e[t.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");i=Yf(d,t.mode,t.isResize)}else{let c=e[t.sizesInputIdx];if(!c||c.size===0)throw new Error("Either scales or sizes MUST be provided as input.");u=Array.from(c.integerData),i=Jf(u,n,t.mode,t.isResize)}}else if(e[t.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");let l=u||n.map((d,c)=>Math.floor(d*i[c]));return[i,l]},Yf=(e,t,n)=>{let i=Array.from(e.floatData);return qo(i,t,n),i},Jf=(e,t,n,i)=>{let u=t.length,l=new Array(u);for(let d=0,c=u;d{"use strict";Ln(),Tv=(e,t)=>(Qf(t),[new xt([t[0].dims.length],"int32",void 0,void 0,new Int32Array(t[0].dims))]),Qf=e=>{if(!e||e.length!==1)throw new Error("Shape requires 1 input.")}}),xo,Sv,Iv,Pa,em,Ov,tm,rm,sA=D(()=>{"use strict";ut(),os(),Me(),Pe(),xo={name:"Slice",inputNames:["A"],inputTypes:[0]},Sv=(e,t,n)=>(em(t),[e.run({...xo,cacheHint:n.cacheKey,get:()=>Pa(e,t[0],n)},t)]),Iv=e=>{let t=e.attributes.getInts("starts"),n=e.attributes.getInts("ends"),i=e.attributes.getInts("axes",[]);return je({starts:t,ends:n,axes:i})},Pa=(e,t,n)=>{let i=n.axes.length===0?t.dims.slice(0).map((o,a)=>a):n.axes,u=ye.normalizeAxes(i,t.dims.length),l=n.starts.map((o,a)=>o>t.dims[u[a]]-1?t.dims[u[a]]:ye.normalizeAxis(o,t.dims[u[a]])),d=n.ends.map((o,a)=>o>t.dims[u[a]]-1?t.dims[u[a]]:ye.normalizeAxis(o,t.dims[u[a]])),c=t.dims.slice(),s=[];for(let o=0;o0&&s.push(`outputIdx[${u[o]}] += ${l[o]};`);let r=` + `;return{...$o,output:{dims:l,type:t[0].type,textureType:2},hasMain:!0,shaderSource:w}},tm=(e,t)=>{let n=e[0].dims,i=t.scales,u;if(i.length===0){let d=e[t.scalesInputIdx];if(d&&d.size!==0){if(e[t.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");i=rm(d,t.mode,t.isResize)}else{let c=e[t.sizesInputIdx];if(!c||c.size===0)throw new Error("Either scales or sizes MUST be provided as input.");u=Array.from(c.integerData),i=nm(u,n,t.mode,t.isResize)}}else if(e[t.sizesInputIdx])throw new Error("Only one of scales or sizes must be provided as input.");let l=u||n.map((d,c)=>Math.floor(d*i[c]));return[i,l]},rm=(e,t,n)=>{let i=Array.from(e.floatData);return Ho(i,t,n),i},nm=(e,t,n,i)=>{let u=t.length,l=new Array(u);for(let d=0,c=u;d{"use strict";Ln(),Av=(e,t)=>(im(t),[new xt([t[0].dims.length],"int32",void 0,void 0,new Int32Array(t[0].dims))]),im=e=>{if(!e||e.length!==1)throw new Error("Shape requires 1 input.")}}),To,kv,Pv,Da,om,Cv,sm,am,hA=D(()=>{"use strict";ut(),as(),Me(),Pe(),To={name:"Slice",inputNames:["A"],inputTypes:[0]},kv=(e,t,n)=>(om(t),[e.run({...To,cacheHint:n.cacheKey,get:()=>Da(e,t[0],n)},t)]),Pv=e=>{let t=e.attributes.getInts("starts"),n=e.attributes.getInts("ends"),i=e.attributes.getInts("axes",[]);return je({starts:t,ends:n,axes:i})},Da=(e,t,n)=>{let i=n.axes.length===0?t.dims.slice(0).map((o,a)=>a):n.axes,u=ye.normalizeAxes(i,t.dims.length),l=n.starts.map((o,a)=>o>t.dims[u[a]]-1?t.dims[u[a]]:ye.normalizeAxis(o,t.dims[u[a]])),d=n.ends.map((o,a)=>o>t.dims[u[a]]-1?t.dims[u[a]]:ye.normalizeAxis(o,t.dims[u[a]])),c=t.dims.slice(),s=[];for(let o=0;o0&&s.push(`outputIdx[${u[o]}] += ${l[o]};`);let r=` float process(int outputIdx[${c.length}]) { ${s.join(` `)} return _A(outputIdx); - }`;return{...xo,output:{dims:c,type:t.type,textureType:0},shaderSource:r}},em=e=>{if(!e||e.length!==1)throw new Error("Slice requires 1 input.");if(Fi.indexOf(e[0].type)===-1)throw new Error("Invalid input type.")},Ov=(e,t)=>{rm(t);let n=tm(e,t);return[e.run({...xo,cacheHint:n.cacheKey,get:()=>Pa(e,t[0],n)},[t[0]])]},tm=(e,t)=>{if(!e.session.isInitializer(t[1].dataId)||!e.session.isInitializer(t[2].dataId)||t.length>=4&&!e.session.isInitializer(t[3].dataId)||t.length>=5&&!e.session.isInitializer(t[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(t.length>=5&&t[4].integerData.some(d=>d!==1))throw new Error("currently non-1 steps is not supported for Slice");let n=Array.from(t[1].integerData),i=Array.from(t[2].integerData),u=t.length>=4?Array.from(t[3].integerData):[],l=`${u};${n};${i}`;return{starts:n,ends:i,axes:u,cacheKey:l}},rm=e=>{if(!e||e.length<3||e.length>5)throw new Error("Invalid input number.");if(e[1].type!=="int32"||e[1].dims.length!==1)throw new Error("Invalid input type.");if(e[2].type!=="int32"||e[2].dims.length!==1)throw new Error("Invalid input type.");if(e.length>=4&&(e[3].type!=="int32"||e[3].dims.length!==1))throw new Error("Invalid input type.");if(e.length>=5&&(e[4].type!=="int32"||e[4].dims.length!==1))throw new Error("Invalid input type.")}}),Ca,Ra,Da,Ev,Av,kv,Pv,Ma,nm,im,om,Na,aA=D(()=>{"use strict";ut(),Me(),Ke(),Pe(),Jl(),Ca={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[0]},Ra={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[0,0]},Da={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[0,0,0]},Ev=(e,t,n)=>{Na(t);let i=t[0].dims.slice(),u=ye.normalizeAxis(n.axis,i.length),l=ye.sizeToDimension(i,u),d=ye.sizeFromDimension(i,u);return Ma(e,t,n,l,d)},Av=e=>je({axis:e.attributes.getInt("axis",1)}),kv=e=>je({axis:e.attributes.getInt("axis",-1)}),Pv=(e,t,n)=>{Na(t);let i=t[0].dims.slice(),u=ye.normalizeAxis(n.axis,i.length),l=i.length,d=u!==l-1,c=[],s=[],r=[],o;d&&(s=Array.from({length:l}).map((m,g)=>g),s[u]=l-1,s[l-1]=u,s.map(m=>c.push(i[m])),o=je({perm:s}),r=Di(e,t,o));let a=d?ye.sizeToDimension(c,l-1):ye.sizeToDimension(i,l-1),p=d?ye.sizeFromDimension(c,l-1):ye.sizeFromDimension(i,l-1),h=Ma(e,d?r:t,n,a,p);return d?Di(e,h,o):h},Ma=(e,t,n,i,u)=>{let l=nm(e,t[0],i,u,[i]),d=e.run({...Ca,cacheHint:n.cacheKey,get:()=>l},t),c=im(e,t[0],i,u,l.output.dims,[i]),s=e.run({...Ra,cacheHint:n.cacheKey,get:()=>c},[t[0],d]),r=om(e,t[0],i,u,l.output.dims,c.output.dims);return[e.run({...Da,cacheHint:n.cacheKey,get:()=>r},[t[0],d,s])]},nm=(e,t,n,i,u)=>{let[l,d]=e.calculateTextureWidthAndHeight(t.dims,0),c=u.length;if(n<1||i<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(u.length!==1)throw new Error("Dimensionality of the output should be 1");if(u[0]!==n)throw new Error("Shape of the output should be equal to logical row count");let s=Ae(e.session.backend.glContext.version),r=` + }`;return{...To,output:{dims:c,type:t.type,textureType:0},shaderSource:r}},om=e=>{if(!e||e.length!==1)throw new Error("Slice requires 1 input.");if(ji.indexOf(e[0].type)===-1)throw new Error("Invalid input type.")},Cv=(e,t)=>{am(t);let n=sm(e,t);return[e.run({...To,cacheHint:n.cacheKey,get:()=>Da(e,t[0],n)},[t[0]])]},sm=(e,t)=>{if(!e.session.isInitializer(t[1].dataId)||!e.session.isInitializer(t[2].dataId)||t.length>=4&&!e.session.isInitializer(t[3].dataId)||t.length>=5&&!e.session.isInitializer(t[4].dataId))throw new Error("dynamic slice attributes are not allowed");if(t.length>=5&&t[4].integerData.some(d=>d!==1))throw new Error("currently non-1 steps is not supported for Slice");let n=Array.from(t[1].integerData),i=Array.from(t[2].integerData),u=t.length>=4?Array.from(t[3].integerData):[],l=`${u};${n};${i}`;return{starts:n,ends:i,axes:u,cacheKey:l}},am=e=>{if(!e||e.length<3||e.length>5)throw new Error("Invalid input number.");if(e[1].type!=="int32"||e[1].dims.length!==1)throw new Error("Invalid input type.");if(e[2].type!=="int32"||e[2].dims.length!==1)throw new Error("Invalid input type.");if(e.length>=4&&(e[3].type!=="int32"||e[3].dims.length!==1))throw new Error("Invalid input type.");if(e.length>=5&&(e[4].type!=="int32"||e[4].dims.length!==1))throw new Error("Invalid input type.")}}),Ma,Na,za,Rv,Dv,Mv,Nv,Ba,um,lm,dm,Fa,fA=D(()=>{"use strict";ut(),Me(),Ke(),Pe(),td(),Ma={name:"SoftmaxComputeMax",inputNames:["A"],inputTypes:[0]},Na={name:"SoftmaxComputeScale",inputNames:["A","Max"],inputTypes:[0,0]},za={name:"SoftMax",inputNames:["A","Max","Norm"],inputTypes:[0,0,0]},Rv=(e,t,n)=>{Fa(t);let i=t[0].dims.slice(),u=ye.normalizeAxis(n.axis,i.length),l=ye.sizeToDimension(i,u),d=ye.sizeFromDimension(i,u);return Ba(e,t,n,l,d)},Dv=e=>je({axis:e.attributes.getInt("axis",1)}),Mv=e=>je({axis:e.attributes.getInt("axis",-1)}),Nv=(e,t,n)=>{Fa(t);let i=t[0].dims.slice(),u=ye.normalizeAxis(n.axis,i.length),l=i.length,d=u!==l-1,c=[],s=[],r=[],o;d&&(s=Array.from({length:l}).map((m,g)=>g),s[u]=l-1,s[l-1]=u,s.map(m=>c.push(i[m])),o=je({perm:s}),r=Ni(e,t,o));let a=d?ye.sizeToDimension(c,l-1):ye.sizeToDimension(i,l-1),p=d?ye.sizeFromDimension(c,l-1):ye.sizeFromDimension(i,l-1),h=Ba(e,d?r:t,n,a,p);return d?Ni(e,h,o):h},Ba=(e,t,n,i,u)=>{let l=um(e,t[0],i,u,[i]),d=e.run({...Ma,cacheHint:n.cacheKey,get:()=>l},t),c=lm(e,t[0],i,u,l.output.dims,[i]),s=e.run({...Na,cacheHint:n.cacheKey,get:()=>c},[t[0],d]),r=dm(e,t[0],i,u,l.output.dims,c.output.dims);return[e.run({...za,cacheHint:n.cacheKey,get:()=>r},[t[0],d,s])]},um=(e,t,n,i,u)=>{let[l,d]=e.calculateTextureWidthAndHeight(t.dims,0),c=u.length;if(n<1||i<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(u.length!==1)throw new Error("Dimensionality of the output should be 1");if(u[0]!==n)throw new Error("Shape of the output should be equal to logical row count");let s=Ae(e.session.backend.glContext.version),r=` float process(int[${c}] indices) { int logical_row_start_offset = indices[0] * ${i}; @@ -1245,7 +1245,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( } return max; - }`;return{...Ca,output:{dims:u,type:t.type,textureType:0},shaderSource:r}},im=(e,t,n,i,u,l)=>{let[d,c]=e.calculateTextureWidthAndHeight(t.dims,0),s=l.length;if(n<1||i<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(l.length!==1)throw new Error("Dimensionality of the output should be 1");if(l[0]!==n)throw new Error("Shape of the output should be equal to logical row count");if(u.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(u[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");let r=Ae(e.session.backend.glContext.version),o=` + }`;return{...Ma,output:{dims:u,type:t.type,textureType:0},shaderSource:r}},lm=(e,t,n,i,u,l)=>{let[d,c]=e.calculateTextureWidthAndHeight(t.dims,0),s=l.length;if(n<1||i<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(l.length!==1)throw new Error("Dimensionality of the output should be 1");if(l[0]!==n)throw new Error("Shape of the output should be equal to logical row count");if(u.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(u[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");let r=Ae(e.session.backend.glContext.version),o=` float process(int[${s}] indices) { int logical_row_start_offset = indices[0] * ${i}; @@ -1258,7 +1258,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( } return norm_factor; - }`;return{...Ra,output:{dims:l,type:t.type,textureType:0},shaderSource:o}},om=(e,t,n,i,u,l)=>{let[d,c]=e.calculateTextureWidthAndHeight(t.dims,0),s=t.dims.length;if(n<1||i<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(u.length!==1||l.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(u[0]!==n||l[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");let r=` + }`;return{...Na,output:{dims:l,type:t.type,textureType:0},shaderSource:o}},dm=(e,t,n,i,u,l)=>{let[d,c]=e.calculateTextureWidthAndHeight(t.dims,0),s=t.dims.length;if(n<1||i<1)throw new Error("Logical row count N and feature count D must be greater than or equal to 1");if(u.length!==1||l.length!==1)throw new Error("Dimensionality of the intermediate results should be 1");if(u[0]!==n||l[0]!==n)throw new Error("Shape of the intermediate results should be equal to logical row count");let r=` float process(int[${s}] indices) { // get offset of current logical tensor index from the 2-D texture coordinates (TexCoords) @@ -1277,31 +1277,31 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( return 0.0; return exp(_A(indices) - _Max(logical_row_index)) / norm_factor; - }`;return{...Da,output:{dims:t.dims,type:t.type,textureType:0},shaderSource:r}},Na=e=>{if(!e||e.length!==1)throw new Error("Softmax requires 1 input.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("Invalid input type")}}),za,Cv,Rv,sm,am,um,uA=D(()=>{"use strict";ut(),Me(),Pe(),za={name:"Split",inputNames:["A"],inputTypes:[0]},Cv=(e,t,n)=>{um(t);let i=ye.normalizeAxis(n.axis,t[0].dims.length),u=sm(e,t,i,n),l=[];for(let d=0;dam(e,t[0],n,i,d)},t));return l},Rv=e=>{let t=e.attributes.getInt("axis",0),n=e.attributes.getInts("split",[]),i=e.outputs.length;return je({axis:t,split:n,numOutputs:i})},sm=(e,t,n,i)=>{let[,u]=il.splitShape(t[0].dims,n,i.split,i.numOutputs);return u.length},am=(e,t,n,i,u)=>{let[l,d]=il.splitShape(t.dims,i,n.split,n.numOutputs),c=d[u],s=l[u],r=` + }`;return{...za,output:{dims:t.dims,type:t.type,textureType:0},shaderSource:r}},Fa=e=>{if(!e||e.length!==1)throw new Error("Softmax requires 1 input.");if(e[0].type!=="float32"&&e[0].type!=="float64")throw new Error("Invalid input type")}}),La,zv,Bv,cm,pm,hm,mA=D(()=>{"use strict";ut(),Me(),Pe(),La={name:"Split",inputNames:["A"],inputTypes:[0]},zv=(e,t,n)=>{hm(t);let i=ye.normalizeAxis(n.axis,t[0].dims.length),u=cm(e,t,i,n),l=[];for(let d=0;dpm(e,t[0],n,i,d)},t));return l},Bv=e=>{let t=e.attributes.getInt("axis",0),n=e.attributes.getInts("split",[]),i=e.outputs.length;return je({axis:t,split:n,numOutputs:i})},cm=(e,t,n,i)=>{let[,u]=al.splitShape(t[0].dims,n,i.split,i.numOutputs);return u.length},pm=(e,t,n,i,u)=>{let[l,d]=al.splitShape(t.dims,i,n.split,n.numOutputs),c=d[u],s=l[u],r=` float process(int indices[${s.length}]) { indices[${i}] += ${c}; return _A(indices); } - `;return{...za,cacheHint:`${n.cacheKey}:${u}`,output:{dims:s,type:t.type,textureType:0},shaderSource:r}},um=e=>{if(!e||e.length!==1)throw new Error("Split requires one input.");if(e[0].type!=="int8"&&e[0].type!=="uint8"&&e[0].type!=="int16"&&e[0].type!=="uint16"&&e[0].type!=="int32"&&e[0].type!=="uint32"&&e[0].type!=="float32"&&e[0].type!=="float64"&&e[0].type!=="bool")throw new Error("Invalid input type.")}}),vl,Dv,Mv,lm,dm,lA=D(()=>{"use strict";Me(),vl=(e,t,n)=>{lm(t);let i=ye.squeezeShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],i)]},Dv=(e,t)=>(dm(t),vl(e,[t[0]],Array.from(t[1].integerData))),Mv=e=>e.attributes.getInts("axes"),lm=e=>{if(!e||e.length!==1)throw new Error("Squeeze requires 1 input.");if(e[0].type==="string")throw new Error("invalid input tensor types.")},dm=e=>{if(!e||e.length!==2)throw new Error("Squeeze requires 2 inputs.");if(e[1].type!=="int32")throw new Error("Invalid input type.")}}),Nv,cm,pm,dA=D(()=>{"use strict";Ke(),Pe(),Nv=(e,t)=>{pm(t);let n={name:"Sum",inputNames:t.map((i,u)=>`X${u}`),inputTypes:new Array(t.length).fill(0)};return[e.run({...n,get:()=>cm(e,t,n)},t)]},cm=(e,t,n)=>{let i=Ae(e.session.backend.glContext.version),u=t[0].dims.slice(),l=` + `;return{...La,cacheHint:`${n.cacheKey}:${u}`,output:{dims:s,type:t.type,textureType:0},shaderSource:r}},hm=e=>{if(!e||e.length!==1)throw new Error("Split requires one input.");if(e[0].type!=="int8"&&e[0].type!=="uint8"&&e[0].type!=="int16"&&e[0].type!=="uint16"&&e[0].type!=="int32"&&e[0].type!=="uint32"&&e[0].type!=="float32"&&e[0].type!=="float64"&&e[0].type!=="bool")throw new Error("Invalid input type.")}}),Tl,Fv,Lv,fm,mm,gA=D(()=>{"use strict";Me(),Tl=(e,t,n)=>{fm(t);let i=ye.squeezeShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],i)]},Fv=(e,t)=>(mm(t),Tl(e,[t[0]],Array.from(t[1].integerData))),Lv=e=>e.attributes.getInts("axes"),fm=e=>{if(!e||e.length!==1)throw new Error("Squeeze requires 1 input.");if(e[0].type==="string")throw new Error("invalid input tensor types.")},mm=e=>{if(!e||e.length!==2)throw new Error("Squeeze requires 2 inputs.");if(e[1].type!=="int32")throw new Error("Invalid input type.")}}),jv,gm,bm,bA=D(()=>{"use strict";Ke(),Pe(),jv=(e,t)=>{bm(t);let n={name:"Sum",inputNames:t.map((i,u)=>`X${u}`),inputTypes:new Array(t.length).fill(0)};return[e.run({...n,get:()=>gm(e,t,n)},t)]},gm=(e,t,n)=>{let i=Ae(e.session.backend.glContext.version),u=t[0].dims.slice(),l=` void main() { vec4 result = ${t.map((d,c)=>`${i.texture2D}(X${c},TexCoords)`).join(" + ")}; ${i.output} = result; } - `;return{...n,output:{dims:u,type:t[0].type,textureType:0},hasMain:!0,shaderSource:l}},pm=e=>{if(!e||e.length===0)throw new Error("Sum requires inputs.");let t=e[0].dims.length;for(let n=1;n{"use strict";os(),Pe(),zv=(e,t)=>{fm(t);let n={name:"Tile",inputNames:["A"],inputTypes:[0]};return[e.run({...n,get:()=>hm(e,t,n)},t)]},hm=(e,t,n)=>{let i=t[0].dims.slice(),u=new Array(i.length),l=[];for(let s=0;s{if(!e||e.length===0)throw new Error("Sum requires inputs.");let t=e[0].dims.length;for(let n=1;n{"use strict";as(),Pe(),Uv=(e,t)=>{wm(t);let n={name:"Tile",inputNames:["A"],inputTypes:[0]};return[e.run({...n,get:()=>ym(e,t,n)},t)]},ym=(e,t,n)=>{let i=t[0].dims.slice(),u=new Array(i.length),l=[];for(let s=0;s{if(!e||e.length!==2)throw new Error("Tile requires 2 input.");if(e[1].dims.length!==1)throw new Error("The second input shape must 1 dimension.");if(e[1].dims[0]!==e[0].dims.length)throw new Error("Invalid input shape.");if(Fi.indexOf(e[0].type)===-1)throw new Error("Invalid input type.");if(e[1].type!=="int32"&&e[1].type!=="int16")throw new Error("Invalid repeat type.")}}),xl,Bv,Fv,mm,gm,pA=D(()=>{"use strict";Me(),xl=(e,t,n)=>{mm(t);let i=ye.unsqueezeShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],i)]},Bv=(e,t)=>(gm(t),xl(e,[t[0]],Array.from(t[1].integerData))),Fv=e=>e.attributes.getInts("axes"),mm=e=>{if(!e||e.length!==1)throw new Error("Unsqueeze requires 1 input.");if(e[0].type==="string")throw new Error("invalid input tensor types.")},gm=e=>{if(!e||e.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(e[1].type!=="int32")throw new Error("Invalid input type.")}}),Lv,hA=D(()=>{"use strict";eE(),fE(),mE(),bE(),Yl(),qE(),GE(),HE(),WE(),KE(),XE(),ZE(),QE(),Xl(),eA(),tA(),rA(),nA(),iA(),oA(),sA(),aA(),uA(),lA(),dA(),cA(),Jl(),S_(),pA(),vv(),Lv=[["Abs","","6+",r_],["Acos","","7+",n_],["Add","","7+",Nw],["And","","7+",zw],["Asin","","7+",i_],["Atan","","7+",o_],["AveragePool","","7+",iv,ov],["BatchNormalization","","7+",Cw,Rw],["Cast","","6+",Kw,Xw],["Ceil","","6+",u_],["Clip","","6-10",cl,s_],["Clip","","11+",a_],["Concat","","4+",Yw,Jw],["Conv","","1+",fl,ml],["ConvTranspose","","1+",B_,F_],["Cos","","7+",l_],["Div","","7+",Bw],["Dropout","","7+",pl],["DepthToSpace","","1+",j_,U_],["Equal","","7+",Fw],["Elu","","6+",d_,c_],["Exp","","6+",p_],["Flatten","","1+",V_,q_],["Floor","","6+",h_],["FusedConv","com.microsoft","1+",fl,ml],["Gather","","1+",G_,H_],["Gemm","","7-10",gl,W_],["Gemm","","11+",gl,K_],["GlobalAveragePool","","1+",sv,av],["GlobalMaxPool","","1+",dv],["Greater","","7+",Lw],["Identity","","1+",pl],["ImageScaler","","1+",X_,Z_],["InstanceNormalization","","6+",Y_,J_],["LeakyRelu","","6+",f_,m_],["Less","","7+",jw],["LRN","","1+",Q_,ev],["Log","","6+",g_],["MatMul","","1+",k_,P_],["MaxPool","","1+",uv,lv],["Mul","","7+",Uw],["Neg","","6+",b_],["Not","","1+",y_],["Or","","7+",Vw],["Pad","","2-10",bl,tv],["Pad","","11+",rv,nv],["Pow","","7+",qw],["PRelu","","7+",Gw],["ReduceLogSum","","1+",gv,Or],["ReduceMax","","1+",hv,Or],["ReduceMean","","1+",pv,Or],["ReduceMin","","1+",fv,Or],["ReduceProd","","1+",mv,Or],["ReduceSum","","1-12",cv,Or],["ReduceSumSquare","","1+",bv,Or],["Relu","","6+",w_],["Reshape","","5+",yv],["Resize","","10",_l,xv],["Resize","","11+",_l,$v],["Shape","","1+",Tv],["Sigmoid","","6+",__],["Sin","","7+",v_],["Slice","","10+",Ov],["Slice","","1-9",Sv,Iv],["Softmax","","1-12",Ev,Av],["Softmax","","13+",Pv,kv],["Split","","2-12",Cv,Rv],["Sqrt","","6+",x_],["Squeeze","","1-12",vl,Mv],["Squeeze","","13+",Dv],["Sub","","7+",Hw],["Sum","","6+",Nv],["Tan","","7+",$_],["Tanh","","6+",T_],["Tile","","6+",zv],["Transpose","","1+",Di,L_],["Upsample","","7-8",yl,wv],["Upsample","","9",yl,_v],["Unsqueeze","","1-12",xl,Fv],["Unsqueeze","","13+",Bv],["Xor","","7+",Ww]]});function fA(e){let t={},n;for(;(n=$l.exec(e))!==null;){let i=n[3].split(",").map(u=>{let l=u.trim().split(" ");return l&&l.length===2?{type:l[0],name:l[1]}:null}).filter(u=>u!==null);t[n[2]]={params:i,body:n[4]}}for(let i in t){let u=jv.replace("__FUNC__",i),l=new RegExp(u,"gm");for(;(n=l.exec(e))!==null;){let d=n[1],c=n[2],s=n[3].split(","),r=d?`${d} ${c};`:"",o=t[i].body,a="";t[i].params.forEach((h,m)=>{h&&(a+=`${h.type} ${h.name} = ${s[m]}; + `;return{...n,output:{dims:u,type:t[0].type,textureType:0},shaderSource:c}},wm=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 input.");if(e[1].dims.length!==1)throw new Error("The second input shape must 1 dimension.");if(e[1].dims[0]!==e[0].dims.length)throw new Error("Invalid input shape.");if(ji.indexOf(e[0].type)===-1)throw new Error("Invalid input type.");if(e[1].type!=="int32"&&e[1].type!=="int16")throw new Error("Invalid repeat type.")}}),Sl,Vv,Gv,_m,vm,wA=D(()=>{"use strict";Me(),Sl=(e,t,n)=>{_m(t);let i=ye.unsqueezeShape(t[0].dims,n);return[e.reshapeUnpacked(t[0],i)]},Vv=(e,t)=>(vm(t),Sl(e,[t[0]],Array.from(t[1].integerData))),Gv=e=>e.attributes.getInts("axes"),_m=e=>{if(!e||e.length!==1)throw new Error("Unsqueeze requires 1 input.");if(e[0].type==="string")throw new Error("invalid input tensor types.")},vm=e=>{if(!e||e.length!==2)throw new Error("Unsqueeze requires 2 inputs.");if(e[1].type!=="int32")throw new Error("Invalid input type.")}}),qv,_A=D(()=>{"use strict";aE(),vE(),xE(),TE(),ed(),YE(),JE(),QE(),eA(),tA(),rA(),nA(),sA(),Jl(),aA(),uA(),lA(),dA(),cA(),pA(),hA(),fA(),mA(),gA(),bA(),yA(),td(),k_(),wA(),Iv(),qv=[["Abs","","6+",a_],["Acos","","7+",u_],["Add","","7+",jw],["And","","7+",Uw],["Asin","","7+",l_],["Atan","","7+",d_],["AveragePool","","7+",lv,dv],["BatchNormalization","","7+",zw,Bw],["Cast","","6+",Qw,e_],["Ceil","","6+",h_],["Clip","","6-10",fl,c_],["Clip","","11+",p_],["Concat","","4+",r_,n_],["Conv","","1+",bl,yl],["ConvTranspose","","1+",V_,G_],["Cos","","7+",f_],["Div","","7+",Vw],["Dropout","","7+",ml],["DepthToSpace","","1+",H_,W_],["Equal","","7+",Gw],["Elu","","6+",m_,g_],["Exp","","6+",b_],["Flatten","","1+",K_,X_],["Floor","","6+",y_],["FusedConv","com.microsoft","1+",bl,yl],["Gather","","1+",Z_,Y_],["Gemm","","7-10",wl,J_],["Gemm","","11+",wl,Q_],["GlobalAveragePool","","1+",cv,pv],["GlobalMaxPool","","1+",mv],["Greater","","7+",qw],["Identity","","1+",ml],["ImageScaler","","1+",ev,tv],["InstanceNormalization","","6+",rv,nv],["LeakyRelu","","6+",w_,__],["Less","","7+",Hw],["LRN","","1+",iv,ov],["Log","","6+",v_],["MatMul","","1+",M_,N_],["MaxPool","","1+",hv,fv],["Mul","","7+",Ww],["Neg","","6+",x_],["Not","","1+",$_],["Or","","7+",Kw],["Pad","","2-10",_l,sv],["Pad","","11+",av,uv],["Pow","","7+",Xw],["PRelu","","7+",Zw],["ReduceLogSum","","1+",vv,Or],["ReduceMax","","1+",yv,Or],["ReduceMean","","1+",bv,Or],["ReduceMin","","1+",wv,Or],["ReduceProd","","1+",_v,Or],["ReduceSum","","1-12",gv,Or],["ReduceSumSquare","","1+",xv,Or],["Relu","","6+",T_],["Reshape","","5+",$v],["Resize","","10",$l,Ov],["Resize","","11+",$l,Ev],["Shape","","1+",Av],["Sigmoid","","6+",S_],["Sin","","7+",I_],["Slice","","10+",Cv],["Slice","","1-9",kv,Pv],["Softmax","","1-12",Rv,Dv],["Softmax","","13+",Nv,Mv],["Split","","2-12",zv,Bv],["Sqrt","","6+",O_],["Squeeze","","1-12",Tl,Lv],["Squeeze","","13+",Fv],["Sub","","7+",Yw],["Sum","","6+",jv],["Tan","","7+",E_],["Tanh","","6+",A_],["Tile","","6+",Uv],["Transpose","","1+",Ni,q_],["Upsample","","7-8",vl,Tv],["Upsample","","9",vl,Sv],["Unsqueeze","","1-12",Sl,Gv],["Unsqueeze","","13+",Vv],["Xor","","7+",Jw]]});function vA(e){let t={},n;for(;(n=Il.exec(e))!==null;){let i=n[3].split(",").map(u=>{let l=u.trim().split(" ");return l&&l.length===2?{type:l[0],name:l[1]}:null}).filter(u=>u!==null);t[n[2]]={params:i,body:n[4]}}for(let i in t){let u=Hv.replace("__FUNC__",i),l=new RegExp(u,"gm");for(;(n=l.exec(e))!==null;){let d=n[1],c=n[2],s=n[3].split(","),r=d?`${d} ${c};`:"",o=t[i].body,a="";t[i].params.forEach((h,m)=>{h&&(a+=`${h.type} ${h.name} = ${s[m]}; `)}),o=`${a} ${o}`,o=o.replace("return",`${c} = `);let p=` ${r} { ${o} } - `;e=e.replace(n[0],p)}}return e=e.replace($l,""),e}var $l,jv,mA=D(()=>{"use strict";$l=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm,jv="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;"});function xi(e,t){let n=[],i=[],u=t!=null&&Array.isArray(t)&&t.length===0,l=t==null||u?null:gA(t,e).sort(),d=0;for(let c=0;cc)&&e[c]===1&&(n.push(e[c]),i.push(c)),l[d]<=c&&d++}e[c]!==1&&(n.push(e[c]),i.push(c))}return{newShape:n,keptDims:i}}function gA(e,t){let n=t.length;return e=e==null?t.map((i,u)=>u):[].concat(e),jo(e.every(i=>i>=-n&&i`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),jo(e.every(bA),()=>`All values in axis param must be integers but got axis ${e}`),e.map(i=>i<0?n+i:i)}function bA(e){return e%1===0}function yA(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n{"use strict";qt(),Me(),Uv=class{constructor(e){this.maxTextureSize=e}computeTextureWH(e,t){let n=this.computeTexture(e,t);return t&&t.isPacked&&(n[0]/=2,n[1]/=2),t&&t.reverseWH?[n[1],n[0]]:n}computeTexture(e,t){let n=t&&t.isPacked;if(e.length===0)return n?[2,2]:[1,1];let i=this.maxTextureSize;if(t&&t.breakAxis!==void 0){let d=t.breakAxis>=e.length?1:e.slice(t.breakAxis).reduce((s,r)=>s*r),c=t.breakAxis<=0?1:e.slice(0,t.breakAxis).reduce((s,r)=>s*r);if(d>i||c>i)Je.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${e}, breakAxis:${t.breakAxis}`);else return[d,c]}let u=e.slice(0);n&&(i=i*2,u=u.map((d,c)=>c>=u.length-2?u[c]%2===0?u[c]:u[c]+1:u[c]),u.length===1&&(u=[2,u[0]])),u.length!==2&&(u=xi(u).newShape);let l=yA(u);return u.length<=1&&l<=i?[1,l]:u.length===2&&u[0]<=i&&u[1]<=i?u:u.length===3&&u[0]*u[1]<=i&&u[2]<=i?[u[0]*u[1],u[2]]:u.length===3&&u[0]<=i&&u[1]*u[2]<=i?[u[0],u[1]*u[2]]:u.length===4&&u[0]*u[1]*u[2]<=i&&u[3]<=i?[u[0]*u[1]*u[2],u[3]]:u.length===4&&u[0]<=i&&u[1]*u[2]*u[3]<=i?[u[0],u[1]*u[2]*u[3]]:n?bm(l/4).map(d=>d*2):bm(l)}}}),qv,wA=D(()=>{"use strict";Me(),Pr(),Ke(),Vv(),ar(),qv=class extends Un{constructor(e){super(e)}getFunctions(){return{...this.offsetToCoords(),...this.coordsToOffset(),...this.toVec(),...this.valueFrom(),...this.getCommonUtilFuncs(),...this.getInputsSamplingSnippets(),...this.getOutputSamplingSnippet()}}getCustomTypes(){return{}}offsetToCoords(){let e="offsetToCoords";return{offsetToCoords:new ie(` + `;e=e.replace(n[0],p)}}return e=e.replace(Il,""),e}var Il,Hv,xA=D(()=>{"use strict";Il=/@inline[\s\n\r]+(\w+)[\s\n\r]+([0-9a-zA-Z_]+)\s*\(([^)]*)\)\s*{(([^}]|[\n\r])*)}/gm,Hv="(\\w+)?\\s+([_0-9a-zA-Z]+)\\s+=\\s+__FUNC__\\((.*)\\)\\s*;"});function Ti(e,t){let n=[],i=[],u=t!=null&&Array.isArray(t)&&t.length===0,l=t==null||u?null:$A(t,e).sort(),d=0;for(let c=0;cc)&&e[c]===1&&(n.push(e[c]),i.push(c)),l[d]<=c&&d++}e[c]!==1&&(n.push(e[c]),i.push(c))}return{newShape:n,keptDims:i}}function $A(e,t){let n=t.length;return e=e==null?t.map((i,u)=>u):[].concat(e),Vo(e.every(i=>i>=-n&&i`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),Vo(e.every(TA),()=>`All values in axis param must be integers but got axis ${e}`),e.map(i=>i<0?n+i:i)}function TA(e){return e%1===0}function SA(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n{"use strict";Gt(),Me(),Wv=class{constructor(e){this.maxTextureSize=e}computeTextureWH(e,t){let n=this.computeTexture(e,t);return t&&t.isPacked&&(n[0]/=2,n[1]/=2),t&&t.reverseWH?[n[1],n[0]]:n}computeTexture(e,t){let n=t&&t.isPacked;if(e.length===0)return n?[2,2]:[1,1];let i=this.maxTextureSize;if(t&&t.breakAxis!==void 0){let d=t.breakAxis>=e.length?1:e.slice(t.breakAxis).reduce((s,r)=>s*r),c=t.breakAxis<=0?1:e.slice(0,t.breakAxis).reduce((s,r)=>s*r);if(d>i||c>i)Je.verbose("TextureLayout",`Given width/height preferences were unattainable: shape:${e}, breakAxis:${t.breakAxis}`);else return[d,c]}let u=e.slice(0);n&&(i=i*2,u=u.map((d,c)=>c>=u.length-2?u[c]%2===0?u[c]:u[c]+1:u[c]),u.length===1&&(u=[2,u[0]])),u.length!==2&&(u=Ti(u).newShape);let l=SA(u);return u.length<=1&&l<=i?[1,l]:u.length===2&&u[0]<=i&&u[1]<=i?u:u.length===3&&u[0]*u[1]<=i&&u[2]<=i?[u[0]*u[1],u[2]]:u.length===3&&u[0]<=i&&u[1]*u[2]<=i?[u[0],u[1]*u[2]]:u.length===4&&u[0]*u[1]*u[2]<=i&&u[3]<=i?[u[0]*u[1]*u[2],u[3]]:u.length===4&&u[0]<=i&&u[1]*u[2]*u[3]<=i?[u[0],u[1]*u[2]*u[3]]:n?xm(l/4).map(d=>d*2):xm(l)}}}),Xv,IA=D(()=>{"use strict";Me(),Pr(),Ke(),Kv(),ar(),Xv=class extends Un{constructor(e){super(e)}getFunctions(){return{...this.offsetToCoords(),...this.coordsToOffset(),...this.toVec(),...this.valueFrom(),...this.getCommonUtilFuncs(),...this.getInputsSamplingSnippets(),...this.getOutputSamplingSnippet()}}getCustomTypes(){return{}}offsetToCoords(){let e="offsetToCoords";return{offsetToCoords:new ie(` vec2 ${e}(int offset, int width, int height) { int t = offset / width; int s = offset - t*width; @@ -1341,7 +1341,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( vec2(${n[0]}, ${n[1]})); return 2 * (resTexRC.y * ${n[0]} + resTexRC.x); } - `,new ie(i))}getOutputPacked2DCoords(e,t){let n="";if(_i.arraysEqual(e,t))return n=` + `,new ie(i))}getOutputPacked2DCoords(e,t){let n="";if(xi.arraysEqual(e,t))return n=` ivec2 getOutputCoords() { return 2 * ivec2(TexCoords.xy * vec2(${t[0]}, ${t[1]})); } @@ -1474,7 +1474,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( `),t="sampleTexture";let n=Ae(this.context.glContext.version);return e[t]=new ie(` float sampleTexture(sampler2D textureSampler, vec2 uv) { return ${n.texture2D}(textureSampler, uv).r; - }`),e}getInputsSamplingSnippets(){let e={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((n,i)=>{let u=this.context.inputTextureLayouts[i],l=ga(n);u.isPacked?e[l]=this.getPackedSamplerFromInput(l,n,u):e[l]=this.getUnpackedSamplerFromInput(l,n,u);let d=FO(n);u.unpackedShape.length<=t.unpackedShape.length&&(u.isPacked?e[d]=this.getPackedSamplerAtOutputCoords(d,u,t,n):e[d]=this.getUnpackedSamplerAtOutputCoords(d,u,t,n))}),e}getPackedSamplerAtOutputCoords(e,t,n,i){let u=t.unpackedShape,l=n.unpackedShape,d=ga(i),c=u.length,s=l.length,r=Qt.getBroadcastDims(u,l),o=Ar(s),a=s-c,p,h=zn();c===0?p="":s<2&&r.length>=1?p="coords = 0;":p=r.map(S=>`coords.${h[S+a]} = 0;`).join(` + }`),e}getInputsSamplingSnippets(){let e={},t=this.context.outputTextureLayout;return this.context.programInfo.inputNames.forEach((n,i)=>{let u=this.context.inputTextureLayouts[i],l=wa(n);u.isPacked?e[l]=this.getPackedSamplerFromInput(l,n,u):e[l]=this.getUnpackedSamplerFromInput(l,n,u);let d=HO(n);u.unpackedShape.length<=t.unpackedShape.length&&(u.isPacked?e[d]=this.getPackedSamplerAtOutputCoords(d,u,t,n):e[d]=this.getUnpackedSamplerAtOutputCoords(d,u,t,n))}),e}getPackedSamplerAtOutputCoords(e,t,n,i){let u=t.unpackedShape,l=n.unpackedShape,d=wa(i),c=u.length,s=l.length,r=Qt.getBroadcastDims(u,l),o=Ar(s),a=s-c,p,h=zn();c===0?p="":s<2&&r.length>=1?p="coords = 0;":p=r.map(S=>`coords.${h[S+a]} = 0;`).join(` `);let m="";s<2&&c>0?m="coords":m=u.map((S,O)=>`coords.${h[O+a]}`).join(", ");let g="return outputValue;",_=ye.size(u)===1,w=ye.size(l)===1;if(c===1&&!_&&!w)g=` return vec4(outputValue.xy, outputValue.xy); `;else if(_&&!w)s===1?g=` @@ -1493,7 +1493,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( vec4 outputValue = ${d}(${m}); ${g} } - `;return new ie(T,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(e,t,n,i){let u=[n.width,n.height],l=[t.width,t.height],d=t.unpackedShape.length,c=n.unpackedShape.length,s=t.unpackedShape,r=n.unpackedShape,o=ga(i);if(d===c&&_i.arraysEqual(l,u)){let y=` + `;return new ie(T,["coordinates.getOutputCoords"])}getUnpackedSamplerAtOutputCoords(e,t,n,i){let u=[n.width,n.height],l=[t.width,t.height],d=t.unpackedShape.length,c=n.unpackedShape.length,s=t.unpackedShape,r=n.unpackedShape,o=wa(i);if(d===c&&xi.arraysEqual(l,u)){let y=` float ${e}() { return sampleTexture(${i}, TexCoords); } @@ -1512,15 +1512,15 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( vec2 uv = packedUVfrom1D( ${u[0]}, ${u[1]}, index); return ${l.texture2D}(${t}, uv); - }`;return new ie(d,["coordinates.packedUVfrom1D"])}getPackedSampler2D(e,t,n){let i=n.unpackedShape,u=[n.width,n.height],l=Ae(this.context.glContext.version),d=u[0],c=u[1];if(u!=null&&_i.arraysEqual(i,u)){let a=`vec4 ${e}(int row, int col) { + }`;return new ie(d,["coordinates.packedUVfrom1D"])}getPackedSampler2D(e,t,n){let i=n.unpackedShape,u=[n.width,n.height],l=Ae(this.context.glContext.version),d=u[0],c=u[1];if(u!=null&&xi.arraysEqual(i,u)){let a=`vec4 ${e}(int row, int col) { vec2 uv = (vec2(col, row) + halfCR) / vec2(${c}.0, ${d}.0); return ${l.texture2D}(${t}, uv); }`;return new ie(a)}let s=u,r=Math.ceil(i[1]/2),o=`vec4 ${e}(int row, int col) { vec2 uv = packedUVfrom2D(${s[1]}, ${s[0]}, ${r}, row, col); return ${l.texture2D}(${t}, uv); - }`;return new ie(o,["coordinates.packedUVfrom2D"])}getPackedSampler3D(e,t,n){let i=n.unpackedShape,u=[n.width,n.height],l=[u[0],u[1]],d=Ae(this.context.glContext.version);if(i[0]===1){let p=i.slice(1),h=[1,2],m=ii(i,p),g=["b","row","col"],_=JSON.parse(JSON.stringify(n));_.unpackedShape=m;let w=this.getPackedSamplerFromInput(e,t,_),y=`${w.routineBody} + }`;return new ie(o,["coordinates.packedUVfrom2D"])}getPackedSampler3D(e,t,n){let i=n.unpackedShape,u=[n.width,n.height],l=[u[0],u[1]],d=Ae(this.context.glContext.version);if(i[0]===1){let p=i.slice(1),h=[1,2],m=si(i,p),g=["b","row","col"],_=JSON.parse(JSON.stringify(n));_.unpackedShape=m;let w=this.getPackedSamplerFromInput(e,t,_),y=`${w.routineBody} vec4 ${e}(int b, int row, int col) { - return ${e}(${oi(g,h)}); + return ${e}(${ai(g,h)}); } `;return new ie(y,w.dependencies)}let c=l[0],s=l[1],r=Math.ceil(i[2]/2),o=r*Math.ceil(i[1]/2),a=`vec4 ${e}(int b, int row, int col) { vec2 uv = packedUVfrom3D( ${s}, ${c}, ${o}, ${r}, b, row, col); @@ -1559,15 +1559,15 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( vec2 uv = uvFromFlat(${i}, ${u}, index); return sampleTexture(${t}, uv); } - `;return new ie(l,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler2D(e,t,n){let i=n.unpackedShape,u=[n.height,n.width];if(u!=null&&_i.arraysEqual(i,u)){let a=u[1],p=u[0],h=` + `;return new ie(l,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler2D(e,t,n){let i=n.unpackedShape,u=[n.height,n.width];if(u!=null&&xi.arraysEqual(i,u)){let a=u[1],p=u[0],h=` float ${e}(int row, int col) { vec2 uv = (vec2(row, col) + halfCR) / vec2(${a}.0, ${p}.0); return sampleTexture(${t}, uv); } - `;return new ie(h,["coordinates.sampleTexture"])}let{newShape:l,keptDims:d}=xi(i),c=l;if(c.lengthyr( vec2 uv = uvFromFlat(${s}, ${r}, index); return sampleTexture(${t}, uv); } - `;return new ie(o,["coordinates.uvFromFlat","coordinates.sampleTexture","coordinates.coordsToOffset"])}getUnpackedSampler3D(e,t,n){let i=n.unpackedShape,u=i[1]*i[2],l=i[2],{newShape:d,keptDims:c}=xi(i),s=d;if(s.lengthyr( vec2 uv = uvFromFlat(${c}, ${s}, index); return sampleTexture(${t}, uv); } - `;return new ie(r,["coordinates.uvFromFlat","coordinates.sampleTexture"])}getUnpackedSampler5D(e,t,n){let i=n.unpackedShape,u=i[4],l=i[3]*u,d=i[2]*l,c=i[1]*d,{newShape:s,keptDims:r}=xi(i);if(s.lengthyr( vec2 uv = uvFromFlat(${o}, ${a}, index); return sampleTexture(${t}, uv); } - `;return new ie(p,["coordinates.sampleTexture","coordinates.uvFromFlat"])}getUnpackedSampler6D(e,t,n){let i=n.unpackedShape,u=i[5],l=i[4]*u,d=i[3]*l,c=i[2]*d,s=i[1]*c,{newShape:r,keptDims:o}=xi(i);if(r.lengthyr( vec2 coords = offsetToCoords(offset, ${n}, ${i}); return ${d.texture2D}(${e}, coords); } - `}}}),Gv,_A=D(()=>{"use strict";Pr(),Gv=class Tl extends Un{constructor(t){super(t)}getFunctions(){return{...this.encodeFloat32(),...this.decodeFloat32()}}getCustomTypes(){return{}}encodeFloat32(){return{encode:new ie(`highp vec4 encode(highp float f) { + `}}}),Zv,OA=D(()=>{"use strict";Pr(),Zv=class Ol extends Un{constructor(t){super(t)}getFunctions(){return{...this.encodeFloat32(),...this.decodeFloat32()}}getCustomTypes(){return{}}encodeFloat32(){return{encode:new ie(`highp vec4 encode(highp float f) { return vec4(f, 0.0, 0.0, 0.0); } `)}}decodeFloat32(){return{decode:new ie(`highp float decode(highp vec4 rgba) { return rgba.r; } - `)}}encodeUint8(){let t=Tl.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new ie(` + `)}}encodeUint8(){let t=Ol.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{encode:new ie(` highp vec4 encode(highp float f) { highp float F = abs(f); highp float Sign = step(0.0,-f); @@ -1680,7 +1680,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( rgba = rgba / 255.0; // values need to be normalized to [0,1] return rgba; } - `)}}decodeUint8(){let t=Tl.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new ie(` + `)}}decodeUint8(){let t=Ol.isLittleEndian()?"rgba.rgba=rgba.abgr;":"";return{decode:new ie(` highp float decode(highp vec4 rgba) { rgba = rgba * 255.0; // values need to be de-normalized from [0,1] to [0,255] ${t} @@ -1690,7 +1690,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( highp float Result = Sign * exp2(Exponent) * (Mantissa * exp2(-23.0 )); return Result; } - `)}}static isLittleEndian(){let t=new ArrayBuffer(4),n=new Uint32Array(t),i=new Uint8Array(t);if(n[0]=3735928559,i[0]===239)return!0;if(i[0]===222)return!1;throw new Error("unknown endianness")}}}),Hv,vA=D(()=>{"use strict";Pr(),Ke(),Hv=class extends Un{constructor(e){super(e)}getFunctions(){return{...this.setFragColor(),...this.getColorAsFloat()}}getCustomTypes(){return{}}setFragColor(){let e=Ae(this.context.glContext.version);return{setFragColor:new ie(` + `)}}static isLittleEndian(){let t=new ArrayBuffer(4),n=new Uint32Array(t),i=new Uint8Array(t);if(n[0]=3735928559,i[0]===239)return!0;if(i[0]===222)return!1;throw new Error("unknown endianness")}}}),Yv,EA=D(()=>{"use strict";Pr(),Ke(),Yv=class extends Un{constructor(e){super(e)}getFunctions(){return{...this.setFragColor(),...this.getColorAsFloat()}}getCustomTypes(){return{}}setFragColor(){let e=Ae(this.context.glContext.version);return{setFragColor:new ie(` void setFragColor(float value) { ${e.output} = encode(value); } @@ -1698,7 +1698,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( float getColorAsFloat(vec4 color) { return decode(color); } - `,["encoding.decode"])}}}}),Wv,xA=D(()=>{"use strict";Pr(),Wv=class $i extends Un{constructor(t){super(t)}getFunctions(){return{...this.bcastIndex(),...this.bcastMatmulIndex(),...this.offsetToIndices(),...this.indicesToOffset(),...this.incrementIndices()}}getCustomTypes(){return{}}bcastIndex(){let t=this.context.outputTextureLayout.shape.length,n={};return this.context.programInfo.inputNames.forEach((i,u)=>{let l=this.context.inputTextureLayouts[u].unpackedShape;if(l.length<=t){let d=l.length,c=t-d,s=`bcastIndices_${i}`,r="";for(let a=0;a{"use strict";Pr(),Jv=class Si extends Un{constructor(t){super(t)}getFunctions(){return{...this.bcastIndex(),...this.bcastMatmulIndex(),...this.offsetToIndices(),...this.indicesToOffset(),...this.incrementIndices()}}getCustomTypes(){return{}}bcastIndex(){let t=this.context.outputTextureLayout.shape.length,n={};return this.context.programInfo.inputNames.forEach((i,u)=>{let l=this.context.inputTextureLayouts[u].unpackedShape;if(l.length<=t){let d=l.length,c=t-d,s=`bcastIndices_${i}`,r="";for(let a=0;ayr( realIndices[${d-1}] = bcastedIndices[${t-1}]; realIndices[${d-2}] = bcastedIndices[${t-2}]; } - `;n[s]=new ie(o)}}),n}indicesToOffset(){let t={};return this.context.programInfo.inputNames.forEach((n,i)=>{let u=this.context.inputTextureLayouts[i].shape,l=this.context.inputTextureLayouts[i].strides,d=u.length,c=`indicesToOffset_${n}`;t[c]=new ie($i.indexToOffsetSingle(c,d,l)),c=`indicesToOffset_${n}_T`,t[c]=new ie($i.indexToOffsetSingle(c,d,l.slice().reverse()))}),t}static indexToOffsetSingle(t,n,i){let u="";for(let l=n-1;l>=0;--l)u+=` + `;n[s]=new ie(o)}}),n}indicesToOffset(){let t={};return this.context.programInfo.inputNames.forEach((n,i)=>{let u=this.context.inputTextureLayouts[i].shape,l=this.context.inputTextureLayouts[i].strides,d=u.length,c=`indicesToOffset_${n}`;t[c]=new ie(Si.indexToOffsetSingle(c,d,l)),c=`indicesToOffset_${n}_T`,t[c]=new ie(Si.indexToOffsetSingle(c,d,l.slice().reverse()))}),t}static indexToOffsetSingle(t,n,i){let u="";for(let l=n-1;l>=0;--l)u+=` offset += indices[${l}] * ${i[l]}; `;return` int ${t}(int indices[${n}]) { @@ -1720,7 +1720,7 @@ value = _A(inputIdx);`,"value = min(value, _A(inputIdx));",""]}),mv=(e,t,n)=>yr( ${u} return offset; } - `}offsetToIndices(){let t={};return this.context.programInfo.inputNames.forEach((n,i)=>{let u=this.context.inputTextureLayouts[i].shape,l=this.context.inputTextureLayouts[i].strides,d=u.length,c=`offsetToIndices_${n}`;t[c]=new ie($i.offsetToIndicesSingle(c,d,l)),c=`offsetToIndices_${n}_T`,t[c]=new ie($i.offsetToIndicesSingle(c,d,l.slice().reverse()))}),t}static offsetToIndicesSingle(t,n,i){let u=[];for(let l=0;l{let u=this.context.inputTextureLayouts[i].shape,l=this.context.inputTextureLayouts[i].strides,d=u.length,c=`offsetToIndices_${n}`;t[c]=new ie(Si.offsetToIndicesSingle(c,d,l)),c=`offsetToIndices_${n}_T`,t[c]=new ie(Si.offsetToIndicesSingle(c,d,l.slice().reverse()))}),t}static offsetToIndicesSingle(t,n,i){let u=[];for(let l=0;lyr( indices[i] = 0; } } - `;t[d]=new ie(s)}),t}}}),Kv,$A=D(()=>{"use strict";Pr(),Kv=class extends Un{constructor(e){super(e)}getCustomTypes(){return{}}getFunctions(){return{...this.binaryVecFunctions(),...this.copyVec(),...this.setVecItem(),...this.getVecItem()}}binaryVecFunctions(){let e=this.context.outputTextureLayout.shape.length,t={add:"+=",sub:"-=",mul:"*=",div:"/="},n={};for(let i in t){let u=`${i}Vec`,l="";for(let c=0;c{"use strict";Pr(),Qv=class extends Un{constructor(e){super(e)}getCustomTypes(){return{}}getFunctions(){return{...this.binaryVecFunctions(),...this.copyVec(),...this.setVecItem(),...this.getVecItem()}}binaryVecFunctions(){let e=this.context.outputTextureLayout.shape.length,t={add:"+=",sub:"-=",mul:"*=",div:"/="},n={};for(let i in t){let u=`${i}Vec`,l="";for(let c=0;cyr( int getVecItem(int m[${e}], int index) { ${t} } - `;return{getVecItem:new ie(n)}}}}),Sl,TA=D(()=>{"use strict";wA(),_A(),vA(),xA(),$A(),Sl={encoding:Gv,fragcolor:Hv,vec:Kv,shapeUtils:Wv,coordinates:qv}}),Xv,SA=D(()=>{"use strict";Pr(),mA(),TA(),Ke(),Xv=class{constructor(e,t,n,i){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new Dw(e,t,n,i),Object.keys(Sl).forEach(l=>{let d=new Sl[l](this.context);this.libs[l]=d});let u=this.glslLibRoutineDependencyGraph;for(let l in this.libs){let d=this.libs[l].getFunctions();for(let c in d){let s=l+"."+c,r;u[s]?(r=u[s],r.routineBody=d[c].routineBody):(r=new dl(s,d[c].routineBody),u[s]=r);let o=d[c].dependencies;if(o)for(let a=0;a{"use strict";IA(),OA(),EA(),AA(),kA(),El={encoding:Zv,fragcolor:Yv,vec:Qv,shapeUtils:Jv,coordinates:Xv}}),ex,CA=D(()=>{"use strict";Pr(),xA(),PA(),Ke(),ex=class{constructor(e,t,n,i){this.libs={},this.glslLibRoutineDependencyGraph={},this.context=new Fw(e,t,n,i),Object.keys(El).forEach(l=>{let d=new El[l](this.context);this.libs[l]=d});let u=this.glslLibRoutineDependencyGraph;for(let l in this.libs){let d=this.libs[l].getFunctions();for(let c in d){let s=l+"."+c,r;u[s]?(r=u[s],r.routineBody=d[c].routineBody):(r=new hl(s,d[c].routineBody),u[s]=r);let o=d[c].dependencies;if(o)for(let a=0;a{let i=n.split(".")[1];e.indexOf(i)!==-1&&t.push(this.glslLibRoutineDependencyGraph[n])}),Mw.returnOrderedNodes(t)}getUniforms(e,t){let n=[];if(e)for(let i of e)n.push(`uniform sampler2D ${i};`);if(t)for(let i of t)n.push(`uniform ${i.type} ${i.name}${i.arrayLength?`[${i.arrayLength}]`:""};`);return n.join(` -`)}}}),Zv,IA=D(()=>{"use strict";dt(),qt(),SA(),Ke(),Zv=class{constructor(e,t,n){this.profiler=e,this.glContext=t,this.textureLayoutStrategy=n,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n){this.profiler.event("op",`ProgramManager.run ${e.programInfo.name??"unknown kernel"}`,()=>{let i=this.glContext.gl,u=e.program;i.useProgram(u);try{this.bindOutput(n),this.attributesBound||this.bindAttributes(e.attribLocations),this.bindUniforms(e.uniformLocations,e.programInfo.variables??[],t)}catch(l){throw Je.error("ProgramManager",e.programInfo.shaderSource),l}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach(e=>this.glContext.deleteProgram(e.program))}build(e,t,n){return this.profiler.event("backend","ProgramManager.build",()=>{let i=new Xv(this.glContext,e,t,n),u=i.preprocess(),l=this.compile(u);return{programInfo:e,program:l,uniformLocations:this.getUniformLocations(l,i.context.programInfo.inputNames,i.context.programInfo.variables),attribLocations:this.getAttribLocations(l)}})}compile(e){if(!this.vertexShader){Je.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");let i=NO(this.glContext.version);this.vertexShader=this.glContext.compileShader(i,this.glContext.gl.VERTEX_SHADER)}me.debug&&Je.verbose("ProrgramManager",`FragShader: +`;else throw new Error(`Missing body for the Glsl Library routine: ${t[i].name}`);return n}selectGlslLibRoutinesToBeIncluded(e){let t=[];return Object.keys(this.glslLibRoutineDependencyGraph).forEach(n=>{let i=n.split(".")[1];e.indexOf(i)!==-1&&t.push(this.glslLibRoutineDependencyGraph[n])}),Lw.returnOrderedNodes(t)}getUniforms(e,t){let n=[];if(e)for(let i of e)n.push(`uniform sampler2D ${i};`);if(t)for(let i of t)n.push(`uniform ${i.type} ${i.name}${i.arrayLength?`[${i.arrayLength}]`:""};`);return n.join(` +`)}}}),tx,RA=D(()=>{"use strict";dt(),Gt(),CA(),Ke(),tx=class{constructor(e,t,n){this.profiler=e,this.glContext=t,this.textureLayoutStrategy=n,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n){this.profiler.event("op",`ProgramManager.run ${e.programInfo.name??"unknown kernel"}`,()=>{let i=this.glContext.gl,u=e.program;i.useProgram(u);try{this.bindOutput(n),this.attributesBound||this.bindAttributes(e.attribLocations),this.bindUniforms(e.uniformLocations,e.programInfo.variables??[],t)}catch(l){throw Je.error("ProgramManager",e.programInfo.shaderSource),l}this.profiler.event("backend","GlContext.draw()",()=>{this.glContext.draw()})},this.glContext)}dispose(){this.vertexShader&&this.glContext.deleteShader(this.vertexShader),this.repo.forEach(e=>this.glContext.deleteProgram(e.program))}build(e,t,n){return this.profiler.event("backend","ProgramManager.build",()=>{let i=new ex(this.glContext,e,t,n),u=i.preprocess(),l=this.compile(u);return{programInfo:e,program:l,uniformLocations:this.getUniformLocations(l,i.context.programInfo.inputNames,i.context.programInfo.variables),attribLocations:this.getAttribLocations(l)}})}compile(e){if(!this.vertexShader){Je.verbose("ProrgramManager","Compiling and caching Vertex shader for the first time");let i=VO(this.glContext.version);this.vertexShader=this.glContext.compileShader(i,this.glContext.gl.VERTEX_SHADER)}me.debug&&Je.verbose("ProrgramManager",`FragShader: ${e} -`);let t=this.glContext.compileShader(e,this.glContext.gl.FRAGMENT_SHADER),n=this.glContext.createProgram(this.vertexShader,t);return this.glContext.deleteShader(t),n}bindOutput(e){let t=e.width,n=e.height;Je.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${t}/${n}, shape=${e.shape}, type=${e.tensor.type}`),this.glContext.attachFramebuffer(e.texture,t,n)}bindAttributes(e){let t=e.position,n=e.textureCoord;this.glContext.setVertexAttributes(t,n),this.attributesBound=!0}bindUniforms(e,t,n){let i=this.glContext.gl,u=0;for(let{name:l,type:d,location:c,arrayLength:s}of e){let r=t.find(o=>o.name===l)?.data;if(d!=="sampler2D"&&!r)throw new Error(`variable '${l}' does not have data defined in program info`);switch(d){case"sampler2D":this.bindTexture(n[u],c,u),u++;break;case"float":s?i.uniform1fv(c,r):i.uniform1f(c,r);break;case"int":s?i.uniform1iv(c,r):i.uniform1i(c,r);break;default:throw new Error(`Uniform not implemented: ${d}`)}}}bindTexture(e,t,n){this.glContext.bindTextureToUniform(e.texture,n,t)}getAttribLocations(e){return{position:this.getAttribLocation(e,"position"),textureCoord:this.getAttribLocation(e,"textureCoord")}}getUniformLocations(e,t,n){let i=[];if(t)for(let u of t)i.push({name:u,type:"sampler2D",location:this.getUniformLocation(e,u)});if(n)for(let u of n)i.push({...u,location:this.getUniformLocation(e,u.name)});return i}getUniformLocation(e,t){let n=this.glContext.gl.getUniformLocation(e,t);if(n===null)throw new Error(`Uniform ${t} not found.`);return n}getAttribLocation(e,t){return this.glContext.gl.getAttribLocation(e,t)}}}),Yv,OA=D(()=>{"use strict";qt(),Vo(),Yv=class{constructor(e,t,n,i){this.glContext=e,this.layoutStrategy=t,this.profiler=n,this.config=i,this.pendingRead=new Map,i.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(e,t,n,i){let u=this.toEncoderType(e),l=this.glContext.getEncoder(u,t.channels||1,i);if(t.isPacked&&i===1)throw new Error("not implemented");let d=t.width,c=t.height,s,r;if(this.config.reuseTextures){s=`${d}x${c}_${l.format}_${l.internalFormat}_${l.textureType}`,r=this.inUseTextures.get(s),r||(r=[],this.inUseTextures.set(s,r));let a=this.idleTextures.get(s);if(a&&a.length>0){let p=a.pop();return r.push(p),i===1&&this.glContext.updateTexture(p,d,c,l,this.toTextureData(e,n)),p}}Je.verbose("TextureManager",`Creating new texture of size ${t.width}x${t.height}`);let o=this.glContext.allocateTexture(d,c,l,this.toTextureData(e,n));return this.config.reuseTextures&&(r.push(o),this.textureLookup.set(o,s)),o}readTexture(e,t,n){return n||(n=1),this.profiler.event("backend","TextureManager.readTexture",()=>{let i=e.shape.reduce((l,d)=>l*d)*n,u=this.glContext.readTexture(e.texture,e.width,e.height,i,this.toEncoderType(t),n);return this.toTensorData(t,u)})}async readTextureAsync(e,t,n){let i=e.tensor.dataId;if(n||(n=1),this.pendingRead.has(i)){let u=this.pendingRead.get(i);return new Promise(l=>u?.push(l))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(i,[]);let u=e.shape.reduce((s,r)=>s*r)*n;await this.glContext.createAndWaitForFence();let l=this.glContext.readTexture(e.texture,e.width,e.height,u,this.toEncoderType(t),n),d=this.toTensorData(t,l),c=this.pendingRead.get(i);return this.pendingRead.delete(i),c?.forEach(s=>s(d)),d})}readUint8TextureAsFloat(e){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{let t=e.shape.reduce((i,u)=>i*u),n=this.glContext.readTexture(e.texture,e.width,e.height,t*4,"byte",4);return new Float32Array(n.buffer,n.byteOffset,t)})}releaseTexture(e,t){let n;if(this.config.reuseTextures&&(n=this.textureLookup.get(e.texture),n)){t&&this.textureLookup.delete(n);let i=this.inUseTextures.get(n);if(i){let u=i.indexOf(e.texture);if(u!==-1){i.splice(u,1);let l=this.idleTextures.get(n);l||(l=[],this.idleTextures.set(n,l)),l.push(e.texture)}}}(!n||t)&&(Je.verbose("TextureManager",`Deleting texture of size ${e.width}x${e.height}`),this.glContext.deleteTexture(e.texture))}toTensorData(e,t){switch(e){case"int16":return t instanceof Int16Array?t:Int16Array.from(t);case"int32":return t instanceof Int32Array?t:Int32Array.from(t);case"int8":return t instanceof Int8Array?t:Int8Array.from(t);case"uint16":return t instanceof Uint16Array?t:Uint16Array.from(t);case"uint32":return t instanceof Uint32Array?t:Uint32Array.from(t);case"uint8":case"bool":return t instanceof Uint8Array?t:Uint8Array.from(t);case"float32":return t instanceof Float32Array?t:Float32Array.from(t);case"float64":return t instanceof Float64Array?t:Float64Array.from(t);default:throw new Error(`TensorData type ${e} is not supported`)}}toTextureData(e,t){if(t)return t instanceof Float32Array?t:new Float32Array(t)}toEncoderType(e){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}}),Jv,EA=D(()=>{"use strict";qt(),z3(),QO(),hA(),IA(),Vv(),OA(),Jv=class{constructor(e,t){this.backend=e,this.context=t,this.layoutStrategy=new Uv(e.glContext.maxTextureSize),this.programManager=new Zv(this.context.profiler,e.glContext,this.layoutStrategy),this.textureManager=new Yv(e.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:e.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=e.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new Pw(this)}onGraphInitialized(e){let t=e.getValues().filter(n=>n.from===-1&&n.tensor).map(n=>n.tensor.dataId);this.initializers=new Set(t)}isInitializer(e){return this.initializers?this.initializers.has(e):!1}addInitializer(e){this.initializers.add(e)}getTextureData(e,t){return t?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,t,n=!1){Je.verbose("WebGLSessionHandler","Storing Texture data in cache"),n?this.packedTextureDataCache.set(e,t):this.unpackedTextureDataCache.set(e,t)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.textureManager.releaseTexture(e,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.textureManager.releaseTexture(e,!0)),this.unpackedTextureDataCache=new Map}resolve(e,t,n){let i=M3(e,t,Lv);return{impl:i.opImpl,context:i.opInit?i.opInit(e,n):e}}}});function AA(e){let t=0;for(;t{"use strict";dt(),Vo(),Vo(),ar(),Il=class{constructor(e,t){this.frameBufferBound=!1,this.itemsToPoll=[],this.gl=e,this.version=t,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(e,t,n,i){let u=this.gl,l=u.createTexture();u.bindTexture(u.TEXTURE_2D,l),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MIN_FILTER,u.NEAREST),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MAG_FILTER,u.NEAREST),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE);let d=i?n.encode(i,e*t):null;return u.texImage2D(u.TEXTURE_2D,0,n.internalFormat,e,t,0,n.format,n.textureType,d),this.checkError(),l}updateTexture(e,t,n,i,u){let l=this.gl;l.bindTexture(l.TEXTURE_2D,e);let d=i.encode(u,t*n);l.texSubImage2D(l.TEXTURE_2D,0,0,0,t,n,i.format,i.textureType,d),this.checkError()}attachFramebuffer(e,t,n){let i=this.gl;i.bindTexture(i.TEXTURE_2D,e),i.bindFramebuffer(i.FRAMEBUFFER,this.framebuffer),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,e,0),this.checkError(),i.viewport(0,0,t,n),i.scissor(0,0,t,n)}readTexture(e,t,n,i,u,l){let d=this.gl;l||(l=1),this.frameBufferBound||this.attachFramebuffer(e,t,n);let c=this.getEncoder(u,l),s=c.allocate(t*n);return d.bindTexture(d.TEXTURE_2D,e),d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,e,0),d.readPixels(0,0,t,n,d.RGBA,c.textureType,s),this.checkError(),c.decode(s,i)}isFramebufferReady(){return!0}getActiveTexture(){let e=this.gl;return`TEXTURE${e.getParameter(this.gl.ACTIVE_TEXTURE)-e.TEXTURE0}`}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(e,t){let n=this.gl;n.vertexAttribPointer(e,3,n.FLOAT,!1,20,0),n.enableVertexAttribArray(e),t!==-1&&(n.vertexAttribPointer(t,2,n.FLOAT,!1,20,12),n.enableVertexAttribArray(t)),this.checkError()}createProgram(e,t){let n=this.gl,i=n.createProgram();return n.attachShader(i,e),n.attachShader(i,t),n.linkProgram(i),i}compileShader(e,t){let n=this.gl,i=n.createShader(t);if(!i)throw new Error(`createShader() returned null with type ${t}`);if(n.shaderSource(i,e),n.compileShader(i),n.getShaderParameter(i,n.COMPILE_STATUS)===!1)throw new Error(`Failed to compile shader: ${n.getShaderInfoLog(i)} +`);let t=this.glContext.compileShader(e,this.glContext.gl.FRAGMENT_SHADER),n=this.glContext.createProgram(this.vertexShader,t);return this.glContext.deleteShader(t),n}bindOutput(e){let t=e.width,n=e.height;Je.verbose("ProrgramManager",`Binding output texture to Framebuffer: w/h=${t}/${n}, shape=${e.shape}, type=${e.tensor.type}`),this.glContext.attachFramebuffer(e.texture,t,n)}bindAttributes(e){let t=e.position,n=e.textureCoord;this.glContext.setVertexAttributes(t,n),this.attributesBound=!0}bindUniforms(e,t,n){let i=this.glContext.gl,u=0;for(let{name:l,type:d,location:c,arrayLength:s}of e){let r=t.find(o=>o.name===l)?.data;if(d!=="sampler2D"&&!r)throw new Error(`variable '${l}' does not have data defined in program info`);switch(d){case"sampler2D":this.bindTexture(n[u],c,u),u++;break;case"float":s?i.uniform1fv(c,r):i.uniform1f(c,r);break;case"int":s?i.uniform1iv(c,r):i.uniform1i(c,r);break;default:throw new Error(`Uniform not implemented: ${d}`)}}}bindTexture(e,t,n){this.glContext.bindTextureToUniform(e.texture,n,t)}getAttribLocations(e){return{position:this.getAttribLocation(e,"position"),textureCoord:this.getAttribLocation(e,"textureCoord")}}getUniformLocations(e,t,n){let i=[];if(t)for(let u of t)i.push({name:u,type:"sampler2D",location:this.getUniformLocation(e,u)});if(n)for(let u of n)i.push({...u,location:this.getUniformLocation(e,u.name)});return i}getUniformLocation(e,t){let n=this.glContext.gl.getUniformLocation(e,t);if(n===null)throw new Error(`Uniform ${t} not found.`);return n}getAttribLocation(e,t){return this.glContext.gl.getAttribLocation(e,t)}}}),rx,DA=D(()=>{"use strict";Gt(),qo(),rx=class{constructor(e,t,n,i){this.glContext=e,this.layoutStrategy=t,this.profiler=n,this.config=i,this.pendingRead=new Map,i.reuseTextures&&(this.inUseTextures=new Map,this.idleTextures=new Map,this.textureLookup=new Map)}createTextureFromLayout(e,t,n,i){let u=this.toEncoderType(e),l=this.glContext.getEncoder(u,t.channels||1,i);if(t.isPacked&&i===1)throw new Error("not implemented");let d=t.width,c=t.height,s,r;if(this.config.reuseTextures){s=`${d}x${c}_${l.format}_${l.internalFormat}_${l.textureType}`,r=this.inUseTextures.get(s),r||(r=[],this.inUseTextures.set(s,r));let a=this.idleTextures.get(s);if(a&&a.length>0){let p=a.pop();return r.push(p),i===1&&this.glContext.updateTexture(p,d,c,l,this.toTextureData(e,n)),p}}Je.verbose("TextureManager",`Creating new texture of size ${t.width}x${t.height}`);let o=this.glContext.allocateTexture(d,c,l,this.toTextureData(e,n));return this.config.reuseTextures&&(r.push(o),this.textureLookup.set(o,s)),o}readTexture(e,t,n){return n||(n=1),this.profiler.event("backend","TextureManager.readTexture",()=>{let i=e.shape.reduce((l,d)=>l*d)*n,u=this.glContext.readTexture(e.texture,e.width,e.height,i,this.toEncoderType(t),n);return this.toTensorData(t,u)})}async readTextureAsync(e,t,n){let i=e.tensor.dataId;if(n||(n=1),this.pendingRead.has(i)){let u=this.pendingRead.get(i);return new Promise(l=>u?.push(l))}return this.profiler.event("backend","TextureManager.readTextureAsync",async()=>{this.pendingRead.set(i,[]);let u=e.shape.reduce((s,r)=>s*r)*n;await this.glContext.createAndWaitForFence();let l=this.glContext.readTexture(e.texture,e.width,e.height,u,this.toEncoderType(t),n),d=this.toTensorData(t,l),c=this.pendingRead.get(i);return this.pendingRead.delete(i),c?.forEach(s=>s(d)),d})}readUint8TextureAsFloat(e){return this.profiler.event("backend","TextureManager.readUint8TextureAsFloat",()=>{let t=e.shape.reduce((i,u)=>i*u),n=this.glContext.readTexture(e.texture,e.width,e.height,t*4,"byte",4);return new Float32Array(n.buffer,n.byteOffset,t)})}releaseTexture(e,t){let n;if(this.config.reuseTextures&&(n=this.textureLookup.get(e.texture),n)){t&&this.textureLookup.delete(n);let i=this.inUseTextures.get(n);if(i){let u=i.indexOf(e.texture);if(u!==-1){i.splice(u,1);let l=this.idleTextures.get(n);l||(l=[],this.idleTextures.set(n,l)),l.push(e.texture)}}}(!n||t)&&(Je.verbose("TextureManager",`Deleting texture of size ${e.width}x${e.height}`),this.glContext.deleteTexture(e.texture))}toTensorData(e,t){switch(e){case"int16":return t instanceof Int16Array?t:Int16Array.from(t);case"int32":return t instanceof Int32Array?t:Int32Array.from(t);case"int8":return t instanceof Int8Array?t:Int8Array.from(t);case"uint16":return t instanceof Uint16Array?t:Uint16Array.from(t);case"uint32":return t instanceof Uint32Array?t:Uint32Array.from(t);case"uint8":case"bool":return t instanceof Uint8Array?t:Uint8Array.from(t);case"float32":return t instanceof Float32Array?t:Float32Array.from(t);case"float64":return t instanceof Float64Array?t:Float64Array.from(t);default:throw new Error(`TensorData type ${e} is not supported`)}}toTextureData(e,t){if(t)return t instanceof Float32Array?t:new Float32Array(t)}toEncoderType(e){return"float"}clearActiveTextures(){this.glContext.clearActiveTextures()}}}),nx,MA=D(()=>{"use strict";Gt(),G3(),sE(),_A(),RA(),Kv(),DA(),nx=class{constructor(e,t){this.backend=e,this.context=t,this.layoutStrategy=new Wv(e.glContext.maxTextureSize),this.programManager=new tx(this.context.profiler,e.glContext,this.layoutStrategy),this.textureManager=new rx(e.glContext,this.layoutStrategy,this.context.profiler,{reuseTextures:e.textureCacheMode==="full"}),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache=new Map,this.pack=e.pack,this.pack2unpackMap=new Map,this.unpack2packMap=new Map}createInferenceHandler(){return new Nw(this)}onGraphInitialized(e){let t=e.getValues().filter(n=>n.from===-1&&n.tensor).map(n=>n.tensor.dataId);this.initializers=new Set(t)}isInitializer(e){return this.initializers?this.initializers.has(e):!1}addInitializer(e){this.initializers.add(e)}getTextureData(e,t){return t?this.packedTextureDataCache.get(e):this.unpackedTextureDataCache.get(e)}setTextureData(e,t,n=!1){Je.verbose("WebGLSessionHandler","Storing Texture data in cache"),n?this.packedTextureDataCache.set(e,t):this.unpackedTextureDataCache.set(e,t)}dispose(){this.programManager.dispose(),this.textureManager.clearActiveTextures(),this.packedTextureDataCache.forEach(e=>this.textureManager.releaseTexture(e,!0)),this.packedTextureDataCache=new Map,this.unpackedTextureDataCache.forEach(e=>this.textureManager.releaseTexture(e,!0)),this.unpackedTextureDataCache=new Map}resolve(e,t,n){let i=U3(e,t,qv);return{impl:i.opImpl,context:i.opInit?i.opInit(e,n):e}}}});function NA(e){let t=0;for(;t{"use strict";dt(),qo(),qo(),ar(),Al=class{constructor(e,t){this.frameBufferBound=!1,this.itemsToPoll=[],this.gl=e,this.version=t,this.getExtensions(),this.vertexbuffer=this.createVertexbuffer(),this.framebuffer=this.createFramebuffer(),this.queryVitalParameters()}allocateTexture(e,t,n,i){let u=this.gl,l=u.createTexture();u.bindTexture(u.TEXTURE_2D,l),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MIN_FILTER,u.NEAREST),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_MAG_FILTER,u.NEAREST),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_S,u.CLAMP_TO_EDGE),u.texParameteri(u.TEXTURE_2D,u.TEXTURE_WRAP_T,u.CLAMP_TO_EDGE);let d=i?n.encode(i,e*t):null;return u.texImage2D(u.TEXTURE_2D,0,n.internalFormat,e,t,0,n.format,n.textureType,d),this.checkError(),l}updateTexture(e,t,n,i,u){let l=this.gl;l.bindTexture(l.TEXTURE_2D,e);let d=i.encode(u,t*n);l.texSubImage2D(l.TEXTURE_2D,0,0,0,t,n,i.format,i.textureType,d),this.checkError()}attachFramebuffer(e,t,n){let i=this.gl;i.bindTexture(i.TEXTURE_2D,e),i.bindFramebuffer(i.FRAMEBUFFER,this.framebuffer),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,e,0),this.checkError(),i.viewport(0,0,t,n),i.scissor(0,0,t,n)}readTexture(e,t,n,i,u,l){let d=this.gl;l||(l=1),this.frameBufferBound||this.attachFramebuffer(e,t,n);let c=this.getEncoder(u,l),s=c.allocate(t*n);return d.bindTexture(d.TEXTURE_2D,e),d.framebufferTexture2D(d.FRAMEBUFFER,d.COLOR_ATTACHMENT0,d.TEXTURE_2D,e,0),d.readPixels(0,0,t,n,d.RGBA,c.textureType,s),this.checkError(),c.decode(s,i)}isFramebufferReady(){return!0}getActiveTexture(){let e=this.gl;return`TEXTURE${e.getParameter(this.gl.ACTIVE_TEXTURE)-e.TEXTURE0}`}getTextureBinding(){return this.gl.getParameter(this.gl.TEXTURE_BINDING_2D)}getFramebufferBinding(){return this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING)}setVertexAttributes(e,t){let n=this.gl;n.vertexAttribPointer(e,3,n.FLOAT,!1,20,0),n.enableVertexAttribArray(e),t!==-1&&(n.vertexAttribPointer(t,2,n.FLOAT,!1,20,12),n.enableVertexAttribArray(t)),this.checkError()}createProgram(e,t){let n=this.gl,i=n.createProgram();return n.attachShader(i,e),n.attachShader(i,t),n.linkProgram(i),i}compileShader(e,t){let n=this.gl,i=n.createShader(t);if(!i)throw new Error(`createShader() returned null with type ${t}`);if(n.shaderSource(i,e),n.compileShader(i),n.getShaderParameter(i,n.COMPILE_STATUS)===!1)throw new Error(`Failed to compile shader: ${n.getShaderInfoLog(i)} Shader source: -${e}`);return i}deleteShader(e){this.gl.deleteShader(e)}bindTextureToUniform(e,t,n){let i=this.gl;i.activeTexture(i.TEXTURE0+t),this.checkError(),i.bindTexture(i.TEXTURE_2D,e),this.checkError(),i.uniform1i(n,t),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(me.debug){let e=this.gl,t=e.getError(),n="";switch(t){case e.NO_ERROR:return;case e.INVALID_ENUM:n="INVALID_ENUM";break;case e.INVALID_VALUE:n="INVALID_VALUE";break;case e.INVALID_OPERATION:n="INVALID_OPERATION";break;case e.INVALID_FRAMEBUFFER_OPERATION:n="INVALID_FRAMEBUFFER_OPERATION";break;case e.OUT_OF_MEMORY:n="OUT_OF_MEMORY";break;case e.CONTEXT_LOST_WEBGL:n="CONTEXT_LOST_WEBGL";break;default:n=`Unknown WebGL Error: ${t.toString(16)}`}throw new Error(n)}}deleteTexture(e){this.gl.deleteTexture(e)}deleteProgram(e){this.gl.deleteProgram(e)}getEncoder(e,t,n=0){if(this.version===2)return new Ew(this.gl,t);switch(e){case"float":return n===1||this.isRenderFloat32Supported?new ul(this.gl,t):new ul(this.gl,t,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new Aw(this.gl,t);default:throw new Error(`Invalid dataType: ${e}`)}}clearActiveTextures(){let e=this.gl;for(let t=0;tthis.isTimerResultAvailable(e)),this.getTimerResult(e)}async createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n=e,i=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),i===null?t=()=>!0:t=()=>{let u=n.clientWaitSync(i,0,0);return u===n.ALREADY_SIGNALED||u===n.CONDITION_SATISFIED},{query:i,isFencePassed:t}}async pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=AA(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}async addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),!(this.itemsToPoll.length>1)&&await fh(()=>(this.pollItems(),this.itemsToPoll.length===0))}}});function Qv(e){let t;if((!e||e==="webgl2")&&"webgl2"in sn?t=sn.webgl2:(!e||e==="webgl")&&"webgl"in sn&&(t=sn.webgl),!t)try{let i=CA();t=ym(i,e)}catch{let i=PA();t=ym(i,e)}e=e||t.version===1?"webgl":"webgl2";let n=t.gl;return sn[e]=t,n.isContextLost()?(delete sn[e],Qv(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),t)}function ym(e,t){let n={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1},i,u=n;if((!t||t==="webgl2")&&(i=e.getContext("webgl2",u),i))try{return new Il(i,2)}catch(l){Je.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${l}`)}if((!t||t==="webgl")&&(i=e.getContext("webgl",u)||e.getContext("experimental-webgl",u),i))try{return new Il(i,1)}catch(l){Je.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${l}`)}throw new Error("WebGL is not supported")}function PA(){if(typeof document>"u")throw new TypeError("failed to create canvas: document is not supported");let e=document.createElement("canvas");return e.width=1,e.height=1,e}function CA(){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}var sn,RA=D(()=>{"use strict";qt(),kA(),sn={}}),ex,DA=D(()=>{"use strict";dt(),qt(),EA(),RA(),ex=class{get contextId(){return me.webgl.contextId}set contextId(e){me.webgl.contextId=e}get matmulMaxBatchSize(){return me.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(e){me.webgl.matmulMaxBatchSize=e}get textureCacheMode(){return me.webgl.textureCacheMode}set textureCacheMode(e){me.webgl.textureCacheMode=e}get pack(){return me.webgl.pack}set pack(e){me.webgl.pack=e}get async(){return me.webgl.async}set async(e){me.webgl.async=e}initialize(){try{return this.glContext=Qv(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),Je.setWithEnv(me),me.webgl.context||Object.defineProperty(me.webgl,"context",{value:this.glContext.gl}),Je.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(e){return Je.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${e}`),!1}}createSessionHandler(e){return new Jv(this,e)}dispose(){this.glContext.dispose()}}});async function tx(e){if(e){let t=typeof e=="string"?[e]:e;for(let n of t){let i=ed.get(n);if(i)return i;let u=await MA(n);if(u)return u}}else return tx(["webgl"]);throw new Error("no available backend to use")}async function MA(e){let t=rx;if(typeof t[e]<"u"&&NA(t[e])){let n=t[e],i=n.initialize();if(typeof i=="object"&&"then"in i&&(i=await i),i)return ed.set(e,n),n}}function NA(e){let t=e;return"initialize"in t&&typeof t.initialize=="function"&&"createSessionHandler"in t&&typeof t.createSessionHandler=="function"&&"dispose"in t&&typeof t.dispose=="function"}var ed,rx,zA=D(()=>{"use strict";DA(),ed=new Map,rx={webgl:new ex}}),wm,nx,BA=D(()=>{"use strict";qt(),wm=class{constructor(e,t){this.op=e,this.node=t}},nx=class{constructor(e,t,n){this.graph=e,this.profiler=n,this.initialize(t)}initialize(e){this.profiler.event("session","ExecutionPlan.initialize",()=>{let t=this.graph.getNodes();if(t.length!==e.length)throw new Error("The size of nodes and OPs do not match.");this._ops=e.map((n,i)=>new wm(n,t[i])),this.reset(),this._starter=[],this._ops.forEach((n,i)=>{let u=!0;for(let l of n.node.inputs)if(!this._values[l]&&this.graph.getInputIndices().indexOf(l)===-1){u=!1;break}u&&this._starter.push(i)})})}reset(){this._values=this.graph.getValues().map(e=>e.tensor)}async execute(e,t){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();let n=e.createInferenceHandler(),i=this.graph.getInputIndices();if(t.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${t.length} expected: ${i.length}`);t.forEach((r,o)=>{let a=i[o];this._values[a]=r});let u=this._starter.slice(0),l=this.graph.getValues(),d=this.graph.getNodes(),c=0;for(;cthis._values[g]);if(a.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${o.node}`);let p=a;Je.verbose("ExecPlan",`Running op:${o.node.name} (${p.map((g,_)=>`'${o.node.inputs[_]}': ${g.type}[${g.dims.join(",")}]`).join(", ")})`);let h=await this.profiler.event("node",o.node.name,async()=>o.op.impl(n,p,o.op.context));if(h.length!==o.node.outputs.length)throw new Error("the size of output does not match model definition.");h.forEach((g,_)=>{let w=o.node.outputs[_];if(this._values[w])throw new Error(`output [${w}] already has value: op:${o.node.name}`);this._values[w]=g});let m=new Set;h.forEach((g,_)=>{let w=o.node.outputs[_];for(let y of l[w].to){let T=d[y],S=!0;for(let O of T.inputs)if(!this._values[O]){S=!1;break}S&&m.add(y)}}),u.push(...m)}let s=[];for(let r=0;r{"use strict";ns(),Se=be(Ni()),Ln(),Me(),Ol=class Ti{constructor(t){if(this._attributes=new Map,t!=null){for(let n of t)n instanceof Se.onnx.AttributeProto?this._attributes.set(n.name,[Ti.getValue(n),Ti.getType(n)]):n instanceof rl.Attribute&&this._attributes.set(n.name(),[Ti.getValue(n),Ti.getType(n)]);if(this._attributes.sizext.fromProto(u));if(t instanceof rl.Attribute)return i.map(u=>xt.fromOrtTensor(u))}return n===Se.onnx.AttributeProto.AttributeType.STRING&&t instanceof Se.onnx.AttributeProto?nl(i):n===Se.onnx.AttributeProto.AttributeType.STRINGS&&t instanceof Se.onnx.AttributeProto?i.map(nl):i}static getValueNoCheck(t){return t instanceof Se.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(t):this.getValueNoCheckFromOrtFormat(t)}static getValueNoCheckFromOnnxFormat(t){switch(t.type){case Se.onnx.AttributeProto.AttributeType.FLOAT:return t.f;case Se.onnx.AttributeProto.AttributeType.INT:return t.i;case Se.onnx.AttributeProto.AttributeType.STRING:return t.s;case Se.onnx.AttributeProto.AttributeType.TENSOR:return t.t;case Se.onnx.AttributeProto.AttributeType.GRAPH:return t.g;case Se.onnx.AttributeProto.AttributeType.FLOATS:return t.floats;case Se.onnx.AttributeProto.AttributeType.INTS:return t.ints;case Se.onnx.AttributeProto.AttributeType.STRINGS:return t.strings;case Se.onnx.AttributeProto.AttributeType.TENSORS:return t.tensors;case Se.onnx.AttributeProto.AttributeType.GRAPHS:return t.graphs;default:throw new Error(`unsupported attribute type: ${Se.onnx.AttributeProto.AttributeType[t.type]}`)}}static getValueNoCheckFromOrtFormat(t){switch(t.type()){case jt.AttributeType.FLOAT:return t.f();case jt.AttributeType.INT:return t.i();case jt.AttributeType.STRING:return t.s();case jt.AttributeType.TENSOR:return t.t();case jt.AttributeType.GRAPH:return t.g();case jt.AttributeType.FLOATS:return t.floatsArray();case jt.AttributeType.INTS:{let n=[];for(let i=0;i{"use strict";FA(),ns(),Ba=be(Ni()),Ln(),Me(),El={from:(e,t)=>new _m(e,t)},nr=class{constructor(e){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,e&&(this.type=wt.tensorValueTypeFromProto(e.type.tensorType))}get from(){return this._from}get to(){return this._to}},Fa=class{constructor(e,t){e instanceof Ba.onnx.NodeProto?(this.name=e.name,this.opType=e.opType,this.attributes=new Ol(e.attribute)):e instanceof mw.Node&&(this.name=t??e.name(),this.opType=e.opType(),this.attributes=new Ol(wt.tensorAttributesFromORTFormat(e))),this.inputs=[],this.outputs=[],this.executeNode=!0}},_m=class{constructor(e,t){if(!e)throw new TypeError("graph is empty");this.buildGraph(e),this.transformGraph(t),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(e){if(e instanceof Ba.onnx.GraphProto)this.buildGraphFromOnnxFormat(e);else if(e instanceof hw.Graph)this.buildGraphFromOrtFormat(e);else throw new TypeError("Graph type is not supported.")}buildGraphFromOnnxFormat(e){let t=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let n=new Map;if(!e.input)throw new Error("missing information in graph: input");let i=[];for(let u of e.input){if(t.has(u.name))throw new Error(`duplicated input name: ${u.name}`);let l=this._allData.push(new nr(u))-1;t.set(u.name,l),i.push(u.name)}if(!e.initializer)throw new Error("missing information in graph: initializer");for(let u of e.initializer){let l=t.get(u.name);if(l===void 0){let d=new nr;d.type={shape:{dims:wt.tensorDimsFromProto(u.dims)},tensorType:wt.tensorDataTypeFromProto(u.dataType)},l=this._allData.push(d)-1,t.set(u.name,l)}this._allData[l]._from=-1,this._allData[l].tensor=xt.fromProto(u)}for(let u=0;u"u"&&(s=this._allData.push(new nr)-1,t.set(c,s)),l.outputs.push(s),this._allData[s]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${s}`);if(this._allData[s]._from=u,d.opType==="Constant"){if(!d.attribute||d.attribute.length!==1||!d.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!d.output||d.output.length!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");l.outputs.pop(),l.executeNode=!1,this._allData[s]._from=-1,this._allData[s].tensor=xt.fromProto(d.attribute[0].t)}}}for(let u=0;u"u"){if(c===""&&(d.input.length===3||d.input.length===4)&&d.opType==="Resize")continue;throw new Error(`unrecognized input '${c}' for node: ${d.name}`)}l.inputs.push(s),this._allData[s]._to.push(u)}}return!0}buildGraphFromOrtFormat(e){let t=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let n=new Map,i=[];for(let u=0;u"u"&&(r=this._allData.push(new nr)-1,t.set(s,r)),l.outputs.push(r),this._allData[r]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${r}`);if(this._allData[r]._from=u,d.opType()==="Constant"){if(d.attributesLength()!==1||!d.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(d.outputsLength()!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");l.outputs.pop(),l.executeNode=!1,this._allData[r]._from=-1,this._allData[r].tensor=xt.fromOrtTensor(d.attributes(0).t())}}}for(let u=0;u"u")throw new Error(`unrecognized input '${s}' for node: ${d.name()}`);l.inputs.push(r),this._allData[r]._to.push(u)}}}checkIsAcyclic(){let e=new Set;this._allInputIndices.forEach(i=>{this._allData[i]._to.forEach(u=>{e.add(u)})});let t=Array.from(e),n=new Array(this._nodes.length).fill("white");for(;t.length>0;){let i=t.pop();n[i]==="gray"?n[i]="black":(t.push(i),n[i]="gray",this._nodes[i].outputs.forEach(u=>{let l=this._allData[u];if(typeof l.tensor<"u")throw new Error("node outputs should not be initialized");if(l._from!==i)throw new Error("from property of the Value object doesn't match index of Node being processed");l._to.forEach(d=>{if(n[d]==="gray")throw new Error("model graph is cyclic");n[d]==="white"&&t.push(d)})}))}}transformGraph(e){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),e&&e.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let e=0,t=new Array(this._nodes.length,0),n=0;for(let i=0;i{this._allData[u]._from=-2});this._nodes.splice(n,this._nodes.length-n);for(let i=0;i=0)u._to[l]=t[u._to[l]];else throw new Error("Trying to update a removed node")}e=0;for(let i=0;i0){let u=-1;this._allData[i].from!==void 0&&this._allData[i].from!==-1?(u=this._nodes[this._allData[i].from].outputs.indexOf(i+e),u!==-1&&(this._nodes[this._allData[i].from].outputs[u]=i)):(u=this._allInputIndices.indexOf(i+e),u!==-1&&(this._allInputIndices[u]=i)),this._allData[i].to.forEach(l=>{u=this._nodes[l].inputs.indexOf(i+e),u!==-1&&(this._nodes[l].inputs[u]=i)}),this._allData[i].to.length===0&&(u=this._allOutputIndices.indexOf(i+e),u!==-1&&(this._allOutputIndices[u]=i))}}}deleteNode(e){let t=this._nodes[e];if(t.outputs.length>1){for(let d=1;d0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}t.executeNode=!1;let n=t.inputs[0],i=t.outputs[0],u=this._allData[i].to;for(let d=0;d0)for(let d of u){let c=this._nodes[d].inputs.indexOf(i);if(c===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[d].inputs[c]=n,this._allData[n].to.push(d)}}removeAllDropoutNodes(){let e=0;for(let t of this._nodes){if(t.opType==="Dropout"){if(t.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(t.outputs.length!==1&&t.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(t.outputs.length===2&&this._allData[t.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(e)}e++}}removeAllIdentityNodes(){let e=0;for(let t of this._nodes)t.opType==="Identity"&&this.deleteNode(e),e++}isActivation(e){switch(e.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(let e of this._nodes)if(e.opType==="Conv"){let t=this._allData[e.outputs[0]]._to;if(t.length===1&&this.isActivation(this._nodes[t[0]])){let n=this._nodes[t[0]];if(n.opType==="Clip")if(n.inputs.length===1)try{e.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch{e.attributes.set("activation_params","floats",[Ci,Ri])}else if(n.inputs.length>=3&&this._allData[n.inputs[1]].tensor!==void 0&&this._allData[n.inputs[2]].tensor!==void 0)e.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]]);else continue;e.attributes.set("activation","string",n.opType),this.deleteNode(t[0])}}}}}),vm,xm,ix,jA=D(()=>{"use strict";vm=be(De()),LA(),ns(),xm=be(Ni()),Me(),ix=class{constructor(){}load(e,t,n){let i;if(!n)try{this.loadFromOnnxFormat(e,t);return}catch(u){if(n!==void 0)throw u;i=u}try{this.loadFromOrtFormat(e,t)}catch(u){throw n!==void 0?u:new Error(`Failed to load model as ONNX format: ${i} -as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=xm.onnx.ModelProto.decode(e);if(Yt.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map(i=>({domain:i.domain,version:Yt.longToNumber(i.version)})),this._graph=El.from(n.graph,t)}loadFromOrtFormat(e,t){let n=new vm.ByteBuffer(e),i=fw.InferenceSession.getRootAsInferenceSession(n).model();if(Yt.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let u=0;u{"use strict";zA(),BA(),qt(),jA(),ox=class{constructor(e={}){this._initialized=!1,this.backendHint=e.backendHint,this.profiler=A0.create(e.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(e,t,n){await this.profiler.event("session","Session.loadModel",async()=>{let i=await tx(this.backendHint);if(this.sessionHandler=i.createSessionHandler(this.context),this._model=new ix,typeof e=="string"){let u=e.endsWith(".ort");{let l=await(await fetch(e)).arrayBuffer();this.initialize(new Uint8Array(l),u)}}else if(ArrayBuffer.isView(e))this.initialize(e);else{let u=new Uint8Array(e,t||0,n||e.byteLength);this.initialize(u)}})}initialize(e,t){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{let n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(e,n,t),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new nx(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(e){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{let t=this.normalizeAndValidateInputs(e),n=await this._executionPlan.execute(this.sessionHandler,t);return this.createOutput(n)})}normalizeAndValidateInputs(e){let t=this._model.graph.getInputNames();if(Array.isArray(e)){if(e.length!==t.length)throw new Error(`incorrect input array length: expected ${t.length} but got ${e.length}`)}else{if(e.size!==t.length)throw new Error(`incorrect input map size: expected ${t.length} but got ${e.size}`);let n=new Array(e.size),i=0;for(let u=0;u{"use strict";dt(),Ln(),sx=class{constructor(e){this.session=e,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}get inputMetadata(){throw new Error("Getting model metadata is not supported in webgl backend.")}get outputMetadata(){throw new Error("Getting model metadata is not supported in webgl backend.")}async dispose(){}async run(e,t,n){let i=new Map;for(let d in e)if(Object.hasOwnProperty.call(e,d)){let c=e[d];i.set(d,new xt(c.dims,c.type,void 0,void 0,c.data))}let u=await this.session.run(i),l={};return u.forEach((d,c)=>{l[c]=new vt(d.type,d.data,d.dims)}),l}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}}),ax={};wn(ax,{onnxjsBackend:()=>ux});var $m,ux,qA=D(()=>{"use strict";UA(),VA(),$m=class{async init(){}async createInferenceSessionHandler(e,t){let n=new ox(t);return typeof e=="string"?await n.loadModel(e):await n.loadModel(e),new sx(n)}},ux=new $m}),td=D(()=>{"use strict"}),lx={};wn(lx,{default:()=>dx});var La,ja,dx,GA=D(()=>{"use strict";y$(),vn(),rd(),La="ort-wasm-proxy-worker",ja=globalThis.self?.name===La,ja&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":nd(n.wasm).then(()=>{_d(n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:u}=n;vd(u,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=n,u=Yo(i);postMessage({type:t,out:u});break}case"create":{let{model:i,options:u}=n;xd(i,u).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":$d(n),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:u,inputs:l,outputIndices:d,options:c}=n;Td(i,u,l,d,new Array(d.length).fill(null),c).then(s=>{s.some(r=>r[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:s},Id([...l,...s]))},s=>{postMessage({type:t,err:s})});break}case"end-profiling":Sd(n),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),dx=ja?null:e=>new Worker(e??yt,{type:"module",name:La})}),cx={};wn(cx,{default:()=>px});async function Tm(e={}){var t=e,n=!!globalThis.window,i=!!globalThis.WorkerGlobalScope,u=i&&self.name?.startsWith("em-pthread");t.mountExternalData=(f,b)=>{f.startsWith("./")&&(f=f.substring(2)),(t.Yc||(t.Yc=new Map)).set(f,b)},t.unmountExternalData=()=>{delete t.Yc,delete t.Zd,delete t.Yd,delete t.$d},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let l=f=>async(...b)=>{try{if(t.Xc)throw Error("Session already started");let $=t.Xc={Kd:b[0],errors:[]},x=await f(...b);if(t.Xc!==$)throw Error("Session mismatch");t.dd?.flush();let E=$.errors;if(0M),0{if(f==="webgpu"){[t.dd,t.Ad,t.Ed,t.ed,t.Dd,t.$b,t.Fd,t.Hd,t.Bd,t.Cd,t.Gd]=b;let $=t.dd;t.jsepRegisterBuffer=(x,E,k,M)=>$.registerBuffer(x,E,k,M),t.jsepGetBuffer=x=>$.getBuffer(x),t.jsepCreateDownloader=(x,E,k)=>$.createDownloader(x,E,k),t.jsepOnCreateSession=x=>{$.onCreateSession(x)},t.jsepOnReleaseSession=x=>{$.onReleaseSession(x)},t.jsepOnRunStart=x=>$.onRunStart(x),t.Id=(x,E)=>{$.upload(x,E)}}else if(f==="webnn"){let $=b[0];[t.Sd,t.sd,t.webnnEnsureTensor,t.td,t.webnnDownloadTensor,t.Rd,t.webnnEnableTraceEvent]=b.slice(1),t.webnnReleaseTensorId=t.sd,t.webnnUploadTensor=t.td,t.webnnRegisterMLContext=t.Rd,t.webnnOnRunStart=x=>$.onRunStart(x),t.webnnOnRunEnd=$.onRunEnd.bind($),t.webnnOnReleaseSession=x=>{$.onReleaseSession(x)},t.webnnCreateMLTensorDownloader=(x,E)=>$.createMLTensorDownloader(x,E),t.webnnRegisterMLTensor=(x,E,k,M)=>$.registerMLTensor(x,E,k,M),t.webnnCreateMLContext=x=>$.createMLContext(x),t.webnnRegisterGraphInput=$.registerGraphInput.bind($),t.webnnIsGraphInput=$.isGraphInput.bind($),t.webnnRegisterGraphOutput=$.registerGraphOutput.bind($),t.webnnIsGraphOutput=$.isGraphOutput.bind($),t.webnnCreateTemporaryTensor=$.createTemporaryTensor.bind($),t.webnnIsGraphInputOutputTypeSupported=$.isGraphInputOutputTypeSupported.bind($)}};let d=()=>{let f=b=>(...$)=>{let x=Wt;return $=b(...$),Wt!=x?new Promise((E,k)=>{Ks={resolve:E,reject:k}}):$};(()=>{for(let b of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[b]=f(t[b])})(),l!==void 0&&(t._OrtRun=l(t._OrtRun),t._OrtRunWithBinding=l(t._OrtRunWithBinding)),d=void 0};t.asyncInit=()=>{d?.()};var c,s,r=(f,b)=>{throw b},o=import.meta.url,a="";if(n||i){try{a=new URL(".",o).href}catch{}i&&(s=f=>{var b=new XMLHttpRequest;return b.open("GET",f,!1),b.responseType="arraybuffer",b.send(null),new Uint8Array(b.response)}),c=async f=>{if(P(f))return new Promise(($,x)=>{var E=new XMLHttpRequest;E.open("GET",f,!0),E.responseType="arraybuffer",E.onload=()=>{E.status==200||E.status==0&&E.response?$(E.response):x(E.status)},E.onerror=x,E.send(null)});var b=await fetch(f,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url)}}var p,h,m,g,_,w,y=console.log.bind(console),T=console.error.bind(console),S=y,O=T,A=!1,P=f=>f.startsWith("file://");function I(){hr.buffer!=J.buffer&&Y()}if(u){let f=function(b){try{var $=b.data,x=$.Sc;if(x==="load"){let E=[];self.onmessage=k=>E.push(k),w=()=>{postMessage({Sc:"loaded"});for(let k of E)f(k);self.onmessage=f};for(let k of $.xd)t[k]&&!t[k].proxy||(t[k]=(...M)=>{postMessage({Sc:"callHandler",vd:k,args:M})},k=="print"&&(S=t[k]),k=="printErr"&&(O=t[k]));hr=$.Od,Y(),h=$.Pd,re(),bo()}else if(x==="run"){(function(E){var k=(I(),R)[E+52>>>2>>>0];E=(I(),R)[E+56>>>2>>>0],mp(k,k-E),we(k)})($.Rc),Qs($.Rc,0,0,1,0,0),gc(),Gs($.Rc),G||(lp(),G=!0);try{oS($.Md,$.bd)}catch(E){if(E!="unwind")throw E}}else $.target!=="setimmediate"&&(x==="checkMailbox"?G&&lo():x&&(O(`worker: received unknown command ${x}`),O($)))}catch(E){throw dp(),E}};var z=f,G=!1;self.onunhandledrejection=b=>{throw b.reason||b},self.onmessage=f}var J,q,C,ee,v,R,H,L,V,K,B,te=!1;function Y(){var f=hr.buffer;t.HEAP8=J=new Int8Array(f),C=new Int16Array(f),t.HEAPU8=q=new Uint8Array(f),ee=new Uint16Array(f),t.HEAP32=v=new Int32Array(f),t.HEAPU32=R=new Uint32Array(f),H=new Float32Array(f),L=new Float64Array(f),V=new BigInt64Array(f),K=new BigUint64Array(f)}function N(){te=!0,u?w():rr.sb()}function X(f){throw O(f="Aborted("+f+")"),A=!0,f=new WebAssembly.RuntimeError(f+". Build with -sASSERTIONS for more info."),_?.(f),f}function W(){return{a:{ma:kI,hb:AI,g:sS,J:aS,f:uS,o:lS,i:dS,$:cS,b:pS,S:hS,Ia:xc,n:fS,aa:Ic,Ya:Oc,Ea:Ec,Ga:Ac,Za:kc,Wa:Pc,Pa:Cc,Va:Rc,ka:Dc,Fa:Mc,Ca:Nc,Xa:zc,Da:Bc,cb:mS,fa:bS,xa:yS,va:_S,ea:xS,N:$S,H:TS,wa:SS,_:CS,ya:RS,Sa:DS,Aa:NS,Ja:zS,ta:BS,ga:FS,Ra:Gs,$a:LS,Q:qS,r:XS,c:Vs,ib:ZS,y:YS,M:JS,D:QS,l:eI,s:Hc,jb:tI,I:rI,R:nI,j:iI,u:oI,q:sI,k:aI,Ma:uI,Na:lI,Oa:dI,Ka:Zc,La:Yc,ua:Jc,eb:pI,bb:mI,v:gI,ba:bI,ha:yI,ab:hI,V:wI,_a:_I,Ba:vI,F:cI,T:xI,la:mo,za:TI,gb:$I,fb:SI,Ta:rp,Ua:np,Ha:zr,U:ip,ja:op,Qa:sp,ia:ap,lb:p3,na:a3,mb:c3,oa:s3,G:ZI,e:DI,t:CI,w:PI,B:qI,nb:n3,Z:r3,x:zI,pa:i3,X:u3,ca:t3,ob:e3,pb:QI,O:GI,qa:JI,qb:YI,L:KI,Y:o3,d:RI,A:NI,m:MI,kb:h3,p:FI,z:LI,C:BI,E:jI,K:HI,ra:XI,P:l3,da:WI,W:d3,rb:VI,sa:UI,h:OI,a:hr,db:ht}}}async function re(){function f(x,E){var k=rr=x.exports;x={};for(let[M,U]of Object.entries(k))typeof U=="function"?(k=jS(U),x[M]=k):x[M]=U;return rr=x,rr=(function(){var M=rr,U=ne=>ge=>ne(ge)>>>0,Q=ne=>()=>ne()>>>0;return(M=Object.assign({},M)).tb=U(M.tb),M.Xb=Q(M.Xb),M.Zb=U(M.Zb),M.lc=U(M.lc),M.mc=Q(M.mc),M.qc=U(M.qc),M})(),fc.push(rr._b),up=(x=rr).tb,lp=x.ub,t._OrtInit=x.vb,t._OrtGetLastError=x.wb,t._OrtCreateSessionOptions=x.xb,t._OrtAppendExecutionProvider=x.yb,t._OrtAddFreeDimensionOverride=x.zb,t._OrtAddSessionConfigEntry=x.Ab,t._OrtReleaseSessionOptions=x.Bb,t._OrtCreateSession=x.Cb,t._OrtReleaseSession=x.Db,t._OrtGetInputOutputCount=x.Eb,t._OrtGetInputOutputMetadata=x.Fb,t._OrtFree=x.Gb,t._OrtCreateTensor=x.Hb,t._OrtGetTensorData=x.Ib,t._OrtReleaseTensor=x.Jb,t._OrtCreateRunOptions=x.Kb,t._OrtAddRunConfigEntry=x.Lb,t._OrtReleaseRunOptions=x.Mb,t._OrtCreateBinding=x.Nb,t._OrtBindInput=x.Ob,t._OrtBindOutput=x.Pb,t._OrtClearBoundOutputs=x.Qb,t._OrtReleaseBinding=x.Rb,t._OrtRunWithBinding=x.Sb,t._OrtRun=x.Tb,t._OrtEndProfiling=x.Ub,t._JsepOutput=x.Vb,t._JsepGetNodeName=x.Wb,go=x.Xb,Kt=t._free=x.Yb,ei=t._malloc=x.Zb,Qs=x.ac,dp=x.bc,cp=x.cc,pp=x.dc,ea=x.ec,hp=x.fc,fp=x.gc,Te=x.hc,ti=x.ic,mp=x.jc,we=x.kc,ta=x.lc,_e=x.mc,gp=x.nc,ra=x.oc,bp=x.pc,yp=x.qc,wp=x.rc,na=x.sc,_p=x.tc,vp=x.uc,xp=x.vc,$p=x.wc,Tp=x.xc,Sp=x.yc,Ip=x.zc,Op=x.Ac,Ep=x.Bc,Ap=x.Cc,kp=x.Dc,Pp=x.Ec,Cp=x.Fc,Rp=x.Gc,Dp=x.Hc,Mp=x.Ic,Np=x.Jc,zp=x.Kc,Bp=x.Lc,Fp=x.Mc,Lp=x.Nc,jp=x.Pc,Up=x.Qc,Vp=x.$c,qp=x.ad,Gp=x.fd,Hp=x.kd,Wp=x.ld,Kp=x.md,Xp=x.nd,Zp=x.od,Yp=x.pd,Jp=x.qd,Qp=x.rd,eh=x.wd,th=x.Ud,rh=x.Vd,nh=x.Wd,ih=x.Xd,h=E,rr}var b,$=W();return t.instantiateWasm?new Promise(x=>{t.instantiateWasm($,(E,k)=>{x(f(E,k))})}):u?f(new WebAssembly.Instance(h,W()),h):(B??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.jsep.wasm",a):a+"ort-wasm-simd-threaded.jsep.wasm":new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url).href,b=await(async function(x){var E=B;if(!p&&!P(E))try{var k=fetch(E,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(k,x)}catch(M){O(`wasm streaming compile failed: ${M}`),O("falling back to ArrayBuffer instantiation")}return(async function(M,U){try{var Q=await(async function(ne){if(!p)try{var ge=await c(ne);return new Uint8Array(ge)}catch{}if(ne==B&&p)ne=new Uint8Array(p);else{if(!s)throw"both async and sync fetching of the wasm failed";ne=s(ne)}return ne})(M);return await WebAssembly.instantiate(Q,U)}catch(ne){O(`failed to asynchronously prepare wasm: ${ne}`),X(ne)}})(E,x)})($),f(b.instance,b.module))}class le{name="ExitStatus";constructor(b){this.message=`Program terminated with exit(${b})`,this.status=b}}var ce=f=>{f.terminate(),f.onmessage=()=>{}},xe=[],qe=0,Ve=null,it=f=>{Gt.length==0&&(yc(),bc(Gt[0]));var b=Gt.pop();if(!b)return 6;Jn.push(b),Br[f.Rc]=b,b.Rc=f.Rc;var $={Sc:"run",Md:f.Ld,bd:f.bd,Rc:f.Rc};return b.postMessage($,f.jd),0},Ze=0,$e=(f,b,...$)=>{var x,E=16*$.length,k=_e(),M=ta(E),U=M>>>3;for(x of $)typeof x=="bigint"?((I(),V)[U++>>>0]=1n,(I(),V)[U++>>>0]=x):((I(),V)[U++>>>0]=0n,(I(),L)[U++>>>0]=x);return f=cp(f,0,E,M,b),we(k),f};function ht(f){if(u)return $e(0,1,f);if(m=f,!(0{if(m=f,u)throw It(f),"unwind";ht(f)},Gt=[],Jn=[],fc=[],Br={},mc=f=>{var b=f.Rc;delete Br[b],Gt.push(f),Jn.splice(Jn.indexOf(f),1),f.Rc=0,pp(b)};function gc(){fc.forEach(f=>f())}var bc=f=>new Promise(b=>{f.onmessage=E=>{var k=E.data;if(E=k.Sc,k.Zc&&k.Zc!=go()){var M=Br[k.Zc];M?M.postMessage(k,k.jd):O(`Internal error! Worker sent a message "${E}" to target pthread ${k.Zc}, but that thread no longer exists!`)}else E==="checkMailbox"?lo():E==="spawnThread"?it(k):E==="cleanupThread"?uo(()=>{mc(Br[k.Nd])}):E==="loaded"?(f.loaded=!0,b(f)):k.target==="setimmediate"?f.postMessage(k):E==="uncaughtException"?f.onerror(k.error):E==="callHandler"?t[k.vd](...k.args):E&&O(`worker sent an unknown command ${E}`)},f.onerror=E=>{throw O(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var $,x=[];for($ of[])t.propertyIsEnumerable($)&&x.push($);f.postMessage({Sc:"load",xd:x,Od:hr,Pd:h})});function yc(){var f=new Worker((()=>{let b=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new b("ort.all.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});Gt.push(f)}var hr,oS=(f,b)=>{Ze=0,f=na(f,b),0>>=0);return(I(),J)[b.Tc+12>>>0]==0&&(wc(b,!0),so--),_c(b,!1),oo.push(b),yp(f)}var On=0,aS=()=>{Te(0,0);var f=oo.pop();gp(f.cd),On=0};function wc(f,b){b=b?1:0,(I(),J)[f.Tc+12>>>0]=b}function _c(f,b){b=b?1:0,(I(),J)[f.Tc+13>>>0]=b}class Fs{constructor(b){this.cd=b,this.Tc=b-24}}var Ls=f=>{var b=On;if(!b)return ti(0),0;var $=new Fs(b);(I(),R)[$.Tc+16>>>2>>>0]=b;var x=(I(),R)[$.Tc+4>>>2>>>0];if(!x)return ti(0),b;for(var E of f){if(E===0||E===x)break;if(bp(E,x,$.Tc+16))return ti(E),b}return ti(x),b};function uS(){return Ls([])}function lS(f){return Ls([f>>>0])}function dS(f,b,$,x){return Ls([f>>>0,b>>>0,$>>>0,x>>>0])}var cS=()=>{var f=oo.pop();f||X("no exception to throw");var b=f.cd;throw(I(),J)[f.Tc+13>>>0]==0&&(oo.push(f),_c(f,!0),wc(f,!1),so++),ra(b),On=b};function pS(f,b,$){var x=new Fs(f>>>=0);throw b>>>=0,$>>>=0,(I(),R)[x.Tc+16>>>2>>>0]=0,(I(),R)[x.Tc+4>>>2>>>0]=b,(I(),R)[x.Tc+8>>>2>>>0]=$,ra(f),so++,On=f}var hS=()=>so;function vc(f,b,$,x){return u?$e(2,1,f,b,$,x):xc(f,b,$,x)}function xc(f,b,$,x){if(f>>>=0,b>>>=0,$>>>=0,x>>>=0,!globalThis.SharedArrayBuffer)return 6;var E=[];return u&&E.length===0?vc(f,b,$,x):(f={Ld:$,Rc:f,bd:x,jd:E},u?(f.Sc="spawnThread",postMessage(f,E),0):it(f))}function fS(f){throw On||=f>>>0,On}var $c=globalThis.TextDecoder&&new TextDecoder,Tc=(f,b,$,x)=>{if($=b+$,x)return $;for(;f[b]&&!(b>=$);)++b;return b},Sc=(f,b=0,$,x)=>{if(16<($=Tc(f,b>>>=0,$,x))-b&&f.buffer&&$c)return $c.decode(f.buffer instanceof ArrayBuffer?f.subarray(b,$):f.slice(b,$));for(x="";b<$;){var E=f[b++];if(128&E){var k=63&f[b++];if((224&E)==192)x+=String.fromCharCode((31&E)<<6|k);else{var M=63&f[b++];65536>(E=(240&E)==224?(15&E)<<12|k<<6|M:(7&E)<<18|k<<12|M<<6|63&f[b++])?x+=String.fromCharCode(E):(E-=65536,x+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else x+=String.fromCharCode(E)}return x},et=(f,b,$)=>(f>>>=0)?Sc((I(),q),f,b,$):"";function Ic(f,b,$){return u?$e(3,1,f,b,$):0}function Oc(f,b){if(u)return $e(4,1,f,b)}function Ec(f,b){if(u)return $e(5,1,f,b)}function Ac(f,b,$){if(u)return $e(6,1,f,b,$)}function kc(f,b,$){return u?$e(7,1,f,b,$):0}function Pc(f,b){if(u)return $e(8,1,f,b)}function Cc(f,b,$){if(u)return $e(9,1,f,b,$)}function Rc(f,b,$,x){if(u)return $e(10,1,f,b,$,x)}function Dc(f,b,$,x){if(u)return $e(11,1,f,b,$,x)}function Mc(f,b,$,x){if(u)return $e(12,1,f,b,$,x)}function Nc(f){if(u)return $e(13,1,f)}function zc(f,b){if(u)return $e(14,1,f,b)}function Bc(f,b,$){if(u)return $e(15,1,f,b,$)}var mS=()=>X(""),Ht=f=>{f>>>=0;for(var b="";;){var $=(I(),q)[f++>>>0];if(!$)return b;b+=String.fromCharCode($)}},js={},Us={},gS={},En=class extends Error{constructor(f){super(f),this.name="BindingError"}};function tr(f,b,$={}){return(function(x,E,k={}){var M=E.name;if(!x)throw new En(`type "${M}" must have a positive integer typeid pointer`);if(Us.hasOwnProperty(x)){if(k.yd)return;throw new En(`Cannot register type '${M}' twice`)}Us[x]=E,delete gS[x],js.hasOwnProperty(x)&&(E=js[x],delete js[x],E.forEach(U=>U()))})(f,b,$)}var Fc=(f,b,$)=>{switch(b){case 1:return $?x=>(I(),J)[x>>>0]:x=>(I(),q)[x>>>0];case 2:return $?x=>(I(),C)[x>>>1>>>0]:x=>(I(),ee)[x>>>1>>>0];case 4:return $?x=>(I(),v)[x>>>2>>>0]:x=>(I(),R)[x>>>2>>>0];case 8:return $?x=>(I(),V)[x>>>3>>>0]:x=>(I(),K)[x>>>3>>>0];default:throw new TypeError(`invalid integer width (${b}): ${f}`)}};function bS(f,b,$,x,E){f>>>=0,$>>>=0,b=Ht(b>>>0);let k=M=>M;if(x=x===0n){let M=8*$;k=U=>BigInt.asUintN(M,U),E=k(E)}tr(f,{name:b,Oc:k,Vc:(M,U)=>(typeof U=="number"&&(U=BigInt(U)),U),Uc:Fc(b,$,!x),Wc:null})}function yS(f,b,$,x){tr(f>>>=0,{name:b=Ht(b>>>0),Oc:function(E){return!!E},Vc:function(E,k){return k?$:x},Uc:function(E){return this.Oc((I(),q)[E>>>0])},Wc:null})}var Lc=[],Fr=[0,1,,1,null,1,!0,1,!1,1];function Vs(f){9<(f>>>=0)&&--Fr[f+1]===0&&(Fr[f]=void 0,Lc.push(f))}var Ot=f=>{if(!f)throw new En(`Cannot use deleted val. handle = ${f}`);return Fr[f]},Mt=f=>{switch(f){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let b=Lc.pop()||Fr.length;return Fr[b]=f,Fr[b+1]=1,b}};function qs(f){return this.Oc((I(),R)[f>>>2>>>0])}var wS={name:"emscripten::val",Oc:f=>{var b=Ot(f);return Vs(f),b},Vc:(f,b)=>Mt(b),Uc:qs,Wc:null};function _S(f){return tr(f>>>0,wS)}var vS=(f,b)=>{switch(b){case 4:return function($){return this.Oc((I(),H)[$>>>2>>>0])};case 8:return function($){return this.Oc((I(),L)[$>>>3>>>0])};default:throw new TypeError(`invalid float width (${b}): ${f}`)}};function xS(f,b,$){$>>>=0,tr(f>>>=0,{name:b=Ht(b>>>0),Oc:x=>x,Vc:(x,E)=>E,Uc:vS(b,$),Wc:null})}function $S(f,b,$,x,E){f>>>=0,$>>>=0,b=Ht(b>>>0);let k=U=>U;if(x===0){var M=32-8*$;k=U=>U<>>M,E=k(E)}tr(f,{name:b,Oc:k,Vc:(U,Q)=>Q,Uc:Fc(b,$,x!==0),Wc:null})}function TS(f,b,$){function x(k){var M=(I(),R)[k>>>2>>>0];return k=(I(),R)[k+4>>>2>>>0],new E((I(),J).buffer,k,M)}var E=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];tr(f>>>=0,{name:$=Ht($>>>0),Oc:x,Uc:x},{yd:!0})}var fr=(f,b,$)=>{var x=(I(),q);if(b>>>=0,0<$){var E=b;$=b+$-1;for(var k=0;k=M){if(b>=$)break;x[b++>>>0]=M}else if(2047>=M){if(b+1>=$)break;x[b++>>>0]=192|M>>6,x[b++>>>0]=128|63&M}else if(65535>=M){if(b+2>=$)break;x[b++>>>0]=224|M>>12,x[b++>>>0]=128|M>>6&63,x[b++>>>0]=128|63&M}else{if(b+3>=$)break;x[b++>>>0]=240|M>>18,x[b++>>>0]=128|M>>12&63,x[b++>>>0]=128|M>>6&63,x[b++>>>0]=128|63&M,k++}}x[b>>>0]=0,f=b-E}else f=0;return f},ao=f=>{for(var b=0,$=0;$=x?b++:2047>=x?b+=2:55296<=x&&57343>=x?(b+=4,++$):b+=3}return b};function SS(f,b){tr(f>>>=0,{name:b=Ht(b>>>0),Oc($){var x=(I(),R)[$>>>2>>>0];return x=et($+4,x,!0),Kt($),x},Vc($,x){x instanceof ArrayBuffer&&(x=new Uint8Array(x));var E=typeof x=="string";if(!(E||ArrayBuffer.isView(x)&&x.BYTES_PER_ELEMENT==1))throw new En("Cannot pass non-string to std::string");var k=E?ao(x):x.length,M=ei(4+k+1),U=M+4;return(I(),R)[M>>>2>>>0]=k,E?fr(x,U,k+1):(I(),q).set(x,U>>>0),$!==null&&$.push(Kt,M),M},Uc:qs,Wc($){Kt($)}})}var jc=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,IS=(f,b,$)=>{if(f>>>=1,16<(b=Tc((I(),ee),f,b/2,$))-f&&jc)return jc.decode((I(),ee).slice(f,b));for($="";f>>0];$+=String.fromCharCode(x)}return $},OS=(f,b,$)=>{if($??=2147483647,2>$)return 0;var x=b;$=($-=2)<2*f.length?$/2:f.length;for(var E=0;E<$;++E){var k=f.charCodeAt(E);(I(),C)[b>>>1>>>0]=k,b+=2}return(I(),C)[b>>>1>>>0]=0,b-x},ES=f=>2*f.length,AS=(f,b,$)=>{var x="";f>>>=2;for(var E=0;!(E>=b/4);E++){var k=(I(),R)[f+E>>>0];if(!k&&!$)break;x+=String.fromCodePoint(k)}return x},kS=(f,b,$)=>{if(b>>>=0,$??=2147483647,4>$)return 0;var x=b;$=x+$-4;for(var E=0;E>>2>>>0]=k,(b+=4)+4>$)break}return(I(),v)[b>>>2>>>0]=0,b-x},PS=f=>{for(var b=0,$=0;$>>=0,b>>>=0,$=Ht($>>>=0),b===2)var x=IS,E=OS,k=ES;else x=AS,E=kS,k=PS;tr(f,{name:$,Oc:M=>{var U=(I(),R)[M>>>2>>>0];return U=x(M+4,U*b,!0),Kt(M),U},Vc:(M,U)=>{if(typeof U!="string")throw new En(`Cannot pass non-string to C++ string type ${$}`);var Q=k(U),ne=ei(4+Q+b);return(I(),R)[ne>>>2>>>0]=Q/b,E(U,ne+4,Q+b),M!==null&&M.push(Kt,ne),ne},Uc:qs,Wc(M){Kt(M)}})}function RS(f,b){tr(f>>>=0,{zd:!0,name:b=Ht(b>>>0),Oc:()=>{},Vc:()=>{}})}function DS(f){Qs(f>>>0,!i,1,!n,131072,!1),gc()}var uo=f=>{if(!A)try{if(f(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Gs(f){f>>>=0,MS||(Atomics.waitAsync((I(),v),f>>>2,f).value.then(lo),f+=128,Atomics.store((I(),v),f>>>2,1))}var lo=()=>uo(()=>{var f=go();f&&(Gs(f),fp())});function NS(f,b){(f>>>=0)==b>>>0?setTimeout(lo):u?postMessage({Zc:f,Sc:"checkMailbox"}):(f=Br[f])&&f.postMessage({Sc:"checkMailbox"})}var Hs=[];function zS(f,b,$,x,E){for(b>>>=0,E>>>=0,Hs.length=0,$=E>>>3,x=E+x>>>3;$>>0]?(I(),V)[$++>>>0]:(I(),L)[$++>>>0],Hs.push(k)}return(b?ia[b]:EI[f])(...Hs)}var BS=()=>{Ze=0};function FS(f){f>>>=0,u?postMessage({Sc:"cleanupThread",Nd:f}):mc(Br[f])}function LS(f){}var co=f=>{try{f()}catch(b){X(b)}};function jS(f){var b=(...$)=>{po.push(f);try{return f(...$)}finally{A||(po.pop(),Wt&&mr===1&&po.length===0&&(mr=0,Ze+=1,co(rh),typeof Fibers<"u"&&Fibers.be()))}};return qc.set(f,b),b}var mr=0,Wt=null,Uc=0,po=[],Ws=new Map,Vc=new Map,qc=new Map,US=0,Ks=null,VS=[],Gc=f=>(function(b){if(!A){if(mr===0){var $=!1,x=!1;b((E=0)=>{if(!A&&(Uc=E,$=!0,x)){mr=2,co(()=>nh(Wt)),typeof MainLoop<"u"&&MainLoop.ud&&MainLoop.resume(),E=!1;try{var k=(function(){var Q=(I(),v)[Wt+8>>>2>>>0];return Q=Vc.get(Q),Q=qc.get(Q),--Ze,Q()})()}catch(Q){k=Q,E=!0}var M=!1;if(!Wt){var U=Ks;U&&(Ks=null,(E?U.reject:U.resolve)(k),M=!0)}if(E&&!M)throw k}}),x=!0,$||(mr=1,Wt=(function(){var E=ei(65548),k=E+12;if((I(),R)[E>>>2>>>0]=k,(I(),R)[E+4>>>2>>>0]=k+65536,k=po[0],!Ws.has(k)){var M=US++;Ws.set(k,M),Vc.set(M,k)}return k=Ws.get(k),(I(),v)[E+8>>>2>>>0]=k,E})(),typeof MainLoop<"u"&&MainLoop.ud&&MainLoop.pause(),co(()=>th(Wt)))}else mr===2?(mr=0,co(ih),Kt(Wt),Wt=null,VS.forEach(uo)):X(`invalid state: ${mr}`);return Uc}})(b=>{f().then(b)});function qS(f){return f>>>=0,Gc(async()=>{var b=await Ot(f);return Mt(b)})}var Xs=[],GS=f=>{var b=Xs.length;return Xs.push(f),b},HS=(f,b)=>{for(var $=Array(f),x=0;x>>2>>>0],M=Us[k];if(M===void 0)throw f=`parameter ${x}`,k=up(k),b=Ht(k),Kt(k),new En(`${f} has unknown type ${b}`);$[E]=M}return $},WS=(f,b,$)=>{var x=[];return f=f(x,$),x.length&&((I(),R)[b>>>2>>>0]=Mt(x)),f},KS={},ho=f=>{var b=KS[f];return b===void 0?Ht(f):b};function XS(f,b,$){var[x,...E]=HS(f,b>>>0);b=x.Vc.bind(x);var k=E.map(Q=>Q.Uc.bind(Q));f--;var M={toValue:Ot};switch(f=k.map((Q,ne)=>{var ge=`argFromPtr${ne}`;return M[ge]=Q,`${ge}(args${ne?"+"+8*ne:""})`}),$){case 0:var U="toValue(handle)";break;case 2:U="new (toValue(handle))";break;case 3:U="";break;case 1:M.getStringOrSymbol=ho,U="toValue(handle)[getStringOrSymbol(methodName)]"}return U+=`(${f})`,x.zd||(M.toReturnWire=b,M.emval_returnValue=WS,U=`return emval_returnValue(toReturnWire, destructorsRef, ${U})`),U=`return function (handle, methodName, destructorsRef, args) { +${e}`);return i}deleteShader(e){this.gl.deleteShader(e)}bindTextureToUniform(e,t,n){let i=this.gl;i.activeTexture(i.TEXTURE0+t),this.checkError(),i.bindTexture(i.TEXTURE_2D,e),this.checkError(),i.uniform1i(n,t),this.checkError()}draw(){this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),this.checkError()}checkError(){if(me.debug){let e=this.gl,t=e.getError(),n="";switch(t){case e.NO_ERROR:return;case e.INVALID_ENUM:n="INVALID_ENUM";break;case e.INVALID_VALUE:n="INVALID_VALUE";break;case e.INVALID_OPERATION:n="INVALID_OPERATION";break;case e.INVALID_FRAMEBUFFER_OPERATION:n="INVALID_FRAMEBUFFER_OPERATION";break;case e.OUT_OF_MEMORY:n="OUT_OF_MEMORY";break;case e.CONTEXT_LOST_WEBGL:n="CONTEXT_LOST_WEBGL";break;default:n=`Unknown WebGL Error: ${t.toString(16)}`}throw new Error(n)}}deleteTexture(e){this.gl.deleteTexture(e)}deleteProgram(e){this.gl.deleteProgram(e)}getEncoder(e,t,n=0){if(this.version===2)return new Rw(this.gl,t);switch(e){case"float":return n===1||this.isRenderFloat32Supported?new cl(this.gl,t):new cl(this.gl,t,this.textureHalfFloatExtension.HALF_FLOAT_OES);case"int":throw new Error("not implemented");case"byte":return new Dw(this.gl,t);default:throw new Error(`Invalid dataType: ${e}`)}}clearActiveTextures(){let e=this.gl;for(let t=0;tthis.isTimerResultAvailable(e)),this.getTimerResult(e)}async createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n=e,i=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),i===null?t=()=>!0:t=()=>{let u=n.clientWaitSync(i,0,0);return u===n.ALREADY_SIGNALED||u===n.CONDITION_SATISFIED},{query:i,isFencePassed:t}}async pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=NA(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}async addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),!(this.itemsToPoll.length>1)&&await wh(()=>(this.pollItems(),this.itemsToPoll.length===0))}}});function ix(e){let t;if((!e||e==="webgl2")&&"webgl2"in sn?t=sn.webgl2:(!e||e==="webgl")&&"webgl"in sn&&(t=sn.webgl),!t)try{let i=FA();t=$m(i,e)}catch{let i=BA();t=$m(i,e)}e=e||t.version===1?"webgl":"webgl2";let n=t.gl;return sn[e]=t,n.isContextLost()?(delete sn[e],ix(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),t)}function $m(e,t){let n={alpha:!1,depth:!1,antialias:!1,stencil:!1,preserveDrawingBuffer:!1,premultipliedAlpha:!1,failIfMajorPerformanceCaveat:!1},i,u=n;if((!t||t==="webgl2")&&(i=e.getContext("webgl2",u),i))try{return new Al(i,2)}catch(l){Je.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl2'. Error: ${l}`)}if((!t||t==="webgl")&&(i=e.getContext("webgl",u)||e.getContext("experimental-webgl",u),i))try{return new Al(i,1)}catch(l){Je.warning("GlContextFactory",`failed to create WebGLContext using contextId 'webgl' or 'experimental-webgl'. Error: ${l}`)}throw new Error("WebGL is not supported")}function BA(){if(typeof document>"u")throw new TypeError("failed to create canvas: document is not supported");let e=document.createElement("canvas");return e.width=1,e.height=1,e}function FA(){if(typeof OffscreenCanvas>"u")throw new TypeError("failed to create offscreen canvas: OffscreenCanvas is not supported");return new OffscreenCanvas(1,1)}var sn,LA=D(()=>{"use strict";Gt(),zA(),sn={}}),ox,jA=D(()=>{"use strict";dt(),Gt(),MA(),LA(),ox=class{get contextId(){return me.webgl.contextId}set contextId(e){me.webgl.contextId=e}get matmulMaxBatchSize(){return me.webgl.matmulMaxBatchSize}set matmulMaxBatchSize(e){me.webgl.matmulMaxBatchSize=e}get textureCacheMode(){return me.webgl.textureCacheMode}set textureCacheMode(e){me.webgl.textureCacheMode=e}get pack(){return me.webgl.pack}set pack(e){me.webgl.pack=e}get async(){return me.webgl.async}set async(e){me.webgl.async=e}initialize(){try{return this.glContext=ix(this.contextId),typeof this.matmulMaxBatchSize!="number"&&(this.matmulMaxBatchSize=16),typeof this.textureCacheMode!="string"&&(this.textureCacheMode="full"),typeof this.pack!="boolean"&&(this.pack=!1),typeof this.async!="boolean"&&(this.async=!1),Je.setWithEnv(me),me.webgl.context||Object.defineProperty(me.webgl,"context",{value:this.glContext.gl}),Je.verbose("WebGLBackend",`Created WebGLContext: ${typeof this.glContext} with matmulMaxBatchSize: ${this.matmulMaxBatchSize}; textureCacheMode: ${this.textureCacheMode}; pack: ${this.pack}; async: ${this.async}.`),!0}catch(e){return Je.warning("WebGLBackend",`Unable to initialize WebGLBackend. ${e}`),!1}}createSessionHandler(e){return new nx(this,e)}dispose(){this.glContext.dispose()}}});async function sx(e){if(e){let t=typeof e=="string"?[e]:e;for(let n of t){let i=nd.get(n);if(i)return i;let u=await UA(n);if(u)return u}}else return sx(["webgl"]);throw new Error("no available backend to use")}async function UA(e){let t=ax;if(typeof t[e]<"u"&&VA(t[e])){let n=t[e],i=n.initialize();if(typeof i=="object"&&"then"in i&&(i=await i),i)return nd.set(e,n),n}}function VA(e){let t=e;return"initialize"in t&&typeof t.initialize=="function"&&"createSessionHandler"in t&&typeof t.createSessionHandler=="function"&&"dispose"in t&&typeof t.dispose=="function"}var nd,ax,GA=D(()=>{"use strict";jA(),nd=new Map,ax={webgl:new ox}}),Tm,ux,qA=D(()=>{"use strict";Gt(),Tm=class{constructor(e,t){this.op=e,this.node=t}},ux=class{constructor(e,t,n){this.graph=e,this.profiler=n,this.initialize(t)}initialize(e){this.profiler.event("session","ExecutionPlan.initialize",()=>{let t=this.graph.getNodes();if(t.length!==e.length)throw new Error("The size of nodes and OPs do not match.");this._ops=e.map((n,i)=>new Tm(n,t[i])),this.reset(),this._starter=[],this._ops.forEach((n,i)=>{let u=!0;for(let l of n.node.inputs)if(!this._values[l]&&this.graph.getInputIndices().indexOf(l)===-1){u=!1;break}u&&this._starter.push(i)})})}reset(){this._values=this.graph.getValues().map(e=>e.tensor)}async execute(e,t){return this.profiler.event("session","ExecutionPlan.execute",async()=>{this.reset();let n=e.createInferenceHandler(),i=this.graph.getInputIndices();if(t.length!==i.length)throw new Error(`number of input tensors don't match the number of inputs to the model: actual: ${t.length} expected: ${i.length}`);t.forEach((r,o)=>{let a=i[o];this._values[a]=r});let u=this._starter.slice(0),l=this.graph.getValues(),d=this.graph.getNodes(),c=0;for(;cthis._values[g]);if(a.indexOf(void 0)!==-1)throw new Error(`unresolved input detected: op: ${o.node}`);let p=a;Je.verbose("ExecPlan",`Running op:${o.node.name} (${p.map((g,_)=>`'${o.node.inputs[_]}': ${g.type}[${g.dims.join(",")}]`).join(", ")})`);let h=await this.profiler.event("node",o.node.name,async()=>o.op.impl(n,p,o.op.context));if(h.length!==o.node.outputs.length)throw new Error("the size of output does not match model definition.");h.forEach((g,_)=>{let w=o.node.outputs[_];if(this._values[w])throw new Error(`output [${w}] already has value: op:${o.node.name}`);this._values[w]=g});let m=new Set;h.forEach((g,_)=>{let w=o.node.outputs[_];for(let y of l[w].to){let T=d[y],S=!0;for(let O of T.inputs)if(!this._values[O]){S=!1;break}S&&m.add(y)}}),u.push(...m)}let s=[];for(let r=0;r{"use strict";os(),Se=be(Bi()),Ln(),Me(),kl=class Ii{constructor(t){if(this._attributes=new Map,t!=null){for(let n of t)n instanceof Se.onnx.AttributeProto?this._attributes.set(n.name,[Ii.getValue(n),Ii.getType(n)]):n instanceof ol.Attribute&&this._attributes.set(n.name(),[Ii.getValue(n),Ii.getType(n)]);if(this._attributes.sizext.fromProto(u));if(t instanceof ol.Attribute)return i.map(u=>xt.fromOrtTensor(u))}return n===Se.onnx.AttributeProto.AttributeType.STRING&&t instanceof Se.onnx.AttributeProto?sl(i):n===Se.onnx.AttributeProto.AttributeType.STRINGS&&t instanceof Se.onnx.AttributeProto?i.map(sl):i}static getValueNoCheck(t){return t instanceof Se.onnx.AttributeProto?this.getValueNoCheckFromOnnxFormat(t):this.getValueNoCheckFromOrtFormat(t)}static getValueNoCheckFromOnnxFormat(t){switch(t.type){case Se.onnx.AttributeProto.AttributeType.FLOAT:return t.f;case Se.onnx.AttributeProto.AttributeType.INT:return t.i;case Se.onnx.AttributeProto.AttributeType.STRING:return t.s;case Se.onnx.AttributeProto.AttributeType.TENSOR:return t.t;case Se.onnx.AttributeProto.AttributeType.GRAPH:return t.g;case Se.onnx.AttributeProto.AttributeType.FLOATS:return t.floats;case Se.onnx.AttributeProto.AttributeType.INTS:return t.ints;case Se.onnx.AttributeProto.AttributeType.STRINGS:return t.strings;case Se.onnx.AttributeProto.AttributeType.TENSORS:return t.tensors;case Se.onnx.AttributeProto.AttributeType.GRAPHS:return t.graphs;default:throw new Error(`unsupported attribute type: ${Se.onnx.AttributeProto.AttributeType[t.type]}`)}}static getValueNoCheckFromOrtFormat(t){switch(t.type()){case jt.AttributeType.FLOAT:return t.f();case jt.AttributeType.INT:return t.i();case jt.AttributeType.STRING:return t.s();case jt.AttributeType.TENSOR:return t.t();case jt.AttributeType.GRAPH:return t.g();case jt.AttributeType.FLOATS:return t.floatsArray();case jt.AttributeType.INTS:{let n=[];for(let i=0;i{"use strict";HA(),os(),ja=be(Bi()),Ln(),Me(),Pl={from:(e,t)=>new Sm(e,t)},nr=class{constructor(e){this._from=void 0,this._to=[],this.tensor=void 0,this.type=void 0,e&&(this.type=wt.tensorValueTypeFromProto(e.type.tensorType))}get from(){return this._from}get to(){return this._to}},Ua=class{constructor(e,t){e instanceof ja.onnx.NodeProto?(this.name=e.name,this.opType=e.opType,this.attributes=new kl(e.attribute)):e instanceof _w.Node&&(this.name=t??e.name(),this.opType=e.opType(),this.attributes=new kl(wt.tensorAttributesFromORTFormat(e))),this.inputs=[],this.outputs=[],this.executeNode=!0}},Sm=class{constructor(e,t){if(!e)throw new TypeError("graph is empty");this.buildGraph(e),this.transformGraph(t),this.checkIsAcyclic()}getInputIndices(){return this._allInputIndices}getInputNames(){return this._allInputNames}getOutputIndices(){return this._allOutputIndices}getOutputNames(){return this._allOutputNames}getValues(){return this._allData}getNodes(){return this._nodes}buildGraph(e){if(e instanceof ja.onnx.GraphProto)this.buildGraphFromOnnxFormat(e);else if(e instanceof yw.Graph)this.buildGraphFromOrtFormat(e);else throw new TypeError("Graph type is not supported.")}buildGraphFromOnnxFormat(e){let t=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let n=new Map;if(!e.input)throw new Error("missing information in graph: input");let i=[];for(let u of e.input){if(t.has(u.name))throw new Error(`duplicated input name: ${u.name}`);let l=this._allData.push(new nr(u))-1;t.set(u.name,l),i.push(u.name)}if(!e.initializer)throw new Error("missing information in graph: initializer");for(let u of e.initializer){let l=t.get(u.name);if(l===void 0){let d=new nr;d.type={shape:{dims:wt.tensorDimsFromProto(u.dims)},tensorType:wt.tensorDataTypeFromProto(u.dataType)},l=this._allData.push(d)-1,t.set(u.name,l)}this._allData[l]._from=-1,this._allData[l].tensor=xt.fromProto(u)}for(let u=0;u"u"&&(s=this._allData.push(new nr)-1,t.set(c,s)),l.outputs.push(s),this._allData[s]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${s}`);if(this._allData[s]._from=u,d.opType==="Constant"){if(!d.attribute||d.attribute.length!==1||!d.attribute[0].t)throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(!d.output||d.output.length!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");l.outputs.pop(),l.executeNode=!1,this._allData[s]._from=-1,this._allData[s].tensor=xt.fromProto(d.attribute[0].t)}}}for(let u=0;u"u"){if(c===""&&(d.input.length===3||d.input.length===4)&&d.opType==="Resize")continue;throw new Error(`unrecognized input '${c}' for node: ${d.name}`)}l.inputs.push(s),this._allData[s]._to.push(u)}}return!0}buildGraphFromOrtFormat(e){let t=new Map;this._allData=[],this._allInputIndices=[],this._allInputNames=[],this._allOutputIndices=[],this._allOutputNames=[],this._nodes=[];let n=new Map,i=[];for(let u=0;u"u"&&(r=this._allData.push(new nr)-1,t.set(s,r)),l.outputs.push(r),this._allData[r]._from!==void 0)throw new Error(`multiple nodes output to one data value: ${r}`);if(this._allData[r]._from=u,d.opType()==="Constant"){if(d.attributesLength()!==1||!d.attributes(0).t())throw new Error("missing attributes or missing tensor value in attributes for this Constant operator");if(d.outputsLength()!==1)throw new Error("missing output or incorrect number of outputs for this Constant operator");l.outputs.pop(),l.executeNode=!1,this._allData[r]._from=-1,this._allData[r].tensor=xt.fromOrtTensor(d.attributes(0).t())}}}for(let u=0;u"u")throw new Error(`unrecognized input '${s}' for node: ${d.name()}`);l.inputs.push(r),this._allData[r]._to.push(u)}}}checkIsAcyclic(){let e=new Set;this._allInputIndices.forEach(i=>{this._allData[i]._to.forEach(u=>{e.add(u)})});let t=Array.from(e),n=new Array(this._nodes.length).fill("white");for(;t.length>0;){let i=t.pop();n[i]==="gray"?n[i]="black":(t.push(i),n[i]="gray",this._nodes[i].outputs.forEach(u=>{let l=this._allData[u];if(typeof l.tensor<"u")throw new Error("node outputs should not be initialized");if(l._from!==i)throw new Error("from property of the Value object doesn't match index of Node being processed");l._to.forEach(d=>{if(n[d]==="gray")throw new Error("model graph is cyclic");n[d]==="white"&&t.push(d)})}))}}transformGraph(e){this.removeAllIdentityNodes(),this.removeAllDropoutNodes(),this.fuseConvActivationNodes(),e&&e.transformGraph(this),this.finalizeGraph()}finalizeGraph(){let e=0,t=new Array(this._nodes.length,0),n=0;for(let i=0;i{this._allData[u]._from=-2});this._nodes.splice(n,this._nodes.length-n);for(let i=0;i=0)u._to[l]=t[u._to[l]];else throw new Error("Trying to update a removed node")}e=0;for(let i=0;i0){let u=-1;this._allData[i].from!==void 0&&this._allData[i].from!==-1?(u=this._nodes[this._allData[i].from].outputs.indexOf(i+e),u!==-1&&(this._nodes[this._allData[i].from].outputs[u]=i)):(u=this._allInputIndices.indexOf(i+e),u!==-1&&(this._allInputIndices[u]=i)),this._allData[i].to.forEach(l=>{u=this._nodes[l].inputs.indexOf(i+e),u!==-1&&(this._nodes[l].inputs[u]=i)}),this._allData[i].to.length===0&&(u=this._allOutputIndices.indexOf(i+e),u!==-1&&(this._allOutputIndices[u]=i))}}}deleteNode(e){let t=this._nodes[e];if(t.outputs.length>1){for(let d=1;d0)throw new Error("Node deletion with more than one output connected to other nodes is not supported. ")}t.executeNode=!1;let n=t.inputs[0],i=t.outputs[0],u=this._allData[i].to;for(let d=0;d0)for(let d of u){let c=this._nodes[d].inputs.indexOf(i);if(c===-1)throw new Error("The Node object doesn't have the output Value in it's 'inputs' property ");this._nodes[d].inputs[c]=n,this._allData[n].to.push(d)}}removeAllDropoutNodes(){let e=0;for(let t of this._nodes){if(t.opType==="Dropout"){if(t.inputs.length!==1)throw new Error("Dropout nodes should only contain one input. ");if(t.outputs.length!==1&&t.outputs.length!==2)throw new Error("Dropout nodes should contain either 1 or 2 output(s)");if(t.outputs.length===2&&this._allData[t.outputs[1]]._to.length!==0)throw new Error("Dropout nodes's second output should not be referenced by other nodes");this.deleteNode(e)}e++}}removeAllIdentityNodes(){let e=0;for(let t of this._nodes)t.opType==="Identity"&&this.deleteNode(e),e++}isActivation(e){switch(e.opType){case"Relu":case"Sigmoid":case"Clip":return!0;default:return!1}}fuseConvActivationNodes(){for(let e of this._nodes)if(e.opType==="Conv"){let t=this._allData[e.outputs[0]]._to;if(t.length===1&&this.isActivation(this._nodes[t[0]])){let n=this._nodes[t[0]];if(n.opType==="Clip")if(n.inputs.length===1)try{e.attributes.set("activation_params","floats",[n.attributes.getFloat("min"),n.attributes.getFloat("max")])}catch{e.attributes.set("activation_params","floats",[Di,Mi])}else if(n.inputs.length>=3&&this._allData[n.inputs[1]].tensor!==void 0&&this._allData[n.inputs[2]].tensor!==void 0)e.attributes.set("activation_params","floats",[this._allData[n.inputs[1]].tensor.floatData[0],this._allData[n.inputs[2]].tensor.floatData[0]]);else continue;e.attributes.set("activation","string",n.opType),this.deleteNode(t[0])}}}}}),Im,Om,lx,KA=D(()=>{"use strict";Im=be(De()),WA(),os(),Om=be(Bi()),Me(),lx=class{constructor(){}load(e,t,n){let i;if(!n)try{this.loadFromOnnxFormat(e,t);return}catch(u){if(n!==void 0)throw u;i=u}try{this.loadFromOrtFormat(e,t)}catch(u){throw n!==void 0?u:new Error(`Failed to load model as ONNX format: ${i} +as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=Om.onnx.ModelProto.decode(e);if(Yt.longToNumber(n.irVersion)<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=n.opsetImport.map(i=>({domain:i.domain,version:Yt.longToNumber(i.version)})),this._graph=Pl.from(n.graph,t)}loadFromOrtFormat(e,t){let n=new Im.ByteBuffer(e),i=ww.InferenceSession.getRootAsInferenceSession(n).model();if(Yt.longToNumber(i.irVersion())<3)throw new Error("only support ONNX model with IR_VERSION>=3");this._opsets=[];for(let u=0;u{"use strict";GA(),qA(),Gt(),KA(),dx=class{constructor(e={}){this._initialized=!1,this.backendHint=e.backendHint,this.profiler=D0.create(e.profiler),this.context={profiler:this.profiler,graphInputTypes:[],graphInputDims:[]}}get inputNames(){return this._model.graph.getInputNames()}get outputNames(){return this._model.graph.getOutputNames()}startProfiling(){this.profiler.start()}endProfiling(){this.profiler.stop()}async loadModel(e,t,n){await this.profiler.event("session","Session.loadModel",async()=>{let i=await sx(this.backendHint);if(this.sessionHandler=i.createSessionHandler(this.context),this._model=new lx,typeof e=="string"){let u=e.endsWith(".ort");{let l=await(await fetch(e)).arrayBuffer();this.initialize(new Uint8Array(l),u)}}else if(ArrayBuffer.isView(e))this.initialize(e);else{let u=new Uint8Array(e,t||0,n||e.byteLength);this.initialize(u)}})}initialize(e,t){if(this._initialized)throw new Error("already initialized");this.profiler.event("session","Session.initialize",()=>{let n=this.sessionHandler.transformGraph?this.sessionHandler:void 0;this._model.load(e,n,t),this.sessionHandler.onGraphInitialized&&this.sessionHandler.onGraphInitialized(this._model.graph),this.initializeOps(this._model.graph),this._executionPlan=new ux(this._model.graph,this._ops,this.profiler)}),this._initialized=!0}async run(e){if(!this._initialized)throw new Error("session not initialized yet");return this.profiler.event("session","Session.run",async()=>{let t=this.normalizeAndValidateInputs(e),n=await this._executionPlan.execute(this.sessionHandler,t);return this.createOutput(n)})}normalizeAndValidateInputs(e){let t=this._model.graph.getInputNames();if(Array.isArray(e)){if(e.length!==t.length)throw new Error(`incorrect input array length: expected ${t.length} but got ${e.length}`)}else{if(e.size!==t.length)throw new Error(`incorrect input map size: expected ${t.length} but got ${e.size}`);let n=new Array(e.size),i=0;for(let u=0;u{"use strict";dt(),Ln(),cx=class{constructor(e){this.session=e,this.inputNames=this.session.inputNames,this.outputNames=this.session.outputNames}get inputMetadata(){throw new Error("Getting model metadata is not supported in webgl backend.")}get outputMetadata(){throw new Error("Getting model metadata is not supported in webgl backend.")}async dispose(){}async run(e,t,n){let i=new Map;for(let d in e)if(Object.hasOwnProperty.call(e,d)){let c=e[d];i.set(d,new xt(c.dims,c.type,void 0,void 0,c.data))}let u=await this.session.run(i),l={};return u.forEach((d,c)=>{l[c]=new vt(d.type,d.data,d.dims)}),l}startProfiling(){this.session.startProfiling()}endProfiling(){this.session.endProfiling()}}}),px={};wn(px,{onnxjsBackend:()=>hx});var Em,hx,YA=D(()=>{"use strict";XA(),ZA(),Em=class{async init(){}async createInferenceSessionHandler(e,t){let n=new dx(t);return typeof e=="string"?await n.loadModel(e):await n.loadModel(e),new cx(n)}},hx=new Em}),id=D(()=>{"use strict"}),fx={};wn(fx,{default:()=>mx});var Va,Ga,mx,JA=D(()=>{"use strict";$$(),vn(),od(),Va="ort-wasm-proxy-worker",Ga=globalThis.self?.name===Va,Ga&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case"init-wasm":sd(n.wasm).then(()=>{$d(n).then(()=>{postMessage({type:t})},i=>{postMessage({type:t,err:i})})},i=>{postMessage({type:t,err:i})});break;case"init-ep":{let{epName:i,env:u}=n;Td(u,i).then(()=>{postMessage({type:t})},l=>{postMessage({type:t,err:l})});break}case"copy-from":{let{buffer:i}=n,u=Qo(i);postMessage({type:t,out:u});break}case"create":{let{model:i,options:u}=n;Sd(i,u).then(l=>{postMessage({type:t,out:l})},l=>{postMessage({type:t,err:l})});break}case"release":Id(n),postMessage({type:t});break;case"run":{let{sessionId:i,inputIndices:u,inputs:l,outputIndices:d,options:c}=n;Od(i,u,l,d,new Array(d.length).fill(null),c).then(s=>{s.some(r=>r[3]!=="cpu")?postMessage({type:t,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:t,out:s},Ad([...l,...s]))},s=>{postMessage({type:t,err:s})});break}case"end-profiling":Ed(n),postMessage({type:t});break;default:}}catch(i){postMessage({type:t,err:i})}}),mx=Ga?null:e=>new Worker(e??yt,{type:"module",name:Va})}),gx={};wn(gx,{default:()=>bx});async function Am(e={}){var t=e,n=!!globalThis.window,i=!!globalThis.WorkerGlobalScope,u=i&&self.name?.startsWith("em-pthread");t.mountExternalData=(f,b)=>{f.startsWith("./")&&(f=f.substring(2)),(t.Yc||(t.Yc=new Map)).set(f,b)},t.unmountExternalData=()=>{delete t.Yc,delete t.Zd,delete t.Yd,delete t.$d},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,shared:!0}).buffer.constructor;let l=f=>async(...b)=>{try{if(t.Xc)throw Error("Session already started");let $=t.Xc={Kd:b[0],errors:[]},x=await f(...b);if(t.Xc!==$)throw Error("Session mismatch");t.dd?.flush();let E=$.errors;if(0M),0{if(f==="webgpu"){[t.dd,t.Ad,t.Ed,t.ed,t.Dd,t.$b,t.Fd,t.Hd,t.Bd,t.Cd,t.Gd]=b;let $=t.dd;t.jsepRegisterBuffer=(x,E,k,M)=>$.registerBuffer(x,E,k,M),t.jsepGetBuffer=x=>$.getBuffer(x),t.jsepCreateDownloader=(x,E,k)=>$.createDownloader(x,E,k),t.jsepOnCreateSession=x=>{$.onCreateSession(x)},t.jsepOnReleaseSession=x=>{$.onReleaseSession(x)},t.jsepOnRunStart=x=>$.onRunStart(x),t.Id=(x,E)=>{$.upload(x,E)}}else if(f==="webnn"){let $=b[0];[t.Sd,t.sd,t.webnnEnsureTensor,t.td,t.webnnDownloadTensor,t.Rd,t.webnnEnableTraceEvent]=b.slice(1),t.webnnReleaseTensorId=t.sd,t.webnnUploadTensor=t.td,t.webnnRegisterMLContext=t.Rd,t.webnnOnRunStart=x=>$.onRunStart(x),t.webnnOnRunEnd=$.onRunEnd.bind($),t.webnnOnReleaseSession=x=>{$.onReleaseSession(x)},t.webnnCreateMLTensorDownloader=(x,E)=>$.createMLTensorDownloader(x,E),t.webnnRegisterMLTensor=(x,E,k,M)=>$.registerMLTensor(x,E,k,M),t.webnnCreateMLContext=x=>$.createMLContext(x),t.webnnRegisterGraphInput=$.registerGraphInput.bind($),t.webnnIsGraphInput=$.isGraphInput.bind($),t.webnnRegisterGraphOutput=$.registerGraphOutput.bind($),t.webnnIsGraphOutput=$.isGraphOutput.bind($),t.webnnCreateTemporaryTensor=$.createTemporaryTensor.bind($),t.webnnIsGraphInputOutputTypeSupported=$.isGraphInputOutputTypeSupported.bind($)}};let d=()=>{let f=b=>(...$)=>{let x=Wt;return $=b(...$),Wt!=x?new Promise((E,k)=>{Ys={resolve:E,reject:k}}):$};(()=>{for(let b of["_OrtAppendExecutionProvider","_OrtCreateSession","_OrtRun","_OrtRunWithBinding","_OrtBindInput"])t[b]=f(t[b])})(),l!==void 0&&(t._OrtRun=l(t._OrtRun),t._OrtRunWithBinding=l(t._OrtRunWithBinding)),d=void 0};t.asyncInit=()=>{d?.()};var c,s,r=(f,b)=>{throw b},o=import.meta.url,a="";if(n||i){try{a=new URL(".",o).href}catch{}i&&(s=f=>{var b=new XMLHttpRequest;return b.open("GET",f,!1),b.responseType="arraybuffer",b.send(null),new Uint8Array(b.response)}),c=async f=>{if(P(f))return new Promise(($,x)=>{var E=new XMLHttpRequest;E.open("GET",f,!0),E.responseType="arraybuffer",E.onload=()=>{E.status==200||E.status==0&&E.response?$(E.response):x(E.status)},E.onerror=x,E.send(null)});var b=await fetch(f,{credentials:"same-origin"});if(b.ok)return b.arrayBuffer();throw Error(b.status+" : "+b.url)}}var p,h,m,g,_,w,y=console.log.bind(console),T=console.error.bind(console),S=y,O=T,A=!1,P=f=>f.startsWith("file://");function I(){hr.buffer!=J.buffer&&Y()}if(u){let f=function(b){try{var $=b.data,x=$.Sc;if(x==="load"){let E=[];self.onmessage=k=>E.push(k),w=()=>{postMessage({Sc:"loaded"});for(let k of E)f(k);self.onmessage=f};for(let k of $.xd)t[k]&&!t[k].proxy||(t[k]=(...M)=>{postMessage({Sc:"callHandler",vd:k,args:M})},k=="print"&&(S=t[k]),k=="printErr"&&(O=t[k]));hr=$.Od,Y(),h=$.Pd,re(),wo()}else if(x==="run"){(function(E){var k=(I(),R)[E+52>>>2>>>0];E=(I(),R)[E+56>>>2>>>0],_p(k,k-E),we(k)})($.Rc),ra($.Rc,0,0,1,0,0),vc(),Ks($.Rc),q||(fp(),q=!0);try{pS($.Md,$.bd)}catch(E){if(E!="unwind")throw E}}else $.target!=="setimmediate"&&(x==="checkMailbox"?q&&po():x&&(O(`worker: received unknown command ${x}`),O($)))}catch(E){throw mp(),E}};var z=f,q=!1;self.onunhandledrejection=b=>{throw b.reason||b},self.onmessage=f}var J,G,C,ee,v,R,H,L,V,K,B,te=!1;function Y(){var f=hr.buffer;t.HEAP8=J=new Int8Array(f),C=new Int16Array(f),t.HEAPU8=G=new Uint8Array(f),ee=new Uint16Array(f),t.HEAP32=v=new Int32Array(f),t.HEAPU32=R=new Uint32Array(f),H=new Float32Array(f),L=new Float64Array(f),V=new BigInt64Array(f),K=new BigUint64Array(f)}function N(){te=!0,u?w():rr.sb()}function X(f){throw O(f="Aborted("+f+")"),A=!0,f=new WebAssembly.RuntimeError(f+". Build with -sASSERTIONS for more info."),_?.(f),f}function W(){return{a:{ma:zI,hb:NI,g:hS,J:fS,f:mS,o:gS,i:bS,$:yS,b:wS,S:_S,Ia:Oc,n:vS,aa:Pc,Ya:Cc,Ea:Rc,Ga:Dc,Za:Mc,Wa:Nc,Pa:zc,Va:Bc,ka:Fc,Fa:Lc,Ca:jc,Xa:Uc,Da:Vc,cb:xS,fa:TS,xa:SS,va:OS,ea:AS,N:kS,H:PS,wa:CS,_:FS,ya:LS,Sa:jS,Aa:VS,Ja:GS,ta:qS,ga:HS,Ra:Ks,$a:WS,Q:YS,r:rI,c:Hs,ib:nI,y:iI,M:oI,D:sI,l:aI,s:Yc,jb:uI,I:lI,R:dI,j:cI,u:pI,q:hI,k:fI,Ma:mI,Na:gI,Oa:bI,Ka:tp,La:rp,ua:np,eb:wI,bb:xI,v:$I,ba:TI,ha:SI,ab:_I,V:II,_a:OI,Ba:EI,F:yI,T:AI,la:bo,za:PI,gb:kI,fb:CI,Ta:ap,Ua:up,Ha:zr,U:lp,ja:dp,Qa:cp,ia:pp,lb:w3,na:f3,mb:y3,oa:h3,G:n3,e:jI,t:FI,w:BI,B:YI,nb:d3,Z:l3,x:GI,pa:c3,X:m3,ca:u3,ob:a3,pb:s3,O:JI,qa:o3,qb:i3,L:t3,Y:p3,d:LI,A:VI,m:UI,kb:_3,p:HI,z:WI,C:qI,E:KI,K:QI,ra:r3,P:g3,da:e3,W:b3,rb:ZI,sa:XI,h:DI,a:hr,db:ht}}}async function re(){function f(x,E){var k=rr=x.exports;x={};for(let[M,U]of Object.entries(k))typeof U=="function"?(k=KS(U),x[M]=k):x[M]=U;return rr=x,rr=(function(){var M=rr,U=ne=>ge=>ne(ge)>>>0,Q=ne=>()=>ne()>>>0;return(M=Object.assign({},M)).tb=U(M.tb),M.Xb=Q(M.Xb),M.Zb=U(M.Zb),M.lc=U(M.lc),M.mc=Q(M.mc),M.qc=U(M.qc),M})(),wc.push(rr._b),hp=(x=rr).tb,fp=x.ub,t._OrtInit=x.vb,t._OrtGetLastError=x.wb,t._OrtCreateSessionOptions=x.xb,t._OrtAppendExecutionProvider=x.yb,t._OrtAddFreeDimensionOverride=x.zb,t._OrtAddSessionConfigEntry=x.Ab,t._OrtReleaseSessionOptions=x.Bb,t._OrtCreateSession=x.Cb,t._OrtReleaseSession=x.Db,t._OrtGetInputOutputCount=x.Eb,t._OrtGetInputOutputMetadata=x.Fb,t._OrtFree=x.Gb,t._OrtCreateTensor=x.Hb,t._OrtGetTensorData=x.Ib,t._OrtReleaseTensor=x.Jb,t._OrtCreateRunOptions=x.Kb,t._OrtAddRunConfigEntry=x.Lb,t._OrtReleaseRunOptions=x.Mb,t._OrtCreateBinding=x.Nb,t._OrtBindInput=x.Ob,t._OrtBindOutput=x.Pb,t._OrtClearBoundOutputs=x.Qb,t._OrtReleaseBinding=x.Rb,t._OrtRunWithBinding=x.Sb,t._OrtRun=x.Tb,t._OrtEndProfiling=x.Ub,t._JsepOutput=x.Vb,t._JsepGetNodeName=x.Wb,yo=x.Xb,Kt=t._free=x.Yb,ri=t._malloc=x.Zb,ra=x.ac,mp=x.bc,gp=x.cc,bp=x.dc,na=x.ec,yp=x.fc,wp=x.gc,Te=x.hc,ni=x.ic,_p=x.jc,we=x.kc,ia=x.lc,_e=x.mc,vp=x.nc,oa=x.oc,xp=x.pc,$p=x.qc,Tp=x.rc,sa=x.sc,Sp=x.tc,Ip=x.uc,Op=x.vc,Ep=x.wc,Ap=x.xc,kp=x.yc,Pp=x.zc,Cp=x.Ac,Rp=x.Bc,Dp=x.Cc,Mp=x.Dc,Np=x.Ec,zp=x.Fc,Bp=x.Gc,Fp=x.Hc,Lp=x.Ic,jp=x.Jc,Up=x.Kc,Vp=x.Lc,Gp=x.Mc,qp=x.Nc,Hp=x.Pc,Wp=x.Qc,Kp=x.$c,Xp=x.ad,Zp=x.fd,Yp=x.kd,Jp=x.ld,Qp=x.md,eh=x.nd,th=x.od,rh=x.pd,nh=x.qd,ih=x.rd,oh=x.wd,sh=x.Ud,ah=x.Vd,uh=x.Wd,lh=x.Xd,h=E,rr}var b,$=W();return t.instantiateWasm?new Promise(x=>{t.instantiateWasm($,(E,k)=>{x(f(E,k))})}):u?f(new WebAssembly.Instance(h,W()),h):(B??=t.locateFile?t.locateFile?t.locateFile("ort-wasm-simd-threaded.jsep.wasm",a):a+"ort-wasm-simd-threaded.jsep.wasm":new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url).href,b=await(async function(x){var E=B;if(!p&&!P(E))try{var k=fetch(E,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(k,x)}catch(M){O(`wasm streaming compile failed: ${M}`),O("falling back to ArrayBuffer instantiation")}return(async function(M,U){try{var Q=await(async function(ne){if(!p)try{var ge=await c(ne);return new Uint8Array(ge)}catch{}if(ne==B&&p)ne=new Uint8Array(p);else{if(!s)throw"both async and sync fetching of the wasm failed";ne=s(ne)}return ne})(M);return await WebAssembly.instantiate(Q,U)}catch(ne){O(`failed to asynchronously prepare wasm: ${ne}`),X(ne)}})(E,x)})($),f(b.instance,b.module))}class le{name="ExitStatus";constructor(b){this.message=`Program terminated with exit(${b})`,this.status=b}}var ce=f=>{f.terminate(),f.onmessage=()=>{}},xe=[],Ge=0,Ve=null,it=f=>{qt.length==0&&($c(),xc(qt[0]));var b=qt.pop();if(!b)return 6;ei.push(b),Br[f.Rc]=b,b.Rc=f.Rc;var $={Sc:"run",Md:f.Ld,bd:f.bd,Rc:f.Rc};return b.postMessage($,f.jd),0},Ze=0,$e=(f,b,...$)=>{var x,E=16*$.length,k=_e(),M=ia(E),U=M>>>3;for(x of $)typeof x=="bigint"?((I(),V)[U++>>>0]=1n,(I(),V)[U++>>>0]=x):((I(),V)[U++>>>0]=0n,(I(),L)[U++>>>0]=x);return f=gp(f,0,E,M,b),we(k),f};function ht(f){if(u)return $e(0,1,f);if(m=f,!(0{if(m=f,u)throw It(f),"unwind";ht(f)},qt=[],ei=[],wc=[],Br={},_c=f=>{var b=f.Rc;delete Br[b],qt.push(f),ei.splice(ei.indexOf(f),1),f.Rc=0,bp(b)};function vc(){wc.forEach(f=>f())}var xc=f=>new Promise(b=>{f.onmessage=E=>{var k=E.data;if(E=k.Sc,k.Zc&&k.Zc!=yo()){var M=Br[k.Zc];M?M.postMessage(k,k.jd):O(`Internal error! Worker sent a message "${E}" to target pthread ${k.Zc}, but that thread no longer exists!`)}else E==="checkMailbox"?po():E==="spawnThread"?it(k):E==="cleanupThread"?co(()=>{_c(Br[k.Nd])}):E==="loaded"?(f.loaded=!0,b(f)):k.target==="setimmediate"?f.postMessage(k):E==="uncaughtException"?f.onerror(k.error):E==="callHandler"?t[k.vd](...k.args):E&&O(`worker sent an unknown command ${E}`)},f.onerror=E=>{throw O(`worker sent an error! ${E.filename}:${E.lineno}: ${E.message}`),E};var $,x=[];for($ of[])t.propertyIsEnumerable($)&&x.push($);f.postMessage({Sc:"load",xd:x,Od:hr,Pd:h})});function $c(){var f=new Worker((()=>{let b=URL;return import.meta.url>"file:"&&import.meta.url<"file;"?new b("ort.all.bundle.min.mjs",import.meta.url):new URL(import.meta.url)})(),{type:"module",workerData:"em-pthread",name:"em-pthread"});qt.push(f)}var hr,pS=(f,b)=>{Ze=0,f=sa(f,b),0>>=0);return(I(),J)[b.Tc+12>>>0]==0&&(Tc(b,!0),uo--),Sc(b,!1),ao.push(b),$p(f)}var On=0,fS=()=>{Te(0,0);var f=ao.pop();vp(f.cd),On=0};function Tc(f,b){b=b?1:0,(I(),J)[f.Tc+12>>>0]=b}function Sc(f,b){b=b?1:0,(I(),J)[f.Tc+13>>>0]=b}class Us{constructor(b){this.cd=b,this.Tc=b-24}}var Vs=f=>{var b=On;if(!b)return ni(0),0;var $=new Us(b);(I(),R)[$.Tc+16>>>2>>>0]=b;var x=(I(),R)[$.Tc+4>>>2>>>0];if(!x)return ni(0),b;for(var E of f){if(E===0||E===x)break;if(xp(E,x,$.Tc+16))return ni(E),b}return ni(x),b};function mS(){return Vs([])}function gS(f){return Vs([f>>>0])}function bS(f,b,$,x){return Vs([f>>>0,b>>>0,$>>>0,x>>>0])}var yS=()=>{var f=ao.pop();f||X("no exception to throw");var b=f.cd;throw(I(),J)[f.Tc+13>>>0]==0&&(ao.push(f),Sc(f,!0),Tc(f,!1),uo++),oa(b),On=b};function wS(f,b,$){var x=new Us(f>>>=0);throw b>>>=0,$>>>=0,(I(),R)[x.Tc+16>>>2>>>0]=0,(I(),R)[x.Tc+4>>>2>>>0]=b,(I(),R)[x.Tc+8>>>2>>>0]=$,oa(f),uo++,On=f}var _S=()=>uo;function Ic(f,b,$,x){return u?$e(2,1,f,b,$,x):Oc(f,b,$,x)}function Oc(f,b,$,x){if(f>>>=0,b>>>=0,$>>>=0,x>>>=0,!globalThis.SharedArrayBuffer)return 6;var E=[];return u&&E.length===0?Ic(f,b,$,x):(f={Ld:$,Rc:f,bd:x,jd:E},u?(f.Sc="spawnThread",postMessage(f,E),0):it(f))}function vS(f){throw On||=f>>>0,On}var Ec=globalThis.TextDecoder&&new TextDecoder,Ac=(f,b,$,x)=>{if($=b+$,x)return $;for(;f[b]&&!(b>=$);)++b;return b},kc=(f,b=0,$,x)=>{if(16<($=Ac(f,b>>>=0,$,x))-b&&f.buffer&&Ec)return Ec.decode(f.buffer instanceof ArrayBuffer?f.subarray(b,$):f.slice(b,$));for(x="";b<$;){var E=f[b++];if(128&E){var k=63&f[b++];if((224&E)==192)x+=String.fromCharCode((31&E)<<6|k);else{var M=63&f[b++];65536>(E=(240&E)==224?(15&E)<<12|k<<6|M:(7&E)<<18|k<<12|M<<6|63&f[b++])?x+=String.fromCharCode(E):(E-=65536,x+=String.fromCharCode(55296|E>>10,56320|1023&E))}}else x+=String.fromCharCode(E)}return x},et=(f,b,$)=>(f>>>=0)?kc((I(),G),f,b,$):"";function Pc(f,b,$){return u?$e(3,1,f,b,$):0}function Cc(f,b){if(u)return $e(4,1,f,b)}function Rc(f,b){if(u)return $e(5,1,f,b)}function Dc(f,b,$){if(u)return $e(6,1,f,b,$)}function Mc(f,b,$){return u?$e(7,1,f,b,$):0}function Nc(f,b){if(u)return $e(8,1,f,b)}function zc(f,b,$){if(u)return $e(9,1,f,b,$)}function Bc(f,b,$,x){if(u)return $e(10,1,f,b,$,x)}function Fc(f,b,$,x){if(u)return $e(11,1,f,b,$,x)}function Lc(f,b,$,x){if(u)return $e(12,1,f,b,$,x)}function jc(f){if(u)return $e(13,1,f)}function Uc(f,b){if(u)return $e(14,1,f,b)}function Vc(f,b,$){if(u)return $e(15,1,f,b,$)}var xS=()=>X(""),Ht=f=>{f>>>=0;for(var b="";;){var $=(I(),G)[f++>>>0];if(!$)return b;b+=String.fromCharCode($)}},Gs={},qs={},$S={},En=class extends Error{constructor(f){super(f),this.name="BindingError"}};function tr(f,b,$={}){return(function(x,E,k={}){var M=E.name;if(!x)throw new En(`type "${M}" must have a positive integer typeid pointer`);if(qs.hasOwnProperty(x)){if(k.yd)return;throw new En(`Cannot register type '${M}' twice`)}qs[x]=E,delete $S[x],Gs.hasOwnProperty(x)&&(E=Gs[x],delete Gs[x],E.forEach(U=>U()))})(f,b,$)}var Gc=(f,b,$)=>{switch(b){case 1:return $?x=>(I(),J)[x>>>0]:x=>(I(),G)[x>>>0];case 2:return $?x=>(I(),C)[x>>>1>>>0]:x=>(I(),ee)[x>>>1>>>0];case 4:return $?x=>(I(),v)[x>>>2>>>0]:x=>(I(),R)[x>>>2>>>0];case 8:return $?x=>(I(),V)[x>>>3>>>0]:x=>(I(),K)[x>>>3>>>0];default:throw new TypeError(`invalid integer width (${b}): ${f}`)}};function TS(f,b,$,x,E){f>>>=0,$>>>=0,b=Ht(b>>>0);let k=M=>M;if(x=x===0n){let M=8*$;k=U=>BigInt.asUintN(M,U),E=k(E)}tr(f,{name:b,Oc:k,Vc:(M,U)=>(typeof U=="number"&&(U=BigInt(U)),U),Uc:Gc(b,$,!x),Wc:null})}function SS(f,b,$,x){tr(f>>>=0,{name:b=Ht(b>>>0),Oc:function(E){return!!E},Vc:function(E,k){return k?$:x},Uc:function(E){return this.Oc((I(),G)[E>>>0])},Wc:null})}var qc=[],Fr=[0,1,,1,null,1,!0,1,!1,1];function Hs(f){9<(f>>>=0)&&--Fr[f+1]===0&&(Fr[f]=void 0,qc.push(f))}var Ot=f=>{if(!f)throw new En(`Cannot use deleted val. handle = ${f}`);return Fr[f]},Mt=f=>{switch(f){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let b=qc.pop()||Fr.length;return Fr[b]=f,Fr[b+1]=1,b}};function Ws(f){return this.Oc((I(),R)[f>>>2>>>0])}var IS={name:"emscripten::val",Oc:f=>{var b=Ot(f);return Hs(f),b},Vc:(f,b)=>Mt(b),Uc:Ws,Wc:null};function OS(f){return tr(f>>>0,IS)}var ES=(f,b)=>{switch(b){case 4:return function($){return this.Oc((I(),H)[$>>>2>>>0])};case 8:return function($){return this.Oc((I(),L)[$>>>3>>>0])};default:throw new TypeError(`invalid float width (${b}): ${f}`)}};function AS(f,b,$){$>>>=0,tr(f>>>=0,{name:b=Ht(b>>>0),Oc:x=>x,Vc:(x,E)=>E,Uc:ES(b,$),Wc:null})}function kS(f,b,$,x,E){f>>>=0,$>>>=0,b=Ht(b>>>0);let k=U=>U;if(x===0){var M=32-8*$;k=U=>U<>>M,E=k(E)}tr(f,{name:b,Oc:k,Vc:(U,Q)=>Q,Uc:Gc(b,$,x!==0),Wc:null})}function PS(f,b,$){function x(k){var M=(I(),R)[k>>>2>>>0];return k=(I(),R)[k+4>>>2>>>0],new E((I(),J).buffer,k,M)}var E=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][b];tr(f>>>=0,{name:$=Ht($>>>0),Oc:x,Uc:x},{yd:!0})}var fr=(f,b,$)=>{var x=(I(),G);if(b>>>=0,0<$){var E=b;$=b+$-1;for(var k=0;k=M){if(b>=$)break;x[b++>>>0]=M}else if(2047>=M){if(b+1>=$)break;x[b++>>>0]=192|M>>6,x[b++>>>0]=128|63&M}else if(65535>=M){if(b+2>=$)break;x[b++>>>0]=224|M>>12,x[b++>>>0]=128|M>>6&63,x[b++>>>0]=128|63&M}else{if(b+3>=$)break;x[b++>>>0]=240|M>>18,x[b++>>>0]=128|M>>12&63,x[b++>>>0]=128|M>>6&63,x[b++>>>0]=128|63&M,k++}}x[b>>>0]=0,f=b-E}else f=0;return f},lo=f=>{for(var b=0,$=0;$=x?b++:2047>=x?b+=2:55296<=x&&57343>=x?(b+=4,++$):b+=3}return b};function CS(f,b){tr(f>>>=0,{name:b=Ht(b>>>0),Oc($){var x=(I(),R)[$>>>2>>>0];return x=et($+4,x,!0),Kt($),x},Vc($,x){x instanceof ArrayBuffer&&(x=new Uint8Array(x));var E=typeof x=="string";if(!(E||ArrayBuffer.isView(x)&&x.BYTES_PER_ELEMENT==1))throw new En("Cannot pass non-string to std::string");var k=E?lo(x):x.length,M=ri(4+k+1),U=M+4;return(I(),R)[M>>>2>>>0]=k,E?fr(x,U,k+1):(I(),G).set(x,U>>>0),$!==null&&$.push(Kt,M),M},Uc:Ws,Wc($){Kt($)}})}var Hc=globalThis.TextDecoder?new TextDecoder("utf-16le"):void 0,RS=(f,b,$)=>{if(f>>>=1,16<(b=Ac((I(),ee),f,b/2,$))-f&&Hc)return Hc.decode((I(),ee).slice(f,b));for($="";f>>0];$+=String.fromCharCode(x)}return $},DS=(f,b,$)=>{if($??=2147483647,2>$)return 0;var x=b;$=($-=2)<2*f.length?$/2:f.length;for(var E=0;E<$;++E){var k=f.charCodeAt(E);(I(),C)[b>>>1>>>0]=k,b+=2}return(I(),C)[b>>>1>>>0]=0,b-x},MS=f=>2*f.length,NS=(f,b,$)=>{var x="";f>>>=2;for(var E=0;!(E>=b/4);E++){var k=(I(),R)[f+E>>>0];if(!k&&!$)break;x+=String.fromCodePoint(k)}return x},zS=(f,b,$)=>{if(b>>>=0,$??=2147483647,4>$)return 0;var x=b;$=x+$-4;for(var E=0;E>>2>>>0]=k,(b+=4)+4>$)break}return(I(),v)[b>>>2>>>0]=0,b-x},BS=f=>{for(var b=0,$=0;$>>=0,b>>>=0,$=Ht($>>>=0),b===2)var x=RS,E=DS,k=MS;else x=NS,E=zS,k=BS;tr(f,{name:$,Oc:M=>{var U=(I(),R)[M>>>2>>>0];return U=x(M+4,U*b,!0),Kt(M),U},Vc:(M,U)=>{if(typeof U!="string")throw new En(`Cannot pass non-string to C++ string type ${$}`);var Q=k(U),ne=ri(4+Q+b);return(I(),R)[ne>>>2>>>0]=Q/b,E(U,ne+4,Q+b),M!==null&&M.push(Kt,ne),ne},Uc:Ws,Wc(M){Kt(M)}})}function LS(f,b){tr(f>>>=0,{zd:!0,name:b=Ht(b>>>0),Oc:()=>{},Vc:()=>{}})}function jS(f){ra(f>>>0,!i,1,!n,131072,!1),vc()}var co=f=>{if(!A)try{if(f(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ks(f){f>>>=0,US||(Atomics.waitAsync((I(),v),f>>>2,f).value.then(po),f+=128,Atomics.store((I(),v),f>>>2,1))}var po=()=>co(()=>{var f=yo();f&&(Ks(f),wp())});function VS(f,b){(f>>>=0)==b>>>0?setTimeout(po):u?postMessage({Zc:f,Sc:"checkMailbox"}):(f=Br[f])&&f.postMessage({Sc:"checkMailbox"})}var Xs=[];function GS(f,b,$,x,E){for(b>>>=0,E>>>=0,Xs.length=0,$=E>>>3,x=E+x>>>3;$>>0]?(I(),V)[$++>>>0]:(I(),L)[$++>>>0],Xs.push(k)}return(b?aa[b]:MI[f])(...Xs)}var qS=()=>{Ze=0};function HS(f){f>>>=0,u?postMessage({Sc:"cleanupThread",Nd:f}):_c(Br[f])}function WS(f){}var ho=f=>{try{f()}catch(b){X(b)}};function KS(f){var b=(...$)=>{fo.push(f);try{return f(...$)}finally{A||(fo.pop(),Wt&&mr===1&&fo.length===0&&(mr=0,Ze+=1,ho(ah),typeof Fibers<"u"&&Fibers.be()))}};return Xc.set(f,b),b}var mr=0,Wt=null,Wc=0,fo=[],Zs=new Map,Kc=new Map,Xc=new Map,XS=0,Ys=null,ZS=[],Zc=f=>(function(b){if(!A){if(mr===0){var $=!1,x=!1;b((E=0)=>{if(!A&&(Wc=E,$=!0,x)){mr=2,ho(()=>uh(Wt)),typeof MainLoop<"u"&&MainLoop.ud&&MainLoop.resume(),E=!1;try{var k=(function(){var Q=(I(),v)[Wt+8>>>2>>>0];return Q=Kc.get(Q),Q=Xc.get(Q),--Ze,Q()})()}catch(Q){k=Q,E=!0}var M=!1;if(!Wt){var U=Ys;U&&(Ys=null,(E?U.reject:U.resolve)(k),M=!0)}if(E&&!M)throw k}}),x=!0,$||(mr=1,Wt=(function(){var E=ri(65548),k=E+12;if((I(),R)[E>>>2>>>0]=k,(I(),R)[E+4>>>2>>>0]=k+65536,k=fo[0],!Zs.has(k)){var M=XS++;Zs.set(k,M),Kc.set(M,k)}return k=Zs.get(k),(I(),v)[E+8>>>2>>>0]=k,E})(),typeof MainLoop<"u"&&MainLoop.ud&&MainLoop.pause(),ho(()=>sh(Wt)))}else mr===2?(mr=0,ho(lh),Kt(Wt),Wt=null,ZS.forEach(co)):X(`invalid state: ${mr}`);return Wc}})(b=>{f().then(b)});function YS(f){return f>>>=0,Zc(async()=>{var b=await Ot(f);return Mt(b)})}var Js=[],JS=f=>{var b=Js.length;return Js.push(f),b},QS=(f,b)=>{for(var $=Array(f),x=0;x>>2>>>0],M=qs[k];if(M===void 0)throw f=`parameter ${x}`,k=hp(k),b=Ht(k),Kt(k),new En(`${f} has unknown type ${b}`);$[E]=M}return $},eI=(f,b,$)=>{var x=[];return f=f(x,$),x.length&&((I(),R)[b>>>2>>>0]=Mt(x)),f},tI={},mo=f=>{var b=tI[f];return b===void 0?Ht(f):b};function rI(f,b,$){var[x,...E]=QS(f,b>>>0);b=x.Vc.bind(x);var k=E.map(Q=>Q.Uc.bind(Q));f--;var M={toValue:Ot};switch(f=k.map((Q,ne)=>{var ge=`argFromPtr${ne}`;return M[ge]=Q,`${ge}(args${ne?"+"+8*ne:""})`}),$){case 0:var U="toValue(handle)";break;case 2:U="new (toValue(handle))";break;case 3:U="";break;case 1:M.getStringOrSymbol=mo,U="toValue(handle)[getStringOrSymbol(methodName)]"}return U+=`(${f})`,x.zd||(M.toReturnWire=b,M.emval_returnValue=eI,U=`return emval_returnValue(toReturnWire, destructorsRef, ${U})`),U=`return function (handle, methodName, destructorsRef, args) { ${U} - }`,$=new Function(Object.keys(M),U)(...Object.values(M)),U=`methodCaller<(${E.map(Q=>Q.name)}) => ${x.name}>`,GS(Object.defineProperty($,"name",{value:U}))}function ZS(f,b){return b>>>=0,(f=Ot(f>>>0))==Ot(b)}function YS(f){return(f>>>=0)?(f=ho(f),Mt(globalThis[f])):Mt(globalThis)}function JS(f){return f=ho(f>>>0),Mt(t[f])}function QS(f,b){return b>>>=0,f=Ot(f>>>0),b=Ot(b),Mt(f[b])}function eI(f){9<(f>>>=0)&&(Fr[f+1]+=1)}function Hc(f,b,$,x,E){return Xs[f>>>0](b>>>0,$>>>0,x>>>0,E>>>0)}function tI(f,b,$,x,E){return Hc(f>>>0,b>>>0,$>>>0,x>>>0,E>>>0)}function rI(){return Mt([])}function nI(f){f=Ot(f>>>0);for(var b=Array(f.length),$=0;$>>0))}function oI(){return Mt({})}function sI(f){for(var b=Ot(f>>>=0);b.length;){var $=b.pop();b.pop()($)}Vs(f)}function aI(f,b,$){b>>>=0,$>>>=0,f=Ot(f>>>0),b=Ot(b),$=Ot($),f[b]=$}function uI(f,b){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),(I(),v)[b>>>2>>>0]=f.getUTCSeconds(),(I(),v)[b+4>>>2>>>0]=f.getUTCMinutes(),(I(),v)[b+8>>>2>>>0]=f.getUTCHours(),(I(),v)[b+12>>>2>>>0]=f.getUTCDate(),(I(),v)[b+16>>>2>>>0]=f.getUTCMonth(),(I(),v)[b+20>>>2>>>0]=f.getUTCFullYear()-1900,(I(),v)[b+24>>>2>>>0]=f.getUTCDay(),f=(f.getTime()-Date.UTC(f.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(I(),v)[b+28>>>2>>>0]=f}var Wc=f=>f%4==0&&(f%100!=0||f%400==0),Kc=[0,31,60,91,121,152,182,213,244,274,305,335],Xc=[0,31,59,90,120,151,181,212,243,273,304,334];function lI(f,b){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),(I(),v)[b>>>2>>>0]=f.getSeconds(),(I(),v)[b+4>>>2>>>0]=f.getMinutes(),(I(),v)[b+8>>>2>>>0]=f.getHours(),(I(),v)[b+12>>>2>>>0]=f.getDate(),(I(),v)[b+16>>>2>>>0]=f.getMonth(),(I(),v)[b+20>>>2>>>0]=f.getFullYear()-1900,(I(),v)[b+24>>>2>>>0]=f.getDay();var $=(Wc(f.getFullYear())?Kc:Xc)[f.getMonth()]+f.getDate()-1|0;(I(),v)[b+28>>>2>>>0]=$,(I(),v)[b+36>>>2>>>0]=-60*f.getTimezoneOffset(),$=new Date(f.getFullYear(),6,1).getTimezoneOffset();var x=new Date(f.getFullYear(),0,1).getTimezoneOffset();f=0|($!=x&&f.getTimezoneOffset()==Math.min(x,$)),(I(),v)[b+32>>>2>>>0]=f}function dI(f){f>>>=0;var b=new Date((I(),v)[f+20>>>2>>>0]+1900,(I(),v)[f+16>>>2>>>0],(I(),v)[f+12>>>2>>>0],(I(),v)[f+8>>>2>>>0],(I(),v)[f+4>>>2>>>0],(I(),v)[f>>>2>>>0],0),$=(I(),v)[f+32>>>2>>>0],x=b.getTimezoneOffset(),E=new Date(b.getFullYear(),6,1).getTimezoneOffset(),k=new Date(b.getFullYear(),0,1).getTimezoneOffset(),M=Math.min(k,E);return 0>$?(I(),v)[f+32>>>2>>>0]=+(E!=k&&M==x):0<$!=(M==x)&&(E=Math.max(k,E),b.setTime(b.getTime()+6e4*((0<$?M:E)-x))),(I(),v)[f+24>>>2>>>0]=b.getDay(),$=(Wc(b.getFullYear())?Kc:Xc)[b.getMonth()]+b.getDate()-1|0,(I(),v)[f+28>>>2>>>0]=$,(I(),v)[f>>>2>>>0]=b.getSeconds(),(I(),v)[f+4>>>2>>>0]=b.getMinutes(),(I(),v)[f+8>>>2>>>0]=b.getHours(),(I(),v)[f+12>>>2>>>0]=b.getDate(),(I(),v)[f+16>>>2>>>0]=b.getMonth(),(I(),v)[f+20>>>2>>>0]=b.getYear(),f=b.getTime(),BigInt(isNaN(f)?-1:f/1e3)}function Zc(f,b,$,x,E,k,M){return u?$e(16,1,f,b,$,x,E,k,M):-52}function Yc(f,b,$,x,E,k){if(u)return $e(17,1,f,b,$,x,E,k)}var Qn={},cI=()=>performance.timeOrigin+performance.now();function Jc(f,b){if(u)return $e(18,1,f,b);if(Qn[f]&&(clearTimeout(Qn[f].id),delete Qn[f]),!b)return 0;var $=setTimeout(()=>{delete Qn[f],uo(()=>hp(f,performance.timeOrigin+performance.now()))},b);return Qn[f]={id:$,ae:b},0}function pI(f,b,$,x){f>>>=0,b>>>=0,$>>>=0,x>>>=0;var E=new Date().getFullYear(),k=new Date(E,0,1).getTimezoneOffset();E=new Date(E,6,1).getTimezoneOffset();var M=Math.max(k,E);(I(),R)[f>>>2>>>0]=60*M,(I(),v)[b>>>2>>>0]=+(k!=E),f=(b=U=>{var Q=Math.abs(U);return`UTC${0<=U?"-":"+"}${String(Math.floor(Q/60)).padStart(2,"0")}${String(Q%60).padStart(2,"0")}`})(k),b=b(E),EDate.now(),fI=1;function mI(f,b,$){if($>>>=0,!(0<=f&&3>=f))return 28;if(f===0)f=Date.now();else{if(!fI)return 52;f=performance.timeOrigin+performance.now()}return f=Math.round(1e6*f),(I(),V)[$>>>3>>>0]=BigInt(f),0}var Zs=[],Qc=(f,b)=>{Zs.length=0;for(var $;$=(I(),q)[f++>>>0];){var x=$!=105;b+=(x&=$!=112)&&b%8?4:0,Zs.push($==112?(I(),R)[b>>>2>>>0]:$==106?(I(),V)[b>>>3>>>0]:$==105?(I(),v)[b>>>2>>>0]:(I(),L)[b>>>3>>>0]),b+=x?8:4}return Zs};function gI(f,b,$){return f>>>=0,b=Qc(b>>>0,$>>>0),ia[f](...b)}function bI(f,b,$){return f>>>=0,b=Qc(b>>>0,$>>>0),ia[f](...b)}var yI=()=>{};function wI(f,b){return O(et(f>>>0,b>>>0))}var _I=()=>{throw Ze+=1,"unwind"};function vI(){return 4294901760}var xI=()=>navigator.hardwareConcurrency,Lr={},fo=f=>{var b;return(b=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(f))?+b[1]:(b=/:(\d+):\d+(?:\)|$)/.exec(f))?2147483648|+b[1]:0},ep=f=>{for(var b of f)(f=fo(b))&&(Lr[f]=b)};function $I(){var f=Error().stack.toString().split(` -`);return f[0]=="Error"&&f.shift(),ep(f),Lr.gd=fo(f[3]),Lr.Jd=f,Lr.gd}function mo(f){if(!(f=Lr[f>>>0]))return 0;var b;if(b=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(f))f=b[1];else if(b=/^\s+at (.*) \(.*\)$/.exec(f))f=b[1];else{if(!(b=/^(.+?)@/.exec(f)))return 0;f=b[1]}Kt(mo.hd??0),b=ao(f)+1;var $=ei(b);return $&&fr(f,$,b),mo.hd=$,mo.hd}function TI(f){f>>>=0;var b=(I(),q).length;if(f<=b||4294901760=$;$*=2){var x=b*(1+.2/$);x=Math.min(x,f+100663296);e:{x=(Math.min(4294901760,65536*Math.ceil(Math.max(f,x)/65536))-hr.buffer.byteLength+65535)/65536|0;try{hr.grow(x),Y();var E=1;break e}catch{}E=void 0}if(E)return!0}return!1}function SI(f,b,$){if(f>>>=0,b>>>=0,Lr.gd==f)var x=Lr.Jd;else(x=Error().stack.toString().split(` -`))[0]=="Error"&&x.shift(),ep(x);for(var E=3;x[E]&&fo(x[E])!=f;)++E;for(f=0;f<$&&x[f+E];++f)(I(),v)[b+4*f>>>2>>>0]=fo(x[f+E]);return f}var Ys,Js={},tp=()=>{if(!Ys){var f,b={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(f in Js)Js[f]===void 0?delete b[f]:b[f]=Js[f];var $=[];for(f in b)$.push(`${f}=${b[f]}`);Ys=$}return Ys};function rp(f,b){if(u)return $e(19,1,f,b);f>>>=0,b>>>=0;var $,x=0,E=0;for($ of tp()){var k=b+x;(I(),R)[f+E>>>2>>>0]=k,x+=fr($,k,1/0)+1,E+=4}return 0}function np(f,b){if(u)return $e(20,1,f,b);f>>>=0,b>>>=0;var $=tp();for(var x of((I(),R)[f>>>2>>>0]=$.length,f=0,$))f+=ao(x)+1;return(I(),R)[b>>>2>>>0]=f,0}function ip(f){return u?$e(21,1,f):52}function op(f,b,$,x){return u?$e(22,1,f,b,$,x):52}function sp(f,b,$,x){return u?$e(23,1,f,b,$,x):70}var II=[null,[],[]];function ap(f,b,$,x){if(u)return $e(24,1,f,b,$,x);b>>>=0,$>>>=0,x>>>=0;for(var E=0,k=0;k<$;k++){var M=(I(),R)[b>>>2>>>0],U=(I(),R)[b+4>>>2>>>0];b+=8;for(var Q=0;Q>>0],Oe=II[ne];ge===0||ge===10?((ne===1?S:O)(Sc(Oe)),Oe.length=0):Oe.push(ge)}E+=U}return(I(),R)[x>>>2>>>0]=E,0}function OI(f){return f>>>0}u||(function(){for(var f=t.numThreads-1;f--;)yc();xe.push(async()=>{var b=(async function(){if(!u)return Promise.all(Gt.map(bc))})();qe++,await b,--qe==0&&Ve&&(b=Ve,Ve=null,b())})})(),u||(hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Y()),t.wasmBinary&&(p=t.wasmBinary),t.stackSave=()=>_e(),t.stackRestore=f=>we(f),t.stackAlloc=f=>ta(f),t.setValue=function(f,b,$="i8"){switch($.endsWith("*")&&($="*"),$){case"i1":case"i8":(I(),J)[f>>>0]=b;break;case"i16":(I(),C)[f>>>1>>>0]=b;break;case"i32":(I(),v)[f>>>2>>>0]=b;break;case"i64":(I(),V)[f>>>3>>>0]=BigInt(b);break;case"float":(I(),H)[f>>>2>>>0]=b;break;case"double":(I(),L)[f>>>3>>>0]=b;break;case"*":(I(),R)[f>>>2>>>0]=b;break;default:X(`invalid type for setValue: ${$}`)}},t.getValue=function(f,b="i8"){switch(b.endsWith("*")&&(b="*"),b){case"i1":case"i8":return(I(),J)[f>>>0];case"i16":return(I(),C)[f>>>1>>>0];case"i32":return(I(),v)[f>>>2>>>0];case"i64":return(I(),V)[f>>>3>>>0];case"float":return(I(),H)[f>>>2>>>0];case"double":return(I(),L)[f>>>3>>>0];case"*":return(I(),R)[f>>>2>>>0];default:X(`invalid type for getValue: ${b}`)}},t.UTF8ToString=et,t.stringToUTF8=fr,t.lengthBytesUTF8=ao;var up,lp,go,Kt,ei,Qs,dp,cp,pp,ea,hp,fp,Te,ti,mp,we,ta,_e,gp,ra,bp,yp,wp,na,_p,vp,xp,$p,Tp,Sp,Ip,Op,Ep,Ap,kp,Pp,Cp,Rp,Dp,Mp,Np,zp,Bp,Fp,Lp,jp,Up,Vp,qp,Gp,Hp,Wp,Kp,Xp,Zp,Yp,Jp,Qp,eh,th,rh,nh,ih,rr,EI=[ht,It,vc,Ic,Oc,Ec,Ac,kc,Pc,Cc,Rc,Dc,Mc,Nc,zc,Bc,Zc,Yc,Jc,rp,np,ip,op,sp,ap],ia={1055492:(f,b,$,x,E)=>{if(t===void 0||!t.Yc)return 1;if((f=et(Number(f>>>0))).startsWith("./")&&(f=f.substring(2)),!(f=t.Yc.get(f)))return 2;if(b=Number(b>>>0),$=Number($>>>0),x=Number(x>>>0),b+$>f.byteLength)return 3;try{let k=f.subarray(b,b+$);switch(E){case 0:(I(),q).set(k,x>>>0);break;case 1:t.Qd?t.Qd(x,k):t.Id(x,k);break;default:return 4}return 0}catch{return 4}},1056316:(f,b,$)=>{t.td(f,(I(),q).subarray(b>>>0,b+$>>>0))},1056380:()=>t.Sd(),1056422:f=>{t.sd(f)},1056459:()=>{t.Bd()},1056490:()=>{t.Cd()},1056519:()=>{t.Gd()},1056544:f=>t.Ad(f),1056577:f=>t.Ed(f),1056609:(f,b,$)=>{t.ed(Number(f),Number(b),Number($),!0)},1056672:(f,b,$)=>{t.ed(Number(f),Number(b),Number($))},1056729:()=>typeof wasmOffsetConverter<"u",1056786:f=>{t.$b("Abs",f,void 0)},1056837:f=>{t.$b("Neg",f,void 0)},1056888:f=>{t.$b("Floor",f,void 0)},1056941:f=>{t.$b("Ceil",f,void 0)},1056993:f=>{t.$b("Reciprocal",f,void 0)},1057051:f=>{t.$b("Sqrt",f,void 0)},1057103:f=>{t.$b("Exp",f,void 0)},1057154:f=>{t.$b("Erf",f,void 0)},1057205:f=>{t.$b("Sigmoid",f,void 0)},1057260:(f,b,$)=>{t.$b("HardSigmoid",f,{alpha:b,beta:$})},1057339:f=>{t.$b("HardSwish",f,void 0)},1057396:f=>{t.$b("Log",f,void 0)},1057447:f=>{t.$b("Sin",f,void 0)},1057498:f=>{t.$b("Cos",f,void 0)},1057549:f=>{t.$b("Tan",f,void 0)},1057600:f=>{t.$b("Asin",f,void 0)},1057652:f=>{t.$b("Acos",f,void 0)},1057704:f=>{t.$b("Atan",f,void 0)},1057756:f=>{t.$b("Sinh",f,void 0)},1057808:f=>{t.$b("Cosh",f,void 0)},1057860:f=>{t.$b("Asinh",f,void 0)},1057913:f=>{t.$b("Acosh",f,void 0)},1057966:f=>{t.$b("Atanh",f,void 0)},1058019:f=>{t.$b("Tanh",f,void 0)},1058071:f=>{t.$b("Not",f,void 0)},1058122:(f,b,$)=>{t.$b("Clip",f,{min:b,max:$})},1058191:f=>{t.$b("Clip",f,void 0)},1058243:(f,b)=>{t.$b("Elu",f,{alpha:b})},1058301:f=>{t.$b("Gelu",f,void 0)},1058353:f=>{t.$b("Relu",f,void 0)},1058405:(f,b)=>{t.$b("LeakyRelu",f,{alpha:b})},1058469:(f,b)=>{t.$b("ThresholdedRelu",f,{alpha:b})},1058539:(f,b)=>{t.$b("Cast",f,{to:b})},1058597:f=>{t.$b("Add",f,void 0)},1058648:f=>{t.$b("Sub",f,void 0)},1058699:f=>{t.$b("Mul",f,void 0)},1058750:f=>{t.$b("Div",f,void 0)},1058801:f=>{t.$b("Pow",f,void 0)},1058852:f=>{t.$b("Equal",f,void 0)},1058905:f=>{t.$b("Greater",f,void 0)},1058960:f=>{t.$b("GreaterOrEqual",f,void 0)},1059022:f=>{t.$b("Less",f,void 0)},1059074:f=>{t.$b("LessOrEqual",f,void 0)},1059133:(f,b,$,x,E)=>{t.$b("ReduceMean",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059308:(f,b,$,x,E)=>{t.$b("ReduceMax",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059482:(f,b,$,x,E)=>{t.$b("ReduceMin",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059656:(f,b,$,x,E)=>{t.$b("ReduceProd",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059831:(f,b,$,x,E)=>{t.$b("ReduceSum",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060005:(f,b,$,x,E)=>{t.$b("ReduceL1",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060178:(f,b,$,x,E)=>{t.$b("ReduceL2",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060351:(f,b,$,x,E)=>{t.$b("ReduceLogSum",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060528:(f,b,$,x,E)=>{t.$b("ReduceSumSquare",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060708:(f,b,$,x,E)=>{t.$b("ReduceLogSumExp",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060888:f=>{t.$b("Where",f,void 0)},1060941:(f,b,$)=>{t.$b("Transpose",f,{perm:b?Array.from((I(),v).subarray(Number(b)>>>0,Number($)>>>0)):[]})},1061065:(f,b,$,x)=>{t.$b("DepthToSpace",f,{blocksize:b,mode:et($),format:x?"NHWC":"NCHW"})},1061198:(f,b,$,x)=>{t.$b("DepthToSpace",f,{blocksize:b,mode:et($),format:x?"NHWC":"NCHW"})},1061331:(f,b,$,x)=>{t.$b("DFT",f,{axis:b,inverse:$,onesided:x})},1061423:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr)=>{t.$b("ConvTranspose",f,{format:Q?"NHWC":"NCHW",autoPad:b,dilations:[$],group:x,kernelShape:[E],pads:[k,M],strides:[U],wIsConst:()=>!!(I(),J)[ne>>>0],outputPadding:ge?Array.from((I(),v).subarray(Number(ge)>>>0,Number(Oe)>>>0)):[],outputShape:Ne?Array.from((I(),v).subarray(Number(Ne)>>>0,Number(Fe)>>>0)):[],activation:et(gr)})},1061856:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("ConvTranspose",f,{format:U?"NHWC":"NCHW",autoPad:b,dilations:Array.from((I(),v).subarray(Number($)>>>0,(Number($)>>>0)+2>>>0)),group:x,kernelShape:Array.from((I(),v).subarray(Number(E)>>>0,(Number(E)>>>0)+2>>>0)),pads:Array.from((I(),v).subarray(Number(k)>>>0,(Number(k)>>>0)+4>>>0)),strides:Array.from((I(),v).subarray(Number(M)>>>0,(Number(M)>>>0)+2>>>0)),wIsConst:()=>!!(I(),J)[Q>>>0],outputPadding:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],outputShape:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[],activation:et(Fe)})},1062517:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr)=>{t.$b("ConvTranspose",f,{format:Q?"NHWC":"NCHW",autoPad:b,dilations:[$],group:x,kernelShape:[E],pads:[k,M],strides:[U],wIsConst:()=>!!(I(),J)[ne>>>0],outputPadding:ge?Array.from((I(),v).subarray(Number(ge)>>>0,Number(Oe)>>>0)):[],outputShape:Ne?Array.from((I(),v).subarray(Number(Ne)>>>0,Number(Fe)>>>0)):[],activation:et(gr)})},1062950:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("ConvTranspose",f,{format:U?"NHWC":"NCHW",autoPad:b,dilations:Array.from((I(),v).subarray(Number($)>>>0,(Number($)>>>0)+2>>>0)),group:x,kernelShape:Array.from((I(),v).subarray(Number(E)>>>0,(Number(E)>>>0)+2>>>0)),pads:Array.from((I(),v).subarray(Number(k)>>>0,(Number(k)>>>0)+4>>>0)),strides:Array.from((I(),v).subarray(Number(M)>>>0,(Number(M)>>>0)+2>>>0)),wIsConst:()=>!!(I(),J)[Q>>>0],outputPadding:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],outputShape:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[],activation:et(Fe)})},1063611:(f,b)=>{t.$b("GlobalAveragePool",f,{format:b?"NHWC":"NCHW"})},1063702:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("AveragePool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1064181:(f,b)=>{t.$b("GlobalAveragePool",f,{format:b?"NHWC":"NCHW"})},1064272:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("AveragePool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1064751:(f,b)=>{t.$b("GlobalMaxPool",f,{format:b?"NHWC":"NCHW"})},1064838:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("MaxPool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1065313:(f,b)=>{t.$b("GlobalMaxPool",f,{format:b?"NHWC":"NCHW"})},1065400:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("MaxPool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1065875:(f,b,$,x,E)=>{t.$b("Gemm",f,{alpha:b,beta:$,transA:x,transB:E})},1065979:f=>{t.$b("MatMul",f,void 0)},1066033:(f,b,$,x)=>{t.$b("ArgMax",f,{keepDims:!!b,selectLastIndex:!!$,axis:x})},1066141:(f,b,$,x)=>{t.$b("ArgMin",f,{keepDims:!!b,selectLastIndex:!!$,axis:x})},1066249:(f,b)=>{t.$b("Softmax",f,{axis:b})},1066312:(f,b)=>{t.$b("Concat",f,{axis:b})},1066372:(f,b,$,x,E)=>{t.$b("Split",f,{axis:b,numOutputs:$,splitSizes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1066528:f=>{t.$b("Expand",f,void 0)},1066582:(f,b)=>{t.$b("Gather",f,{axis:Number(b)})},1066653:(f,b)=>{t.$b("GatherElements",f,{axis:Number(b)})},1066732:(f,b)=>{t.$b("GatherND",f,{batch_dims:Number(b)})},1066811:(f,b,$,x,E,k,M,U,Q,ne,ge)=>{t.$b("Resize",f,{antialias:b,axes:$?Array.from((I(),v).subarray(Number($)>>>0,Number(x)>>>0)):[],coordinateTransformMode:et(E),cubicCoeffA:k,excludeOutside:M,extrapolationValue:U,keepAspectRatioPolicy:et(Q),mode:et(ne),nearestMode:et(ge)})},1067173:(f,b,$,x,E,k,M)=>{t.$b("Slice",f,{starts:b?Array.from((I(),v).subarray(Number(b)>>>0,Number($)>>>0)):[],ends:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[],axes:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[]})},1067437:f=>{t.$b("Tile",f,void 0)},1067489:(f,b,$)=>{t.$b("InstanceNormalization",f,{epsilon:b,format:$?"NHWC":"NCHW"})},1067603:(f,b,$)=>{t.$b("InstanceNormalization",f,{epsilon:b,format:$?"NHWC":"NCHW"})},1067717:f=>{t.$b("Range",f,void 0)},1067770:(f,b)=>{t.$b("Einsum",f,{equation:et(b)})},1067851:(f,b,$,x,E)=>{t.$b("Pad",f,{mode:b,value:$,pads:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1067994:(f,b,$,x,E,k)=>{t.$b("BatchNormalization",f,{epsilon:b,momentum:$,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},1068163:(f,b,$,x,E,k)=>{t.$b("BatchNormalization",f,{epsilon:b,momentum:$,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},1068332:(f,b,$)=>{t.$b("CumSum",f,{exclusive:Number(b),reverse:Number($)})},1068429:(f,b,$)=>{t.$b("DequantizeLinear",f,{axis:b,blockSize:$})},1068519:(f,b,$,x,E)=>{t.$b("GridSample",f,{align_corners:b,mode:et($),padding_mode:et(x),format:E?"NHWC":"NCHW"})},1068689:(f,b,$,x,E)=>{t.$b("GridSample",f,{align_corners:b,mode:et($),padding_mode:et(x),format:E?"NHWC":"NCHW"})},1068859:(f,b)=>{t.$b("ScatterND",f,{reduction:et(b)})},1068944:(f,b,$,x,E,k,M,U,Q)=>{t.$b("Attention",f,{numHeads:b,isUnidirectional:$,maskFilterValue:x,scale:E,doRotary:k,qkvHiddenSizes:M?Array.from((I(),v).subarray(Number(U)>>>0,Number(U)+M>>>0)):[],pastPresentShareBuffer:!!Q})},1069216:f=>{t.$b("BiasAdd",f,void 0)},1069271:f=>{t.$b("BiasSplitGelu",f,void 0)},1069332:f=>{t.$b("FastGelu",f,void 0)},1069388:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr,oa)=>{t.$b("Conv",f,{format:Oe?"NHWC":"NCHW",auto_pad:b,dilations:$?Array.from((I(),v).subarray(Number($)>>>0,Number(x)>>>0)):[],group:E,kernel_shape:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],pads:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],strides:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],w_is_const:()=>!!(I(),J)[Number(Ne)>>>0],activation:et(Fe),activation_params:gr?Array.from((I(),H).subarray(Number(gr)>>>0,Number(oa)>>>0)):[]})},1069972:f=>{t.$b("Gelu",f,void 0)},1070024:(f,b,$,x,E,k,M,U,Q)=>{t.$b("GroupQueryAttention",f,{numHeads:b,kvNumHeads:$,scale:x,softcap:E,doRotary:k,rotaryInterleaved:M,smoothSoftmax:U,localWindowSize:Q})},1070241:(f,b,$,x)=>{t.$b("LayerNormalization",f,{axis:b,epsilon:$,simplified:!!x})},1070352:(f,b,$,x)=>{t.$b("LayerNormalization",f,{axis:b,epsilon:$,simplified:!!x})},1070463:(f,b,$,x,E,k)=>{t.$b("MatMulNBits",f,{k:b,n:$,accuracyLevel:x,bits:E,blockSize:k})},1070590:(f,b,$,x,E,k)=>{t.$b("MultiHeadAttention",f,{numHeads:b,isUnidirectional:$,maskFilterValue:x,scale:E,doRotary:k})},1070749:(f,b)=>{t.$b("QuickGelu",f,{alpha:b})},1070813:(f,b,$,x,E)=>{t.$b("RotaryEmbedding",f,{interleaved:!!b,numHeads:$,rotaryEmbeddingDim:x,scale:E})},1070952:(f,b,$)=>{t.$b("SkipLayerNormalization",f,{epsilon:b,simplified:!!$})},1071054:(f,b,$)=>{t.$b("SkipLayerNormalization",f,{epsilon:b,simplified:!!$})},1071156:(f,b,$,x)=>{t.$b("GatherBlockQuantized",f,{gatherAxis:b,quantizeAxis:$,blockSize:x})},1071277:f=>{t.Fd(f)},1071311:(f,b)=>t.Hd(Number(f),Number(b),t.Xc.Kd,t.Xc.errors)};function AI(f,b,$){return Gc(async()=>{await t.Dd(Number(f),Number(b),Number($))})}function kI(){return typeof wasmOffsetConverter<"u"}function PI(f,b,$,x){var E=_e();try{return Op(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function CI(f,b,$){var x=_e();try{return $p(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function RI(f){var b=_e();try{_p(f)}catch($){if(we(b),$!==$+0)throw $;Te(1,0)}}function DI(f,b){var $=_e();try{return na(f,b)}catch(x){if(we($),x!==x+0)throw x;Te(1,0)}}function MI(f,b,$){var x=_e();try{wp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function NI(f,b){var $=_e();try{Ep(f,b)}catch(x){if(we($),x!==x+0)throw x;Te(1,0)}}function zI(f,b,$,x,E,k,M){var U=_e();try{return Sp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function BI(f,b,$,x,E,k){var M=_e();try{vp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function FI(f,b,$,x){var E=_e();try{Ip(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function LI(f,b,$,x,E){var k=_e();try{xp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function jI(f,b,$,x,E,k,M){var U=_e();try{kp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function UI(f,b,$,x,E,k,M){var U=_e();try{Pp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function VI(f,b,$,x,E,k,M,U){var Q=_e();try{Mp(f,b,$,x,E,k,M,U)}catch(ne){if(we(Q),ne!==ne+0)throw ne;Te(1,0)}}function qI(f,b,$,x,E){var k=_e();try{return Ap(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function GI(f,b,$){var x=_e();try{return Np(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function HI(f,b,$,x,E,k,M,U){var Q=_e();try{zp(f,b,$,x,E,k,M,U)}catch(ne){if(we(Q),ne!==ne+0)throw ne;Te(1,0)}}function WI(f,b,$,x,E,k,M,U,Q,ne,ge,Oe){var Ne=_e();try{Cp(f,b,$,x,E,k,M,U,Q,ne,ge,Oe)}catch(Fe){if(we(Ne),Fe!==Fe+0)throw Fe;Te(1,0)}}function KI(f,b,$){var x=_e();try{return Bp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;return Te(1,0),0n}}function XI(f,b,$,x,E,k,M,U,Q){var ne=_e();try{Tp(f,b,$,x,E,k,M,U,Q)}catch(ge){if(we(ne),ge!==ge+0)throw ge;Te(1,0)}}function ZI(f){var b=_e();try{return Fp(f)}catch($){if(we(b),$!==$+0)throw $;Te(1,0)}}function YI(f,b){var $=_e();try{return eh(f,b)}catch(x){if(we($),x!==x+0)throw x;return Te(1,0),0n}}function JI(f){var b=_e();try{return Lp(f)}catch($){if(we(b),$!==$+0)throw $;return Te(1,0),0n}}function QI(f,b,$,x){var E=_e();try{return Hp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function e3(f,b,$,x,E){var k=_e();try{return Wp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function t3(f,b,$,x,E,k){var M=_e();try{return Kp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function r3(f,b,$,x,E,k){var M=_e();try{return Rp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function n3(f,b,$,x,E,k){var M=_e();try{return Xp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function i3(f,b,$,x,E,k,M,U){var Q=_e();try{return Dp(f,b,$,x,E,k,M,U)}catch(ne){if(we(Q),ne!==ne+0)throw ne;Te(1,0)}}function o3(f,b,$,x,E){var k=_e();try{return Zp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;return Te(1,0),0n}}function s3(f,b,$,x){var E=_e();try{return Yp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function a3(f,b,$,x){var E=_e();try{return Jp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function u3(f,b,$,x,E,k,M,U,Q,ne,ge,Oe){var Ne=_e();try{return Qp(f,b,$,x,E,k,M,U,Q,ne,ge,Oe)}catch(Fe){if(we(Ne),Fe!==Fe+0)throw Fe;Te(1,0)}}function l3(f,b,$,x,E,k,M,U,Q,ne,ge){var Oe=_e();try{qp(f,b,$,x,E,k,M,U,Q,ne,ge)}catch(Ne){if(we(Oe),Ne!==Ne+0)throw Ne;Te(1,0)}}function d3(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr,oa){var f3=_e();try{Gp(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr,oa)}catch(sa){if(we(f3),sa!==sa+0)throw sa;Te(1,0)}}function c3(f,b,$){var x=_e();try{return jp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function p3(f,b,$){var x=_e();try{return Up(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function h3(f,b,$,x){var E=_e();try{Vp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function bo(){if(0{g=f,_=b})}var px,Sm,HA=D(()=>{"use strict";px=Tm,Sm=globalThis.self?.name?.startsWith("em-pthread"),Sm&&Tm()}),Ua,Al,Im,yt,hx,$o,Om,Em,Va,Am,qa,fx,Ga,mx,rd=D(()=>{"use strict";td(),Ua=typeof location>"u"?void 0:location.origin,Al=import.meta.url>"file:"&&import.meta.url<"file;",Im=()=>{if(Al){let e=URL;return new URL(new e("ort.all.bundle.min.mjs",import.meta.url).href,Ua).href}return import.meta.url},yt=Im(),hx=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},$o=(e,t)=>{try{let n=t??yt;return(n?new URL(e,n):new URL(e)).origin===Ua}catch{return!1}},Om=(e,t)=>{let n=t??yt;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Em=(e,t)=>`${t??"./"}${e}`,Va=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Am=async e=>(await import(e)).default,qa=(GA(),Nn(lx)).default,fx=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if($o(yt))return[void 0,qa()];let e=await Va(yt);return[e,qa(e)]},Ga=(HA(),Nn(cx)).default,mx=async(e,t,n,i)=>{let u=Ga&&!(e||t);if(u)if(yt)u=$o(yt)||i&&!n;else if(i&&!n)u=!0;else throw new Error("cannot determine the script source URL.");if(u)return[void 0,Ga];{let l="ort-wasm-simd-threaded.jsep.mjs",d=e??Om(l,t),c=n&&d&&!$o(d,t),s=c?await Va(d):d??Em(l,t);return[c?s:void 0,await Am(s)]}}}),Ha,To,li,Wa,km,Pm,Cm,nd,Be,vn=D(()=>{"use strict";rd(),To=!1,li=!1,Wa=!1,km=()=>{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}},Pm=()=>{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}},Cm=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},nd=async e=>{if(To)return Promise.resolve();if(li)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Wa)throw new Error("previous call to 'initializeWebAssembly()' failed.");li=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!Cm())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Pm())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=km();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=n=1);let u=e.wasmPaths,l=typeof u=="string"?u:void 0,d=u?.mjs,c=d?.href??d,s=u?.wasm,r=s?.href??s,o=e.wasmBinary,[a,p]=await mx(c,l,n>1,!!o||!!r),h=!1,m=[];if(t>0&&m.push(new Promise(g=>{setTimeout(()=>{h=!0,g()},t)})),m.push(new Promise((g,_)=>{let w={numThreads:n};if(o)w.wasmBinary=o,w.locateFile=y=>y;else if(r||l)w.locateFile=y=>r??l+y;else if(c&&c.indexOf("blob:")!==0)w.locateFile=y=>new URL(y,c).href;else if(a){let y=hx();y&&(w.locateFile=T=>y+T)}p(w).then(y=>{li=!1,To=!0,Ha=y,g(),a&&URL.revokeObjectURL(a)},y=>{li=!1,Wa=!0,_(y)})})),await Promise.race(m),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Be=()=>{if(To&&Ha)return Ha;throw new Error("WebAssembly is not initialized yet.")}}),Ut,Go,Re,id=D(()=>{"use strict";vn(),Ut=(e,t)=>{let n=Be(),i=n.lengthBytesUTF8(e)+1,u=n._malloc(i);return n.stringToUTF8(e,u,i),t.push(u),u},Go=(e,t,n,i)=>{if(typeof e=="object"&&e!==null){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([u,l])=>{let d=t?t+u:u;if(typeof l=="object")Go(l,d+".",n,i);else if(typeof l=="string"||typeof l=="number")i(d,l.toString());else if(typeof l=="boolean")i(d,l?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof l}`)})},Re=e=>{let t=Be(),n=t.stackSave();try{let i=t.PTR_SIZE,u=t.stackAlloc(2*i);t._OrtGetLastError(u,u+i);let l=Number(t.getValue(u,i===4?"i32":"i64")),d=t.getValue(u+i,"*"),c=d?t.UTF8ToString(d):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(n)}}}),gx,WA=D(()=>{"use strict";vn(),id(),gx=e=>{let t=Be(),n=0,i=[],u=e||{};try{if(e?.logSeverityLevel===void 0)u.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)u.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(u.terminate=!1);let l=0;return e?.tag!==void 0&&(l=Ut(e.tag,i)),n=t._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,l),n===0&&Re("Can't create run options."),e?.extra!==void 0&&Go(e.extra,"",new WeakSet,(d,c)=>{let s=Ut(d,i),r=Ut(c,i);t._OrtAddRunConfigEntry(n,s,r)!==0&&Re(`Can't set a run config entry: ${d} - ${c}.`)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseRunOptions(n),i.forEach(d=>t._free(d)),l}}}),Rm,Dm,Mm,qr,Nm,bx,KA=D(()=>{"use strict";vn(),id(),Rm=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Dm=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Mm=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(e.enableMemPattern=!1)},qr=(e,t,n,i)=>{let u=Ut(t,i),l=Ut(n,i);Be()._OrtAddSessionConfigEntry(e,u,l)!==0&&Re(`Can't set a session config entry: ${t} - ${n}.`)},Nm=async(e,t,n)=>{let i=t.executionProviders;for(let u of i){let l=typeof u=="string"?u:u.name,d=[];switch(l){case"webnn":if(l="WEBNN",qr(e,"session.disable_quant_qdq","1",n),qr(e,"session.disable_qdq_constant_folding","1",n),typeof u!="string"){let a=u?.deviceType;a&&qr(e,"deviceType",a,n)}break;case"webgpu":if(l="JS",typeof u!="string"){let a=u;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);qr(e,"preferredLayout",a.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let c=Ut(l,n),s=d.length,r=0,o=0;if(s>0){r=Be()._malloc(s*Be().PTR_SIZE),n.push(r),o=Be()._malloc(s*Be().PTR_SIZE),n.push(o);for(let a=0;a{let t=Be(),n=0,i=[],u=e||{};Mm(u);try{let l=Rm(u.graphOptimizationLevel??"all"),d=Dm(u.executionMode??"sequential"),c=typeof u.logId=="string"?Ut(u.logId,i):0,s=u.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw new Error(`log severity level is not valid: ${s}`);let r=u.logVerbosityLevel??0;if(!Number.isInteger(r)||r<0||r>4)throw new Error(`log verbosity level is not valid: ${r}`);let o=typeof u.optimizedModelFilePath=="string"?Ut(u.optimizedModelFilePath,i):0;if(n=t._OrtCreateSessionOptions(l,!!u.enableCpuMemArena,!!u.enableMemPattern,d,!!u.enableProfiling,0,c,s,r,o),n===0&&Re("Can't create session options."),u.executionProviders&&await Nm(n,u,i),u.enableGraphCapture!==void 0){if(typeof u.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${u.enableGraphCapture}`);qr(n,"enableGraphCapture",u.enableGraphCapture.toString(),i)}if(u.freeDimensionOverrides)for(let[a,p]of Object.entries(u.freeDimensionOverrides)){if(typeof a!="string")throw new Error(`free dimension override name must be a string: ${a}`);if(typeof p!="number"||!Number.isInteger(p)||p<0)throw new Error(`free dimension override value must be a non-negative integer: ${p}`);let h=Ut(a,i);t._OrtAddFreeDimensionOverride(n,h,p)!==0&&Re(`Can't set a free dimension override: ${a} - ${p}.`)}return u.extra!==void 0&&Go(u.extra,"",new WeakSet,(a,p)=>{qr(n,a,p,i)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&Re("Can't release session options."),i.forEach(d=>t._free(d)),l}}}),dn,sr,cn,ss,Ho,od,sd,kl,de=D(()=>{"use strict";dn=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},sr=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},cn=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i=typeof t=="number"?t:t.reduce((u,l)=>u*l,1);return n>0?Math.ceil(i*n):void 0},ss=e=>{switch(e){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Ho=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},od=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",sd=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",kl=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),ad,yx=D(()=>{"use strict";td(),ad=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),i=n?parseInt(n,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let u=t.body.getReader(),l;try{l=new ArrayBuffer(i)}catch(c){if(c instanceof RangeError){let s=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:s,maximum:s}).buffer}else throw c}let d=0;for(;;){let{done:c,value:s}=await u.read();if(c)break;let r=s.byteLength;new Uint8Array(l,d,r).set(s),d+=r}return new Uint8Array(l,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),zm,Bm,Fm,Lm,ud,jm,Ie,ur=D(()=>{"use strict";de(),zm=["V","I","W","E","F"],Bm=(e,t)=>{console.log(`[${zm[e]},${new Date().toISOString()}]${t}`)},ud=(e,t)=>{Fm=e,Lm=t},jm=(e,t)=>{let n=Ho(e),i=Ho(Fm);n>=i&&Bm(n,typeof t=="function"?t():t)},Ie=(...e)=>{Lm&&jm(...e)}}),Um,Bn,F,Wo,wx,_x,vx,pe=D(()=>{"use strict";Um=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Bn=class{static calcShape(e,t,n=!1){let i=e.length,u=t.length;if(i===0)return t;if(u===0)return e;let l=Math.max(e.length,t.length),d=new Array(l);if(n){if(i<2||u<2)return;let c=Um.calcMatMulShape([e[i-2],e[i-1]],[t[u-2],t[u-1]]);if(c===void 0)return;[d[l-2],d[l-1]]=c}for(let c=n?3:1;c<=l;c++){let s=i-c<0?1:e[i-c],r=u-c<0?1:t[u-c];if(s!==r&&s>1&&r>1)return;let o=Math.max(s,r);if(s&&r)d[l-c]=Math.max(s,r);else{if(o>1)return;d[l-c]=0}}return d}static isValidBroadcast(e,t){let n=e.length,i=t.length;if(n>i)return!1;for(let u=1;u<=n;u++)if(e[n-u]!==1&&e[n-u]!==t[i-u])return!1;return!0}},F=class Bo{static size(t){return Bo.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,n=4){let i=t.length;if(i===0)return[];let u=new Array(i),l=i-1;for(;l>=0;){if(t[l]%n===0){u[l]=t[l]/n;break}if(n%t[l]!==0)throw new Error("cannot convert shape");u[l]=1,n/=t[l],l--}for(l--;l>=0;l--)u[l]=t[l];return u}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Bo.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Bo.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let u=1;for(let l=n;l=0;--u)i[u]=i[u+1]*t[u+1];return i}static normalizeAxis(t,n){if(t<-n&&t>=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n??t.length))}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((u,l)=>u+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,u)=>i===n[u])}},Wo=class Er{static adjustPoolAttributes(t,n,i,u,l,d){if(!t&&i.length!==n.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c=i[c]||d[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,u,l,d,c){if(c){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let s=0;s=i+u&&(d-=1)),d}static adjustPadAndReturnShape(t,n,i,u,l,d,c,s,r=0){let o=i*(u-1)+1;if(s&&s!=="NOTSET")switch(s){case"VALID":return l[d]=0,l[c]=0,Er.computeOutputSize(t-o,n,t,0,r);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let a=(Math.floor((t+n-1)/n)-1)*n+u-t;return l[d]=Math.floor(s==="SAME_LOWER"?(a+1)/2:a/2),l[c]=a-l[d],Er.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}default:throw new Error("Unsupported AutoPad type")}else return Er.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}},wx=class{static getShapeOfGemmResult(e,t,n,i,u){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,d,c;t?(l=e[1],d=e[0]):(l=e[0],d=e[1]);let s=-1;if(i?(c=n[0],s=1):(c=n[1],s=0),n[s]!==d)throw new Error("dimension mismatch");if(l<=0||c<=0||d<=0)throw new Error("invalid shape specified");if(u&&!Bn.isValidBroadcast(u,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,d]}},_x=-34028234663852886e22,vx=34028234663852886e22}),ld,xx=D(()=>{"use strict";de(),ld=(e,t)=>new(ss(t))(e)}),Ka,Vm,Xa,qm,Za,Gm,Ya,Ja,Qa,Hm,$x,XA=D(()=>{"use strict";de(),ur(),Ka=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Vm=(e,t)=>{if(t==="int32")return e;let n=Ka.get(t);if(!n)throw new Error(`WebNN backend does not support data type: ${t}`);let i=n/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let u=e.byteLength/i,l=new(ss(t))(e.buffer,e.byteOffset,u);switch(t){case"int64":case"uint64":{let d=new Int32Array(u);for(let c=0;c2147483647n||s<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");d[c]=Number(s)}return new Uint8Array(d.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(c=>c>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let d=Int32Array.from(l,Number);return new Uint8Array(d.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Xa=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let n=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case"int64":{let u=BigInt64Array.from(i,BigInt);return new Uint8Array(u.buffer)}case"uint64":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let u=BigUint64Array.from(i,BigInt);return new Uint8Array(u.buffer)}case"int8":{if(i.some(l=>l<-128||l>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let u=Int8Array.from(i,Number);return new Uint8Array(u.buffer)}case"uint8":{if(i.some(u=>u<0||u>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(i,Number)}case"uint32":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let u=Uint32Array.from(i,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},qm=1,Za=()=>qm++,Gm=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Ya=(e,t)=>{let n=Ka.get(e);if(!n)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,u)=>i*u)*n/8):0},Ja=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:i,dataType:u,shape:l,fallbackDataType:d}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=i,this.dataType=u,this.tensorShape=l,this.fallbackDataType=d}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Ya(this.dataType,this.tensorShape)}destroy(){Ie("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Xa(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return new Uint8Array(n).buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((i,u)=>i===n[u])}setIsDataConverted(e){this.isDataConverted=e}},Qa=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,i){let u=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),d;if(!l?.input.dataTypes.includes(t)){if(d=Gm.get(t),!d||l?.input.dataTypes.includes(d))throw new Error(`WebNN backend does not support data type: ${t}`);Ie("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${d}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(u,t,n))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==Ya(t,n))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,c,!0,!0,d),i&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=Vm(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Ie("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Xa(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Hm=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Za();return this.tensorTrackersById.set(e,new Qa(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,i,u){Ie("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${i}, copyOld: ${u}}`);let l=this.tensorTrackersById.get(t);if(!l)throw new Error("Tensor not found.");return l.ensureTensor(e,n,i,u)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");n.upload(t)}async download(e,t){Ie("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,i){let u=this.getMLContext(e),l=Za(),d=new Ja({sessionId:e,context:u,tensor:t,dataType:n,shape:i});return this.tensorTrackersById.set(l,new Qa(this,d)),this.externalTensors.add(d),l}async getCachedTensor(e,t,n,i,u,l,d){let c=this.getMLContext(e);for(let[r,o]of this.freeTensors.entries())if(o.canReuseTensor(c,t,n)){Ie("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${d?`fallbackDataType: ${d},`:""} shape: ${n}`);let a=this.freeTensors.splice(r,1)[0];return a.sessionId=e,a}Ie("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${d?`fallbackDataType: ${d},`:""} shape: ${n}}`);let s=await c.createTensor({dataType:d??t,shape:n,dimensions:n,usage:i,writable:u,readable:l});return new Ja({sessionId:e,context:c,tensor:s,dataType:t,shape:n,fallbackDataType:d})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},$x=(...e)=>new Hm(...e)}),di,Wm,Tx,ZA=D(()=>{"use strict";de(),vn(),xx(),XA(),ur(),di=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Wm=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),i=Object.keys(t).sort();return n.length===i.length&&n.every((u,l)=>u===i[l]&&e[u]===t[u])},Tx=class{constructor(e){this.tensorManager=$x(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,ud(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Ie("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Ie("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let n of t)Ie("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${n}}`),this.tensorManager.releaseTensorId(n);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let n=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let n=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(n=>Wm(n.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:n}),n}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let i=this.mlContextCache.findIndex(u=>u.mlContext===t);i!==-1&&this.mlContextCache.splice(i,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Ie("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,i,u){let l=di.get(n);if(!l)throw new Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,i,u)}async createTemporaryTensor(e,t,n){Ie("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let i=di.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let u=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,u,i,n,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(u):this.temporarySessionTensorIds.set(e,[u]),u}uploadTensor(e,t){if(!Be().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ie("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return ld(n,t)}}registerMLTensor(e,t,n,i){let u=di.get(n);if(!u)throw new Error(`Unsupported ONNX data type: ${n}`);let l=this.tensorManager.registerTensor(e,t,u,i);return Ie("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${u}, dimensions: ${i}} -> {tensorId: ${l}}`),l}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let i=di.get(dn(t)),u=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:n?!!u?.input.dataTypes.includes(i):!!u?.output.dataTypes.includes(i)}flush(){}}}),dd=D(()=>{"use strict"}),eu,So,Io,Km,Xm,tu,Pl,Zm,Sx,YA=D(()=>{"use strict";ur(),dd(),eu=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]]),So=[],Io=e=>Math.ceil(Number(e)/16)*16,Km=e=>{for(let t=0;tXm++,Pl=async(e,t,n,i)=>{let u=Io(n),l=e.device.createBuffer({size:u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=e.getCommandEncoder();e.endComputePass(),d.copyBufferToBuffer(t,0,l,0,u),e.flush(),await l.mapAsync(GPUMapMode.READ);let c=l.getMappedRange();if(i){let s=i();return s.set(new Uint8Array(c,0,n)),s}else return new Uint8Array(c.slice(0,n))}finally{l.destroy()}},Zm=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of eu)So.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,i=t.byteOffset,u=t.byteLength,l=Io(u),d=this.storageCache.get(e);if(!d)throw new Error("gpu data for uploading does not exist");if(Number(d.originalSize)!==u)throw new Error(`inconsistent data size. gpu data size=${d.originalSize}, data size=${u}`);if(l===u&&i%4===0)this.backend.device.queue.writeBuffer(d.gpuData.buffer,0,n,i,u);else{let c=new Uint8Array(l);c.set(t),this.backend.device.queue.writeBuffer(d.gpuData.buffer,0,c,0,l)}Ie("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(t);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let u=Io(n.originalSize),l=this.backend.getCommandEncoder();this.backend.endComputePass(),l.copyBufferToBuffer(n.gpuData.buffer,0,i.gpuData.buffer,0,u)}registerExternalBuffer(e,t,n){let i;if(n){if(i=n[0],e===n[1])return Ie("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. - Please use the previous external buffer!`)}else i=tu();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),Ie("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Ie("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=Km(e),i,u=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,l=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(u||l){let c=(u?this.freeBuffers:this.freeUniformBuffers).get(n);c?c.length>0?i=c.pop():i=this.backend.device.createBuffer({size:n,usage:t}):i=this.backend.device.createBuffer({size:n,usage:t})}else i=this.backend.device.createBuffer({size:n,usage:t});let d={id:tu(),type:0,buffer:i};return this.storageCache.set(d.id,{gpuData:d,originalSize:Number(e)}),Ie("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${d.id}`),d}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,n=this.storageCache.get(t);if(!n){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Ie("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw new Error("data does not exist");await Pl(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=eu.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Ie("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},Sx=(...e)=>new Zm(...e)}),Ym,ke,He=D(()=>{"use strict";Ym=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},ke=e=>new Ym(e)}),Fn,Oo,nt,rt,ue,Ge,Cl,Mn,kr,se,ci,j,oe,Ix,cd,Jm,Ox,he=D(()=>{"use strict";de(),pe(),Fn=64,Oo=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},nt=(e,t=1)=>{let n=Oo(e,t);return typeof n=="string"?n:n[0]},rt=(e,t=1)=>{let n=Oo(e,t);return typeof n=="string"?n:n[1]},ue=(...e)=>{let t=[];return e.forEach(n=>{n.length!==0&&t.push({type:12,data:n},{type:12,data:F.computeStrides(n)})}),t},Ge=e=>e%4===0?4:e%2===0?2:1,Cl=(e="f32",t,n="0")=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,Mn=(e,t,n)=>e==="f32"?n:t===1?`f32(${n})`:`vec${t}(${n})`,kr=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,se=(e,t,n,i)=>e.startsWith("uniforms.")&&n>4?typeof t=="string"?i==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:i==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,ci=(e,t,n,i,u)=>{let l=typeof n=="number",d=l?n:n.length,c=[...new Array(d).keys()],s=d<2?"u32":d<=4?`vec${d}`:`array`,r=Oo(t,u),o=typeof r=="string"?r:r[1],a=typeof r=="string"?r:r[0],p={indices:s,value:o,storage:a,tensor:t},h=B=>typeof B=="string"?B:`${B}u`,m={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},g=l?"uniforms.":"",_=`${g}${e}_shape`,w=`${g}${e}_strides`,y="";for(let B=0;BQ.name)}) => ${x.name}>`,JS(Object.defineProperty($,"name",{value:U}))}function nI(f,b){return b>>>=0,(f=Ot(f>>>0))==Ot(b)}function iI(f){return(f>>>=0)?(f=mo(f),Mt(globalThis[f])):Mt(globalThis)}function oI(f){return f=mo(f>>>0),Mt(t[f])}function sI(f,b){return b>>>=0,f=Ot(f>>>0),b=Ot(b),Mt(f[b])}function aI(f){9<(f>>>=0)&&(Fr[f+1]+=1)}function Yc(f,b,$,x,E){return Js[f>>>0](b>>>0,$>>>0,x>>>0,E>>>0)}function uI(f,b,$,x,E){return Yc(f>>>0,b>>>0,$>>>0,x>>>0,E>>>0)}function lI(){return Mt([])}function dI(f){f=Ot(f>>>0);for(var b=Array(f.length),$=0;$>>0))}function pI(){return Mt({})}function hI(f){for(var b=Ot(f>>>=0);b.length;){var $=b.pop();b.pop()($)}Hs(f)}function fI(f,b,$){b>>>=0,$>>>=0,f=Ot(f>>>0),b=Ot(b),$=Ot($),f[b]=$}function mI(f,b){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),(I(),v)[b>>>2>>>0]=f.getUTCSeconds(),(I(),v)[b+4>>>2>>>0]=f.getUTCMinutes(),(I(),v)[b+8>>>2>>>0]=f.getUTCHours(),(I(),v)[b+12>>>2>>>0]=f.getUTCDate(),(I(),v)[b+16>>>2>>>0]=f.getUTCMonth(),(I(),v)[b+20>>>2>>>0]=f.getUTCFullYear()-1900,(I(),v)[b+24>>>2>>>0]=f.getUTCDay(),f=(f.getTime()-Date.UTC(f.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(I(),v)[b+28>>>2>>>0]=f}var Jc=f=>f%4==0&&(f%100!=0||f%400==0),Qc=[0,31,60,91,121,152,182,213,244,274,305,335],ep=[0,31,59,90,120,151,181,212,243,273,304,334];function gI(f,b){f=-9007199254740992>f||9007199254740992>>=0,f=new Date(1e3*f),(I(),v)[b>>>2>>>0]=f.getSeconds(),(I(),v)[b+4>>>2>>>0]=f.getMinutes(),(I(),v)[b+8>>>2>>>0]=f.getHours(),(I(),v)[b+12>>>2>>>0]=f.getDate(),(I(),v)[b+16>>>2>>>0]=f.getMonth(),(I(),v)[b+20>>>2>>>0]=f.getFullYear()-1900,(I(),v)[b+24>>>2>>>0]=f.getDay();var $=(Jc(f.getFullYear())?Qc:ep)[f.getMonth()]+f.getDate()-1|0;(I(),v)[b+28>>>2>>>0]=$,(I(),v)[b+36>>>2>>>0]=-60*f.getTimezoneOffset(),$=new Date(f.getFullYear(),6,1).getTimezoneOffset();var x=new Date(f.getFullYear(),0,1).getTimezoneOffset();f=0|($!=x&&f.getTimezoneOffset()==Math.min(x,$)),(I(),v)[b+32>>>2>>>0]=f}function bI(f){f>>>=0;var b=new Date((I(),v)[f+20>>>2>>>0]+1900,(I(),v)[f+16>>>2>>>0],(I(),v)[f+12>>>2>>>0],(I(),v)[f+8>>>2>>>0],(I(),v)[f+4>>>2>>>0],(I(),v)[f>>>2>>>0],0),$=(I(),v)[f+32>>>2>>>0],x=b.getTimezoneOffset(),E=new Date(b.getFullYear(),6,1).getTimezoneOffset(),k=new Date(b.getFullYear(),0,1).getTimezoneOffset(),M=Math.min(k,E);return 0>$?(I(),v)[f+32>>>2>>>0]=+(E!=k&&M==x):0<$!=(M==x)&&(E=Math.max(k,E),b.setTime(b.getTime()+6e4*((0<$?M:E)-x))),(I(),v)[f+24>>>2>>>0]=b.getDay(),$=(Jc(b.getFullYear())?Qc:ep)[b.getMonth()]+b.getDate()-1|0,(I(),v)[f+28>>>2>>>0]=$,(I(),v)[f>>>2>>>0]=b.getSeconds(),(I(),v)[f+4>>>2>>>0]=b.getMinutes(),(I(),v)[f+8>>>2>>>0]=b.getHours(),(I(),v)[f+12>>>2>>>0]=b.getDate(),(I(),v)[f+16>>>2>>>0]=b.getMonth(),(I(),v)[f+20>>>2>>>0]=b.getYear(),f=b.getTime(),BigInt(isNaN(f)?-1:f/1e3)}function tp(f,b,$,x,E,k,M){return u?$e(16,1,f,b,$,x,E,k,M):-52}function rp(f,b,$,x,E,k){if(u)return $e(17,1,f,b,$,x,E,k)}var ti={},yI=()=>performance.timeOrigin+performance.now();function np(f,b){if(u)return $e(18,1,f,b);if(ti[f]&&(clearTimeout(ti[f].id),delete ti[f]),!b)return 0;var $=setTimeout(()=>{delete ti[f],co(()=>yp(f,performance.timeOrigin+performance.now()))},b);return ti[f]={id:$,ae:b},0}function wI(f,b,$,x){f>>>=0,b>>>=0,$>>>=0,x>>>=0;var E=new Date().getFullYear(),k=new Date(E,0,1).getTimezoneOffset();E=new Date(E,6,1).getTimezoneOffset();var M=Math.max(k,E);(I(),R)[f>>>2>>>0]=60*M,(I(),v)[b>>>2>>>0]=+(k!=E),f=(b=U=>{var Q=Math.abs(U);return`UTC${0<=U?"-":"+"}${String(Math.floor(Q/60)).padStart(2,"0")}${String(Q%60).padStart(2,"0")}`})(k),b=b(E),EDate.now(),vI=1;function xI(f,b,$){if($>>>=0,!(0<=f&&3>=f))return 28;if(f===0)f=Date.now();else{if(!vI)return 52;f=performance.timeOrigin+performance.now()}return f=Math.round(1e6*f),(I(),V)[$>>>3>>>0]=BigInt(f),0}var Qs=[],ip=(f,b)=>{Qs.length=0;for(var $;$=(I(),G)[f++>>>0];){var x=$!=105;b+=(x&=$!=112)&&b%8?4:0,Qs.push($==112?(I(),R)[b>>>2>>>0]:$==106?(I(),V)[b>>>3>>>0]:$==105?(I(),v)[b>>>2>>>0]:(I(),L)[b>>>3>>>0]),b+=x?8:4}return Qs};function $I(f,b,$){return f>>>=0,b=ip(b>>>0,$>>>0),aa[f](...b)}function TI(f,b,$){return f>>>=0,b=ip(b>>>0,$>>>0),aa[f](...b)}var SI=()=>{};function II(f,b){return O(et(f>>>0,b>>>0))}var OI=()=>{throw Ze+=1,"unwind"};function EI(){return 4294901760}var AI=()=>navigator.hardwareConcurrency,Lr={},go=f=>{var b;return(b=/\bwasm-function\[\d+\]:(0x[0-9a-f]+)/.exec(f))?+b[1]:(b=/:(\d+):\d+(?:\)|$)/.exec(f))?2147483648|+b[1]:0},op=f=>{for(var b of f)(f=go(b))&&(Lr[f]=b)};function kI(){var f=Error().stack.toString().split(` +`);return f[0]=="Error"&&f.shift(),op(f),Lr.gd=go(f[3]),Lr.Jd=f,Lr.gd}function bo(f){if(!(f=Lr[f>>>0]))return 0;var b;if(b=/^\s+at .*\.wasm\.(.*) \(.*\)$/.exec(f))f=b[1];else if(b=/^\s+at (.*) \(.*\)$/.exec(f))f=b[1];else{if(!(b=/^(.+?)@/.exec(f)))return 0;f=b[1]}Kt(bo.hd??0),b=lo(f)+1;var $=ri(b);return $&&fr(f,$,b),bo.hd=$,bo.hd}function PI(f){f>>>=0;var b=(I(),G).length;if(f<=b||4294901760=$;$*=2){var x=b*(1+.2/$);x=Math.min(x,f+100663296);e:{x=(Math.min(4294901760,65536*Math.ceil(Math.max(f,x)/65536))-hr.buffer.byteLength+65535)/65536|0;try{hr.grow(x),Y();var E=1;break e}catch{}E=void 0}if(E)return!0}return!1}function CI(f,b,$){if(f>>>=0,b>>>=0,Lr.gd==f)var x=Lr.Jd;else(x=Error().stack.toString().split(` +`))[0]=="Error"&&x.shift(),op(x);for(var E=3;x[E]&&go(x[E])!=f;)++E;for(f=0;f<$&&x[f+E];++f)(I(),v)[b+4*f>>>2>>>0]=go(x[f+E]);return f}var ea,ta={},sp=()=>{if(!ea){var f,b={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"};for(f in ta)ta[f]===void 0?delete b[f]:b[f]=ta[f];var $=[];for(f in b)$.push(`${f}=${b[f]}`);ea=$}return ea};function ap(f,b){if(u)return $e(19,1,f,b);f>>>=0,b>>>=0;var $,x=0,E=0;for($ of sp()){var k=b+x;(I(),R)[f+E>>>2>>>0]=k,x+=fr($,k,1/0)+1,E+=4}return 0}function up(f,b){if(u)return $e(20,1,f,b);f>>>=0,b>>>=0;var $=sp();for(var x of((I(),R)[f>>>2>>>0]=$.length,f=0,$))f+=lo(x)+1;return(I(),R)[b>>>2>>>0]=f,0}function lp(f){return u?$e(21,1,f):52}function dp(f,b,$,x){return u?$e(22,1,f,b,$,x):52}function cp(f,b,$,x){return u?$e(23,1,f,b,$,x):70}var RI=[null,[],[]];function pp(f,b,$,x){if(u)return $e(24,1,f,b,$,x);b>>>=0,$>>>=0,x>>>=0;for(var E=0,k=0;k<$;k++){var M=(I(),R)[b>>>2>>>0],U=(I(),R)[b+4>>>2>>>0];b+=8;for(var Q=0;Q>>0],Oe=RI[ne];ge===0||ge===10?((ne===1?S:O)(kc(Oe)),Oe.length=0):Oe.push(ge)}E+=U}return(I(),R)[x>>>2>>>0]=E,0}function DI(f){return f>>>0}u||(function(){for(var f=t.numThreads-1;f--;)$c();xe.push(async()=>{var b=(async function(){if(!u)return Promise.all(qt.map(xc))})();Ge++,await b,--Ge==0&&Ve&&(b=Ve,Ve=null,b())})})(),u||(hr=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),Y()),t.wasmBinary&&(p=t.wasmBinary),t.stackSave=()=>_e(),t.stackRestore=f=>we(f),t.stackAlloc=f=>ia(f),t.setValue=function(f,b,$="i8"){switch($.endsWith("*")&&($="*"),$){case"i1":case"i8":(I(),J)[f>>>0]=b;break;case"i16":(I(),C)[f>>>1>>>0]=b;break;case"i32":(I(),v)[f>>>2>>>0]=b;break;case"i64":(I(),V)[f>>>3>>>0]=BigInt(b);break;case"float":(I(),H)[f>>>2>>>0]=b;break;case"double":(I(),L)[f>>>3>>>0]=b;break;case"*":(I(),R)[f>>>2>>>0]=b;break;default:X(`invalid type for setValue: ${$}`)}},t.getValue=function(f,b="i8"){switch(b.endsWith("*")&&(b="*"),b){case"i1":case"i8":return(I(),J)[f>>>0];case"i16":return(I(),C)[f>>>1>>>0];case"i32":return(I(),v)[f>>>2>>>0];case"i64":return(I(),V)[f>>>3>>>0];case"float":return(I(),H)[f>>>2>>>0];case"double":return(I(),L)[f>>>3>>>0];case"*":return(I(),R)[f>>>2>>>0];default:X(`invalid type for getValue: ${b}`)}},t.UTF8ToString=et,t.stringToUTF8=fr,t.lengthBytesUTF8=lo;var hp,fp,yo,Kt,ri,ra,mp,gp,bp,na,yp,wp,Te,ni,_p,we,ia,_e,vp,oa,xp,$p,Tp,sa,Sp,Ip,Op,Ep,Ap,kp,Pp,Cp,Rp,Dp,Mp,Np,zp,Bp,Fp,Lp,jp,Up,Vp,Gp,qp,Hp,Wp,Kp,Xp,Zp,Yp,Jp,Qp,eh,th,rh,nh,ih,oh,sh,ah,uh,lh,rr,MI=[ht,It,Ic,Pc,Cc,Rc,Dc,Mc,Nc,zc,Bc,Fc,Lc,jc,Uc,Vc,tp,rp,np,ap,up,lp,dp,cp,pp],aa={1055492:(f,b,$,x,E)=>{if(t===void 0||!t.Yc)return 1;if((f=et(Number(f>>>0))).startsWith("./")&&(f=f.substring(2)),!(f=t.Yc.get(f)))return 2;if(b=Number(b>>>0),$=Number($>>>0),x=Number(x>>>0),b+$>f.byteLength)return 3;try{let k=f.subarray(b,b+$);switch(E){case 0:(I(),G).set(k,x>>>0);break;case 1:t.Qd?t.Qd(x,k):t.Id(x,k);break;default:return 4}return 0}catch{return 4}},1056316:(f,b,$)=>{t.td(f,(I(),G).subarray(b>>>0,b+$>>>0))},1056380:()=>t.Sd(),1056422:f=>{t.sd(f)},1056459:()=>{t.Bd()},1056490:()=>{t.Cd()},1056519:()=>{t.Gd()},1056544:f=>t.Ad(f),1056577:f=>t.Ed(f),1056609:(f,b,$)=>{t.ed(Number(f),Number(b),Number($),!0)},1056672:(f,b,$)=>{t.ed(Number(f),Number(b),Number($))},1056729:()=>typeof wasmOffsetConverter<"u",1056786:f=>{t.$b("Abs",f,void 0)},1056837:f=>{t.$b("Neg",f,void 0)},1056888:f=>{t.$b("Floor",f,void 0)},1056941:f=>{t.$b("Ceil",f,void 0)},1056993:f=>{t.$b("Reciprocal",f,void 0)},1057051:f=>{t.$b("Sqrt",f,void 0)},1057103:f=>{t.$b("Exp",f,void 0)},1057154:f=>{t.$b("Erf",f,void 0)},1057205:f=>{t.$b("Sigmoid",f,void 0)},1057260:(f,b,$)=>{t.$b("HardSigmoid",f,{alpha:b,beta:$})},1057339:f=>{t.$b("HardSwish",f,void 0)},1057396:f=>{t.$b("Log",f,void 0)},1057447:f=>{t.$b("Sin",f,void 0)},1057498:f=>{t.$b("Cos",f,void 0)},1057549:f=>{t.$b("Tan",f,void 0)},1057600:f=>{t.$b("Asin",f,void 0)},1057652:f=>{t.$b("Acos",f,void 0)},1057704:f=>{t.$b("Atan",f,void 0)},1057756:f=>{t.$b("Sinh",f,void 0)},1057808:f=>{t.$b("Cosh",f,void 0)},1057860:f=>{t.$b("Asinh",f,void 0)},1057913:f=>{t.$b("Acosh",f,void 0)},1057966:f=>{t.$b("Atanh",f,void 0)},1058019:f=>{t.$b("Tanh",f,void 0)},1058071:f=>{t.$b("Not",f,void 0)},1058122:(f,b,$)=>{t.$b("Clip",f,{min:b,max:$})},1058191:f=>{t.$b("Clip",f,void 0)},1058243:(f,b)=>{t.$b("Elu",f,{alpha:b})},1058301:f=>{t.$b("Gelu",f,void 0)},1058353:f=>{t.$b("Relu",f,void 0)},1058405:(f,b)=>{t.$b("LeakyRelu",f,{alpha:b})},1058469:(f,b)=>{t.$b("ThresholdedRelu",f,{alpha:b})},1058539:(f,b)=>{t.$b("Cast",f,{to:b})},1058597:f=>{t.$b("Add",f,void 0)},1058648:f=>{t.$b("Sub",f,void 0)},1058699:f=>{t.$b("Mul",f,void 0)},1058750:f=>{t.$b("Div",f,void 0)},1058801:f=>{t.$b("Pow",f,void 0)},1058852:f=>{t.$b("Equal",f,void 0)},1058905:f=>{t.$b("Greater",f,void 0)},1058960:f=>{t.$b("GreaterOrEqual",f,void 0)},1059022:f=>{t.$b("Less",f,void 0)},1059074:f=>{t.$b("LessOrEqual",f,void 0)},1059133:(f,b,$,x,E)=>{t.$b("ReduceMean",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059308:(f,b,$,x,E)=>{t.$b("ReduceMax",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059482:(f,b,$,x,E)=>{t.$b("ReduceMin",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059656:(f,b,$,x,E)=>{t.$b("ReduceProd",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1059831:(f,b,$,x,E)=>{t.$b("ReduceSum",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060005:(f,b,$,x,E)=>{t.$b("ReduceL1",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060178:(f,b,$,x,E)=>{t.$b("ReduceL2",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060351:(f,b,$,x,E)=>{t.$b("ReduceLogSum",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060528:(f,b,$,x,E)=>{t.$b("ReduceSumSquare",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060708:(f,b,$,x,E)=>{t.$b("ReduceLogSumExp",f,{keepDims:!!b,noopWithEmptyAxes:!!$,axes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1060888:f=>{t.$b("Where",f,void 0)},1060941:(f,b,$)=>{t.$b("Transpose",f,{perm:b?Array.from((I(),v).subarray(Number(b)>>>0,Number($)>>>0)):[]})},1061065:(f,b,$,x)=>{t.$b("DepthToSpace",f,{blocksize:b,mode:et($),format:x?"NHWC":"NCHW"})},1061198:(f,b,$,x)=>{t.$b("DepthToSpace",f,{blocksize:b,mode:et($),format:x?"NHWC":"NCHW"})},1061331:(f,b,$,x)=>{t.$b("DFT",f,{axis:b,inverse:$,onesided:x})},1061423:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr)=>{t.$b("ConvTranspose",f,{format:Q?"NHWC":"NCHW",autoPad:b,dilations:[$],group:x,kernelShape:[E],pads:[k,M],strides:[U],wIsConst:()=>!!(I(),J)[ne>>>0],outputPadding:ge?Array.from((I(),v).subarray(Number(ge)>>>0,Number(Oe)>>>0)):[],outputShape:Ne?Array.from((I(),v).subarray(Number(Ne)>>>0,Number(Fe)>>>0)):[],activation:et(gr)})},1061856:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("ConvTranspose",f,{format:U?"NHWC":"NCHW",autoPad:b,dilations:Array.from((I(),v).subarray(Number($)>>>0,(Number($)>>>0)+2>>>0)),group:x,kernelShape:Array.from((I(),v).subarray(Number(E)>>>0,(Number(E)>>>0)+2>>>0)),pads:Array.from((I(),v).subarray(Number(k)>>>0,(Number(k)>>>0)+4>>>0)),strides:Array.from((I(),v).subarray(Number(M)>>>0,(Number(M)>>>0)+2>>>0)),wIsConst:()=>!!(I(),J)[Q>>>0],outputPadding:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],outputShape:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[],activation:et(Fe)})},1062517:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr)=>{t.$b("ConvTranspose",f,{format:Q?"NHWC":"NCHW",autoPad:b,dilations:[$],group:x,kernelShape:[E],pads:[k,M],strides:[U],wIsConst:()=>!!(I(),J)[ne>>>0],outputPadding:ge?Array.from((I(),v).subarray(Number(ge)>>>0,Number(Oe)>>>0)):[],outputShape:Ne?Array.from((I(),v).subarray(Number(Ne)>>>0,Number(Fe)>>>0)):[],activation:et(gr)})},1062950:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("ConvTranspose",f,{format:U?"NHWC":"NCHW",autoPad:b,dilations:Array.from((I(),v).subarray(Number($)>>>0,(Number($)>>>0)+2>>>0)),group:x,kernelShape:Array.from((I(),v).subarray(Number(E)>>>0,(Number(E)>>>0)+2>>>0)),pads:Array.from((I(),v).subarray(Number(k)>>>0,(Number(k)>>>0)+4>>>0)),strides:Array.from((I(),v).subarray(Number(M)>>>0,(Number(M)>>>0)+2>>>0)),wIsConst:()=>!!(I(),J)[Q>>>0],outputPadding:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],outputShape:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[],activation:et(Fe)})},1063611:(f,b)=>{t.$b("GlobalAveragePool",f,{format:b?"NHWC":"NCHW"})},1063702:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("AveragePool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1064181:(f,b)=>{t.$b("GlobalAveragePool",f,{format:b?"NHWC":"NCHW"})},1064272:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("AveragePool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1064751:(f,b)=>{t.$b("GlobalMaxPool",f,{format:b?"NHWC":"NCHW"})},1064838:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("MaxPool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1065313:(f,b)=>{t.$b("GlobalMaxPool",f,{format:b?"NHWC":"NCHW"})},1065400:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe)=>{t.$b("MaxPool",f,{format:Fe?"NHWC":"NCHW",auto_pad:b,ceil_mode:$,count_include_pad:x,storage_order:E,dilations:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],kernel_shape:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],pads:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],strides:Oe?Array.from((I(),v).subarray(Number(Oe)>>>0,Number(Ne)>>>0)):[]})},1065875:(f,b,$,x,E)=>{t.$b("Gemm",f,{alpha:b,beta:$,transA:x,transB:E})},1065979:f=>{t.$b("MatMul",f,void 0)},1066033:(f,b,$,x)=>{t.$b("ArgMax",f,{keepDims:!!b,selectLastIndex:!!$,axis:x})},1066141:(f,b,$,x)=>{t.$b("ArgMin",f,{keepDims:!!b,selectLastIndex:!!$,axis:x})},1066249:(f,b)=>{t.$b("Softmax",f,{axis:b})},1066312:(f,b)=>{t.$b("Concat",f,{axis:b})},1066372:(f,b,$,x,E)=>{t.$b("Split",f,{axis:b,numOutputs:$,splitSizes:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1066528:f=>{t.$b("Expand",f,void 0)},1066582:(f,b)=>{t.$b("Gather",f,{axis:Number(b)})},1066653:(f,b)=>{t.$b("GatherElements",f,{axis:Number(b)})},1066732:(f,b)=>{t.$b("GatherND",f,{batch_dims:Number(b)})},1066811:(f,b,$,x,E,k,M,U,Q,ne,ge)=>{t.$b("Resize",f,{antialias:b,axes:$?Array.from((I(),v).subarray(Number($)>>>0,Number(x)>>>0)):[],coordinateTransformMode:et(E),cubicCoeffA:k,excludeOutside:M,extrapolationValue:U,keepAspectRatioPolicy:et(Q),mode:et(ne),nearestMode:et(ge)})},1067173:(f,b,$,x,E,k,M)=>{t.$b("Slice",f,{starts:b?Array.from((I(),v).subarray(Number(b)>>>0,Number($)>>>0)):[],ends:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[],axes:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[]})},1067437:f=>{t.$b("Tile",f,void 0)},1067489:(f,b,$)=>{t.$b("InstanceNormalization",f,{epsilon:b,format:$?"NHWC":"NCHW"})},1067603:(f,b,$)=>{t.$b("InstanceNormalization",f,{epsilon:b,format:$?"NHWC":"NCHW"})},1067717:f=>{t.$b("Range",f,void 0)},1067770:(f,b)=>{t.$b("Einsum",f,{equation:et(b)})},1067851:(f,b,$,x,E)=>{t.$b("Pad",f,{mode:b,value:$,pads:x?Array.from((I(),v).subarray(Number(x)>>>0,Number(E)>>>0)):[]})},1067994:(f,b,$,x,E,k)=>{t.$b("BatchNormalization",f,{epsilon:b,momentum:$,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},1068163:(f,b,$,x,E,k)=>{t.$b("BatchNormalization",f,{epsilon:b,momentum:$,spatial:!!E,trainingMode:!!x,format:k?"NHWC":"NCHW"})},1068332:(f,b,$)=>{t.$b("CumSum",f,{exclusive:Number(b),reverse:Number($)})},1068429:(f,b,$)=>{t.$b("DequantizeLinear",f,{axis:b,blockSize:$})},1068519:(f,b,$,x,E)=>{t.$b("GridSample",f,{align_corners:b,mode:et($),padding_mode:et(x),format:E?"NHWC":"NCHW"})},1068689:(f,b,$,x,E)=>{t.$b("GridSample",f,{align_corners:b,mode:et($),padding_mode:et(x),format:E?"NHWC":"NCHW"})},1068859:(f,b)=>{t.$b("ScatterND",f,{reduction:et(b)})},1068944:(f,b,$,x,E,k,M,U,Q)=>{t.$b("Attention",f,{numHeads:b,isUnidirectional:$,maskFilterValue:x,scale:E,doRotary:k,qkvHiddenSizes:M?Array.from((I(),v).subarray(Number(U)>>>0,Number(U)+M>>>0)):[],pastPresentShareBuffer:!!Q})},1069216:f=>{t.$b("BiasAdd",f,void 0)},1069271:f=>{t.$b("BiasSplitGelu",f,void 0)},1069332:f=>{t.$b("FastGelu",f,void 0)},1069388:(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr,ua)=>{t.$b("Conv",f,{format:Oe?"NHWC":"NCHW",auto_pad:b,dilations:$?Array.from((I(),v).subarray(Number($)>>>0,Number(x)>>>0)):[],group:E,kernel_shape:k?Array.from((I(),v).subarray(Number(k)>>>0,Number(M)>>>0)):[],pads:U?Array.from((I(),v).subarray(Number(U)>>>0,Number(Q)>>>0)):[],strides:ne?Array.from((I(),v).subarray(Number(ne)>>>0,Number(ge)>>>0)):[],w_is_const:()=>!!(I(),J)[Number(Ne)>>>0],activation:et(Fe),activation_params:gr?Array.from((I(),H).subarray(Number(gr)>>>0,Number(ua)>>>0)):[]})},1069972:f=>{t.$b("Gelu",f,void 0)},1070024:(f,b,$,x,E,k,M,U,Q)=>{t.$b("GroupQueryAttention",f,{numHeads:b,kvNumHeads:$,scale:x,softcap:E,doRotary:k,rotaryInterleaved:M,smoothSoftmax:U,localWindowSize:Q})},1070241:(f,b,$,x)=>{t.$b("LayerNormalization",f,{axis:b,epsilon:$,simplified:!!x})},1070352:(f,b,$,x)=>{t.$b("LayerNormalization",f,{axis:b,epsilon:$,simplified:!!x})},1070463:(f,b,$,x,E,k)=>{t.$b("MatMulNBits",f,{k:b,n:$,accuracyLevel:x,bits:E,blockSize:k})},1070590:(f,b,$,x,E,k)=>{t.$b("MultiHeadAttention",f,{numHeads:b,isUnidirectional:$,maskFilterValue:x,scale:E,doRotary:k})},1070749:(f,b)=>{t.$b("QuickGelu",f,{alpha:b})},1070813:(f,b,$,x,E)=>{t.$b("RotaryEmbedding",f,{interleaved:!!b,numHeads:$,rotaryEmbeddingDim:x,scale:E})},1070952:(f,b,$)=>{t.$b("SkipLayerNormalization",f,{epsilon:b,simplified:!!$})},1071054:(f,b,$)=>{t.$b("SkipLayerNormalization",f,{epsilon:b,simplified:!!$})},1071156:(f,b,$,x)=>{t.$b("GatherBlockQuantized",f,{gatherAxis:b,quantizeAxis:$,blockSize:x})},1071277:f=>{t.Fd(f)},1071311:(f,b)=>t.Hd(Number(f),Number(b),t.Xc.Kd,t.Xc.errors)};function NI(f,b,$){return Zc(async()=>{await t.Dd(Number(f),Number(b),Number($))})}function zI(){return typeof wasmOffsetConverter<"u"}function BI(f,b,$,x){var E=_e();try{return Cp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function FI(f,b,$){var x=_e();try{return Ep(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function LI(f){var b=_e();try{Sp(f)}catch($){if(we(b),$!==$+0)throw $;Te(1,0)}}function jI(f,b){var $=_e();try{return sa(f,b)}catch(x){if(we($),x!==x+0)throw x;Te(1,0)}}function UI(f,b,$){var x=_e();try{Tp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function VI(f,b){var $=_e();try{Rp(f,b)}catch(x){if(we($),x!==x+0)throw x;Te(1,0)}}function GI(f,b,$,x,E,k,M){var U=_e();try{return kp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function qI(f,b,$,x,E,k){var M=_e();try{Ip(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function HI(f,b,$,x){var E=_e();try{Pp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function WI(f,b,$,x,E){var k=_e();try{Op(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function KI(f,b,$,x,E,k,M){var U=_e();try{Mp(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function XI(f,b,$,x,E,k,M){var U=_e();try{Np(f,b,$,x,E,k,M)}catch(Q){if(we(U),Q!==Q+0)throw Q;Te(1,0)}}function ZI(f,b,$,x,E,k,M,U){var Q=_e();try{Lp(f,b,$,x,E,k,M,U)}catch(ne){if(we(Q),ne!==ne+0)throw ne;Te(1,0)}}function YI(f,b,$,x,E){var k=_e();try{return Dp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function JI(f,b,$){var x=_e();try{return jp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function QI(f,b,$,x,E,k,M,U){var Q=_e();try{Up(f,b,$,x,E,k,M,U)}catch(ne){if(we(Q),ne!==ne+0)throw ne;Te(1,0)}}function e3(f,b,$,x,E,k,M,U,Q,ne,ge,Oe){var Ne=_e();try{zp(f,b,$,x,E,k,M,U,Q,ne,ge,Oe)}catch(Fe){if(we(Ne),Fe!==Fe+0)throw Fe;Te(1,0)}}function t3(f,b,$){var x=_e();try{return Vp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;return Te(1,0),0n}}function r3(f,b,$,x,E,k,M,U,Q){var ne=_e();try{Ap(f,b,$,x,E,k,M,U,Q)}catch(ge){if(we(ne),ge!==ge+0)throw ge;Te(1,0)}}function n3(f){var b=_e();try{return Gp(f)}catch($){if(we(b),$!==$+0)throw $;Te(1,0)}}function i3(f,b){var $=_e();try{return oh(f,b)}catch(x){if(we($),x!==x+0)throw x;return Te(1,0),0n}}function o3(f){var b=_e();try{return qp(f)}catch($){if(we(b),$!==$+0)throw $;return Te(1,0),0n}}function s3(f,b,$,x){var E=_e();try{return Yp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function a3(f,b,$,x,E){var k=_e();try{return Jp(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;Te(1,0)}}function u3(f,b,$,x,E,k){var M=_e();try{return Qp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function l3(f,b,$,x,E,k){var M=_e();try{return Bp(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function d3(f,b,$,x,E,k){var M=_e();try{return eh(f,b,$,x,E,k)}catch(U){if(we(M),U!==U+0)throw U;Te(1,0)}}function c3(f,b,$,x,E,k,M,U){var Q=_e();try{return Fp(f,b,$,x,E,k,M,U)}catch(ne){if(we(Q),ne!==ne+0)throw ne;Te(1,0)}}function p3(f,b,$,x,E){var k=_e();try{return th(f,b,$,x,E)}catch(M){if(we(k),M!==M+0)throw M;return Te(1,0),0n}}function h3(f,b,$,x){var E=_e();try{return rh(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function f3(f,b,$,x){var E=_e();try{return nh(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function m3(f,b,$,x,E,k,M,U,Q,ne,ge,Oe){var Ne=_e();try{return ih(f,b,$,x,E,k,M,U,Q,ne,ge,Oe)}catch(Fe){if(we(Ne),Fe!==Fe+0)throw Fe;Te(1,0)}}function g3(f,b,$,x,E,k,M,U,Q,ne,ge){var Oe=_e();try{Xp(f,b,$,x,E,k,M,U,Q,ne,ge)}catch(Ne){if(we(Oe),Ne!==Ne+0)throw Ne;Te(1,0)}}function b3(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr,ua){var v3=_e();try{Zp(f,b,$,x,E,k,M,U,Q,ne,ge,Oe,Ne,Fe,gr,ua)}catch(la){if(we(v3),la!==la+0)throw la;Te(1,0)}}function y3(f,b,$){var x=_e();try{return Hp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function w3(f,b,$){var x=_e();try{return Wp(f,b,$)}catch(E){if(we(x),E!==E+0)throw E;Te(1,0)}}function _3(f,b,$,x){var E=_e();try{Kp(f,b,$,x)}catch(k){if(we(E),k!==k+0)throw k;Te(1,0)}}function wo(){if(0{g=f,_=b})}var bx,km,QA=D(()=>{"use strict";bx=Am,km=globalThis.self?.name?.startsWith("em-pthread"),km&&Am()}),qa,Cl,Pm,yt,yx,So,Cm,Rm,Ha,Dm,Wa,wx,Ka,_x,od=D(()=>{"use strict";id(),qa=typeof location>"u"?void 0:location.origin,Cl=import.meta.url>"file:"&&import.meta.url<"file;",Pm=()=>{if(Cl){let e=URL;return new URL(new e("ort.all.bundle.min.mjs",import.meta.url).href,qa).href}return import.meta.url},yt=Pm(),yx=()=>{if(yt&&!yt.startsWith("blob:"))return yt.substring(0,yt.lastIndexOf("/")+1)},So=(e,t)=>{try{let n=t??yt;return(n?new URL(e,n):new URL(e)).origin===qa}catch{return!1}},Cm=(e,t)=>{let n=t??yt;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},Rm=(e,t)=>`${t??"./"}${e}`,Ha=async e=>{let t=await(await fetch(e,{credentials:"same-origin"})).blob();return URL.createObjectURL(t)},Dm=async e=>(await import(e)).default,Wa=(JA(),Nn(fx)).default,wx=async()=>{if(!yt)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(So(yt))return[void 0,Wa()];let e=await Ha(yt);return[e,Wa(e)]},Ka=(QA(),Nn(gx)).default,_x=async(e,t,n,i)=>{let u=Ka&&!(e||t);if(u)if(yt)u=So(yt)||i&&!n;else if(i&&!n)u=!0;else throw new Error("cannot determine the script source URL.");if(u)return[void 0,Ka];{let l="ort-wasm-simd-threaded.jsep.mjs",d=e??Cm(l,t),c=n&&d&&!So(d,t),s=c?await Ha(d):d??Rm(l,t);return[c?s:void 0,await Dm(s)]}}}),Xa,Io,ci,Za,Mm,Nm,zm,sd,Be,vn=D(()=>{"use strict";od(),Io=!1,ci=!1,Za=!1,Mm=()=>{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}},Nm=()=>{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}},zm=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},sd=async e=>{if(Io)return Promise.resolve();if(ci)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Za)throw new Error("previous call to 'initializeWebAssembly()' failed.");ci=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd==="relaxed"){if(!zm())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Nm())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let i=Mm();n>1&&!i&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+n+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),e.numThreads=n=1);let u=e.wasmPaths,l=typeof u=="string"?u:void 0,d=u?.mjs,c=d?.href??d,s=u?.wasm,r=s?.href??s,o=e.wasmBinary,[a,p]=await _x(c,l,n>1,!!o||!!r),h=!1,m=[];if(t>0&&m.push(new Promise(g=>{setTimeout(()=>{h=!0,g()},t)})),m.push(new Promise((g,_)=>{let w={numThreads:n};if(o)w.wasmBinary=o,w.locateFile=y=>y;else if(r||l)w.locateFile=y=>r??l+y;else if(c&&c.indexOf("blob:")!==0)w.locateFile=y=>new URL(y,c).href;else if(a){let y=yx();y&&(w.locateFile=T=>y+T)}p(w).then(y=>{ci=!1,Io=!0,Xa=y,g(),a&&URL.revokeObjectURL(a)},y=>{ci=!1,Za=!0,_(y)})})),await Promise.race(m),h)throw new Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},Be=()=>{if(Io&&Xa)return Xa;throw new Error("WebAssembly is not initialized yet.")}}),Ut,Wo,Re,ad=D(()=>{"use strict";vn(),Ut=(e,t)=>{let n=Be(),i=n.lengthBytesUTF8(e)+1,u=n._malloc(i);return n.stringToUTF8(e,u,i),t.push(u),u},Wo=(e,t,n,i)=>{if(typeof e=="object"&&e!==null){if(n.has(e))throw new Error("Circular reference in options");n.add(e)}Object.entries(e).forEach(([u,l])=>{let d=t?t+u:u;if(typeof l=="object")Wo(l,d+".",n,i);else if(typeof l=="string"||typeof l=="number")i(d,l.toString());else if(typeof l=="boolean")i(d,l?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof l}`)})},Re=e=>{let t=Be(),n=t.stackSave();try{let i=t.PTR_SIZE,u=t.stackAlloc(2*i);t._OrtGetLastError(u,u+i);let l=Number(t.getValue(u,i===4?"i32":"i64")),d=t.getValue(u+i,"*"),c=d?t.UTF8ToString(d):"";throw new Error(`${e} ERROR_CODE: ${l}, ERROR_MESSAGE: ${c}`)}finally{t.stackRestore(n)}}}),vx,ek=D(()=>{"use strict";vn(),ad(),vx=e=>{let t=Be(),n=0,i=[],u=e||{};try{if(e?.logSeverityLevel===void 0)u.logSeverityLevel=2;else if(typeof e.logSeverityLevel!="number"||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)u.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!="number"||!Number.isInteger(e.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(u.terminate=!1);let l=0;return e?.tag!==void 0&&(l=Ut(e.tag,i)),n=t._OrtCreateRunOptions(u.logSeverityLevel,u.logVerbosityLevel,!!u.terminate,l),n===0&&Re("Can't create run options."),e?.extra!==void 0&&Wo(e.extra,"",new WeakSet,(d,c)=>{let s=Ut(d,i),r=Ut(c,i);t._OrtAddRunConfigEntry(n,s,r)!==0&&Re(`Can't set a run config entry: ${d} - ${c}.`)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseRunOptions(n),i.forEach(d=>t._free(d)),l}}}),Bm,Fm,Lm,Gr,jm,xx,tk=D(()=>{"use strict";vn(),ad(),Bm=e=>{switch(e){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${e}`)}},Fm=e=>{switch(e){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${e}`)}},Lm=e=>{e.extra||(e.extra={}),e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||(t.use_ort_model_bytes_directly="1"),e.executionProviders&&e.executionProviders.some(n=>(typeof n=="string"?n:n.name)==="webgpu")&&(e.enableMemPattern=!1)},Gr=(e,t,n,i)=>{let u=Ut(t,i),l=Ut(n,i);Be()._OrtAddSessionConfigEntry(e,u,l)!==0&&Re(`Can't set a session config entry: ${t} - ${n}.`)},jm=async(e,t,n)=>{let i=t.executionProviders;for(let u of i){let l=typeof u=="string"?u:u.name,d=[];switch(l){case"webnn":if(l="WEBNN",Gr(e,"session.disable_quant_qdq","1",n),Gr(e,"session.disable_qdq_constant_folding","1",n),typeof u!="string"){let a=u?.deviceType;a&&Gr(e,"deviceType",a,n)}break;case"webgpu":if(l="JS",typeof u!="string"){let a=u;if(a?.preferredLayout){if(a.preferredLayout!=="NCHW"&&a.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${a.preferredLayout}`);Gr(e,"preferredLayout",a.preferredLayout,n)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${l}`)}let c=Ut(l,n),s=d.length,r=0,o=0;if(s>0){r=Be()._malloc(s*Be().PTR_SIZE),n.push(r),o=Be()._malloc(s*Be().PTR_SIZE),n.push(o);for(let a=0;a{let t=Be(),n=0,i=[],u=e||{};Lm(u);try{let l=Bm(u.graphOptimizationLevel??"all"),d=Fm(u.executionMode??"sequential"),c=typeof u.logId=="string"?Ut(u.logId,i):0,s=u.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw new Error(`log severity level is not valid: ${s}`);let r=u.logVerbosityLevel??0;if(!Number.isInteger(r)||r<0||r>4)throw new Error(`log verbosity level is not valid: ${r}`);let o=typeof u.optimizedModelFilePath=="string"?Ut(u.optimizedModelFilePath,i):0;if(n=t._OrtCreateSessionOptions(l,!!u.enableCpuMemArena,!!u.enableMemPattern,d,!!u.enableProfiling,0,c,s,r,o),n===0&&Re("Can't create session options."),u.executionProviders&&await jm(n,u,i),u.enableGraphCapture!==void 0){if(typeof u.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${u.enableGraphCapture}`);Gr(n,"enableGraphCapture",u.enableGraphCapture.toString(),i)}if(u.freeDimensionOverrides)for(let[a,p]of Object.entries(u.freeDimensionOverrides)){if(typeof a!="string")throw new Error(`free dimension override name must be a string: ${a}`);if(typeof p!="number"||!Number.isInteger(p)||p<0)throw new Error(`free dimension override value must be a non-negative integer: ${p}`);let h=Ut(a,i);t._OrtAddFreeDimensionOverride(n,h,p)!==0&&Re(`Can't set a free dimension override: ${a} - ${p}.`)}return u.extra!==void 0&&Wo(u.extra,"",new WeakSet,(a,p)=>{Gr(n,a,p,i)}),[n,i]}catch(l){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&Re("Can't release session options."),i.forEach(d=>t._free(d)),l}}}),dn,sr,cn,us,Ko,ud,ld,Rl,de=D(()=>{"use strict";dn=e=>{switch(e){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${e}`)}},sr=e=>{switch(e){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${e}`)}},cn=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],i=typeof t=="number"?t:t.reduce((u,l)=>u*l,1);return n>0?Math.ceil(i*n):void 0},us=e=>{switch(e){case"float16":return typeof Float16Array<"u"?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${e}`)}},Ko=e=>{switch(e){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${e}`)}},ud=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",ld=e=>e==="float32"||e==="float16"||e==="int32"||e==="int64"||e==="uint32"||e==="uint64"||e==="int8"||e==="uint8"||e==="bool"||e==="uint4"||e==="int4",Rl=e=>{switch(e){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${e}`)}}}),dd,$x=D(()=>{"use strict";id(),dd=async e=>{if(typeof e=="string"){let t=await fetch(e);if(!t.ok)throw new Error(`failed to load external data file: ${e}`);let n=t.headers.get("Content-Length"),i=n?parseInt(n,10):0;if(i<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw new Error(`failed to load external data file: ${e}, no response body.`);let u=t.body.getReader(),l;try{l=new ArrayBuffer(i)}catch(c){if(c instanceof RangeError){let s=Math.ceil(i/65536);l=new WebAssembly.Memory({initial:s,maximum:s}).buffer}else throw c}let d=0;for(;;){let{done:c,value:s}=await u.read();if(c)break;let r=s.byteLength;new Uint8Array(l,d,r).set(s),d+=r}return new Uint8Array(l,0,i)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Um,Vm,Gm,qm,cd,Hm,Ie,ur=D(()=>{"use strict";de(),Um=["V","I","W","E","F"],Vm=(e,t)=>{console.log(`[${Um[e]},${new Date().toISOString()}]${t}`)},cd=(e,t)=>{Gm=e,qm=t},Hm=(e,t)=>{let n=Ko(e),i=Ko(Gm);n>=i&&Vm(n,typeof t=="function"?t():t)},Ie=(...e)=>{qm&&Hm(...e)}}),Wm,Bn,F,Xo,Tx,Sx,Ix,pe=D(()=>{"use strict";Wm=class{static calcMatMulShape(e,t){return e[1]!==t[0]?void 0:[e[0],t[1]]}},Bn=class{static calcShape(e,t,n=!1){let i=e.length,u=t.length;if(i===0)return t;if(u===0)return e;let l=Math.max(e.length,t.length),d=new Array(l);if(n){if(i<2||u<2)return;let c=Wm.calcMatMulShape([e[i-2],e[i-1]],[t[u-2],t[u-1]]);if(c===void 0)return;[d[l-2],d[l-1]]=c}for(let c=n?3:1;c<=l;c++){let s=i-c<0?1:e[i-c],r=u-c<0?1:t[u-c];if(s!==r&&s>1&&r>1)return;let o=Math.max(s,r);if(s&&r)d[l-c]=Math.max(s,r);else{if(o>1)return;d[l-c]=0}}return d}static isValidBroadcast(e,t){let n=e.length,i=t.length;if(n>i)return!1;for(let u=1;u<=n;u++)if(e[n-u]!==1&&e[n-u]!==t[i-u])return!1;return!0}},F=class Lo{static size(t){return Lo.getSizeFromDimensionRange(t,0,t.length)}static convertShape(t,n=4){let i=t.length;if(i===0)return[];let u=new Array(i),l=i-1;for(;l>=0;){if(t[l]%n===0){u[l]=t[l]/n;break}if(n%t[l]!==0)throw new Error("cannot convert shape");u[l]=1,n/=t[l],l--}for(l--;l>=0;l--)u[l]=t[l];return u}static sizeFromDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeFromDimension as Tensor has ${t.length} dimensions.`);return Lo.getSizeFromDimensionRange(t,n,t.length)}static sizeToDimension(t,n){if(n<0||n>t.length)throw new Error(`invalid dimension of ${n} for sizeToDimension as Tensor has ${t.length} dimensions.`);return Lo.getSizeFromDimensionRange(t,0,n)}static getSizeFromDimensionRange(t,n,i){let u=1;for(let l=n;l=0;--u)i[u]=i[u+1]*t[u+1];return i}static normalizeAxis(t,n){if(t<-n&&t>=n)throw new Error("unsupported axis for this operation.");return t<0?t+n:t}static normalizeAxes(t,n){return t.map(i=>this.normalizeAxis(i,n??t.length))}static sortBasedOnPerm(t,n){return n?n.map(i=>t[i]):t.slice().reverse()}static padShape(t,n){let i=t.length;return t.map((u,l)=>u+n[l]+n[l+i])}static areEqual(t,n){return t.length!==n.length?!1:t.every((i,u)=>i===n[u])}},Xo=class Er{static adjustPoolAttributes(t,n,i,u,l,d){if(!t&&i.length!==n.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(t)for(let c=0;c=i.length?i.push(n[c+2]):i[c]=n[c+2];for(let c=0;c=i[c]||d[c+i.length]>=i[c])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(t,n,i,u,l,d,c){if(c){if(l.length!==2*(t.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(n.length!==t.length-2)throw new Error("length of strides should be the length of data dimensions");if(u.length!==t.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let s=0;s=i+u&&(d-=1)),d}static adjustPadAndReturnShape(t,n,i,u,l,d,c,s,r=0){let o=i*(u-1)+1;if(s&&s!=="NOTSET")switch(s){case"VALID":return l[d]=0,l[c]=0,Er.computeOutputSize(t-o,n,t,0,r);case"SAME_LOWER":case"SAME_UPPER":if(i!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let a=(Math.floor((t+n-1)/n)-1)*n+u-t;return l[d]=Math.floor(s==="SAME_LOWER"?(a+1)/2:a/2),l[c]=a-l[d],Er.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}default:throw new Error("Unsupported AutoPad type")}else return Er.computeOutputSize(t+l[d]+l[c]-o,n,t,l[d],r)}},Tx=class{static getShapeOfGemmResult(e,t,n,i,u){if(e.length!==2||n.length!==2)throw new Error("shape need to be of size 2");let l,d,c;t?(l=e[1],d=e[0]):(l=e[0],d=e[1]);let s=-1;if(i?(c=n[0],s=1):(c=n[1],s=0),n[s]!==d)throw new Error("dimension mismatch");if(l<=0||c<=0||d<=0)throw new Error("invalid shape specified");if(u&&!Bn.isValidBroadcast(u,[l,c]))throw new Error("gemm: invalid bias shape for broadcast");return[l,c,d]}},Sx=-34028234663852886e22,Ix=34028234663852886e22}),pd,Ox=D(()=>{"use strict";de(),pd=(e,t)=>new(us(t))(e)}),Ya,Km,Ja,Xm,Qa,Zm,eu,tu,ru,Ym,Ex,rk=D(()=>{"use strict";de(),ur(),Ya=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),Km=(e,t)=>{if(t==="int32")return e;let n=Ya.get(t);if(!n)throw new Error(`WebNN backend does not support data type: ${t}`);let i=n/8;if(e.byteLength%i!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${i}.`);let u=e.byteLength/i,l=new(us(t))(e.buffer,e.byteOffset,u);switch(t){case"int64":case"uint64":{let d=new Int32Array(u);for(let c=0;c2147483647n||s<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");d[c]=Number(s)}return new Uint8Array(d.buffer)}case"int8":case"uint8":case"uint32":{if(t==="uint32"&&l.some(c=>c>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let d=Int32Array.from(l,Number);return new Uint8Array(d.buffer)}default:throw new Error(`Unsupported data conversion from ${t} to 'int32'`)}},Ja=(e,t)=>{if(t==="int32")return e;if(e.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let n=e.byteLength/4,i=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case"int64":{let u=BigInt64Array.from(i,BigInt);return new Uint8Array(u.buffer)}case"uint64":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let u=BigUint64Array.from(i,BigInt);return new Uint8Array(u.buffer)}case"int8":{if(i.some(l=>l<-128||l>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let u=Int8Array.from(i,Number);return new Uint8Array(u.buffer)}case"uint8":{if(i.some(u=>u<0||u>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(i,Number)}case"uint32":{if(i.some(l=>l<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let u=Uint32Array.from(i,Number);return new Uint8Array(u.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${t}`)}},Xm=1,Qa=()=>Xm++,Zm=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),eu=(e,t)=>{let n=Ya.get(e);if(!n)throw new Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((i,u)=>i*u)*n/8):0},tu=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:i,dataType:u,shape:l,fallbackDataType:d}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=i,this.dataType=u,this.tensorShape=l,this.fallbackDataType=d}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return eu(this.dataType,this.tensorShape)}destroy(){Ie("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Ja(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return new Uint8Array(n).buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((i,u)=>i===n[u])}setIsDataConverted(e){this.isDataConverted=e}},ru=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,i){let u=this.tensorManager.getMLContext(e),l=this.tensorManager.getMLOpSupportLimits(e),d;if(!l?.input.dataTypes.includes(t)){if(d=Zm.get(t),!d||l?.input.dataTypes.includes(d))throw new Error(`WebNN backend does not support data type: ${t}`);Ie("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${d}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(u,t,n))return this.wrapper.tensor;if(i){if(this.wrapper.byteLength!==eu(t,n))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let c=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,c,!0,!0,d),i&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")t=Km(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Ie("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Ja(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return e?this.wrapper.read(e):this.wrapper.read()}},Ym=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw new Error("MLContext not found for session.");return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=Qa();return this.tensorTrackersById.set(e,new ru(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,i,u){Ie("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${i}, copyOld: ${u}}`);let l=this.tensorTrackersById.get(t);if(!l)throw new Error("Tensor not found.");return l.ensureTensor(e,n,i,u)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");n.upload(t)}async download(e,t){Ie("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw new Error("Tensor not found.");return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,i){let u=this.getMLContext(e),l=Qa(),d=new tu({sessionId:e,context:u,tensor:t,dataType:n,shape:i});return this.tensorTrackersById.set(l,new ru(this,d)),this.externalTensors.add(d),l}async getCachedTensor(e,t,n,i,u,l,d){let c=this.getMLContext(e);for(let[r,o]of this.freeTensors.entries())if(o.canReuseTensor(c,t,n)){Ie("verbose",()=>`[WebNN] Reusing tensor {dataType: ${t}, ${d?`fallbackDataType: ${d},`:""} shape: ${n}`);let a=this.freeTensors.splice(r,1)[0];return a.sessionId=e,a}Ie("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${d?`fallbackDataType: ${d},`:""} shape: ${n}}`);let s=await c.createTensor({dataType:d??t,shape:n,dimensions:n,usage:i,writable:u,readable:l});return new tu({sessionId:e,context:c,tensor:s,dataType:t,shape:n,fallbackDataType:d})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},Ex=(...e)=>new Ym(...e)}),pi,Jm,Ax,nk=D(()=>{"use strict";de(),vn(),Ox(),rk(),ur(),pi=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),Jm=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),i=Object.keys(t).sort();return n.length===i.length&&n.every((u,l)=>u===i[l]&&e[u]===t[u])},Ax=class{constructor(e){this.tensorManager=Ex(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,cd(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(e){Ie("verbose",()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Ie("verbose",()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let n of t)Ie("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${n}}`),this.tensorManager.releaseTensorId(n);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let n=this.mlContextCache.findIndex(i=>i.gpuDevice===e);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:i}),i}}else if(e===void 0){let n=this.mlContextCache.findIndex(i=>i.options===void 0&&i.gpuDevice===void 0);if(n!==-1)return this.mlContextCache[n].mlContext;{let i=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:i}),i}}let t=this.mlContextCache.findIndex(n=>Jm(n.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let n=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:n}),n}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let i=this.mlContextCache.findIndex(u=>u.mlContext===t);i!==-1&&this.mlContextCache.splice(i,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Ie("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,i,u){let l=pi.get(n);if(!l)throw new Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,l,i,u)}async createTemporaryTensor(e,t,n){Ie("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let i=pi.get(t);if(!i)throw new Error(`Unsupported ONNX data type: ${t}`);let u=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,u,i,n,!1);let l=this.temporarySessionTensorIds.get(e);return l?l.push(u):this.temporarySessionTensorIds.set(e,[u]),u}uploadTensor(e,t){if(!Be().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");Ie("verbose",()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return pd(n,t)}}registerMLTensor(e,t,n,i){let u=pi.get(n);if(!u)throw new Error(`Unsupported ONNX data type: ${n}`);let l=this.tensorManager.registerTensor(e,t,u,i);return Ie("verbose",()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${u}, dimensions: ${i}} -> {tensorId: ${l}}`),l}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let i=pi.get(dn(t)),u=this.mlOpSupportLimitsBySessionId.get(e);return typeof i>"u"?!1:n?!!u?.input.dataTypes.includes(i):!!u?.output.dataTypes.includes(i)}flush(){}}}),hd=D(()=>{"use strict"}),nu,Oo,Eo,Qm,eg,iu,Dl,tg,kx,ik=D(()=>{"use strict";ur(),hd(),nu=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]]),Oo=[],Eo=e=>Math.ceil(Number(e)/16)*16,Qm=e=>{for(let t=0;teg++,Dl=async(e,t,n,i)=>{let u=Eo(n),l=e.device.createBuffer({size:u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let d=e.getCommandEncoder();e.endComputePass(),d.copyBufferToBuffer(t,0,l,0,u),e.flush(),await l.mapAsync(GPUMapMode.READ);let c=l.getMappedRange();if(i){let s=i();return s.set(new Uint8Array(c,0,n)),s}else return new Uint8Array(c.slice(0,n))}finally{l.destroy()}},tg=class{constructor(e){this.backend=e,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[t]of nu)Oo.push(t),this.freeBuffers.set(t,[]),this.freeUniformBuffers.set(t,[]);this.sessionCount=0}upload(e,t){let n=t.buffer,i=t.byteOffset,u=t.byteLength,l=Eo(u),d=this.storageCache.get(e);if(!d)throw new Error("gpu data for uploading does not exist");if(Number(d.originalSize)!==u)throw new Error(`inconsistent data size. gpu data size=${d.originalSize}, data size=${u}`);if(l===u&&i%4===0)this.backend.device.queue.writeBuffer(d.gpuData.buffer,0,n,i,u);else{let c=new Uint8Array(l);c.set(t),this.backend.device.queue.writeBuffer(d.gpuData.buffer,0,c,0,l)}Ie("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${e})`)}memcpy(e,t){let n=this.storageCache.get(e);if(!n)throw new Error("source gpu data for memcpy does not exist");let i=this.storageCache.get(t);if(!i)throw new Error("destination gpu data for memcpy does not exist");if(n.originalSize!==i.originalSize)throw new Error("inconsistent source and destination gpu data size");let u=Eo(n.originalSize),l=this.backend.getCommandEncoder();this.backend.endComputePass(),l.copyBufferToBuffer(n.gpuData.buffer,0,i.gpuData.buffer,0,u)}registerExternalBuffer(e,t,n){let i;if(n){if(i=n[0],e===n[1])return Ie("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, buffer is the same, skip.`),i;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet. + Please use the previous external buffer!`)}else i=iu();return this.storageCache.set(i,{gpuData:{id:i,type:0,buffer:e},originalSize:t}),Ie("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${t}) => id=${i}, registered.`),i}unregisterExternalBuffer(e){e!==void 0&&(this.storageCache.delete(e),Ie("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${e}`))}create(e,t=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let n=Qm(e),i,u=(t&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,l=(t&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(u||l){let c=(u?this.freeBuffers:this.freeUniformBuffers).get(n);c?c.length>0?i=c.pop():i=this.backend.device.createBuffer({size:n,usage:t}):i=this.backend.device.createBuffer({size:n,usage:t})}else i=this.backend.device.createBuffer({size:n,usage:t});let d={id:iu(),type:0,buffer:i};return this.storageCache.set(d.id,{gpuData:d,originalSize:Number(e)}),Ie("verbose",()=>`[WebGPU] GpuDataManager.create(size=${e}) => id=${d.id}`),d}get(e){return this.storageCache.get(e)?.gpuData}release(e){let t=typeof e=="bigint"?Number(e):e,n=this.storageCache.get(t);if(!n){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return Ie("verbose",()=>`[WebGPU] GpuDataManager.release(id=${t}), gpuDataId=${n.gpuData.id}`),this.storageCache.delete(t),this.buffersPending.push(n.gpuData.buffer),n.originalSize}async download(e,t){let n=this.storageCache.get(Number(e));if(!n)throw new Error("data does not exist");await Dl(this.backend,n.gpuData.buffer,n.originalSize,t)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let e of this.buffersPending){let t=nu.get(e.size);if((e.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let n=this.freeBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else if((e.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let n=this.freeUniformBuffers.get(e.size)||[];t===void 0||n.length>=t?e.destroy():n.push(e)}else e.destroy()}this.buffersPending=[]}else{let e=this.capturedPendingBuffers.get(this.backend.currentSessionId);e||(e=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,e));for(let t of this.buffersPending)e.push(t);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.freeUniformBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache.forEach(e=>{e.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(e=>{e.forEach(t=>{t.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(e){let t=this.capturedPendingBuffers.get(e);t&&(t.forEach(n=>{n.destroy()}),this.capturedPendingBuffers.delete(e)),this.sessionCount-=1,this.sessionCount===0&&(Ie("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(n=>{n.gpuData.buffer.destroy()}),this.storageCache=new Map)}},kx=(...e)=>new tg(...e)}),rg,ke,He=D(()=>{"use strict";rg=class{constructor(e){Object.assign(this,e)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(e=>`${this[e]}`).join(";")),this.key}},ke=e=>new rg(e)}),Fn,Ao,nt,rt,ue,qe,Ml,Mn,kr,se,hi,j,oe,Px,fd,ng,Cx,he=D(()=>{"use strict";de(),pe(),Fn=64,Ao=(e,t)=>{if(t===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(e)){case 10:return t>1?`vec${t}`:"f16";case 1:return t>1?`vec${t}`:"f32";case 6:return t>1?`vec${t}`:"i32";case 12:return t>1?`vec${t}`:"u32";case 7:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","i32"];case 13:if(t>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2","u32"];case 9:if(t!==4)throw new Error("bool must be vec4");return["u32","vec4"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${e}`)}},nt=(e,t=1)=>{let n=Ao(e,t);return typeof n=="string"?n:n[0]},rt=(e,t=1)=>{let n=Ao(e,t);return typeof n=="string"?n:n[1]},ue=(...e)=>{let t=[];return e.forEach(n=>{n.length!==0&&t.push({type:12,data:n},{type:12,data:F.computeStrides(n)})}),t},qe=e=>e%4===0?4:e%2===0?2:1,Ml=(e="f32",t,n="0")=>!t||t===1?`${e}(${n})`:`vec${t}<${e}>(${n})`,Mn=(e,t,n)=>e==="f32"?n:t===1?`f32(${n})`:`vec${t}(${n})`,kr=(e,t)=>t===4?`(${e}.x + ${e}.y + ${e}.z + ${e}.w)`:t===2?`(${e}.x + ${e}.y)`:t===3?`(${e}.x + ${e}.y + ${e}.z)`:e,se=(e,t,n,i)=>e.startsWith("uniforms.")&&n>4?typeof t=="string"?i==="f16"?`${e}[(${t}) / 8][(${t}) % 8 / 4][(${t}) % 8 % 4]`:`${e}[(${t}) / 4][(${t}) % 4]`:i==="f16"?`${e}[${Math.floor(t/8)}][${Math.floor(t%8/4)}][${t%8%4}]`:`${e}[${Math.floor(t/4)}][${t%4}]`:n>1?`${e}[${t}]`:e,hi=(e,t,n,i,u)=>{let l=typeof n=="number",d=l?n:n.length,c=[...new Array(d).keys()],s=d<2?"u32":d<=4?`vec${d}`:`array`,r=Ao(t,u),o=typeof r=="string"?r:r[1],a=typeof r=="string"?r:r[0],p={indices:s,value:o,storage:a,tensor:t},h=B=>typeof B=="string"?B:`${B}u`,m={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},g=l?"uniforms.":"",_=`${g}${e}_shape`,w=`${g}${e}_strides`,y="";for(let B=0;B(m.offsetToIndices=!0,d<2?B:`o2i_${e}(${B})`),O=[];if(d>=2)for(let B=d-1;B>=0;B--)O.push(`${se(w,B,d)} * (indices[${B}])`);let A=d<2?"":` fn i2o_${e}(indices: ${p.indices}) -> u32 { return ${O.join("+")}; - }`,P=B=>(m.indicesToOffset=!0,d<2?B:`i2o_${e}(${B})`),I=(...B)=>d===0?"0u":`${p.indices}(${B.map(h).join(",")})`,z=(B,te)=>d<2?`${B}`:`${se(B,te,d)}`,G=(B,te,Y)=>d<2?`${B}=${Y};`:`${se(B,te,d)}=${Y};`,J={},q=(B,te)=>{m.broadcastedIndicesToOffset=!0;let Y=`${te.name}broadcastedIndicesTo${e}Offset`;if(Y in J)return`${Y}(${B})`;let N=[];for(let X=d-1;X>=0;X--){let W=te.indicesGet("outputIndices",X+te.rank-d);N.push(`${z(w,X)} * (${W} % ${z(_,X)})`)}return J[Y]=`fn ${Y}(outputIndices: ${te.type.indices}) -> u32 { + }`,P=B=>(m.indicesToOffset=!0,d<2?B:`i2o_${e}(${B})`),I=(...B)=>d===0?"0u":`${p.indices}(${B.map(h).join(",")})`,z=(B,te)=>d<2?`${B}`:`${se(B,te,d)}`,q=(B,te,Y)=>d<2?`${B}=${Y};`:`${se(B,te,d)}=${Y};`,J={},G=(B,te)=>{m.broadcastedIndicesToOffset=!0;let Y=`${te.name}broadcastedIndicesTo${e}Offset`;if(Y in J)return`${Y}(${B})`;let N=[];for(let X=d-1;X>=0;X--){let W=te.indicesGet("outputIndices",X+te.rank-d);N.push(`${z(w,X)} * (${W} % ${z(_,X)})`)}return J[Y]=`fn ${Y}(outputIndices: ${te.type.indices}) -> u32 { return ${N.length>0?N.join("+"):"0u"}; }`,`${Y}(${B})`},C=(B,te)=>(()=>{if(p.storage===p.value)return`${e}[${B}]=${te};`;if(p.storage==="vec2"&&p.value==="i32")return`${e}[${B}]=vec2(u32(${te}), select(0u, 0xFFFFFFFFu, ${te} < 0));`;if(p.storage==="vec2"&&p.value==="u32")return`${e}[${B}]=vec2(u32(${te}), 0u);`;if(p.storage==="u32"&&p.value==="vec4")return`${e}[${B}]=dot(vec4(0x1, 0x100, 0x10000, 0x1000000), vec4(${te}));`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),ee=B=>(()=>{if(p.storage===p.value)return`${e}[${B}]`;if(p.storage==="vec2"&&p.value==="i32")return`i32(${e}[${B}].x)`;if(p.storage==="vec2"&&p.value==="u32")return`u32(${e}[${B}].x)`;if(p.storage==="u32"&&p.value==="vec4")return`vec4(bool(${e}[${B}] & 0xFFu), bool(${e}[${B}] & 0xFF00u), bool(${e}[${B}] & 0xFF0000u), bool(${e}[${B}] & 0xFF000000u))`;throw new Error(`not supported combination of storage type ${p.storage} and value type ${p.value} yet`)})(),v=d<2?"":` fn get_${e}ByIndices(indices: ${p.indices}) -> ${o} { @@ -1829,7 +1829,7 @@ as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=xm.onnx.ModelProto.decode(e fn set_${e}(${B}, value: ${o}) { set_${e}ByIndices(${I(te)}, value); }`})();return{impl:()=>{let B=[],te=!1;return m.offsetToIndices&&(B.push(T),te=!0),m.indicesToOffset&&(B.push(A),te=!0),m.broadcastedIndicesToOffset&&(Object.values(J).forEach(Y=>B.push(Y)),te=!0),m.set&&(B.push(K),te=!0),m.setByIndices&&(B.push(V),te=!0),m.get&&(B.push(R),te=!0),m.getByIndices&&(B.push(v),te=!0),!l&&te&&B.unshift(`const ${_} = ${p.indices}(${n.join(",")});`,`const ${w} = ${p.indices}(${F.computeStrides(n).join(",")});`),B.join(` -`)},type:p,offsetToIndices:S,indicesToOffset:P,broadcastedIndicesToOffset:q,indices:I,indicesGet:z,indicesSet:G,set:(...B)=>{if(B.length!==d+1)throw new Error(`indices length must be ${d}`);let te=B[d];if(typeof te!="string")throw new Error("value must be string");let Y=B.slice(0,d).map(h).join(",");return d===0?C("0u",te):d===1?C(Y[0],te):(m.set=!0,m.setByIndices=!0,m.indicesToOffset=!0,`set_${e}(${Y}, ${te})`)},setByOffset:C,setByIndices:(B,te)=>d<2?C(B,te):(m.setByIndices=!0,m.indicesToOffset=!0,`set_${e}ByIndices(${B}, ${te});`),get:H,getByOffset:ee,getByIndices:L,usage:i,name:e,strides:w,shape:_,rank:d}},j=(e,t,n,i=1)=>ci(e,t,n,"input",i),oe=(e,t,n,i=1)=>ci(e,t,n,"output",i),Ix=(e,t,n)=>ci(e,t,n,"atomicOutput",1),cd=(e,t,n,i=1)=>ci(e,t,n,"internal",i),Jm=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Fn){let t=typeof e=="number"?e:e[0],n=typeof e=="number"?1:e[1],i=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${n}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${n}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let u=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,l=u?`@builtin(global_invocation_id) global_id : vec3, +`)},type:p,offsetToIndices:S,indicesToOffset:P,broadcastedIndicesToOffset:G,indices:I,indicesGet:z,indicesSet:q,set:(...B)=>{if(B.length!==d+1)throw new Error(`indices length must be ${d}`);let te=B[d];if(typeof te!="string")throw new Error("value must be string");let Y=B.slice(0,d).map(h).join(",");return d===0?C("0u",te):d===1?C(Y[0],te):(m.set=!0,m.setByIndices=!0,m.indicesToOffset=!0,`set_${e}(${Y}, ${te})`)},setByOffset:C,setByIndices:(B,te)=>d<2?C(B,te):(m.setByIndices=!0,m.indicesToOffset=!0,`set_${e}ByIndices(${B}, ${te});`),get:H,getByOffset:ee,getByIndices:L,usage:i,name:e,strides:w,shape:_,rank:d}},j=(e,t,n,i=1)=>hi(e,t,n,"input",i),oe=(e,t,n,i=1)=>hi(e,t,n,"output",i),Px=(e,t,n)=>hi(e,t,n,"atomicOutput",1),fd=(e,t,n,i=1)=>hi(e,t,n,"internal",i),ng=class{constructor(e,t){this.normalizedDispatchGroup=e,this.limits=t,this.internalVariables=[],this.variables=[],this.uniforms=[],this.variableIndex=0}guardAgainstOutOfBoundsWorkgroupSizes(e){return`if (global_idx >= ${typeof e=="number"?`${e}u`:e}) { return; }`}mainStart(e=Fn){let t=typeof e=="number"?e:e[0],n=typeof e=="number"?1:e[1],i=typeof e=="number"?1:e[2];if(t>this.limits.maxComputeWorkgroupSizeX||n>this.limits.maxComputeWorkgroupSizeY||i>this.limits.maxComputeWorkgroupSizeZ)throw new Error(`workgroup size [${t}, ${n}, ${i}] exceeds the maximum workgroup size [${this.limits.maxComputeWorkgroupSizeX}, ${this.limits.maxComputeWorkgroupSizeY}, ${this.limits.maxComputeWorkgroupSizeZ}].`);if(t*n*i>this.limits.maxComputeInvocationsPerWorkgroup)throw new Error(`workgroup size [${t}, ${n}, ${i}] exceeds the maximum workgroup invocations ${this.limits.maxComputeInvocationsPerWorkgroup}.`);let u=this.normalizedDispatchGroup[1]===1&&this.normalizedDispatchGroup[2]===1,l=u?`@builtin(global_invocation_id) global_id : vec3, @builtin(workgroup_id) workgroup_id : vec3, @builtin(local_invocation_index) local_idx : u32, @builtin(local_invocation_id) local_id : vec3`:`@builtin(global_invocation_id) global_id : vec3, @@ -1847,13 +1847,13 @@ as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=xm.onnx.ModelProto.decode(e struct Uniforms { ${e.join(", ")} }; @group(0) @binding(${this.variableIndex}) var uniforms: Uniforms;`}get additionalImplementations(){return this.uniformDeclaration()+this.variables.map(e=>e.impl()).join(` `)+this.internalVariables.map(e=>e.impl()).join(` -`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},Ox=(e,t)=>new Jm(e,t)}),Qm,ru,eg,tg,rg,ng,$t,Ex,Ax,Cr=D(()=>{"use strict";de(),pe(),He(),he(),Qm=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},ru=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),eg=(e,t)=>F.sortBasedOnPerm(e,ru(e.length,t)),tg=(e,t,n,i)=>{let u=`fn perm(i: ${i.type.indices}) -> ${n.type.indices} { - var a: ${n.type.indices};`;for(let l=0;l{let n=[],i=[];for(let u=0;u{let n=0;for(let i=0;i{let n=e.dataType,i=e.dims.length,u=ru(i,t),l=eg(e.dims,u),d=e.dims,c=l,s=i<2||ng(u,e.dims),r;if(s)return r=m=>{let g=j("input",n,d,4),_=oe("output",n,c,4);return` +`)}get variablesInfo(){if(this.uniforms.length===0)return;let e=t=>[12,10,1,6][["u32","f16","f32","i32"].indexOf(t)];return this.uniforms.map(t=>[e(t.type),t.length??1])}},Cx=(e,t)=>new ng(e,t)}),ig,ou,og,sg,ag,ug,$t,Rx,Dx,Cr=D(()=>{"use strict";de(),pe(),He(),he(),ig=(e,t)=>{if(!e||e.length!==1)throw new Error("Transpose requires 1 input.");if(t.length!==0&&t.length!==e[0].dims.length)throw new Error(`perm size ${t.length} does not match input rank ${e[0].dims.length}`)},ou=(e,t)=>t.length!==0?t:[...new Array(e).keys()].reverse(),og=(e,t)=>F.sortBasedOnPerm(e,ou(e.length,t)),sg=(e,t,n,i)=>{let u=`fn perm(i: ${i.type.indices}) -> ${n.type.indices} { + var a: ${n.type.indices};`;for(let l=0;l{let n=[],i=[];for(let u=0;u{let n=0;for(let i=0;i{let n=e.dataType,i=e.dims.length,u=ou(i,t),l=og(e.dims,u),d=e.dims,c=l,s=i<2||ug(u,e.dims),r;if(s)return r=m=>{let g=j("input",n,d,4),_=oe("output",n,c,4);return` ${m.registerUniform("output_size","u32").declareVariables(g,_)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} output[global_idx] = input[global_idx]; - }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let m=F.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(m/64/4)},programUniforms:[{type:12,data:Math.ceil(m/4)}]}},getShaderSource:r};let{newShape:o,newPerm:a}=rg(e.dims,u),p=F.areEqual(a,[2,3,1]),h=F.areEqual(a,[3,1,2]);if(o.length===2||p||h){d=p?[o[0],o[1]*o[2]]:h?[o[0]*o[1],o[2]]:o,c=[d[1],d[0]];let m=16;return r=g=>{let _=j("a",n,d.length),w=oe("output",n,c.length);return` + }`},{name:"TransposeCopy",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let m=F.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(m/64/4)},programUniforms:[{type:12,data:Math.ceil(m/4)}]}},getShaderSource:r};let{newShape:o,newPerm:a}=ag(e.dims,u),p=F.areEqual(a,[2,3,1]),h=F.areEqual(a,[3,1,2]);if(o.length===2||p||h){d=p?[o[0],o[1]*o[2]]:h?[o[0]*o[1],o[2]]:o,c=[d[1],d[0]];let m=16;return r=g=>{let _=j("a",n,d.length),w=oe("output",n,c.length);return` ${g.registerUniform("output_size","u32").declareVariables(_,w)} var tile : array, ${m}>; ${g.mainStart([m,m,1])} @@ -1875,7 +1875,7 @@ as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=xm.onnx.ModelProto.decode(e }`},{name:"TransposeShared",shaderCache:{inputDependencies:["type"]},getRunData:()=>{let g=F.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(c[1]/m),y:Math.ceil(c[0]/m)},programUniforms:[{type:12,data:g},...ue(d,c)]}},getShaderSource:r}}return r=m=>{let g=j("a",n,d.length),_=oe("output",n,c.length);return` ${m.registerUniform("output_size","u32").declareVariables(g,_)} - ${tg(u,i,g,_)} + ${sg(u,i,g,_)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -1884,7 +1884,7 @@ as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=xm.onnx.ModelProto.decode(e let aIndices = perm(indices); ${_.setByOffset("global_idx",g.getByIndices("aIndices"))} - }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let m=F.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...ue(d,c)]}},getShaderSource:r}},Ex=(e,t)=>{Qm(e.inputs,t.perm),e.compute($t(e.inputs[0],t.perm))},Ax=e=>ke({perm:e.perm})}),ig,og,sg,ag,ug,lg,dg,cg,pg,hg,Nt,kx,Px,Cx,Rx,Dx,Mx,Nx,zx,Bx,Fx,JA=D(()=>{"use strict";de(),pe(),he(),pd(),Cr(),ig={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"},og={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"},sg={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},ag={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},ug=(e,t)=>{let n=[];for(let i=t-e;i{let n=[],i=e.length;for(let l=0;le[l]);return[n,u]},dg=(e,t)=>{let n=e.length+t.length,i=[],u=0;for(let l=0;l{for(let n=0;n{let n=[];if(!cg(e,t)){for(let i=0;in.push(i))}return n},hg=(e,t,n,i,u,l,d)=>{let c=n[0].dims,s=F.size(l),r=F.size(d),o=j("_A",n[0].dataType,c),a=oe("output",u,l),p=64;s===1&&(p=256);let h=` + }`},{name:"Transpose",shaderCache:{hint:`${t}`,inputDependencies:["rank"]},getRunData:()=>{let m=F.size(l);return{outputs:[{dims:l,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...ue(d,c)]}},getShaderSource:r}},Rx=(e,t)=>{ig(e.inputs,t.perm),e.compute($t(e.inputs[0],t.perm))},Dx=e=>ke({perm:e.perm})}),lg,dg,cg,pg,hg,fg,mg,gg,bg,yg,Nt,Mx,Nx,zx,Bx,Fx,Lx,jx,Ux,Vx,Gx,ok=D(()=>{"use strict";de(),pe(),he(),md(),Cr(),lg={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"},dg={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"},cg={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},pg={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},hg=(e,t)=>{let n=[];for(let i=t-e;i{let n=[],i=e.length;for(let l=0;le[l]);return[n,u]},mg=(e,t)=>{let n=e.length+t.length,i=[],u=0;for(let l=0;l{for(let n=0;n{let n=[];if(!gg(e,t)){for(let i=0;in.push(i))}return n},yg=(e,t,n,i,u,l,d)=>{let c=n[0].dims,s=F.size(l),r=F.size(d),o=j("_A",n[0].dataType,c),a=oe("output",u,l),p=64;s===1&&(p=256);let h=` var aBestValues : array; `,m=g=>` ${g.registerUniform("reduceSize","u32").declareVariables(o,a)} @@ -1897,11 +1897,11 @@ as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=xm.onnx.ModelProto.decode(e let outputIndex = global_idx / ${p}; let offset = outputIndex * uniforms.reduceSize; - var bestValue = f32(${sg[i]}); + var bestValue = f32(${cg[i]}); let Length = uniforms.reduceSize; for (var k = local_idx; k < Length; k = k + ${p}) { let candidate = f32(${o.getByOffset("offset + k")}); - bestValue = ${ig[i]}; + bestValue = ${lg[i]}; } aBestValues[local_idx] = bestValue; workgroupBarrier(); @@ -1912,7 +1912,7 @@ as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=xm.onnx.ModelProto.decode(e let interval = DIV_CEIL(reduceSize, 2u); if (local_idx < currentSize) { let candidate = aBestValues[local_idx + interval]; - bestValue = ${og[i]}; + bestValue = ${dg[i]}; aBestValues[local_idx] = bestValue; } reduceSize = interval; @@ -1920,9 +1920,9 @@ as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=xm.onnx.ModelProto.decode(e } if (local_idx == 0u) { - ${a.setByOffset("outputIndex",`${i==="mean"?`${a.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${a.type.storage}(${ag[i]})`}`)}; + ${a.setByOffset("outputIndex",`${i==="mean"?`${a.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${a.type.storage}(${pg[i]})`}`)}; } - }`;return{name:e,shaderCache:{hint:`${t};${p}`,inputDependencies:["type"]},getShaderSource:m,getRunData:()=>({outputs:[{dims:l,dataType:u}],dispatchGroup:{x:s},programUniforms:[{type:12,data:r}]})}},Nt=(e,t,n,i)=>{let u=e.inputs.length===1?n:Rl(e.inputs,n),l=u.axes;l.length===0&&!u.noopWithEmptyAxes&&(l=e.inputs[0].dims.map((h,m)=>m));let d=F.normalizeAxes(l,e.inputs[0].dims.length),c=d,s=e.inputs[0],r=pg(c,e.inputs[0].dims.length);r.length>0&&(s=e.compute($t(e.inputs[0],r),{inputs:[0],outputs:[-1]})[0],c=ug(c.length,s.dims.length));let[o,a]=lg(s.dims,c),p=o;u.keepDims&&(p=dg(o,d)),e.compute(hg(t,u.cacheKey,[s],i,e.inputs[0].dataType,p,a),{inputs:[s]})},kx=(e,t)=>{Nt(e,"ReduceMeanShared",t,"mean")},Px=(e,t)=>{Nt(e,"ReduceL1Shared",t,"l1")},Cx=(e,t)=>{Nt(e,"ReduceL2Shared",t,"l2")},Rx=(e,t)=>{Nt(e,"ReduceLogSumExpShared",t,"logSumExp")},Dx=(e,t)=>{Nt(e,"ReduceMaxShared",t,"max")},Mx=(e,t)=>{Nt(e,"ReduceMinShared",t,"min")},Nx=(e,t)=>{Nt(e,"ReduceProdShared",t,"prod")},zx=(e,t)=>{Nt(e,"ReduceSumShared",t,"sum")},Bx=(e,t)=>{Nt(e,"ReduceSumSquareShared",t,"sumSquare")},Fx=(e,t)=>{Nt(e,"ReduceLogSumShared",t,"logSum")}}),zt,fg,Ko,Rl,Bt,mg,gg,bg,yg,wg,_g,vg,xg,$g,Tg,Ft,Lx,jx,Ux,Vx,qx,Gx,Hx,Wx,Kx,Xx,pd=D(()=>{"use strict";de(),pe(),He(),he(),JA(),zt=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},fg=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Ko=(e,t,n,i,u,l,d=!1,c=!1)=>{let s=[],r=n[0].dims,o=r.length,a=F.normalizeAxes(u,o),p=!c&&a.length===0;r.forEach((g,_)=>{p||a.indexOf(_)>=0?d&&s.push(1):s.push(g)});let h=s.length,m=F.size(s);return{name:e,shaderCache:t,getShaderSource:g=>{let _=[],w=j("_A",n[0].dataType,o),y=oe("output",l,h),T=i(w,y,a),S=T[2];for(let O=0,A=0;O=0?(d&&A++,S=`for(var j${O}: u32 = 0; j${O} < ${r[O]}; j${O}++) { + }`;return{name:e,shaderCache:{hint:`${t};${p}`,inputDependencies:["type"]},getShaderSource:m,getRunData:()=>({outputs:[{dims:l,dataType:u}],dispatchGroup:{x:s},programUniforms:[{type:12,data:r}]})}},Nt=(e,t,n,i)=>{let u=e.inputs.length===1?n:Nl(e.inputs,n),l=u.axes;l.length===0&&!u.noopWithEmptyAxes&&(l=e.inputs[0].dims.map((h,m)=>m));let d=F.normalizeAxes(l,e.inputs[0].dims.length),c=d,s=e.inputs[0],r=bg(c,e.inputs[0].dims.length);r.length>0&&(s=e.compute($t(e.inputs[0],r),{inputs:[0],outputs:[-1]})[0],c=hg(c.length,s.dims.length));let[o,a]=fg(s.dims,c),p=o;u.keepDims&&(p=mg(o,d)),e.compute(yg(t,u.cacheKey,[s],i,e.inputs[0].dataType,p,a),{inputs:[s]})},Mx=(e,t)=>{Nt(e,"ReduceMeanShared",t,"mean")},Nx=(e,t)=>{Nt(e,"ReduceL1Shared",t,"l1")},zx=(e,t)=>{Nt(e,"ReduceL2Shared",t,"l2")},Bx=(e,t)=>{Nt(e,"ReduceLogSumExpShared",t,"logSumExp")},Fx=(e,t)=>{Nt(e,"ReduceMaxShared",t,"max")},Lx=(e,t)=>{Nt(e,"ReduceMinShared",t,"min")},jx=(e,t)=>{Nt(e,"ReduceProdShared",t,"prod")},Ux=(e,t)=>{Nt(e,"ReduceSumShared",t,"sum")},Vx=(e,t)=>{Nt(e,"ReduceSumSquareShared",t,"sumSquare")},Gx=(e,t)=>{Nt(e,"ReduceLogSumShared",t,"logSum")}}),zt,wg,Zo,Nl,Bt,_g,vg,xg,$g,Tg,Sg,Ig,Og,Eg,Ag,Ft,qx,Hx,Wx,Kx,Xx,Zx,Yx,Jx,Qx,e1,md=D(()=>{"use strict";de(),pe(),He(),he(),ok(),zt=e=>{if(!e||e.length===0||e.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(e.length===2&&e[1].dims.length!==1)throw new Error("Invalid axes input dims.")},wg=e=>["","",`var value = ${e.getByIndices("input_indices")};`,""],Zo=(e,t,n,i,u,l,d=!1,c=!1)=>{let s=[],r=n[0].dims,o=r.length,a=F.normalizeAxes(u,o),p=!c&&a.length===0;r.forEach((g,_)=>{p||a.indexOf(_)>=0?d&&s.push(1):s.push(g)});let h=s.length,m=F.size(s);return{name:e,shaderCache:t,getShaderSource:g=>{let _=[],w=j("_A",n[0].dataType,o),y=oe("output",l,h),T=i(w,y,a),S=T[2];for(let O=0,A=0;O=0?(d&&A++,S=`for(var j${O}: u32 = 0; j${O} < ${r[O]}; j${O}++) { ${T[2].includes("last_index")?`let last_index = j${O};`:""} ${w.indicesSet("input_indices",O,`j${O}`)} ${S} @@ -1943,19 +1943,19 @@ as ORT format: ${u}`)}}loadFromOnnxFormat(e,t){let n=xm.onnx.ModelProto.decode(e ${T[3]} ${T.length===4?y.setByOffset("global_idx","value"):T.slice(4).join(` `)} - }`},getRunData:()=>({outputs:[{dims:s,dataType:l}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...ue(r,s)]})}},Rl=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(i=>n.push(Number(i))),ke({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Bt=(e,t,n,i)=>{let u=e.inputs,l=u.length===1?n:Rl(u,n);e.compute(Ko(t,{hint:l.cacheKey,inputDependencies:["rank"]},[u[0]],l.noopWithEmptyAxes&&l.axes.length===0?fg:i,l.axes,u[0].dataType,l.keepDims,l.noopWithEmptyAxes),{inputs:[0]})},mg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceLogSum",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},gg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceL1",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},bg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceL2",t,(n,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},yg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceLogSumExp",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},wg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceMax",t,(n,i,u)=>{let l=[];for(let d=0;d=0||u.length===0)&&l.push(n.indicesSet("input_indices",d,0));return[`${l.join(` -`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},_g=(e,t)=>{zt(e.inputs),Bt(e,"ReduceMean",t,(n,i,u)=>{let l=1;for(let d=0;d=0||u.length===0)&&(l*=e.inputs[0].dims[d]);return["var sum = f32(0);","",`sum += f32(${n.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${l});`]})},vg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceMin",t,(n,i,u)=>{let l=[];for(let d=0;d=0||u.length===0)&&l.push(`input_indices[${d}] = 0;`);return[`${l.join(` -`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},xg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceProd",t,(n,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},$g=(e,t)=>{zt(e.inputs),Bt(e,"ReduceSum",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},Tg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceSumSquare",t,(n,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += t * t;`,""])},Ft=(e,t,n)=>{if(t.length===0)return n;let i=1,u=1;for(let l=0;l1024},Lx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?_g(e,t):kx(e,t)},jx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?gg(e,t):Px(e,t)},Ux=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?bg(e,t):Cx(e,t)},Vx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?yg(e,t):Rx(e,t)},qx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?wg(e,t):Dx(e,t)},Gx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vg(e,t):Mx(e,t)},Hx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xg(e,t):Nx(e,t)},Wx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$g(e,t):zx(e,t)},Kx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Tg(e,t):Bx(e,t)},Xx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?mg(e,t):Fx(e,t)}}),nu,Zx,Yx,Dl,QA=D(()=>{"use strict";de(),He(),pd(),nu=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},Zx=(e,t)=>{nu(e.inputs);let n=(i,u,l)=>{let d=[];for(let c=0;c=0||l.length===0)&&d.push(`input_indices[${c}] = 0;`);return[`${d.join(` + }`},getRunData:()=>({outputs:[{dims:s,dataType:l}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:[{type:12,data:m},...ue(r,s)]})}},Nl=(e,t)=>{let n=[];return e[1].dims[0]>0&&e[1].getBigInt64Array().forEach(i=>n.push(Number(i))),ke({axes:n,keepDims:t.keepDims,noopWithEmptyAxes:t.noopWithEmptyAxes})},Bt=(e,t,n,i)=>{let u=e.inputs,l=u.length===1?n:Nl(u,n);e.compute(Zo(t,{hint:l.cacheKey,inputDependencies:["rank"]},[u[0]],l.noopWithEmptyAxes&&l.axes.length===0?wg:i,l.axes,u[0].dataType,l.keepDims,l.noopWithEmptyAxes),{inputs:[0]})},_g=(e,t)=>{zt(e.inputs),Bt(e,"ReduceLogSum",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,"value = log(value);"])},vg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceL1",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += abs(${n.getByIndices("input_indices")});`,""])},xg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceL2",t,(n,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},$g=(e,t)=>{zt(e.inputs),Bt(e,"ReduceLogSumExp",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += exp(${n.getByIndices("input_indices")});`,"value = log(value);"])},Tg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceMax",t,(n,i,u)=>{let l=[];for(let d=0;d=0||u.length===0)&&l.push(n.indicesSet("input_indices",d,0));return[`${l.join(` +`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = max(value, ${n.getByIndices("input_indices")});`,""]})},Sg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceMean",t,(n,i,u)=>{let l=1;for(let d=0;d=0||u.length===0)&&(l*=e.inputs[0].dims[d]);return["var sum = f32(0);","",`sum += f32(${n.getByIndices("input_indices")});`,`let value = ${i.type.value}(sum / ${l});`]})},Ig=(e,t)=>{zt(e.inputs),Bt(e,"ReduceMin",t,(n,i,u)=>{let l=[];for(let d=0;d=0||u.length===0)&&l.push(`input_indices[${d}] = 0;`);return[`${l.join(` +`)}`,`var value = ${n.getByIndices("input_indices")};`,`value = min(value, ${n.getByIndices("input_indices")});`,""]})},Og=(e,t)=>{zt(e.inputs),Bt(e,"ReduceProd",t,(n,i)=>[`var value = ${i.type.storage}(1);`,"",`value *= ${n.getByIndices("input_indices")};`,""])},Eg=(e,t)=>{zt(e.inputs),Bt(e,"ReduceSum",t,(n,i)=>[`var value = ${i.type.storage}(0);`,"",`value += ${n.getByIndices("input_indices")};`,""])},Ag=(e,t)=>{zt(e.inputs),Bt(e,"ReduceSumSquare",t,(n,i)=>[`var t = ${i.type.value}(0); var value = ${i.type.value}(0);`,"",`t = ${n.getByIndices("input_indices")}; value += t * t;`,""])},Ft=(e,t,n)=>{if(t.length===0)return n;let i=1,u=1;for(let l=0;l1024},qx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Sg(e,t):Mx(e,t)},Hx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?vg(e,t):Nx(e,t)},Wx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?xg(e,t):zx(e,t)},Kx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?$g(e,t):Bx(e,t)},Xx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Tg(e,t):Fx(e,t)},Zx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ig(e,t):Lx(e,t)},Yx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Og(e,t):jx(e,t)},Jx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Eg(e,t):Ux(e,t)},Qx=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?Ag(e,t):Vx(e,t)},e1=(e,t)=>{Ft(e.inputs[0].dims,t.axes,t.noopWithEmptyAxes)?_g(e,t):Gx(e,t)}}),su,t1,r1,zl,sk=D(()=>{"use strict";de(),He(),md(),su=e=>{if(!e||e.length===0||e.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(e[0].dataType!==1)throw new Error("Invalid input type.")},t1=(e,t)=>{su(e.inputs);let n=(i,u,l)=>{let d=[];for(let c=0;c=0||l.length===0)&&d.push(`input_indices[${c}] = 0;`);return[`${d.join(` `)}`,`var value = ${i.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?"<=":"<"} value) { value = ${i.getByIndices("input_indices")}; best_index = i32(last_index); - }`,"",u.setByOffset("global_idx","best_index")]};e.compute(Ko("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},Yx=(e,t)=>{nu(e.inputs);let n=(i,u,l)=>{let d=[];for(let c=0;c=0||l.length===0)&&d.push(`input_indices[${c}] = 0;`);return[`${d.join(` + }`,"",u.setByOffset("global_idx","best_index")]};e.compute(Zo("ArgMin",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},r1=(e,t)=>{su(e.inputs);let n=(i,u,l)=>{let d=[];for(let c=0;c=0||l.length===0)&&d.push(`input_indices[${c}] = 0;`);return[`${d.join(` `)}`,`var value = ${i.getByIndices("input_indices")}; var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLastIndex>0?">=":">"} value) { value = ${i.getByIndices("input_indices")}; best_index = i32(last_index); - }`,"",u.setByOffset("global_idx","best_index")]};e.compute(Ko("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},Dl=e=>ke(e)}),Sg,Eo,Ig,Og,Eg,Mi,Ag,Jx,hd=D(()=>{"use strict";de(),pe(),dd(),he(),Sg=(e,t)=>{let n=e[0],i=e[1],u=e[2],l=e[3],d=e[4],c=e[5];if(d&&c)throw new Error("Attention cannot have both past and attention_bias");if(n.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let s=n.dims[0],r=n.dims[1],o=n.dims[2];if(u.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(i.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(i.dims[0]!==o)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(u.dims[0]!==i.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let a=u.dims[0]/3,p=a,h=p;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let T of t.qkvHiddenSizes)if(T%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");a=t.qkvHiddenSizes[0],p=t.qkvHiddenSizes[1],h=t.qkvHiddenSizes[2]}let m=r;if(a!==p)throw new Error("qkv_hidden_sizes first element should be same as the second");if(u.dims[0]!==a+p+h)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let g=0;if(d){if(p!==h)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]!==s)throw new Error('Input "past" second dimension must be batch_size');if(d.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(d.dims[4]!==p/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(g=d.dims[3])}let _=m+g,w=-1,y=0;if(l)throw new Error("Mask not supported");if(d)throw new Error("past is not supported");if(c){if(c.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(c.dims[0]!==s||c.dims[1]!==t.numHeads||c.dims[2]!==r||c.dims[3]!==_)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:s,sequenceLength:r,pastSequenceLength:g,kvSequenceLength:m,totalSequenceLength:_,maxSequenceLength:w,inputHiddenSize:o,hiddenSize:a,vHiddenSize:h,headSize:Math.floor(a/t.numHeads),vHeadSize:Math.floor(h/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:y,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},Eo=(e,t,n)=>t&&e?` + }`,"",u.setByOffset("global_idx","best_index")]};e.compute(Zo("argMax",{hint:t.cacheKey,inputDependencies:["rank"]},[e.inputs[0]],n,[t.axis],7,t.keepDims),{inputs:[0]})},zl=e=>ke(e)}),kg,ko,Pg,Cg,Rg,zi,Dg,n1,gd=D(()=>{"use strict";de(),pe(),hd(),he(),kg=(e,t)=>{let n=e[0],i=e[1],u=e[2],l=e[3],d=e[4],c=e[5];if(d&&c)throw new Error("Attention cannot have both past and attention_bias");if(n.dims.length!==3)throw new Error('Input "input" must have 3 dimensions');let s=n.dims[0],r=n.dims[1],o=n.dims[2];if(u.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimensions');if(i.dims.length!==2)throw new Error('Input "weights" is expected to have 2 dimensions');if(i.dims[0]!==o)throw new Error("Input 1 dimension 0 should have same length as dimension 2 of input 0");if(u.dims[0]!==i.dims[1])throw new Error('Input "bias" dimension 0 should have same length as dimension 1 of input "weights"');let a=u.dims[0]/3,p=a,h=p;if(t.qkvHiddenSizes.length>0){if(t.qkvHiddenSizes.length!==3)throw new Error("qkv_hidden_sizes attribute should have 3 elements");for(let T of t.qkvHiddenSizes)if(T%t.numHeads!==0)throw new Error("qkv_hidden_sizes should be divisible by num_heads");a=t.qkvHiddenSizes[0],p=t.qkvHiddenSizes[1],h=t.qkvHiddenSizes[2]}let m=r;if(a!==p)throw new Error("qkv_hidden_sizes first element should be same as the second");if(u.dims[0]!==a+p+h)throw new Error('Input "bias" dimension 0 should have same length as sum of Q/K/V hidden sizes');let g=0;if(d){if(p!==h)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]!==s)throw new Error('Input "past" second dimension must be batch_size');if(d.dims[2]!==t.numHeads)throw new Error('Input "past" third dimension must be num_heads');if(d.dims[4]!==p/t.numHeads)throw new Error('Input "past" fifth dimension must be k_hidden_size / num_heads');t.pastPresentShareBuffer||(g=d.dims[3])}let _=m+g,w=-1,y=0;if(l)throw new Error("Mask not supported");if(d)throw new Error("past is not supported");if(c){if(c.dims.length!==4)throw new Error('Input "attention_bias" must have 4 dimensions');if(c.dims[0]!==s||c.dims[1]!==t.numHeads||c.dims[2]!==r||c.dims[3]!==_)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:s,sequenceLength:r,pastSequenceLength:g,kvSequenceLength:m,totalSequenceLength:_,maxSequenceLength:w,inputHiddenSize:o,hiddenSize:a,vHiddenSize:h,headSize:Math.floor(a/t.numHeads),vHeadSize:Math.floor(h/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:y,scale:t.scale,broadcastResPosBias:!1,passPastInKv:!1,qkvFormat:1}},ko=(e,t,n)=>t&&e?` let total_sequence_length_input = u32(${t.getByOffset("0")}); let present_sequence_length = max(total_sequence_length_input, uniforms.past_sequence_length); let is_subsequent_prompt: bool = sequence_length > 1 && sequence_length != total_sequence_length_input; @@ -1968,7 +1968,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas `:` ${n?"let past_sequence_length = uniforms.past_sequence_length":""}; let present_sequence_length = total_sequence_length; - `,Ig=(e,t,n,i,u,l,d,c)=>{let s=Ge(d?1:l),r=64,o=l/s;o{let y=oe("x",e.dataType,e.dims,s),T=[y],S=d?j("seq_lens",d.dataType,d.dims):void 0;S&&T.push(S);let O=c?j("total_sequence_length_input",c.dataType,c.dims):void 0;O&&T.push(O);let A=rt(e.dataType),P=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` + `,Pg=(e,t,n,i,u,l,d,c)=>{let s=qe(d?1:l),r=64,o=l/s;o{let y=oe("x",e.dataType,e.dims,s),T=[y],S=d?j("seq_lens",d.dataType,d.dims):void 0;S&&T.push(S);let O=c?j("total_sequence_length_input",c.dataType,c.dims):void 0;O&&T.push(O);let A=rt(e.dataType),P=[{name:"batch_size",type:"u32"},{name:"num_heads",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"sequence_length",type:"u32"},{name:"total_sequence_length",type:"u32"},{name:"elements_per_thread",type:"u32"}];return` var thread_max: array; var thread_sum: array; ${w.registerUniforms(P).declareVariables(...T)} @@ -1977,7 +1977,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas let headIdx = workgroup_id.z % uniforms.num_heads; let sequence_length = uniforms.sequence_length; var total_sequence_length = uniforms.total_sequence_length; - ${Eo(S,O,!1)} + ${ko(S,O,!1)} let local_offset = local_idx * uniforms.elements_per_thread; let offset = (global_idx / ${r}) * uniforms.total_sequence_length + local_offset; let seq_causal_length = ${d?"u32(past_sequence_length + workgroup_id.y + 1)":"total_sequence_length"}; @@ -2019,12 +2019,12 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas for (var total_seq_id: u32 = seq_causal_length; total_seq_id + local_offset < uniforms.total_sequence_length; total_seq_id++) { x[offset + total_seq_id] = ${y.type.value}(${A}(0)); }`:""}; - }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${r};${h};${s}`,inputDependencies:g},getShaderSource:_,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:u,z:t*n},programUniforms:p})}},Og=(e,t,n,i,u,l,d,c,s)=>{let r=d+l.kvSequenceLength,o=[l.batchSize,l.numHeads,l.sequenceLength,r],a=e>1&&i,p=l.kvNumHeads?l.kvNumHeads:l.numHeads,h=a?[l.batchSize,p,r,l.headSize]:void 0,m=l.nReps?l.nReps:1,g=l.scale===0?1/Math.sqrt(l.headSize):l.scale,_=Ge(l.headSize),w=l.headSize/_,y=12,T={x:Math.ceil(r/y),y:Math.ceil(l.sequenceLength/y),z:l.batchSize*l.numHeads},S=[{type:12,data:l.sequenceLength},{type:12,data:w},{type:12,data:r},{type:12,data:l.numHeads},{type:12,data:l.headSize},{type:1,data:g},{type:12,data:d},{type:12,data:l.kvSequenceLength},{type:12,data:m}],O=a&&i&&F.size(i.dims)>0,A=["type","type"];O&&A.push("type"),u&&A.push("type"),c&&A.push("type"),s&&A.push("type");let P=[{dims:o,dataType:t.dataType,gpuDataType:0}];a&&P.push({dims:h,dataType:t.dataType,gpuDataType:0});let I=z=>{let G=j("q",t.dataType,t.dims,_),J=j("key",n.dataType,n.dims,_),q=[G,J];if(O){let V=j("past_key",i.dataType,i.dims,_);q.push(V)}u&&q.push(j("attention_bias",u.dataType,u.dims));let C=c?j("seq_lens",c.dataType,c.dims):void 0;C&&q.push(C);let ee=s?j("total_sequence_length_input",s.dataType,s.dims):void 0;ee&&q.push(ee);let v=oe("output",t.dataType,o),R=[v];a&&R.push(oe("present_key",t.dataType,h,_));let H=rt(1,_),L=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + }`};return{name:"AttentionProbsSoftmax",shaderCache:{hint:`${r};${h};${s}`,inputDependencies:g},getShaderSource:_,getRunData:()=>({outputs:[],dispatchGroup:{x:1,y:u,z:t*n},programUniforms:p})}},Cg=(e,t,n,i,u,l,d,c,s)=>{let r=d+l.kvSequenceLength,o=[l.batchSize,l.numHeads,l.sequenceLength,r],a=e>1&&i,p=l.kvNumHeads?l.kvNumHeads:l.numHeads,h=a?[l.batchSize,p,r,l.headSize]:void 0,m=l.nReps?l.nReps:1,g=l.scale===0?1/Math.sqrt(l.headSize):l.scale,_=qe(l.headSize),w=l.headSize/_,y=12,T={x:Math.ceil(r/y),y:Math.ceil(l.sequenceLength/y),z:l.batchSize*l.numHeads},S=[{type:12,data:l.sequenceLength},{type:12,data:w},{type:12,data:r},{type:12,data:l.numHeads},{type:12,data:l.headSize},{type:1,data:g},{type:12,data:d},{type:12,data:l.kvSequenceLength},{type:12,data:m}],O=a&&i&&F.size(i.dims)>0,A=["type","type"];O&&A.push("type"),u&&A.push("type"),c&&A.push("type"),s&&A.push("type");let P=[{dims:o,dataType:t.dataType,gpuDataType:0}];a&&P.push({dims:h,dataType:t.dataType,gpuDataType:0});let I=z=>{let q=j("q",t.dataType,t.dims,_),J=j("key",n.dataType,n.dims,_),G=[q,J];if(O){let V=j("past_key",i.dataType,i.dims,_);G.push(V)}u&&G.push(j("attention_bias",u.dataType,u.dims));let C=c?j("seq_lens",c.dataType,c.dims):void 0;C&&G.push(C);let ee=s?j("total_sequence_length_input",s.dataType,s.dims):void 0;ee&&G.push(ee);let v=oe("output",t.dataType,o),R=[v];a&&R.push(oe("present_key",t.dataType,h,_));let H=rt(1,_),L=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"alpha",type:"f32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${y}u; - var tileQ: array<${G.type.storage}, ${y*y}>; - var tileK: array<${G.type.storage}, ${y*y}>; - ${z.registerUniforms(L).declareVariables(...q,...R)} + var tileQ: array<${q.type.storage}, ${y*y}>; + var tileK: array<${q.type.storage}, ${y*y}>; + ${z.registerUniforms(L).declareVariables(...G,...R)} ${z.mainStart([y,y,1])} // x holds the N and y holds the M let headIdx = workgroup_id.z % uniforms.num_heads; @@ -2035,7 +2035,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas let n = workgroup_id.x * TILE_SIZE; let sequence_length = uniforms.M; var total_sequence_length = uniforms.N; - ${Eo(C,ee,!0)} + ${ko(C,ee,!0)} let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; let qOffset = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; ${O&&a?"let pastKeyOffset = absKvHeadIdx * uniforms.past_sequence_length * uniforms.K;":""}; @@ -2076,11 +2076,11 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas var sum: f32 = ${(()=>{switch(_){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: ${_}`)}})()}; output[outputIdx] = ${v.type.value} (sum * uniforms.alpha) + ${u?"attention_bias[outputIdx]":"0.0"}; } - }`};return{name:"AttentionProbs",shaderCache:{hint:`${_};${u!==void 0};${i!==void 0};${e}`,inputDependencies:A},getRunData:()=>({outputs:P,dispatchGroup:T,programUniforms:S}),getShaderSource:I}},Eg=(e,t,n,i,u,l,d=void 0,c=void 0)=>{let s=l+u.kvSequenceLength,r=u.nReps?u.nReps:1,o=u.vHiddenSize*r,a=e>1&&i,p=u.kvNumHeads?u.kvNumHeads:u.numHeads,h=a?[u.batchSize,p,s,u.headSize]:void 0,m=[u.batchSize,u.sequenceLength,o],g=12,_={x:Math.ceil(u.vHeadSize/g),y:Math.ceil(u.sequenceLength/g),z:u.batchSize*u.numHeads},w=[{type:12,data:u.sequenceLength},{type:12,data:s},{type:12,data:u.vHeadSize},{type:12,data:u.numHeads},{type:12,data:u.headSize},{type:12,data:o},{type:12,data:l},{type:12,data:u.kvSequenceLength},{type:12,data:r}],y=a&&i&&F.size(i.dims)>0,T=["type","type"];y&&T.push("type"),d&&T.push("type"),c&&T.push("type");let S=[{dims:m,dataType:t.dataType,gpuDataType:0}];a&&S.push({dims:h,dataType:t.dataType,gpuDataType:0});let O=A=>{let P=j("probs",t.dataType,t.dims),I=j("v",n.dataType,n.dims),z=[P,I];y&&z.push(j("past_value",i.dataType,i.dims));let G=d?j("seq_lens",d.dataType,d.dims):void 0;d&&z.push(G);let J=c?j("total_sequence_length_input",c.dataType,c.dims):void 0;c&&z.push(J);let q=[oe("output",t.dataType,m)];a&&q.push(oe("present_value",t.dataType,h));let C=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` + }`};return{name:"AttentionProbs",shaderCache:{hint:`${_};${u!==void 0};${i!==void 0};${e}`,inputDependencies:A},getRunData:()=>({outputs:P,dispatchGroup:T,programUniforms:S}),getShaderSource:I}},Rg=(e,t,n,i,u,l,d=void 0,c=void 0)=>{let s=l+u.kvSequenceLength,r=u.nReps?u.nReps:1,o=u.vHiddenSize*r,a=e>1&&i,p=u.kvNumHeads?u.kvNumHeads:u.numHeads,h=a?[u.batchSize,p,s,u.headSize]:void 0,m=[u.batchSize,u.sequenceLength,o],g=12,_={x:Math.ceil(u.vHeadSize/g),y:Math.ceil(u.sequenceLength/g),z:u.batchSize*u.numHeads},w=[{type:12,data:u.sequenceLength},{type:12,data:s},{type:12,data:u.vHeadSize},{type:12,data:u.numHeads},{type:12,data:u.headSize},{type:12,data:o},{type:12,data:l},{type:12,data:u.kvSequenceLength},{type:12,data:r}],y=a&&i&&F.size(i.dims)>0,T=["type","type"];y&&T.push("type"),d&&T.push("type"),c&&T.push("type");let S=[{dims:m,dataType:t.dataType,gpuDataType:0}];a&&S.push({dims:h,dataType:t.dataType,gpuDataType:0});let O=A=>{let P=j("probs",t.dataType,t.dims),I=j("v",n.dataType,n.dims),z=[P,I];y&&z.push(j("past_value",i.dataType,i.dims));let q=d?j("seq_lens",d.dataType,d.dims):void 0;d&&z.push(q);let J=c?j("total_sequence_length_input",c.dataType,c.dims):void 0;c&&z.push(J);let G=[oe("output",t.dataType,m)];a&&G.push(oe("present_value",t.dataType,h));let C=[{name:"M",type:"u32"},{name:"K",type:"u32"},{name:"N",type:"u32"},{name:"num_heads",type:"u32"},{name:"head_size",type:"u32"},{name:"v_hidden_size",type:"u32"},{name:"past_sequence_length",type:"u32"},{name:"kv_sequence_length",type:"u32"},{name:"n_reps",type:"u32"}];return` const TILE_SIZE = ${g}u; var tileQ: array<${P.type.value}, ${g*g}>; var tileV: array<${P.type.value}, ${g*g}>; - ${A.registerUniforms(C).declareVariables(...z,...q)} + ${A.registerUniforms(C).declareVariables(...z,...G)} ${A.mainStart([g,g,1])} let headIdx = workgroup_id.z % uniforms.num_heads; let batchIdx = workgroup_id.z / uniforms.num_heads; @@ -2090,7 +2090,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas let n = global_id.x; let sequence_length = uniforms.M; var total_sequence_length = uniforms.K; - ${Eo(G,J,!0)} + ${ko(q,J,!0)} let offsetA = workgroup_id.z * uniforms.M * uniforms.K + m * uniforms.K; let absKvHeadIdx = batchIdx * kv_num_heads + kvHeadIdx; // kvHeadIdx is relative to the batch ${y&&a?"let pastValueOffset = absKvHeadIdx * uniforms.N * uniforms.past_sequence_length + n;":""}; @@ -2131,7 +2131,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas + headIdx * uniforms.N + n; output[outputIdx] = value; } - }`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${e}`,inputDependencies:T},getRunData:()=>({outputs:S,dispatchGroup:_,programUniforms:w}),getShaderSource:O}},Mi=(e,t,n,i,u,l,d,c,s,r,o=void 0,a=void 0)=>{let p=Math.min(e.outputCount,1+(d?1:0)+(c?1:0)),h=p>1?d:void 0,m=p>1?c:void 0,g=p>1?r.pastSequenceLength:0,_=g+r.kvSequenceLength,w=s&&F.size(s.dims)>0?s:void 0,y=[t,n];h&&F.size(h.dims)>0&&y.push(h),w&&y.push(w),o&&y.push(o),a&&y.push(a);let T=e.compute(Og(p,t,n,h,w,r,g,o,a),{inputs:y,outputs:p>1?[-1,1]:[-1]})[0];e.compute(Ig(T,r.batchSize,r.numHeads,g,r.sequenceLength,_,o,a),{inputs:o&&a?[T,o,a]:[T],outputs:[]});let S=[T,i];m&&F.size(m.dims)>0&&S.push(m),o&&S.push(o),a&&S.push(a),e.compute(Eg(p,T,i,m,r,g,o,a),{inputs:S,outputs:p>1?[0,2]:[0]})},Ag=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],i=t.sequenceLength,u=t.inputHiddenSize,l=t.headSize,d=12,c={x:Math.ceil(t.headSize/d),y:Math.ceil(t.sequenceLength/d),z:t.batchSize*t.numHeads},s=[e.inputs[0],e.inputs[1],e.inputs[2]],r=[{type:12,data:i},{type:12,data:u},{type:12,data:l},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],o=a=>{let p=oe("output_q",s[0].dataType,n),h=oe("output_k",s[0].dataType,n),m=oe("output_v",s[0].dataType,n),g=j("input",s[0].dataType,s[0].dims),_=j("weight",s[1].dataType,s[1].dims),w=j("bias",s[2].dataType,s[2].dims),y=g.type.storage,T=[{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` + }`};return{name:"AttentionScore",shaderCache:{hint:`${i!==void 0};${e}`,inputDependencies:T},getRunData:()=>({outputs:S,dispatchGroup:_,programUniforms:w}),getShaderSource:O}},zi=(e,t,n,i,u,l,d,c,s,r,o=void 0,a=void 0)=>{let p=Math.min(e.outputCount,1+(d?1:0)+(c?1:0)),h=p>1?d:void 0,m=p>1?c:void 0,g=p>1?r.pastSequenceLength:0,_=g+r.kvSequenceLength,w=s&&F.size(s.dims)>0?s:void 0,y=[t,n];h&&F.size(h.dims)>0&&y.push(h),w&&y.push(w),o&&y.push(o),a&&y.push(a);let T=e.compute(Cg(p,t,n,h,w,r,g,o,a),{inputs:y,outputs:p>1?[-1,1]:[-1]})[0];e.compute(Pg(T,r.batchSize,r.numHeads,g,r.sequenceLength,_,o,a),{inputs:o&&a?[T,o,a]:[T],outputs:[]});let S=[T,i];m&&F.size(m.dims)>0&&S.push(m),o&&S.push(o),a&&S.push(a),e.compute(Rg(p,T,i,m,r,g,o,a),{inputs:S,outputs:p>1?[0,2]:[0]})},Dg=(e,t)=>{let n=[t.batchSize,t.numHeads,t.sequenceLength,t.headSize],i=t.sequenceLength,u=t.inputHiddenSize,l=t.headSize,d=12,c={x:Math.ceil(t.headSize/d),y:Math.ceil(t.sequenceLength/d),z:t.batchSize*t.numHeads},s=[e.inputs[0],e.inputs[1],e.inputs[2]],r=[{type:12,data:i},{type:12,data:u},{type:12,data:l},{type:12,data:t.numHeads},{type:12,data:t.headSize},{type:12,data:t.hiddenSize},{type:12,data:t.hiddenSize+t.hiddenSize+t.vHiddenSize}],o=a=>{let p=oe("output_q",s[0].dataType,n),h=oe("output_k",s[0].dataType,n),m=oe("output_v",s[0].dataType,n),g=j("input",s[0].dataType,s[0].dims),_=j("weight",s[1].dataType,s[1].dims),w=j("bias",s[2].dataType,s[2].dims),y=g.type.storage,T=[{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<${y}, ${d*d}>; var tileWeightQ: array<${y}, ${d*d}>; @@ -2186,7 +2186,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas output_k[outputIdx] = valueK; output_v[outputIdx] = valueV; } - }`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:r}),getShaderSource:o},{inputs:s,outputs:[-1,-1,-1]})},Jx=(e,t)=>{let n=Sg(e.inputs,t),[i,u,l]=Ag(e,n);return Mi(e,i,u,l,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}}),kg,Pg,Cg,Qx,ek=D(()=>{"use strict";dt(),de(),pe(),He(),he(),kg=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let n=(i,u,l)=>{let d=u.length;if(d!==i.length)throw new Error(`${l}: num dimensions != ${d}`);u.forEach((c,s)=>{if(c!==i[s])throw new Error(`${l}: dim[${s}] do not match`)})};if(e[0].dims.length>1){let i=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);n(e[1].dims,i,"Invalid input scale"),n(e[2].dims,i,"Invalid input B"),n(e[3].dims,i,"Invalid input mean"),n(e[4].dims,i,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},Pg=(e,t)=>{let{epsilon:n,spatial:i,format:u}=t,l=e[0].dims,d=i?Ge(l[l.length-1]):1,c=u==="NHWC"&&l.length>1?d:1,s=F.size(l)/d,r=i,o=r?l.length:l,a=j("x",e[0].dataType,e[0].dims,d),p=j("scale",e[1].dataType,e[1].dims,c),h=j("bias",e[2].dataType,e[2].dims,c),m=j("inputMean",e[3].dataType,e[3].dims,c),g=j("inputVar",e[4].dataType,e[4].dims,c),_=oe("y",e[0].dataType,o,d),w=()=>{let T="";if(i)T=`let cOffset = ${l.length===1?"0u":u==="NHWC"?`outputIndices[${l.length-1}] / ${d}`:"outputIndices[1]"};`;else if(u==="NCHW")T=` + }`};return e.compute({name:"AttentionPrepare",shaderCache:{inputDependencies:["type","type","type"]},getRunData:()=>({outputs:[{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0},{dims:n,dataType:e.inputs[0].dataType,gpuDataType:0}],dispatchGroup:c,programUniforms:r}),getShaderSource:o},{inputs:s,outputs:[-1,-1,-1]})},n1=(e,t)=>{let n=kg(e.inputs,t),[i,u,l]=Dg(e,n);return zi(e,i,u,l,e.inputs[4],void 0,void 0,void 0,e.inputs[5],n)}}),Mg,Ng,zg,i1,ak=D(()=>{"use strict";dt(),de(),pe(),He(),he(),Mg=(e,t)=>{if(!e||e.length!==5)throw new Error("BatchNormalization requires 5 inputs");let n=(i,u,l)=>{let d=u.length;if(d!==i.length)throw new Error(`${l}: num dimensions != ${d}`);u.forEach((c,s)=>{if(c!==i[s])throw new Error(`${l}: dim[${s}] do not match`)})};if(e[0].dims.length>1){let i=t.format==="NHWC"?t.spatial?e[0].dims.slice(-1):e[0].dims.slice(-1).concat(e[0].dims.slice(1,e[0].dims.length-1)):e[0].dims.slice(1,t.spatial?2:void 0);n(e[1].dims,i,"Invalid input scale"),n(e[2].dims,i,"Invalid input B"),n(e[3].dims,i,"Invalid input mean"),n(e[4].dims,i,"Invalid input var")}else n(e[1].dims,[1],"Invalid input scale"),n(e[2].dims,[1],"Invalid input B"),n(e[3].dims,[1],"Invalid input mean"),n(e[4].dims,[1],"Invalid input var")},Ng=(e,t)=>{let{epsilon:n,spatial:i,format:u}=t,l=e[0].dims,d=i?qe(l[l.length-1]):1,c=u==="NHWC"&&l.length>1?d:1,s=F.size(l)/d,r=i,o=r?l.length:l,a=j("x",e[0].dataType,e[0].dims,d),p=j("scale",e[1].dataType,e[1].dims,c),h=j("bias",e[2].dataType,e[2].dims,c),m=j("inputMean",e[3].dataType,e[3].dims,c),g=j("inputVar",e[4].dataType,e[4].dims,c),_=oe("y",e[0].dataType,o,d),w=()=>{let T="";if(i)T=`let cOffset = ${l.length===1?"0u":u==="NHWC"?`outputIndices[${l.length-1}] / ${d}`:"outputIndices[1]"};`;else if(u==="NCHW")T=` ${_.indicesSet("outputIndices","0","0")} let cOffset = ${_.indicesToOffset("outputIndices")};`;else{T=`var cIndices = ${p.type.indices}(0); cIndices[0] = outputIndices[${l.length-1}];`;for(let S=1;S` @@ -2203,7 +2203,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas let x = ${a.getByOffset("global_idx")}; let value = (x - inputMean) * inverseSqrt(inputVar + epsilon) * scale + bias; ${_.setByOffset("global_idx","value")} - }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${i}_${d}`,inputDependencies:r?["rank","type","type","type","type"]:void 0},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:r?[{type:12,data:s},...ue(l)]:[{type:12,data:s}]})}},Cg=e=>ke(e),Qx=(e,t)=>{let{inputs:n,outputCount:i}=e,u=Cg({...t,outputCount:i});if(me.webgpu.validateInputContent&&kg(n,u),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Pg(n,u))}}),Rg,Dg,e1,tk=D(()=>{"use strict";pe(),he(),Rg=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Dg=e=>{let t=e[0].dims,n=e[0].dims[2],i=F.size(t)/4,u=e[0].dataType,l=j("input",u,t,4),d=j("bias",u,[n],4),c=j("residual",u,t,4),s=oe("output",u,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:r=>` + }`;return{name:"BatchNormalization",shaderCache:{hint:`${t.epsilon}_${t.format}_${i}_${d}`,inputDependencies:r?["rank","type","type","type","type"]:void 0},getShaderSource:y,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:r?[{type:12,data:s},...ue(l)]:[{type:12,data:s}]})}},zg=e=>ke(e),i1=(e,t)=>{let{inputs:n,outputCount:i}=e,u=zg({...t,outputCount:i});if(me.webgpu.validateInputContent&&Mg(n,u),t.trainingMode)throw new Error("BatchNormalization trainingMode is not supported yet.");e.compute(Ng(n,u))}}),Bg,Fg,o1,uk=D(()=>{"use strict";pe(),he(),Bg=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![320,640,1280].includes(e[0].dims[2]))throw new Error("number of channels should be 320, 640 or 1280");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Fg=e=>{let t=e[0].dims,n=e[0].dims[2],i=F.size(t)/4,u=e[0].dataType,l=j("input",u,t,4),d=j("bias",u,[n],4),c=j("residual",u,t,4),s=oe("output",u,t,4);return{name:"BiasAdd",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(i/64)}}),getShaderSource:r=>` const channels = ${n}u / 4; ${r.declareVariables(l,d,c,s)} @@ -2212,7 +2212,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas let value = ${l.getByOffset("global_idx")} + ${d.getByOffset("global_idx % channels")} + ${c.getByOffset("global_idx")}; ${s.setByOffset("global_idx","value")} - }`}},e1=e=>{Rg(e.inputs),e.compute(Dg(e.inputs))}}),Mg,Ee,t1,r1,n1,i1,o1,s1,a1,u1,l1,Ng,d1,c1,p1,h1,Si,f1,Fo,m1,g1,b1,y1,w1,_1,v1,x1,$1,T1,S1,I1,O1,E1,A1,k1,P1,iu,C1,Ml,Nl,R1,D1,M1,zg,Bg,N1,fd=D(()=>{"use strict";de(),pe(),He(),he(),Mg=(e,t,n,i,u,l,d)=>{let c=Math.ceil(t/4),s="";typeof u=="string"?s=`${u}(a)`:s=u("a");let r=j("inputData",n,[c],4),o=oe("outputData",i,[c],4),a=[{name:"vec_size",type:"u32"}];return d&&a.push(...d),` + }`}},o1=e=>{Bg(e.inputs),e.compute(Fg(e.inputs))}}),Lg,Ee,s1,a1,u1,l1,d1,c1,p1,h1,f1,jg,m1,g1,b1,y1,Oi,w1,jo,_1,v1,x1,$1,T1,S1,I1,O1,E1,A1,k1,P1,C1,R1,D1,M1,N1,au,z1,Bl,Fl,B1,F1,L1,Ug,Vg,j1,bd=D(()=>{"use strict";de(),pe(),He(),he(),Lg=(e,t,n,i,u,l,d)=>{let c=Math.ceil(t/4),s="";typeof u=="string"?s=`${u}(a)`:s=u("a");let r=j("inputData",n,[c],4),o=oe("outputData",i,[c],4),a=[{name:"vec_size",type:"u32"}];return d&&a.push(...d),` ${e.registerUniforms(a).declareVariables(r,o)} ${l??""} @@ -2222,7 +2222,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas let a = ${r.getByOffset("global_idx")}; ${o.setByOffset("global_idx",s)} - }`},Ee=(e,t,n,i,u,l=e.dataType,d,c)=>{let s=[{type:12,data:Math.ceil(F.size(e.dims)/4)}];return d&&s.push(...d),{name:t,shaderCache:{hint:u,inputDependencies:["type"]},getShaderSource:r=>Mg(r,F.size(e.dims),e.dataType,l,n,i,c),getRunData:r=>({outputs:[{dims:e.dims,dataType:l}],dispatchGroup:{x:Math.ceil(F.size(r[0].dims)/64/4)},programUniforms:s})}},t1=e=>{e.compute(Ee(e.inputs[0],"Abs","abs"))},r1=e=>{e.compute(Ee(e.inputs[0],"Acos","acos"))},n1=e=>{e.compute(Ee(e.inputs[0],"Acosh","acosh"))},i1=e=>{e.compute(Ee(e.inputs[0],"Asin","asin"))},o1=e=>{e.compute(Ee(e.inputs[0],"Asinh","asinh"))},s1=e=>{e.compute(Ee(e.inputs[0],"Atan","atan"))},a1=e=>{e.compute(Ee(e.inputs[0],"Atanh","atanh"))},u1=e=>ke(e),l1=(e,t)=>{let n;switch(t.to){case 10:n="vec4";break;case 1:n="vec4";break;case 12:n="vec4";break;case 6:n="vec4";break;case 9:n="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(Ee(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},Ng=e=>{let t,n,i=e.length>=2&&e[1].data!==0,u=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=i?e[1].getFloat32Array()[0]:-34028234663852886e22,n=u?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=i?e[1].getUint16Array()[0]:64511,n=u?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return ke({min:t,max:n})},d1=(e,t)=>{let n=t||Ng(e.inputs),i=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Clip",u=>`clamp(${u}, vec4<${i}>(uniforms.min), vec4<${i}>(uniforms.max))`,void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:"min",type:i},{name:"max",type:i}]),{inputs:[0]})},c1=e=>{e.compute(Ee(e.inputs[0],"Ceil","ceil"))},p1=e=>{e.compute(Ee(e.inputs[0],"Cos","cos"))},h1=e=>{e.compute(Ee(e.inputs[0],"Cosh","cosh"))},Si=e=>ke(e),f1=(e,t)=>{let n=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Elu",i=>`elu_vf32(${i})`,` + }`},Ee=(e,t,n,i,u,l=e.dataType,d,c)=>{let s=[{type:12,data:Math.ceil(F.size(e.dims)/4)}];return d&&s.push(...d),{name:t,shaderCache:{hint:u,inputDependencies:["type"]},getShaderSource:r=>Lg(r,F.size(e.dims),e.dataType,l,n,i,c),getRunData:r=>({outputs:[{dims:e.dims,dataType:l}],dispatchGroup:{x:Math.ceil(F.size(r[0].dims)/64/4)},programUniforms:s})}},s1=e=>{e.compute(Ee(e.inputs[0],"Abs","abs"))},a1=e=>{e.compute(Ee(e.inputs[0],"Acos","acos"))},u1=e=>{e.compute(Ee(e.inputs[0],"Acosh","acosh"))},l1=e=>{e.compute(Ee(e.inputs[0],"Asin","asin"))},d1=e=>{e.compute(Ee(e.inputs[0],"Asinh","asinh"))},c1=e=>{e.compute(Ee(e.inputs[0],"Atan","atan"))},p1=e=>{e.compute(Ee(e.inputs[0],"Atanh","atanh"))},h1=e=>ke(e),f1=(e,t)=>{let n;switch(t.to){case 10:n="vec4";break;case 1:n="vec4";break;case 12:n="vec4";break;case 6:n="vec4";break;case 9:n="vec4";break;default:throw new RangeError(`not supported type (specified in attribute 'to' from 'Cast' operator): ${t.to}`)}e.compute(Ee(e.inputs[0],"Cast",n,void 0,t.cacheKey,t.to))},jg=e=>{let t,n,i=e.length>=2&&e[1].data!==0,u=e.length>=3&&e[2].data!==0;switch(e[0].dataType){case 1:t=i?e[1].getFloat32Array()[0]:-34028234663852886e22,n=u?e[2].getFloat32Array()[0]:34028234663852886e22;break;case 10:t=i?e[1].getUint16Array()[0]:64511,n=u?e[2].getUint16Array()[0]:31743;break;default:throw new Error("Unsupport data type")}return ke({min:t,max:n})},m1=(e,t)=>{let n=t||jg(e.inputs),i=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Clip",u=>`clamp(${u}, vec4<${i}>(uniforms.min), vec4<${i}>(uniforms.max))`,void 0,n.cacheKey,void 0,[{type:e.inputs[0].dataType,data:n.min},{type:e.inputs[0].dataType,data:n.max}],[{name:"min",type:i},{name:"max",type:i}]),{inputs:[0]})},g1=e=>{e.compute(Ee(e.inputs[0],"Ceil","ceil"))},b1=e=>{e.compute(Ee(e.inputs[0],"Cos","cos"))},y1=e=>{e.compute(Ee(e.inputs[0],"Cosh","cosh"))},Oi=e=>ke(e),w1=(e,t)=>{let n=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Elu",i=>`elu_vf32(${i})`,` const elu_alpha_ = ${n}(${t.alpha}); fn elu_f32(a: ${n}) -> ${n} { @@ -2231,7 +2231,7 @@ var best_index : i32 = 0;`,`if (${i.getByIndices("input_indices")} ${t.selectLas fn elu_vf32(v: vec4<${n}>) -> vec4<${n}> { return vec4(elu_f32(v.x), elu_f32(v.y), elu_f32(v.z), elu_f32(v.w)); - }`,t.cacheKey))},Fo=(e="f32")=>` + }`,t.cacheKey))},jo=(e="f32")=>` const r0: ${e} = 0.3275911; const r1: ${e} = 0.254829592; const r2: ${e} = -0.284496736; @@ -2243,15 +2243,15 @@ fn erf_vf32(v: vec4<${e}>) -> vec4<${e}> { let absv = abs(v); let x = 1.0 / (1.0 + r0 * absv); return sign(v) * (1.0 - ((((r5 * x + r4) * x + r3) * x + r2) * x + r1) * x * exp(-absv * absv)); -}`,m1=e=>{let t=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Erf",n=>`erf_vf32(${n})`,Fo(t)))},g1=e=>{e.compute(Ee(e.inputs[0],"Exp","exp"))},b1=e=>{e.compute(Ee(e.inputs[0],"Floor","floor"))},y1=e=>{let t=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Gelu",n=>`0.5 * ${n} * (1.0 + erf_vf32(${n} * 0.7071067811865475))`,Fo(t)))},w1=(e,t)=>{let n=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"LeakyRelu",i=>`select(leaky_relu_alpha_ * ${i}, ${i}, ${i} >= vec4<${n}>(0.0))`,`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},_1=e=>{e.compute(Ee(e.inputs[0],"Not",t=>`!${t}`))},v1=e=>{e.compute(Ee(e.inputs[0],"Neg",t=>`-${t}`))},x1=e=>{e.compute(Ee(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},$1=e=>{let t=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Relu",n=>`select(vec4<${t}>(0.0), ${n}, ${n} > vec4<${t}>(0.0))`))},T1=e=>{e.compute(Ee(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},S1=e=>ke(e),I1=(e,t)=>{let n=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"HardSigmoid",i=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${i} + vec4<${n}>(${t.beta})))`,void 0,t.cacheKey))},O1=e=>{let t=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"HardSwish",n=>`${n} * max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), vec4<${t}>(${t}(1.0 / 6.0)) * ${n} + vec4<${t}>(0.5)))`))},E1=e=>{e.compute(Ee(e.inputs[0],"Sin","sin"))},A1=e=>{e.compute(Ee(e.inputs[0],"Sinh","sinh"))},k1=e=>{e.compute(Ee(e.inputs[0],"Sqrt","sqrt"))},P1=e=>{e.compute(Ee(e.inputs[0],"Tan","tan"))},iu=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,C1=e=>{e.compute(Ee(e.inputs[0],"Tanh",iu))},Ml=(e="f32")=>` +}`,_1=e=>{let t=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Erf",n=>`erf_vf32(${n})`,jo(t)))},v1=e=>{e.compute(Ee(e.inputs[0],"Exp","exp"))},x1=e=>{e.compute(Ee(e.inputs[0],"Floor","floor"))},$1=e=>{let t=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Gelu",n=>`0.5 * ${n} * (1.0 + erf_vf32(${n} * 0.7071067811865475))`,jo(t)))},T1=(e,t)=>{let n=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"LeakyRelu",i=>`select(leaky_relu_alpha_ * ${i}, ${i}, ${i} >= vec4<${n}>(0.0))`,`const leaky_relu_alpha_ = ${n}(${t.alpha});`,t.cacheKey))},S1=e=>{e.compute(Ee(e.inputs[0],"Not",t=>`!${t}`))},I1=e=>{e.compute(Ee(e.inputs[0],"Neg",t=>`-${t}`))},O1=e=>{e.compute(Ee(e.inputs[0],"Reciprocal",t=>`1.0/${t}`))},E1=e=>{let t=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"Relu",n=>`select(vec4<${t}>(0.0), ${n}, ${n} > vec4<${t}>(0.0))`))},A1=e=>{e.compute(Ee(e.inputs[0],"Sigmoid",t=>`(1.0 / (1.0 + exp(-${t})))`))},k1=e=>ke(e),P1=(e,t)=>{let n=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"HardSigmoid",i=>`max(vec4<${n}>(0.0), min(vec4<${n}>(1.0), ${t.alpha} * ${i} + vec4<${n}>(${t.beta})))`,void 0,t.cacheKey))},C1=e=>{let t=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"HardSwish",n=>`${n} * max(vec4<${t}>(0.0), min(vec4<${t}>(1.0), vec4<${t}>(${t}(1.0 / 6.0)) * ${n} + vec4<${t}>(0.5)))`))},R1=e=>{e.compute(Ee(e.inputs[0],"Sin","sin"))},D1=e=>{e.compute(Ee(e.inputs[0],"Sinh","sinh"))},M1=e=>{e.compute(Ee(e.inputs[0],"Sqrt","sqrt"))},N1=e=>{e.compute(Ee(e.inputs[0],"Tan","tan"))},au=e=>`sign(${e}) * (1 - exp(-2 * abs(${e}))) / (1 + exp(-2 * abs(${e})))`,z1=e=>{e.compute(Ee(e.inputs[0],"Tanh",au))},Bl=(e="f32")=>` const fast_gelu_a: ${e} = 0.5; const fast_gelu_b: ${e} = 0.7978845608028654; const fast_gelu_c: ${e} = 0.035677408136300125; fn tanh_v(v: vec4<${e}>) -> vec4<${e}> { - return ${iu("v")}; + return ${au("v")}; } -`,Nl=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,R1=e=>{let t=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"FastGelu",Nl,Ml(t),void 0,e.inputs[0].dataType))},D1=(e,t)=>{let n=rt(e.inputs[0].dataType);return e.compute(Ee(e.inputs[0],"ThresholdedRelu",i=>`select(vec4<${n}>(0.0), ${i}, ${i} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},M1=e=>{e.compute(Ee(e.inputs[0],"Log","log"))},zg=(e,t)=>` +`,Fl=e=>`(fast_gelu_a + fast_gelu_a * tanh_v(${e} * (fast_gelu_c * ${e} * ${e} + fast_gelu_b))) * ${e}`,B1=e=>{let t=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"FastGelu",Fl,Bl(t),void 0,e.inputs[0].dataType))},F1=(e,t)=>{let n=rt(e.inputs[0].dataType);return e.compute(Ee(e.inputs[0],"ThresholdedRelu",i=>`select(vec4<${n}>(0.0), ${i}, ${i} > thresholded_relu_alpha_)`,`const thresholded_relu_alpha_ = vec4<${n}>(${t.alpha});`,t.cacheKey)),0},L1=e=>{e.compute(Ee(e.inputs[0],"Log","log"))},Ug=(e,t)=>` const alpha = vec4<${e}>(${t}); const one = ${e}(1.0); const zero = ${e}(0.0); @@ -2268,13 +2268,13 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { } return x * x1; } -`,Bg=e=>`quick_gelu_impl(${e})`,N1=(e,t)=>{let n=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"QuickGelu",Bg,zg(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Fg,Lg,z1,rk=D(()=>{"use strict";pe(),he(),fd(),Fg=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},Lg=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=j("input",e[0].dataType,e[0].dims,4),i=j("bias",e[0].dataType,[e[0].dims[2]],4),u=oe("output",e[0].dataType,t,4),l=F.size(t)/4,d=nt(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)}}),getShaderSource:c=>` +`,Vg=e=>`quick_gelu_impl(${e})`,j1=(e,t)=>{let n=rt(e.inputs[0].dataType);e.compute(Ee(e.inputs[0],"QuickGelu",Vg,Ug(n,t.alpha),t.cacheKey,e.inputs[0].dataType))}}),Gg,qg,U1,lk=D(()=>{"use strict";pe(),he(),bd(),Gg=e=>{if(e[0].dims.length!==3)throw new Error("input should have 3 dimensions");if(![2560,5120,10240].includes(e[0].dims[2]))throw new Error("hidden state should be 2560, 5120 or 10240");if(e[1].dims.length!==1)throw new Error("bias is expected to have 1 dimensions");if(e[0].dims[2]!==e[1].dims[0])throw new Error("last dimension of input and bias are not the same")},qg=e=>{let t=e[0].dims.slice();t[2]=t[2]/2;let n=j("input",e[0].dataType,e[0].dims,4),i=j("bias",e[0].dataType,[e[0].dims[2]],4),u=oe("output",e[0].dataType,t,4),l=F.size(t)/4,d=nt(e[0].dataType);return{name:"BiasSplitGelu",getRunData:()=>({outputs:[{dims:t,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)}}),getShaderSource:c=>` const M_SQRT2 = sqrt(2.0); const halfChannels = ${e[0].dims[2]/4/2}u; ${c.declareVariables(n,i,u)} - ${Fo(d)} + ${jo(d)} ${c.mainStart()} ${c.guardAgainstOutOfBoundsWorkgroupSizes(l)} @@ -2286,7 +2286,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { let geluRight = valueRight * 0.5 * (erf_vf32(valueRight / M_SQRT2) + 1); ${u.setByOffset("global_idx","valueLeft * geluRight")} - }`}},z1=e=>{Fg(e.inputs),e.compute(Lg(e.inputs))}}),jg,Ug,Lt,B1,F1,L1,j1,U1,V1,q1,G1,H1,W1,nk=D(()=>{"use strict";de(),pe(),he(),jg=(e,t,n,i,u,l,d,c,s,r,o,a)=>{let p,h;typeof c=="string"?p=h=(y,T)=>`${c}((${y}),(${T}))`:typeof c=="function"?p=h=c:(p=c.scalar,h=c.vector);let m=oe("outputData",o,i.length,4),g=j("aData",s,t.length,4),_=j("bData",r,n.length,4),w;if(u)if(l){let y=F.size(t)===1,T=F.size(n)===1,S=t.length>0&&t[t.length-1]%4===0,O=n.length>0&&n[n.length-1]%4===0;y||T?w=m.setByOffset("global_idx",h(y?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"),T?`${_.type.value}(${_.getByOffset("0")}.x)`:_.getByOffset("global_idx"))):w=` + }`}},U1=e=>{Gg(e.inputs),e.compute(qg(e.inputs))}}),Hg,Wg,Lt,V1,G1,q1,H1,W1,K1,X1,Z1,Y1,J1,dk=D(()=>{"use strict";de(),pe(),he(),Hg=(e,t,n,i,u,l,d,c,s,r,o,a)=>{let p,h;typeof c=="string"?p=h=(y,T)=>`${c}((${y}),(${T}))`:typeof c=="function"?p=h=c:(p=c.scalar,h=c.vector);let m=oe("outputData",o,i.length,4),g=j("aData",s,t.length,4),_=j("bData",r,n.length,4),w;if(u)if(l){let y=F.size(t)===1,T=F.size(n)===1,S=t.length>0&&t[t.length-1]%4===0,O=n.length>0&&n[n.length-1]%4===0;y||T?w=m.setByOffset("global_idx",h(y?`${g.type.value}(${g.getByOffset("0")}.x)`:g.getByOffset("global_idx"),T?`${_.type.value}(${_.getByOffset("0")}.x)`:_.getByOffset("global_idx"))):w=` let outputIndices = ${m.offsetToIndices("global_idx * 4u")}; let offsetA = ${g.broadcastedIndicesToOffset("outputIndices",m)}; let offsetB = ${_.broadcastedIndicesToOffset("outputIndices",m)}; @@ -2319,7 +2319,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${w} - }`},Ug=(e,t,n,i,u,l,d=n.dataType)=>{let c=n.dims.map(Number),s=i.dims.map(Number),r=!F.areEqual(c,s),o=c,a=F.size(c),p=!1,h=!1,m=[r];if(r){let g=Bn.calcShape(c,s,!1);if(!g)throw new Error("Can't perform binary op on the given tensors");o=g.slice(),a=F.size(o);let _=F.size(c)===1,w=F.size(s)===1,y=c.length>0&&c[c.length-1]%4===0,T=s.length>0&&s[s.length-1]%4===0;m.push(_),m.push(w),m.push(y),m.push(T);let S=1;for(let O=1;Og.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:g=>jg(g,c,s,o,p,r,h,u,n.dataType,i.dataType,d,l),getRunData:()=>({outputs:[{dims:o,dataType:d}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:Math.ceil(F.size(o)/4)},...ue(c,s,o)]})}},Lt=(e,t,n,i,u,l)=>{e.compute(Ug(t,u??"",e.inputs[0],e.inputs[1],n,i,l))},B1=e=>{Lt(e,"Add",(t,n)=>`${t}+${n}`)},F1=e=>{Lt(e,"Div",(t,n)=>`${t}/${n}`)},L1=e=>{Lt(e,"Equal",{scalar:(t,n)=>`u32(${t}==${n})`,vector:(t,n)=>`vec4(${t}==${n})`},void 0,void 0,9)},j1=e=>{Lt(e,"Mul",(t,n)=>`${t}*${n}`)},U1=e=>{let t=j("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Lt(e,"Pow",{scalar:(n,i)=>`pow_custom(${n},${i})`,vector:(n,i)=>`pow_vector_custom(${n},${i})`},` + }`},Wg=(e,t,n,i,u,l,d=n.dataType)=>{let c=n.dims.map(Number),s=i.dims.map(Number),r=!F.areEqual(c,s),o=c,a=F.size(c),p=!1,h=!1,m=[r];if(r){let g=Bn.calcShape(c,s,!1);if(!g)throw new Error("Can't perform binary op on the given tensors");o=g.slice(),a=F.size(o);let _=F.size(c)===1,w=F.size(s)===1,y=c.length>0&&c[c.length-1]%4===0,T=s.length>0&&s[s.length-1]%4===0;m.push(_),m.push(w),m.push(y),m.push(T);let S=1;for(let O=1;Og.toString()).join("_"),inputDependencies:["rank","rank"]},getShaderSource:g=>Hg(g,c,s,o,p,r,h,u,n.dataType,i.dataType,d,l),getRunData:()=>({outputs:[{dims:o,dataType:d}],dispatchGroup:{x:Math.ceil(a/64/4)},programUniforms:[{type:12,data:Math.ceil(F.size(o)/4)},...ue(c,s,o)]})}},Lt=(e,t,n,i,u,l)=>{e.compute(Wg(t,u??"",e.inputs[0],e.inputs[1],n,i,l))},V1=e=>{Lt(e,"Add",(t,n)=>`${t}+${n}`)},G1=e=>{Lt(e,"Div",(t,n)=>`${t}/${n}`)},q1=e=>{Lt(e,"Equal",{scalar:(t,n)=>`u32(${t}==${n})`,vector:(t,n)=>`vec4(${t}==${n})`},void 0,void 0,9)},H1=e=>{Lt(e,"Mul",(t,n)=>`${t}*${n}`)},W1=e=>{let t=j("input",e.inputs[0].dataType,e.inputs[0].dims).type.value;Lt(e,"Pow",{scalar:(n,i)=>`pow_custom(${n},${i})`,vector:(n,i)=>`pow_vector_custom(${n},${i})`},` fn pow_custom(a : ${t}, b : ${t}) -> ${t} { if (b == ${t}(0.0)) { return ${t}(1.0); @@ -2332,7 +2332,7 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { // TODO: implement vectorized pow return vec4<${t}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w)); } - `)},V1=e=>{Lt(e,"Sub",(t,n)=>`${t}-${n}`)},q1=e=>{Lt(e,"Greater",{scalar:(t,n)=>`u32(${t}>${n})`,vector:(t,n)=>`vec4(${t}>${n})`},void 0,void 0,9)},G1=e=>{Lt(e,"Less",{scalar:(t,n)=>`u32(${t}<${n})`,vector:(t,n)=>`vec4(${t}<${n})`},void 0,void 0,9)},H1=e=>{Lt(e,"GreaterOrEqual",{scalar:(t,n)=>`u32(${t}>=${n})`,vector:(t,n)=>`vec4(${t}>=${n})`},void 0,void 0,9)},W1=e=>{Lt(e,"LessOrEqual",{scalar:(t,n)=>`u32(${t}<=${n})`,vector:(t,n)=>`vec4(${t}<=${n})`},void 0,void 0,9)}}),Vg,qg,Gg,Hg,K1,X1,ik=D(()=>{"use strict";de(),pe(),He(),he(),Vg=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let n=0,i=e[n],u=i.dataType,l=i.dims.length;e.forEach((d,c)=>{if(c!==n){if(d.dataType!==u)throw new Error("input tensors should be one type");if(d.dims.length!==l)throw new Error("input tensors should have the same shape");d.dims.forEach((s,r)=>{if(r!==t&&s!==i.dims[r])throw new Error("non concat dimensions must match")})}})},qg=(e,t)=>` + `)},K1=e=>{Lt(e,"Sub",(t,n)=>`${t}-${n}`)},X1=e=>{Lt(e,"Greater",{scalar:(t,n)=>`u32(${t}>${n})`,vector:(t,n)=>`vec4(${t}>${n})`},void 0,void 0,9)},Z1=e=>{Lt(e,"Less",{scalar:(t,n)=>`u32(${t}<${n})`,vector:(t,n)=>`vec4(${t}<${n})`},void 0,void 0,9)},Y1=e=>{Lt(e,"GreaterOrEqual",{scalar:(t,n)=>`u32(${t}>=${n})`,vector:(t,n)=>`vec4(${t}>=${n})`},void 0,void 0,9)},J1=e=>{Lt(e,"LessOrEqual",{scalar:(t,n)=>`u32(${t}<=${n})`,vector:(t,n)=>`vec4(${t}<=${n})`},void 0,void 0,9)}}),Kg,Xg,Zg,Yg,Q1,e2,ck=D(()=>{"use strict";de(),pe(),He(),he(),Kg=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");let n=0,i=e[n],u=i.dataType,l=i.dims.length;e.forEach((d,c)=>{if(c!==n){if(d.dataType!==u)throw new Error("input tensors should be one type");if(d.dims.length!==l)throw new Error("input tensors should have the same shape");d.dims.forEach((s,r)=>{if(r!==t&&s!==i.dims[r])throw new Error("non concat dimensions must match")})}})},Xg=(e,t)=>` fn calculateInputIndex(index: u32) -> u32 { let sizeInConcatAxis = array(${t}); for (var i: u32 = 0u; i < ${e}; i += 1u ) { @@ -2341,12 +2341,12 @@ fn quick_gelu_impl(x: vec4<${e}>) -> vec4<${e}> { } } return ${e}u; - }`,Gg=(e,t)=>{let n=e.length,i=[];for(let u=0;u{let u=F.size(n),l=new Array(e.length),d=new Array(e.length),c=0,s=[],r=[],o=[{type:12,data:u}];for(let g=0;g`uniforms.sizeInConcatAxis${g}`).join(","),m=g=>` + }`,Zg=(e,t)=>{let n=e.length,i=[];for(let u=0;u{let u=F.size(n),l=new Array(e.length),d=new Array(e.length),c=0,s=[],r=[],o=[{type:12,data:u}];for(let g=0;g`uniforms.sizeInConcatAxis${g}`).join(","),m=g=>` ${(()=>{g.registerUniform("outputSize","u32");for(let _=0;_) -> vec4<${e}> { ${p} -= sizeInConcatAxis[inputIndex - 1u]; } - ${Gg(d,a)} - }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:s},getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:o}),getShaderSource:m}},K1=(e,t)=>{let n=e.inputs,i=n[0].dims,u=F.normalizeAxis(t.axis,i.length);Vg(n,u);let l=i.slice();l[u]=n.reduce((c,s)=>c+(s.dims.length>u?s.dims[u]:0),0);let d=n.filter(c=>F.size(c.dims)>0);e.compute(Hg(d,u,l,n[0].dataType),{inputs:d})},X1=e=>ke({axis:e.axis})}),gn,bn,yn,md,xn=D(()=>{"use strict";de(),pe(),gn=(e,t,n="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); + ${Zg(d,a)} + }`;return{name:"Concat",shaderCache:{hint:`${t}`,inputDependencies:s},getRunData:()=>({outputs:[{dims:n,dataType:i}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:o}),getShaderSource:m}},Q1=(e,t)=>{let n=e.inputs,i=n[0].dims,u=F.normalizeAxis(t.axis,i.length);Kg(n,u);let l=i.slice();l[u]=n.reduce((c,s)=>c+(s.dims.length>u?s.dims[u]:0),0);let d=n.filter(c=>F.size(c.dims)>0);e.compute(Yg(d,u,l,n[0].dataType),{inputs:d})},e2=e=>ke({axis:e.axis})}),gn,bn,yn,yd,xn=D(()=>{"use strict";de(),pe(),gn=(e,t,n="f32")=>{switch(e.activation){case"Relu":return`value = max(value, ${t}(0.0));`;case"Sigmoid":return`value = (${t}(1.0) / (${t}(1.0) + exp(-value)));`;case"Clip":return`value = clamp(value, ${t}(${n}(uniforms.clip_min)), ${t}(${n}(uniforms.clip_max)));`;case"HardSigmoid":return`value = max(${t}(0.0), min(${t}(1.0), ${n}(uniforms.alpha) * value + ${n}(uniforms.beta)));`;case"LeakyRelu":return`value = select(${n}(uniforms.alpha) * value, value, value >= ${t}(0.0));`;case"Tanh":return`let e2x = exp(-2.0 * abs(value)); value = sign(value) * (1.0 - e2x) / (1.0 + e2x); - `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},bn=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},yn=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},md=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[n,i]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:i}}else if(t==="Clip"){let[n,i]=e?.activation_params||[_x,vx];return{activation:t,clipMax:i,clipMin:n}}else if(t==="LeakyRelu"){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}}),at,Z1,gd=D(()=>{"use strict";at=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},Z1=e=>` + `;case"":return"";default:throw new Error(`Unsupported activation ${e.activation}`)}},bn=(e,t)=>{e.activation==="Clip"?t.push({type:1,data:e.clipMax},{type:1,data:e.clipMin}):e.activation==="HardSigmoid"?t.push({type:1,data:e.alpha},{type:1,data:e.beta}):e.activation==="LeakyRelu"&&t.push({type:1,data:e.alpha})},yn=(e,t)=>{e.activation==="Clip"?t.push({name:"clip_max",type:"f32"},{name:"clip_min",type:"f32"}):e.activation==="HardSigmoid"?t.push({name:"alpha",type:"f32"},{name:"beta",type:"f32"}):e.activation==="LeakyRelu"&&t.push({name:"alpha",type:"f32"})},yd=e=>{let t=e?.activation||"";if(t==="HardSigmoid"){let[n,i]=e?.activation_params||[.2,.5];return{activation:t,alpha:n,beta:i}}else if(t==="Clip"){let[n,i]=e?.activation_params||[Sx,Ix];return{activation:t,clipMax:i,clipMin:n}}else if(t==="LeakyRelu"){let[n]=e?.activation_params||[.01];return{activation:t,alpha:n}}return{activation:t}}}),at,t2,wd=D(()=>{"use strict";at=(e,t)=>{switch(e){case 1:return t;case 2:return`vec2<${t}>`;case 3:return`vec3<${t}>`;case 4:return`vec4<${t}>`;default:throw new Error(`${e}-component is not supported.`)}},t2=e=>` ${e?"value = value + getBiasByOutputCoords(coords);":""} - `}),Y1,ok=D(()=>{"use strict";Y1=e=>` + `}),r2,pk=D(()=>{"use strict";r2=e=>` fn getIndexFromCoords4D(coords : vec4, shape : vec4) -> i32 { return dot(coords, vec4( shape.y * shape.z * shape.w, shape.z * shape.w, shape.w, 1)); @@ -2373,14 +2373,14 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { return dot(coords, vec4( i32(${e}.x), i32(${e}.y), i32(${e}.z), 1)); } -`}),Pi,bd,yd=D(()=>{"use strict";de(),pe(),he(),xn(),Pi=(e,t,n,i,u)=>{let l=i-n;return` +`}),Ri,_d,vd=D(()=>{"use strict";de(),pe(),he(),xn(),Ri=(e,t,n,i,u)=>{let l=i-n;return` ${Array.from({length:n}).map((d,c)=>` if (${se(t.shape,c,t.rank)} != 1) { ${t.indicesSet(e,c,se(u,c+l,i))} } else { ${t.indicesSet(e,c,0)} }`).join("")} -`},bd=(e,t,n,i,u=!1,l)=>{let d=e[0].dims,c=e[1].dims,s=d[d.length-2],r=c[c.length-1],o=d[d.length-1],a=Ge(r),p=Ge(o),h=Ge(s),m=F.size(n)/a/h,g=e.length>2,_=i?i.slice(0,-2):n.slice(0,-2),w=[F.size(_),s,r],y=[{type:12,data:m},{type:12,data:s},{type:12,data:r},{type:12,data:o}];bn(t,y),y.push(...ue(_,d,c)),g&&y.push(...ue(e[2].dims)),y.push(...ue(w));let T=S=>{let O=cd("batch_dims",e[0].dataType,_.length),A=j("a",e[0].dataType,d.length,p),P=j("b",e[1].dataType,c.length,a),I=oe("output",e[0].dataType,w.length,a),z=nt(I.type.tensor),G=gn(t,I.type.value,z),J=[A,P],q="";if(g){let v=u?a:1;J.push(j("bias",e[2].dataType,e[2].dims.length,v)),q=`${u?`value += bias[col / ${v}];`:`value += ${I.type.value}(bias[row + i]);`}`}let C=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];yn(t,C);let ee=()=>{let v=`var a_data: ${A.type.value};`;for(let R=0;R{let d=e[0].dims,c=e[1].dims,s=d[d.length-2],r=c[c.length-1],o=d[d.length-1],a=qe(r),p=qe(o),h=qe(s),m=F.size(n)/a/h,g=e.length>2,_=i?i.slice(0,-2):n.slice(0,-2),w=[F.size(_),s,r],y=[{type:12,data:m},{type:12,data:s},{type:12,data:r},{type:12,data:o}];bn(t,y),y.push(...ue(_,d,c)),g&&y.push(...ue(e[2].dims)),y.push(...ue(w));let T=S=>{let O=fd("batch_dims",e[0].dataType,_.length),A=j("a",e[0].dataType,d.length,p),P=j("b",e[1].dataType,c.length,a),I=oe("output",e[0].dataType,w.length,a),z=nt(I.type.tensor),q=gn(t,I.type.value,z),J=[A,P],G="";if(g){let v=u?a:1;J.push(j("bias",e[2].dataType,e[2].dims.length,v)),G=`${u?`value += bias[col / ${v}];`:`value += ${I.type.value}(bias[row + i]);`}`}let C=[{name:"output_size",type:"u32"},{name:"M",type:"u32"},{name:"N",type:"u32"},{name:"K",type:"u32"}];yn(t,C);let ee=()=>{let v=`var a_data: ${A.type.value};`;for(let R=0;R) -> i32 { ${n.length===2?"":`let batch_indices = ${O.offsetToIndices("batch")};`} var a_indices: ${A.type.indices}; - ${Pi("a_indices",A,A.rank-2,O.rank,"batch_indices")} + ${Ri("a_indices",A,A.rank-2,O.rank,"batch_indices")} ${A.indicesSet("a_indices",A.rank-2,0)} ${A.indicesSet("a_indices",A.rank-1,0)} let a_offset = ${A.indicesToOffset("a_indices")}; var b_indices: ${P.type.indices}; - ${Pi("b_indices",P,P.rank-2,O.rank,"batch_indices")} + ${Ri("b_indices",P,P.rank-2,O.rank,"batch_indices")} ${P.indicesSet("b_indices",P.rank-2,0)} ${P.indicesSet("b_indices",P.rank-1,0)} let b_offset = ${P.indicesToOffset("b_indices")}; @@ -2412,14 +2412,14 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { } for (var i = 0u; i < ${h}u; i++) { var value = values[i]; - ${q} ${G} + ${q} let cur_indices = ${I.type.indices}(batch, row + i, col); let offset = ${I.indicesToOffset("cur_indices")}; ${I.setByOffset(`offset / ${a}`,"value")}; } } - `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${a};${p};${h};${u}`,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:T}}}),Wg,Kg,zl,ou,Xg,Bl,Zg,Xo,wd=D(()=>{"use strict";de(),pe(),he(),xn(),yd(),gd(),Wg=(e,t)=>e?` + `};return{name:"MatMulNaive",shaderCache:{hint:`${t.activation};${a};${p};${h};${u}`,inputDependencies:g?["rank","rank","rank"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(m/64)},programUniforms:y}),getShaderSource:T}}}),Jg,Qg,Ll,uu,eb,jl,tb,Yo,xd=D(()=>{"use strict";de(),pe(),he(),xn(),vd(),wd(),Jg=(e,t)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart / innerElementSize + inputCol${t?", batchIndices":""}); @@ -2427,7 +2427,7 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRow + innerRow, kStart / innerElementSize + inputCol${t?", batchIndices":""}); - `,Kg=(e,t)=>e?` + `,Qg=(e,t)=>e?` let ACached0 = mm_Asub[k * innerElementSize][localRow]; let ACached1 = mm_Asub[k * innerElementSize + 1][localRow]; let ACached2 = mm_Asub[k * innerElementSize + 2][localRow]; @@ -2444,7 +2444,7 @@ fn getOutputIndexFromCoords(coords : vec4) -> i32 { acc[i] = BCached1 * ACached.y + acc[i]; acc[i] = BCached2 * ACached.z + acc[i]; ${t===3?"":"acc[i] = BCached3 * ACached.w + acc[i];"} - }`,zl=(e,t,n="f32",i,u=!1,l=32,d=!1,c=32)=>{let s=t[1]*e[1],r=t[0]*e[0],o=u?s:l,a=u?l:s,p=o/t[0],h=l/t[1];if(!((u&&p===4&&e[1]===4||!u&&(p===3||p===4))&&o%t[0]===0&&l%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${u} is true, innerElementSize ${p} and workPerThread[1] ${e[1]} must be 4. + }`,Ll=(e,t,n="f32",i,u=!1,l=32,d=!1,c=32)=>{let s=t[1]*e[1],r=t[0]*e[0],o=u?s:l,a=u?l:s,p=o/t[0],h=l/t[1];if(!((u&&p===4&&e[1]===4||!u&&(p===3||p===4))&&o%t[0]===0&&l%t[1]===0&&e[0]===4))throw new Error(`If transposeA ${u} is true, innerElementSize ${p} and workPerThread[1] ${e[1]} must be 4. Otherwise, innerElementSize ${p} must be 3 or 4. tileAWidth ${o} must be divisible by workgroupSize[0]${t[0]}. tileInner ${l} must be divisible by workgroupSize[1] ${t[1]}. colPerThread ${e[0]} must be 4.`);return` var mm_Asub: array, ${o/p}>, ${a}>; @@ -2481,7 +2481,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { let inputRow = tileRow + innerRow; let inputCol = tileCol; - ${Wg(u,i)} + ${Jg(u,i)} } // Load one tile of B into local memory. @@ -2500,7 +2500,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, let BCached2 = mm_Bsub[k * innerElementSize + 2][tileCol]; ${p===3?"":"let BCached3 = mm_Bsub[k * innerElementSize + 3][tileCol];"} - ${Kg(u,p)} + ${Qg(u,p)} } workgroupBarrier(); @@ -2509,7 +2509,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { mm_write(batch, globalRow + innerRow, globalCol, acc[innerRow]); } -}`},ou=(e,t)=>e?` +}`},uu=(e,t)=>e?` mm_Asub[inputRow][inputCol] = mm_readA(batch, kStart + inputRow, globalRowStart + inputCol${t?", batchIndices":""}); @@ -2517,7 +2517,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, mm_Asub[inputRow][inputCol] = mm_readA(batch, globalRowStart + inputRow, kStart + inputCol${t?", batchIndices":""}); - `,Xg=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",Bl=(e,t,n="f32",i,u=!1,l=32,d=!1,c=32,s=!1)=>{let r=e[1]*t[1],o=e[0]*t[0],a=u?r:l,p=u?l:r;if(!(p%t[1]===0&&a%t[0]===0&&l%t[1]===0))throw new Error(`tileAHight ${p} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${a} must be divisible by workgroupSize[0]${t[0]}, tileInner ${l} must be divisible by workgroupSize[1]${t[1]}`);let h=p/t[1],m=a/t[0],g=l/t[1],_=s?` + `,eb=e=>e?"let ACached = mm_Asub[k][tileRow + innerRow];":"let ACached = mm_Asub[tileRow + innerRow][k];",jl=(e,t,n="f32",i,u=!1,l=32,d=!1,c=32,s=!1)=>{let r=e[1]*t[1],o=e[0]*t[0],a=u?r:l,p=u?l:r;if(!(p%t[1]===0&&a%t[0]===0&&l%t[1]===0))throw new Error(`tileAHight ${p} must be divisible by workgroupSize[1]${t[1]}, tileAWidth ${a} must be divisible by workgroupSize[0]${t[0]}, tileInner ${l} must be divisible by workgroupSize[1]${t[1]}`);let h=p/t[1],m=a/t[0],g=l/t[1],_=s?` let localRow = i32(localId.y); let localCol = i32(localId.x); let globalRowStart = i32(workgroupId.y) * ${r}; @@ -2528,7 +2528,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, // Load one tile of A into local memory. for (var inputRow = localRow; inputRow < ${p}; inputRow = inputRow + ${t[1]}) { for (var inputCol = localCol; inputCol < ${a}; inputCol = inputCol + ${t[0]}) { - ${ou(u,i)} + ${uu(u,i)} } } // Load one tile of B into local memory. @@ -2583,7 +2583,7 @@ for (var t = 0; t < num_tiles; t = t + 1) { for (var innerCol = 0; innerCol < ${m}; innerCol = innerCol + 1) { let inputRow = tileRowA + innerRow; let inputCol = tileColA + innerCol; - ${ou(u,i)} + ${uu(u,i)} } } @@ -2608,7 +2608,7 @@ for (var t = 0; t < num_tiles; t = t + 1) { } for (var innerRow = 0; innerRow < rowPerThread; innerRow = innerRow + 1) { - ${Xg(u)} + ${eb(u)} for (var innerCol = 0; innerCol < colPerThread; innerCol = innerCol + 1) { acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol]; } @@ -2643,14 +2643,14 @@ fn main(@builtin(local_invocation_id) localId : vec3, var acc : array, rowPerThread>; ${_} } -`},Zg=(e,t,n,i,u=!1)=>{let[l,d,c,s]=i,r=nt(i[0].type.tensor);return` +`},tb=(e,t,n,i,u=!1)=>{let[l,d,c,s]=i,r=nt(i[0].type.tensor);return` fn mm_readA(batch: i32, row: i32, colIn: i32, batchIndices: ${l.type.indices}) -> ${at(e,r)} { var value = ${at(e,r)}(0.0); let col = colIn * ${e}; if(row < uniforms.dim_a_outer && col < uniforms.dim_inner) { var aIndices: ${d.type.indices}; - ${Pi("aIndices",d,d.rank-2,l.rank,"batchIndices")} + ${Ri("aIndices",d,d.rank-2,l.rank,"batchIndices")} ${d.indicesSet("aIndices",d.rank-2,"u32(row)")} ${d.indicesSet("aIndices",d.rank-1,"u32(colIn)")} value = ${d.getByIndices("aIndices")}; @@ -2664,7 +2664,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, if(row < uniforms.dim_inner && col < uniforms.dim_b_outer) { var bIndices: ${c.type.indices}; - ${Pi("bIndices",c,c.rank-2,l.rank,"batchIndices")} + ${Ri("bIndices",c,c.rank-2,l.rank,"batchIndices")} ${c.indicesSet("bIndices",c.rank-2,"u32(row)")} ${c.indicesSet("bIndices",c.rank-1,"u32(colIn)")} value = ${c.getByIndices("bIndices")}; @@ -2682,11 +2682,11 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${s.setByIndices("vec3(coords)","value")} } } - `},Xo=(e,t,n,i,u=!1,l)=>{let d=e[0].dims,c=e[1].dims,s=d.slice(0,-2),r=c.slice(0,-2),o=i?i.slice(0,-2):n.slice(0,-2),a=F.size(o),p=d[d.length-2],h=d[d.length-1],m=c[c.length-1],g=h%4===0&&m%4===0,_=p<=8?[4,1,1]:[4,4,1],w=[8,8,1],y=[Math.ceil(m/w[0]/_[0]),Math.ceil(p/w[1]/_[1]),Math.ceil(a/w[2]/_[2])],T=g?4:1,S=[...s,p,h/T],O=S.length,A=[...r,h,m/T],P=A.length,I=[a,p,m/T],z=[{type:6,data:p},{type:6,data:m},{type:6,data:h}];bn(t,z),z.push(...ue(o,S,A));let G=["rank","rank"],J=e.length>2;J&&(z.push(...ue(e[2].dims)),G.push("rank")),z.push(...ue(I));let q=C=>{let ee=o.length,v=cd("batchDims",e[0].dataType,ee,1),R=nt(e[0].dataType),H=j("a",e[0].dataType,O,T),L=j("b",e[1].dataType,P,T),V=oe("result",e[0].dataType,I.length,T),K=[H,L];if(J){let X=u?T:1;K.push(j("bias",e[2].dataType,e[2].dims.length,X))}let B=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];yn(t,B);let te=nt(V.type.tensor),Y=gn(t,V.type.value,te),N=Zg(T,J,Y,[v,H,L,V],u);return` + `},Yo=(e,t,n,i,u=!1,l)=>{let d=e[0].dims,c=e[1].dims,s=d.slice(0,-2),r=c.slice(0,-2),o=i?i.slice(0,-2):n.slice(0,-2),a=F.size(o),p=d[d.length-2],h=d[d.length-1],m=c[c.length-1],g=h%4===0&&m%4===0,_=p<=8?[4,1,1]:[4,4,1],w=[8,8,1],y=[Math.ceil(m/w[0]/_[0]),Math.ceil(p/w[1]/_[1]),Math.ceil(a/w[2]/_[2])],T=g?4:1,S=[...s,p,h/T],O=S.length,A=[...r,h,m/T],P=A.length,I=[a,p,m/T],z=[{type:6,data:p},{type:6,data:m},{type:6,data:h}];bn(t,z),z.push(...ue(o,S,A));let q=["rank","rank"],J=e.length>2;J&&(z.push(...ue(e[2].dims)),q.push("rank")),z.push(...ue(I));let G=C=>{let ee=o.length,v=fd("batchDims",e[0].dataType,ee,1),R=nt(e[0].dataType),H=j("a",e[0].dataType,O,T),L=j("b",e[1].dataType,P,T),V=oe("result",e[0].dataType,I.length,T),K=[H,L];if(J){let X=u?T:1;K.push(j("bias",e[2].dataType,e[2].dims.length,X))}let B=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"}];yn(t,B);let te=nt(V.type.tensor),Y=gn(t,V.type.value,te),N=tb(T,J,Y,[v,H,L,V],u);return` ${C.registerUniforms(B).registerInternalVariables(v).declareVariables(...K,V)} ${N} - ${g?zl(_,w,R,v):Bl(_,w,R,v)} - `};return{name:"MatMul",shaderCache:{hint:`${_};${t.activation};${g};${u}`,inputDependencies:G},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:z}),getShaderSource:q}}}),Yg,J1,sk=D(()=>{"use strict";de(),ur(),he(),xn(),gd(),ok(),wd(),Yg=(e,t,n,i,u=!1,l,d=4,c=4,s=4,r="f32")=>{let o=z=>{switch(z){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${r}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${z} is not supported.`)}},a=z=>{switch(z){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${z} is not supported.`)}},p=e?` + ${g?Ll(_,w,R,v):jl(_,w,R,v)} + `};return{name:"MatMul",shaderCache:{hint:`${_};${t.activation};${g};${u}`,inputDependencies:q},getRunData:()=>({outputs:[{dims:l?l(n):n,dataType:e[0].dataType}],dispatchGroup:{x:y[0],y:y[1],z:y[2]},programUniforms:z}),getShaderSource:G}}}),rb,n2,hk=D(()=>{"use strict";de(),ur(),he(),xn(),wd(),pk(),xd(),rb=(e,t,n,i,u=!1,l,d=4,c=4,s=4,r="f32")=>{let o=z=>{switch(z){case 1:return"resData = x[xIndex];";case 3:return`resData = vec3<${r}>(x[xIndex], x[xIndex + 1], x[xIndex + 2]);`;case 4:return"resData = x[xIndex / 4];";default:throw new Error(`innerElementSize ${z} is not supported.`)}},a=z=>{switch(z){case 1:return"return w[row * i32(uniforms.w_shape[3]) + colIn];";case 4:return"return w[row * i32(uniforms.w_shape[3]) / 4 + colIn];";default:throw new Error(`innerElementSize ${z} is not supported.`)}},p=e?` let coord = vec4(batch, xRow, xCol, xCh); `:` let coord = vec4(batch, xCh, xRow, xCol); @@ -2761,11 +2761,11 @@ fn main(@builtin(local_invocation_id) localId : vec3, var value = valueIn; let outWidth = ${e?"i32(uniforms.result_shape[2])":"i32(uniforms.result_shape[3])"}; ${h} - ${Z1(u)} + ${t2(u)} ${I} setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], value); } - }`},J1=(e,t,n,i,u,l,d,c,s)=>{let r=t.format==="NHWC",o=r?e[0].dims[3]:e[0].dims[1],a=n[0],p=r?n[2]:n[3],h=r?n[1]:n[2],m=r?n[3]:n[1],g=r&&(o%4===0||o%3===0)&&m%4===0,_=r?m:p*h,w=r?p*h:m,y=[8,8,1],T=i<=8?[4,1,1]:[4,4,1],S=[Math.ceil(_/y[0]/T[0]),Math.ceil(w/y[1]/T[1]),Math.ceil(a/y[2]/T[2])];Ie("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${S}`);let O=g?r&&o%4!==0?3:4:1,A=y[1]*T[1],P=y[0]*T[0],I=Math.max(y[0]*O,y[1]),z=i%A===0,G=u%P===0,J=l%I===0,q=g?[O,4,4]:[1,1,1],C=[{type:6,data:i},{type:6,data:u},{type:6,data:l},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];bn(t,C),C.push(...ue(e[0].dims,e[1].dims));let ee=["rank","rank"];d&&(C.push(...ue(e[2].dims)),ee.push("rank")),C.push(...ue(n));let v=R=>{let H=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];yn(t,H);let L=g?4:1,V=nt(e[0].dataType),K=` + }`},n2=(e,t,n,i,u,l,d,c,s)=>{let r=t.format==="NHWC",o=r?e[0].dims[3]:e[0].dims[1],a=n[0],p=r?n[2]:n[3],h=r?n[1]:n[2],m=r?n[3]:n[1],g=r&&(o%4===0||o%3===0)&&m%4===0,_=r?m:p*h,w=r?p*h:m,y=[8,8,1],T=i<=8?[4,1,1]:[4,4,1],S=[Math.ceil(_/y[0]/T[0]),Math.ceil(w/y[1]/T[1]),Math.ceil(a/y[2]/T[2])];Ie("verbose",()=>`[conv2d_mm_webgpu] dispatch = ${S}`);let O=g?r&&o%4!==0?3:4:1,A=y[1]*T[1],P=y[0]*T[0],I=Math.max(y[0]*O,y[1]),z=i%A===0,q=u%P===0,J=l%I===0,G=g?[O,4,4]:[1,1,1],C=[{type:6,data:i},{type:6,data:u},{type:6,data:l},{type:6,data:[t.pads[0],t.pads[1]]},{type:6,data:t.strides},{type:6,data:t.dilations}];bn(t,C),C.push(...ue(e[0].dims,e[1].dims));let ee=["rank","rank"];d&&(C.push(...ue(e[2].dims)),ee.push("rank")),C.push(...ue(n));let v=R=>{let H=[{name:"dim_a_outer",type:"i32"},{name:"dim_b_outer",type:"i32"},{name:"dim_inner",type:"i32"},{name:"pad",type:"i32",length:2},{name:"stride",type:"i32",length:2},{name:"dilation",type:"i32",length:2}];yn(t,H);let L=g?4:1,V=nt(e[0].dataType),K=` fn setOutputAtIndex(flatIndex : i32, value : ${g?`vec4<${V}>`:V}) { result[flatIndex] = ${g?`vec4<${V}>`:V}(value); } @@ -2776,18 +2776,18 @@ fn main(@builtin(local_invocation_id) localId : vec3, fn getBiasByOutputCoords(coords : vec4) -> ${g?`vec4<${V}>`:V} { return bias[coords.${r?"w":"y"}${g?"/ 4":""}]; }`}return` - ${Y1("uniforms.result_strides")} + ${r2("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 }; ${R.registerUniforms(H).declareVariables(...Y,N)} ${K} - ${Yg(r,z,G,J,d,t,q[0],q[1],q[2],V)} - ${g?zl(T,y,V,void 0,!r,I):Bl(T,y,V,void 0,!r,I,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${O};${g};${z};${G};${J};${A};${P};${I}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:s?s(n):n,dataType:e[0].dataType}],dispatchGroup:{x:S[0],y:S[1],z:S[2]},programUniforms:C}),getShaderSource:v}}}),Jg,su,pi,Qg,au,eb,Q1,e2,ak=D(()=>{"use strict";de(),ur(),pe(),he(),xn(),gd(),Jg=e=>{let t=1;for(let n=0;ntypeof e=="number"?[e,e,e]:e,pi=(e,t)=>t<=1?e:e+(e-1)*(t-1),Qg=(e,t,n,i=1)=>{let u=pi(t,i);return Math.floor((e[0]*(n-1)-n+u)/2)},au=(e,t,n,i,u)=>{u==null&&(u=Qg(e,t[0],i[0]));let l=[0,0,0,n];for(let d=0;d<3;d++)e[d]+2*u>=t[d]&&(l[d]=Math.trunc((e[d]-t[d]+2*u)/i[d]+1));return l},eb=(e,t,n,i,u,l,d,c,s,r)=>{let o,a,p,h;if(e==="VALID"&&(e=0),typeof e=="number"){o={top:e,bottom:e,left:e,right:e,front:e,back:e};let m=au([t,n,i,1],[c,s,r],1,[u,l,d],e);a=m[0],p=m[1],h=m[2]}else if(Array.isArray(e)){if(!e.every((g,_,w)=>g===w[0]))throw Error(`Unsupported padding parameter: ${e}`);o={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let m=au([t,n,i,1],[c,s,r],1,[u,l,d],e[0]);a=m[0],p=m[1],h=m[2]}else if(e==="SAME_UPPER"){a=Math.ceil(t/u),p=Math.ceil(n/l),h=Math.ceil(i/d);let m=(a-1)*u+c-t,g=(p-1)*l+s-n,_=(h-1)*d+r-i,w=Math.floor(m/2),y=m-w,T=Math.floor(g/2),S=g-T,O=Math.floor(_/2),A=_-O;o={top:T,bottom:S,left:O,right:A,front:w,back:y}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:o,outDepth:a,outHeight:p,outWidth:h}},Q1=(e,t,n,i,u,l=!1,d="channelsLast")=>{let c,s,r,o,a;if(d==="channelsLast")[c,s,r,o,a]=e;else if(d==="channelsFirst")[c,a,s,r,o]=e;else throw new Error(`Unknown dataFormat ${d}`);let[p,,h,m,g]=t,[_,w,y]=su(n),[T,S,O]=su(i),A=pi(h,T),P=pi(m,S),I=pi(g,O),{padInfo:z,outDepth:G,outHeight:J,outWidth:q}=eb(u,s,r,o,_,w,y,A,P,I),C=l?p*a:p,ee=[0,0,0,0,0];return d==="channelsFirst"?ee=[c,C,G,J,q]:d==="channelsLast"&&(ee=[c,G,J,q,C]),{batchSize:c,dataFormat:d,inDepth:s,inHeight:r,inWidth:o,inChannels:a,outDepth:G,outHeight:J,outWidth:q,outChannels:C,padInfo:z,strideDepth:_,strideHeight:w,strideWidth:y,filterDepth:h,filterHeight:m,filterWidth:g,effectiveFilterDepth:A,effectiveFilterHeight:P,effectiveFilterWidth:I,dilationDepth:T,dilationHeight:S,dilationWidth:O,inShape:e,outShape:ee,filterShape:t}},e2=(e,t,n,i,u,l)=>{let d=l==="channelsLast",c=d?e[0].dims[3]:e[0].dims[1],s=!1,r=[64,1,1],o={x:n.map((y,T)=>T)},a=[Math.ceil(Jg(o.x.map(y=>n[y]))/r[0]),1,1];Ie("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${a}`);let p=s?d&&c%4!==0?3:4:1,h=F.size(n),m=[{type:12,data:h},{type:12,data:i},{type:12,data:u},{type:12,data:t.strides},{type:12,data:t.dilations}];bn(t,m),m.push(...ue(e[0].dims,e[1].dims));let g=["rank","rank"],_=e.length===3;_&&(m.push(...ue(e[2].dims)),g.push("rank")),m.push(...ue(n));let w=y=>{let T=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:i.length},{name:"pads",type:"u32",length:u.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];yn(t,T);let S=s?4:1,O=nt(e[0].dataType),A=j("x",e[0].dataType,e[0].dims.length,p===3?1:p),P=j("W",e[1].dataType,e[1].dims.length,S),I=[A,P],z=oe("result",e[0].dataType,n.length,S),G="";if(_){let C=j("bias",e[2].dataType,e[2].dims.length,S);I.push(C),G+=` + ${rb(r,z,q,J,d,t,G[0],G[1],G[2],V)} + ${g?Ll(T,y,V,void 0,!r,I):jl(T,y,V,void 0,!r,I,!1,void 0,c)}`};return{name:"Conv2DMatMul",shaderCache:{hint:`${t.cacheKey};${O};${g};${z};${q};${J};${A};${P};${I}`,inputDependencies:ee},getRunData:()=>({outputs:[{dims:s?s(n):n,dataType:e[0].dataType}],dispatchGroup:{x:S[0],y:S[1],z:S[2]},programUniforms:C}),getShaderSource:v}}}),nb,lu,fi,ib,du,ob,i2,o2,fk=D(()=>{"use strict";de(),ur(),pe(),he(),xn(),wd(),nb=e=>{let t=1;for(let n=0;ntypeof e=="number"?[e,e,e]:e,fi=(e,t)=>t<=1?e:e+(e-1)*(t-1),ib=(e,t,n,i=1)=>{let u=fi(t,i);return Math.floor((e[0]*(n-1)-n+u)/2)},du=(e,t,n,i,u)=>{u==null&&(u=ib(e,t[0],i[0]));let l=[0,0,0,n];for(let d=0;d<3;d++)e[d]+2*u>=t[d]&&(l[d]=Math.trunc((e[d]-t[d]+2*u)/i[d]+1));return l},ob=(e,t,n,i,u,l,d,c,s,r)=>{let o,a,p,h;if(e==="VALID"&&(e=0),typeof e=="number"){o={top:e,bottom:e,left:e,right:e,front:e,back:e};let m=du([t,n,i,1],[c,s,r],1,[u,l,d],e);a=m[0],p=m[1],h=m[2]}else if(Array.isArray(e)){if(!e.every((g,_,w)=>g===w[0]))throw Error(`Unsupported padding parameter: ${e}`);o={top:e[0],bottom:e[1],left:e[2],right:e[3],front:e[4],back:e[5]};let m=du([t,n,i,1],[c,s,r],1,[u,l,d],e[0]);a=m[0],p=m[1],h=m[2]}else if(e==="SAME_UPPER"){a=Math.ceil(t/u),p=Math.ceil(n/l),h=Math.ceil(i/d);let m=(a-1)*u+c-t,g=(p-1)*l+s-n,_=(h-1)*d+r-i,w=Math.floor(m/2),y=m-w,T=Math.floor(g/2),S=g-T,O=Math.floor(_/2),A=_-O;o={top:T,bottom:S,left:O,right:A,front:w,back:y}}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:o,outDepth:a,outHeight:p,outWidth:h}},i2=(e,t,n,i,u,l=!1,d="channelsLast")=>{let c,s,r,o,a;if(d==="channelsLast")[c,s,r,o,a]=e;else if(d==="channelsFirst")[c,a,s,r,o]=e;else throw new Error(`Unknown dataFormat ${d}`);let[p,,h,m,g]=t,[_,w,y]=lu(n),[T,S,O]=lu(i),A=fi(h,T),P=fi(m,S),I=fi(g,O),{padInfo:z,outDepth:q,outHeight:J,outWidth:G}=ob(u,s,r,o,_,w,y,A,P,I),C=l?p*a:p,ee=[0,0,0,0,0];return d==="channelsFirst"?ee=[c,C,q,J,G]:d==="channelsLast"&&(ee=[c,q,J,G,C]),{batchSize:c,dataFormat:d,inDepth:s,inHeight:r,inWidth:o,inChannels:a,outDepth:q,outHeight:J,outWidth:G,outChannels:C,padInfo:z,strideDepth:_,strideHeight:w,strideWidth:y,filterDepth:h,filterHeight:m,filterWidth:g,effectiveFilterDepth:A,effectiveFilterHeight:P,effectiveFilterWidth:I,dilationDepth:T,dilationHeight:S,dilationWidth:O,inShape:e,outShape:ee,filterShape:t}},o2=(e,t,n,i,u,l)=>{let d=l==="channelsLast",c=d?e[0].dims[3]:e[0].dims[1],s=!1,r=[64,1,1],o={x:n.map((y,T)=>T)},a=[Math.ceil(nb(o.x.map(y=>n[y]))/r[0]),1,1];Ie("verbose",()=>`[conv3d_naive_webgpu] dispatch = ${a}`);let p=s?d&&c%4!==0?3:4:1,h=F.size(n),m=[{type:12,data:h},{type:12,data:i},{type:12,data:u},{type:12,data:t.strides},{type:12,data:t.dilations}];bn(t,m),m.push(...ue(e[0].dims,e[1].dims));let g=["rank","rank"],_=e.length===3;_&&(m.push(...ue(e[2].dims)),g.push("rank")),m.push(...ue(n));let w=y=>{let T=[{name:"output_size",type:"u32"},{name:"filter_dims",type:"u32",length:i.length},{name:"pads",type:"u32",length:u.length},{name:"strides",type:"u32",length:t.strides.length},{name:"dilations",type:"u32",length:t.dilations.length}];yn(t,T);let S=s?4:1,O=nt(e[0].dataType),A=j("x",e[0].dataType,e[0].dims.length,p===3?1:p),P=j("W",e[1].dataType,e[1].dims.length,S),I=[A,P],z=oe("result",e[0].dataType,n.length,S),q="";if(_){let C=j("bias",e[2].dataType,e[2].dims.length,S);I.push(C),q+=` fn getBiasByOutputCoords(coords : array) -> ${s?`vec4<${O}>`:O} { return bias[${d?se("coords",4,5):se("coords",1,5)}${s?"/ 4":""}]; - }`}let J=at(p,O),q=gn(t,J,O);return` - ${G} + }`}let J=at(p,O),G=gn(t,J,O);return` + ${q} fn getX(d0 : u32, d1 : u32, d2 : u32, d3 : u32, d4 : u32) -> f32 { let aIndices = array(d0, d1, d2, d3, d4); return ${A.getByIndices("aIndices")}; @@ -2889,9 +2889,9 @@ fn main(@builtin(local_invocation_id) localId : vec3, } } ${_?"value = value + getBiasByOutputCoords(coords)":""}; - ${q} + ${G} result[global_idx] = f32(value); - }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${d};${p};${_}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:a[0],y:a[1],z:a[2]},programUniforms:m}),getShaderSource:w}}}),t2,r2,uk=D(()=>{"use strict";de(),pe(),he(),xn(),t2=(e,t,n,i)=>{let u=e.length>2,l=u?"value += b[output_channel];":"",d=e[0].dims,c=e[1].dims,s=t.format==="NHWC",r=s?n[3]:n[1],o=r/t.group,a=s&&o>=4?Ge(r):1,p=F.size(n)/a,h=[{type:12,data:p},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:o}];bn(t,h),h.push(...ue(d,[c[0],c[1],c[2],c[3]/a]));let m=u?["rank","rank","rank"]:["rank","rank"];h.push(...ue([n[0],n[1],n[2],n[3]/a]));let g=_=>{let w=oe("output",e[0].dataType,n.length,a),y=nt(w.type.tensor),T=gn(t,w.type.value,y),S=j("x",e[0].dataType,d.length),O=j("w",e[1].dataType,c.length,a),A=[S,O];u&&A.push(j("b",e[2].dataType,e[2].dims,a));let P=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];yn(t,P);let I=s?` + }`};return{name:"Conv3DNaive",shaderCache:{hint:`${t.cacheKey};${d};${p};${_}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:a[0],y:a[1],z:a[2]},programUniforms:m}),getShaderSource:w}}}),s2,a2,mk=D(()=>{"use strict";de(),pe(),he(),xn(),s2=(e,t,n,i)=>{let u=e.length>2,l=u?"value += b[output_channel];":"",d=e[0].dims,c=e[1].dims,s=t.format==="NHWC",r=s?n[3]:n[1],o=r/t.group,a=s&&o>=4?qe(r):1,p=F.size(n)/a,h=[{type:12,data:p},{type:12,data:t.dilations},{type:12,data:[t.strides[0],t.strides[1]]},{type:12,data:[t.pads[0],t.pads[1]]},{type:12,data:o}];bn(t,h),h.push(...ue(d,[c[0],c[1],c[2],c[3]/a]));let m=u?["rank","rank","rank"]:["rank","rank"];h.push(...ue([n[0],n[1],n[2],n[3]/a]));let g=_=>{let w=oe("output",e[0].dataType,n.length,a),y=nt(w.type.tensor),T=gn(t,w.type.value,y),S=j("x",e[0].dataType,d.length),O=j("w",e[1].dataType,c.length,a),A=[S,O];u&&A.push(j("b",e[2].dataType,e[2].dims,a));let P=[{name:"output_size",type:"u32"},{name:"dilations",type:"u32",length:t.dilations.length},{name:"strides",type:"u32",length:2},{name:"pads",type:"u32",length:2},{name:"output_channels_per_group",type:"u32"}];yn(t,P);let I=s?` for (var wHeight: u32 = 0u; wHeight < uniforms.w_shape[0]; wHeight++) { let xHeight = xRCCorner.x + wHeight * uniforms.dilations[0]; @@ -2953,7 +2953,7 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${l} ${T} ${w.setByOffset("global_idx","value")} - }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${a}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:g}},r2=(e,t,n,i)=>{let u=e.length>2,l=Ge(n[3]),d=Ge(n[2]),c=F.size(n)/l/d,s=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/l],r=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/l],o=[n[0],n[1],n[2],n[3]/l],a=[{type:12,data:c},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];bn(t,a),a.push(...ue(s,r,o));let p=(d-1)*t.strides[1]+r[1],h=m=>{let g=oe("output",e[0].dataType,o.length,l),_=nt(g.type.tensor),w=gn(t,g.type.value,_),y=j("x",e[0].dataType,s.length,l),T=j("w",e[1].dataType,r.length,l),S=[y,T];u&&S.push(j("b",e[2].dataType,e[2].dims,l));let O=u?"value += b[output_channel];":"",A=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return yn(t,A),` + }`};return{name:"GroupedConv",shaderCache:{hint:`${t.cacheKey}_${a}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:g}},a2=(e,t,n,i)=>{let u=e.length>2,l=qe(n[3]),d=qe(n[2]),c=F.size(n)/l/d,s=[e[0].dims[0],e[0].dims[1],e[0].dims[2],e[0].dims[3]/l],r=[e[1].dims[0],e[1].dims[1],e[1].dims[2],e[1].dims[3]/l],o=[n[0],n[1],n[2],n[3]/l],a=[{type:12,data:c},{type:6,data:[t.strides[0],t.strides[1]]},{type:6,data:[t.pads[0],t.pads[1]]}];bn(t,a),a.push(...ue(s,r,o));let p=(d-1)*t.strides[1]+r[1],h=m=>{let g=oe("output",e[0].dataType,o.length,l),_=nt(g.type.tensor),w=gn(t,g.type.value,_),y=j("x",e[0].dataType,s.length,l),T=j("w",e[1].dataType,r.length,l),S=[y,T];u&&S.push(j("b",e[2].dataType,e[2].dims,l));let O=u?"value += b[output_channel];":"",A=[{name:"output_size",type:"u32"},{name:"strides",type:"i32",length:2},{name:"pads",type:"i32",length:2}];return yn(t,A),` ${m.registerUniforms(A).declareVariables(...S,g)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -2998,16 +2998,16 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${w} ${g.set("batch","row","col + i","output_channel","value")}; } - }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${l};${d};${p};${r[0]};${r[1]}`,inputDependencies:u?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:a}),getShaderSource:h}}}),tb,Ao,rb,ko,Fl,uu,nb,ib,Ll,lk=D(()=>{"use strict";pe(),sk(),ak(),wd(),uk(),xn(),yd(),Cr(),tb=(e,t,n,i,u,l)=>{let d=e[0],c=e.slice(l?1:2,l?3:4),s=c.length,r=t[0],o=t.slice(2).map((p,h)=>p+(p-1)*(n[h]-1)),a=c.map((p,h)=>p+i[h]+i[h+s]).map((p,h)=>Math.floor((p-o[h]+u[h])/u[h]));return a.splice(0,0,d),a.splice(l?3:1,0,r),a},Ao=[2,3,1,0],rb=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let n=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[1]*t.group;if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let u=e[0].dims.length-2;if(t.dilations.length!==u)throw new Error(`dilations should be ${u}D`);if(t.strides.length!==u)throw new Error(`strides should be ${u}D`);if(t.pads.length!==u*2)throw new Error(`pads should be ${u*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},ko=(e,t)=>{let n=e.kernelShape.slice();n.length{let t=md(e),n=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],u=e.dilations,l=e.group,d=e.kernel_shape,c=e.pads,s=e.strides,r=e.w_is_const();return{autoPad:i,format:n,dilations:u,group:l,kernelShape:d,pads:c,strides:s,wIsConst:r,...t,cacheKey:`${e.format};${t.activation};`}},uu=(e,t,n,i)=>{let u=n.format==="NHWC",l=tb(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,u);if(n.group!==1){let A=[t[0]];if(u){let P=e.kernelCustomData.wT??e.compute($t(t[1],Ao),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=P),A.push(P)}else A.push(t[1]);t.length===3&&A.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&u&&t[1].dims[0]===n.group&&t[1].dims[1]===1&&n.dilations[0]===1&&n.dilations[1]===1?e.compute(r2(A,n,l,i),{inputs:A}):e.compute(t2(A,n,l,i),{inputs:A});return}let d=t.length===3,c=t[0].dims[u?1:2],s=t[0].dims[u?2:3],r=t[0].dims[u?3:1],o=t[1].dims[2],a=t[1].dims[3],p=l[u?1:2],h=l[u?2:3],m=l[u?3:1],g=u&&o===c&&a===s&&n.pads[0]===0&&n.pads[1]===0;if(g||o===1&&a===1&&n.dilations[0]===1&&n.dilations[1]===1&&n.strides[0]===1&&n.strides[1]===1&&n.pads[0]===0&&n.pads[1]===0){let A=l[0],P,I,z,G=[];if(u){let C=e.kernelCustomData.wT??e.compute($t(t[1],Ao),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=C),g){let ee=c*s*r;P=t[0].reshape([1,A,ee]),I=C.reshape([1,ee,m]),z=[1,A,m]}else P=t[0].reshape([A,c*s,r]),I=C.reshape([1,r,m]),z=[A,p*h,m];G.push(P),G.push(I)}else P=t[0].reshape([A,r,c*s]),I=t[1].reshape([1,m,r]),z=[A,m,p*h],G.push(I),G.push(P);d&&G.push(t[2]);let J=z[2],q=G[0].dims[G[0].dims.length-1];J<8&&q<8?e.compute(bd(G,n,l,z,u,i),{inputs:G}):e.compute(Xo(G,n,l,z,u,i),{inputs:G});return}let _=!0,w=e.kernelCustomData.wT??e.compute($t(t[1],Ao),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let y=[t[0],w];d&&y.push(t[2]);let T=u?p*h:m,S=u?m:p*h,O=o*a*r;e.compute(J1(y,n,l,T,S,O,d,_,i),{inputs:y})},nb=(e,t)=>{let n=t.format==="NHWC",i=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&i.push(e.inputs[2]);let u=[0,t.pads[0],0,t.pads[1]],l=[1].concat(t.strides),d=[1].concat(t.dilations),c=[1].concat(t.kernelShape),s=ko({...t,pads:u,strides:l,dilations:d,kernelShape:c},i);uu(e,i,s,r=>n?[r[0],r[2],r[3]]:[r[0],r[1],r[3]])},ib=(e,t,n)=>{let i=n.format==="NHWC"?"channelsLast":"channelsFirst",u=ko(n,t),l=n.autoPad==="NOTSET"?n.pads:n.autoPad,d=Q1(t[0].dims,t[1].dims,n.strides,n.dilations,l,!1,i);e.compute(e2(t,u,d.outShape,[d.filterDepth,d.filterHeight,d.filterWidth],[d.padInfo.front,d.padInfo.top,d.padInfo.left],i))},Ll=(e,t)=>{if(rb(e.inputs,t),e.inputs[0].dims.length===3)nb(e,t);else if(e.inputs[0].dims.length===5)ib(e,e.inputs,t);else{let n=ko(t,e.inputs);uu(e,e.inputs,n)}}}),n2,dk=D(()=>{"use strict";de(),ur(),pe(),he(),n2=(e,t,n)=>{let i=e.length>2,u=t.outputShape,l=t.format==="NHWC",d=t.group,c=e[1].dims,s=c[2]/d,r=c[3],o=l?Ge(s):1,a=l&&r===1&&s>=4,p=a?Math.floor(s/4)*4:Math.floor(s/o)*o,h=s-p,m=l?Ge(r):1,g=l?r===1?o:m:1,_=F.size(u)/m,w=[Math.ceil(_/64),1,1];Ie("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let y=["rank","rank"],T=[t.strides[0],t.strides[1]],S=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],O=[t.dilations[0],t.dilations[1]],A=[S[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),S[1]+(t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1))],P=[A[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),A[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],I=[{type:12,data:_},{type:12,data:T},{type:12,data:S},{type:12,data:O},{type:12,data:A},{type:6,data:P},{type:12,data:p},{type:12,data:s},{type:12,data:r},...ue(e[0].dims,e[1].dims)];i&&(I.push(...ue(e[2].dims)),y.push("rank")),I.push(...ue(u));let z=G=>{let J=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:T.length},{name:"filter_dims",type:"u32",length:S.length},{name:"dilations",type:"u32",length:S.length},{name:"effective_filter_dims",type:"u32",length:A.length},{name:"pads",type:"i32",length:P.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],q=nt(e[0].dataType),C=l?1:2,ee=l?2:3,v=l?3:1,R=j("W",e[1].dataType,e[1].dims.length,g),H=j("Dy",e[0].dataType,e[0].dims.length,o),L=[H,R];i&&L.push(j("bias",e[2].dataType,[u[v]].length,m));let V=oe("result",e[0].dataType,u.length,m),K=()=>{let Y="";if(a)o===4?Y+=` + }`};return{name:"GroupedConv-Vectorize",shaderCache:{hint:`${t.cacheKey};${l};${d};${p};${r[0]};${r[1]}`,inputDependencies:u?["rank","rank","type"]:["rank","rank"]},getRunData:()=>({outputs:[{dims:i?i(n):n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:a}),getShaderSource:h}}}),sb,Po,ab,Co,Ul,cu,ub,lb,Vl,gk=D(()=>{"use strict";pe(),hk(),fk(),xd(),mk(),xn(),vd(),Cr(),sb=(e,t,n,i,u,l)=>{let d=e[0],c=e.slice(l?1:2,l?3:4),s=c.length,r=t[0],o=t.slice(2).map((p,h)=>p+(p-1)*(n[h]-1)),a=c.map((p,h)=>p+i[h]+i[h+s]).map((p,h)=>Math.floor((p-o[h]+u[h])/u[h]));return a.splice(0,0,d),a.splice(l?3:1,0,r),a},Po=[2,3,1,0],ab=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length>5)throw new Error("greater than 5D is not supported");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let n=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[1]*t.group;if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");if(e.length===3&&(e[2].dims.length!==1||e[1].dims[0]!==e[2].dims[0]))throw new Error("invalid bias");let u=e[0].dims.length-2;if(t.dilations.length!==u)throw new Error(`dilations should be ${u}D`);if(t.strides.length!==u)throw new Error(`strides should be ${u}D`);if(t.pads.length!==u*2)throw new Error(`pads should be ${u*2}D`);if(t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape")},Co=(e,t)=>{let n=e.kernelShape.slice();n.length{let t=yd(e),n=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],u=e.dilations,l=e.group,d=e.kernel_shape,c=e.pads,s=e.strides,r=e.w_is_const();return{autoPad:i,format:n,dilations:u,group:l,kernelShape:d,pads:c,strides:s,wIsConst:r,...t,cacheKey:`${e.format};${t.activation};`}},cu=(e,t,n,i)=>{let u=n.format==="NHWC",l=sb(t[0].dims,t[1].dims,n.dilations,n.pads,n.strides,u);if(n.group!==1){let A=[t[0]];if(u){let P=e.kernelCustomData.wT??e.compute($t(t[1],Po),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=P),A.push(P)}else A.push(t[1]);t.length===3&&A.push(t[2]),!e.adapterInfo.isArchitecture("ampere")&&u&&t[1].dims[0]===n.group&&t[1].dims[1]===1&&n.dilations[0]===1&&n.dilations[1]===1?e.compute(a2(A,n,l,i),{inputs:A}):e.compute(s2(A,n,l,i),{inputs:A});return}let d=t.length===3,c=t[0].dims[u?1:2],s=t[0].dims[u?2:3],r=t[0].dims[u?3:1],o=t[1].dims[2],a=t[1].dims[3],p=l[u?1:2],h=l[u?2:3],m=l[u?3:1],g=u&&o===c&&a===s&&n.pads[0]===0&&n.pads[1]===0;if(g||o===1&&a===1&&n.dilations[0]===1&&n.dilations[1]===1&&n.strides[0]===1&&n.strides[1]===1&&n.pads[0]===0&&n.pads[1]===0){let A=l[0],P,I,z,q=[];if(u){let C=e.kernelCustomData.wT??e.compute($t(t[1],Po),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];if(n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=C),g){let ee=c*s*r;P=t[0].reshape([1,A,ee]),I=C.reshape([1,ee,m]),z=[1,A,m]}else P=t[0].reshape([A,c*s,r]),I=C.reshape([1,r,m]),z=[A,p*h,m];q.push(P),q.push(I)}else P=t[0].reshape([A,r,c*s]),I=t[1].reshape([1,m,r]),z=[A,m,p*h],q.push(I),q.push(P);d&&q.push(t[2]);let J=z[2],G=q[0].dims[q[0].dims.length-1];J<8&&G<8?e.compute(_d(q,n,l,z,u,i),{inputs:q}):e.compute(Yo(q,n,l,z,u,i),{inputs:q});return}let _=!0,w=e.kernelCustomData.wT??e.compute($t(t[1],Po),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=w);let y=[t[0],w];d&&y.push(t[2]);let T=u?p*h:m,S=u?m:p*h,O=o*a*r;e.compute(n2(y,n,l,T,S,O,d,_,i),{inputs:y})},ub=(e,t)=>{let n=t.format==="NHWC",i=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&i.push(e.inputs[2]);let u=[0,t.pads[0],0,t.pads[1]],l=[1].concat(t.strides),d=[1].concat(t.dilations),c=[1].concat(t.kernelShape),s=Co({...t,pads:u,strides:l,dilations:d,kernelShape:c},i);cu(e,i,s,r=>n?[r[0],r[2],r[3]]:[r[0],r[1],r[3]])},lb=(e,t,n)=>{let i=n.format==="NHWC"?"channelsLast":"channelsFirst",u=Co(n,t),l=n.autoPad==="NOTSET"?n.pads:n.autoPad,d=i2(t[0].dims,t[1].dims,n.strides,n.dilations,l,!1,i);e.compute(o2(t,u,d.outShape,[d.filterDepth,d.filterHeight,d.filterWidth],[d.padInfo.front,d.padInfo.top,d.padInfo.left],i))},Vl=(e,t)=>{if(ab(e.inputs,t),e.inputs[0].dims.length===3)ub(e,t);else if(e.inputs[0].dims.length===5)lb(e,e.inputs,t);else{let n=Co(t,e.inputs);cu(e,e.inputs,n)}}}),u2,bk=D(()=>{"use strict";de(),ur(),pe(),he(),u2=(e,t,n)=>{let i=e.length>2,u=t.outputShape,l=t.format==="NHWC",d=t.group,c=e[1].dims,s=c[2]/d,r=c[3],o=l?qe(s):1,a=l&&r===1&&s>=4,p=a?Math.floor(s/4)*4:Math.floor(s/o)*o,h=s-p,m=l?qe(r):1,g=l?r===1?o:m:1,_=F.size(u)/m,w=[Math.ceil(_/64),1,1];Ie("verbose",()=>`[conv2d_backprop_webgpu] dispatch = ${w}`);let y=["rank","rank"],T=[t.strides[0],t.strides[1]],S=[t.kernelShape[l?1:2],t.kernelShape[l?2:3]],O=[t.dilations[0],t.dilations[1]],A=[S[0]+(t.dilations[0]<=1?0:(t.kernelShape[l?1:2]-1)*(t.dilations[0]-1)),S[1]+(t.dilations[1]<=1?0:(t.kernelShape[l?2:3]-1)*(t.dilations[1]-1))],P=[A[0]-1-Math.floor((t.pads[0]+t.pads[2])/2),A[1]-1-Math.floor((t.pads[1]+t.pads[3])/2)],I=[{type:12,data:_},{type:12,data:T},{type:12,data:S},{type:12,data:O},{type:12,data:A},{type:6,data:P},{type:12,data:p},{type:12,data:s},{type:12,data:r},...ue(e[0].dims,e[1].dims)];i&&(I.push(...ue(e[2].dims)),y.push("rank")),I.push(...ue(u));let z=q=>{let J=[{name:"output_size",type:"u32"},{name:"strides",type:"u32",length:T.length},{name:"filter_dims",type:"u32",length:S.length},{name:"dilations",type:"u32",length:S.length},{name:"effective_filter_dims",type:"u32",length:A.length},{name:"pads",type:"i32",length:P.length},{name:"input_channels_per_group_int",type:"u32"},{name:"input_channels_per_group",type:"u32"},{name:"output_channels_per_group",type:"u32"}],G=nt(e[0].dataType),C=l?1:2,ee=l?2:3,v=l?3:1,R=j("W",e[1].dataType,e[1].dims.length,g),H=j("Dy",e[0].dataType,e[0].dims.length,o),L=[H,R];i&&L.push(j("bias",e[2].dataType,[u[v]].length,m));let V=oe("result",e[0].dataType,u.length,m),K=()=>{let Y="";if(a)o===4?Y+=` let xValue = ${H.getByOffset("x_offset")}; let wValue = ${R.getByOffset("w_offset")}; dotProd = dotProd + dot(xValue, wValue); x_offset += 1u; w_offset += 1u;`:o===2?Y+=` - dotProd = dotProd + dot(vec4<${q}>(${H.getByOffset("x_offset")}, ${H.getByOffset("x_offset + 1u")}), vec4<${q}>(${R.getByOffset("w_offset")}, ${R.getByOffset("w_offset + 1u")})); + dotProd = dotProd + dot(vec4<${G}>(${H.getByOffset("x_offset")}, ${H.getByOffset("x_offset + 1u")}), vec4<${G}>(${R.getByOffset("w_offset")}, ${R.getByOffset("w_offset + 1u")})); x_offset += 2u; w_offset += 2u;`:o===1&&(Y+=` - dotProd = dotProd + dot(vec4<${q}>(${H.getByOffset("x_offset")}, ${H.getByOffset("x_offset + 1u")}, ${H.getByOffset("x_offset + 2u")}, ${H.getByOffset("x_offset + 3u")}), vec4<${q}>(${R.getByOffset("w_offset")}, ${R.getByOffset("w_offset + 1u")}, ${R.getByOffset("w_offset + 2u")}, ${R.getByOffset("w_offset + 3u")})); + dotProd = dotProd + dot(vec4<${G}>(${H.getByOffset("x_offset")}, ${H.getByOffset("x_offset + 1u")}, ${H.getByOffset("x_offset + 2u")}, ${H.getByOffset("x_offset + 3u")}), vec4<${G}>(${R.getByOffset("w_offset")}, ${R.getByOffset("w_offset + 1u")}, ${R.getByOffset("w_offset + 2u")}, ${R.getByOffset("w_offset + 3u")})); x_offset += 4u; w_offset += 4u;`);else if(Y+=` let xValue = ${l?H.getByOffset(`${H.indicesToOffset(`${H.type.indices}(batch, idyR, idyC, inputChannel)`)} / ${o}`):H.get("batch","inputChannel","idyR","idyC")}; @@ -3043,9 +3043,9 @@ fn main(@builtin(local_invocation_id) localId : vec3, if (wR % uniforms.dilations.x != 0) { continue; } - let dyR = (${q}(dyRCorner) + ${q}(wR)) / ${q}(uniforms.strides[0]); + let dyR = (${G}(dyRCorner) + ${G}(wR)) / ${G}(uniforms.strides[0]); let wRPerm = uniforms.filter_dims.x - 1 - wR / uniforms.dilations.x; - if (dyR < 0.0 || dyR >= ${q}(uniforms.Dy_shape[${C}]) || fract(dyR) > 0.0 || + if (dyR < 0.0 || dyR >= ${G}(uniforms.Dy_shape[${C}]) || fract(dyR) > 0.0 || wRPerm < 0) { continue; } @@ -3059,9 +3059,9 @@ fn main(@builtin(local_invocation_id) localId : vec3, if (wC % uniforms.dilations.y != 0) { continue; } - let dyC = (${q}(dyCCorner) + ${q}(wC)) / ${q}(uniforms.strides.y); + let dyC = (${G}(dyCCorner) + ${G}(wC)) / ${G}(uniforms.strides.y); let wCPerm = uniforms.filter_dims.y - 1 - wC / uniforms.dilations.y; - if (dyC < 0.0 || dyC >= ${q}(uniforms.Dy_shape[${ee}]) || + if (dyC < 0.0 || dyC >= ${G}(uniforms.Dy_shape[${ee}]) || fract(dyC) > 0.0 || wCPerm < 0) { continue; } @@ -3083,10 +3083,10 @@ fn main(@builtin(local_invocation_id) localId : vec3, let value = dotProd${i?` + bias[d1 / ${m}]`:""}; ${V.setByOffset("global_idx","value")}; `;return` - ${G.registerUniforms(J).declareVariables(...L,V)} - ${G.mainStart()} - ${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; - ${te}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${o}${g}${m}${a}${h}`,inputDependencies:y},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:n?n(u):u,dataType:e[0].dataType}],programUniforms:I}),getShaderSource:z}}}),ob,sb,ab,lu,i2,ub,du,lb,o2,ck=D(()=>{"use strict";dk(),xn(),Cr(),ob=(e,t,n,i,u,l)=>(e-1)*t+n+(i-1)*u+1-l,sb=(e,t,n,i,u)=>{let l=Math.floor(e/2);t==="SAME_UPPER"?(n[i]=l,n[u]=e-l):t==="SAME_LOWER"&&(n[i]=e-l,n[u]=l)},ab=(e,t,n,i,u,l,d,c,s,r)=>{let o=e.length-2,a=r.length===0;s.length{let n=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((a,p)=>a*p,1)===0){n.length=0;for(let a=2;aa+p,0)===0){let a=t[0].dims.length-2;s=new Array(a).fill(1)}let r=e.strides.slice();if(r.reduce((a,p)=>a+p,0)===0){let a=t[0].dims.length-2;r=new Array(a).fill(1)}ab(c,n,s,e.autoPad,e.group,u,r,i,d,l);let o=Object.assign({},e);return Object.assign(o,{kernelShape:n,pads:u,outputPadding:d,outputShape:l,dilations:s,strides:r}),o},i2=e=>{let t=md(e),n=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],u=e.dilations,l=e.group??1,d=e.kernelShape,c=e.pads,s=e.strides,r=e.wIsConst(),o=e.outputPadding,a=e.outputShape;return{autoPad:i,format:n,dilations:u,group:l,kernelShape:d,outputPadding:o,outputShape:a,pads:c,strides:s,wIsConst:r,...t,cacheKey:`${e.format};${t.activation};`}},ub=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let n=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[0];if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let u=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==u))throw new Error("invalid bias");let l=e[0].dims.length-2;if(t.dilations.reduce((d,c)=>d+c,0)>0&&t.dilations.length!==l)throw new Error(`dilations should be ${l}D`);if(t.strides.reduce((d,c)=>d+c,0)>0&&t.strides.length!==l)throw new Error(`strides should be ${l}D`);if(t.pads.reduce((d,c)=>d+c,0)>0&&t.pads.length!==l*2)throw new Error(`pads should be ${l*2}D`);if(t.outputPadding.length!==l&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${l}D`);if(t.kernelShape.reduce((d,c)=>d+c,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},du=(e,t,n,i)=>{let u=e.kernelCustomData.wT??e.compute($t(t[1],[2,3,0,1]),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=u);let l=[t[0],u];t.length===3&&l.push(t[2]),e.compute(n2(l,n,i),{inputs:l})},lb=(e,t)=>{let n=t.format==="NHWC",i=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&i.push(e.inputs[2]);let u=t.kernelShape;(u.length===0||u[0]===0)&&(u=[e.inputs[1].dims[2]]);let l=t.dilations;(l.length===0||l[0]===0)&&(l=[1]);let d=t.strides;(d.length===0||d[0]===0)&&(d=[1]);let c=t.pads;c.length===0&&(c=[0,0]),c=[0,c[0],0,c[1]],d=[1].concat(d),l=[1].concat(l),u=[1].concat(u);let s=t.outputPadding;s=[0].concat(s);let r=lu({...t,pads:c,strides:d,dilations:l,kernelShape:u,outputPadding:s},i);du(e,i,r,o=>n?[o[0],o[2],o[3]]:[o[0],o[1],o[3]])},o2=(e,t)=>{if(ub(e.inputs,t),e.inputs[0].dims.length===3)lb(e,t);else{let n=lu(t,e.inputs);du(e,e.inputs,n)}}}),db,s2,a2,pk=D(()=>{"use strict";de(),pe(),He(),he(),db=(e,t,n,i)=>{let u=F.size(t),l=t.length,d=j("input",e,l),c=oe("output",e,l),s=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),r=F.normalizeAxis(s,l),o=a=>{let p=` i32(${d.indicesGet("inputIndices","uniforms.axis")}) `,h=se("uniforms.input_shape","uniforms.axis",l),m=i.reverse?p+(i.exclusive?" + 1":""):"0",g=i.reverse?h:p+(i.exclusive?"":" + 1");return` + ${q.registerUniforms(J).declareVariables(...L,V)} + ${q.mainStart()} + ${q.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}; + ${te}}`};return{name:"ConvTranspose2D",shaderCache:{hint:`${t.cacheKey};${o}${g}${m}${a}${h}`,inputDependencies:y},getRunData:()=>({dispatchGroup:{x:w[0],y:w[1],z:w[2]},outputs:[{dims:n?n(u):u,dataType:e[0].dataType}],programUniforms:I}),getShaderSource:z}}}),db,cb,pb,pu,l2,hb,hu,fb,d2,yk=D(()=>{"use strict";bk(),xn(),Cr(),db=(e,t,n,i,u,l)=>(e-1)*t+n+(i-1)*u+1-l,cb=(e,t,n,i,u)=>{let l=Math.floor(e/2);t==="SAME_UPPER"?(n[i]=l,n[u]=e-l):t==="SAME_LOWER"&&(n[i]=e-l,n[u]=l)},pb=(e,t,n,i,u,l,d,c,s,r)=>{let o=e.length-2,a=r.length===0;s.length{let n=e.kernelShape.slice();if(e.kernelShape.length===0||e.kernelShape.reduce((a,p)=>a*p,1)===0){n.length=0;for(let a=2;aa+p,0)===0){let a=t[0].dims.length-2;s=new Array(a).fill(1)}let r=e.strides.slice();if(r.reduce((a,p)=>a+p,0)===0){let a=t[0].dims.length-2;r=new Array(a).fill(1)}pb(c,n,s,e.autoPad,e.group,u,r,i,d,l);let o=Object.assign({},e);return Object.assign(o,{kernelShape:n,pads:u,outputPadding:d,outputShape:l,dilations:s,strides:r}),o},l2=e=>{let t=yd(e),n=e.format,i=["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][typeof e.autoPad>"u"?0:e.autoPad],u=e.dilations,l=e.group??1,d=e.kernelShape,c=e.pads,s=e.strides,r=e.wIsConst(),o=e.outputPadding,a=e.outputShape;return{autoPad:i,format:n,dilations:u,group:l,kernelShape:d,outputPadding:o,outputShape:a,pads:c,strides:s,wIsConst:r,...t,cacheKey:`${e.format};${t.activation};`}},hb=(e,t)=>{if(!e||e.length!==2&&e.length!==3)throw new Error("Conv requires 2 or 3 inputs");if(e[0].dims.length!==4&&e[0].dims.length!==3)throw new Error("currently only support 2-dimensional conv");if(e[0].dims.length!==e[1].dims.length)throw new Error("filter does not have same dimension as input");let n=e[0].dims[t.format==="NHWC"?e[0].dims.length-1:1],i=e[1].dims[0];if(n!==i)throw new Error("FILTER_IN_CHANNEL should be equal to DATA_CHANNEL");let u=e[1].dims[1]*t.group;if(e.length===3&&(e[2].dims.length!==1||e[2].dims[0]!==u))throw new Error("invalid bias");let l=e[0].dims.length-2;if(t.dilations.reduce((d,c)=>d+c,0)>0&&t.dilations.length!==l)throw new Error(`dilations should be ${l}D`);if(t.strides.reduce((d,c)=>d+c,0)>0&&t.strides.length!==l)throw new Error(`strides should be ${l}D`);if(t.pads.reduce((d,c)=>d+c,0)>0&&t.pads.length!==l*2)throw new Error(`pads should be ${l*2}D`);if(t.outputPadding.length!==l&&t.outputPadding.length!==0)throw new Error(`output_padding should be ${l}D`);if(t.kernelShape.reduce((d,c)=>d+c,0)>0&&t.kernelShape.length!==0&&t.kernelShape.length!==e[1].dims.length-2)throw new Error("invalid kernel shape");if(t.outputShape.length!==0&&t.outputShape.length!==e[0].dims.length-2)throw new Error("invalid output shape")},hu=(e,t,n,i)=>{let u=e.kernelCustomData.wT??e.compute($t(t[1],[2,3,0,1]),{inputs:[1],outputs:[n.wIsConst?-2:-1]})[0];n.wIsConst&&!e.kernelCustomData.wT&&(e.kernelCustomData.wT=u);let l=[t[0],u];t.length===3&&l.push(t[2]),e.compute(u2(l,n,i),{inputs:l})},fb=(e,t)=>{let n=t.format==="NHWC",i=[e.inputs[0].reshape(n?[e.inputs[0].dims[0],1,e.inputs[0].dims[1],e.inputs[0].dims[2]]:[e.inputs[0].dims[0],e.inputs[0].dims[1],1,e.inputs[0].dims[2]]),e.inputs[1].reshape([e.inputs[1].dims[0],e.inputs[1].dims[1],1,e.inputs[1].dims[2]])];e.inputs.length===3&&i.push(e.inputs[2]);let u=t.kernelShape;(u.length===0||u[0]===0)&&(u=[e.inputs[1].dims[2]]);let l=t.dilations;(l.length===0||l[0]===0)&&(l=[1]);let d=t.strides;(d.length===0||d[0]===0)&&(d=[1]);let c=t.pads;c.length===0&&(c=[0,0]),c=[0,c[0],0,c[1]],d=[1].concat(d),l=[1].concat(l),u=[1].concat(u);let s=t.outputPadding;s=[0].concat(s);let r=pu({...t,pads:c,strides:d,dilations:l,kernelShape:u,outputPadding:s},i);hu(e,i,r,o=>n?[o[0],o[2],o[3]]:[o[0],o[1],o[3]])},d2=(e,t)=>{if(hb(e.inputs,t),e.inputs[0].dims.length===3)fb(e,t);else{let n=pu(t,e.inputs);hu(e,e.inputs,n)}}}),mb,c2,p2,wk=D(()=>{"use strict";de(),pe(),He(),he(),mb=(e,t,n,i)=>{let u=F.size(t),l=t.length,d=j("input",e,l),c=oe("output",e,l),s=n.dataType===6?n.getInt32Array()[0]:Number(n.getBigInt64Array()[0]),r=F.normalizeAxis(s,l),o=a=>{let p=` i32(${d.indicesGet("inputIndices","uniforms.axis")}) `,h=se("uniforms.input_shape","uniforms.axis",l),m=i.reverse?p+(i.exclusive?" + 1":""):"0",g=i.reverse?h:p+(i.exclusive?"":" + 1");return` ${a.registerUniform("outputSize","u32").registerUniform("axis","u32").declareVariables(d,c)} ${a.mainStart()} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} @@ -3099,12 +3099,12 @@ fn main(@builtin(local_invocation_id) localId : vec3, sum = sum + ${d.getByIndices("inputIndices")}; } ${c.setByOffset("global_idx","sum")}; - }`};return{name:"CumSum",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:12,data:r},...ue(t,t)]}),getShaderSource:o}},s2=(e,t)=>{let n=e.inputs[0].dims,i=e.inputs[0].dataType,u=e.inputs[1];e.compute(db(i,n,u,t),{inputs:[0]})},a2=e=>{let t=e.exclusive===1,n=e.reverse===1;return ke({exclusive:t,reverse:n})}}),cb,pb,hb,u2,l2,hk=D(()=>{"use strict";de(),pe(),He(),he(),cb=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},pb=(e,t,n,i)=>{let u=[];u.push(`fn perm(i: ${i.type.indices}) -> ${n.type.indices} { + }`};return{name:"CumSum",shaderCache:{hint:i.cacheKey,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:t,dataType:e}],dispatchGroup:{x:Math.ceil(u/64)},programUniforms:[{type:12,data:u},{type:12,data:r},...ue(t,t)]}),getShaderSource:o}},c2=(e,t)=>{let n=e.inputs[0].dims,i=e.inputs[0].dataType,u=e.inputs[1];e.compute(mb(i,n,u,t),{inputs:[0]})},p2=e=>{let t=e.exclusive===1,n=e.reverse===1;return ke({exclusive:t,reverse:n})}}),gb,bb,yb,h2,f2,_k=D(()=>{"use strict";de(),pe(),He(),he(),gb=e=>{if(!e||e.length!==1)throw new Error("DepthToSpace requires 1 input.");if(e[0].dims.length!==4)throw new Error("DepthToSpace requires 4D input.")},bb=(e,t,n,i)=>{let u=[];u.push(`fn perm(i: ${i.type.indices}) -> ${n.type.indices} { var a: ${n.type.indices};`);for(let l=0;l{let n,i,u,l,d,c,s=t.format==="NHWC",r=t.blocksize,o=t.mode==="DCR";s?([n,i,u,l]=e.dims,d=o?[n,i,u,r,r,l/r**2]:[n,i,u,l/r**2,r,r],c=o?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,i,u,l]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],d=o?[n,r,r,l/r**2,i,u]:[n,l/r**2,r,r,i,u],c=o?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let a=e.reshape(d),p=a.dims.length,h=e.dataType,m=j("a",h,p),g=oe("output",h,p),_=w=>` +`)},yb=(e,t)=>{let n,i,u,l,d,c,s=t.format==="NHWC",r=t.blocksize,o=t.mode==="DCR";s?([n,i,u,l]=e.dims,d=o?[n,i,u,r,r,l/r**2]:[n,i,u,l/r**2,r,r],c=o?[0,1,3,2,4,5]:[0,1,4,2,5,3]):([n,i,u,l]=[e.dims[0],e.dims[2],e.dims[3],e.dims[1]],d=o?[n,r,r,l/r**2,i,u]:[n,l/r**2,r,r,i,u],c=o?[0,3,4,1,5,2]:[0,1,4,2,5,3]);let a=e.reshape(d),p=a.dims.length,h=e.dataType,m=j("a",h,p),g=oe("output",h,p),_=w=>` ${w.registerUniform("output_size","u32").declareVariables(m,g)} - ${pb(c,p,m,g)} + ${bb(c,p,m,g)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -3113,12 +3113,12 @@ fn main(@builtin(local_invocation_id) localId : vec3, let aIndices = perm(indices); ${g.setByOffset("global_idx",m.getByIndices("aIndices"))} - }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:w=>{let y=s?[n,i*r,u*r,l/r**2]:[n,l/r**2,i*r,u*r],T=F.size(y),S=a.dims,O=F.sortBasedOnPerm(S,c);return{outputs:[{dims:y,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:[{type:12,data:T},...ue(S,O)]}},getShaderSource:_}},u2=(e,t)=>{cb(e.inputs),e.compute(hb(e.inputs[0],t))},l2=e=>ke({blocksize:e.blocksize,mode:e.mode,format:e.format})}),ir,hi,Po,cu,wr,fb,mb,gb,pu,hu,fu,bb,yb,mu,wb,d2,c2,fk=D(()=>{"use strict";de(),pe(),He(),he(),ir=256,hi=512,Po=2*Math.PI,cu=e=>{let t=[],n=e;for(let i of[4,2,3,5])for(;n%i===0;)t.push(i),n/=i;return n===1?t:void 0},wr=e=>{let t=e.toPrecision(9);return/[.eE]/.test(t)?t:`${t}.0`},fb=(e,t,n,i,u)=>{let l=n/e,d=hi-i,c=r=>`smem[${d}u + base + ${r*t}u]`,s=` for (var t = local_idx; t < ${l}u; t += ${ir}u) { + }`;return{name:"DepthToSpace",shaderCache:{hint:`${e.dims};${t.blocksize};${t.mode}`,inputDependencies:["rank"]},getRunData:w=>{let y=s?[n,i*r,u*r,l/r**2]:[n,l/r**2,i*r,u*r],T=F.size(y),S=a.dims,O=F.sortBasedOnPerm(S,c);return{outputs:[{dims:y,dataType:w[0].dataType}],dispatchGroup:{x:Math.ceil(T/64)},programUniforms:[{type:12,data:T},...ue(S,O)]}},getShaderSource:_}},h2=(e,t)=>{gb(e.inputs),e.compute(yb(e.inputs[0],t))},f2=e=>ke({blocksize:e.blocksize,mode:e.mode,format:e.format})}),ir,mi,Ro,fu,wr,wb,_b,vb,mu,gu,bu,xb,$b,yu,Tb,m2,g2,vk=D(()=>{"use strict";de(),pe(),He(),he(),ir=256,mi=512,Ro=2*Math.PI,fu=e=>{let t=[],n=e;for(let i of[4,2,3,5])for(;n%i===0;)t.push(i),n/=i;return n===1?t:void 0},wr=e=>{let t=e.toPrecision(9);return/[.eE]/.test(t)?t:`${t}.0`},wb=(e,t,n,i,u)=>{let l=n/e,d=mi-i,c=r=>`smem[${d}u + base + ${r*t}u]`,s=` for (var t = local_idx; t < ${l}u; t += ${ir}u) { `;s+=` let twiddleIndex = t % ${t}u; let angleUnit = f32(twiddleIndex); `,s+=` var leg: array, 5>; `;for(let r=0;r(cos(a), sin(a))); } +`;else{let a=u*Ro*r/(e*t);s+=` { let a = ${wr(a)} * angleUnit; leg[${r}] = cmul(smem[${o}], vec2(cos(a), sin(a))); } `}}if(s+=` let base = (t / ${t}u) * ${t*e}u + twiddleIndex; `,e===2)s+=` ${c(0)} = leg[0] + leg[1]; ${c(1)} = leg[0] - leg[1]; @@ -3129,10 +3129,10 @@ fn main(@builtin(local_invocation_id) localId : vec3, ${c(1)} = evenDiff + oddRot; `,s+=` ${c(2)} = evenSum - oddSum; ${c(3)} = evenDiff - oddRot; -`}else for(let r=0;r(leg[${a}].x*${h} - leg[${a}].y*${m}, leg[${a}].x*${m} + leg[${a}].y*${h})`)}s+=` ${c(r)} = ${o.join(" + ")}; +`}else for(let r=0;r(leg[${a}].x*${h} - leg[${a}].y*${m}, leg[${a}].x*${m} + leg[${a}].y*${h})`)}s+=` ${c(r)} = ${o.join(" + ")}; `}return`${s} } workgroupBarrier(); -`},mb=(e,t,n)=>{let i="",u=1,l=0;for(let d of e)i+=fb(d,u,t,l,n),u*=d,l=hi-l;return{code:i,resultOffset:l}},gb=(e,t,n,i,u)=>{let l=e.dims,d=l.length,c=l[d-1],s=l[t],r=n&&i?(s-1)*2:s;u!==void 0&&(r=u);let o=n&&i?1:2,a=i&&!n?Math.floor(r/2)+1:r,p=l.slice();p[t]=a,p[d-1]=o;let h=1;for(let g=t+1;g[t,e.length,e.inputComponents,e.outputComponents,e.inverse,e.onesided].join(";"),hu=e=>[{type:12,data:e.batch},{type:12,data:e.signalLength},{type:12,data:e.inner},{type:12,data:e.outputLength}],fu=(e,t,n)=>e.registerUniform("batch","u32").registerUniform("signalLength","u32").registerUniform("inner","u32").registerUniform("outputLength","u32").declareVariables(t,n),bb=e=>{let{dataType:t,length:n,inputComponents:i,outputComponents:u,inverse:l,onesided:d}=e,c=rt(t),s=l?1:-1,r=l?1/n:1,o=cu(n),a=p=>{let h=j("x",t,[1]),m=oe("y",t,[1]),g=O=>{let A=`inBase + (${O}) * uniforms.inner * ${i}u`,P=`f32(${h.getByOffset(A)})`,I=i===2?`f32(${h.getByOffset(`${A} + 1u`)})`:"0.0";return`vec2(${P}, ${I})`},_;if(l&&d){let O=Math.floor(n/2)+1,A=n%2===0?`select(provided, provided - 1u, provided == ${O}u)`:"provided";_=` +`},_b=(e,t,n)=>{let i="",u=1,l=0;for(let d of e)i+=wb(d,u,t,l,n),u*=d,l=mi-l;return{code:i,resultOffset:l}},vb=(e,t,n,i,u)=>{let l=e.dims,d=l.length,c=l[d-1],s=l[t],r=n&&i?(s-1)*2:s;u!==void 0&&(r=u);let o=n&&i?1:2,a=i&&!n?Math.floor(r/2)+1:r,p=l.slice();p[t]=a,p[d-1]=o;let h=1;for(let g=t+1;g[t,e.length,e.inputComponents,e.outputComponents,e.inverse,e.onesided].join(";"),gu=e=>[{type:12,data:e.batch},{type:12,data:e.signalLength},{type:12,data:e.inner},{type:12,data:e.outputLength}],bu=(e,t,n)=>e.registerUniform("batch","u32").registerUniform("signalLength","u32").registerUniform("inner","u32").registerUniform("outputLength","u32").declareVariables(t,n),xb=e=>{let{dataType:t,length:n,inputComponents:i,outputComponents:u,inverse:l,onesided:d}=e,c=rt(t),s=l?1:-1,r=l?1/n:1,o=fu(n),a=p=>{let h=j("x",t,[1]),m=oe("y",t,[1]),g=O=>{let A=`inBase + (${O}) * uniforms.inner * ${i}u`,P=`f32(${h.getByOffset(A)})`,I=i===2?`f32(${h.getByOffset(`${A} + 1u`)})`:"0.0";return`vec2(${P}, ${I})`},_;if(l&&d){let O=Math.floor(n/2)+1,A=n%2===0?`select(provided, provided - 1u, provided == ${O}u)`:"provided";_=` let provided = min(uniforms.signalLength, ${O}u); for (var i = local_idx; i < ${n}u; i += ${ir}u) { if (i < provided) { smem[i] = ${g("i")}; } else { smem[i] = vec2(0.0); } @@ -3147,9 +3147,9 @@ fn main(@builtin(local_invocation_id) localId : vec3, for (var i = local_idx; i < ${n}u; i += ${ir}u) { if (i < loadCount) { smem[i] = ${g("i")}; } else { smem[i] = vec2(0.0); } } - workgroupBarrier();`;let{code:w,resultOffset:y}=mb(o,n,s),T=r===1?`smem[${y}u + i]`:`smem[${y}u + i] * ${wr(r)}`,S=u===2?m.setByOffset("off + 1u",`${c}(v.y)`):"";return` - ${fu(p,h,m)} - var smem: array, ${2*hi}>; + workgroupBarrier();`;let{code:w,resultOffset:y}=_b(o,n,s),T=r===1?`smem[${y}u + i]`:`smem[${y}u + i] * ${wr(r)}`,S=u===2?m.setByOffset("off + 1u",`${c}(v.y)`):"";return` + ${bu(p,h,m)} + var smem: array, ${2*mi}>; fn cmul(a: vec2, b: vec2) -> vec2 { return vec2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x); } @@ -3167,7 +3167,7 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { ${m.setByOffset("off",`${c}(v.x)`)} ${S} } - }`};return{name:"DFT",shaderCache:{hint:pu(e,"fft"),inputDependencies:["type"]},getShaderSource:a,getRunData:()=>({outputs:[{dims:e.outputDims,dataType:t}],programUniforms:hu(e),dispatchGroup:{x:e.batch}})}},yb=e=>{let{dataType:t,length:n,inputComponents:i,outputComponents:u,inverse:l,onesided:d}=e,c=rt(t),s=l?1:-1,r=l?1/n:1,o=a=>{let p=j("x",t,[1]),h=oe("y",t,[1]),m=T=>{let S=`inBase + (${T}) * uniforms.inner * ${i}u`,O=`f32(${p.getByOffset(S)})`,A=i===2?`f32(${p.getByOffset(`${S} + 1u`)})`:"0.0";return`vec2(${O}, ${A})`},g=l&&d?`fn spectrum(inBase: u32, k: u32) -> vec2 { + }`};return{name:"DFT",shaderCache:{hint:mu(e,"fft"),inputDependencies:["type"]},getShaderSource:a,getRunData:()=>({outputs:[{dims:e.outputDims,dataType:t}],programUniforms:gu(e),dispatchGroup:{x:e.batch}})}},$b=e=>{let{dataType:t,length:n,inputComponents:i,outputComponents:u,inverse:l,onesided:d}=e,c=rt(t),s=l?1:-1,r=l?1/n:1,o=a=>{let p=j("x",t,[1]),h=oe("y",t,[1]),m=T=>{let S=`inBase + (${T}) * uniforms.inner * ${i}u`,O=`f32(${p.getByOffset(S)})`,A=i===2?`f32(${p.getByOffset(`${S} + 1u`)})`:"0.0";return`vec2(${O}, ${A})`},g=l&&d?`fn spectrum(inBase: u32, k: u32) -> vec2 { let provided = min(uniforms.signalLength, ${Math.floor(n/2)+1}u); if (k < provided) { return ${m("k")}; } let m = ${n}u - k; @@ -3180,11 +3180,11 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { if (n < uniforms.signalLength) { return ${m("n")}; } return vec2(0.0, 0.0); }`,_=` - let angle = ${wr(s*Po)} * f32(knMod) / ${wr(n)}; + let angle = ${wr(s*Ro)} * f32(knMod) / ${wr(n)}; acc += cmul(spectrum(inBase, n), vec2(cos(angle), sin(angle))); knMod += k; if (knMod >= ${n}u) { knMod -= ${n}u; }`,w=u===2?h.setByOffset("off + 1u",`${c}(v.y)`):"",y=r===1?"acc":`acc * ${wr(r)}`;return` - ${fu(a,p,h)} + ${bu(a,p,h)} fn cmul(a: vec2, b: vec2) -> vec2 { return vec2(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x); } @@ -3206,8 +3206,8 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { ${h.setByOffset("off",`${c}(v.x)`)} ${w} } - }`};return{name:"DFT",shaderCache:{hint:pu(e,"direct"),inputDependencies:["type"]},getShaderSource:o,getRunData:()=>({outputs:[{dims:e.outputDims,dataType:t}],programUniforms:hu(e),dispatchGroup:{x:e.batch}})}},mu=e=>{if(!e||e.dataType===0)return;if(F.size(e.dims)!==1)throw new Error("DFT optional scalar inputs must have exactly 1 element.");if(e.dataType===6)return e.getInt32Array()[0];let t=Number(e.getBigInt64Array()[0]);if(!Number.isSafeInteger(t))throw new Error("DFT optional scalar inputs are out of JavaScript safe integer range.");return t},wb=e=>{if(!e||e.length<1)throw new Error("DFT requires at least 1 input.");let t=e[0].dims;if(t.length<2)throw new Error("DFT input must have at least 2 dimensions.");let n=t[t.length-1];if(n!==1&&n!==2)throw new Error("DFT input's innermost dimension must be 1 (real) or 2 (complex).")},d2=(e,t)=>{wb(e.inputs);let n=e.inputs[0],i=n.dims.length,u=t.inverse!==0,l=t.onesided!==0,d=mu(e.inputs[1]);if(d!==void 0&&d<=0)throw new Error("dft_length must be greater than zero.");let c=F.normalizeAxis(mu(e.inputs[2])??t.axis,i);if(c===i-1)throw new Error("DFT axis must refer to a signal dimension, not the innermost (real/imaginary) dimension.");if(u&&l&&n.dims[i-1]!==2)throw new Error("Inverse one-sided DFT (IRFFT) requires complex-valued input (innermost dimension 2).");let s=gb(n,c,u,l,d);if(s.length<=0)throw new Error(`Invalid DFT length: ${s.length}`);let r=s.length<=hi&&cu(s.length)!==void 0?bb(s):yb(s);e.compute(r,{inputs:[0]})},c2=e=>ke({axis:e.axis??1,inverse:e.inverse??0,onesided:e.onesided??0})}),Co,fi,gu,_b,vb,xb,$b,bu,Tb,p2,h2,mk=D(()=>{"use strict";de(),pe(),He(),he(),Co="[a-zA-Z]|\\.\\.\\.",fi="("+Co+")+",gu="^"+fi+"$",_b="("+fi+",)*"+fi,vb="^"+_b+"$",xb=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);n===void 0?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},$b=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,i]=t.includes("->")?t.split("->",2):[t,""];if(!n.match(RegExp(vb)))throw new Error("Invalid LHS term");if(n.split(",").forEach((u,l)=>{let d=e[l].dims.slice();if(!u.match(RegExp(gu)))throw new Error("Invalid LHS term");let c=this.processTerm(u,!0,d,l);this.lhs.push(c)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([u,l])=>l.count===1||u==="...").map(([u])=>u).join("");else if(!i.match(RegExp(fi)))throw new Error("Invalid RHS");i.match(RegExp(Co,"g"))?.forEach(u=>{if(u==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let l=this.symbolToInfo.get(u);if(l===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(l.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(e,t,n){let i=this.symbolToInfo.get(e);if(i!==void 0){if(i.dimValue!==t&&i.count!==1)throw new Error("Dimension mismatch");i.count++,i.inputIndices.push(n)}else i={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,i)}processTerm(e,t,n,i=-1){let u=n.length,l=!1,d=[],c=0;if(!e.match(RegExp(gu))&&!t&&e!=="")throw new Error("Invalid LHS term");let s=e.match(RegExp(Co,"g")),r=new xb(i);return s?.forEach((o,a)=>{if(o==="..."){if(l)throw new Error("Only one ellipsis is allowed per input term");l=!0;let p=u-s.length+1;if(p<0)throw new Error("Ellipsis out of bounds");if(d=n.slice(c,c+p),this.hasEllipsis){if(this.ellipsisDims.length!==d.length||this.ellipsisDims.toString()!==d.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=d;else throw new Error("Ellipsis must be specified in the LHS");for(let h=0;he+"_max",Tb=(e,t,n,i)=>{let u=e.map(r=>r.length).map((r,o)=>j(`input${o}`,t,r)),l=F.size(i),d=oe("output",t,i.length),c=[...n.symbolToInfo.keys()].filter(r=>!n.rhs.symbolToIndices.has(r)),s=r=>{let o=[],a="var prod = 1.0;",p="var sum = 0.0;",h="sum += prod;",m=[],g=[],_=[],w=[],y=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach((S,O)=>{if(n.rhs.symbolToIndices.has(O)){let A=n.rhs.symbolToIndices.get(O)?.[0];A!==void 0&&n.lhs.forEach((P,I)=>{if(S.inputIndices.includes(I)){let z=P.symbolToIndices.get(O);if(z===void 0)throw new Error("Invalid symbol error");z.forEach(G=>{o.push(`${u[I].indicesSet(`input${I}Indices`,G,d.indicesGet("outputIndices",A))}`)})}})}else n.lhs.forEach((A,P)=>{if(S.inputIndices.includes(P)){let I=A.symbolToIndices.get(O);if(I===void 0)throw new Error("Invalid symbol error");I.forEach(z=>{m.push(`${u[P].indicesSet(`input${P}Indices`,z,`${O}`)}`)}),w.push(`prod *= ${u[P].getByIndices(`input${P}Indices`)};`)}}),g.push(`for(var ${O}: u32 = 0; ${O} < uniforms.${bu(O)}; ${O}++) {`),_.push("}")});let T=y?[...o,`let sum = ${u.map((S,O)=>S.getByIndices(`input${O}Indices`)).join(" * ")};`]:[...o,p,...g,...m,a,...w,h,..._];return` - ${r.registerUniforms(c.map(S=>({name:`${bu(S)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...u,d)} + }`};return{name:"DFT",shaderCache:{hint:mu(e,"direct"),inputDependencies:["type"]},getShaderSource:o,getRunData:()=>({outputs:[{dims:e.outputDims,dataType:t}],programUniforms:gu(e),dispatchGroup:{x:e.batch}})}},yu=e=>{if(!e||e.dataType===0)return;if(F.size(e.dims)!==1)throw new Error("DFT optional scalar inputs must have exactly 1 element.");if(e.dataType===6)return e.getInt32Array()[0];let t=Number(e.getBigInt64Array()[0]);if(!Number.isSafeInteger(t))throw new Error("DFT optional scalar inputs are out of JavaScript safe integer range.");return t},Tb=e=>{if(!e||e.length<1)throw new Error("DFT requires at least 1 input.");let t=e[0].dims;if(t.length<2)throw new Error("DFT input must have at least 2 dimensions.");let n=t[t.length-1];if(n!==1&&n!==2)throw new Error("DFT input's innermost dimension must be 1 (real) or 2 (complex).")},m2=(e,t)=>{Tb(e.inputs);let n=e.inputs[0],i=n.dims.length,u=t.inverse!==0,l=t.onesided!==0,d=yu(e.inputs[1]);if(d!==void 0&&d<=0)throw new Error("dft_length must be greater than zero.");let c=F.normalizeAxis(yu(e.inputs[2])??t.axis,i);if(c===i-1)throw new Error("DFT axis must refer to a signal dimension, not the innermost (real/imaginary) dimension.");if(u&&l&&n.dims[i-1]!==2)throw new Error("Inverse one-sided DFT (IRFFT) requires complex-valued input (innermost dimension 2).");let s=vb(n,c,u,l,d);if(s.length<=0)throw new Error(`Invalid DFT length: ${s.length}`);let r=s.length<=mi&&fu(s.length)!==void 0?xb(s):$b(s);e.compute(r,{inputs:[0]})},g2=e=>ke({axis:e.axis??1,inverse:e.inverse??0,onesided:e.onesided??0})}),Do,gi,wu,Sb,Ib,Ob,Eb,_u,Ab,b2,y2,xk=D(()=>{"use strict";de(),pe(),He(),he(),Do="[a-zA-Z]|\\.\\.\\.",gi="("+Do+")+",wu="^"+gi+"$",Sb="("+gi+",)*"+gi,Ib="^"+Sb+"$",Ob=class{constructor(e=-1){this.symbolToIndices=new Map,this.inputIndex=e}addSymbol(e,t){let n=this.symbolToIndices.get(e);n===void 0?n=[t]:n.push(t),this.symbolToIndices.set(e,n)}},Eb=class{constructor(e,t){this.equation=t,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[n,i]=t.includes("->")?t.split("->",2):[t,""];if(!n.match(RegExp(Ib)))throw new Error("Invalid LHS term");if(n.split(",").forEach((u,l)=>{let d=e[l].dims.slice();if(!u.match(RegExp(wu)))throw new Error("Invalid LHS term");let c=this.processTerm(u,!0,d,l);this.lhs.push(c)}),i==="")i+=[...this.symbolToInfo.entries()].filter(([u,l])=>l.count===1||u==="...").map(([u])=>u).join("");else if(!i.match(RegExp(gi)))throw new Error("Invalid RHS");i.match(RegExp(Do,"g"))?.forEach(u=>{if(u==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let l=this.symbolToInfo.get(u);if(l===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(l.dimValue)}}),this.rhs=this.processTerm(i,!1,this.outputDims)}addSymbol(e,t,n){let i=this.symbolToInfo.get(e);if(i!==void 0){if(i.dimValue!==t&&i.count!==1)throw new Error("Dimension mismatch");i.count++,i.inputIndices.push(n)}else i={count:1,dimValue:t,inputIndices:[n]};this.symbolToInfo.set(e,i)}processTerm(e,t,n,i=-1){let u=n.length,l=!1,d=[],c=0;if(!e.match(RegExp(wu))&&!t&&e!=="")throw new Error("Invalid LHS term");let s=e.match(RegExp(Do,"g")),r=new Ob(i);return s?.forEach((o,a)=>{if(o==="..."){if(l)throw new Error("Only one ellipsis is allowed per input term");l=!0;let p=u-s.length+1;if(p<0)throw new Error("Ellipsis out of bounds");if(d=n.slice(c,c+p),this.hasEllipsis){if(this.ellipsisDims.length!==d.length||this.ellipsisDims.toString()!==d.toString())throw new Error("Ellipsis dimensions mismatch")}else if(t)this.hasEllipsis=!0,this.ellipsisDims=d;else throw new Error("Ellipsis must be specified in the LHS");for(let h=0;he+"_max",Ab=(e,t,n,i)=>{let u=e.map(r=>r.length).map((r,o)=>j(`input${o}`,t,r)),l=F.size(i),d=oe("output",t,i.length),c=[...n.symbolToInfo.keys()].filter(r=>!n.rhs.symbolToIndices.has(r)),s=r=>{let o=[],a="var prod = 1.0;",p="var sum = 0.0;",h="sum += prod;",m=[],g=[],_=[],w=[],y=n.symbolToInfo.size===n.rhs.symbolToIndices.size;n.symbolToInfo.forEach((S,O)=>{if(n.rhs.symbolToIndices.has(O)){let A=n.rhs.symbolToIndices.get(O)?.[0];A!==void 0&&n.lhs.forEach((P,I)=>{if(S.inputIndices.includes(I)){let z=P.symbolToIndices.get(O);if(z===void 0)throw new Error("Invalid symbol error");z.forEach(q=>{o.push(`${u[I].indicesSet(`input${I}Indices`,q,d.indicesGet("outputIndices",A))}`)})}})}else n.lhs.forEach((A,P)=>{if(S.inputIndices.includes(P)){let I=A.symbolToIndices.get(O);if(I===void 0)throw new Error("Invalid symbol error");I.forEach(z=>{m.push(`${u[P].indicesSet(`input${P}Indices`,z,`${O}`)}`)}),w.push(`prod *= ${u[P].getByIndices(`input${P}Indices`)};`)}}),g.push(`for(var ${O}: u32 = 0; ${O} < uniforms.${_u(O)}; ${O}++) {`),_.push("}")});let T=y?[...o,`let sum = ${u.map((S,O)=>S.getByIndices(`input${O}Indices`)).join(" * ")};`]:[...o,p,...g,...m,a,...w,h,..._];return` + ${r.registerUniforms(c.map(S=>({name:`${_u(S)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...u,d)} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} @@ -3217,7 +3217,7 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { ${T.join(` `)}; ${d.setByOffset("global_idx","sum")}; - }`};return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let r=c.filter(a=>n.symbolToInfo.has(a)).map(a=>({type:12,data:n.symbolToInfo.get(a)?.dimValue||0}));r.push({type:12,data:l});let o=e.map((a,p)=>[...ue(a)]).reduce((a,p)=>a.concat(p),r);return o.push(...ue(i)),{outputs:[{dims:i,dataType:t}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:o}},getShaderSource:s}},p2=(e,t)=>{let n=new $b(e.inputs,t.equation),i=n.outputDims,u=e.inputs.map((l,d)=>l.dims);e.compute(Tb(u,e.inputs[0].dataType,n,i))},h2=e=>{let t=e.equation.replace(/\s+/g,"");return ke({equation:t})}}),Sb,yu,Ib,Ob,f2,gk=D(()=>{"use strict";de(),pe(),he(),Sb=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=n.length{let n=e.length-t.length,i=[];for(let u=0;ue.length>t.length?yu(e,t):yu(t,e),Ob=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=Ib(t,n),u=e[0].dataType,l=u===9||F.size(t)===1,d=u===9||t.length>0&&t[t.length-1]%4===0?4:1,c=l||i.length>0&&i[i.length-1]%4===0?4:1,s=Math.ceil(F.size(i)/c),r=a=>{let p=j("input",u,t.length,d),h=oe("output",u,i.length,c),m;if(u===9){let g=(_,w,y="")=>` + }`};return{name:"Einsum",shaderCache:{hint:n.equation,inputDependencies:e.map(()=>"rank")},getRunData:()=>{let r=c.filter(a=>n.symbolToInfo.has(a)).map(a=>({type:12,data:n.symbolToInfo.get(a)?.dimValue||0}));r.push({type:12,data:l});let o=e.map((a,p)=>[...ue(a)]).reduce((a,p)=>a.concat(p),r);return o.push(...ue(i)),{outputs:[{dims:i,dataType:t}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:o}},getShaderSource:s}},b2=(e,t)=>{let n=new Eb(e.inputs,t.equation),i=n.outputDims,u=e.inputs.map((l,d)=>l.dims);e.compute(Ab(u,e.inputs[0].dataType,n,i))},y2=e=>{let t=e.equation.replace(/\s+/g,"");return ke({equation:t})}}),kb,vu,Pb,Cb,w2,$k=D(()=>{"use strict";de(),pe(),he(),kb=e=>{if(!e||e.length!==2)throw new Error("Expand requires 2 input.");let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=n.length{let n=e.length-t.length,i=[];for(let u=0;ue.length>t.length?vu(e,t):vu(t,e),Cb=e=>{let t=e[0].dims,n=Array.from(e[1].getBigInt64Array(),Number),i=Pb(t,n),u=e[0].dataType,l=u===9||F.size(t)===1,d=u===9||t.length>0&&t[t.length-1]%4===0?4:1,c=l||i.length>0&&i[i.length-1]%4===0?4:1,s=Math.ceil(F.size(i)/c),r=a=>{let p=j("input",u,t.length,d),h=oe("output",u,i.length,c),m;if(u===9){let g=(_,w,y="")=>` let outputIndices${w} = ${h.offsetToIndices(`outputOffset + ${w}u`)}; let offset${w} = ${p.broadcastedIndicesToOffset(`outputIndices${w}`,h)}; let index${w} = offset${w} / 4u; @@ -3240,13 +3240,13 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { ${a.registerUniform("vec_size","u32").declareVariables(p,h)} ${a.mainStart()} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} - ${m}`},o=[{type:12,data:s},...ue(t,i)];return{name:"Expand",shaderCache:{hint:`${i.length};${d}${c}`,inputDependencies:["rank"]},getShaderSource:r,getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:o})}},f2=e=>{Sb(e.inputs),e.compute(Ob(e.inputs),{inputs:[0]})}}),Eb,m2,bk=D(()=>{"use strict";de(),pe(),he(),fd(),Eb=e=>{let t=e[0].dataType,n=F.size(e[0].dims),i=F.size(e[1].dims),u=i%4===0,l=d=>{let c=j("x",t,[1],4),s=j("bias",t,[1],4),r=oe("y",t,[1],4),o=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],a=h=>` + ${m}`},o=[{type:12,data:s},...ue(t,i)];return{name:"Expand",shaderCache:{hint:`${i.length};${d}${c}`,inputDependencies:["rank"]},getShaderSource:r,getRunData:()=>({outputs:[{dims:i,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:o})}},w2=e=>{kb(e.inputs),e.compute(Cb(e.inputs),{inputs:[0]})}}),Rb,_2,Tk=D(()=>{"use strict";de(),pe(),he(),bd(),Rb=e=>{let t=e[0].dataType,n=F.size(e[0].dims),i=F.size(e[1].dims),u=i%4===0,l=d=>{let c=j("x",t,[1],4),s=j("bias",t,[1],4),r=oe("y",t,[1],4),o=[{name:"output_vec_size",type:"u32"},{name:"bias_size",type:"u32"}],a=h=>` let bias${h}_offset: u32 = (global_idx * 4 + ${h}) % uniforms.bias_size; let bias${h} = ${s.getByOffset(`bias${h}_offset / 4`)}[bias${h}_offset % 4];`,p=u?` let bias = ${s.getByOffset("global_idx % (uniforms.bias_size / 4)")};`:`${a(0)}${a(1)}${a(2)}${a(3)} let bias = ${c.type.value}(bias0, bias1, bias2, bias3);`;return`${d.registerUniforms(o).declareVariables(c,s,r)} - ${Ml(rt(t))} + ${Bl(rt(t))} ${d.mainStart(Fn)} ${d.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_vec_size")} @@ -3254,8 +3254,8 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { let x = ${c.getByOffset("global_idx")}; ${p} let x_in = x + bias; - ${r.setByOffset("global_idx",Nl("x_in"))} - }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${u}`,inputDependencies:["type","type"]},getShaderSource:l,getRunData:d=>({outputs:[{dims:d[0].dims,dataType:d[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:i}],dispatchGroup:{x:Math.ceil(n/Fn/4)}})}},m2=e=>{e.inputs.length<2||F.size(e.inputs[1].dims)===0?R1(e):e.compute(Eb(e.inputs))}}),Ab,kb,g2,b2,yk=D(()=>{"use strict";de(),pe(),He(),he(),Ab=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},kb=(e,t)=>{let n=e[0].dims,i=e[1].dims,u=n.length,l=F.normalizeAxis(t.axis,u),d=n.slice(0);d.splice(l,1,...i);let c=n[l],s=e[0].dataType===9?4:1,r=Math.ceil(F.size(d)/s),o=[{type:12,data:r},{type:6,data:c},{type:12,data:l},...ue(e[0].dims,e[1].dims,d)],a=p=>{let h=j("data",e[0].dataType,e[0].dims.length,s),m=j("inputIndices",e[1].dataType,e[1].dims.length),g=oe("output",e[0].dataType,d.length,s),_=y=>{let T=i.length,S=`var indicesIndices${y} = ${m.type.indices}(0);`;for(let O=0;O1?`indicesIndices${y}[${O}]`:`indicesIndices${y}`} = ${d.length>1?`outputIndices${y}[uniforms.axis + ${O}]`:`outputIndices${y}`};`;S+=` + ${r.setByOffset("global_idx",Fl("x_in"))} + }`};return{name:"FastGeluWithBias",shaderCache:{hint:`${u}`,inputDependencies:["type","type"]},getShaderSource:l,getRunData:d=>({outputs:[{dims:d[0].dims,dataType:d[0].dataType}],programUniforms:[{type:12,data:Math.ceil(n/4)},{type:12,data:i}],dispatchGroup:{x:Math.ceil(n/Fn/4)}})}},_2=e=>{e.inputs.length<2||F.size(e.inputs[1].dims)===0?B1(e):e.compute(Rb(e.inputs))}}),Db,Mb,v2,x2,Sk=D(()=>{"use strict";de(),pe(),He(),he(),Db=e=>{if(!e||e.length!==2)throw new Error("Gather requires 2 inputs.")},Mb=(e,t)=>{let n=e[0].dims,i=e[1].dims,u=n.length,l=F.normalizeAxis(t.axis,u),d=n.slice(0);d.splice(l,1,...i);let c=n[l],s=e[0].dataType===9?4:1,r=Math.ceil(F.size(d)/s),o=[{type:12,data:r},{type:6,data:c},{type:12,data:l},...ue(e[0].dims,e[1].dims,d)],a=p=>{let h=j("data",e[0].dataType,e[0].dims.length,s),m=j("inputIndices",e[1].dataType,e[1].dims.length),g=oe("output",e[0].dataType,d.length,s),_=y=>{let T=i.length,S=`var indicesIndices${y} = ${m.type.indices}(0);`;for(let O=0;O1?`indicesIndices${y}[${O}]`:`indicesIndices${y}`} = ${d.length>1?`outputIndices${y}[uniforms.axis + ${O}]`:`outputIndices${y}`};`;S+=` var idx${y} = ${m.getByIndices(`indicesIndices${y}`)}; if (idx${y} < 0) { idx${y} = idx${y} + uniforms.axisDimLimit; @@ -3286,7 +3286,7 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} ${w} - }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:o}),getShaderSource:a}},g2=e=>ke({axis:e.axis}),b2=(e,t)=>{let n=e.inputs;Ab(n),e.compute(kb(e.inputs,t))}}),Pb,y2,w2,wk=D(()=>{"use strict";de(),pe(),he(),Pb=(e,t,n,i,u,l,d,c,s)=>{let r=[{type:12,data:l},{type:12,data:i},{type:12,data:u},{type:12,data:n},{type:12,data:d},{type:12,data:c},{type:12,data:s}],o=[l];r.push(...ue(t.dims,o));let a=p=>{let h=j("indices_data",t.dataType,t.dims.length),m=oe("input_slice_offsets_data",12,1,1),g=[h,m],_=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:u.length},{name:"sizes_from_slice_dims_data",type:"u32",length:n.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` + }`};return{name:"Gather",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:d,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:o}),getShaderSource:a}},v2=e=>ke({axis:e.axis}),x2=(e,t)=>{let n=e.inputs;Db(n),e.compute(Mb(e.inputs,t))}}),Nb,$2,T2,Ik=D(()=>{"use strict";de(),pe(),he(),Nb=(e,t,n,i,u,l,d,c,s)=>{let r=[{type:12,data:l},{type:12,data:i},{type:12,data:u},{type:12,data:n},{type:12,data:d},{type:12,data:c},{type:12,data:s}],o=[l];r.push(...ue(t.dims,o));let a=p=>{let h=j("indices_data",t.dataType,t.dims.length),m=oe("input_slice_offsets_data",12,1,1),g=[h,m],_=[{name:"output_size",type:"u32"},{name:"batch_dims",type:"u32"},{name:"input_dims",type:"u32",length:u.length},{name:"sizes_from_slice_dims_data",type:"u32",length:n.length},{name:"num_slices_per_batch",type:"u32"},{name:"input_batch_stride",type:"u32"},{name:"num_slice_dims",type:"u32"}];return` ${p.registerUniforms(_).declareVariables(...g)} ${p.mainStart()} ${p.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -3305,13 +3305,13 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { } input_slice_offsets_data[global_idx] = base_offset + u32(relative_slice_offset); - }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${u.length}_${n.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:r}),getShaderSource:a},{inputs:[t],outputs:[-1]})[0]},y2=(e,t)=>{let n=e.inputs,i=n[0].dims,u=n[0].dataType,l=n[1].dims,d=l[l.length-1],c=F.sizeToDimension(l,l.length-1),s=F.sizeFromDimension(i,t.batchDims+d),r=F.sizeToDimension(i,t.batchDims),o=F.sizeFromDimension(i,t.batchDims),a=c/r,p=new Array(d),h=s;for(let S=0;Si.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let _=l.slice(0,-1).concat(i.slice(g)),w=F.size(_),y=[{type:12,data:w},{type:12,data:s},...ue(n[0].dims,m.dims,_)],T=S=>{let O=j("data",n[0].dataType,n[0].dims.length),A=j("slice_offsets",12,m.dims.length),P=oe("output",n[0].dataType,_.length);return` + }`};return e.compute({name:"computeSliceOffsets",shaderCache:{hint:`${u.length}_${n.length}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:o,dataType:e.inputs[1].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:r}),getShaderSource:a},{inputs:[t],outputs:[-1]})[0]},$2=(e,t)=>{let n=e.inputs,i=n[0].dims,u=n[0].dataType,l=n[1].dims,d=l[l.length-1],c=F.sizeToDimension(l,l.length-1),s=F.sizeFromDimension(i,t.batchDims+d),r=F.sizeToDimension(i,t.batchDims),o=F.sizeFromDimension(i,t.batchDims),a=c/r,p=new Array(d),h=s;for(let S=0;Si.length)throw new Error("last dimension of indices must not be larger than rank of input tensor");let _=l.slice(0,-1).concat(i.slice(g)),w=F.size(_),y=[{type:12,data:w},{type:12,data:s},...ue(n[0].dims,m.dims,_)],T=S=>{let O=j("data",n[0].dataType,n[0].dims.length),A=j("slice_offsets",12,m.dims.length),P=oe("output",n[0].dataType,_.length);return` ${S.registerUniform("output_size","u32").registerUniform("slice_size","u32").declareVariables(O,A,P)} ${S.mainStart()} ${S.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let slice_offset = slice_offsets[global_idx / uniforms.slice_size]; output[global_idx] = data[u32(slice_offset) + global_idx % uniforms.slice_size]; - }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:_,dataType:u}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:y}),getShaderSource:T},{inputs:[n[0],m]})},w2=e=>({batchDims:e.batch_dims,cacheKey:""})}),Cb,Rb,_2,v2,_k=D(()=>{"use strict";de(),pe(),He(),he(),Cb=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let n=F.normalizeAxis(t.quantizeAxis,e[0].dims.length),i=t.blockSize,u=e[0],l=e[2],d=e.length===4?e[3]:void 0;if(l.dims.length!==u.dims.length||!u.dims.map((c,s)=>s===n?Math.ceil(c/i)===l.dims[s]:c===l.dims[s]).reduce((c,s)=>c&&s,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(d){if(d.dataType!==u.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(d.dims.length!==l.dims.length||!d.dims.map((c,s)=>c===l.dims[s]).reduce((c,s)=>c&&s,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Rb=(e,t)=>{let n=e[0].dims,i=e[1].dims,u=n.length,l=F.normalizeAxis(t.gatherAxis,u),d=F.normalizeAxis(t.quantizeAxis,u),c=n.slice(0);c.splice(l,1,...i);let s=F.size(c),r=e[2].dataType,o=e[0].dataType===22,a=[{type:12,data:s},{type:12,data:d},{type:12,data:l},{type:12,data:t.blockSize},...ue(...e.map((h,m)=>h.dims),c)],p=h=>{let m=j("data",e[0].dataType,e[0].dims.length),g=j("inputIndices",e[1].dataType,e[1].dims.length),_=j("scales",e[2].dataType,e[2].dims.length),w=e.length>3?j("zeroPoint",e[3].dataType,e[3].dims.length):void 0,y=oe("output",r,c.length),T=[m,g,_];w&&T.push(w);let S=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` + }`};e.compute({name:"GatherND",shaderCache:{hint:t.cacheKey,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:_,dataType:u}],dispatchGroup:{x:Math.ceil(w/64)},programUniforms:y}),getShaderSource:T},{inputs:[n[0],m]})},T2=e=>({batchDims:e.batch_dims,cacheKey:""})}),zb,Bb,S2,I2,Ok=D(()=>{"use strict";de(),pe(),He(),he(),zb=(e,t)=>{if(e.length<3||e.length>4)throw new Error("GatherBlockQuantized requires 3 or 4 inputs.");let n=F.normalizeAxis(t.quantizeAxis,e[0].dims.length),i=t.blockSize,u=e[0],l=e[2],d=e.length===4?e[3]:void 0;if(l.dims.length!==u.dims.length||!u.dims.map((c,s)=>s===n?Math.ceil(c/i)===l.dims[s]:c===l.dims[s]).reduce((c,s)=>c&&s,!0))throw new Error("Scales must have the same rank as the input tensor and the dims should match except on gatherAxis.");if(d){if(d.dataType!==u.dataType)throw new Error("Zero point must have the same data type as the input tensor.");if(d.dims.length!==l.dims.length||!d.dims.map((c,s)=>c===l.dims[s]).reduce((c,s)=>c&&s,!0))throw new Error("Zero point must have the same rank as the input tensor and the dims should match except on quantizeAxis.")}},Bb=(e,t)=>{let n=e[0].dims,i=e[1].dims,u=n.length,l=F.normalizeAxis(t.gatherAxis,u),d=F.normalizeAxis(t.quantizeAxis,u),c=n.slice(0);c.splice(l,1,...i);let s=F.size(c),r=e[2].dataType,o=e[0].dataType===22,a=[{type:12,data:s},{type:12,data:d},{type:12,data:l},{type:12,data:t.blockSize},...ue(...e.map((h,m)=>h.dims),c)],p=h=>{let m=j("data",e[0].dataType,e[0].dims.length),g=j("inputIndices",e[1].dataType,e[1].dims.length),_=j("scales",e[2].dataType,e[2].dims.length),w=e.length>3?j("zeroPoint",e[3].dataType,e[3].dims.length):void 0,y=oe("output",r,c.length),T=[m,g,_];w&&T.push(w);let S=[{name:"output_size",type:"u32"},{name:"quantize_axis",type:"u32"},{name:"gather_axis",type:"u32"},{name:"block_size",type:"u32"}];return` ${h.registerUniforms(S).declareVariables(...T,y)} ${h.mainStart()} let output_indices = ${y.offsetToIndices("global_idx")}; @@ -3356,8 +3356,8 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { let zero_point = zero_point_vec[zero_point_index / 2];`:"var zero_point = 0"}; let dequantized_data = ${rt(r)}(quantized_data - zero_point) * scale; ${y.setByOffset("global_idx","dequantized_data")}; - }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((h,m)=>m!==1).map(h=>h.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(h,m)=>"rank")},getRunData:()=>({outputs:[{dims:c,dataType:r}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:a}),getShaderSource:p}},_2=(e,t)=>{let n=e.inputs;Cb(n,t),e.compute(Rb(e.inputs,t))},v2=e=>ke({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Db,Mb,x2,$2,vk=D(()=>{"use strict";de(),pe(),He(),he(),Db=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and - indices input tensors be of same rank.`)},Mb=(e,t)=>{let n=e[0].dims,i=e[0].dataType,u=n.length,l=e[1].dims,d=e[1].dataType,c=F.normalizeAxis(t.axis,u),s=n[c],r=l.slice(0),o=F.size(r),a=j("input",i,u),p=j("indicesInput",d,l.length),h=oe("output",i,r.length),m=[{type:12,data:o},{type:6,data:s},{type:12,data:c}];return m.push(...ue(n,l,r)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:g=>` + }`};return{name:"GatherBlockQuantized",shaderCache:{hint:`${t.cacheKey};${e.filter((h,m)=>m!==1).map(h=>h.dims.join("_")).join(";")}`,inputDependencies:Array.from({length:e.length},(h,m)=>"rank")},getRunData:()=>({outputs:[{dims:c,dataType:r}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:a}),getShaderSource:p}},S2=(e,t)=>{let n=e.inputs;zb(n,t),e.compute(Bb(e.inputs,t))},I2=e=>ke({blockSize:e.blockSize,gatherAxis:e.gatherAxis,quantizeAxis:e.quantizeAxis})}),Fb,Lb,O2,E2,Ek=D(()=>{"use strict";de(),pe(),He(),he(),Fb=e=>{if(!e||e.length!==2)throw new Error("GatherElements requires 2 inputs.");if(e[0].dims.length<1)throw new Error("GatherElements requires that the data input be rank >= 1.");if(e[0].dims.length!==e[1].dims.length)throw new Error(`GatherElements requires that the data input and + indices input tensors be of same rank.`)},Lb=(e,t)=>{let n=e[0].dims,i=e[0].dataType,u=n.length,l=e[1].dims,d=e[1].dataType,c=F.normalizeAxis(t.axis,u),s=n[c],r=l.slice(0),o=F.size(r),a=j("input",i,u),p=j("indicesInput",d,l.length),h=oe("output",i,r.length),m=[{type:12,data:o},{type:6,data:s},{type:12,data:c}];return m.push(...ue(n,l,r)),{name:"GatherElements",shaderCache:{inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:r,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:m}),getShaderSource:g=>` ${g.registerUniform("outputSize","u32").registerUniform("axisDimLimit","i32").registerUniform("axis","u32").declareVariables(a,p,h)} ${g.mainStart()} ${g.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} @@ -3373,8 +3373,8 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { let value = ${a.getByIndices("inputIndices")}; ${h.setByOffset("global_idx","value")}; - }`}},x2=e=>ke({axis:e.axis}),$2=(e,t)=>{let n=e.inputs;Db(n),e.compute(Mb(e.inputs,t))}}),Nb,zb,T2,S2,xk=D(()=>{"use strict";de(),pe(),he(),Nb=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},zb=(e,t)=>{let n=e[0].dims.slice(),i=e[1].dims.slice(),[u,l,d]=wx.getShapeOfGemmResult(n,t.transA,i,t.transB,e.length===3?e[2].dims:void 0),c=[u,l];if(!c)throw new Error("Can't use gemm on the given tensors");let s=16,r=Math.ceil(l/s),o=Math.ceil(u/s),a=!0,p=F.size(c),h=[{type:12,data:a?r:p},{type:12,data:u},{type:12,data:l},{type:12,data:d},{type:1,data:t.alpha},{type:1,data:t.beta}],m=["type","type"];e.length===3&&(h.push(...ue(e[2].dims)),m.push("rank")),h.push(...ue(c));let g=w=>{let y="";t.transA&&t.transB?y="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?y="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?y="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(y="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let T=t.alpha===1?"":"value *= uniforms.alpha;",S=j("a",e[0].dataType,e[0].dims),O=j("b",e[1].dataType,e[1].dims),A=S.type.value,P=null,I=[S,O];e.length===3&&(P=j("c",e[2].dataType,e[2].dims.length),I.push(P));let z=oe("output",e[0].dataType,c.length);I.push(z);let G=[{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` - ${w.registerUniforms(G).declareVariables(...I)} + }`}},O2=e=>ke({axis:e.axis}),E2=(e,t)=>{let n=e.inputs;Fb(n),e.compute(Lb(e.inputs,t))}}),jb,Ub,A2,k2,Ak=D(()=>{"use strict";de(),pe(),he(),jb=e=>{if(!e)throw new Error("Input is missing");if(e.length<2||e.length>3)throw new Error("Invaid input number.");if(e.length===3&&e[2].dims.length>2)throw new Error("Invalid input shape of C");if(e[0].dataType!==e[1].dataType||e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("Input types are mismatched")},Ub=(e,t)=>{let n=e[0].dims.slice(),i=e[1].dims.slice(),[u,l,d]=Tx.getShapeOfGemmResult(n,t.transA,i,t.transB,e.length===3?e[2].dims:void 0),c=[u,l];if(!c)throw new Error("Can't use gemm on the given tensors");let s=16,r=Math.ceil(l/s),o=Math.ceil(u/s),a=!0,p=F.size(c),h=[{type:12,data:a?r:p},{type:12,data:u},{type:12,data:l},{type:12,data:d},{type:1,data:t.alpha},{type:1,data:t.beta}],m=["type","type"];e.length===3&&(h.push(...ue(e[2].dims)),m.push("rank")),h.push(...ue(c));let g=w=>{let y="";t.transA&&t.transB?y="value += a[k * uniforms.M + m] * b[n * uniforms.K + k];":t.transA&&!t.transB?y="value += a[k * uniforms.M + m] * b[k * uniforms.N + n];":!t.transA&&t.transB?y="value += a[m * uniforms.K + k] * b[n * uniforms.K + k];":!t.transA&&!t.transB&&(y="value += a[m * uniforms.K + k] * b[k * uniforms.N + n];");let T=t.alpha===1?"":"value *= uniforms.alpha;",S=j("a",e[0].dataType,e[0].dims),O=j("b",e[1].dataType,e[1].dims),A=S.type.value,P=null,I=[S,O];e.length===3&&(P=j("c",e[2].dataType,e[2].dims.length),I.push(P));let z=oe("output",e[0].dataType,c.length);I.push(z);let q=[{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` + ${w.registerUniforms(q).declareVariables(...I)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -3454,7 +3454,7 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { } else { tile_b[local_id.y][local_id.x] = ${T.type.value}(0); } - `,I="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let G=t.alpha===1?"":"value *= uniforms.alpha;";return` + `,I="value += tile_a[local_id.y][k] * tile_b[k][local_id.x];");let q=t.alpha===1?"":"value *= uniforms.alpha;";return` ${w.registerUniforms(P).declareVariables(...O)} var tile_a: array, ${s}>; var tile_b: array, ${s}>; @@ -3475,14 +3475,14 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { workgroupBarrier(); } - ${G} + ${q} let m = tile_row_start + local_id.y; let n = tile_col_start + local_id.x; ${S!=null?`let cOffset = ${S.broadcastedIndicesToOffset("vec2(m, n)",A)}; value += ${A.type.value}(uniforms.beta) * ${S.getByOffset("cOffset")};`:""} if (m < uniforms.M && n < uniforms.N) { output[m * uniforms.N + n] = value; } - }`};return a?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:r*o},programUniforms:h}),getShaderSource:_}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:g}},T2=e=>{let t=e.transA,n=e.transB,i=e.alpha,u=e.beta;return{transA:t,transB:n,alpha:i,beta:u,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},S2=(e,t)=>{Nb(e.inputs),e.compute(zb(e.inputs,t))}}),Xt,or,Gr,Hr,Bb,Fb,Lb,jb,Ub,Vb,qb,Gb,I2,O2,$k=D(()=>{"use strict";de(),pe(),He(),he(),[Xt,or,Gr,Hr]=[0,1,2,3],Bb=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},Fb=` + }`};return a?{name:"GemmShared",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:r*o},programUniforms:h}),getShaderSource:_}:{name:"Gemm",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:c,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:h}),getShaderSource:g}},A2=e=>{let t=e.transA,n=e.transB,i=e.alpha,u=e.beta;return{transA:t,transB:n,alpha:i,beta:u,cacheKey:`${e.transA};${e.transB};${e.alpha===1}`}},k2=(e,t)=>{jb(e.inputs),e.compute(Ub(e.inputs,t))}}),Xt,or,qr,Hr,Vb,Gb,qb,Hb,Wb,Kb,Xb,Zb,P2,C2,kk=D(()=>{"use strict";de(),pe(),He(),he(),[Xt,or,qr,Hr]=[0,1,2,3],Vb=e=>{if(e[0].dims.length!==4)throw new Error("only 4-D tensor is supported.");if(e[0].dims.length!==e[1].dims.length)throw new Error("input dimensions must be equal to grid dimensions");if(e[0].dims.length-2!==e[1].dims[e[1].dims.length-1])throw new Error(`last dimension of grid must be equal to ${e[0].dims.length-2}`);if(e[0].dims[0]!==e[1].dims[0])throw new Error("grid batch size must match input batch size")},Gb=` fn gs_get_cubic_coeffs(x: f32) -> vec4 { let cubic_alpha = -0.75f; let x_abs = abs(x); @@ -3493,7 +3493,7 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { coeffs[3] = (((cubic_alpha * (2 - x_abs) - 5 * cubic_alpha) * (2 - x_abs) + 8 * cubic_alpha) * (2 - x_abs) - 4 * cubic_alpha); return coeffs; } -`,Lb=e=>` +`,qb=e=>` fn gs_bicubic_interpolate(p: mat4x4<${e}>, x: f32, y: f32) -> ${e} { var v: vec4; var coeffs = gs_get_cubic_coeffs(x); @@ -3504,7 +3504,7 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { let pixel = ${e}(coeffs[0] * v[0] + coeffs[1] * v[1] + coeffs[2] * v[2] + coeffs[3] * v[3]); return pixel; } -`,jb=e=>` +`,Hb=e=>` fn gs_denormalize(n: f32, length: i32) -> f32 { ${e.alignCorners===0?` // alignCorners: false => [-1, 1] to [-0.5, length - 0.5] @@ -3514,7 +3514,7 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { return (n + 1.0) / 2.0 * (f32(length - 1)); `} } -`,Ub=e=>` +`,Wb=e=>` ${e.paddingMode==="reflection"?` fn gs_reflect(x: i32, x_min: f32, x_max: f32) -> u32 { var dx = 0.0; @@ -3541,28 +3541,28 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { } return u32(fx); }`:""} -`,Vb=(e,t,n)=>` +`,Kb=(e,t,n)=>` fn pixel_at_grid(r: i32, c: i32, H: i32, W: i32, batch: u32, channel: u32, border: vec4) -> ${t} { var pixel = ${t}(0); var indices = vec4(0); indices[${Xt}] = batch; indices[${or}] = channel;`+(()=>{switch(n.paddingMode){case"zeros":return` if (r >= 0 && r < H && c >=0 && c < W) { - indices[${Gr}] = u32(r); + indices[${qr}] = u32(r); indices[${Hr}] = u32(c); } else { return ${t}(0); } `;case"border":return` - indices[${Gr}] = u32(clamp(r, 0, H - 1)); + indices[${qr}] = u32(clamp(r, 0, H - 1)); indices[${Hr}] = u32(clamp(c, 0, W - 1)); `;case"reflection":return` - indices[${Gr}] = gs_reflect(r, border[1], border[3]); + indices[${qr}] = gs_reflect(r, border[1], border[3]); indices[${Hr}] = gs_reflect(c, border[0], border[2]); `;default:throw new Error(`padding mode ${n.paddingMode} is not supported`)}})()+` return ${e.getByIndices("indices")}; } -`,qb=(e,t,n)=>(()=>{switch(n.mode){case"nearest":return` +`,Xb=(e,t,n)=>(()=>{switch(n.mode){case"nearest":return` let result = pixel_at_grid(i32(round(y)), i32(round(x)), H_in, W_in, indices[${Xt}], indices[${or}], border); `;case"bilinear":return` let x1 = i32(floor(x)); @@ -3593,17 +3593,17 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { let dx = x - f32(x0 + 1); let dy = y - f32(y0 + 1); let result = gs_bicubic_interpolate(p, dx, dy); - `;default:throw new Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Gb=(e,t)=>{let n=j("x",e[0].dataType,e[0].dims.length),i=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],u=j("grid",e[1].dataType,i.length,2),l=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(l=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Xt,or,Gr,Hr]=[0,3,1,2]);let d=oe("output",e[0].dataType,l.length),c=n.type.value,s=F.size(l),r=[{type:12,data:s},...ue(e[0].dims,i,l)],o=a=>` + `;default:throw new Error(`mode ${n.mode} is not supported`)}})()+`${e.setByOffset("global_idx","result")}`,Zb=(e,t)=>{let n=j("x",e[0].dataType,e[0].dims.length),i=[e[1].dims[0],e[1].dims[1],e[1].dims[2]],u=j("grid",e[1].dataType,i.length,2),l=[e[0].dims[0],e[0].dims[1],e[1].dims[1],e[1].dims[2]];t.format==="NHWC"&&(l=[e[0].dims[0],e[1].dims[1],e[1].dims[2],e[0].dims[3]],[Xt,or,qr,Hr]=[0,3,1,2]);let d=oe("output",e[0].dataType,l.length),c=n.type.value,s=F.size(l),r=[{type:12,data:s},...ue(e[0].dims,i,l)],o=a=>` ${a.registerUniform("output_size","u32").declareVariables(n,u,d)} - ${Fb} - ${Lb(c)} - ${jb(t)} - ${Ub(t)} - ${Vb(n,c,t)} + ${Gb} + ${qb(c)} + ${Hb(t)} + ${Wb(t)} + ${Kb(n,c,t)} ${a.mainStart()} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} - let H_in = i32(uniforms.x_shape[${Gr}]); + let H_in = i32(uniforms.x_shape[${qr}]); let W_in = i32(uniforms.x_shape[${Hr}]); ${t.alignCorners===0?` @@ -3620,20 +3620,20 @@ ${w} for (var i = local_idx; i < uniforms.outputLength; i += ${ir}u) { let border = vec4(x_min, y_min, x_max, y_max); let indices = ${d.offsetToIndices("global_idx")}; - var grid_indices = vec3(indices[${Xt}], indices[${Gr}], indices[${Hr}]); + var grid_indices = vec3(indices[${Xt}], indices[${qr}], indices[${Hr}]); let nxy = ${u.getByIndices("grid_indices")}; var x = gs_denormalize(f32(nxy[0]), W_in); var y = gs_denormalize(f32(nxy[1]), H_in); - ${qb(d,c,t)} - }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:a=>{let p=F.size(l);return{outputs:[{dims:l,dataType:a[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:r}},getShaderSource:o}},I2=(e,t)=>{Bb(e.inputs),e.compute(Gb(e.inputs,t))},O2=e=>ke({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),ct,Hb,E2,wu,Wb,Ii,A2,k2=D(()=>{"use strict";de(),pe(),He(),dd(),hd(),he(),Cr(),ct=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Hb=(e,t)=>{let n=e[0],i=ct(e,1),u=ct(e,2),l=ct(e,3),d=ct(e,4),c=ct(e,5),s=ct(e,6),r=ct(e,7);if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let o=n.dims[0],a=n.dims[1],p=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],h=a,m=0,g=0,_=Math.floor(p/t.numHeads);if(s&&r&&F.size(s.dims)&&F.size(r.dims)){if(s.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(s.dims[0]!==o||s.dims[1]!==t.numHeads||s.dims[3]!==_)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(r.dims[0]!==o||r.dims[1]!==t.numHeads||r.dims[3]!==_)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(s.dims[2]!==r.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(r.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');m=s.dims[2],g=s.dims[2]}else if(s&&F.size(s.dims)||r&&F.size(r.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(i&&F.size(i.dims)>0){if(n.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(i.dims.length<3||i.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(i.dims.length===3){if(i.dims[2]!==n.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');w=2,h=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(u)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,h=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,h=i.dims[2]}}else{if(n.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(n.dims[2]!==t.numHeads||n.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}if(l&&F.size(l.dims)>0){if(l.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(i&&i.dims.length===5&&i.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let y=m+h,T=0;if(d&&F.size(d.dims)>0){T=8;let P=d.dims;throw P.length===1?P[0]===o?T=1:P[0]===3*o+2&&(T=3):P.length===2&&P[0]===o&&P[1]===y&&(T=5),T===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let S=!1,O=p;if(u&&F.size(u.dims)>0){if(u.dims.length!==3&&u.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==u.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(u.dims.length===3){if(h!==u.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');O=u.dims[2]}else{if(h!==u.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');O=u.dims[1]*u.dims[3],S=!0}}let A=!1;if(d&&F.size(d.dims)>0)throw new Error("Key padding mask is not supported");if(c&&F.size(c.dims)>0){if(c.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(c.dims[0]!==o||c.dims[1]!==t.numHeads||c.dims[2]!==a||c.dims[3]!==y)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:o,sequenceLength:a,pastSequenceLength:m,kvSequenceLength:h,totalSequenceLength:y,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:p,vHiddenSize:O,headSize:_,vHeadSize:Math.floor(O/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:T,scale:t.scale,broadcastResPosBias:A,passPastInKv:S,qkvFormat:w}},E2=e=>ke({...e}),wu=ke({perm:[0,2,1,3]}),Wb=(e,t,n,i,u,l,d)=>{let c=[i,u,l],s=F.size(c),r=[{type:12,data:s},{type:12,data:d},{type:12,data:l}],o=a=>{let p=oe("qkv_with_bias",t.dataType,c),h=j("qkv",t.dataType,c),m=j("bias",n.dataType,c),g=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` + ${Xb(d,c,t)} + }`;return{name:"GridSample",shaderCache:{hint:`${t.cacheKey}`,inputDependencies:["type","type"]},getRunData:a=>{let p=F.size(l);return{outputs:[{dims:l,dataType:a[0].dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:r}},getShaderSource:o}},P2=(e,t)=>{Vb(e.inputs),e.compute(Zb(e.inputs,t))},C2=e=>ke({alignCorners:e.align_corners,mode:e.mode,paddingMode:e.padding_mode,format:e.format})}),ct,Yb,R2,xu,Jb,Ei,D2,M2=D(()=>{"use strict";de(),pe(),He(),hd(),gd(),he(),Cr(),ct=(e,t)=>e.length>t&&e[t].dims.length>0?e[t]:void 0,Yb=(e,t)=>{let n=e[0],i=ct(e,1),u=ct(e,2),l=ct(e,3),d=ct(e,4),c=ct(e,5),s=ct(e,6),r=ct(e,7);if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let o=n.dims[0],a=n.dims[1],p=n.dims.length===3?n.dims[2]:t.numHeads*n.dims[4],h=a,m=0,g=0,_=Math.floor(p/t.numHeads);if(s&&r&&F.size(s.dims)&&F.size(r.dims)){if(s.dims.length!==4)throw new Error('Input "past_key" is expected to have 4 dimensions');if(s.dims[0]!==o||s.dims[1]!==t.numHeads||s.dims[3]!==_)throw new Error('Input "past_key" shape (batch_size, num_heads, past_sequence_length, head_size)');if(r.dims[0]!==o||r.dims[1]!==t.numHeads||r.dims[3]!==_)throw new Error('Input "past_value" shape (batch_size, num_heads, past_sequence_length, head_size)');if(s.dims[2]!==r.dims[2])throw new Error('Input "past_key" and "past_value" shall have same dim 2 (past_sequence_length)');if(r.dims.length!==4)throw new Error('Input "past_value" is expected to have 4 dimensions');m=s.dims[2],g=s.dims[2]}else if(s&&F.size(s.dims)||r&&F.size(r.dims))throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w;if(i&&F.size(i.dims)>0){if(n.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(i.dims.length<3||i.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(i.dims.length===3){if(i.dims[2]!==n.dims[2])throw new Error('Input "query" and "key" shall have same dim 2 (hidden_size)');w=2,h=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==_)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(u)throw new Error('Expect "value" be none when "key" has packed kv format.');w=5,h=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==_)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');w=0,h=i.dims[2]}}else{if(n.dims.length!==5)throw new Error('Input "query" is expected to have 5 dimensions when key is empty');if(n.dims[2]!==t.numHeads||n.dims[3]!==3)throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}if(l&&F.size(l.dims)>0){if(l.dims.length!==1)throw new Error('Input "bias" is expected to have 1 dimension');if(i&&i.dims.length===5&&i.dims[3]===2)throw new Error("bias is not allowed for packed kv.")}let y=m+h,T=0;if(d&&F.size(d.dims)>0){T=8;let P=d.dims;throw P.length===1?P[0]===o?T=1:P[0]===3*o+2&&(T=3):P.length===2&&P[0]===o&&P[1]===y&&(T=5),T===8?new Error('Input "key_padding_mask" shape shall be (batch_size) or (batch_size, total_sequence_length)'):new Error("Mask not supported")}let S=!1,O=p;if(u&&F.size(u.dims)>0){if(u.dims.length!==3&&u.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==u.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(u.dims.length===3){if(h!==u.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');O=u.dims[2]}else{if(h!==u.dims[2])throw new Error('Input "key" and "value" shall have the same dim 2 (kv_sequence_length)');O=u.dims[1]*u.dims[3],S=!0}}let A=!1;if(d&&F.size(d.dims)>0)throw new Error("Key padding mask is not supported");if(c&&F.size(c.dims)>0){if(c.dims.length!==4)throw new Error('Input "attention_bias" is expected to have 4 dimensions');if(c.dims[0]!==o||c.dims[1]!==t.numHeads||c.dims[2]!==a||c.dims[3]!==y)throw new Error('Expect "attention_bias" shape (batch_size, num_heads, sequence_length, total_sequence_length)')}return{batchSize:o,sequenceLength:a,pastSequenceLength:m,kvSequenceLength:h,totalSequenceLength:y,maxSequenceLength:g,inputHiddenSize:0,hiddenSize:p,vHiddenSize:O,headSize:_,vHeadSize:Math.floor(O/t.numHeads),numHeads:t.numHeads,isUnidirectional:!1,pastPresentShareBuffer:!1,maskFilterValue:t.maskFilterValue,maskType:T,scale:t.scale,broadcastResPosBias:A,passPastInKv:S,qkvFormat:w}},R2=e=>ke({...e}),xu=ke({perm:[0,2,1,3]}),Jb=(e,t,n,i,u,l,d)=>{let c=[i,u,l],s=F.size(c),r=[{type:12,data:s},{type:12,data:d},{type:12,data:l}],o=a=>{let p=oe("qkv_with_bias",t.dataType,c),h=j("qkv",t.dataType,c),m=j("bias",n.dataType,c),g=[{name:"output_size",type:"u32"},{name:"bias_offset",type:"u32"},{name:"hidden_size",type:"u32"}];return` ${a.registerUniforms(g).declareVariables(h,m,p)} ${a.mainStart()} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let bias_offset_idx = (global_idx % uniforms.hidden_size) + uniforms.bias_offset; qkv_with_bias[global_idx] = qkv[global_idx] + bias[bias_offset_idx]; - }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:r}),getShaderSource:o},{inputs:[t,n],outputs:[-1]})[0]},Ii=(e,t,n,i,u,l,d,c)=>{let s=l;if(d&&F.size(d.dims)>0){if(i===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return s=Wb(e,l,d,t,i,n*u,c),s=s.reshape([t,i,n,u]),n===1||i===1?s:e.compute($t(s,wu.perm),{inputs:[s],outputs:[-1]})[0]}else return l.dims.length===3&&(s=l.reshape([t,i,n,u])),n===1||i===1?s:e.compute($t(s,wu.perm),{inputs:[s],outputs:[-1]})[0]},A2=(e,t)=>{let n=Hb(e.inputs,t),i=e.inputs[0],u=ct(e.inputs,1),l=ct(e.inputs,2),d=ct(e.inputs,3),c=ct(e.inputs,4),s=ct(e.inputs,5),r=ct(e.inputs,6),o=ct(e.inputs,7);if(i.dims.length===5)throw new Error("Packed QKV is not implemented");if(u?.dims.length===5)throw new Error("Packed KV is not implemented");let a=u&&l&&u.dims.length===4&&l.dims.length===4,p=Ii(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,i,d,0);if(a)return Mi(e,p,u,l,c,void 0,r,o,s,n);if(!u||!l)throw new Error("key and value must be provided");let h=Ii(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,u,d,n.hiddenSize),m=Ii(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,l,d,2*n.hiddenSize);Mi(e,p,h,m,c,void 0,r,o,s,n)}}),Kb,Xb,Zb,Yb,jl,P2,C2,R2=D(()=>{"use strict";de(),pe(),He(),he(),Kb=e=>{if(!e||e.length<1)throw new Error("too few inputs")},Xb=(e,t)=>{let n=[],i=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(u=>n.push(Number(u))),i=n.length),ke({numOutputs:i,axis:t.axis,splitSizes:n})},Zb=e=>` + }`};return e.compute({name:"MultiHeadAttentionAddBias",shaderCache:{inputDependencies:["type","type"]},getRunData:()=>({outputs:[{dims:c,dataType:t.dataType,gpuDataType:0}],dispatchGroup:{x:Math.ceil(s/64)},programUniforms:r}),getShaderSource:o},{inputs:[t,n],outputs:[-1]})[0]},Ei=(e,t,n,i,u,l,d,c)=>{let s=l;if(d&&F.size(d.dims)>0){if(i===1)throw new Error("AddBiasReshape is not implemented. Please export your model with packed QKV or KV");return s=Jb(e,l,d,t,i,n*u,c),s=s.reshape([t,i,n,u]),n===1||i===1?s:e.compute($t(s,xu.perm),{inputs:[s],outputs:[-1]})[0]}else return l.dims.length===3&&(s=l.reshape([t,i,n,u])),n===1||i===1?s:e.compute($t(s,xu.perm),{inputs:[s],outputs:[-1]})[0]},D2=(e,t)=>{let n=Yb(e.inputs,t),i=e.inputs[0],u=ct(e.inputs,1),l=ct(e.inputs,2),d=ct(e.inputs,3),c=ct(e.inputs,4),s=ct(e.inputs,5),r=ct(e.inputs,6),o=ct(e.inputs,7);if(i.dims.length===5)throw new Error("Packed QKV is not implemented");if(u?.dims.length===5)throw new Error("Packed KV is not implemented");let a=u&&l&&u.dims.length===4&&l.dims.length===4,p=Ei(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,i,d,0);if(a)return zi(e,p,u,l,c,void 0,r,o,s,n);if(!u||!l)throw new Error("key and value must be provided");let h=Ei(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.headSize,u,d,n.hiddenSize),m=Ei(e,n.batchSize,n.numHeads,n.kvSequenceLength,n.vHeadSize,l,d,2*n.hiddenSize);zi(e,p,h,m,c,void 0,r,o,s,n)}}),Qb,ey,ty,ry,Gl,N2,z2,B2=D(()=>{"use strict";de(),pe(),He(),he(),Qb=e=>{if(!e||e.length<1)throw new Error("too few inputs")},ey=(e,t)=>{let n=[],i=t.numOutputs;return e[1].dims[0]>0&&(e[1].getBigInt64Array().forEach(u=>n.push(Number(u))),i=n.length),ke({numOutputs:i,axis:t.axis,splitSizes:n})},ty=e=>` fn calculateOutputIndex(index: u32) -> u32 { for (var i: u32 = 0u; i < ${e}u; i += 1u ) { if (index < ${se("uniforms.size_in_split_axis","i",e)}) { @@ -3641,14 +3641,14 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return ${e}u; -}`,Yb=e=>{let t=e.length,n=[];for(let i=0;i{let t=e.length,n=[];for(let i=0;i{let n=e[0].dims,i=F.size(n),u=e[0].dataType,l=F.normalizeAxis(t.axis,n.length),d=new Array(t.numOutputs),c=j("input",u,n.length),s=new Array(t.numOutputs),r=[],o=[],a=0,p=[{type:12,data:i}];for(let m=0;m` + }`},Gl=(e,t)=>{let n=e[0].dims,i=F.size(n),u=e[0].dataType,l=F.normalizeAxis(t.axis,n.length),d=new Array(t.numOutputs),c=j("input",u,n.length),s=new Array(t.numOutputs),r=[],o=[],a=0,p=[{type:12,data:i}];for(let m=0;m` ${m.registerUniform("input_size","u32").registerUniform("size_in_split_axis","u32",s.length).declareVariables(c,...d)} - ${Zb(s.length)} - ${Yb(d)} + ${ty(s.length)} + ${ry(d)} ${m.mainStart()} ${m.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.input_size")} @@ -3661,7 +3661,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${c.indicesSet("indices",l,"index")}; } writeBufferData(output_number, indices, global_idx); - }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:r,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p})}},P2=(e,t)=>{Kb(e.inputs);let n=e.inputs.length===1?t:Xb(e.inputs,t);e.compute(jl(e.inputs,n),{inputs:[0]})},C2=e=>{let t=e.axis,n=e.splitSizes,i=e.numOutputs<0?n.length:e.numOutputs;if(i!==n.length)throw new Error("numOutputs and splitSizes length must be equal");return ke({axis:t,numOutputs:i,splitSizes:n})}}),Jb,Zo,D2,M2=D(()=>{"use strict";de(),pe(),He(),he(),Jb=(e,t)=>{let[n,i,u,l]=e,{numHeads:d,rotaryEmbeddingDim:c}=t;if(n.dims.length!==3&&n.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!F.areEqual(i.dims,[])&&!F.areEqual(i.dims,[1])&&i.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${i.dims.length}`);if(u.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${u.dims.length}`);if(l.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${l.dims.length}`);if(!F.areEqual(u.dims,l.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(c>0&&d===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let s=n.dims[0],r=n.dims[n.dims.length-2],o=u.dims[0],a=F.sizeFromDimension(n.dims,1)/r,p=c===0?u.dims[1]*2:a/d;if(c>p)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(i.dims.length===2){if(s!==i.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${i.dims[0]}`);if(r!==i.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${i.dims[1]}`)}if(r>o)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported");if(p/2!==u.dims[1]&&c/2!==u.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${u.dims[1]}`)},Zo=(e,t)=>{let{interleaved:n,numHeads:i,rotaryEmbeddingDim:u,scale:l}=t,d=e[0].dims[0],c=F.sizeFromDimension(e[0].dims,1),s=e[0].dims[e[0].dims.length-2],r=c/s,o=e[2].dims[1],a=u===0?o*2:r/i,p=new Array(d,s,r/a,a-o),h=F.computeStrides(p),m=[{type:1,data:l},{type:12,data:p},{type:12,data:h},...e[0].dims.length===3?new Array({type:12,data:[c,r,a,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,a,s*a,1]}):[],...ue(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],g=_=>{let w=j("input",e[0].dataType,e[0].dims.length),y=j("position_ids",e[1].dataType,e[1].dims.length),T=j("cos_cache",e[2].dataType,e[2].dims.length),S=j("sin_cache",e[3].dataType,e[3].dims.length),O=oe("output",e[0].dataType,e[0].dims.length);return _.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:p.length},{name:"global_strides",type:"u32",length:h.length},{name:"input_output_strides",type:"u32",length:h.length}]),` + }`;return{name:"Split",shaderCache:{hint:t.cacheKey,inputDependencies:["rank"]},getShaderSource:h,getRunData:()=>({outputs:r,dispatchGroup:{x:Math.ceil(i/64)},programUniforms:p})}},N2=(e,t)=>{Qb(e.inputs);let n=e.inputs.length===1?t:ey(e.inputs,t);e.compute(Gl(e.inputs,n),{inputs:[0]})},z2=e=>{let t=e.axis,n=e.splitSizes,i=e.numOutputs<0?n.length:e.numOutputs;if(i!==n.length)throw new Error("numOutputs and splitSizes length must be equal");return ke({axis:t,numOutputs:i,splitSizes:n})}}),ny,Jo,F2,L2=D(()=>{"use strict";de(),pe(),He(),he(),ny=(e,t)=>{let[n,i,u,l]=e,{numHeads:d,rotaryEmbeddingDim:c}=t;if(n.dims.length!==3&&n.dims.length!==4)throw new Error(`Input 'x' is expected to have 3 or 4 dimensions, got ${n.dims.length}`);if(!F.areEqual(i.dims,[])&&!F.areEqual(i.dims,[1])&&i.dims.length!==2)throw new Error(`Input 'position_ids' is expected to have 0, 1, or 2 dimensions, got ${i.dims.length}`);if(u.dims.length!==2)throw new Error(`Input 'cos_cache' is expected to have 2 dimensions, got ${u.dims.length}`);if(l.dims.length!==2)throw new Error(`Input 'sin_cache' is expected to have 2 dimensions, got ${l.dims.length}`);if(!F.areEqual(u.dims,l.dims))throw new Error("Inputs 'cos_cache' and 'sin_cache' are expected to have the same shape");if(c>0&&d===0)throw new Error("num_heads must be provided if rotary_embedding_dim is specified");let s=n.dims[0],r=n.dims[n.dims.length-2],o=u.dims[0],a=F.sizeFromDimension(n.dims,1)/r,p=c===0?u.dims[1]*2:a/d;if(c>p)throw new Error("rotary_embedding_dim must be less than or equal to head_size");if(i.dims.length===2){if(s!==i.dims[0])throw new Error(`Input 'position_ids' dimension 0 should be of size batch_size, got ${i.dims[0]}`);if(r!==i.dims[1])throw new Error(`Input 'position_ids' dimension 1 should be of size sequence_length, got ${i.dims[1]}`)}if(r>o)throw new Error("Updating cos_cache and sin_cache in RotaryEmbedding is not currently supported");if(p/2!==u.dims[1]&&c/2!==u.dims[1])throw new Error(`Input 'cos_cache' dimension 1 should be same as head_size / 2 or rotary_embedding_dim / 2, got ${u.dims[1]}`)},Jo=(e,t)=>{let{interleaved:n,numHeads:i,rotaryEmbeddingDim:u,scale:l}=t,d=e[0].dims[0],c=F.sizeFromDimension(e[0].dims,1),s=e[0].dims[e[0].dims.length-2],r=c/s,o=e[2].dims[1],a=u===0?o*2:r/i,p=new Array(d,s,r/a,a-o),h=F.computeStrides(p),m=[{type:1,data:l},{type:12,data:p},{type:12,data:h},...e[0].dims.length===3?new Array({type:12,data:[c,r,a,1]}):[],...e[0].dims.length===4?new Array({type:12,data:[c,a,s*a,1]}):[],...ue(e[0].dims,e[1].dims,e[2].dims,e[3].dims,e[0].dims)],g=_=>{let w=j("input",e[0].dataType,e[0].dims.length),y=j("position_ids",e[1].dataType,e[1].dims.length),T=j("cos_cache",e[2].dataType,e[2].dims.length),S=j("sin_cache",e[3].dataType,e[3].dims.length),O=oe("output",e[0].dataType,e[0].dims.length);return _.registerUniforms([{name:"scale",type:"f32"},{name:"global_shape",type:"u32",length:p.length},{name:"global_strides",type:"u32",length:h.length},{name:"input_output_strides",type:"u32",length:h.length}]),` ${_.declareVariables(w,y,T,S,O)} ${_.mainStart(Fn)} @@ -3687,7 +3687,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let k = dot(bsnh, uniforms.input_output_strides) + half_rotary_emb_dim; ${O.setByOffset("k",w.getByOffset("k"))} } - }`};return{name:"RotaryEmbedding",shaderCache:{hint:ke({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(F.size(p)/Fn)},programUniforms:m})}},D2=(e,t)=>{Jb(e.inputs,t),e.compute(Zo(e.inputs,t))}}),Qb,ey,_u,ty,N2,Tk=D(()=>{"use strict";He(),de(),hd(),k2(),R2(),Cr(),M2(),he(),Qb=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let n=e[0],i=e[1],u=e[2],l=e[3],d=e[4];if(t.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=!1,s=n.dims[0],r=n.dims[1],o=n.dims.length===3?c?n.dims[2]/3:n.dims[2]:t.numHeads*n.dims[4],a=r,p=0,h=!i||i.dims.length===0,m=Math.floor(h?o/(t.numHeads+2*t.kvNumHeads):o/t.numHeads);h&&(o=m*t.numHeads);let g=l&&l.dims.length!==0,_=d&&d.dims.length!==0;if(g&&l.dims.length===4&&l.dims[0]===s&&l.dims[1]!==t.kvNumHeads&&l.dims[2]===t.kvNumHeads&&l.dims[3]===m)throw new Error("BSNH pastKey/pastValue is not supported");if(g&&_){if(l.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');p=l.dims[2]}else if(g||_)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=1;if(i&&i.dims.length>0){if(n.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(i.dims.length<3||i.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(i.dims.length===3){if(n.dims[2]%i.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');a=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==m)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(u)throw new Error('Expect "value" be none when "key" has packed kv format.');a=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==m)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');a=i.dims[2]}}else{if(n.dims.length!==3&&n.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(n.dims.length===5&&(n.dims[2]!==t.numHeads||n.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}let y=0,T=!1,S=t.kvNumHeads?m*t.kvNumHeads:o;if(u&&u.dims.length>0){if(u.dims.length!==3&&u.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==u.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(u.dims.length===3){if(a!==u.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');S=u.dims[2]}else{if(a!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');S=u.dims[1]*u.dims[3],T=!0}}let O=e.length>4?e[5]:void 0;if(O){if(O.dims.length===0)throw new Error("seqlens_k must be at least 1D, got scalar.");let A=O.dims.reduce((P,I)=>P*I,1);if(A!==s)throw new Error(`seqlens_k must have batch_size (${s}) elements, got ${A}.`);for(let P=0;P{let i=t,u=n.kvNumHeads;return t.dims.length===3&&n.kvSequenceLength!==0&&(i=t.reshape([n.batchSize,n.kvSequenceLength,u,n.headSize]),i=e.compute($t(i,ey.perm),{inputs:[i],outputs:[-1]})[0]),i},ty=(e,t,n,i)=>{let u=7,l=["type","type"],d=[e*t],c=e*t,s=[{type:12,data:c},{type:12,data:t},{type:12,data:e}],r=o=>{let a=j("seq_lens",n.dataType,n.dims),p=j("total_seq_lens",i.dataType,i.dims),h=oe("pos_ids",u,d),m=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` + }`};return{name:"RotaryEmbedding",shaderCache:{hint:ke({interleaved:n}).cacheKey,inputDependencies:["rank","rank","rank","rank"]},getShaderSource:g,getRunData:()=>({outputs:[{dims:e[0].dims,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(F.size(p)/Fn)},programUniforms:m})}},F2=(e,t)=>{ny(e.inputs,t),e.compute(Jo(e.inputs,t))}}),iy,oy,$u,sy,j2,Pk=D(()=>{"use strict";He(),de(),gd(),M2(),B2(),Cr(),L2(),he(),iy=(e,t)=>{if(t.doRotary&&e.length<=7)throw new Error("cos_cache and sin_cache inputs are required if do_rotary is specified");let n=e[0],i=e[1],u=e[2],l=e[3],d=e[4];if(t.doRotary!==0&&e.length<=7)throw new Error("cos_cast and sin_cache are expected if do_rotary attribute is non-zero");if(t.localWindowSize!==-1)throw new Error("Local attention is not supported");if(t.softcap!==0)throw new Error("Softcap is not supported");if(t.rotaryInterleaved!==0)throw new Error("Rotary interleaved is not supported");if(t.smoothSoftmax)throw new Error("Smooth softmax is not supported");if(n.dims.length!==3&&n.dims.length!==5)throw new Error("Input query is expected to have 3 or 5 dimensions");let c=!1,s=n.dims[0],r=n.dims[1],o=n.dims.length===3?c?n.dims[2]/3:n.dims[2]:t.numHeads*n.dims[4],a=r,p=0,h=!i||i.dims.length===0,m=Math.floor(h?o/(t.numHeads+2*t.kvNumHeads):o/t.numHeads);h&&(o=m*t.numHeads);let g=l&&l.dims.length!==0,_=d&&d.dims.length!==0;if(g&&l.dims.length===4&&l.dims[0]===s&&l.dims[1]!==t.kvNumHeads&&l.dims[2]===t.kvNumHeads&&l.dims[3]===m)throw new Error("BSNH pastKey/pastValue is not supported");if(g&&_){if(l.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');p=l.dims[2]}else if(g||_)throw new Error('Input "past_key" and "past_value" shall be both present or both absent');let w=1;if(i&&i.dims.length>0){if(n.dims.length!==3)throw new Error('Input "query" is expected to have 3 dimensions when key is given');if(i.dims.length<3||i.dims.length>5)throw new Error('Input "key" is expected to have 3, 4, or 5 dimensions');if(n.dims[0]!==i.dims[0])throw new Error('Input "query" and "key" shall have same dim 0 (batch size)');if(i.dims.length===3){if(n.dims[2]%i.dims[2]!==0)throw new Error('Dimension 2 of "query" should be a multiple of "key"');a=i.dims[1]}else if(i.dims.length===5){if(i.dims[2]!==t.numHeads||i.dims[3]!==2||i.dims[4]!==m)throw new Error('Expect "key" shape (batch_size, kv_sequence_length, num_heads, 2, head_size) for packed kv');if(u)throw new Error('Expect "value" be none when "key" has packed kv format.');a=i.dims[1]}else{if(i.dims[1]!==t.numHeads||i.dims[3]!==m)throw new Error('Expect "key" shape (batch_size, num_heads, kv_sequence_length, head_size) for past_key');a=i.dims[2]}}else{if(n.dims.length!==3&&n.dims.length!==5)throw new Error('Input "query" is expected to have 3 or 5 dimensions when key is empty');if(n.dims.length===5&&(n.dims[2]!==t.numHeads||n.dims[3]!==3))throw new Error('Expect "query" shape (batch_size, kv_sequence_length, num_heads, 3, head_size) for packed kv');w=3}let y=0,T=!1,S=t.kvNumHeads?m*t.kvNumHeads:o;if(u&&u.dims.length>0){if(u.dims.length!==3&&u.dims.length!==4)throw new Error('Input "value" is expected to have 3 or 4 dimensions');if(n.dims[0]!==u.dims[0])throw new Error('Input "query" and "value" shall have same dim 0 (batch_size)');if(u.dims.length===3){if(a!==u.dims[1])throw new Error('Input "key" and "value" shall have the same dim 1 (kv_sequence_length)');S=u.dims[2]}else{if(a!==u.dims[2])throw new Error('Input "past_key" and "past_value" shall have the same dim 2 (kv_sequence_length)');S=u.dims[1]*u.dims[3],T=!0}}let O=e.length>4?e[5]:void 0;if(O){if(O.dims.length===0)throw new Error("seqlens_k must be at least 1D, got scalar.");let A=O.dims.reduce((P,I)=>P*I,1);if(A!==s)throw new Error(`seqlens_k must have batch_size (${s}) elements, got ${A}.`);for(let P=0;P{let i=t,u=n.kvNumHeads;return t.dims.length===3&&n.kvSequenceLength!==0&&(i=t.reshape([n.batchSize,n.kvSequenceLength,u,n.headSize]),i=e.compute($t(i,oy.perm),{inputs:[i],outputs:[-1]})[0]),i},sy=(e,t,n,i)=>{let u=7,l=["type","type"],d=[e*t],c=e*t,s=[{type:12,data:c},{type:12,data:t},{type:12,data:e}],r=o=>{let a=j("seq_lens",n.dataType,n.dims),p=j("total_seq_lens",i.dataType,i.dims),h=oe("pos_ids",u,d),m=[{name:"output_size",type:"u32"},{name:"sequence_length",type:"u32"},{name:"batch_size",type:"u32"}];return` ${o.registerUniforms(m).declareVariables(a,p,h)} ${o.mainStart()} ${o.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -3718,7 +3718,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${h.setByOffset("global_idx","seqlen")} }; } - `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:d,dataType:u}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:s}),getShaderSource:r}},N2=(e,t)=>{if(e.inputs.length>14&&e.inputs[14]||e.inputs.length>15&&e.inputs[15])throw new Error("GroupQueryAttention (JSEP): q_norm_weight / k_norm_weight inputs are not supported. The per-head Q/K RMS normalization prologue is implemented only on the CUDA and native WebGPU EPs.");let n=Qb(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let i=e.inputs[0],u=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,l=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,d=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,c=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,s=e.inputs.length>4?e.inputs[5]:void 0,r=e.inputs.length>5?e.inputs[6]:void 0,o=n.kvNumHeads?n.kvNumHeads:n.numHeads,a=ke({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,o*n.headSize,o*n.headSize]}),[p,h,m]=!u&&!l?e.compute(jl([i],a),{inputs:[i],outputs:[-1,-1,-1]}):[i,u,l],g,_;if(t.doRotary){let S=e.compute(ty(n.batchSize,n.sequenceLength,s,r),{inputs:[s,r],outputs:[-1]})[0],O=e.inputs[7],A=e.inputs[8],P=ke({interleaved:t.rotaryInterleaved!==0,numHeads:n.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),I=[p,S,O,A],z=[-1];g=e.compute(Zo(I,P),{inputs:I,outputs:z})[0],I.splice(0,1,h);let G=ke({interleaved:t.rotaryInterleaved!==0,numHeads:n.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});_=e.compute(Zo(I,G),{inputs:I,outputs:z})[0]}let w=Ii(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.doRotary?g:p,void 0,0),y=_u(e,t.doRotary?_:h,n),T=_u(e,m,n);Mi(e,w,y,T,void 0,void 0,d,c,void 0,n,s,r)}}),vu,ry,ny,z2,Sk=D(()=>{"use strict";de(),pe(),Cr(),he(),vu=(e,t,n,i,u,l,d,c)=>{let s=Ge(l),r=s===1?"f32":`vec${s}f`,o=s===1?"vec2f":`mat2x${s}f`,a=u*d,p=64;a===1&&(p=256);let h=[u,d,l/s],m=[u,d,2],g=["rank","type","type"],_=[];_.push(...ue(h,m));let w=y=>{let T=j("x",t.dataType,3,s),S=j("scale",n.dataType,n.dims),O=j("bias",i.dataType,i.dims),A=oe("output",1,3,2),P=[T,S,O,A];return` + `};return{name:"GeneratePositionIds",shaderCache:{hint:`${e};${t}`,inputDependencies:l},getRunData:()=>({outputs:[{dims:d,dataType:u}],dispatchGroup:{x:Math.ceil(c/64)},programUniforms:s}),getShaderSource:r}},j2=(e,t)=>{if(e.inputs.length>14&&e.inputs[14]||e.inputs.length>15&&e.inputs[15])throw new Error("GroupQueryAttention (JSEP): q_norm_weight / k_norm_weight inputs are not supported. The per-head Q/K RMS normalization prologue is implemented only on the CUDA and native WebGPU EPs.");let n=iy(e.inputs,t);if(e.inputs[0].dims.length===5)throw new Error("Packed QKV is not implemented");if(e.inputs[1]?.dims.length===5)throw new Error("Packed KV is not implemented");let i=e.inputs[0],u=e.inputs[1]&&e.inputs[1].dims.length>0?e.inputs[1]:void 0,l=e.inputs[2]&&e.inputs[2].dims.length>0?e.inputs[2]:void 0,d=e.inputs[3]&&e.inputs[3].dims.length!==0?e.inputs[3]:void 0,c=e.inputs[4]&&e.inputs[4].dims.length!==0?e.inputs[4]:void 0,s=e.inputs.length>4?e.inputs[5]:void 0,r=e.inputs.length>5?e.inputs[6]:void 0,o=n.kvNumHeads?n.kvNumHeads:n.numHeads,a=ke({axis:2,numOutputs:3,splitSizes:[n.numHeads*n.headSize,o*n.headSize,o*n.headSize]}),[p,h,m]=!u&&!l?e.compute(Gl([i],a),{inputs:[i],outputs:[-1,-1,-1]}):[i,u,l],g,_;if(t.doRotary){let S=e.compute(sy(n.batchSize,n.sequenceLength,s,r),{inputs:[s,r],outputs:[-1]})[0],O=e.inputs[7],A=e.inputs[8],P=ke({interleaved:t.rotaryInterleaved!==0,numHeads:n.numHeads,rotaryEmbeddingDim:0,scale:t.scale}),I=[p,S,O,A],z=[-1];g=e.compute(Jo(I,P),{inputs:I,outputs:z})[0],I.splice(0,1,h);let q=ke({interleaved:t.rotaryInterleaved!==0,numHeads:n.kvNumHeads,rotaryEmbeddingDim:0,scale:t.scale});_=e.compute(Jo(I,q),{inputs:I,outputs:z})[0]}let w=Ei(e,n.batchSize,n.numHeads,n.sequenceLength,n.headSize,t.doRotary?g:p,void 0,0),y=$u(e,t.doRotary?_:h,n),T=$u(e,m,n);zi(e,w,y,T,void 0,void 0,d,c,void 0,n,s,r)}}),Tu,ay,uy,U2,Ck=D(()=>{"use strict";de(),pe(),Cr(),he(),Tu=(e,t,n,i,u,l,d,c)=>{let s=qe(l),r=s===1?"f32":`vec${s}f`,o=s===1?"vec2f":`mat2x${s}f`,a=u*d,p=64;a===1&&(p=256);let h=[u,d,l/s],m=[u,d,2],g=["rank","type","type"],_=[];_.push(...ue(h,m));let w=y=>{let T=j("x",t.dataType,3,s),S=j("scale",n.dataType,n.dims),O=j("bias",i.dataType,i.dims),A=oe("output",1,3,2),P=[T,S,O,A];return` var workgroup_shared : array<${o}, ${p}>; const workgroup_size = ${p}u; ${y.declareVariables(...P)} @@ -3752,7 +3752,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let channel_shift = f32(bias[channel]) - sum_final * channel_scale; output[workgroup_index] = vec2f(channel_scale, channel_shift); } - }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${s};${c};${p}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:m,dataType:1}],dispatchGroup:{x:a},programUniforms:_}),getShaderSource:w},{inputs:[t,n,i],outputs:[-1]})[0]},ry=(e,t,n)=>{let i=t[0].dims,u=i,l=2,d=i[0],c=i[1],s=F.sizeFromDimension(i,l),r=Ge(s),o=F.size(u)/r,a=vu(e,t[0],t[1],t[2],d,s,c,n.epsilon),p=[d,c,s/r],h=[d,c],m=["type","none"],g=_=>{let w=j("x",t[0].dataType,p.length,r),y=j("scale_shift",1,h.length,2),T=oe("output",t[0].dataType,p.length,r),S=[w,y,T];return` + }`};return e.compute({name:"InstanceNormComputeChannelScaleShift",shaderCache:{hint:`${s};${c};${p}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:m,dataType:1}],dispatchGroup:{x:a},programUniforms:_}),getShaderSource:w},{inputs:[t,n,i],outputs:[-1]})[0]},ay=(e,t,n)=>{let i=t[0].dims,u=i,l=2,d=i[0],c=i[1],s=F.sizeFromDimension(i,l),r=qe(s),o=F.size(u)/r,a=Tu(e,t[0],t[1],t[2],d,s,c,n.epsilon),p=[d,c,s/r],h=[d,c],m=["type","none"],g=_=>{let w=j("x",t[0].dataType,p.length,r),y=j("scale_shift",1,h.length,2),T=oe("output",t[0].dataType,p.length,r),S=[w,y,T];return` ${_.registerUniform("output_size","u32").declareVariables(...S)} ${_.mainStart()} ${_.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -3762,7 +3762,7 @@ fn calculateOutputIndex(index: u32) -> u32 { let scale_shift = ${y.getByIndices("vec2(batch, channel)")}; let value = ${w.getByOffset("global_idx")} * ${T.type.value}(scale_shift.x) + ${T.type.value}(scale_shift.y); ${T.setByOffset("global_idx","value")}; - }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${r}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:u,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...ue(p,h,p)]}),getShaderSource:g},{inputs:[t[0],a]})},ny=(e,t,n)=>{let i=t[0].dims,u=i,l=i[0],d=i[i.length-1],c=F.sizeFromDimension(i,1)/d,s=Ge(d),r=F.size(u)/s,o=[{type:12,data:c},{type:12,data:Math.floor(d/s)}],a=["type","type"],p=!1,h=[0,i.length-1];for(let w=0;wi[h[y]])),g=vu(e,m,t[1],t[2],l,c,d,n.epsilon),_=w=>{let y=nt(t[0].dataType),T=s===1?"vec2f":`mat${s}x2f`,S=P=>{let I=P===0?"x":"y",z=s===1?"f32":`vec${s}f`;switch(s){case 1:return`${y}(${z}(scale.${I}))`;case 2:return`vec2<${y}>(${z}(scale[0].${I}, scale[1].${I}))`;case 4:return`vec4<${y}>(${z}(scale[0].${I}, scale[1].${I}, scale[2].${I}, scale[3].${I}))`;default:throw new Error(`Not supported compoents ${s}`)}},O=j("input",t[0].dataType,t[0].dims,s),A=oe("output",t[0].dataType,u,s);return` + }`};e.compute({name:"InstanceNormalization",shaderCache:{hint:`${r}`,inputDependencies:m},getRunData:()=>({outputs:[{dims:u,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(o/64)},programUniforms:[{type:12,data:o},...ue(p,h,p)]}),getShaderSource:g},{inputs:[t[0],a]})},uy=(e,t,n)=>{let i=t[0].dims,u=i,l=i[0],d=i[i.length-1],c=F.sizeFromDimension(i,1)/d,s=qe(d),r=F.size(u)/s,o=[{type:12,data:c},{type:12,data:Math.floor(d/s)}],a=["type","type"],p=!1,h=[0,i.length-1];for(let w=0;wi[h[y]])),g=Tu(e,m,t[1],t[2],l,c,d,n.epsilon),_=w=>{let y=nt(t[0].dataType),T=s===1?"vec2f":`mat${s}x2f`,S=P=>{let I=P===0?"x":"y",z=s===1?"f32":`vec${s}f`;switch(s){case 1:return`${y}(${z}(scale.${I}))`;case 2:return`vec2<${y}>(${z}(scale[0].${I}, scale[1].${I}))`;case 4:return`vec4<${y}>(${z}(scale[0].${I}, scale[1].${I}, scale[2].${I}, scale[3].${I}))`;default:throw new Error(`Not supported compoents ${s}`)}},O=j("input",t[0].dataType,t[0].dims,s),A=oe("output",t[0].dataType,u,s);return` @group(0) @binding(0) var input : array<${O.type.storage}>; @group(0) @binding(1) var scale_input : array<${T}>; @group(0) @binding(2) var output : array<${A.type.storage}>; @@ -3776,15 +3776,15 @@ fn calculateOutputIndex(index: u32) -> u32 { let scale_offset = current_image_number * uniforms.C + current_channel_number; let scale = scale_input[scale_offset]; output[global_idx] = fma(input[global_idx], ${S(0)}, ${S(1)}); - }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${s}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:u,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:o}),getShaderSource:_},{inputs:[t[0],g]})},z2=(e,t)=>{t.format==="NHWC"?ny(e,e.inputs,t):ry(e,e.inputs,t)}}),iy,oy,B2,Ik=D(()=>{"use strict";de(),pe(),he(),iy=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},oy=(e,t,n)=>{let i=t.simplified,u=e[0].dims,l=e[1],d=!i&&e[2],c=u,s=F.normalizeAxis(t.axis,u.length),r=F.sizeToDimension(u,s),o=F.sizeFromDimension(u,s),a=F.size(l.dims),p=d?F.size(d.dims):0;if(a!==o||d&&p!==o)throw new Error(`Size of X.shape()[axis:] == ${o}. + }`};e.compute({name:"InstanceNormalizationNHWC",shaderCache:{hint:`${s}`,inputDependencies:a},getRunData:()=>({outputs:[{dims:u,dataType:t[0].dataType}],dispatchGroup:{x:Math.ceil(r/64)},programUniforms:o}),getShaderSource:_},{inputs:[t[0],g]})},U2=(e,t)=>{t.format==="NHWC"?uy(e,e.inputs,t):ay(e,e.inputs,t)}}),ly,dy,V2,Rk=D(()=>{"use strict";de(),pe(),he(),ly=e=>{if(!e||e.length<2)throw new Error("layerNorm requires at least 2 inputs.")},dy=(e,t,n)=>{let i=t.simplified,u=e[0].dims,l=e[1],d=!i&&e[2],c=u,s=F.normalizeAxis(t.axis,u.length),r=F.sizeToDimension(u,s),o=F.sizeFromDimension(u,s),a=F.size(l.dims),p=d?F.size(d.dims):0;if(a!==o||d&&p!==o)throw new Error(`Size of X.shape()[axis:] == ${o}. Size of scale and bias (if provided) must match this. - Got scale size of ${a} and bias size of ${p}`);let h=[];for(let O=0;O1,y=n>2,T=O=>{let A=nt(e[0].dataType),P=[j("x",e[0].dataType,e[0].dims,m),j("scale",l.dataType,l.dims,m)];d&&P.push(j("bias",d.dataType,d.dims,m)),P.push(oe("output",e[0].dataType,c,m)),w&&P.push(oe("mean_data_output",1,h)),y&&P.push(oe("inv_std_output",1,h));let I=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` + Got scale size of ${a} and bias size of ${p}`);let h=[];for(let O=0;O1,y=n>2,T=O=>{let A=nt(e[0].dataType),P=[j("x",e[0].dataType,e[0].dims,m),j("scale",l.dataType,l.dims,m)];d&&P.push(j("bias",d.dataType,d.dims,m)),P.push(oe("output",e[0].dataType,c,m)),w&&P.push(oe("mean_data_output",1,h)),y&&P.push(oe("inv_std_output",1,h));let I=[{name:"norm_count",type:"u32"},{name:"norm_size",type:"f32"},{name:"norm_size_vectorized",type:"u32"},{name:"epsilon",type:"f32"}];return` ${O.registerUniforms(I).declareVariables(...P)} ${O.mainStart()} ${O.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.norm_count")} let offset = global_idx * uniforms.norm_size_vectorized; - var mean_vector = ${Cl("f32",m)}; - var mean_square_vector = ${Cl("f32",m)}; + var mean_vector = ${Ml("f32",m)}; + var mean_square_vector = ${Ml("f32",m)}; for (var h: u32 = 0u; h < uniforms.norm_size_vectorized; h++) { let value = ${Mn(A,m,"x[h + offset]")}; @@ -3804,7 +3804,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${w?"mean_data_output[global_idx] = mean":""}; ${y?"inv_std_output[global_idx] = inv_std_dev":""}; - }`},S=[{dims:c,dataType:e[0].dataType}];return w&&S.push({dims:h,dataType:1}),y&&S.push({dims:h,dataType:1}),{name:"LayerNormalization",shaderCache:{hint:`${m};${n};${i}`,inputDependencies:g},getRunData:()=>({outputs:S,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:_}),getShaderSource:T}},B2=(e,t)=>{iy(e.inputs),e.compute(oy(e.inputs,t,e.outputCount))}}),sy,F2,Ok=D(()=>{"use strict";pe(),yd(),wd(),sy=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},F2=e=>{sy(e.inputs);let t=Bn.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let n=t[t.length-1],i=e.inputs[0].dims[e.inputs[0].dims.length-1];if(n<8&&i<8)e.compute(bd(e.inputs,{activation:""},t));else{let u=t[t.length-2],l=F.size(e.inputs[0].dims.slice(0,-2)),d=F.size(e.inputs[1].dims.slice(0,-2));if(l!==1&&u===1&&d===1){let c=e.inputs[0].reshape([1,l,i]),s=e.inputs[1].reshape([1,i,n]),r=[1,l,n],o=[c,s];e.compute(Xo(o,{activation:""},t,r),{inputs:o})}else e.compute(Xo(e.inputs,{activation:""},t))}}}),ay,uy,ly,L2,j2,Ek=D(()=>{"use strict";de(),pe(),He(),he(),ay=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let n=e[0],i=n.dims.length;if(n.dims[i-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let u=Math.floor((t.k+t.blockSize-1)/t.blockSize),l=t.blockSize/8*t.bits,d=e[1];if(!F.areEqual(d.dims,[t.n,u,l]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let c=e[2].dims;if(F.size(c)!==t.n*u)throw new Error("scales input size error.");if(e.length===4){let s=e[3].dims,r=t.n*(t.bits===8?u:Math.floor((u*t.bits+7)/8));if(F.size(s)!==r)throw new Error("zeroPoints input size error.")}},uy=(e,t)=>{let n=e[0].dims,i=n.length,u=n[i-2],l=t.k,d=t.n,c=n.slice(0,i-2),s=F.size(c),r=e[1].dims[2]/4,o=e[0].dataType,a=Ge(t.k),p=Ge(r),h=Ge(d),m=c.concat([u,d]),g=u>1&&d/h%2===0?2:1,_=F.size(m)/h/g,w=64,y=[],T=[s,u,l/a],S=F.convertShape(e[1].dims).slice();S.splice(-1,1,r/p),y.push(...ue(T)),y.push(...ue(S)),y.push(...ue(e[2].dims)),e.length===4&&y.push(...ue(F.convertShape(e[3].dims)));let O=[s,u,d/h];y.push(...ue(O));let A=P=>{let I=T.length,z=j("a",e[0].dataType,I,a),G=j("b",12,S.length,p),J=j("scales",e[2].dataType,e[2].dims.length),q=[z,G,J],C=e.length===4?j("zero_points",12,e[3].dims.length):void 0;C&&q.push(C);let ee=O.length,v=oe("output",e[0].dataType,ee,h),R=nt(e[0].dataType),H=(()=>{switch(a){case 1:return`array<${R}, 8>`;case 2:return`mat4x2<${R}>`;case 4:return`mat2x4<${R}>`;default:throw new Error(`${a}-component is not supported.`)}})(),L=Math.floor(32/t.bits),V=Math.floor(L/8),K=()=>{let Y="";for(let N=0;N({outputs:S,dispatchGroup:{x:Math.ceil(r/64)},programUniforms:_}),getShaderSource:T}},V2=(e,t)=>{ly(e.inputs),e.compute(dy(e.inputs,t,e.outputCount))}}),cy,G2,Dk=D(()=>{"use strict";pe(),vd(),xd(),cy=e=>{if(!e||e.length!==2)throw new Error("MatMul requires 2 inputs.");if(e[0].dims[e[0].dims.length-1]!==e[1].dims[e[1].dims.length-2])throw new Error("shared dimension does not match.")},G2=e=>{cy(e.inputs);let t=Bn.calcShape(e.inputs[0].dims,e.inputs[1].dims,!0);if(!t)throw new Error("Can't use matmul on the given tensors");let n=t[t.length-1],i=e.inputs[0].dims[e.inputs[0].dims.length-1];if(n<8&&i<8)e.compute(_d(e.inputs,{activation:""},t));else{let u=t[t.length-2],l=F.size(e.inputs[0].dims.slice(0,-2)),d=F.size(e.inputs[1].dims.slice(0,-2));if(l!==1&&u===1&&d===1){let c=e.inputs[0].reshape([1,l,i]),s=e.inputs[1].reshape([1,i,n]),r=[1,l,n],o=[c,s];e.compute(Yo(o,{activation:""},t,r),{inputs:o})}else e.compute(Yo(e.inputs,{activation:""},t))}}}),py,hy,fy,q2,H2,Mk=D(()=>{"use strict";de(),pe(),He(),he(),py=(e,t)=>{if(e.length<3||e.length>4)throw new Error("MatMulNBits requires 3 or 4 inputs");let n=e[0],i=n.dims.length;if(n.dims[i-1]!==t.k)throw new Error("The last dim of input shape does not match the k value");let u=Math.floor((t.k+t.blockSize-1)/t.blockSize),l=t.blockSize/8*t.bits,d=e[1];if(!F.areEqual(d.dims,[t.n,u,l]))throw new Error("The second inputs must be 3D tensor with shape N X nBlocksPerCol X blobSize");let c=e[2].dims;if(F.size(c)!==t.n*u)throw new Error("scales input size error.");if(e.length===4){let s=e[3].dims,r=t.n*(t.bits===8?u:Math.floor((u*t.bits+7)/8));if(F.size(s)!==r)throw new Error("zeroPoints input size error.")}},hy=(e,t)=>{let n=e[0].dims,i=n.length,u=n[i-2],l=t.k,d=t.n,c=n.slice(0,i-2),s=F.size(c),r=e[1].dims[2]/4,o=e[0].dataType,a=qe(t.k),p=qe(r),h=qe(d),m=c.concat([u,d]),g=u>1&&d/h%2===0?2:1,_=F.size(m)/h/g,w=64,y=[],T=[s,u,l/a],S=F.convertShape(e[1].dims).slice();S.splice(-1,1,r/p),y.push(...ue(T)),y.push(...ue(S)),y.push(...ue(e[2].dims)),e.length===4&&y.push(...ue(F.convertShape(e[3].dims)));let O=[s,u,d/h];y.push(...ue(O));let A=P=>{let I=T.length,z=j("a",e[0].dataType,I,a),q=j("b",12,S.length,p),J=j("scales",e[2].dataType,e[2].dims.length),G=[z,q,J],C=e.length===4?j("zero_points",12,e[3].dims.length):void 0;C&&G.push(C);let ee=O.length,v=oe("output",e[0].dataType,ee,h),R=nt(e[0].dataType),H=(()=>{switch(a){case 1:return`array<${R}, 8>`;case 2:return`mat4x2<${R}>`;case 4:return`mat2x4<${R}>`;default:throw new Error(`${a}-component is not supported.`)}})(),L=Math.floor(32/t.bits),V=Math.floor(L/8),K=()=>{let Y="";for(let N=0;N0?N:""} = ${N===0?z.indicesToOffset(`${z.type.indices}(batch, row, word_offset)`):"input_offset"}; var a_data${N>0?N:""}: ${H}; @@ -3849,7 +3849,7 @@ fn calculateOutputIndex(index: u32) -> u32 { zero_point_word = ${C.getByOffset("zero_point_word_index")} >> zero_point_bits_offset; let zero_point${N} = ${R}((zero_point_word) & ${t.bits===2?"0x3u":"0xFu"});`:""} col_index += 1;`;return Y},te=()=>{let Y=`col_index = col * ${h};`;for(let N=0;N u32 { var b_quantized_values: ${H}; var b_dequantized_values: ${H};`,Y};return` var workgroup_shared: array<${v.type.value}, ${g*w}>; - ${P.declareVariables(...q,v)} + ${P.declareVariables(...G,v)} ${P.mainStart([w,1,1])} let output_indices = ${v.offsetToIndices(`(global_idx / ${w}) * ${g}`)}; let col = output_indices[2]; @@ -3889,7 +3889,7 @@ fn calculateOutputIndex(index: u32) -> u32 { } ${v.setByIndices(`${v.type.indices}(batch, row, col + local_id.x)`,"output_value")}; } - }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${a};${p};${h};${g};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:m,dataType:o}],dispatchGroup:{x:_},programUniforms:y}),getShaderSource:A}},ly=(e,t)=>{let n=e[0].dims,i=n.length,u=n[i-2],l=t.k,d=t.n,c=n.slice(0,i-2),s=F.size(c),r=e[1].dims[2]/4,o=e[0].dataType,a=Ge(t.k),p=Ge(r),h=c.concat([u,d]),m=128,g=d%8===0?8:d%4===0?4:1,_=m/g,w=Math.floor(32/t.bits),y=_*p*w,T=y/a,S=y/t.blockSize,O=F.size(h)/g,A=[],P=[s,u,l/a],I=F.convertShape(e[1].dims).slice();I.splice(-1,1,r/p),A.push(...ue(P)),A.push(...ue(I)),A.push(...ue(e[2].dims)),e.length===4&&A.push(...ue(F.convertShape(e[3].dims)));let z=[s,u,d];A.push(...ue(z));let G=J=>{let q=P.length,C=j("a",e[0].dataType,q,a),ee=j("b",12,I.length,p),v=j("scales",e[2].dataType,e[2].dims.length),R=[C,ee,v],H=e.length===4?j("zero_points",12,e[3].dims.length):void 0;H&&R.push(H);let L=z.length,V=oe("output",e[0].dataType,L),K=nt(e[0].dataType),B=()=>{switch(a){case 1:return` + }`};return{name:"MatMulNBits",shaderCache:{hint:`${t.blockSize};${t.bits};${a};${p};${h};${g};${w}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:m,dataType:o}],dispatchGroup:{x:_},programUniforms:y}),getShaderSource:A}},fy=(e,t)=>{let n=e[0].dims,i=n.length,u=n[i-2],l=t.k,d=t.n,c=n.slice(0,i-2),s=F.size(c),r=e[1].dims[2]/4,o=e[0].dataType,a=qe(t.k),p=qe(r),h=c.concat([u,d]),m=128,g=d%8===0?8:d%4===0?4:1,_=m/g,w=Math.floor(32/t.bits),y=_*p*w,T=y/a,S=y/t.blockSize,O=F.size(h)/g,A=[],P=[s,u,l/a],I=F.convertShape(e[1].dims).slice();I.splice(-1,1,r/p),A.push(...ue(P)),A.push(...ue(I)),A.push(...ue(e[2].dims)),e.length===4&&A.push(...ue(F.convertShape(e[3].dims)));let z=[s,u,d];A.push(...ue(z));let q=J=>{let G=P.length,C=j("a",e[0].dataType,G,a),ee=j("b",12,I.length,p),v=j("scales",e[2].dataType,e[2].dims.length),R=[C,ee,v],H=e.length===4?j("zero_points",12,e[3].dims.length):void 0;H&&R.push(H);let L=z.length,V=oe("output",e[0].dataType,L),K=nt(e[0].dataType),B=()=>{switch(a){case 1:return` let a_data0 = vec4<${K}>(sub_a[word_offset], sub_a[word_offset + 1], sub_a[word_offset + 2], sub_a[word_offset + 3]); let a_data1 = vec4<${K}>(sub_a[word_offset + 4], sub_a[word_offset + 5], sub_a[word_offset + 6], sub_a[word_offset + 7]);`;case 2:return` let a_data0 = vec4<${K}>(sub_a[word_offset], sub_a[word_offset + 1]); @@ -3973,7 +3973,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${V.setByIndices(`${V.type.indices}(batch, row, col + local_idx)`,"output_value")} } } - }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${a};${p};${_};${g}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:h,dataType:o}],dispatchGroup:{x:O},programUniforms:A}),getShaderSource:G}},L2=(e,t)=>{ay(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(ly(e.inputs,t)):e.compute(uy(e.inputs,t))},j2=e=>ke(e)}),dy,cy,py,hy,fy,my,gy,by,U2,Ak=D(()=>{"use strict";de(),pe(),he(),dy=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},cy=(e,t,n)=>{let i="";for(let u=t-1;u>=0;--u)i+=` + }`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${t.blockSize};${a};${p};${_};${g}`,inputDependencies:Array(e.length).fill("rank")},getRunData:()=>({outputs:[{dims:h,dataType:o}],dispatchGroup:{x:O},programUniforms:A}),getShaderSource:q}},q2=(e,t)=>{py(e.inputs,t),t.blockSize===32&&e.adapterInfo.isVendor("intel")&&e.adapterInfo.isArchitecture("gen-12lp")?e.compute(fy(e.inputs,t)):e.compute(hy(e.inputs,t))},H2=e=>ke(e)}),my,gy,by,yy,wy,_y,vy,xy,W2,Nk=D(()=>{"use strict";de(),pe(),he(),my=e=>{if(!e||e.length<1)throw new Error("Too few inputs");if(e[0].dataType!==1&&e[0].dataType!==10)throw new Error("Input type must be float or float16.");if(e.length>=2){let t=e[0].dims.length*2===e[1].dims[0];if(e.length===4&&(t=e[3].dims[0]*2===e[1].dims[0]),!t)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},gy=(e,t,n)=>{let i="";for(let u=t-1;u>=0;--u)i+=` k = i32(${e.indicesGet("indices",u)}) - ${se("uniforms.pads",u,n)}; if (k < 0) { break; @@ -3990,7 +3990,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${i} value = x[offset]; } - `},py=(e,t,n)=>{let i="";for(let u=t-1;u>=0;--u)i+=` + `},by=(e,t,n)=>{let i="";for(let u=t-1;u>=0;--u)i+=` k = i32(${e.indicesGet("indices",u)}) - ${se("uniforms.pads",u,n)}; if (k < 0) { k = -k; @@ -4008,7 +4008,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var k = 0; ${i} value = x[offset]; - `},hy=(e,t,n)=>{let i="";for(let u=t-1;u>=0;--u)i+=` + `},yy=(e,t,n)=>{let i="";for(let u=t-1;u>=0;--u)i+=` k = i32(${e.indicesGet("indices",u)}) - ${se("uniforms.pads",u,n)}; if (k < 0) { k = 0; @@ -4022,7 +4022,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var k = 0; ${i} value = x[offset]; - `},fy=(e,t,n)=>{let i="";for(let u=t-1;u>=0;--u)i+=` + `},wy=(e,t,n)=>{let i="";for(let u=t-1;u>=0;--u)i+=` k = i32(${e.indicesGet("indices",u)}) - ${se("uniforms.pads",u,n)}; if (k < 0) { k += i32(${se("uniforms.x_shape",u,t)}]); @@ -4036,7 +4036,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var k = 0; ${i} value = x[offset]; - `},my=(e,t,n)=>{switch(n.mode){case 0:return cy(e,t,n.pads.length);case 1:return py(e,t,n.pads.length);case 2:return hy(e,t,n.pads.length);case 3:return fy(e,t,n.pads.length);default:throw new Error("Invalid mode")}},gy=(e,t)=>{let n=F.padShape(e[0].dims.slice(),t.pads),i=e[0].dims,u=F.size(n),l=[{type:12,data:u},{type:6,data:t.pads}],d=e.length>=3&&e[2].data;t.mode===0&&l.push({type:d?e[2].dataType:1,data:t.value}),l.push(...ue(e[0].dims,n));let c=["rank"],s=r=>{let o=oe("output",e[0].dataType,n.length),a=j("x",e[0].dataType,i.length),p=a.type.value,h=my(o,i.length,t),m=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&m.push({name:"constant_value",type:d?p:"f32"}),` + `},_y=(e,t,n)=>{switch(n.mode){case 0:return gy(e,t,n.pads.length);case 1:return by(e,t,n.pads.length);case 2:return yy(e,t,n.pads.length);case 3:return wy(e,t,n.pads.length);default:throw new Error("Invalid mode")}},vy=(e,t)=>{let n=F.padShape(e[0].dims.slice(),t.pads),i=e[0].dims,u=F.size(n),l=[{type:12,data:u},{type:6,data:t.pads}],d=e.length>=3&&e[2].data;t.mode===0&&l.push({type:d?e[2].dataType:1,data:t.value}),l.push(...ue(e[0].dims,n));let c=["rank"],s=r=>{let o=oe("output",e[0].dataType,n.length),a=j("x",e[0].dataType,i.length),p=a.type.value,h=_y(o,i.length,t),m=[{name:"output_size",type:"u32"},{name:"pads",type:"i32",length:t.pads.length}];return t.mode===0&&m.push({name:"constant_value",type:d?p:"f32"}),` ${r.registerUniforms(m).declareVariables(a,o)} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -4046,7 +4046,7 @@ fn calculateOutputIndex(index: u32) -> u32 { var value = ${p}(0); ${h} output[global_idx] = value; - }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${d}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(F.size(n)/64)},programUniforms:l}),getShaderSource:s}},by=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),i=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,u=e[0].dims.length,l=new Int32Array(2*u).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let s=0;sl[Number(s)]=Number(c));let d=[];return l.forEach(c=>d.push(c)),{mode:t.mode,value:i,pads:d}}else return t},U2=(e,t)=>{dy(e.inputs);let n=by(e.inputs,t);e.compute(gy(e.inputs,n),{inputs:[0]})}}),mi,xu,$u,Tu,Su,yy,wy,Iu,Ou,V2,q2,Eu,G2,H2,Au,W2,K2,X2,Z2,kk=D(()=>{"use strict";dt(),de(),pe(),he(),mi=e=>{if(me.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},xu=(e,t,n)=>{let i=t.format==="NHWC",u=e.dims.slice();i&&u.splice(1,0,u.pop());let l=Object.hasOwnProperty.call(t,"dilations"),d=t.kernelShape.slice(),c=t.strides.slice(),s=l?t.dilations.slice():[],r=t.pads.slice();Wo.adjustPoolAttributes(n,u,d,c,s,r);let o=Wo.computePoolOutputShape(n,u,c,s,d,r,t.autoPad,t.ceilMode),a=Object.assign({},t);l?Object.assign(a,{kernelShape:d,strides:c,pads:r,dilations:s,cacheKey:t.cacheKey}):Object.assign(a,{kernelShape:d,strides:c,pads:r,cacheKey:t.cacheKey});let p=o.slice();return p.push(p.splice(1,1)[0]),[a,i?p:o]},$u=(e,t)=>{let n=t.format==="NHWC",i=F.size(e),u=F.size(t.kernelShape),l=[{type:12,data:i},{type:12,data:u}],d=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let c=t.kernelShape[t.kernelShape.length-1],s=t.strides[t.strides.length-1],r=t.pads[t.pads.length/2-1],o=t.pads[t.pads.length-1],a=!!(r+o);l.push({type:12,data:c},{type:12,data:s},{type:12,data:r},{type:12,data:o}),d.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let p=!1;if(t.kernelShape.length===2){let h=t.kernelShape[t.kernelShape.length-2],m=t.strides[t.strides.length-2],g=t.pads[t.pads.length/2-2],_=t.pads[t.pads.length-2];p=!!(g+_),l.push({type:12,data:h},{type:12,data:m},{type:12,data:g},{type:12,data:_}),d.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[l,d,!0,a,p]}else{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let c=F.computeStrides(t.kernelShape);l.push({type:12,data:c},{type:12,data:t.pads},{type:12,data:t.strides}),d.push({name:"kernelStrides",type:"u32",length:c.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let s=t.pads.reduce((r,o)=>r+o);return[l,d,!!s,!1,!1]}},Tu=(e,t,n,i,u,l,d,c,s,r,o,a)=>{let p=u.format==="NHWC",h=t.type.value,m=oe("output",t.type.tensor,i);if(u.kernelShape.length<=2){let g="",_="",w="",y=n-(p?2:1);if(o?g=` + }`};return{name:"Pad",shaderCache:{hint:`${t.mode}${d}`,inputDependencies:c},getRunData:()=>({outputs:[{dims:n,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(F.size(n)/64)},programUniforms:l}),getShaderSource:s}},xy=(e,t)=>{if(e.length>1){let n=e[1].getBigInt64Array(),i=e.length>=3&&e[2].data?e[2].dataType===10?e[2].getUint16Array()[0]:e[2].getFloat32Array()[0]:0,u=e[0].dims.length,l=new Int32Array(2*u).fill(0);if(e.length>=4){let c=e[3].getBigInt64Array();for(let s=0;sl[Number(s)]=Number(c));let d=[];return l.forEach(c=>d.push(c)),{mode:t.mode,value:i,pads:d}}else return t},W2=(e,t)=>{my(e.inputs);let n=xy(e.inputs,t);e.compute(vy(e.inputs,n),{inputs:[0]})}}),bi,Su,Iu,Ou,Eu,$y,Ty,Au,ku,K2,X2,Pu,Z2,Y2,Cu,J2,Q2,e$,t$,zk=D(()=>{"use strict";dt(),de(),pe(),he(),bi=e=>{if(me.webgpu.validateInputContent&&(!e||e.length!==1))throw new Error("Pool ops requires 1 input.")},Su=(e,t,n)=>{let i=t.format==="NHWC",u=e.dims.slice();i&&u.splice(1,0,u.pop());let l=Object.hasOwnProperty.call(t,"dilations"),d=t.kernelShape.slice(),c=t.strides.slice(),s=l?t.dilations.slice():[],r=t.pads.slice();Xo.adjustPoolAttributes(n,u,d,c,s,r);let o=Xo.computePoolOutputShape(n,u,c,s,d,r,t.autoPad,t.ceilMode),a=Object.assign({},t);l?Object.assign(a,{kernelShape:d,strides:c,pads:r,dilations:s,cacheKey:t.cacheKey}):Object.assign(a,{kernelShape:d,strides:c,pads:r,cacheKey:t.cacheKey});let p=o.slice();return p.push(p.splice(1,1)[0]),[a,i?p:o]},Iu=(e,t)=>{let n=t.format==="NHWC",i=F.size(e),u=F.size(t.kernelShape),l=[{type:12,data:i},{type:12,data:u}],d=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(t.kernelShape.length<=2){let c=t.kernelShape[t.kernelShape.length-1],s=t.strides[t.strides.length-1],r=t.pads[t.pads.length/2-1],o=t.pads[t.pads.length-1],a=!!(r+o);l.push({type:12,data:c},{type:12,data:s},{type:12,data:r},{type:12,data:o}),d.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let p=!1;if(t.kernelShape.length===2){let h=t.kernelShape[t.kernelShape.length-2],m=t.strides[t.strides.length-2],g=t.pads[t.pads.length/2-2],_=t.pads[t.pads.length-2];p=!!(g+_),l.push({type:12,data:h},{type:12,data:m},{type:12,data:g},{type:12,data:_}),d.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[l,d,!0,a,p]}else{if(n)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let c=F.computeStrides(t.kernelShape);l.push({type:12,data:c},{type:12,data:t.pads},{type:12,data:t.strides}),d.push({name:"kernelStrides",type:"u32",length:c.length},{name:"pads",type:"u32",length:t.pads.length},{name:"strides",type:"u32",length:t.strides.length});let s=t.pads.reduce((r,o)=>r+o);return[l,d,!!s,!1,!1]}},Ou=(e,t,n,i,u,l,d,c,s,r,o,a)=>{let p=u.format==="NHWC",h=t.type.value,m=oe("output",t.type.tensor,i);if(u.kernelShape.length<=2){let g="",_="",w="",y=n-(p?2:1);if(o?g=` for (var i: u32 = 0u; i < uniforms.kw; i++) { xIndices[${y}] = indices[${y}] * uniforms.sw - uniforms.pwStart + i; if (xIndices[${y}] < 0 || xIndices[${y}] @@ -4135,10 +4135,10 @@ fn calculateOutputIndex(index: u32) -> u32 { ${d} output[global_idx] = value; - }`}},Su=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,yy=e=>`${Su(e)};${e.countIncludePad}`,wy=e=>`${Su(e)};${e.storageOrder};${e.dilations}`,Iu=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),Ou=(e,t,n,i)=>{let[u,l]=xu(t,i,n),d=j("x",t.dataType,t.dims.length),c=d.type.value,s="value += x_val;",r="";u.countIncludePad?r+=`value /= ${c}(uniforms.kernelSize);`:r+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[o,a,p,h,m]=$u(l,u);o.push(...ue(t.dims,l));let g=["rank"];return{name:e,shaderCache:{hint:`${i.cacheKey};${p};${h};${m}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(F.size(l)/64)},programUniforms:o}),getShaderSource:_=>Tu(_,d,t.dims.length,l.length,u,s,r,0,a,p,h,m)}},V2=e=>{let t=e.count_include_pad!==0,n=Iu(e);if(n.ceilMode!==0)throw new Error("ceil_mode output-shape is computed, but ceil_mode kernel execution (padding/divisor) is not yet implemented in the WebGPU AveragePool kernel");let i={countIncludePad:t,...n,cacheKey:""};return{...i,cacheKey:yy(i)}},q2=(e,t)=>{mi(e.inputs),e.compute(Ou("AveragePool",e.inputs[0],!1,t))},Eu={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},G2=e=>{let t=e.format;return{format:t,...Eu,cacheKey:t}},H2=(e,t)=>{mi(e.inputs),e.compute(Ou("GlobalAveragePool",e.inputs[0],!0,t))},Au=(e,t,n,i)=>{let[u,l]=xu(t,i,n),d=` + }`}},Eu=e=>`${e.format};${e.ceilMode};${e.autoPad};${e.kernelShape.length}`,$y=e=>`${Eu(e)};${e.countIncludePad}`,Ty=e=>`${Eu(e)};${e.storageOrder};${e.dilations}`,Au=e=>({format:e.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][e.auto_pad],ceilMode:e.ceil_mode,kernelShape:e.kernel_shape,strides:e.strides,pads:e.pads}),ku=(e,t,n,i)=>{let[u,l]=Su(t,i,n),d=j("x",t.dataType,t.dims.length),c=d.type.value,s="value += x_val;",r="";u.countIncludePad?r+=`value /= ${c}(uniforms.kernelSize);`:r+=`value /= ${c}(i32(uniforms.kernelSize) - pad);`;let[o,a,p,h,m]=Iu(l,u);o.push(...ue(t.dims,l));let g=["rank"];return{name:e,shaderCache:{hint:`${i.cacheKey};${p};${h};${m}`,inputDependencies:g},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(F.size(l)/64)},programUniforms:o}),getShaderSource:_=>Ou(_,d,t.dims.length,l.length,u,s,r,0,a,p,h,m)}},K2=e=>{let t=e.count_include_pad!==0,n=Au(e);if(n.ceilMode!==0)throw new Error("ceil_mode output-shape is computed, but ceil_mode kernel execution (padding/divisor) is not yet implemented in the WebGPU AveragePool kernel");let i={countIncludePad:t,...n,cacheKey:""};return{...i,cacheKey:$y(i)}},X2=(e,t)=>{bi(e.inputs),e.compute(ku("AveragePool",e.inputs[0],!1,t))},Pu={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},Z2=e=>{let t=e.format;return{format:t,...Pu,cacheKey:t}},Y2=(e,t)=>{bi(e.inputs),e.compute(ku("GlobalAveragePool",e.inputs[0],!0,t))},Cu=(e,t,n,i)=>{let[u,l]=Su(t,i,n),d=` value = max(x_val, value); - `,c="",s=j("x",t.dataType,t.dims.length),r=["rank"],[o,a,p,h,m]=$u(l,u);return o.push(...ue(t.dims,l)),{name:e,shaderCache:{hint:`${i.cacheKey};${p};${h};${m}`,inputDependencies:r},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(F.size(l)/64)},programUniforms:o}),getShaderSource:g=>Tu(g,s,t.dims.length,l.length,u,d,c,t.dataType===10?-65504:-1e5,a,p,h,m)}},W2=(e,t)=>{mi(e.inputs),e.compute(Au("MaxPool",e.inputs[0],!1,t))},K2=e=>{let t=e.storage_order,n=e.dilations,i=Iu(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(i.ceilMode!==0)throw new Error("ceil_mode output-shape is computed, but ceil_mode kernel execution (padding) is not yet implemented in the WebGPU MaxPool kernel");let u={storageOrder:t,dilations:n,...i,cacheKey:""};return{...u,cacheKey:wy(u)}},X2=e=>{let t=e.format;return{format:t,...Eu,cacheKey:t}},Z2=(e,t)=>{mi(e.inputs),e.compute(Au("GlobalMaxPool",e.inputs[0],!0,t))}}),_y,vy,Y2,J2,Pk=D(()=>{"use strict";de(),pe(),He(),he(),_y=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((n,i)=>n===e[2].dims[i]).reduce((n,i)=>n&&i,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((u,l)=>l===t.axis||u===e[0].dims[l]).reduce((u,l)=>u&&l,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let n=e[0].dims[t.axis],i=e[1].dims[t.axis];if(t.blockSizeMath.ceil(n/(i-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},vy=(e,t)=>{let n=F.normalizeAxis(t.axis,e[0].dims.length),i=e[0].dataType,u=i===3,l=e[0].dims,d=e[1].dataType,c=F.size(l),s=i===3||i===2,r=s?[Math.ceil(F.size(e[0].dims)/4)]:e[0].dims,o=e[1].dims,a=e.length>2?e[2]:void 0,p=a?s?[Math.ceil(F.size(a.dims)/4)]:a.dims:void 0,h=o.length===0||o.length===1&&o[0]===1,m=h===!1&&o.length===1,g=Ge(c),_=h&&(!s||g===4),w=_?g:1,y=_&&!s?g:1,T=j("input",s?12:i,r.length,y),S=j("scale",d,o.length),O=a?j("zero_point",s?12:i,p.length):void 0,A=oe("output",d,l.length,w),P=[T,S];O&&P.push(O);let I=[r,o];a&&I.push(p);let z=[{type:12,data:c/w},{type:12,data:n},{type:12,data:t.blockSize},...ue(...I,l)],G=J=>{let q=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` - ${J.registerUniforms(q).declareVariables(...P,A)} + `,c="",s=j("x",t.dataType,t.dims.length),r=["rank"],[o,a,p,h,m]=Iu(l,u);return o.push(...ue(t.dims,l)),{name:e,shaderCache:{hint:`${i.cacheKey};${p};${h};${m}`,inputDependencies:r},getRunData:()=>({outputs:[{dims:l,dataType:t.dataType}],dispatchGroup:{x:Math.ceil(F.size(l)/64)},programUniforms:o}),getShaderSource:g=>Ou(g,s,t.dims.length,l.length,u,d,c,t.dataType===10?-65504:-1e5,a,p,h,m)}},J2=(e,t)=>{bi(e.inputs),e.compute(Cu("MaxPool",e.inputs[0],!1,t))},Q2=e=>{let t=e.storage_order,n=e.dilations,i=Au(e);if(t!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(i.ceilMode!==0)throw new Error("ceil_mode output-shape is computed, but ceil_mode kernel execution (padding) is not yet implemented in the WebGPU MaxPool kernel");let u={storageOrder:t,dilations:n,...i,cacheKey:""};return{...u,cacheKey:Ty(u)}},e$=e=>{let t=e.format;return{format:t,...Pu,cacheKey:t}},t$=(e,t)=>{bi(e.inputs),e.compute(Cu("GlobalMaxPool",e.inputs[0],!0,t))}}),Sy,Iy,r$,n$,Bk=D(()=>{"use strict";de(),pe(),He(),he(),Sy=(e,t)=>{if(e.length<2||e.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(e.length===3&&e[1].dims===e[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(e.length===3&&e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==0&&e[1].dims.length!==1&&e[1].dims.length!==e[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(e.length>2){if(e[0].dataType!==e[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(e[1].dims.length!==e[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!e[1].dims.map((n,i)=>n===e[2].dims[i]).reduce((n,i)=>n&&i,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(t.blockSize>0){if(e[1].dims.length===0||e[1].dims.length===1&&e[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!e[1].dims.map((u,l)=>l===t.axis||u===e[0].dims[l]).reduce((u,l)=>u&&l,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(e[1].dims.length!==e[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let n=e[0].dims[t.axis],i=e[1].dims[t.axis];if(t.blockSizeMath.ceil(n/(i-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},Iy=(e,t)=>{let n=F.normalizeAxis(t.axis,e[0].dims.length),i=e[0].dataType,u=i===3,l=e[0].dims,d=e[1].dataType,c=F.size(l),s=i===3||i===2,r=s?[Math.ceil(F.size(e[0].dims)/4)]:e[0].dims,o=e[1].dims,a=e.length>2?e[2]:void 0,p=a?s?[Math.ceil(F.size(a.dims)/4)]:a.dims:void 0,h=o.length===0||o.length===1&&o[0]===1,m=h===!1&&o.length===1,g=qe(c),_=h&&(!s||g===4),w=_?g:1,y=_&&!s?g:1,T=j("input",s?12:i,r.length,y),S=j("scale",d,o.length),O=a?j("zero_point",s?12:i,p.length):void 0,A=oe("output",d,l.length,w),P=[T,S];O&&P.push(O);let I=[r,o];a&&I.push(p);let z=[{type:12,data:c/w},{type:12,data:n},{type:12,data:t.blockSize},...ue(...I,l)],q=J=>{let G=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return` + ${J.registerUniforms(G).declareVariables(...P,A)} ${J.mainStart()} ${J.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} let output_indices = ${A.offsetToIndices("global_idx")}; @@ -4175,12 +4175,12 @@ fn calculateOutputIndex(index: u32) -> u32 { let zero_point_value = zero_point_vec[zero_point_offset % 4];`:`let zero_point_value = ${O.getByIndices("scale_indices")};`:`let zero_point_value = ${s?u?"i32":"u32":T.type.value}(0);`}; // Compute and write output ${A.setByOffset("global_idx",`${A.type.value}(x_value - zero_point_value) * scale_value`)}; - }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:O?["rank","rank","rank"]:["rank","rank"]},getShaderSource:G,getRunData:()=>({outputs:[{dims:l,dataType:d}],dispatchGroup:{x:Math.ceil(c/w/64),y:1,z:1},programUniforms:z})}},Y2=(e,t)=>{_y(e.inputs,t),e.compute(vy(e.inputs,t))},J2=e=>ke({axis:e.axis,blockSize:e.blockSize})}),xy,$y,Q2,Ck=D(()=>{"use strict";dt(),de(),he(),xy=(e,t,n)=>{let i=e===t,u=et&&n>0;if(i||u||l)throw new Error("Range these inputs' contents are invalid.")},$y=(e,t,n,i)=>{let u=Math.abs(Math.ceil((t-e)/n)),l=[u],d=u,c=[{type:12,data:d},{type:i,data:e},{type:i,data:n},...ue(l)],s=r=>{let o=oe("output",i,l.length),a=o.type.value,p=[{name:"outputSize",type:"u32"},{name:"start",type:a},{name:"delta",type:a}];return` + }`};return{name:"DequantizeLinear",shaderCache:{hint:t.cacheKey,inputDependencies:O?["rank","rank","rank"]:["rank","rank"]},getShaderSource:q,getRunData:()=>({outputs:[{dims:l,dataType:d}],dispatchGroup:{x:Math.ceil(c/w/64),y:1,z:1},programUniforms:z})}},r$=(e,t)=>{Sy(e.inputs,t),e.compute(Iy(e.inputs,t))},n$=e=>ke({axis:e.axis,blockSize:e.blockSize})}),Oy,Ey,i$,Fk=D(()=>{"use strict";dt(),de(),he(),Oy=(e,t,n)=>{let i=e===t,u=et&&n>0;if(i||u||l)throw new Error("Range these inputs' contents are invalid.")},Ey=(e,t,n,i)=>{let u=Math.abs(Math.ceil((t-e)/n)),l=[u],d=u,c=[{type:12,data:d},{type:i,data:e},{type:i,data:n},...ue(l)],s=r=>{let o=oe("output",i,l.length),a=o.type.value,p=[{name:"outputSize",type:"u32"},{name:"start",type:a},{name:"delta",type:a}];return` ${r.registerUniforms(p).declareVariables(o)} ${r.mainStart()} ${r.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} output[global_idx] = uniforms.start + ${a}(global_idx) * uniforms.delta; - }`};return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:s,getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c})}},Q2=e=>{let t=0,n=0,i=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],i=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],i=e.inputs[2].getFloat32Array()[0]),me.webgpu.validateInputContent&&xy(t,n,i),e.compute($y(t,n,i,e.inputs[0].dataType),{inputs:[]})}}),Ty,Sy,e$,t$,Rk=D(()=>{"use strict";de(),pe(),He(),he(),Ty=(e,t,n,i)=>{if(e!=="none"&&i!=="i32"&&i!=="u32"&&i!=="f32")throw new Error(`Input ${i} is not supported with reduction ${e}.`);let u=`{ + }`};return{name:"Range",shaderCache:{hint:`${i}`},getShaderSource:s,getRunData:()=>({outputs:[{dims:l,dataType:i}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:c})}},i$=e=>{let t=0,n=0,i=0;e.inputs[0].dataType===6?(t=e.inputs[0].getInt32Array()[0],n=e.inputs[1].getInt32Array()[0],i=e.inputs[2].getInt32Array()[0]):e.inputs[0].dataType===1&&(t=e.inputs[0].getFloat32Array()[0],n=e.inputs[1].getFloat32Array()[0],i=e.inputs[2].getFloat32Array()[0]),me.webgpu.validateInputContent&&Oy(t,n,i),e.compute(Ey(t,n,i,e.inputs[0].dataType),{inputs:[]})}}),Ay,ky,o$,s$,Lk=D(()=>{"use strict";de(),pe(),He(),he(),Ay=(e,t,n,i)=>{if(e!=="none"&&i!=="i32"&&i!=="u32"&&i!=="f32")throw new Error(`Input ${i} is not supported with reduction ${e}.`);let u=`{ var oldValue = 0; loop { let newValueF32 =`,l=`; @@ -4193,7 +4193,7 @@ fn calculateOutputIndex(index: u32) -> u32 { } }`;switch(e){case"none":return`${t}=${n};`;case"add":return i==="i32"||i==="u32"?`atomicAdd(&${t}, bitcast<${i}>(${n}));`:` ${u}bitcast<${i}>(oldValue) + (${n})${l}`;case"max":return i==="i32"||i==="u32"?`atomicMax(&${t}, bitcast<${i}>(${n}));`:` - ${u}max(bitcast(oldValue), (${n}))${l}`;case"min":return i==="i32"||i==="u32"?`atomicMin(&${t}, bitcast<${i}>(${n}));`:`${u}min(bitcast<${i}>(oldValue), (${n}))${l}`;case"mul":return`${u}(bitcast<${i}>(oldValue) * (${n}))${l}`;default:throw new Error(`Reduction ${e} is not supported.`)}},Sy=(e,t)=>{let n=e[0].dims,i=e[1].dims,u=n,l=1,d=Math.ceil(F.sizeToDimension(i,i.length-1)/l),c=i[i.length-1],s=F.sizeFromDimension(n,c),r=[{type:12,data:d},{type:12,data:c},{type:12,data:s},...ue(e[1].dims,e[2].dims,u)],o=a=>{let p=j("indices",e[1].dataType,e[1].dims.length),h=j("updates",e[2].dataType,e[2].dims.length,l),m=t.reduction!=="none"&&t.reduction!==""?Ix("output",e[0].dataType,u.length):oe("output",e[0].dataType,u.length,l);return` + ${u}max(bitcast(oldValue), (${n}))${l}`;case"min":return i==="i32"||i==="u32"?`atomicMin(&${t}, bitcast<${i}>(${n}));`:`${u}min(bitcast<${i}>(oldValue), (${n}))${l}`;case"mul":return`${u}(bitcast<${i}>(oldValue) * (${n}))${l}`;default:throw new Error(`Reduction ${e} is not supported.`)}},ky=(e,t)=>{let n=e[0].dims,i=e[1].dims,u=n,l=1,d=Math.ceil(F.sizeToDimension(i,i.length-1)/l),c=i[i.length-1],s=F.sizeFromDimension(n,c),r=[{type:12,data:d},{type:12,data:c},{type:12,data:s},...ue(e[1].dims,e[2].dims,u)],o=a=>{let p=j("indices",e[1].dataType,e[1].dims.length),h=j("updates",e[2].dataType,e[2].dims.length,l),m=t.reduction!=="none"&&t.reduction!==""?Px("output",e[0].dataType,u.length):oe("output",e[0].dataType,u.length,l);return` ${a.registerUniform("output_size","u32").registerUniform("last_index_dimension","u32").registerUniform("num_updates_elements","u32").declareVariables(p,h,m)} ${a.mainStart()} ${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")} @@ -4223,11 +4223,11 @@ fn calculateOutputIndex(index: u32) -> u32 { for (var i = 0u; i < uniforms.num_updates_elements; i++) { let value = updates[uniforms.num_updates_elements * global_idx + i]; - ${Ty(t.reduction,"output[data_offset + i]","value",m.type.value)} + ${Ay(t.reduction,"output[data_offset + i]","value",m.type.value)} } - }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:r}),getShaderSource:o}},e$=e=>ke({reduction:e.reduction}),t$=(e,t)=>{e.compute(Sy(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Iy,Oy,Ey,ku,Ay,ky,Py,Cy,Ry,Dy,My,Ny,Pu,zy,By,Fy,Ly,jy,r$,n$,Dk=D(()=>{"use strict";de(),pe(),He(),he(),Iy=(e,t)=>{if(e.every(n=>n>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and - one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Oy=(e,t,n)=>{t.every(u=>u>=0&&u{throw new Error("Resize requires axes input values to be positive and less than rank")}));let i=new Array(n).fill(1);return t.forEach((u,l)=>i[u]=e[l]),i},Ey=(e,t,n,i,u,l)=>{let[d,c,s]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],r=e[0].dims.length;if(d>0&&e.length>d&&e[d].dims.length>0)e[d].getFloat32Array().forEach(o=>l.push(o));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(c>0&&e.length>c&&e[c].dims.length===1&&e[c].dims[0]>0){if(e[c].getFloat32Array().forEach(o=>i.push(o)),i.length!==0&&i.length!==r&&n>=18&&i.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Iy(i,t),t.axes.length>0&&Oy(i,t.axes,r).forEach((o,a)=>i[a]=o)}if(s>0&&e.length>s&&e[s].dims.length===1&&e[s].dims[0]>0&&(e[s].getBigInt64Array().forEach(o=>u.push(Number(o))),u.length!==0&&u.length!==r&&n>=18&&u.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(u.length!==0&&u.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof i<"u"&&typeof u<"u"&&i.length>0&&u.length>r)throw new Error("Resize requires only of scales or sizes to be specified")},ku=(e,t,n,i)=>` + }`};return{name:"ScatterND",shaderCache:{hint:`${t.cacheKey}_${t.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(d/64)},programUniforms:r}),getShaderSource:o}},o$=e=>ke({reduction:e.reduction}),s$=(e,t)=>{e.compute(ky(e.inputs,t),{inputs:[e.inputs[1],e.inputs[2]],outputs:[]})}}),Py,Cy,Ry,Ru,Dy,My,Ny,zy,By,Fy,Ly,jy,Du,Uy,Vy,Gy,qy,Hy,a$,u$,jk=D(()=>{"use strict";de(),pe(),He(),he(),Py=(e,t)=>{if(e.every(n=>n>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),e.length>0){if(t.mode==="linear"){if(!(e.length===2||e.length===3||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1||e.length===5&&e[0]===1&&e[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and + one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(t.mode==="cubic"&&!(e.length===2||e.length===4&&e[0]===1&&e[1]===1||e.length===4&&e[0]===1&&e[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Cy=(e,t,n)=>{t.every(u=>u>=0&&u{throw new Error("Resize requires axes input values to be positive and less than rank")}));let i=new Array(n).fill(1);return t.forEach((u,l)=>i[u]=e[l]),i},Ry=(e,t,n,i,u,l)=>{let[d,c,s]=n>10?[1,2,3]:[-1,e.length>1?1:-1,-1],r=e[0].dims.length;if(d>0&&e.length>d&&e[d].dims.length>0)e[d].getFloat32Array().forEach(o=>l.push(o));else if(t.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(c>0&&e.length>c&&e[c].dims.length===1&&e[c].dims[0]>0){if(e[c].getFloat32Array().forEach(o=>i.push(o)),i.length!==0&&i.length!==r&&n>=18&&i.length!==t.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");Py(i,t),t.axes.length>0&&Cy(i,t.axes,r).forEach((o,a)=>i[a]=o)}if(s>0&&e.length>s&&e[s].dims.length===1&&e[s].dims[0]>0&&(e[s].getBigInt64Array().forEach(o=>u.push(Number(o))),u.length!==0&&u.length!==r&&n>=18&&u.length!==t.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(t.axes.length>0){if(i.length!==0&&i.length!==t.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(u.length!==0&&u.length!==t.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof i<"u"&&typeof u<"u"&&i.length>0&&u.length>r)throw new Error("Resize requires only of scales or sizes to be specified")},Ru=(e,t,n,i)=>` // 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(). @@ -4235,12 +4235,12 @@ fn calculateOutputIndex(index: u32) -> u32 { let whole = ${i}(big / (${n})); let fract = ${i}(big % (${n})) / ${i}(${n}); return whole + fract; -`,Ay=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, +`,Dy=(e,t)=>`fn getOriginalCoordinateFromResizedCoordinate(xResized: u32, xScale: f32, lengthResized: u32, lengthOriginal: u32, roiStart: f32, roiEnd: f32) -> ${t} { `+(()=>{switch(e){case"asymmetric":return` if (xScale < 1.0 || floor(xScale) != xScale) { return ${t}(xResized) / ${t}(xScale); } else { - ${ku("xResized","lengthOriginal","lengthResized",t)} + ${Ru("xResized","lengthOriginal","lengthResized",t)} } `;case"pytorch_half_pixel":return`if (lengthResized > 1) { return (${t}(xResized) + 0.5) / ${t}(xScale) - 0.5; @@ -4249,7 +4249,7 @@ fn calculateOutputIndex(index: u32) -> u32 { }`;case"tf_half_pixel_for_nn":return`return (${t}(xResized) + 0.5) / ${t}(xScale);`;case"align_corners":return`if (lengthResized == 1) { return 0.0; } else { - ${ku("xResized","lengthOriginal - 1","lengthResized - 1",t)} + ${Ru("xResized","lengthOriginal - 1","lengthResized - 1",t)} }`;case"tf_crop_and_resize":return`if (lengthResized > 1) { return ${t}(roiStart) * ${t}(lengthOriginal - 1) + (${t}(xResized) * ${t}(roiEnd - roiStart) * ${t}(lengthOriginal - 1)) / @@ -4260,7 +4260,7 @@ fn calculateOutputIndex(index: u32) -> u32 { const adjustment = ${t}(lengthResized) / outputWidth; const center = ${t}(lengthOriginal) / 2; const offset = center * (1 - adjustment); - return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",ky=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Py=(e,t,n)=>{let i=new Array(n).fill(0).concat(new Array(n).fill(1)),u=e.length===0?i:e.slice();return t.length>0?(t.forEach((l,d)=>{i[l]=u[d],i[d+n]=u[t.length+d]}),i):u},Cy=(e,t,n,i)=>{let u=[];if(n.length>0)if(i.length>0){if(e.forEach(l=>u.push(l)),Math.max(...i)>e.length)throw new Error("axes is out of bound");i.forEach((l,d)=>u[l]=n[d])}else n.forEach(l=>u.push(l));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");u=e.map((l,d)=>Math.round(l*t[d]))}return u},Ry=(e,t,n)=>{let i=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map(l=>t[l]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map(l=>t[l]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let u=e.slice();return n.axes.length>0?(n.axes.forEach(l=>t[l]=i),n.axes.forEach(l=>u[l]=Math.round(e[l]*t[l]))):(t.fill(i,0,t.length),u.forEach((l,d)=>u[d]=Math.round(l*t[d]))),u},Dy=(e,t,n,i,u)=>` + return offset + ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;case"half_pixel":return`return ((${t}(xResized) + 0.5) / ${t}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${e} is not supported`)}})()+"}",My=(e,t,n)=>`fn getNearestPixelFromOriginal(xOriginal: ${n}, isDownSample: bool) -> ${n} {`+(()=>{switch(e){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";default:if(t<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${e} is not supported`)}})()+"}",Ny=(e,t,n)=>{let i=new Array(n).fill(0).concat(new Array(n).fill(1)),u=e.length===0?i:e.slice();return t.length>0?(t.forEach((l,d)=>{i[l]=u[d],i[d+n]=u[t.length+d]}),i):u},zy=(e,t,n,i)=>{let u=[];if(n.length>0)if(i.length>0){if(e.forEach(l=>u.push(l)),Math.max(...i)>e.length)throw new Error("axes is out of bound");i.forEach((l,d)=>u[l]=n[d])}else n.forEach(l=>u.push(l));else{if(t.length===0)throw new Error("Resize requires either scales or sizes.");u=e.map((l,d)=>Math.round(l*t[d]))}return u},By=(e,t,n)=>{let i=(()=>{switch(n.keepAspectRatioPolicy){case"not_larger":return n.axes.length>0?Math.min(...n.axes.map(l=>t[l]),Number.MAX_VALUE):Math.min(...t,Number.MAX_VALUE);case"not_smaller":return n.axes.length>0?Math.max(...n.axes.map(l=>t[l]),Number.MIN_VALUE):Math.max(...t,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${n.keepAspectRatioPolicy} is not supported`)}})();t.fill(1,0,t.length);let u=e.slice();return n.axes.length>0?(n.axes.forEach(l=>t[l]=i),n.axes.forEach(l=>u[l]=Math.round(e[l]*t[l]))):(t.fill(i,0,t.length),u.forEach((l,d)=>u[d]=Math.round(l*t[d]))),u},Fy=(e,t,n,i,u)=>` fn calculateOriginalIndicesFromOutputIndices(output_indices: ${e.type.indices}) -> array<${e.type.value}, ${n.length}> { var original_indices: array<${e.type.value}, ${n.length}>; for (var i:u32 = 0; i < ${n.length}; i++) { @@ -4278,7 +4278,7 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return original_indices; - }`,My=(e,t,n,i,u,l,d)=>` + }`,Ly=(e,t,n,i,u,l,d)=>` fn calculateInputIndicesFromOutputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; for (var i:u32 = 0; i < ${i.length}; i++) { @@ -4309,7 +4309,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.indicesSet("input_indices","i","input_index")} } return input_indices; - }`,Ny=(e,t)=>` + }`,jy=(e,t)=>` fn checkInputIndices(input_indices: ${e.type.indices}) -> bool { for (var i:u32 = 0; i < ${t.length}; i++) { var input_index = ${e.indicesGet("input_indices","i")}; @@ -4318,15 +4318,15 @@ fn calculateOutputIndex(index: u32) -> u32 { } } return true; - }`,Pu=(e,t,n,i)=>e.rank>i?` + }`,Du=(e,t,n,i)=>e.rank>i?` ${e.indicesSet("input_indices",t,"channel")}; ${e.indicesSet("input_indices",n,"batch")}; -`:"",zy=(e,t,n,i,u)=>{let[l,d,c,s]=n.length===2?[-1,0,1,-1]:[0,2,3,1],r=e.type.value;return` +`:"",Uy=(e,t,n,i,u)=>{let[l,d,c,s]=n.length===2?[-1,0,1,-1]:[0,2,3,1],r=e.type.value;return` fn getInputValue(batch: u32, channel: u32, row: u32, col: u32) -> ${r} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",d,`max(0, min(row, ${n[d]} - 1))`)}; ${e.indicesSet("input_indices",c,`max(0, min(col, ${n[c]} - 1))`)}; - ${Pu(e,s,l,2)} + ${Du(e,s,l,2)} return ${e.getByIndices("input_indices")}; } @@ -4362,7 +4362,7 @@ fn calculateOutputIndex(index: u32) -> u32 { dy2 = 0.5; } return (x11 * dx2 * dy2 + x12 * dx2 * dy1 + x21 * dx1 * dy2 + x22 * dx1 * dy1); - }`},By=(e,t,n,i,u,l,d,c,s,r)=>{let o=n.length===2,a=!0,[p,h]=o?[0,1]:a?[2,3]:[1,2],m=e.type.value,g=_=>{let w=_===p?"row":"col";return` + }`},Vy=(e,t,n,i,u,l,d,c,s,r)=>{let o=n.length===2,a=!0,[p,h]=o?[0,1]:a?[2,3]:[1,2],m=e.type.value,g=_=>{let w=_===p?"row":"col";return` fn ${w}CubicInterpolation(input_indices: ${e.type.indices}, output_indices: ${t.type.indices}) -> ${m} { var output_index = ${t.indicesGet("output_indices",_)}; var originalIdx: ${m} = getOriginalCoordinateFromResizedCoordinate(output_index, ${u[_]}, @@ -4410,13 +4410,13 @@ fn calculateOutputIndex(index: u32) -> u32 { var input_indices: ${e.type.indices} = output_indices; return colCubicInterpolation(input_indices, output_indices); } - `},Fy=(e,t,n,i,u)=>{let[l,d,c,s,r]=n.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],o=e.type.value;return` + `},Gy=(e,t,n,i,u)=>{let[l,d,c,s,r]=n.length===3?[-1,0,1,2,-1]:[0,2,3,4,1],o=e.type.value;return` fn getInputValue(batch: u32, channel: u32, depth:u32, height: u32, width: u32) -> ${o} { var input_indices: ${e.type.indices}; ${e.indicesSet("input_indices",d,`max(0, min(depth, ${n[d]} - 1))`)}; ${e.indicesSet("input_indices",c,`max(0, min(height, ${n[c]} - 1))`)}; ${e.indicesSet("input_indices",s,`max(0, min(width, ${n[s]} - 1))`)}; - ${Pu(e,r,l,3)} + ${Du(e,r,l,3)} return ${e.getByIndices("input_indices")}; } @@ -4469,18 +4469,18 @@ fn calculateOutputIndex(index: u32) -> u32 { } 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); - }`},Ly=(e,t,n,i,u,l)=>{let d=e.dims,c=Py(l,t.axes,d.length),s=Cy(d,i,u,t.axes),r=i.slice();i.length===0&&(r=d.map((y,T)=>y===0?1:s[T]/y),t.keepAspectRatioPolicy!=="stretch"&&(s=Ry(d,r,t)));let o=oe("output",e.dataType,s.length),a=j("input",e.dataType,d.length),p=F.size(s),h=d.length===s.length&&d.every((y,T)=>y===s[T]),m=t.coordinateTransformMode==="tf_crop_and_resize",g=t.extrapolationValue,_=a.type.value,w=y=>` + }`},qy=(e,t,n,i,u,l)=>{let d=e.dims,c=Ny(l,t.axes,d.length),s=zy(d,i,u,t.axes),r=i.slice();i.length===0&&(r=d.map((y,T)=>y===0?1:s[T]/y),t.keepAspectRatioPolicy!=="stretch"&&(s=By(d,r,t)));let o=oe("output",e.dataType,s.length),a=j("input",e.dataType,d.length),p=F.size(s),h=d.length===s.length&&d.every((y,T)=>y===s[T]),m=t.coordinateTransformMode==="tf_crop_and_resize",g=t.extrapolationValue,_=a.type.value,w=y=>` ${h?"":` - ${Ay(t.coordinateTransformMode,_)}; + ${Dy(t.coordinateTransformMode,_)}; ${(()=>{switch(t.mode){case"nearest":return` - ${Ny(a,d)}; - ${ky(t.nearestMode,n,_)}; - ${My(a,o,d,s,r.length,c.length,m)}; + ${jy(a,d)}; + ${My(t.nearestMode,n,_)}; + ${Ly(a,o,d,s,r.length,c.length,m)}; `;case"linear":return` - ${Dy(o,d,s,r.length,c.length)}; - ${(()=>{if(d.length===2||d.length===4)return`${zy(a,o,d,m,g)}`;if(d.length===3||d.length===5)return`${Fy(a,o,d,m,g)}`;throw Error("Linear mode only supports input dims 2, 3, 4 and 5 are supported in linear mode.")})()}; + ${Fy(o,d,s,r.length,c.length)}; + ${(()=>{if(d.length===2||d.length===4)return`${Uy(a,o,d,m,g)}`;if(d.length===3||d.length===5)return`${Gy(a,o,d,m,g)}`;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`${By(a,o,d,s,r,c,t.cubicCoeffA,m,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; + ${(()=>{if(d.length===2||d.length===4)return`${Vy(a,o,d,s,r,c,t.cubicCoeffA,m,t.extrapolationValue,t.excludeOutside)}`;throw Error("Cubic mode only supports input dims 2 and 4 are supported in linear mode.")})()}; `;default:throw Error("Invalid resize mode")}})()}; `} ${y.registerUniform("output_size","u32").registerUniform("scales","f32",r.length).registerUniform("roi","f32",c.length).declareVariables(a,o)} @@ -4496,7 +4496,7 @@ fn calculateOutputIndex(index: u32) -> u32 { output[global_idx] = ${t.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: ${t.mode}`)}})()}; `} - }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${r.length>0?t.mode==="cubic"?r:r.length:""}|${u.length>0?u:""}|${c.length>0?c:""}|${h}|${t.mode==="nearest"?d.length:d}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:s,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},{type:1,data:r},{type:1,data:c},...ue(d,s)]})}},jy=e=>{let t=e.customDataBuffer;return new Uint32Array(t.buffer,t.byteOffset,1)[0]},r$=(e,t)=>{let n=[],i=[],u=[],l=jy(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Ey(e.inputs,t,l,n,i,u),e.compute(Ly(e.inputs[0],t,l,n,i,u),{inputs:[0]})},n$=e=>{let t=e.antialias,n=e.axes,i=e.coordinateTransformMode,u=e.cubicCoeffA,l=e.excludeOutside!==0,d=e.extrapolationValue,c=e.keepAspectRatioPolicy,s=e.mode,r=e.nearestMode===""?"simple":e.nearestMode;return ke({antialias:t,axes:n,coordinateTransformMode:i,cubicCoeffA:u,excludeOutside:l,extrapolationValue:d,keepAspectRatioPolicy:c,mode:s,nearestMode:r})}}),Uy,Vy,i$,Mk=D(()=>{"use strict";de(),pe(),he(),Uy=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],n=e[1],i=e[2];if(t.dataType!==n.dataType||t.dataType!==i.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(n.dims.length!==3&&n.dims.length!==2)throw new Error("Skip must be 2D or 3D");let u=t.dims[t.dims.length-1],l=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==u)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==l)throw new Error("Skip must have the same sequence length as input");if(i.dims.length!==1)throw new Error("Gamma must be 1D");if(i.dims[i.dims.length-1]!==u)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let d=e[3];if(d.dims.length!==1)throw new Error("Beta must be 1D");if(d.dims[d.dims.length-1]!==u)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let d=e[4];if(d.dims.length!==1)throw new Error("Bias must be 1D");if(d.dims[d.dims.length-1]!==u)throw new Error("Bias must have the same hidden size as input")}},Vy=(e,t,n,i)=>{let u=t.simplified,l=e[0].dims,d=F.size(l),c=l,s=d,r=l.slice(-1)[0],o=i?l.slice(0,-1).concat(1):[],a=!u&&e.length>3,p=e.length>4,h=i&&n>1,m=i&&n>2,g=n>3,_=64,w=Ge(r),y=[{type:12,data:s},{type:12,data:w},{type:12,data:r},{type:1,data:t.epsilon}],T=O=>{let A=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],P=[j("x",e[0].dataType,e[0].dims,w),j("skip",e[1].dataType,e[1].dims,w),j("gamma",e[2].dataType,e[2].dims,w)];a&&P.push(j("beta",e[3].dataType,e[3].dims,w)),p&&P.push(j("bias",e[4].dataType,e[4].dims,w)),P.push(oe("output",e[0].dataType,c,w)),h&&P.push(oe("mean_output",1,o)),m&&P.push(oe("inv_std_output",1,o)),g&&P.push(oe("input_skip_bias_sum",e[0].dataType,c,w));let I=nt(e[0].dataType),z=nt(1,w);return` + }`;return{name:"Resize",shaderCache:{hint:`${t.cacheKey}|${n}|${r.length>0?t.mode==="cubic"?r:r.length:""}|${u.length>0?u:""}|${c.length>0?c:""}|${h}|${t.mode==="nearest"?d.length:d}`,inputDependencies:["rank"]},getShaderSource:w,getRunData:()=>({outputs:[{dims:s,dataType:e.dataType}],dispatchGroup:{x:Math.ceil(p/64)},programUniforms:[{type:12,data:p},{type:1,data:r},{type:1,data:c},...ue(d,s)]})}},Hy=e=>{let t=e.customDataBuffer;return new Uint32Array(t.buffer,t.byteOffset,1)[0]},a$=(e,t)=>{let n=[],i=[],u=[],l=Hy(e);if(t.antialias!==0)throw Error("Only default value (0) for Antialias attribute is supported");Ry(e.inputs,t,l,n,i,u),e.compute(qy(e.inputs[0],t,l,n,i,u),{inputs:[0]})},u$=e=>{let t=e.antialias,n=e.axes,i=e.coordinateTransformMode,u=e.cubicCoeffA,l=e.excludeOutside!==0,d=e.extrapolationValue,c=e.keepAspectRatioPolicy,s=e.mode,r=e.nearestMode===""?"simple":e.nearestMode;return ke({antialias:t,axes:n,coordinateTransformMode:i,cubicCoeffA:u,excludeOutside:l,extrapolationValue:d,keepAspectRatioPolicy:c,mode:s,nearestMode:r})}}),Wy,Ky,l$,Uk=D(()=>{"use strict";de(),pe(),he(),Wy=e=>{if(!e||e.length<3)throw new Error("layerNorm requires at least 3 inputs.");let t=e[0],n=e[1],i=e[2];if(t.dataType!==n.dataType||t.dataType!==i.dataType)throw new Error("All inputs must have the same data type");if(t.dims.length!==3&&t.dims.length!==2)throw new Error("Input must be 2D or 3D");if(n.dims.length!==3&&n.dims.length!==2)throw new Error("Skip must be 2D or 3D");let u=t.dims[t.dims.length-1],l=t.dims[t.dims.length-2];if(n.dims[n.dims.length-1]!==u)throw new Error("Skip must have the same hidden size as input");if(n.dims[n.dims.length-2]!==l)throw new Error("Skip must have the same sequence length as input");if(i.dims.length!==1)throw new Error("Gamma must be 1D");if(i.dims[i.dims.length-1]!==u)throw new Error("Gamma must have the same hidden size as input");if(e.length>3){let d=e[3];if(d.dims.length!==1)throw new Error("Beta must be 1D");if(d.dims[d.dims.length-1]!==u)throw new Error("Beta must have the same hidden size as input")}if(e.length>4){let d=e[4];if(d.dims.length!==1)throw new Error("Bias must be 1D");if(d.dims[d.dims.length-1]!==u)throw new Error("Bias must have the same hidden size as input")}},Ky=(e,t,n,i)=>{let u=t.simplified,l=e[0].dims,d=F.size(l),c=l,s=d,r=l.slice(-1)[0],o=i?l.slice(0,-1).concat(1):[],a=!u&&e.length>3,p=e.length>4,h=i&&n>1,m=i&&n>2,g=n>3,_=64,w=qe(r),y=[{type:12,data:s},{type:12,data:w},{type:12,data:r},{type:1,data:t.epsilon}],T=O=>{let A=[{name:"output_size",type:"u32"},{name:"components",type:"u32"},{name:"hidden_size",type:"u32"},{name:"epsilon",type:"f32"}],P=[j("x",e[0].dataType,e[0].dims,w),j("skip",e[1].dataType,e[1].dims,w),j("gamma",e[2].dataType,e[2].dims,w)];a&&P.push(j("beta",e[3].dataType,e[3].dims,w)),p&&P.push(j("bias",e[4].dataType,e[4].dims,w)),P.push(oe("output",e[0].dataType,c,w)),h&&P.push(oe("mean_output",1,o)),m&&P.push(oe("inv_std_output",1,o)),g&&P.push(oe("input_skip_bias_sum",e[0].dataType,c,w));let I=nt(e[0].dataType),z=nt(1,w);return` ${O.registerUniforms(A).declareVariables(...P)} var sum_shared : array<${z}, ${_}>; @@ -4548,7 +4548,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${I}(inv_std_dev) * gamma[offset1d + i] ${a?"+ beta[offset1d + i]":""}; } - }`},S=[{dims:c,dataType:e[0].dataType}];return n>1&&S.push({dims:o,dataType:1}),n>2&&S.push({dims:o,dataType:1}),n>3&&S.push({dims:l,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${h};${m};${g}`,inputDependencies:e.map((O,A)=>"type")},getShaderSource:T,getRunData:()=>({outputs:S,dispatchGroup:{x:Math.ceil(s/r)},programUniforms:y})}},i$=(e,t)=>{Uy(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Vy(e.inputs,t,e.outputCount,!1),{outputs:n})}}),qy,gi,Gy,Cu,Hy,Wy,o$,s$,Nk=D(()=>{"use strict";de(),pe(),He(),he(),qy=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((n,i)=>{if(e[i+1].dataType!==6&&e[i+1].dataType!==7)throw new Error(`Input ${i} must be an array of int32 or int64`)})},gi=(e,t)=>{let n=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(i=>n.push(Number(i)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(i=>n.push(Number(i)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return n},Gy=(e,t)=>{if(e.length>1){let n=gi(e,1),i=gi(e,2),u=gi(e,3);return u.length===0&&(u=[...Array(e[0].dims.length).keys()]),ke({starts:n,ends:i,axes:u})}else return t},Cu=(e,t,n,i,u)=>{let l=e;return e<0&&(l+=n[i[t]]),u[t]<0?Math.max(0,Math.min(l,n[i[t]]-1)):Math.max(0,Math.min(l,n[i[t]]))},Hy=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { + }`},S=[{dims:c,dataType:e[0].dataType}];return n>1&&S.push({dims:o,dataType:1}),n>2&&S.push({dims:o,dataType:1}),n>3&&S.push({dims:l,dataType:e[0].dataType}),{name:"SkipLayerNormalization",shaderCache:{hint:`${w};${h};${m};${g}`,inputDependencies:e.map((O,A)=>"type")},getShaderSource:T,getRunData:()=>({outputs:S,dispatchGroup:{x:Math.ceil(s/r)},programUniforms:y})}},l$=(e,t)=>{Wy(e.inputs);let n=[0];e.outputCount>1&&n.push(-3),e.outputCount>2&&n.push(-3),e.outputCount>3&&n.push(3),e.compute(Ky(e.inputs,t,e.outputCount,!1),{outputs:n})}}),Xy,yi,Zy,Mu,Yy,Jy,d$,c$,Vk=D(()=>{"use strict";de(),pe(),He(),he(),Xy=(e,t)=>{if(!e||e.length<1)throw new Error("too few inputs");if(t.axes.length!==0){if(t.axes.length!==t.starts.length||t.axes.length!==t.ends.length)throw new Error("axes, starts and ends must have the same length")}else if(t.starts.length!==t.ends.length)throw new Error("starts and ends must have the same length");e.slice(1).forEach((n,i)=>{if(e[i+1].dataType!==6&&e[i+1].dataType!==7)throw new Error(`Input ${i} must be an array of int32 or int64`)})},yi=(e,t)=>{let n=[];if(e.length>t)if(e[t].dataType===7)e[t].getBigInt64Array().forEach(i=>n.push(Number(i)));else if(e[t].dataType===6)e[t].getInt32Array().forEach(i=>n.push(Number(i)));else throw new Error(`Input ${t} must be an array of int32 or int64`);return n},Zy=(e,t)=>{if(e.length>1){let n=yi(e,1),i=yi(e,2),u=yi(e,3);return u.length===0&&(u=[...Array(e[0].dims.length).keys()]),ke({starts:n,ends:i,axes:u})}else return t},Mu=(e,t,n,i,u)=>{let l=e;return e<0&&(l+=n[i[t]]),u[t]<0?Math.max(0,Math.min(l,n[i[t]]-1)):Math.max(0,Math.min(l,n[i[t]]))},Yy=(e,t,n)=>`fn calculateInputIndices(output_indices: ${t.type.indices}) -> ${e.type.indices} { var input_indices: ${e.type.indices}; var carry = 0u; for (var i = ${n.length-1}; i >= 0; i--) { @@ -4566,15 +4566,15 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.indicesSet("input_indices","i","input_index")}; } return input_indices; - }`,Wy=(e,t)=>{let n=e[0].dims,i=F.size(n),u=t.axes.length>0?F.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],l=gi(e,4);l.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),l.length===0&&(l=Array(u.length).fill(1));let d=t.starts.map((w,y)=>Cu(w,y,n,u,l)),c=t.ends.map((w,y)=>Cu(w,y,n,u,l));if(u.length!==d.length||u.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(u.length!==n.length)for(let w=0;wMath.sign(w));l.forEach((w,y,T)=>{if(w<0){let S=(c[y]-d[y])/w,O=d[y],A=O+S*l[y];d[y]=A,c[y]=O,T[y]=-w}});let r=n.slice(0);u.forEach((w,y)=>{r[w]=Math.ceil((c[w]-d[w])/l[w])});let o={dims:r,dataType:e[0].dataType},a=oe("output",e[0].dataType,r.length),p=j("input",e[0].dataType,e[0].dims.length),h=F.size(r),m=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:d.length},{name:"signs",type:"i32",length:s.length},{name:"steps",type:"u32",length:l.length}],g=[{type:12,data:h},{type:12,data:d},{type:6,data:s},{type:12,data:l},...ue(e[0].dims,r)],_=w=>` + }`,Jy=(e,t)=>{let n=e[0].dims,i=F.size(n),u=t.axes.length>0?F.normalizeAxes(t.axes,n.length):[...Array(n.length).keys()],l=yi(e,4);l.forEach(w=>w!==0||(()=>{throw new Error("step cannot be 0")})),l.length===0&&(l=Array(u.length).fill(1));let d=t.starts.map((w,y)=>Mu(w,y,n,u,l)),c=t.ends.map((w,y)=>Mu(w,y,n,u,l));if(u.length!==d.length||u.length!==c.length)throw new Error("start, ends and axes should have the same number of elements");if(u.length!==n.length)for(let w=0;wMath.sign(w));l.forEach((w,y,T)=>{if(w<0){let S=(c[y]-d[y])/w,O=d[y],A=O+S*l[y];d[y]=A,c[y]=O,T[y]=-w}});let r=n.slice(0);u.forEach((w,y)=>{r[w]=Math.ceil((c[w]-d[w])/l[w])});let o={dims:r,dataType:e[0].dataType},a=oe("output",e[0].dataType,r.length),p=j("input",e[0].dataType,e[0].dims.length),h=F.size(r),m=[{name:"outputSize",type:"u32"},{name:"starts",type:"u32",length:d.length},{name:"signs",type:"i32",length:s.length},{name:"steps",type:"u32",length:l.length}],g=[{type:12,data:h},{type:12,data:d},{type:6,data:s},{type:12,data:l},...ue(e[0].dims,r)],_=w=>` ${w.registerUniforms(m).declareVariables(p,a)} - ${Hy(p,a,n)} + ${Yy(p,a,n)} ${w.mainStart()} ${w.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")} let output_indices = ${a.offsetToIndices("global_idx")}; let input_indices = calculateInputIndices(output_indices); ${a.setByOffset("global_idx",p.getByIndices("input_indices"))} - }`;return{name:"Slice",shaderCache:{hint:`${s.length}_${d.length}_${l.length}`,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:[o],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:g})}},o$=(e,t)=>{qy(e.inputs,t);let n=Gy(e.inputs,t);e.compute(Wy(e.inputs,n),{inputs:[0]})},s$=e=>{let t=e.starts,n=e.ends,i=e.axes;return ke({starts:t,ends:n,axes:i})}}),Ky,Xy,a$,u$,zk=D(()=>{"use strict";de(),pe(),He(),Cr(),he(),Ky=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},Xy=(e,t)=>{let n=e.inputs[0],i=n.dims,u=F.size(i),l=i.length,d=F.normalizeAxis(t.axis,l),c=dI),r[d]=l-1,r[l-1]=d,s=e.compute($t(n,r),{inputs:[n],outputs:[-1]})[0]):s=n;let o=s.dims,a=o[l-1],p=u/a,h=Ge(a),m=a/h,g=64;p===1&&(g=256);let _=(P,I)=>I===4?`max(max(${P}.x, ${P}.y), max(${P}.z, ${P}.w))`:I===2?`max(${P}.x, ${P}.y)`:I===3?`max(max(${P}.x, ${P}.y), ${P}.z)`:P,w=j("x",s.dataType,s.dims,h),y=oe("result",s.dataType,s.dims,h),T=w.type.value,S=nt(s.dataType)==="f32"?`var threadMax = ${T}(-3.4028234663852886e+38f);`:`var threadMax = ${T}(-65504.0h);`,O=P=>` + }`;return{name:"Slice",shaderCache:{hint:`${s.length}_${d.length}_${l.length}`,inputDependencies:["rank"]},getShaderSource:_,getRunData:()=>({outputs:[o],dispatchGroup:{x:Math.ceil(i/64)},programUniforms:g})}},d$=(e,t)=>{Xy(e.inputs,t);let n=Zy(e.inputs,t);e.compute(Jy(e.inputs,n),{inputs:[0]})},c$=e=>{let t=e.starts,n=e.ends,i=e.axes;return ke({starts:t,ends:n,axes:i})}}),Qy,e0,p$,h$,Gk=D(()=>{"use strict";de(),pe(),He(),Cr(),he(),Qy=e=>{if(!e||e.length!==1)throw new Error("Softmax op requires 1 input.")},e0=(e,t)=>{let n=e.inputs[0],i=n.dims,u=F.size(i),l=i.length,d=F.normalizeAxis(t.axis,l),c=dI),r[d]=l-1,r[l-1]=d,s=e.compute($t(n,r),{inputs:[n],outputs:[-1]})[0]):s=n;let o=s.dims,a=o[l-1],p=u/a,h=qe(a),m=a/h,g=64;p===1&&(g=256);let _=(P,I)=>I===4?`max(max(${P}.x, ${P}.y), max(${P}.z, ${P}.w))`:I===2?`max(${P}.x, ${P}.y)`:I===3?`max(max(${P}.x, ${P}.y), ${P}.z)`:P,w=j("x",s.dataType,s.dims,h),y=oe("result",s.dataType,s.dims,h),T=w.type.value,S=nt(s.dataType)==="f32"?`var threadMax = ${T}(-3.4028234663852886e+38f);`:`var threadMax = ${T}(-65504.0h);`,O=P=>` var rowMaxShared : ${T}; var rowSumShared : ${T}; var threadShared : array<${T}, ${g}>; @@ -4648,7 +4648,7 @@ fn calculateOutputIndex(index: u32) -> u32 { value = max(value, ${T}(0.0)); setValue(row, col, row_stride, value); } - }`,A=e.compute({name:"Softmax",shaderCache:{hint:`${h};${g}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:o,dataType:s.dataType}],dispatchGroup:{x:p},programUniforms:[{type:6,data:m}]}),getShaderSource:O},{inputs:[s],outputs:[c?-1:0]})[0];c&&e.compute($t(A,r),{inputs:[A]})},a$=(e,t)=>{Ky(e.inputs),Xy(e,t)},u$=e=>ke({axis:e.axis})}),Ru,Zy,Yy,Jy,l$,Bk=D(()=>{"use strict";de(),pe(),he(),Ru=e=>Array.from(e.getBigInt64Array(),Number),Zy=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Ru(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},Yy=(e,t)=>{let n=[];for(let i=0;i{let n=e[0].dims,i=t??Ru(e[1]),u=Yy(n,i),l=F.size(u),d=e[0].dataType,c=j("input",d,n.length),s=oe("output",d,u.length),r=o=>` + }`,A=e.compute({name:"Softmax",shaderCache:{hint:`${h};${g}`,inputDependencies:["type"]},getRunData:()=>({outputs:[{dims:o,dataType:s.dataType}],dispatchGroup:{x:p},programUniforms:[{type:6,data:m}]}),getShaderSource:O},{inputs:[s],outputs:[c?-1:0]})[0];c&&e.compute($t(A,r),{inputs:[A]})},p$=(e,t)=>{Qy(e.inputs),e0(e,t)},h$=e=>ke({axis:e.axis})}),Nu,t0,r0,n0,f$,qk=D(()=>{"use strict";de(),pe(),he(),Nu=e=>Array.from(e.getBigInt64Array(),Number),t0=e=>{if(!e||e.length!==2)throw new Error("Tile requires 2 inputs.");if(e[0].dataType!==1&&e[0].dataType!==10&&e[0].dataType!==6&&e[0].dataType!==12)throw new Error("Tile only support float, float16, int32, and uint32 data types");if(e[1].dataType!==7)throw new Error("Tile `repeats` input should be of int64 data type");if(e[1].dims.length!==1)throw new Error("Tile `repeats` input should be 1-D");if(Nu(e[1]).length!==e[0].dims.length)throw new Error("Tile `repeats` input should have same number of elements as rank of input data tensor")},r0=(e,t)=>{let n=[];for(let i=0;i{let n=e[0].dims,i=t??Nu(e[1]),u=r0(n,i),l=F.size(u),d=e[0].dataType,c=j("input",d,n.length),s=oe("output",d,u.length),r=o=>` const inputShape = ${c.indices(...n)}; ${o.registerUniform("output_size","u32").declareVariables(c,s)} ${o.mainStart()} @@ -4662,7 +4662,7 @@ fn calculateOutputIndex(index: u32) -> u32 { ${c.indicesSet("input_indices","i","input_dim_value")} } ${s.setByOffset("global_idx",c.getByIndices("input_indices"))} - }`;return{name:"Tile",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},...ue(e[0].dims,u)]}),getShaderSource:r}},l$=e=>{Zy(e.inputs),e.compute(Jy(e.inputs),{inputs:[0]})}}),Qy,e0,d$,Fk=D(()=>{"use strict";de(),pe(),he(),Qy=(e,t,n,i,u)=>{let l=oe("output_data",u,n.length,4),d=j("a_data",t[1].dataType,t[1].dims.length,4),c=j("b_data",t[2].dataType,t[2].dims.length,4),s=j("c_data",t[0].dataType,t[0].dims.length,4),r,o=(a,p,h)=>`select(${p}, ${a}, ${h})`;if(!i)r=l.setByOffset("global_idx",o(d.getByOffset("global_idx"),c.getByOffset("global_idx"),s.getByOffset("global_idx")));else{let a=(p,h,m="")=>{let g=`a_data[index_a${h}][component_a${h}]`,_=`b_data[index_b${h}][component_b${h}]`,w=`bool(c_data[index_c${h}] & (0xffu << (component_c${h} * 8)))`;return` + }`;return{name:"Tile",shaderCache:{hint:`${i}`,inputDependencies:["rank"]},getRunData:()=>({outputs:[{dims:u,dataType:e[0].dataType}],dispatchGroup:{x:Math.ceil(l/64)},programUniforms:[{type:12,data:l},...ue(e[0].dims,u)]}),getShaderSource:r}},f$=e=>{t0(e.inputs),e.compute(n0(e.inputs),{inputs:[0]})}}),i0,o0,m$,Hk=D(()=>{"use strict";de(),pe(),he(),i0=(e,t,n,i,u)=>{let l=oe("output_data",u,n.length,4),d=j("a_data",t[1].dataType,t[1].dims.length,4),c=j("b_data",t[2].dataType,t[2].dims.length,4),s=j("c_data",t[0].dataType,t[0].dims.length,4),r,o=(a,p,h)=>`select(${p}, ${a}, ${h})`;if(!i)r=l.setByOffset("global_idx",o(d.getByOffset("global_idx"),c.getByOffset("global_idx"),s.getByOffset("global_idx")));else{let a=(p,h,m="")=>{let g=`a_data[index_a${h}][component_a${h}]`,_=`b_data[index_b${h}][component_b${h}]`,w=`bool(c_data[index_c${h}] & (0xffu << (component_c${h} * 8)))`;return` let output_indices${h} = ${l.offsetToIndices(`global_idx * 4u + ${h}u`)}; let offset_a${h} = ${d.broadcastedIndicesToOffset(`output_indices${h}`,l)}; let offset_b${h} = ${c.broadcastedIndicesToOffset(`output_indices${h}`,l)}; @@ -4690,22 +4690,22 @@ fn calculateOutputIndex(index: u32) -> u32 { ${e.mainStart()} ${e.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")} ${r} - }`},e0=e=>{let t=e[1].dims,n=e[2].dims,i=e[0].dims,u=e[1].dataType,l=!(F.areEqual(t,n)&&F.areEqual(n,i)),d=t,c=F.size(t);if(l){let r=Bn.calcShape(Bn.calcShape(t,n,!1),i,!1);if(!r)throw new Error("Can't perform where op on the given tensors");d=r,c=F.size(d)}let s=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:r=>Qy(r,e,d,l,u),getRunData:()=>({outputs:[{dims:d,dataType:u}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:s},...ue(i,t,n,d)]})}},d$=e=>{e.compute(e0(e.inputs))}}),c$,Lk=D(()=>{"use strict";QA(),hd(),ek(),tk(),rk(),nk(),ik(),lk(),ck(),pk(),hk(),fk(),mk(),gk(),bk(),yk(),wk(),_k(),vk(),xk(),$k(),Tk(),Sk(),Ik(),Ok(),Ek(),k2(),Ak(),kk(),Pk(),Ck(),Rk(),pd(),Dk(),M2(),Mk(),Nk(),zk(),R2(),Bk(),Cr(),fd(),Fk(),c$=new Map([["Abs",[t1]],["Acos",[r1]],["Acosh",[n1]],["Add",[B1]],["ArgMax",[Yx,Dl]],["ArgMin",[Zx,Dl]],["Asin",[i1]],["Asinh",[o1]],["Atan",[s1]],["Atanh",[a1]],["Attention",[Jx]],["AveragePool",[q2,V2]],["BatchNormalization",[Qx]],["BiasAdd",[e1]],["BiasSplitGelu",[z1]],["Cast",[l1,u1]],["Ceil",[c1]],["Clip",[d1]],["Concat",[K1,X1]],["Conv",[Ll,Fl]],["ConvTranspose",[o2,i2]],["Cos",[p1]],["Cosh",[h1]],["CumSum",[s2,a2]],["DepthToSpace",[u2,l2]],["DequantizeLinear",[Y2,J2]],["DFT",[d2,c2]],["Div",[F1]],["Einsum",[p2,h2]],["Elu",[f1,Si]],["Equal",[L1]],["Erf",[m1]],["Exp",[g1]],["Expand",[f2]],["FastGelu",[m2]],["Floor",[b1]],["FusedConv",[Ll,Fl]],["Gather",[b2,g2]],["GatherElements",[$2,x2]],["GatherBlockQuantized",[_2,v2]],["GatherND",[y2,w2]],["Gelu",[y1]],["Gemm",[S2,T2]],["GlobalAveragePool",[H2,G2]],["GlobalMaxPool",[Z2,X2]],["Greater",[q1]],["GreaterOrEqual",[H1]],["GridSample",[I2,O2]],["GroupQueryAttention",[N2]],["HardSigmoid",[I1,S1]],["HardSwish",[O1]],["InstanceNormalization",[z2]],["LayerNormalization",[B2]],["LeakyRelu",[w1,Si]],["Less",[G1]],["LessOrEqual",[W1]],["Log",[M1]],["MatMul",[F2]],["MatMulNBits",[L2,j2]],["MaxPool",[W2,K2]],["Mul",[j1]],["MultiHeadAttention",[A2,E2]],["Neg",[v1]],["Not",[_1]],["Pad",[U2]],["Pow",[U1]],["QuickGelu",[N1,Si]],["Range",[Q2]],["Reciprocal",[x1]],["ReduceMin",[Gx]],["ReduceMean",[Lx]],["ReduceMax",[qx]],["ReduceSum",[Wx]],["ReduceProd",[Hx]],["ReduceL1",[jx]],["ReduceL2",[Ux]],["ReduceLogSum",[Xx]],["ReduceLogSumExp",[Vx]],["ReduceSumSquare",[Kx]],["Relu",[$1]],["Resize",[r$,n$]],["RotaryEmbedding",[D2]],["ScatterND",[t$,e$]],["Sigmoid",[T1]],["Sin",[E1]],["Sinh",[A1]],["Slice",[o$,s$]],["SkipLayerNormalization",[i$]],["Split",[P2,C2]],["Sqrt",[k1]],["Softmax",[a$,u$]],["Sub",[V1]],["Tan",[P1]],["Tanh",[C1]],["ThresholdedRelu",[D1,Si]],["Tile",[l$]],["Transpose",[Ex,Ax]],["Where",[d$]]])}),p$,jk=D(()=>{"use strict";dt(),ur(),he(),p$=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,i,u){Jt(e.programInfo.name);let l=this.backend.device,d=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let c=[];for(let r of t)c.push({binding:c.length,resource:{buffer:r.buffer}});for(let r of n)c.push({binding:c.length,resource:{buffer:r.buffer}});u&&c.push({binding:c.length,resource:u});let s=l.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:c,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let r={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:s,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(r)}d.setPipeline(e.computePipeline),d.setBindGroup(0,s),d.dispatchWorkgroups(...i),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(),Vt(e.programInfo.name)}dispose(){}build(e,t){Jt(e.name);let n=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(r=>{n.features.has(r.feature)&&i.push(`enable ${r.extension};`)});let u=Ox(t,this.backend.device.limits),l=e.getShaderSource(u),d=`${i.join(` + }`},o0=e=>{let t=e[1].dims,n=e[2].dims,i=e[0].dims,u=e[1].dataType,l=!(F.areEqual(t,n)&&F.areEqual(n,i)),d=t,c=F.size(t);if(l){let r=Bn.calcShape(Bn.calcShape(t,n,!1),i,!1);if(!r)throw new Error("Can't perform where op on the given tensors");d=r,c=F.size(d)}let s=Math.ceil(c/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:r=>i0(r,e,d,l,u),getRunData:()=>({outputs:[{dims:d,dataType:u}],dispatchGroup:{x:Math.ceil(c/64/4)},programUniforms:[{type:12,data:s},...ue(i,t,n,d)]})}},m$=e=>{e.compute(o0(e.inputs))}}),g$,Wk=D(()=>{"use strict";sk(),gd(),ak(),uk(),lk(),dk(),ck(),gk(),yk(),wk(),_k(),vk(),xk(),$k(),Tk(),Sk(),Ik(),Ok(),Ek(),Ak(),kk(),Pk(),Ck(),Rk(),Dk(),Mk(),M2(),Nk(),zk(),Bk(),Fk(),Lk(),md(),jk(),L2(),Uk(),Vk(),Gk(),B2(),qk(),Cr(),bd(),Hk(),g$=new Map([["Abs",[s1]],["Acos",[a1]],["Acosh",[u1]],["Add",[V1]],["ArgMax",[r1,zl]],["ArgMin",[t1,zl]],["Asin",[l1]],["Asinh",[d1]],["Atan",[c1]],["Atanh",[p1]],["Attention",[n1]],["AveragePool",[X2,K2]],["BatchNormalization",[i1]],["BiasAdd",[o1]],["BiasSplitGelu",[U1]],["Cast",[f1,h1]],["Ceil",[g1]],["Clip",[m1]],["Concat",[Q1,e2]],["Conv",[Vl,Ul]],["ConvTranspose",[d2,l2]],["Cos",[b1]],["Cosh",[y1]],["CumSum",[c2,p2]],["DepthToSpace",[h2,f2]],["DequantizeLinear",[r$,n$]],["DFT",[m2,g2]],["Div",[G1]],["Einsum",[b2,y2]],["Elu",[w1,Oi]],["Equal",[q1]],["Erf",[_1]],["Exp",[v1]],["Expand",[w2]],["FastGelu",[_2]],["Floor",[x1]],["FusedConv",[Vl,Ul]],["Gather",[x2,v2]],["GatherElements",[E2,O2]],["GatherBlockQuantized",[S2,I2]],["GatherND",[$2,T2]],["Gelu",[$1]],["Gemm",[k2,A2]],["GlobalAveragePool",[Y2,Z2]],["GlobalMaxPool",[t$,e$]],["Greater",[X1]],["GreaterOrEqual",[Y1]],["GridSample",[P2,C2]],["GroupQueryAttention",[j2]],["HardSigmoid",[P1,k1]],["HardSwish",[C1]],["InstanceNormalization",[U2]],["LayerNormalization",[V2]],["LeakyRelu",[T1,Oi]],["Less",[Z1]],["LessOrEqual",[J1]],["Log",[L1]],["MatMul",[G2]],["MatMulNBits",[q2,H2]],["MaxPool",[J2,Q2]],["Mul",[H1]],["MultiHeadAttention",[D2,R2]],["Neg",[I1]],["Not",[S1]],["Pad",[W2]],["Pow",[W1]],["QuickGelu",[j1,Oi]],["Range",[i$]],["Reciprocal",[O1]],["ReduceMin",[Zx]],["ReduceMean",[qx]],["ReduceMax",[Xx]],["ReduceSum",[Jx]],["ReduceProd",[Yx]],["ReduceL1",[Hx]],["ReduceL2",[Wx]],["ReduceLogSum",[e1]],["ReduceLogSumExp",[Kx]],["ReduceSumSquare",[Qx]],["Relu",[E1]],["Resize",[a$,u$]],["RotaryEmbedding",[F2]],["ScatterND",[s$,o$]],["Sigmoid",[A1]],["Sin",[R1]],["Sinh",[D1]],["Slice",[d$,c$]],["SkipLayerNormalization",[l$]],["Split",[N2,z2]],["Sqrt",[M1]],["Softmax",[p$,h$]],["Sub",[K1]],["Tan",[N1]],["Tanh",[z1]],["ThresholdedRelu",[F1,Oi]],["Tile",[f$]],["Transpose",[Rx,Dx]],["Where",[m$]]])}),b$,Kk=D(()=>{"use strict";dt(),ur(),he(),b$=class{constructor(e){this.backend=e,this.repo=new Map,this.attributesBound=!1}getArtifact(e){return this.repo.get(e)}setArtifact(e,t){this.repo.set(e,t)}run(e,t,n,i,u){Jt(e.programInfo.name);let l=this.backend.device,d=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let c=[];for(let r of t)c.push({binding:c.length,resource:{buffer:r.buffer}});for(let r of n)c.push({binding:c.length,resource:{buffer:r.buffer}});u&&c.push({binding:c.length,resource:u});let s=l.createBindGroup({layout:e.computePipeline.getBindGroupLayout(0),entries:c,label:e.programInfo.name});if(this.backend.sessionStatus==="capturing"){let r={kernelId:this.backend.currentKernelId,computePipeline:e.computePipeline,bindGroup:s,dispatchGroup:i};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(r)}d.setPipeline(e.computePipeline),d.setBindGroup(0,s),d.dispatchWorkgroups(...i),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(),Vt(e.programInfo.name)}dispose(){}build(e,t){Jt(e.name);let n=this.backend.device,i=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(r=>{n.features.has(r.feature)&&i.push(`enable ${r.extension};`)});let u=Cx(t,this.backend.device.limits),l=e.getShaderSource(u),d=`${i.join(` `)} ${u.additionalImplementations} -${l}`,c=n.createShaderModule({code:d,label:e.name});Ie("verbose",()=>`[WebGPU] ${e.name} shader code: ${d}`);let s=n.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return Vt(e.name),{programInfo:e,computePipeline:s,uniformVariablesInfo:u.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,n=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,u=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=u&&n<=u&&i<=u)return[t,n,i];let l=t*n*i,d=Math.ceil(Math.sqrt(l));if(d>u){if(d=Math.ceil(Math.cbrt(l)),d>u)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),h$={};wn(h$,{WebGpuBackend:()=>f$});var t0,r0,n0,f$,Uk=D(()=>{"use strict";dt(),de(),ur(),xx(),YA(),Lk(),jk(),t0=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let i=0;i{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+n+`:${t0(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},n0=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},f$=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},u=c=>t.features.has(c)&&n.push(c)&&!0;u("chromium-experimental-timestamp-query-inside-passes")||u("timestamp-query"),u("shader-f16"),u("subgroups"),this.device=await t.requestDevice(i);let l=t,d=t.info??(typeof l.requestAdapterInfo=="function"?await l.requestAdapterInfo():void 0);this.adapterInfo=new n0(d),this.gpuDataManager=Sx(this),this.programManager=new p$(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,ud(e.logLevel,!!e.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:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&this.env?.webgpu&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Jt(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=p);let m=Number(p-this.queryTimeBase),g=Number(h-this.queryTimeBase);if(!Number.isSafeInteger(m)||!Number.isSafeInteger(g))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:o.map(_=>({dims:_.dims,dataType:sr(_.dataType)})),outputsMetadata:a.map(_=>({dims:_.dims,dataType:sr(_.dataType)})),kernelId:l,kernelType:c,kernelName:s,programName:r,startTime:m,endTime:g});else{let _="";o.forEach((y,T)=>{_+=`input[${T}]: [${y.dims}] | ${sr(y.dataType)}, `});let w="";a.forEach((y,T)=>{w+=`output[${T}]: [${y.dims}] | ${sr(y.dataType)}, `}),console.log(`[profiling] kernel "${l}|${c}|${s}|${r}" ${_}${w}start time: ${m} ns, execution time: ${g-m} ns`)}Lo("GPU",`${r}::${p}::${h}`)}e.unmap(),this.pendingQueries.delete(e)}),Vt()}run(e,t,n,i,u,l){Jt(e.name);let d=[];for(let y=0;yT):n;if(o.length!==c.length)throw new Error(`Output size ${o.length} must be equal to ${c.length}.`);let a=[],p=[];for(let y=0;y=l)throw new Error(`Invalid output index: ${o[y]}`);if(o[y]===-3)continue;let T=o[y]===-1,S=o[y]===-2,O=T||S?u(c[y].dataType,c[y].dims):i(o[y],c[y].dataType,c[y].dims);if(a.push(O),O.data===0)continue;let A=this.gpuDataManager.get(O.data);if(!A)throw new Error(`no GPU data for output: ${O.data}`);if(T&&this.temporaryData.push(A),S){let P=this.kernelPersistentData.get(this.currentKernelId);P||(P=[],this.kernelPersistentData.set(this.currentKernelId,P)),P.push(A)}p.push(A)}if(d.length!==t.length||p.length!==a.length){if(p.length===0)return Vt(e.name),a;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let h;if(r){let y=0,T=[];r.forEach(P=>{let I=typeof P.data=="number"?[P.data]:P.data;if(I.length===0)return;let z=P.type===10?2:4,G,J;P.type===10?(J=I.length>4?16:I.length>2?8:I.length*z,G=I.length>4?16:z*I.length):(J=I.length<=2?I.length*z:16,G=16),y=Math.ceil(y/J)*J,T.push(y);let q=P.type===10?8:4;y+=I.length>4?Math.ceil(I.length/q)*G:I.length*z});let S=16;y=Math.ceil(y/S)*S;let O=new ArrayBuffer(y);r.forEach((P,I)=>{let z=T[I],G=typeof P.data=="number"?[P.data]:P.data;if(P.type===6)new Int32Array(O,z,G.length).set(G);else if(P.type===12)new Uint32Array(O,z,G.length).set(G);else if(P.type===10)new Uint16Array(O,z,G.length).set(G);else if(P.type===1)new Float32Array(O,z,G.length).set(G);else throw new Error(`Unsupported uniform type: ${sr(P.type)}`)});let A=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(A.buffer,0,O,0,y),this.gpuDataManager.release(A.id),h={offset:0,size:y,buffer:A.buffer}}let m=this.programManager.normalizeDispatchGroupSize(s),g=m[1]===1&&m[2]===1,_=r0(e,t,g),w=this.programManager.getArtifact(_);if(w||(w=this.programManager.build(e,m),this.programManager.setArtifact(_,w),Ie("info",()=>`[artifact] key: ${_}, programName: ${e.name}`)),r&&w.uniformVariablesInfo){if(r.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${r.length} in program "${w.programInfo.name}".`);for(let y=0;y`[ProgramManager] run "${e.name}" (key=${_}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:t,outputTensorViews:a};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(w,d,p,m,h),Vt(e.name),a}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,i){let u=c$.get(e);if(!u)throw new Error(`kernel not implemented: ${e}`);let l={kernelType:e,kernelName:i,kernelEntry:u[0],attributes:[u[1],n]};this.kernels.set(t,l)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let n of t)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let u=i.kernelType,l=i.kernelName,d=i.kernelEntry,c=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${u}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,c[0]&&(c[1]=c[0](c[1]),c[0]=void 0),Ie("info",()=>`[WebGPU] Start to run kernel "[${u}] ${l}"...`);let s=this.env.debug;this.temporaryData=[];try{return s&&this.device.pushErrorScope("validation"),d(t,c[1]),0}catch(r){return n.push(Promise.resolve(`[WebGPU] Kernel "[${u}] ${l}" failed. ${r}`)),1}finally{s&&n.push(this.device.popErrorScope().then(r=>r?`GPU validation error for kernel "[${u}] ${l}": ${r.message}`:null));for(let r of this.temporaryData)this.gpuDataManager.release(r.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,i){let u=this.sessionExternalDataMapping.get(e);u||(u=new Map,this.sessionExternalDataMapping.set(e,u));let l=u.get(t),d=this.gpuDataManager.registerExternalBuffer(n,i,l);return u.set(t,[d,n]),d}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let i=await Pl(this,e,t);return ld(i.buffer,n)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.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(){Ie("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(){Ie("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ie("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let i=0;i=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),m$={};wn(m$,{init:()=>g$});var Ro,i0,g$,Vk=D(()=>{"use strict";de(),ur(),pe(),ZA(),Ro=class b${constructor(t,n,i,u){this.module=t,this.dataType=n,this.data=i,this.dims=u}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(F.size(t)!==F.size(this.dims))throw new Error("Invalid new shape");return new b$(this.module,this.dataType,this.data,t)}},i0=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,u=n/e.PTR_SIZE,l=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*u++,l));let d=Number(e.getValue(i*u++,l));this.outputCount=Number(e.getValue(i*u++,l)),this.customDataOffset=Number(e.getValue(i*u++,"*")),this.customDataSize=Number(e.getValue(i*u++,l));let c=[];for(let s=0;stypeof d=="number"?this.inputs[d]:d)??this.inputs,i=t?.outputs??[],u=(d,c,s)=>new Ro(this.module,c,this.output(d,s),s),l=(d,c)=>{let s=cn(d,c);if(!s)throw new Error(`Unsupported data type: ${d}`);let r=s>0?this.backend.gpuDataManager.create(s).id:0;return new Ro(this.module,d,r,c)};return this.backend.run(e,n,i,u,l,this.outputCount)}output(e,t){let n=this.module.stackSave();try{let i=this.module.PTR_SIZE,u=i===4?"i32":"i64",l=this.module.stackAlloc((1+t.length)*i);this.module.setValue(l,t.length,u);for(let d=0;d{let u=t.jsepInit;if(!u)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let l=(Uk(),Nn(h$)).WebGpuBackend,d=new l;await d.initialize(n,i),u("webgpu",[d,c=>d.alloc(Number(c)),c=>d.free(c),(c,s,r,o=!1)=>{if(o)Ie("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(c)}, dst=${Number(s)}, size=${Number(r)}`),d.memcpy(Number(c),Number(s));else{Ie("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(c)}, gpuDataId=${Number(s)}, size=${Number(r)}`);let a=t.HEAPU8.subarray(Number(c>>>0),Number(c>>>0)+Number(r));d.upload(Number(s),a)}},async(c,s,r)=>{Ie("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${c}, dataOffset=${s}, size=${r}`),await d.download(Number(c),()=>t.HEAPU8.subarray(Number(s)>>>0,Number(s+r)>>>0))},(c,s,r)=>d.createKernel(c,Number(s),r,t.UTF8ToString(t._JsepGetNodeName(Number(s)))),c=>d.releaseKernel(c),(c,s,r,o)=>{Ie("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${c}, contextDataOffset=${s}`);let a=new i0(t,d,Number(s));return d.computeKernel(Number(c),a,o)},()=>d.captureBegin(),()=>d.captureEnd(),()=>d.replay()])}else{let l=new Tx(n);u("webnn",[l,()=>l.reserveTensorId(),d=>l.releaseTensorId(d),async(d,c,s,r,o)=>l.ensureTensor(d,c,s,r,o),(d,c)=>{l.uploadTensor(d,c)},async(d,c)=>l.downloadTensor(d,c),(d,c)=>l.registerMLContext(d,c),!!n.trace])}}}),o0,_d,vd,_r,s0,Du,Yo,xd,$d,Mu,Td,Sd,Id,y$=D(()=>{"use strict";dt(),WA(),KA(),de(),vn(),id(),yx(),o0=(e,t)=>{Be()._OrtInit(e,t)!==0&&Re("Can't initialize onnxruntime.")},_d=async e=>{o0(e.wasm.numThreads,Ho(e.logLevel))},vd=async(e,t)=>{Be().asyncInit?.();let n=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let u=e.webgpu.forceFallbackAdapter;if(u!==void 0&&typeof u!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${u}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:u}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let i=(Vk(),Nn(m$)).init;t==="webgpu"&&await i("webgpu",Be(),e,n),t==="webnn"&&await i("webnn",Be(),e)}},_r=new Map,s0=e=>{let t=Be(),n=t.stackSave();try{let i=t.PTR_SIZE,u=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,u,u+i)!==0&&Re("Can't get session input/output count.");let l=i===4?"i32":"i64";return[Number(t.getValue(u,l)),Number(t.getValue(u+i,l))]}finally{t.stackRestore(n)}},Du=(e,t)=>{let n=Be(),i=n.stackSave(),u=0;try{let l=n.PTR_SIZE,d=n.stackAlloc(2*l);n._OrtGetInputOutputMetadata(e,t,d,d+l)!==0&&Re("Can't get session input/output metadata.");let c=Number(n.getValue(d,"*"));u=Number(n.getValue(d+l,"*"));let s=n.HEAP32[u/4];if(s===0)return[c,0];let r=n.HEAPU32[u/4+1],o=[];for(let a=0;a{let t=Be(),n=t._malloc(e.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},xd=async(e,t)=>{let n,i,u=Be();Array.isArray(e)?[n,i]=e:e.buffer===u.HEAPU8.buffer?[n,i]=[e.byteOffset,e.byteLength]:[n,i]=Yo(e);let l=0,d=0,c=0,s=[],r=[],o=[];try{if([d,s]=await bx(t),t?.externalData&&u.mountExternalData){let S=[];for(let O of t.externalData){let A=typeof O=="string"?O:O.path,P=typeof O=="string"?O:O.data;S.push(ad(P).then(I=>{u.mountExternalData(A,I)}))}await Promise.all(S)}for(let S of t?.executionProviders??[])if((typeof S=="string"?S:S.name)==="webnn"){if(u.shouldTransferToMLTensor=!1,typeof S!="string"){let O=S,A=O?.context,P=O?.gpuDevice,I=O?.deviceType,z=O?.powerPreference;A?u.currentContext=A:P?u.currentContext=await u.webnnCreateMLContext(P):u.currentContext=await u.webnnCreateMLContext({deviceType:I,powerPreference:z})}else u.currentContext=await u.webnnCreateMLContext();break}l=await u._OrtCreateSession(n,i,d),u.webgpuOnCreateSession?.(l),l===0&&Re("Can't create a session."),u.jsepOnCreateSession?.(),u.currentContext&&(u.webnnRegisterMLContext(l,u.currentContext),u.currentContext=void 0,u.shouldTransferToMLTensor=!0);let[a,p]=s0(l),h=!!t?.enableGraphCapture,m=[],g=[],_=[],w=[],y=[];for(let S=0;SS==="gpu-buffer"||S==="ml-tensor"||S==="ml-tensor-cpu-output")&&(c=u._OrtCreateBinding(l),c===0&&Re("Can't create IO binding."),T={handle:c,outputPreferredLocations:y,outputPreferredLocationsEncoded:y.map(S=>S==="ml-tensor-cpu-output"?"ml-tensor":S).map(S=>kl(S))}),_r.set(l,[l,r,o,T,h,!1]),[l,m,g,_,w]}catch(a){throw r.forEach(p=>u._OrtFree(p)),o.forEach(p=>u._OrtFree(p)),c!==0&&u._OrtReleaseBinding(c)!==0&&Re("Can't release IO binding."),l!==0&&u._OrtReleaseSession(l)!==0&&Re("Can't release session."),a}finally{u._free(n),d!==0&&u._OrtReleaseSessionOptions(d)!==0&&Re("Can't release session options."),s.forEach(a=>u._free(a)),u.unmountExternalData?.()}},$d=e=>{let t=Be(),n=_r.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,u,l,d,c]=n;d&&(c&&t._OrtClearBoundOutputs(d.handle)!==0&&Re("Can't clear bound outputs."),t._OrtReleaseBinding(d.handle)!==0&&Re("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),u.forEach(s=>t._OrtFree(s)),l.forEach(s=>t._OrtFree(s)),t._OrtReleaseSession(i)!==0&&Re("Can't release session."),_r.delete(e)},Mu=async(e,t,n,i,u,l,d=!1)=>{if(!e){t.push(0);return}let c=Be(),s=c.PTR_SIZE,r=e[0],o=e[1],a=e[3],p=a,h,m;if(r==="string"&&(a==="gpu-buffer"||a==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(d&&a!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${l} when enableGraphCapture is true.`);if(a==="gpu-buffer"){let w=e[2].gpuBuffer;m=cn(dn(r),o);{let y=c.jsepRegisterBuffer;if(!y)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=y(i,l,w,m)}}else if(a==="ml-tensor"){let w=e[2].mlTensor;m=cn(dn(r),o);let y=c.webnnRegisterMLTensor;if(!y)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=y(i,w,dn(r),o)}else{let w=e[2];if(Array.isArray(w)){m=s*w.length,h=c._malloc(m),n.push(h);for(let y=0;yc.setValue(_+T*s,y,s===4?"i32":"i64"));let w=c._OrtCreateTensor(dn(r),h,m,_,o.length,kl(p));w===0&&Re(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(w)}finally{c.stackRestore(g)}},Td=async(e,t,n,i,u,l)=>{let d=Be(),c=d.PTR_SIZE,s=_r.get(e);if(!s)throw new Error(`cannot run inference. invalid session id: ${e}`);let r=s[0],o=s[1],a=s[2],p=s[3],h=s[4],m=s[5],g=t.length,_=i.length,w=0,y=[],T=[],S=[],O=[],A=[],P=d.stackSave(),I=d.stackAlloc(g*c),z=d.stackAlloc(g*c),G=d.stackAlloc(_*c),J=d.stackAlloc(_*c);try{[w,y]=gx(l),hn("wasm prepareInputOutputTensor");for(let v=0;vce*xe,1);K=sr(Y);let le=p?.outputPreferredLocations[i[v]];if(K==="string"){if(le==="gpu-buffer"||le==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ce=[];for(let xe=0;xe0){let ce=d.jsepGetBuffer;if(!ce)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=ce(B),qe=cn(Y,re);if(qe===void 0||!od(K))throw new Error(`Unsupported data type: ${K}`);V=!0,C.push([K,W,{gpuBuffer:xe,download:d.jsepCreateDownloader(xe,qe,K),dispose:()=>{d._OrtReleaseTensor(R)!==0&&Re("Can't release tensor.")}},"gpu-buffer"])}else if(le==="ml-tensor"&&re>0){let ce=d.webnnEnsureTensor,xe=d.webnnIsGraphInputOutputTypeSupported;if(!ce||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(cn(Y,re)===void 0||!sd(K))throw new Error(`Unsupported data type: ${K}`);if(!xe(e,K,!1))throw new Error(`preferredLocation "ml-tensor" for ${K} output is not supported by current WebNN Context.`);let qe=await ce(e,B,Y,W,!1);V=!0,C.push([K,W,{mlTensor:qe,download:d.webnnCreateMLTensorDownloader(B,K),dispose:()=>{d.webnnReleaseTensorId(B),d._OrtReleaseTensor(R)}},"ml-tensor"])}else if(le==="ml-tensor-cpu-output"&&re>0){let ce=d.webnnCreateMLTensorDownloader(B,K)(),xe=C.length;V=!0,ee.push((async()=>{let qe=[xe,await ce];return d.webnnReleaseTensorId(B),d._OrtReleaseTensor(R),qe})()),C.push([K,W,[],"cpu"])}else{let ce=ss(K),xe=new ce(re);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(d.HEAPU8.subarray(B,B+xe.byteLength)),C.push([K,W,xe,"cpu"])}}finally{d.stackRestore(H),K==="string"&&B&&d._free(B),V||d._OrtReleaseTensor(R)}}p&&!h&&(d._OrtClearBoundOutputs(p.handle)!==0&&Re("Can't clear bound outputs."),_r.set(e,[r,o,a,p,h,!1]));for(let[v,R]of await Promise.all(ee))C[v][2]=R;return fn("wasm ProcessOutputTensor"),C}finally{d.webnnOnRunEnd?.(r),d.stackRestore(P),T.forEach(q=>d._OrtReleaseTensor(q)),S.forEach(q=>d._OrtReleaseTensor(q)),O.forEach(q=>d._free(q)),w!==0&&d._OrtReleaseRunOptions(w),y.forEach(q=>d._free(q))}},Sd=e=>{let t=Be(),n=_r.get(e);if(!n)throw new Error("invalid session id");let i=n[0],u=t._OrtEndProfiling(i);u===0&&Re("Can't get an profile file name."),t._OrtFree(u)},Id=e=>{let t=[];for(let n of e){let i=n[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),vr,At,An,bi,yi,Do,Nu,Mo,Wr,Kr,a0,w$,_$,v$,x$,$$,T$,S$,I$=D(()=>{"use strict";dt(),y$(),vn(),rd(),vr=()=>!!me.wasm.proxy&&typeof document<"u",An=!1,bi=!1,yi=!1,Mo=new Map,Wr=(e,t)=>{let n=Mo.get(e);n?n.push(t):Mo.set(e,[t])},Kr=()=>{if(An||!bi||yi||!At)throw new Error("worker not ready")},a0=e=>{switch(e.data.type){case"init-wasm":An=!1,e.data.err?(yi=!0,Nu[1](e.data.err)):(bi=!0,Nu[0]()),Do&&(URL.revokeObjectURL(Do),Do=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=Mo.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},w$=async()=>{if(!bi){if(An)throw new Error("multiple calls to 'initWasm()' detected.");if(yi)throw new Error("previous call to 'initWasm()' failed.");if(An=!0,vr())return new Promise((e,t)=>{At?.terminate(),fx().then(([n,i])=>{try{At=i,At.onerror=l=>t(l),At.onmessage=a0,Nu=[e,t];let u={type:"init-wasm",in:me};!u.in.wasm.wasmPaths&&(n||Al)&&(u.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url).href}),At.postMessage(u),Do=n}catch(u){t(u)}},t)});try{await nd(me.wasm),await _d(me),bi=!0}catch(e){throw yi=!0,e}finally{An=!1}}},_$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:me}};At.postMessage(i)});await vd(me,e)},v$=async e=>vr()?(Kr(),new Promise((t,n)=>{Wr("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};At.postMessage(i,[e.buffer])})):Yo(e),x$=async(e,t)=>{if(vr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Kr(),new Promise((n,i)=>{Wr("create",[n,i]);let u={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),At.postMessage(u,l)})}else return xd(e,t)},$$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("release",[t,n]);let i={type:"release",in:e};At.postMessage(i)});$d(e)},T$=async(e,t,n,i,u,l)=>{if(vr()){if(n.some(d=>d[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(u.some(d=>d))throw new Error("pre-allocated output tensor is not supported for proxy.");return Kr(),new Promise((d,c)=>{Wr("run",[d,c]);let s=n,r={type:"run",in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:i,options:l}};At.postMessage(r,Id(s))})}else return Td(e,t,n,i,u,l)},S$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("end-profiling",[t,n]);let i={type:"end-profiling",in:e};At.postMessage(i)});Sd(e)}}),zu,u0,O$,qk=D(()=>{"use strict";dt(),I$(),de(),td(),yx(),zu=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},u0=e=>{switch(e[3]){case"cpu":return new vt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!od(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:u}=e[2];return vt.fromGpuBuffer(n,{dataType:t,dims:e[1],download:i,dispose:u})}case"ml-tensor":{let t=e[0];if(!sd(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:u}=e[2];return vt.fromMLTensor(n,{dataType:t,dims:e[1],download:i,dispose:u})}default:throw new Error(`invalid data location: ${e[3]}`)}},O$=class{async fetchModelAndCopyToWasmMemory(e){return v$(await ad(e))}async loadModel(e,t){Jt();let n;typeof e=="string"?n=await this.fetchModelAndCopyToWasmMemory(e):n=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await x$(n,t),Vt()}async dispose(){return $$(this.sessionId)}async run(e,t,n){Jt();let i=[],u=[];Object.entries(e).forEach(a=>{let p=a[0],h=a[1],m=this.inputNames.indexOf(p);if(m===-1)throw new Error(`invalid input '${p}'`);i.push(h),u.push(m)});let l=[],d=[];Object.entries(t).forEach(a=>{let p=a[0],h=a[1],m=this.outputNames.indexOf(p);if(m===-1)throw new Error(`invalid output '${p}'`);l.push(h),d.push(m)});let c=i.map((a,p)=>zu(a,()=>`input "${this.inputNames[u[p]]}"`)),s=l.map((a,p)=>a?zu(a,()=>`output "${this.outputNames[d[p]]}"`):null),r=await T$(this.sessionId,u,c,d,s,n),o={};for(let a=0;aVl,initializeFlags:()=>Ul,wasmBackend:()=>A$});var Ul,Vl,A$,Gk=D(()=>{"use strict";dt(),I$(),qk(),Ul=()=>{(typeof me.wasm.initTimeout!="number"||me.wasm.initTimeout<0)&&(me.wasm.initTimeout=0);let e=me.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),me.wasm.simd=!1),typeof me.wasm.proxy!="boolean"&&(me.wasm.proxy=!1),typeof me.wasm.trace!="boolean"&&(me.wasm.trace=!1),typeof me.wasm.numThreads!="number"||!Number.isInteger(me.wasm.numThreads)||me.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)me.wasm.numThreads=1;else{let t=typeof navigator>"u"?Bu("node:os").cpus().length:navigator.hardwareConcurrency;me.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Vl=class{async init(e){Ul(),await w$(),await _$(e)}async createInferenceSessionHandler(e,t){let n=new O$;return await n.loadModel(e,t),n}},A$=new Vl});dt();dt();dt();var Hk="1.29.0";{let e=(qA(),Nn(ax)).onnxjsBackend;pn("webgl",e,-10)}{let e=(Gk(),Nn(E$)).wasmBackend;pn("webgpu",e,5),pn("webnn",e,5),pn("cpu",e,10),pn("wasm",e,10)}Object.defineProperty(me.versions,"web",{value:Hk,enumerable:!0});function k$(){return me.versions.web??""}function P$(e={}){me.wasm.numThreads=e.wasmThreads??1,e.wasmPaths!==void 0&&(me.wasm.wasmPaths=e.wasmPaths)}var as=[];function Od(){let e=as;return as=[],e}async function us(e,t,n){for(let i of t){let u=null;try{let l=performance.now();u=await Qo.create(e.slice().buffer,{executionProviders:[i]});let d=performance.now();if(await n(u))return{session:u,ep:i,createMs:d-l,firstRunMs:performance.now()-d};as.push(`${i}: the model does not have the inputs and outputs the release describes`)}catch(l){as.push(`${i}: ${l instanceof Error?l.message:String(l)}`.slice(0,300))}await u?.release().catch(()=>{})}return null}function qn(e,t){return new vt("float32",e,t)}function Ed(e){return{cx:e.x+e.width/2,cy:e.y+e.height/2,w:e.width,h:e.height,angle:0}}function Gn(e,t){let n=Math.max(e.x,t.x),i=Math.max(e.y,t.y),u=Math.min(e.x+e.width,t.x+t.width),l=Math.min(e.y+e.height,t.y+t.height);if(u<=n||l<=i)return 0;let d=(u-n)*(l-i);return d/(e.width*e.height+t.width*t.height-d)}function Ad(e,t,n,i){let u=[...e].sort((d,c)=>n(c)-n(d)),l=[];for(let d of u){let c=t(d);l.every(s=>Gn(c,t(s))O&&(O=P,S=A)}O>=l&&(c.push(w),s.push(O),r.push(S))}let o=c.length;if(o===0)return[];let a=new Float32Array(o),p=new Float32Array(o),h=new Float32Array(o),m=new Float32Array(o);for(let w=0;wy).sort((w,y)=>s[y]-s[w]||w-y),_=[];for(;g.length>0;){let w=g[0];if(_.push(w),g.length===1)break;let y=Qe(Qe(h[w]-a[w])*Qe(m[w]-p[w])),T=[];for(let S=1;S{let y={x:a[w]/n,y:p[w]/n,width:Qe(h[w]-a[w])/n,height:Qe(m[w]-p[w])/n};return{aabb:y,rect:Ed(y),score:s[w],cls:r[w]}})}function ls(e,t,n,i=Hn){let u=Math.trunc(Math.max(0,e.x)),l=Math.trunc(Math.max(0,e.y)),d=Math.trunc(Math.min(t,e.x+e.width)),c=Math.trunc(Math.min(n,e.y+e.height));return d-u>=i&&c-l>=i}function R$(e,t,n,i,u,l=kd,d=Hn){return C$(e,t,n,l).filter(c=>ls(c.aabb,i,u,d))}function Xk(e,t,n,i,u){let l=i/t,d=u/n;return[Math.max(0,e.x*l),Math.max(0,e.y*d),Math.min(i,(e.x+e.width)*l),Math.min(u,(e.y+e.height)*d)]}function D$(e,t){let n=e.aabb;if(n.x>=0&&n.y>=0&&n.x+n.width<=t.width&&n.y+n.height<=t.height)return e;let[i,u,l,d]=Xk(n,t.width,t.height,t.width,t.height),c={x:i,y:u,width:Math.max(0,l-i),height:Math.max(0,d-u)};return{...e,aabb:c,rect:Ed(c)}}function M$(e,t=Rr){let n=[],i=[];for(let u of e)(u.cls===t?n:i).push(u);return{faces:n,others:i}}function Zk(e){return e<0&&(e=-e),e<1?1-e:0}function N$(e,t){let n=e/t,i=n<1?1:n,u=i,l=Math.ceil(u)*2+1,d=new Int32Array(t*2),c=new Int32Array(t*l),s=new Float64Array(l);for(let r=0;re&&(m=e),m-=h;for(let g=0;g>22;return t<0?0:t>255?255:t}var z$="",Pd=null,Cd=null;function Yk(e,t,n,i){let u=`${e}x${t}>${n}x${i}`;return(u!==z$||!Pd||!Cd)&&(Pd=N$(e,n),Cd=N$(t,i),z$=u),{h:Pd,v:Cd}}function cs(e,t,n,i,u){let{h:l,v:d}=Yk(t,n,i,u),c=i!==t,s=u!==n,r,o;if(c){let w=s?d.bounds[0]:0,T=(s?d.bounds[u*2-2]+d.bounds[u*2-1]:n)-w;o=w,r=new Uint8Array(i*T*3);let{ksize:S,bounds:O,kk:A}=l;for(let P=0;P.5?t+1:n<.5||t%2===0?t:t+1}function Rd(e,t,n=ps){let i=Math.min(n.height/t,n.width/e);return{ratio:i,width:B$(e*i),height:B$(t*i)}}function Jk(e,t,n,i=ps){let u=Rd(t,n,i),l=cs(e,t,n,u.width,u.height),d=new Uint8Array(i.width*i.height*3).fill(i.pad);for(let c=0;c{let o=(await s.run({[n.inputName]:qn(new Float32Array(3*u*l),[1,3,l,u])}))[n.outputName]?.dims??[];return o.length===3&&o[0]===1&&o[1]===n.anchors&&o[2]===d});return c?new e(c.session,c.ep,n,{createMs:c.createMs,firstRunMs:c.firstRunMs}):null}async propose(t){let{letterbox:n,inputName:i,outputName:u,decode:l,minCropPx:d}=this.settings,c=performance.now(),{tensor:s,ratio:r}=Dd(t.data,t.width,t.height,n),o=performance.now(),a=await this.session.run({[i]:qn(s,[1,3,n.height,n.width])});return this.lastTimings={preprocessMs:o-c,inferMs:performance.now()-o},R$(a[u].data,this.columns,r,t.width,t.height,l,d)}async release(){await this.session.release().catch(()=>{})}};var Qk=32;async function eP(e,t,n,i,u=Qk){if(n<=u)return e(t,n);let l=t.length/n,d=new Float32Array(n*i);for(let c=0;c(await d.run({[n.inputName]:qn(new Float32Array(3*u*u),[1,3,u,u])}))[n.outputName]?.data.length===n.dim);return l?new e(l.session,l.ep,n,{createMs:l.createMs,firstRunMs:l.firstRunMs}):null}async embedBatch(t,n){return eP((i,u)=>this.run(i,u),t,n,this.settings.dim)}async run(t,n){let{inputName:i,outputName:u,inputSize:l,dim:d}=this.settings,s=(await this.session.run({[i]:qn(t,[n,3,l,l])}))[u].data;if(s.length!==n*d)throw new Error(`unexpected embedding size ${s.length} for ${n} crops`);return s}async release(){await this.session.release().catch(()=>{})}};var tP=["orb","akaze","sift"];var rP={orb:[["scaleFactor",1.2,!1],["nLevels",8,!0],["edgeThreshold",15,!0],["patchSize",15,!0],["fastThreshold",10,!0]],akaze:[["threshold",.001,!1],["nOctaves",4,!0],["nOctaveLayers",4,!0]],sift:[["nOctaveLayers",3,!0],["contrastThreshold",.04,!1],["edgeThreshold",10,!1],["sigma",1.6,!1]]},DD=Object.fromEntries(tP.map(e=>[e,Object.fromEntries(rP[e].map(([t,n])=>[t,n]))])),MD=Object.freeze({seed:0,features:{type:"orb",maxFeatures:300,artLongSide:320,mask:[],params:{}},crop:{longSide:320,maxFeatures:500},candidates:{embeddingTopK:5,voteTopN:0},vote:{matcher:"bf",ratio:.8,lshTables:12,lshKeySize:20,lshProbes:2,kdTrees:4,checks:64},match:{ratio:.8},ransac:{model:"homography",method:"ransac",threshold:6,maxIters:2e3,confidence:.995,minAreaRatio:.25,maxAreaRatio:4},fusion:{weight:.1,minInliers:8,fullInliers:30,penalty:0,baseline:"none",reorder:!0},gate:{belowAccept:!1,sources:null}}),nP=["features","crop","candidates","vote","match","ransac","fusion","gate"],ND=["index","seed",...nP];var BD=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function F$(e,t,n){let i=new Float64Array(e);for(let u of t){let l=u.fused-u.cosine;for(let d of n(u.cardId))i[d]=i[d]+l}return i}var iP=10n;function oP(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let n=t.getUint32(0),i=t.getUint32(4),u=n>>>31?-1n:1n,l=n>>>20&2047,d=BigInt(n&1048575)<<32n|BigInt(i),c;return l===0?c=-1074:(d|=1n<<52n,c=l-1075),{mantissa:u*d,exponent:c}}function Ui(e,t){if(!Number.isFinite(e)||e===0)return e;let{mantissa:n,exponent:i}=oP(e),u=n<0n,d=(u?-n:n)*iP**BigInt(t),c=1n;i>=0?d<<=BigInt(i):c<<=BigInt(-i);let s=d/c,o=2n*(d-s*c);if((o>c||o===c&&s%2n===1n)&&(s+=1n),s===0n)return u?-0:0;let a=`${u?"-":""}${s.toString()}e-${t}`;return Number(a)}function sP(e){return{cardId:e.cardId,cosine:Ui(e.cosine,6),foundBy:e.foundBy,votes:e.votes,matches:e.matches,inliers:e.inliers,evidence:Ui(e.evidence,6),fused:Ui(e.fused,6)}}function L$(e,t){return{before:{topId:e.topId,similarity:Ui(e.similarity,6),margin:Ui(e.margin,6),accepted:e.accepted},candidates:t.candidates.map(sP),...t.debug?{debug:t.debug}:{}}}var aP=23,UD=(1<!n.representative.has(d))??[...u].sort()[0];for(let d of u)i.set(d,`group:${n.representative.get(d)??l}`)}return i}var Wn="file:///";function U$(e){let t=new URL(e,Wn).href.slice(Wn.length);try{return decodeURIComponent(t)}catch{return t}}var V$="busy";var er={full128:{id:"full128",size:128,centerMask:!1,poolVersion:2,crop:"truncate"}};function Md(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(er,e)}function hs(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(!Md(t.id))return null;let n=er[t.id],i=Object.keys(t);return i.length===Object.keys(n).length&&i.every(l=>n[l]===t[l])?t.id:null}function G$(e,t,n,i,u,l){let d=new Float64Array(i*u*3),c=new Uint32Array(i*u);for(let a=0;a0&&(d[a*3]=d[a*3]/p,d[a*3+1]=d[a*3+1]/p,d[a*3+2]=d[a*3+2]/p)}if(l===1||t>=i&&n>=u||t<=0||n<=0)return d;let s=q$(n,u),r=q$(t,i),o=new Float64Array(d.length);for(let a=0;a=0&&!n[l];)l--;let d=u+1;for(;d=0&&(d>=t||u-l<=d-u)?l:d}return i}function fs(e,t,n,i){let u=i.size,l=G$(e,t,n,u,u,i.poolVersion),d=new Float32Array(3*u*u),c=u*u;for(let s=0;s>10&31,s=l&1023;c===0?i[u]=d*s*2**-24:c===31?i[u]=s?NaN:d*(1/0):i[u]=d*(1+s/1024)*2**(c-15)}return i}function lP(e,t){let n;try{n=atob(e)}catch{return null}if(n.length!==t*2)return null;let i=new Uint8Array(n.length);for(let u=0;u0)||!Number.isFinite(u))return!1;for(let l=0;l=Kn.length&&Kn.every((t,n)=>e[n]===t)}function Bd(e){return zd(e)&&e.length>Kn.length?e[Kn.length]:null}function X$(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);if(Bd(t)!==gs||t.lengthtypeof a=="string")||u.entryCount!==d.length)return null;let c=u.artVs;if(c!==void 0&&(!Array.isArray(c)||c.length!==d.length||!c.every(a=>a===null||typeof a=="string")))return null;let s=l.dim,r=Vi+n;if(t.length-r!==d.length*s*2)return null;let o=new Float32Array(d.length*s);for(let a=0;a({x:i+p*s-h*r,y:u+p*r+h*s}))}}function Z$(e,t){let{points:n}=t,i=0;for(let u=0;u0?1:-1;if(i===0)i=p;else if(p!==i)return!1}return!0}function Ld(e,t){let n=null;for(let i of t)Z$(e,i.quad)&&(!n||i.zIndex>=n.zIndex)&&(n=i);return n?n.card:null}function Xn(e){return e<0?0:e>1?1:e}function bs(e,t){let{frameWidth:n,frameHeight:i,names:u}=t;return e.map(l=>{let{aabb:d}=l,c=l.identity?u.get(l.identity):void 0,s=c!==void 0&&l.outline?l.outline:l.rect,r={instanceId:l.instanceId,bounds:{x:Xn(d.x/n),y:Xn(d.y/i),width:Xn(d.width/n),height:Xn(d.height/i)},rotation:(s.angle+45)%90-45,localWidth:Xn(s.w/n),localHeight:Xn(s.h/i),landscape:s.w>s.h,cardId:null,name:null};return l.identity&&c!==void 0&&(r.cardId=l.identity,r.name=c),r})}var J$=["accepted-nms","best-score","detector-score"];function Q$(e){return typeof e=="string"&&J$.includes(e)}var jd="accepted-nms",pP=.5,hP="hover_";function Y$(e){return e.width*e.height}function eT(e,t){let n=t==="accepted-nms"?e.kept:e.proposals.map((u,l)=>l),i=(u,l)=>{let d=e.proposals[u],c=e.proposals[l];if(t==="detector-score")return d.detectorScore!==c.detectorScore?d.detectorScore{let u=e.proposals[n];return{proposal:n,aabb:u.aabb,rect:u.rect,...u.outline?{outline:u.outline}:{},identity:u.accepted?u.displayId:null,score:u.score,zIndex:i+1}})}var ys=class{prev=[];nextId=1;reset(){this.prev=[]}assign(t){let n=new Set,i=t.map((l,d)=>d).sort((l,d)=>t[d].zIndex-t[l].zIndex),u=new Array(t.length);for(let l of i){let d=t[l],c=-1,s=pP;for(let r=0;r=s&&(c<0||o>s)&&(c=r,s=o)}c>=0?(n.add(c),u[l]=this.prev[c].id):u[l]=`${hP}${String(this.nextId++).padStart(4,"0")}`}return this.prev=t.map((l,d)=>({id:u[d],aabb:l.aabb,identity:l.identity})),u}};function ws(e,t,n,i=u=>u){return bs(e.map((l,d)=>({instanceId:t[d],aabb:l.aabb,rect:l.rect,...l.outline?{outline:l.outline}:{},identity:l.identity})),n).map((l,d)=>({...l,zIndex:e[d].zIndex,boxIndex:i(e[d].proposal)}))}var fP={card:null,boxIndex:null,box:null,cardId:null,name:null};function Ud(e,t,n){let i=e.map(l=>({card:l,quad:Fd(l,n),zIndex:l.zIndex??0})),u=Ld(t,i);return u?{card:u,boxIndex:u.boxIndex??null,box:{x:u.bounds.x*n.width,y:u.bounds.y*n.height,width:u.bounds.width*n.width,height:u.bounds.height*n.height},cardId:u.cardId,name:u.name}:fP}var mP="identity-groups";function Vd(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.schemaVersion!==1||t.kind!==mP||typeof t.version!="number"||!Number.isInteger(t.version)||!Array.isArray(t.groups)||typeof t.representative!="object"||t.representative===null||Array.isArray(t.representative))return null;let n=new Map,i=[];for(let l of t.groups){if(!Array.isArray(l)||l.length<2)return null;let d=[];for(let c of l){if(typeof c!="string"||c.length===0||n.has(c))return null;n.set(c,i.length),d.push(c)}i.push(d)}let u=new Map;for(let[l,d]of Object.entries(t.representative)){if(typeof d!="string"||l===d)return null;let c=n.get(l);if(c===void 0||n.get(d)!==c)return null;u.set(l,d)}for(let l of i){let d=l.filter(c=>!u.has(c));if(d.length!==1||l.some(c=>u.has(c)&&u.get(c)!==d[0]))return null}return{version:t.version,groups:i,representative:u}}var gP=["name","printing"];function qd(e){return gP.includes(e)}function rT(e,t){return t==="printing"?e.printingOf??e.id:e.name}function nT(e,t){let n=new Map;for(let i of[...new Set(e)].sort(tT)){let u=t.get(i);if(u===void 0)continue;let l=n.get(u);l?l.push(i):n.set(u,[i])}return[...n.values()].filter(i=>i.length>=2).sort((i,u)=>tT(i[0],u[0]))}function tT(e,t){return et?1:0}var Tn=class{rep=new Map;display;constructor(t=null,n,i="representative"){if(this.display=i,!!t)for(let[u,l]of t.representative)i==="representative"&&n&&!n(l)||this.rep.set(u,l)}of(t){return this.rep.get(t)??t}shown(t){return this.display==="best-printing"?t:this.of(t)}get collapsedCount(){return this.rep.size}};var _s=["webgpu","wasm"];function Gd(e,t=e.hover.selection){let n=e.boxes.flatMap((s,r)=>s.face!==null?[r]:[]),i=n.map(s=>e.boxes[s]),u=new Map,l=i.map(s=>{let r=s.face;r.cardId!==null&&r.name!==null&&u.set(r.cardId,r.name);let o={x:s.box[0],y:s.box[1],width:s.box[2],height:s.box[3]};return{aabb:o,rect:{cx:o.x+o.width/2,cy:o.y+o.height/2,w:o.width,h:o.height,angle:0},score:r.similarity,detectorScore:s.score,accepted:r.cardId!==null,displayId:r.cardId??r.topId}}),d=i.flatMap((s,r)=>s.face.kept?[r]:[]),c=qi({proposals:l,kept:d},t);return ws(c,c.map((s,r)=>`${t}_${r}`),{frameWidth:e.frame.width,frameHeight:e.frame.height,names:u},s=>n[s])}function vs(e,t,n,i){let u=i===void 0||i===e.hover.selection?e.hover.cards:Gd(e,i);return Ud(u,{x:t,y:n},e.frame)}var fe=Math.fround,iT=63/88,bP=128,Tt=90,yP=.2,wP=8,_P=.35,vP=.55,xP=.9,$P=Object.freeze({scales:[.95,1,1.05],maxFacesPerFrame:8,budgetMs:1500}),TP=[1,.8824969025845955,.6065306597126334,.32465246735834974,.1353352832366127,.04393693362340742,.011108996538242306],oT=6,SP=fe(fe(180)/fe(Math.PI)),Hd=[fe(.299),fe(.587),fe(.114)];function IP(e){let t=e-90*Math.ceil((e-45)/90);return t<=-45?45:t}function OP(e,t){let n=e%t;return n!==0&&n<0!=t<0?n+t:n}function EP(e,t){let n=e%t;return n===0?0:n<0?fe(n+t):n}function sT(e){let t=Math.floor(e),n=e-t;return n<.5?t:n>.5?t+1:t%2===0?t:t+1}function AP(e,t){let n=e.length,i=Float32Array.from(e).sort(),u=fe(t),l=fe(fe(fe(n*u)+fe(1+fe(u*-1)))-1),d,c;l>=n-1?d=c=n-1:l<0?d=c=0:(d=Math.floor(l),c=d+1);let s=d===c?0:fe(l-d),r=i[d],o=i[c],a=fe(o-r);return s>=.5?fe(o-fe(a*fe(1-s))):fe(r+fe(a*s))}function Wd(e){let{width:t,height:n}=e,i=e.channels??4,u=Math.max(1,Math.ceil(Math.max(n,t)/bP)),l=u===1?n:Math.floor(n/u),d=u===1?t:Math.floor(t/u);if(Math.min(l,d)c[Math.min(l-1,Math.max(0,C))*d+Math.min(d-1,Math.max(0,ee))],o=l-2,a=d-2,p=o*a,h=new Float32Array(p),m=new Float32Array(p),g=new Uint8Array(p),_=new Float32Array(p),w=0,y=0;for(let C=0;Cy&&(y=_[B]))}if(y<=0)return 0;let T=new Float32Array(w);for(let C=0,ee=0;C=S)||!(ee>0))continue;let v=EP(fe(fe(Math.atan2(m[C],h[C]))*SP),90),R=Math.min(Math.trunc(fe(fe(v/90)*Tt)),Tt-1);O[R]=O[R]+ee}let A=new Float64Array(Tt);for(let C=0;CA[P]&&(P=C);let I=A[(P-1+Tt)%Tt],z=A[(P+1)%Tt],G=I-2*A[P]+z,J=G!==0?.5*(I-z)/G:0,q=OP((P+.5+J)*90/Tt,90);return IP(q)}var aT=1;function Kd(e,t,n){let i=Math.abs(n)*(Math.PI/180),u=Math.cos(i),l=Math.sin(i),d=u*u-l*l;if(d>_P){let s=(e*u-t*l)/d,r=(t*u-e*l)/d;if(s>0&&r>0){let o=Math.min(s,r)/Math.max(s,r);if(o>=vP&&o<=xP)return{w:s,h:r,how:"exact"}}}let c=null;for(let s of[iT,1/iT]){let r=s*u+l,o=s*l+u,a=(e*r+t*o)/(r*r+o*o),p=(e-a*r)**2+(t-a*o)**2;(c===null||pw>=0&&w=0&&yuT(e,c,s,l*r,d*r,u))}}function lT(e,t,n){if(Math.abs(e)!["scales","maxFacesPerFrame","budgetMs"].includes(l));if(n.length>0)return`tiltedRetry has unknown key(s) ${n.sort().join(", ")}`;let i=t.scales;if(!Array.isArray(i)||i.length<1||i.length>5||!i.every(l=>typeof l=="number"&&Number.isFinite(l)&&l>=.5&&l<=1.5))return"tiltedRetry.scales must list 1 to 5 numbers from 0.5 to 1.5";let u=l=>typeof l=="number"&&Number.isInteger(l)&&l>=1;return u(t.maxFacesPerFrame)?u(t.budgetMs)?null:"tiltedRetry.budgetMs must be a whole number above 0":"tiltedRetry.maxFacesPerFrame must be a whole number above 0"}var kP=.3;function hT(e,t){let n=Math.max(0,Math.floor(t.x)),i=Math.max(0,Math.floor(t.y)),u=Math.min(e.width,Math.floor(t.x+t.width)),l=Math.min(e.height,Math.floor(t.y+t.height)),d=Math.max(0,u-n),c=Math.max(0,l-i),s=new Uint8ClampedArray(d*c*4);for(let r=0;r=t.tau&&e.margin>=t.delta}function fT(e,t,n){if(lr(e,n)||!n.rotationRetry)return{orientation:0,match:e,retried:!1};let i=[e,...t()],u=-1;for(let l=0;li[u].similarity)&&(u=l);if(u<0){u=0;for(let l=1;li[u].similarity&&(u=l)}return{orientation:u,match:i[u],retried:!0}}function cT(e){let t=[],n=[];return e.forEach((i,u)=>{let l=i.tilted!==void 0&&i.tilted.scale!==null;i.tauPassed&&(i.orientation===0&&!l?t:n).push(u)}),[...t,...n]}function pT(e,t){let n=(t??e.map((i,u)=>u)).filter(i=>e[i].tauPassed);return Ad(n,i=>e[i].aabb,i=>e[i].score,kP)}async function Yd(e,t,n,i,u=Hn,l=null,d=null,c=!1){let s=n.preprocessing,r=n.rule,o=s.size,a=n.dim,p=[],h=[],m=[];for(let N of i){let X=hT(e,N.aabb),{rgba:W,width:re,height:le}=X;ren.matchScored(w,X*a)),T=[];if(r.rotationRetry)for(let N=0;N[N,X])),O=null;if(T.length>0){let N=new Float32Array(T.length*3*g);for(let X=0;X{let W=S.get(N);if(W===void 0||O===null)throw new Error(`the turned looks of proposal ${N} were not embedded`);return(W*3+X-1)*a},P=h.map((N,X)=>fT(y[X],()=>[1,2,3].map(W=>n.matchScored(O,A(X,W))),r)),I=N=>P[N].orientation===0?{embs:w,off:N*a}:{embs:O,off:A(N,P[N].orientation)},z=new Map,G,J,q=!1;if(l)try{let N=performance.now(),X=[],W=[],re=[];for(let le=0;le0){let le=await l.verifyBatch(re,n.bankIds);X.forEach((ce,xe)=>{let qe=le[xe],Ve=W[xe],it=P[ce].match,Ze=F$(Ve,qe.candidates,zr=>n.columnsOf(zr)),$e=l.reorder?n.lookOf(Ze):n.lookWithin(Ze,n.lookOf(Ve).row),{row:ht,...It}=$e;z.set(ce,{match:It,geometric:L$({topId:it.topId,similarity:it.similarity,margin:it.margin,accepted:lr(it,r)},qe)})})}G=performance.now()-N}catch(N){q=!0,J=N,z.clear(),G=void 0}let C=new Map,ee,v,R=!1,H=0;if(d)try{let N=performance.now(),{scales:X,maxFacesPerFrame:W}=d.settings,re=ce=>z.get(ce)?.match??P[ce].match,le=mT(h.map((ce,xe)=>({aabb:ce.aabb,similarity:P[xe].match.similarity,accepted:lr(re(xe),r)})),d.focus??null).slice(0,W);if(le.length>0){let ce=[],xe=new Float32Array(le.length*X.length*g);le.forEach((Ve,it)=>{let Ze=m[Ve],{tilt:$e,rects:ht}=Xd(e,h[Ve].aabb,{data:Ze.rgba,width:Ze.width,height:Ze.height},X);ce.push($e),ht.forEach((It,zr)=>{let Gt=fs(It.rgba,It.width,It.height,s);xe.set(ms(Gt,P[Ve].orientation,o),(it*X.length+zr)*g)})}),H=le.length*X.length;let qe=await t.embedBatch(xe,H);le.forEach((Ve,it)=>{let Ze=re(Ve),$e=null;for(let ht=0;ht$e.match.similarity)&&($e={q:ht,match:It})}C.set(Ve,{match:$e?$e.match:null,evidence:{tilt:ce[it],scale:$e?X[$e.q]:null,before:{topId:Ze.topId,similarity:Ze.similarity,margin:Ze.margin}}})})}ee=performance.now()-N}catch(N){R=!0,v=N,C.clear(),H=0,ee=void 0}let L=new Map,V=N=>{let X=L.get(N);if(X===void 0){let{aabb:W}=h[N],re=m[N],{tilt:le,w:ce,h:xe}=Zd({data:re.rgba,width:re.width,height:re.height},W.width,W.height);X={cx:W.x+W.width/2,cy:W.y+W.height/2,w:ce,h:xe,angle:le},L.set(N,X)}return X},K=N=>{let X=[];for(let W=0;Wt!==null&&t.x>=d.x&&t.x<=d.x+d.width&&t.y>=d.y&&t.y<=d.y+d.height,i=e.map((d,c)=>c).filter(d=>!e[d].accepted),u=i.filter(d=>n(e[d].aabb)).sort((d,c)=>e[d].aabb.width*e[d].aabb.height-e[c].aabb.width*e[c].aabb.height),l=i.filter(d=>!n(e[d].aabb)).sort((d,c)=>e[c].similarity-e[d].similarity);return[...u,...l]}var $s={tau:.62,delta:.05,rotationRetry:!0},xs=-2,Gi=class{constructor(t,n=$s,i=new Tn){this.bank=t;this.rule=n;this.contract=er[t.preprocessing],this.rowShown=t.ids.map(l=>i.shown(l));let u=new Map;this.rowIdent=new Int32Array(t.ids.length);for(let l=0;lc&&(c=p,s=a)}let r=xs,o=s>=0?this.rowIdent[s]:-1;for(let a=0;ar&&(r=d[a]);return{bestRow:s,best:c,other:r}}matchScored(t,n){let{bestRow:i,best:u,other:l}=this.topAndOther(t,n),d=this.bank.ids[i];return{cardId:u>=this.rule.tau?d:null,similarity:u,topId:d,identity:this.identRep[this.rowIdent[i]],displayId:this.rowShown[i],margin:u-l}}scoreRow(t,n){let{matrix:i,dim:u,ids:l}=this.bank,d=new Float64Array(l.length);for(let c=0;cd);n.sort((l,d)=>t[d]-t[l]);let i=new Set,u=[];for(let l of n){let d=this.bank.ids[l];i.has(d)||(i.add(d),u.push({cardId:d,cosine:t[l]}))}return u}columns=null;columnsOf(t){return this.columns===null&&(this.columns=new Map,this.bank.ids.forEach((n,i)=>{let u=this.columns.get(n);u?u.push(i):this.columns.set(n,[i])})),this.columns.get(t)??[]}bankIdSet=null;get bankIds(){return this.columnsOf(""),this.bankIdSet??=new Set(this.columns.keys()),this.bankIdSet}scored(t,n,i){let u=this.bank.ids[t];return{cardId:n>=this.rule.tau?u:null,similarity:n,topId:u,identity:this.identRep[this.rowIdent[t]],displayId:this.rowShown[t],margin:n-i,row:t}}lookOf(t){let n=0;for(let d=1;dt[n]&&(n=d);let i=this.rowIdent[n],u=xs,l=!1;for(let d=0;du)&&(u=t[d]),l=!0);return this.scored(n,t[n],u)}lookWithin(t,n){let i=this.rowIdent[n],u=-1,l=xs,d=!1;for(let c=0;ct[u])&&(u=c):((!d||t[c]>l)&&(l=t[c]),d=!0);return this.scored(u,t[u],l)}matchPooled(t,n=this.rule.delta){let{bestRow:i,best:u,other:l}=this.topAndOther(t,0),d=u-l;return{cardId:u>=this.rule.tau&&d>=n?this.rowShown[i]:null,similarity:u,margin:d}}};var Hi=class{constructor(t=3){this.k=t;if(!Number.isInteger(t)||t<1)throw new RangeError(`k must be a positive integer, got ${t}`)}k;run=0;misses=0;showing=!1;reset(){this.run=0,this.misses=0,this.showing=!1}observe(t){return t?(this.run+=1,this.misses=0,this.run>=this.k&&(this.showing=!0)):(this.run=0,this.misses+=1,this.misses>=this.k&&(this.showing=!1)),{confirmed:this.showing,consecutive:this.run}}};var PP=.4,CP=2,RP=5,DP=2,MP="track_";function gT(e){let t=e[0].length,n=new Float32Array(t);for(let l of e)for(let d=0;d0))return null;for(let l=0;lu));for(let i of this.tracks){let u=-1,l=PP;for(let d of n){let c=Gn(i.detection.aabb,t[d].aabb);c>l&&(l=c,u=d)}if(u>=0){let d=t[u];i.detection=d,i.misses=0,i.age+=1,i.embeddings.push(d.embedding),i.embeddings.length>RP&&i.embeddings.shift(),n.delete(u)}else i.misses+=1}this.tracks=this.tracks.filter(i=>i.misses<=CP);for(let i of n){let u=t[i];this.tracks.push({instanceId:`${MP}${String(this.nextId++).padStart(4,"0")}`,detection:u,embeddings:[u.embedding],misses:0,age:1})}return this.tracks.filter(i=>i.misses===0).map(i=>({instanceId:i.instanceId,detection:i.detection,identity:i.age>=DP?this.identityOf(i):null}))}};var NP=.25,zP=5;function BP(e,t){if(e===null||t===void 0)return!1;let n=t-e;return n<-NP||n>zP}function FP(e){return[e.x,e.y,e.width,e.height]}var Ki=class{hoverSelection;detector;embedder;recognizer;names;classNames;faceClass;minCropPx;now;tracker;gate=new Hi(3);hoverIds=new ys;heldCards=[];lastVideoTimeSec=null;geometric;geometricFailure=null;tiltedRetry;tiltedFailure=null;constructor(t){this.detector=t.detector,this.embedder=t.embedder,this.names=t.names,this.classNames=t.classNames??["face","back"],this.faceClass=t.faceClass??Rr,this.minCropPx=t.minCropPx??Hn,this.hoverSelection=t.hoverSelection??jd,this.now=t.now??(()=>performance.now()),this.geometric=t.geometric??null,this.tiltedRetry=t.tiltedRetry??null;let n=new Tn(t.identityGroups??null,i=>this.names.has(i),t.identityDisplay??"best-printing");this.recognizer=new Gi(t.bank,t.accept??$s,n),this.tracker=new Wi(i=>this.recognizer.matchPooled(i).cardId)}get size(){return this.recognizer.size}takeGeometricFailure(){let t=this.geometricFailure;return this.geometricFailure=null,t}takeTiltedFailure(){let t=this.tiltedFailure;return this.tiltedFailure=null,t}get tiltedSettings(){return this.tiltedRetry}setTiltedRetry(t){this.tiltedRetry=t,this.tiltedFailure=null}get geometricStage(){return this.geometric}setGeometric(t){this.geometric=t,this.geometricFailure=null}reset(){this.tracker.reset(),this.gate.reset(),this.heldCards=[],this.hoverIds.reset(),this.lastVideoTimeSec=null}async analyze(t,n,i={}){let u=this.now(),l=BP(this.lastVideoTimeSec,n);l&&this.reset(),n!==void 0&&(this.lastVideoTimeSec=n);let d=await this.detector.propose(t),c=this.now()-u,s=d.filter(I=>ls(I.aabb,t.width,t.height,this.minCropPx)).map(I=>D$(I,t)),{faces:r}=M$(s,this.faceClass),o=this.now(),a=this.tiltedRetry&&i.tilted!==!1?{settings:this.tiltedRetry,focus:i.focus??null}:null,p=await Yd(t,this.embedder,this.recognizer,r,this.minCropPx,this.geometric,a,i.rotatedOutlines===!0),h=this.now()-o;if(p.tiltedError!==void 0&&this.tiltedRetry&&(this.tiltedFailure={error:p.tiltedError},this.tiltedRetry=null),p.geometricError!==void 0&&this.geometric&&(this.geometricFailure={stage:this.geometric,error:p.geometricError},this.geometric=null),p.proposals.length!==r.length)throw new Error("pipeline: a valid face box was not recognized");let m={frameWidth:t.width,frameHeight:t.height,names:this.names},g=qi(p,this.hoverSelection),_=r.map(I=>s.indexOf(I)),w=ws(g,this.hoverIds.assign(g),m,I=>_[I]),y=p.base??p,T=y.kept.map(I=>{let z=y.proposals[I];return{aabb:z.aabb,rect:z.rect,cardId:z.topId,embedding:z.embedding,...z.outline?{outline:z.outline}:{}}}),S=this.tracker.update(T),O=T.length>0,A=this.gate.observe(O),P;return A.confirmed?O?(P=bs(S.map(I=>({instanceId:I.instanceId,aabb:I.detection.aabb,rect:I.detection.rect,...I.detection.outline?{outline:I.detection.outline}:{},identity:I.identity})),m),this.heldCards=P):P=this.heldCards:(this.heldCards=[],P=[]),{frame:{width:t.width,height:t.height},boxes:this.boxResults(s,r,p),hover:{selection:this.hoverSelection,cards:w},tracks:{shown:A.confirmed,cards:P},discontinuity:l,retried:p.retried,embeddings:p.embeddings,timings:{detectorMs:c,recognizeMs:h,analyzeMs:this.now()-u,...p.geometricMs!==void 0?{geometricMs:p.geometricMs}:{},...p.tiltedMs!==void 0?{tiltedMs:p.tiltedMs}:{}}}}boxResults(t,n,i){let u=new Map(n.map((d,c)=>[d,c])),l=new Set(i.kept);return t.map(d=>{let c=u.get(d),s=null;if(c!==void 0){let r=i.proposals[c],o=r.accepted&&this.names.has(r.displayId)?r.displayId:null;s={topId:r.topId,topName:this.names.get(r.topId)??null,similarity:r.score,margin:r.margin,look:r.orientation,retried:r.retried,tauPassed:r.tauPassed,accepted:r.accepted,cardId:o,name:o===null?null:this.names.get(o)??null,kept:l.has(c),...r.geometric?{geometric:r.geometric}:{},...r.tilted?{tilted:r.tilted}:{}}}return{box:FP(d.aabb),score:d.score,cls:d.cls,className:this.classNames[d.cls]??String(d.cls),face:s}})}};var bT=1,yT="vision-release",LP=[8,16,32];function wT(e,t){return LP.reduce((n,i)=>n+Math.floor(e/i)*Math.floor(t/i),0)}var jP=/^[0-9a-f]{16}$/,UP=/^[0-9a-f]{64}$/,VP=/^\d+\.\d+\.\d+$/,qP=["schemaVersion","kind","id","game","locale","detector","recognizer","bank","identity","catalog","accept","hover","runtime","tiltedRetry"],_T=["tau","delta","rotationRetry"],Ue=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ft=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,Ji=e=>typeof e=="number"&&Number.isFinite(e),tt=e=>typeof e=="string"&&e.trim()!=="";function GP(e){return!tt(e)||e.includes("\\")||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e)||/[\x00-\x1f\x7f]/.test(e)||/^ | $/.test(e)||e.startsWith("/")?!1:!e.split("/").some(t=>{let n=t.replace(/%2e/gi,".");return n==="."||n===".."})}function Zi(e){return!Ue(e)||!GP(e.path)||typeof e.sha256!="string"||!UP.test(e.sha256)||!ft(e.bytes)?null:{path:e.path,sha256:e.sha256,bytes:e.bytes}}function HP(e){let t=e.input,n=e.decode;if(!Ue(t)||!ft(t.width)||!ft(t.height))return"detector.input must give a width and a height";if(!Ue(n))return"detector.decode must be an object";if(!tt(n.inputName)||!tt(n.outputName))return"detector.decode must name the model's input and output";let i=[["layout","NCHW"],["channels","BGR"],["scale","0-255"],["score","obj * max(cls)"],["class","argmax(cls)"]];for(let[o,a]of i)if(n[o]!==a)return`detector.decode.${o} is not ${JSON.stringify(a)}, the contract this runtime implements`;let u=n.letterbox;if(!Ue(u)||u.width!==t.width||u.height!==t.height)return"detector.decode.letterbox differs from detector.input";if(typeof u.pad!="number"||!Number.isInteger(u.pad)||u.pad<0||u.pad>255)return"detector.decode.letterbox.pad must be a whole number from 0 to 255";let l=[["anchor","top-left"],["resize","pillow-bilinear"],["ratio","min(height / frameHeight, width / frameWidth)"],["size","round(frame * ratio)"]];for(let[o,a]of l)if(u[o]!==a)return`detector.decode.letterbox.${o} is not ${JSON.stringify(a)}`;let d=n.classes;if(!Array.isArray(d)||d.length===0||!d.every(tt)||new Set(d).size!==d.length)return"detector.decode.classes must be a list of distinct class names";if(e.faceClass!==Rr||d[Rr]!=="face")return`detector.faceClass must be ${Rr} and that class must be named "face"`;let c=n.output,s=["cx","cy","w","h","obj",...d.map(o=>`cls_${o}`)];if(!Ue(c)||!Array.isArray(c.columns)||c.columns.length!==s.length||!c.columns.every((o,a)=>o===s[a]))return"detector.decode.output.columns must be cx, cy, w, h, obj and one cls_ per class";if(c.anchors!==wT(t.width,t.height))return`detector.decode.output.anchors must be ${wT(t.width,t.height)} for a ${t.width} x ${t.height} input`;if(!Ji(n.threshold)||!(n.threshold>0&&n.threshold<1))return"detector.decode.threshold must be a number between 0 and 1";if(n.threshold<.01)return`detector.decode.threshold ${n.threshold} is below 0.01, the lowest score at which the detector export checks box parity`;let r=n.nms;return!Ue(r)||!Ji(r.iou)||!(r.iou>0&&r.iou<=1)||r.classAgnostic!==!0||r.greedy!==!0?"detector.decode.nms must give an iou above 0 and at most 1, with classAgnostic and greedy both true":ft(n.maxProposals)?ft(e.minCropPx)?{inputName:n.inputName,outputName:n.outputName,letterbox:{width:t.width,height:t.height,pad:u.pad},anchors:c.anchors,classes:d,decode:{threshold:n.threshold,nmsIou:r.iou,maxProposals:n.maxProposals},faceClass:Rr,minCropPx:e.minCropPx}:"detector.minCropPx must be a whole number above 0":"detector.decode.maxProposals must be a whole number above 0"}function xT(e){let t=A=>({error:A});if(!Ue(e)||e.schemaVersion!==bT||e.kind!==yT)return t(`not a "${yT}" document of schema version ${bT}`);let n=Object.keys(e).filter(A=>!qP.includes(A));if(n.length>0)return t(`unknown key(s) ${n.sort().join(", ")}`);if(typeof e.id!="string"||!jP.test(e.id))return t("id must be 16 lowercase hex digits");if(!tt(e.game)||!tt(e.locale))return t("game and locale must be non-empty strings");let i=e.detector;if(!Ue(i))return t("incomplete release: detector missing (a release is all-or-nothing)");let u=Zi(i);if(!u||!tt(i.version)||!tt(i.weights))return t("detector must pin a file and carry a version and a weights label");if(i.arm!=="yolox")return t(`detector.arm ${JSON.stringify(i.arm)} is not one this runtime implements`);let l=HP(i);if(typeof l=="string")return t(l);let d=e.recognizer;if(!Ue(d))return t("incomplete release: recognizer missing (a release is all-or-nothing)");let c=Zi(d);if(!c||!tt(d.version)||!tt(d.weights)||!ft(d.dim))return t("recognizer must pin a file and carry a version, a weights label and a dim");if(!tt(d.inputName)||!tt(d.outputName))return t("recognizer must name the model's input and output");let s=hs(d.preprocessing);if(s===null)return t(`recognizer.preprocessing is not a contract this runtime implements (known: ${Object.keys(er).join(", ")})`);let r=e.bank;if(!Ue(r))return t("incomplete release: bank missing (a release is all-or-nothing)");let o=Zi(r);if(!o||!ft(r.version)||!ft(r.cardCount)||!ft(r.entryCount))return t("bank must pin a file and carry a version, a cardCount and an entryCount");if(r.aggregation!=="mean")return t('bank.aggregation must be "mean"');let a=e.identity;if(!Ue(a)||!qd(a.level))return t('identity.level must be "name" or "printing"');let p=a.groups,h=Zi(p);if(!h||!Ue(p)||!ft(p.version))return t("incomplete release: identity.groups must pin a file and carry a version");if(a.display!=="best-printing"&&a.display!=="representative")return t(`identity.display ${JSON.stringify(a.display)} is not one of best-printing, representative`);let m=e.catalog,g=Zi(m);if(!g||!Ue(m)||!ft(m.cardCount))return t("incomplete release: catalog must pin a file and carry a cardCount");let _=e.accept;if(!Ue(_))return t("incomplete release: accept missing (a release is all-or-nothing)");if(Object.keys(_).some(A=>!_T.includes(A)))return t(`accept has unknown key(s) (expected ${_T.join(", ")})`);if(!Ji(_.tau)||!(_.tau>0&&_.tau<=1))return t("accept.tau must be a number above 0 and at most 1");if(!Ji(_.delta)||!(_.delta>=0&&_.delta<1))return t("accept.delta must be a number from 0 to below 1");if(typeof _.rotationRetry!="boolean")return t("accept.rotationRetry must be true or false");let w=e.hover;if(!Ue(w)||!Q$(w.selection))return t("hover.selection is not one of accepted-nms, best-score, detector-score");if(!ft(w.maxAgeMs))return t("hover.maxAgeMs must be a whole number above 0");let y=e.runtime;if(!Ue(y)||typeof y.ortWeb!="string"||!VP.test(y.ortWeb))return t("runtime.ortWeb must be an exact version of the form 1.2.3");if(y.wasmThreads!==1)return t("runtime.wasmThreads must be 1");let T=y.executionProviders;if(!Array.isArray(T)||T.length===0||new Set(T).size!==T.length||!T.every(A=>_s.includes(A)))return t(`runtime.executionProviders must list one or more of ${_s.join(", ")}, each once`);let S=y.analysisWidth;if(!Ue(S)||!ft(S.min)||!ft(S.max)||S.min>S.max)return t("runtime.analysisWidth must give whole numbers min <= max above 0");let O=null;if("tiltedRetry"in e){let A=dT(e.tiltedRetry);if(A!==null)return t(A);let P=e.tiltedRetry;O={scales:[...P.scales],maxFacesPerFrame:P.maxFacesPerFrame,budgetMs:P.budgetMs}}return{release:{id:e.id,game:e.game,locale:e.locale,detector:{...u,arm:"yolox",version:i.version,weights:i.weights,settings:l},recognizer:{...c,version:d.version,weights:d.weights,dim:d.dim,inputName:d.inputName,outputName:d.outputName,preprocessing:s},bank:{...o,version:r.version,cardCount:r.cardCount,entryCount:r.entryCount},identity:{level:a.level,groups:{...h,version:p.version},display:a.display},catalog:{...g,cardCount:m.cardCount},accept:{tau:_.tau,delta:_.delta,rotationRetry:_.rotationRetry},hover:{selection:w.selection,maxAgeMs:w.maxAgeMs},runtime:{ortWeb:y.ortWeb,executionProviders:T,wasmThreads:1,analysisWidth:{min:S.min,max:S.max}},tiltedRetry:O}}}function WP(e){let t=0,n=()=>{throw new Error("not JSON")},i=()=>{for(;t{let c=t;for(e[t]!=='"'&&n(),t++;t=e.length&&n(),t++,JSON.parse(e.slice(c,t))},l=c=>{i();let s=e[t];if(s==="{"){t++;let o=[];if(i(),e[t]==="}")t++;else for(;;){i();let a=u();i(),e[t]!==":"&&n(),t++;let p=l(!1);if(c&&a==="id"||o.push([a,p]),i(),e[t]===",")t++;else if(e[t]==="}"){t++;break}else n()}return o.sort((a,p)=>a[0]p[0]?1:0),`{${o.map(([a,p])=>`${JSON.stringify(a)}:${p}`).join(",")}}`}if(s==="["){t++;let o=[];if(i(),e[t]==="]")t++;else for(;;)if(o.push(l(!1)),i(),e[t]===",")t++;else if(e[t]==="]"){t++;break}else n();return`[${o.join(",")}]`}if(s==='"')return JSON.stringify(u());let r=/^(?:true|false|null|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(e.slice(t,t+64));return r?(t+=r[0].length,r[0]):n()};i(),e[t]!=="{"&&n();let d=l(!0);return i(),t!==e.length&&n(),d}async function KP(e,t){let n=new TextEncoder().encode(WP(e));return(await t(n.buffer)).slice(0,16)}async function XP(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}var Jd={fetchFn:e=>fetch(e),digestSha256Hex:XP};function ZP(e,t){let n=l=>/^(\d+)\.(\d+)\.\d+/.exec(l),i=n(e),u=n(t);return i!==null&&u!==null&&i[1]===u[1]&&i[2]===u[2]}var We=class extends Error{};async function $T(e,t,n){let i;try{i=await e.fetchFn(t)}catch(u){throw new We(`${n}: fetch failed (${String(u)})`)}if(!i.ok)throw new We(`${n}: HTTP ${i.status}`);return i.arrayBuffer()}async function Yi(e,t,n,i){let u=await $T(e,new URL(n.path,t).href,i);if(u.byteLength!==n.bytes)throw new We(`${i}: ${n.path} is ${u.byteLength} bytes, the release says ${n.bytes}`);if(await e.digestSha256Hex(u)!==n.sha256)throw new We(`${i}: sha256 of ${n.path} does not match the release`);return u}function Ts(e,t){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new We(`${t}: the file is not JSON`)}}var YP=/^[a-z][a-zA-Z0-9]*$/,JP=["key","label","values","type"],vT=e=>typeof e=="string"?"text":"number",dr=e=>JSON.stringify(e)??String(e);function TT(e,t,n){for(let i=0;i!JP.includes(r));if(l.length>0)return`${u}: unknown key(s) ${l.join(", ")}`;if(typeof i.key!="string"||!YP.test(i.key))return`${u}: "key" ${dr(i.key)} must be a lowercase letter, then letters and digits only`;let d=i.key;if(d==="kind")return`${u}: "key" "kind" is reserved: the card's kind is always the first filter`;if(t.some(r=>r.key===d))return`${u}: duplicate key ${dr(d)}`;if(!tt(i.label))return`${u} (${d}): "label" must be a non-empty string`;let c=null;if("type"in i){if(i.type!=="text"&&i.type!=="number")return`${u} (${d}): "type" must be "text" or "number", not ${dr(i.type)}`;c=i.type}let s=null;if("values"in i){if(!Array.isArray(i.values)||i.values.length===0)return`${u} (${d}): "values" must be a non-empty list`;let r=TT(i.values,c,`${u} (${d}) values`);if(r!=="text"&&r!=="number")return r;c=r,s=i.values}t.push({key:d,label:i.label,type:c,values:s})}return t}function eC(e,t,n,i){let u=`card ${n}`;if(!Ue(e))return`${u}: "facets" must be an object of facet key to a value or a list of values`;for(let[l,d]of Object.entries(e)){let c=t.find(o=>o.key===l);if(c===void 0)return`${u}: facets.${l}: the catalog declares no facet ${dr(l)}`;let s=Array.isArray(d)?d:[d];if(s.length===0)return`${u}: facets.${l} is an empty list (leave the key out instead)`;let r=TT(s,c.type,`${u}: facets.${l}`);if(r!=="text"&&r!=="number")return r;c.type=r;for(let o of s){if(c.values!==null&&!c.values.includes(o))return`${u}: facets.${l}: ${dr(o)} is not one of the declared values`;let a=i.get(l)??[];a.includes(o)||a.push(o),i.set(l,a)}}return null}function tC(e){if(!Ue(e)||!tt(e.game)||!tt(e.locale)||!Array.isArray(e.cards)||e.cards.length===0)return"the file is not a catalog (game, locale and a list of cards)";let t=e.identity===void 0?"name":e.identity;if(!qd(t))return`"identity" must be "name" or "printing", not ${JSON.stringify(e.identity)}`;let n=e.facets===void 0?[]:QP(e.facets);if(typeof n=="string")return n;let i=new Map,u=new Map,l=[];for(let c of e.cards){if(!Ue(c)||!tt(c.id)||!tt(c.name))return"every card needs an id, a name and an art path";if(!("art"in c)||c.art!==null&&!tt(c.art))return`card ${c.id}: "art" must be an art path (a file path or an http(s) URL), or null for a card without art`;if(u.has(c.id))return`card id ${c.id} appears twice`;let s=c.printingOf??null;if(s!==null&&!tt(s))return`card ${c.id}: "printingOf" must be a card id or null`;let r=c.facets===void 0?null:eC(c.facets,n,c.id,i);if(r!==null)return r;if(c.extra!==void 0&&!Ue(c.extra))return`card ${c.id}: "extra" must be an object (any keys and values), not ${dr(c.extra)}`;let o={id:c.id,name:c.name,art:c.art,printingOf:s};c.extra!==void 0&&(o.extra=c.extra),u.set(o.id,o),l.push(o)}if(t==="printing")for(let c of l){if(c.printingOf===null)continue;let s=u.get(c.printingOf);if(s===void 0||s===c)return`card ${c.id}: "printingOf" names ${c.printingOf}, which is not another card`;if(s.printingOf!==null)return`card ${c.id}: "printingOf" names ${c.printingOf}, which is itself a printing of ${s.printingOf}`}let d=n.map(c=>{let s=c.values??[...i.get(c.key)??[]];return c.values===null&&c.type==="number"&&s.sort((r,o)=>r-o),{key:c.key,label:c.label,type:c.type??"text",values:[...s]}});return{game:e.game,locale:e.locale,identity:t,cards:l,facets:d}}async function Qd(e,t=Jd,n={}){try{let i=await $T(t,e,"release"),u=xT(Ts(i,"release"));if("error"in u)throw new We(`release: ${u.error}`);let l=u.release,d=await KP(new TextDecoder().decode(i),t.digestSha256Hex);if(d!==l.id)throw new We(`release: id ${l.id} is not the hash of the document (which is ${d})`);if(n.ortWeb!==void 0&&!ZP(l.runtime.ortWeb,n.ortWeb))throw new We(`release: measured on onnxruntime-web ${l.runtime.ortWeb}, this build runs ${n.ortWeb} (major and minor version must match)`);try{n.onDocument?.([l.detector,l.recognizer,l.bank,l.identity.groups,l.catalog].reduce((G,J)=>G+J.bytes,0))}catch{}let[c,s,r,o,a]=await Promise.all([Yi(t,e,l.detector,"detector"),Yi(t,e,l.recognizer,"recognizer"),Yi(t,e,l.bank,"bank"),Yi(t,e,l.identity.groups,"identity.groups"),Yi(t,e,l.catalog,"catalog")]);try{n.onFetched?.()}catch{}let p=new Uint8Array(r),h=Bd(p);if(h!==null&&h!==gs)throw new We(`bank: the binary bank is of format version ${h}, and this runtime reads version ${gs} only`);let m=zd(p)?X$(p):Nd(Ts(r,"bank"));if(!m)throw new We("bank: the file is not a bank this runtime can read");let g=[[m.version===l.bank.version,"bank.version differs from the bank file's"],[m.model===l.recognizer.version,`bank: the file's model ${JSON.stringify(m.model)} is not recognizer.version ${JSON.stringify(l.recognizer.version)}`],[m.dim===l.recognizer.dim,"bank: the vector size differs from recognizer.dim"],[m.preprocessing===l.recognizer.preprocessing,"bank: the file's preprocessing differs from recognizer.preprocessing"],[m.ids.length===l.bank.entryCount,"bank.entryCount is not the number of entries in the bank file"],[new Set(m.ids).size===l.bank.cardCount,"bank.cardCount is not the number of distinct card ids in the bank file"],[m.tau===null||m.tau===l.accept.tau,`bank: the file records tau ${m.tau}, accept.tau is ${l.accept.tau}`]];for(let[G,J]of g)if(!G)throw new We(J);let _=tC(Ts(a,"catalog"));if(typeof _=="string")throw new We(`catalog: ${_}`);if(_.game!==l.game||_.locale!==l.locale)throw new We("catalog: the file is for another game or locale");if(_.cards.length!==l.catalog.cardCount)throw new We(`catalog.cardCount ${l.catalog.cardCount} is not the file's ${_.cards.length} cards`);let w=new Map(_.cards.map(G=>[G.id,G.name])),y=m.ids.filter(G=>!w.has(G));if(y.length>0)throw new We(`${new Set(y).size} bank id(s) are not in the catalog (e.g. ${y[0]})`);let T=Ts(o,"identity.groups"),S=Vd(T);if(!S)throw new We("identity.groups: the file is not an identity-groups document");if(S.version!==l.identity.groups.version)throw new We("identity.groups.version differs from the file's");if((Ue(T)&&Ue(T.bank)?T.bank.sha256:void 0)!==l.bank.sha256)throw new We("identity.groups: the file was not made for this release's bank (its bank sha256 differs)");let A=_.identity;if(l.identity.level!==A)throw new We(`identity.level is "${l.identity.level}", and the catalog states the identity rule "${A}": a release is used with the rule its catalog states`);if((Ue(T)&&Ue(T.rule)?T.rule.level:void 0)!==A)throw new We(`identity.groups: the file's groups are not by ${A}`);let I=new Map(_.cards.map(G=>[G.id,rT(G,A)])),z=G=>JSON.stringify(G.map(J=>[...J].sort()).sort((J,q)=>J[0]q[0]?1:0));if(z(S.groups)!==z(nT(m.ids,I)))throw new We(`identity.groups: the groups are not the ones the catalog's ${A==="name"?"names give":"identity rule gives"} for the bank's ids`);return{ok:!0,data:{release:l,detectorBytes:new Uint8Array(c),recognizerBytes:new Uint8Array(s),bank:m,identityGroups:S,cards:_.cards,names:w}}}catch(i){return{ok:!1,reason:i instanceof We?i.message:`unexpected: ${String(i)}`}}}async function rC(e){for(let t of e)try{await t?.release?.()}catch{}}async function ST(e,t,n=e.release.runtime.executionProviders){let{release:i}=e,u=null,l=null,d=async c=>(await rC([u,l]),{error:c});try{if(n.length===0)return await d("no execution provider to try");let c=i.recognizer;return u=await t.embedder(e.recognizerBytes,{inputName:c.inputName,outputName:c.outputName,inputSize:er[c.preprocessing].size,dim:c.dim},n),u?(l=await t.detector(e.detectorBytes,i.detector.settings,n),l?{pipeline:new Ki({detector:l,embedder:u,bank:e.bank,accept:i.accept,identityGroups:e.identityGroups,identityDisplay:i.identity.display,names:e.names,hoverSelection:i.hover.selection,classNames:i.detector.settings.classes,faceClass:i.detector.settings.faceClass,minCropPx:i.detector.settings.minCropPx,tiltedRetry:i.tiltedRetry}),embedder:u,detector:l,providers:[...n]}:await d("detector: the model did not initialize on any execution provider, or is not the model the release describes")):await d("recognizer: the model did not initialize on any execution provider, or is not the model the release describes")}catch(c){return await d(`unexpected while building: ${String(c)}`)}}var Qi=class extends Error{constructor(n){super(`the release could not be loaded: ${n}`);this.reason=n;this.name="ReleaseError"}reason};function nC(e){return async t=>{if(!t.startsWith(Wn))throw new Error(`${t} is not one of the release's files`);let n=U$(t.slice(Wn.length)),i=Object.hasOwn(e,n)?e[n]:void 0;if(i===void 0)throw new Error(`no file ${n} among the release's files`);return{ok:!0,status:200,arrayBuffer:()=>i.arrayBuffer()}}}var Dr=e=>Math.round(e);function iC(e){let t=(n,i)=>{let u=performance.now()-i;return{createMs:Dr(n.createMs),firstRunMs:Dr(n.firstRunMs),failedProvidersMs:Dr(Math.max(0,u-n.createMs-n.firstRunMs)),totalMs:Dr(u)}};return{embedder:async(n,i,u)=>{let l=performance.now(),d=await ji.create(n,i,u);return d&&(e.recognizer=t(d.setup,l)),d},detector:async(n,i,u)=>{let l=performance.now(),d=await Li.create(n,i,u);return d&&(e.detector=t(d.setup,l)),d}}}async function oC(e,t={}){let n=t.files?Wn:typeof location<"u"?location.href:void 0,i=new URL(e,n).href,u=g=>{try{t.onProgress?.(g)}catch{}},l=performance.now();u({phase:"downloading",bytes:null});let d={...Jd,...t.deps,...t.files?{fetchFn:nC(t.files)}:{}},c=null,s=await Qd(i,d,{ortWeb:k$(),onFetched:()=>{c=performance.now()},...t.onProgress?{onDocument:g=>u({phase:"downloading",bytes:g})}:{}});if(!s.ok)throw new Qi(s.reason);let r=performance.now(),o=(c??r)-l,a=r-(c??r);u({phase:"preparing"});let{data:p}=s;P$({wasmThreads:p.release.runtime.wasmThreads,...t.wasmPaths!==void 0?{wasmPaths:t.wasmPaths}:{}}),Od();let h={},m=await ST(p,iC(h),t.providers??p.release.runtime.executionProviders);if("error"in m){let g=Od();throw new Qi(g.length>0?`${m.error} (${g.join("; ")})`:m.error)}return{release:p.release,pipeline:m.pipeline,backend:{detector:m.detector.ep,recognizer:m.embedder.ep},cards:p.cards,names:p.names,stageInputs:{bankSha256:p.release.bank.sha256,bankIds:[...new Set(p.bank.ids)],identities:j$(p.cards,p.release.identity.level,p.identityGroups)},...h.recognizer&&h.detector?{timings:{startedAtMs:Dr(l),filesMs:Dr(o),readMs:Dr(a),recognizer:h.recognizer,detector:h.detector,totalMs:Dr(performance.now()-l)}}:{},dispose:async()=>{await m.embedder.release?.(),await m.detector.release?.()}}}function sC(e,t,n){return e.pipeline.analyze(t,n)}function Ss(e){return e==="wasm"?2e3:1e3}function aC(e){return e==="wasm"?1e3:500}function Is(e,t){return t==="always-on"?Ss(e):aC(e)}var uC=1920,lC=720;function As(e,t,n={min:720,max:1920}){let i=Math.max(n.min,Math.min(n.max,e));return{width:i,height:Math.max(1,Math.round(i*t/e))}}function ET(e,t,n){if(!(e.width>0&&e.height>0))return null;let i=(t-e.left)/e.width,u=(n-e.top)/e.height;return i>=0&&i<=1&&u>=0&&u<=1?{x:i,y:u}:null}function Zn(e){return e instanceof HTMLVideoElement?{width:e.videoWidth,height:e.videoHeight}:{width:e.naturalWidth,height:e.naturalHeight}}function dC(e){return e instanceof HTMLVideoElement?e.currentTime:0}async function ec(e,t,n,i){let u=Zn(e),l=As(u.width,u.height,i);t.width=l.width,t.height=l.height;let d=performance.now(),c=dC(e);return n.drawImage(e,0,0,t.width,t.height),{bitmap:await createImageBitmap(t),videoTimeSec:c,tapMs:performance.now()-d}}var IT=128,OT=.06,cC=.5,AT=60,Es=class{ref=null;seeded=!1;seed(t){this.ref=t,this.seeded=!0}reset(){this.ref=null,this.seeded=!1}get hasReference(){return this.ref!==null}observe(t,n){let i=this.ref;if(i===null||i.width!==t.width||i.height!==t.height)return this.ref=t,this.seeded=!1,{distance:null,cut:!1};let u=fC(i,t,n);return u===null?{distance:u,cut:!1}:u>OT?{distance:u,cut:!0}:((this.seeded||u<=OT*cC)&&(this.ref=t),this.seeded=!1,{distance:u,cut:!1})}};function pC(e,t){return{width:IT,height:Math.max(1,Math.round(IT*t/Math.max(1,e)))}}function hC(e,t,n){let i=new Uint8Array(t*n);for(let u=0,l=0;u>8;return i}function fC(e,t,n){if(e.width!==t.width||e.height!==t.height||!(n.width>0)||!(n.height>0))return null;let{width:i,height:u}=e,l=Os(Math.floor(n.x*i),0,i-1),d=Os(Math.ceil((n.x+n.width)*i),l+1,i),c=Os(Math.floor(n.y*u),0,u-1),s=Os(Math.ceil((n.y+n.height)*u),c+1,u),r=0;for(let o=c;o`[WebGPU] ${e.name} shader code: ${d}`);let s=n.createComputePipeline({compute:{module:c,entryPoint:"main"},layout:"auto",label:e.name});return Vt(e.name),{programInfo:e,computePipeline:s,uniformVariablesInfo:u.variablesInfo}}normalizeDispatchGroupSize(e){let t=typeof e=="number"?e:e.x,n=typeof e=="number"?1:e.y||1,i=typeof e=="number"?1:e.z||1,u=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(t<=u&&n<=u&&i<=u)return[t,n,i];let l=t*n*i,d=Math.ceil(Math.sqrt(l));if(d>u){if(d=Math.ceil(Math.cbrt(l)),d>u)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[d,d,d]}else return[d,d,1]}}}),y$={};wn(y$,{WebGpuBackend:()=>w$});var s0,a0,u0,w$,Xk=D(()=>{"use strict";dt(),de(),ur(),Ox(),ik(),Wk(),Kk(),s0=(e,t)=>{if(t.length!==e.length)throw new Error(`inputDependencies length ${t.length} is not equal to inputTensors length ${e.length}.`);let n=[];for(let i=0;i{let i=e.name;return e.shaderCache?.hint&&(i+="["+e.shaderCache.hint+"]"),i+=":"+n+`:${s0(t,e.shaderCache?.inputDependencies??new Array(t.length).fill("dims"))}`,i},u0=class{constructor(e){e&&(this.architecture=e.architecture,this.vendor=e.vendor)}isArchitecture(e){return this.architecture===e}isVendor(e){return this.vendor===e}},w$=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let e=this.kernelCustomData.get(this.currentKernelId);return e||(e={},this.kernelCustomData.set(this.currentKernelId,e)),e}async initialize(e,t){this.env=e;let n=[],i={requiredLimits:{maxComputeWorkgroupStorageSize:t.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:t.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:t.limits.maxStorageBufferBindingSize,maxBufferSize:t.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:t.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:t.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:t.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:t.limits.maxComputeWorkgroupSizeZ},requiredFeatures:n},u=c=>t.features.has(c)&&n.push(c)&&!0;u("chromium-experimental-timestamp-query-inside-passes")||u("timestamp-query"),u("shader-f16"),u("subgroups"),this.device=await t.requestDevice(i);let l=t,d=t.info??(typeof l.requestAdapterInfo=="function"?await l.requestAdapterInfo():void 0);this.adapterInfo=new u0(d),this.gpuDataManager=kx(this),this.programManager=new b$(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,cd(e.logLevel,!!e.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:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:t,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&this.env?.webgpu&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let e=this.getCommandEncoder(),t={};this.queryType==="at-passes"&&(t.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=e.beginComputePass(t)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Jt(),this.endComputePass();let e;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),e=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(e,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,e,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&e.mapAsync(GPUMapMode.READ).then(()=>{let t=new BigUint64Array(e.getMappedRange()),n=this.pendingQueries.get(e);for(let i=0;i"u"&&(this.queryTimeBase=p);let m=Number(p-this.queryTimeBase),g=Number(h-this.queryTimeBase);if(!Number.isSafeInteger(m)||!Number.isSafeInteger(g))throw new RangeError("incorrect timestamp range");if(this.env.webgpu.profiling?.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:o.map(_=>({dims:_.dims,dataType:sr(_.dataType)})),outputsMetadata:a.map(_=>({dims:_.dims,dataType:sr(_.dataType)})),kernelId:l,kernelType:c,kernelName:s,programName:r,startTime:m,endTime:g});else{let _="";o.forEach((y,T)=>{_+=`input[${T}]: [${y.dims}] | ${sr(y.dataType)}, `});let w="";a.forEach((y,T)=>{w+=`output[${T}]: [${y.dims}] | ${sr(y.dataType)}, `}),console.log(`[profiling] kernel "${l}|${c}|${s}|${r}" ${_}${w}start time: ${m} ns, execution time: ${g-m} ns`)}Uo("GPU",`${r}::${p}::${h}`)}e.unmap(),this.pendingQueries.delete(e)}),Vt()}run(e,t,n,i,u,l){Jt(e.name);let d=[];for(let y=0;yT):n;if(o.length!==c.length)throw new Error(`Output size ${o.length} must be equal to ${c.length}.`);let a=[],p=[];for(let y=0;y=l)throw new Error(`Invalid output index: ${o[y]}`);if(o[y]===-3)continue;let T=o[y]===-1,S=o[y]===-2,O=T||S?u(c[y].dataType,c[y].dims):i(o[y],c[y].dataType,c[y].dims);if(a.push(O),O.data===0)continue;let A=this.gpuDataManager.get(O.data);if(!A)throw new Error(`no GPU data for output: ${O.data}`);if(T&&this.temporaryData.push(A),S){let P=this.kernelPersistentData.get(this.currentKernelId);P||(P=[],this.kernelPersistentData.set(this.currentKernelId,P)),P.push(A)}p.push(A)}if(d.length!==t.length||p.length!==a.length){if(p.length===0)return Vt(e.name),a;throw new Error(`Program ${e.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let h;if(r){let y=0,T=[];r.forEach(P=>{let I=typeof P.data=="number"?[P.data]:P.data;if(I.length===0)return;let z=P.type===10?2:4,q,J;P.type===10?(J=I.length>4?16:I.length>2?8:I.length*z,q=I.length>4?16:z*I.length):(J=I.length<=2?I.length*z:16,q=16),y=Math.ceil(y/J)*J,T.push(y);let G=P.type===10?8:4;y+=I.length>4?Math.ceil(I.length/G)*q:I.length*z});let S=16;y=Math.ceil(y/S)*S;let O=new ArrayBuffer(y);r.forEach((P,I)=>{let z=T[I],q=typeof P.data=="number"?[P.data]:P.data;if(P.type===6)new Int32Array(O,z,q.length).set(q);else if(P.type===12)new Uint32Array(O,z,q.length).set(q);else if(P.type===10)new Uint16Array(O,z,q.length).set(q);else if(P.type===1)new Float32Array(O,z,q.length).set(q);else throw new Error(`Unsupported uniform type: ${sr(P.type)}`)});let A=this.gpuDataManager.create(y,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(A.buffer,0,O,0,y),this.gpuDataManager.release(A.id),h={offset:0,size:y,buffer:A.buffer}}let m=this.programManager.normalizeDispatchGroupSize(s),g=m[1]===1&&m[2]===1,_=a0(e,t,g),w=this.programManager.getArtifact(_);if(w||(w=this.programManager.build(e,m),this.programManager.setArtifact(_,w),Ie("info",()=>`[artifact] key: ${_}, programName: ${e.name}`)),r&&w.uniformVariablesInfo){if(r.length!==w.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${w.uniformVariablesInfo.length}, got ${r.length} in program "${w.programInfo.name}".`);for(let y=0;y`[ProgramManager] run "${e.name}" (key=${_}) with ${m[0]}x${m[1]}x${m[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let y={kernelId:this.currentKernelId,programName:w.programInfo.name,inputTensorViews:t,outputTensorViews:a};this.pendingKernels.push(y),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(y)}return this.programManager.run(w,d,p,m,h),Vt(e.name),a}upload(e,t){this.gpuDataManager.upload(e,t)}memcpy(e,t){this.gpuDataManager.memcpy(e,t)}async download(e,t){await this.gpuDataManager.download(e,t)}alloc(e){return this.gpuDataManager.create(e).id}free(e){return this.gpuDataManager.release(e)}createKernel(e,t,n,i){let u=g$.get(e);if(!u)throw new Error(`kernel not implemented: ${e}`);let l={kernelType:e,kernelName:i,kernelEntry:u[0],attributes:[u[1],n]};this.kernels.set(t,l)}releaseKernel(e){let t=this.kernelPersistentData.get(e);if(t){for(let n of t)this.gpuDataManager.release(n.id);this.kernelPersistentData.delete(e)}this.kernelCustomData.delete(e),this.kernels.delete(e)}computeKernel(e,t,n){let i=this.kernels.get(e);if(!i)throw new Error(`kernel not created: ${e}`);let u=i.kernelType,l=i.kernelName,d=i.kernelEntry,c=i.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${u}] ${l}" is not allowed to be called recursively`);this.currentKernelId=e,c[0]&&(c[1]=c[0](c[1]),c[0]=void 0),Ie("info",()=>`[WebGPU] Start to run kernel "[${u}] ${l}"...`);let s=this.env.debug;this.temporaryData=[];try{return s&&this.device.pushErrorScope("validation"),d(t,c[1]),0}catch(r){return n.push(Promise.resolve(`[WebGPU] Kernel "[${u}] ${l}" failed. ${r}`)),1}finally{s&&n.push(this.device.popErrorScope().then(r=>r?`GPU validation error for kernel "[${u}] ${l}": ${r.message}`:null));for(let r of this.temporaryData)this.gpuDataManager.release(r.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(e,t,n,i){let u=this.sessionExternalDataMapping.get(e);u||(u=new Map,this.sessionExternalDataMapping.set(e,u));let l=u.get(t),d=this.gpuDataManager.registerExternalBuffer(n,i,l);return u.set(t,[d,n]),d}unregisterBuffers(e){let t=this.sessionExternalDataMapping.get(e);t&&(t.forEach(n=>this.gpuDataManager.unregisterExternalBuffer(n[0])),this.sessionExternalDataMapping.delete(e))}getBuffer(e){let t=this.gpuDataManager.get(e);if(!t)throw new Error(`no GPU data for buffer: ${e}`);return t.buffer}createDownloader(e,t,n){return async()=>{let i=await Dl(this,e,t);return pd(i.buffer,n)}}writeTimestamp(e){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,e)}setQueryType(){this.queryType="none",(this.env.webgpu.profiling?.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(){Ie("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(){Ie("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){Ie("info","replay"),this.sessionStatus="replaying";let e=this.capturedCommandList.get(this.currentSessionId),t=this.capturedPendingKernels.get(this.currentSessionId),n=e.length;this.pendingKernels=[];for(let i=0;i=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(e){this.unregisterBuffers(e),this.capturedCommandList.has(e)&&this.capturedCommandList.delete(e),this.capturedPendingKernels.has(e)&&this.capturedPendingKernels.delete(e),this.gpuDataManager.onReleaseSession(e)}onRunStart(e){this.currentSessionId=e,this.setQueryType()}}}),_$={};wn(_$,{init:()=>v$});var Mo,l0,v$,Zk=D(()=>{"use strict";de(),ur(),pe(),nk(),Mo=class x${constructor(t,n,i,u){this.module=t,this.dataType=n,this.data=i,this.dims=u}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,t)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,t)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,t)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let t=F.size(this.dims);return t===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,t)}reshape(t){if(F.size(t)!==F.size(this.dims))throw new Error("Invalid new shape");return new x$(this.module,this.dataType,this.data,t)}},l0=class{constructor(e,t,n){this.module=e,this.backend=t,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=t.adapterInfo;let i=e.PTR_SIZE,u=n/e.PTR_SIZE,l=i===4?"i32":"i64";this.opKernelContext=Number(e.getValue(i*u++,l));let d=Number(e.getValue(i*u++,l));this.outputCount=Number(e.getValue(i*u++,l)),this.customDataOffset=Number(e.getValue(i*u++,"*")),this.customDataSize=Number(e.getValue(i*u++,l));let c=[];for(let s=0;stypeof d=="number"?this.inputs[d]:d)??this.inputs,i=t?.outputs??[],u=(d,c,s)=>new Mo(this.module,c,this.output(d,s),s),l=(d,c)=>{let s=cn(d,c);if(!s)throw new Error(`Unsupported data type: ${d}`);let r=s>0?this.backend.gpuDataManager.create(s).id:0;return new Mo(this.module,d,r,c)};return this.backend.run(e,n,i,u,l,this.outputCount)}output(e,t){let n=this.module.stackSave();try{let i=this.module.PTR_SIZE,u=i===4?"i32":"i64",l=this.module.stackAlloc((1+t.length)*i);this.module.setValue(l,t.length,u);for(let d=0;d{let u=t.jsepInit;if(!u)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(e==="webgpu"){let l=(Xk(),Nn(y$)).WebGpuBackend,d=new l;await d.initialize(n,i),u("webgpu",[d,c=>d.alloc(Number(c)),c=>d.free(c),(c,s,r,o=!1)=>{if(o)Ie("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(c)}, dst=${Number(s)}, size=${Number(r)}`),d.memcpy(Number(c),Number(s));else{Ie("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(c)}, gpuDataId=${Number(s)}, size=${Number(r)}`);let a=t.HEAPU8.subarray(Number(c>>>0),Number(c>>>0)+Number(r));d.upload(Number(s),a)}},async(c,s,r)=>{Ie("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${c}, dataOffset=${s}, size=${r}`),await d.download(Number(c),()=>t.HEAPU8.subarray(Number(s)>>>0,Number(s+r)>>>0))},(c,s,r)=>d.createKernel(c,Number(s),r,t.UTF8ToString(t._JsepGetNodeName(Number(s)))),c=>d.releaseKernel(c),(c,s,r,o)=>{Ie("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${r}, kernel=${c}, contextDataOffset=${s}`);let a=new l0(t,d,Number(s));return d.computeKernel(Number(c),a,o)},()=>d.captureBegin(),()=>d.captureEnd(),()=>d.replay()])}else{let l=new Ax(n);u("webnn",[l,()=>l.reserveTensorId(),d=>l.releaseTensorId(d),async(d,c,s,r,o)=>l.ensureTensor(d,c,s,r,o),(d,c)=>{l.uploadTensor(d,c)},async(d,c)=>l.downloadTensor(d,c),(d,c)=>l.registerMLContext(d,c),!!n.trace])}}}),d0,$d,Td,_r,c0,zu,Qo,Sd,Id,Bu,Od,Ed,Ad,$$=D(()=>{"use strict";dt(),ek(),tk(),de(),vn(),ad(),$x(),d0=(e,t)=>{Be()._OrtInit(e,t)!==0&&Re("Can't initialize onnxruntime.")},$d=async e=>{d0(e.wasm.numThreads,Ko(e.logLevel))},Td=async(e,t)=>{Be().asyncInit?.();let n=e.webgpu.adapter;if(t==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(n){if(typeof n.limits!="object"||typeof n.features!="object"||typeof n.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let i=e.webgpu.powerPreference;if(i!==void 0&&i!=="low-power"&&i!=="high-performance")throw new Error(`Invalid powerPreference setting: "${i}"`);let u=e.webgpu.forceFallbackAdapter;if(u!==void 0&&typeof u!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${u}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:i,forceFallbackAdapter:u}),!n)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(t==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let i=(Zk(),Nn(_$)).init;t==="webgpu"&&await i("webgpu",Be(),e,n),t==="webnn"&&await i("webnn",Be(),e)}},_r=new Map,c0=e=>{let t=Be(),n=t.stackSave();try{let i=t.PTR_SIZE,u=t.stackAlloc(2*i);t._OrtGetInputOutputCount(e,u,u+i)!==0&&Re("Can't get session input/output count.");let l=i===4?"i32":"i64";return[Number(t.getValue(u,l)),Number(t.getValue(u+i,l))]}finally{t.stackRestore(n)}},zu=(e,t)=>{let n=Be(),i=n.stackSave(),u=0;try{let l=n.PTR_SIZE,d=n.stackAlloc(2*l);n._OrtGetInputOutputMetadata(e,t,d,d+l)!==0&&Re("Can't get session input/output metadata.");let c=Number(n.getValue(d,"*"));u=Number(n.getValue(d+l,"*"));let s=n.HEAP32[u/4];if(s===0)return[c,0];let r=n.HEAPU32[u/4+1],o=[];for(let a=0;a{let t=Be(),n=t._malloc(e.byteLength);if(n===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},Sd=async(e,t)=>{let n,i,u=Be();Array.isArray(e)?[n,i]=e:e.buffer===u.HEAPU8.buffer?[n,i]=[e.byteOffset,e.byteLength]:[n,i]=Qo(e);let l=0,d=0,c=0,s=[],r=[],o=[];try{if([d,s]=await xx(t),t?.externalData&&u.mountExternalData){let S=[];for(let O of t.externalData){let A=typeof O=="string"?O:O.path,P=typeof O=="string"?O:O.data;S.push(dd(P).then(I=>{u.mountExternalData(A,I)}))}await Promise.all(S)}for(let S of t?.executionProviders??[])if((typeof S=="string"?S:S.name)==="webnn"){if(u.shouldTransferToMLTensor=!1,typeof S!="string"){let O=S,A=O?.context,P=O?.gpuDevice,I=O?.deviceType,z=O?.powerPreference;A?u.currentContext=A:P?u.currentContext=await u.webnnCreateMLContext(P):u.currentContext=await u.webnnCreateMLContext({deviceType:I,powerPreference:z})}else u.currentContext=await u.webnnCreateMLContext();break}l=await u._OrtCreateSession(n,i,d),u.webgpuOnCreateSession?.(l),l===0&&Re("Can't create a session."),u.jsepOnCreateSession?.(),u.currentContext&&(u.webnnRegisterMLContext(l,u.currentContext),u.currentContext=void 0,u.shouldTransferToMLTensor=!0);let[a,p]=c0(l),h=!!t?.enableGraphCapture,m=[],g=[],_=[],w=[],y=[];for(let S=0;SS==="gpu-buffer"||S==="ml-tensor"||S==="ml-tensor-cpu-output")&&(c=u._OrtCreateBinding(l),c===0&&Re("Can't create IO binding."),T={handle:c,outputPreferredLocations:y,outputPreferredLocationsEncoded:y.map(S=>S==="ml-tensor-cpu-output"?"ml-tensor":S).map(S=>Rl(S))}),_r.set(l,[l,r,o,T,h,!1]),[l,m,g,_,w]}catch(a){throw r.forEach(p=>u._OrtFree(p)),o.forEach(p=>u._OrtFree(p)),c!==0&&u._OrtReleaseBinding(c)!==0&&Re("Can't release IO binding."),l!==0&&u._OrtReleaseSession(l)!==0&&Re("Can't release session."),a}finally{u._free(n),d!==0&&u._OrtReleaseSessionOptions(d)!==0&&Re("Can't release session options."),s.forEach(a=>u._free(a)),u.unmountExternalData?.()}},Id=e=>{let t=Be(),n=_r.get(e);if(!n)throw new Error(`cannot release session. invalid session id: ${e}`);let[i,u,l,d,c]=n;d&&(c&&t._OrtClearBoundOutputs(d.handle)!==0&&Re("Can't clear bound outputs."),t._OrtReleaseBinding(d.handle)!==0&&Re("Can't release IO binding.")),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),u.forEach(s=>t._OrtFree(s)),l.forEach(s=>t._OrtFree(s)),t._OrtReleaseSession(i)!==0&&Re("Can't release session."),_r.delete(e)},Bu=async(e,t,n,i,u,l,d=!1)=>{if(!e){t.push(0);return}let c=Be(),s=c.PTR_SIZE,r=e[0],o=e[1],a=e[3],p=a,h,m;if(r==="string"&&(a==="gpu-buffer"||a==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(d&&a!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${l} when enableGraphCapture is true.`);if(a==="gpu-buffer"){let w=e[2].gpuBuffer;m=cn(dn(r),o);{let y=c.jsepRegisterBuffer;if(!y)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');h=y(i,l,w,m)}}else if(a==="ml-tensor"){let w=e[2].mlTensor;m=cn(dn(r),o);let y=c.webnnRegisterMLTensor;if(!y)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');h=y(i,w,dn(r),o)}else{let w=e[2];if(Array.isArray(w)){m=s*w.length,h=c._malloc(m),n.push(h);for(let y=0;yc.setValue(_+T*s,y,s===4?"i32":"i64"));let w=c._OrtCreateTensor(dn(r),h,m,_,o.length,Rl(p));w===0&&Re(`Can't create tensor for input/output. session=${i}, index=${l}.`),t.push(w)}finally{c.stackRestore(g)}},Od=async(e,t,n,i,u,l)=>{let d=Be(),c=d.PTR_SIZE,s=_r.get(e);if(!s)throw new Error(`cannot run inference. invalid session id: ${e}`);let r=s[0],o=s[1],a=s[2],p=s[3],h=s[4],m=s[5],g=t.length,_=i.length,w=0,y=[],T=[],S=[],O=[],A=[],P=d.stackSave(),I=d.stackAlloc(g*c),z=d.stackAlloc(g*c),q=d.stackAlloc(_*c),J=d.stackAlloc(_*c);try{[w,y]=vx(l),hn("wasm prepareInputOutputTensor");for(let v=0;vce*xe,1);K=sr(Y);let le=p?.outputPreferredLocations[i[v]];if(K==="string"){if(le==="gpu-buffer"||le==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ce=[];for(let xe=0;xe0){let ce=d.jsepGetBuffer;if(!ce)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let xe=ce(B),Ge=cn(Y,re);if(Ge===void 0||!ud(K))throw new Error(`Unsupported data type: ${K}`);V=!0,C.push([K,W,{gpuBuffer:xe,download:d.jsepCreateDownloader(xe,Ge,K),dispose:()=>{d._OrtReleaseTensor(R)!==0&&Re("Can't release tensor.")}},"gpu-buffer"])}else if(le==="ml-tensor"&&re>0){let ce=d.webnnEnsureTensor,xe=d.webnnIsGraphInputOutputTypeSupported;if(!ce||!xe)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(cn(Y,re)===void 0||!ld(K))throw new Error(`Unsupported data type: ${K}`);if(!xe(e,K,!1))throw new Error(`preferredLocation "ml-tensor" for ${K} output is not supported by current WebNN Context.`);let Ge=await ce(e,B,Y,W,!1);V=!0,C.push([K,W,{mlTensor:Ge,download:d.webnnCreateMLTensorDownloader(B,K),dispose:()=>{d.webnnReleaseTensorId(B),d._OrtReleaseTensor(R)}},"ml-tensor"])}else if(le==="ml-tensor-cpu-output"&&re>0){let ce=d.webnnCreateMLTensorDownloader(B,K)(),xe=C.length;V=!0,ee.push((async()=>{let Ge=[xe,await ce];return d.webnnReleaseTensorId(B),d._OrtReleaseTensor(R),Ge})()),C.push([K,W,[],"cpu"])}else{let ce=us(K),xe=new ce(re);new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength).set(d.HEAPU8.subarray(B,B+xe.byteLength)),C.push([K,W,xe,"cpu"])}}finally{d.stackRestore(H),K==="string"&&B&&d._free(B),V||d._OrtReleaseTensor(R)}}p&&!h&&(d._OrtClearBoundOutputs(p.handle)!==0&&Re("Can't clear bound outputs."),_r.set(e,[r,o,a,p,h,!1]));for(let[v,R]of await Promise.all(ee))C[v][2]=R;return fn("wasm ProcessOutputTensor"),C}finally{d.webnnOnRunEnd?.(r),d.stackRestore(P),T.forEach(G=>d._OrtReleaseTensor(G)),S.forEach(G=>d._OrtReleaseTensor(G)),O.forEach(G=>d._free(G)),w!==0&&d._OrtReleaseRunOptions(w),y.forEach(G=>d._free(G))}},Ed=e=>{let t=Be(),n=_r.get(e);if(!n)throw new Error("invalid session id");let i=n[0],u=t._OrtEndProfiling(i);u===0&&Re("Can't get an profile file name."),t._OrtFree(u)},Ad=e=>{let t=[];for(let n of e){let i=n[2];!Array.isArray(i)&&"buffer"in i&&t.push(i.buffer)}return t}}),vr,At,An,wi,_i,No,Fu,zo,Wr,Kr,p0,T$,S$,I$,O$,E$,A$,k$,P$=D(()=>{"use strict";dt(),$$(),vn(),od(),vr=()=>!!me.wasm.proxy&&typeof document<"u",An=!1,wi=!1,_i=!1,zo=new Map,Wr=(e,t)=>{let n=zo.get(e);n?n.push(t):zo.set(e,[t])},Kr=()=>{if(An||!wi||_i||!At)throw new Error("worker not ready")},p0=e=>{switch(e.data.type){case"init-wasm":An=!1,e.data.err?(_i=!0,Fu[1](e.data.err)):(wi=!0,Fu[0]()),No&&(URL.revokeObjectURL(No),No=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let t=zo.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},T$=async()=>{if(!wi){if(An)throw new Error("multiple calls to 'initWasm()' detected.");if(_i)throw new Error("previous call to 'initWasm()' failed.");if(An=!0,vr())return new Promise((e,t)=>{At?.terminate(),wx().then(([n,i])=>{try{At=i,At.onerror=l=>t(l),At.onmessage=p0,Fu=[e,t];let u={type:"init-wasm",in:me};!u.in.wasm.wasmPaths&&(n||Cl)&&(u.in.wasm.wasmPaths={wasm:new URL("ort-wasm-simd-threaded.jsep.wasm",import.meta.url).href}),At.postMessage(u),No=n}catch(u){t(u)}},t)});try{await sd(me.wasm),await $d(me),wi=!0}catch(e){throw _i=!0,e}finally{An=!1}}},S$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("init-ep",[t,n]);let i={type:"init-ep",in:{epName:e,env:me}};At.postMessage(i)});await Td(me,e)},I$=async e=>vr()?(Kr(),new Promise((t,n)=>{Wr("copy-from",[t,n]);let i={type:"copy-from",in:{buffer:e}};At.postMessage(i,[e.buffer])})):Qo(e),O$=async(e,t)=>{if(vr()){if(t?.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Kr(),new Promise((n,i)=>{Wr("create",[n,i]);let u={type:"create",in:{model:e,options:{...t}}},l=[];e instanceof Uint8Array&&l.push(e.buffer),At.postMessage(u,l)})}else return Sd(e,t)},E$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("release",[t,n]);let i={type:"release",in:e};At.postMessage(i)});Id(e)},A$=async(e,t,n,i,u,l)=>{if(vr()){if(n.some(d=>d[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(u.some(d=>d))throw new Error("pre-allocated output tensor is not supported for proxy.");return Kr(),new Promise((d,c)=>{Wr("run",[d,c]);let s=n,r={type:"run",in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:i,options:l}};At.postMessage(r,Ad(s))})}else return Od(e,t,n,i,u,l)},k$=async e=>{if(vr())return Kr(),new Promise((t,n)=>{Wr("end-profiling",[t,n]);let i={type:"end-profiling",in:e};At.postMessage(i)});Ed(e)}}),Lu,h0,C$,Yk=D(()=>{"use strict";dt(),P$(),de(),id(),$x(),Lu=(e,t)=>{switch(e.location){case"cpu":return[e.type,e.dims,e.data,"cpu"];case"gpu-buffer":return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[e.type,e.dims,{mlTensor:e.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${e.location} for ${t()}`)}},h0=e=>{switch(e[3]){case"cpu":return new vt(e[0],e[2],e[1]);case"gpu-buffer":{let t=e[0];if(!ud(t))throw new Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:i,dispose:u}=e[2];return vt.fromGpuBuffer(n,{dataType:t,dims:e[1],download:i,dispose:u})}case"ml-tensor":{let t=e[0];if(!ld(t))throw new Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:i,dispose:u}=e[2];return vt.fromMLTensor(n,{dataType:t,dims:e[1],download:i,dispose:u})}default:throw new Error(`invalid data location: ${e[3]}`)}},C$=class{async fetchModelAndCopyToWasmMemory(e){return I$(await dd(e))}async loadModel(e,t){Jt();let n;typeof e=="string"?n=await this.fetchModelAndCopyToWasmMemory(e):n=e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await O$(n,t),Vt()}async dispose(){return E$(this.sessionId)}async run(e,t,n){Jt();let i=[],u=[];Object.entries(e).forEach(a=>{let p=a[0],h=a[1],m=this.inputNames.indexOf(p);if(m===-1)throw new Error(`invalid input '${p}'`);i.push(h),u.push(m)});let l=[],d=[];Object.entries(t).forEach(a=>{let p=a[0],h=a[1],m=this.outputNames.indexOf(p);if(m===-1)throw new Error(`invalid output '${p}'`);l.push(h),d.push(m)});let c=i.map((a,p)=>Lu(a,()=>`input "${this.inputNames[u[p]]}"`)),s=l.map((a,p)=>a?Lu(a,()=>`output "${this.outputNames[d[p]]}"`):null),r=await A$(this.sessionId,u,c,d,s,n),o={};for(let a=0;aHl,initializeFlags:()=>ql,wasmBackend:()=>D$});var ql,Hl,D$,Jk=D(()=>{"use strict";dt(),P$(),Yk(),ql=()=>{(typeof me.wasm.initTimeout!="number"||me.wasm.initTimeout<0)&&(me.wasm.initTimeout=0);let e=me.wasm.simd;if(typeof e!="boolean"&&e!==void 0&&e!=="fixed"&&e!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),me.wasm.simd=!1),typeof me.wasm.proxy!="boolean"&&(me.wasm.proxy=!1),typeof me.wasm.trace!="boolean"&&(me.wasm.trace=!1),typeof me.wasm.numThreads!="number"||!Number.isInteger(me.wasm.numThreads)||me.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)me.wasm.numThreads=1;else{let t=typeof navigator>"u"?ju("node:os").cpus().length:navigator.hardwareConcurrency;me.wasm.numThreads=Math.min(4,Math.ceil((t||1)/2))}},Hl=class{async init(e){ql(),await T$(),await S$(e)}async createInferenceSessionHandler(e,t){let n=new C$;return await n.loadModel(e,t),n}},D$=new Hl});dt();dt();dt();var Qk="1.29.0";{let e=(YA(),Nn(px)).onnxjsBackend;pn("webgl",e,-10)}{let e=(Jk(),Nn(R$)).wasmBackend;pn("webgpu",e,5),pn("webnn",e,5),pn("cpu",e,10),pn("wasm",e,10)}Object.defineProperty(me.versions,"web",{value:Qk,enumerable:!0});function M$(){return me.versions.web??""}function N$(e={}){me.wasm.numThreads=e.wasmThreads??1,e.wasmPaths!==void 0&&(me.wasm.wasmPaths=e.wasmPaths)}var ls=[];function kd(){let e=ls;return ls=[],e}async function ds(e,t,n){for(let i of t){let u=null;try{let l=performance.now();u=await ts.create(e.slice().buffer,{executionProviders:[i]});let d=performance.now();if(await n(u))return{session:u,ep:i,createMs:d-l,firstRunMs:performance.now()-d};ls.push(`${i}: the model does not have the inputs and outputs the release describes`)}catch(l){ls.push(`${i}: ${l instanceof Error?l.message:String(l)}`.slice(0,300))}await u?.release().catch(()=>{})}return null}function Gn(e,t){return new vt("float32",e,t)}function Pd(e){return{cx:e.x+e.width/2,cy:e.y+e.height/2,w:e.width,h:e.height,angle:0}}function qn(e,t){let n=Math.max(e.x,t.x),i=Math.max(e.y,t.y),u=Math.min(e.x+e.width,t.x+t.width),l=Math.min(e.y+e.height,t.y+t.height);if(u<=n||l<=i)return 0;let d=(u-n)*(l-i);return d/(e.width*e.height+t.width*t.height-d)}function Cd(e,t,n,i){let u=[...e].sort((d,c)=>n(c)-n(d)),l=[];for(let d of u){let c=t(d);l.every(s=>qn(c,t(s))O&&(O=P,S=A)}O>=l&&(c.push(w),s.push(O),r.push(S))}let o=c.length;if(o===0)return[];let a=new Float32Array(o),p=new Float32Array(o),h=new Float32Array(o),m=new Float32Array(o);for(let w=0;wy).sort((w,y)=>s[y]-s[w]||w-y),_=[];for(;g.length>0;){let w=g[0];if(_.push(w),g.length===1)break;let y=Qe(Qe(h[w]-a[w])*Qe(m[w]-p[w])),T=[];for(let S=1;S{let y={x:a[w]/n,y:p[w]/n,width:Qe(h[w]-a[w])/n,height:Qe(m[w]-p[w])/n};return{aabb:y,rect:Pd(y),score:s[w],cls:r[w]}})}function cs(e,t,n,i=Hn){let u=Math.trunc(Math.max(0,e.x)),l=Math.trunc(Math.max(0,e.y)),d=Math.trunc(Math.min(t,e.x+e.width)),c=Math.trunc(Math.min(n,e.y+e.height));return d-u>=i&&c-l>=i}function B$(e,t,n,i,u,l=Rd,d=Hn){return z$(e,t,n,l).filter(c=>cs(c.aabb,i,u,d))}function rP(e,t,n,i,u){let l=i/t,d=u/n;return[Math.max(0,e.x*l),Math.max(0,e.y*d),Math.min(i,(e.x+e.width)*l),Math.min(u,(e.y+e.height)*d)]}function F$(e,t){let n=e.aabb;if(n.x>=0&&n.y>=0&&n.x+n.width<=t.width&&n.y+n.height<=t.height)return e;let[i,u,l,d]=rP(n,t.width,t.height,t.width,t.height),c={x:i,y:u,width:Math.max(0,l-i),height:Math.max(0,d-u)};return{...e,aabb:c,rect:Pd(c)}}function L$(e,t=Rr){let n=[],i=[];for(let u of e)(u.cls===t?n:i).push(u);return{faces:n,others:i}}function nP(e){return e<0&&(e=-e),e<1?1-e:0}function j$(e,t){let n=e/t,i=n<1?1:n,u=i,l=Math.ceil(u)*2+1,d=new Int32Array(t*2),c=new Int32Array(t*l),s=new Float64Array(l);for(let r=0;re&&(m=e),m-=h;for(let g=0;g>22;return t<0?0:t>255?255:t}var U$="",Dd=null,Md=null;function iP(e,t,n,i){let u=`${e}x${t}>${n}x${i}`;return(u!==U$||!Dd||!Md)&&(Dd=j$(e,n),Md=j$(t,i),U$=u),{h:Dd,v:Md}}function hs(e,t,n,i,u){let{h:l,v:d}=iP(t,n,i,u),c=i!==t,s=u!==n,r,o;if(c){let w=s?d.bounds[0]:0,T=(s?d.bounds[u*2-2]+d.bounds[u*2-1]:n)-w;o=w,r=new Uint8Array(i*T*3);let{ksize:S,bounds:O,kk:A}=l;for(let P=0;P.5?t+1:n<.5||t%2===0?t:t+1}function Nd(e,t,n=fs){let i=Math.min(n.height/t,n.width/e);return{ratio:i,width:V$(e*i),height:V$(t*i)}}function oP(e,t,n,i=fs){let u=Nd(t,n,i),l=hs(e,t,n,u.width,u.height),d=new Uint8Array(i.width*i.height*3).fill(i.pad);for(let c=0;c{let o=(await s.run({[n.inputName]:Gn(new Float32Array(3*u*l),[1,3,l,u])}))[n.outputName]?.dims??[];return o.length===3&&o[0]===1&&o[1]===n.anchors&&o[2]===d});return c?new e(c.session,c.ep,n,{createMs:c.createMs,firstRunMs:c.firstRunMs}):null}async propose(t){let{letterbox:n,inputName:i,outputName:u,decode:l,minCropPx:d}=this.settings,c=performance.now(),{tensor:s,ratio:r}=zd(t.data,t.width,t.height,n),o=performance.now(),a=await this.session.run({[i]:Gn(s,[1,3,n.height,n.width])});return this.lastTimings={preprocessMs:o-c,inferMs:performance.now()-o},B$(a[u].data,this.columns,r,t.width,t.height,l,d)}async release(){await this.session.release().catch(()=>{})}};var sP=32;async function aP(e,t,n,i,u=sP){if(n<=u)return e(t,n);let l=t.length/n,d=new Float32Array(n*i);for(let c=0;c(await d.run({[n.inputName]:Gn(new Float32Array(3*u*u),[1,3,u,u])}))[n.outputName]?.data.length===n.dim);return l?new e(l.session,l.ep,n,{createMs:l.createMs,firstRunMs:l.firstRunMs}):null}async embedBatch(t,n){return aP((i,u)=>this.run(i,u),t,n,this.settings.dim)}async run(t,n){let{inputName:i,outputName:u,inputSize:l,dim:d}=this.settings,s=(await this.session.run({[i]:Gn(t,[n,3,l,l])}))[u].data;if(s.length!==n*d)throw new Error(`unexpected embedding size ${s.length} for ${n} crops`);return s}async release(){await this.session.release().catch(()=>{})}};var uP=["orb","akaze","sift"];var lP={orb:[["scaleFactor",1.2,!1],["nLevels",8,!0],["edgeThreshold",15,!0],["patchSize",15,!0],["fastThreshold",10,!0]],akaze:[["threshold",.001,!1],["nOctaves",4,!0],["nOctaveLayers",4,!0]],sift:[["nOctaveLayers",3,!0],["contrastThreshold",.04,!1],["edgeThreshold",10,!1],["sigma",1.6,!1]]},KD=Object.fromEntries(uP.map(e=>[e,Object.fromEntries(lP[e].map(([t,n])=>[t,n]))])),XD=Object.freeze({seed:0,features:{type:"orb",maxFeatures:300,artLongSide:320,mask:[],params:{}},crop:{longSide:320,maxFeatures:500},candidates:{embeddingTopK:5,voteTopN:0},vote:{matcher:"bf",ratio:.8,lshTables:12,lshKeySize:20,lshProbes:2,kdTrees:4,checks:64},match:{ratio:.8},ransac:{model:"homography",method:"ransac",threshold:6,maxIters:2e3,confidence:.995,minAreaRatio:.25,maxAreaRatio:4},fusion:{weight:.1,minInliers:8,fullInliers:30,penalty:0,baseline:"none",reorder:!0},gate:{belowAccept:!1,sources:null}}),dP=["features","crop","candidates","vote","match","ransac","fusion","gate"],ZD=["index","seed",...dP];var JD=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function G$(e,t,n){let i=new Float64Array(e);for(let u of t){let l=u.fused-u.cosine;for(let d of n(u.cardId))i[d]=i[d]+l}return i}var cP=10n;function pP(e){let t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);let n=t.getUint32(0),i=t.getUint32(4),u=n>>>31?-1n:1n,l=n>>>20&2047,d=BigInt(n&1048575)<<32n|BigInt(i),c;return l===0?c=-1074:(d|=1n<<52n,c=l-1075),{mantissa:u*d,exponent:c}}function Gi(e,t){if(!Number.isFinite(e)||e===0)return e;let{mantissa:n,exponent:i}=pP(e),u=n<0n,d=(u?-n:n)*cP**BigInt(t),c=1n;i>=0?d<<=BigInt(i):c<<=BigInt(-i);let s=d/c,o=2n*(d-s*c);if((o>c||o===c&&s%2n===1n)&&(s+=1n),s===0n)return u?-0:0;let a=`${u?"-":""}${s.toString()}e-${t}`;return Number(a)}function hP(e){return{cardId:e.cardId,cosine:Gi(e.cosine,6),foundBy:e.foundBy,votes:e.votes,matches:e.matches,inliers:e.inliers,evidence:Gi(e.evidence,6),fused:Gi(e.fused,6)}}function q$(e,t){return{before:{topId:e.topId,similarity:Gi(e.similarity,6),margin:Gi(e.margin,6),accepted:e.accepted},candidates:t.candidates.map(hP),...t.debug?{debug:t.debug}:{}}}var fP=23,r4=(1<!n.representative.has(d))??[...u].sort()[0];for(let d of u)i.set(d,`group:${n.representative.get(d)??l}`)}return i}var Wn="file:///";function W$(e){let t=new URL(e,Wn).href.slice(Wn.length);try{return decodeURIComponent(t)}catch{return t}}var K$="busy";var er={full128:{id:"full128",size:128,centerMask:!1,poolVersion:2,crop:"truncate"}};function Bd(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(er,e)}function ms(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(!Bd(t.id))return null;let n=er[t.id],i=Object.keys(t);return i.length===Object.keys(n).length&&i.every(l=>n[l]===t[l])?t.id:null}function Z$(e,t,n,i,u,l){let d=new Float64Array(i*u*3),c=new Uint32Array(i*u);for(let a=0;a0&&(d[a*3]=d[a*3]/p,d[a*3+1]=d[a*3+1]/p,d[a*3+2]=d[a*3+2]/p)}if(l===1||t>=i&&n>=u||t<=0||n<=0)return d;let s=X$(n,u),r=X$(t,i),o=new Float64Array(d.length);for(let a=0;a=0&&!n[l];)l--;let d=u+1;for(;d=0&&(d>=t||u-l<=d-u)?l:d}return i}function gs(e,t,n,i){let u=i.size,l=Z$(e,t,n,u,u,i.poolVersion),d=new Float32Array(3*u*u),c=u*u;for(let s=0;s>10&31,s=l&1023;c===0?i[u]=d*s*2**-24:c===31?i[u]=s?NaN:d*(1/0):i[u]=d*(1+s/1024)*2**(c-15)}return i}function gP(e,t){let n;try{n=atob(e)}catch{return null}if(n.length!==t*2)return null;let i=new Uint8Array(n.length);for(let u=0;u0)||!Number.isFinite(u))return!1;for(let l=0;l=Kn.length&&Kn.every((t,n)=>e[n]===t)}function jd(e){return Ld(e)&&e.length>Kn.length?e[Kn.length]:null}function eT(e){let t=e instanceof Uint8Array?e:new Uint8Array(e);if(jd(t)!==ys||t.lengthtypeof a=="string")||u.entryCount!==d.length)return null;let c=u.artVs;if(c!==void 0&&(!Array.isArray(c)||c.length!==d.length||!c.every(a=>a===null||typeof a=="string")))return null;let s=l.dim,r=qi+n;if(t.length-r!==d.length*s*2)return null;let o=new Float32Array(d.length*s);for(let a=0;a({x:i+p*s-h*r,y:u+p*r+h*s}))}}function tT(e,t){let{points:n}=t,i=0;for(let u=0;u0?1:-1;if(i===0)i=p;else if(p!==i)return!1}return!0}function Vd(e,t){let n=null;for(let i of t)tT(e,i.quad)&&(!n||i.zIndex>=n.zIndex)&&(n=i);return n?n.card:null}function Xn(e){return e<0?0:e>1?1:e}function ws(e,t){let{frameWidth:n,frameHeight:i,names:u}=t;return e.map(l=>{let{aabb:d}=l,c=l.identity?u.get(l.identity):void 0,s=c!==void 0&&l.outline?l.outline:l.rect,r={instanceId:l.instanceId,bounds:{x:Xn(d.x/n),y:Xn(d.y/i),width:Xn(d.width/n),height:Xn(d.height/i)},rotation:(s.angle+45)%90-45,localWidth:Xn(s.w/n),localHeight:Xn(s.h/i),landscape:s.w>s.h,cardId:null,name:null};return l.identity&&c!==void 0&&(r.cardId=l.identity,r.name=c),r})}var nT=["accepted-nms","best-score","detector-score"];function iT(e){return typeof e=="string"&&nT.includes(e)}var Gd="accepted-nms",wP=.5,_P="hover_";function rT(e){return e.width*e.height}function oT(e,t){let n=t==="accepted-nms"?e.kept:e.proposals.map((u,l)=>l),i=(u,l)=>{let d=e.proposals[u],c=e.proposals[l];if(t==="detector-score")return d.detectorScore!==c.detectorScore?d.detectorScore{let u=e.proposals[n];return{proposal:n,aabb:u.aabb,rect:u.rect,...u.outline?{outline:u.outline}:{},identity:u.accepted?u.displayId:null,score:u.score,zIndex:i+1}})}var _s=class{prev=[];nextId=1;reset(){this.prev=[]}assign(t){let n=new Set,i=t.map((l,d)=>d).sort((l,d)=>t[d].zIndex-t[l].zIndex),u=new Array(t.length);for(let l of i){let d=t[l],c=-1,s=wP;for(let r=0;r=s&&(c<0||o>s)&&(c=r,s=o)}c>=0?(n.add(c),u[l]=this.prev[c].id):u[l]=`${_P}${String(this.nextId++).padStart(4,"0")}`}return this.prev=t.map((l,d)=>({id:u[d],aabb:l.aabb,identity:l.identity})),u}};function vs(e,t,n,i=u=>u){return ws(e.map((l,d)=>({instanceId:t[d],aabb:l.aabb,rect:l.rect,...l.outline?{outline:l.outline}:{},identity:l.identity})),n).map((l,d)=>({...l,zIndex:e[d].zIndex,boxIndex:i(e[d].proposal)}))}var vP={card:null,boxIndex:null,box:null,cardId:null,name:null};function qd(e,t,n){let i=e.map(l=>({card:l,quad:Ud(l,n),zIndex:l.zIndex??0})),u=Vd(t,i);return u?{card:u,boxIndex:u.boxIndex??null,box:{x:u.bounds.x*n.width,y:u.bounds.y*n.height,width:u.bounds.width*n.width,height:u.bounds.height*n.height},cardId:u.cardId,name:u.name}:vP}var xP="identity-groups";function Hd(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.schemaVersion!==1||t.kind!==xP||typeof t.version!="number"||!Number.isInteger(t.version)||!Array.isArray(t.groups)||typeof t.representative!="object"||t.representative===null||Array.isArray(t.representative))return null;let n=new Map,i=[];for(let l of t.groups){if(!Array.isArray(l)||l.length<2)return null;let d=[];for(let c of l){if(typeof c!="string"||c.length===0||n.has(c))return null;n.set(c,i.length),d.push(c)}i.push(d)}let u=new Map;for(let[l,d]of Object.entries(t.representative)){if(typeof d!="string"||l===d)return null;let c=n.get(l);if(c===void 0||n.get(d)!==c)return null;u.set(l,d)}for(let l of i){let d=l.filter(c=>!u.has(c));if(d.length!==1||l.some(c=>u.has(c)&&u.get(c)!==d[0]))return null}return{version:t.version,groups:i,representative:u}}var $P=["name","printing"];function Wd(e){return $P.includes(e)}function aT(e,t){return t==="printing"?e.printingOf??e.id:e.name}function uT(e,t){let n=new Map;for(let i of[...new Set(e)].sort(sT)){let u=t.get(i);if(u===void 0)continue;let l=n.get(u);l?l.push(i):n.set(u,[i])}return[...n.values()].filter(i=>i.length>=2).sort((i,u)=>sT(i[0],u[0]))}function sT(e,t){return et?1:0}var Tn=class{rep=new Map;display;constructor(t=null,n,i="representative"){if(this.display=i,!!t)for(let[u,l]of t.representative)i==="representative"&&n&&!n(l)||this.rep.set(u,l)}of(t){return this.rep.get(t)??t}shown(t){return this.display==="best-printing"?t:this.of(t)}get collapsedCount(){return this.rep.size}};var xs=["webgpu","wasm"];function Kd(e,t=e.hover.selection){let n=e.boxes.flatMap((s,r)=>s.face!==null?[r]:[]),i=n.map(s=>e.boxes[s]),u=new Map,l=i.map(s=>{let r=s.face;r.cardId!==null&&r.name!==null&&u.set(r.cardId,r.name);let o={x:s.box[0],y:s.box[1],width:s.box[2],height:s.box[3]};return{aabb:o,rect:{cx:o.x+o.width/2,cy:o.y+o.height/2,w:o.width,h:o.height,angle:0},score:r.similarity,detectorScore:s.score,accepted:r.cardId!==null,displayId:r.cardId??r.topId}}),d=i.flatMap((s,r)=>s.face.kept?[r]:[]),c=Hi({proposals:l,kept:d},t);return vs(c,c.map((s,r)=>`${t}_${r}`),{frameWidth:e.frame.width,frameHeight:e.frame.height,names:u},s=>n[s])}function $s(e,t,n,i){let u=i===void 0||i===e.hover.selection?e.hover.cards:Kd(e,i);return qd(u,{x:t,y:n},e.frame)}var fe=Math.fround,lT=63/88,TP=128,Tt=90,SP=.2,IP=8,OP=.35,EP=.55,AP=.9,kP=Object.freeze({scales:[.95,1,1.05],maxFacesPerFrame:8,budgetMs:1500}),PP=[1,.8824969025845955,.6065306597126334,.32465246735834974,.1353352832366127,.04393693362340742,.011108996538242306],dT=6,CP=fe(fe(180)/fe(Math.PI)),Xd=[fe(.299),fe(.587),fe(.114)];function RP(e){let t=e-90*Math.ceil((e-45)/90);return t<=-45?45:t}function DP(e,t){let n=e%t;return n!==0&&n<0!=t<0?n+t:n}function MP(e,t){let n=e%t;return n===0?0:n<0?fe(n+t):n}function cT(e){let t=Math.floor(e),n=e-t;return n<.5?t:n>.5?t+1:t%2===0?t:t+1}function NP(e,t){let n=e.length,i=Float32Array.from(e).sort(),u=fe(t),l=fe(fe(fe(n*u)+fe(1+fe(u*-1)))-1),d,c;l>=n-1?d=c=n-1:l<0?d=c=0:(d=Math.floor(l),c=d+1);let s=d===c?0:fe(l-d),r=i[d],o=i[c],a=fe(o-r);return s>=.5?fe(o-fe(a*fe(1-s))):fe(r+fe(a*s))}function Zd(e){let{width:t,height:n}=e,i=e.channels??4,u=Math.max(1,Math.ceil(Math.max(n,t)/TP)),l=u===1?n:Math.floor(n/u),d=u===1?t:Math.floor(t/u);if(Math.min(l,d)c[Math.min(l-1,Math.max(0,C))*d+Math.min(d-1,Math.max(0,ee))],o=l-2,a=d-2,p=o*a,h=new Float32Array(p),m=new Float32Array(p),g=new Uint8Array(p),_=new Float32Array(p),w=0,y=0;for(let C=0;Cy&&(y=_[B]))}if(y<=0)return 0;let T=new Float32Array(w);for(let C=0,ee=0;C=S)||!(ee>0))continue;let v=MP(fe(fe(Math.atan2(m[C],h[C]))*CP),90),R=Math.min(Math.trunc(fe(fe(v/90)*Tt)),Tt-1);O[R]=O[R]+ee}let A=new Float64Array(Tt);for(let C=0;CA[P]&&(P=C);let I=A[(P-1+Tt)%Tt],z=A[(P+1)%Tt],q=I-2*A[P]+z,J=q!==0?.5*(I-z)/q:0,G=DP((P+.5+J)*90/Tt,90);return RP(G)}var pT=1;function Yd(e,t,n){let i=Math.abs(n)*(Math.PI/180),u=Math.cos(i),l=Math.sin(i),d=u*u-l*l;if(d>OP){let s=(e*u-t*l)/d,r=(t*u-e*l)/d;if(s>0&&r>0){let o=Math.min(s,r)/Math.max(s,r);if(o>=EP&&o<=AP)return{w:s,h:r,how:"exact"}}}let c=null;for(let s of[lT,1/lT]){let r=s*u+l,o=s*l+u,a=(e*r+t*o)/(r*r+o*o),p=(e-a*r)**2+(t-a*o)**2;(c===null||pw>=0&&w=0&&yhT(e,c,s,l*r,d*r,u))}}function fT(e,t,n){if(Math.abs(e)!["scales","maxFacesPerFrame","budgetMs"].includes(l));if(n.length>0)return`tiltedRetry has unknown key(s) ${n.sort().join(", ")}`;let i=t.scales;if(!Array.isArray(i)||i.length<1||i.length>5||!i.every(l=>typeof l=="number"&&Number.isFinite(l)&&l>=.5&&l<=1.5))return"tiltedRetry.scales must list 1 to 5 numbers from 0.5 to 1.5";let u=l=>typeof l=="number"&&Number.isInteger(l)&&l>=1;return u(t.maxFacesPerFrame)?u(t.budgetMs)?null:"tiltedRetry.budgetMs must be a whole number above 0":"tiltedRetry.maxFacesPerFrame must be a whole number above 0"}var zP=.3;function yT(e,t){let n=Math.max(0,Math.floor(t.x)),i=Math.max(0,Math.floor(t.y)),u=Math.min(e.width,Math.floor(t.x+t.width)),l=Math.min(e.height,Math.floor(t.y+t.height)),d=Math.max(0,u-n),c=Math.max(0,l-i),s=new Uint8ClampedArray(d*c*4);for(let r=0;r=t.tau&&e.margin>=t.delta}function wT(e,t,n){if(lr(e,n)||!n.rotationRetry)return{orientation:0,match:e,retried:!1};let i=[e,...t()],u=-1;for(let l=0;li[u].similarity)&&(u=l);if(u<0){u=0;for(let l=1;li[u].similarity&&(u=l)}return{orientation:u,match:i[u],retried:!0}}function gT(e){let t=[],n=[];return e.forEach((i,u)=>{let l=i.tilted!==void 0&&i.tilted.scale!==null;i.tauPassed&&(i.orientation===0&&!l?t:n).push(u)}),[...t,...n]}function bT(e,t){let n=(t??e.map((i,u)=>u)).filter(i=>e[i].tauPassed);return Cd(n,i=>e[i].aabb,i=>e[i].score,zP)}async function ec(e,t,n,i,u=Hn,l=null,d=null,c=!1){let s=n.preprocessing,r=n.rule,o=s.size,a=n.dim,p=[],h=[],m=[];for(let N of i){let X=yT(e,N.aabb),{rgba:W,width:re,height:le}=X;ren.matchScored(w,X*a)),T=[];if(r.rotationRetry)for(let N=0;N[N,X])),O=null;if(T.length>0){let N=new Float32Array(T.length*3*g);for(let X=0;X{let W=S.get(N);if(W===void 0||O===null)throw new Error(`the turned looks of proposal ${N} were not embedded`);return(W*3+X-1)*a},P=h.map((N,X)=>wT(y[X],()=>[1,2,3].map(W=>n.matchScored(O,A(X,W))),r)),I=N=>P[N].orientation===0?{embs:w,off:N*a}:{embs:O,off:A(N,P[N].orientation)},z=new Map,q,J,G=!1;if(l)try{let N=performance.now(),X=[],W=[],re=[];for(let le=0;le0){let le=await l.verifyBatch(re,n.bankIds);X.forEach((ce,xe)=>{let Ge=le[xe],Ve=W[xe],it=P[ce].match,Ze=G$(Ve,Ge.candidates,zr=>n.columnsOf(zr)),$e=l.reorder?n.lookOf(Ze):n.lookWithin(Ze,n.lookOf(Ve).row),{row:ht,...It}=$e;z.set(ce,{match:It,geometric:q$({topId:it.topId,similarity:it.similarity,margin:it.margin,accepted:lr(it,r)},Ge)})})}q=performance.now()-N}catch(N){G=!0,J=N,z.clear(),q=void 0}let C=new Map,ee,v,R=!1,H=0;if(d)try{let N=performance.now(),{scales:X,maxFacesPerFrame:W}=d.settings,re=ce=>z.get(ce)?.match??P[ce].match,le=_T(h.map((ce,xe)=>({aabb:ce.aabb,similarity:P[xe].match.similarity,accepted:lr(re(xe),r)})),d.focus??null).slice(0,W);if(le.length>0){let ce=[],xe=new Float32Array(le.length*X.length*g);le.forEach((Ve,it)=>{let Ze=m[Ve],{tilt:$e,rects:ht}=Jd(e,h[Ve].aabb,{data:Ze.rgba,width:Ze.width,height:Ze.height},X);ce.push($e),ht.forEach((It,zr)=>{let qt=gs(It.rgba,It.width,It.height,s);xe.set(bs(qt,P[Ve].orientation,o),(it*X.length+zr)*g)})}),H=le.length*X.length;let Ge=await t.embedBatch(xe,H);le.forEach((Ve,it)=>{let Ze=re(Ve),$e=null;for(let ht=0;ht$e.match.similarity)&&($e={q:ht,match:It})}C.set(Ve,{match:$e?$e.match:null,evidence:{tilt:ce[it],scale:$e?X[$e.q]:null,before:{topId:Ze.topId,similarity:Ze.similarity,margin:Ze.margin}}})})}ee=performance.now()-N}catch(N){R=!0,v=N,C.clear(),H=0,ee=void 0}let L=new Map,V=N=>{let X=L.get(N);if(X===void 0){let{aabb:W}=h[N],re=m[N],{tilt:le,w:ce,h:xe}=Qd({data:re.rgba,width:re.width,height:re.height},W.width,W.height);X={cx:W.x+W.width/2,cy:W.y+W.height/2,w:ce,h:xe,angle:le},L.set(N,X)}return X},K=N=>{let X=[];for(let W=0;Wt!==null&&t.x>=d.x&&t.x<=d.x+d.width&&t.y>=d.y&&t.y<=d.y+d.height,i=e.map((d,c)=>c).filter(d=>!e[d].accepted),u=i.filter(d=>n(e[d].aabb)).sort((d,c)=>e[d].aabb.width*e[d].aabb.height-e[c].aabb.width*e[c].aabb.height),l=i.filter(d=>!n(e[d].aabb)).sort((d,c)=>e[c].similarity-e[d].similarity);return[...u,...l]}var Ss={tau:.62,delta:.05,rotationRetry:!0},Ts=-2,Wi=class{constructor(t,n=Ss,i=new Tn){this.bank=t;this.rule=n;this.contract=er[t.preprocessing],this.rowShown=t.ids.map(l=>i.shown(l));let u=new Map;this.rowIdent=new Int32Array(t.ids.length);for(let l=0;lc&&(c=p,s=a)}let r=Ts,o=s>=0?this.rowIdent[s]:-1;for(let a=0;ar&&(r=d[a]);return{bestRow:s,best:c,other:r}}matchScored(t,n){let{bestRow:i,best:u,other:l}=this.topAndOther(t,n),d=this.bank.ids[i];return{cardId:u>=this.rule.tau?d:null,similarity:u,topId:d,identity:this.identRep[this.rowIdent[i]],displayId:this.rowShown[i],margin:u-l}}scoreRow(t,n){let{matrix:i,dim:u,ids:l}=this.bank,d=new Float64Array(l.length);for(let c=0;cd);n.sort((l,d)=>t[d]-t[l]);let i=new Set,u=[];for(let l of n){let d=this.bank.ids[l];i.has(d)||(i.add(d),u.push({cardId:d,cosine:t[l]}))}return u}columns=null;columnsOf(t){return this.columns===null&&(this.columns=new Map,this.bank.ids.forEach((n,i)=>{let u=this.columns.get(n);u?u.push(i):this.columns.set(n,[i])})),this.columns.get(t)??[]}bankIdSet=null;get bankIds(){return this.columnsOf(""),this.bankIdSet??=new Set(this.columns.keys()),this.bankIdSet}scored(t,n,i){let u=this.bank.ids[t];return{cardId:n>=this.rule.tau?u:null,similarity:n,topId:u,identity:this.identRep[this.rowIdent[t]],displayId:this.rowShown[t],margin:n-i,row:t}}lookOf(t){let n=0;for(let d=1;dt[n]&&(n=d);let i=this.rowIdent[n],u=Ts,l=!1;for(let d=0;du)&&(u=t[d]),l=!0);return this.scored(n,t[n],u)}lookWithin(t,n){let i=this.rowIdent[n],u=-1,l=Ts,d=!1;for(let c=0;ct[u])&&(u=c):((!d||t[c]>l)&&(l=t[c]),d=!0);return this.scored(u,t[u],l)}matchPooled(t,n=this.rule.delta){let{bestRow:i,best:u,other:l}=this.topAndOther(t,0),d=u-l;return{cardId:u>=this.rule.tau&&d>=n?this.rowShown[i]:null,similarity:u,margin:d}}};var Ki=class{constructor(t=3){this.k=t;if(!Number.isInteger(t)||t<1)throw new RangeError(`k must be a positive integer, got ${t}`)}k;run=0;misses=0;showing=!1;reset(){this.run=0,this.misses=0,this.showing=!1}observe(t){return t?(this.run+=1,this.misses=0,this.run>=this.k&&(this.showing=!0)):(this.run=0,this.misses+=1,this.misses>=this.k&&(this.showing=!1)),{confirmed:this.showing,consecutive:this.run}}};var BP=.4,FP=2,LP=5,jP=2,UP="track_";function vT(e){let t=e[0].length,n=new Float32Array(t);for(let l of e)for(let d=0;d0))return null;for(let l=0;lu));for(let i of this.tracks){let u=-1,l=BP;for(let d of n){let c=qn(i.detection.aabb,t[d].aabb);c>l&&(l=c,u=d)}if(u>=0){let d=t[u];i.detection=d,i.misses=0,i.age+=1,i.embeddings.push(d.embedding),i.embeddings.length>LP&&i.embeddings.shift(),n.delete(u)}else i.misses+=1}this.tracks=this.tracks.filter(i=>i.misses<=FP);for(let i of n){let u=t[i];this.tracks.push({instanceId:`${UP}${String(this.nextId++).padStart(4,"0")}`,detection:u,embeddings:[u.embedding],misses:0,age:1})}return this.tracks.filter(i=>i.misses===0).map(i=>({instanceId:i.instanceId,detection:i.detection,identity:i.age>=jP?this.identityOf(i):null}))}};var VP=.25,GP=5;function qP(e,t){if(e===null||t===void 0)return!1;let n=t-e;return n<-VP||n>GP}function HP(e){return[e.x,e.y,e.width,e.height]}var Zi=class{hoverSelection;detector;embedder;recognizer;names;classNames;faceClass;minCropPx;now;tracker;gate=new Ki(3);hoverIds=new _s;heldCards=[];lastVideoTimeSec=null;geometric;geometricFailure=null;tiltedRetry;tiltedFailure=null;constructor(t){this.detector=t.detector,this.embedder=t.embedder,this.names=t.names,this.classNames=t.classNames??["face","back"],this.faceClass=t.faceClass??Rr,this.minCropPx=t.minCropPx??Hn,this.hoverSelection=t.hoverSelection??Gd,this.now=t.now??(()=>performance.now()),this.geometric=t.geometric??null,this.tiltedRetry=t.tiltedRetry??null;let n=new Tn(t.identityGroups??null,i=>this.names.has(i),t.identityDisplay??"best-printing");this.recognizer=new Wi(t.bank,t.accept??Ss,n),this.tracker=new Xi(i=>this.recognizer.matchPooled(i).cardId)}get size(){return this.recognizer.size}takeGeometricFailure(){let t=this.geometricFailure;return this.geometricFailure=null,t}takeTiltedFailure(){let t=this.tiltedFailure;return this.tiltedFailure=null,t}get tiltedSettings(){return this.tiltedRetry}setTiltedRetry(t){this.tiltedRetry=t,this.tiltedFailure=null}get geometricStage(){return this.geometric}setGeometric(t){this.geometric=t,this.geometricFailure=null}reset(){this.tracker.reset(),this.gate.reset(),this.heldCards=[],this.hoverIds.reset(),this.lastVideoTimeSec=null}async analyze(t,n,i={}){let u=this.now(),l=qP(this.lastVideoTimeSec,n);l&&this.reset(),n!==void 0&&(this.lastVideoTimeSec=n);let d=await this.detector.propose(t),c=this.now()-u,s=d.filter(I=>cs(I.aabb,t.width,t.height,this.minCropPx)).map(I=>F$(I,t)),{faces:r}=L$(s,this.faceClass),o=this.now(),a=this.tiltedRetry&&i.tilted!==!1?{settings:this.tiltedRetry,focus:i.focus??null}:null,p=await ec(t,this.embedder,this.recognizer,r,this.minCropPx,this.geometric,a,i.rotatedOutlines===!0),h=this.now()-o;if(p.tiltedError!==void 0&&this.tiltedRetry&&(this.tiltedFailure={error:p.tiltedError},this.tiltedRetry=null),p.geometricError!==void 0&&this.geometric&&(this.geometricFailure={stage:this.geometric,error:p.geometricError},this.geometric=null),p.proposals.length!==r.length)throw new Error("pipeline: a valid face box was not recognized");let m={frameWidth:t.width,frameHeight:t.height,names:this.names},g=Hi(p,this.hoverSelection),_=r.map(I=>s.indexOf(I)),w=vs(g,this.hoverIds.assign(g),m,I=>_[I]),y=p.base??p,T=y.kept.map(I=>{let z=y.proposals[I];return{aabb:z.aabb,rect:z.rect,cardId:z.topId,embedding:z.embedding,...z.outline?{outline:z.outline}:{}}}),S=this.tracker.update(T),O=T.length>0,A=this.gate.observe(O),P;return A.confirmed?O?(P=ws(S.map(I=>({instanceId:I.instanceId,aabb:I.detection.aabb,rect:I.detection.rect,...I.detection.outline?{outline:I.detection.outline}:{},identity:I.identity})),m),this.heldCards=P):P=this.heldCards:(this.heldCards=[],P=[]),{frame:{width:t.width,height:t.height},boxes:this.boxResults(s,r,p),hover:{selection:this.hoverSelection,cards:w},tracks:{shown:A.confirmed,cards:P},discontinuity:l,retried:p.retried,embeddings:p.embeddings,timings:{detectorMs:c,recognizeMs:h,analyzeMs:this.now()-u,...p.geometricMs!==void 0?{geometricMs:p.geometricMs}:{},...p.tiltedMs!==void 0?{tiltedMs:p.tiltedMs}:{}}}}boxResults(t,n,i){let u=new Map(n.map((d,c)=>[d,c])),l=new Set(i.kept);return t.map(d=>{let c=u.get(d),s=null;if(c!==void 0){let r=i.proposals[c],o=r.accepted&&this.names.has(r.displayId)?r.displayId:null;s={topId:r.topId,topName:this.names.get(r.topId)??null,similarity:r.score,margin:r.margin,look:r.orientation,retried:r.retried,tauPassed:r.tauPassed,accepted:r.accepted,cardId:o,name:o===null?null:this.names.get(o)??null,kept:l.has(c),...r.geometric?{geometric:r.geometric}:{},...r.tilted?{tilted:r.tilted}:{}}}return{box:HP(d.aabb),score:d.score,cls:d.cls,className:this.classNames[d.cls]??String(d.cls),face:s}})}};var xT=1,$T="vision-release",WP=[8,16,32];function TT(e,t){return WP.reduce((n,i)=>n+Math.floor(e/i)*Math.floor(t/i),0)}var KP=/^[0-9a-f]{16}$/,XP=/^[0-9a-f]{64}$/,ZP=/^\d+\.\d+\.\d+$/,YP=["schemaVersion","kind","id","game","locale","detector","recognizer","bank","identity","catalog","accept","hover","runtime","tiltedRetry"],ST=["tau","delta","rotationRetry"],Ue=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),ft=e=>typeof e=="number"&&Number.isInteger(e)&&e>0,eo=e=>typeof e=="number"&&Number.isFinite(e),tt=e=>typeof e=="string"&&e.trim()!=="";function JP(e){return!tt(e)||e.includes("\\")||/^[A-Za-z][A-Za-z0-9+.-]*:/.test(e)||/[\x00-\x1f\x7f]/.test(e)||/^ | $/.test(e)||e.startsWith("/")?!1:!e.split("/").some(t=>{let n=t.replace(/%2e/gi,".");return n==="."||n===".."})}function Ji(e){return!Ue(e)||!JP(e.path)||typeof e.sha256!="string"||!XP.test(e.sha256)||!ft(e.bytes)?null:{path:e.path,sha256:e.sha256,bytes:e.bytes}}function QP(e){let t=e.input,n=e.decode;if(!Ue(t)||!ft(t.width)||!ft(t.height))return"detector.input must give a width and a height";if(!Ue(n))return"detector.decode must be an object";if(!tt(n.inputName)||!tt(n.outputName))return"detector.decode must name the model's input and output";let i=[["layout","NCHW"],["channels","BGR"],["scale","0-255"],["score","obj * max(cls)"],["class","argmax(cls)"]];for(let[o,a]of i)if(n[o]!==a)return`detector.decode.${o} is not ${JSON.stringify(a)}, the contract this runtime implements`;let u=n.letterbox;if(!Ue(u)||u.width!==t.width||u.height!==t.height)return"detector.decode.letterbox differs from detector.input";if(typeof u.pad!="number"||!Number.isInteger(u.pad)||u.pad<0||u.pad>255)return"detector.decode.letterbox.pad must be a whole number from 0 to 255";let l=[["anchor","top-left"],["resize","pillow-bilinear"],["ratio","min(height / frameHeight, width / frameWidth)"],["size","round(frame * ratio)"]];for(let[o,a]of l)if(u[o]!==a)return`detector.decode.letterbox.${o} is not ${JSON.stringify(a)}`;let d=n.classes;if(!Array.isArray(d)||d.length===0||!d.every(tt)||new Set(d).size!==d.length)return"detector.decode.classes must be a list of distinct class names";if(e.faceClass!==Rr||d[Rr]!=="face")return`detector.faceClass must be ${Rr} and that class must be named "face"`;let c=n.output,s=["cx","cy","w","h","obj",...d.map(o=>`cls_${o}`)];if(!Ue(c)||!Array.isArray(c.columns)||c.columns.length!==s.length||!c.columns.every((o,a)=>o===s[a]))return"detector.decode.output.columns must be cx, cy, w, h, obj and one cls_ per class";if(c.anchors!==TT(t.width,t.height))return`detector.decode.output.anchors must be ${TT(t.width,t.height)} for a ${t.width} x ${t.height} input`;if(!eo(n.threshold)||!(n.threshold>0&&n.threshold<1))return"detector.decode.threshold must be a number between 0 and 1";if(n.threshold<.01)return`detector.decode.threshold ${n.threshold} is below 0.01, the lowest score at which the detector export checks box parity`;let r=n.nms;return!Ue(r)||!eo(r.iou)||!(r.iou>0&&r.iou<=1)||r.classAgnostic!==!0||r.greedy!==!0?"detector.decode.nms must give an iou above 0 and at most 1, with classAgnostic and greedy both true":ft(n.maxProposals)?ft(e.minCropPx)?{inputName:n.inputName,outputName:n.outputName,letterbox:{width:t.width,height:t.height,pad:u.pad},anchors:c.anchors,classes:d,decode:{threshold:n.threshold,nmsIou:r.iou,maxProposals:n.maxProposals},faceClass:Rr,minCropPx:e.minCropPx}:"detector.minCropPx must be a whole number above 0":"detector.decode.maxProposals must be a whole number above 0"}function OT(e){let t=A=>({error:A});if(!Ue(e)||e.schemaVersion!==xT||e.kind!==$T)return t(`not a "${$T}" document of schema version ${xT}`);let n=Object.keys(e).filter(A=>!YP.includes(A));if(n.length>0)return t(`unknown key(s) ${n.sort().join(", ")}`);if(typeof e.id!="string"||!KP.test(e.id))return t("id must be 16 lowercase hex digits");if(!tt(e.game)||!tt(e.locale))return t("game and locale must be non-empty strings");let i=e.detector;if(!Ue(i))return t("incomplete release: detector missing (a release is all-or-nothing)");let u=Ji(i);if(!u||!tt(i.version)||!tt(i.weights))return t("detector must pin a file and carry a version and a weights label");if(i.arm!=="yolox")return t(`detector.arm ${JSON.stringify(i.arm)} is not one this runtime implements`);let l=QP(i);if(typeof l=="string")return t(l);let d=e.recognizer;if(!Ue(d))return t("incomplete release: recognizer missing (a release is all-or-nothing)");let c=Ji(d);if(!c||!tt(d.version)||!tt(d.weights)||!ft(d.dim))return t("recognizer must pin a file and carry a version, a weights label and a dim");if(!tt(d.inputName)||!tt(d.outputName))return t("recognizer must name the model's input and output");let s=ms(d.preprocessing);if(s===null)return t(`recognizer.preprocessing is not a contract this runtime implements (known: ${Object.keys(er).join(", ")})`);let r=e.bank;if(!Ue(r))return t("incomplete release: bank missing (a release is all-or-nothing)");let o=Ji(r);if(!o||!ft(r.version)||!ft(r.cardCount)||!ft(r.entryCount))return t("bank must pin a file and carry a version, a cardCount and an entryCount");if(r.aggregation!=="mean")return t('bank.aggregation must be "mean"');let a=e.identity;if(!Ue(a)||!Wd(a.level))return t('identity.level must be "name" or "printing"');let p=a.groups,h=Ji(p);if(!h||!Ue(p)||!ft(p.version))return t("incomplete release: identity.groups must pin a file and carry a version");if(a.display!=="best-printing"&&a.display!=="representative")return t(`identity.display ${JSON.stringify(a.display)} is not one of best-printing, representative`);let m=e.catalog,g=Ji(m);if(!g||!Ue(m)||!ft(m.cardCount))return t("incomplete release: catalog must pin a file and carry a cardCount");let _=e.accept;if(!Ue(_))return t("incomplete release: accept missing (a release is all-or-nothing)");if(Object.keys(_).some(A=>!ST.includes(A)))return t(`accept has unknown key(s) (expected ${ST.join(", ")})`);if(!eo(_.tau)||!(_.tau>0&&_.tau<=1))return t("accept.tau must be a number above 0 and at most 1");if(!eo(_.delta)||!(_.delta>=0&&_.delta<1))return t("accept.delta must be a number from 0 to below 1");if(typeof _.rotationRetry!="boolean")return t("accept.rotationRetry must be true or false");let w=e.hover;if(!Ue(w)||!iT(w.selection))return t("hover.selection is not one of accepted-nms, best-score, detector-score");if(!ft(w.maxAgeMs))return t("hover.maxAgeMs must be a whole number above 0");let y=e.runtime;if(!Ue(y)||typeof y.ortWeb!="string"||!ZP.test(y.ortWeb))return t("runtime.ortWeb must be an exact version of the form 1.2.3");if(y.wasmThreads!==1)return t("runtime.wasmThreads must be 1");let T=y.executionProviders;if(!Array.isArray(T)||T.length===0||new Set(T).size!==T.length||!T.every(A=>xs.includes(A)))return t(`runtime.executionProviders must list one or more of ${xs.join(", ")}, each once`);let S=y.analysisWidth;if(!Ue(S)||!ft(S.min)||!ft(S.max)||S.min>S.max)return t("runtime.analysisWidth must give whole numbers min <= max above 0");let O=null;if("tiltedRetry"in e){let A=mT(e.tiltedRetry);if(A!==null)return t(A);let P=e.tiltedRetry;O={scales:[...P.scales],maxFacesPerFrame:P.maxFacesPerFrame,budgetMs:P.budgetMs}}return{release:{id:e.id,game:e.game,locale:e.locale,detector:{...u,arm:"yolox",version:i.version,weights:i.weights,settings:l},recognizer:{...c,version:d.version,weights:d.weights,dim:d.dim,inputName:d.inputName,outputName:d.outputName,preprocessing:s},bank:{...o,version:r.version,cardCount:r.cardCount,entryCount:r.entryCount},identity:{level:a.level,groups:{...h,version:p.version},display:a.display},catalog:{...g,cardCount:m.cardCount},accept:{tau:_.tau,delta:_.delta,rotationRetry:_.rotationRetry},hover:{selection:w.selection,maxAgeMs:w.maxAgeMs},runtime:{ortWeb:y.ortWeb,executionProviders:T,wasmThreads:1,analysisWidth:{min:S.min,max:S.max}},tiltedRetry:O}}}function eC(e){let t=0,n=()=>{throw new Error("not JSON")},i=()=>{for(;t{let c=t;for(e[t]!=='"'&&n(),t++;t=e.length&&n(),t++,JSON.parse(e.slice(c,t))},l=c=>{i();let s=e[t];if(s==="{"){t++;let o=[];if(i(),e[t]==="}")t++;else for(;;){i();let a=u();i(),e[t]!==":"&&n(),t++;let p=l(!1);if(c&&a==="id"||o.push([a,p]),i(),e[t]===",")t++;else if(e[t]==="}"){t++;break}else n()}return o.sort((a,p)=>a[0]p[0]?1:0),`{${o.map(([a,p])=>`${JSON.stringify(a)}:${p}`).join(",")}}`}if(s==="["){t++;let o=[];if(i(),e[t]==="]")t++;else for(;;)if(o.push(l(!1)),i(),e[t]===",")t++;else if(e[t]==="]"){t++;break}else n();return`[${o.join(",")}]`}if(s==='"')return JSON.stringify(u());let r=/^(?:true|false|null|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(e.slice(t,t+64));return r?(t+=r[0].length,r[0]):n()};i(),e[t]!=="{"&&n();let d=l(!0);return i(),t!==e.length&&n(),d}async function tC(e,t){let n=new TextEncoder().encode(eC(e));return(await t(n.buffer)).slice(0,16)}async function rC(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}var tc={fetchFn:e=>fetch(e),digestSha256Hex:rC};function nC(e,t){let n=l=>/^(\d+)\.(\d+)\.\d+/.exec(l),i=n(e),u=n(t);return i!==null&&u!==null&&i[1]===u[1]&&i[2]===u[2]}var We=class extends Error{};async function ET(e,t,n){let i;try{i=await e.fetchFn(t)}catch(u){throw new We(`${n}: fetch failed (${String(u)})`)}if(!i.ok)throw new We(`${n}: HTTP ${i.status}`);return i.arrayBuffer()}async function Qi(e,t,n,i){let u=await ET(e,new URL(n.path,t).href,i);if(u.byteLength!==n.bytes)throw new We(`${i}: ${n.path} is ${u.byteLength} bytes, the release says ${n.bytes}`);if(await e.digestSha256Hex(u)!==n.sha256)throw new We(`${i}: sha256 of ${n.path} does not match the release`);return u}function Is(e,t){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e))}catch{throw new We(`${t}: the file is not JSON`)}}var iC=/^[a-z][a-zA-Z0-9]*$/,oC=["key","label","values","type"],IT=e=>typeof e=="string"?"text":"number",dr=e=>JSON.stringify(e)??String(e);function AT(e,t,n){for(let i=0;i!oC.includes(r));if(l.length>0)return`${u}: unknown key(s) ${l.join(", ")}`;if(typeof i.key!="string"||!iC.test(i.key))return`${u}: "key" ${dr(i.key)} must be a lowercase letter, then letters and digits only`;let d=i.key;if(d==="kind")return`${u}: "key" "kind" is reserved: the card's kind is always the first filter`;if(t.some(r=>r.key===d))return`${u}: duplicate key ${dr(d)}`;if(!tt(i.label))return`${u} (${d}): "label" must be a non-empty string`;let c=null;if("type"in i){if(i.type!=="text"&&i.type!=="number")return`${u} (${d}): "type" must be "text" or "number", not ${dr(i.type)}`;c=i.type}let s=null;if("values"in i){if(!Array.isArray(i.values)||i.values.length===0)return`${u} (${d}): "values" must be a non-empty list`;let r=AT(i.values,c,`${u} (${d}) values`);if(r!=="text"&&r!=="number")return r;c=r,s=i.values}t.push({key:d,label:i.label,type:c,values:s})}return t}function aC(e,t,n,i){let u=`card ${n}`;if(!Ue(e))return`${u}: "facets" must be an object of facet key to a value or a list of values`;for(let[l,d]of Object.entries(e)){let c=t.find(o=>o.key===l);if(c===void 0)return`${u}: facets.${l}: the catalog declares no facet ${dr(l)}`;let s=Array.isArray(d)?d:[d];if(s.length===0)return`${u}: facets.${l} is an empty list (leave the key out instead)`;let r=AT(s,c.type,`${u}: facets.${l}`);if(r!=="text"&&r!=="number")return r;c.type=r;for(let o of s){if(c.values!==null&&!c.values.includes(o))return`${u}: facets.${l}: ${dr(o)} is not one of the declared values`;let a=i.get(l)??[];a.includes(o)||a.push(o),i.set(l,a)}}return null}function uC(e){if(!Ue(e)||!tt(e.game)||!tt(e.locale)||!Array.isArray(e.cards)||e.cards.length===0)return"the file is not a catalog (game, locale and a list of cards)";let t=e.identity===void 0?"name":e.identity;if(!Wd(t))return`"identity" must be "name" or "printing", not ${JSON.stringify(e.identity)}`;let n=e.facets===void 0?[]:sC(e.facets);if(typeof n=="string")return n;let i=new Map,u=new Map,l=[];for(let c of e.cards){if(!Ue(c)||!tt(c.id)||!tt(c.name))return"every card needs an id, a name and an art path";if(!("art"in c)||c.art!==null&&!tt(c.art))return`card ${c.id}: "art" must be an art path (a file path or an http(s) URL), or null for a card without art`;if(u.has(c.id))return`card id ${c.id} appears twice`;let s=c.printingOf??null;if(s!==null&&!tt(s))return`card ${c.id}: "printingOf" must be a card id or null`;let r=c.facets===void 0?null:aC(c.facets,n,c.id,i);if(r!==null)return r;if(c.extra!==void 0&&!Ue(c.extra))return`card ${c.id}: "extra" must be an object (any keys and values), not ${dr(c.extra)}`;let o={id:c.id,name:c.name,art:c.art,printingOf:s};c.extra!==void 0&&(o.extra=c.extra),u.set(o.id,o),l.push(o)}if(t==="printing")for(let c of l){if(c.printingOf===null)continue;let s=u.get(c.printingOf);if(s===void 0||s===c)return`card ${c.id}: "printingOf" names ${c.printingOf}, which is not another card`;if(s.printingOf!==null)return`card ${c.id}: "printingOf" names ${c.printingOf}, which is itself a printing of ${s.printingOf}`}let d=n.map(c=>{let s=c.values??[...i.get(c.key)??[]];return c.values===null&&c.type==="number"&&s.sort((r,o)=>r-o),{key:c.key,label:c.label,type:c.type??"text",values:[...s]}});return{game:e.game,locale:e.locale,identity:t,cards:l,facets:d}}async function rc(e,t=tc,n={}){try{let i=await ET(t,e,"release"),u=OT(Is(i,"release"));if("error"in u)throw new We(`release: ${u.error}`);let l=u.release,d=await tC(new TextDecoder().decode(i),t.digestSha256Hex);if(d!==l.id)throw new We(`release: id ${l.id} is not the hash of the document (which is ${d})`);if(n.ortWeb!==void 0&&!nC(l.runtime.ortWeb,n.ortWeb))throw new We(`release: measured on onnxruntime-web ${l.runtime.ortWeb}, this build runs ${n.ortWeb} (major and minor version must match)`);try{n.onDocument?.([l.detector,l.recognizer,l.bank,l.identity.groups,l.catalog].reduce((q,J)=>q+J.bytes,0))}catch{}let[c,s,r,o,a]=await Promise.all([Qi(t,e,l.detector,"detector"),Qi(t,e,l.recognizer,"recognizer"),Qi(t,e,l.bank,"bank"),Qi(t,e,l.identity.groups,"identity.groups"),Qi(t,e,l.catalog,"catalog")]);try{n.onFetched?.()}catch{}let p=new Uint8Array(r),h=jd(p);if(h!==null&&h!==ys)throw new We(`bank: the binary bank is of format version ${h}, and this runtime reads version ${ys} only`);let m=Ld(p)?eT(p):Fd(Is(r,"bank"));if(!m)throw new We("bank: the file is not a bank this runtime can read");let g=[[m.version===l.bank.version,"bank.version differs from the bank file's"],[m.model===l.recognizer.version,`bank: the file's model ${JSON.stringify(m.model)} is not recognizer.version ${JSON.stringify(l.recognizer.version)}`],[m.dim===l.recognizer.dim,"bank: the vector size differs from recognizer.dim"],[m.preprocessing===l.recognizer.preprocessing,"bank: the file's preprocessing differs from recognizer.preprocessing"],[m.ids.length===l.bank.entryCount,"bank.entryCount is not the number of entries in the bank file"],[new Set(m.ids).size===l.bank.cardCount,"bank.cardCount is not the number of distinct card ids in the bank file"],[m.tau===null||m.tau===l.accept.tau,`bank: the file records tau ${m.tau}, accept.tau is ${l.accept.tau}`]];for(let[q,J]of g)if(!q)throw new We(J);let _=uC(Is(a,"catalog"));if(typeof _=="string")throw new We(`catalog: ${_}`);if(_.game!==l.game||_.locale!==l.locale)throw new We("catalog: the file is for another game or locale");if(_.cards.length!==l.catalog.cardCount)throw new We(`catalog.cardCount ${l.catalog.cardCount} is not the file's ${_.cards.length} cards`);let w=new Map(_.cards.map(q=>[q.id,q.name])),y=m.ids.filter(q=>!w.has(q));if(y.length>0)throw new We(`${new Set(y).size} bank id(s) are not in the catalog (e.g. ${y[0]})`);let T=Is(o,"identity.groups"),S=Hd(T);if(!S)throw new We("identity.groups: the file is not an identity-groups document");if(S.version!==l.identity.groups.version)throw new We("identity.groups.version differs from the file's");if((Ue(T)&&Ue(T.bank)?T.bank.sha256:void 0)!==l.bank.sha256)throw new We("identity.groups: the file was not made for this release's bank (its bank sha256 differs)");let A=_.identity;if(l.identity.level!==A)throw new We(`identity.level is "${l.identity.level}", and the catalog states the identity rule "${A}": a release is used with the rule its catalog states`);if((Ue(T)&&Ue(T.rule)?T.rule.level:void 0)!==A)throw new We(`identity.groups: the file's groups are not by ${A}`);let I=new Map(_.cards.map(q=>[q.id,aT(q,A)])),z=q=>JSON.stringify(q.map(J=>[...J].sort()).sort((J,G)=>J[0]G[0]?1:0));if(z(S.groups)!==z(uT(m.ids,I)))throw new We(`identity.groups: the groups are not the ones the catalog's ${A==="name"?"names give":"identity rule gives"} for the bank's ids`);return{ok:!0,data:{release:l,detectorBytes:new Uint8Array(c),recognizerBytes:new Uint8Array(s),bank:m,identityGroups:S,cards:_.cards,names:w}}}catch(i){return{ok:!1,reason:i instanceof We?i.message:`unexpected: ${String(i)}`}}}async function lC(e){for(let t of e)try{await t?.release?.()}catch{}}async function kT(e,t,n=e.release.runtime.executionProviders){let{release:i}=e,u=null,l=null,d=async c=>(await lC([u,l]),{error:c});try{if(n.length===0)return await d("no execution provider to try");let c=i.recognizer;return u=await t.embedder(e.recognizerBytes,{inputName:c.inputName,outputName:c.outputName,inputSize:er[c.preprocessing].size,dim:c.dim},n),u?(l=await t.detector(e.detectorBytes,i.detector.settings,n),l?{pipeline:new Zi({detector:l,embedder:u,bank:e.bank,accept:i.accept,identityGroups:e.identityGroups,identityDisplay:i.identity.display,names:e.names,hoverSelection:i.hover.selection,classNames:i.detector.settings.classes,faceClass:i.detector.settings.faceClass,minCropPx:i.detector.settings.minCropPx,tiltedRetry:i.tiltedRetry}),embedder:u,detector:l,providers:[...n]}:await d("detector: the model did not initialize on any execution provider, or is not the model the release describes")):await d("recognizer: the model did not initialize on any execution provider, or is not the model the release describes")}catch(c){return await d(`unexpected while building: ${String(c)}`)}}var to=class extends Error{constructor(n){super(`the release could not be loaded: ${n}`);this.reason=n;this.name="ReleaseError"}reason};function dC(e){return async t=>{if(!t.startsWith(Wn))throw new Error(`${t} is not one of the release's files`);let n=W$(t.slice(Wn.length)),i=Object.hasOwn(e,n)?e[n]:void 0;if(i===void 0)throw new Error(`no file ${n} among the release's files`);return{ok:!0,status:200,arrayBuffer:()=>i.arrayBuffer()}}}var Dr=e=>Math.round(e);function cC(e){let t=(n,i)=>{let u=performance.now()-i;return{createMs:Dr(n.createMs),firstRunMs:Dr(n.firstRunMs),failedProvidersMs:Dr(Math.max(0,u-n.createMs-n.firstRunMs)),totalMs:Dr(u)}};return{embedder:async(n,i,u)=>{let l=performance.now(),d=await Vi.create(n,i,u);return d&&(e.recognizer=t(d.setup,l)),d},detector:async(n,i,u)=>{let l=performance.now(),d=await Ui.create(n,i,u);return d&&(e.detector=t(d.setup,l)),d}}}async function pC(e,t={}){let n=t.files?Wn:typeof location<"u"?location.href:void 0,i=new URL(e,n).href,u=g=>{try{t.onProgress?.(g)}catch{}},l=performance.now();u({phase:"downloading",bytes:null});let d={...tc,...t.deps,...t.files?{fetchFn:dC(t.files)}:{}},c=null,s=await rc(i,d,{ortWeb:M$(),onFetched:()=>{c=performance.now()},...t.onProgress?{onDocument:g=>u({phase:"downloading",bytes:g})}:{}});if(!s.ok)throw new to(s.reason);let r=performance.now(),o=(c??r)-l,a=r-(c??r);u({phase:"preparing"});let{data:p}=s;N$({wasmThreads:p.release.runtime.wasmThreads,...t.wasmPaths!==void 0?{wasmPaths:t.wasmPaths}:{}}),kd();let h={},m=await kT(p,cC(h),t.providers??p.release.runtime.executionProviders);if("error"in m){let g=kd();throw new to(g.length>0?`${m.error} (${g.join("; ")})`:m.error)}return{release:p.release,pipeline:m.pipeline,backend:{detector:m.detector.ep,recognizer:m.embedder.ep},cards:p.cards,names:p.names,stageInputs:{bankSha256:p.release.bank.sha256,bankIds:[...new Set(p.bank.ids)],identities:H$(p.cards,p.release.identity.level,p.identityGroups)},...h.recognizer&&h.detector?{timings:{startedAtMs:Dr(l),filesMs:Dr(o),readMs:Dr(a),recognizer:h.recognizer,detector:h.detector,totalMs:Dr(performance.now()-l)}}:{},dispose:async()=>{await m.embedder.release?.(),await m.detector.release?.()}}}function hC(e,t,n){return e.pipeline.analyze(t,n)}var fC=250,Os=250,mC=1e4,nc=5e3,gC=400,ic=2e3;function CT(e,t,n){return Math.abs(t-e)*1e3<=n}var bC=250,RT=5e3,DT=15e3,PT=[250,500,1e3,2e3];function oc(e,t){return e===void 0?"stale-request":e.requestId<=t.lastAcceptedRequestId?"superseded":e.requestId!==t.inFlightRequestId?"stale-request":e.videoKey!==t.videoKey?"video-key":e.generation!==t.generation?"generation":null}function MT(e){return e==="video-key"||e==="generation"}var ro=class{constructor(t,n=3,i="always-on",u=t,l=null){this.intervalMs=t;this.confirmFrames=n;this.mode=i;this.readingIntervalMs=u;this.probeIntervalMs=l;this.checkProbe(i)}intervalMs;confirmFrames;mode;readingIntervalMs;probeIntervalMs;pending=!1;repeatsLeft=0;lastStartedAt=-1/0;pointerInside=!1;lastPointerAt=-1/0;tooltipShowing=!1;lastTooltipAt=-1/0;lastHoverTriggerAt=-1/0;lastVideoTimeSec=null;discontinuitySinceLast=!1;lastTriggerKind=null;lookRequested=!1;unanswered=0;retryAt=null;retryPrompt=!1;lastUnansweredCapture=!1;refused=!1;pointerAnalysis=!1;checkProbe(t){if(t==="layout"&&!(this.probeIntervalMs!==null&&this.probeIntervalMs>0))throw new Error("layout mode needs a positive probe interval")}setProbeIntervalMs(t){this.probeIntervalMs=t,this.checkProbe(this.mode)}setPointerAnalysis(t){this.pointerAnalysis=t}setIntervalMs(t){this.intervalMs=t}setReadingIntervalMs(t){this.readingIntervalMs=t}setTooltipShowing(t,n){this.tooltipShowing=t,t&&this.pointerInside&&(this.lastTooltipAt=n)}setMode(t){this.checkProbe(t),this.mode=t}get analysisMode(){return this.mode}framePresented(){this.pending=!0,this.repeatsLeft=0}discontinuity(){this.discontinuitySinceLast=!0,this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}requestLook(){this.discontinuitySinceLast=!0,this.pending=!0,this.repeatsLeft=0,this.lookRequested=!0}lookUnanswered(t,n={}){this.repeatsLeft=0,this.retryAt=t+PT[Math.min(this.unanswered,PT.length-1)],this.retryPrompt=n.prompt===!0,this.lastUnansweredCapture=n.prompt===!0,this.unanswered+=1}lookAnswered(){this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}lookRefused(){this.refused=!0}pictureReceived(){this.refused=!1,this.lastUnansweredCapture&&(this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1)}retryReady(t){return this.retryAt!==null&&t>=this.retryAt}get lookPending(){return this.lookRequested}pointerMoved(t){this.pointerInside=!0,this.lastPointerAt=t,(this.unanswered>0||this.refused)&&this.retryAt===null&&(this.retryAt=t,this.retryPrompt=!1)}pointerLeft(t){this.pointerInside&&(this.lastPointerAt=t),this.pointerInside=!1,this.lastTooltipAt=-1/0}tapped(t){this.lastPointerAt=t}pointerActive(t){return t-this.lastPointerAt=this.intervalInEffectMs(t):this.analysisState(t)==="probe"?!1:this.repeatsLeft>0&&n>=fC}staleFrameMs(t){return Math.max(gC,this.intervalInEffectMs(t))}frameStale(t,n){return this.lastVideoTimeSec===null||this.discontinuitySinceLast?!0:Math.abs(t-this.lastVideoTimeSec)*1e3>this.staleFrameMs(n)}hoverTriggerDue(t,n,i){let u=this.analysisState(t);return i||u==="idle"||u==="probe"||t-this.lastHoverTriggerAt0&&(this.repeatsLeft-=1)}get lastTrigger(){return this.lastTriggerKind}msSinceLastAnalysis(t){return this.lastStartedAt===-1/0?null:t-this.lastStartedAt}get idle(){return!this.pending&&this.repeatsLeft===0&&this.retryAt===null}};var yC=1e3,wC=2e3,_C=500,vC=1e3;function Zn(e){return e==="wasm"?wC:yC}function zT(e){return e==="wasm"?vC:_C}function As(e,t){return t==="always-on"?Zn(e):zT(e)}var NT=.25,xC=4e3,$C=8e3;function TC(e){return e+nc-Os}var SC=3,BT=5;function Yn(e){if(e===void 0||e===!1)return null;if(e!==!0&&(typeof e!="object"||e===null))throw new RangeError("measuredPacing must be a boolean or an object with a share");let t=e===!0?NT:e.share??NT;if(!(t>0&&t<=1))throw new RangeError("measuredPacing.share must be above 0 and at most 1");return t}function IC(e){let t=e.slice(-BT).sort((i,u)=>i-u),n=t.length>>1;return t.length%2===1?t[n]:(t[n-1]+t[n])/2}function sc(e,t,n,i){return n.lengthBT&&this.times.shift())}intervalMs(t,n){return n==="always-on"?this.slowMs(t):this.activeMs(t)}readingMs(t,n){return sc(Zn(t),TC(n),this.times,this.share)}activeMs(t){return sc(zT(t),xC,this.times,this.share)}slowMs(t){return sc(Zn(t),$C,this.times,this.share)}};var OC=1920,EC=720;function Cs(e,t,n={min:720,max:1920}){let i=Math.max(n.min,Math.min(n.max,e));return{width:i,height:Math.max(1,Math.round(i*t/e))}}function jT(e,t,n){if(!(e.width>0&&e.height>0))return null;let i=(t-e.left)/e.width,u=(n-e.top)/e.height;return i>=0&&i<=1&&u>=0&&u<=1?{x:i,y:u}:null}function Jn(e){return e instanceof HTMLVideoElement?{width:e.videoWidth,height:e.videoHeight}:{width:e.naturalWidth,height:e.naturalHeight}}function AC(e){return e instanceof HTMLVideoElement?e.currentTime:0}async function ac(e,t,n,i){let u=Jn(e),l=Cs(u.width,u.height,i);t.width=l.width,t.height=l.height;let d=performance.now(),c=AC(e);return n.drawImage(e,0,0,t.width,t.height),{bitmap:await createImageBitmap(t),videoTimeSec:c,tapMs:performance.now()-d}}var FT=128,LT=.06,kC=.5,UT=60,Ps=class{ref=null;seeded=!1;seed(t){this.ref=t,this.seeded=!0}reset(){this.ref=null,this.seeded=!1}get hasReference(){return this.ref!==null}observe(t,n){let i=this.ref;if(i===null||i.width!==t.width||i.height!==t.height)return this.ref=t,this.seeded=!1,{distance:null,cut:!1};let u=RC(i,t,n);return u===null?{distance:u,cut:!1}:u>LT?{distance:u,cut:!0}:((this.seeded||u<=LT*kC)&&(this.ref=t),this.seeded=!1,{distance:u,cut:!1})}};function PC(e,t){return{width:FT,height:Math.max(1,Math.round(FT*t/Math.max(1,e)))}}function CC(e,t,n){let i=new Uint8Array(t*n);for(let u=0,l=0;u>8;return i}function RC(e,t,n){if(e.width!==t.width||e.height!==t.height||!(n.width>0)||!(n.height>0))return null;let{width:i,height:u}=e,l=ks(Math.floor(n.x*i),0,i-1),d=ks(Math.ceil((n.x+n.width)*i),l+1,i),c=ks(Math.floor(n.y*u),0,u-1),s=ks(Math.ceil((n.y+n.height)*u),c+1,u),r=0;for(let o=c;o{s=!1});function o(p){return d.find(h=>h.ticket===p)}function a(p){p.fence&&t.deleteSync(p.fence),p.fence=null,p.ticket=null}return{get usable(){return s&&!t.isContextLost()},sample(p){let h=Zn(p);if(!this.usable||h.width===0||h.height===0)return null;let m=d.find(y=>y.ticket===null);if(!m){if(d.length>=mC)return null;let y=t.createBuffer();if(!y)return null;m={pbo:y,fence:null,width:0,height:0,ticket:null},d.push(m)}let{width:g,height:_}=pC(h.width,h.height);try{(e.width!==g||e.height!==_)&&(e.width=g,e.height=_),t.viewport(0,0,g,_),t.bindTexture(t.TEXTURE_2D,l),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,p),t.generateMipmap(t.TEXTURE_2D),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindBuffer(t.PIXEL_PACK_BUFFER,m.pbo),(m.width!==g||m.height!==_)&&(t.bufferData(t.PIXEL_PACK_BUFFER,g*_*4,t.STREAM_READ),m.width=g,m.height=_),t.readPixels(0,0,g,_,t.RGBA,t.UNSIGNED_BYTE,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),m.fence=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0),t.flush()}catch{return s=!1,null}if(!m.fence)return null;let w={id:c++};return m.ticket=w,w},read(p){let h=o(p);if(!h||!h.fence||!this.usable||t.getSyncParameter(h.fence,t.SYNC_STATUS)!==t.SIGNALED)return null;let m=h.width*h.height*4;r.length!==m&&(r=new Uint8Array(m)),t.bindBuffer(t.PIXEL_PACK_BUFFER,h.pbo),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,r),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);let g={width:h.width,height:h.height,luma:hC(r,h.width,h.height)};return a(h),g},release(p){if(!p)return;let h=o(p);h&&a(h)},dispose(){if(s=!1,!t.isContextLost()){for(let p of d)a(p),t.deleteBuffer(p.pbo);d.length=0,t.getExtension("WEBGL_lose_context")?.loseContext()}}}}function tc(e,t,n){let i={left:e.left,top:e.top,width:e.width,height:e.height};if(t.width<=0||t.height<=0||n==="fill")return i;let u=e.width/t.width,l=e.height/t.height,d;n==="cover"?d=Math.max(u,l):n==="none"?d=1:n==="scale-down"?d=Math.min(1,u,l):d=Math.min(u,l);let c=t.width*d,s=t.height*d;return{left:e.left+(e.width-c)/2,top:e.top+(e.height-s)/2,width:c,height:s}}var wC=250,CT=250,_C=1e4,vC=5e3,xC=400,rc=2e3;function RT(e,t,n){return Math.abs(t-e)*1e3<=n}var $C=250,DT=5e3,MT=15e3,PT=[250,500,1e3,2e3];function nc(e,t){return e===void 0?"stale-request":e.requestId<=t.lastAcceptedRequestId?"superseded":e.requestId!==t.inFlightRequestId?"stale-request":e.videoKey!==t.videoKey?"video-key":e.generation!==t.generation?"generation":null}function NT(e){return e==="video-key"||e==="generation"}var eo=class{constructor(t,n=3,i="always-on",u=t,l=null){this.intervalMs=t;this.confirmFrames=n;this.mode=i;this.readingIntervalMs=u;this.probeIntervalMs=l;this.checkProbe(i)}intervalMs;confirmFrames;mode;readingIntervalMs;probeIntervalMs;pending=!1;repeatsLeft=0;lastStartedAt=-1/0;pointerInside=!1;lastPointerAt=-1/0;tooltipShowing=!1;lastTooltipAt=-1/0;lastHoverTriggerAt=-1/0;lastVideoTimeSec=null;discontinuitySinceLast=!1;lastTriggerKind=null;lookRequested=!1;unanswered=0;retryAt=null;retryPrompt=!1;lastUnansweredCapture=!1;refused=!1;pointerAnalysis=!1;checkProbe(t){if(t==="layout"&&!(this.probeIntervalMs!==null&&this.probeIntervalMs>0))throw new Error("layout mode needs a positive probe interval")}setProbeIntervalMs(t){this.probeIntervalMs=t,this.checkProbe(this.mode)}setPointerAnalysis(t){this.pointerAnalysis=t}setIntervalMs(t){this.intervalMs=t}setReadingIntervalMs(t){this.readingIntervalMs=t}setTooltipShowing(t,n){this.tooltipShowing=t,t&&this.pointerInside&&(this.lastTooltipAt=n)}setMode(t){this.checkProbe(t),this.mode=t}get analysisMode(){return this.mode}framePresented(){this.pending=!0,this.repeatsLeft=0}discontinuity(){this.discontinuitySinceLast=!0,this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}requestLook(){this.discontinuitySinceLast=!0,this.pending=!0,this.repeatsLeft=0,this.lookRequested=!0}lookUnanswered(t,n={}){this.repeatsLeft=0,this.retryAt=t+PT[Math.min(this.unanswered,PT.length-1)],this.retryPrompt=n.prompt===!0,this.lastUnansweredCapture=n.prompt===!0,this.unanswered+=1}lookAnswered(){this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}lookRefused(){this.refused=!0}pictureReceived(){this.refused=!1,this.lastUnansweredCapture&&(this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1)}retryReady(t){return this.retryAt!==null&&t>=this.retryAt}get lookPending(){return this.lookRequested}pointerMoved(t){this.pointerInside=!0,this.lastPointerAt=t,(this.unanswered>0||this.refused)&&this.retryAt===null&&(this.retryAt=t,this.retryPrompt=!1)}pointerLeft(t){this.pointerInside&&(this.lastPointerAt=t),this.pointerInside=!1,this.lastTooltipAt=-1/0}tapped(t){this.lastPointerAt=t}pointerActive(t){return t-this.lastPointerAt<_C}analysisState(t){if(this.mode==="always-on")return"always-on";if(this.mode==="layout"){let n=this.pointerAnalysis?this.pointerState(t):"idle";return n==="idle"?"probe":n}return this.pointerState(t)}pointerState(t){return this.pointerActive(t)?"fast":this.pointerInside&&(this.tooltipShowing||t-this.lastTooltipAt=this.intervalInEffectMs(t):this.analysisState(t)==="probe"?!1:this.repeatsLeft>0&&n>=wC}staleFrameMs(t){return Math.max(xC,this.intervalInEffectMs(t))}frameStale(t,n){return this.lastVideoTimeSec===null||this.discontinuitySinceLast?!0:Math.abs(t-this.lastVideoTimeSec)*1e3>this.staleFrameMs(n)}hoverTriggerDue(t,n,i){let u=this.analysisState(t);return i||u==="idle"||u==="probe"||t-this.lastHoverTriggerAt<$C?!1:this.frameStale(n,t)}started(t,n={}){this.retryReady(t)&&(this.retryAt=null,this.retryPrompt=!1,this.pending=!0,this.repeatsLeft=0),this.lastStartedAt=t;let i=n.trigger==="hover",u=n.trigger==="cut"||this.lookRequested;this.lastTriggerKind=i?"hover":u?"cut":this.pending?"cadence":"repeat",i&&(this.lastHoverTriggerAt=t),n.videoTimeSec!==void 0&&(this.lastVideoTimeSec=n.videoTimeSec),this.discontinuitySinceLast=!1,this.lookRequested=!1,this.pending||i||u?(this.pending=!1,this.repeatsLeft=this.analysisState(t)==="probe"?0:this.confirmFrames-1):this.repeatsLeft>0&&(this.repeatsLeft-=1)}get lastTrigger(){return this.lastTriggerKind}msSinceLastAnalysis(t){return this.lastStartedAt===-1/0?null:t-this.lastStartedAt}get idle(){return!this.pending&&this.repeatsLeft===0&&this.retryAt===null}};var ks="no picture",SC="no picture (the paused video draws nothing)",ic="no 2d context",IC="the video may not be read",OC="the picture is too large",EC=16,AC=9,zT=()=>document.createElement("canvas"),kC=e=>createImageBitmap(e);function oc(){return{canvas:null,readable:!1}}function BT(e){return e.paused&&e.readyState<2&&e.videoWidth>0}function sc(e,t){let n=t?.lastPlayingTime??null;return BT(e)&&n!==null?n:e.currentTime}function PC(e,t=zT){let n=EC,i=t();i.width=n,i.height=n;let u=i.getContext("2d");if(!u)return!1;u.drawImage(e,0,0,n,n);let l=u.getImageData(0,0,n,n).data,d=0,c=0;for(let r=0;r({kind:"failed",reason:h,retry:m}),u=e?.video;if(!e||!u||(n.requireConnected??!0)&&!u.isConnected||u.videoWidth===0)return i(ks,!0);let l=BT(u);if(u.readyState<2&&!l)return i(ks,!0);let d=n.createCanvas??zT,c=As(u.videoWidth,u.videoHeight,t),s=n.maxSide??4096;if(c.width>s||c.height>s)return i(OC);let r=e.source;r.canvas||(r.canvas=d(),r.readable=!1);let o=r.canvas;o.width=c.width,o.height=c.height;let a=o.getContext("2d");if(!a)return i(ic);let p=sc(u,e);try{return a.drawImage(u,0,0,c.width,c.height),l&&PC(o,d)?(r.readable=!0,i(SC,!0)):(r.readable||(a.getImageData(0,0,1,1),r.readable=!0),{kind:"frame",bitmap:await(n.createImageBitmap??kC)(o),mediaTime:p})}catch(h){return i(CC(h)?IC:String(h))}}function LT(e,t){let n=null,i=oc(),u={video:e,get lastPlayingTime(){return n},get source(){return i},mediaTime:()=>sc(e,u),detach:a},l=()=>t.discontinuity(!1),d=()=>{i=oc(),n=null,t.discontinuity(!0)},c=()=>{!e.paused&&e.readyState>=2&&(n=e.currentTime),t.presented(u.mediaTime())},s=()=>t.presented(u.mediaTime()),r=[["seeking",l],["emptied",d],["loadeddata",d],["timeupdate",c],["seeked",c],["canplay",s],["playing",s]];for(let[p,h]of r)e.addEventListener(p,h);let o=!0;function a(){if(o){o=!1;for(let[p,h]of r)e.removeEventListener(p,h)}}return u}var EM=1440*60*1e3;var RC=[/^the worker did not start/,/^unexpected error while loading/];function jT(e,t){return t||e.startsWith("unexpected:")?!1:!RC.some(n=>n.test(e))}var NM=Object.freeze({misses:2,maxMs:5e3,sameBoxIou:.5});function DC(e,t){return e==="loading"?{phase:t.phase,bytes:t.bytes}:void 0}function MC(e){if(!e||!Number.isFinite(e.rotation)||e.rotation===0)return{};let{rotation:t,localWidth:n,localHeight:i}=e;return t>-45&&t<=45&&n>0&&n<=1&&i>0&&i<=1?{rotation:t,localWidth:n,localHeight:i}:{}}function NC(e,t,n=40){return(e.hover?.cards??[]).map(i=>i.bounds).filter(i=>i&&!(Math.abs(i.x-t.x)<1e-6&&Math.abs(i.y-t.y)<1e-6&&Math.abs(i.width-t.width)<1e-6)).slice(0,n).map(i=>({x:i.x,y:i.y,width:i.width,height:i.height}))}var Ps=class{constructor(t,n={}){this.deps=t;this.mode=n.mode??"pointer",this.hold=n.hold??null,this.maxOtherBoxes=n.maxOtherBoxes??40,this.rotatedOutlines=n.rotatedOutlines===!0,this.hitTest=t.hoverAt??vs,this.scheduler=new eo(Is(null,this.mode),3,this.mode,Ss(null)),this.st={state:"loading",error:null,release:null,backend:null,schedule:"idle",frames:0,lastWorkerMs:null,lastRoundTripMs:null,lastFrameError:null,geometric:n.geometric?{state:"loading",reason:null,bytes:null}:null,loading:null,tilted:null},this.lastStatusKey=this.statusKey()}deps;scheduler;mode;hold;maxOtherBoxes;rotatedOutlines;hitTest;st;cardList=[];analysisWidth={min:720,max:1920};maxAgeMs=rc;nextRequestId=1;inFlight=null;lastAcceptedRequestId=0;analyzedSinceLoad=!1;generation=0;sourceCount=0;result=null;pointerAt=null;mediaTime=0;lastShownKey="null";lastStatusKey="";held=null;get videoKey(){return`source-${this.sourceCount}`}pointer(t,n,i,u=!1){if(this.st.state==="stopped")return;let l=this.deps.now();this.pointerAt={x:t,y:n},this.mediaTime=i,u?this.scheduler.tapped(l):this.scheduler.pointerMoved(l),this.st.state==="ready"&&this.scheduler.hoverTriggerDue(l,this.videoTime(),this.inFlight!==null)&&this.requestCapture("hover"),this.publish()}pointerLeft(){this.st.state!=="stopped"&&(this.pointerAt=null,this.scheduler.pointerLeft(this.deps.now()),this.publish())}presented(t){this.st.state!=="stopped"&&(this.mediaTime=t,this.scheduler.framePresented(),this.publish())}discontinuity(t){this.st.state!=="stopped"&&(this.generation+=1,t&&(this.sourceCount+=1),this.scheduler.discontinuity(),this.result=null,this.held=null,t&&this.scheduler.framePresented(),this.publish())}cut(){this.st.state!=="stopped"&&(this.generation+=1,this.result=null,this.held=null,this.scheduler.requestLook(),this.publish())}frame(t,n,i){let u=this.inFlight;if(this.st.state==="stopped"||!u||u.requestId!==t||u.analyzing){n.close();return}if(this.scheduler.pictureReceived(),u.generation!==this.generation||u.videoKey!==this.videoKey){this.inFlight=null,n.close(),this.publish();return}u.analyzing=!0;let l={requestId:u.requestId,mediaTimeSec:i,generation:u.generation,videoKey:u.videoKey};try{this.deps.toWorker({kind:"frame",bitmap:n,videoTimeSec:i,envelope:l,...this.rotatedOutlines?{rotatedOutlines:!0}:{}},[n])}catch(d){n.close(),this.inFlight=null,this.st.lastFrameError=`analysis-failed: ${String(d)}`,this.scheduler.lookUnanswered(this.deps.now())}this.publish()}captureFailed(t,n,i=!1){let u=this.inFlight;this.st.state==="stopped"||!u||u.requestId!==t||u.analyzing||(this.inFlight=null,this.st.lastFrameError=`capture-failed: ${n}`,i?this.scheduler.lookUnanswered(this.deps.now(),{prompt:!0}):this.scheduler.lookRefused(),this.publish())}fromWorker(t){if(this.st.state!=="stopped")switch(t.kind){case"geometric-status":this.st.geometric={state:t.state,reason:t.reason,bytes:t.bytes},this.deps.onGeometricStatus?.(t),this.publishStatus();return;case"tilted-status":this.st.tilted={state:"off",reason:t.reason},this.deps.onTiltedStatus?.(t),this.publishStatus();return;case"release-progress":{let n=DC(this.st.state,t);n!==void 0&&(this.st.loading=n),this.publishStatus();return}case"release-status":this.st.state=t.ok?"ready":"failed",this.analyzedSinceLoad=!1,this.st.error=t.error,this.st.release=t.release,this.st.loading=null,this.st.tilted=t.release?.tiltedRetry?{state:"on",reason:null}:null,this.cardList=t.cards,t.release&&(this.st.backend=t.release.recognizer.ep,this.maxAgeMs=t.release.hoverMaxAgeMs,this.analysisWidth={...t.release.analysisWidth},this.scheduler.setIntervalMs(Is(this.st.backend,this.mode)),this.scheduler.setReadingIntervalMs(Ss(this.st.backend)),this.scheduler.framePresented()),this.publish();return;case"frame-result":this.onFrameResult(t);return;default:return}}onFrameResult(t){let n=this.deps.now(),i=nc(t.envelope,{inFlightRequestId:this.inFlight?.requestId??null,lastAcceptedRequestId:this.lastAcceptedRequestId,generation:this.generation,videoKey:this.videoKey});if(i!==null&&!NT(i))return;let u=this.inFlight;if(this.inFlight=null,i!==null){this.publish();return}this.lastAcceptedRequestId=t.envelope.requestId,this.st.lastFrameError=t.error??null,this.st.lastWorkerMs=t.workerMs,this.st.lastRoundTripMs=+(n-u.sentAt).toFixed(2),t.analysis?(this.analyzedSinceLoad=!0,this.scheduler.lookAnswered(),this.st.frames+=1,this.result={analysis:t.analysis,videoTimeSec:t.videoTimeSec},this.deps.onAnalysis?.(t.analysis)):(this.result=null,t.error===V$&&this.scheduler.lookUnanswered(n)),this.held&&this.pointerAt&&this.current()&&!this.fresh()&&(this.held.misses+=1),this.scheduler.setTooltipShowing(this.shown()!==null,n),this.publish()}tick(){if(this.st.state==="stopped")return;let t=this.deps.now(),n=this.analyzedSinceLoad?DT:MT;this.inFlight&&t-this.inFlight.sentAt>=n&&(this.inFlight=null,this.st.lastFrameError="no reply",this.scheduler.lookUnanswered(t)),this.scheduler.setTooltipShowing(this.shown()!==null,t),this.st.state==="ready"&&!this.inFlight&&this.scheduler.due(t)&&this.requestCapture(this.scheduler.lookPending?"cut":void 0),this.publish()}stop(){this.st.state!=="stopped"&&(this.st.state="stopped",this.st.loading=null,this.inFlight=null,this.result=null,this.held=null,this.pointerAt=null,this.publishShown(),this.publishStatus())}workerStopped(t){if(!(this.st.state==="stopped"||this.st.state==="failed")){if(this.inFlight=null,this.result=null,this.held=null,this.st.loading=null,this.publishShown(),"restart"in t){let n={kind:"geometric-status",state:"off",reason:"worker-restarted",bytes:null};this.st.geometric&&(this.st.geometric={state:n.state,reason:n.reason,bytes:n.bytes}),this.deps.onGeometricStatus?.(n),this.st.state="loading",this.analyzedSinceLoad=!1,this.st.error=null}else this.st.state="failed",this.st.error=t.error;this.publishStatus()}}reloading(t){this.st.state==="loading"&&(this.st.geometric=t.geometric?{state:"loading",reason:null,bytes:null}:null,this.st.loading=null,this.publishStatus())}requestCapture(t){if(this.st.state!=="ready"||this.inFlight)return;let n=this.deps.now(),i=this.nextRequestId++;this.inFlight={requestId:i,sentAt:n,generation:this.generation,videoKey:this.videoKey,analyzing:!1},this.scheduler.started(n,{videoTimeSec:this.videoTime(),...t?{trigger:t}:{}}),this.deps.capture(i,{...this.analysisWidth})}status(){return{...this.st,schedule:this.scheduler.analysisState(this.deps.now())}}analysis(){return this.current()?.analysis??null}cards(){return this.cardList}hitAt(t,n){let i=this.current();if(!i)return null;let{width:u,height:l}=i.analysis.frame;if(!(u>0&&l>0))return null;let d=t*u,c=n*l;if(!Number.isFinite(d)||!Number.isFinite(c))return null;let s=this.hitTest(i.analysis,d,c);if(!s.box||s.cardId===null||s.name===null)return null;let r={x:s.box.x/u,y:s.box.y/l,width:s.box.width/u,height:s.box.height/l},o={x:s.box.x,y:s.box.y,width:s.box.width,height:s.box.height};return{cardId:s.cardId,name:s.name,box:r,frameBox:o,others:NC(i.analysis,r,this.maxOtherBoxes),...MC(s.card)}}fresh(){return this.pointerAt?this.hitAt(this.pointerAt.x,this.pointerAt.y):null}shown(){let t=this.fresh(),n=this.hold;if(!n)return t;let i=this.deps.now();if(t)return this.held={card:t,misses:0,seenAt:i},t;let u=this.held;return!u||!this.pointerAt||!BC(u.card.box,this.pointerAt)?(this.held=null,null):this.boxAtPointer(u.card.box,n.sameBoxIou)==="other"||u.misses>=n.misses||i-u.seenAt>=n.maxMs?(this.held=null,null):u.card}current(){let t=this.result;return t&&RT(t.videoTimeSec,this.videoTime(),this.maxAgeMs)?t:null}videoTime(){return this.deps.mediaTimeNow?this.deps.mediaTimeNow():this.mediaTime}boxAtPointer(t,n){let i=this.current();if(!i||!this.pointerAt)return"unknown";let{width:u,height:l}=i.analysis.frame;if(!(u>0&&l>0))return"unknown";let d=this.pointerAt.x*u,c=this.pointerAt.y*l,s={x:t.x*u,y:t.y*l,width:t.width*u,height:t.height*l},r=0,o=!1;for(let a of i.analysis.boxes??[]){let[p,h,m,g]=a.box;dp+m||ch+g||(o=!0,r=Math.max(r,zC(s,{x:p,y:h,width:m,height:g})))}return o?r>=n?"same":"other":"none"}publish(){this.publishShown(),this.publishStatus()}publishShown(){let t=this.shown(),n=t?`${t.cardId}|${t.box.x}|${t.box.y}|${t.box.width}|${t.box.height}|${t.rotation??""}|${t.localWidth??""}|${t.localHeight??""}`:"null";n!==this.lastShownKey&&(this.lastShownKey=n,this.deps.onShown?.(t))}statusKey(){let t=this.status();return JSON.stringify({...t,release:t.release?t.release.id:null})}publishStatus(){let t=this.statusKey();t!==this.lastStatusKey&&(this.lastStatusKey=t,this.deps.onStatus?.(this.status()))}};function zC(e,t){let n=Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x),i=Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y);if(n<=0||i<=0)return 0;let u=n*i;return u/(e.width*e.height+t.width*t.height-u)}function BC(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}var VT=1;function FC(e){let{geometricUrl:t,geometricManifestSha256:n,geometricWatchdog:i,...u}=e;return u}function qT(e){let t=null,n=null,i=0,u=!1,l=null,d=!1,c=null,s={source:e.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},r=y=>{e.onDecision?.({reused:0,downloaded:0,ms:0,...y})},o=y=>new Ps({now:e.now,toWorker:(T,S)=>t?.postMessage(T,S??[]),capture:e.capture,...e.onShown?{onShown:e.onShown}:{},...e.onStatus?{onStatus:e.onStatus}:{},...e.onAnalysis?{onAnalysis:e.onAnalysis}:{},...e.onGeometricStatus?{onGeometricStatus:e.onGeometricStatus}:{},...e.hoverAt?{hoverAt:e.hoverAt}:{},...e.mediaTimeNow?{mediaTimeNow:e.mediaTimeNow}:{}},{...e.mode?{mode:e.mode}:{},...e.hold?{hold:e.hold}:{},...e.rotatedOutlines?{rotatedOutlines:!0}:{},geometric:y.geometricUrl!==void 0}),a=y=>{u||!n||(l&&y.kind==="release-progress"&&y.phase==="preparing"&&(d=!0),!(y.kind==="release-status"&&(n.status().state!=="loading"||l&&!h(y)))&&(y.kind==="release-status"&&!y.ok&&p(),n.fromWorker(y)))},p=()=>{u=!0,l=null,t?.terminate(),t=null},h=y=>{let T=l;if(y.ok&&y.release?.id===T.pointer.id)return l=null,c=T.pointer.id,s.source="remote",s.id=T.pointer.id,s.reason="ok",s.table=T.facts,r({source:"remote",reason:"ok",pointer:T.pointer.id,reused:T.reused,downloaded:T.downloaded,ms:T.ms}),!0;if(y.ok)return e.recordSkip?.(T.pointer,"id-mismatch"),m("id-mismatch"),!1;let S=y.error??"no reason given";return jT(S,d)&&e.recordSkip?.(T.pointer,`runtime:${S.slice(0,120)}`),m(`runtime:${S}`),!1},m=y=>{let T=l;l=null,t?.terminate(),s.source="bundled",s.id=null,s.reason=y,s.table=null,r({source:"bundled",reason:y,pointer:T.pointer.id,reused:T.reused,downloaded:T.downloaded,ms:T.ms});let S=T.fallback??e.loadRequest;n?.reloading({geometric:S.geometricUrl!==void 0}),w(S)},g=y=>{if(u||!n)return;let T=n.status().state;if(T==="failed"||T==="stopped")return;let S=y.message||"see the console";if(l){h({kind:"release-status",ok:!1,error:`the worker did not start (${S})`,release:null,cards:[]});return}if(t?.terminate(),T==="loading"&&i===0){p(),n.workerStopped({error:`the worker did not start (${S})`});return}if(i{let T=e.createWorker();T.onmessage=S=>{T===t&&a(S.data)},T.onerror=S=>{T===t&&g(S)},t=T,T.postMessage(y)},w=y=>{n??=o(y);try{_(y)}catch(T){t=null,l=null,u=!0,n.workerStopped({error:`the recognition worker could not start (${String(T)})`})}};return e.chooseRelease?e.chooseRelease({onDownloading:()=>e.onDownloading?.()}).catch(y=>({source:"bundled",reason:`unexpected:${String(y)}`,pointer:null,downloaded:0,ms:0})).then(y=>{if(!u){if(y.source==="remote"){l=y,d=!1,w(y.request);return}s.source="bundled",s.reason=y.reason,r({source:"bundled",reason:y.reason,pointer:y.pointer?.id??null,downloaded:y.downloaded,ms:y.ms}),w(y.request??e.loadRequest)}}):w(e.loadRequest),{get core(){return n},get stopped(){return u},get restarts(){return i},get release(){return{...s}},tick(){u||n?.tick()},stop(){u=!0,l=null,t?.terminate(),t=null,n?.stop()}}}var LC={requireConnected:!1,maxSide:1/0};function jC(e,t){let n=e instanceof HTMLVideoElement?e:null,i=e,u=t.workerUrl??new URL("./worker.js",import.meta.url),l=()=>performance.now(),d=!1,c=0,s=!1,r=()=>{c>0?s=!0:d&&t.onUpdate?.()},o=(N,X=!1)=>{c+=1;try{N()}finally{c-=1}X&&(s=!0),c===0&&s&&(s=!1,d&&t.onUpdate?.())},a=null,p=new Es,h=null,m=null,g=-1/0,_=()=>{let N=h&&a?a.read(h):null;N?p.seed(N):(a?.release(h),p.reset()),h=null},w=n?null:document.createElement("canvas"),y=w?.getContext("2d")??null,T=async N=>{if(!w||!y)return{kind:"failed",reason:ic,retry:!1};let X=Zn(e);if(X.width===0||X.height===0)return{kind:"failed",reason:ks,retry:!0};try{let W=await ec(e,w,y,N);return{kind:"frame",bitmap:W.bitmap,mediaTime:W.videoTimeSec}}catch(W){return{kind:"failed",reason:String(W),retry:!1}}},S=(N,X)=>{a?.release(h),h=a?.usable?a.sample(e):null,(z?FT(z,X,LC):T(X)).then(W=>o(()=>{W.kind==="frame"?q.frame(N,W.bitmap,W.mediaTime):q.captureFailed(N,W.reason,W.retry)},W.kind==="failed"))},O=0,A=null,P=()=>{O+=1;let N;try{N=new Worker(u,{type:"module"})}catch(W){throw O===1&&(A={error:W}),W}let X={postMessage:(W,re)=>N.postMessage(W,re??[]),terminate:()=>N.terminate(),onmessage:null,onerror:null};return N.onmessage=W=>o(()=>X.onmessage?.(W)),N.onerror=W=>o(()=>X.onerror?.(W)),X},I={kind:"load",releaseUrl:t.releaseFiles?String(t.releaseUrl):new URL(t.releaseUrl,location.href).href,...t.releaseFiles?{files:t.releaseFiles}:{},...t.wasmPaths!==void 0?{wasmPaths:t.wasmPaths}:{},...t.providers?{providers:t.providers}:{},...t.geometricUrl!==void 0?{geometricUrl:new URL(t.geometricUrl,location.href).href}:{},...t.geometricManifestSha256!==void 0?{geometricManifestSha256:t.geometricManifestSha256}:{},...t.geometricWatchdog===!1?{geometricWatchdog:!1}:{}},z=n?LT(n,{presented:N=>o(()=>q.presented(N)),discontinuity:N=>o(()=>{p.reset(),q.discontinuity(N)},!0)}):null,G=()=>z?.mediaTime()??0,J=qT({createWorker:P,loadRequest:I,now:l,...t.mode?{mode:t.mode}:{},...t.rotatedOutlines?{rotatedOutlines:!0}:{},capture:S,mediaTimeNow:()=>G(),onShown:r,onStatus:r,onAnalysis:_});if(A)throw z?.detach(),J.stop(),A.error;let q=J.core,C=(N,X)=>{let W=tc(e.getBoundingClientRect(),Zn(e),getComputedStyle(e).objectFit);if(W.width<=0||W.height<=0)return null;let re=q.hitAt((N-W.left)/W.width,(X-W.top)/W.height);return re?{hit:re,picture:W}:null},ee=(N,X)=>{let W=C(N,X);if(!W)return null;let{hit:re,picture:le}=W;return{name:re.name,cardId:re.cardId,box:{left:le.left+re.box.x*le.width,top:le.top+re.box.y*le.height,width:re.box.width*le.width,height:re.box.height*le.height},frameBox:re.frameBox,...re.rotation!==void 0&&re.localWidth!==void 0&&re.localHeight!==void 0?{rotation:re.rotation,localWidth:re.localWidth,localHeight:re.localHeight}:{}}},v=null,R=()=>v?ee(v.x,v.y):null,H=N=>{let X=v?C(v.x,v.y)?.hit.box??null:null;if(!X){a?.release(m),m=null;return}if(a||(a=kT()),!!a?.usable){if(m){let W=a.read(m);if(W&&(m=null,p.observe(W,X).cut)){p.reset(),q.cut(),s=!0;return}}!m&&N-g>=AT&&(g=N,m=a.sample(e))}},L=null,V=()=>{!d||!n||(o(()=>{q.presented(G()),H(l())}),L=n.requestVideoFrameCallback(V))},K=()=>o(()=>{p.reset(),q.discontinuity(!0)},!0),B=N=>o(()=>{v={x:N.clientX,y:N.clientY};let X=tc(e.getBoundingClientRect(),Zn(e),getComputedStyle(e).objectFit),W=ET(X,N.clientX,N.clientY)??{x:(N.clientX-X.left)/X.width,y:(N.clientY-X.top)/X.height};q.pointer(W.x,W.y,G(),N.pointerType==="touch")},!0),te=()=>o(()=>{v=null,q.pointerLeft()},!0);n&&"requestVideoFrameCallback"in n&&(L=n.requestVideoFrameCallback(V)),n||e.addEventListener("load",K),i.addEventListener("pointermove",B),i.addEventListener("pointerdown",B),i.addEventListener("pointerleave",te);let Y=setInterval(()=>o(()=>J.tick()),CT);return d=!0,{status:()=>q.status(),at:ee,atPointer:R,analysis:()=>q.analysis(),cards:()=>q.cards(),stop:()=>{d&&(d=!1,clearInterval(Y),L!==null&&n&&"cancelVideoFrameCallback"in n&&n.cancelVideoFrameCallback(L),L=null,z?.detach(),e.removeEventListener("load",K),i.removeEventListener("pointermove",B),i.removeEventListener("pointerdown",B),i.removeEventListener("pointerleave",te),a?.release(h),a?.release(m),a?.dispose(),p.reset(),J.stop())}}}var Mr={maxCorrespondences:40,fitMinInliers:3,inlierShare:[2,3],ambiguityMin:2,compatTol:.01,scaleRatioTol:.03},ac=1e-9,Cs=5;function cr(e,t){let n=Math.max(0,Math.min(e.x+e.w,t.x+t.w)-Math.max(e.x,t.x)),i=Math.max(0,Math.min(e.y+e.h,t.y+t.h)-Math.max(e.y,t.y)),u=n*i,l=e.w*e.h+t.w*t.h-u;return l>0?u/l:0}function Sn(e,t){return{x:e.sx*t.x+e.tx,y:e.sy*t.y+e.ty,w:e.sx*t.w,h:e.sy*t.h}}function to(e,t){return{x:e.sx*t.x+e.tx,y:e.sy*t.y+e.ty}}function uc(e){return{x:e.tx,y:e.ty,width:e.sx,height:e.sy}}function Rs(e){if(e.cards.length===0)return null;let t=1/0,n=1/0,i=-1/0,u=-1/0;for(let{bounds:l}of e.cards)t=Math.min(t,l.x),n=Math.min(n,l.y),i=Math.max(i,l.x+l.w),u=Math.max(u,l.y+l.h);return{x:t,y:n,w:i-t,h:u-n}}function lc(e){let t=[];for(let n=0;n=e.x&&t.x<=e.x+e.w&&t.y>=e.y&&t.y<=e.y+e.h}function GT(e,t){return et?1:0}function UC(e,t){return t.identity===void 0?!1:e.blocking===void 0||!In(e.blocking,XT(t.bounds))}function Ds(e,t,n=Mr.maxCorrespondences){let i=new Map;for(let d of e)i.set(d.identity,i.has(d.identity)?null:d);let u=new Map;for(let d of t.cards){if(!UC(t,d))continue;let c=d.identity;u.set(c,u.has(c)?null:d)}let l=[];for(let[d,c]of i){let s=u.get(d);!c||!s||l.push({identity:d,v:c.bounds,r:s.bounds,instance:s.instance})}return l.length>n&&(l.sort((d,c)=>c.v.w*c.v.h-d.v.w*d.v.h||GT(d.identity,c.identity)),l=l.slice(0,n)),l.sort((d,c)=>GT(d.identity,c.identity))}function VC(e){if(!(e.r.w>0)||!(e.r.h>0))return null;let t=e.v.w/e.r.w,n=e.v.h/e.r.h,i={sx:t,sy:n,tx:e.v.x-t*e.r.x,ty:e.v.y-n*e.r.y};return![i.sx,i.sy,i.tx,i.ty].every(Number.isFinite)||!(t>0)||!(n>0)?null:i}function HT(e){let t=e.length;if(t===0)return null;let n=0,i=0;for(let[s,r]of e)n+=s,i+=r;n/=t,i/=t;let u=0,l=0;for(let[s,r]of e)u+=(s-n)*(r-i),l+=(s-n)*(s-n);if(!(l>0))return null;let d=u/l;if(!(d>0)||!Number.isFinite(d))return null;let c=i-d*n;return Number.isFinite(c)?{s:d,t:c}:null}function WT(e){let t=[],n=[];for(let{r:l,v:d}of e)t.push([l.x,d.x],[l.x+l.w,d.x+d.w]),n.push([l.y,d.y],[l.y+l.h,d.y+d.h]);let i=HT(t),u=HT(n);return!i||!u?null:{sx:i.s,sy:u.s,tx:i.t,ty:u.t}}function dc(e,t,n){if(e.length===0||!(t>0)||!(n>0))return null;let i=[],u=[];for(let{r:y,v:T}of e)i.push([y.x,T.x],[y.x+y.w,T.x+T.w]),u.push([y.y,T.y],[y.y+y.h,T.y+T.h]);let l=(y,T)=>y.reduce((S,O)=>S+O[T],0)/y.length,d=l(i,0),c=l(i,1),s=l(u,0),r=l(u,1),o=0,a=0,p=0,h=0;for(let[y,T]of i)o+=(y-d)*(y-d),a+=(y-d)*(T-c);for(let[y,T]of u)p+=(y-s)*(y-s),h+=(y-s)*(T-r);let m=n*n,g=m*o+t*t*p;if(!(g>0))return null;let _=(m*a+t*h)/g;if(!(_>0)||!Number.isFinite(_))return null;let w={sx:_,sy:t*_,tx:c-_*d,ty:r-t*_*s};return[w.sy,w.tx,w.ty].every(Number.isFinite)?w:null}function qC(e,t){if(e.aspect===void 0||t===void 0)return null;let n=i=>Number.isFinite(i)&&i>0;return!n(e.aspect)||!n(t)?NaN:t/e.aspect}function GC(e,t,n,i,u=1){return Ms(e,t,n,i,u).outcome}function Ms(e,t,n,i,u=1){if(t===null)return{outcome:{kind:"no-layout"},correspondences:[],support:[],winner:-1,aspectRejected:[]};let l=Ds(e,t,n.maxCorrespondences),d=l.length,c=[],s=(L,V,K=[],B=-1)=>({outcome:{kind:"insufficient",reason:L,n:d,inliers:V},correspondences:l,support:K,winner:B,aspectRejected:c}),r=qC(t,i);if(r!==null&&(Number.isNaN(r)||!(Number.isFinite(u)&&u>0)))return s("degenerate",0);let o=L=>r!==null&&Math.abs(L.sy/L.sx/r-1)>n.scaleRatioTol,a=L=>{let V=[];for(let K=0;K=n.fitMinIoU&&V.push(K);return V},p=l.map(VC),h=p.map((L,V)=>L&&o(L)?(c.push(V),null):L),m=()=>c.some(L=>a(p[L]).length>=2),g=[],_=[];for(let L=0;L=n.fitMinIoU&&(K.push(te),B+=Y)}g.push(K),_.push(B)}let w=-1;for(let L=0;LK||V===K&&_[L]>_[w]+ac)&&(w=L)}if(w<0){let L=d=n.fitMinInliers)return s(m()?"aspect":"zero-inliers",0,g,w);let y=g[w].map(L=>l[L]),T=r===null?WT(y):dc(y,r*u,i);if(!T)return s("degenerate",0,g,w);let S=[],O=1/0;for(let L of g[w]){let V=cr(Sn(T,l[L].r),l[L].v);V>=n.fitMinIoU&&(S.push(L),O=Math.min(O,V))}let A=S.map(L=>l[L].identity),P=Rs(t),I=new Set(S),z=[];for(let L=0;L!I.has(B));K.length>z.length&&(z=K)}if(z.length>=n.ambiguityMin)return{outcome:{kind:"ambiguous",transform:T,inliers:A,runnerUp:z.map(L=>l[L].identity),n:d},correspondences:l,support:g,winner:w,aspectRejected:c};if(A.lengthl[V]));if(!L||o(L))return s("aspect",A.length,g,w);H=L.sy/L.sx/r}return{outcome:{kind:"verified",transform:T,inliers:A,n:d,minIoU:O,span:R,...H!==void 0?{boardRatio:H}:{}},correspondences:l,support:g,winner:w,aspectRejected:c}}var HC=8,WC=20,KC=.3;function XC(e,t,n,i,u){let l=0;for(let d of lc(n)){let c=to(e,d),s=to(t,d);l=Math.max(l,Math.abs(c.x-s.x)*i,Math.abs(c.y-s.y)*u)}return l}function ZC(e,t){return t?e<=HC?"correct":e<=WC?"loose":"false":"none"}function ZT(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}function YC(e,t,n,i=[]){let u=ZT(e.box);if(!In(n,u)||i.some(c=>In(c,u)))return"blocked";let l=null,d=-1;for(let c of t){let s=cr(e.box,c.box);s>=KC&&s>d&&(l=c,d=s)}return l?!l.faceUp||l.identity===void 0?"back-hidden":l.identity===e.identity?"correct":"wrong-identity":"empty"}function JC(e,t,n,i=[]){let u=0,l=0;for(let d of e){if(!d.faceUp||d.identity===void 0)continue;let c=ZT(d.box);!In(n,c)||i.some(s=>In(s,c))||(u+=1,t.some(s=>s.identity===d.identity&&In(s.box,c))&&(l+=1))}return u===0?null:l/u}function QC(e,t){return t.map(n=>eR(e,n))}function eR(e,t){let n=null;for(let i of e){if(i.atMs>t)break;n=i.display}if(n!=="fitted")return 0;for(let i of e)if(i.atMs>=t&&i.display!=="fitted")return i.atMs-t;return null}var Ns={window:10,minIdentities:3,trip:.4,recover:.7},ro=class{params;exclude;window=[];stateValue="unknown";recoverRun=0;constructor(t={}){this.params=t.params??Ns,this.exclude=t.exclude??(()=>!1)}get state(){return this.stateValue}get tripped(){return this.stateValue==="tripped"}get share(){return this.summary().share}observe(t){if(t.windowIdentities.size===0)return{state:this.stateValue,event:null,...this.summary(),counted:!1};let n=new Map;for(let c of t.accepted)this.exclude(c)||n.set(c,(n.get(c)??!1)||t.windowIdentities.has(c));this.window.push(n),this.window.length>this.params.window&&this.window.shift();let{identities:i,share:u}=this.summary(),l=i>=this.params.minIdentities&&u!==null,d=null;return this.stateValue==="tripped"?(this.recoverRun=l&&u>=this.params.recover?this.recoverRun+1:0,this.recoverRun>=this.params.window&&(this.stateValue="in",this.recoverRun=0,d="recover")):l&&(u0&&t.scaleRatioTol<=.25))return"scaleRatioTol must be above 0 and at most 0.25";let n=t;return n.fitMinIoU<.5||n.fitMinIoU>1?"fitMinIoU must be between 0.5 and 1":n.minSpan<0||n.minSpan>1?"minSpan must be between 0 and 1":!Number.isInteger(n.confirmFits)||n.confirmFits<1||n.confirmFits>3?"confirmFits must be 1, 2 or 3":n.suppressionIoU<=0||n.suppressionIoU>1?"suppressionIoU must be above 0 and at most 1":n.intervalMs<=0?"intervalMs must be positive":n.confirmWindowMs<3*n.intervalMs?"confirmWindowMs must be at least 3 \xD7 intervalMs":n.freshnessMs<2*n.intervalMs?"freshnessMs must be at least 2 \xD7 intervalMs":n.holdMs=u){d.add(c.instance);break}}return e.cards.map(c=>c.instance).filter(c=>d.has(c))}var eS=15;function tR(e){let t=[...e].sort((i,u)=>i-u),n=t.length>>1;return t.length%2===1?t[n]:(t[n-1]+t[n])/2}var no=class{config;fitParams;monitor;generationValue=null;stateValue="off";contradicted=!1;verifiedThisGen=!1;run=null;confirmed=null;confirmedBasis=null;ratioPool=[];appliedScale=1;holdStart=null;lastAnalysisAt=null;zeroStreak=0;lastFrame={kind:"no-layout"};suppressed=[];current;constructor(t,n={}){let i=JT(t);if(i)throw new Error(i);this.config=Object.freeze({...t}),this.fitParams={...Mr,fitMinIoU:t.fitMinIoU,minSpan:t.minSpan,ambiguityMin:t.ambiguityMin??Mr.ambiguityMin,scaleRatioTol:t.scaleRatioTol??Mr.scaleRatioTol},this.monitor=new ro({exclude:n.exclude,params:Ns}),this.current=this.build(0,0)}get generation(){return this.generationValue}get state(){return this.stateValue}get verdict(){return this.current}eligibilityLost(t){return this.clear(),this.generationValue=null,this.stateValue="off",this.current=this.build(1,t)}reset(t,n){return this.clear(),this.generationValue=t,this.stateValue="unverified",this.current=this.build(2,n)}tick(t){return this.expired(t)?(this.expire(),this.current=this.build(11,t)):this.current=this.build(0,t)}analyze(t,n){if(this.generationValue===null||t.generation!==this.generationValue)return null;let i=this.expired(n);i&&this.expire();let u=this.stateValue,l=this.ratioScale(),d=Ms(t.observations,t.layout,this.fitParams,t.frameAspect,l),c=d.outcome;this.lastFrame=c;let s=null;c.kind==="verified"&&c.boardRatio!==void 0&&(s={correspondences:d.support[d.winner].map(_=>d.correspondences[_]),ratio:t.frameAspect/t.layout.aspect,frameAspect:t.frameAspect});let r=this.monitor.observe({windowIdentities:t.windowIdentities,accepted:t.observations.map(_=>_.identity)});this.lastAnalysisAt=n,this.zeroStreak=c.kind==="insufficient"&&c.reason==="zero-inliers"?this.zeroStreak+1:0;let o=t.layout?Rs(t.layout):null,a=c.kind==="verified"&&o!==null?c:null,p=this.fitParams.compatTol,h=a!==null&&this.confirmed!==null&&!Yn(a.transform,this.confirmed,o,p),m=this.run;if(a){let _=this.run!==null&&Yn(a.transform,this.run.latest,o,p)&&t.capturedAtMs-this.run.capturedAtMs<=this.config.confirmWindowMs;m={latest:a.transform,capturedAtMs:t.capturedAtMs,length:_?this.run.length+1:1,basis:s}}let g;return r.event==="trip"?(g=3,this.run=m,this.stateValue="mismatch",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0):u==="mismatch"&&r.event==="recover"?(g=4,this.run=m,this.stateValue="unverified"):h?(g=5,this.run={latest:a.transform,capturedAtMs:t.capturedAtMs,length:1,basis:s},this.stateValue="contradicted",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0,this.verifiedThisGen=!0):this.zeroStreak>=2&&(u==="verified"||u==="held")?(g=6,this.stateValue="contradicted",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0,this.verifiedThisGen=!0):t.faces===0&&t.layout!==null&&t.layout.cards.length>=3&&this.verifiedThisGen&&u!=="mismatch"?(g=7,this.run=m,this.stateValue="no-faces"):a&&m.length>=this.config.confirmFits?(g=9,this.run=m,this.stateValue="verified",this.confirmed=a.transform,this.confirmedBasis=s,this.contradicted=!1,this.holdStart=n,this.verifiedThisGen=!0,this.monitor.clearTrip()):(this.run=m,(u==="verified"||u==="held"||u==="no-faces"&&a!==null)&&this.confirmed!==null&&this.holdStart!==null&&n-this.holdStarteS&&this.ratioPool.shift()),this.applyScale(this.ratioScale()),(this.stateValue==="verified"||this.stateValue==="held")&&this.confirmed&&t.layout?this.suppressed=QT(t.layout,t.observations,this.confirmed,this.fitParams.fitMinIoU,this.config.suppressionIoU,this.fitParams.maxCorrespondences):this.suppressed=[],this.current=this.build(g,n)}expired(t){let n=this.stateValue;if(n!=="verified"&&n!=="held"&&n!=="no-faces")return!1;let i=this.holdStart!==null&&t-this.holdStart>=this.config.holdMs,u=this.lastAnalysisAt!==null&&t-this.lastAnalysisAt>=this.config.freshnessMs;return i||u}applyScale(t){if(t===this.appliedScale)return;let n=i=>i?dc(i.correspondences,i.ratio*t,i.frameAspect):null;this.confirmed&&(this.confirmed=n(this.confirmedBasis)??this.confirmed),this.run&&(this.run.latest=n(this.run.basis)??this.run.latest),this.appliedScale=t}ratioScale(){if(this.ratioPool.length<2)return 1;let t=this.fitParams.scaleRatioTol;return Math.min(1+t,Math.max(1-t,tR(this.ratioPool)))}expire(){this.stateValue=this.monitor.tripped?"mismatch":"unverified",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.suppressed=[]}clear(){this.contradicted=!1,this.verifiedThisGen=!1,this.run=null,this.confirmed=null,this.confirmedBasis=null,this.ratioPool=[],this.appliedScale=1,this.holdStart=null,this.lastAnalysisAt=null,this.zeroStreak=0,this.lastFrame={kind:"no-layout"},this.suppressed=[],this.monitor.reset()}display(){switch(this.stateValue){case"off":return"today";case"verified":case"held":return"fitted";case"no-faces":return"hidden";case"mismatch":case"contradicted":return"vision";case"unverified":return this.contradicted?"vision":"today"}}build(t,n){let i=this.display(),u={display:i,suppressed:i==="fitted"?[...this.suppressed]:[],state:this.stateValue,contradicted:this.contradicted,frame:this.lastFrame,diagnostics:{elapsedSinceLastAnalysisMs:this.lastAnalysisAt===null?0:n-this.lastAnalysisAt,runLength:this.run?.length??0,monitorShare:this.monitor.share,row:t,ratioScale:this.ratioScale()}};return i==="fitted"&&(u.region=uc(this.confirmed)),u}};var cc="layout-recording/1",zs=2,rS=[{x:.05,y:.05},{x:.95,y:.05},{x:.5,y:.5},{x:.05,y:.95},{x:.95,y:.95}],rR=["supported-game","two-region","negative-no-faces","negative-gallery","negative-other-layout","transition"],Bs=class extends Error{};function St(e,t){throw new Bs(`${e}: ${t}`)}function mt(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&St(t,"must be an object"),e}function Nr(e,t){return Array.isArray(e)||St(t,"must be an array"),e}function Xe(e,t,n={}){return(typeof e!="number"||!Number.isFinite(e))&&St(t,"must be a finite number"),n.integer&&!Number.isInteger(e)&&St(t,"must be an integer"),n.min!==void 0&&e{let c=`${t}.cards[${d}]`,s=mt(l,c),r={instance:pr(s.instance,`${c}.instance`),bounds:io(s.bounds,`${c}.bounds`)};return s.identity!==void 0&&(r.identity=pr(s.identity,`${c}.identity`)),s.rotated!==void 0&&(typeof s.rotated!="boolean"&&St(`${c}.rotated`,"must be a boolean"),r.rotated=s.rotated),r}),u={key:pr(n.key,`${t}.key`),cards:i};return n.blocking!==void 0&&(u.blocking=io(n.blocking,`${t}.blocking`)),n.aspect!==void 0&&(u.aspect=Xe(n.aspect,`${t}.aspect`),u.aspect>0||St(`${t}.aspect`,"must be positive")),u}function iR(e,t){try{let n=mt(e,t),i=n.region!==null;return{region:i?tS(n.region,`${t}.region`):null,residualPx:i?Xe(n.residualPx,`${t}.residualPx`,{min:0}):typeof n.residualPx=="number"?n.residualPx:0,mask:io(n.mask,`${t}.mask`),blockers:n.blockers===void 0?[]:Nr(n.blockers,`${t}.blockers`).map((u,l)=>io(u,`${t}.blockers[${l}]`)),solves:n.solves===void 0?[]:Nr(n.solves,`${t}.solves`).map((u,l)=>{let d=mt(u,`${t}.solves[${l}]`);return{atMs:Xe(d.atMs,`${t}.solves[${l}].atMs`),residualPx:Xe(d.residualPx,`${t}.solves[${l}].residualPx`,{min:0}),region:i?tS(d.region,`${t}.solves[${l}].region`):null}})}}catch(n){if(n instanceof Bs)return n.message;throw n}}function oR(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))return n.push(`${t}: no clock`),{status:"missing"};let i=e;return i.status!=="ok"&&i.status!=="undecodable"&&i.status!=="missing"?(n.push(`${t}.status: unknown status ${JSON.stringify(i.status)}`),{status:"missing"}):i.status!=="ok"?{status:i.status}:typeof i.streamTimeMs!="number"||!Number.isFinite(i.streamTimeMs)?(n.push(`${t}.streamTimeMs: an ok clock without a finite time`),{status:"missing"}):{status:"ok",streamTimeMs:i.streamTimeMs}}function sR(e){let t=[],n=mt(e,"recording");n.schema!==cc&&St("recording.schema",`must be "${cc}"`);let i=mt(n.frame,"recording.frame"),u={width:Xe(i.width,"recording.frame.width",{min:1}),height:Xe(i.height,"recording.frame.height",{min:1})},l=Nr(n.cadenceProfiles,"recording.cadenceProfiles").map((o,a)=>{let p=mt(o,`recording.cadenceProfiles[${a}]`),h=Xe(p.intervalMs,`recording.cadenceProfiles[${a}].intervalMs`);return h>0||St(`recording.cadenceProfiles[${a}].intervalMs`,"must be positive"),{name:pr(p.name,`recording.cadenceProfiles[${a}].name`),intervalMs:h}}),d=Nr(n.scenes,"recording.scenes").map((o,a)=>{let p=`recording.scenes[${a}]`,h=mt(o,p),m=pr(h.class,`${p}.class`);rR.includes(m)||St(`${p}.class`,`unknown scene class "${m}"`);let g={id:pr(h.id,`${p}.id`),class:m,startMs:Xe(h.startMs,`${p}.startMs`),endMs:Xe(h.endMs,`${p}.endMs`)};if(g.endMs{let p=`recording.frames[${a}]`,h=mt(o,p),m=Xe(h.capturedAtMs,`${p}.capturedAtMs`);m{let T=`${p}.analysis.observations[${y}]`,S=mt(w,T);return{identity:pr(S.identity,`${T}.identity`),bounds:io(S.bounds,`${T}.bounds`)}})}}}),r=Nr(n.candidates,"recording.candidates").map((o,a)=>{let p=`recording.candidates[${a}]`,h=mt(o,p);return{key:pr(h.key,`${p}.key`),producedAtMs:Xe(h.producedAtMs,`${p}.producedAtMs`),arrivedAtMs:Xe(h.arrivedAtMs,`${p}.arrivedAtMs`),layout:nR(h.layout,`${p}.layout`)}});return{schema:cc,frame:u,cadenceProfiles:l,scenes:d,frames:s,candidates:r,problems:t}}function nS(e,t){return e.candidates.map((n,i)=>({c:n,i})).filter(({c:n})=>n.arrivedAtMs<=t).sort((n,i)=>n.c.arrivedAtMs-i.c.arrivedAtMs||n.i-i.i).map(({c:n})=>n)}function pc(e,t){let n=nS(e,t);return n.length>0?n[n.length-1]:null}function aR(e,t){if(!hc(t.clock))return null;let n=t.clock.streamTimeMs,i=null;for(let u of e.candidates)u.producedAtMs<=n&&(i===null||u.producedAtMs>i.producedAtMs)&&(i=u);return i}function hc(e){return e?.status==="ok"&&typeof e.streamTimeMs=="number"&&Number.isFinite(e.streamTimeMs)}function uR(e){let t=e.frames.filter(n=>hc(n.clock));return{frames:t,excluded:e.frames.length-t.length}}function lR(e,t){return e.scenes.find(n=>t>=n.startMs&&tu.residualPx<=zs))return!1;let i=[n.region];for(let u of n.solves){if(!u.region)return!1;i.push(u.region)}for(let u=0;uzs||l>zs)return!1}return!0}function iS(e){return{layoutAt:t=>pc(e,t)?.layout??null,windowIdentitiesAt:t=>pR(pc(e,t)?.layout??null)}}function pR(e){let t=new Set;for(let n of e?.cards??[])n.identity!==void 0&&t.add(n.identity);return t}function hR(e,t){let n=e.cadenceProfiles.find(p=>p.name===t.profile);if(!n)throw new Error(`no cadence profile "${t.profile}" in the recording`);let i={...t.config,intervalMs:n.intervalMs},u=new no(i,{exclude:t.exclude}),l=t.scheduler(n.intervalMs),d=t.source??iS(e),c=[],s=[],r=null,o=1;e.frames.length>0&&u.reset(o,e.frames[0].capturedAtMs);let a=()=>{let p=r;r=null;let h=p.frame,m={generation:o,capturedAtMs:h.capturedAtMs,faces:h.analysis.faces,observations:h.analysis.observations,layout:d.layoutAt(h.capturedAtMs),windowIdentities:d.windowIdentitiesAt(h.capturedAtMs),frameAspect:e.frame.width/e.frame.height};u.analyze(m,p.endedAtMs),s.push({frameIndex:h.index,startedAtMs:p.startedAtMs,endedAtMs:p.endedAtMs,late:p.endedAtMs>p.startedAtMs+n.intervalMs})};for(let p of e.frames){let h=p.capturedAtMs;r&&r.endedAtMs<=h&&a(),l.framePresented(),!r&&l.due(h)&&(l.started(h),r={frame:p,startedAtMs:h,endedAtMs:h+p.analysis.durationMs},p.analysis.durationMs===0&&a()),c.push({frameIndex:p.index,atMs:h,result:u.tick(h)})}return r&&a(),{steps:c,analyses:s}}export{$s as DEFAULT_ACCEPT,kd as DEFAULT_DECODE,ps as DEFAULT_LETTERBOX,$P as DEFAULT_TILTED_RETRY,Li as Detector,_s as EXECUTION_PROVIDERS,ji as Embedder,Gi as EmbeddingRecognizer,rS as FIDUCIAL_POINTS,eo as FrameScheduler,rc as HOVER_MAX_AGE_MS,J$ as HOVER_SELECTIONS,Tn as IdentityMap,Mr as LAYOUT_FIT_DEFAULTS,no as LayoutRegistration,uC as MAX_ANALYSIS_WIDTH,lC as MIN_ANALYSIS_WIDTH,Ns as MONITOR_DEFAULTS,ro as MismatchMonitor,aT as OUTLINE_MIN_TILT,er as PREPROCESSING,Ki as Pipeline,eS as RATIO_POOL_SIZE,Qi as ReleaseError,Hi as TemporalGate,Wi as Tracker,As as analysisSize,sC as analyzeFrame,G$ as boxAverageRgb,Is as cadenceMs,ec as captureFrame,fT as chooseLook,ZC as classifyAccept,YC as classifyHitbox,hc as clockUsable,Yn as compatible,Fd as computeCardQuad,Ds as correspondences,JC as coverage,jC as createSession,hT as cropRgba,C$ as decodeDetections,Wd as estimateTilt,QC as exitLatency,XC as fitError,GC as fitFrame,Ms as fitFrameDetail,vs as hoverAt,Gd as hoverCardsOf,eT as hoverOrder,Gn as iou,pc as latestOffered,JT as layoutConfigError,Rs as layoutExtent,cr as layoutIoU,Jk as letterboxBgr,Rd as letterboxGeometry,oC as loadRelease,Qd as loadReleaseData,lr as lookAccepted,Ad as nonMaxSuppression,nS as offeredCandidates,lT as outlineFromTilt,Zd as outlineRect,Nd as parseBank,Vd as parseIdentityGroups,xT as parseRelease,KT as placementDistance,Z$ as pointInConvexQuad,gT as poolEmbeddings,Sn as project,sR as readLayoutRecording,Yd as recognizeFrame,iS as recordingSource,Kd as rectFromAabb,hR as replayRecording,nc as replyRejection,cs as resizeBilinearRgb,Ud as resolveHover,Ld as resolveHoveredCard,ms as rotateTensor90,uT as sampleRect,lR as sceneAt,qi as selectHoverLayer,QT as suppressedInstances,mT as tiltedOrder,Xd as tiltedRects,uR as timedFrames,fs as toContractTensor,Dd as toDetectorTensor,uc as toRegion,aR as truthCandidate,dR as truthUsable,ls as validBox}; +}`;function VT(){try{return zC()}catch{return null}}function zC(){let e=document.createElement("canvas"),t=e.getContext("webgl2",{alpha:!0,antialias:!1,depth:!1,stencil:!1,preserveDrawingBuffer:!1,powerPreference:"low-power"});if(!t)return null;let n=t.createProgram();for(let[p,h]of[[t.VERTEX_SHADER,MC],[t.FRAGMENT_SHADER,NC]]){let m=t.createShader(p);if(!m)return null;t.shaderSource(m,h),t.compileShader(m),t.attachShader(n,m)}if(t.linkProgram(n),!t.getProgramParameter(n,t.LINK_STATUS))return null;t.useProgram(n);let i=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,i),t.bufferData(t.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,1,1]),t.STATIC_DRAW);let u=t.getAttribLocation(n,"p");t.enableVertexAttribArray(u),t.vertexAttribPointer(u,2,t.FLOAT,!1,0,0);let l=t.createTexture();t.bindTexture(t.TEXTURE_2D,l),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR_MIPMAP_LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);let d=[],c=1,s=!0,r=new Uint8Array(0);e.addEventListener("webglcontextlost",()=>{s=!1});function o(p){return d.find(h=>h.ticket===p)}function a(p){p.fence&&t.deleteSync(p.fence),p.fence=null,p.ticket=null}return{get usable(){return s&&!t.isContextLost()},sample(p){let h=Jn(p);if(!this.usable||h.width===0||h.height===0)return null;let m=d.find(y=>y.ticket===null);if(!m){if(d.length>=DC)return null;let y=t.createBuffer();if(!y)return null;m={pbo:y,fence:null,width:0,height:0,ticket:null},d.push(m)}let{width:g,height:_}=PC(h.width,h.height);try{(e.width!==g||e.height!==_)&&(e.width=g,e.height=_),t.viewport(0,0,g,_),t.bindTexture(t.TEXTURE_2D,l),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,p),t.generateMipmap(t.TEXTURE_2D),t.drawArrays(t.TRIANGLE_STRIP,0,4),t.bindBuffer(t.PIXEL_PACK_BUFFER,m.pbo),(m.width!==g||m.height!==_)&&(t.bufferData(t.PIXEL_PACK_BUFFER,g*_*4,t.STREAM_READ),m.width=g,m.height=_),t.readPixels(0,0,g,_,t.RGBA,t.UNSIGNED_BYTE,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),m.fence=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0),t.flush()}catch{return s=!1,null}if(!m.fence)return null;let w={id:c++};return m.ticket=w,w},read(p){let h=o(p);if(!h||!h.fence||!this.usable||t.getSyncParameter(h.fence,t.SYNC_STATUS)!==t.SIGNALED)return null;let m=h.width*h.height*4;r.length!==m&&(r=new Uint8Array(m)),t.bindBuffer(t.PIXEL_PACK_BUFFER,h.pbo),t.getBufferSubData(t.PIXEL_PACK_BUFFER,0,r),t.bindBuffer(t.PIXEL_PACK_BUFFER,null);let g={width:h.width,height:h.height,luma:CC(r,h.width,h.height)};return a(h),g},release(p){if(!p)return;let h=o(p);h&&a(h)},dispose(){if(s=!1,!t.isContextLost()){for(let p of d)a(p),t.deleteBuffer(p.pbo);d.length=0,t.getExtension("WEBGL_lose_context")?.loseContext()}}}}function uc(e,t,n){let i={left:e.left,top:e.top,width:e.width,height:e.height};if(t.width<=0||t.height<=0||n==="fill")return i;let u=e.width/t.width,l=e.height/t.height,d;n==="cover"?d=Math.max(u,l):n==="none"?d=1:n==="scale-down"?d=Math.min(1,u,l):d=Math.min(u,l);let c=t.width*d,s=t.height*d;return{left:e.left+(e.width-c)/2,top:e.top+(e.height-s)/2,width:c,height:s}}var Rs="no picture",FC="no picture (the paused video draws nothing)",lc="no 2d context",LC="the video may not be read",jC="the picture is too large",UC=16,VC=9,GT=()=>document.createElement("canvas"),GC=e=>createImageBitmap(e);function dc(){return{canvas:null,readable:!1}}function qT(e){return e.paused&&e.readyState<2&&e.videoWidth>0}function cc(e,t){let n=t?.lastPlayingTime??null;return qT(e)&&n!==null?n:e.currentTime}function qC(e,t=GT){let n=UC,i=t();i.width=n,i.height=n;let u=i.getContext("2d");if(!u)return!1;u.drawImage(e,0,0,n,n);let l=u.getImageData(0,0,n,n).data,d=0,c=0;for(let r=0;r({kind:"failed",reason:h,retry:m}),u=e?.video;if(!e||!u||(n.requireConnected??!0)&&!u.isConnected||u.videoWidth===0)return i(Rs,!0);let l=qT(u);if(u.readyState<2&&!l)return i(Rs,!0);let d=n.createCanvas??GT,c=Cs(u.videoWidth,u.videoHeight,t),s=n.maxSide??4096;if(c.width>s||c.height>s)return i(jC);let r=e.source;r.canvas||(r.canvas=d(),r.readable=!1);let o=r.canvas;o.width=c.width,o.height=c.height;let a=o.getContext("2d");if(!a)return i(lc);let p=cc(u,e);try{return a.drawImage(u,0,0,c.width,c.height),l&&qC(o,d)?(r.readable=!0,i(FC,!0)):(r.readable||(a.getImageData(0,0,1,1),r.readable=!0),{kind:"frame",bitmap:await(n.createImageBitmap??GC)(o),mediaTime:p})}catch(h){return i(HC(h)?LC:String(h))}}function WT(e,t){let n=null,i=dc(),u={video:e,get lastPlayingTime(){return n},get source(){return i},mediaTime:()=>cc(e,u),detach:a},l=()=>t.discontinuity(!1),d=()=>{i=dc(),n=null,t.discontinuity(!0)},c=()=>{!e.paused&&e.readyState>=2&&(n=e.currentTime),t.presented(u.mediaTime())},s=()=>t.presented(u.mediaTime()),r=[["seeking",l],["emptied",d],["loadeddata",d],["timeupdate",c],["seeked",c],["canplay",s],["playing",s]];for(let[p,h]of r)e.addEventListener(p,h);let o=!0;function a(){if(o){o=!1;for(let[p,h]of r)e.removeEventListener(p,h)}}return u}var VM=1440*60*1e3;var WC=[/^the worker did not start/,/^unexpected error while loading/];function KT(e,t){return t||e.startsWith("unexpected:")?!1:!WC.some(n=>n.test(e))}var YM=Object.freeze({misses:2,maxMs:5e3,sameBoxIou:.5});function KC(e,t){return e==="loading"?{phase:t.phase,bytes:t.bytes}:void 0}function XC(e){if(!e||!Number.isFinite(e.rotation)||e.rotation===0)return{};let{rotation:t,localWidth:n,localHeight:i}=e;return t>-45&&t<=45&&n>0&&n<=1&&i>0&&i<=1?{rotation:t,localWidth:n,localHeight:i}:{}}function ZC(e,t,n=40){return(e.hover?.cards??[]).map(i=>i.bounds).filter(i=>i&&!(Math.abs(i.x-t.x)<1e-6&&Math.abs(i.y-t.y)<1e-6&&Math.abs(i.width-t.width)<1e-6)).slice(0,n).map(i=>({x:i.x,y:i.y,width:i.width,height:i.height}))}var Ds=class{constructor(t,n={}){this.deps=t;this.mode=n.mode??"pointer",this.hold=n.hold??null,this.maxOtherBoxes=n.maxOtherBoxes??40,this.rotatedOutlines=n.rotatedOutlines===!0,this.hitTest=t.hoverAt??$s;let i=Yn(n.measuredPacing);this.pacer=i===null?null:new Es(i),this.scheduler=new ro(As(null,this.mode),3,this.mode,Zn(null)),this.st={state:"loading",error:null,release:null,backend:null,schedule:"idle",frames:0,lastWorkerMs:null,lastRoundTripMs:null,lastFrameError:null,geometric:n.geometric?{state:"loading",reason:null,bytes:null}:null,loading:null,tilted:null},this.lastStatusKey=this.statusKey()}deps;scheduler;mode;hold;maxOtherBoxes;rotatedOutlines;hitTest;pacer;st;cardList=[];analysisWidth={min:720,max:1920};maxAgeMs=ic;nextRequestId=1;inFlight=null;lastAcceptedRequestId=0;analyzedSinceLoad=!1;generation=0;sourceCount=0;result=null;pointerAt=null;mediaTime=0;lastShownKey="null";lastStatusKey="";held=null;get videoKey(){return`source-${this.sourceCount}`}pointer(t,n,i,u=!1){if(this.st.state==="stopped")return;let l=this.deps.now();this.pointerAt={x:t,y:n},this.mediaTime=i,u?this.scheduler.tapped(l):this.scheduler.pointerMoved(l),this.st.state==="ready"&&this.scheduler.hoverTriggerDue(l,this.videoTime(),this.inFlight!==null)&&this.requestCapture("hover"),this.publish()}pointerLeft(){this.st.state!=="stopped"&&(this.pointerAt=null,this.scheduler.pointerLeft(this.deps.now()),this.publish())}presented(t){this.st.state!=="stopped"&&(this.mediaTime=t,this.scheduler.framePresented(),this.publish())}discontinuity(t){this.st.state!=="stopped"&&(this.generation+=1,t&&(this.sourceCount+=1),this.scheduler.discontinuity(),this.result=null,this.held=null,t&&this.scheduler.framePresented(),this.publish())}cut(){this.st.state!=="stopped"&&(this.generation+=1,this.result=null,this.held=null,this.scheduler.requestLook(),this.publish())}frame(t,n,i){let u=this.inFlight;if(this.st.state==="stopped"||!u||u.requestId!==t||u.analyzing){n.close();return}if(this.scheduler.pictureReceived(),u.generation!==this.generation||u.videoKey!==this.videoKey){this.inFlight=null,n.close(),this.publish();return}u.analyzing=!0;let l={requestId:u.requestId,mediaTimeSec:i,generation:u.generation,videoKey:u.videoKey};try{this.deps.toWorker({kind:"frame",bitmap:n,videoTimeSec:i,envelope:l,...this.rotatedOutlines?{rotatedOutlines:!0}:{}},[n])}catch(d){n.close(),this.inFlight=null,this.st.lastFrameError=`analysis-failed: ${String(d)}`,this.scheduler.lookUnanswered(this.deps.now())}this.publish()}captureFailed(t,n,i=!1){let u=this.inFlight;this.st.state==="stopped"||!u||u.requestId!==t||u.analyzing||(this.inFlight=null,this.st.lastFrameError=`capture-failed: ${n}`,i?this.scheduler.lookUnanswered(this.deps.now(),{prompt:!0}):this.scheduler.lookRefused(),this.publish())}fromWorker(t){if(this.st.state!=="stopped")switch(t.kind){case"geometric-status":this.st.geometric={state:t.state,reason:t.reason,bytes:t.bytes},this.deps.onGeometricStatus?.(t),this.publishStatus();return;case"tilted-status":this.st.tilted={state:"off",reason:t.reason},this.deps.onTiltedStatus?.(t),this.publishStatus();return;case"release-progress":{let n=KC(this.st.state,t);n!==void 0&&(this.st.loading=n),this.publishStatus();return}case"release-status":this.st.state=t.ok?"ready":"failed",this.analyzedSinceLoad=!1,this.st.error=t.error,this.st.release=t.release,this.st.loading=null,this.st.tilted=t.release?.tiltedRetry?{state:"on",reason:null}:null,this.cardList=t.cards,t.release&&(this.st.backend=t.release.recognizer.ep,this.maxAgeMs=t.release.hoverMaxAgeMs,this.analysisWidth={...t.release.analysisWidth},this.applyCadence(),this.scheduler.framePresented()),this.publish();return;case"frame-result":this.onFrameResult(t);return;default:return}}applyCadence(){let t=this.st.backend;this.scheduler.setIntervalMs(this.pacer?this.pacer.intervalMs(t,this.mode):As(t,this.mode)),this.scheduler.setReadingIntervalMs(this.pacer?this.pacer.readingMs(t,this.maxAgeMs):Zn(t))}onFrameResult(t){let n=this.deps.now(),i=oc(t.envelope,{inFlightRequestId:this.inFlight?.requestId??null,lastAcceptedRequestId:this.lastAcceptedRequestId,generation:this.generation,videoKey:this.videoKey});if(i!==null&&!MT(i))return;let u=this.inFlight;if(this.inFlight=null,i!==null){this.publish();return}this.lastAcceptedRequestId=t.envelope.requestId,this.st.lastFrameError=t.error??null,this.st.lastWorkerMs=t.workerMs,this.st.lastRoundTripMs=+(n-u.sentAt).toFixed(2),t.analysis?(this.analyzedSinceLoad=!0,this.pacer&&(this.pacer.record(t.workerMs),this.applyCadence()),this.scheduler.lookAnswered(),this.st.frames+=1,this.result={analysis:t.analysis,videoTimeSec:t.videoTimeSec},this.deps.onAnalysis?.(t.analysis)):(this.result=null,t.error===K$&&this.scheduler.lookUnanswered(n)),this.held&&this.pointerAt&&this.current()&&!this.fresh()&&(this.held.misses+=1),this.scheduler.setTooltipShowing(this.shown()!==null,n),this.publish()}tick(){if(this.st.state==="stopped")return;let t=this.deps.now(),n=this.analyzedSinceLoad?RT:DT;this.inFlight&&t-this.inFlight.sentAt>=n&&(this.inFlight=null,this.st.lastFrameError="no reply",this.scheduler.lookUnanswered(t)),this.scheduler.setTooltipShowing(this.shown()!==null,t),this.st.state==="ready"&&!this.inFlight&&this.scheduler.due(t)&&this.requestCapture(this.scheduler.lookPending?"cut":void 0),this.publish()}stop(){this.st.state!=="stopped"&&(this.st.state="stopped",this.st.loading=null,this.inFlight=null,this.result=null,this.held=null,this.pointerAt=null,this.publishShown(),this.publishStatus())}workerStopped(t){if(!(this.st.state==="stopped"||this.st.state==="failed")){if(this.inFlight=null,this.result=null,this.held=null,this.st.loading=null,this.publishShown(),"restart"in t){let n={kind:"geometric-status",state:"off",reason:"worker-restarted",bytes:null};this.st.geometric&&(this.st.geometric={state:n.state,reason:n.reason,bytes:n.bytes}),this.deps.onGeometricStatus?.(n),this.st.state="loading",this.analyzedSinceLoad=!1,this.st.error=null}else this.st.state="failed",this.st.error=t.error;this.publishStatus()}}reloading(t){this.st.state==="loading"&&(this.st.geometric=t.geometric?{state:"loading",reason:null,bytes:null}:null,this.st.loading=null,this.publishStatus())}requestCapture(t){if(this.st.state!=="ready"||this.inFlight)return;let n=this.deps.now(),i=this.nextRequestId++;this.inFlight={requestId:i,sentAt:n,generation:this.generation,videoKey:this.videoKey,analyzing:!1},this.scheduler.started(n,{videoTimeSec:this.videoTime(),...t?{trigger:t}:{}}),this.deps.capture(i,{...this.analysisWidth})}status(){return{...this.st,schedule:this.scheduler.analysisState(this.deps.now())}}analysis(){return this.current()?.analysis??null}cards(){return this.cardList}hitAt(t,n){let i=this.current();if(!i)return null;let{width:u,height:l}=i.analysis.frame;if(!(u>0&&l>0))return null;let d=t*u,c=n*l;if(!Number.isFinite(d)||!Number.isFinite(c))return null;let s=this.hitTest(i.analysis,d,c);if(!s.box||s.cardId===null||s.name===null)return null;let r={x:s.box.x/u,y:s.box.y/l,width:s.box.width/u,height:s.box.height/l},o={x:s.box.x,y:s.box.y,width:s.box.width,height:s.box.height};return{cardId:s.cardId,name:s.name,box:r,frameBox:o,others:ZC(i.analysis,r,this.maxOtherBoxes),...XC(s.card)}}fresh(){return this.pointerAt?this.hitAt(this.pointerAt.x,this.pointerAt.y):null}shown(){let t=this.fresh(),n=this.hold;if(!n)return t;let i=this.deps.now();if(t)return this.held={card:t,misses:0,seenAt:i},t;let u=this.held;return!u||!this.pointerAt||!JC(u.card.box,this.pointerAt)?(this.held=null,null):this.boxAtPointer(u.card.box,n.sameBoxIou)==="other"||u.misses>=n.misses||i-u.seenAt>=n.maxMs?(this.held=null,null):u.card}current(){let t=this.result;return t&&CT(t.videoTimeSec,this.videoTime(),this.maxAgeMs)?t:null}videoTime(){return this.deps.mediaTimeNow?this.deps.mediaTimeNow():this.mediaTime}boxAtPointer(t,n){let i=this.current();if(!i||!this.pointerAt)return"unknown";let{width:u,height:l}=i.analysis.frame;if(!(u>0&&l>0))return"unknown";let d=this.pointerAt.x*u,c=this.pointerAt.y*l,s={x:t.x*u,y:t.y*l,width:t.width*u,height:t.height*l},r=0,o=!1;for(let a of i.analysis.boxes??[]){let[p,h,m,g]=a.box;dp+m||ch+g||(o=!0,r=Math.max(r,YC(s,{x:p,y:h,width:m,height:g})))}return o?r>=n?"same":"other":"none"}publish(){this.publishShown(),this.publishStatus()}publishShown(){let t=this.shown(),n=t?`${t.cardId}|${t.box.x}|${t.box.y}|${t.box.width}|${t.box.height}|${t.rotation??""}|${t.localWidth??""}|${t.localHeight??""}`:"null";n!==this.lastShownKey&&(this.lastShownKey=n,this.deps.onShown?.(t))}statusKey(){let t=this.status();return JSON.stringify({...t,release:t.release?t.release.id:null})}publishStatus(){let t=this.statusKey();t!==this.lastStatusKey&&(this.lastStatusKey=t,this.deps.onStatus?.(this.status()))}};function YC(e,t){let n=Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x),i=Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y);if(n<=0||i<=0)return 0;let u=n*i;return u/(e.width*e.height+t.width*t.height-u)}function JC(e,t){return t.x>=e.x&&t.x<=e.x+e.width&&t.y>=e.y&&t.y<=e.y+e.height}var ZT=1;function QC(e){let{geometricUrl:t,geometricManifestSha256:n,geometricWatchdog:i,...u}=e;return u}function YT(e){Yn(e.measuredPacing);let t=null,n=null,i=0,u=!1,l=null,d=!1,c=null,s={source:e.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},r=y=>{e.onDecision?.({reused:0,downloaded:0,ms:0,...y})},o=y=>new Ds({now:e.now,toWorker:(T,S)=>t?.postMessage(T,S??[]),capture:e.capture,...e.onShown?{onShown:e.onShown}:{},...e.onStatus?{onStatus:e.onStatus}:{},...e.onAnalysis?{onAnalysis:e.onAnalysis}:{},...e.onGeometricStatus?{onGeometricStatus:e.onGeometricStatus}:{},...e.hoverAt?{hoverAt:e.hoverAt}:{},...e.mediaTimeNow?{mediaTimeNow:e.mediaTimeNow}:{}},{...e.mode?{mode:e.mode}:{},...e.measuredPacing?{measuredPacing:e.measuredPacing}:{},...e.hold?{hold:e.hold}:{},...e.rotatedOutlines?{rotatedOutlines:!0}:{},geometric:y.geometricUrl!==void 0}),a=y=>{u||!n||(l&&y.kind==="release-progress"&&y.phase==="preparing"&&(d=!0),!(y.kind==="release-status"&&(n.status().state!=="loading"||l&&!h(y)))&&(y.kind==="release-status"&&!y.ok&&p(),n.fromWorker(y)))},p=()=>{u=!0,l=null,t?.terminate(),t=null},h=y=>{let T=l;if(y.ok&&y.release?.id===T.pointer.id)return l=null,c=T.pointer.id,s.source="remote",s.id=T.pointer.id,s.reason="ok",s.table=T.facts,r({source:"remote",reason:"ok",pointer:T.pointer.id,reused:T.reused,downloaded:T.downloaded,ms:T.ms}),!0;if(y.ok)return e.recordSkip?.(T.pointer,"id-mismatch"),m("id-mismatch"),!1;let S=y.error??"no reason given";return KT(S,d)&&e.recordSkip?.(T.pointer,`runtime:${S.slice(0,120)}`),m(`runtime:${S}`),!1},m=y=>{let T=l;l=null,t?.terminate(),s.source="bundled",s.id=null,s.reason=y,s.table=null,r({source:"bundled",reason:y,pointer:T.pointer.id,reused:T.reused,downloaded:T.downloaded,ms:T.ms});let S=T.fallback??e.loadRequest;n?.reloading({geometric:S.geometricUrl!==void 0}),w(S)},g=y=>{if(u||!n)return;let T=n.status().state;if(T==="failed"||T==="stopped")return;let S=y.message||"see the console";if(l){h({kind:"release-status",ok:!1,error:`the worker did not start (${S})`,release:null,cards:[]});return}if(t?.terminate(),T==="loading"&&i===0){p(),n.workerStopped({error:`the worker did not start (${S})`});return}if(i{let T=e.createWorker();T.onmessage=S=>{T===t&&a(S.data)},T.onerror=S=>{T===t&&g(S)},t=T,T.postMessage(y)},w=y=>{n??=o(y);try{_(y)}catch(T){t=null,l=null,u=!0,n.workerStopped({error:`the recognition worker could not start (${String(T)})`})}};return e.chooseRelease?e.chooseRelease({onDownloading:()=>e.onDownloading?.()}).catch(y=>({source:"bundled",reason:`unexpected:${String(y)}`,pointer:null,downloaded:0,ms:0})).then(y=>{if(!u){if(y.source==="remote"){l=y,d=!1,w(y.request);return}s.source="bundled",s.reason=y.reason,r({source:"bundled",reason:y.reason,pointer:y.pointer?.id??null,downloaded:y.downloaded,ms:y.ms}),w(y.request??e.loadRequest)}}):w(e.loadRequest),{get core(){return n},get stopped(){return u},get restarts(){return i},get release(){return{...s}},tick(){u||n?.tick()},stop(){u=!0,l=null,t?.terminate(),t=null,n?.stop()}}}var eR={requireConnected:!1,maxSide:1/0};function tR(e,t){Yn(t.measuredPacing);let n=e instanceof HTMLVideoElement?e:null,i=e,u=t.workerUrl??new URL("./worker.js",import.meta.url),l=()=>performance.now(),d=!1,c=0,s=!1,r=()=>{c>0?s=!0:d&&t.onUpdate?.()},o=(N,X=!1)=>{c+=1;try{N()}finally{c-=1}X&&(s=!0),c===0&&s&&(s=!1,d&&t.onUpdate?.())},a=null,p=new Ps,h=null,m=null,g=-1/0,_=()=>{let N=h&&a?a.read(h):null;N?p.seed(N):(a?.release(h),p.reset()),h=null},w=n?null:document.createElement("canvas"),y=w?.getContext("2d")??null,T=async N=>{if(!w||!y)return{kind:"failed",reason:lc,retry:!1};let X=Jn(e);if(X.width===0||X.height===0)return{kind:"failed",reason:Rs,retry:!0};try{let W=await ac(e,w,y,N);return{kind:"frame",bitmap:W.bitmap,mediaTime:W.videoTimeSec}}catch(W){return{kind:"failed",reason:String(W),retry:!1}}},S=(N,X)=>{a?.release(h),h=a?.usable?a.sample(e):null,(z?HT(z,X,eR):T(X)).then(W=>o(()=>{W.kind==="frame"?G.frame(N,W.bitmap,W.mediaTime):G.captureFailed(N,W.reason,W.retry)},W.kind==="failed"))},O=0,A=null,P=()=>{O+=1;let N;try{N=new Worker(u,{type:"module"})}catch(W){throw O===1&&(A={error:W}),W}let X={postMessage:(W,re)=>N.postMessage(W,re??[]),terminate:()=>N.terminate(),onmessage:null,onerror:null};return N.onmessage=W=>o(()=>X.onmessage?.(W)),N.onerror=W=>o(()=>X.onerror?.(W)),X},I={kind:"load",releaseUrl:t.releaseFiles?String(t.releaseUrl):new URL(t.releaseUrl,location.href).href,...t.releaseFiles?{files:t.releaseFiles}:{},...t.wasmPaths!==void 0?{wasmPaths:t.wasmPaths}:{},...t.providers?{providers:t.providers}:{},...t.geometricUrl!==void 0?{geometricUrl:new URL(t.geometricUrl,location.href).href}:{},...t.geometricManifestSha256!==void 0?{geometricManifestSha256:t.geometricManifestSha256}:{},...t.geometricWatchdog===!1?{geometricWatchdog:!1}:{}},z=n?WT(n,{presented:N=>o(()=>G.presented(N)),discontinuity:N=>o(()=>{p.reset(),G.discontinuity(N)},!0)}):null,q=()=>z?.mediaTime()??0,J=YT({createWorker:P,loadRequest:I,now:l,...t.mode?{mode:t.mode}:{},...t.measuredPacing?{measuredPacing:t.measuredPacing}:{},...t.rotatedOutlines?{rotatedOutlines:!0}:{},capture:S,mediaTimeNow:()=>q(),onShown:r,onStatus:r,onAnalysis:_});if(A)throw z?.detach(),J.stop(),A.error;let G=J.core,C=(N,X)=>{let W=uc(e.getBoundingClientRect(),Jn(e),getComputedStyle(e).objectFit);if(W.width<=0||W.height<=0)return null;let re=G.hitAt((N-W.left)/W.width,(X-W.top)/W.height);return re?{hit:re,picture:W}:null},ee=(N,X)=>{let W=C(N,X);if(!W)return null;let{hit:re,picture:le}=W;return{name:re.name,cardId:re.cardId,box:{left:le.left+re.box.x*le.width,top:le.top+re.box.y*le.height,width:re.box.width*le.width,height:re.box.height*le.height},frameBox:re.frameBox,...re.rotation!==void 0&&re.localWidth!==void 0&&re.localHeight!==void 0?{rotation:re.rotation,localWidth:re.localWidth,localHeight:re.localHeight}:{}}},v=null,R=()=>v?ee(v.x,v.y):null,H=N=>{let X=v?C(v.x,v.y)?.hit.box??null:null;if(!X){a?.release(m),m=null;return}if(a||(a=VT()),!!a?.usable){if(m){let W=a.read(m);if(W&&(m=null,p.observe(W,X).cut)){p.reset(),G.cut(),s=!0;return}}!m&&N-g>=UT&&(g=N,m=a.sample(e))}},L=null,V=()=>{!d||!n||(o(()=>{G.presented(q()),H(l())}),L=n.requestVideoFrameCallback(V))},K=()=>o(()=>{p.reset(),G.discontinuity(!0)},!0),B=N=>o(()=>{v={x:N.clientX,y:N.clientY};let X=uc(e.getBoundingClientRect(),Jn(e),getComputedStyle(e).objectFit),W=jT(X,N.clientX,N.clientY)??{x:(N.clientX-X.left)/X.width,y:(N.clientY-X.top)/X.height};G.pointer(W.x,W.y,q(),N.pointerType==="touch")},!0),te=()=>o(()=>{v=null,G.pointerLeft()},!0);n&&"requestVideoFrameCallback"in n&&(L=n.requestVideoFrameCallback(V)),n||e.addEventListener("load",K),i.addEventListener("pointermove",B),i.addEventListener("pointerdown",B),i.addEventListener("pointerleave",te);let Y=setInterval(()=>o(()=>J.tick()),Os);return d=!0,{status:()=>G.status(),at:ee,atPointer:R,analysis:()=>G.analysis(),cards:()=>G.cards(),stop:()=>{d&&(d=!1,clearInterval(Y),L!==null&&n&&"cancelVideoFrameCallback"in n&&n.cancelVideoFrameCallback(L),L=null,z?.detach(),e.removeEventListener("load",K),i.removeEventListener("pointermove",B),i.removeEventListener("pointerdown",B),i.removeEventListener("pointerleave",te),a?.release(h),a?.release(m),a?.dispose(),p.reset(),J.stop())}}}var Mr={maxCorrespondences:40,fitMinInliers:3,inlierShare:[2,3],ambiguityMin:2,compatTol:.01,scaleRatioTol:.03},pc=1e-9,Ms=5;function cr(e,t){let n=Math.max(0,Math.min(e.x+e.w,t.x+t.w)-Math.max(e.x,t.x)),i=Math.max(0,Math.min(e.y+e.h,t.y+t.h)-Math.max(e.y,t.y)),u=n*i,l=e.w*e.h+t.w*t.h-u;return l>0?u/l:0}function Sn(e,t){return{x:e.sx*t.x+e.tx,y:e.sy*t.y+e.ty,w:e.sx*t.w,h:e.sy*t.h}}function no(e,t){return{x:e.sx*t.x+e.tx,y:e.sy*t.y+e.ty}}function hc(e){return{x:e.tx,y:e.ty,width:e.sx,height:e.sy}}function Ns(e){if(e.cards.length===0)return null;let t=1/0,n=1/0,i=-1/0,u=-1/0;for(let{bounds:l}of e.cards)t=Math.min(t,l.x),n=Math.min(n,l.y),i=Math.max(i,l.x+l.w),u=Math.max(u,l.y+l.h);return{x:t,y:n,w:i-t,h:u-n}}function fc(e){let t=[];for(let n=0;n=e.x&&t.x<=e.x+e.w&&t.y>=e.y&&t.y<=e.y+e.h}function JT(e,t){return et?1:0}function rR(e,t){return t.identity===void 0?!1:e.blocking===void 0||!In(e.blocking,rS(t.bounds))}function zs(e,t,n=Mr.maxCorrespondences){let i=new Map;for(let d of e)i.set(d.identity,i.has(d.identity)?null:d);let u=new Map;for(let d of t.cards){if(!rR(t,d))continue;let c=d.identity;u.set(c,u.has(c)?null:d)}let l=[];for(let[d,c]of i){let s=u.get(d);!c||!s||l.push({identity:d,v:c.bounds,r:s.bounds,instance:s.instance})}return l.length>n&&(l.sort((d,c)=>c.v.w*c.v.h-d.v.w*d.v.h||JT(d.identity,c.identity)),l=l.slice(0,n)),l.sort((d,c)=>JT(d.identity,c.identity))}function nR(e){if(!(e.r.w>0)||!(e.r.h>0))return null;let t=e.v.w/e.r.w,n=e.v.h/e.r.h,i={sx:t,sy:n,tx:e.v.x-t*e.r.x,ty:e.v.y-n*e.r.y};return![i.sx,i.sy,i.tx,i.ty].every(Number.isFinite)||!(t>0)||!(n>0)?null:i}function QT(e){let t=e.length;if(t===0)return null;let n=0,i=0;for(let[s,r]of e)n+=s,i+=r;n/=t,i/=t;let u=0,l=0;for(let[s,r]of e)u+=(s-n)*(r-i),l+=(s-n)*(s-n);if(!(l>0))return null;let d=u/l;if(!(d>0)||!Number.isFinite(d))return null;let c=i-d*n;return Number.isFinite(c)?{s:d,t:c}:null}function eS(e){let t=[],n=[];for(let{r:l,v:d}of e)t.push([l.x,d.x],[l.x+l.w,d.x+d.w]),n.push([l.y,d.y],[l.y+l.h,d.y+d.h]);let i=QT(t),u=QT(n);return!i||!u?null:{sx:i.s,sy:u.s,tx:i.t,ty:u.t}}function mc(e,t,n){if(e.length===0||!(t>0)||!(n>0))return null;let i=[],u=[];for(let{r:y,v:T}of e)i.push([y.x,T.x],[y.x+y.w,T.x+T.w]),u.push([y.y,T.y],[y.y+y.h,T.y+T.h]);let l=(y,T)=>y.reduce((S,O)=>S+O[T],0)/y.length,d=l(i,0),c=l(i,1),s=l(u,0),r=l(u,1),o=0,a=0,p=0,h=0;for(let[y,T]of i)o+=(y-d)*(y-d),a+=(y-d)*(T-c);for(let[y,T]of u)p+=(y-s)*(y-s),h+=(y-s)*(T-r);let m=n*n,g=m*o+t*t*p;if(!(g>0))return null;let _=(m*a+t*h)/g;if(!(_>0)||!Number.isFinite(_))return null;let w={sx:_,sy:t*_,tx:c-_*d,ty:r-t*_*s};return[w.sy,w.tx,w.ty].every(Number.isFinite)?w:null}function iR(e,t){if(e.aspect===void 0||t===void 0)return null;let n=i=>Number.isFinite(i)&&i>0;return!n(e.aspect)||!n(t)?NaN:t/e.aspect}function oR(e,t,n,i,u=1){return Bs(e,t,n,i,u).outcome}function Bs(e,t,n,i,u=1){if(t===null)return{outcome:{kind:"no-layout"},correspondences:[],support:[],winner:-1,aspectRejected:[]};let l=zs(e,t,n.maxCorrespondences),d=l.length,c=[],s=(L,V,K=[],B=-1)=>({outcome:{kind:"insufficient",reason:L,n:d,inliers:V},correspondences:l,support:K,winner:B,aspectRejected:c}),r=iR(t,i);if(r!==null&&(Number.isNaN(r)||!(Number.isFinite(u)&&u>0)))return s("degenerate",0);let o=L=>r!==null&&Math.abs(L.sy/L.sx/r-1)>n.scaleRatioTol,a=L=>{let V=[];for(let K=0;K=n.fitMinIoU&&V.push(K);return V},p=l.map(nR),h=p.map((L,V)=>L&&o(L)?(c.push(V),null):L),m=()=>c.some(L=>a(p[L]).length>=2),g=[],_=[];for(let L=0;L=n.fitMinIoU&&(K.push(te),B+=Y)}g.push(K),_.push(B)}let w=-1;for(let L=0;LK||V===K&&_[L]>_[w]+pc)&&(w=L)}if(w<0){let L=d=n.fitMinInliers)return s(m()?"aspect":"zero-inliers",0,g,w);let y=g[w].map(L=>l[L]),T=r===null?eS(y):mc(y,r*u,i);if(!T)return s("degenerate",0,g,w);let S=[],O=1/0;for(let L of g[w]){let V=cr(Sn(T,l[L].r),l[L].v);V>=n.fitMinIoU&&(S.push(L),O=Math.min(O,V))}let A=S.map(L=>l[L].identity),P=Ns(t),I=new Set(S),z=[];for(let L=0;L!I.has(B));K.length>z.length&&(z=K)}if(z.length>=n.ambiguityMin)return{outcome:{kind:"ambiguous",transform:T,inliers:A,runnerUp:z.map(L=>l[L].identity),n:d},correspondences:l,support:g,winner:w,aspectRejected:c};if(A.lengthl[V]));if(!L||o(L))return s("aspect",A.length,g,w);H=L.sy/L.sx/r}return{outcome:{kind:"verified",transform:T,inliers:A,n:d,minIoU:O,span:R,...H!==void 0?{boardRatio:H}:{}},correspondences:l,support:g,winner:w,aspectRejected:c}}var sR=8,aR=20,uR=.3;function lR(e,t,n,i,u){let l=0;for(let d of fc(n)){let c=no(e,d),s=no(t,d);l=Math.max(l,Math.abs(c.x-s.x)*i,Math.abs(c.y-s.y)*u)}return l}function dR(e,t){return t?e<=sR?"correct":e<=aR?"loose":"false":"none"}function nS(e){return{x:e.x+e.w/2,y:e.y+e.h/2}}function cR(e,t,n,i=[]){let u=nS(e.box);if(!In(n,u)||i.some(c=>In(c,u)))return"blocked";let l=null,d=-1;for(let c of t){let s=cr(e.box,c.box);s>=uR&&s>d&&(l=c,d=s)}return l?!l.faceUp||l.identity===void 0?"back-hidden":l.identity===e.identity?"correct":"wrong-identity":"empty"}function pR(e,t,n,i=[]){let u=0,l=0;for(let d of e){if(!d.faceUp||d.identity===void 0)continue;let c=nS(d.box);!In(n,c)||i.some(s=>In(s,c))||(u+=1,t.some(s=>s.identity===d.identity&&In(s.box,c))&&(l+=1))}return u===0?null:l/u}function hR(e,t){return t.map(n=>fR(e,n))}function fR(e,t){let n=null;for(let i of e){if(i.atMs>t)break;n=i.display}if(n!=="fitted")return 0;for(let i of e)if(i.atMs>=t&&i.display!=="fitted")return i.atMs-t;return null}var Fs={window:10,minIdentities:3,trip:.4,recover:.7},io=class{params;exclude;window=[];stateValue="unknown";recoverRun=0;constructor(t={}){this.params=t.params??Fs,this.exclude=t.exclude??(()=>!1)}get state(){return this.stateValue}get tripped(){return this.stateValue==="tripped"}get share(){return this.summary().share}observe(t){if(t.windowIdentities.size===0)return{state:this.stateValue,event:null,...this.summary(),counted:!1};let n=new Map;for(let c of t.accepted)this.exclude(c)||n.set(c,(n.get(c)??!1)||t.windowIdentities.has(c));this.window.push(n),this.window.length>this.params.window&&this.window.shift();let{identities:i,share:u}=this.summary(),l=i>=this.params.minIdentities&&u!==null,d=null;return this.stateValue==="tripped"?(this.recoverRun=l&&u>=this.params.recover?this.recoverRun+1:0,this.recoverRun>=this.params.window&&(this.stateValue="in",this.recoverRun=0,d="recover")):l&&(u0&&t.scaleRatioTol<=.25))return"scaleRatioTol must be above 0 and at most 0.25";let n=t;return n.fitMinIoU<.5||n.fitMinIoU>1?"fitMinIoU must be between 0.5 and 1":n.minSpan<0||n.minSpan>1?"minSpan must be between 0 and 1":!Number.isInteger(n.confirmFits)||n.confirmFits<1||n.confirmFits>3?"confirmFits must be 1, 2 or 3":n.suppressionIoU<=0||n.suppressionIoU>1?"suppressionIoU must be above 0 and at most 1":n.intervalMs<=0?"intervalMs must be positive":n.confirmWindowMs<3*n.intervalMs?"confirmWindowMs must be at least 3 \xD7 intervalMs":n.freshnessMs<2*n.intervalMs?"freshnessMs must be at least 2 \xD7 intervalMs":n.holdMs=u){d.add(c.instance);break}}return e.cards.map(c=>c.instance).filter(c=>d.has(c))}var aS=15;function mR(e){let t=[...e].sort((i,u)=>i-u),n=t.length>>1;return t.length%2===1?t[n]:(t[n-1]+t[n])/2}var oo=class{config;fitParams;monitor;generationValue=null;stateValue="off";contradicted=!1;verifiedThisGen=!1;run=null;confirmed=null;confirmedBasis=null;ratioPool=[];appliedScale=1;holdStart=null;lastAnalysisAt=null;zeroStreak=0;lastFrame={kind:"no-layout"};suppressed=[];current;constructor(t,n={}){let i=oS(t);if(i)throw new Error(i);this.config=Object.freeze({...t}),this.fitParams={...Mr,fitMinIoU:t.fitMinIoU,minSpan:t.minSpan,ambiguityMin:t.ambiguityMin??Mr.ambiguityMin,scaleRatioTol:t.scaleRatioTol??Mr.scaleRatioTol},this.monitor=new io({exclude:n.exclude,params:Fs}),this.current=this.build(0,0)}get generation(){return this.generationValue}get state(){return this.stateValue}get verdict(){return this.current}eligibilityLost(t){return this.clear(),this.generationValue=null,this.stateValue="off",this.current=this.build(1,t)}reset(t,n){return this.clear(),this.generationValue=t,this.stateValue="unverified",this.current=this.build(2,n)}tick(t){return this.expired(t)?(this.expire(),this.current=this.build(11,t)):this.current=this.build(0,t)}analyze(t,n){if(this.generationValue===null||t.generation!==this.generationValue)return null;let i=this.expired(n);i&&this.expire();let u=this.stateValue,l=this.ratioScale(),d=Bs(t.observations,t.layout,this.fitParams,t.frameAspect,l),c=d.outcome;this.lastFrame=c;let s=null;c.kind==="verified"&&c.boardRatio!==void 0&&(s={correspondences:d.support[d.winner].map(_=>d.correspondences[_]),ratio:t.frameAspect/t.layout.aspect,frameAspect:t.frameAspect});let r=this.monitor.observe({windowIdentities:t.windowIdentities,accepted:t.observations.map(_=>_.identity)});this.lastAnalysisAt=n,this.zeroStreak=c.kind==="insufficient"&&c.reason==="zero-inliers"?this.zeroStreak+1:0;let o=t.layout?Ns(t.layout):null,a=c.kind==="verified"&&o!==null?c:null,p=this.fitParams.compatTol,h=a!==null&&this.confirmed!==null&&!Qn(a.transform,this.confirmed,o,p),m=this.run;if(a){let _=this.run!==null&&Qn(a.transform,this.run.latest,o,p)&&t.capturedAtMs-this.run.capturedAtMs<=this.config.confirmWindowMs;m={latest:a.transform,capturedAtMs:t.capturedAtMs,length:_?this.run.length+1:1,basis:s}}let g;return r.event==="trip"?(g=3,this.run=m,this.stateValue="mismatch",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0):u==="mismatch"&&r.event==="recover"?(g=4,this.run=m,this.stateValue="unverified"):h?(g=5,this.run={latest:a.transform,capturedAtMs:t.capturedAtMs,length:1,basis:s},this.stateValue="contradicted",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0,this.verifiedThisGen=!0):this.zeroStreak>=2&&(u==="verified"||u==="held")?(g=6,this.stateValue="contradicted",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.contradicted=!0,this.verifiedThisGen=!0):t.faces===0&&t.layout!==null&&t.layout.cards.length>=3&&this.verifiedThisGen&&u!=="mismatch"?(g=7,this.run=m,this.stateValue="no-faces"):a&&m.length>=this.config.confirmFits?(g=9,this.run=m,this.stateValue="verified",this.confirmed=a.transform,this.confirmedBasis=s,this.contradicted=!1,this.holdStart=n,this.verifiedThisGen=!0,this.monitor.clearTrip()):(this.run=m,(u==="verified"||u==="held"||u==="no-faces"&&a!==null)&&this.confirmed!==null&&this.holdStart!==null&&n-this.holdStartaS&&this.ratioPool.shift()),this.applyScale(this.ratioScale()),(this.stateValue==="verified"||this.stateValue==="held")&&this.confirmed&&t.layout?this.suppressed=sS(t.layout,t.observations,this.confirmed,this.fitParams.fitMinIoU,this.config.suppressionIoU,this.fitParams.maxCorrespondences):this.suppressed=[],this.current=this.build(g,n)}expired(t){let n=this.stateValue;if(n!=="verified"&&n!=="held"&&n!=="no-faces")return!1;let i=this.holdStart!==null&&t-this.holdStart>=this.config.holdMs,u=this.lastAnalysisAt!==null&&t-this.lastAnalysisAt>=this.config.freshnessMs;return i||u}applyScale(t){if(t===this.appliedScale)return;let n=i=>i?mc(i.correspondences,i.ratio*t,i.frameAspect):null;this.confirmed&&(this.confirmed=n(this.confirmedBasis)??this.confirmed),this.run&&(this.run.latest=n(this.run.basis)??this.run.latest),this.appliedScale=t}ratioScale(){if(this.ratioPool.length<2)return 1;let t=this.fitParams.scaleRatioTol;return Math.min(1+t,Math.max(1-t,mR(this.ratioPool)))}expire(){this.stateValue=this.monitor.tripped?"mismatch":"unverified",this.confirmed=null,this.confirmedBasis=null,this.holdStart=null,this.suppressed=[]}clear(){this.contradicted=!1,this.verifiedThisGen=!1,this.run=null,this.confirmed=null,this.confirmedBasis=null,this.ratioPool=[],this.appliedScale=1,this.holdStart=null,this.lastAnalysisAt=null,this.zeroStreak=0,this.lastFrame={kind:"no-layout"},this.suppressed=[],this.monitor.reset()}display(){switch(this.stateValue){case"off":return"today";case"verified":case"held":return"fitted";case"no-faces":return"hidden";case"mismatch":case"contradicted":return"vision";case"unverified":return this.contradicted?"vision":"today"}}build(t,n){let i=this.display(),u={display:i,suppressed:i==="fitted"?[...this.suppressed]:[],state:this.stateValue,contradicted:this.contradicted,frame:this.lastFrame,diagnostics:{elapsedSinceLastAnalysisMs:this.lastAnalysisAt===null?0:n-this.lastAnalysisAt,runLength:this.run?.length??0,monitorShare:this.monitor.share,row:t,ratioScale:this.ratioScale()}};return i==="fitted"&&(u.region=hc(this.confirmed)),u}};var gc="layout-recording/1",Ls=2,lS=[{x:.05,y:.05},{x:.95,y:.05},{x:.5,y:.5},{x:.05,y:.95},{x:.95,y:.95}],gR=["supported-game","two-region","negative-no-faces","negative-gallery","negative-other-layout","transition"],js=class extends Error{};function St(e,t){throw new js(`${e}: ${t}`)}function mt(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&St(t,"must be an object"),e}function Nr(e,t){return Array.isArray(e)||St(t,"must be an array"),e}function Xe(e,t,n={}){return(typeof e!="number"||!Number.isFinite(e))&&St(t,"must be a finite number"),n.integer&&!Number.isInteger(e)&&St(t,"must be an integer"),n.min!==void 0&&e{let c=`${t}.cards[${d}]`,s=mt(l,c),r={instance:pr(s.instance,`${c}.instance`),bounds:so(s.bounds,`${c}.bounds`)};return s.identity!==void 0&&(r.identity=pr(s.identity,`${c}.identity`)),s.rotated!==void 0&&(typeof s.rotated!="boolean"&&St(`${c}.rotated`,"must be a boolean"),r.rotated=s.rotated),r}),u={key:pr(n.key,`${t}.key`),cards:i};return n.blocking!==void 0&&(u.blocking=so(n.blocking,`${t}.blocking`)),n.aspect!==void 0&&(u.aspect=Xe(n.aspect,`${t}.aspect`),u.aspect>0||St(`${t}.aspect`,"must be positive")),u}function yR(e,t){try{let n=mt(e,t),i=n.region!==null;return{region:i?uS(n.region,`${t}.region`):null,residualPx:i?Xe(n.residualPx,`${t}.residualPx`,{min:0}):typeof n.residualPx=="number"?n.residualPx:0,mask:so(n.mask,`${t}.mask`),blockers:n.blockers===void 0?[]:Nr(n.blockers,`${t}.blockers`).map((u,l)=>so(u,`${t}.blockers[${l}]`)),solves:n.solves===void 0?[]:Nr(n.solves,`${t}.solves`).map((u,l)=>{let d=mt(u,`${t}.solves[${l}]`);return{atMs:Xe(d.atMs,`${t}.solves[${l}].atMs`),residualPx:Xe(d.residualPx,`${t}.solves[${l}].residualPx`,{min:0}),region:i?uS(d.region,`${t}.solves[${l}].region`):null}})}}catch(n){if(n instanceof js)return n.message;throw n}}function wR(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))return n.push(`${t}: no clock`),{status:"missing"};let i=e;return i.status!=="ok"&&i.status!=="undecodable"&&i.status!=="missing"?(n.push(`${t}.status: unknown status ${JSON.stringify(i.status)}`),{status:"missing"}):i.status!=="ok"?{status:i.status}:typeof i.streamTimeMs!="number"||!Number.isFinite(i.streamTimeMs)?(n.push(`${t}.streamTimeMs: an ok clock without a finite time`),{status:"missing"}):{status:"ok",streamTimeMs:i.streamTimeMs}}function _R(e){let t=[],n=mt(e,"recording");n.schema!==gc&&St("recording.schema",`must be "${gc}"`);let i=mt(n.frame,"recording.frame"),u={width:Xe(i.width,"recording.frame.width",{min:1}),height:Xe(i.height,"recording.frame.height",{min:1})},l=Nr(n.cadenceProfiles,"recording.cadenceProfiles").map((o,a)=>{let p=mt(o,`recording.cadenceProfiles[${a}]`),h=Xe(p.intervalMs,`recording.cadenceProfiles[${a}].intervalMs`);return h>0||St(`recording.cadenceProfiles[${a}].intervalMs`,"must be positive"),{name:pr(p.name,`recording.cadenceProfiles[${a}].name`),intervalMs:h}}),d=Nr(n.scenes,"recording.scenes").map((o,a)=>{let p=`recording.scenes[${a}]`,h=mt(o,p),m=pr(h.class,`${p}.class`);gR.includes(m)||St(`${p}.class`,`unknown scene class "${m}"`);let g={id:pr(h.id,`${p}.id`),class:m,startMs:Xe(h.startMs,`${p}.startMs`),endMs:Xe(h.endMs,`${p}.endMs`)};if(g.endMs{let p=`recording.frames[${a}]`,h=mt(o,p),m=Xe(h.capturedAtMs,`${p}.capturedAtMs`);m{let T=`${p}.analysis.observations[${y}]`,S=mt(w,T);return{identity:pr(S.identity,`${T}.identity`),bounds:so(S.bounds,`${T}.bounds`)}})}}}),r=Nr(n.candidates,"recording.candidates").map((o,a)=>{let p=`recording.candidates[${a}]`,h=mt(o,p);return{key:pr(h.key,`${p}.key`),producedAtMs:Xe(h.producedAtMs,`${p}.producedAtMs`),arrivedAtMs:Xe(h.arrivedAtMs,`${p}.arrivedAtMs`),layout:bR(h.layout,`${p}.layout`)}});return{schema:gc,frame:u,cadenceProfiles:l,scenes:d,frames:s,candidates:r,problems:t}}function dS(e,t){return e.candidates.map((n,i)=>({c:n,i})).filter(({c:n})=>n.arrivedAtMs<=t).sort((n,i)=>n.c.arrivedAtMs-i.c.arrivedAtMs||n.i-i.i).map(({c:n})=>n)}function bc(e,t){let n=dS(e,t);return n.length>0?n[n.length-1]:null}function vR(e,t){if(!yc(t.clock))return null;let n=t.clock.streamTimeMs,i=null;for(let u of e.candidates)u.producedAtMs<=n&&(i===null||u.producedAtMs>i.producedAtMs)&&(i=u);return i}function yc(e){return e?.status==="ok"&&typeof e.streamTimeMs=="number"&&Number.isFinite(e.streamTimeMs)}function xR(e){let t=e.frames.filter(n=>yc(n.clock));return{frames:t,excluded:e.frames.length-t.length}}function $R(e,t){return e.scenes.find(n=>t>=n.startMs&&tu.residualPx<=Ls))return!1;let i=[n.region];for(let u of n.solves){if(!u.region)return!1;i.push(u.region)}for(let u=0;uLs||l>Ls)return!1}return!0}function cS(e){return{layoutAt:t=>bc(e,t)?.layout??null,windowIdentitiesAt:t=>IR(bc(e,t)?.layout??null)}}function IR(e){let t=new Set;for(let n of e?.cards??[])n.identity!==void 0&&t.add(n.identity);return t}function OR(e,t){let n=e.cadenceProfiles.find(p=>p.name===t.profile);if(!n)throw new Error(`no cadence profile "${t.profile}" in the recording`);let i={...t.config,intervalMs:n.intervalMs},u=new oo(i,{exclude:t.exclude}),l=t.scheduler(n.intervalMs),d=t.source??cS(e),c=[],s=[],r=null,o=1;e.frames.length>0&&u.reset(o,e.frames[0].capturedAtMs);let a=()=>{let p=r;r=null;let h=p.frame,m={generation:o,capturedAtMs:h.capturedAtMs,faces:h.analysis.faces,observations:h.analysis.observations,layout:d.layoutAt(h.capturedAtMs),windowIdentities:d.windowIdentitiesAt(h.capturedAtMs),frameAspect:e.frame.width/e.frame.height};u.analyze(m,p.endedAtMs),s.push({frameIndex:h.index,startedAtMs:p.startedAtMs,endedAtMs:p.endedAtMs,late:p.endedAtMs>p.startedAtMs+n.intervalMs})};for(let p of e.frames){let h=p.capturedAtMs;r&&r.endedAtMs<=h&&a(),l.framePresented(),!r&&l.due(h)&&(l.started(h),r={frame:p,startedAtMs:h,endedAtMs:h+p.analysis.durationMs},p.analysis.durationMs===0&&a()),c.push({frameIndex:p.index,atMs:h,result:u.tick(h)})}return r&&a(),{steps:c,analyses:s}}export{Ss as DEFAULT_ACCEPT,Rd as DEFAULT_DECODE,fs as DEFAULT_LETTERBOX,kP as DEFAULT_TILTED_RETRY,Ui as Detector,xs as EXECUTION_PROVIDERS,Vi as Embedder,Wi as EmbeddingRecognizer,lS as FIDUCIAL_POINTS,ro as FrameScheduler,ic as HOVER_MAX_AGE_MS,nT as HOVER_SELECTIONS,Tn as IdentityMap,Mr as LAYOUT_FIT_DEFAULTS,oo as LayoutRegistration,OC as MAX_ANALYSIS_WIDTH,EC as MIN_ANALYSIS_WIDTH,Fs as MONITOR_DEFAULTS,io as MismatchMonitor,pT as OUTLINE_MIN_TILT,er as PREPROCESSING,Zi as Pipeline,aS as RATIO_POOL_SIZE,to as ReleaseError,Ki as TemporalGate,Xi as Tracker,Cs as analysisSize,hC as analyzeFrame,Z$ as boxAverageRgb,As as cadenceMs,ac as captureFrame,wT as chooseLook,dR as classifyAccept,cR as classifyHitbox,yc as clockUsable,Qn as compatible,Ud as computeCardQuad,zs as correspondences,pR as coverage,tR as createSession,yT as cropRgba,z$ as decodeDetections,Zd as estimateTilt,hR as exitLatency,lR as fitError,oR as fitFrame,Bs as fitFrameDetail,$s as hoverAt,Kd as hoverCardsOf,oT as hoverOrder,qn as iou,bc as latestOffered,oS as layoutConfigError,Ns as layoutExtent,cr as layoutIoU,oP as letterboxBgr,Nd as letterboxGeometry,pC as loadRelease,rc as loadReleaseData,lr as lookAccepted,Cd as nonMaxSuppression,dS as offeredCandidates,fT as outlineFromTilt,Qd as outlineRect,Fd as parseBank,Hd as parseIdentityGroups,OT as parseRelease,tS as placementDistance,tT as pointInConvexQuad,vT as poolEmbeddings,Sn as project,_R as readLayoutRecording,ec as recognizeFrame,cS as recordingSource,Yd as rectFromAabb,OR as replayRecording,oc as replyRejection,hs as resizeBilinearRgb,qd as resolveHover,Vd as resolveHoveredCard,bs as rotateTensor90,hT as sampleRect,$R as sceneAt,Hi as selectHoverLayer,sS as suppressedInstances,_T as tiltedOrder,Jd as tiltedRects,xR as timedFrames,gs as toContractTensor,zd as toDetectorTensor,hc as toRegion,vR as truthCandidate,TR as truthUsable,cs as validBox}; /*! For license information please see cardvision.js.LEGAL.txt */ diff --git a/vendor/cardvision-browser/compute-session.js b/vendor/cardvision-browser/compute-session.js index a28e66a..a1ecdc3 100644 --- a/vendor/cardvision-browser/compute-session.js +++ b/vendor/cardvision-browser/compute-session.js @@ -1 +1 @@ -function _(t){return t==="wasm"?2e3:1e3}function ye(t){return t==="wasm"?1e3:500}function F(t,e){return e==="always-on"?_(t):ye(t)}var ge=250,be=250,Se=1e4,xe=5e3,ve=400,W=2e3;function z(t,e,r){return Math.abs(e-t)*1e3<=r}var we=250,K=5e3,X=15e3,G=[250,500,1e3,2e3];function H(t,e){return t===void 0?"stale-request":t.requestId<=e.lastAcceptedRequestId?"superseded":t.requestId!==e.inFlightRequestId?"stale-request":t.videoKey!==e.videoKey?"video-key":t.generation!==e.generation?"generation":null}function $(t){return t==="video-key"||t==="generation"}var T=class{constructor(e,r=3,i="always-on",n=e,o=null){this.intervalMs=e;this.confirmFrames=r;this.mode=i;this.readingIntervalMs=n;this.probeIntervalMs=o;this.checkProbe(i)}intervalMs;confirmFrames;mode;readingIntervalMs;probeIntervalMs;pending=!1;repeatsLeft=0;lastStartedAt=-1/0;pointerInside=!1;lastPointerAt=-1/0;tooltipShowing=!1;lastTooltipAt=-1/0;lastHoverTriggerAt=-1/0;lastVideoTimeSec=null;discontinuitySinceLast=!1;lastTriggerKind=null;lookRequested=!1;unanswered=0;retryAt=null;retryPrompt=!1;lastUnansweredCapture=!1;refused=!1;pointerAnalysis=!1;checkProbe(e){if(e==="layout"&&!(this.probeIntervalMs!==null&&this.probeIntervalMs>0))throw new Error("layout mode needs a positive probe interval")}setProbeIntervalMs(e){this.probeIntervalMs=e,this.checkProbe(this.mode)}setPointerAnalysis(e){this.pointerAnalysis=e}setIntervalMs(e){this.intervalMs=e}setReadingIntervalMs(e){this.readingIntervalMs=e}setTooltipShowing(e,r){this.tooltipShowing=e,e&&this.pointerInside&&(this.lastTooltipAt=r)}setMode(e){this.checkProbe(e),this.mode=e}get analysisMode(){return this.mode}framePresented(){this.pending=!0,this.repeatsLeft=0}discontinuity(){this.discontinuitySinceLast=!0,this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}requestLook(){this.discontinuitySinceLast=!0,this.pending=!0,this.repeatsLeft=0,this.lookRequested=!0}lookUnanswered(e,r={}){this.repeatsLeft=0,this.retryAt=e+G[Math.min(this.unanswered,G.length-1)],this.retryPrompt=r.prompt===!0,this.lastUnansweredCapture=r.prompt===!0,this.unanswered+=1}lookAnswered(){this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}lookRefused(){this.refused=!0}pictureReceived(){this.refused=!1,this.lastUnansweredCapture&&(this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1)}retryReady(e){return this.retryAt!==null&&e>=this.retryAt}get lookPending(){return this.lookRequested}pointerMoved(e){this.pointerInside=!0,this.lastPointerAt=e,(this.unanswered>0||this.refused)&&this.retryAt===null&&(this.retryAt=e,this.retryPrompt=!1)}pointerLeft(e){this.pointerInside&&(this.lastPointerAt=e),this.pointerInside=!1,this.lastTooltipAt=-1/0}tapped(e){this.lastPointerAt=e}pointerActive(e){return e-this.lastPointerAt=this.intervalInEffectMs(e):this.analysisState(e)==="probe"?!1:this.repeatsLeft>0&&r>=ge}staleFrameMs(e){return Math.max(ve,this.intervalInEffectMs(e))}frameStale(e,r){return this.lastVideoTimeSec===null||this.discontinuitySinceLast?!0:Math.abs(e-this.lastVideoTimeSec)*1e3>this.staleFrameMs(r)}hoverTriggerDue(e,r,i){let n=this.analysisState(e);return i||n==="idle"||n==="probe"||e-this.lastHoverTriggerAt0&&(this.repeatsLeft-=1)}get lastTrigger(){return this.lastTriggerKind}msSinceLastAnalysis(e){return this.lastStartedAt===-1/0?null:e-this.lastStartedAt}get idle(){return!this.pending&&this.repeatsLeft===0&&this.retryAt===null}};function Ae(t){let e=t.localWidth??t.bounds.width,r=t.localHeight??t.bounds.height,i=t.bounds.x+t.bounds.width/2,n=t.bounds.y+t.bounds.height/2;return{left:i-e/2,top:n-r/2,width:e,height:r}}function U(t,e){let r=Ae(t),i=(r.left+r.width/2)*e.width,n=(r.top+r.height/2)*e.height,o=r.width/2*e.width,s=r.height/2*e.height,l=t.rotation*Math.PI/180,a=Math.cos(l),u=Math.sin(l);return{points:[{x:-o,y:-s},{x:o,y:-s},{x:o,y:s},{x:-o,y:s}].map(({x:g,y:b})=>({x:i+g*a-b*u,y:n+g*u+b*a}))}}function ke(t,e){let{points:r}=e,i=0;for(let n=0;n0?1:-1;if(i===0)i=g;else if(g!==i)return!1}return!0}function Y(t,e){let r=null;for(let i of e)ke(t,i.quad)&&(!r||i.zIndex>=r.zIndex)&&(r=i);return r?r.card:null}function E(t){return t<0?0:t>1?1:t}function Z(t,e){let{frameWidth:r,frameHeight:i,names:n}=e;return t.map(o=>{let{aabb:s}=o,l=o.identity?n.get(o.identity):void 0,a=l!==void 0&&o.outline?o.outline:o.rect,u={instanceId:o.instanceId,bounds:{x:E(s.x/r),y:E(s.y/i),width:E(s.width/r),height:E(s.height/i)},rotation:(a.angle+45)%90-45,localWidth:E(a.w/r),localHeight:E(a.h/i),landscape:a.w>a.h,cardId:null,name:null};return o.identity&&l!==void 0&&(u.cardId=o.identity,u.name=l),u})}var Ie="accepted-nms";function Q(t){return t.width*t.height}function Re(t,e){let r=e==="accepted-nms"?t.kept:t.proposals.map((n,o)=>o),i=(n,o)=>{let s=t.proposals[n],l=t.proposals[o];if(e==="detector-score")return s.detectorScore!==l.detectorScore?s.detectorScore{let n=t.proposals[r];return{proposal:r,aabb:n.aabb,rect:n.rect,...n.outline?{outline:n.outline}:{},identity:n.accepted?n.displayId:null,score:n.score,zIndex:i+1}})}function ee(t,e,r,i=n=>n){return Z(t.map((o,s)=>({instanceId:e[s],aabb:o.aabb,rect:o.rect,...o.outline?{outline:o.outline}:{},identity:o.identity})),r).map((o,s)=>({...o,zIndex:t[s].zIndex,boxIndex:i(t[s].proposal)}))}var Ee={card:null,boxIndex:null,box:null,cardId:null,name:null};function te(t,e,r){let i=t.map(o=>({card:o,quad:U(o,r),zIndex:o.zIndex??0})),n=Y(e,i);return n?{card:n,boxIndex:n.boxIndex??null,box:{x:n.bounds.x*r.width,y:n.bounds.y*r.height,width:n.bounds.width*r.width,height:n.bounds.height*r.height},cardId:n.cardId,name:n.name}:Ee}function Te(t,e=t.hover.selection){let r=t.boxes.flatMap((a,u)=>a.face!==null?[u]:[]),i=r.map(a=>t.boxes[a]),n=new Map,o=i.map(a=>{let u=a.face;u.cardId!==null&&u.name!==null&&n.set(u.cardId,u.name);let p={x:a.box[0],y:a.box[1],width:a.box[2],height:a.box[3]};return{aabb:p,rect:{cx:p.x+p.width/2,cy:p.y+p.height/2,w:p.width,h:p.height,angle:0},score:u.similarity,detectorScore:a.score,accepted:u.cardId!==null,displayId:u.cardId??u.topId}}),s=i.flatMap((a,u)=>a.face.kept?[u]:[]),l=J({proposals:o,kept:s},e);return ee(l,l.map((a,u)=>`${e}_${u}`),{frameWidth:t.frame.width,frameHeight:t.frame.height,names:n},a=>r[a])}function B(t,e,r,i){let n=i===void 0||i===t.hover.selection?t.hover.cards:Te(t,i);return te(n,{x:e,y:r},t.frame)}var N=1,q=4096,P=40,Me=200,j=200,Ce=/^[0-9a-f]{16}$/,_e=/^[0-9a-f]{16}$/,v=t=>typeof t=="number"&&Number.isFinite(t),re=t=>v(t)&&t>=0&&t<=1,L=t=>Number.isSafeInteger(t)&&t>0,ne=(t,e=200)=>typeof t=="string"&&t.length>0&&t.length<=e,ie=L,oe=t=>Number.isInteger(t)&&t>=1&&t<=4096,se=t=>t===null?null:typeof t=="string"?t.slice(0,200):void 0;function Fe(t){return typeof ImageBitmap<"u"&&t instanceof ImageBitmap}function Le(t){let{width:e,height:r}=t;return Number.isInteger(e)&&Number.isInteger(r)&&e>0&&r>0&&e<=4096&&r<=4096}function ae(t){if(typeof t!="object"||t===null)return null;let e=t;return v(e.x)&&v(e.y)&&v(e.width)&&v(e.height)&&e.width>0&&e.height>0?{x:e.x,y:e.y,width:e.width,height:e.height}:null}function Pe(t){let{rotation:e,localWidth:r,localHeight:i}=t,n=o=>v(o)&&o>0&&o<=1;return v(e)&&e>-45&&e<=45&&n(r)&&n(i)?{rotation:e,localWidth:r,localHeight:i}:{}}var Oe=new Set(["kind","x","y","mediaTime","touch","newSource","requestId","bitmap","reason","retry","state","error","backend","analysisWidth","card","version","instance"]),We=/^[a-z][a-z0-9-]*$/;function He(t="cardvision"){if(typeof t!="string"||!We.test(t)||Oe.has(t))throw new TypeError(`computeProtocol: not a usable tag: ${String(t)}`);function e(o){if(typeof o!="object"||o===null)return null;let s=o;return s[t]===1&&typeof s.kind=="string"?s:null}function r(o){return Fe(o.bitmap)?L(o.requestId)&&v(o.mediaTime)&&Le(o.bitmap)?{kind:"frame",requestId:o.requestId,bitmap:o.bitmap,mediaTime:o.mediaTime}:(o.bitmap.close(),null):null}function i(o){let s=e(o);if(!s)return null;switch(s.kind){case"hello":return ie(s.version)?{kind:"hello",version:s.version}:null;case"pointer":return re(s.x)&&re(s.y)&&v(s.mediaTime)&&typeof s.touch=="boolean"?{kind:"pointer",x:s.x,y:s.y,mediaTime:s.mediaTime,touch:s.touch}:null;case"leave":return{kind:"leave"};case"presented":return v(s.mediaTime)?{kind:"presented",mediaTime:s.mediaTime}:null;case"discontinuity":return typeof s.newSource=="boolean"?{kind:"discontinuity",newSource:s.newSource}:null;case"cut":return{kind:"cut"};case"frame":return r(s);case"capture-failed":return L(s.requestId)&&typeof s.reason=="string"?{kind:"capture-failed",requestId:s.requestId,reason:s.reason.slice(0,200),retry:s.retry===!0}:null;default:return null}}function n(o){let s=e(o);if(!s)return null;switch(s.kind){case"ready":return ie(s.version)&&typeof s.instance=="string"&&_e.test(s.instance)?{kind:"ready",version:s.version,instance:s.instance}:null;case"status":{let l=se(s.error),a=se(s.backend);return(s.state==="loading"||s.state==="ready"||s.state==="failed")&&l!==void 0&&a!==void 0?{kind:"status",state:s.state,error:l,backend:a}:null}case"capture":{let l=s.analysisWidth;return L(s.requestId)&&typeof l=="object"&&l!==null&&oe(l.min)&&oe(l.max)&&l.max>=l.min?{kind:"capture",requestId:s.requestId,analysisWidth:{min:l.min,max:l.max}}:null}case"shown":{if(s.card===null)return{kind:"shown",card:null};let l=s.card,a=typeof l=="object"&&l!==null?ae(l.box):null;if(!(l&&ne(l.cardId)&&ne(l.name)&&a))return null;let u=Array.isArray(l.others)?l.others.slice(0,40).map(ae).filter(y=>y!==null):[],p=typeof l.releaseId=="string"&&Ce.test(l.releaseId)?l.releaseId:void 0;return{kind:"shown",card:{cardId:l.cardId,name:l.name,...p?{releaseId:p}:{},box:a,others:u,...Pe(l)}}}default:return null}}return{name:t,tag:o=>({...o,[t]:1}),parseComputeIn:i,parseComputeOut:n}}var le="busy";var Be=Object.freeze({misses:2,maxMs:5e3,sameBoxIou:.5});function Ne(t,e){return t==="loading"?{phase:e.phase,bytes:e.bytes}:void 0}function qe(t){if(!t||!Number.isFinite(t.rotation)||t.rotation===0)return{};let{rotation:e,localWidth:r,localHeight:i}=t;return e>-45&&e<=45&&r>0&&r<=1&&i>0&&i<=1?{rotation:e,localWidth:r,localHeight:i}:{}}function ue(t,e,r=40){return(t.hover?.cards??[]).map(i=>i.bounds).filter(i=>i&&!(Math.abs(i.x-e.x)<1e-6&&Math.abs(i.y-e.y)<1e-6&&Math.abs(i.width-e.width)<1e-6)).slice(0,r).map(i=>({x:i.x,y:i.y,width:i.width,height:i.height}))}var M=class{constructor(e,r={}){this.deps=e;this.mode=r.mode??"pointer",this.hold=r.hold??null,this.maxOtherBoxes=r.maxOtherBoxes??40,this.rotatedOutlines=r.rotatedOutlines===!0,this.hitTest=e.hoverAt??B,this.scheduler=new T(F(null,this.mode),3,this.mode,_(null)),this.st={state:"loading",error:null,release:null,backend:null,schedule:"idle",frames:0,lastWorkerMs:null,lastRoundTripMs:null,lastFrameError:null,geometric:r.geometric?{state:"loading",reason:null,bytes:null}:null,loading:null,tilted:null},this.lastStatusKey=this.statusKey()}deps;scheduler;mode;hold;maxOtherBoxes;rotatedOutlines;hitTest;st;cardList=[];analysisWidth={min:720,max:1920};maxAgeMs=W;nextRequestId=1;inFlight=null;lastAcceptedRequestId=0;analyzedSinceLoad=!1;generation=0;sourceCount=0;result=null;pointerAt=null;mediaTime=0;lastShownKey="null";lastStatusKey="";held=null;get videoKey(){return`source-${this.sourceCount}`}pointer(e,r,i,n=!1){if(this.st.state==="stopped")return;let o=this.deps.now();this.pointerAt={x:e,y:r},this.mediaTime=i,n?this.scheduler.tapped(o):this.scheduler.pointerMoved(o),this.st.state==="ready"&&this.scheduler.hoverTriggerDue(o,this.videoTime(),this.inFlight!==null)&&this.requestCapture("hover"),this.publish()}pointerLeft(){this.st.state!=="stopped"&&(this.pointerAt=null,this.scheduler.pointerLeft(this.deps.now()),this.publish())}presented(e){this.st.state!=="stopped"&&(this.mediaTime=e,this.scheduler.framePresented(),this.publish())}discontinuity(e){this.st.state!=="stopped"&&(this.generation+=1,e&&(this.sourceCount+=1),this.scheduler.discontinuity(),this.result=null,this.held=null,e&&this.scheduler.framePresented(),this.publish())}cut(){this.st.state!=="stopped"&&(this.generation+=1,this.result=null,this.held=null,this.scheduler.requestLook(),this.publish())}frame(e,r,i){let n=this.inFlight;if(this.st.state==="stopped"||!n||n.requestId!==e||n.analyzing){r.close();return}if(this.scheduler.pictureReceived(),n.generation!==this.generation||n.videoKey!==this.videoKey){this.inFlight=null,r.close(),this.publish();return}n.analyzing=!0;let o={requestId:n.requestId,mediaTimeSec:i,generation:n.generation,videoKey:n.videoKey};try{this.deps.toWorker({kind:"frame",bitmap:r,videoTimeSec:i,envelope:o,...this.rotatedOutlines?{rotatedOutlines:!0}:{}},[r])}catch(s){r.close(),this.inFlight=null,this.st.lastFrameError=`analysis-failed: ${String(s)}`,this.scheduler.lookUnanswered(this.deps.now())}this.publish()}captureFailed(e,r,i=!1){let n=this.inFlight;this.st.state==="stopped"||!n||n.requestId!==e||n.analyzing||(this.inFlight=null,this.st.lastFrameError=`capture-failed: ${r}`,i?this.scheduler.lookUnanswered(this.deps.now(),{prompt:!0}):this.scheduler.lookRefused(),this.publish())}fromWorker(e){if(this.st.state!=="stopped")switch(e.kind){case"geometric-status":this.st.geometric={state:e.state,reason:e.reason,bytes:e.bytes},this.deps.onGeometricStatus?.(e),this.publishStatus();return;case"tilted-status":this.st.tilted={state:"off",reason:e.reason},this.deps.onTiltedStatus?.(e),this.publishStatus();return;case"release-progress":{let r=Ne(this.st.state,e);r!==void 0&&(this.st.loading=r),this.publishStatus();return}case"release-status":this.st.state=e.ok?"ready":"failed",this.analyzedSinceLoad=!1,this.st.error=e.error,this.st.release=e.release,this.st.loading=null,this.st.tilted=e.release?.tiltedRetry?{state:"on",reason:null}:null,this.cardList=e.cards,e.release&&(this.st.backend=e.release.recognizer.ep,this.maxAgeMs=e.release.hoverMaxAgeMs,this.analysisWidth={...e.release.analysisWidth},this.scheduler.setIntervalMs(F(this.st.backend,this.mode)),this.scheduler.setReadingIntervalMs(_(this.st.backend)),this.scheduler.framePresented()),this.publish();return;case"frame-result":this.onFrameResult(e);return;default:return}}onFrameResult(e){let r=this.deps.now(),i=H(e.envelope,{inFlightRequestId:this.inFlight?.requestId??null,lastAcceptedRequestId:this.lastAcceptedRequestId,generation:this.generation,videoKey:this.videoKey});if(i!==null&&!$(i))return;let n=this.inFlight;if(this.inFlight=null,i!==null){this.publish();return}this.lastAcceptedRequestId=e.envelope.requestId,this.st.lastFrameError=e.error??null,this.st.lastWorkerMs=e.workerMs,this.st.lastRoundTripMs=+(r-n.sentAt).toFixed(2),e.analysis?(this.analyzedSinceLoad=!0,this.scheduler.lookAnswered(),this.st.frames+=1,this.result={analysis:e.analysis,videoTimeSec:e.videoTimeSec},this.deps.onAnalysis?.(e.analysis)):(this.result=null,e.error===le&&this.scheduler.lookUnanswered(r)),this.held&&this.pointerAt&&this.current()&&!this.fresh()&&(this.held.misses+=1),this.scheduler.setTooltipShowing(this.shown()!==null,r),this.publish()}tick(){if(this.st.state==="stopped")return;let e=this.deps.now(),r=this.analyzedSinceLoad?K:X;this.inFlight&&e-this.inFlight.sentAt>=r&&(this.inFlight=null,this.st.lastFrameError="no reply",this.scheduler.lookUnanswered(e)),this.scheduler.setTooltipShowing(this.shown()!==null,e),this.st.state==="ready"&&!this.inFlight&&this.scheduler.due(e)&&this.requestCapture(this.scheduler.lookPending?"cut":void 0),this.publish()}stop(){this.st.state!=="stopped"&&(this.st.state="stopped",this.st.loading=null,this.inFlight=null,this.result=null,this.held=null,this.pointerAt=null,this.publishShown(),this.publishStatus())}workerStopped(e){if(!(this.st.state==="stopped"||this.st.state==="failed")){if(this.inFlight=null,this.result=null,this.held=null,this.st.loading=null,this.publishShown(),"restart"in e){let r={kind:"geometric-status",state:"off",reason:"worker-restarted",bytes:null};this.st.geometric&&(this.st.geometric={state:r.state,reason:r.reason,bytes:r.bytes}),this.deps.onGeometricStatus?.(r),this.st.state="loading",this.analyzedSinceLoad=!1,this.st.error=null}else this.st.state="failed",this.st.error=e.error;this.publishStatus()}}reloading(e){this.st.state==="loading"&&(this.st.geometric=e.geometric?{state:"loading",reason:null,bytes:null}:null,this.st.loading=null,this.publishStatus())}requestCapture(e){if(this.st.state!=="ready"||this.inFlight)return;let r=this.deps.now(),i=this.nextRequestId++;this.inFlight={requestId:i,sentAt:r,generation:this.generation,videoKey:this.videoKey,analyzing:!1},this.scheduler.started(r,{videoTimeSec:this.videoTime(),...e?{trigger:e}:{}}),this.deps.capture(i,{...this.analysisWidth})}status(){return{...this.st,schedule:this.scheduler.analysisState(this.deps.now())}}analysis(){return this.current()?.analysis??null}cards(){return this.cardList}hitAt(e,r){let i=this.current();if(!i)return null;let{width:n,height:o}=i.analysis.frame;if(!(n>0&&o>0))return null;let s=e*n,l=r*o;if(!Number.isFinite(s)||!Number.isFinite(l))return null;let a=this.hitTest(i.analysis,s,l);if(!a.box||a.cardId===null||a.name===null)return null;let u={x:a.box.x/n,y:a.box.y/o,width:a.box.width/n,height:a.box.height/o},p={x:a.box.x,y:a.box.y,width:a.box.width,height:a.box.height};return{cardId:a.cardId,name:a.name,box:u,frameBox:p,others:ue(i.analysis,u,this.maxOtherBoxes),...qe(a.card)}}fresh(){return this.pointerAt?this.hitAt(this.pointerAt.x,this.pointerAt.y):null}shown(){let e=this.fresh(),r=this.hold;if(!r)return e;let i=this.deps.now();if(e)return this.held={card:e,misses:0,seenAt:i},e;let n=this.held;return!n||!this.pointerAt||!De(n.card.box,this.pointerAt)?(this.held=null,null):this.boxAtPointer(n.card.box,r.sameBoxIou)==="other"||n.misses>=r.misses||i-n.seenAt>=r.maxMs?(this.held=null,null):n.card}current(){let e=this.result;return e&&z(e.videoTimeSec,this.videoTime(),this.maxAgeMs)?e:null}videoTime(){return this.deps.mediaTimeNow?this.deps.mediaTimeNow():this.mediaTime}boxAtPointer(e,r){let i=this.current();if(!i||!this.pointerAt)return"unknown";let{width:n,height:o}=i.analysis.frame;if(!(n>0&&o>0))return"unknown";let s=this.pointerAt.x*n,l=this.pointerAt.y*o,a={x:e.x*n,y:e.y*o,width:e.width*n,height:e.height*o},u=0,p=!1;for(let y of i.analysis.boxes??[]){let[g,b,w,k]=y.box;sg+w||lb+k||(p=!0,u=Math.max(u,je(a,{x:g,y:b,width:w,height:k})))}return p?u>=r?"same":"other":"none"}publish(){this.publishShown(),this.publishStatus()}publishShown(){let e=this.shown(),r=e?`${e.cardId}|${e.box.x}|${e.box.y}|${e.box.width}|${e.box.height}|${e.rotation??""}|${e.localWidth??""}|${e.localHeight??""}`:"null";r!==this.lastShownKey&&(this.lastShownKey=r,this.deps.onShown?.(e))}statusKey(){let e=this.status();return JSON.stringify({...e,release:e.release?e.release.id:null})}publishStatus(){let e=this.statusKey();e!==this.lastStatusKey&&(this.lastStatusKey=e,this.deps.onStatus?.(this.status()))}};function je(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),i=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);if(r<=0||i<=0)return 0;let n=r*i;return n/(t.width*t.height+e.width*e.height-n)}function De(t,e){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}var vt=1440*60*1e3;var Ve=[/^the worker did not start/,/^unexpected error while loading/];function de(t,e){return e||t.startsWith("unexpected:")?!1:!Ve.some(r=>r.test(t))}var ce=1;function he(t){let{geometricUrl:e,geometricManifestSha256:r,geometricWatchdog:i,...n}=t;return n}function D(t){let e=null,r=null,i=0,n=!1,o=null,s=!1,l=null,a={source:t.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},u=c=>{t.onDecision?.({reused:0,downloaded:0,ms:0,...c})},p=c=>new M({now:t.now,toWorker:(h,f)=>e?.postMessage(h,f??[]),capture:t.capture,...t.onShown?{onShown:t.onShown}:{},...t.onStatus?{onStatus:t.onStatus}:{},...t.onAnalysis?{onAnalysis:t.onAnalysis}:{},...t.onGeometricStatus?{onGeometricStatus:t.onGeometricStatus}:{},...t.hoverAt?{hoverAt:t.hoverAt}:{},...t.mediaTimeNow?{mediaTimeNow:t.mediaTimeNow}:{}},{...t.mode?{mode:t.mode}:{},...t.hold?{hold:t.hold}:{},...t.rotatedOutlines?{rotatedOutlines:!0}:{},geometric:c.geometricUrl!==void 0}),y=c=>{n||!r||(o&&c.kind==="release-progress"&&c.phase==="preparing"&&(s=!0),!(c.kind==="release-status"&&(r.status().state!=="loading"||o&&!b(c)))&&(c.kind==="release-status"&&!c.ok&&g(),r.fromWorker(c)))},g=()=>{n=!0,o=null,e?.terminate(),e=null},b=c=>{let h=o;if(c.ok&&c.release?.id===h.pointer.id)return o=null,l=h.pointer.id,a.source="remote",a.id=h.pointer.id,a.reason="ok",a.table=h.facts,u({source:"remote",reason:"ok",pointer:h.pointer.id,reused:h.reused,downloaded:h.downloaded,ms:h.ms}),!0;if(c.ok)return t.recordSkip?.(h.pointer,"id-mismatch"),w("id-mismatch"),!1;let f=c.error??"no reason given";return de(f,s)&&t.recordSkip?.(h.pointer,`runtime:${f.slice(0,120)}`),w(`runtime:${f}`),!1},w=c=>{let h=o;o=null,e?.terminate(),a.source="bundled",a.id=null,a.reason=c,a.table=null,u({source:"bundled",reason:c,pointer:h.pointer.id,reused:h.reused,downloaded:h.downloaded,ms:h.ms});let f=h.fallback??t.loadRequest;r?.reloading({geometric:f.geometricUrl!==void 0}),I(f)},k=c=>{if(n||!r)return;let h=r.status().state;if(h==="failed"||h==="stopped")return;let f=c.message||"see the console";if(o){b({kind:"release-status",ok:!1,error:`the worker did not start (${f})`,release:null,cards:[]});return}if(e?.terminate(),h==="loading"&&i===0){g(),r.workerStopped({error:`the worker did not start (${f})`});return}if(i{let h=t.createWorker();h.onmessage=f=>{h===e&&y(f.data)},h.onerror=f=>{h===e&&k(f)},e=h,h.postMessage(c)},I=c=>{r??=p(c);try{C(c)}catch(h){e=null,o=null,n=!0,r.workerStopped({error:`the recognition worker could not start (${String(h)})`})}};return t.chooseRelease?t.chooseRelease({onDownloading:()=>t.onDownloading?.()}).catch(c=>({source:"bundled",reason:`unexpected:${String(c)}`,pointer:null,downloaded:0,ms:0})).then(c=>{if(!n){if(c.source==="remote"){o=c,s=!1,I(c.request);return}a.source="bundled",a.reason=c.reason,u({source:"bundled",reason:c.reason,pointer:c.pointer?.id??null,downloaded:c.downloaded,ms:c.ms}),I(c.request??t.loadRequest)}}):I(t.loadRequest),{get core(){return r},get stopped(){return n},get restarts(){return i},get release(){return{...a}},tick(){n||r?.tick()},stop(){n=!0,o=null,e?.terminate(),e=null,r?.stop()}}}var Ge=/^[0-9a-f]{16}$/;function ze(){let t=crypto.getRandomValues(new Uint8Array(8));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function Ke(t){let e=t.parentOrigin;if(!t.framed||e===null||!t.allowedParentOrigin(e))return null;let{win:r,protocol:i}=t,n=(t.instanceId??ze)();if(typeof n!="string"||!Ge.test(n))throw new TypeError(`startComputeFrame: not an instance id: ${String(n)}`);let o=d=>r.parent.postMessage(i.tag(d),e),s=()=>o({kind:"ready",version:1,instance:n}),l=!1,a=()=>{l||(l=!0,s())},u={state:"loading",error:null,backend:null},p=d=>d===null?null:d.slice(0,200),y=(d,m,S,R=!1)=>{let A={state:d,error:p(m),backend:p(S)};!R&&A.state===u.state&&A.error===u.error&&A.backend===u.backend||(u=A,o({kind:"status",...A}))},g=d=>{d.state!=="stopped"&&y(d.state,d.error,d.state==="ready"?d.backend:null)},b=null,w=()=>b?.release??{source:t.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},k=null,C=d=>{k=d,t.onShown?.(d,w()),o({kind:"shown",card:d})},I=d=>{let m=w(),S=d?{cardId:d.cardId,name:d.name,...m.source==="remote"&&m.id!==null?{releaseId:m.id}:{},box:{...d.box},others:d.others.map(R=>({...R})),...d.rotation!==void 0&&d.localWidth!==void 0&&d.localHeight!==void 0?{rotation:d.rotation,localWidth:d.localWidth,localHeight:d.localHeight}:{}}:null;C(S)},{win:c,framed:h,parentOrigin:f,allowedParentOrigin:$e,protocol:Ue,onShown:Ye,instanceId:Ze,...pe}=t,x=D({...pe,createWorker:()=>(a(),t.createWorker()),capture:(d,m)=>{let S=Math.min(m.max,4096);o({kind:"capture",requestId:d,analysisWidth:{min:Math.min(m.min,S),max:S}})},onShown:I,onStatus:g,onDownloading:()=>{y("loading",null,null,!0),t.onDownloading?.()}});b=x,x.core&&a();let me=()=>{s(),y(u.state,u.error,u.backend,!0),C(k)},fe=(d,m)=>{switch(m.kind){case"pointer":d.pointer(m.x,m.y,m.mediaTime,m.touch);return;case"leave":d.pointerLeft();return;case"presented":d.presented(m.mediaTime);return;case"discontinuity":d.discontinuity(m.newSource);return;case"cut":d.cut();return;case"frame":d.frame(m.requestId,m.bitmap,m.mediaTime);return;case"capture-failed":d.captureFailed(m.requestId,m.reason,m.retry===!0);return}},V=d=>{let S=d.source===r.parent&&d.origin===e?i.parseComputeIn(d.data):null,R=x.core,A=null;try{S?.kind==="hello"?R&&me():S&&R&&!x.stopped&&(S.kind==="frame"&&(A=S.bitmap),fe(R,S))}finally{Xe(d.data,A)}};return r.addEventListener("message",V),{get core(){return x.core},get stopped(){return x.stopped},get restarts(){return x.restarts},get release(){return x.release},instance:n,tick(){x.tick()},stop(){r.removeEventListener("message",V),x.stop()}}}function Xe(t,e){if(!(typeof ImageBitmap>"u"||typeof t!="object"||t===null))for(let r of Object.values(t))r!==e&&r instanceof ImageBitmap&&r.close()}export{be as DRIVER_TICK_MS,T as FrameScheduler,W as HOVER_MAX_AGE_MS,q as MAX_FRAME_SIDE,P as MAX_OTHER_BOXES,Me as MAX_REASON_LENGTH,j as MAX_TEXT_LENGTH,N as PROTOCOL_VERSION,Be as SHOWN_HOLD,M as SessionCore,ce as WORKER_RESTARTS,F as cadenceMs,He as computeProtocol,D as createWorkerSession,B as hoverAt,ue as neighborBoxes,he as plainLoad,H as replyRejection,Ke as startComputeFrame}; +var ke=250,N=250,Ie=1e4,B=5e3,Re=400,q=2e3;function Y(t,e,r){return Math.abs(e-t)*1e3<=r}var Ee=250,Q=5e3,Z=15e3,U=[250,500,1e3,2e3];function D(t,e){return t===void 0?"stale-request":t.requestId<=e.lastAcceptedRequestId?"superseded":t.requestId!==e.inFlightRequestId?"stale-request":t.videoKey!==e.videoKey?"video-key":t.generation!==e.generation?"generation":null}function J(t){return t==="video-key"||t==="generation"}var T=class{constructor(e,r=3,i="always-on",n=e,s=null){this.intervalMs=e;this.confirmFrames=r;this.mode=i;this.readingIntervalMs=n;this.probeIntervalMs=s;this.checkProbe(i)}intervalMs;confirmFrames;mode;readingIntervalMs;probeIntervalMs;pending=!1;repeatsLeft=0;lastStartedAt=-1/0;pointerInside=!1;lastPointerAt=-1/0;tooltipShowing=!1;lastTooltipAt=-1/0;lastHoverTriggerAt=-1/0;lastVideoTimeSec=null;discontinuitySinceLast=!1;lastTriggerKind=null;lookRequested=!1;unanswered=0;retryAt=null;retryPrompt=!1;lastUnansweredCapture=!1;refused=!1;pointerAnalysis=!1;checkProbe(e){if(e==="layout"&&!(this.probeIntervalMs!==null&&this.probeIntervalMs>0))throw new Error("layout mode needs a positive probe interval")}setProbeIntervalMs(e){this.probeIntervalMs=e,this.checkProbe(this.mode)}setPointerAnalysis(e){this.pointerAnalysis=e}setIntervalMs(e){this.intervalMs=e}setReadingIntervalMs(e){this.readingIntervalMs=e}setTooltipShowing(e,r){this.tooltipShowing=e,e&&this.pointerInside&&(this.lastTooltipAt=r)}setMode(e){this.checkProbe(e),this.mode=e}get analysisMode(){return this.mode}framePresented(){this.pending=!0,this.repeatsLeft=0}discontinuity(){this.discontinuitySinceLast=!0,this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}requestLook(){this.discontinuitySinceLast=!0,this.pending=!0,this.repeatsLeft=0,this.lookRequested=!0}lookUnanswered(e,r={}){this.repeatsLeft=0,this.retryAt=e+U[Math.min(this.unanswered,U.length-1)],this.retryPrompt=r.prompt===!0,this.lastUnansweredCapture=r.prompt===!0,this.unanswered+=1}lookAnswered(){this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1,this.refused=!1}lookRefused(){this.refused=!0}pictureReceived(){this.refused=!1,this.lastUnansweredCapture&&(this.unanswered=0,this.retryAt=null,this.lastUnansweredCapture=!1)}retryReady(e){return this.retryAt!==null&&e>=this.retryAt}get lookPending(){return this.lookRequested}pointerMoved(e){this.pointerInside=!0,this.lastPointerAt=e,(this.unanswered>0||this.refused)&&this.retryAt===null&&(this.retryAt=e,this.retryPrompt=!1)}pointerLeft(e){this.pointerInside&&(this.lastPointerAt=e),this.pointerInside=!1,this.lastTooltipAt=-1/0}tapped(e){this.lastPointerAt=e}pointerActive(e){return e-this.lastPointerAt=this.intervalInEffectMs(e):this.analysisState(e)==="probe"?!1:this.repeatsLeft>0&&r>=ke}staleFrameMs(e){return Math.max(Re,this.intervalInEffectMs(e))}frameStale(e,r){return this.lastVideoTimeSec===null||this.discontinuitySinceLast?!0:Math.abs(e-this.lastVideoTimeSec)*1e3>this.staleFrameMs(r)}hoverTriggerDue(e,r,i){let n=this.analysisState(e);return i||n==="idle"||n==="probe"||e-this.lastHoverTriggerAt0&&(this.repeatsLeft-=1)}get lastTrigger(){return this.lastTriggerKind}msSinceLastAnalysis(e){return this.lastStartedAt===-1/0?null:e-this.lastStartedAt}get idle(){return!this.pending&&this.repeatsLeft===0&&this.retryAt===null}};var Me=1e3,Te=2e3,Ce=500,_e=1e3;function E(t){return t==="wasm"?Te:Me}function te(t){return t==="wasm"?_e:Ce}function F(t,e){return e==="always-on"?E(t):te(t)}var ee=.25,Pe=4e3,Fe=8e3;function Oe(t){return t+B-N}var Le=3,re=5;function O(t){if(t===void 0||t===!1)return null;if(t!==!0&&(typeof t!="object"||t===null))throw new RangeError("measuredPacing must be a boolean or an object with a share");let e=t===!0?ee:t.share??ee;if(!(e>0&&e<=1))throw new RangeError("measuredPacing.share must be above 0 and at most 1");return e}function We(t){let e=t.slice(-re).sort((i,n)=>i-n),r=e.length>>1;return e.length%2===1?e[r]:(e[r-1]+e[r])/2}function j(t,e,r,i){return r.lengthre&&this.times.shift())}intervalMs(e,r){return r==="always-on"?this.slowMs(e):this.activeMs(e)}readingMs(e,r){return j(E(e),Oe(r),this.times,this.share)}activeMs(e){return j(te(e),Pe,this.times,this.share)}slowMs(e){return j(E(e),Fe,this.times,this.share)}};function He(t){let e=t.localWidth??t.bounds.width,r=t.localHeight??t.bounds.height,i=t.bounds.x+t.bounds.width/2,n=t.bounds.y+t.bounds.height/2;return{left:i-e/2,top:n-r/2,width:e,height:r}}function ne(t,e){let r=He(t),i=(r.left+r.width/2)*e.width,n=(r.top+r.height/2)*e.height,s=r.width/2*e.width,o=r.height/2*e.height,l=t.rotation*Math.PI/180,a=Math.cos(l),u=Math.sin(l);return{points:[{x:-s,y:-o},{x:s,y:-o},{x:s,y:o},{x:-s,y:o}].map(({x:g,y:b})=>({x:i+g*a-b*u,y:n+g*u+b*a}))}}function Ne(t,e){let{points:r}=e,i=0;for(let n=0;n0?1:-1;if(i===0)i=g;else if(g!==i)return!1}return!0}function ie(t,e){let r=null;for(let i of e)Ne(t,i.quad)&&(!r||i.zIndex>=r.zIndex)&&(r=i);return r?r.card:null}function M(t){return t<0?0:t>1?1:t}function se(t,e){let{frameWidth:r,frameHeight:i,names:n}=e;return t.map(s=>{let{aabb:o}=s,l=s.identity?n.get(s.identity):void 0,a=l!==void 0&&s.outline?s.outline:s.rect,u={instanceId:s.instanceId,bounds:{x:M(o.x/r),y:M(o.y/i),width:M(o.width/r),height:M(o.height/i)},rotation:(a.angle+45)%90-45,localWidth:M(a.w/r),localHeight:M(a.h/i),landscape:a.w>a.h,cardId:null,name:null};return s.identity&&l!==void 0&&(u.cardId=s.identity,u.name=l),u})}var Be="accepted-nms";function oe(t){return t.width*t.height}function qe(t,e){let r=e==="accepted-nms"?t.kept:t.proposals.map((n,s)=>s),i=(n,s)=>{let o=t.proposals[n],l=t.proposals[s];if(e==="detector-score")return o.detectorScore!==l.detectorScore?o.detectorScore{let n=t.proposals[r];return{proposal:r,aabb:n.aabb,rect:n.rect,...n.outline?{outline:n.outline}:{},identity:n.accepted?n.displayId:null,score:n.score,zIndex:i+1}})}function le(t,e,r,i=n=>n){return se(t.map((s,o)=>({instanceId:e[o],aabb:s.aabb,rect:s.rect,...s.outline?{outline:s.outline}:{},identity:s.identity})),r).map((s,o)=>({...s,zIndex:t[o].zIndex,boxIndex:i(t[o].proposal)}))}var De={card:null,boxIndex:null,box:null,cardId:null,name:null};function ue(t,e,r){let i=t.map(s=>({card:s,quad:ne(s,r),zIndex:s.zIndex??0})),n=ie(e,i);return n?{card:n,boxIndex:n.boxIndex??null,box:{x:n.bounds.x*r.width,y:n.bounds.y*r.height,width:n.bounds.width*r.width,height:n.bounds.height*r.height},cardId:n.cardId,name:n.name}:De}function je(t,e=t.hover.selection){let r=t.boxes.flatMap((a,u)=>a.face!==null?[u]:[]),i=r.map(a=>t.boxes[a]),n=new Map,s=i.map(a=>{let u=a.face;u.cardId!==null&&u.name!==null&&n.set(u.cardId,u.name);let p={x:a.box[0],y:a.box[1],width:a.box[2],height:a.box[3]};return{aabb:p,rect:{cx:p.x+p.width/2,cy:p.y+p.height/2,w:p.width,h:p.height,angle:0},score:u.similarity,detectorScore:a.score,accepted:u.cardId!==null,displayId:u.cardId??u.topId}}),o=i.flatMap((a,u)=>a.face.kept?[u]:[]),l=ae({proposals:s,kept:o},e);return le(l,l.map((a,u)=>`${e}_${u}`),{frameWidth:t.frame.width,frameHeight:t.frame.height,names:n},a=>r[a])}function G(t,e,r,i){let n=i===void 0||i===t.hover.selection?t.hover.cards:je(t,i);return ue(n,{x:e,y:r},t.frame)}var V=1,z=4096,W=40,Ge=200,K=200,Ve=/^[0-9a-f]{16}$/,ze=/^[0-9a-f]{16}$/,v=t=>typeof t=="number"&&Number.isFinite(t),de=t=>v(t)&&t>=0&&t<=1,L=t=>Number.isSafeInteger(t)&&t>0,ce=(t,e=200)=>typeof t=="string"&&t.length>0&&t.length<=e,he=L,pe=t=>Number.isInteger(t)&&t>=1&&t<=4096,me=t=>t===null?null:typeof t=="string"?t.slice(0,200):void 0;function Ke(t){return typeof ImageBitmap<"u"&&t instanceof ImageBitmap}function Xe(t){let{width:e,height:r}=t;return Number.isInteger(e)&&Number.isInteger(r)&&e>0&&r>0&&e<=4096&&r<=4096}function fe(t){if(typeof t!="object"||t===null)return null;let e=t;return v(e.x)&&v(e.y)&&v(e.width)&&v(e.height)&&e.width>0&&e.height>0?{x:e.x,y:e.y,width:e.width,height:e.height}:null}function $e(t){let{rotation:e,localWidth:r,localHeight:i}=t,n=s=>v(s)&&s>0&&s<=1;return v(e)&&e>-45&&e<=45&&n(r)&&n(i)?{rotation:e,localWidth:r,localHeight:i}:{}}var Ue=new Set(["kind","x","y","mediaTime","touch","newSource","requestId","bitmap","reason","retry","state","error","backend","analysisWidth","card","version","instance"]),Ye=/^[a-z][a-z0-9-]*$/;function Qe(t="cardvision"){if(typeof t!="string"||!Ye.test(t)||Ue.has(t))throw new TypeError(`computeProtocol: not a usable tag: ${String(t)}`);function e(s){if(typeof s!="object"||s===null)return null;let o=s;return o[t]===1&&typeof o.kind=="string"?o:null}function r(s){return Ke(s.bitmap)?L(s.requestId)&&v(s.mediaTime)&&Xe(s.bitmap)?{kind:"frame",requestId:s.requestId,bitmap:s.bitmap,mediaTime:s.mediaTime}:(s.bitmap.close(),null):null}function i(s){let o=e(s);if(!o)return null;switch(o.kind){case"hello":return he(o.version)?{kind:"hello",version:o.version}:null;case"pointer":return de(o.x)&&de(o.y)&&v(o.mediaTime)&&typeof o.touch=="boolean"?{kind:"pointer",x:o.x,y:o.y,mediaTime:o.mediaTime,touch:o.touch}:null;case"leave":return{kind:"leave"};case"presented":return v(o.mediaTime)?{kind:"presented",mediaTime:o.mediaTime}:null;case"discontinuity":return typeof o.newSource=="boolean"?{kind:"discontinuity",newSource:o.newSource}:null;case"cut":return{kind:"cut"};case"frame":return r(o);case"capture-failed":return L(o.requestId)&&typeof o.reason=="string"?{kind:"capture-failed",requestId:o.requestId,reason:o.reason.slice(0,200),retry:o.retry===!0}:null;default:return null}}function n(s){let o=e(s);if(!o)return null;switch(o.kind){case"ready":return he(o.version)&&typeof o.instance=="string"&&ze.test(o.instance)?{kind:"ready",version:o.version,instance:o.instance}:null;case"status":{let l=me(o.error),a=me(o.backend);return(o.state==="loading"||o.state==="ready"||o.state==="failed")&&l!==void 0&&a!==void 0?{kind:"status",state:o.state,error:l,backend:a}:null}case"capture":{let l=o.analysisWidth;return L(o.requestId)&&typeof l=="object"&&l!==null&&pe(l.min)&&pe(l.max)&&l.max>=l.min?{kind:"capture",requestId:o.requestId,analysisWidth:{min:l.min,max:l.max}}:null}case"shown":{if(o.card===null)return{kind:"shown",card:null};let l=o.card,a=typeof l=="object"&&l!==null?fe(l.box):null;if(!(l&&ce(l.cardId)&&ce(l.name)&&a))return null;let u=Array.isArray(l.others)?l.others.slice(0,40).map(fe).filter(y=>y!==null):[],p=typeof l.releaseId=="string"&&Ve.test(l.releaseId)?l.releaseId:void 0;return{kind:"shown",card:{cardId:l.cardId,name:l.name,...p?{releaseId:p}:{},box:a,others:u,...$e(l)}}}default:return null}}return{name:t,tag:s=>({...s,[t]:1}),parseComputeIn:i,parseComputeOut:n}}var ye="busy";var Ze=Object.freeze({misses:2,maxMs:5e3,sameBoxIou:.5});function Je(t,e){return t==="loading"?{phase:e.phase,bytes:e.bytes}:void 0}function et(t){if(!t||!Number.isFinite(t.rotation)||t.rotation===0)return{};let{rotation:e,localWidth:r,localHeight:i}=t;return e>-45&&e<=45&&r>0&&r<=1&&i>0&&i<=1?{rotation:e,localWidth:r,localHeight:i}:{}}function ge(t,e,r=40){return(t.hover?.cards??[]).map(i=>i.bounds).filter(i=>i&&!(Math.abs(i.x-e.x)<1e-6&&Math.abs(i.y-e.y)<1e-6&&Math.abs(i.width-e.width)<1e-6)).slice(0,r).map(i=>({x:i.x,y:i.y,width:i.width,height:i.height}))}var C=class{constructor(e,r={}){this.deps=e;this.mode=r.mode??"pointer",this.hold=r.hold??null,this.maxOtherBoxes=r.maxOtherBoxes??40,this.rotatedOutlines=r.rotatedOutlines===!0,this.hitTest=e.hoverAt??G;let i=O(r.measuredPacing);this.pacer=i===null?null:new P(i),this.scheduler=new T(F(null,this.mode),3,this.mode,E(null)),this.st={state:"loading",error:null,release:null,backend:null,schedule:"idle",frames:0,lastWorkerMs:null,lastRoundTripMs:null,lastFrameError:null,geometric:r.geometric?{state:"loading",reason:null,bytes:null}:null,loading:null,tilted:null},this.lastStatusKey=this.statusKey()}deps;scheduler;mode;hold;maxOtherBoxes;rotatedOutlines;hitTest;pacer;st;cardList=[];analysisWidth={min:720,max:1920};maxAgeMs=q;nextRequestId=1;inFlight=null;lastAcceptedRequestId=0;analyzedSinceLoad=!1;generation=0;sourceCount=0;result=null;pointerAt=null;mediaTime=0;lastShownKey="null";lastStatusKey="";held=null;get videoKey(){return`source-${this.sourceCount}`}pointer(e,r,i,n=!1){if(this.st.state==="stopped")return;let s=this.deps.now();this.pointerAt={x:e,y:r},this.mediaTime=i,n?this.scheduler.tapped(s):this.scheduler.pointerMoved(s),this.st.state==="ready"&&this.scheduler.hoverTriggerDue(s,this.videoTime(),this.inFlight!==null)&&this.requestCapture("hover"),this.publish()}pointerLeft(){this.st.state!=="stopped"&&(this.pointerAt=null,this.scheduler.pointerLeft(this.deps.now()),this.publish())}presented(e){this.st.state!=="stopped"&&(this.mediaTime=e,this.scheduler.framePresented(),this.publish())}discontinuity(e){this.st.state!=="stopped"&&(this.generation+=1,e&&(this.sourceCount+=1),this.scheduler.discontinuity(),this.result=null,this.held=null,e&&this.scheduler.framePresented(),this.publish())}cut(){this.st.state!=="stopped"&&(this.generation+=1,this.result=null,this.held=null,this.scheduler.requestLook(),this.publish())}frame(e,r,i){let n=this.inFlight;if(this.st.state==="stopped"||!n||n.requestId!==e||n.analyzing){r.close();return}if(this.scheduler.pictureReceived(),n.generation!==this.generation||n.videoKey!==this.videoKey){this.inFlight=null,r.close(),this.publish();return}n.analyzing=!0;let s={requestId:n.requestId,mediaTimeSec:i,generation:n.generation,videoKey:n.videoKey};try{this.deps.toWorker({kind:"frame",bitmap:r,videoTimeSec:i,envelope:s,...this.rotatedOutlines?{rotatedOutlines:!0}:{}},[r])}catch(o){r.close(),this.inFlight=null,this.st.lastFrameError=`analysis-failed: ${String(o)}`,this.scheduler.lookUnanswered(this.deps.now())}this.publish()}captureFailed(e,r,i=!1){let n=this.inFlight;this.st.state==="stopped"||!n||n.requestId!==e||n.analyzing||(this.inFlight=null,this.st.lastFrameError=`capture-failed: ${r}`,i?this.scheduler.lookUnanswered(this.deps.now(),{prompt:!0}):this.scheduler.lookRefused(),this.publish())}fromWorker(e){if(this.st.state!=="stopped")switch(e.kind){case"geometric-status":this.st.geometric={state:e.state,reason:e.reason,bytes:e.bytes},this.deps.onGeometricStatus?.(e),this.publishStatus();return;case"tilted-status":this.st.tilted={state:"off",reason:e.reason},this.deps.onTiltedStatus?.(e),this.publishStatus();return;case"release-progress":{let r=Je(this.st.state,e);r!==void 0&&(this.st.loading=r),this.publishStatus();return}case"release-status":this.st.state=e.ok?"ready":"failed",this.analyzedSinceLoad=!1,this.st.error=e.error,this.st.release=e.release,this.st.loading=null,this.st.tilted=e.release?.tiltedRetry?{state:"on",reason:null}:null,this.cardList=e.cards,e.release&&(this.st.backend=e.release.recognizer.ep,this.maxAgeMs=e.release.hoverMaxAgeMs,this.analysisWidth={...e.release.analysisWidth},this.applyCadence(),this.scheduler.framePresented()),this.publish();return;case"frame-result":this.onFrameResult(e);return;default:return}}applyCadence(){let e=this.st.backend;this.scheduler.setIntervalMs(this.pacer?this.pacer.intervalMs(e,this.mode):F(e,this.mode)),this.scheduler.setReadingIntervalMs(this.pacer?this.pacer.readingMs(e,this.maxAgeMs):E(e))}onFrameResult(e){let r=this.deps.now(),i=D(e.envelope,{inFlightRequestId:this.inFlight?.requestId??null,lastAcceptedRequestId:this.lastAcceptedRequestId,generation:this.generation,videoKey:this.videoKey});if(i!==null&&!J(i))return;let n=this.inFlight;if(this.inFlight=null,i!==null){this.publish();return}this.lastAcceptedRequestId=e.envelope.requestId,this.st.lastFrameError=e.error??null,this.st.lastWorkerMs=e.workerMs,this.st.lastRoundTripMs=+(r-n.sentAt).toFixed(2),e.analysis?(this.analyzedSinceLoad=!0,this.pacer&&(this.pacer.record(e.workerMs),this.applyCadence()),this.scheduler.lookAnswered(),this.st.frames+=1,this.result={analysis:e.analysis,videoTimeSec:e.videoTimeSec},this.deps.onAnalysis?.(e.analysis)):(this.result=null,e.error===ye&&this.scheduler.lookUnanswered(r)),this.held&&this.pointerAt&&this.current()&&!this.fresh()&&(this.held.misses+=1),this.scheduler.setTooltipShowing(this.shown()!==null,r),this.publish()}tick(){if(this.st.state==="stopped")return;let e=this.deps.now(),r=this.analyzedSinceLoad?Q:Z;this.inFlight&&e-this.inFlight.sentAt>=r&&(this.inFlight=null,this.st.lastFrameError="no reply",this.scheduler.lookUnanswered(e)),this.scheduler.setTooltipShowing(this.shown()!==null,e),this.st.state==="ready"&&!this.inFlight&&this.scheduler.due(e)&&this.requestCapture(this.scheduler.lookPending?"cut":void 0),this.publish()}stop(){this.st.state!=="stopped"&&(this.st.state="stopped",this.st.loading=null,this.inFlight=null,this.result=null,this.held=null,this.pointerAt=null,this.publishShown(),this.publishStatus())}workerStopped(e){if(!(this.st.state==="stopped"||this.st.state==="failed")){if(this.inFlight=null,this.result=null,this.held=null,this.st.loading=null,this.publishShown(),"restart"in e){let r={kind:"geometric-status",state:"off",reason:"worker-restarted",bytes:null};this.st.geometric&&(this.st.geometric={state:r.state,reason:r.reason,bytes:r.bytes}),this.deps.onGeometricStatus?.(r),this.st.state="loading",this.analyzedSinceLoad=!1,this.st.error=null}else this.st.state="failed",this.st.error=e.error;this.publishStatus()}}reloading(e){this.st.state==="loading"&&(this.st.geometric=e.geometric?{state:"loading",reason:null,bytes:null}:null,this.st.loading=null,this.publishStatus())}requestCapture(e){if(this.st.state!=="ready"||this.inFlight)return;let r=this.deps.now(),i=this.nextRequestId++;this.inFlight={requestId:i,sentAt:r,generation:this.generation,videoKey:this.videoKey,analyzing:!1},this.scheduler.started(r,{videoTimeSec:this.videoTime(),...e?{trigger:e}:{}}),this.deps.capture(i,{...this.analysisWidth})}status(){return{...this.st,schedule:this.scheduler.analysisState(this.deps.now())}}analysis(){return this.current()?.analysis??null}cards(){return this.cardList}hitAt(e,r){let i=this.current();if(!i)return null;let{width:n,height:s}=i.analysis.frame;if(!(n>0&&s>0))return null;let o=e*n,l=r*s;if(!Number.isFinite(o)||!Number.isFinite(l))return null;let a=this.hitTest(i.analysis,o,l);if(!a.box||a.cardId===null||a.name===null)return null;let u={x:a.box.x/n,y:a.box.y/s,width:a.box.width/n,height:a.box.height/s},p={x:a.box.x,y:a.box.y,width:a.box.width,height:a.box.height};return{cardId:a.cardId,name:a.name,box:u,frameBox:p,others:ge(i.analysis,u,this.maxOtherBoxes),...et(a.card)}}fresh(){return this.pointerAt?this.hitAt(this.pointerAt.x,this.pointerAt.y):null}shown(){let e=this.fresh(),r=this.hold;if(!r)return e;let i=this.deps.now();if(e)return this.held={card:e,misses:0,seenAt:i},e;let n=this.held;return!n||!this.pointerAt||!rt(n.card.box,this.pointerAt)?(this.held=null,null):this.boxAtPointer(n.card.box,r.sameBoxIou)==="other"||n.misses>=r.misses||i-n.seenAt>=r.maxMs?(this.held=null,null):n.card}current(){let e=this.result;return e&&Y(e.videoTimeSec,this.videoTime(),this.maxAgeMs)?e:null}videoTime(){return this.deps.mediaTimeNow?this.deps.mediaTimeNow():this.mediaTime}boxAtPointer(e,r){let i=this.current();if(!i||!this.pointerAt)return"unknown";let{width:n,height:s}=i.analysis.frame;if(!(n>0&&s>0))return"unknown";let o=this.pointerAt.x*n,l=this.pointerAt.y*s,a={x:e.x*n,y:e.y*s,width:e.width*n,height:e.height*s},u=0,p=!1;for(let y of i.analysis.boxes??[]){let[g,b,w,k]=y.box;og+w||lb+k||(p=!0,u=Math.max(u,tt(a,{x:g,y:b,width:w,height:k})))}return p?u>=r?"same":"other":"none"}publish(){this.publishShown(),this.publishStatus()}publishShown(){let e=this.shown(),r=e?`${e.cardId}|${e.box.x}|${e.box.y}|${e.box.width}|${e.box.height}|${e.rotation??""}|${e.localWidth??""}|${e.localHeight??""}`:"null";r!==this.lastShownKey&&(this.lastShownKey=r,this.deps.onShown?.(e))}statusKey(){let e=this.status();return JSON.stringify({...e,release:e.release?e.release.id:null})}publishStatus(){let e=this.statusKey();e!==this.lastStatusKey&&(this.lastStatusKey=e,this.deps.onStatus?.(this.status()))}};function tt(t,e){let r=Math.min(t.x+t.width,e.x+e.width)-Math.max(t.x,e.x),i=Math.min(t.y+t.height,e.y+e.height)-Math.max(t.y,e.y);if(r<=0||i<=0)return 0;let n=r*i;return n/(t.width*t.height+e.width*e.height-n)}function rt(t,e){return e.x>=t.x&&e.x<=t.x+t.width&&e.y>=t.y&&e.y<=t.y+t.height}var Wt=1440*60*1e3;var nt=[/^the worker did not start/,/^unexpected error while loading/];function be(t,e){return e||t.startsWith("unexpected:")?!1:!nt.some(r=>r.test(t))}var Se=1;function xe(t){let{geometricUrl:e,geometricManifestSha256:r,geometricWatchdog:i,...n}=t;return n}function X(t){O(t.measuredPacing);let e=null,r=null,i=0,n=!1,s=null,o=!1,l=null,a={source:t.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},u=c=>{t.onDecision?.({reused:0,downloaded:0,ms:0,...c})},p=c=>new C({now:t.now,toWorker:(h,f)=>e?.postMessage(h,f??[]),capture:t.capture,...t.onShown?{onShown:t.onShown}:{},...t.onStatus?{onStatus:t.onStatus}:{},...t.onAnalysis?{onAnalysis:t.onAnalysis}:{},...t.onGeometricStatus?{onGeometricStatus:t.onGeometricStatus}:{},...t.hoverAt?{hoverAt:t.hoverAt}:{},...t.mediaTimeNow?{mediaTimeNow:t.mediaTimeNow}:{}},{...t.mode?{mode:t.mode}:{},...t.measuredPacing?{measuredPacing:t.measuredPacing}:{},...t.hold?{hold:t.hold}:{},...t.rotatedOutlines?{rotatedOutlines:!0}:{},geometric:c.geometricUrl!==void 0}),y=c=>{n||!r||(s&&c.kind==="release-progress"&&c.phase==="preparing"&&(o=!0),!(c.kind==="release-status"&&(r.status().state!=="loading"||s&&!b(c)))&&(c.kind==="release-status"&&!c.ok&&g(),r.fromWorker(c)))},g=()=>{n=!0,s=null,e?.terminate(),e=null},b=c=>{let h=s;if(c.ok&&c.release?.id===h.pointer.id)return s=null,l=h.pointer.id,a.source="remote",a.id=h.pointer.id,a.reason="ok",a.table=h.facts,u({source:"remote",reason:"ok",pointer:h.pointer.id,reused:h.reused,downloaded:h.downloaded,ms:h.ms}),!0;if(c.ok)return t.recordSkip?.(h.pointer,"id-mismatch"),w("id-mismatch"),!1;let f=c.error??"no reason given";return be(f,o)&&t.recordSkip?.(h.pointer,`runtime:${f.slice(0,120)}`),w(`runtime:${f}`),!1},w=c=>{let h=s;s=null,e?.terminate(),a.source="bundled",a.id=null,a.reason=c,a.table=null,u({source:"bundled",reason:c,pointer:h.pointer.id,reused:h.reused,downloaded:h.downloaded,ms:h.ms});let f=h.fallback??t.loadRequest;r?.reloading({geometric:f.geometricUrl!==void 0}),I(f)},k=c=>{if(n||!r)return;let h=r.status().state;if(h==="failed"||h==="stopped")return;let f=c.message||"see the console";if(s){b({kind:"release-status",ok:!1,error:`the worker did not start (${f})`,release:null,cards:[]});return}if(e?.terminate(),h==="loading"&&i===0){g(),r.workerStopped({error:`the worker did not start (${f})`});return}if(i{let h=t.createWorker();h.onmessage=f=>{h===e&&y(f.data)},h.onerror=f=>{h===e&&k(f)},e=h,h.postMessage(c)},I=c=>{r??=p(c);try{_(c)}catch(h){e=null,s=null,n=!0,r.workerStopped({error:`the recognition worker could not start (${String(h)})`})}};return t.chooseRelease?t.chooseRelease({onDownloading:()=>t.onDownloading?.()}).catch(c=>({source:"bundled",reason:`unexpected:${String(c)}`,pointer:null,downloaded:0,ms:0})).then(c=>{if(!n){if(c.source==="remote"){s=c,o=!1,I(c.request);return}a.source="bundled",a.reason=c.reason,u({source:"bundled",reason:c.reason,pointer:c.pointer?.id??null,downloaded:c.downloaded,ms:c.ms}),I(c.request??t.loadRequest)}}):I(t.loadRequest),{get core(){return r},get stopped(){return n},get restarts(){return i},get release(){return{...a}},tick(){n||r?.tick()},stop(){n=!0,s=null,e?.terminate(),e=null,r?.stop()}}}var it=/^[0-9a-f]{16}$/;function st(){let t=crypto.getRandomValues(new Uint8Array(8));return Array.from(t,e=>e.toString(16).padStart(2,"0")).join("")}function ot(t){let e=t.parentOrigin;if(!t.framed||e===null||!t.allowedParentOrigin(e))return null;let{win:r,protocol:i}=t,n=(t.instanceId??st)();if(typeof n!="string"||!it.test(n))throw new TypeError(`startComputeFrame: not an instance id: ${String(n)}`);let s=d=>r.parent.postMessage(i.tag(d),e),o=()=>s({kind:"ready",version:1,instance:n}),l=!1,a=()=>{l||(l=!0,o())},u={state:"loading",error:null,backend:null},p=d=>d===null?null:d.slice(0,200),y=(d,m,S,R=!1)=>{let A={state:d,error:p(m),backend:p(S)};!R&&A.state===u.state&&A.error===u.error&&A.backend===u.backend||(u=A,s({kind:"status",...A}))},g=d=>{d.state!=="stopped"&&y(d.state,d.error,d.state==="ready"?d.backend:null)},b=null,w=()=>b?.release??{source:t.chooseRelease?"choosing":"bundled",id:null,reason:null,table:null},k=null,_=d=>{k=d,t.onShown?.(d,w()),s({kind:"shown",card:d})},I=d=>{let m=w(),S=d?{cardId:d.cardId,name:d.name,...m.source==="remote"&&m.id!==null?{releaseId:m.id}:{},box:{...d.box},others:d.others.map(R=>({...R})),...d.rotation!==void 0&&d.localWidth!==void 0&&d.localHeight!==void 0?{rotation:d.rotation,localWidth:d.localWidth,localHeight:d.localHeight}:{}}:null;_(S)},{win:c,framed:h,parentOrigin:f,allowedParentOrigin:lt,protocol:ut,onShown:dt,instanceId:ct,...ve}=t,x=X({...ve,createWorker:()=>(a(),t.createWorker()),capture:(d,m)=>{let S=Math.min(m.max,4096);s({kind:"capture",requestId:d,analysisWidth:{min:Math.min(m.min,S),max:S}})},onShown:I,onStatus:g,onDownloading:()=>{y("loading",null,null,!0),t.onDownloading?.()}});b=x,x.core&&a();let we=()=>{o(),y(u.state,u.error,u.backend,!0),_(k)},Ae=(d,m)=>{switch(m.kind){case"pointer":d.pointer(m.x,m.y,m.mediaTime,m.touch);return;case"leave":d.pointerLeft();return;case"presented":d.presented(m.mediaTime);return;case"discontinuity":d.discontinuity(m.newSource);return;case"cut":d.cut();return;case"frame":d.frame(m.requestId,m.bitmap,m.mediaTime);return;case"capture-failed":d.captureFailed(m.requestId,m.reason,m.retry===!0);return}},$=d=>{let S=d.source===r.parent&&d.origin===e?i.parseComputeIn(d.data):null,R=x.core,A=null;try{S?.kind==="hello"?R&&we():S&&R&&!x.stopped&&(S.kind==="frame"&&(A=S.bitmap),Ae(R,S))}finally{at(d.data,A)}};return r.addEventListener("message",$),{get core(){return x.core},get stopped(){return x.stopped},get restarts(){return x.restarts},get release(){return x.release},instance:n,tick(){x.tick()},stop(){r.removeEventListener("message",$),x.stop()}}}function at(t,e){if(!(typeof ImageBitmap>"u"||typeof t!="object"||t===null))for(let r of Object.values(t))r!==e&&r instanceof ImageBitmap&&r.close()}export{N as DRIVER_TICK_MS,T as FrameScheduler,q as HOVER_MAX_AGE_MS,z as MAX_FRAME_SIDE,W as MAX_OTHER_BOXES,Ge as MAX_REASON_LENGTH,K as MAX_TEXT_LENGTH,V as PROTOCOL_VERSION,Ze as SHOWN_HOLD,C as SessionCore,Se as WORKER_RESTARTS,F as cadenceMs,Qe as computeProtocol,X as createWorkerSession,G as hoverAt,ge as neighborBoxes,xe as plainLoad,D as replyRejection,ot as startComputeFrame}; diff --git a/vendor/cardvision-browser/types/cadence.d.ts b/vendor/cardvision-browser/types/cadence.d.ts index 8c18c55..6945320 100644 --- a/vendor/cardvision-browser/types/cadence.d.ts +++ b/vendor/cardvision-browser/types/cadence.d.ts @@ -19,3 +19,50 @@ export declare function activeAnalyzeIntervalMs(ep: ExecutionProvider | null): n export declare function cadenceMs(ep: ExecutionProvider | null, mode: AnalysisMode): number; /** Whether this device runs the slower cadences. */ export declare function isSlowDevice(ep: ExecutionProvider | null): boolean; +/** Measured pacing: the share of time spent analyzing, by default. */ +export declare const MEASURED_PACING_SHARE = 0.25; +/** Measured pacing: the longest wait while the pointer is active. */ +export declare const MEASURED_PACING_ACTIVE_CEILING_MS = 4000; +/** Measured pacing: the longest wait in always-on mode. */ +export declare const MEASURED_PACING_SLOW_CEILING_MS = 8000; +/** Measured pacing: the longest wait while the pointer rests ("reading"). A name stops showing + * `hoverMaxAgeMs` after its frame and the reading state ends `READING_LINGER_MS` after that, so a + * longer wait would never come due and analysis would stop until the pointer moved. */ +export declare function readingCeilingMs(hoverMaxAgeMs: number): number; +/** Measured pacing: analyses measured before the measured wait applies. */ +export declare const MEASURED_PACING_MIN_SAMPLES = 3; +/** Measured pacing: how many of the latest analyses the median is taken over. */ +export declare const MEASURED_PACING_WINDOW = 5; +/** The `measuredPacing` option: `true` for the default share, or the share of time analysis may + * take, in (0, 1]. */ +export type MeasuredPacingOption = boolean | { + share?: number; +}; +/** The share the option asks for, or null when pacing is off. Throws on a share outside (0, 1]. */ +export declare function resolveMeasuredPacing(option: MeasuredPacingOption | undefined): number | null; +/** + * The wait between analyses under measured pacing. + * @param fixedMs Today's fixed interval for the mode and backend: the wait is never shorter, and + * it is the wait until `MEASURED_PACING_MIN_SAMPLES` analyses have been measured. + * @param ceilingMs The longest wait: `MEASURED_PACING_ACTIVE_CEILING_MS` while the pointer is + * active, `readingCeilingMs` while it rests, `MEASURED_PACING_SLOW_CEILING_MS` in always-on mode. + * @param timesMs Measured analysis times, oldest first. + * @param share The share of time analysis may take. + */ +export declare function pacedIntervalMs(fixedMs: number, ceilingMs: number, timesMs: readonly number[], share: number): number; +/** Learns the analysis time within one session (nothing is stored) and gives the waits. */ +export declare class MeasuredPacer { + private readonly share; + private times; + constructor(share: number); + /** Record one analysis's measured time (the reply's `workerMs`); not a number: ignored. */ + record(ms: number): void; + /** The wait in force: the fast cadence in pointer mode, the slow one in always-on mode. */ + intervalMs(ep: ExecutionProvider | null, mode: AnalysisMode): number; + /** The wait while the pointer rests on a showing tooltip, capped by `readingCeilingMs`. */ + readingMs(ep: ExecutionProvider | null, hoverMaxAgeMs: number): number; + /** The wait while the pointer is active. */ + activeMs(ep: ExecutionProvider | null): number; + /** The wait in always-on mode. */ + slowMs(ep: ExecutionProvider | null): number; +} diff --git a/vendor/cardvision-browser/types/index.d.ts b/vendor/cardvision-browser/types/index.d.ts index 807f8f7..df4462c 100644 --- a/vendor/cardvision-browser/types/index.d.ts +++ b/vendor/cardvision-browser/types/index.d.ts @@ -4,7 +4,7 @@ export { type ClientBox, createSession, type Session, type SessionOptions, type export { type AnalyzeOptions, type BoxResult, type FaceResult, type FrameAnalysis, hoverAt, hoverCardsOf, Pipeline, type PipelineOptions } from "./pipeline.js"; export { type AABB, type Candidate, iou, nonMaxSuppression, type Rect } from "./boxes.js"; export { type EmbeddingBank, parseBank } from "./bank.js"; -export { type AnalysisMode, cadenceMs, type SessionMode } from "./cadence.js"; +export { type AnalysisMode, cadenceMs, type MeasuredPacingOption, type SessionMode } from "./cadence.js"; export { analysisSize, captureFrame, type FrameSource, MAX_ANALYSIS_WIDTH, MIN_ANALYSIS_WIDTH } from "./capture.js"; export { type DecodeSettings, decodeDetections, DEFAULT_DECODE, validBox } from "./detector/decode.js"; export { Detector, type DetectorSettings, type Frame, type FrameDetector } from "./detector/detector.js"; diff --git a/vendor/cardvision-browser/types/session-core.d.ts b/vendor/cardvision-browser/types/session-core.d.ts index e9dcb70..64c08e9 100644 --- a/vendor/cardvision-browser/types/session-core.d.ts +++ b/vendor/cardvision-browser/types/session-core.d.ts @@ -1,6 +1,6 @@ import type { AABB } from "./boxes.js"; import type { AnalysisWidth } from "./capture.js"; -import { type SessionMode } from "./cadence.js"; +import { type MeasuredPacingOption, type SessionMode } from "./cadence.js"; import { FrameScheduler } from "./frame-scheduler.js"; import { type GeometricStatus, type ReleaseProgress, type ReleaseStatus, type TiltedStatus, type WorkerReply, type WorkerRequest } from "./messages.js"; import { type FractionBox } from "./compute-messages.js"; @@ -80,6 +80,9 @@ export interface SessionCoreOptions { /** True: named cards follow their outline on every frame (`SessionOptions.rotatedOutlines`). * Default false. */ rotatedOutlines?: boolean; + /** Pace analysis from the measured analysis time (`SessionOptions.measuredPacing`). Off when + * absent. */ + measuredPacing?: MeasuredPacingOption; } /** What `status().loading` becomes on a release-progress reply: the reply's phase while the * release loads; `undefined` (no change) once it has loaded or failed, or the session has @@ -95,6 +98,7 @@ export declare class SessionCore { private readonly maxOtherBoxes; private readonly rotatedOutlines; private readonly hitTest; + private readonly pacer; private readonly st; private cardList; private analysisWidth; @@ -134,6 +138,9 @@ export declare class SessionCore { * blank) and is looked at again after a back-off; otherwise a refusal, retried by nothing. */ captureFailed(requestId: number, reason: string, retry?: boolean): void; fromWorker(reply: WorkerReply): void; + /** Arm the scheduler with the cadence for the backend: today's fixed rates, or the measured + * ones with `measuredPacing`. */ + private applyCadence; private onFrameResult; /** Call every `DRIVER_TICK_MS`. */ tick(): void; diff --git a/vendor/cardvision-browser/types/session.d.ts b/vendor/cardvision-browser/types/session.d.ts index 184ca0f..6815386 100644 --- a/vendor/cardvision-browser/types/session.d.ts +++ b/vendor/cardvision-browser/types/session.d.ts @@ -1,5 +1,5 @@ import { type AABB } from "./boxes.js"; -import { type SessionMode } from "./cadence.js"; +import { type MeasuredPacingOption, type SessionMode } from "./cadence.js"; import { type ClientBox, type FrameSource, pictureBox } from "./capture.js"; import { type AnalysisState } from "./frame-scheduler.js"; import type { GeometricStatus, ReleaseStatus } from "./messages.js"; @@ -25,6 +25,14 @@ export interface SessionOptions { /** "pointer" (the default): analyze only around pointer activity. "always-on": analyze for as * long as the session runs. */ mode?: SessionMode; + /** Pace analysis from the time recent analyses took on this device. Default off: the fixed + * rates. `true`, or `{ share }`: the wait is the median of the last 5 measured analyses + * divided by the share of time analysis may take (default 0.25), never shorter than the fixed + * rate. It is at most 4 s while the pointer is active, the release's `hover.maxAgeMs` + 4.75 s + * (6.75 s by default) while the pointer rests on a tooltip, and 8 s in always-on mode. The + * fixed rate applies until 3 analyses have been measured. Learned within the session, never + * stored. A share outside (0, 1] throws. */ + measuredPacing?: MeasuredPacingOption; /** URL of the geometric stage's settings document (it names the packed index). Optional and * off by default: without it recognition is the embedding's alone. With it the stage loads * after the release and joins between frames; `status().geometric` says where it is. */ diff --git a/vendor/cardvision-browser/types/worker-session.d.ts b/vendor/cardvision-browser/types/worker-session.d.ts index f8dba09..9b6bd5e 100644 --- a/vendor/cardvision-browser/types/worker-session.d.ts +++ b/vendor/cardvision-browser/types/worker-session.d.ts @@ -1,5 +1,5 @@ import type { AnalysisWidth } from "./capture.js"; -import type { SessionMode } from "./cadence.js"; +import { type MeasuredPacingOption, type SessionMode } from "./cadence.js"; import type { GeometricStatus, WorkerReply, WorkerRequest } from "./messages.js"; import type { FrameAnalysis } from "./pipeline.js"; import type { CardTable } from "./remote/card-table.js"; @@ -37,6 +37,8 @@ export interface WorkerSessionEnv { /** The clock, in ms. */ now(): number; mode?: SessionMode; + /** Measured pacing (`SessionOptions.measuredPacing`); off when absent. */ + measuredPacing?: MeasuredPacingOption; /** Hold a shown card through short gaps (`SHOWN_HOLD`); off when absent. */ hold?: ShownHold; /** True: named cards follow their outline (`SessionOptions.rotatedOutlines`). */