diff --git a/NOTICE b/NOTICE index 4ca4bc6..236e655 100644 --- a/NOTICE +++ b/NOTICE @@ -18,15 +18,11 @@ Bundled libraries (npm) - js-yaml ...................... MIT Vendored code -- public/vendor/paddleocr-vl/ — PaddleOCR-VL WebGPU 0.1.0 (commit f7d2f8a), Apache-2.0, - Copyright 2026 SotaOCR. Modified: configurable model base URL, no second cache copy while - loading. See public/vendor/paddleocr-vl/LICENSE.txt and NOTICE.txt. - src/ocr/ppocr.worker.js — pre/post-processing written after PaddleOCR's DBPostProcess, CTCLabelDecode and get_rotate_crop_image (PaddleOCR, Apache-2.0). Models downloaded at runtime (from the configured host) - PP-OCRv6 tiny / medium (det + rec ONNX), PaddlePaddle ............ Apache-2.0 -- PaddleOCR-VL 1.6 WebGPU build (glebkudr/PaddleOCR-VL-1.6-WebGPU) .. Apache-2.0 - IBM Granite Embedding 311M Multilingual R2 (ONNX q8) (ibm-granite / onnx-community ports) ............................. Apache-2.0 - Qwen2.5 0.5B / 1.5B Instruct, Qwen3.5 0.8B (MLC builds) .......... Apache-2.0 diff --git a/README.md b/README.md index 551e249..394a7ac 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ When you add a document, models download once (then stay cached) and run **local | Step | What it does | Model | | --- | --- | --- | -| **Read the page** | Photo/PDF → text | PP-OCRv6 (tiny by default; medium or PaddleOCR-VL on desktop) | +| **Read the page** | Photo/PDF → text | PP-OCRv6 (tiny by default; medium optional) | | **Fill the filing card** | Suggests title, sender, date, labels | Small Qwen models via WebLLM | | **Search by meaning** | Finds docs by idea, not exact words | IBM Granite Embedding 311M Multilingual R2 | @@ -119,9 +119,8 @@ Only **one** engine is in memory at a time (so phones stay stable). While models | Model | Size | Notes | | --- | --- | --- | -| PP-OCRv6 tiny | ~12 MB | Default; ships with the app; good on phones | +| PP-OCRv6 tiny | ~12 MB | Default; good on phones | | PP-OCRv6 medium | ~107 MB | Same family, more accurate | -| PaddleOCR-VL 1.6 | ~1.9 GB | Desktop + WebGPU; 100+ languages (incl. Arabic) | **Metadata (title / from / date / labels)** @@ -144,7 +143,6 @@ Weights are **not** in git. They download on first use and cache on the device. | Model | Job | License | | --- | --- | --- | | PP-OCRv6 tiny / medium | OCR | Apache-2.0 | -| PaddleOCR-VL 1.6 | OCR (desktop) | Apache-2.0 | | Qwen2.5 / Qwen3.5 (above) | Metadata | Apache-2.0 | | Granite Embedding 311M R2 | Meaning search | Apache-2.0 | @@ -175,7 +173,7 @@ More detail: [docs/architecture.md](docs/architecture.md) · [ADR 0001](docs/adr - Closing the tab while a document is still being read loses that upload - Trash can be restored here; “delete forever” is left to whatever manages the bucket - Large documents use a single PUT (no multipart upload) -- PP-OCRv6 has no Arabic; use PaddleOCR-VL on desktop for that +- PP-OCRv6 has no Arabic or Japanese - After changing embedding models, rebuild the search index in Settings → Search ## Contributing & license diff --git a/docs/adr/0001-browser-only-pwa-with-direct-s3-storage.md b/docs/adr/0001-browser-only-pwa-with-direct-s3-storage.md index a5f65a1..6b0cf31 100644 --- a/docs/adr/0001-browser-only-pwa-with-direct-s3-storage.md +++ b/docs/adr/0001-browser-only-pwa-with-direct-s3-storage.md @@ -28,7 +28,7 @@ or keys. deleted on start. - The S3 keys are encrypted with a user password: PBKDF2-SHA-256 (600,000 rounds) → AES-256-GCM, stored in IndexedDB. The app shows an unlock screen on every open and forgets the plain keys after 15 minutes idle. -- OCR (PP-OCRv6 via onnxruntime-web, optional PaddleOCR-VL via WebGPU), metadata (WebLLM / Qwen) and meaning-search +- OCR (PP-OCRv6 via onnxruntime-web), metadata (WebLLM / Qwen) and meaning-search embeddings (**IBM Granite Embedding 311M Multilingual R2** via transformers.js, Apache-2.0) all run on the device. Models download from Hugging Face / official WebLLM libs on first use and are cached in the browser (not in the document bucket). - Memory rules for phones: one model in memory at a time, downloads one file at a time streamed into the cache, diff --git a/public/vendor/paddleocr-vl/LICENSE.txt b/public/vendor/paddleocr-vl/LICENSE.txt deleted file mode 100644 index d645695..0000000 --- a/public/vendor/paddleocr-vl/LICENSE.txt +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/public/vendor/paddleocr-vl/NOTICE.txt b/public/vendor/paddleocr-vl/NOTICE.txt deleted file mode 100644 index 37d624d..0000000 --- a/public/vendor/paddleocr-vl/NOTICE.txt +++ /dev/null @@ -1,7 +0,0 @@ -PaddleOCR-VL WebGPU -Copyright 2026 SotaOCR - -This product includes a model-specific inference engine developed by SotaOCR. - -PaddleOCR-VL model artifacts are derived from the PaddlePaddle/PaddleOCR-VL-1.6 -checkpoint and retain the upstream model license and notices. diff --git a/public/vendor/paddleocr-vl/browser_diagnostics.mjs b/public/vendor/paddleocr-vl/browser_diagnostics.mjs deleted file mode 100644 index d7f2019..0000000 --- a/public/vendor/paddleocr-vl/browser_diagnostics.mjs +++ /dev/null @@ -1,145 +0,0 @@ -export const MODEL_DOWNLOAD_BYTES = 2_038_286_862; -export const RECOMMENDED_DEVICE_MEMORY_GB = 8; -export const MIN_STORAGE_BYTES = 2_500_000_000; -export const MIN_BUFFER_BYTES = 256 * 1024 * 1024; -export const MIN_STORAGE_BUFFER_BYTES = 128 * 1024 * 1024; - -function finitePositive(value) { - const normalized = Number(value); - return Number.isFinite(normalized) && normalized > 0 ? normalized : null; -} - -async function storageAvailable(navigatorLike) { - try { - const estimate = await navigatorLike.storage?.estimate(); - const quota = finitePositive(estimate?.quota); - const usage = Number(estimate?.usage); - if (quota === null || !Number.isFinite(usage) || usage < 0) return null; - return Math.max(0, quota - usage); - } catch { - return null; - } -} - -export async function diagnoseBrowser( - navigatorLike = globalThis.navigator ?? {}, - performanceLike = globalThis.performance ?? {}, -) { - const deviceMemoryGB = finitePositive(navigatorLike.deviceMemory); - const jsHeapLimitBytes = finitePositive( - performanceLike.memory?.jsHeapSizeLimit, - ); - const storageAvailableBytes = await storageAvailable(navigatorLike); - - if (!navigatorLike.gpu) { - return { - status: "unsupported", - memory: deviceMemoryGB === null ? "unknown" : "limited", - webgpu: false, - adapter: false, - shaderF16: false, - deviceMemoryGB, - jsHeapLimitBytes, - storageAvailableBytes, - maxBufferSize: null, - maxStorageBufferBindingSize: null, - reasons: ["webgpu_unavailable"], - }; - } - - let adapter = null; - try { - adapter = await navigatorLike.gpu.requestAdapter({ - powerPreference: "high-performance", - }); - } catch { - adapter = null; - } - if (!adapter) { - return { - status: "unsupported", - memory: deviceMemoryGB === null ? "unknown" : "limited", - webgpu: true, - adapter: false, - shaderF16: false, - deviceMemoryGB, - jsHeapLimitBytes, - storageAvailableBytes, - maxBufferSize: null, - maxStorageBufferBindingSize: null, - reasons: ["adapter_unavailable"], - }; - } - - const reasons = []; - const shaderF16 = adapter.features?.has("shader-f16") === true; - const maxBufferSize = finitePositive(adapter.limits?.maxBufferSize); - const maxStorageBufferBindingSize = finitePositive( - adapter.limits?.maxStorageBufferBindingSize, - ); - - if (!shaderF16) reasons.push("shader_f16_unavailable"); - if ( - (maxBufferSize !== null && maxBufferSize < MIN_BUFFER_BYTES) || - ( - maxStorageBufferBindingSize !== null && - maxStorageBufferBindingSize < MIN_STORAGE_BUFFER_BYTES - ) - ) { - reasons.push("gpu_buffer_limits_low"); - } - if ( - deviceMemoryGB !== null && - deviceMemoryGB < RECOMMENDED_DEVICE_MEMORY_GB - ) { - reasons.push("device_memory_low"); - } - if (jsHeapLimitBytes !== null && jsHeapLimitBytes < MIN_STORAGE_BYTES) { - reasons.push("js_heap_low"); - } - if ( - storageAvailableBytes !== null && - storageAvailableBytes < MIN_STORAGE_BYTES - ) { - reasons.push("storage_low"); - } - - const hasMemorySignal = - deviceMemoryGB !== null || - jsHeapLimitBytes !== null || - storageAvailableBytes !== null; - const memoryLimited = reasons.some((reason) => - reason === "device_memory_low" || - reason === "js_heap_low" || - reason === "storage_low" || - reason === "gpu_buffer_limits_low" - ); - const memory = memoryLimited - ? "limited" - : hasMemorySignal - ? "enough" - : "unknown"; - if (!hasMemorySignal) reasons.push("memory_unknown"); - - const unsupported = reasons.some((reason) => - reason === "shader_f16_unavailable" || - reason === "gpu_buffer_limits_low" - ); - return { - status: unsupported - ? "unsupported" - : memory === "enough" - ? "ready" - : "limited", - memory, - webgpu: true, - adapter: true, - shaderF16, - deviceMemoryGB, - jsHeapLimitBytes, - storageAvailableBytes, - maxBufferSize, - maxStorageBufferBindingSize, - reasons, - }; -} diff --git a/public/vendor/paddleocr-vl/browser_ocr_runtime.mjs b/public/vendor/paddleocr-vl/browser_ocr_runtime.mjs deleted file mode 100644 index af321d5..0000000 --- a/public/vendor/paddleocr-vl/browser_ocr_runtime.mjs +++ /dev/null @@ -1,673 +0,0 @@ -// Copy of paddleocr-vl-webgpu 0.1.0 (commit f7d2f8a, Apache-2.0). Modified for Documents Manager: configurable model -// base URL (globalThis.__PVL_MODEL_BASE__, set by vl-worker.mjs) and a fetchBytes without a second cache copy. -import * as runtimeWasmModule from "./pkg/pvlc_runtime_web.js"; -import { runGreedyGeneration } from "./greedy_generation.mjs"; -import { - AdaptiveOcrConcurrency, - BrowserRuntimePool, - recommendOcrParallelism, -} from "./ocr_concurrency.mjs"; -import { - PADDLEOCR_VL_TASKS, - recognitionOptionsForTask, -} from "./paddleocr_vl_tasks.mjs"; -import { - assembleEmbeddings, - buildMultimodalSessionPack, - buildVisionStackManifest, - loadMultimodalTokenizer, - mropePositions, - multimodalF32Bytes, - multimodalPromptInputIds, - narrowMultimodalF32ToF16Bytes, - patchEmbeddingWebGpu, - preprocessImage, - readMultimodalSafetensors, - readSessionPackShardBytes, - ropeTables, - runSyntheticVisionStack, - widenMultimodalF16Bytes, -} from "./multimodal_ocr.mjs"; - -const { default: init, WebRuntime } = runtimeWasmModule; - -export const MODEL_REPOSITORY = "glebkudr/PaddleOCR-VL-1.6-WebGPU"; -export const MODEL_REVISION = "5219606297d00bbd23b2ec193271af0c0b427dfc"; -export const MODEL_DOWNLOAD_BYTES = 2_038_286_862; - -// Model files: from the app's local model folder (downloaded once by the app) or straight from Hugging Face. -const MODEL_BASE_URL = String( - globalThis.__PVL_MODEL_BASE__ || - `https://huggingface.co/${MODEL_REPOSITORY}/resolve/${MODEL_REVISION}`, -).replace(/\/+$/, ""); -// Optional: mirrors that store very large files in parts (`.part0`, `.part1`, …) can list them here. -const SPLIT_PARTS = new Map(Object.entries(globalThis.__PVL_SPLIT_PARTS__ || {})); -const PROMPT_PREFIX_IDS = Object.freeze([ - 100273, 2969, 93963, 93919, 101305, -]); -const ASSETS = Object.freeze({ - stackBase: - `${MODEL_BASE_URL}/m7u-vision-stack-full-fp16-input-major-official`, - visionEmbedUrl: `${MODEL_BASE_URL}/m6e10-vision-embed.safetensors`, - projectorBase: - `${MODEL_BASE_URL}/m7v-projector-full-fp16-input-major-official`, - decoderPackUrl: - `${MODEL_BASE_URL}/m7q1-decoder-stack-logits-fp16-official.pvlc`, - embedTokensUrl: `${MODEL_BASE_URL}/m6e9-embed-tokens.f32`, - tokenizerUrl: `${MODEL_BASE_URL}/m6e9-tokenizer.json`, -}); - -const completedAssetUrls = new Set(); -const assetDownloadBytes = new Map(); - -function emitProgress(onProgress, update) { - if (typeof onProgress === "function") { - onProgress(update); - } -} - -function modelLoadedBytes() { - let total = 0; - for (const value of assetDownloadBytes.values()) { - total += value; - } - return Math.min(total, MODEL_DOWNLOAD_BYTES); -} - -async function fetchBytes(url, label, onProgress) { - // No second Cache Storage copy, - // one preallocated buffer per file (no chunk list + copy), and errors that name the file. - const name = url.split("/").pop(); - const split = SPLIT_PARTS.get(name); - const parts = split - ? split.map((size, i) => ({ url: `${url}.part${i}`, size })) - : [{ url, size: 0 }]; - const expected = split ? split.reduce((a, b) => a + b, 0) : 0; - let bytes = expected ? new Uint8Array(expected) : null; - let chunks = expected ? null : []; - let loadedBytes = 0; - for (const part of parts) { - let response; - try { - response = await fetch(part.url, { credentials: "same-origin" }); - } catch (error) { - throw new Error(`${label} download failed (${part.url}): ${error && error.message ? error.message : error}`); - } - if (!response.ok) { - throw new Error(`${label} fetch failed: HTTP ${response.status} (${part.url})`); - } - const partLength = Number(response.headers.get("content-length")) || 0; - if (!bytes && !split && partLength > 0 && !response.headers.get("content-encoding")) { - bytes = new Uint8Array(partLength); chunks = null; - } - const totalBytes = expected || partLength || null; - const take = (value) => { - if (bytes) { - if (loadedBytes + value.byteLength > bytes.byteLength) { - throw new Error(`${label}: ${part.url} is larger than expected (${bytes.byteLength} bytes)`); - } - bytes.set(value, loadedBytes); - } else { - chunks.push(value); - } - loadedBytes += value.byteLength; - if (!completedAssetUrls.has(url)) assetDownloadBytes.set(url, loadedBytes); - emitProgress(onProgress, { - kind: "download", - asset: label, - assetLoadedBytes: loadedBytes, - assetTotalBytes: totalBytes, - modelLoadedBytes: modelLoadedBytes(), - modelTotalBytes: MODEL_DOWNLOAD_BYTES, - fromPersistentCache: false, - }); - }; - if (!response.body) { - take(new Uint8Array(await response.arrayBuffer())); - } else { - const reader = response.body.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) break; - take(value); - } - } - } - if (chunks) { - bytes = new Uint8Array(loadedBytes); - let offset = 0; - for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } - chunks = null; - } else if (loadedBytes !== bytes.byteLength) { - throw new Error(`${label}: got ${loadedBytes} of ${bytes.byteLength} bytes (${url}${split ? ".part*" : ""})`); - } - if (!completedAssetUrls.has(url)) { - assetDownloadBytes.set(url, loadedBytes); - completedAssetUrls.add(url); - } - return bytes; -} - -class BrowserModelAssets { - #memoized = new Map(); - - #once(key, loader) { - if (!this.#memoized.has(key)) { - const pending = Promise.resolve() - .then(loader) - .catch((error) => { - this.#memoized.delete(key); - throw error; - }); - this.#memoized.set(key, pending); - } - return this.#memoized.get(key); - } - - bytes(url, label, onProgress) { - return this.#once( - `bytes:${url}`, - () => fetchBytes(url, label, onProgress), - ); - } - - visionEmbed(onProgress) { - return this.#once("parsed:vision-embed", async () => - readMultimodalSafetensors( - await this.bytes( - ASSETS.visionEmbedUrl, - "Vision embeddings", - onProgress, - ), - "vision embed", - ) - ); - } - - visionManifest(onProgress) { - return this.#once("parsed:vision-manifest", async () => - JSON.parse(new TextDecoder().decode( - await this.bytes( - `${ASSETS.stackBase}/manifest.json`, - "Vision manifest", - onProgress, - ), - )) - ); - } - - projectorDescriptor(onProgress) { - return this.#once("parsed:projector-descriptor", async () => { - const json = new TextDecoder().decode( - await this.bytes( - `${ASSETS.projectorBase}/manifest.json`, - "Projector manifest", - onProgress, - ), - ); - return Object.freeze({ json, value: JSON.parse(json) }); - }); - } - - tokenEmbeddings(onProgress) { - return this.#once("parsed:token-embeddings", async () => - new Float32Array( - (await this.bytes( - ASSETS.embedTokensUrl, - "Token embeddings", - onProgress, - )).buffer, - ) - ); - } - - decoderShards(runtime, onProgress) { - return this.#once("parsed:decoder-shards", async () => - readSessionPackShardBytes( - await this.bytes( - ASSETS.decoderPackUrl, - "Decoder weights", - onProgress, - ), - (bytes) => runtime.blake3_bytes_hex(bytes), - ) - ); - } - - tokenizer(onProgress) { - return this.#once("parsed:tokenizer", async () => - loadMultimodalTokenizer( - await this.bytes( - ASSETS.tokenizerUrl, - "Tokenizer", - onProgress, - ), - ) - ); - } - - preload(onProgress) { - return Object.freeze({ - visionEmbed: this.visionEmbed(onProgress), - visionManifest: this.visionManifest(onProgress), - projectorDescriptor: this.projectorDescriptor(onProgress), - tokenEmbeddings: this.tokenEmbeddings(onProgress), - tokenizer: this.tokenizer(onProgress), - }); - } - - releaseDecoderShards() { - this.#memoized.delete("parsed:decoder-shards"); - this.#memoized.delete(`bytes:${ASSETS.decoderPackUrl}`); - } - - release() { - this.#memoized.clear(); - } -} - -function canvasRgb(canvas) { - const imageData = canvas - .getContext("2d", { willReadFrequently: true }) - .getImageData(0, 0, canvas.width, canvas.height); - const rgb = new Uint8Array(canvas.width * canvas.height * 3); - for (let index = 0; index < canvas.width * canvas.height; index += 1) { - rgb[index * 3] = imageData.data[index * 4]; - rgb[index * 3 + 1] = imageData.data[index * 4 + 1]; - rgb[index * 3 + 2] = imageData.data[index * 4 + 2]; - } - return rgb; -} - -async function runCanvasInference( - runtime, - assets, - canvas, - options, - onProgress, -) { - const startedAt = performance.now(); - const residentState = typeof runtime.decoder_stack_resident_weights_json === "function" - ? JSON.parse(runtime.decoder_stack_resident_weights_json()) - : { ready: false }; - const canUseResidentBegin = - residentState.ready === true && - typeof runtime.begin_decoder_stack_session_resident === "function"; - let decoderShardsPromise = canUseResidentBegin - ? null - : assets.decoderShards(runtime, onProgress); - const preloaded = assets.preload(onProgress); - const mark = (stage, detail) => { - emitProgress(onProgress, { kind: "inference", stage, detail }); - }; - - const rgb = canvasRgb(canvas); - const { pixelValues, gridThw } = preprocessImage( - rgb, - canvas.height, - canvas.width, - ); - const tokens = gridThw[0] * gridThw[1] * gridThw[2]; - mark("preprocess", `${tokens} vision tokens`); - - const visionEmbed = await preloaded.visionEmbed; - const embedded = await patchEmbeddingWebGpu(runtime, pixelValues, { - weight: visionEmbed("patch_embedding_weight"), - bias: visionEmbed("patch_embedding_bias"), - positionEmbedding: visionEmbed("position_embedding_weight"), - gridThw, - }); - mark("patch_embedding", "Patch and position embeddings ready"); - - const officialManifest = await preloaded.visionManifest; - const layerSuffix = officialManifest.matrix_weight_storage === "f16" - ? ".bin" - : ".f32"; - const loadShard = (id) => fetchBytes( - `${ASSETS.stackBase}/${id}${layerSuffix}`, - `Vision ${id}`, - onProgress, - ); - const activationStorage = officialManifest.activation_storage ?? "f32"; - const visionInputBytes = activationStorage === "f16" - ? narrowMultimodalF32ToF16Bytes( - embedded.output, - "vision stack input embeddings", - ) - : multimodalF32Bytes(embedded.output); - const visionManifest = buildVisionStackManifest({ - tokens, - weightShards: officialManifest.shards.slice(1), - inputBlake3: runtime.blake3_bytes_hex(visionInputBytes), - caseId: "sotaocr.free_ocr_browser", - matrixWeightStorage: - officialManifest.matrix_weight_storage ?? "f32", - matrixWeightLayout: - officialManifest.matrix_weight_layout ?? "output_major", - vectorWeightStorage: - officialManifest.vector_weight_storage ?? "f32", - activationStorage, - checkpointLayers: [], - }); - - const { - json: projectorDescriptorJson, - value: projectorDescriptor, - } = await preloaded.projectorDescriptor; - if (!runtime.has_projector_f16_resident_weights(projectorDescriptorJson)) { - runtime.prepare_projector_f16_resident_weights( - projectorDescriptorJson, - await fetchBytes( - `${ASSETS.projectorBase}/weights.projector.bin`, - "Projector weights", - onProgress, - ), - ); - } - - const imageTokens = tokens / 4; - const projectorF16 = Object.freeze({ - descriptorJson: projectorDescriptorJson, - imageGridThwJson: JSON.stringify([gridThw]), - outputTokens: imageTokens, - outputSize: projectorDescriptor.output_size, - }); - const visionExecution = await runSyntheticVisionStack( - runtime, - visionManifest, - loadShard, - visionInputBytes, - { gridThw, projectorF16 }, - ); - mark("vision_encoder", "Vision encoder complete"); - - let projectorBytes = visionExecution.projectorBytes; - if (!visionExecution.timings.projectorChained) { - const visionFinal = activationStorage === "f16" - ? visionExecution.bytes - : narrowMultimodalF32ToF16Bytes( - new Float32Array( - visionExecution.bytes.buffer, - visionExecution.bytes.byteOffset, - visionExecution.bytes.byteLength / 4, - ), - "vision stack final activation", - ); - const projected = await runtime.run_projector_f16_resident_bytes( - projectorDescriptorJson, - projectorF16.imageGridThwJson, - visionFinal, - ); - projectorBytes = projected.checkpoint_bytes; - } - if ( - !(projectorBytes instanceof Uint8Array) || - projectorBytes.byteLength !== - imageTokens * projectorDescriptor.output_size * 2 - ) { - throw new Error("FP16 projector readback drifted"); - } - const projectorFinal = new Float32Array( - widenMultimodalF16Bytes( - projectorBytes, - "FP16 projector output", - ).buffer, - ); - mark("projector", "Visual features projected"); - - const inputIds = multimodalPromptInputIds(gridThw, { - prefixIds: PROMPT_PREFIX_IDS, - suffixIds: options.promptSuffixIds, - }); - const promptTokens = inputIds.length; - const capacity = promptTokens + options.maxGeneratedTokens; - const embedTokens = await preloaded.tokenEmbeddings; - const tokenEmbedding = Object.freeze({ - values: embedTokens, - gather(id) { - return embedTokens.subarray(id * 1024, (id + 1) * 1024); - }, - }); - const assembled = assembleEmbeddings( - tokenEmbedding, - projectorFinal, - inputIds, - ); - const { positionIds, ropeDelta } = mropePositions(inputIds, gridThw); - const rope = ropeTables(positionIds, ropeDelta, { capacity }); - mark("prompt", `${promptTokens} prompt tokens`); - - let sessionPack = null; - if (!canUseResidentBegin) { - const decoderShards = await decoderShardsPromise; - const sourceDescriptor = JSON.parse(new TextDecoder().decode( - decoderShards.get("ir.decoder_stack_00"), - )); - const shardView = (id) => decoderShards.get(id); - sessionPack = buildMultimodalSessionPack({ - descriptor: { prefix_tokens: 0, cache_capacity: capacity }, - weights: { - norm1: shardView("weights.input_layernorm"), - q: shardView("weights.q_proj"), - k: shardView("weights.k_proj"), - v: shardView("weights.v_proj"), - o: shardView("weights.o_proj"), - ropeCos: rope.cos, - ropeSin: rope.sin, - norm2: shardView("weights.post_attention_layernorm"), - gate: shardView("weights.gate_proj"), - up: shardView("weights.up_proj"), - down: shardView("weights.down_proj"), - finalNorm: shardView("weights.final_layernorm"), - lmHead: shardView("weights.lm_head"), - }, - blake3Hex: (bytes) => runtime.blake3_bytes_hex(bytes), - caseId: "sotaocr.free_ocr_browser.decoder", - weightStorage: "f16", - checkpointIdentity: { - blake3: sourceDescriptor.checkpoint_blake3, - bytes: sourceDescriptor.checkpoint_bytes, - }, - }); - } - - const descriptor = { - schema_version: 1, - layers: 18, - hidden_size: 1024, - intermediate_size: 3072, - query_heads: 16, - key_value_heads: 2, - head_dim: 128, - query_width: 2048, - key_value_width: 256, - prefix_tokens: 0, - cache_capacity: capacity, - mrope_sections: [16, 24, 24], - rms_norm_epsilon: 1e-5, - prefill_tokens: promptTokens, - vocab_size: 103424, - }; - - let decoderSessionStarted = false; - const decoderSetupStartedAt = performance.now(); - let decoderCreationDiagnostics = null; - try { - const descriptorJson = JSON.stringify(descriptor); - decoderCreationDiagnostics = JSON.parse(canUseResidentBegin - ? await runtime.begin_decoder_stack_session_resident( - descriptorJson, - multimodalF32Bytes(rope.cos), - multimodalF32Bytes(rope.sin), - ) - : await runtime.begin_decoder_stack_session( - descriptorJson, - sessionPack, - new Uint8Array(18 * capacity * 256 * 4), - new Uint8Array(18 * capacity * 256 * 4), - )); - decoderSessionStarted = true; - sessionPack = null; - decoderShardsPromise = null; - if (!canUseResidentBegin) { - assets.releaseDecoderShards(); - } - const decoderSetupMs = performance.now() - decoderSetupStartedAt; - await runtime.prefill_decoder_stack_session( - multimodalF32Bytes(assembled), - ); - mark("decoder_prefill", "Decoder prefill complete"); - - const generationStartedAt = performance.now(); - const greedy = await runGreedyGeneration(runtime, { - embedding: embedTokens, - eosTokenId: 2, - maxSteps: options.maxGeneratedTokens, - cacheCapacity: capacity, - initialCacheTokens: promptTokens, - }); - const generationMs = performance.now() - generationStartedAt; - const tokensPerSecond = generationMs === 0 - ? 0 - : greedy.tokenIds.length * 1000 / generationMs; - mark("generation", `${greedy.tokenIds.length} generated tokens`); - - const tokenizer = await preloaded.tokenizer; - return { - greedy, - text: tokenizer.detokenize([...greedy.tokenIds]), - generationMs, - tokensPerSecond, - visionTokens: tokens, - promptTokens, - gpuTop1: greedy.gpuTop1, - logitsReadbackBytes: greedy.logitsReadbackBytes, - selectionQueueWallTimeNs: greedy.selectionQueueWallTimeNs, - decoderSetupMs, - decoderResidentWeightBytes: - JSON.parse(runtime.decoder_stack_resident_weights_json()) - .resident_weight_bytes, - decoderResidentWeightCacheHit: - canUseResidentBegin, - elapsedMs: performance.now() - startedAt, - }; - } finally { - if (decoderSessionStarted) { - runtime.abort_decoder_stack_session(); - } - } -} - -export { - PADDLEOCR_VL_TASKS, - recognitionOptionsForTask, -}; - -export class PaddleOcrVlEngine { - #runtimePool; - #concurrency; - #assets; - #disposed = false; - - constructor(runtimes, concurrency) { - this.#runtimePool = new BrowserRuntimePool(runtimes); - this.#concurrency = concurrency; - this.#assets = new BrowserModelAssets(); - } - - recognitionConcurrency(remaining = Number.POSITIVE_INFINITY) { - if (this.#disposed) { - throw new Error("PaddleOCR-VL engine has been disposed"); - } - return this.#concurrency.current(remaining); - } - - recordRecognitionWave(wave) { - if (this.#disposed) { - throw new Error("PaddleOCR-VL engine has been disposed"); - } - return this.#concurrency.recordWave(wave); - } - - async recognizeCanvas( - canvas, - { - task = "ocr", - promptSuffixIds, - maxGeneratedTokens = 512, - onProgress = () => {}, - } = {}, - ) { - if (this.#disposed) { - throw new Error("PaddleOCR-VL engine has been disposed"); - } - if ( - !canvas || - !Number.isInteger(canvas.width) || - !Number.isInteger(canvas.height) || - canvas.width <= 0 || - canvas.height <= 0 || - typeof canvas.getContext !== "function" - ) { - throw new TypeError("recognizeCanvas() expects a non-empty canvas"); - } - const taskOptions = recognitionOptionsForTask(task, { - maxGeneratedTokens, - }); - return this.#runtimePool.run((runtime) => - runCanvasInference( - runtime, - this.#assets, - canvas, - { - ...taskOptions, - promptSuffixIds: - promptSuffixIds ?? taskOptions.promptSuffixIds, - }, - onProgress, - ) - ); - } - - async recognizeImage(image, options = {}) { - if (!(image instanceof Blob)) { - throw new TypeError("recognizeImage() expects a browser File or Blob"); - } - const bitmap = await createImageBitmap(image); - try { - const canvas = document.createElement("canvas"); - canvas.width = bitmap.width; - canvas.height = bitmap.height; - const context = canvas.getContext("2d"); - if (!context) throw new Error("Could not create an image canvas"); - context.drawImage(bitmap, 0, 0); - return await this.recognizeCanvas(canvas, options); - } finally { - bitmap.close(); - } - } - - async dispose() { - if (this.#disposed) return; - this.#disposed = true; - this.#assets.release(); - this.#runtimePool.dispose(); - } -} - -export async function createPaddleOcrVlEngine() { - await init(); - const primaryRuntime = await WebRuntime.create(); - const capabilities = JSON.parse(primaryRuntime.capabilities_json()); - const profile = recommendOcrParallelism(capabilities); - const extraRuntimes = await Promise.all( - Array.from( - { length: profile.maxParallelism - 1 }, - () => WebRuntime.create(), - ), - ); - return new PaddleOcrVlEngine( - [primaryRuntime, ...extraRuntimes], - new AdaptiveOcrConcurrency(profile), - ); -} diff --git a/public/vendor/paddleocr-vl/greedy_generation.mjs b/public/vendor/paddleocr-vl/greedy_generation.mjs deleted file mode 100644 index e8cbe7f..0000000 --- a/public/vendor/paddleocr-vl/greedy_generation.mjs +++ /dev/null @@ -1,208 +0,0 @@ -// PVLC M6e9 caller-owned greedy generation driver -// (docs/m6e9_browser_greedy_generation_contract.md). -// -// A pure caller-owned composition of the accepted persistent-session -// operations (prefill/step/logits) into a greedy generation loop. The module -// is self-contained within the runner layer: it imports NOTHING from -// web/tests — the M6c1 top-1 comparator (value descending under the f32 -// total order, ties broken by the smaller token id) is implemented locally. -// The driver holds no runtime state, never mutates its inputs, and surfaces -// session rejections exactly as the runtime raises them (no new failure -// modes). - -const DEFAULT_HIDDEN_SIZE = 1024; -const LOGITS_BYTES = 103424 * 4; - -function fail(message) { - throw new Error(`greedy generation: ${message}`); -} - -function isRecord(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} - -// Exact little-endian f32 widening of one f32 row (the step operand: the -// gathered embedding row). -export function f32RowToBytes(row) { - const bytes = new Uint8Array(row.length * 4); - const view = new DataView(bytes.buffer); - for (let index = 0; index < row.length; index += 1) { - view.setFloat32(index * 4, row[index], true); - } - return bytes; -} - -// The exact M6c1 top-1 comparator over the f32 total order: larger value -// first; -0.0 ranks below +0.0; +NaN above everything, -NaN below everything -// (unreachable on the contract's finite logits, kept so the comparator is a -// faithful total_cmp mirror); exact bit ties are broken by the smaller -// token id. -const TOP1_F32_SCRATCH = new Float32Array(1); -const TOP1_I32_SCRATCH = new Int32Array(TOP1_F32_SCRATCH.buffer); - -function f32TotalOrderKey(value) { - TOP1_F32_SCRATCH[0] = value; - const bits = TOP1_I32_SCRATCH[0]; - return (bits ^ ((bits >> 31) >>> 1)) | 0; -} - -export function compareGreedyTopKEntries(left, right) { - const leftKey = f32TotalOrderKey(left.value); - const rightKey = f32TotalOrderKey(right.value); - if (leftKey !== rightKey) return leftKey > rightKey ? -1 : 1; - return left.index - right.index; -} - -// Top-1 selection over the raw little-endian f32 logits readback, exactly -// the accepted M6c1 comparator. The readback is scanned once, directly. -export function top1FromLogitsBytes(logitsBytes) { - if (!(logitsBytes instanceof Uint8Array) || logitsBytes.byteLength !== LOGITS_BYTES) { - fail(`logits readback must be a ${LOGITS_BYTES}-byte Uint8Array`); - } - const view = new DataView(logitsBytes.buffer, logitsBytes.byteOffset, logitsBytes.byteLength); - let bestIndex = -1; - let bestValue = 0; - for (let index = 0; index < LOGITS_BYTES / 4; index += 1) { - const value = view.getFloat32(index * 4, true); - if (!Number.isFinite(value)) { - fail(`logits readback contains a nonfinite f32 at ${index}`); - } - if ( - bestIndex < 0 || - compareGreedyTopKEntries({ index, value }, { index: bestIndex, value: bestValue }) < 0 - ) { - bestIndex = index; - bestValue = value; - } - } - return { index: bestIndex, value: bestValue }; -} - -// One greedy generation loop over a LIVE M6e8 logits-capable session (the -// prompt was already admitted by the accepted prefill). Every iteration: -// the capacity check from the tracked cache token count (BEFORE any call — -// a zero-step capacity admission yields an empty token id sequence), then -// the accepted pure-readout logits, the exact top-1 selection, the EOS -// stop (no step), otherwise the accepted decode step on the gathered -// embedding row. `embedding` is either a Float32Array [vocab, hidden] table -// or an object with gather(id); it is never mutated. `cacheCapacity` is the -// session's admitted capacity and `initialCacheTokens` the cache token -// count after the prompt admission (the prefill token count, or the caller's -// last accepted step count); later counts are tracked from the runtime's -// own step diagnostics. -export async function runGreedyGeneration(runtime, { - embedding, - eosTokenId, - maxSteps, - cacheCapacity, - initialCacheTokens, - onStep = null, -}) { - if (embedding === null || embedding === undefined) { - fail("embedding table is missing"); - } - const gather = embedding instanceof Float32Array - ? (id) => embedding.subarray(id * DEFAULT_HIDDEN_SIZE, (id + 1) * DEFAULT_HIDDEN_SIZE) - : embedding.gather?.bind(embedding); - if (typeof gather !== "function") { - fail("embedding must be a Float32Array table or expose gather(id)"); - } - if (!Number.isSafeInteger(eosTokenId) || eosTokenId < 0) { - fail("eosTokenId must be an unsigned integer"); - } - if (!Number.isSafeInteger(maxSteps) || maxSteps <= 0) { - fail("maxSteps must be a positive integer"); - } - if (!Number.isSafeInteger(cacheCapacity) || cacheCapacity <= 0) { - fail("cacheCapacity must be a positive integer"); - } - if ( - !Number.isSafeInteger(initialCacheTokens) || - initialCacheTokens < 0 || - initialCacheTokens > cacheCapacity - ) { - fail("initialCacheTokens must satisfy 0 <= tokens <= cacheCapacity"); - } - if (onStep !== null && typeof onStep !== "function") { - fail("onStep must be a function when provided"); - } - - const tokenIds = []; - const steps = []; - const gpuTop1 = typeof runtime.top1_decoder_stack_session === "function"; - let logitsReadbackBytes = 0; - let selectionQueueWallTimeNs = 0; - let cacheTokens = initialCacheTokens; - let stopReason = "max_steps"; - for (let iteration = 0; iteration < maxSteps; iteration += 1) { - if (cacheTokens >= cacheCapacity) { - stopReason = "capacity_exhausted"; - break; - } - const selectionResult = gpuTop1 - ? await runtime.top1_decoder_stack_session() - : await runtime.logits_decoder_stack_session(); - const diagnostics = JSON.parse(selectionResult.diagnostics_json); - if ( - !isRecord(diagnostics) || - diagnostics.cache_tokens !== cacheTokens - ) { - fail( - `logits diagnostics cache_tokens drifted from the tracked ${cacheTokens}`, - ); - } - const logitsBytes = gpuTop1 ? null : selectionResult.logits_bytes; - const top1 = gpuTop1 - ? { index: selectionResult.token_id, value: selectionResult.value } - : top1FromLogitsBytes(logitsBytes); - if ( - !Number.isSafeInteger(top1.index) || - top1.index < 0 || - top1.index >= LOGITS_BYTES / 4 || - !Number.isFinite(top1.value) - ) { - fail("GPU top-1 returned an invalid token id or score"); - } - logitsReadbackBytes += diagnostics.readback_bytes ?? logitsBytes?.byteLength ?? 0; - selectionQueueWallTimeNs += diagnostics.queue_wall_time_ns ?? 0; - const position = cacheTokens; - tokenIds.push(top1.index); - steps.push(Object.freeze({ - position, - selectedTokenId: top1.index, - value: top1.value, - })); - if (onStep !== null) { - await onStep(Object.freeze({ - position, - selectedTokenId: top1.index, - logitsBytes, - gpuTop1, - })); - } - if (top1.index === eosTokenId) { - stopReason = "eos"; - break; - } - const stepResult = await runtime.step_decoder_stack_session( - f32RowToBytes(gather(top1.index)), - ); - const stepDiagnostics = JSON.parse(stepResult.diagnostics_json); - if ( - !isRecord(stepDiagnostics) || - stepDiagnostics.cache_tokens_after !== cacheTokens + 1 - ) { - fail("step diagnostics cache_tokens transition drifted"); - } - cacheTokens += 1; - } - return Object.freeze({ - tokenIds: Object.freeze([...tokenIds]), - stopReason, - steps: Object.freeze(steps), - cacheTokensAfter: cacheTokens, - gpuTop1, - logitsReadbackBytes, - selectionQueueWallTimeNs, - }); -} diff --git a/public/vendor/paddleocr-vl/multimodal_ocr.mjs b/public/vendor/paddleocr-vl/multimodal_ocr.mjs deleted file mode 100644 index e625fb1..0000000 --- a/public/vendor/paddleocr-vl/multimodal_ocr.mjs +++ /dev/null @@ -1,1703 +0,0 @@ -// PVLC M6e10 caller-owned multimodal assembly pipeline -// (docs/m6e10_browser_multimodal_assembly_contract.md). -// -// The host-side image-to-prefill assembly: preprocessing (smart_resize, the -// Pillow bicubic mirror, rescale/normalize, patch extraction), patch -// embedding (the accepted patch_projection_f32 semantics plus bilinear -// position interpolation), prompt ids (per-case pinned text sides plus the -// image-run expansion), embedding assembly, M-RoPE positions, and the -// standard RoPE tables (rope_theta 500000, sections [16, 24, 24], duplicated -// halves, decode-continuation rows from the pinned rope delta). The module -// is self-contained within the runner layer: it imports NOTHING from -// web/tests — the test-side oracle (web/tests/support/m6e10_multimodal_oracle.mjs) -// remains the comparison authority; this module is the production mirror -// composed by the demo page and exercised by the M6e10 browser gate. - -export const MULTIMODAL = Object.freeze({ - factor: 28, - minPixels: 112896, - maxPixels: 1003520, - patchSize: 14, - mergeSize: 2, - imageMean: 0.5, - imageStd: 0.5, - rescale: 1 / 255, - ropeTheta: 500000, - headDim: 128, - mropeSections: Object.freeze([16, 24, 24]), - imageTokenId: 100295, - visionStartTokenId: 101305, - visionHidden: 1152, - visionHeadDim: 72, - visionRopeTheta: 10000, - decoderHidden: 1024, - positionGrid: 27, -}); - -function fail(message) { - throw new Error(`multimodal assembly: ${message}`); -} - -export function enqueueVisionStackLayer(runtime, shardId, payload) { - if ( - typeof runtime?.enqueue_vision_encoder_stack_sharded_layer_json === - "function" - ) { - return { - streaming: true, - status: runtime.enqueue_vision_encoder_stack_sharded_layer_json( - shardId, - payload, - ), - }; - } - if ( - typeof runtime?.run_vision_encoder_stack_sharded_layer_json === "function" - ) { - return { - streaming: false, - completion: runtime.run_vision_encoder_stack_sharded_layer_json( - shardId, - payload, - ), - }; - } - throw new Error("vision stack layer API is unavailable"); -} - -export async function preflightVisionStackShards( - runtime, - shards, - loadShard, - inputBytes, -) { - if ( - typeof runtime?.preflight_vision_encoder_stack_manifest_shard_json === - "function" - ) { - for (const shard of shards) { - runtime.preflight_vision_encoder_stack_manifest_shard_json(shard.id); - } - return "manifest"; - } - if ( - typeof runtime?.preflight_vision_encoder_stack_shard_json === "function" - ) { - for (const [index, shard] of shards.entries()) { - const payload = index === 0 ? inputBytes : await loadShard(shard.id); - runtime.preflight_vision_encoder_stack_shard_json(shard.id, payload); - } - return "payload"; - } - throw new Error("vision stack preflight API is unavailable"); -} - -// One synthetic-oracle vision-stack run over caller-computed embeddings. -// Manifest preflight proves only ordered intent; each payload remains fully -// authenticated by the runtime immediately before its execution GPU effects. -export function visionRope2dTables(gridThw, { - headDim = MULTIMODAL.visionHeadDim, - theta = MULTIMODAL.visionRopeTheta, -} = {}) { - const grids = Array.isArray(gridThw?.[0]) ? gridThw : [gridThw]; - if ( - grids.length === 0 || - !Number.isSafeInteger(headDim) || - headDim <= 0 || - headDim % 4 !== 0 || - !Number.isFinite(theta) || - theta <= 0 || - grids.some((grid) => - !Array.isArray(grid) || - grid.length !== 3 || - grid.some((value) => !Number.isSafeInteger(value) || value <= 0) - ) - ) { - fail("vision RoPE geometry is invalid"); - } - let tokens = 0; - for (const [temporal, height, width] of grids) { - const gridTokens = temporal * height * width; - if (!Number.isSafeInteger(gridTokens) || - !Number.isSafeInteger(tokens + gridTokens)) { - fail("vision RoPE token geometry overflowed"); - } - tokens += gridTokens; - } - const pairCount = headDim / 2; - const frequencyCount = pairCount / 2; - const tableElements = tokens * pairCount; - if (!Number.isSafeInteger(tableElements)) { - fail("vision RoPE table geometry overflowed"); - } - const cos = new Float32Array(tableElements); - const sin = new Float32Array(tableElements); - let token = 0; - for (const [temporal, height, width] of grids) { - for (let time = 0; time < temporal; time += 1) { - for (let y = 0; y < height; y += 1) { - for (let x = 0; x < width; x += 1) { - const tableStart = token * pairCount; - for (let pair = 0; pair < pairCount; pair += 1) { - const position = pair < frequencyCount ? y : x; - const frequency = pair % frequencyCount; - const inverseFrequency = theta ** (-(2 * frequency) / pairCount); - const angle = position * inverseFrequency; - cos[tableStart + pair] = Math.cos(angle); - sin[tableStart + pair] = Math.sin(angle); - } - token += 1; - } - } - } - } - return { cos, sin }; -} - -export async function runSyntheticVisionStack( - runtime, - manifest, - loadShard, - inputBytes, - { gridThw, projectorF16 } = {}, -) { - const startedAt = performance.now(); - const manifestJson = visionStackManifestJson(manifest); - const qkvPolicy = manifest.matrix_weight_storage === "f16" - ? "disabled" - : "required"; - const qkvSelection = runtime.compile_vision_encoder_stack_qkv_selection( - manifestJson, - qkvPolicy, - ); - const residentWeightApiAvailable = - manifest.matrix_weight_storage === "f16" && - manifest.matrix_weight_layout === "input_major" && - typeof runtime?.has_vision_encoder_stack_resident_weights === "function" && - typeof runtime - ?.begin_vision_encoder_stack_sharded_resident_with_activation_strategy_and_qkv_selection_json === - "function" && - typeof runtime - ?.enqueue_vision_encoder_stack_sharded_resident_layer_json === - "function" && - typeof runtime?.finish_vision_encoder_stack_sharded_resident === "function"; - const residentCacheHit = residentWeightApiAvailable - ? runtime.has_vision_encoder_stack_resident_weights(manifestJson) - : false; - const beginJson = residentWeightApiAvailable - ? runtime - .begin_vision_encoder_stack_sharded_resident_with_activation_strategy_and_qkv_selection_json( - manifestJson, - "static_arena_alias", - qkvSelection, - ) - : runtime - .begin_vision_encoder_stack_sharded_with_activation_strategy_and_qkv_selection_json( - manifestJson, - "static_arena_alias", - qkvSelection, - ); - const begin = JSON.parse( - beginJson, - ); - if (begin.phase !== "preflight") { - throw new Error("vision stack begin drifted"); - } - if (gridThw !== undefined) { - if ( - typeof runtime?.configure_vision_encoder_stack_spatial_rope_f32 !== - "function" - ) { - throw new Error("vision stack spatial RoPE API is unavailable"); - } - const { cos, sin } = visionRope2dTables(gridThw); - runtime.configure_vision_encoder_stack_spatial_rope_f32(cos, sin); - } - const preflightStartedAt = performance.now(); - await preflightVisionStackShards(runtime, manifest.shards, loadShard, inputBytes); - const preflightMs = performance.now() - preflightStartedAt; - const executionStartedAt = performance.now(); - await runtime.start_vision_encoder_stack_sharded_json( - manifest.shards[0].id, - inputBytes, - ); - const layerMs = []; - const layerLoadMs = []; - const layerRuntimeMs = []; - for (let layer = 0; layer < manifest.layer_count; layer += 1) { - const shard = manifest.shards[layer + 1]; - const layerStartedAt = performance.now(); - const payload = residentCacheHit ? undefined : await loadShard(shard.id); - const runtimeStartedAt = performance.now(); - const submitted = residentCacheHit - ? { - streaming: true, - status: - runtime.enqueue_vision_encoder_stack_sharded_resident_layer_json( - shard.id, - ), - } - : enqueueVisionStackLayer(runtime, shard.id, payload); - if (!submitted.streaming) await submitted.completion; - layerLoadMs.push(runtimeStartedAt - layerStartedAt); - layerRuntimeMs.push(performance.now() - runtimeStartedAt); - layerMs.push(performance.now() - layerStartedAt); - } - const finishStartedAt = performance.now(); - const lastShard = manifest.shards.at(-1); - const projectorChained = - residentCacheHit && - projectorF16 !== undefined && - typeof runtime - ?.finish_vision_encoder_stack_sharded_resident_with_projector_f16 === - "function"; - const finished = projectorChained - ? await runtime - .finish_vision_encoder_stack_sharded_resident_with_projector_f16( - lastShard.id, - projectorF16.descriptorJson, - projectorF16.imageGridThwJson, - ) - : residentCacheHit - ? await runtime.finish_vision_encoder_stack_sharded_resident(lastShard.id) - : await runtime.finish_vision_encoder_stack_sharded( - lastShard.id, - await loadShard(lastShard.id), - ); - const finishMs = performance.now() - finishStartedAt; - const activationBytes = - (manifest.activation_storage ?? "f32") === "f16" ? 2 : 4; - const planeBytes = - manifest.tokens * MULTIMODAL.visionHidden * activationBytes; - const expectedReadbackBytes = projectorChained - ? projectorF16.outputTokens * projectorF16.outputSize * 2 - : (manifest.checkpoint_layers.length + 1) * planeBytes; - if ( - !(finished.checkpoint_bytes instanceof Uint8Array) || - finished.checkpoint_bytes.byteLength !== expectedReadbackBytes - ) { - throw new Error("vision stack finish readback drifted"); - } - return { - bytes: projectorChained - ? null - : finished.checkpoint_bytes.subarray( - finished.checkpoint_bytes.byteLength - planeBytes, - ), - projectorBytes: projectorChained ? finished.checkpoint_bytes : null, - timings: { - totalMs: performance.now() - startedAt, - preflightMs, - executionMs: performance.now() - executionStartedAt, - finishMs, - layerMs, - layerLoadMs, - layerRuntimeMs, - residentCacheHit, - projectorChained, - finishDiagnostics: JSON.parse(finished.diagnostics_json), - }, - }; -} - -export function widenMultimodalF16Bytes(bytes, label = "F16 tensor") { - if (!(bytes instanceof Uint8Array) || bytes.byteLength % 2 !== 0) { - fail(`${label} byte length is not F16-aligned`); - } - const source = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - const values = new Float32Array(bytes.byteLength / 2); - const bitScratch = new Uint32Array(1); - const floatScratch = new Float32Array(bitScratch.buffer); - for (let index = 0; index < values.length; index += 1) { - const bits = source.getUint16(index * 2, true); - const sign = (bits & 0x8000) << 16; - const exponent = (bits >>> 10) & 0x1f; - const fraction = bits & 0x03ff; - if (exponent === 0) { - if (fraction === 0) { - bitScratch[0] = sign; - values[index] = floatScratch[0]; - } else { - values[index] = (sign === 0 ? 1 : -1) * 2 ** -14 * (fraction / 1024); - } - } else if (exponent === 0x1f) { - bitScratch[0] = sign | 0x7f800000 | (fraction << 13); - values[index] = floatScratch[0]; - } else { - bitScratch[0] = sign | ((exponent + 112) << 23) | (fraction << 13); - values[index] = floatScratch[0]; - } - if (!Number.isFinite(values[index])) { - fail(`${label} contains a nonfinite F16 element at ${index}`); - } - } - return new Uint8Array(values.buffer); -} - -export function narrowMultimodalF32ToF16Bytes( - values, - label = "F32 tensor", -) { - if (!(values instanceof Float32Array)) { - fail(`${label} must be a Float32Array`); - } - const output = new Uint8Array(values.length * 2); - const destination = new DataView(output.buffer); - const bitScratch = new Uint32Array(1); - const floatScratch = new Float32Array(bitScratch.buffer); - const roundShiftToEven = (value, shift) => { - const divisor = 2 ** shift; - const quotient = Math.floor(value / divisor); - const remainder = value - quotient * divisor; - const halfway = divisor / 2; - return quotient + - Number(remainder > halfway || (remainder === halfway && quotient % 2 === 1)); - }; - for (let index = 0; index < values.length; index += 1) { - const value = values[index]; - if (!Number.isFinite(value)) { - fail(`${label} contains a nonfinite F32 element at ${index}`); - } - floatScratch[0] = value; - const bits = bitScratch[0]; - const sign = (bits >>> 16) & 0x8000; - const exponent = (bits >>> 23) & 0xff; - const fraction = bits & 0x7fffff; - let half = sign; - if (exponent === 0) { - half = sign; - } else if (exponent < 103) { - half = sign; - } else if (exponent < 113) { - half = sign | roundShiftToEven( - fraction | 0x800000, - 126 - exponent, - ); - } else { - let halfExponent = exponent - 112; - let halfFraction = roundShiftToEven(fraction, 13); - if (halfFraction === 0x400) { - halfExponent += 1; - halfFraction = 0; - } - if (halfExponent >= 31) { - fail(`${label} overflows F16 at element ${index}`); - } - half = sign | (halfExponent << 10) | halfFraction; - } - destination.setUint16(index * 2, half, true); - } - return output; -} - -export function readMultimodalSafetensors(bytes, label = "safetensors") { - if (!(bytes instanceof Uint8Array) || bytes.byteLength < 8) { - fail(`${label} must be a nonempty Uint8Array`); - } - const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); - const headerLength = Number(view.getBigUint64(0, true)); - const headerEnd = 8 + headerLength; - if (!Number.isSafeInteger(headerLength) || headerLength <= 0 || headerEnd > bytes.byteLength) { - fail(`${label} header length drifted`); - } - const header = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode( - bytes.subarray(8, headerEnd), - )); - const bitScratch = new Uint32Array(1); - const floatScratch = new Float32Array(bitScratch.buffer); - return (name) => { - const info = header[name]; - if (info === undefined) fail(`${label} tensor ${name} is missing`); - if (!Array.isArray(info.shape) || - !info.shape.every((dimension) => Number.isSafeInteger(dimension) && dimension >= 0) || - !Array.isArray(info.data_offsets) || - info.data_offsets.length !== 2) { - fail(`${label} tensor ${name} metadata drifted`); - } - const elements = info.shape.reduce((total, dimension) => total * dimension, 1); - const [begin, end] = info.data_offsets; - const width = info.dtype === "F32" ? 4 : info.dtype === "BF16" || info.dtype === "F16" ? 2 : 0; - if (width === 0 || begin < 0 || end !== begin + elements * width || headerEnd + end > bytes.byteLength) { - fail(`${label} tensor ${name} payload drifted`); - } - if (info.dtype === "F32") { - return new Float32Array(bytes.buffer, bytes.byteOffset + headerEnd + begin, elements); - } - if (info.dtype === "F16") { - const widened = widenMultimodalF16Bytes( - bytes.subarray(headerEnd + begin, headerEnd + end), - `${label} tensor ${name}`, - ); - return new Float32Array(widened.buffer); - } - const values = new Float32Array(elements); - for (let index = 0; index < elements; index += 1) { - const bits = view.getUint16(headerEnd + begin + index * 2, true); - bitScratch[0] = bits << 16; - values[index] = floatScratch[0]; - } - return values; - }; -} - -// --------------------------------------------------------------------------- -// smart_resize (image_processing_paddleocr_vl.py): factor-divisible -// dimensions, pixel budget [min_pixels, max_pixels], aspect preserved as -// closely as possible, Python round-half-even semantics. -function pythonRound(value) { - const floor = Math.floor(value); - const fraction = value - floor; - if (fraction < 0.5) return floor; - if (fraction > 0.5) return floor + 1; - return floor % 2 === 0 ? floor : floor + 1; -} - -export function smartResize(height, width, { - factor = MULTIMODAL.factor, - minPixels = MULTIMODAL.minPixels, - maxPixels = MULTIMODAL.maxPixels, - patchSize = MULTIMODAL.patchSize, -} = {}) { - if (!Number.isSafeInteger(height) || !Number.isSafeInteger(width) || - height <= 0 || width <= 0) { - fail("smart_resize dimensions must be positive integers"); - } - let resizedHeight = height; - let resizedWidth = width; - if (resizedHeight < factor) { - resizedWidth = pythonRound((resizedWidth * factor) / resizedHeight); - resizedHeight = factor; - } - if (resizedWidth < factor) { - resizedHeight = pythonRound((resizedHeight * factor) / resizedWidth); - resizedWidth = factor; - } - if (Math.max(resizedHeight, resizedWidth) / Math.min(resizedHeight, resizedWidth) > 200) { - fail("smart_resize absolute aspect ratio must be smaller than 200"); - } - let heightBar = pythonRound(resizedHeight / factor) * factor; - let widthBar = pythonRound(resizedWidth / factor) * factor; - if (heightBar * widthBar > maxPixels) { - const beta = Math.sqrt((resizedHeight * resizedWidth) / maxPixels); - heightBar = Math.floor(resizedHeight / beta / factor) * factor; - widthBar = Math.floor(resizedWidth / beta / factor) * factor; - } else if (heightBar * widthBar < minPixels) { - const beta = Math.sqrt(minPixels / (resizedHeight * resizedWidth)); - heightBar = Math.ceil((resizedHeight * beta) / factor) * factor; - widthBar = Math.ceil((resizedWidth * beta) / factor) * factor; - } - return { - height: heightBar, - width: widthBar, - gridThw: [1, heightBar / patchSize, widthBar / patchSize], - }; -} - -// --------------------------------------------------------------------------- -// The Pillow bicubic mirror (the HF image processor resizes with PIL -// Image.resize(BICUBIC)): Keys kernel a = -0.5, support 2 (widened by the -// scale on downscale), window built from the center, weights normalized, and -// the two-pass pipeline — HORIZONTAL (width) first, then VERTICAL (height) — -// with the 8-bit quantization of the intermediate and the final image. -function bicubicKernel(value) { - const a = -0.5; - const x = Math.abs(value); - if (x < 1) { - return (a + 2) * x ** 3 - (a + 3) * x ** 2 + 1; - } - if (x < 2) { - return a * x ** 3 - 5 * a * x ** 2 + 8 * a * x - 4 * a; - } - return 0; -} - -export function bicubicAxisPlan(sourceSize, targetSize) { - if (!Number.isSafeInteger(sourceSize) || sourceSize <= 0 || - !Number.isSafeInteger(targetSize) || targetSize <= 0) { - fail("bicubic axis sizes must be positive integers"); - } - const scale = sourceSize / targetSize; - const filterScale = Math.max(scale, 1); - const support = 2 * filterScale; - const plan = []; - for (let index = 0; index < targetSize; index += 1) { - const center = (index + 0.5) * scale; - const xmin = Math.max(Math.trunc(center - support + 0.5), 0); - const xmax = Math.min(Math.trunc(center + support + 0.5), sourceSize); - const weights = []; - let total = 0; - for (let source = xmin; source < xmax; source += 1) { - const weight = bicubicKernel((source - center + 0.5) / filterScale); - weights.push(weight); - total += weight; - } - if (weights.length === 0 || total === 0) { - fail("bicubic weights collapsed to zero"); - } - for (let index2 = 0; index2 < weights.length; index2 += 1) { - weights[index2] /= total; - } - plan.push(Object.freeze({ xmin, weights: Object.freeze(weights) })); - } - return Object.freeze(plan); -} - -export function bicubicResizeF32(input, sourceHeight, sourceWidth, targetHeight, targetWidth, channels = 3) { - if (input.length !== sourceHeight * sourceWidth * channels) { - fail("bicubic input length drifted"); - } - const widthPlan = bicubicAxisPlan(sourceWidth, targetWidth); - const heightPlan = bicubicAxisPlan(sourceHeight, targetHeight); - const intermediate = new Float64Array(sourceHeight * targetWidth * channels); - for (let y = 0; y < sourceHeight; y += 1) { - for (let targetX = 0; targetX < targetWidth; targetX += 1) { - const { xmin, weights } = widthPlan[targetX]; - for (let channel = 0; channel < channels; channel += 1) { - let sum = 0; - for (let k = 0; k < weights.length; k += 1) { - const sourceX = Math.min(xmin + k, sourceWidth - 1); - sum += weights[k] * input[(y * sourceWidth + sourceX) * channels + channel]; - } - intermediate[(y * targetWidth + targetX) * channels + channel] = - Math.min(255, Math.max(0, Math.round(sum))); - } - } - } - const output = new Float32Array(targetHeight * targetWidth * channels); - for (let targetY = 0; targetY < targetHeight; targetY += 1) { - const { xmin, weights } = heightPlan[targetY]; - for (let x = 0; x < targetWidth; x += 1) { - for (let channel = 0; channel < channels; channel += 1) { - let sum = 0; - for (let k = 0; k < weights.length; k += 1) { - const sourceY = Math.min(xmin + k, sourceHeight - 1); - sum += weights[k] * intermediate[(sourceY * targetWidth + x) * channels + channel]; - } - output[(targetY * targetWidth + x) * channels + channel] = - Math.min(255, Math.max(0, Math.round(sum))); - } - } - } - return output; -} - -// --------------------------------------------------------------------------- -// Full preprocessing: decoded RGB pixels (channel-last, values 0..255) → -// smart_resize → bicubic → rescale 1/255 → normalize (x - 0.5) / 0.5 → -// patch extraction [T·gh·gw, 588] with the pinned (t, h, w) patch order and -// (channel, y, x) element order inside a patch. -export function preprocessImage(pixels, sourceHeight, sourceWidth, channels = 3) { - if (!Number.isSafeInteger(sourceHeight) || sourceHeight <= 0 || - !Number.isSafeInteger(sourceWidth) || sourceWidth <= 0) { - fail("preprocess image dimensions must be positive integers"); - } - if (channels !== 3) { - fail("preprocess expects RGB pixels (3 channels)"); - } - if (pixels.length !== sourceHeight * sourceWidth * channels) { - fail("preprocess pixel buffer length drifted"); - } - const input = new Float32Array(pixels.length); - for (let index = 0; index < pixels.length; index += 1) { - const value = pixels[index]; - if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 255) { - fail(`preprocess pixel ${index} is outside the 0..255 range`); - } - input[index] = value; - } - const { height, width, gridThw } = smartResize(sourceHeight, sourceWidth); - const resized = bicubicResizeF32(input, sourceHeight, sourceWidth, height, width, channels); - const [, gridH, gridW] = gridThw; - const patchCount = gridThw[0] * gridH * gridW; - const patchElements = channels * MULTIMODAL.patchSize * MULTIMODAL.patchSize; - const pixelValues = new Float32Array(patchCount * patchElements); - for (let time = 0; time < gridThw[0]; time += 1) { - for (let gridY = 0; gridY < gridH; gridY += 1) { - for (let gridX = 0; gridX < gridW; gridX += 1) { - const patchIndex = (time * gridH + gridY) * gridW + gridX; - for (let channel = 0; channel < channels; channel += 1) { - for (let y = 0; y < MULTIMODAL.patchSize; y += 1) { - for (let x = 0; x < MULTIMODAL.patchSize; x += 1) { - const sourceY = gridY * MULTIMODAL.patchSize + y; - const sourceX = gridX * MULTIMODAL.patchSize + x; - const normalized = - (resized[(sourceY * width + sourceX) * channels + channel] * MULTIMODAL.rescale - - MULTIMODAL.imageMean) / - MULTIMODAL.imageStd; - pixelValues[ - patchIndex * patchElements + - ((channel * MULTIMODAL.patchSize + y) * MULTIMODAL.patchSize + x) - ] = normalized; - } - } - } - } - } - } - return { pixelValues, gridThw, resizedHeight: height, resizedWidth: width }; -} - -// --------------------------------------------------------------------------- -// Patch embedding: the accepted patch_projection_f32 semantics (conv-14 as a -// bias linear over the 588-dim flattened patches, bias accumulator start, -// ascending input order) plus bilinear position interpolation of the -// [27×27, 1152] table (the cpu-ref bilinear_axis rule). -export function patchProjection(pixelValues, weight, bias, { - hiddenSize = MULTIMODAL.visionHidden, -} = {}) { - const patchElements = 3 * MULTIMODAL.patchSize * MULTIMODAL.patchSize; - if (pixelValues.length === 0 || pixelValues.length % patchElements !== 0) { - fail("patch projection input length drifted"); - } - if (weight.length !== hiddenSize * patchElements) { - fail("patch projection weight length drifted"); - } - if (bias.length !== hiddenSize) { - fail("patch projection bias length drifted"); - } - const patchCount = pixelValues.length / patchElements; - const output = new Float32Array(patchCount * hiddenSize); - for (let patch = 0; patch < patchCount; patch += 1) { - for (let channel = 0; channel < hiddenSize; channel += 1) { - let accumulator = bias[channel]; - const weightBase = channel * patchElements; - const patchBase = patch * patchElements; - for (let depth = 0; depth < patchElements; depth += 1) { - accumulator += pixelValues[patchBase + depth] * weight[weightBase + depth]; - } - output[patch * hiddenSize + channel] = accumulator; - } - } - return output; -} - -function bilinearAxis(sourceSize, targetSize, targetIndex) { - const coordinate = targetSize === 1 - ? 0 - : targetIndex * (sourceSize - 1) / (targetSize - 1); - const lower = Math.min(Math.floor(coordinate), sourceSize - 1); - const upper = Math.min(lower + 1, sourceSize - 1); - return [lower, upper, coordinate - lower]; -} - -export function addPositionEmbedding(patchEmbeddings, positionEmbedding, gridThw, { - hiddenSize = MULTIMODAL.visionHidden, - sourceHeight = MULTIMODAL.positionGrid, - sourceWidth = MULTIMODAL.positionGrid, -} = {}) { - const [temporal, gridH, gridW] = gridThw; - if (!(temporal > 0 && gridH > 0 && gridW > 0)) { - fail("position embedding grid drifted"); - } - const patchCount = temporal * gridH * gridW; - if (patchEmbeddings.length !== patchCount * hiddenSize) { - fail("position embedding input length drifted"); - } - if (positionEmbedding.length !== sourceHeight * sourceWidth * hiddenSize) { - fail("position embedding table length drifted"); - } - const output = new Float32Array(patchEmbeddings); - let tokenOffset = 0; - for (let time = 0; time < temporal; time += 1) { - for (let y = 0; y < gridH; y += 1) { - const [sourceY0, sourceY1, yFraction] = bilinearAxis(sourceHeight, gridH, y); - for (let x = 0; x < gridW; x += 1) { - const [sourceX0, sourceX1, xFraction] = bilinearAxis(sourceWidth, gridW, x); - const targetToken = tokenOffset + time * gridH * gridW + y * gridW + x; - const targetStart = targetToken * hiddenSize; - for (let channel = 0; channel < hiddenSize; channel += 1) { - const topLeft = positionEmbedding[(sourceY0 * sourceWidth + sourceX0) * hiddenSize + channel]; - const topRight = positionEmbedding[(sourceY0 * sourceWidth + sourceX1) * hiddenSize + channel]; - const bottomLeft = positionEmbedding[(sourceY1 * sourceWidth + sourceX0) * hiddenSize + channel]; - const bottomRight = positionEmbedding[(sourceY1 * sourceWidth + sourceX1) * hiddenSize + channel]; - const top = topLeft + (topRight - topLeft) * xFraction; - const bottom = bottomLeft + (bottomRight - bottomLeft) * xFraction; - output[targetStart + channel] += top + (bottom - top) * yFraction; - } - } - } - tokenOffset += gridH * gridW; - } - return output; -} - -export function patchEmbedding(pixelValues, { weight, bias, positionEmbedding, gridThw }) { - const patch = patchProjection(pixelValues, weight, bias); - const output = addPositionEmbedding(patch, positionEmbedding, gridThw); - return { patch, output }; -} - -export async function patchEmbeddingWebGpu( - runtime, - pixelValues, - { weight, bias, positionEmbedding, gridThw }, -) { - if (typeof runtime?.run_vision_patch_projection_bytes !== "function") { - fail("WebGPU patch-projection runtime bytes API is unavailable"); - } - const patchElements = 3 * MULTIMODAL.patchSize * MULTIMODAL.patchSize; - if (!(pixelValues instanceof Float32Array) || - pixelValues.length === 0 || - pixelValues.length % patchElements !== 0) { - fail("WebGPU patch-projection input length drifted"); - } - if (!(weight instanceof Float32Array) || - weight.length !== MULTIMODAL.visionHidden * patchElements) { - fail("WebGPU patch-projection weight length drifted"); - } - if (!(bias instanceof Float32Array) || bias.length !== MULTIMODAL.visionHidden) { - fail("WebGPU patch-projection bias length drifted"); - } - const patchCount = pixelValues.length / patchElements; - const execution = await runtime.run_vision_patch_projection_bytes( - JSON.stringify({ - schema_version: 1, - patch_count: patchCount, - input_width: patchElements, - output_width: MULTIMODAL.visionHidden, - weight_storage: "f32", - }), - multimodalF32Bytes(pixelValues), - multimodalF32Bytes(weight), - multimodalF32Bytes(bias), - ); - const checkpointBytes = execution?.checkpoint_bytes; - const expectedBytes = patchCount * MULTIMODAL.visionHidden * 4; - if (!(checkpointBytes instanceof Uint8Array) || - checkpointBytes.byteLength !== expectedBytes) { - fail("WebGPU patch-projection output byte length drifted"); - } - if (typeof execution.diagnostics_json !== "string") { - fail("WebGPU patch-projection diagnostics drifted"); - } - const patch = new Float32Array(checkpointBytes.slice().buffer); - const output = addPositionEmbedding(patch, positionEmbedding, gridThw); - return { - patch, - output, - diagnostics: JSON.parse(execution.diagnostics_json), - }; -} - -// --------------------------------------------------------------------------- -// Prompt ids: the per-case pinned text sides plus the image-run expansion -// (prod(grid) / merge^2 image tokens), exactly the golden processor layout. -export function multimodalPromptInputIds(gridThw, { prefixIds, suffixIds }) { - const [temporal, height, width] = gridThw; - if (!Number.isSafeInteger(temporal) || temporal <= 0 || - !Number.isSafeInteger(height) || height <= 0 || height % MULTIMODAL.mergeSize !== 0 || - !Number.isSafeInteger(width) || width <= 0 || width % MULTIMODAL.mergeSize !== 0) { - fail("prompt grid drifted (dimensions must be positive and merge-divisible)"); - } - if (!Array.isArray(prefixIds) || !Array.isArray(suffixIds) || - prefixIds.length === 0 || suffixIds.length === 0 || - [...prefixIds, ...suffixIds].some((id) => !Number.isSafeInteger(id) || id < 0)) { - fail("prompt text sides drifted"); - } - const imageTokens = temporal * (height / MULTIMODAL.mergeSize) * (width / MULTIMODAL.mergeSize); - const ids = [...prefixIds]; - for (let index = 0; index < imageTokens; index += 1) { - ids.push(MULTIMODAL.imageTokenId); - } - ids.push(...suffixIds); - return ids; -} - -// --------------------------------------------------------------------------- -// The accepted assemble_multimodal_embeddings_f32 semantics: the text rows -// are gathered from the token embedding table for every id, then the image -// rows are scattered from the projected image embeddings IN ORDER. -export function assembleEmbeddings(tokenEmbedding, projectedImageEmbeddings, inputIds, { - imageTokenId = MULTIMODAL.imageTokenId, - hiddenSize = MULTIMODAL.decoderHidden, -} = {}) { - if (!Array.isArray(inputIds) || inputIds.length === 0 || - !inputIds.every((id) => Number.isSafeInteger(id) && id >= 0)) { - fail("assembly input ids drifted"); - } - if (typeof tokenEmbedding?.gather !== "function") { - fail("assembly token embedding table must expose gather(id)"); - } - const imageRows = inputIds.filter((id) => id === imageTokenId).length; - if (projectedImageEmbeddings.length !== imageRows * hiddenSize) { - fail(`assembly projected image rows drifted: expected ${imageRows}`); - } - const output = new Float32Array(inputIds.length * hiddenSize); - for (let row = 0; row < inputIds.length; row += 1) { - output.set(tokenEmbedding.gather(inputIds[row]), row * hiddenSize); - } - let projectedRow = 0; - for (let row = 0; row < inputIds.length; row += 1) { - if (inputIds[row] !== imageTokenId) continue; - output.set( - projectedImageEmbeddings.subarray(projectedRow * hiddenSize, (projectedRow + 1) * hiddenSize), - row * hiddenSize, - ); - projectedRow += 1; - } - if (projectedRow !== imageRows) { - fail("assembly scatter row count drifted"); - } - return output; -} - -// --------------------------------------------------------------------------- -// The accepted mrope_position_ids semantics: text runs share one counter, -// image tokens carry [t, h, w] grid positions over the MERGED grid, the next -// text run continues at visual_start + max(h, w) + 1, and the decode -// continuation rows use rope(j + rope_delta). -export function mropePositions(inputIds, gridThw, { - imageTokenId = MULTIMODAL.imageTokenId, - visionStartTokenId = MULTIMODAL.visionStartTokenId, - spatialMergeSize = MULTIMODAL.mergeSize, -} = {}) { - if (!Array.isArray(inputIds) || inputIds.length === 0 || - !inputIds.every((id) => Number.isSafeInteger(id) && id >= 0)) { - fail("mrope input ids drifted"); - } - if (imageTokenId === visionStartTokenId) { - fail("mrope token boundaries drifted"); - } - const [temporal, rawHeight, rawWidth] = gridThw; - if (!Number.isSafeInteger(temporal) || temporal <= 0 || - !Number.isSafeInteger(rawHeight) || rawHeight <= 0 || rawHeight % spatialMergeSize !== 0 || - !Number.isSafeInteger(rawWidth) || rawWidth <= 0 || rawWidth % spatialMergeSize !== 0) { - fail("mrope grid drifted (dimensions must be positive and merge-divisible)"); - } - const grid = { - temporal, - height: rawHeight / spatialMergeSize, - width: rawWidth / spatialMergeSize, - }; - grid.tokens = grid.temporal * grid.height * grid.width; - - const visionStart = inputIds.indexOf(visionStartTokenId); - if (visionStart < 0) { - fail("mrope input ids contain no vision start token"); - } - if (inputIds.indexOf(visionStartTokenId, visionStart + 1) !== -1) { - fail("mrope input ids contain a second vision start token"); - } - const imageStart = visionStart + 1; - const imageEnd = imageStart + grid.tokens; - if (imageEnd > inputIds.length || - !inputIds.slice(imageStart, imageEnd).every((id) => id === imageTokenId) || - inputIds[imageEnd] === imageTokenId) { - fail("mrope image run length drifted"); - } - if (!inputIds.slice(imageEnd).every( - (id) => id !== imageTokenId && id !== visionStartTokenId, - )) { - fail("mrope input ids contain image tokens outside the image run"); - } - - const positionIds = [ - new Float64Array(inputIds.length), - new Float64Array(inputIds.length), - new Float64Array(inputIds.length), - ]; - for (let index = 0; index < imageStart; index += 1) { - positionIds[0][index] = index; - positionIds[1][index] = index; - positionIds[2][index] = index; - } - const visualStart = imageStart; - for (let time = 0; time < grid.temporal; time += 1) { - for (let y = 0; y < grid.height; y += 1) { - for (let x = 0; x < grid.width; x += 1) { - const token = imageStart + (time * grid.height + y) * grid.width + x; - positionIds[0][token] = visualStart; - positionIds[1][token] = visualStart + y; - positionIds[2][token] = visualStart + x; - } - } - } - const nextPosition = visualStart + Math.max(grid.height - 1, grid.width - 1) + 1; - for (let index = imageEnd; index < inputIds.length; index += 1) { - const position = nextPosition + (index - imageEnd); - positionIds[0][index] = position; - positionIds[1][index] = position; - positionIds[2][index] = position; - } - let maxPosition = 0; - for (const axis of positionIds) { - for (const value of axis) maxPosition = Math.max(maxPosition, value); - } - return { - positionIds, - ropeDelta: maxPosition + 1 - inputIds.length, - }; -} - -// --------------------------------------------------------------------------- -// Standard RoPE tables in the accepted axis-major layout [3, tokens, 128] -// (axis planes in the pinned [16, 24, 24] section layout, duplicated second -// half), with the decode-continuation rows [promptTokens, capacity) filled -// from rope(j + ropeDelta) — the same rows the M6e8 decode flow consumes. -export function ropeTables(positionIds, ropeDelta, { - capacity = null, - theta = MULTIMODAL.ropeTheta, - headDim = MULTIMODAL.headDim, -} = {}) { - if (!Array.isArray(positionIds) || positionIds.length !== 3) { - fail("rope positions drifted"); - } - const promptTokens = positionIds[0].length; - if (promptTokens === 0 || - positionIds[1].length !== promptTokens || positionIds[2].length !== promptTokens) { - fail("rope position axis length drifted"); - } - if (!Number.isSafeInteger(ropeDelta)) { - fail("rope delta drifted"); - } - const tokens = capacity ?? promptTokens; - if (!Number.isSafeInteger(tokens) || tokens < promptTokens) { - fail("rope table capacity drifted"); - } - if (typeof theta !== "number" || !Number.isFinite(theta) || theta <= 0) { - fail("rope theta drifted"); - } - const halfDim = headDim / 2; - const inverseFrequencies = new Float64Array(halfDim); - for (let index = 0; index < halfDim; index += 1) { - inverseFrequencies[index] = theta ** (-(2 * index) / headDim); - } - const cos = new Float32Array(3 * tokens * headDim); - const sin = new Float32Array(3 * tokens * headDim); - for (let axis = 0; axis < 3; axis += 1) { - for (let token = 0; token < tokens; token += 1) { - const position = token < promptTokens - ? positionIds[axis][token] - : token + ropeDelta; - for (let dim = 0; dim < headDim; dim += 1) { - const half = dim >= halfDim ? dim - halfDim : dim; - const angle = position * inverseFrequencies[half]; - const index = (axis * tokens + token) * headDim + dim; - cos[index] = Math.cos(angle); - sin[index] = Math.sin(angle); - } - } - } - return { cos, sin }; -} - -// --------------------------------------------------------------------------- -// Caller-owned detokenization for the pinned tokenizer.json (SentencePiece- -// style BPE: "▁" -> " ", <0xNN> byte fallback, added_tokens with special -// flags suppressed). -export function loadMultimodalTokenizer(bytes) { - if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) { - fail("tokenizer must be a nonempty Uint8Array"); - } - const document = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); - if (document?.model?.type !== "BPE" || - typeof document.model.vocab !== "object" || document.model.vocab === null || - !Array.isArray(document.added_tokens)) { - fail("tokenizer schema drifted from the pinned BPE layout"); - } - const idToToken = new Map(); - for (const [token, id] of Object.entries(document.model.vocab)) { - if (!Number.isSafeInteger(id) || id < 0) { - fail("tokenizer vocab id drifted"); - } - idToToken.set(id, token); - } - const addedById = new Map(); - for (const added of document.added_tokens) { - if (!Number.isSafeInteger(added.id) || added.id < 0 || - typeof added.content !== "string" || typeof added.special !== "boolean") { - fail("tokenizer added_tokens entry drifted"); - } - addedById.set(added.id, added); - } - const byteFallback = /^<0x[0-9A-Fa-f]{2}>$/; - function detokenize(ids) { - if (!Array.isArray(ids) || !ids.every((id) => Number.isSafeInteger(id) && id >= 0)) { - fail("detokenize ids must be unsigned integers"); - } - const output = []; - for (const id of ids) { - const added = addedById.get(id); - if (added !== undefined && added.special) continue; - const piece = added === undefined ? idToToken.get(id) : added.content; - if (piece === undefined) { - fail(`detokenize unknown token id ${id}`); - } - if (byteFallback.test(piece)) { - output.push(Number.parseInt(piece.slice(3, 5), 16)); - } else { - for (const byte of new TextEncoder().encode(piece.replaceAll("▁", " "))) { - output.push(byte); - } - } - } - return new TextDecoder("utf-8").decode(new Uint8Array(output)); - } - return Object.freeze({ idToToken, detokenize }); -} - -// Exact little-endian f32 widening of a row of f32 values (the prefill -// hidden operand layout). -export function multimodalF32Bytes(values) { - const bytes = new Uint8Array(values.length * 4); - const view = new DataView(bytes.buffer); - for (let index = 0; index < values.length; index += 1) { - view.setFloat32(index * 4, values[index], true); - } - return bytes; -} - -// --------------------------------------------------------------------------- -// Per-case decoder session pack builder (PVLCPK01, the accepted M6e6/M6e8 -// layout authority mirrored in the runner layer): the 11 accepted decoder -// weight shards plus `weights.final_layernorm` and `weights.lm_head` in the -// pinned order, canonical-JSON manifest/descriptor, 56-byte fixed directory -// entries, 256-byte section alignment. The demo and the browser page build -// per-case packs in-page because the rope tables and the cache capacity are -// per-case pipeline outputs; the decoder weights are the accepted official -// payloads. `blake3Hex` is the digest authority (the WASM runtime's -// blake3_bytes_hex in the browser). -const SESSION_PACK_SHARD_IDS = Object.freeze([ - "weights.input_layernorm", - "weights.q_proj", - "weights.k_proj", - "weights.v_proj", - "weights.o_proj", - "weights.mrope_cos", - "weights.mrope_sin", - "weights.post_attention_layernorm", - "weights.gate_proj", - "weights.up_proj", - "weights.down_proj", - "weights.final_layernorm", - "weights.lm_head", -]); - -const SESSION_PACK_SHARD_ROLES = Object.freeze({ - "weights.input_layernorm": "norm1", - "weights.q_proj": "q", - "weights.k_proj": "k", - "weights.v_proj": "v", - "weights.o_proj": "o", - "weights.mrope_cos": "ropeCos", - "weights.mrope_sin": "ropeSin", - "weights.post_attention_layernorm": "norm2", - "weights.gate_proj": "gate", - "weights.up_proj": "up", - "weights.down_proj": "down", - "weights.final_layernorm": "finalNorm", - "weights.lm_head": "lmHead", -}); - -const SESSION_PACK_MODEL_REVISION = "66317acc4c9fc17bd154591ce650735cd2855f3e"; -const SESSION_PACK_MODEL_ID = "PaddlePaddle/PaddleOCR-VL-1.6"; -const SESSION_PACK_HEADER_BYTES = 32; -const SESSION_PACK_DIRECTORY_FIXED_BYTES = 56; -const SESSION_PACK_SECTION_ALIGNMENT = 256; - -function sessionPackCanonicalJson(value, formatNumber = JSON.stringify) { - if (value === null || typeof value === "string" || typeof value === "boolean") { - return JSON.stringify(value); - } - if (typeof value === "number") { - if (!Number.isFinite(value)) { - fail("session pack JSON number is not finite"); - } - return formatNumber(value); - } - if (Array.isArray(value)) { - return `[${value.map((item) => sessionPackCanonicalJson(item, formatNumber)).join(",")}]`; - } - if (typeof value !== "object") { - fail("session pack JSON value is unsupported"); - } - const entries = Object.keys(value) - .sort() - .map((key) => `${JSON.stringify(key)}:${sessionPackCanonicalJson(value[key], formatNumber)}`); - return `{${entries.join(",")}}`; -} - -function sessionPackCanonicalJsonBytes(value, formatNumber) { - return new TextEncoder().encode(`${sessionPackCanonicalJson(value, formatNumber)}\n`); -} - -function sessionPackAlignUp(value, alignment) { - const remainder = value % alignment; - return remainder === 0 ? value : value + alignment - remainder; -} - -function sessionPackDigestBytes(hex) { - const bytes = new Uint8Array(32); - for (let index = 0; index < 32; index += 1) { - bytes[index] = Number.parseInt(hex.slice(index * 2, index * 2 + 2), 16); - } - return bytes; -} - -export function buildMultimodalSessionPack({ - descriptor, - weights, - blake3Hex, - oracle = "official_l3", - caseId = "official.decoder_stack_multimodal_demo", - weightStorage = "f32", - checkpointIdentity = null, -}) { - if (typeof blake3Hex !== "function") { - fail("session pack builder needs a BLAKE3 digest function"); - } - if (oracle !== "synthetic" && oracle !== "official_l3") { - fail("unknown session pack oracle"); - } - if (typeof caseId !== "string" || caseId.length === 0) { - fail("invalid session pack case id"); - } - if (!Number.isSafeInteger(descriptor.prefix_tokens) || descriptor.prefix_tokens < 0 || - !Number.isSafeInteger(descriptor.cache_capacity) || - descriptor.cache_capacity <= descriptor.prefix_tokens) { - fail("session pack descriptor cache geometry drifted"); - } - if (weightStorage !== "f32" && weightStorage !== "f16") { - fail("session pack weight storage is unsupported"); - } - if (weightStorage === "f16" && - (checkpointIdentity === null || - typeof checkpointIdentity !== "object" || - typeof checkpointIdentity.blake3 !== "string" || - !/^[0-9a-f]{64}$/.test(checkpointIdentity.blake3) || - !Number.isSafeInteger(checkpointIdentity.bytes) || - checkpointIdentity.bytes <= 0)) { - fail("F16 session pack checkpoint identity is invalid"); - } - const payloadEntries = SESSION_PACK_SHARD_IDS.map((id) => { - const values = weights[SESSION_PACK_SHARD_ROLES[id]]; - const ropeTable = id === "weights.mrope_cos" || id === "weights.mrope_sin"; - const expectedF32 = weightStorage === "f32" || ropeTable; - if (expectedF32 && !(values instanceof Float32Array)) { - fail(`session pack shard ${id} operand is missing or not Float32Array`); - } - if (!expectedF32 && - (!(values instanceof Uint8Array) || values.byteLength === 0 || - values.byteLength % 2 !== 0)) { - fail(`session pack shard ${id} operand is missing or not aligned F16 bytes`); - } - const payload = values instanceof Float32Array - ? new Uint8Array(values.buffer, values.byteOffset, values.byteLength) - : values; - return { - id, - kind: 2, - payload, - blake3: blake3Hex(payload), - dtype: expectedF32 ? "f32" : "f16", - }; - }); - const descriptorObject = { - schema_version: 1, - oracle, - case_id: caseId, - model_revision: SESSION_PACK_MODEL_REVISION, - layers: 18, - hidden_size: 1024, - intermediate_size: 3072, - query_heads: 16, - key_value_heads: 2, - head_dim: 128, - query_width: 2048, - key_value_width: 256, - prefix_tokens: descriptor.prefix_tokens, - cache_capacity: descriptor.cache_capacity, - rms_norm_epsilon: 0.00001, - mrope_sections: [16, 24, 24], - ...(weightStorage === "f16" - ? { - checkpoint_blake3: checkpointIdentity.blake3, - checkpoint_bytes: checkpointIdentity.bytes, - weight_storage: "f16", - } - : {}), - shards: Object.fromEntries( - payloadEntries.map((entry) => [ - entry.id, - { - bytes: entry.payload.byteLength, - blake3: entry.blake3, - ...(weightStorage === "f16" ? { dtype: entry.dtype } : {}), - }, - ]), - ), - }; - const descriptorPayload = sessionPackCanonicalJsonBytes(descriptorObject); - const manifestPayload = sessionPackCanonicalJsonBytes({ - compiler_build: "0".repeat(64), - compiler_model_abi: 1, - context_limit: 4096, - model_id: SESSION_PACK_MODEL_ID, - model_revision: SESSION_PACK_MODEL_REVISION, - precision_profile: weightStorage === "f16" ? "balanced" : "fidelity", - resolution_buckets: [[672, 672]], - }); - const sections = [ - { - id: "ir.decoder_stack_00", - kind: 1, - payload: descriptorPayload, - blake3: blake3Hex(descriptorPayload), - }, - ...payloadEntries, - ]; - const directoryEntries = sections.map((section) => { - const idBytes = new TextEncoder().encode(section.id); - const entryBytes = sessionPackAlignUp( - SESSION_PACK_DIRECTORY_FIXED_BYTES + idBytes.length, - 8, - ); - return { ...section, idBytes, entryBytes }; - }); - const directoryLength = directoryEntries.reduce( - (total, entry) => total + entry.entryBytes, - 0, - ); - let cursor = SESSION_PACK_HEADER_BYTES + manifestPayload.byteLength + directoryLength; - for (const entry of directoryEntries) { - cursor = sessionPackAlignUp(cursor, SESSION_PACK_SECTION_ALIGNMENT); - entry.offset = cursor; - cursor += entry.payload.byteLength; - } - const fileLength = cursor; - const pack = new Uint8Array(fileLength); - const view = new DataView(pack.buffer); - pack.set(new TextEncoder().encode("PVLCPK01"), 0); - view.setUint32(8, 1, true); - view.setUint32(12, manifestPayload.byteLength, true); - view.setUint32(16, directoryLength, true); - view.setUint32(20, directoryEntries.length, true); - view.setBigUint64(24, BigInt(fileLength), true); - pack.set(manifestPayload, SESSION_PACK_HEADER_BYTES); - let directoryCursor = SESSION_PACK_HEADER_BYTES + manifestPayload.byteLength; - for (const entry of directoryEntries) { - view.setUint16(directoryCursor, entry.idBytes.length, true); - view.setUint8(directoryCursor + 2, entry.kind); - view.setUint8(directoryCursor + 3, 0); - view.setUint32(directoryCursor + 4, SESSION_PACK_SECTION_ALIGNMENT, true); - view.setBigUint64(directoryCursor + 8, BigInt(entry.offset), true); - view.setBigUint64(directoryCursor + 16, BigInt(entry.payload.byteLength), true); - pack.set(sessionPackDigestBytes(entry.blake3), directoryCursor + 24); - pack.set(entry.idBytes, directoryCursor + SESSION_PACK_DIRECTORY_FIXED_BYTES); - directoryCursor += entry.entryBytes; - pack.set(entry.payload, entry.offset); - } - return pack; -} - -// --------------------------------------------------------------------------- -// Minimal PVLCPK01 shard reader for the accepted decoder session packs -// (their shard order is the pinned semantic order, NOT the canonical sorted -// order the projector pack family uses): walks the directory, maps shard id -// to its payload bytes, and verifies every directory digest against the -// payload via the caller-provided BLAKE3 function. -export function readSessionPackShardBytes(packBytes, blake3Hex, shardIds) { - if (!(packBytes instanceof Uint8Array)) { - fail("session pack must be Uint8Array"); - } - if (typeof blake3Hex !== "function") { - fail("session pack reader needs a BLAKE3 digest function"); - } - const view = new DataView(packBytes.buffer, packBytes.byteOffset, packBytes.byteLength); - if (new TextDecoder().decode(packBytes.subarray(0, 8)) !== "PVLCPK01") { - fail("session pack magic mismatch"); - } - if (view.getUint32(8, true) !== 1) { - fail("session pack version is unsupported"); - } - const manifestLength = view.getUint32(12, true); - const directoryLength = view.getUint32(16, true); - const sectionCount = view.getUint32(20, true); - const fileLength = view.getBigUint64(24, true); - if (fileLength !== BigInt(packBytes.byteLength)) { - fail("session pack declared length drifted"); - } - const decoder = new TextDecoder(); - const shards = new Map(); - let cursor = SESSION_PACK_HEADER_BYTES + manifestLength; - const directoryEnd = cursor + directoryLength; - for (let index = 0; index < sectionCount; index += 1) { - const idLength = view.getUint16(cursor, true); - const offset = Number(view.getBigUint64(cursor + 8, true)); - const byteLength = Number(view.getBigUint64(cursor + 16, true)); - const id = decoder.decode(packBytes.subarray(cursor + 56, cursor + 56 + idLength)); - const digest = [...packBytes.subarray(cursor + 24, cursor + 56)] - .map((byte) => byte.toString(16).padStart(2, "0")) - .join(""); - const payload = packBytes.subarray(offset, offset + byteLength); - if (blake3Hex(payload) !== digest) { - fail(`session pack shard ${id} directory digest mismatch`); - } - shards.set(id, payload); - cursor += sessionPackAlignUp(SESSION_PACK_DIRECTORY_FIXED_BYTES + idLength, 8); - } - if (cursor !== directoryEnd) { - fail("session pack directory length drifted"); - } - const wanted = shardIds ?? SESSION_PACK_SHARD_IDS; - for (const id of wanted) { - if (!shards.has(id)) { - fail(`session pack shard ${id} is missing`); - } - } - return shards; -} - -export function readSessionPackShards(packBytes, blake3Hex, shardIds) { - const shards = readSessionPackShardBytes(packBytes, blake3Hex, shardIds); - const wanted = shardIds ?? SESSION_PACK_SHARD_IDS; - const floats = new Map(); - for (const id of wanted) { - const payload = shards.get(id); - floats.set( - id, - new Float32Array(payload.buffer, payload.byteOffset, payload.byteLength / 4), - ); - } - return floats; -} - -// --------------------------------------------------------------------------- -// Arbitrary-input admission (M6e11). The accepted M3 vision stack session -// and the M4 projector session already admit caller-declared -// `synthetic`-oracle manifests/packs: provenance-free, structurally -// validated shard directories (crates/pvlc-pack/src/vision_stack_shards.rs — -// Synthetic rejects only official provenance fields, the shard directory is -// validated for id/kind/order/bytes/blake3 form; and -// crates/pvlc-pack/src/projector_self_test.rs — the synthetic projector -// descriptor rejects official provenance and official profile names). The -// builders below declare exactly that accepted surface with the official -// weights and the caller-computed inputs. The sealed official -// manifests/packs keep their accepted provenance paths unchanged. - -// A `synthetic`-oracle vision-stack manifest for a caller-computed input: -// tokens and cu_seqlens from the image grid, checkpoint layers [0, 1, 13, -// 26], the pinned vision geometry (1152/16/72/4304/eps 1e-6, 27 layers), and -// NO provenance fields (golden_bundle_digest/semantic_fingerprint must be -// ABSENT — the synthetic oracle rejects their presence). `weightShards` are -// the accepted official weight shard pins ({id, bytes, blake3} copied from -// the locked official manifest); the input.embeddings pin is declared from -// the caller-computed patch embeddings. -export function buildVisionStackManifest({ - tokens, - weightShards, - inputBlake3, - caseId = "multimodal.arbitrary_vision_stack", - matrixWeightStorage = "f32", - matrixWeightLayout = "output_major", - vectorWeightStorage = "f32", - activationStorage = "f32", - checkpointLayers = [0, 1, 13, 26], -}) { - if (!Number.isSafeInteger(tokens) || tokens <= 0) { - fail("vision-stack synthetic manifest token count drifted"); - } - if (typeof caseId !== "string" || caseId.length === 0 || caseId.length > 256 || - !/^[a-zA-Z0-9._/-]+$/.test(caseId)) { - fail("vision-stack synthetic manifest case id is invalid"); - } - if (!Array.isArray(weightShards) || weightShards.length !== 28) { - fail("vision-stack synthetic manifest weight shard count drifted"); - } - if (typeof inputBlake3 !== "string" || !/^[0-9a-f]{64}$/.test(inputBlake3)) { - fail("vision-stack synthetic manifest input digest is invalid"); - } - if (matrixWeightStorage !== "f32" && matrixWeightStorage !== "f16") { - fail("vision-stack matrix weight storage is invalid"); - } - if (matrixWeightLayout !== "output_major" && matrixWeightLayout !== "input_major") { - fail("vision-stack matrix weight layout is invalid"); - } - if (matrixWeightLayout === "input_major" && matrixWeightStorage !== "f16") { - fail("vision-stack input-major matrix weight layout requires FP16 storage"); - } - if (vectorWeightStorage !== "f32" && vectorWeightStorage !== "f16") { - fail("vision-stack vector weight storage is invalid"); - } - if (activationStorage !== "f32" && activationStorage !== "f16") { - fail("vision-stack activation storage is invalid"); - } - const legacyF32 = - vectorWeightStorage === "f32" && activationStorage === "f32"; - const fullF16 = - matrixWeightStorage === "f16" && - matrixWeightLayout === "input_major" && - vectorWeightStorage === "f16" && - activationStorage === "f16"; - if (!legacyF32 && !fullF16) { - fail("vision-stack precision profile is incoherent"); - } - if ( - !Array.isArray(checkpointLayers) || - checkpointLayers.some( - (layer, index) => - !Number.isSafeInteger(layer) || - layer < 0 || - layer >= 27 || - (index > 0 && checkpointLayers[index - 1] >= layer), - ) - ) { - fail("vision-stack checkpoint layer selection is invalid"); - } - const activationBytes = activationStorage === "f16" ? 2 : 4; - const shards = [ - { - id: "input.embeddings", - kind: "input", - layer_index: null, - bytes: tokens * 1152 * activationBytes, - blake3: inputBlake3, - }, - ...weightShards.map((shard) => ({ - id: shard.id, - kind: shard.kind, - layer_index: shard.layer_index, - bytes: shard.bytes, - blake3: shard.blake3, - })), - ]; - if (shards.length !== 29 || - shards[1].id !== "weights.vision_layer.00" || - shards[27].id !== "weights.vision_layer.26" || - shards[28].id !== "weights.vision_post_norm") { - fail("vision-stack synthetic manifest shard directory drifted"); - } - return { - schema_version: 1, - oracle: "synthetic", - case_id: caseId, - model_id: "PaddlePaddle/PaddleOCR-VL-1.6", - model_revision: "66317acc4c9fc17bd154591ce650735cd2855f3e", - compiler_model_abi: 1, - compiler_build: "0".repeat(64), - golden_bundle_digest: null, - semantic_fingerprint: null, - ...(matrixWeightStorage === "f16" - ? { matrix_weight_storage: "f16" } - : {}), - ...(matrixWeightLayout === "input_major" - ? { matrix_weight_layout: "input_major" } - : {}), - ...(vectorWeightStorage === "f16" - ? { vector_weight_storage: "f16" } - : {}), - ...(activationStorage === "f16" - ? { activation_storage: "f16" } - : {}), - tokens, - hidden_size: 1152, - attention_heads: 16, - head_dim: 72, - intermediate_size: 4304, - layer_norm_epsilon: 0.000001, - cu_seqlens: [0, tokens], - layer_count: 27, - checkpoint_layers: [...checkpointLayers], - shards, - }; -} - -// Generic PVLCPK01 section writer for the projector self-test pack family: -// sections are laid out in the canonical strictly-increasing id order (the -// projector pack family requires it), 56-byte fixed directory entries, -// 256-byte section alignment, each payload digest declared in its directory -// entry. -export function buildCanonicalPvlcPack({ manifestObject, sections }) { - const sorted = [...sections].sort((left, right) => left.id.localeCompare(right.id)); - for (let index = 1; index < sorted.length; index += 1) { - if (sorted[index - 1].id >= sorted[index].id) { - fail("canonical pack section ids are not strictly increasing"); - } - } - const manifestPayload = sessionPackCanonicalJsonBytes(manifestObject); - const directoryEntries = sorted.map((section) => { - const idBytes = new TextEncoder().encode(section.id); - const entryBytes = sessionPackAlignUp( - SESSION_PACK_DIRECTORY_FIXED_BYTES + idBytes.length, - 8, - ); - return { ...section, idBytes, entryBytes }; - }); - const directoryLength = directoryEntries.reduce( - (total, entry) => total + entry.entryBytes, - 0, - ); - let cursor = SESSION_PACK_HEADER_BYTES + manifestPayload.byteLength + directoryLength; - for (const entry of directoryEntries) { - cursor = sessionPackAlignUp(cursor, entry.alignment ?? SESSION_PACK_SECTION_ALIGNMENT); - entry.offset = cursor; - cursor += entry.bytes.byteLength; - } - const fileLength = cursor; - const pack = new Uint8Array(fileLength); - const view = new DataView(pack.buffer); - pack.set(new TextEncoder().encode("PVLCPK01"), 0); - view.setUint32(8, 1, true); - view.setUint32(12, manifestPayload.byteLength, true); - view.setUint32(16, directoryLength, true); - view.setUint32(20, directoryEntries.length, true); - view.setBigUint64(24, BigInt(fileLength), true); - pack.set(manifestPayload, SESSION_PACK_HEADER_BYTES); - let directoryCursor = SESSION_PACK_HEADER_BYTES + manifestPayload.byteLength; - for (const entry of directoryEntries) { - view.setUint16(directoryCursor, entry.idBytes.length, true); - view.setUint8(directoryCursor + 2, entry.kind); - view.setUint8(directoryCursor + 3, 0); - view.setUint32(directoryCursor + 4, entry.alignment ?? SESSION_PACK_SECTION_ALIGNMENT, true); - view.setBigUint64(directoryCursor + 8, BigInt(entry.offset), true); - view.setBigUint64(directoryCursor + 16, BigInt(entry.bytes.byteLength), true); - pack.set(sessionPackDigestBytes(entry.blake3), directoryCursor + 24); - pack.set(entry.idBytes, directoryCursor + SESSION_PACK_DIRECTORY_FIXED_BYTES); - directoryCursor += entry.entryBytes; - pack.set(entry.bytes, entry.offset); - } - return pack; -} - -// A `synthetic`-oracle projector self-test pack for a caller-computed input: -// the accepted official projector weights (with their {bytes, blake3} pin), -// a caller-declared input section (the computed vision.final bytes), and a -// structurally valid expected section (the self-test checkpoint surface; the -// runtime requires only its exact byte length — for the pinned golden case -// it carries the golden projector.final, for arbitrary images it is a -// caller-owned placeholder of the same length). The descriptor carries NO -// provenance and a non-official profile name (the synthetic oracle rejects -// both). -// The pinned projector LayerNorm epsilon (fround(1e-5)). The canonical -// descriptor byte form is produced by serde_json re-serialization, which -// prints this f64 in ryu scientific form ("9.999999747378752e-6") while -// JSON.stringify prints the decimal form — the formatter below bridges that -// one constant (all other descriptor numbers are integers). -const PROJECTOR_LAYER_NORM_EPSILON = Math.fround(0.00001); -const PROJECTOR_LAYER_NORM_EPSILON_JSON = "9.999999747378752e-6"; - -function projectorDescriptorNumberJson(value) { - return value === PROJECTOR_LAYER_NORM_EPSILON - ? PROJECTOR_LAYER_NORM_EPSILON_JSON - : JSON.stringify(value); -} - -export function buildSyntheticProjectorPack({ - weightsBytes, - weightsBlake3, - profile, - imageGridThw, - inputBytes, - expectedBytes, - blake3Hex, -}) { - if (!(weightsBytes instanceof Uint8Array) || - typeof weightsBlake3 !== "string" || !/^[0-9a-f]{64}$/.test(weightsBlake3)) { - fail("synthetic projector weights pin drifted"); - } - if (typeof profile !== "string" || - profile === "ocr-clean-latin-l3" || profile === "table-simple-l2" || - !/^[a-zA-Z0-9._/-]+$/.test(profile)) { - fail("synthetic projector profile name drifted"); - } - if (!(inputBytes instanceof Uint8Array) || !(expectedBytes instanceof Uint8Array)) { - fail("synthetic projector input/expected sections must be Uint8Array"); - } - if (typeof blake3Hex !== "function") { - fail("synthetic projector pack builder needs a BLAKE3 digest function"); - } - const grid = imageGridThw[0]; - const tokens = grid[0] * grid[1] * grid[2]; - const outputTokens = (grid[1] / 2) * (grid[2] / 2) * grid[0]; - if (inputBytes.byteLength !== tokens * 1152 * 4) { - fail("synthetic projector input byte length drifted"); - } - if (expectedBytes.byteLength !== outputTokens * 1024 * 4) { - fail("synthetic projector expected byte length drifted"); - } - const descriptor = { - schema_version: 1, - oracle: "synthetic", - model_revision: "66317acc4c9fc17bd154591ce650735cd2855f3e", - hidden_size: 1152, - output_size: 1024, - // The pinned projector epsilon, bit-exact with the official descriptor - // (fround(1e-5) = 0.000009999999747378752 — the sealed compute path - // reads eps from the descriptor, so the bit-exact value is required). - layer_norm_epsilon: PROJECTOR_LAYER_NORM_EPSILON, - weights: { - section_id: "weights.projector", - bytes: weightsBytes.byteLength, - blake3: weightsBlake3, - }, - cases: [ - { - profile, - case_id: `multimodal.${profile}/projector`, - trace_level: "synthetic", - golden_bundle_digest: null, - semantic_fingerprint: null, - image_grid_thw: [grid], - readback: "output_only", - input: { - section_id: `input.projector.${profile}`, - bytes: inputBytes.byteLength, - blake3: blake3Hex(inputBytes), - }, - expected: { - section_id: `self_test.projector.${profile}`, - bytes: expectedBytes.byteLength, - blake3: blake3Hex(expectedBytes), - }, - stage_order: ["linear2"], - }, - ], - }; - const descriptorBytes = sessionPackCanonicalJsonBytes(descriptor, projectorDescriptorNumberJson); - const pack = buildCanonicalPvlcPack({ - manifestObject: { - compiler_build: "0".repeat(64), - compiler_model_abi: 1, - context_limit: 4096, - model_id: "PaddlePaddle/PaddleOCR-VL-1.6", - model_revision: "66317acc4c9fc17bd154591ce650735cd2855f3e", - precision_profile: "fidelity", - resolution_buckets: [[grid[1], grid[2]]], - }, - sections: [ - { - id: "ir.projector.official", - kind: 1, - alignment: 64, - bytes: descriptorBytes, - blake3: blake3Hex(descriptorBytes), - }, - { - id: `input.projector.${profile}`, - kind: 2, - bytes: inputBytes, - blake3: blake3Hex(inputBytes), - }, - { - id: `self_test.projector.${profile}`, - kind: 3, - bytes: expectedBytes, - blake3: blake3Hex(expectedBytes), - }, - { - id: "weights.projector", - kind: 2, - bytes: weightsBytes, - blake3: weightsBlake3, - }, - ], - }); - return { packBytes: pack, descriptorJson: new TextDecoder().decode(descriptorBytes) }; -} - -// The canonical byte form of a vision-stack manifest (minified JSON with a -// trailing newline, in the pinned field order — the runtime re-serializes -// and compares byte-exactly, matching the locked official manifest format). -export function visionStackManifestJson(manifest) { - return `${JSON.stringify(manifest)}\n`; -} diff --git a/public/vendor/paddleocr-vl/ocr_concurrency.mjs b/public/vendor/paddleocr-vl/ocr_concurrency.mjs deleted file mode 100644 index d699780..0000000 --- a/public/vendor/paddleocr-vl/ocr_concurrency.mjs +++ /dev/null @@ -1,191 +0,0 @@ -const MAX_BROWSER_OCR_PARALLELISM = 4; - -function finitePositive(value, fallback) { - return Number.isFinite(value) && value > 0 ? value : fallback; -} - -export function recommendOcrParallelism( - capabilities = {}, - { - hardwareConcurrency = globalThis.navigator?.hardwareConcurrency ?? 1, - deviceMemory = globalThis.navigator?.deviceMemory ?? 0, - } = {}, -) { - const adapter = String(capabilities.adapter_name ?? "").toLowerCase(); - const deviceType = String(capabilities.adapter_device_type ?? "").toLowerCase(); - const software = /(swiftshader|llvmpipe|software|cpu)/.test(adapter); - if (software) { - return Object.freeze({ - maxParallelism: 1, - initialParallelism: 1, - reason: "software_adapter", - }); - } - - let maxParallelism = 1; - let reason = "conservative_default"; - if ( - /(rtx|quadro|tesla).*(3090|4090|5090|a6000|a100|h100)/.test(adapter) || - /(radeon|rx).*(7900|6900)/.test(adapter) || - /apple.*(max|ultra)/.test(adapter) - ) { - maxParallelism = 4; - reason = "large_discrete_gpu"; - } else if ( - /(rtx|quadro|tesla).*(3080|4080|5080|a5000)/.test(adapter) || - /(radeon|rx).*(7800|6800)/.test(adapter) - ) { - maxParallelism = 3; - reason = "high_end_discrete_gpu"; - } else if ( - /(nvidia|geforce|rtx|radeon|amd rx|intel arc)/.test(adapter) || - deviceType === "discretegpu" || - deviceType === "discrete_gpu" || - /apple.*pro/.test(adapter) - ) { - maxParallelism = 2; - reason = "parallel_capable_gpu"; - } else if (hardwareConcurrency >= 12 && deviceMemory >= 8 && deviceType !== "integratedgpu") { - maxParallelism = 2; - reason = "high_end_host_probe"; - } - - maxParallelism = Math.max( - 1, - Math.min(MAX_BROWSER_OCR_PARALLELISM, maxParallelism), - ); - return Object.freeze({ - maxParallelism, - // The first block deliberately warms all shared resident weights alone. - initialParallelism: 1, - reason, - }); -} - -function resultWorkUnits(outcome) { - if (!outcome?.ok) return 0; - const result = outcome.result ?? {}; - const generated = finitePositive( - result.greedy?.tokenIds?.length ?? result.generatedTokens, - 1, - ); - const vision = finitePositive(result.visionTokens, 1); - return generated + vision * 0.2 + 8; -} - -export class AdaptiveOcrConcurrency { - #maxParallelism; - #currentParallelism; - #bestParallelism = 1; - #bestRate = 0; - #waves = []; - - constructor(profile) { - this.profile = Object.freeze({ ...profile }); - this.#maxParallelism = Math.max( - 1, - Math.min( - MAX_BROWSER_OCR_PARALLELISM, - Number(profile?.maxParallelism) || 1, - ), - ); - this.#currentParallelism = 1; - } - - current(remaining = Number.POSITIVE_INFINITY) { - return Math.max( - 1, - Math.min(this.#currentParallelism, this.#maxParallelism, remaining), - ); - } - - recordWave({ width, wallMs, outcomes }) { - const safeWallMs = finitePositive(wallMs, 1); - const failures = outcomes.filter((outcome) => !outcome?.ok).length; - const workUnits = outcomes.reduce( - (total, outcome) => total + resultWorkUnits(outcome), - 0, - ); - const rate = workUnits / safeWallMs; - const wave = Object.freeze({ - width, - wallMs: safeWallMs, - workUnits, - rate, - failures, - }); - this.#waves.push(wave); - - if (failures > 0) { - this.#currentParallelism = Math.max(1, Math.min(this.#bestParallelism, width - 1)); - return wave; - } - if (rate > this.#bestRate * 1.08 || this.#bestRate === 0) { - this.#bestRate = rate; - this.#bestParallelism = width; - this.#currentParallelism = Math.min(this.#maxParallelism, width + 1); - return wave; - } - if (rate < this.#bestRate * 0.9) { - this.#currentParallelism = this.#bestParallelism; - return wave; - } - this.#currentParallelism = width; - return wave; - } - - report() { - return Object.freeze({ - ...this.profile, - currentParallelism: this.#currentParallelism, - bestParallelism: this.#bestParallelism, - bestRate: this.#bestRate, - waves: Object.freeze([...this.#waves]), - }); - } -} - -export class BrowserRuntimePool { - #available; - #waiters = []; - #all; - - constructor(runtimes) { - if (!Array.isArray(runtimes) || runtimes.length === 0) { - throw new Error("browser OCR runtime pool requires at least one runtime"); - } - this.#all = [...runtimes]; - this.#available = [...runtimes]; - } - - async acquire() { - const runtime = this.#available.pop(); - if (runtime) return runtime; - return new Promise((resolve) => this.#waiters.push(resolve)); - } - - release(runtime) { - const waiter = this.#waiters.shift(); - if (waiter) { - waiter(runtime); - return; - } - this.#available.push(runtime); - } - - async run(task) { - const runtime = await this.acquire(); - try { - return await task(runtime); - } finally { - this.release(runtime); - } - } - - dispose() { - for (const runtime of this.#all) runtime.free(); - this.#all = []; - this.#available = []; - this.#waiters = []; - } -} diff --git a/public/vendor/paddleocr-vl/paddleocr_vl_tasks.mjs b/public/vendor/paddleocr-vl/paddleocr_vl_tasks.mjs deleted file mode 100644 index fe1897e..0000000 --- a/public/vendor/paddleocr-vl/paddleocr_vl_tasks.mjs +++ /dev/null @@ -1,45 +0,0 @@ -export const PADDLEOCR_VL_TASKS = Object.freeze({ - ocr: Object.freeze({ - prompt: "OCR:", - promptSuffixIds: Object.freeze([ - 101306, 93972, 2497, 93963, 23, 92267, 93963, 23, - ]), - }), - table: Object.freeze({ - prompt: "Table Recognition:", - promptSuffixIds: Object.freeze([ - 101306, 2567, 93514, 93963, 23, 92267, 93963, 23, - ]), - }), - formula: Object.freeze({ - prompt: "Formula Recognition:", - promptSuffixIds: Object.freeze([ - 101306, 59352, 93514, 93963, 23, 92267, 93963, 23, - ]), - }), - chart: Object.freeze({ - prompt: "Chart Recognition:", - promptSuffixIds: Object.freeze([ - 101306, 17720, 93514, 93963, 23, 92267, 93963, 23, - ]), - }), -}); - -export function recognitionOptionsForTask(task, { - maxGeneratedTokens = 512, -} = {}) { - const definition = PADDLEOCR_VL_TASKS[task]; - if (!definition) { - throw new RangeError( - `Unsupported PaddleOCR-VL task: ${String(task)}`, - ); - } - return Object.freeze({ - task, - ...definition, - maxGeneratedTokens: - task === "table" - ? Math.max(1024, maxGeneratedTokens) - : maxGeneratedTokens, - }); -} diff --git a/public/vendor/paddleocr-vl/pkg/pvlc_runtime_web.js b/public/vendor/paddleocr-vl/pkg/pvlc_runtime_web.js deleted file mode 100644 index 984cb64..0000000 --- a/public/vendor/paddleocr-vl/pkg/pvlc_runtime_web.js +++ /dev/null @@ -1,2410 +0,0 @@ -import { own_pvlc_uint8array_bridge_input } from './snippets/pvlc-runtime-web-2887d2e0146ca1ca/inline0.js'; - - -export class WebRuntime { - static __wrap(ptr) { - const obj = Object.create(WebRuntime.prototype); - obj.__wbg_ptr = ptr; - WebRuntimeFinalization.register(obj, obj.__wbg_ptr, obj); - return obj; - } - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; - WebRuntimeFinalization.unregister(this); - return ptr; - } - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_webruntime_free(ptr, 0); - } - abort_decoder_full_layer_session() { - wasm.webruntime_abort_decoder_full_layer_session(this.__wbg_ptr); - } - abort_decoder_kv_session() { - wasm.webruntime_abort_decoder_kv_session(this.__wbg_ptr); - } - abort_decoder_layer_session() { - wasm.webruntime_abort_decoder_layer_session(this.__wbg_ptr); - } - abort_decoder_stack_session() { - wasm.webruntime_abort_decoder_stack_session(this.__wbg_ptr); - } - abort_vision_encoder_stack_sharded() { - wasm.webruntime_abort_vision_encoder_stack_sharded(this.__wbg_ptr); - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} pack - * @param {Uint8Array} key_cache - * @param {Uint8Array} value_cache - * @returns {Promise} - */ - begin_decoder_full_layer_session(descriptor_json, pack, key_cache, value_cache) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_decoder_full_layer_session(this.__wbg_ptr, ptr0, len0, pack, key_cache, value_cache); - return ret; - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} pack - * @param {Uint8Array} key_cache - * @param {Uint8Array} value_cache - * @param {string} kernel - * @param {string} source - * @returns {Promise} - */ - begin_decoder_full_layer_session_with_shader_override(descriptor_json, pack, key_cache, value_cache, kernel, source) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(kernel, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(source, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_decoder_full_layer_session_with_shader_override(this.__wbg_ptr, ptr0, len0, pack, key_cache, value_cache, ptr1, len1, ptr2, len2); - return ret; - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} key_cache - * @param {Uint8Array} value_cache - * @returns {Promise} - */ - begin_decoder_kv_session(descriptor_json, key_cache, value_cache) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_decoder_kv_session(this.__wbg_ptr, ptr0, len0, key_cache, value_cache); - return ret; - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} key_cache - * @param {Uint8Array} value_cache - * @param {string} kernel - * @param {string} source - * @returns {Promise} - */ - begin_decoder_kv_session_with_shader_override(descriptor_json, key_cache, value_cache, kernel, source) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(kernel, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(source, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_decoder_kv_session_with_shader_override(this.__wbg_ptr, ptr0, len0, key_cache, value_cache, ptr1, len1, ptr2, len2); - return ret; - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} pack - * @param {Uint8Array} key_cache - * @param {Uint8Array} value_cache - * @returns {Promise} - */ - begin_decoder_layer_session(descriptor_json, pack, key_cache, value_cache) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_decoder_layer_session(this.__wbg_ptr, ptr0, len0, pack, key_cache, value_cache); - return ret; - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} pack - * @param {Uint8Array} key_cache - * @param {Uint8Array} value_cache - * @param {string} kernel - * @param {string} source - * @returns {Promise} - */ - begin_decoder_layer_session_with_shader_override(descriptor_json, pack, key_cache, value_cache, kernel, source) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(kernel, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(source, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_decoder_layer_session_with_shader_override(this.__wbg_ptr, ptr0, len0, pack, key_cache, value_cache, ptr1, len1, ptr2, len2); - return ret; - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} pack - * @param {Uint8Array} key_cache - * @param {Uint8Array} value_cache - * @returns {Promise} - */ - begin_decoder_stack_session(descriptor_json, pack, key_cache, value_cache) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_decoder_stack_session(this.__wbg_ptr, ptr0, len0, pack, key_cache, value_cache); - return ret; - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} rope_cos - * @param {Uint8Array} rope_sin - * @returns {Promise} - */ - begin_decoder_stack_session_resident(descriptor_json, rope_cos, rope_sin) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_decoder_stack_session_resident(this.__wbg_ptr, ptr0, len0, rope_cos, rope_sin); - return ret; - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} pack - * @param {Uint8Array} key_cache - * @param {Uint8Array} value_cache - * @param {string} kernel - * @param {string} source - * @returns {Promise} - */ - begin_decoder_stack_session_with_shader_override(descriptor_json, pack, key_cache, value_cache, kernel, source) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(kernel, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(source, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_decoder_stack_session_with_shader_override(this.__wbg_ptr, ptr0, len0, pack, key_cache, value_cache, ptr1, len1, ptr2, len2); - return ret; - } - /** - * @param {string} manifest_json - * @returns {string} - */ - begin_vision_encoder_stack_sharded_json(manifest_json) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_vision_encoder_stack_sharded_json(this.__wbg_ptr, ptr0, len0); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } - } - /** - * @param {string} manifest_json - * @param {string} activation_strategy - * @param {WebVisionQkvStackSelection} qkv_selection - * @returns {string} - */ - begin_vision_encoder_stack_sharded_resident_with_activation_strategy_and_qkv_selection_json(manifest_json, activation_strategy, qkv_selection) { - let deferred4_0; - let deferred4_1; - try { - const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(activation_strategy, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - _assertClass(qkv_selection, WebVisionQkvStackSelection); - const ret = wasm.webruntime_begin_vision_encoder_stack_sharded_resident_with_activation_strategy_and_qkv_selection_json(this.__wbg_ptr, ptr0, len0, ptr1, len1, qkv_selection.__wbg_ptr); - var ptr3 = ret[0]; - var len3 = ret[1]; - if (ret[3]) { - ptr3 = 0; len3 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred4_0 = ptr3; - deferred4_1 = len3; - return getStringFromWasm0(ptr3, len3); - } finally { - wasm.__wbindgen_free(deferred4_0, deferred4_1, 1); - } - } - /** - * @param {string} manifest_json - * @param {string} activation_strategy - * @param {string} memory_hardening - * @param {WebVisionQkvStackSelection} qkv_selection - * @returns {string} - */ - begin_vision_encoder_stack_sharded_with_activation_strategy_and_memory_hardening_and_qkv_selection_json(manifest_json, activation_strategy, memory_hardening, qkv_selection) { - let deferred5_0; - let deferred5_1; - try { - const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(activation_strategy, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(memory_hardening, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - _assertClass(qkv_selection, WebVisionQkvStackSelection); - const ret = wasm.webruntime_begin_vision_encoder_stack_sharded_with_activation_strategy_and_memory_hardening_and_qkv_selection_json(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2, qkv_selection.__wbg_ptr); - var ptr4 = ret[0]; - var len4 = ret[1]; - if (ret[3]) { - ptr4 = 0; len4 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred5_0 = ptr4; - deferred5_1 = len4; - return getStringFromWasm0(ptr4, len4); - } finally { - wasm.__wbindgen_free(deferred5_0, deferred5_1, 1); - } - } - /** - * @param {string} manifest_json - * @param {string} activation_strategy - * @param {string} memory_hardening - * @returns {string} - */ - begin_vision_encoder_stack_sharded_with_activation_strategy_and_memory_hardening_json(manifest_json, activation_strategy, memory_hardening) { - let deferred5_0; - let deferred5_1; - try { - const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(activation_strategy, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(memory_hardening, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_vision_encoder_stack_sharded_with_activation_strategy_and_memory_hardening_json(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2); - var ptr4 = ret[0]; - var len4 = ret[1]; - if (ret[3]) { - ptr4 = 0; len4 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred5_0 = ptr4; - deferred5_1 = len4; - return getStringFromWasm0(ptr4, len4); - } finally { - wasm.__wbindgen_free(deferred5_0, deferred5_1, 1); - } - } - /** - * @param {string} manifest_json - * @param {string} activation_strategy - * @param {WebVisionQkvStackSelection} qkv_selection - * @returns {string} - */ - begin_vision_encoder_stack_sharded_with_activation_strategy_and_qkv_selection_json(manifest_json, activation_strategy, qkv_selection) { - let deferred4_0; - let deferred4_1; - try { - const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(activation_strategy, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - _assertClass(qkv_selection, WebVisionQkvStackSelection); - const ret = wasm.webruntime_begin_vision_encoder_stack_sharded_with_activation_strategy_and_qkv_selection_json(this.__wbg_ptr, ptr0, len0, ptr1, len1, qkv_selection.__wbg_ptr); - var ptr3 = ret[0]; - var len3 = ret[1]; - if (ret[3]) { - ptr3 = 0; len3 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred4_0 = ptr3; - deferred4_1 = len3; - return getStringFromWasm0(ptr3, len3); - } finally { - wasm.__wbindgen_free(deferred4_0, deferred4_1, 1); - } - } - /** - * @param {string} manifest_json - * @param {string} activation_strategy - * @returns {string} - */ - begin_vision_encoder_stack_sharded_with_activation_strategy_json(manifest_json, activation_strategy) { - let deferred4_0; - let deferred4_1; - try { - const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(activation_strategy, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_begin_vision_encoder_stack_sharded_with_activation_strategy_json(this.__wbg_ptr, ptr0, len0, ptr1, len1); - var ptr3 = ret[0]; - var len3 = ret[1]; - if (ret[3]) { - ptr3 = 0; len3 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred4_0 = ptr3; - deferred4_1 = len3; - return getStringFromWasm0(ptr3, len3); - } finally { - wasm.__wbindgen_free(deferred4_0, deferred4_1, 1); - } - } - /** - * @param {Uint8Array} bytes - * @returns {string} - */ - blake3_bytes_hex(bytes) { - let deferred1_0; - let deferred1_1; - try { - const ret = wasm.webruntime_blake3_bytes_hex(this.__wbg_ptr, bytes); - deferred1_0 = ret[0]; - deferred1_1 = ret[1]; - return getStringFromWasm0(ret[0], ret[1]); - } finally { - wasm.__wbindgen_free(deferred1_0, deferred1_1, 1); - } - } - /** - * @param {string} source - * @returns {string} - */ - blake3_hex(source) { - let deferred2_0; - let deferred2_1; - try { - const ptr0 = passStringToWasm0(source, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_blake3_hex(this.__wbg_ptr, ptr0, len0); - deferred2_0 = ret[0]; - deferred2_1 = ret[1]; - return getStringFromWasm0(ret[0], ret[1]); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } - /** - * @returns {string} - */ - capabilities_json() { - let deferred2_0; - let deferred2_1; - try { - const ret = wasm.webruntime_capabilities_json(this.__wbg_ptr); - var ptr1 = ret[0]; - var len1 = ret[1]; - if (ret[3]) { - ptr1 = 0; len1 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred2_0 = ptr1; - deferred2_1 = len1; - return getStringFromWasm0(ptr1, len1); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } - /** - * @param {string} manifest_json - * @param {string} policy - * @returns {WebVisionQkvStackSelection} - */ - compile_vision_encoder_stack_qkv_selection(manifest_json, policy) { - const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(policy, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_compile_vision_encoder_stack_qkv_selection(this.__wbg_ptr, ptr0, len0, ptr1, len1); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - return WebVisionQkvStackSelection.__wrap(ret[0]); - } - /** - * @param {Float32Array} cos - * @param {Float32Array} sin - * @returns {string} - */ - configure_vision_encoder_stack_spatial_rope_f32(cos, sin) { - let deferred2_0; - let deferred2_1; - try { - const ret = wasm.webruntime_configure_vision_encoder_stack_spatial_rope_f32(this.__wbg_ptr, cos, sin); - var ptr1 = ret[0]; - var len1 = ret[1]; - if (ret[3]) { - ptr1 = 0; len1 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred2_0 = ptr1; - deferred2_1 = len1; - return getStringFromWasm0(ptr1, len1); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } - /** - * @returns {Promise} - */ - static create() { - const ret = wasm.webruntime_create(); - return ret; - } - /** - * @returns {string} - */ - decoder_full_layer_session_shader_sources_json() { - let deferred2_0; - let deferred2_1; - try { - const ret = wasm.webruntime_decoder_full_layer_session_shader_sources_json(this.__wbg_ptr); - var ptr1 = ret[0]; - var len1 = ret[1]; - if (ret[3]) { - ptr1 = 0; len1 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred2_0 = ptr1; - deferred2_1 = len1; - return getStringFromWasm0(ptr1, len1); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } - /** - * @returns {string} - */ - decoder_kv_session_shader_sources_json() { - let deferred2_0; - let deferred2_1; - try { - const ret = wasm.webruntime_decoder_kv_session_shader_sources_json(this.__wbg_ptr); - var ptr1 = ret[0]; - var len1 = ret[1]; - if (ret[3]) { - ptr1 = 0; len1 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred2_0 = ptr1; - deferred2_1 = len1; - return getStringFromWasm0(ptr1, len1); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } - /** - * @returns {string} - */ - decoder_layer_session_shader_sources_json() { - let deferred2_0; - let deferred2_1; - try { - const ret = wasm.webruntime_decoder_layer_session_shader_sources_json(this.__wbg_ptr); - var ptr1 = ret[0]; - var len1 = ret[1]; - if (ret[3]) { - ptr1 = 0; len1 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred2_0 = ptr1; - deferred2_1 = len1; - return getStringFromWasm0(ptr1, len1); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } - /** - * @returns {string} - */ - decoder_stack_resident_weights_json() { - let deferred2_0; - let deferred2_1; - try { - const ret = wasm.webruntime_decoder_stack_resident_weights_json(this.__wbg_ptr); - var ptr1 = ret[0]; - var len1 = ret[1]; - if (ret[3]) { - ptr1 = 0; len1 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred2_0 = ptr1; - deferred2_1 = len1; - return getStringFromWasm0(ptr1, len1); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } - /** - * @returns {string} - */ - decoder_stack_session_shader_sources_json() { - let deferred2_0; - let deferred2_1; - try { - const ret = wasm.webruntime_decoder_stack_session_shader_sources_json(this.__wbg_ptr); - var ptr1 = ret[0]; - var len1 = ret[1]; - if (ret[3]) { - ptr1 = 0; len1 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred2_0 = ptr1; - deferred2_1 = len1; - return getStringFromWasm0(ptr1, len1); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } - /** - * @param {string} shard_id - * @param {Uint8Array} bytes - * @returns {string} - */ - enqueue_vision_encoder_stack_sharded_layer_json(shard_id, bytes) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passStringToWasm0(shard_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_enqueue_vision_encoder_stack_sharded_layer_json(this.__wbg_ptr, ptr0, len0, bytes); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } - } - /** - * @param {string} shard_id - * @returns {string} - */ - enqueue_vision_encoder_stack_sharded_resident_layer_json(shard_id) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passStringToWasm0(shard_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_enqueue_vision_encoder_stack_sharded_resident_layer_json(this.__wbg_ptr, ptr0, len0); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } - } - /** - * @returns {Promise} - */ - finish_decoder_full_layer_session() { - const ret = wasm.webruntime_finish_decoder_full_layer_session(this.__wbg_ptr); - return ret; - } - /** - * @returns {Promise} - */ - finish_decoder_kv_session() { - const ret = wasm.webruntime_finish_decoder_kv_session(this.__wbg_ptr); - return ret; - } - /** - * @returns {Promise} - */ - finish_decoder_layer_session() { - const ret = wasm.webruntime_finish_decoder_layer_session(this.__wbg_ptr); - return ret; - } - /** - * @returns {Promise} - */ - finish_decoder_stack_session() { - const ret = wasm.webruntime_finish_decoder_stack_session(this.__wbg_ptr); - return ret; - } - /** - * @param {string} shard_id - * @param {Uint8Array} bytes - * @returns {Promise} - */ - finish_vision_encoder_stack_sharded(shard_id, bytes) { - const ptr0 = passStringToWasm0(shard_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_finish_vision_encoder_stack_sharded(this.__wbg_ptr, ptr0, len0, bytes); - return ret; - } - /** - * @param {string} shard_id - * @returns {Promise} - */ - finish_vision_encoder_stack_sharded_resident(shard_id) { - const ptr0 = passStringToWasm0(shard_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_finish_vision_encoder_stack_sharded_resident(this.__wbg_ptr, ptr0, len0); - return ret; - } - /** - * @param {string} shard_id - * @param {string} projector_descriptor_json - * @param {string} image_grid_thw_json - * @returns {Promise} - */ - finish_vision_encoder_stack_sharded_resident_with_projector_f16(shard_id, projector_descriptor_json, image_grid_thw_json) { - const ptr0 = passStringToWasm0(shard_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(projector_descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(image_grid_thw_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_finish_vision_encoder_stack_sharded_resident_with_projector_f16(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2); - return ret; - } - /** - * @param {string} descriptor_json - * @returns {boolean} - */ - has_projector_f16_resident_weights(descriptor_json) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_has_projector_f16_resident_weights(this.__wbg_ptr, ptr0, len0); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - return ret[0] !== 0; - } - /** - * @param {string} manifest_json - * @returns {boolean} - */ - has_vision_encoder_stack_resident_weights(manifest_json) { - const ptr0 = passStringToWasm0(manifest_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_has_vision_encoder_stack_resident_weights(this.__wbg_ptr, ptr0, len0); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - return ret[0] !== 0; - } - /** - * @returns {Promise} - */ - logits_decoder_stack_session() { - const ret = wasm.webruntime_logits_decoder_stack_session(this.__wbg_ptr); - return ret; - } - /** - * @param {Uint8Array} hidden_states - * @returns {Promise} - */ - prefill_decoder_stack_session(hidden_states) { - const ret = wasm.webruntime_prefill_decoder_stack_session(this.__wbg_ptr, hidden_states); - return ret; - } - /** - * @param {string} shard_id - * @returns {string} - */ - preflight_vision_encoder_stack_manifest_shard_json(shard_id) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passStringToWasm0(shard_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_preflight_vision_encoder_stack_manifest_shard_json(this.__wbg_ptr, ptr0, len0); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } - } - /** - * @param {string} shard_id - * @param {Uint8Array} bytes - * @returns {string} - */ - preflight_vision_encoder_stack_shard_json(shard_id, bytes) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passStringToWasm0(shard_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_preflight_vision_encoder_stack_shard_json(this.__wbg_ptr, ptr0, len0, bytes); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} weights - * @returns {string} - */ - prepare_projector_f16_resident_weights(descriptor_json, weights) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_prepare_projector_f16_resident_weights(this.__wbg_ptr, ptr0, len0, weights); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } - } - /** - * @param {string} precision_profile - * @param {boolean} shader_f16_available - * @returns {string} - */ - probe_m7q1_precision_admission_json(precision_profile, shader_f16_available) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passStringToWasm0(precision_profile, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_probe_m7q1_precision_admission_json(this.__wbg_ptr, ptr0, len0, shader_f16_available); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } - } - /** - * @param {string} label - * @param {string} source - * @param {string} missing_entry_point - * @returns {Promise} - */ - probe_validation_error_json(label, source, missing_entry_point) { - const ptr0 = passStringToWasm0(label, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(source, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(missing_entry_point, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_probe_validation_error_json(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2); - return ret; - } - /** - * @returns {string} - */ - projector_shader_sources_json() { - let deferred2_0; - let deferred2_1; - try { - const ret = wasm.webruntime_projector_shader_sources_json(this.__wbg_ptr); - var ptr1 = ret[0]; - var len1 = ret[1]; - if (ret[3]) { - ptr1 = 0; len1 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred2_0 = ptr1; - deferred2_1 = len1; - return getStringFromWasm0(ptr1, len1); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } - /** - * @param {string} invocation_json - * @returns {Promise} - */ - run_json(invocation_json) { - const ptr0 = passStringToWasm0(invocation_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_json(this.__wbg_ptr, ptr0, len0); - return ret; - } - /** - * @param {string} fixture_json - * @returns {Promise} - */ - run_m7q1_fp16_weight_probe_json(fixture_json) { - const ptr0 = passStringToWasm0(fixture_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_m7q1_fp16_weight_probe_json(this.__wbg_ptr, ptr0, len0); - return ret; - } - /** - * @param {string} descriptor_json - * @param {string} profile - * @param {Uint8Array} input - * @param {Uint8Array} weights - * @returns {Promise} - */ - run_projector_bytes(descriptor_json, profile, input, weights) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(profile, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_projector_bytes(this.__wbg_ptr, ptr0, len0, ptr1, len1, input, weights); - return ret; - } - /** - * @param {string} descriptor_json - * @param {string} image_grid_thw_json - * @param {Uint8Array} input - * @returns {Promise} - */ - run_projector_f16_resident_bytes(descriptor_json, image_grid_thw_json, input) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(image_grid_thw_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_projector_f16_resident_bytes(this.__wbg_ptr, ptr0, len0, ptr1, len1, input); - return ret; - } - /** - * @param {string} invocation_json - * @param {string} readback - * @returns {Promise} - */ - run_projector_json(invocation_json, readback) { - const ptr0 = passStringToWasm0(invocation_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(readback, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_projector_json(this.__wbg_ptr, ptr0, len0, ptr1, len1); - return ret; - } - /** - * @param {string} invocation_json - * @param {string} readback - * @param {string} kernel - * @param {string} source - * @returns {Promise} - */ - run_projector_with_shader_override_json(invocation_json, readback, kernel, source) { - const ptr0 = passStringToWasm0(invocation_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(readback, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(kernel, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - const ptr3 = passStringToWasm0(source, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len3 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_projector_with_shader_override_json(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3); - return ret; - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} weights - * @param {string} readback - * @returns {Promise} - */ - run_vision_encoder_layer_identity_rope_bytes(descriptor_json, weights, readback) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(readback, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_vision_encoder_layer_identity_rope_bytes(this.__wbg_ptr, ptr0, len0, weights, ptr1, len1); - return ret; - } - /** - * @param {string} invocation_json - * @param {string} readback - * @returns {Promise} - */ - run_vision_encoder_layer_identity_rope_json(invocation_json, readback) { - const ptr0 = passStringToWasm0(invocation_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(readback, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_vision_encoder_layer_identity_rope_json(this.__wbg_ptr, ptr0, len0, ptr1, len1); - return ret; - } - /** - * @param {string} invocation_json - * @param {string} readback - * @param {string} kernel - * @param {string} source - * @returns {Promise} - */ - run_vision_encoder_layer_identity_rope_with_shader_override_json(invocation_json, readback, kernel, source) { - const ptr0 = passStringToWasm0(invocation_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(readback, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(kernel, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - const ptr3 = passStringToWasm0(source, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len3 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_vision_encoder_layer_identity_rope_with_shader_override_json(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3); - return ret; - } - /** - * @param {string} shard_id - * @param {Uint8Array} bytes - * @returns {Promise} - */ - run_vision_encoder_stack_sharded_layer_json(shard_id, bytes) { - const ptr0 = passStringToWasm0(shard_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_vision_encoder_stack_sharded_layer_json(this.__wbg_ptr, ptr0, len0, bytes); - return ret; - } - /** - * @param {string} descriptor_json - * @param {Uint8Array} input - * @param {Uint8Array} weight - * @param {Uint8Array} bias - * @returns {Promise} - */ - run_vision_patch_projection_bytes(descriptor_json, input, weight, bias) { - const ptr0 = passStringToWasm0(descriptor_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_vision_patch_projection_bytes(this.__wbg_ptr, ptr0, len0, input, weight, bias); - return ret; - } - /** - * @param {string} invocation_json - * @param {string} label - * @param {string} source - * @param {string} entry_point - * @returns {Promise} - */ - run_with_shader_json(invocation_json, label, source, entry_point) { - const ptr0 = passStringToWasm0(invocation_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(label, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ptr2 = passStringToWasm0(source, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len2 = WASM_VECTOR_LEN; - const ptr3 = passStringToWasm0(entry_point, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len3 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_run_with_shader_json(this.__wbg_ptr, ptr0, len0, ptr1, len1, ptr2, len2, ptr3, len3); - return ret; - } - /** - * @param {string} shard_id - * @param {Uint8Array} bytes - * @returns {Promise} - */ - start_vision_encoder_stack_sharded_json(shard_id, bytes) { - const ptr0 = passStringToWasm0(shard_id, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_start_vision_encoder_stack_sharded_json(this.__wbg_ptr, ptr0, len0, bytes); - return ret; - } - /** - * @param {Uint8Array} hidden_token - * @returns {Promise} - */ - step_decoder_full_layer_session(hidden_token) { - const ret = wasm.webruntime_step_decoder_full_layer_session(this.__wbg_ptr, hidden_token); - return ret; - } - /** - * @param {Uint8Array} query - * @param {Uint8Array} appended_key - * @param {Uint8Array} appended_value - * @returns {Promise} - */ - step_decoder_kv_session(query, appended_key, appended_value) { - const ret = wasm.webruntime_step_decoder_kv_session(this.__wbg_ptr, query, appended_key, appended_value); - return ret; - } - /** - * @param {Uint8Array} hidden_token - * @returns {Promise} - */ - step_decoder_layer_session(hidden_token) { - const ret = wasm.webruntime_step_decoder_layer_session(this.__wbg_ptr, hidden_token); - return ret; - } - /** - * @param {Uint8Array} hidden_token - * @returns {Promise} - */ - step_decoder_stack_session(hidden_token) { - const ret = wasm.webruntime_step_decoder_stack_session(this.__wbg_ptr, hidden_token); - return ret; - } - /** - * @returns {Promise} - */ - top1_decoder_stack_session() { - const ret = wasm.webruntime_top1_decoder_stack_session(this.__wbg_ptr); - return ret; - } - /** - * @returns {Promise} - */ - validate_all_pipelines_json() { - const ret = wasm.webruntime_validate_all_pipelines_json(this.__wbg_ptr); - return ret; - } - /** - * @returns {Promise} - */ - validate_projector_pipelines_json() { - const ret = wasm.webruntime_validate_projector_pipelines_json(this.__wbg_ptr); - return ret; - } - /** - * @returns {Promise} - */ - validate_vision_attention_pipeline_json() { - const ret = wasm.webruntime_validate_vision_attention_pipeline_json(this.__wbg_ptr); - return ret; - } - /** - * @returns {Promise} - */ - validate_vision_encoder_layer_pipelines_json() { - const ret = wasm.webruntime_validate_vision_encoder_layer_pipelines_json(this.__wbg_ptr); - return ret; - } - /** - * @returns {string} - */ - vision_encoder_layer_shader_sources_json() { - let deferred2_0; - let deferred2_1; - try { - const ret = wasm.webruntime_vision_encoder_layer_shader_sources_json(this.__wbg_ptr); - var ptr1 = ret[0]; - var len1 = ret[1]; - if (ret[3]) { - ptr1 = 0; len1 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred2_0 = ptr1; - deferred2_1 = len1; - return getStringFromWasm0(ptr1, len1); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } - /** - * @param {string} activation_strategy - * @returns {string} - */ - vision_encoder_stack_qkv_shader_sources_json(activation_strategy) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passStringToWasm0(activation_strategy, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_vision_encoder_stack_qkv_shader_sources_json(this.__wbg_ptr, ptr0, len0); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } - } - /** - * @param {string} activation_strategy - * @returns {string} - */ - vision_encoder_stack_shader_sources_json(activation_strategy) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passStringToWasm0(activation_strategy, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.webruntime_vision_encoder_stack_shader_sources_json(this.__wbg_ptr, ptr0, len0); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } - } -} -if (Symbol.dispose) WebRuntime.prototype[Symbol.dispose] = WebRuntime.prototype.free; - -export class WebVisionQkvStackSelection { - static __wrap(ptr) { - const obj = Object.create(WebVisionQkvStackSelection.prototype); - obj.__wbg_ptr = ptr; - WebVisionQkvStackSelectionFinalization.register(obj, obj.__wbg_ptr, obj); - return obj; - } - __destroy_into_raw() { - const ptr = this.__wbg_ptr; - this.__wbg_ptr = 0; - WebVisionQkvStackSelectionFinalization.unregister(this); - return ptr; - } - free() { - const ptr = this.__destroy_into_raw(); - wasm.__wbg_webvisionqkvstackselection_free(ptr, 0); - } - /** - * @returns {string} - */ - evidence_json() { - let deferred2_0; - let deferred2_1; - try { - const ret = wasm.webvisionqkvstackselection_evidence_json(this.__wbg_ptr); - var ptr1 = ret[0]; - var len1 = ret[1]; - if (ret[3]) { - ptr1 = 0; len1 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred2_0 = ptr1; - deferred2_1 = len1; - return getStringFromWasm0(ptr1, len1); - } finally { - wasm.__wbindgen_free(deferred2_0, deferred2_1, 1); - } - } -} -if (Symbol.dispose) WebVisionQkvStackSelection.prototype[Symbol.dispose] = WebVisionQkvStackSelection.prototype.free; - -/** - * @param {Uint8Array} canonical_input - * @returns {Uint8Array} - */ -export function assemble_browser_benchmark_cohort_v1(canonical_input) { - const ret = wasm.assemble_browser_benchmark_cohort_v1(canonical_input); - if (ret[2]) { - throw takeFromExternrefTable0(ret[1]); - } - return takeFromExternrefTable0(ret[0]); -} - -/** - * @param {string} activation_strategy - * @returns {string} - */ -export function canonical_vision_encoder_stack_shader_sources_json(activation_strategy) { - let deferred3_0; - let deferred3_1; - try { - const ptr0 = passStringToWasm0(activation_strategy, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.canonical_vision_encoder_stack_shader_sources_json(ptr0, len0); - var ptr2 = ret[0]; - var len2 = ret[1]; - if (ret[3]) { - ptr2 = 0; len2 = 0; - throw takeFromExternrefTable0(ret[2]); - } - deferred3_0 = ptr2; - deferred3_1 = len2; - return getStringFromWasm0(ptr2, len2); - } finally { - wasm.__wbindgen_free(deferred3_0, deferred3_1, 1); - } -} - -/** - * @param {Uint8Array} canonical_plan - */ -export function validate_browser_benchmark_cohort_plan_v1(canonical_plan) { - const ret = wasm.validate_browser_benchmark_cohort_plan_v1(canonical_plan); - if (ret[1]) { - throw takeFromExternrefTable0(ret[0]); - } -} -function __wbg_get_imports() { - const import0 = { - __proto__: null, - __wbg_Window_afcc911b2f9c92e2: function(arg0) { - const ret = arg0.Window; - return ret; - }, - __wbg_WorkerGlobalScope_5d19ebc889ff397e: function(arg0) { - const ret = arg0.WorkerGlobalScope; - return ret; - }, - __wbg___wbindgen_debug_string_c25d447a39f5578f: function(arg0, arg1) { - const ret = debugString(arg1); - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }, - __wbg___wbindgen_is_function_1ff95bcc5517c252: function(arg0) { - const ret = typeof(arg0) === 'function'; - return ret; - }, - __wbg___wbindgen_is_null_ea9085d691f535d3: function(arg0) { - const ret = arg0 === null; - return ret; - }, - __wbg___wbindgen_is_string_ea5e6cc2e4141dfe: function(arg0) { - const ret = typeof(arg0) === 'string'; - return ret; - }, - __wbg___wbindgen_is_undefined_c05833b95a3cf397: function(arg0) { - const ret = arg0 === undefined; - return ret; - }, - __wbg___wbindgen_string_get_b0ca35b86a603356: function(arg0, arg1) { - const obj = arg1; - const ret = typeof(obj) === 'string' ? obj : undefined; - var ptr1 = isLikeNone(ret) ? 0 : passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - var len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }, - __wbg___wbindgen_throw_344f42d3211c4765: function(arg0, arg1) { - throw new Error(getStringFromWasm0(arg0, arg1)); - }, - __wbg__wbg_cb_unref_fffb441def202758: function(arg0) { - arg0._wbg_cb_unref(); - }, - __wbg_beginComputePass_431a159006c13c7c: function(arg0, arg1) { - const ret = arg0.beginComputePass(arg1); - return ret; - }, - __wbg_byteLength_41862ca4020b9c43: function(arg0) { - const ret = arg0.byteLength; - return ret; - }, - __wbg_call_424ac0f137abafbc: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5, arg6) { - const ret = arg0.call(arg1, arg2, arg3, arg4, arg5, arg6); - return ret; - }, arguments); }, - __wbg_call_44b7209e1e252e6a: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) { - const ret = arg0.call(arg1, arg2, arg3, arg4); - return ret; - }, arguments); }, - __wbg_call_8a2dd23819f8a60a: function() { return handleError(function (arg0, arg1) { - const ret = arg0.call(arg1); - return ret; - }, arguments); }, - __wbg_call_a6e5c5dce5018821: function() { return handleError(function (arg0, arg1, arg2) { - const ret = arg0.call(arg1, arg2); - return ret; - }, arguments); }, - __wbg_call_e3b662382210db98: function() { return handleError(function (arg0, arg1, arg2, arg3) { - const ret = arg0.call(arg1, arg2, arg3); - return ret; - }, arguments); }, - __wbg_configure_0e4789c0f6b35c8e: function() { return handleError(function (arg0, arg1) { - arg0.configure(arg1); - }, arguments); }, - __wbg_copyBufferToBuffer_5e2cd8f10ae78183: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4) { - arg0.copyBufferToBuffer(arg1, arg2, arg3, arg4); - }, arguments); }, - __wbg_copyBufferToBuffer_ca30deb8de65f5d5: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5) { - arg0.copyBufferToBuffer(arg1, arg2, arg3, arg4, arg5); - }, arguments); }, - __wbg_createBindGroup_655c6e6c0258530e: function(arg0, arg1) { - const ret = arg0.createBindGroup(arg1); - return ret; - }, - __wbg_createBuffer_0726dd2ab09ea1d2: function() { return handleError(function (arg0, arg1) { - const ret = arg0.createBuffer(arg1); - return ret; - }, arguments); }, - __wbg_createCommandEncoder_ec1f40f0cb4d09df: function(arg0, arg1) { - const ret = arg0.createCommandEncoder(arg1); - return ret; - }, - __wbg_createComputePipeline_2545c47f08715810: function(arg0, arg1) { - const ret = arg0.createComputePipeline(arg1); - return ret; - }, - __wbg_createShaderModule_2e44fc7677c6288b: function(arg0, arg1) { - const ret = arg0.createShaderModule(arg1); - return ret; - }, - __wbg_description_02485704e69b1e7f: function(arg0, arg1) { - const ret = arg1.description; - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }, - __wbg_destroy_fe937f756bf8df37: function(arg0) { - arg0.destroy(); - }, - __wbg_dispatchWorkgroups_afb2344298c62227: function(arg0, arg1, arg2, arg3) { - arg0.dispatchWorkgroups(arg1 >>> 0, arg2 >>> 0, arg3 >>> 0); - }, - __wbg_end_c36889de8ddef882: function(arg0) { - arg0.end(); - }, - __wbg_error_622f41c5c32a13db: function(arg0) { - const ret = arg0.error; - return ret; - }, - __wbg_features_2b07a28fe18ad0ce: function(arg0) { - const ret = arg0.features; - return ret; - }, - __wbg_features_d4d2020319592cbe: function(arg0) { - const ret = arg0.features; - return ret; - }, - __wbg_finish_4d91de5e927dd13f: function(arg0, arg1) { - const ret = arg0.finish(arg1); - return ret; - }, - __wbg_finish_6e06b68ab68cd9f6: function(arg0) { - const ret = arg0.finish(); - return ret; - }, - __wbg_getBindGroupLayout_d38545dfc4eab8d5: function(arg0, arg1) { - const ret = arg0.getBindGroupLayout(arg1 >>> 0); - return ret; - }, - __wbg_getContext_fd298c901058eb31: function() { return handleError(function (arg0, arg1, arg2) { - const ret = arg0.getContext(getStringFromWasm0(arg1, arg2)); - return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); - }, arguments); }, - __wbg_getMappedRange_d0bf3141224111b6: function() { return handleError(function (arg0, arg1, arg2) { - const ret = arg0.getMappedRange(arg1, arg2); - return ret; - }, arguments); }, - __wbg_get_78f252d074a84d0b: function() { return handleError(function (arg0, arg1) { - const ret = Reflect.get(arg0, arg1); - return ret; - }, arguments); }, - __wbg_gpu_2ccc250735d24a2a: function(arg0) { - const ret = arg0.gpu; - return ret; - }, - __wbg_has_0c97053e877f47cc: function(arg0, arg1, arg2) { - const ret = arg0.has(getStringFromWasm0(arg1, arg2)); - return ret; - }, - __wbg_info_cf0d9a286850cd24: function(arg0) { - const ret = arg0.info; - return ret; - }, - __wbg_instanceof_GpuBuffer_56b142dc26a43583: function(arg0) { - let result; - try { - result = arg0 instanceof GPUBuffer; - } catch (_) { - result = false; - } - const ret = result; - return ret; - }, - __wbg_instanceof_GpuOutOfMemoryError_6429c750997f1c8d: function(arg0) { - let result; - try { - result = arg0 instanceof GPUOutOfMemoryError; - } catch (_) { - result = false; - } - const ret = result; - return ret; - }, - __wbg_instanceof_GpuValidationError_75fa3611f065f4df: function(arg0) { - let result; - try { - result = arg0 instanceof GPUValidationError; - } catch (_) { - result = false; - } - const ret = result; - return ret; - }, - __wbg_instanceof_Object_33f20e6f12439f3e: function(arg0) { - let result; - try { - result = arg0 instanceof Object; - } catch (_) { - result = false; - } - const ret = result; - return ret; - }, - __wbg_instanceof_Promise_4cb210c0b8f8c959: function(arg0) { - let result; - try { - result = arg0 instanceof Promise; - } catch (_) { - result = false; - } - const ret = result; - return ret; - }, - __wbg_instanceof_Uint8Array_309b927aaf7a3fc7: function(arg0) { - let result; - try { - result = arg0 instanceof Uint8Array; - } catch (_) { - result = false; - } - const ret = result; - return ret; - }, - __wbg_isFallbackAdapter_8ccb967428491dcb: function(arg0) { - const ret = arg0.isFallbackAdapter; - return ret; - }, - __wbg_is_7b9d0b289033c7de: function(arg0, arg1) { - const ret = Object.is(arg0, arg1); - return ret; - }, - __wbg_label_7ed42f25f841996b: function(arg0, arg1) { - const ret = arg1.label; - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }, - __wbg_length_1f0964f4a5e2c6d8: function(arg0) { - const ret = arg0.length; - return ret; - }, - __wbg_length_98f10d1e2f4ea968: function(arg0) { - const ret = arg0.length; - return ret; - }, - __wbg_limits_20c6f56636df7d38: function(arg0) { - const ret = arg0.limits; - return ret; - }, - __wbg_limits_328c61cd41512420: function(arg0) { - const ret = arg0.limits; - return ret; - }, - __wbg_mapAsync_52b01fa9e8f765fd: function(arg0, arg1, arg2, arg3) { - const ret = arg0.mapAsync(arg1 >>> 0, arg2, arg3); - return ret; - }, - __wbg_maxBindGroupsPlusVertexBuffers_33e5006b23e20478: function(arg0) { - const ret = arg0.maxBindGroupsPlusVertexBuffers; - return ret; - }, - __wbg_maxBindGroups_f6d26f3a67826666: function(arg0) { - const ret = arg0.maxBindGroups; - return ret; - }, - __wbg_maxBindingsPerBindGroup_edab2e8dabbf6060: function(arg0) { - const ret = arg0.maxBindingsPerBindGroup; - return ret; - }, - __wbg_maxBufferSize_bbc69284c14aa7da: function(arg0) { - const ret = arg0.maxBufferSize; - return ret; - }, - __wbg_maxColorAttachmentBytesPerSample_63ebe4f81de2f34c: function(arg0) { - const ret = arg0.maxColorAttachmentBytesPerSample; - return ret; - }, - __wbg_maxColorAttachments_aed8c38beabf3a5c: function(arg0) { - const ret = arg0.maxColorAttachments; - return ret; - }, - __wbg_maxComputeInvocationsPerWorkgroup_2d964564c37f1c65: function(arg0) { - const ret = arg0.maxComputeInvocationsPerWorkgroup; - return ret; - }, - __wbg_maxComputeWorkgroupSizeX_a3e3206570da184f: function(arg0) { - const ret = arg0.maxComputeWorkgroupSizeX; - return ret; - }, - __wbg_maxComputeWorkgroupSizeY_dffa4a62244b7563: function(arg0) { - const ret = arg0.maxComputeWorkgroupSizeY; - return ret; - }, - __wbg_maxComputeWorkgroupSizeZ_976ebcb760f6d07d: function(arg0) { - const ret = arg0.maxComputeWorkgroupSizeZ; - return ret; - }, - __wbg_maxComputeWorkgroupStorageSize_2e8dbece6e532e2a: function(arg0) { - const ret = arg0.maxComputeWorkgroupStorageSize; - return ret; - }, - __wbg_maxComputeWorkgroupsPerDimension_bb7d36b4d20c80f4: function(arg0) { - const ret = arg0.maxComputeWorkgroupsPerDimension; - return ret; - }, - __wbg_maxDynamicStorageBuffersPerPipelineLayout_1ca859cb96a414e0: function(arg0) { - const ret = arg0.maxDynamicStorageBuffersPerPipelineLayout; - return ret; - }, - __wbg_maxDynamicUniformBuffersPerPipelineLayout_e968f2c8cd8f4d46: function(arg0) { - const ret = arg0.maxDynamicUniformBuffersPerPipelineLayout; - return ret; - }, - __wbg_maxInterStageShaderVariables_138ac882c4d6a3d3: function(arg0) { - const ret = arg0.maxInterStageShaderVariables; - return ret; - }, - __wbg_maxSampledTexturesPerShaderStage_bb3e6b2698321fa6: function(arg0) { - const ret = arg0.maxSampledTexturesPerShaderStage; - return ret; - }, - __wbg_maxSamplersPerShaderStage_98c00a1829fa414b: function(arg0) { - const ret = arg0.maxSamplersPerShaderStage; - return ret; - }, - __wbg_maxStorageBufferBindingSize_e500e31f479e669e: function(arg0) { - const ret = arg0.maxStorageBufferBindingSize; - return ret; - }, - __wbg_maxStorageBuffersPerShaderStage_eb663f6d7521b6a7: function(arg0) { - const ret = arg0.maxStorageBuffersPerShaderStage; - return ret; - }, - __wbg_maxStorageTexturesPerShaderStage_bb3ad93b53e618c0: function(arg0) { - const ret = arg0.maxStorageTexturesPerShaderStage; - return ret; - }, - __wbg_maxTextureArrayLayers_2a56d05fb261c99a: function(arg0) { - const ret = arg0.maxTextureArrayLayers; - return ret; - }, - __wbg_maxTextureDimension1D_84590c1d4770d319: function(arg0) { - const ret = arg0.maxTextureDimension1D; - return ret; - }, - __wbg_maxTextureDimension2D_7f2b5c8b2727e3fc: function(arg0) { - const ret = arg0.maxTextureDimension2D; - return ret; - }, - __wbg_maxTextureDimension3D_7f3babddf55c32a6: function(arg0) { - const ret = arg0.maxTextureDimension3D; - return ret; - }, - __wbg_maxUniformBufferBindingSize_d80a09e23c0b284c: function(arg0) { - const ret = arg0.maxUniformBufferBindingSize; - return ret; - }, - __wbg_maxUniformBuffersPerShaderStage_0b8b2de676fa740e: function(arg0) { - const ret = arg0.maxUniformBuffersPerShaderStage; - return ret; - }, - __wbg_maxVertexAttributes_a693dd921316649b: function(arg0) { - const ret = arg0.maxVertexAttributes; - return ret; - }, - __wbg_maxVertexBufferArrayStride_f256d91f281076cb: function(arg0) { - const ret = arg0.maxVertexBufferArrayStride; - return ret; - }, - __wbg_maxVertexBuffers_70ab564b25d5ac20: function(arg0) { - const ret = arg0.maxVertexBuffers; - return ret; - }, - __wbg_message_4ada57a3710f1502: function(arg0, arg1) { - const ret = arg1.message; - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }, - __wbg_minStorageBufferOffsetAlignment_3248ed00dcdbf79f: function(arg0) { - const ret = arg0.minStorageBufferOffsetAlignment; - return ret; - }, - __wbg_minUniformBufferOffsetAlignment_3b9fa4caae03e903: function(arg0) { - const ret = arg0.minUniformBufferOffsetAlignment; - return ret; - }, - __wbg_navigator_51379c10a84aeec9: function(arg0) { - const ret = arg0.navigator; - return ret; - }, - __wbg_navigator_99621db14b3f1099: function(arg0) { - const ret = arg0.navigator; - return ret; - }, - __wbg_new_25e75d1f0df4d87a: function() { return handleError(function (arg0, arg1) { - const ret = new OffscreenCanvas(arg0 >>> 0, arg1 >>> 0); - return ret; - }, arguments); }, - __wbg_new_32b398fb48b6d94a: function() { - const ret = new Array(); - return ret; - }, - __wbg_new_aec3e25493d729fe: function(arg0, arg1) { - try { - var state0 = {a: arg0, b: arg1}; - var cb0 = (arg0, arg1) => { - const a = state0.a; - state0.a = 0; - try { - return wasm_bindgen__convert__closures_____invoke__h963f897f0e02fd13(a, state0.b, arg0, arg1); - } finally { - state0.a = a; - } - }; - const ret = new Promise(cb0); - return ret; - } finally { - state0.a = 0; - } - }, - __wbg_new_b667d279fd5aa943: function(arg0, arg1) { - const ret = new Error(getStringFromWasm0(arg0, arg1)); - return ret; - }, - __wbg_new_cd45aabdf6073e84: function(arg0) { - const ret = new Uint8Array(arg0); - return ret; - }, - __wbg_new_da52cf8fe3429cb2: function() { - const ret = new Object(); - return ret; - }, - __wbg_new_from_slice_77cdfb7977362f3c: function(arg0, arg1) { - const ret = new Uint8Array(getArrayU8FromWasm0(arg0, arg1)); - return ret; - }, - __wbg_new_typed_1824d93f294193e5: function(arg0, arg1) { - try { - var state0 = {a: arg0, b: arg1}; - var cb0 = (arg0, arg1) => { - const a = state0.a; - state0.a = 0; - try { - return wasm_bindgen__convert__closures_____invoke__h963f897f0e02fd13(a, state0.b, arg0, arg1); - } finally { - state0.a = a; - } - }; - const ret = new Promise(cb0); - return ret; - } finally { - state0.a = 0; - } - }, - __wbg_new_typed_4148bd5ae72ab3f0: function() { - const ret = new Object(); - return ret; - }, - __wbg_new_with_byte_offset_and_length_54c7724ee3ec7d82: function(arg0, arg1, arg2) { - const ret = new Uint8Array(arg0, arg1 >>> 0, arg2 >>> 0); - return ret; - }, - __wbg_now_86c0d4ba3fa605b8: function() { - const ret = Date.now(); - return ret; - }, - __wbg_onSubmittedWorkDone_270d6b5a45520e79: function(arg0) { - const ret = arg0.onSubmittedWorkDone(); - return ret; - }, - __wbg_own_pvlc_uint8array_bridge_input_42ed0e9c455b8a74: function() { return handleError(function (arg0) { - const ret = own_pvlc_uint8array_bridge_input(arg0); - return ret; - }, arguments); }, - __wbg_prototypesetcall_4770620bbe4688a0: function(arg0, arg1, arg2) { - Uint8Array.prototype.set.call(getArrayU8FromWasm0(arg0, arg1), arg2); - }, - __wbg_prototypesetcall_ba9c9a7197c11933: function(arg0, arg1, arg2) { - Float32Array.prototype.set.call(getArrayF32FromWasm0(arg0, arg1), arg2); - }, - __wbg_push_d2ae3af0c1217ae6: function(arg0, arg1) { - const ret = arg0.push(arg1); - return ret; - }, - __wbg_queueMicrotask_0ab5b2d2393e99b9: function(arg0) { - const ret = arg0.queueMicrotask; - return ret; - }, - __wbg_queueMicrotask_6a09b7bc46549209: function(arg0) { - queueMicrotask(arg0); - }, - __wbg_queue_adce34608fd0c893: function(arg0) { - const ret = arg0.queue; - return ret; - }, - __wbg_reject_90df95b492dd8563: function(arg0) { - const ret = Promise.reject(arg0); - return ret; - }, - __wbg_requestAdapter_2e6718811c735a57: function(arg0, arg1) { - const ret = arg0.requestAdapter(arg1); - return ret; - }, - __wbg_requestDevice_ab46d0519ea1cc34: function(arg0, arg1) { - const ret = arg0.requestDevice(arg1); - return ret; - }, - __wbg_resolve_2191a4dfe481c25b: function(arg0) { - const ret = Promise.resolve(arg0); - return ret; - }, - __wbg_setBindGroup_3e4ce136bc833ea1: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5, arg6) { - arg0.setBindGroup(arg1 >>> 0, arg2, getArrayU32FromWasm0(arg3, arg4), arg5, arg6 >>> 0); - }, arguments); }, - __wbg_setBindGroup_c22a1b95c0b17f37: function(arg0, arg1, arg2) { - arg0.setBindGroup(arg1 >>> 0, arg2); - }, - __wbg_setPipeline_d73f019e98c76d2d: function(arg0, arg1) { - arg0.setPipeline(arg1); - }, - __wbg_set_4d7dd76f3dae2926: function(arg0, arg1, arg2) { - arg0.set(getArrayU8FromWasm0(arg1, arg2)); - }, - __wbg_set_61e45ae8061eca11: function(arg0, arg1, arg2) { - arg0.set(arg1, arg2 >>> 0); - }, - __wbg_set_8535240470bf2500: function() { return handleError(function (arg0, arg1, arg2) { - const ret = Reflect.set(arg0, arg1, arg2); - return ret; - }, arguments); }, - __wbg_set_beginning_of_pass_write_index_0d4fa06109208ad7: function(arg0, arg1) { - arg0.beginningOfPassWriteIndex = arg1 >>> 0; - }, - __wbg_set_binding_f74df3510792aba1: function(arg0, arg1) { - arg0.binding = arg1 >>> 0; - }, - __wbg_set_buffer_c3410572051920ba: function(arg0, arg1) { - arg0.buffer = arg1; - }, - __wbg_set_code_b4f37f81f45b5b25: function(arg0, arg1, arg2) { - arg0.code = getStringFromWasm0(arg1, arg2); - }, - __wbg_set_compute_d0c2d276b6d4b18d: function(arg0, arg1) { - arg0.compute = arg1; - }, - __wbg_set_device_e275d1d4f3c9eb74: function(arg0, arg1) { - arg0.device = arg1; - }, - __wbg_set_end_of_pass_write_index_49a6ddbb2b888bfa: function(arg0, arg1) { - arg0.endOfPassWriteIndex = arg1 >>> 0; - }, - __wbg_set_entries_a12aca1e458b0456: function(arg0, arg1, arg2) { - arg0.entries = getArrayJsValueViewFromWasm0(arg1, arg2); - }, - __wbg_set_entry_point_5f26aacbe4c545eb: function(arg0, arg1, arg2) { - arg0.entryPoint = getStringFromWasm0(arg1, arg2); - }, - __wbg_set_format_815efd4dc4817bbb: function(arg0, arg1) { - arg0.format = __wbindgen_enum_GpuTextureFormat[arg1]; - }, - __wbg_set_label_08d9be3e4719c226: function(arg0, arg1, arg2) { - arg0.label = getStringFromWasm0(arg1, arg2); - }, - __wbg_set_label_60ad96c811e0d109: function(arg0, arg1, arg2) { - arg0.label = getStringFromWasm0(arg1, arg2); - }, - __wbg_set_label_6db0393d3fdc90a5: function(arg0, arg1, arg2) { - arg0.label = getStringFromWasm0(arg1, arg2); - }, - __wbg_set_label_72bb4f41ef0cb893: function(arg0, arg1, arg2) { - arg0.label = getStringFromWasm0(arg1, arg2); - }, - __wbg_set_label_79387decda299036: function(arg0, arg1, arg2) { - arg0.label = getStringFromWasm0(arg1, arg2); - }, - __wbg_set_label_d010f237b26f2c55: function(arg0, arg1, arg2) { - arg0.label = getStringFromWasm0(arg1, arg2); - }, - __wbg_set_label_e3944e54881b8c50: function(arg0, arg1, arg2) { - arg0.label = getStringFromWasm0(arg1, arg2); - }, - __wbg_set_label_ef44793ddf4455c5: function(arg0, arg1, arg2) { - arg0.label = getStringFromWasm0(arg1, arg2); - }, - __wbg_set_layout_41021cfd2a2f62df: function(arg0, arg1) { - arg0.layout = arg1; - }, - __wbg_set_layout_913d53c17194c989: function(arg0, arg1) { - arg0.layout = arg1; - }, - __wbg_set_layout_gpu_auto_layout_mode_0a5a185b3d52b726: function(arg0, arg1) { - arg0.layout = __wbindgen_enum_GpuAutoLayoutMode[arg1]; - }, - __wbg_set_mapped_at_creation_81b586dc90a50347: function(arg0, arg1) { - arg0.mappedAtCreation = arg1 !== 0; - }, - __wbg_set_module_5db9b76ee2dd2a59: function(arg0, arg1) { - arg0.module = arg1; - }, - __wbg_set_offset_f64_89f0ce01a689839e: function(arg0, arg1) { - arg0.offset = arg1; - }, - __wbg_set_onuncapturederror_c8a77eb8695205a0: function(arg0, arg1) { - arg0.onuncapturederror = arg1; - }, - __wbg_set_power_preference_8fdca0b7af640d49: function(arg0, arg1) { - arg0.powerPreference = __wbindgen_enum_GpuPowerPreference[arg1]; - }, - __wbg_set_query_set_4889dd944d5ec0fd: function(arg0, arg1) { - arg0.querySet = arg1; - }, - __wbg_set_required_features_1baf274a8669db60: function(arg0, arg1, arg2) { - arg0.requiredFeatures = getArrayJsValueViewFromWasm0(arg1, arg2); - }, - __wbg_set_required_limits_871ed33c68613dcb: function(arg0, arg1) { - arg0.requiredLimits = arg1; - }, - __wbg_set_resource_5ae7b5e67924f234: function(arg0, arg1) { - arg0.resource = arg1; - }, - __wbg_set_resource_gpu_buffer_binding_e5dbca063e7cb67b: function(arg0, arg1) { - arg0.resource = arg1; - }, - __wbg_set_resource_gpu_texture_view_eb46c355d51ad7e5: function(arg0, arg1) { - arg0.resource = arg1; - }, - __wbg_set_size_f64_6bcd40704bf4cfdc: function(arg0, arg1) { - arg0.size = arg1; - }, - __wbg_set_size_f64_8b8f6bba5d678162: function(arg0, arg1) { - arg0.size = arg1; - }, - __wbg_set_timestamp_writes_59c2d19ed8aecd97: function(arg0, arg1) { - arg0.timestampWrites = arg1; - }, - __wbg_set_usage_b2a2935f37bf3d08: function(arg0, arg1) { - arg0.usage = arg1 >>> 0; - }, - __wbg_static_accessor_GLOBAL_4ef717fb391d88b7: function() { - const ret = typeof global === 'undefined' ? null : global; - return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); - }, - __wbg_static_accessor_GLOBAL_THIS_8d1badc68b5a74f4: function() { - const ret = typeof globalThis === 'undefined' ? null : globalThis; - return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); - }, - __wbg_static_accessor_SELF_146583524fe1469b: function() { - const ret = typeof self === 'undefined' ? null : self; - return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); - }, - __wbg_static_accessor_WINDOW_f2829a2234d7819e: function() { - const ret = typeof window === 'undefined' ? null : window; - return isLikeNone(ret) ? 0 : addToExternrefTable0(ret); - }, - __wbg_subarray_3ed232c8a6baee09: function(arg0, arg1, arg2) { - const ret = arg0.subarray(arg1 >>> 0, arg2 >>> 0); - return ret; - }, - __wbg_subgroupMaxSize_1527c5f7a8fe91bb: function(arg0) { - const ret = arg0.subgroupMaxSize; - return ret; - }, - __wbg_subgroupMinSize_d6c5ad4bddc828e9: function(arg0) { - const ret = arg0.subgroupMinSize; - return ret; - }, - __wbg_submit_ce44115121cd166c: function(arg0, arg1, arg2) { - arg0.submit(getArrayJsValueViewFromWasm0(arg1, arg2)); - }, - __wbg_then_16d107c451e9905d: function(arg0, arg1, arg2) { - const ret = arg0.then(arg1, arg2); - return ret; - }, - __wbg_then_6ec10ae38b3e92f7: function(arg0, arg1) { - const ret = arg0.then(arg1); - return ret; - }, - __wbg_unconfigure_0a07a0a40de8988d: function(arg0) { - arg0.unconfigure(); - }, - __wbg_unmap_adaf93276fdf9aaf: function(arg0) { - arg0.unmap(); - }, - __wbg_valueOf_64f89f12f08671ee: function(arg0) { - const ret = arg0.valueOf(); - return ret; - }, - __wbg_webruntime_new: function(arg0) { - const ret = WebRuntime.__wrap(arg0); - return ret; - }, - __wbg_writeBuffer_8b5bd251a89198bc: function() { return handleError(function (arg0, arg1, arg2, arg3, arg4, arg5, arg6) { - arg0.writeBuffer(arg1, arg2, getArrayU8FromWasm0(arg3, arg4), arg5, arg6); - }, arguments); }, - __wbindgen_cast_0000000000000001: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 869, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h0b14ad808bd1fafd); - return ret; - }, - __wbindgen_cast_0000000000000002: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("GPUDevice")], shim_idx: 824, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h64756eda9b70f90e); - return ret; - }, - __wbindgen_cast_0000000000000003: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("GPUUncapturedErrorEvent")], shim_idx: 821, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h05686dd3e351e542); - return ret; - }, - __wbindgen_cast_0000000000000004: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("any")], shim_idx: 824, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h64756eda9b70f90e_3); - return ret; - }, - __wbindgen_cast_0000000000000005: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("undefined")], shim_idx: 824, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, wasm_bindgen__convert__closures_____invoke__h64756eda9b70f90e_4); - return ret; - }, - __wbindgen_cast_0000000000000006: function(arg0) { - // Cast intrinsic for `F64 -> Externref`. - const ret = arg0; - return ret; - }, - __wbindgen_cast_0000000000000007: function(arg0, arg1) { - // Cast intrinsic for `Ref(Slice(U8)) -> NamedExternref("Uint8Array")`. - const ret = getArrayU8FromWasm0(arg0, arg1); - return ret; - }, - __wbindgen_cast_0000000000000008: function(arg0, arg1) { - // Cast intrinsic for `Ref(String) -> Externref`. - const ret = getStringFromWasm0(arg0, arg1); - return ret; - }, - __wbindgen_init_externref_table: function() { - const table = wasm.__wbindgen_externrefs; - const offset = table.grow(4); - table.set(0, undefined); - table.set(offset + 0, undefined); - table.set(offset + 1, null); - table.set(offset + 2, true); - table.set(offset + 3, false); - }, - }; - return { - __proto__: null, - "./pvlc_runtime_web_bg.js": import0, - }; -} - -function wasm_bindgen__convert__closures_____invoke__h05686dd3e351e542(arg0, arg1, arg2) { - wasm.wasm_bindgen__convert__closures_____invoke__h05686dd3e351e542(arg0, arg1, arg2); -} - -function wasm_bindgen__convert__closures_____invoke__h0b14ad808bd1fafd(arg0, arg1, arg2) { - const ret = wasm.wasm_bindgen__convert__closures_____invoke__h0b14ad808bd1fafd(arg0, arg1, arg2); - if (ret[1]) { - throw takeFromExternrefTable0(ret[0]); - } -} - -function wasm_bindgen__convert__closures_____invoke__h64756eda9b70f90e(arg0, arg1, arg2) { - const ret = wasm.wasm_bindgen__convert__closures_____invoke__h64756eda9b70f90e(arg0, arg1, arg2); - if (ret[1]) { - throw takeFromExternrefTable0(ret[0]); - } -} - -function wasm_bindgen__convert__closures_____invoke__h64756eda9b70f90e_3(arg0, arg1, arg2) { - const ret = wasm.wasm_bindgen__convert__closures_____invoke__h64756eda9b70f90e_3(arg0, arg1, arg2); - if (ret[1]) { - throw takeFromExternrefTable0(ret[0]); - } -} - -function wasm_bindgen__convert__closures_____invoke__h64756eda9b70f90e_4(arg0, arg1, arg2) { - const ret = wasm.wasm_bindgen__convert__closures_____invoke__h64756eda9b70f90e_4(arg0, arg1, arg2); - if (ret[1]) { - throw takeFromExternrefTable0(ret[0]); - } -} - -function wasm_bindgen__convert__closures_____invoke__h963f897f0e02fd13(arg0, arg1, arg2, arg3) { - wasm.wasm_bindgen__convert__closures_____invoke__h963f897f0e02fd13(arg0, arg1, arg2, arg3); -} - - -const __wbindgen_enum_GpuAutoLayoutMode = ["auto"]; - - -const __wbindgen_enum_GpuPowerPreference = ["low-power", "high-performance"]; - - -const __wbindgen_enum_GpuTextureFormat = ["r8unorm", "r8snorm", "r8uint", "r8sint", "r16unorm", "r16snorm", "r16uint", "r16sint", "r16float", "rg8unorm", "rg8snorm", "rg8uint", "rg8sint", "r32uint", "r32sint", "r32float", "rg16unorm", "rg16snorm", "rg16uint", "rg16sint", "rg16float", "rgba8unorm", "rgba8unorm-srgb", "rgba8snorm", "rgba8uint", "rgba8sint", "bgra8unorm", "bgra8unorm-srgb", "rgb9e5ufloat", "rgb10a2uint", "rgb10a2unorm", "rg11b10ufloat", "rg32uint", "rg32sint", "rg32float", "rgba16unorm", "rgba16snorm", "rgba16uint", "rgba16sint", "rgba16float", "rgba32uint", "rgba32sint", "rgba32float", "stencil8", "depth16unorm", "depth24plus", "depth24plus-stencil8", "depth32float", "depth32float-stencil8", "bc1-rgba-unorm", "bc1-rgba-unorm-srgb", "bc2-rgba-unorm", "bc2-rgba-unorm-srgb", "bc3-rgba-unorm", "bc3-rgba-unorm-srgb", "bc4-r-unorm", "bc4-r-snorm", "bc5-rg-unorm", "bc5-rg-snorm", "bc6h-rgb-ufloat", "bc6h-rgb-float", "bc7-rgba-unorm", "bc7-rgba-unorm-srgb", "etc2-rgb8unorm", "etc2-rgb8unorm-srgb", "etc2-rgb8a1unorm", "etc2-rgb8a1unorm-srgb", "etc2-rgba8unorm", "etc2-rgba8unorm-srgb", "eac-r11unorm", "eac-r11snorm", "eac-rg11unorm", "eac-rg11snorm", "astc-4x4-unorm", "astc-4x4-unorm-srgb", "astc-5x4-unorm", "astc-5x4-unorm-srgb", "astc-5x5-unorm", "astc-5x5-unorm-srgb", "astc-6x5-unorm", "astc-6x5-unorm-srgb", "astc-6x6-unorm", "astc-6x6-unorm-srgb", "astc-8x5-unorm", "astc-8x5-unorm-srgb", "astc-8x6-unorm", "astc-8x6-unorm-srgb", "astc-8x8-unorm", "astc-8x8-unorm-srgb", "astc-10x5-unorm", "astc-10x5-unorm-srgb", "astc-10x6-unorm", "astc-10x6-unorm-srgb", "astc-10x8-unorm", "astc-10x8-unorm-srgb", "astc-10x10-unorm", "astc-10x10-unorm-srgb", "astc-12x10-unorm", "astc-12x10-unorm-srgb", "astc-12x12-unorm", "astc-12x12-unorm-srgb"]; -const WebRuntimeFinalization = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(ptr => wasm.__wbg_webruntime_free(ptr, 1)); -const WebVisionQkvStackSelectionFinalization = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(ptr => wasm.__wbg_webvisionqkvstackselection_free(ptr, 1)); - -function addToExternrefTable0(obj) { - const idx = wasm.__externref_table_alloc(); - wasm.__wbindgen_externrefs.set(idx, obj); - return idx; -} - -function _assertClass(instance, klass) { - if (!(instance instanceof klass)) { - throw new Error(`expected instance of ${klass.name}`); - } -} - -const CLOSURE_DTORS = (typeof FinalizationRegistry === 'undefined') - ? { register: () => {}, unregister: () => {} } - : new FinalizationRegistry(state => wasm.__wbindgen_destroy_closure(state.a, state.b)); - -function debugString(val) { - // primitive types - const type = typeof val; - if (type == 'number' || type == 'boolean' || val == null) { - return `${val}`; - } - if (type == 'string') { - return `"${val}"`; - } - if (type == 'symbol') { - const description = val.description; - if (description == null) { - return 'Symbol'; - } else { - return `Symbol(${description})`; - } - } - if (type == 'function') { - const name = val.name; - if (typeof name == 'string' && name.length > 0) { - return `Function(${name})`; - } else { - return 'Function'; - } - } - // objects - if (Array.isArray(val)) { - const length = val.length; - let debug = '['; - if (length > 0) { - debug += debugString(val[0]); - } - for(let i = 1; i < length; i++) { - debug += ', ' + debugString(val[i]); - } - debug += ']'; - return debug; - } - // Test for built-in - const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); - let className; - if (builtInMatches && builtInMatches.length > 1) { - className = builtInMatches[1]; - } else { - // Failed to match the standard '[object ClassName]' - return toString.call(val); - } - if (className == 'Object') { - // we're a user defined class or Object - // JSON.stringify avoids problems with cycles, and is generally much - // easier than looping through ownProperties of `val`. - try { - return 'Object(' + JSON.stringify(val) + ')'; - } catch (_) { - return 'Object'; - } - } - // errors - if (val instanceof Error) { - return `${val.name}: ${val.message}\n${val.stack}`; - } - // TODO we could test for more things here, like `Set`s and `Map`s. - return className; -} - -function getArrayF32FromWasm0(ptr, len) { - ptr = ptr >>> 0; - return getFloat32ArrayMemory0().subarray(ptr / 4, ptr / 4 + len); -} - -function getArrayJsValueViewFromWasm0(ptr, len) { - ptr = ptr >>> 0; - const mem = getDataViewMemory0(); - const result = []; - for (let i = ptr; i < ptr + 4 * len; i += 4) { - result.push(wasm.__wbindgen_externrefs.get(mem.getUint32(i, true))); - } - return result; -} - -function getArrayU32FromWasm0(ptr, len) { - ptr = ptr >>> 0; - return getUint32ArrayMemory0().subarray(ptr / 4, ptr / 4 + len); -} - -function getArrayU8FromWasm0(ptr, len) { - ptr = ptr >>> 0; - return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len); -} - -let cachedDataViewMemory0 = null; -function getDataViewMemory0() { - if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { - cachedDataViewMemory0 = new DataView(wasm.memory.buffer); - } - return cachedDataViewMemory0; -} - -let cachedFloat32ArrayMemory0 = null; -function getFloat32ArrayMemory0() { - if (cachedFloat32ArrayMemory0 === null || cachedFloat32ArrayMemory0.byteLength === 0) { - cachedFloat32ArrayMemory0 = new Float32Array(wasm.memory.buffer); - } - return cachedFloat32ArrayMemory0; -} - -function getStringFromWasm0(ptr, len) { - return decodeText(ptr >>> 0, len); -} - -let cachedUint32ArrayMemory0 = null; -function getUint32ArrayMemory0() { - if (cachedUint32ArrayMemory0 === null || cachedUint32ArrayMemory0.byteLength === 0) { - cachedUint32ArrayMemory0 = new Uint32Array(wasm.memory.buffer); - } - return cachedUint32ArrayMemory0; -} - -let cachedUint8ArrayMemory0 = null; -function getUint8ArrayMemory0() { - if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { - cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); - } - return cachedUint8ArrayMemory0; -} - -function handleError(f, args) { - try { - return f.apply(this, args); - } catch (e) { - const idx = addToExternrefTable0(e); - wasm.__wbindgen_exn_store(idx); - } -} - -function isLikeNone(x) { - return x === undefined || x === null; -} - -function makeMutClosure(arg0, arg1, f) { - const state = { a: arg0, b: arg1, cnt: 1 }; - const real = (...args) => { - - // First up with a closure we increment the internal reference - // count. This ensures that the Rust closure environment won't - // be deallocated while we're invoking it. - state.cnt++; - const a = state.a; - state.a = 0; - try { - return f(a, state.b, ...args); - } finally { - state.a = a; - real._wbg_cb_unref(); - } - }; - real._wbg_cb_unref = () => { - if (--state.cnt === 0) { - wasm.__wbindgen_destroy_closure(state.a, state.b); - state.a = 0; - CLOSURE_DTORS.unregister(state); - } - }; - CLOSURE_DTORS.register(real, state, state); - return real; -} - -function passStringToWasm0(arg, malloc, realloc) { - if (realloc === undefined) { - const buf = cachedTextEncoder.encode(arg); - const ptr = malloc(buf.length, 1) >>> 0; - getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); - WASM_VECTOR_LEN = buf.length; - return ptr; - } - - let len = arg.length; - let ptr = malloc(len, 1) >>> 0; - - const mem = getUint8ArrayMemory0(); - - let offset = 0; - - for (; offset < len; offset++) { - const code = arg.charCodeAt(offset); - if (code > 0x7F) break; - mem[ptr + offset] = code; - } - if (offset !== len) { - if (offset !== 0) { - arg = arg.slice(offset); - } - ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; - const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); - const ret = cachedTextEncoder.encodeInto(arg, view); - - offset += ret.written; - ptr = realloc(ptr, len, offset, 1) >>> 0; - } - - WASM_VECTOR_LEN = offset; - return ptr; -} - -function takeFromExternrefTable0(idx) { - const value = wasm.__wbindgen_externrefs.get(idx); - wasm.__externref_table_dealloc(idx); - return value; -} - -let cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); -cachedTextDecoder.decode(); -const MAX_SAFARI_DECODE_BYTES = 2146435072; -let numBytesDecoded = 0; -function decodeText(ptr, len) { - numBytesDecoded += len; - if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) { - cachedTextDecoder = new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }); - cachedTextDecoder.decode(); - numBytesDecoded = len; - } - return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); -} - -const cachedTextEncoder = new TextEncoder(); - -if (!('encodeInto' in cachedTextEncoder)) { - cachedTextEncoder.encodeInto = function (arg, view) { - const buf = cachedTextEncoder.encode(arg); - view.set(buf); - return { - read: arg.length, - written: buf.length - }; - }; -} - -let WASM_VECTOR_LEN = 0; - -let wasmModule, wasmInstance, wasm; -function __wbg_finalize_init(instance, module) { - wasmInstance = instance; - wasm = instance.exports; - wasmModule = module; - cachedDataViewMemory0 = null; - cachedFloat32ArrayMemory0 = null; - cachedUint32ArrayMemory0 = null; - cachedUint8ArrayMemory0 = null; - wasm.__wbindgen_start(); - return wasm; -} - -async function __wbg_load(module, imports) { - if (typeof Response === 'function' && module instanceof Response) { - if (typeof WebAssembly.instantiateStreaming === 'function') { - try { - return await WebAssembly.instantiateStreaming(module, imports); - } catch (e) { - const validResponse = module.ok && expectedResponseType(module.type); - - if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') { - console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); - - } else { throw e; } - } - } - - const bytes = await module.arrayBuffer(); - return await WebAssembly.instantiate(bytes, imports); - } else { - const instance = await WebAssembly.instantiate(module, imports); - - if (instance instanceof WebAssembly.Instance) { - return { instance, module }; - } else { - return instance; - } - } - - function expectedResponseType(type) { - switch (type) { - case 'basic': case 'cors': case 'default': return true; - } - return false; - } -} - -function initSync(module) { - if (wasm !== undefined) return wasm; - - - if (module !== undefined) { - if (Object.getPrototypeOf(module) === Object.prototype) { - ({module} = module) - } else { - console.warn('using deprecated parameters for `initSync()`; pass a single object instead') - } - } - - const imports = __wbg_get_imports(); - if (!(module instanceof WebAssembly.Module)) { - module = new WebAssembly.Module(module); - } - const instance = new WebAssembly.Instance(module, imports); - return __wbg_finalize_init(instance, module); -} - -async function __wbg_init(module_or_path) { - if (wasm !== undefined) return wasm; - - - if (module_or_path !== undefined) { - if (Object.getPrototypeOf(module_or_path) === Object.prototype) { - ({module_or_path} = module_or_path) - } else { - console.warn('using deprecated parameters for the initialization function; pass a single object instead') - } - } - - if (module_or_path === undefined) { - module_or_path = new URL('pvlc_runtime_web_bg.wasm', import.meta.url); - } - const imports = __wbg_get_imports(); - - if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { - module_or_path = fetch(module_or_path); - } - - const { instance, module } = await __wbg_load(await module_or_path, imports); - - return __wbg_finalize_init(instance, module); -} - -export { initSync, __wbg_init as default }; diff --git a/public/vendor/paddleocr-vl/pkg/pvlc_runtime_web_bg.wasm b/public/vendor/paddleocr-vl/pkg/pvlc_runtime_web_bg.wasm deleted file mode 100644 index 06362f9..0000000 Binary files a/public/vendor/paddleocr-vl/pkg/pvlc_runtime_web_bg.wasm and /dev/null differ diff --git a/public/vendor/paddleocr-vl/pkg/snippets/pvlc-runtime-web-2887d2e0146ca1ca/inline0.js b/public/vendor/paddleocr-vl/pkg/snippets/pvlc-runtime-web-2887d2e0146ca1ca/inline0.js deleted file mode 100644 index 73fae93..0000000 --- a/public/vendor/paddleocr-vl/pkg/snippets/pvlc-runtime-web-2887d2e0146ca1ca/inline0.js +++ /dev/null @@ -1,145 +0,0 @@ - -const PVLC_UINT8_ARRAY = Uint8Array; -const PVLC_UINT8_ARRAY_PROTOTYPE = PVLC_UINT8_ARRAY.prototype; -const PVLC_TYPED_ARRAY_CONSTRUCTOR = Object.getPrototypeOf(PVLC_UINT8_ARRAY); -const PVLC_TYPED_ARRAY_PROTOTYPE = Object.getPrototypeOf(PVLC_UINT8_ARRAY_PROTOTYPE); -const PVLC_GET_PROTOTYPE_OF = Object.getPrototypeOf; -const PVLC_GET_OWN_PROPERTY_DESCRIPTOR = Object.getOwnPropertyDescriptor; -const PVLC_REFLECT_APPLY = Reflect.apply; -const PVLC_ERROR = Error; -const PVLC_GLOBAL = globalThis; -const PVLC_SYMBOL_SPECIES = Symbol.species; -const PVLC_UINT8_ARRAY_GLOBAL_DESCRIPTOR = - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_GLOBAL, "Uint8Array"); -const PVLC_UINT8_ARRAY_CONSTRUCTOR_DESCRIPTOR = - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_UINT8_ARRAY_PROTOTYPE, "constructor"); -const PVLC_UINT8_ARRAY_SPECIES_DESCRIPTOR = - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_UINT8_ARRAY, PVLC_SYMBOL_SPECIES); -const PVLC_TYPED_ARRAY_SPECIES_DESCRIPTOR = - PVLC_GET_OWN_PROPERTY_DESCRIPTOR( - PVLC_TYPED_ARRAY_CONSTRUCTOR, - PVLC_SYMBOL_SPECIES, - ); -const PVLC_BRIDGE_PROPERTY_NAMES = [ - "byteLength", - "length", - "set", - "subarray", - "slice", -]; -const PVLC_TYPED_ARRAY_PROPERTY_DESCRIPTORS = [ - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_TYPED_ARRAY_PROTOTYPE, "byteLength"), - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_TYPED_ARRAY_PROTOTYPE, "length"), - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_TYPED_ARRAY_PROTOTYPE, "set"), - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_TYPED_ARRAY_PROTOTYPE, "subarray"), - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_TYPED_ARRAY_PROTOTYPE, "slice"), -]; -const PVLC_UINT8_ARRAY_PROPERTY_DESCRIPTORS = [ - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_UINT8_ARRAY_PROTOTYPE, "byteLength"), - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_UINT8_ARRAY_PROTOTYPE, "length"), - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_UINT8_ARRAY_PROTOTYPE, "set"), - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_UINT8_ARRAY_PROTOTYPE, "subarray"), - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_UINT8_ARRAY_PROTOTYPE, "slice"), -]; -const PVLC_TYPED_ARRAY_BYTE_LENGTH_GETTER = - PVLC_TYPED_ARRAY_PROPERTY_DESCRIPTORS[0]?.get; -const PVLC_TYPED_ARRAY_SET = PVLC_TYPED_ARRAY_PROPERTY_DESCRIPTORS[2]?.value; - -function pvlcOwnDescriptorField(descriptor, name) { - const field = PVLC_GET_OWN_PROPERTY_DESCRIPTOR(descriptor, name); - return field === undefined ? undefined : field.value; -} - -function pvlcDescriptorMatches(expected, observed) { - if (expected === undefined || observed === undefined) { - return expected === observed; - } - return ( - pvlcOwnDescriptorField(expected, "value") === - pvlcOwnDescriptorField(observed, "value") && - pvlcOwnDescriptorField(expected, "get") === - pvlcOwnDescriptorField(observed, "get") && - pvlcOwnDescriptorField(expected, "set") === - pvlcOwnDescriptorField(observed, "set") && - pvlcOwnDescriptorField(expected, "configurable") === - pvlcOwnDescriptorField(observed, "configurable") && - pvlcOwnDescriptorField(expected, "enumerable") === - pvlcOwnDescriptorField(observed, "enumerable") && - pvlcOwnDescriptorField(expected, "writable") === - pvlcOwnDescriptorField(observed, "writable") - ); -} - -function pvlcAssertUint8ArrayBridgeIntrinsics() { - if (!pvlcDescriptorMatches( - PVLC_UINT8_ARRAY_GLOBAL_DESCRIPTOR, - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_GLOBAL, "Uint8Array"), - ) || - PVLC_UINT8_ARRAY.prototype !== PVLC_UINT8_ARRAY_PROTOTYPE || - PVLC_GET_PROTOTYPE_OF(PVLC_UINT8_ARRAY) !== - PVLC_TYPED_ARRAY_CONSTRUCTOR || - PVLC_GET_PROTOTYPE_OF(PVLC_UINT8_ARRAY_PROTOTYPE) !== - PVLC_TYPED_ARRAY_PROTOTYPE || - !pvlcDescriptorMatches( - PVLC_UINT8_ARRAY_CONSTRUCTOR_DESCRIPTOR, - PVLC_GET_OWN_PROPERTY_DESCRIPTOR( - PVLC_UINT8_ARRAY_PROTOTYPE, - "constructor", - ), - ) || - !pvlcDescriptorMatches( - PVLC_UINT8_ARRAY_SPECIES_DESCRIPTOR, - PVLC_GET_OWN_PROPERTY_DESCRIPTOR( - PVLC_UINT8_ARRAY, - PVLC_SYMBOL_SPECIES, - ), - ) || - !pvlcDescriptorMatches( - PVLC_TYPED_ARRAY_SPECIES_DESCRIPTOR, - PVLC_GET_OWN_PROPERTY_DESCRIPTOR( - PVLC_TYPED_ARRAY_CONSTRUCTOR, - PVLC_SYMBOL_SPECIES, - ), - )) { - throw new PVLC_ERROR("pvlc Uint8Array bridge intrinsic boundary drifted"); - } - for (let index = 0; index < PVLC_BRIDGE_PROPERTY_NAMES.length; index += 1) { - const name = PVLC_BRIDGE_PROPERTY_NAMES[index]; - const observedTypedArray = - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_TYPED_ARRAY_PROTOTYPE, name); - const observedUint8Array = - PVLC_GET_OWN_PROPERTY_DESCRIPTOR(PVLC_UINT8_ARRAY_PROTOTYPE, name); - if (!pvlcDescriptorMatches( - PVLC_TYPED_ARRAY_PROPERTY_DESCRIPTORS[index], - observedTypedArray, - ) || !pvlcDescriptorMatches( - PVLC_UINT8_ARRAY_PROPERTY_DESCRIPTORS[index], - observedUint8Array, - )) { - throw new PVLC_ERROR( - `pvlc Uint8Array bridge intrinsic boundary drifted: ${name}`, - ); - } - } -} - -export function own_pvlc_uint8array_bridge_input(value) { - pvlcAssertUint8ArrayBridgeIntrinsics(); - try { - if (PVLC_GET_PROTOTYPE_OF(value) !== PVLC_UINT8_ARRAY_PROTOTYPE || - typeof PVLC_TYPED_ARRAY_BYTE_LENGTH_GETTER !== "function" || - typeof PVLC_TYPED_ARRAY_SET !== "function") { - throw new PVLC_ERROR("pvlc Uint8Array bridge input is invalid"); - } - const byteLength = PVLC_REFLECT_APPLY( - PVLC_TYPED_ARRAY_BYTE_LENGTH_GETTER, - value, - [], - ); - const owned = new PVLC_UINT8_ARRAY(byteLength); - PVLC_REFLECT_APPLY(PVLC_TYPED_ARRAY_SET, owned, [value, 0]); - return owned; - } catch { - throw new PVLC_ERROR("pvlc Uint8Array bridge input is invalid"); - } -} diff --git a/public/vendor/paddleocr-vl/vl-worker.mjs b/public/vendor/paddleocr-vl/vl-worker.mjs deleted file mode 100644 index 36a108e..0000000 --- a/public/vendor/paddleocr-vl/vl-worker.mjs +++ /dev/null @@ -1,82 +0,0 @@ -// Documents Manager: runs PaddleOCR-VL (WebGPU) in a dedicated module worker so loading the ~1.9 GB of weights -// never blocks the page. The model base URL comes with the init message (local model folder or Hugging Face). Protocol (postMessage): -// → { id, type: "init", base } ← { id, ok: true, info } | { id, error } -// → { id, type: "recognize", bitmap, maxTokens, task } ← { id, progress } … then { id, ok: true, result: { text, tokens, ms, tokensPerSecond } } | { id, error } -// → { id, type: "dispose" } ← { id, ok: true } -let createPaddleOcrVlEngine = null; - -let engine = null; -let pending = null; - -function errOf(e) { - return { name: (e && e.name) || "Error", message: String((e && (e.message || e)) || "unknown error").slice(0, 600), stack: String((e && e.stack) || "").slice(0, 1500) }; -} - -async function init(base) { - if (engine) return { warm: true }; - if (pending) return pending; - pending = (async () => { - if (!self.navigator || !self.navigator.gpu) throw new Error("WebGPU is not available in this browser's workers (needs iOS 26 / Safari 26, or Chrome)"); - let adapter = null; - try { adapter = await self.navigator.gpu.requestAdapter({ powerPreference: "high-performance" }); } - catch (e) { throw new Error("WebGPU adapter request failed: " + ((e && e.message) || e)); } - if (!adapter) throw new Error("WebGPU has no GPU adapter on this device"); - if (!(adapter.features && adapter.features.has("shader-f16"))) throw new Error("this GPU has no WebGPU shader-f16 support (PaddleOCR-VL needs it)"); - const lim = adapter.limits || {}; - if (base) globalThis.__PVL_MODEL_BASE__ = base; - if (!createPaddleOcrVlEngine) ({ createPaddleOcrVlEngine } = await import("./browser_ocr_runtime.mjs")); - engine = await createPaddleOcrVlEngine(); - return { warm: false, maxBufferSize: lim.maxBufferSize, maxStorageBufferBindingSize: lim.maxStorageBufferBindingSize }; - })(); - try { return await pending; } finally { pending = null; } -} - -self.onmessage = async (ev) => { - const m = ev.data || {}; - const id = m.id; - try { - if (m.type === "init") { - self.postMessage({ id, ok: true, info: await init(m.base) }); - } else if (m.type === "recognize") { - await init(m.base); - const bmp = m.bitmap; - const c = new OffscreenCanvas(bmp.width, bmp.height); - c.getContext("2d", { willReadFrequently: true }).drawImage(bmp, 0, 0); - try { bmp.close(); } catch (e) {} - const t0 = performance.now(); - let lastAsset = ""; - const r = await engine.recognizeCanvas(c, { - task: m.task || "ocr", - maxGeneratedTokens: m.maxTokens || 512, - onProgress: (u) => { - if (!u) return; - if (u.kind === "download") { - // throttle: one message per asset change or per ~2 % of the model - const pct = u.modelTotalBytes ? Math.floor((u.modelLoadedBytes || 0) / u.modelTotalBytes * 50) : 0; - const key = u.asset + "|" + pct; - if (key === lastAsset) return; - lastAsset = key; - self.postMessage({ id, progress: { kind: "download", asset: u.asset, modelLoadedBytes: u.modelLoadedBytes, modelTotalBytes: u.modelTotalBytes } }); - } else if (u.kind === "inference") { - self.postMessage({ id, progress: { kind: "inference", stage: u.stage, detail: u.detail } }); - } - }, - }); - c.width = c.height = 1; - self.postMessage({ id, ok: true, result: { - text: String((r && r.text) || ""), - tokens: (r && r.greedy && r.greedy.tokenIds && r.greedy.tokenIds.length) || 0, - ms: Math.round(performance.now() - t0), - tokensPerSecond: (r && r.tokensPerSecond) || 0, - } }); - } else if (m.type === "dispose") { - const e = engine; engine = null; - if (e) { try { await e.dispose(); } catch (err) {} } - self.postMessage({ id, ok: true }); - } else { - throw new Error("unknown request " + m.type); - } - } catch (e) { - self.postMessage({ id, error: errOf(e) }); - } -}; diff --git a/src/components/ModelsCard.tsx b/src/components/ModelsCard.tsx index 611b4a4..b8bee88 100644 --- a/src/components/ModelsCard.tsx +++ b/src/components/ModelsCard.tsx @@ -19,7 +19,7 @@ export function ModelsCard() { const ocr = OCR_BY_KEY[ocrEngineKey()]; const rows: Row[] = [ - { use: "📝 OCR", kind: "ocr", key: ocr.key, name: ocr.emoji + " " + ocr.name, size: ocr.approx, runs: ocr.kind === "vl" ? (gpu?.f16 ? "✅" : "❌ needs WebGPU + shader-f16") : "✅" }, + { use: "📝 OCR", kind: "ocr", key: ocr.key, name: ocr.emoji + " " + ocr.name, size: ocr.approx, runs: "✅" }, ...(["title", "from", "date", "labels"] as const).map((f) => { const m = LLM_BY_KEY[s.metaModels[f]]; return { use: { title: "📝 Title", from: "📨 From", date: "📅 Date", labels: "🏷️ Labels" }[f], kind: "meta" as const, key: m.key, name: m.emoji + " " + m.name, size: m.approx, diff --git a/src/components/SettingsSheet.tsx b/src/components/SettingsSheet.tsx index de17ac0..ddebd3c 100644 --- a/src/components/SettingsSheet.tsx +++ b/src/components/SettingsSheet.tsx @@ -57,13 +57,13 @@ function OcrCard() { const s = useSettings(); const pick = (dev: "phone" | "laptop") => ( ); return ( {OCR_ENGINES.map((m) =>

{m.emoji} {m.name} — {m.note}

)} -

If medium or PaddleOCR-VL fails, PP-OCRv6 tiny reads the rest. Pages are never rotated automatically.

+

If medium fails, PP-OCRv6 tiny reads the rest. Pages are never rotated automatically.

}>
{pick("phone")}
{pick("laptop")}
diff --git a/src/lib/catalog.ts b/src/lib/catalog.ts index 8255adb..27cf05f 100644 --- a/src/lib/catalog.ts +++ b/src/lib/catalog.ts @@ -2,48 +2,40 @@ Weights download from the configured model host (default: Hugging Face) / WebLLM libs URL and are cached on the device. Sizes are approximate download sizes. */ -export type OcrKey = "ppocr-v6t" | "ppocr-v6m" | "paddleocr-vl"; +export type OcrKey = "ppocr-v6t" | "ppocr-v6m"; export interface OcrEngine { key: OcrKey; name: string; emoji: string; - kind: "onnx" | "vl"; approx: string; bytes: number; badge?: string; - laptopOnly?: boolean; note: string; /** Hugging Face-style repos + pinned revisions (det = text detector, rec = text recogniser). */ - det?: { repo: string; rev: string; sha256: string }; - rec?: { repo: string; rev: string; sha256: string; dictSize: number }; + det: { repo: string; rev: string; sha256: string }; + rec: { repo: string; rev: string; sha256: string; dictSize: number }; /** DBPostProcess values from the detector's inference.yml. */ - db?: { thresh: number; boxThresh: number; unclip: number; maxCandidates: number }; - vl?: { repo: string; rev: string; maxTokens: number }; + db: { thresh: number; boxThresh: number; unclip: number; maxCandidates: number }; } export const DEFAULT_OCR: OcrKey = "ppocr-v6t"; export const OCR_ENGINES: OcrEngine[] = [ { - key: "ppocr-v6t", name: "PP-OCRv6 tiny", emoji: "🪶", kind: "onnx", approx: "≈ 12 MB", bytes: 12_200_000, badge: "⭐ Default", + key: "ppocr-v6t", name: "PP-OCRv6 tiny", emoji: "🪶", approx: "≈ 12 MB", bytes: 12_200_000, badge: "⭐ Default", note: "Smallest PaddleOCR model (49 languages incl. German and English; no Arabic, no Japanese). Fastest and lightest. Downloads from the model host on first use.", det: { repo: "PaddlePaddle/PP-OCRv6_tiny_det_onnx", rev: "2ba1506c0380b8f0b03dd142459aac66d4421f6c", sha256: "193bab7a04fca699a6c82e6abb5b81bdb28177f0abd4062552b04908dafb19f8" }, rec: { repo: "PaddlePaddle/PP-OCRv6_tiny_rec_onnx", rev: "2612ab37152ae0a677521bae4e1e3d4fb4cf7c30", sha256: "9ef676d6ed3c88256a2d92c640c44f25b0c40947e111b14b8be8f594091563e6", dictSize: 6904 }, db: { thresh: 0.2, boxThresh: 0.4, unclip: 1.4, maxCandidates: 3000 }, }, { - key: "ppocr-v6m", name: "PP-OCRv6 medium", emoji: "⚡", kind: "onnx", approx: "≈ 107 MB", bytes: 106_600_000, + key: "ppocr-v6m", name: "PP-OCRv6 medium", emoji: "⚡", approx: "≈ 107 MB", bytes: 106_600_000, note: "PaddleOCR detector + reader for German, English and other Latin-script text (no Arabic). More accurate, slower.", det: { repo: "PaddlePaddle/PP-OCRv6_medium_det_onnx", rev: "61323801669c338b7891481ec7bac61ce31b576a", sha256: "eb13b44b25bb36f89528b68720af8a61d9cf381176107f465db1757b65d086e1" }, rec: { repo: "PaddlePaddle/PP-OCRv6_medium_rec_onnx", rev: "50c7eacafc52fa7bcf4194e8cd08e46f8558504b", sha256: "9c09abf0957f7968c7586464b7397b84ad2387a0497a351af40e9acc71b673ba", dictSize: 18708 }, db: { thresh: 0.2, boxThresh: 0.45, unclip: 1.4, maxCandidates: 3000 }, }, - { - key: "paddleocr-vl", name: "PaddleOCR-VL 1.6", emoji: "🧠", kind: "vl", approx: "≈ 1.9 GB", bytes: 2_038_286_862, badge: "💻 Desktop only", laptopOnly: true, - note: "Vision-language OCR for 100+ languages incl. Arabic. Needs WebGPU with shader-f16. Big download, desktop only. If it fails, PP-OCRv6 tiny reads the rest.", - vl: { repo: "glebkudr/PaddleOCR-VL-1.6-WebGPU", rev: "5219606297d00bbd23b2ec193271af0c0b427dfc", maxTokens: 512 }, - }, ]; export const OCR_BY_KEY = Object.fromEntries(OCR_ENGINES.map((m) => [m.key, m])) as Record; diff --git a/src/lib/device.ts b/src/lib/device.ts index 4e4661a..b2442be 100644 --- a/src/lib/device.ts +++ b/src/lib/device.ts @@ -1,4 +1,4 @@ -/* Phone or desktop? Phones get smaller memory budgets and never PaddleOCR-VL or the 7B model. */ +/* Phone or desktop? Phones get smaller memory budgets and skip desktop-only models. */ export function isPhone(): boolean { try { const nav = navigator as Navigator & { userAgentData?: { mobile?: boolean } }; diff --git a/src/lib/modelcache.ts b/src/lib/modelcache.ts index aaca5cf..6a3f871 100644 --- a/src/lib/modelcache.ts +++ b/src/lib/modelcache.ts @@ -1,8 +1,7 @@ /* ⬇️ Model files (OCR models) in the browser's Cache Storage ("dm-models"). Downloads run ONE file at a time and stream straight into the cache (no extra copies in memory — holding big models two or three times while saving them used to crash iPhone Safari). The service worker (public/sw.js) - answers later requests for these URLs from the same cache, so engines that fetch files themselves - (PaddleOCR-VL) also work offline after the first download. */ + answers later requests for these URLs from the same cache. */ import { hub } from "./hub"; export const MODEL_CACHE = "dm-models"; diff --git a/src/lib/settings.ts b/src/lib/settings.ts index e99441b..fd35410 100644 --- a/src/lib/settings.ts +++ b/src/lib/settings.ts @@ -38,7 +38,7 @@ export const DEFAULT_LABELS: Label[] = [ ]; export interface Settings { - /** OCR engine per device type (PaddleOCR-VL is desktop-only). */ + /** OCR engine per device type. */ ocr: { phone: OcrKey; laptop: OcrKey }; /** 📄 Pages to read with OCR (also limits 🔁 Run OCR again and the search text). */ ocrPages: number; @@ -84,14 +84,14 @@ const clamp = (n: unknown, lo: number, hi: number, def: number) => { export function normalize(raw: unknown): Settings { const o = (raw && typeof raw === "object" ? raw : {}) as Partial; const d = DEFAULT_SETTINGS; - const okOcr = (k: unknown, phone: boolean): OcrKey => - typeof k === "string" && k in OCR_BY_KEY && !(phone && OCR_BY_KEY[k as OcrKey].laptopOnly) ? (k as OcrKey) : DEFAULT_OCR; + const okOcr = (k: unknown): OcrKey => + typeof k === "string" && k in OCR_BY_KEY ? (k as OcrKey) : DEFAULT_OCR; const okLlm = (k: unknown) => (typeof k === "string" && k in LLM_BY_KEY ? k : DEFAULT_LLM); const mm = (o.metaModels || {}) as Partial>; const title = okLlm(mm.title); const ocrPages = clamp(o.ocrPages, PAGES_MIN, PAGES_MAX, d.ocrPages); return { - ocr: { phone: okOcr(o.ocr?.phone, true), laptop: okOcr(o.ocr?.laptop, false) }, + ocr: { phone: okOcr(o.ocr?.phone), laptop: okOcr(o.ocr?.laptop) }, ocrPages, metaModels: { title, from: mm.from ? okLlm(mm.from) : title, date: okLlm(mm.date), labels: okLlm(mm.labels) }, metaPages: Math.min(ocrPages, clamp(o.metaPages, PAGES_MIN, PAGES_MAX, d.metaPages)), diff --git a/src/ocr/ocr.ts b/src/ocr/ocr.ts index 9193193..454cc9a 100644 --- a/src/ocr/ocr.ts +++ b/src/ocr/ocr.ts @@ -1,5 +1,5 @@ -/* 📝 OCR dispatcher: PP-OCRv6 tiny (default) / medium in one worker, PaddleOCR-VL (desktop, WebGPU) in another. - If medium or PaddleOCR-VL fails, the real error is reported and the rest of the document is read with tiny. +/* 📝 OCR dispatcher: PP-OCRv6 tiny (default) / medium in one worker. + If medium fails, the real error is reported and the rest of the document is read with tiny. If tiny fails, the page gets no text. No automatic rotation anywhere. */ import yaml from "js-yaml"; import { OCR_BY_KEY, DEFAULT_OCR, type OcrEngine, type OcrKey } from "../lib/catalog"; @@ -52,9 +52,9 @@ const fileUrl = (repo: string, rev: string, path: string) => `${hf()}/${repo}/re function onnxFiles(e: OcrEngine): ModelFile[] { return [ - { url: fileUrl(e.det!.repo, e.det!.rev, "inference.onnx"), bytes: e.bytes * 0.3 }, - { url: fileUrl(e.rec!.repo, e.rec!.rev, "inference.onnx"), bytes: e.bytes * 0.7 }, - { url: fileUrl(e.rec!.repo, e.rec!.rev, "inference.yml"), bytes: 200_000 }, + { url: fileUrl(e.det.repo, e.det.rev, "inference.onnx"), bytes: e.bytes * 0.3 }, + { url: fileUrl(e.rec.repo, e.rec.rev, "inference.onnx"), bytes: e.bytes * 0.7 }, + { url: fileUrl(e.rec.repo, e.rec.rev, "inference.yml"), bytes: 200_000 }, ]; } @@ -90,7 +90,7 @@ async function loadPp(key: OcrKey) { const [det, rec, yml] = [await readModelFile(files[0]), await readModelFile(files[1]), await readModelFile(files[2])]; const dict = parseDict(yml); const gpu = !isPhone() && (await probeGpu()).webgpu; - await pp.call({ type: "init", cfg: { name: e.name, det: e.db, dict, dictSize: e.rec!.dictSize, detBytes: det, recBytes: rec, gpu, wasmPaths: ortWasmBase } }, [det, rec]); + await pp.call({ type: "init", cfg: { name: e.name, det: e.db, dict, dictSize: e.rec.dictSize, detBytes: det, recBytes: rec, gpu, wasmPaths: ortWasmBase } }, [det, rec]); ppKey = key; hub.setLoaded("ocr", key, e.name, "ready"); } catch (err) { @@ -99,49 +99,11 @@ async function loadPp(key: OcrKey) { } } -/* ---------- PaddleOCR-VL */ -const vl = new WorkerClient(() => new Worker("/vendor/paddleocr-vl/vl-worker.mjs", { type: "module" })); -let vlBase: string | null = null; - -async function vlFiles(e: OcrEngine): Promise { - // Tree listing always uses Hugging Face's API (mirrors like R2 do not expose /api/models). - const r = await fetch(`https://huggingface.co/api/models/${e.vl!.repo}/tree/${e.vl!.rev}?recursive=true`); - if (!r.ok) throw new Error("PaddleOCR-VL file list: HTTP " + r.status); - const list = (await r.json()) as { type: string; path: string; size?: number }[]; - return list - .filter((f) => f.type === "file" && !/^(\.gitattributes|README\.md)$/.test(f.path)) - .map((f) => ({ url: fileUrl(e.vl!.repo, e.vl!.rev, f.path), bytes: f.size })); -} - -async function loadVl() { - const e = OCR_BY_KEY["paddleocr-vl"]; - if (isPhone()) throw new Error("PaddleOCR-VL is desktop-only"); - const g = await probeGpu(); - if (!g.webgpu || !g.f16) throw new Error("PaddleOCR-VL needs WebGPU with shader-f16 (" + (g.why || "no shader-f16") + ")"); - if (!vlBase) { - // Files go into the model cache first; the service worker then serves the engine's own fetches from it. - await ensureFiles("ocr-vl", e.name, await vlFiles(e)); - vlBase = `${hf()}/${e.vl!.repo}/resolve/${e.vl!.rev}`; - } - if (vl.alive && hub.get().loaded.some((x) => x.kind === "ocr" && x.key === "paddleocr-vl")) return; - await hub.makeRoom("ocr"); - if (pp.alive) { pp.kill(); ppKey = null; } - hub.setLoaded("ocr", "paddleocr-vl", e.name, "loading"); - try { - await vl.call({ type: "init", base: vlBase }); - hub.setLoaded("ocr", "paddleocr-vl", e.name, "ready"); - } catch (err) { - vl.kill(); hub.setUnloaded("ocr"); - throw err; - } -} - /* ---------- public API */ let idleT: ReturnType | undefined; async function unloadAll() { clearTimeout(idleT); if (pp.alive) { try { await pp.call({ type: "dispose" }); } catch { /* ignore */ } pp.kill(); } - if (vl.alive) { try { await vl.call({ type: "dispose" }); } catch { /* ignore */ } vl.kill(); } ppKey = null; hub.setUnloaded("ocr"); } @@ -154,15 +116,9 @@ export interface OcrPageResult { } /** Read one page image. Falls back to PP-OCRv6 tiny when the chosen engine fails. */ -export async function ocrPage(bitmap: ImageBitmap, engine: OcrKey, onStage?: (s: string) => void): Promise { +export async function ocrPage(bitmap: ImageBitmap, engine: OcrKey): Promise { clearTimeout(idleT); const run = async (key: OcrKey, bmp: ImageBitmap): Promise => { - if (key === "paddleocr-vl") { - await loadVl(); - const r = await vl.call<{ text: string }>({ type: "recognize", bitmap: bmp, maxTokens: OCR_BY_KEY[key].vl!.maxTokens, task: "ocr" }, [bmp], - (p) => p?.kind === "inference" && onStage?.(String(p.stage || ""))); - return r.text; - } await loadPp(key); const r = await pp.call<{ text: string }>({ type: "recognize", bitmap: bmp }, [bmp]); return r.text; @@ -193,16 +149,13 @@ export const unloadOcr = unloadAll; /** For the 🧠 Models card: are this engine's files on the device? */ export async function ocrCached(key: OcrKey): Promise { - const e = OCR_BY_KEY[key]; - const urls = e.kind === "onnx" ? onnxFiles(e).map((f) => f.url) : [fileUrl(e.vl!.repo, e.vl!.rev, "m6e9-tokenizer.json")]; - for (const u of urls) if (!(await isCached(u))) return false; + for (const f of onnxFiles(OCR_BY_KEY[key])) if (!(await isCached(f.url))) return false; return true; } export async function prefetchOcr(key: OcrKey) { const e = OCR_BY_KEY[key]; - if (e.kind === "onnx") await ensureFiles("ocr-" + key, e.name, onnxFiles(e)); - else if (!isPhone()) await ensureFiles("ocr-vl", e.name, await vlFiles(e)); + await ensureFiles("ocr-" + key, e.name, onnxFiles(e)); // tiny is always the fallback if (key !== DEFAULT_OCR) await ensureFiles("ocr-" + DEFAULT_OCR, OCR_BY_KEY[DEFAULT_OCR].name, onnxFiles(OCR_BY_KEY[DEFAULT_OCR])); }