utopia-ia/elffuss-engine public
Changesets · Branches · Tags · Compare
| Changeset | c77c830703d1c190553c3b82b0391754436e967ef24c044aa6889d825dd44cba |
|---|---|
| Author | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-25 13:54 UTC |
| Committer | KikoCis <KikoCis@users.noreply.github.com> · 2026-10-25 13:54 UTC |
| Parents | None: the first changeset |
25 files changed
added CHANGELOG.md +34 −0
| @@ -0,0 +1,34 @@ | ||
| 1 | +# Changelog | |
| 2 | + | |
| 3 | +Changes to what this repository publishes. Version numbers start with 0.1.0, the first release; until then | |
| 4 | +everything is listed under Unreleased. | |
| 5 | + | |
| 6 | +## Unreleased | |
| 7 | + | |
| 8 | +### Fixed | |
| 9 | + | |
| 10 | +- Sampling with a temperature above zero could return the least likely candidate about half of the time, because | |
| 11 | + the random draw fell outside its range; consecutive seeds also gave correlated draws. The draw is now uniform. | |
| 12 | +- `js/tokenizer.js` is plain text: three literal NUL characters are written as `'\u0000'`, which is the same string. | |
| 13 | + | |
| 14 | +### Changed | |
| 15 | + | |
| 16 | +- The sampler follows llama.cpp's order: penalties, top-k, top-p, min-p, then temperature. Top-p and min-p are now | |
| 17 | + computed before the temperature is applied. | |
| 18 | +- The seed advances with every generated token. | |
| 19 | +- When the app sets no sampling, the engine uses the one the registry declares for the model, if any; otherwise it | |
| 20 | + decodes greedily with its default repeat penalty (1.1 over the last 64 tokens). `setSampling()` merges into that. | |
| 21 | +- The published tree is the import closure of `js/provider.js` (19 modules) and the files around it. The README | |
| 22 | + and `package.json` were rewritten for this repository; `package.json` declares `Apache-2.0 AND MIT`, as | |
| 23 | + `js/quant-tables.js` does, and lists `assets/`. | |
| 24 | + | |
| 25 | +### Added | |
| 26 | + | |
| 27 | +- `setSampling()` accepts `minP`, `presence` and `repeatPenalty`. | |
| 28 | +- Models that reason get an open reasoning block and a reply budget of their own; `setSampling({ razonar })` forces | |
| 29 | + reasoning on (`true`) or off (`false`), and `null` leaves it to the registry. | |
| 30 | +- `NOTICE`, and the complete MIT licence of the ggml authors at the top of `js/quant-tables.js`. | |
| 31 | + | |
| 32 | +### Removed | |
| 33 | + | |
| 34 | +- The two articles in `docs/`, which were in Spanish. They will come back rewritten in English. |
added LICENSE +202 −0
| @@ -0,0 +1,202 @@ | ||
| 1 | + | |
| 2 | + Apache License | |
| 3 | + Version 2.0, January 2004 | |
| 4 | + http://www.apache.org/licenses/ | |
| 5 | + | |
| 6 | + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION | |
| 7 | + | |
| 8 | + 1. Definitions. | |
| 9 | + | |
| 10 | + "License" shall mean the terms and conditions for use, reproduction, | |
| 11 | + and distribution as defined by Sections 1 through 9 of this document. | |
| 12 | + | |
| 13 | + "Licensor" shall mean the copyright owner or entity authorized by | |
| 14 | + the copyright owner that is granting the License. | |
| 15 | + | |
| 16 | + "Legal Entity" shall mean the union of the acting entity and all | |
| 17 | + other entities that control, are controlled by, or are under common | |
| 18 | + control with that entity. For the purposes of this definition, | |
| 19 | + "control" means (i) the power, direct or indirect, to cause the | |
| 20 | + direction or management of such entity, whether by contract or | |
| 21 | + otherwise, or (ii) ownership of fifty percent (50%) or more of the | |
| 22 | + outstanding shares, or (iii) beneficial ownership of such entity. | |
| 23 | + | |
| 24 | + "You" (or "Your") shall mean an individual or Legal Entity | |
| 25 | + exercising permissions granted by this License. | |
| 26 | + | |
| 27 | + "Source" form shall mean the preferred form for making modifications, | |
| 28 | + including but not limited to software source code, documentation | |
| 29 | + source, and configuration files. | |
| 30 | + | |
| 31 | + "Object" form shall mean any form resulting from mechanical | |
| 32 | + transformation or translation of a Source form, including but | |
| 33 | + not limited to compiled object code, generated documentation, | |
| 34 | + and conversions to other media types. | |
| 35 | + | |
| 36 | + "Work" shall mean the work of authorship, whether in Source or | |
| 37 | + Object form, made available under the License, as indicated by a | |
| 38 | + copyright notice that is included in or attached to the work | |
| 39 | + (an example is provided in the Appendix below). | |
| 40 | + | |
| 41 | + "Derivative Works" shall mean any work, whether in Source or Object | |
| 42 | + form, that is based on (or derived from) the Work and for which the | |
| 43 | + editorial revisions, annotations, elaborations, or other modifications | |
| 44 | + represent, as a whole, an original work of authorship. For the purposes | |
| 45 | + of this License, Derivative Works shall not include works that remain | |
| 46 | + separable from, or merely link (or bind by name) to the interfaces of, | |
| 47 | + the Work and Derivative Works thereof. | |
| 48 | + | |
| 49 | + "Contribution" shall mean any work of authorship, including | |
| 50 | + the original version of the Work and any modifications or additions | |
| 51 | + to that Work or Derivative Works thereof, that is intentionally | |
| 52 | + submitted to Licensor for inclusion in the Work by the copyright owner | |
| 53 | + or by an individual or Legal Entity authorized to submit on behalf of | |
| 54 | + the copyright owner. For the purposes of this definition, "submitted" | |
| 55 | + means any form of electronic, verbal, or written communication sent | |
| 56 | + to the Licensor or its representatives, including but not limited to | |
| 57 | + communication on electronic mailing lists, source code control systems, | |
| 58 | + and issue tracking systems that are managed by, or on behalf of, the | |
| 59 | + Licensor for the purpose of discussing and improving the Work, but | |
| 60 | + excluding communication that is conspicuously marked or otherwise | |
| 61 | + designated in writing by the copyright owner as "Not a Contribution." | |
| 62 | + | |
| 63 | + "Contributor" shall mean Licensor and any individual or Legal Entity | |
| 64 | + on behalf of whom a Contribution has been received by Licensor and | |
| 65 | + subsequently incorporated within the Work. | |
| 66 | + | |
| 67 | + 2. Grant of Copyright License. Subject to the terms and conditions of | |
| 68 | + this License, each Contributor hereby grants to You a perpetual, | |
| 69 | + worldwide, non-exclusive, no-charge, royalty-free, irrevocable | |
| 70 | + copyright license to reproduce, prepare Derivative Works of, | |
| 71 | + publicly display, publicly perform, sublicense, and distribute the | |
| 72 | + Work and such Derivative Works in Source or Object form. | |
| 73 | + | |
| 74 | + 3. Grant of Patent License. Subject to the terms and conditions of | |
| 75 | + this License, each Contributor hereby grants to You a perpetual, | |
| 76 | + worldwide, non-exclusive, no-charge, royalty-free, irrevocable | |
| 77 | + (except as stated in this section) patent license to make, have made, | |
| 78 | + use, offer to sell, sell, import, and otherwise transfer the Work, | |
| 79 | + where such license applies only to those patent claims licensable | |
| 80 | + by such Contributor that are necessarily infringed by their | |
| 81 | + Contribution(s) alone or by combination of their Contribution(s) | |
| 82 | + with the Work to which such Contribution(s) was submitted. If You | |
| 83 | + institute patent litigation against any entity (including a | |
| 84 | + cross-claim or counterclaim in a lawsuit) alleging that the Work | |
| 85 | + or a Contribution incorporated within the Work constitutes direct | |
| 86 | + or contributory patent infringement, then any patent licenses | |
| 87 | + granted to You under this License for that Work shall terminate | |
| 88 | + as of the date such litigation is filed. | |
| 89 | + | |
| 90 | + 4. Redistribution. You may reproduce and distribute copies of the | |
| 91 | + Work or Derivative Works thereof in any medium, with or without | |
| 92 | + modifications, and in Source or Object form, provided that You | |
| 93 | + meet the following conditions: | |
| 94 | + | |
| 95 | + (a) You must give any other recipients of the Work or | |
| 96 | + Derivative Works a copy of this License; and | |
| 97 | + | |
| 98 | + (b) You must cause any modified files to carry prominent notices | |
| 99 | + stating that You changed the files; and | |
| 100 | + | |
| 101 | + (c) You must retain, in the Source form of any Derivative Works | |
| 102 | + that You distribute, all copyright, patent, trademark, and | |
| 103 | + attribution notices from the Source form of the Work, | |
| 104 | + excluding those notices that do not pertain to any part of | |
| 105 | + the Derivative Works; and | |
| 106 | + | |
| 107 | + (d) If the Work includes a "NOTICE" text file as part of its | |
| 108 | + distribution, then any Derivative Works that You distribute must | |
| 109 | + include a readable copy of the attribution notices contained | |
| 110 | + within such NOTICE file, excluding those notices that do not | |
| 111 | + pertain to any part of the Derivative Works, in at least one | |
| 112 | + of the following places: within a NOTICE text file distributed | |
| 113 | + as part of the Derivative Works; within the Source form or | |
| 114 | + documentation, if provided along with the Derivative Works; or, | |
| 115 | + within a display generated by the Derivative Works, if and | |
| 116 | + wherever such third-party notices normally appear. The contents | |
| 117 | + of the NOTICE file are for informational purposes only and | |
| 118 | + do not modify the License. You may add Your own attribution | |
| 119 | + notices within Derivative Works that You distribute, alongside | |
| 120 | + or as an addendum to the NOTICE text from the Work, provided | |
| 121 | + that such additional attribution notices cannot be construed | |
| 122 | + as modifying the License. | |
| 123 | + | |
| 124 | + You may add Your own copyright statement to Your modifications and | |
| 125 | + may provide additional or different license terms and conditions | |
| 126 | + for use, reproduction, or distribution of Your modifications, or | |
| 127 | + for any such Derivative Works as a whole, provided Your use, | |
| 128 | + reproduction, and distribution of the Work otherwise complies with | |
| 129 | + the conditions stated in this License. | |
| 130 | + | |
| 131 | + 5. Submission of Contributions. Unless You explicitly state otherwise, | |
| 132 | + any Contribution intentionally submitted for inclusion in the Work | |
| 133 | + by You to the Licensor shall be under the terms and conditions of | |
| 134 | + this License, without any additional terms or conditions. | |
| 135 | + Notwithstanding the above, nothing herein shall supersede or modify | |
| 136 | + the terms of any separate license agreement you may have executed | |
| 137 | + with Licensor regarding such Contributions. | |
| 138 | + | |
| 139 | + 6. Trademarks. This License does not grant permission to use the trade | |
| 140 | + names, trademarks, service marks, or product names of the Licensor, | |
| 141 | + except as required for reasonable and customary use in describing the | |
| 142 | + origin of the Work and reproducing the content of the NOTICE file. | |
| 143 | + | |
| 144 | + 7. Disclaimer of Warranty. Unless required by applicable law or | |
| 145 | + agreed to in writing, Licensor provides the Work (and each | |
| 146 | + Contributor provides its Contributions) on an "AS IS" BASIS, | |
| 147 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or | |
| 148 | + implied, including, without limitation, any warranties or conditions | |
| 149 | + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A | |
| 150 | + PARTICULAR PURPOSE. You are solely responsible for determining the | |
| 151 | + appropriateness of using or redistributing the Work and assume any | |
| 152 | + risks associated with Your exercise of permissions under this License. | |
| 153 | + | |
| 154 | + 8. Limitation of Liability. In no event and under no legal theory, | |
| 155 | + whether in tort (including negligence), contract, or otherwise, | |
| 156 | + unless required by applicable law (such as deliberate and grossly | |
| 157 | + negligent acts) or agreed to in writing, shall any Contributor be | |
| 158 | + liable to You for damages, including any direct, indirect, special, | |
| 159 | + incidental, or consequential damages of any character arising as a | |
| 160 | + result of this License or out of the use or inability to use the | |
| 161 | + Work (including but not limited to damages for loss of goodwill, | |
| 162 | + work stoppage, computer failure or malfunction, or any and all | |
| 163 | + other commercial damages or losses), even if such Contributor | |
| 164 | + has been advised of the possibility of such damages. | |
| 165 | + | |
| 166 | + 9. Accepting Warranty or Additional Liability. While redistributing | |
| 167 | + the Work or Derivative Works thereof, You may choose to offer, | |
| 168 | + and charge a fee for, acceptance of support, warranty, indemnity, | |
| 169 | + or other liability obligations and/or rights consistent with this | |
| 170 | + License. However, in accepting such obligations, You may act only | |
| 171 | + on Your own behalf and on Your sole responsibility, not on behalf | |
| 172 | + of any other Contributor, and only if You agree to indemnify, | |
| 173 | + defend, and hold each Contributor harmless for any liability | |
| 174 | + incurred by, or claims asserted against, such Contributor by reason | |
| 175 | + of your accepting any such warranty or additional liability. | |
| 176 | + | |
| 177 | + END OF TERMS AND CONDITIONS | |
| 178 | + | |
| 179 | + APPENDIX: How to apply the Apache License to your work. | |
| 180 | + | |
| 181 | + To apply the Apache License to your work, attach the following | |
| 182 | + boilerplate notice, with the fields enclosed by brackets "[]" | |
| 183 | + replaced with your own identifying information. (Don't include | |
| 184 | + the brackets!) The text should be enclosed in the appropriate | |
| 185 | + comment syntax for the file format. We also recommend that a | |
| 186 | + file or class name and description of purpose be included on the | |
| 187 | + same "printed page" as the copyright notice for easier | |
| 188 | + identification within third-party archives. | |
| 189 | + | |
| 190 | + Copyright [yyyy] [name of copyright owner] | |
| 191 | + | |
| 192 | + Licensed under the Apache License, Version 2.0 (the "License"); | |
| 193 | + you may not use this file except in compliance with the License. | |
| 194 | + You may obtain a copy of the License at | |
| 195 | + | |
| 196 | + http://www.apache.org/licenses/LICENSE-2.0 | |
| 197 | + | |
| 198 | + Unless required by applicable law or agreed to in writing, software | |
| 199 | + distributed under the License is distributed on an "AS IS" BASIS, | |
| 200 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 201 | + See the License for the specific language governing permissions and | |
| 202 | + limitations under the License. |
added NOTICE +11 −0
| @@ -0,0 +1,11 @@ | ||
| 1 | +Elffuss Engine | |
| 2 | +Copyright (c) 2026 UtopiaIA | |
| 3 | + | |
| 4 | +This product is licensed under the Apache License, Version 2.0; see LICENSE. | |
| 5 | + | |
| 6 | +js/quant-tables.js contains grid tables (iq1s_grid, iq2xxs_grid) copied from | |
| 7 | +llama.cpp, ggml/src/ggml-common.h: | |
| 8 | + | |
| 9 | + Copyright (c) 2023-2026 The ggml authors | |
| 10 | + Licensed under the MIT License. The complete licence text is reproduced at | |
| 11 | + the top of js/quant-tables.js. |
added README.md +139 −0
| @@ -0,0 +1,139 @@ | ||
| 1 | +<div align="center"> | |
| 2 | + | |
| 3 | +<img src="assets/logo.svg" alt="" width="72"> | |
| 4 | + | |
| 5 | +# Elffuss Engine | |
| 6 | + | |
| 7 | +**A modular WebGPU runtime for GGUF language models: a GGUF reader, a tokenizer and a sampler in plain ES modules, behind a small chat API. No dependencies, no build step.** | |
| 8 | + | |
| 9 | +[](#licence) | |
| 10 | +[](#layout) | |
| 11 | +[](#what-it-runs) | |
| 12 | + | |
| 13 | +[Elffuss](https://elffuss.com) | |
| 14 | + | |
| 15 | +</div> | |
| 16 | + | |
| 17 | +> **Provisional.** This is version 0.0.0, a snapshot of the engine published before its first release. The API below | |
| 18 | +> works and will change: read the [limits of this version](#limits-of-this-version) and the | |
| 19 | +> [changelog](CHANGELOG.md) before you depend on it. | |
| 20 | + | |
| 21 | +**In this README:** [quick start](#quick-start) · [what it runs](#what-it-runs) · [limits of this version](#limits-of-this-version) · [layout](#layout) · [how it is checked](#how-it-is-checked) · [licence](#licence) | |
| 22 | + | |
| 23 | +## Quick start | |
| 24 | + | |
| 25 | +Inference runs in the page, on WebGPU, and the weights are read from Hugging Face with HTTP range requests. The page | |
| 26 | +needs a secure context (`https://`, or `http://localhost` and `http://127.0.0.1`) and a WebGPU adapter that offers the | |
| 27 | +`shader-f16` feature and a storage-buffer binding limit large enough for the model's largest tensor (see the | |
| 28 | +[limits of this version](#limits-of-this-version)). Serve this repository with any static file server and open a page | |
| 29 | +like this one from it. | |
| 30 | + | |
| 31 | +```html | |
| 32 | +<!doctype html> | |
| 33 | +<meta charset="utf-8"> | |
| 34 | +<pre id="out"></pre> | |
| 35 | +<script type="module"> | |
| 36 | + import * as engine from './js/provider.js'; | |
| 37 | + | |
| 38 | + console.log(engine.models()); // [{ id, label }, …] | |
| 39 | + engine.configure('qwen35-0.8b'); // the small model from Hugging Face (already the default) | |
| 40 | + await engine.load((status) => console.log(status)); | |
| 41 | + | |
| 42 | + engine.setSampling({ temperature: 0.7, seed: 1, maxTokens: 120 }); | |
| 43 | + const out = document.getElementById('out'); | |
| 44 | + const reply = await engine.chat( | |
| 45 | + [{ role: 'user', content: 'Write one short sentence about the sea.' }], | |
| 46 | + 'You are a concise assistant.', | |
| 47 | + (piece) => { out.textContent += piece; }, | |
| 48 | + ); | |
| 49 | + console.log(reply); | |
| 50 | + | |
| 51 | + await engine.unload(); | |
| 52 | +</script> | |
| 53 | +``` | |
| 54 | + | |
| 55 | +This exact page is the one we ran, in headless Chrome, against this tree served from `http://127.0.0.1`. | |
| 56 | + | |
| 57 | +- `models()` lists the registry: an `id` and a `label` per model. | |
| 58 | +- `configure(id)` selects a model. It returns `true` when the selection changes, and `false` otherwise, also for an | |
| 59 | + `id` that does not exist. | |
| 60 | +- `load(onProgress)` downloads and prepares the selected model; `onProgress` receives status text. | |
| 61 | +- `setSampling({ temperature, seed, p, k, minP, presence, repeatPenalty, maxTokens, razonar })` merges into the | |
| 62 | + current sampling settings, where `p` is top-p and `k` is top-k; other keys, `topP` and `topK` among them, are | |
| 63 | + ignored in this version. For a model that reasons, `razonar: true` or `false` forces reasoning on or off, and | |
| 64 | + `null` leaves it to the registry. `setSampling(null)` goes back to the model's defaults. | |
| 65 | +- `chat(history, system, onToken, options)` runs one turn. `history` is an array of `{ role, content }`, and any | |
| 66 | + role other than `assistant` is read as `user`; `system` is the system prompt; `onToken` receives each piece of | |
| 67 | + text as it is generated; the promise resolves to the reply. | |
| 68 | +- To stop a turn, pass `{ signal }` as `options` (a bare `AbortSignal` or an `AbortController` works too), or call | |
| 69 | + `abort()`, which stops the turn in progress and the ones waiting behind it. A stopped turn rejects with an error | |
| 70 | + whose `name` is `AbortError`; its `partial` holds the text emitted until then, and `porDescarga` is `true` when | |
| 71 | + `unload()` or a `configure()` to another model stopped it. | |
| 72 | +- `unload()` releases the model and the WebGPU device. | |
| 73 | + | |
| 74 | +## What it runs | |
| 75 | + | |
| 76 | +- The model of the quick start: Qwen3.5 0.8B in `Q8_0`, from | |
| 77 | + [`ggml-org/Qwen3.5-0.8B-GGUF`](https://huggingface.co/ggml-org/Qwen3.5-0.8B-GGUF) on Hugging Face, Apache-2.0 as its | |
| 78 | + GGUF header declares. Its architecture is `qwen35`, a hybrid of state-space and attention layers. | |
| 79 | +- `models()` also lists two larger models that are hosted for the Elffuss apps. They are not meant to be loaded from | |
| 80 | + other sites. | |
| 81 | +- Weight types the engine reads: `F32`, `F16`, `BF16`, `Q8_0`, `Q2_K`, `Q4_K`, `Q5_K`, `Q6_K`, `IQ1_S`, `IQ2_XXS`, | |
| 82 | + and two third-party ternary formats, `PQ2_0` and `PTQ1_0`. | |
| 83 | + | |
| 84 | +Other GGUF files may fail to load, or load and answer worse without an error: the engine has two architecture | |
| 85 | +profiles (`qwen35` and `llama`), reads only the `gpt2` tokenizer family, and always writes a ChatML prompt instead of | |
| 86 | +reading the chat template of the file. | |
| 87 | + | |
| 88 | +## Limits of this version | |
| 89 | + | |
| 90 | +- **WebGPU features.** The attention cache is stored in half precision, so the engine needs the `shader-f16` feature: | |
| 91 | + without it, `load()` finishes and the first `chat()` fails when it compiles its shaders. It also refuses a model | |
| 92 | + that has a tensor larger than the adapter's `maxStorageBufferBindingSize`, a limit it asks the adapter for. | |
| 93 | +- **No cache of its own.** Inside the Elffuss sites the host app keeps the model in the browser. Anywhere else, every | |
| 94 | + `load()` reads the model from the network again. Even so, `load()` first checks the browser's storage estimate as if | |
| 95 | + it were going to keep the model, and refuses with a message about disk space when the estimate is too small. | |
| 96 | +- **Host files.** `load()` and `chat()` look for optional files of the host app, described under Bundlers below. | |
| 97 | + Outside the Elffuss sites they answer 404, which the browser console shows, and the engine carries on without them | |
| 98 | + (for the missing store it also logs a warning). | |
| 99 | +- **History.** Outside the Elffuss apps the engine keeps the last 12 messages of `history`, then fits them to the | |
| 100 | + context. | |
| 101 | +- **One model per page.** The module holds a single engine; selecting another model unloads the current one. | |
| 102 | +- **Spanish messages.** Progress and error texts are in Spanish, and the console gets a few lines per turn. | |
| 103 | +- **Reasoning is streamed too.** With a model that reasons, `onToken` also receives the reasoning; the resolved reply | |
| 104 | + does not include it. | |
| 105 | +- **Bundlers.** The engine looks for three optional files of the host app (`../runtime/model-store.js`, | |
| 106 | + `../runtime/model-broker.js` and `../context.js`) with literal relative imports, and carries on without them. A | |
| 107 | + bundler may try to resolve those paths when it builds; serve the modules as they are. | |
| 108 | + | |
| 109 | +## Layout | |
| 110 | + | |
| 111 | +``` | |
| 112 | +js/ the runtime: 19 ES modules, served as they are written | |
| 113 | + provider.js the chat API of the quick start | |
| 114 | + registro.js the model registry; it imports nothing, so a page can list models without the engine | |
| 115 | + gguf.js the GGUF reader, which reads by byte ranges | |
| 116 | + tokenizer.js the tokenizer | |
| 117 | + sample.js the sampler | |
| 118 | + model.js a model session on WebGPU | |
| 119 | + device.js the WebGPU device | |
| 120 | + the rest the shaders (kernels.*.wgsl.js) and what runs them (ops.js, state.js, hadamard.js, | |
| 121 | + quant-tables.js) | |
| 122 | +assets/ the logo | |
| 123 | +``` | |
| 124 | + | |
| 125 | +This repository receives curated snapshots of the engine. Development happens elsewhere, so the history here moves in | |
| 126 | +snapshots. | |
| 127 | + | |
| 128 | +## How it is checked | |
| 129 | + | |
| 130 | +We check it internally against llama.cpp: the GGUF reader against llama.cpp's reader, the tokenizer token by token | |
| 131 | +against `llama-tokenize`, the weight types against llama.cpp's decoder (the two ternary formats, which llama.cpp | |
| 132 | +does not have, against their published definition), and forward passes, layer by layer, against llama.cpp's | |
| 133 | +activations for the model formats that llama.cpp reads. The ternary model is checked piece by piece and end to end. | |
| 134 | +Those tests and their reference data are not part of this repository. | |
| 135 | + | |
| 136 | +## Licence | |
| 137 | + | |
| 138 | +Apache-2.0, see [LICENSE](LICENSE). `js/quant-tables.js` carries grid tables copied from llama.cpp under the MIT licence | |
| 139 | +of the ggml authors, reproduced in full at the top of that file; see [NOTICE](NOTICE). |
added assets/logo.svg +1 −0
| @@ -0,0 +1,1 @@ | ||
| 1 | +<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><path fill-rule="evenodd" fill="#191b1e" d="M3 16 10.6 6.5H27.5A2 2 0 0 1 29.5 8.5V23.5A2 2 0 0 1 27.5 25.5H10.6ZM14.2 16a2.7 2.7 0 1 1-5.4 0 2.7 2.7 0 0 1 5.4 0Z"/></svg> |
added js/device.js +225 −0
| @@ -0,0 +1,225 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · creación del GPUDevice y utillaje que hace visibles los fallos. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// En WebGPU casi nada lanza. Un buffer inválido, un binding mal alineado o una | |
| 6 | +// lectura fuera de rango no dan excepción: dan CEROS. Un motor de inferencia | |
| 7 | +// construido sobre eso genera texto plausible y basura numérica sin un solo | |
| 8 | +// error en consola. Este módulo existe para que eso no pase: | |
| 9 | +// · pide los límites de verdad (ver la trampa de abajo, es gorda), | |
| 10 | +// · comprueba que el device no nace ya perdido, | |
| 11 | +// · envuelve cualquier operación en scopes de error, | |
| 12 | +// · y ofrece el round-trip de lectura, que es el único canario fiable. | |
| 13 | +// | |
| 14 | +// TRAMPA MAYOR — `requestDevice({ requiredLimits: adapter.limits })` NO falla: | |
| 15 | +// GPUSupportedLimits expone sus límites como accessors del PROTOTIPO, y la | |
| 16 | +// conversión a `record<K,V>` de WebIDL solo mira propiedades PROPIAS. Así que | |
| 17 | +// `{...adapter.limits}` es `{}` y te devuelve un device con los límites POR | |
| 18 | +// DEFECTO (buffer 256 MiB, binding 128 MiB) sin decir nada. Hay que recorrerlo | |
| 19 | +// con for..in, que sí pasa por el prototipo. (gpuweb/gpuweb#4277) | |
| 20 | +// | |
| 21 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 22 | + | |
| 23 | +// Los dos únicos límites de clase «alignment», donde MEJOR es MENOR y el valor | |
| 24 | +// debe ser potencia de dos. El resto son de clase «maximum» (mejor = mayor). | |
| 25 | +// Pedir algo peor que el defecto no da error: se clampa en silencio. | |
| 26 | +const ALIGNMENT_LIMITS = new Set([ | |
| 27 | + 'minUniformBufferOffsetAlignment', | |
| 28 | + 'minStorageBufferOffsetAlignment', | |
| 29 | +]); | |
| 30 | + | |
| 31 | +// Los límites que de verdad deciden si un modelo cabe y cómo hay que trocearlo. | |
| 32 | +// Se usan como conjunto de reintento si pedirlo todo falla en algún navegador. | |
| 33 | +const CORE_LIMITS = new Set([ | |
| 34 | + 'maxBufferSize', | |
| 35 | + 'maxStorageBufferBindingSize', | |
| 36 | + 'maxStorageBuffersPerShaderStage', | |
| 37 | + 'maxBindGroups', | |
| 38 | + 'minStorageBufferOffsetAlignment', | |
| 39 | + 'maxComputeInvocationsPerWorkgroup', | |
| 40 | + 'maxComputeWorkgroupSizeX', | |
| 41 | + 'maxComputeWorkgroupSizeY', | |
| 42 | + 'maxComputeWorkgroupStorageSize', | |
| 43 | + 'maxComputeWorkgroupsPerDimension', | |
| 44 | +]); | |
| 45 | + | |
| 46 | +// Copia los límites del adaptador a un objeto JS plano. for..in y no Object.keys | |
| 47 | +// ni spread: ver la trampa de la cabecera. Como solo copiamos valores que el | |
| 48 | +// propio adaptador reporta, por construcción nunca pedimos nada «mejor» que él. | |
| 49 | +export function maxOutLimits(adapter, only = null) { | |
| 50 | + const out = {}; | |
| 51 | + for (const key in adapter.limits) { | |
| 52 | + if (only && !only.has(key)) continue; | |
| 53 | + const v = adapter.limits[key]; | |
| 54 | + if (typeof v !== 'number' || !Number.isFinite(v)) continue; | |
| 55 | + // Un límite de alineación que no sea potencia de dos es inválido y tumbaría | |
| 56 | + // la petición entera; se salta en vez de arrastrarlo. | |
| 57 | + if (ALIGNMENT_LIMITS.has(key) && (v <= 0 || !Number.isInteger(Math.log2(v)))) continue; | |
| 58 | + out[key] = v; | |
| 59 | + } | |
| 60 | + return out; | |
| 61 | +} | |
| 62 | + | |
| 63 | +// Crea el device con todo lo que el adaptador dé. Devuelve también si hay f16 y | |
| 64 | +// la información del adaptador, que es lo que permite detectar un adaptador de | |
| 65 | +// software haciéndose pasar por uno de verdad. | |
| 66 | +export async function requestDevice(opts = {}) { | |
| 67 | + if (!globalThis.navigator?.gpu) { | |
| 68 | + // Sin secure context (http:// que no sea localhost, o about:blank) el | |
| 69 | + // navegador ni siquiera define navigator.gpu, y parece un fallo del dispositivo. | |
| 70 | + throw new Error('sin WebGPU: ¿contexto seguro? (https o 127.0.0.1)'); | |
| 71 | + } | |
| 72 | + const adapter = await navigator.gpu.requestAdapter({ | |
| 73 | + powerPreference: opts.powerPreference || 'high-performance', | |
| 74 | + }); | |
| 75 | + if (!adapter) throw new Error('no hay adaptador WebGPU'); | |
| 76 | + | |
| 77 | + const wantF16 = adapter.features.has('shader-f16') && opts.f16 !== false; | |
| 78 | + const wantSG = adapter.features.has('subgroups') && opts.subgroups !== false; | |
| 79 | + // timestamp-query solo se pide si el llamador lo quiere (perfilado); no lo usa | |
| 80 | + // producción, así que por defecto no se activa. | |
| 81 | + const wantTS = adapter.features.has('timestamp-query') && opts.timestamp === true; | |
| 82 | + const required = [...(wantF16 ? ['shader-f16'] : []), ...(wantSG ? ['subgroups'] : []), | |
| 83 | + ...(wantTS ? ['timestamp-query'] : [])]; | |
| 84 | + // Tamaño de subgrupo SOLO si es fijo (min==max): con un tamaño fijo un | |
| 85 | + // workgroup de ese ancho es EXACTAMENTE un subgrupo y `subgroupAdd` da la | |
| 86 | + // reducción entera sin barreras. Si varía, no se asume nada (queda en 0 = off). | |
| 87 | + const sgSize = wantSG && adapter.info && adapter.info.subgroupMinSize === adapter.info.subgroupMaxSize | |
| 88 | + ? (adapter.info.subgroupMinSize || 0) : 0; | |
| 89 | + | |
| 90 | + let device; | |
| 91 | + try { | |
| 92 | + device = await adapter.requestDevice({ | |
| 93 | + label: opts.label || 'elffuss-engine', | |
| 94 | + requiredFeatures: required, | |
| 95 | + requiredLimits: maxOutLimits(adapter), | |
| 96 | + }); | |
| 97 | + } catch (e) { | |
| 98 | + // requestDevice es de UN SOLO USO: tras fallar hay que pedir OTRO adaptador. | |
| 99 | + // El reintento se queda en el núcleo de límites, por si el navegador reporta | |
| 100 | + // alguno inconsistente consigo mismo. | |
| 101 | + const a2 = await navigator.gpu.requestAdapter({ powerPreference: 'high-performance' }); | |
| 102 | + if (!a2) throw e; | |
| 103 | + device = await a2.requestDevice({ | |
| 104 | + label: (opts.label || 'elffuss-engine') + ' (reintento)', | |
| 105 | + requiredFeatures: a2.features.has('shader-f16') && opts.f16 !== false ? ['shader-f16'] : [], | |
| 106 | + requiredLimits: maxOutLimits(a2, CORE_LIMITS), | |
| 107 | + }); | |
| 108 | + } | |
| 109 | + | |
| 110 | + // requestDevice puede RESOLVER con un device ya perdido en vez de rechazar | |
| 111 | + // (la spec lo dice literalmente). Sin esta carrera, el primer síntoma sería | |
| 112 | + // un mapAsync que se cuelga treinta llamadas más tarde. | |
| 113 | + const lost = device.lost.then(i => i); | |
| 114 | + const race = await Promise.race([lost, Promise.resolve(ALIVE)]); | |
| 115 | + if (race !== ALIVE) throw new Error('el device nació perdido: ' + race.reason + ' ' + race.message); | |
| 116 | + | |
| 117 | + // Red de seguridad. La spec NO garantiza que dispare y permite limitarlo, así | |
| 118 | + // que no sirve para controlar nada — pero registrar el listener puede silenciar | |
| 119 | + // el aviso de consola, así que si se registra hay que re-emitirlo. | |
| 120 | + device.addEventListener?.('uncapturederror', (ev) => { | |
| 121 | + console.error('[gpu] error no capturado:', ev.error?.constructor?.name, ev.error?.message); | |
| 122 | + }); | |
| 123 | + | |
| 124 | + return { | |
| 125 | + device, | |
| 126 | + adapter, | |
| 127 | + info: adapter.info || null, | |
| 128 | + // Lo que te DIERON, nunca lo que pediste. | |
| 129 | + hasF16: device.features.has('shader-f16'), | |
| 130 | + // 32 en muchos adaptadores. 0 si no hay subgrupos o el tamaño no es fijo → el motor cae | |
| 131 | + // a la reducción en árbol de siempre. | |
| 132 | + subgroupSize: device.features.has('subgroups') ? sgSize : 0, | |
| 133 | + hasTimestamp: device.features.has('timestamp-query'), | |
| 134 | + limits: device.limits, | |
| 135 | + }; | |
| 136 | +} | |
| 137 | + | |
| 138 | +const ALIVE = Symbol('alive'); | |
| 139 | + | |
| 140 | +// Envuelve una operación en los tres scopes de error. Sin esto, «me devuelve | |
| 141 | +// ceros» nunca se convierte en «createBindGroup falló porque el offset no es | |
| 142 | +// múltiplo de 256», que es la misma información con veinte veces más valor. | |
| 143 | +export async function guard(device, label, fn) { | |
| 144 | + device.pushErrorScope('validation'); | |
| 145 | + device.pushErrorScope('out-of-memory'); | |
| 146 | + device.pushErrorScope('internal'); | |
| 147 | + let out, thrown = null; | |
| 148 | + try { out = await fn(); } catch (e) { thrown = e; } | |
| 149 | + // LIFO, y con await individual: la spec no garantiza el orden de resolución. | |
| 150 | + const internal = await device.popErrorScope(); | |
| 151 | + const oom = await device.popErrorScope(); | |
| 152 | + const validation = await device.popErrorScope(); | |
| 153 | + if (thrown) throw thrown; | |
| 154 | + const first = validation || oom || internal; | |
| 155 | + if (first) { | |
| 156 | + // El tipo es estable, el mensaje es localizable: se reportan los dos. | |
| 157 | + throw new Error(`[${label}] ${first.constructor.name}: ${first.message}`); | |
| 158 | + } | |
| 159 | + return out; | |
| 160 | +} | |
| 161 | + | |
| 162 | +// Lee un rango de un buffer de vuelta a CPU. Es el único canario fiable: en un | |
| 163 | +// device perdido, mapAsync es la ÚNICA operación que falla de forma observable | |
| 164 | +// (el resto «aparenta funcionar»). | |
| 165 | +export async function readback(device, src, offset = 0, size = src.size - offset) { | |
| 166 | + if (offset % 8) throw new Error('readback: el offset debe ser múltiplo de 8 (mapAsync)'); | |
| 167 | + if (size % 4) throw new Error('readback: el tamaño debe ser múltiplo de 4'); | |
| 168 | + | |
| 169 | + // MAP_READ solo puede combinarse con COPY_DST. Añadir STORAGE o COPY_SRC deja | |
| 170 | + // el buffer inválido — y devolviendo ceros, cómo no. | |
| 171 | + const staging = device.createBuffer({ | |
| 172 | + label: 'readback', | |
| 173 | + size, | |
| 174 | + usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, | |
| 175 | + }); | |
| 176 | + try { | |
| 177 | + await guard(device, 'readback/copy', async () => { | |
| 178 | + const enc = device.createCommandEncoder({ label: 'readback' }); | |
| 179 | + enc.copyBufferToBuffer(src, offset, staging, 0, size); | |
| 180 | + device.queue.submit([enc.finish()]); | |
| 181 | + }); | |
| 182 | + await staging.mapAsync(GPUMapMode.READ, 0, size); | |
| 183 | + const mapped = staging.getMappedRange(0, size); | |
| 184 | + // Copiar ANTES de unmap: unmap desacopla el ArrayBuffer (byteLength 0) y | |
| 185 | + // cualquier vista que hubieras hecho sobre él se queda a cero. Ese es el | |
| 186 | + // origen del clásico «me sale todo ceros» que no es del dispositivo. | |
| 187 | + const copy = mapped.slice(0); | |
| 188 | + staging.unmap(); | |
| 189 | + return copy; | |
| 190 | + } finally { | |
| 191 | + staging.destroy(); | |
| 192 | + } | |
| 193 | +} | |
| 194 | + | |
| 195 | +// Preludio del WGSL. Con la extensión se puede ALMACENAR en f16 (que es lo que | |
| 196 | +// de verdad compra: la mitad de presión en memoria compartida, que es el recurso | |
| 197 | +// que limita el tamaño de tile del matmul). Sin ella se degrada el rendimiento, | |
| 198 | +// no se deja de arrancar. Convertir la escala f16→f32 NO necesita la extensión: | |
| 199 | +// unpack2x16float es del núcleo de WGSL. | |
| 200 | +export function wgslPrelude(hasF16) { | |
| 201 | + return hasF16 | |
| 202 | + ? 'enable f16;\nalias half = f16;\nalias half4 = vec4<f16>;\n' | |
| 203 | + : 'alias half = f32;\nalias half4 = vec4<f32>;\n'; | |
| 204 | +} | |
| 205 | + | |
| 206 | +// ¿El adaptador es de verdad o es software haciéndose pasar por uno? | |
| 207 | +// Según cómo se arranque Chromium, `requestAdapter()` puede devolver un | |
| 208 | +// adaptador SwiftShader —software puro— que funciona y miente en cada medición. | |
| 209 | +export function isSoftwareAdapter(info) { | |
| 210 | + const s = ((info?.vendor || '') + ' ' + (info?.architecture || '') + ' ' + | |
| 211 | + (info?.description || '')).toLowerCase(); | |
| 212 | + return /swiftshader|llvmpipe|lavapipe|software|warp|basic render/.test(s); | |
| 213 | +} | |
| 214 | + | |
| 215 | +const GiB = 1024 ** 3, MiB = 1024 ** 2; | |
| 216 | + | |
| 217 | +// Resumen de una línea para diagnóstico, sin datos del usuario. | |
| 218 | +export function summarize({ info, hasF16, limits }) { | |
| 219 | + const gpu = info ? `${info.vendor || '?'}/${info.architecture || '?'}` : 'adaptador anónimo'; | |
| 220 | + return `${gpu} · buffer≤${(limits.maxBufferSize / GiB).toFixed(1)}GiB` + | |
| 221 | + ` · binding≤${(limits.maxStorageBufferBindingSize / MiB) | 0}MiB` + | |
| 222 | + ` · ${limits.maxStorageBuffersPerShaderStage} storage/stage` + | |
| 223 | + ` · align ${limits.minStorageBufferOffsetAlignment}` + | |
| 224 | + ` · f16 ${hasF16 ? 'sí' : 'no'}`; | |
| 225 | +} |
added js/gguf.js +466 −0
| @@ -0,0 +1,466 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · parser de la cabecera GGUF (metadatos + tabla de tensores). | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// Primer módulo del MOTOR: sin esto no sabemos qué hay dentro de un modelo ni | |
| 6 | +// en qué byte empieza cada tensor. Lee por RANGOS con el handle que devuelve | |
| 7 | +// openRanged() de model-store.js ({size, slice(offset,length)}), NUNCA el | |
| 8 | +// fichero entero: un GGUF de 7B ya ocupa gigas y volcarlo a un ArrayBuffer mata | |
| 9 | +// la pestaña — que es justo el problema que nos saca de la dependencia actual. | |
| 10 | +// | |
| 11 | +// La zona de metadatos (cabecera + pares clave/valor + tabla de tensores) ocupa | |
| 12 | +// de unos KB a unos MB, dominada por el vocabulario del tokenizer. Se lee con | |
| 13 | +// una ventana que arranca en 1 MiB y DOBLA cuando el cursor se sale: un modelo | |
| 14 | +// entero se parsea leyendo una fracción pequeña del fichero, no el fichero. | |
| 15 | +// | |
| 16 | +// Paridad con llama.cpp (ggml/src/gguf.cpp): se replican sus validaciones para | |
| 17 | +// rechazar exactamente los mismos ficheros. Un parser permisivo no te avisa de | |
| 18 | +// que el fichero está roto, te da tensores en offsets absurdos y lo descubres | |
| 19 | +// tres capas más arriba con basura en la salida. | |
| 20 | +// | |
| 21 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 22 | + | |
| 23 | +const MAGIC = [0x47, 0x47, 0x55, 0x46]; // 'G','G','U','F' en disco | |
| 24 | +const VERSION_MAX = 3; // v1 rechazada, no hay ruta | |
| 25 | +const DEFAULT_ALIGNMENT = 32; // GGUF_DEFAULT_ALIGNMENT | |
| 26 | +const MAX_STRING_LENGTH = 1024 ** 3; // GGUF_MAX_STRING_LENGTH | |
| 27 | +const MAX_ARRAY_ELEMENTS = 1024 ** 3; // GGUF_MAX_ARRAY_ELEMENTS | |
| 28 | +const MAX_DIMS = 4; // GGML_MAX_DIMS | |
| 29 | +const MAX_NAME = 64; // GGML_MAX_NAME (nombre ≤ 63) | |
| 30 | +const FIRST_WINDOW = 1024 ** 2; // 1 MiB de arranque | |
| 31 | +const MAX_WINDOW = 512 * 1024 ** 2; // tope del doblado a ciegas | |
| 32 | +const BOOL_ARRAY_EAGER = 65536; // por encima, se deja crudo | |
| 33 | + | |
| 34 | +// Tipos de valor de metadatos. El índice es el código en disco. | |
| 35 | +const V_UINT8 = 0, V_INT8 = 1, V_UINT16 = 2, V_INT16 = 3, V_UINT32 = 4, | |
| 36 | + V_INT32 = 5, V_FLOAT32 = 6, V_BOOL = 7, V_STRING = 8, V_ARRAY = 9, | |
| 37 | + V_UINT64 = 10, V_INT64 = 11, V_FLOAT64 = 12, V_COUNT = 13; | |
| 38 | + | |
| 39 | +const V_NAMES = ['uint8', 'int8', 'uint16', 'int16', 'uint32', 'int32', | |
| 40 | + 'float32', 'bool', 'string', 'array', 'uint64', 'int64', 'float64']; | |
| 41 | + | |
| 42 | +// Tamaño en bytes de cada tipo escalar (los variables van a 0 y se tratan | |
| 43 | +// aparte). BOOL ocupa UN byte, no cuatro: leerlo como u32 desplaza el resto del | |
| 44 | +// fichero y el parseo explota mucho más adelante, con un error incomprensible. | |
| 45 | +const V_SIZES = [1, 1, 2, 2, 4, 4, 4, 1, 0, 0, 8, 8, 8]; | |
| 46 | + | |
| 47 | +// Tabla ggml_type: [nombre, blockSize, typeSize]. Los códigos muertos (Q4_2, | |
| 48 | +// Q4_3, los *_4_4/4_8/8_8 retirados) van con blockSize 0 A PROPÓSITO: dividir | |
| 49 | +// por su block size daría Infinity/NaN y se propagaría en silencio a todos los | |
| 50 | +// offsets. Con 0 se rechazan, igual que hace llama.cpp. | |
| 51 | +const TYPES = [ | |
| 52 | + ['F32', 1, 4], ['F16', 1, 2], ['Q4_0', 32, 18], ['Q4_1', 32, 20], | |
| 53 | + ['Q4_2', 0, 0], ['Q4_3', 0, 0], ['Q5_0', 32, 22], ['Q5_1', 32, 24], | |
| 54 | + ['Q8_0', 32, 34], ['Q8_1', 32, 40], ['Q2_K', 256, 84], ['Q3_K', 256, 110], | |
| 55 | + ['Q4_K', 256, 144], ['Q5_K', 256, 176], ['Q6_K', 256, 210], | |
| 56 | + ['Q8_K', 256, 292], ['IQ2_XXS', 256, 66], ['IQ2_XS', 256, 74], | |
| 57 | + ['IQ3_XXS', 256, 98], ['IQ1_S', 256, 50], ['IQ4_NL', 32, 18], | |
| 58 | + ['IQ3_S', 256, 110], ['IQ2_S', 256, 82], ['IQ4_XS', 256, 136], | |
| 59 | + ['I8', 1, 1], ['I16', 1, 2], ['I32', 1, 4], ['I64', 1, 8], ['F64', 1, 8], | |
| 60 | + ['IQ1_M', 256, 56], ['BF16', 1, 2], ['Q4_0_4_4', 0, 0], ['Q4_0_4_8', 0, 0], | |
| 61 | + ['Q4_0_8_8', 0, 0], ['TQ1_0', 256, 54], ['TQ2_0', 256, 66], | |
| 62 | + ['IQ4_NL_4_4', 0, 0], ['IQ4_NL_4_8', 0, 0], ['IQ4_NL_8_8', 0, 0], | |
| 63 | + ['MXFP4', 32, 17], ['NVFP4', 64, 36], ['Q1_0', 128, 18], ['Q2_0', 64, 18], | |
| 64 | +]; | |
| 65 | + | |
| 66 | +// TIPOS FUERA DEL CATALOGO DE ggml. Los codigos 142/143 no son de llama.cpp: | |
| 67 | +// los define un fork de terceros para sus formatos ternarios, y por eso van | |
| 68 | +// APARTE y con su nombre completo. Ponerlos en la tabla de arriba sugeriria que | |
| 69 | +// son estandar y que cualquier GGUF con ese codigo significa esto, que es falso. | |
| 70 | +// | |
| 71 | +// PQ2_0 (142): 128 pesos, escala f16 + 2 bits por peso = 34 bytes | |
| 72 | +// PTQ1_0 (143): 128 pesos, 5 trits por byte en base 3 + escala = 28 bytes | |
| 73 | +// | |
| 74 | +// Ninguno lleva codebook: el peso sale de aritmetica, no de una tabla. Esa es | |
| 75 | +// la razon de soportarlos, no el tamaño. | |
| 76 | +TYPES[142] = ['PQ2_0', 128, 34]; | |
| 77 | +TYPES[143] = ['PTQ1_0', 128, 28]; | |
| 78 | + | |
| 79 | +const DEC = new TextDecoder('utf-8'); // fatal:false a propósito | |
| 80 | +// Los vocabularios BPE llevan tokens de bytes crudos que NO son UTF-8 válido: | |
| 81 | +// con fatal:true el decodificador LANZA al llegar a ellos y no hay modelo. | |
| 82 | + | |
| 83 | +// ¿el host es little-endian? GGUF lo es siempre en la práctica, y las vistas | |
| 84 | +// tipadas usan el orden del host: si algún día corremos en big-endian hay que | |
| 85 | +// decodificar a mano en vez de reinterpretar memoria. | |
| 86 | +const HOST_LE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; | |
| 87 | + | |
| 88 | +// GGML_PAD sin operadores bitwise. La macro original es `((x)+(n)-1) & ~((n)-1)` | |
| 89 | +// y traducirla literal es LA trampa de este formato en JavaScript: & y ~ truncan | |
| 90 | +// a 32 bits con signo → cualquier offset por encima de 2^31 bytes sale negativo, o | |
| 91 | +// sea todos los modelos de 7B en adelante. | |
| 92 | +function pad(x, n) { return x + ((n - (x % n)) % n); } | |
| 93 | + | |
| 94 | +function bad(msg) { throw new Error('GGUF: ' + msg); } | |
| 95 | + | |
| 96 | +// Descripción de un ggml_type por su código, o null si no existe. | |
| 97 | +export function ggmlType(code) { | |
| 98 | + const t = TYPES[code]; | |
| 99 | + return t ? { code, name: t[0], blockSize: t[1], typeSize: t[2] } : null; | |
| 100 | +} | |
| 101 | + | |
| 102 | +// Bytes que ocupa un tensor: (ne0/blockSize) * typeSize * ne1 * ne2 * ne3. | |
| 103 | +// El tamaño NO es nElements * typeSize: en los tipos cuantizados el «elemento» | |
| 104 | +// es un bloque de 32 o 256 pesos con sus escalas dentro. | |
| 105 | +export function tensorBytes(dims, code) { | |
| 106 | + const t = ggmlType(code); | |
| 107 | + if (!t || t.blockSize === 0) return 0; | |
| 108 | + let n = (dims[0] / t.blockSize) * t.typeSize; | |
| 109 | + for (let i = 1; i < dims.length; i++) n *= dims[i]; | |
| 110 | + return n; | |
| 111 | +} | |
| 112 | + | |
| 113 | +// Cursor de lectura sobre el handle por rangos. Mantiene una ventana que | |
| 114 | +// SIEMPRE empieza en el byte 0, así el offset del fichero y el índice del | |
| 115 | +// buffer son el mismo número: se evita de raíz toda una familia de bugs de | |
| 116 | +// «offset relativo a qué». Doblar y releer desde 0 cuesta como mucho 2× la | |
| 117 | +// ventana final, y la ventana final son megas, no gigas. | |
| 118 | +async function cursor(ranged, firstWindow) { | |
| 119 | + let bytes = new Uint8Array(0); | |
| 120 | + let view = new DataView(bytes.buffer); | |
| 121 | + let loaded = 0, reads = 0, bytesRead = 0, pos = 0; | |
| 122 | + | |
| 123 | + async function ensure(end) { | |
| 124 | + if (end <= loaded) return; | |
| 125 | + if (end > ranged.size) bad('fichero truncado: se piden ' + end + | |
| 126 | + ' bytes de un fichero de ' + ranged.size); | |
| 127 | + let want = Math.max(firstWindow, loaded * 2); | |
| 128 | + while (want < end) want *= 2; | |
| 129 | + if (want > MAX_WINDOW && end <= MAX_WINDOW) want = MAX_WINDOW; | |
| 130 | + want = Math.min(want, ranged.size); | |
| 131 | + // Se lee SOLO la cola nueva y se concatena. La ventana sigue empezando en el | |
| 132 | + // byte 0 (offset del fichero == índice del buffer), pero cada byte viaja del | |
| 133 | + // disco UNA vez: releer desde 0 en cada doblado costaba ~2,2× el fichero en | |
| 134 | + // los modelos pequeños, y eso es exactamente lo que openRanged viene a | |
| 135 | + // evitar. Copiar en memoria es un memcpy; releer es E/S. | |
| 136 | + const tail = await ranged.slice(loaded, want - loaded); | |
| 137 | + reads++; bytesRead += tail.byteLength; | |
| 138 | + const grown = new Uint8Array(want); | |
| 139 | + grown.set(bytes.subarray(0, loaded)); | |
| 140 | + grown.set(new Uint8Array(tail), loaded); | |
| 141 | + bytes = grown; | |
| 142 | + view = new DataView(grown.buffer); | |
| 143 | + loaded += tail.byteLength; // slice recorta en silencio | |
| 144 | + if (end > loaded) bad('lectura corta: ' + loaded + ' de ' + want + ' bytes'); | |
| 145 | + } | |
| 146 | + | |
| 147 | + async function take(n) { await ensure(pos + n); const at = pos; pos += n; return at; } | |
| 148 | + | |
| 149 | + // Un u64 que no cabe en un double es, en la práctica, un fichero corrupto: | |
| 150 | + // llama.cpp los mete en int64_t con signo y rechaza los negativos. | |
| 151 | + function u64at(at, what) { | |
| 152 | + const v = view.getBigUint64(at, true); | |
| 153 | + if (v > BigInt(Number.MAX_SAFE_INTEGER)) bad(what + ' fuera de rango: ' + v); | |
| 154 | + return Number(v); | |
| 155 | + } | |
| 156 | + | |
| 157 | + return { | |
| 158 | + get pos() { return pos; }, | |
| 159 | + get loaded() { return loaded; }, | |
| 160 | + get reads() { return reads; }, | |
| 161 | + get bytesRead() { return bytesRead; }, | |
| 162 | + get bytes() { return bytes; }, | |
| 163 | + get view() { return view; }, | |
| 164 | + size: ranged.size, | |
| 165 | + ensure, | |
| 166 | + skip(n) { pos += n; }, | |
| 167 | + async u8() { return view.getUint8(await take(1)); }, | |
| 168 | + async i8() { return view.getInt8(await take(1)); }, | |
| 169 | + async u16() { return view.getUint16(await take(2), true); }, | |
| 170 | + async i16() { return view.getInt16(await take(2), true); }, | |
| 171 | + async u32() { return view.getUint32(await take(4), true); }, | |
| 172 | + async i32() { return view.getInt32(await take(4), true); }, | |
| 173 | + async f32() { return view.getFloat32(await take(4), true); }, | |
| 174 | + async f64() { return view.getFloat64(await take(8), true); }, | |
| 175 | + async u64(what) { return u64at(await take(8), what); }, | |
| 176 | + async i64(what) { | |
| 177 | + const at = await take(8); | |
| 178 | + const v = view.getBigInt64(at, true); | |
| 179 | + if (v > BigInt(Number.MAX_SAFE_INTEGER) || v < -BigInt(Number.MAX_SAFE_INTEGER)) { | |
| 180 | + bad(what + ' fuera de rango: ' + v); | |
| 181 | + } | |
| 182 | + return Number(v); | |
| 183 | + }, | |
| 184 | + // Devuelve {at, len} sin decodificar: el llamador decide si materializa la | |
| 185 | + // string o solo la salta. Con 262k tokens de vocabulario esa diferencia es | |
| 186 | + // la que hay entre parsear en un suspiro y ahogar al recolector. | |
| 187 | + async str(what) { | |
| 188 | + const len = u64at(await take(8), what + ' (longitud)'); | |
| 189 | + if (len > MAX_STRING_LENGTH) bad(what + ': string de ' + len + ' bytes'); | |
| 190 | + if (len > ranged.size - pos) bad(what + ': string más larga que el fichero'); | |
| 191 | + const at = await take(len); | |
| 192 | + return { at, len }; | |
| 193 | + }, | |
| 194 | + }; | |
| 195 | +} | |
| 196 | + | |
| 197 | +function decode(bytes, at, len) { return DEC.decode(bytes.subarray(at, at + len)); } | |
| 198 | + | |
| 199 | +// Array de strings PEREZOSO: al parsear solo se guardan offset y longitud de | |
| 200 | +// cada elemento; las strings se materializan cuando alguien las pide. Un vocab | |
| 201 | +// de 262k tokens serían 262k objetos String creados de golpe para nada — el | |
| 202 | +// motor casi siempre quiere los metadatos de arquitectura, no el vocabulario. | |
| 203 | +function lazyStrings(cur, offs, lens) { | |
| 204 | + // Se consulta cur.bytes al decodificar, no al construir: la ventana crece | |
| 205 | + // durante el parseo y capturar el buffer de entonces dejaría vivo un buffer | |
| 206 | + // viejo además del definitivo. Los offsets valen igual en los dos, porque la | |
| 207 | + // ventana siempre arranca en el byte 0. | |
| 208 | + return { | |
| 209 | + ggufType: 'string[]', | |
| 210 | + length: offs.length, | |
| 211 | + at(i) { | |
| 212 | + if (!(i >= 0 && i < offs.length)) return undefined; | |
| 213 | + return decode(cur.bytes, offs[i], lens[i]); | |
| 214 | + }, | |
| 215 | + toArray() { | |
| 216 | + const out = new Array(offs.length); | |
| 217 | + for (let i = 0; i < offs.length; i++) out[i] = decode(cur.bytes, offs[i], lens[i]); | |
| 218 | + return out; | |
| 219 | + }, | |
| 220 | + }; | |
| 221 | +} | |
| 222 | + | |
| 223 | +// Copia un array de escalares a su vista tipada. Se COPIA (buf.slice) porque un | |
| 224 | +// Int32Array exige que su byteOffset sea múltiplo de 4 y en GGUF los valores no | |
| 225 | +// están alineados a nada: construirlo sobre el buffer original lanzaría. | |
| 226 | +function scalarArray(cur, type, at, n) { | |
| 227 | + const size = V_SIZES[type]; | |
| 228 | + const raw = cur.bytes.buffer.slice(at, at + n * size); | |
| 229 | + if (!HOST_LE) { // camino lento y correcto | |
| 230 | + const v = new DataView(raw); | |
| 231 | + const out = new Array(n); | |
| 232 | + for (let i = 0; i < n; i++) out[i] = readScalarView(v, type, i * size); | |
| 233 | + return out; | |
| 234 | + } | |
| 235 | + switch (type) { | |
| 236 | + case V_UINT8: return new Uint8Array(raw); | |
| 237 | + case V_INT8: return new Int8Array(raw); | |
| 238 | + case V_UINT16: return new Uint16Array(raw); | |
| 239 | + case V_INT16: return new Int16Array(raw); | |
| 240 | + case V_UINT32: return new Uint32Array(raw); | |
| 241 | + case V_INT32: return new Int32Array(raw); | |
| 242 | + case V_FLOAT32: return new Float32Array(raw); | |
| 243 | + case V_UINT64: return new BigUint64Array(raw); | |
| 244 | + case V_INT64: return new BigInt64Array(raw); | |
| 245 | + case V_FLOAT64: return new Float64Array(raw); | |
| 246 | + case V_BOOL: { | |
| 247 | + const u = new Uint8Array(raw); | |
| 248 | + // Los arrays de bool reales son de decenas de elementos (el patrón de | |
| 249 | + // ventana deslizante de Gemma, p.ej.). Si alguna vez llega uno enorme, se | |
| 250 | + // deja crudo en vez de inflar un Array de JS con un booleano por byte. | |
| 251 | + return n <= BOOL_ARRAY_EAGER ? Array.from(u, b => b !== 0) : u; | |
| 252 | + } | |
| 253 | + default: return bad('tipo de array no escalar: ' + type); | |
| 254 | + } | |
| 255 | +} | |
| 256 | + | |
| 257 | +function readScalarView(v, type, at) { | |
| 258 | + switch (type) { | |
| 259 | + case V_UINT8: return v.getUint8(at); | |
| 260 | + case V_INT8: return v.getInt8(at); | |
| 261 | + case V_UINT16: return v.getUint16(at, true); | |
| 262 | + case V_INT16: return v.getInt16(at, true); | |
| 263 | + case V_UINT32: return v.getUint32(at, true); | |
| 264 | + case V_INT32: return v.getInt32(at, true); | |
| 265 | + case V_FLOAT32: return v.getFloat32(at, true); | |
| 266 | + case V_BOOL: return v.getUint8(at) !== 0; | |
| 267 | + case V_UINT64: return v.getBigUint64(at, true); | |
| 268 | + case V_INT64: return v.getBigInt64(at, true); | |
| 269 | + case V_FLOAT64: return v.getFloat64(at, true); | |
| 270 | + default: return bad('tipo escalar desconocido: ' + type); | |
| 271 | + } | |
| 272 | +} | |
| 273 | + | |
| 274 | +async function readValue(cur, type, key) { | |
| 275 | + switch (type) { | |
| 276 | + case V_UINT8: return await cur.u8(); | |
| 277 | + case V_INT8: return await cur.i8(); | |
| 278 | + case V_UINT16: return await cur.u16(); | |
| 279 | + case V_INT16: return await cur.i16(); | |
| 280 | + case V_UINT32: return await cur.u32(); | |
| 281 | + case V_INT32: return await cur.i32(); | |
| 282 | + case V_FLOAT32: return await cur.f32(); | |
| 283 | + case V_FLOAT64: return await cur.f64(); | |
| 284 | + case V_UINT64: return await cur.u64('«' + key + '»'); | |
| 285 | + case V_INT64: return await cur.i64('«' + key + '»'); | |
| 286 | + case V_BOOL: return (await cur.u8()) !== 0; | |
| 287 | + case V_STRING: { const s = await cur.str('«' + key + '»'); return decode(cur.bytes, s.at, s.len); } | |
| 288 | + case V_ARRAY: return await readArray(cur, key); | |
| 289 | + default: return bad('«' + key + '» tiene un tipo inválido: ' + type); | |
| 290 | + } | |
| 291 | +} | |
| 292 | + | |
| 293 | +async function readArray(cur, key) { | |
| 294 | + const sub = await cur.i32(); | |
| 295 | + if (sub === V_ARRAY) bad('«' + key + '»: arrays anidados no permitidos'); | |
| 296 | + if (sub < 0 || sub >= V_COUNT) bad('«' + key + '»: subtipo inválido: ' + sub); | |
| 297 | + const n = await cur.u64('«' + key + '» (nº de elementos)'); | |
| 298 | + if (n > MAX_ARRAY_ELEMENTS) bad('«' + key + '»: array de ' + n + ' elementos'); | |
| 299 | + | |
| 300 | + if (sub === V_STRING) { | |
| 301 | + // Antes de reservar nada: cada string son 8 bytes de longitud como mínimo. | |
| 302 | + // Sin este chequeo, un n falseado nos hace pedir gigas de índice. | |
| 303 | + if (n * 8 > cur.size - cur.pos) bad('«' + key + '»: array de strings mayor que el fichero'); | |
| 304 | + const offs = new Float64Array(n); // los offsets pasan de 2^32 | |
| 305 | + const lens = new Uint32Array(n); // ≤ 1 GiB por string | |
| 306 | + for (let i = 0; i < n; i++) { | |
| 307 | + const s = await cur.str('«' + key + '»[' + i + ']'); | |
| 308 | + offs[i] = s.at; lens[i] = s.len; | |
| 309 | + } | |
| 310 | + return lazyStrings(cur, offs, lens); | |
| 311 | + } | |
| 312 | + | |
| 313 | + const size = V_SIZES[sub]; | |
| 314 | + if (n * size > cur.size - cur.pos) bad('«' + key + '»: array mayor que el fichero'); | |
| 315 | + await cur.ensure(cur.pos + n * size); | |
| 316 | + const at = cur.pos; | |
| 317 | + cur.skip(n * size); | |
| 318 | + return scalarArray(cur, sub, at, n); | |
| 319 | +} | |
| 320 | + | |
| 321 | +// Parsea la zona de metadatos de un GGUF desde un handle por rangos | |
| 322 | +// ({size, slice(offset,length)→ArrayBuffer}). No toca los datos de los tensores: | |
| 323 | +// devuelve dónde está cada uno para que el loader los suba al dispositivo por shards. | |
| 324 | +export async function parseGGUF(ranged, opts = {}) { | |
| 325 | + if (!ranged || typeof ranged.slice !== 'function') bad('handle por rangos inválido'); | |
| 326 | + const cur = await cursor(ranged, opts.firstWindow || FIRST_WINDOW); | |
| 327 | + await cur.ensure(Math.min(24, ranged.size)); | |
| 328 | + | |
| 329 | + for (let i = 0; i < 4; i++) { | |
| 330 | + if (cur.bytes[i] !== MAGIC[i]) bad('no es un fichero GGUF (magic incorrecto)'); | |
| 331 | + } | |
| 332 | + cur.skip(4); | |
| 333 | + | |
| 334 | + const version = await cur.u32(); | |
| 335 | + // Un fichero escrito en el endianness contrario (s390x) da 0x03000000: el | |
| 336 | + // truco es que los 16 bits bajos quedan a cero. Sin esto, el error que ve el | |
| 337 | + // usuario es «versión 50331648» y nadie sabe qué hacer con eso. | |
| 338 | + if (version !== 0 && version % 65536 === 0) { | |
| 339 | + bad('fichero big-endian (versión ' + version + '): no soportado'); | |
| 340 | + } | |
| 341 | + if (version === 0 || version > VERSION_MAX) bad('versión no soportada: ' + version); | |
| 342 | + if (version === 1) bad('GGUFv1 no soportada: reconvierte el modelo'); | |
| 343 | + | |
| 344 | + // En la CABECERA el nº de tensores va ANTES que el de claves, pero en el | |
| 345 | + // CUERPO los pares clave/valor van ANTES que la tabla de tensores. | |
| 346 | + const tensorCount = await cur.u64('nº de tensores'); | |
| 347 | + const kvCount = await cur.u64('nº de claves'); | |
| 348 | + | |
| 349 | + const meta = Object.create(null); | |
| 350 | + const kvTypes = Object.create(null); | |
| 351 | + for (let i = 0; i < kvCount; i++) { | |
| 352 | + const k = await cur.str('clave #' + i); | |
| 353 | + if (k.len === 0) bad('clave vacía en la posición ' + i); | |
| 354 | + const key = decode(cur.bytes, k.at, k.len); | |
| 355 | + if (key in meta) bad('clave duplicada: «' + key + '»'); | |
| 356 | + const type = await cur.i32(); | |
| 357 | + if (type < 0 || type >= V_COUNT) bad('«' + key + '» tiene un tipo inválido: ' + type); | |
| 358 | + kvTypes[key] = V_NAMES[type]; | |
| 359 | + meta[key] = await readValue(cur, type, key); | |
| 360 | + } | |
| 361 | + const kvEnd = cur.pos; | |
| 362 | + | |
| 363 | + // La alineación se resuelve aquí, entre las claves y la tabla de tensores: | |
| 364 | + // solo afecta al relleno del bloque de datos, nunca a los metadatos. | |
| 365 | + let alignment = DEFAULT_ALIGNMENT; | |
| 366 | + const alignmentKey = 'general.alignment' in meta; | |
| 367 | + if (alignmentKey) { | |
| 368 | + if (kvTypes['general.alignment'] !== 'uint32') { | |
| 369 | + bad('general.alignment debe ser uint32, es ' + kvTypes['general.alignment']); | |
| 370 | + } | |
| 371 | + alignment = meta['general.alignment']; | |
| 372 | + // Potencia de dos vía log2 y no con `x & (x-1)`: mismo criterio que | |
| 373 | + // llama.cpp (donde 1 es válida) sin meter operadores bitwise en un módulo | |
| 374 | + // que trabaja con números por encima de 2^32. | |
| 375 | + if (alignment === 0 || !Number.isInteger(Math.log2(alignment))) { | |
| 376 | + bad('alineación no es potencia de 2: ' + alignment); | |
| 377 | + } | |
| 378 | + } | |
| 379 | + | |
| 380 | + const tensors = []; | |
| 381 | + const seen = new Set(); | |
| 382 | + let expected = 0; // offset acumulado esperado | |
| 383 | + for (let i = 0; i < tensorCount; i++) { | |
| 384 | + const n = await cur.str('nombre del tensor #' + i); | |
| 385 | + if (n.len >= MAX_NAME) bad('nombre de tensor demasiado largo (' + n.len + ' bytes)'); | |
| 386 | + const name = decode(cur.bytes, n.at, n.len); | |
| 387 | + if (seen.has(name)) bad('nombre de tensor duplicado: «' + name + '»'); | |
| 388 | + seen.add(name); | |
| 389 | + | |
| 390 | + const nDims = await cur.u32(); // 4 bytes, no 8 | |
| 391 | + if (nDims > MAX_DIMS) bad('«' + name + '» tiene ' + nDims + ' dimensiones (máx ' + MAX_DIMS + ')'); | |
| 392 | + // Las dimensiones que no se escriben valen 1: el escritor solo emite hasta | |
| 393 | + // la última con ne>1, así que una norma o un bias vienen con nDims=1. | |
| 394 | + const dims = [1, 1, 1, 1]; | |
| 395 | + for (let j = 0; j < nDims; j++) { | |
| 396 | + const ne = await cur.i64('dimensión de «' + name + '»'); | |
| 397 | + if (ne < 0) bad('«' + name + '» tiene una dimensión negativa'); | |
| 398 | + dims[j] = ne; | |
| 399 | + } | |
| 400 | + const type = await cur.i32(); | |
| 401 | + const offset = await cur.u64('offset de «' + name + '»'); | |
| 402 | + | |
| 403 | + const t = ggmlType(type); | |
| 404 | + if (!t) bad('«' + name + '» usa un tipo desconocido: ' + type); | |
| 405 | + if (t.blockSize === 0) bad('«' + name + '» usa el tipo retirado ' + t.name); | |
| 406 | + if (dims[0] % t.blockSize !== 0) { | |
| 407 | + bad('«' + name + '»: ne[0]=' + dims[0] + ' no es múltiplo del bloque de ' + t.name); | |
| 408 | + } | |
| 409 | + | |
| 410 | + const nBytes = tensorBytes(dims, type); | |
| 411 | + // El offset de cada tensor tiene que ser exactamente el acumulado de los | |
| 412 | + // anteriores con su relleno. llama.cpp lo comprueba y rechaza el fichero si | |
| 413 | + // no cuadra: es el mejor checksum estructural que hay, y es gratis. | |
| 414 | + if (offset !== expected) { | |
| 415 | + bad('«' + name + '» está en el offset ' + offset + ', se esperaba ' + expected); | |
| 416 | + } | |
| 417 | + expected = pad(expected + nBytes, alignment); | |
| 418 | + | |
| 419 | + tensors.push({ | |
| 420 | + name, dims: dims.slice(0, Math.max(nDims, 1)), type, typeName: t.name, | |
| 421 | + blockSize: t.blockSize, typeSize: t.typeSize, | |
| 422 | + nElements: dims[0] * dims[1] * dims[2] * dims[3], | |
| 423 | + nBytes, offset, | |
| 424 | + }); | |
| 425 | + } | |
| 426 | + const tensorInfoEnd = cur.pos; | |
| 427 | + | |
| 428 | + // Dónde empieza el bloque de datos. llama.cpp SOLO alinea si hay al menos un | |
| 429 | + // tensor (el seek vive dentro de `if (n_tensors > 0)`); gguf-py alinea | |
| 430 | + // siempre. En un fichero de solo vocabulario los dos discrepan y el valor | |
| 431 | + // alineado se sale del final del fichero, así que se devuelven los dos. | |
| 432 | + const dataStart = tensorCount > 0 ? pad(tensorInfoEnd, alignment) : tensorInfoEnd; | |
| 433 | + const dataStartPadded = pad(tensorInfoEnd, alignment); | |
| 434 | + const dataBytes = expected; | |
| 435 | + if (dataStart + dataBytes > ranged.size) { | |
| 436 | + bad('los datos se salen del fichero: hacen falta ' + (dataStart + dataBytes) + | |
| 437 | + ' bytes y hay ' + ranged.size); | |
| 438 | + } | |
| 439 | + | |
| 440 | + for (const t of tensors) t.start = dataStart + t.offset; | |
| 441 | + | |
| 442 | + return { | |
| 443 | + version, alignment, alignmentKey, tensorCount, kvCount, | |
| 444 | + meta, kvTypes, tensors, | |
| 445 | + kvEnd, tensorInfoEnd, dataStart, dataStartPadded, dataBytes, | |
| 446 | + fileBytes: ranged.size, | |
| 447 | + reads: cur.reads, bytesRead: cur.bytesRead, | |
| 448 | + // Rango absoluto de un tensor por nombre, listo para slice() o Range HTTP. | |
| 449 | + range(name) { | |
| 450 | + const t = tensors.find(x => x.name === name); | |
| 451 | + return t ? { offset: t.start, length: t.nBytes } : null; | |
| 452 | + }, | |
| 453 | + }; | |
| 454 | +} | |
| 455 | + | |
| 456 | +// Atajo para el navegador: abre el modelo desde el almacén y parsea su cabecera. | |
| 457 | +// El almacén se INYECTA en vez de importarse: model-store.js vive en el repo | |
| 458 | +// público de Elffuss (web/js/runtime/), no aquí, y duplicar el fichero solo | |
| 459 | +// garantiza que las dos copias se separen. Quien llame pasa el suyo. | |
| 460 | +export async function openGGUF(url, store) { | |
| 461 | + if (!store?.openRanged) throw new Error('openGGUF necesita un almacén con openRanged'); | |
| 462 | + const ranged = await store.openRanged(url); | |
| 463 | + if (!ranged) return null; // sin OPFS: decide el llamador | |
| 464 | + const parsed = await parseGGUF(ranged); | |
| 465 | + return { ...parsed, ranged }; | |
| 466 | +} |
added js/hadamard.js +86 −0
| @@ -0,0 +1,86 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Rotación de Hadamard declarada por el fichero: qué tensores la llevan y cómo. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// Algunos modelos ternarios guardan los pesos en una base girada y declaran la | |
| 6 | +// rotación en sus metadatos. Un runtime que la ignore NO falla: carga, ejecuta y | |
| 7 | +// genera ruido — comprobado, produce tokens plausibles y texto sin sentido. Por | |
| 8 | +// eso esto se decide a partir de lo que dice el FICHERO y nunca se deduce: | |
| 9 | +// | |
| 10 | +// · `weight_names` enumera, uno a uno, los 401 tensores cuya entrada hay que | |
| 11 | +// girar. No se adivina por el nombre ni por la forma. | |
| 12 | +// · `sign_widths` / `sign_values` traen un vector de signos por anchura de | |
| 13 | +// entrada, concatenados. Se elige por la anchura del tensor. | |
| 14 | +// · `inverse_weight_names` son las tablas que guardan las filas ya giradas y | |
| 15 | +// hay que DESgirar tras la búsqueda. | |
| 16 | +// | |
| 17 | +// Si el fichero declara una versión o una transformada que no conocemos, esto | |
| 18 | +// LANZA en vez de seguir. Es la única respuesta honesta: continuar significaría | |
| 19 | +// devolver ruido con cara de respuesta. | |
| 20 | +// | |
| 21 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). | |
| 22 | + | |
| 23 | +const CLAVE = 'prism.hadamard.'; | |
| 24 | + | |
| 25 | +// Los arrays de CADENAS del GGUF no son arrays: el parser los devuelve | |
| 26 | +// perezosos ({length, at(i), toArray()}) para no materializar 248.000 tokens de | |
| 27 | +// vocabulario cada vez que alguien mira los metadatos. Los de escalares sí son | |
| 28 | +// vistas tipadas y se iteran solos. Un `new Set(...)` sobre el perezoso no | |
| 29 | +// lanza nada legible — dice «object is not iterable» — así que se normaliza | |
| 30 | +// aquí, en un sitio, en vez de esparcir la comprobación. | |
| 31 | +const lista = (v) => { | |
| 32 | + if (v == null) return []; | |
| 33 | + if (typeof v.toArray === 'function') return v.toArray(); | |
| 34 | + if (Array.isArray(v) || ArrayBuffer.isView(v)) return Array.from(v); | |
| 35 | + throw new Error('se esperaba una lista en los metadatos de la rotación'); | |
| 36 | +}; | |
| 37 | + | |
| 38 | +export function leeRotacion(meta) { | |
| 39 | + const v = meta[CLAVE + 'version']; | |
| 40 | + if (v === undefined) return null; // modelo sin rotación: normal | |
| 41 | + if (v !== 1) throw new Error(`rotación de Hadamard versión ${v}: no soportada`); | |
| 42 | + | |
| 43 | + const transformada = meta[CLAVE + 'transform']; | |
| 44 | + if (transformada !== 'normalized-sylvester-walsh-hadamard') { | |
| 45 | + throw new Error(`transformada desconocida: «${transformada}»`); | |
| 46 | + } | |
| 47 | + const eje = meta[CLAVE + 'axis']; | |
| 48 | + if (eje !== 'input-last-dimension') throw new Error(`eje de rotación desconocido: «${eje}»`); | |
| 49 | + const modo = meta[CLAVE + 'sign_mode']; | |
| 50 | + if (modo !== 'explicit') throw new Error(`modo de signos desconocido: «${modo}»`); | |
| 51 | + | |
| 52 | + const bloque = Number(meta[CLAVE + 'block_size']); | |
| 53 | + if (!bloque || (bloque & (bloque - 1)) !== 0) { | |
| 54 | + throw new Error(`bloque de rotación inválido: ${bloque}`); | |
| 55 | + } | |
| 56 | + const pesos = new Set(lista(meta[CLAVE + 'weight_names'])); | |
| 57 | + if (!pesos.size) throw new Error('la rotación no declara ningún tensor'); | |
| 58 | + const inversos = new Set(lista(meta[CLAVE + 'inverse_weight_names'])); | |
| 59 | + | |
| 60 | + // Los signos vienen concatenados por anchura, en el orden de `sign_widths`. | |
| 61 | + const anchuras = lista(meta[CLAVE + 'sign_widths']).map(Number); | |
| 62 | + const valores = lista(meta[CLAVE + 'sign_values']); | |
| 63 | + const signos = new Map(); | |
| 64 | + let o = 0; | |
| 65 | + for (const a of anchuras) { | |
| 66 | + if (a <= 0 || a % bloque !== 0) throw new Error(`anchura de signos inválida: ${a}`); | |
| 67 | + const v = new Float32Array(a); | |
| 68 | + for (let i = 0; i < a; i++) { | |
| 69 | + const s = Number(valores[o + i]); | |
| 70 | + if (s !== 1 && s !== -1) throw new Error(`signo que no es ±1 en la posición ${o + i}: ${s}`); | |
| 71 | + v[i] = s; | |
| 72 | + } | |
| 73 | + signos.set(a, v); | |
| 74 | + o += a; | |
| 75 | + } | |
| 76 | + if (o !== valores.length) { | |
| 77 | + throw new Error(`sobran o faltan signos: ${valores.length} valores para ${o} declarados`); | |
| 78 | + } | |
| 79 | + | |
| 80 | + return { | |
| 81 | + bloque, pesos, inversos, signos, | |
| 82 | + vGrouped: meta[CLAVE + 'gdn_v_grouped'] === true, | |
| 83 | + // Cuántos tensores declara, para poder comprobar que se aplicaron todos. | |
| 84 | + total: pesos.size + inversos.size, | |
| 85 | + }; | |
| 86 | +} |
added js/kernels.attn.wgsl.js +342 −0
| @@ -0,0 +1,342 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · shaders del bloque de atención de qwen35. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// Solo 6 de cada 24 bloques son esto; los otros 18 son SSM. Pero son los únicos | |
| 6 | +// que necesitan caché KV, así que son los que fijan el coste de contexto largo. | |
| 7 | +// | |
| 8 | +// La trampa que define este bloque: `attn_q.weight` proyecta 1024 → 4096, y esa | |
| 9 | +// fila NO es «Q en la mitad baja, puerta en la alta». Están INTERCALADOS por | |
| 10 | +// cabeza: | |
| 11 | +// [ q_h0(256) | gate_h0(256) | q_h1(256) | gate_h1(256) | … ] | |
| 12 | +// Partirlo por la mitad da tensores de la forma correcta, magnitudes creíbles y | |
| 13 | +// un modelo que no funciona. Por eso hay un kernel de extracción con paso en vez | |
| 14 | +// de una vista contigua. | |
| 15 | +// | |
| 16 | +// GQA: 8 cabezas de query contra 2 de clave/valor, o sea 4 queries por cada KV. | |
| 17 | +// La cabeza KV se elige con h / (H/KVH); no se replican los tensores. | |
| 18 | +// | |
| 19 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 20 | + | |
| 21 | +// Extrae un sub-tensor con paso: dst[t][h][d] = src[t][h·stride + offset + d]. | |
| 22 | +// Con stride = 2·headDim y offset = 0 saca Q; con offset = headDim, la puerta. | |
| 23 | +export function strideCopyShader(wg = 256) { | |
| 24 | + return /* wgsl */` | |
| 25 | +const WG : u32 = ${wg}u; | |
| 26 | +struct P { headDim : u32, heads : u32, tokens : u32, stride : u32, | |
| 27 | + offset : u32, pad0 : u32, pad1 : u32, pad2 : u32 }; | |
| 28 | +@group(0) @binding(0) var<storage, read> src : array<f32>; | |
| 29 | +@group(0) @binding(1) var<storage, read_write> dst : array<f32>; | |
| 30 | +@group(0) @binding(2) var<uniform> p : P; | |
| 31 | + | |
| 32 | +@compute @workgroup_size(${wg}) | |
| 33 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 34 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 35 | + let total = p.headDim * p.heads * p.tokens; | |
| 36 | + if (i >= total) { return; } | |
| 37 | + let d = i % p.headDim; | |
| 38 | + let rest = i / p.headDim; | |
| 39 | + let h = rest % p.heads; | |
| 40 | + let t = rest / p.heads; | |
| 41 | + // La fila del token mide heads·stride; dentro, cada cabeza ocupa «stride» y | |
| 42 | + // el sub-tensor que queremos empieza en «offset». | |
| 43 | + let srcRow = t * p.heads * p.stride; | |
| 44 | + dst[i] = src[srcRow + h * p.stride + p.offset + d]; | |
| 45 | +}`; | |
| 46 | +} | |
| 47 | + | |
| 48 | +// scores[h][t][j] = Q[t][h] · K[j][kv(h)], sin escalar y sin enmascarar: la | |
| 49 | +// escala y la máscara causal las aplica el softmax, igual que en la referencia. | |
| 50 | +// Compararse contra un `kq` ya escalado sería un falso negativo. | |
| 51 | +// `kvF16` pone la caché KV en media precisión: la mitad de memoria y la mitad | |
| 52 | +// de tráfico al leerla, que en el decode se lee entera por token. El acumulador | |
| 53 | +// sigue en f32 — lo que se guarda en media precisión es el DATO, no la suma, que | |
| 54 | +// es donde la media precisión sí se notaría. | |
| 55 | +export function attnScoresShader(wg = 64, kvF16 = false) { | |
| 56 | + const KV = kvF16 ? 'f16' : 'f32'; | |
| 57 | + return /* wgsl */`${kvF16 ? 'enable f16;\n' : ''} | |
| 58 | +const WG : u32 = ${wg}u; | |
| 59 | +struct P { headDim : u32, heads : u32, kvHeads : u32, tokens : u32, | |
| 60 | + nKv : u32, nPast : u32, pad0 : u32, pad1 : u32 }; | |
| 61 | +@group(0) @binding(0) var<storage, read> q : array<f32>; // [T][H][D] | |
| 62 | +@group(0) @binding(1) var<storage, read> k : array<${KV}>; // [nKv][KVH][D] | |
| 63 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; // [H][T][nKv] | |
| 64 | +@group(0) @binding(3) var<uniform> p : P; | |
| 65 | + | |
| 66 | +@compute @workgroup_size(${wg}) | |
| 67 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 68 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 69 | + let total = p.heads * p.tokens * p.nKv; | |
| 70 | + if (i >= total) { return; } | |
| 71 | + let j = i % p.nKv; | |
| 72 | + let rest = i / p.nKv; | |
| 73 | + let t = rest % p.tokens; | |
| 74 | + let h = rest / p.tokens; | |
| 75 | + | |
| 76 | + let group = p.heads / p.kvHeads; // 4 queries por cada cabeza KV | |
| 77 | + let kvh = h / group; | |
| 78 | + let qOff = (t * p.heads + h) * p.headDim; | |
| 79 | + let kOff = (j * p.kvHeads + kvh) * p.headDim; | |
| 80 | + | |
| 81 | + var acc = 0.0; | |
| 82 | + for (var d = 0u; d < p.headDim; d = d + 1u) { acc = acc + q[qOff + d] * f32(k[kOff + d]); } | |
| 83 | + dst[(h * p.tokens + t) * p.nKv + j] = acc; | |
| 84 | +}`; | |
| 85 | +} | |
| 86 | + | |
| 87 | +// out[t][h][d] = Σ_j probs[h][t][j] · V[j][kv(h)][d]. | |
| 88 | +// Los pesos que caen fuera de la máscara ya vienen a cero del softmax, así que | |
| 89 | +// no hace falta volver a enmascarar aquí. | |
| 90 | +export function attnCombineShader(wg = 64, kvF16 = false) { | |
| 91 | + const KV = kvF16 ? 'f16' : 'f32'; | |
| 92 | + return /* wgsl */`${kvF16 ? 'enable f16;\n' : ''} | |
| 93 | +const WG : u32 = ${wg}u; | |
| 94 | +struct P { headDim : u32, heads : u32, kvHeads : u32, tokens : u32, | |
| 95 | + nKv : u32, nPast : u32, pad0 : u32, pad1 : u32 }; | |
| 96 | +@group(0) @binding(0) var<storage, read> probs : array<f32>; // [H][T][nKv] | |
| 97 | +@group(0) @binding(1) var<storage, read> v : array<${KV}>; // [nKv][KVH][D] | |
| 98 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; // [T][H][D] | |
| 99 | +@group(0) @binding(3) var<uniform> p : P; | |
| 100 | + | |
| 101 | +@compute @workgroup_size(${wg}) | |
| 102 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 103 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 104 | + let total = p.tokens * p.heads * p.headDim; | |
| 105 | + if (i >= total) { return; } | |
| 106 | + let d = i % p.headDim; | |
| 107 | + let rest = i / p.headDim; | |
| 108 | + let h = rest % p.heads; | |
| 109 | + let t = rest / p.heads; | |
| 110 | + | |
| 111 | + let group = p.heads / p.kvHeads; | |
| 112 | + let kvh = h / group; | |
| 113 | + let pOff = (h * p.tokens + t) * p.nKv; | |
| 114 | + | |
| 115 | + var acc = 0.0; | |
| 116 | + for (var j = 0u; j < p.nKv; j = j + 1u) { | |
| 117 | + acc = acc + probs[pOff + j] * f32(v[(j * p.kvHeads + kvh) * p.headDim + d]); | |
| 118 | + } | |
| 119 | + dst[i] = acc; | |
| 120 | +}`; | |
| 121 | +} | |
| 122 | + | |
| 123 | +// Producto elemento a elemento — la puerta de salida multiplica la atención. | |
| 124 | +export function mulShader(wg = 256) { | |
| 125 | + return /* wgsl */` | |
| 126 | +const WG : u32 = ${wg}u; | |
| 127 | +struct P { n : u32, pad0 : u32, pad1 : u32, pad2 : u32 }; | |
| 128 | +@group(0) @binding(0) var<storage, read> a : array<f32>; | |
| 129 | +@group(0) @binding(1) var<storage, read> b : array<f32>; | |
| 130 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; | |
| 131 | +@group(0) @binding(3) var<uniform> p : P; | |
| 132 | + | |
| 133 | +@compute @workgroup_size(${wg}) | |
| 134 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 135 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 136 | + if (i >= p.n) { return; } | |
| 137 | + dst[i] = a[i] * b[i]; | |
| 138 | +}`; | |
| 139 | +} | |
| 140 | + | |
| 141 | +// ── combine PARTIDO: el mismo resultado, con el contexto repartido ─────────── | |
| 142 | +// El `attnCombineShader` de arriba pone un hilo por (token, cabeza, dimension) y | |
| 143 | +// recorre las nKv posiciones en un bucle. A contexto largo eso es ruinoso, y | |
| 144 | +// medido: a 64k de contexto se llevaba el 73 % del tiempo del token, y crecia | |
| 145 | +// tres veces mas rapido de lo que crecen los bytes que lee (lo mide una prueba | |
| 146 | +// interna). Tres cosas apiladas, no una: | |
| 147 | +// | |
| 148 | +// 1. una cadena de nKv sumas DEPENDIENTES, sin paralelismo de instruccion: | |
| 149 | +// cada vuelta espera el resultado de la anterior; | |
| 150 | +// 2. tokens×cabezas×headDim hilos —6.144 en decode— o sea casi nada de | |
| 151 | +// ocupacion para una suma larguisima; | |
| 152 | +// 3. la V se relee heads/kvHeads veces, porque cada cabeza de consulta | |
| 153 | +// recorre por su cuenta la misma V de su cabeza KV. | |
| 154 | +// | |
| 155 | +// Este reparte el contexto en BLOQUES trozos y pone un grupo por | |
| 156 | +// (trozo, cabeza KV, token), con las heads/kvHeads cabezas de consulta de ese | |
| 157 | +// grupo A LA VEZ. Asi la V se lee UNA vez (ataca el 3), los trozos dan | |
| 158 | +// ocupacion (el 2) y las cabezas dan cadenas de suma independientes, o sea que | |
| 159 | +// el paralelismo de instruccion sale gratis de compartir la V (el 1). | |
| 160 | +// | |
| 161 | +// Deja sumas parciales que `combineReduceShader` junta. NO es bit a bit igual al | |
| 162 | +// de arriba: cambia el orden de la suma. Medido contra el, coseno 1.000000 y | |
| 163 | +// desviaciones del orden de 1e-7 a 1e-6 RELATIVAS a la escala, en toda la | |
| 164 | +// rejilla de formas que el motor usa (1 y 32 tokens, contextos de 64 a 32.768), | |
| 165 | +// y en el 27B entero logits bit a bit identicos con seis tokens seguidos | |
| 166 | +// iguales (lo comprueba una prueba interna). | |
| 167 | +export function attnCombineSplitShader({ headDim, grupo, subTrozo = 64, kvF16 = false }) { | |
| 168 | + const KV = kvF16 ? 'f16' : 'f32'; | |
| 169 | + return /* wgsl */`${kvF16 ? 'enable f16;\n' : ''} | |
| 170 | +const D : u32 = ${headDim}u; | |
| 171 | +const G : u32 = ${grupo}u; | |
| 172 | +const SJ : u32 = ${subTrozo}u; | |
| 173 | +struct P { headDim : u32, heads : u32, kvHeads : u32, tokens : u32, | |
| 174 | + nKv : u32, bloques : u32, pad0 : u32, pad1 : u32 }; | |
| 175 | +@group(0) @binding(0) var<storage, read> probs : array<f32>; // [H][T][nKv] | |
| 176 | +@group(0) @binding(1) var<storage, read> v : array<${KV}>; // [nKv][KVH][D] | |
| 177 | +@group(0) @binding(2) var<storage, read_write> parc : array<f32>; // [T][H][BLOQUES][D] | |
| 178 | +@group(0) @binding(3) var<uniform> p : P; | |
| 179 | + | |
| 180 | +// Las probabilidades del sub-trozo, para las G cabezas de este grupo. Sin esto, | |
| 181 | +// los D hilos leerian de memoria global el MISMO valor D veces por cada j. | |
| 182 | +var<workgroup> ps : array<f32, ${grupo * subTrozo}u>; | |
| 183 | + | |
| 184 | +@compute @workgroup_size(${headDim}) | |
| 185 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 186 | + @builtin(local_invocation_id) lid : vec3<u32>) { | |
| 187 | + let bloque = wid.x; | |
| 188 | + let kvh = wid.y; | |
| 189 | + let t = wid.z; | |
| 190 | + let d = lid.x; | |
| 191 | + | |
| 192 | + // El ultimo trozo puede quedar corto: se recorta con nKv. Rellenarlo con | |
| 193 | + // ceros sumaria terminos que no existen. | |
| 194 | + let porBloque = (p.nKv + p.bloques - 1u) / p.bloques; | |
| 195 | + let j0 = bloque * porBloque; | |
| 196 | + let j1 = min(j0 + porBloque, p.nKv); | |
| 197 | + | |
| 198 | + var acc : array<f32, G>; | |
| 199 | + for (var g = 0u; g < G; g = g + 1u) { acc[g] = 0.0; } | |
| 200 | + | |
| 201 | + var jb = j0; | |
| 202 | + loop { | |
| 203 | + if (jb >= j1) { break; } | |
| 204 | + let n = min(SJ, j1 - jb); | |
| 205 | + for (var k = d; k < G * n; k = k + D) { | |
| 206 | + let g = k / n; | |
| 207 | + let jj = k % n; | |
| 208 | + let h = kvh * G + g; | |
| 209 | + ps[g * SJ + jj] = probs[(h * p.tokens + t) * p.nKv + jb + jj]; | |
| 210 | + } | |
| 211 | + workgroupBarrier(); | |
| 212 | + for (var jj = 0u; jj < n; jj = jj + 1u) { | |
| 213 | + // UNA lectura de V alimenta las G cabezas: ahi esta el ahorro de bytes. | |
| 214 | + let vv = f32(v[((jb + jj) * p.kvHeads + kvh) * D + d]); | |
| 215 | + for (var g = 0u; g < G; g = g + 1u) { | |
| 216 | + acc[g] = acc[g] + ps[g * SJ + jj] * vv; | |
| 217 | + } | |
| 218 | + } | |
| 219 | + workgroupBarrier(); | |
| 220 | + jb = jb + n; | |
| 221 | + } | |
| 222 | + | |
| 223 | + for (var g = 0u; g < G; g = g + 1u) { | |
| 224 | + let h = kvh * G + g; | |
| 225 | + parc[((t * p.heads + h) * p.bloques + bloque) * D + d] = acc[g]; | |
| 226 | + } | |
| 227 | +}`; | |
| 228 | +} | |
| 229 | + | |
| 230 | +// Junta las sumas parciales del kernel de arriba. Un hilo por salida. | |
| 231 | +export function combineReduceShader(wg = 256) { | |
| 232 | + return /* wgsl */` | |
| 233 | +struct P { headDim : u32, heads : u32, tokens : u32, bloques : u32 }; | |
| 234 | +@group(0) @binding(0) var<storage, read> parc : array<f32>; | |
| 235 | +@group(0) @binding(1) var<storage, read_write> dst : array<f32>; | |
| 236 | +@group(0) @binding(2) var<uniform> p : P; | |
| 237 | +@compute @workgroup_size(${wg}) | |
| 238 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 239 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 | |
| 240 | + let total = p.tokens * p.heads * p.headDim; | |
| 241 | + if (i >= total) { return; } | |
| 242 | + let d = i % p.headDim; | |
| 243 | + let th = i / p.headDim; | |
| 244 | + var s = 0.0; | |
| 245 | + for (var b = 0u; b < p.bloques; b = b + 1u) { | |
| 246 | + s = s + parc[(th * p.bloques + b) * p.headDim + d]; | |
| 247 | + } | |
| 248 | + dst[i] = s; | |
| 249 | +}`; | |
| 250 | +} | |
| 251 | + | |
| 252 | +// Memoria compartida que pide el scores con K compartida: SOLO las filas de q. | |
| 253 | +// Se expone para poder RECHAZAR la forma con un mensaje que diga cuanto pedia, | |
| 254 | +// en vez de dejar que reviente la validacion de WebGPU con un texto generico. | |
| 255 | +export function compartidaScores(headDim, grupo) { | |
| 256 | + return grupo * headDim * 4; | |
| 257 | +} | |
| 258 | + | |
| 259 | +// Cuantos trozos para una forma. Sale del barrido y no de un razonamiento: el | |
| 260 | +// optimo es el MAXIMO de bloques casi siempre, tambien con 32 tokens, con dos | |
| 261 | +// topes medidos — trozos de menos de 32 posiciones no aportan, y por encima de | |
| 262 | +// 32 bloques empeora (a nKv 65.000, 64 y 128 bloques salian algo peores). | |
| 263 | +export function bloquesCombine(nKv) { | |
| 264 | + return Math.max(1, Math.min(32, Math.ceil(nKv / 32))); | |
| 265 | +} | |
| 266 | + | |
| 267 | +// ── scores PARTIDO: la K leida UNA vez para las cabezas que la comparten ───── | |
| 268 | +// El `attnScoresShader` de arriba pone un hilo por (cabeza, token, posicion) y | |
| 269 | +// cada hilo recorre headDim. El paralelismo es de sobra —millones de hilos— y | |
| 270 | +// el kernel va al 96 % del techo de lectura: NO es ineficiente. | |
| 271 | +// El problema es que lee SEIS VECES lo que necesita. | |
| 272 | +// | |
| 273 | +// La cuenta, con las formas del 27B: cada cabeza de consulta recorre por su | |
| 274 | +// cuenta la K de su cabeza KV, y hay heads/kvHeads = 6 por cada una. O sea que | |
| 275 | +// la K de una capa se lee 6 veces. Medido a 64k de contexto, el kernel se | |
| 276 | +// llevaba el 69 % de lo que el contexto añade al token, y los bytes cuadran con | |
| 277 | +// el tiempo casi exactamente — por eso afinar la forma no servia de nada: no | |
| 278 | +// habia nada que afinar, habia que leer menos. | |
| 279 | +// | |
| 280 | +// Este pone un grupo por (token, cabeza KV, bloque de posiciones) y calcula las | |
| 281 | +// G cabezas de consulta de ese grupo A LA VEZ, con la K del bloque en memoria | |
| 282 | +// compartida. Asi la K se lee una vez, y de paso las G cabezas dan G cadenas de | |
| 283 | +// multiplicacion-suma independientes sobre el mismo dato. | |
| 284 | +// | |
| 285 | +// Es EXACTO: mismo producto, mismos terminos, mismo orden de acumulacion sobre | |
| 286 | +// d. La unica diferencia es de donde se lee cada valor. | |
| 287 | +export function attnScoresSharedShader({ headDim, grupo, kvF16 = false, wg = 64 }) { | |
| 288 | + const KV = kvF16 ? 'f16' : 'f32'; | |
| 289 | + return /* wgsl */`${kvF16 ? 'enable f16;\n' : ''} | |
| 290 | +const D : u32 = ${headDim}u; | |
| 291 | +const G : u32 = ${grupo}u; | |
| 292 | +struct P { headDim : u32, heads : u32, kvHeads : u32, tokens : u32, | |
| 293 | + nKv : u32, pad0 : u32, pad1 : u32, pad2 : u32 }; | |
| 294 | +@group(0) @binding(0) var<storage, read> q : array<f32>; // [T][H][D] | |
| 295 | +@group(0) @binding(1) var<storage, read> k : array<${KV}>; // [nKv][KVH][D] | |
| 296 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; // [H][T][nKv] | |
| 297 | +@group(0) @binding(3) var<uniform> p : P; | |
| 298 | + | |
| 299 | +// SOLO las G filas de q van a memoria compartida, y es a proposito. La primera | |
| 300 | +// version de este kernel metia ahi tambien un bloque de K: pedia por grupo mas | |
| 301 | +// del 90 % del tope de memoria compartida, o sea UN grupo residente por unidad | |
| 302 | +// de computo, y | |
| 303 | +// sin varios grupos en vuelo no hay con que esconder la latencia. Resultado: | |
| 304 | +// leia 6 veces menos bytes y corria 18 veces peor — TRES VECES mas lento que el | |
| 305 | +// kernel de un hilo por salida. Es el mismo modo de fallo que hundio el intento | |
| 306 | +// de cachear la rejilla i-quant en memoria compartida, y lo repeti teniendolo | |
| 307 | +// apuntado. | |
| 308 | +// | |
| 309 | +// Asi que la K se comparte por REGISTROS, no por memoria compartida: cada hilo | |
| 310 | +// lee k[j][d] UNA vez y la usa para las G cabezas. Se mantiene el patron de | |
| 311 | +// acceso del kernel original —que iba al 96 % del techo de lectura, o sea que | |
| 312 | +// no habia nada que arreglar ahi— y se le quitan los 5/6 de bytes redundantes | |
| 313 | +// que le metia la GQA. | |
| 314 | +var<workgroup> qs : array<f32, ${grupo * headDim}u>; | |
| 315 | + | |
| 316 | +@compute @workgroup_size(${wg}) | |
| 317 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 318 | + @builtin(local_invocation_id) lid : vec3<u32>) { | |
| 319 | + let kvh = wid.y; | |
| 320 | + let t = wid.z; | |
| 321 | + let tid = lid.x; | |
| 322 | + for (var i = tid; i < G * D; i = i + ${wg}u) { | |
| 323 | + qs[i] = q[(t * p.heads + kvh * G + i / D) * D + i % D]; | |
| 324 | + } | |
| 325 | + workgroupBarrier(); | |
| 326 | + | |
| 327 | + let j = wid.x * ${wg}u + tid; | |
| 328 | + if (j >= p.nKv) { return; } | |
| 329 | + let kOff = (j * p.kvHeads + kvh) * D; | |
| 330 | + var acc : array<f32, G>; | |
| 331 | + for (var g = 0u; g < G; g = g + 1u) { acc[g] = 0.0; } | |
| 332 | + for (var d = 0u; d < D; d = d + 1u) { | |
| 333 | + // UNA lectura de K alimenta las G cabezas: ahi esta todo el ahorro, y las G | |
| 334 | + // cadenas independientes dan el paralelismo de instruccion de propina. | |
| 335 | + let kv = f32(k[kOff + d]); | |
| 336 | + for (var g = 0u; g < G; g = g + 1u) { acc[g] = acc[g] + qs[g * D + d] * kv; } | |
| 337 | + } | |
| 338 | + for (var g = 0u; g < G; g = g + 1u) { | |
| 339 | + dst[((kvh * G + g) * p.tokens + t) * p.nKv + j] = acc[g]; | |
| 340 | + } | |
| 341 | +}`; | |
| 342 | +} |
added js/kernels.filas.wgsl.js +167 −0
| @@ -0,0 +1,167 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · matmul del decode con VARIAS FILAS por workgroup. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// POR QUÉ EXISTE ESTE FICHERO. El kernel de `kernels.wgsl.js` hace UNA fila por | |
| 6 | +// workgroup, y esa decisión tiene un precio que no se ve hasta que se cuenta el | |
| 7 | +// tráfico: | |
| 8 | +// | |
| 9 | +// · por cada peso se leen 50/256 de byte de peso (IQ1_S)… | |
| 10 | +// · …y 4 bytes de `x`, la activación en f32 que le corresponde. | |
| 11 | +// | |
| 12 | +// No es una errata. Cada workgroup se lee la fila ENTERA de activaciones, y hay | |
| 13 | +// una fila de activaciones leída por cada fila de salida: `x` se vuelve a leer | |
| 14 | +// `rows` veces por matmul. Son 20,5 bytes de activación por cada byte de peso. | |
| 15 | +// Eso cuadra con lo que midió el oráculo __ELFFUSS_X_FIJA (traer `x` = 35,6% del | |
| 16 | +// matmul, contra 6,2% de traer pesos+rejilla). | |
| 17 | +// | |
| 18 | +// La dirección de `x` NO depende de la fila: en el reparto por carril vale | |
| 19 | +// `(base_t*k + k0 + obase) >> 2`, donde `obase` sale de `lid.x` y `k0` de `b`. | |
| 20 | +// O sea que un carril puede leer sus dos vec4 UNA vez y usarlas contra los pesos | |
| 21 | +// de N filas distintas. Con N filas por workgroup: | |
| 22 | +// | |
| 23 | +// · las lecturas de `x` se dividen entre N (con N=4, la cuarta parte), | |
| 24 | +// · los lanzamientos de workgroup se dividen entre N, | |
| 25 | +// · el prólogo (leer params, calcular row, guardas) se paga N veces menos, | |
| 26 | +// · la escritura de `y` deja de ser un f32 suelto por workgroup y pasan a ser | |
| 27 | +// N f32 CONTIGUOS desde el mismo carril, | |
| 28 | +// · y dentro del bucle hay N cadenas de dependencia INDEPENDIENTES (gi -> tbl | |
| 29 | +// -> fma) en vuelo a la vez, que es paralelismo de memoria sin pedir más | |
| 30 | +// ocupancia. | |
| 31 | +// Lo que NO cambia: los bytes de peso leídos, la aritmética por peso y el orden | |
| 32 | +// de acumulación. | |
| 33 | +// | |
| 34 | +// ES BIT A BIT EXACTO, por construcción: cada fila acumula en el mismo carril, | |
| 35 | +// en el mismo orden de `b` y de `j`, y se reduce con el mismo `subgroupAdd` de | |
| 36 | +// 32 carriles. Lo único que cambia es CUÁNTAS filas lleva un workgroup. Se puede | |
| 37 | +// validar con igualdad EXACTA contra el kernel de una fila, no con tolerancia. | |
| 38 | +// | |
| 39 | +// AVISO DE MANTENIMIENTO: el cuerpo por fila de aquí es una COPIA del de | |
| 40 | +// `IQ1_S.decodeCarril` en `kernels.wgsl.js` (mismas nueve líneas, mismo orden). | |
| 41 | +// Se copia y no se reutiliza porque `decodeCarril` emite también el prólogo | |
| 42 | +// (`ib`, `l`, `obase`) y la lectura de `x`, que aquí van IZADOS fuera del bucle | |
| 43 | +// de filas — que es justamente el punto. Si se toca el descuantizador allí, hay | |
| 44 | +// que tocarlo aquí: la prueba de cuantización lo caza, porque valida el matmul | |
| 45 | +// contra la referencia de CPU. | |
| 46 | +// | |
| 47 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 48 | + | |
| 49 | +import { HELPERS, AXIS, quantInfo } from './kernels.wgsl.js'; | |
| 50 | + | |
| 51 | +// Cuántas filas lleva un workgroup. Devuelve 1 (= kernel de siempre) salvo que | |
| 52 | +// se cumpla TODO: interruptor puesto, tipo con reparto por carril, workgroup de | |
| 53 | +// 32, decode (tile 1), y `rows` múltiplo del reparto. | |
| 54 | +// | |
| 55 | +// El múltiplo NO es comodidad: sin él haría falta una cola con guarda por fila | |
| 56 | +// DENTRO del bucle de bloques, que es justo la rama que se quiere quitar. Las | |
| 57 | +// formas del decode del 27B son todas múltiplo de 8 (17408, 10240, 6144, 5120, | |
| 58 | +// 2048, 248320), así que la condición no descarta nada que importe. | |
| 59 | +// | |
| 60 | +// El suelo de 2048 filas es por PARALELISMO: con `rows` pequeño (ssm_alpha y | |
| 61 | +// ssm_beta son 48 filas) dividir entre N deja al despacho sin workgroups para | |
| 62 | +// llenar el dispositivo, y esas dos formas no pesan nada en el token. | |
| 63 | +// | |
| 64 | +// VIVE AQUÍ Y LO IMPORTA ops.js, como AXIS: si el despacho y el shader | |
| 65 | +// calcularan el reparto por su cuenta y se desincronizaran, saldrían filas a | |
| 66 | +// cero sin un solo error. | |
| 67 | +export function filasPorGrupo(type, workgroupSize, tile, carrilSubbloque, rows, subgroup) { | |
| 68 | + const q = Math.max(1, globalThis.__ELFFUSS_FILAS_WG | 0); | |
| 69 | + if (q === 1) return 1; | |
| 70 | + // El shader emite `enable subgroups;` y `subgroupAdd`. Sin subgrupos el | |
| 71 | + // pipeline NO COMPILA, y `threadsFor` devuelve 32 tambien en esa ruta para | |
| 72 | + // bpr=20 y bpr=24 — las dos formas que mas pesan. Sin esta guarda, poner | |
| 73 | + // `__ELFFUSS_NO_SUBGROUP` (lo hacen dos de las pruebas internas) | |
| 74 | + // reventaria la creacion del pipeline en vez de caer al kernel de una fila. | |
| 75 | + if (!subgroup) return 1; | |
| 76 | + const d = quantInfo(type); | |
| 77 | + const porCarril = carrilSubbloque && workgroupSize === 32 | |
| 78 | + && typeof d.decodeCarril === 'function'; | |
| 79 | + if (!porCarril || tile !== 1) return 1; | |
| 80 | + // Suelo de paralelismo, configurable. Con 2048 fijo, el modelo de juguete | |
| 81 | + // (filas de decenas) nunca toma esta ruta y haria falta cargar el 27B solo | |
| 82 | + // para saber si compila. En produccion el defecto sigue siendo 2048, asi que | |
| 83 | + // ssm_alpha y ssm_beta (48 filas) se quedan fuera igual. | |
| 84 | + const suelo = (globalThis.__ELFFUSS_FILAS_MIN | 0) || 2048; | |
| 85 | + if (rows < suelo || rows % q !== 0) return 1; | |
| 86 | + return q; | |
| 87 | +} | |
| 88 | + | |
| 89 | +// y[fila] = Σ_k A[fila][k] · x[k] para `filas` filas consecutivas por workgroup. | |
| 90 | +// Solo decode (tokens = 1, tile = 1) y solo tipos con reparto por carril. | |
| 91 | +export function matmulFilasShader(type, filas, sgSize = 32) { | |
| 92 | + const d = quantInfo(type); | |
| 93 | + if (typeof d.decodeCarril !== 'function' || !d.table) { | |
| 94 | + // Sin esto, un tipo nuevo se llevaría un shader que no le corresponde y el | |
| 95 | + // bind group seguiría siendo válido: filas de ceros sin un solo error. | |
| 96 | + throw new Error(`matmulFilasShader: «${type}» no tiene reparto por carril`); | |
| 97 | + } | |
| 98 | + if (!(filas > 1)) throw new Error('matmulFilasShader: filas debe ser > 1'); | |
| 99 | + const COMP = ['x', 'y', 'z', 'w']; | |
| 100 | + | |
| 101 | + // Cuerpo de UNA fila. Copia literal de IQ1_S.decodeCarril sin su prólogo: | |
| 102 | + // `ib`, `l`, `obase`, `xb`, `xv0` y `xv1` están izados fuera. | |
| 103 | + const fila = (r) => ` { | |
| 104 | + let blk = ((row0 + ${r}u) * bpr${globalThis.__ELFFUSS_W_FIJA === true ? '' : ' + b'}) * ${d.blockBytes}u; | |
| 105 | + let dq = load_scale(blk); | |
| 106 | + let qh = load_u16_at(blk + 34u + ib * 2u); | |
| 107 | + let dl = dq * f32(2u * ((qh >> 12u) & 7u) + 1u); | |
| 108 | + let delta = select(0.125, -0.125, (qh & 0x8000u) != 0u); | |
| 109 | + let gi = load_byte(blk + 2u + ib * 4u + l) | (((qh >> (3u * l)) & 7u) << 8u); | |
| 110 | + let g0 = tbl[gi * 2u]; | |
| 111 | + let g1 = tbl[gi * 2u + 1u]; | |
| 112 | +${Array.from({ length: 8 }, (_, j) => ` { | |
| 113 | + let gv = f32(get_byte_i32(${j < 4 ? 'g0' : 'g1'}, ${j % 4}u)); | |
| 114 | + let wv = dl * (gv + delta); | |
| 115 | + acc${r} = acc${r} + wv * ${j < 4 ? 'xv0' : 'xv1'}.${COMP[j % 4]}; | |
| 116 | + }`).join('\n')} | |
| 117 | + }`; | |
| 118 | + | |
| 119 | + return /* wgsl */`enable subgroups; | |
| 120 | + | |
| 121 | +const FILAS : u32 = ${filas}u; | |
| 122 | +struct Params { nBlocks: u32, blocksPerRow: u32, rows: u32, k: u32, | |
| 123 | + tokens: u32, pad0: u32, pad1: u32, pad2: u32 }; | |
| 124 | +@group(0) @binding(0) var<storage, read> w : array<u32>; | |
| 125 | +@group(0) @binding(1) var<storage, read> x : array<vec4<f32>>; | |
| 126 | +@group(0) @binding(2) var<storage, read_write> y : array<f32>; | |
| 127 | +@group(0) @binding(3) var<uniform> params : Params; | |
| 128 | +@group(0) @binding(4) var<storage, read> tbl : array<u32>; | |
| 129 | +${HELPERS} | |
| 130 | +@compute @workgroup_size(${sgSize}) | |
| 131 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 132 | + @builtin(local_invocation_id) lid : vec3<u32>) { | |
| 133 | + // Dos ejes de filas, igual que el kernel de una fila, pero ahora cada punto | |
| 134 | + // de la rejilla son FILAS filas consecutivas. | |
| 135 | + let row0 = (wid.x + wid.y * ${AXIS}u) * FILAS; | |
| 136 | + let base_t = wid.z; | |
| 137 | + let bpr = params.blocksPerRow; | |
| 138 | + // Prólogo IZADO: no depende ni de la fila ni del bloque. | |
| 139 | + let ib = lid.x >> 2u; | |
| 140 | + let l = lid.x & 3u; | |
| 141 | + let obase = ib * 32u + l * 8u; | |
| 142 | + | |
| 143 | +${Array.from({ length: filas }, (_, r) => ` var acc${r} = 0.0;`).join('\n')} | |
| 144 | + | |
| 145 | + if (row0 < params.rows) { | |
| 146 | + for (var b = 0u; b < bpr; b = b + 1u) { | |
| 147 | + let k0 = b * ${d.blockElems}u; | |
| 148 | + // Las DOS vec4 de activaciones del carril, leídas UNA vez para las FILAS | |
| 149 | + // filas. Aquí es donde se paga o no se paga el 35,6%. | |
| 150 | + let xb = (base_t * params.k${globalThis.__ELFFUSS_X_FIJA === true ? '' : ' + k0 + obase'}) >> 2u; | |
| 151 | + let xv0 = x[xb]; | |
| 152 | + let xv1 = x[xb + 1u]; | |
| 153 | +${Array.from({ length: filas }, (_, r) => fila(r)).join('\n')} | |
| 154 | + } | |
| 155 | + } | |
| 156 | + | |
| 157 | + // Una reducción por fila. Son FILAS por workgroup en vez de una, pero hay | |
| 158 | + // FILAS veces menos workgroups: el total de subgroupAdd no cambia. Lo que sí | |
| 159 | + // cambia es que los FILAS f32 que escribe el carril 0 son CONTIGUOS. | |
| 160 | +${Array.from({ length: filas }, (_, r) => ` { | |
| 161 | + let tot${r} = subgroupAdd(acc${r}); | |
| 162 | + if (lid.x == 0u && row0 + ${r}u < params.rows) { | |
| 163 | + y[base_t * params.rows + row0 + ${r}u] = tot${r}; | |
| 164 | + } | |
| 165 | + }`).join('\n')} | |
| 166 | +}`; | |
| 167 | +} |
added js/kernels.gemm.wgsl.js +434 −0
| @@ -0,0 +1,434 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// GEMM con teselado en REGISTROS para el prefill. | |
| 4 | +// | |
| 5 | +// El matmul de este motor da una fila de salida por subgrupo y procesa un token | |
| 6 | +// cada vez: cada peso que se trae de memoria se usa UNA vez. Con un lote de 32 | |
| 7 | +// tokens eso son 32 lecturas de los mismos pesos. Y el decode está limitado por | |
| 8 | +// traerse los pesos, no por calcular, así que ese factor se paga entero. | |
| 9 | +// | |
| 10 | +// Se ve por los dos lados: el prefill va por detrás de llama.cpp en el MISMO | |
| 11 | +// navegador, y una pasada de 8 tokens cuesta 5,15 veces una de 1 cuando debería | |
| 12 | +// costar poco más que una — que es también la razón por la que el decodificado | |
| 13 | +// especulativo no compensa aquí (verificar K borradores es justo esa pasada). | |
| 14 | +// | |
| 15 | +// La idea es la de cualquier GEMM por bloques, y es la que usa ggml-webgpu: | |
| 16 | +// | |
| 17 | +// · una tesela de pesos y otra de activaciones se llevan a memoria compartida | |
| 18 | +// UNA vez, ya descuantizadas — así el descuantizador también se paga una vez | |
| 19 | +// por tesela y no una vez por salida; | |
| 20 | +// · cada hilo acumula un bloque TM×TN en REGISTROS, así que cada peso que lee | |
| 21 | +// de memoria compartida alimenta TN multiplicaciones en vez de una. | |
| 22 | +// | |
| 23 | +// Con TM=TN=4 y un grupo de 8×8 hilos, un peso traído de memoria global acaba | |
| 24 | +// usándose 32 veces. Ese es todo el cambio. | |
| 25 | +// | |
| 26 | +// Las teselas van en f32 y no en f16 a propósito. f16 halvaría el tráfico de | |
| 27 | +// memoria compartida, pero mezclaría el cambio de MECANISMO con un cambio de | |
| 28 | +// PRECISIÓN, y entonces una diferencia en los logits no se sabría atribuir. | |
| 29 | +// Primero que el mecanismo se mida solo; f16 es un interruptor posterior. | |
| 30 | +// | |
| 31 | +// ── TK NO es el bloque del tipo ───────────────────────────────────────────── | |
| 32 | +// La primera versión ataba `TK` —el paso del bucle sobre k— al `blockElems` del | |
| 33 | +// tipo, porque con Q8_0 (bloques de 32) las dos cosas coincidían y la tirada por | |
| 34 | +// hilo caía dentro de un solo bloque sin pensarlo. PQ2_0, que es el tipo del | |
| 35 | +// modelo de producción, tiene bloques de 128, y ahí esa atadura se rompe por | |
| 36 | +// TRES sitios a la vez: | |
| 37 | +// | |
| 38 | +// 1. MEMORIA COMPARTIDA. Con la forma ganadora (2×4 en un grupo de 8×8) y | |
| 39 | +// TK=128 la tesela son (16 filas + 32 tokens)·128·4 = 24.576 bytes de los | |
| 40 | +// 32.768 que suelen dar los adaptadores. CABE —o sea que atarlo no habría fallado, | |
| 41 | +// habría ido lento y callado— pero se come el 75% del presupuesto, y eso | |
| 42 | +// hunde las ondas residentes. Lo que hizo ganar a 2×4 sobre 4×4 fue | |
| 43 | +// exactamente lo contrario. Se estaría pagando con ocupación lo que se | |
| 44 | +// gana con reúso, y ese cambio no sale a cuenta. | |
| 45 | +// 2. EL BARRIDO SE HUNDE. Las formas de 256 hilos (2×4 g16×16) piden | |
| 46 | +// (32+64)·128·4 = 49.152 bytes: no caben en ningún caso. O sea que el tipo | |
| 47 | +// del modelo decidiría qué formas se pueden ni siquiera probar. | |
| 48 | +// 3. ES UNA COINCIDENCIA, NO UNA RELACIÓN. TK es una propiedad del BUCLE | |
| 49 | +// (cuánta k cabe en la tesela); blockElems es del FORMATO (cada cuántos | |
| 50 | +// pesos hay una escala). Atarlas hace que la forma más rápida dependa del | |
| 51 | +// tipo de cuantización por accidente. | |
| 52 | +// | |
| 53 | +// Y no es un argumento de sobremesa: el punto 1 está MEDIDO. Con todo lo demás | |
| 54 | +// igual sobre el 27B PQ2_0, atar TK al bloque —la opción que no requería tocar | |
| 55 | +// nada— habría dejado sobre la mesa un factor 2,4 frente a TK=32. Todas las | |
| 56 | +// variantes eligen el mismo token, así que se comparan cosas que calculan lo | |
| 57 | +// mismo. | |
| 58 | +// | |
| 59 | +// Así que TK se desacopla: la carga a memoria compartida sabe descuantizar un | |
| 60 | +// tramo PARCIAL de un bloque. La condición que se impone es que **TK divida a | |
| 61 | +// blockElems**, y no la general «TK y blockElems cualesquiera». No es pereza: | |
| 62 | +// mientras una tesela no cruce de bloque, cada tirada lee UNA escala y la | |
| 63 | +// dirección del peso sigue siendo `(fila·bpr + b)·blockBytes`, sin partir nada. | |
| 64 | +// Permitir el cruce obligaría a llevar dos escalas y dos direcciones por tirada | |
| 65 | +// para ganar formas que nadie ha pedido. | |
| 66 | +// | |
| 67 | +// Con TK = blockElems (SUB = 1) el bucle interno queda de una sola vuelta y el | |
| 68 | +// código generado es el de antes: el orden de acumulación de Q8_0 no se mueve, | |
| 69 | +// así que sus logits siguen siendo los mismos bit a bit que antes del cambio. | |
| 70 | +// | |
| 71 | +// Lo que el desacoplo NO regala: que un tipo pueda entrar aquí sigue dependiendo | |
| 72 | +// de que un tramo parcial se pueda descuantizar por sí solo. PQ2_0 puede porque | |
| 73 | +// son cuatro pesos consecutivos por byte y una escala por bloque. PTQ1_0, por | |
| 74 | +// ejemplo, NO: guarda cinco trits por byte y el orden de salida no es el de | |
| 75 | +// los bytes, así que un tramo contiguo de pesos no es un tramo contiguo de | |
| 76 | +// fichero. De ahí que `TIRADAS` sea una tabla explícita y no un `decode` genérico. | |
| 77 | + | |
| 78 | +import { HELPERS, AXIS, quantInfo } from './kernels.wgsl.js'; | |
| 79 | + | |
| 80 | +// Paso por defecto del bucle sobre k. 32 no es el bloque de nadie en concreto: | |
| 81 | +// es el que sale mejor en el 27B PQ2_0, por delante de 16, 64 y 128, y a la vez | |
| 82 | +// el que ya estaba medido en Q8_0. Para un tipo de bloque mayor se toma igual | |
| 83 | +// —min(32, blockElems)— en vez de seguir al bloque, por lo de arriba. | |
| 84 | +export const TK_POR_DEFECTO = 32; | |
| 85 | + | |
| 86 | +// Descuantización de UNA tirada de `n` pesos consecutivos de una fila, dentro de | |
| 87 | +// un solo bloque. Vive aquí y no en el descriptor del tipo porque el contrato es | |
| 88 | +// distinto: el descriptor entrega valores a un `emit` que acumula; esto los | |
| 89 | +// ESCRIBE en memoria compartida. Mezclarlos haría que un cambio en el camino de | |
| 90 | +// decode moviera en silencio el de prefill. | |
| 91 | +// | |
| 92 | +// El andamio les da tres nombres: `blk` (offset en bytes del bloque), `e0` (el | |
| 93 | +// índice del primer peso de la tirada DENTRO del bloque) y `n` como constante. | |
| 94 | +// `e0` es múltiplo de 4 por construcción — lo garantizan las guardas del | |
| 95 | +// constructor— y de eso dependen las dos tiradas. | |
| 96 | +const TIRADAS = { | |
| 97 | + // 32 pesos, 34 bytes: escala f16 + 32 enteros de 8 bits con signo. | |
| 98 | + Q8_0: ({ n, escribe }) => /* wgsl */` | |
| 99 | + // La escala se lee UNA vez por tirada, no una por peso: es lo que permite | |
| 100 | + // esta forma y no la del decode, donde la tirada es de 8. | |
| 101 | + let d = load_scale(blk); | |
| 102 | + for (var i = 0u; i < ${n}u; i = i + 4u) { | |
| 103 | + let q = load_u32_at(blk + 2u + e0 + i); | |
| 104 | + for (var c = 0u; c < 4u; c = c + 1u) { | |
| 105 | + ${escribe('i + c', 'f32(get_byte_i32(q, c)) * d')} | |
| 106 | + } | |
| 107 | + }`, | |
| 108 | + | |
| 109 | + // 128 pesos, 34 bytes: escala f16 + 32 bytes de ranuras de 2 bits. CUATRO | |
| 110 | + // pesos consecutivos por byte, así que un tramo parcial alineado a 4 es un | |
| 111 | + // tramo de bytes entero: ni se parte un byte ni hace falta una segunda escala. | |
| 112 | + // La expresión del valor es CARÁCTER POR CARÁCTER la del `decode` del tipo | |
| 113 | + // (`f32(i32((by >> (c*2)) & 3) - 1) * d`): si se escribiera «mejor» —sacar la | |
| 114 | + // escala del bucle, por ejemplo— los pesos dejarían de ser los mismos bits y | |
| 115 | + // una diferencia en los logits ya no se sabría atribuir al mecanismo. | |
| 116 | + PQ2_0: ({ n, escribe }) => /* wgsl */` | |
| 117 | + let d = load_scale(blk); | |
| 118 | + for (var i = 0u; i < ${n}u; i = i + 4u) { | |
| 119 | + let by = load_byte(blk + 2u + (e0 + i) / 4u); | |
| 120 | + for (var c = 0u; c < 4u; c = c + 1u) { | |
| 121 | + ${escribe('i + c', 'f32(i32((by >> (c * 2u)) & 3u) - 1) * d')} | |
| 122 | + } | |
| 123 | + }`, | |
| 124 | +}; | |
| 125 | + | |
| 126 | +// Qué tipos saben pasar por aquí. La lista SON las claves de `TIRADAS`: tener | |
| 127 | +// dos sitios que decir lo mismo es tener dos sitios que desincronizar. | |
| 128 | +export const TIPOS_GEMM = new Set(Object.keys(TIRADAS)); | |
| 129 | + | |
| 130 | +// Paso del bucle sobre k para un tipo. `override` es para el barrido. | |
| 131 | +export function tkPara(type, override = 0) { | |
| 132 | + const d = quantInfo(type); | |
| 133 | + const tk = (override | 0) || Math.min(TK_POR_DEFECTO, d.blockElems); | |
| 134 | + return tk; | |
| 135 | +} | |
| 136 | + | |
| 137 | +export function soportaGemm(type, k, TK = 0) { | |
| 138 | + if (!TIPOS_GEMM.has(type)) return false; | |
| 139 | + const d = quantInfo(type); | |
| 140 | + const tk = tkPara(type, TK); | |
| 141 | + // TK divide al bloque (una tesela no cruza de bloque), TK es múltiplo de 4 | |
| 142 | + // (las dos tiradas leen de 4 en 4) y k entero en teselas. | |
| 143 | + return tk > 0 && tk % 4 === 0 && d.blockElems % tk === 0 && k % tk === 0; | |
| 144 | +} | |
| 145 | + | |
| 146 | +/** | |
| 147 | + * Y = W · X con W cuantizada (rows×k) y X token-major (tokens×k). | |
| 148 | + * Salida y[token * rows + row], igual que el matmul de siempre: es un sustituto | |
| 149 | + * intercambiable, no un camino paralelo con otro contrato. | |
| 150 | + * | |
| 151 | + * `maxCompartida` es el tope de memoria compartida por grupo del dispositivo | |
| 152 | + * (`limits.maxComputeWorkgroupStorageSize`). Se pasa para poder RECHAZAR una | |
| 153 | + * forma que no cabe con un mensaje que diga cuánto pedía, en vez de que reviente | |
| 154 | + * la validación de WebGPU al crear el pipeline con un texto genérico. | |
| 155 | + */ | |
| 156 | +export function matmulGemmShader(type, { TM = 4, TN = 4, WGM = 8, WGN = 8, TK = 0, maxCompartida = 32768 } = {}) { | |
| 157 | + const d = quantInfo(type); | |
| 158 | + if (!TIPOS_GEMM.has(type)) { | |
| 159 | + throw new Error(`matmulGemmShader: «${type}» todavía no pasa por el GEMM (ver TIRADAS)`); | |
| 160 | + } | |
| 161 | + const tk = tkPara(type, TK); | |
| 162 | + if (tk % 4 !== 0) { | |
| 163 | + throw new Error(`matmulGemmShader: TK=${tk} tiene que ser múltiplo de 4 (las tiradas leen de 4 en 4)`); | |
| 164 | + } | |
| 165 | + // Una tesela que cruzara de bloque necesitaría dos escalas y dos direcciones | |
| 166 | + // por tirada. No se soporta, así que se rechaza: leerla con una sola escala | |
| 167 | + // daría pesos mal escalados SIN lanzar, que es el modo de fallo caro. | |
| 168 | + if (d.blockElems % tk !== 0) { | |
| 169 | + throw new Error(`matmulGemmShader: TK=${tk} tiene que dividir al bloque de «${type}» (${d.blockElems})`); | |
| 170 | + } | |
| 171 | + const SUB = d.blockElems / tk; // sub-teselas por bloque; 1 = el caso de antes | |
| 172 | + const HILOS = WGM * WGN; | |
| 173 | + const FILAS_WG = WGM * TM; // filas de salida por grupo | |
| 174 | + const TOKS_WG = WGN * TN; // tokens por grupo | |
| 175 | + // ── PASO DE LA TESELA: CON RELLENO ───────────────────────────────────────── | |
| 176 | + // El paso entre filas de la tesela era `tk` floats. Con el tk medido como | |
| 177 | + // mejor (32) eso son 32 floats = 128 bytes, y en una arquitectura de 32 bancos | |
| 178 | + // de 4 bytes el banco es `índice % 32`: todas las filas caen en EL MISMO | |
| 179 | + // banco. Conflicto de 32 vías, o sea los accesos de un subgrupo serializados. | |
| 180 | + // Es el peor caso posible y era el último candidato sin probar del prefill | |
| 181 | + // (el matmul corre al 37 % del techo de cálculo). | |
| 182 | + // | |
| 183 | + // Un float de relleno por fila rompe la periodicidad: con paso tk+1, la fila | |
| 184 | + // r en kk cae en el banco (r·(tk+1) + kk) % 32 = (r + kk) % 32 con tk=32, o | |
| 185 | + // sea un banco distinto por fila. Cuesta (FILAS_WG + TOKS_WG) floats de | |
| 186 | + // memoria compartida, que es ruido. | |
| 187 | + // | |
| 188 | + // ⚠️ MEDIDO Y DESCARTADO. Apagado por defecto: con RELLENO=0 el shader | |
| 189 | + // generado es EXACTAMENTE el de antes. | |
| 190 | + // | |
| 191 | + // En un A/B del prefill completo, con el orden alternado en la misma sesión, | |
| 192 | + // el ganador cambia de una ronda a otra: es ruido, no efecto. (Se alterna el | |
| 193 | + // orden y se exige que el ganador se repita porque la primera medida paga la | |
| 194 | + // compilación del shader.) | |
| 195 | + // | |
| 196 | + // Y la razón de que no haya nada que ganar está en el propio bucle: en | |
| 197 | + // `xs[(ln*TN+tn)*SW + kk]` los hilos de un subgrupo que comparten `ln` leen la | |
| 198 | + // MISMA dirección, que es un broadcast y no un conflicto. Un conflicto de | |
| 199 | + // banco exige hilos leyendo direcciones DISTINTAS del mismo banco, y aquí el | |
| 200 | + // patrón es broadcast más paso 1 en kk. Nunca hubo un conflicto de 32 vías | |
| 201 | + // que romper, aunque el paso de 128 bytes lo sugiriera sobre el papel. | |
| 202 | + // | |
| 203 | + // Se conserva el mecanismo (a 1 rellena) porque la medida cuesta una línea y | |
| 204 | + // en otro adaptador, u otro reparto de hilos, podría dejar de ser broadcast. | |
| 205 | + const RELLENO = globalThis.__ELFFUSS_PAD_TESELA === 1 ? 1 : 0; | |
| 206 | + const SW = tk + RELLENO; | |
| 207 | + | |
| 208 | + // La memoria compartida se comprueba AQUÍ y no se deja al driver: el barrido | |
| 209 | + // necesita distinguir «esta forma no cabe» de «esta forma va lenta». | |
| 210 | + // Se cuenta con SW y no con tk: si no, el relleno quedaría fuera de la cuenta | |
| 211 | + // y una tesela al límite pasaría la guarda para que la rechazara el driver, | |
| 212 | + // que es exactamente lo que esta comprobación existe para evitar. | |
| 213 | + const compartida = (FILAS_WG + TOKS_WG) * SW * 4; | |
| 214 | + if (compartida > maxCompartida) { | |
| 215 | + throw new Error(`matmulGemmShader: la tesela pide ${compartida} bytes de memoria compartida ` + | |
| 216 | + `y el tope es ${maxCompartida} (filas ${FILAS_WG} + tokens ${TOKS_WG}, TK=${tk})`); | |
| 217 | + } | |
| 218 | + // Cuántos elementos pone cada hilo en cada tesela. Tiene que repartirse | |
| 219 | + // EXACTO: un reparto con resto dejaría huecos sin escribir en memoria | |
| 220 | + // compartida, y lo que se leería de ahí sería basura de la iteración anterior | |
| 221 | + // —no ceros—, o sea un resultado incorrecto que además no es reproducible. | |
| 222 | + if ((FILAS_WG * tk) % HILOS !== 0 || (TOKS_WG * tk) % HILOS !== 0) { | |
| 223 | + throw new Error(`matmulGemmShader: la tesela no se reparte exacta entre ${HILOS} hilos`); | |
| 224 | + } | |
| 225 | + const POR_HILO_W = (FILAS_WG * tk) / HILOS; | |
| 226 | + const POR_HILO_X = (TOKS_WG * tk) / HILOS; | |
| 227 | + if (POR_HILO_W % 4 !== 0) { | |
| 228 | + throw new Error('matmulGemmShader: la tirada de pesos por hilo debe ser múltiplo de 4 (se leen de 4 en 4)'); | |
| 229 | + } | |
| 230 | + // La carga a memoria compartida calcula UNA fila y UN bloque por hilo, así que | |
| 231 | + // la tirada no puede cruzar de fila. Sin esta guarda, una forma con la tirada | |
| 232 | + // más larga que el bloque lee los pesos de la fila equivocada y devuelve un | |
| 233 | + // resultado incorrecto SIN lanzar — que es justo lo que pasó con 8x4 g16x4: | |
| 234 | + // salía a toda velocidad y contestaba otra cosa. Una forma que no vale tiene | |
| 235 | + // que ser rechazada, no medida. | |
| 236 | + if (POR_HILO_W > tk || POR_HILO_X > tk) { | |
| 237 | + throw new Error(`matmulGemmShader: la tirada por hilo (pesos ${POR_HILO_W}, activaciones ${POR_HILO_X}) ` + | |
| 238 | + `no puede pasar de la tesela (${tk}): cruzaría de fila`); | |
| 239 | + } | |
| 240 | + // Y no basta con que quepa: tiene que ENCAJAR. Con una tirada que no divide a | |
| 241 | + // TK, el hilo `tid` arranca en `(tid·POR_HILO) % TK` y se sale por el final de | |
| 242 | + // su fila, pisando el principio de la siguiente y dejando un hueco detrás. Con | |
| 243 | + // formas potencia de dos no pasa nunca, pero «no pasa nunca con las que he | |
| 244 | + // probado» no es una guarda. | |
| 245 | + if (tk % POR_HILO_W !== 0 || tk % POR_HILO_X !== 0) { | |
| 246 | + throw new Error(`matmulGemmShader: la tirada por hilo (pesos ${POR_HILO_W}, activaciones ${POR_HILO_X}) ` + | |
| 247 | + `tiene que dividir a la tesela (${tk}): si no, se desborda de fila`); | |
| 248 | + } | |
| 249 | + // Y la tirada tampoco puede cruzar de BLOQUE dentro de la fila. Con TK | |
| 250 | + // dividiendo al bloque y la tirada dividiendo a TK esto ya se cumple, pero se | |
| 251 | + // deja escrito porque es la condición de la que depende leer UNA sola escala. | |
| 252 | + if (d.blockElems % POR_HILO_W !== 0) { | |
| 253 | + throw new Error(`matmulGemmShader: la tirada de pesos (${POR_HILO_W}) cruzaría de bloque (${d.blockElems})`); | |
| 254 | + } | |
| 255 | + | |
| 256 | + // El bucle del producto, en DOS formas. La de siempre indexa arrays por la | |
| 257 | + // variable de bucle; la plana genera un escalar por acumulador y ni un indice | |
| 258 | + // dinamico. | |
| 259 | + // | |
| 260 | + // Importa porque un array en ambito de funcion indexado dinamicamente puede | |
| 261 | + // acabar en memoria de RASCADO en vez de en registros, a criterio del | |
| 262 | + // compilador. Si los acumuladores no estan en registros, cada | |
| 263 | + // multiplicacion-acumulacion es un viaje a memoria. | |
| 264 | + // | |
| 265 | + // OJO con lo que esto NO es: el teselado por registros YA estaba puesto —los | |
| 266 | + // pesos se leen una vez por kk y alimentan las TN columnas—. Esto solo probaba | |
| 267 | + // si el indexado dinamico se derrama, que es una duda de compilador y no una | |
| 268 | + // palanca nueva. | |
| 269 | + // | |
| 270 | + // ⚠️ MEDIDO Y DESCARTADO: x1,00 en el prefill completo, y el ganador alterna | |
| 271 | + // entre rondas. El compilador ya mantiene los acumuladores en registros. | |
| 272 | + // Apagado por defecto; el shader que genera el defecto es el de siempre. | |
| 273 | + // | |
| 274 | + // Y una leccion del INSTRUMENTO que vale mas que el resultado: sin calentar, | |
| 275 | + // la primera medida paga la compilacion del shader y sale muy por debajo, y | |
| 276 | + // ese artefacto cae siempre sobre la primera variante medida. Sin calentar, | |
| 277 | + // el plano parecia ganar; calentando las DOS formas y descartando esas | |
| 278 | + // medidas, la diferencia desaparece. Si una variante compila su propio | |
| 279 | + // pipeline, hay que calentarla antes de cronometrarla. | |
| 280 | + const plano = globalThis.__ELFFUSS_GEMM_PLANO === true; | |
| 281 | + const L = []; | |
| 282 | + L.push(` for (var kk = 0u; kk < ${tk}u; kk = kk + 1u) {`); | |
| 283 | + if (plano) { | |
| 284 | + for (let tm = 0; tm < TM; tm++) { | |
| 285 | + L.push(` let w${tm} = ws[(lm * ${TM}u + ${tm}u) * ${SW}u + kk];`); | |
| 286 | + } | |
| 287 | + for (let tn = 0; tn < TN; tn++) { | |
| 288 | + L.push(` let x${tn} = xs[(ln * ${TN}u + ${tn}u) * ${SW}u + kk];`); | |
| 289 | + for (let tm = 0; tm < TM; tm++) { | |
| 290 | + L.push(` a${tm}_${tn} = a${tm}_${tn} + w${tm} * x${tn};`); | |
| 291 | + } | |
| 292 | + } | |
| 293 | + } else { | |
| 294 | + L.push(` var wr : array<f32, ${TM}u>;`); | |
| 295 | + L.push(` for (var tm = 0u; tm < ${TM}u; tm = tm + 1u) {`); | |
| 296 | + L.push(` wr[tm] = ws[(lm * ${TM}u + tm) * ${SW}u + kk];`); | |
| 297 | + L.push(' }'); | |
| 298 | + L.push(` for (var tn = 0u; tn < ${TN}u; tn = tn + 1u) {`); | |
| 299 | + L.push(` let xv = xs[(ln * ${TN}u + tn) * ${SW}u + kk];`); | |
| 300 | + L.push(` for (var tm = 0u; tm < ${TM}u; tm = tm + 1u) {`); | |
| 301 | + L.push(' acc[tm][tn] = acc[tm][tn] + wr[tm] * xv;'); | |
| 302 | + L.push(' }'); | |
| 303 | + L.push(' }'); | |
| 304 | + } | |
| 305 | + L.push(' }'); | |
| 306 | + const PRODUCTO = L.join('\n'); | |
| 307 | + | |
| 308 | + // Declaración de los acumuladores y volcado final, coherentes con la forma | |
| 309 | + // elegida: si el producto usa escalares, aquí NO puede quedar un array, o el | |
| 310 | + // shader ni compila. | |
| 311 | + const D = []; | |
| 312 | + if (plano) { | |
| 313 | + D.push(' // Acumuladores como ESCALARES: ni un indice dinamico en el kernel.'); | |
| 314 | + for (let tm = 0; tm < TM; tm++) { | |
| 315 | + for (let tn = 0; tn < TN; tn++) D.push(` var a${tm}_${tn} = 0.0;`); | |
| 316 | + } | |
| 317 | + } else { | |
| 318 | + D.push(' // Acumulador TM x TN en registros. Esto es el kernel entero: lo que lo'); | |
| 319 | + D.push(' // hace rapido es que estas celdas no vuelven a memoria hasta el final.'); | |
| 320 | + D.push(` var acc : array<array<f32, ${TN}u>, ${TM}u>;`); | |
| 321 | + D.push(` for (var tm = 0u; tm < ${TM}u; tm = tm + 1u) {`); | |
| 322 | + D.push(` for (var tn = 0u; tn < ${TN}u; tn = tn + 1u) { acc[tm][tn] = 0.0; }`); | |
| 323 | + D.push(' }'); | |
| 324 | + } | |
| 325 | + const DECL_ACC = D.join('\n'); | |
| 326 | + | |
| 327 | + const V = []; | |
| 328 | + if (plano) { | |
| 329 | + for (let tn = 0; tn < TN; tn++) { | |
| 330 | + V.push(` {`); | |
| 331 | + V.push(` let tok = tok0 + ln * ${TN}u + ${tn}u;`); | |
| 332 | + V.push(' if (tok < params.tokens) {'); | |
| 333 | + for (let tm = 0; tm < TM; tm++) { | |
| 334 | + V.push(` let f${tm} = fila0 + lm * ${TM}u + ${tm}u;`); | |
| 335 | + V.push(` if (f${tm} < params.rows) { y[tok * params.rows + f${tm}] = a${tm}_${tn}; }`); | |
| 336 | + } | |
| 337 | + V.push(' }'); | |
| 338 | + V.push(' }'); | |
| 339 | + } | |
| 340 | + } else { | |
| 341 | + V.push(` for (var tn = 0u; tn < ${TN}u; tn = tn + 1u) {`); | |
| 342 | + V.push(` let tok = tok0 + ln * ${TN}u + tn;`); | |
| 343 | + V.push(' if (tok >= params.tokens) { continue; }'); | |
| 344 | + V.push(` for (var tm = 0u; tm < ${TM}u; tm = tm + 1u) {`); | |
| 345 | + V.push(` let fila = fila0 + lm * ${TM}u + tm;`); | |
| 346 | + V.push(' if (fila < params.rows) {'); | |
| 347 | + V.push(' y[tok * params.rows + fila] = acc[tm][tn];'); | |
| 348 | + V.push(' }'); | |
| 349 | + V.push(' }'); | |
| 350 | + V.push(' }'); | |
| 351 | + } | |
| 352 | + const VOLCADO = V.join('\n'); | |
| 353 | + | |
| 354 | + const tirada = TIRADAS[type]({ | |
| 355 | + n: POR_HILO_W, | |
| 356 | + escribe: (i, v) => `ws[fila * ${SW}u + kk0 + ${i}] = ${v};`, | |
| 357 | + }); | |
| 358 | + | |
| 359 | + return /* wgsl */` | |
| 360 | +struct Params { nBlocks: u32, blocksPerRow: u32, rows: u32, k: u32, | |
| 361 | + tokens: u32, pad0: u32, pad1: u32, pad2: u32 }; | |
| 362 | +@group(0) @binding(0) var<storage, read> w : array<u32>; | |
| 363 | +@group(0) @binding(1) var<storage, read> x : array<f32>; | |
| 364 | +@group(0) @binding(2) var<storage, read_write> y : array<f32>; | |
| 365 | +@group(0) @binding(3) var<uniform> params : Params; | |
| 366 | +${d.table ? '@group(0) @binding(4) var<storage, read> tbl : array<u32>;' : ''} | |
| 367 | +${HELPERS}${d.helpers} | |
| 368 | + | |
| 369 | +var<workgroup> ws : array<f32, ${FILAS_WG * SW}u>; // tesela de pesos, ya descuantizada (paso con relleno) | |
| 370 | +var<workgroup> xs : array<f32, ${TOKS_WG * SW}u>; // tesela de activaciones (paso con relleno) | |
| 371 | + | |
| 372 | +@compute @workgroup_size(${HILOS}) | |
| 373 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 374 | + @builtin(local_invocation_id) lid : vec3<u32>) { | |
| 375 | + let tid = lid.x; | |
| 376 | + // Reparto del hilo dentro de la tesela de salida. | |
| 377 | + let lm = tid % ${WGM}u; | |
| 378 | + let ln = tid / ${WGM}u; | |
| 379 | + // Las filas van en DOS ejes: uno solo topa en 65.535 y la cabeza de salida | |
| 380 | + // son cientos de miles de filas. Los tokens van en el tercero. | |
| 381 | + let fila0 = (wid.x + wid.y * ${AXIS}u) * ${FILAS_WG}u; | |
| 382 | + let tok0 = wid.z * ${TOKS_WG}u; | |
| 383 | + let bpr = params.blocksPerRow; | |
| 384 | + | |
| 385 | + // Acumulador TM×TN en registros. Esto es el kernel entero: lo que lo hace | |
| 386 | + // rápido es que estas ${TM * TN} celdas no vuelven a memoria hasta el final. | |
| 387 | +${DECL_ACC} | |
| 388 | + | |
| 389 | + for (var b = 0u; b < bpr; b = b + 1u) { | |
| 390 | + // Sub-teselas dentro del bloque. Con SUB=1 (TK = blockElems) esta vuelta | |
| 391 | + // desaparece y queda exactamente el bucle de antes, incluido el orden de | |
| 392 | + // acumulación: por eso Q8_0 no cambia ni un bit al desacoplar TK. | |
| 393 | + for (var s = 0u; s < ${SUB}u; s = s + 1u) { | |
| 394 | + let kOff = s * ${tk}u; // offset dentro del bloque | |
| 395 | + let k0 = b * ${d.blockElems}u + kOff; // offset absoluto en k | |
| 396 | + // ── Tesela de PESOS a memoria compartida, descuantizada una sola vez ── | |
| 397 | + { | |
| 398 | + let plano = tid * ${POR_HILO_W}u; | |
| 399 | + let fila = plano / ${tk}u; | |
| 400 | + let kk0 = plano % ${tk}u; | |
| 401 | + let e0 = kOff + kk0; | |
| 402 | + let global = fila0 + fila; | |
| 403 | + if (global < params.rows) { | |
| 404 | + let blk = (global * bpr + b) * ${d.blockBytes}u; | |
| 405 | +${tirada} | |
| 406 | + } else { | |
| 407 | + // Fuera de rango se escriben CEROS, no se deja lo de la vuelta anterior: | |
| 408 | + // esas filas se calculan igual y solo se descartan al guardar, así que | |
| 409 | + // basura aquí sería basura sumada en acumuladores que sí se guardan. | |
| 410 | + for (var i = 0u; i < ${POR_HILO_W}u; i = i + 1u) { ws[fila * ${SW}u + kk0 + i] = 0.0; } | |
| 411 | + } | |
| 412 | + } | |
| 413 | + // ── Tesela de ACTIVACIONES ── | |
| 414 | + { | |
| 415 | + let plano = tid * ${POR_HILO_X}u; | |
| 416 | + let t = plano / ${tk}u; | |
| 417 | + let kk0 = plano % ${tk}u; | |
| 418 | + let global = tok0 + t; | |
| 419 | + let base = global * params.k + k0 + kk0; | |
| 420 | + for (var i = 0u; i < ${POR_HILO_X}u; i = i + 1u) { | |
| 421 | + xs[t * ${SW}u + kk0 + i] = select(0.0, x[base + i], global < params.tokens); | |
| 422 | + } | |
| 423 | + } | |
| 424 | + workgroupBarrier(); | |
| 425 | + | |
| 426 | +${PRODUCTO} | |
| 427 | + workgroupBarrier(); | |
| 428 | + } | |
| 429 | + } | |
| 430 | + | |
| 431 | +${VOLCADO} | |
| 432 | +} | |
| 433 | +`; | |
| 434 | +} |
added js/kernels.hadamard.wgsl.js +115 −0
| @@ -0,0 +1,115 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Rotación de Hadamard sobre las activaciones — para pesos en base rotada. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// Algunos modelos ternarios guardan los pesos girados por una rotación ortogonal | |
| 6 | +// y esperan que el runtime aplique la misma rotación a las activaciones. No es | |
| 7 | +// opcional: sin ella el modelo no da texto malo, da ruido. El fichero declara la | |
| 8 | +// rotación en sus metadatos, así que un runtime o la aplica o se niega a cargar. | |
| 9 | +// | |
| 10 | +// LA MATRIZ, tal cual la construye la implementación de referencia: | |
| 11 | +// H[r][c] = (-1)^popcount(r & c) / sqrt(N) | |
| 12 | +// Pese a que el fichero la llama «walsh», ese es el orden NATURAL de Sylvester, | |
| 13 | +// y eso importa mucho: la transformada RÁPIDA en orden natural la calcula | |
| 14 | +// exacta, así que el coste es log2(N) etapas de mariposa en vez de una | |
| 15 | +// multiplicación por una matriz de N×N. Con N=1024 son 10 etapas contra un | |
| 16 | +// millón de multiplicaciones por bloque. Comprobado contra la matriz explícita. | |
| 17 | +// | |
| 18 | +// Es SIMÉTRICA y ORTOGONAL, luego es su propia inversa: H(Hx) = x. Por eso la | |
| 19 | +// tabla de embeddings —que guarda las filas ya giradas— se deshace con la misma | |
| 20 | +// transformada, solo que con los signos en el otro orden. | |
| 21 | +// | |
| 22 | +// DOS ÓRDENES, y confundirlos da ruido silencioso: | |
| 23 | +// · directo (antes de un matmul): y = H(s ⊙ x) signos PRIMERO | |
| 24 | +// · inverso (tras el embedding): y = s ⊙ (H x) signos DESPUÉS | |
| 25 | +// | |
| 26 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). | |
| 27 | + | |
| 28 | +// `bloque` es el tamaño de la rotación (1024 en los modelos que la usan) y | |
| 29 | +// `wg` cuántos hilos la procesan. Cada workgroup se queda un bloque entero en | |
| 30 | +// memoria compartida: 1024 f32, holgado frente al mínimo que garantiza WebGPU. | |
| 31 | +export function hadamardShader(bloque = 1024, wg = 256) { | |
| 32 | + const etapas = Math.log2(bloque); | |
| 33 | + if (!Number.isInteger(etapas)) throw new Error(`bloque de Hadamard no es potencia de dos: ${bloque}`); | |
| 34 | + return /* wgsl */` | |
| 35 | +const WG : u32 = ${wg}u; | |
| 36 | +const N : u32 = ${bloque}u; | |
| 37 | +const MITAD : u32 = ${bloque / 2}u; | |
| 38 | +// La normalización 1/sqrt(N) se aplica UNA vez al final, no por etapa: así la | |
| 39 | +// transformada rápida hace solo sumas y restas y no arrastra redondeos. | |
| 40 | +const ESCALA : f32 = ${(1 / Math.sqrt(bloque)).toString()}; | |
| 41 | + | |
| 42 | +struct P { | |
| 43 | + ancho : u32, // elementos por fila (múltiplo de N) | |
| 44 | + filas : u32, | |
| 45 | + porFila : u32, // ancho / N | |
| 46 | + inverso : u32, // 0 = signos antes (directo) · 1 = signos después | |
| 47 | + permHd : u32, // reordenado de rasgos: 0 = ninguno | |
| 48 | + permNk : u32, | |
| 49 | + permRep : u32, | |
| 50 | + pad : u32, | |
| 51 | +}; | |
| 52 | +@group(0) @binding(0) var<storage, read> src : array<f32>; | |
| 53 | +@group(0) @binding(1) var<storage, read> signo : array<f32>; | |
| 54 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; | |
| 55 | +@group(0) @binding(3) var<uniform> p : P; | |
| 56 | + | |
| 57 | +var<workgroup> s : array<f32, ${bloque}>; | |
| 58 | + | |
| 59 | +@compute @workgroup_size(${wg}) | |
| 60 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 61 | + @builtin(local_invocation_id) lid : vec3<u32>) { | |
| 62 | + let grupo = wid.x + wid.y * 65535u; // dos ejes: uno solo topa en 65535 | |
| 63 | + if (grupo >= p.filas * p.porFila) { return; } | |
| 64 | + let fila = grupo / p.porFila; | |
| 65 | + let trozo = grupo % p.porFila; | |
| 66 | + let base = fila * p.ancho + trozo * N; // dónde empieza este bloque | |
| 67 | + let baseSg = trozo * N; // el signo va por POSICIÓN en la fila | |
| 68 | + | |
| 69 | + // Carga. En el camino directo los signos se aplican AQUÍ, antes de rotar. | |
| 70 | + for (var i = lid.x; i < N; i = i + WG) { | |
| 71 | + // REORDENADO DE RASGOS, cuando el fichero lo pide para este tensor. La | |
| 72 | + // activación viene por teselas [hd, nk, rep] y el peso se guardó agrupado | |
| 73 | + // [hd, rep, nk]. Mezcla ENTRE bloques de N, así que no puede hacerse | |
| 74 | + // después de trocear: se hace aquí, al leer, y sale gratis. | |
| 75 | + // | |
| 76 | + // Se calcula el índice ORIGEN a partir del destino, que es lo que necesita | |
| 77 | + // una carga: destino p = hd + Hd*(rep + Rep*nk) -> origen hd + Hd*(nk + Nk*rep). | |
| 78 | + var orig = trozo * N + i; | |
| 79 | + if (p.permRep > 1u) { | |
| 80 | + let pos = trozo * N + i; | |
| 81 | + let hd = pos % p.permHd; | |
| 82 | + let q = pos / p.permHd; | |
| 83 | + // El sentido del reordenado es un 50/50 que NO se deduce de la lectura: | |
| 84 | + // hay que probarlo. El interruptor __ELFFUSS_PERM_INV invierte el par. | |
| 85 | + let rep = select(q % p.permRep, q / p.permNk, p.pad == 1u); | |
| 86 | + let nk = select(q / p.permRep, q % p.permNk, p.pad == 1u); | |
| 87 | + orig = hd + p.permHd * (nk + p.permNk * rep); | |
| 88 | + } | |
| 89 | + let v = src[fila * p.ancho + orig]; | |
| 90 | + s[i] = select(v * signo[baseSg + i], v, p.inverso == 1u); | |
| 91 | + } | |
| 92 | + workgroupBarrier(); | |
| 93 | + | |
| 94 | + // Transformada rápida en orden natural. Las N/2 mariposas de cada etapa tocan | |
| 95 | + // índices DISJUNTOS, así que dentro de una etapa no hace falta barrera; entre | |
| 96 | + // etapas sí. El bucle de etapas es uniforme, que es lo que exige la barrera. | |
| 97 | + for (var et = 0u; et < ${etapas}u; et = et + 1u) { | |
| 98 | + let len = 1u << et; | |
| 99 | + for (var b = lid.x; b < MITAD; b = b + WG) { | |
| 100 | + let j = (b & (len - 1u)) | ((b >> et) << (et + 1u)); | |
| 101 | + let a = s[j]; | |
| 102 | + let c = s[j + len]; | |
| 103 | + s[j] = a + c; | |
| 104 | + s[j + len] = a - c; | |
| 105 | + } | |
| 106 | + workgroupBarrier(); | |
| 107 | + } | |
| 108 | + | |
| 109 | + // Escritura. En el camino inverso los signos se aplican AQUÍ, después. | |
| 110 | + for (var i = lid.x; i < N; i = i + WG) { | |
| 111 | + let v = s[i] * ESCALA; | |
| 112 | + dst[base + i] = select(v, v * signo[baseSg + i], p.inverso == 1u); | |
| 113 | + } | |
| 114 | +}`; | |
| 115 | +} |
added js/kernels.model.wgsl.js +101 −0
| @@ -0,0 +1,101 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · plomería del forward: embeddings, caché y ventana de conv. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// Tres operaciones que no son matemática del modelo pero sin las cuales no hay | |
| 6 | +// forward. Las tres mueven datos, y las tres tienen una forma de equivocarse que | |
| 7 | +// no produce ningún error: escribir en el sitio de al lado. | |
| 8 | +// | |
| 9 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 10 | + | |
| 11 | +// El gather de embeddings vivía aquí, clavado a Q8_0 y con su propia copia de | |
| 12 | +// los helpers de descodificación. Ahora está en `kernels.wgsl.js`, generado por | |
| 13 | +// el mismo andamio que el matmul: la tabla del 27B no es Q8_0, y dos copias de | |
| 14 | +// la descodificación son dos sitios donde equivocarse. | |
| 15 | + | |
| 16 | +// Copia un bloque de elementos dentro de otro buffer, en un desplazamiento. | |
| 17 | +// Es cómo se añaden K y V a la caché: se escribe a partir de nPast, sin tocar | |
| 18 | +// lo anterior. Un desplazamiento mal calculado pisa tokens ya cacheados y el | |
| 19 | +// modelo empieza a «recordar» cosas que no dijo nadie. | |
| 20 | +// `dstF16` es para llenar la caché KV en media precisión: la fuente sigue en | |
| 21 | +// f32 (viene del rope) y la conversión se hace AQUÍ, al guardar, que es el único | |
| 22 | +// sitio donde ocurre una vez por token en vez de una vez por lectura. | |
| 23 | +export function copyIntoShader(wg = 256, dstF16 = false) { | |
| 24 | + return /* wgsl */`${dstF16 ? 'enable f16;\n' : ''} | |
| 25 | +const WG : u32 = ${wg}u; | |
| 26 | +struct P { n : u32, dstOffset : u32, srcOffset : u32, pad : u32 }; | |
| 27 | +@group(0) @binding(0) var<storage, read> src : array<f32>; | |
| 28 | +@group(0) @binding(1) var<storage, read_write> dst : array<${dstF16 ? 'f16' : 'f32'}>; | |
| 29 | +@group(0) @binding(2) var<uniform> p : P; | |
| 30 | + | |
| 31 | +@compute @workgroup_size(${wg}) | |
| 32 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 33 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 34 | + if (i >= p.n) { return; } | |
| 35 | + dst[p.dstOffset + i] = ${dstF16 ? 'f16' : 'f32'}(src[p.srcOffset + i]); | |
| 36 | +}`; | |
| 37 | +} | |
| 38 | + | |
| 39 | +// Monta la ventana de la convolución: por canal, los K-1 valores que quedaron | |
| 40 | +// del token anterior seguidos de los T nuevos. Esto es a la vez una TRANSPOSICIÓN | |
| 41 | +// (qkv viene [token][canal] y la conv lee [canal][tiempo]) y una concatenación. | |
| 42 | +// | |
| 43 | +// El desplazamiento del estado es implícito: no hay memmove, se copian las | |
| 44 | +// últimas K-1 columnas de la ventana de vuelta al estado. | |
| 45 | +export function convWindowShader(wg = 256) { | |
| 46 | + return /* wgsl */` | |
| 47 | +const WG : u32 = ${wg}u; | |
| 48 | +struct P { channels : u32, tokens : u32, keep : u32, window : u32 }; | |
| 49 | +@group(0) @binding(0) var<storage, read> state : array<f32>; // [keep][C] | |
| 50 | +@group(0) @binding(1) var<storage, read> qkv : array<f32>; // [T][C] | |
| 51 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; // [C][window] | |
| 52 | +@group(0) @binding(3) var<uniform> p : P; | |
| 53 | + | |
| 54 | +@compute @workgroup_size(${wg}) | |
| 55 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 56 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 57 | + if (i >= p.channels * p.window) { return; } | |
| 58 | + let tau = i % p.window; | |
| 59 | + let c = i / p.window; | |
| 60 | + if (tau < p.keep) { dst[i] = state[tau * p.channels + c]; } | |
| 61 | + else { dst[i] = qkv[(tau - p.keep) * p.channels + c]; } | |
| 62 | +}`; | |
| 63 | +} | |
| 64 | + | |
| 65 | +// Guarda las últimas keep columnas de la ventana como estado del token siguiente. | |
| 66 | +export function convSaveShader(wg = 256) { | |
| 67 | + return /* wgsl */` | |
| 68 | +const WG : u32 = ${wg}u; | |
| 69 | +struct P { channels : u32, tokens : u32, keep : u32, window : u32 }; | |
| 70 | +@group(0) @binding(0) var<storage, read> win : array<f32>; // [C][window] | |
| 71 | +@group(0) @binding(1) var<storage, read_write> state : array<f32>; // [keep][C] | |
| 72 | +@group(0) @binding(2) var<uniform> p : P; | |
| 73 | + | |
| 74 | +@compute @workgroup_size(${wg}) | |
| 75 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 76 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 77 | + if (i >= p.channels * p.keep) { return; } | |
| 78 | + let c = i % p.channels; | |
| 79 | + let tau = i / p.channels; | |
| 80 | + state[i] = win[c * p.window + (p.window - p.keep + tau)]; | |
| 81 | +}`; | |
| 82 | +} | |
| 83 | + | |
| 84 | +// silu(x) = x·sigmoid(x), elemento a elemento. Se usa sobre los 6144 canales | |
| 85 | +// justo después de la convolución, antes de cortar q|k|v. | |
| 86 | +export function siluShader(wg = 256) { | |
| 87 | + return /* wgsl */` | |
| 88 | +const WG : u32 = ${wg}u; | |
| 89 | +struct P { n : u32, pad0 : u32, pad1 : u32, pad2 : u32 }; | |
| 90 | +@group(0) @binding(0) var<storage, read> src : array<f32>; | |
| 91 | +@group(0) @binding(1) var<storage, read_write> dst : array<f32>; | |
| 92 | +@group(0) @binding(2) var<uniform> p : P; | |
| 93 | + | |
| 94 | +@compute @workgroup_size(${wg}) | |
| 95 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 96 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 97 | + if (i >= p.n) { return; } | |
| 98 | + let x = src[i]; | |
| 99 | + dst[i] = x / (1.0 + exp(-x)); | |
| 100 | +}`; | |
| 101 | +} |
added js/kernels.nn.wgsl.js +224 −0
| @@ -0,0 +1,224 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · shaders WGSL de las operaciones de red: norm, rope, softmax, swiglu. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// Las cuatro son iguales en los dos tipos de bloque de qwen35, así que sirven | |
| 6 | +// pase lo que pase con el resto del forward. | |
| 7 | +// | |
| 8 | +// Las cuatro comparten además un patrón de fallo: un error de indexado que | |
| 9 | +// PRESERVA la forma y la escala. No petan, no dan NaN, y el modelo genera texto | |
| 10 | +// gramatical e incoherente. Solo se ven comparando contra una referencia. Por eso | |
| 11 | +// cada una lleva aquí escrito qué es lo que se rompe en silencio: | |
| 12 | +// · rmsnorm → acumular en f16: el acumulador se estanca o desborda a inf y la | |
| 13 | +// fila sale entera a cero. | |
| 14 | +// · rope → confundir NEOX con NORM: el par de rotación son elementos | |
| 15 | +// distintos. Texto fluido que se degrada al crecer el contexto. | |
| 16 | +// · softmax → no restar el máximo: exp() desborda con logits > 88. | |
| 17 | +// · swiglu → intercambiar gate y up: silu(g)·u ≠ silu(u)·g, y la perplejidad | |
| 18 | +// se dispara sin que nada avise. | |
| 19 | +// | |
| 20 | +// WG_SIZE va por SUSTITUCIÓN DE TEXTO y no como `override` a propósito: el | |
| 21 | +// análisis de uniformidad de WGSL exige que el recorrido de un bucle con | |
| 22 | +// barreras sea constante de compilación, y con override no lo es. | |
| 23 | +// | |
| 24 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 25 | + | |
| 26 | +export const ROPE_NORM = 0; // pares adyacentes: x[2p], x[2p+1] | |
| 27 | +export const ROPE_NEOX = 2; // mitad-mitad: x[p], x[p + nDims/2] | |
| 28 | + | |
| 29 | +// Reducción en árbol. La barrera va FUERA del if: si se mete dentro, WGSL lo | |
| 30 | +// rechaza al crear el pipeline (análisis de uniformidad) — que es la forma | |
| 31 | +// amable de fallar. Lo que NINGÚN validador caza es olvidar la barrera WAR al | |
| 32 | +// reutilizar el scratch, y eso sí es una carrera de datos silenciosa. | |
| 33 | +function reduce(op) { | |
| 34 | + return /* wgsl */` | |
| 35 | + scratch[lid.x] = acc; | |
| 36 | + workgroupBarrier(); | |
| 37 | + for (var off = WG >> 1u; off > 0u; off = off >> 1u) { | |
| 38 | + if (lid.x < off) { scratch[lid.x] = ${op}; } | |
| 39 | + workgroupBarrier(); | |
| 40 | + }`; | |
| 41 | +} | |
| 42 | + | |
| 43 | +// y = (x / sqrt(mean(x²) + eps)) · w, por filas. | |
| 44 | +// El epsilon se suma a la MEDIA, dentro de la raíz. Sumarlo fuera es otro | |
| 45 | +// clásico y da un resultado parecido pero distinto. | |
| 46 | +export function rmsnormShader(wg = 128) { | |
| 47 | + return /* wgsl */` | |
| 48 | +const WG : u32 = ${wg}u; | |
| 49 | +struct P { ne0 : u32, rows : u32, eps : f32, pad : u32 }; | |
| 50 | +@group(0) @binding(0) var<storage, read> src : array<f32>; | |
| 51 | +@group(0) @binding(1) var<storage, read> w : array<f32>; | |
| 52 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; | |
| 53 | +@group(0) @binding(3) var<uniform> p : P; | |
| 54 | +var<workgroup> scratch : array<f32, ${wg}>; | |
| 55 | + | |
| 56 | +@compute @workgroup_size(${wg}) | |
| 57 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 58 | + @builtin(local_invocation_id) lid : vec3<u32>) { | |
| 59 | + let row = wid.x + wid.y * 65535u; // dos ejes: uno solo topa en 65535 // uniforme en el workgroup | |
| 60 | + if (row >= p.rows) { return; } | |
| 61 | + let base = row * p.ne0; | |
| 62 | + | |
| 63 | + // Acumulación SIEMPRE en f32. Este bucle tiene salida no uniforme (cada hilo | |
| 64 | + // sale en una iteración distinta), así que aquí dentro no puede haber barreras. | |
| 65 | + var acc : f32 = 0.0; | |
| 66 | + for (var c = lid.x; c < p.ne0; c = c + WG) { | |
| 67 | + let v = src[base + c]; | |
| 68 | + acc = acc + v * v; // v*v, no pow(v, 2.0) | |
| 69 | + } | |
| 70 | +${reduce('scratch[lid.x] + scratch[lid.x + off]')} | |
| 71 | + let scale = inverseSqrt(scratch[0] / f32(p.ne0) + p.eps); | |
| 72 | + | |
| 73 | + for (var c = lid.x; c < p.ne0; c = c + WG) { | |
| 74 | + dst[base + c] = src[base + c] * scale * w[c]; | |
| 75 | + } | |
| 76 | +}`; | |
| 77 | +} | |
| 78 | + | |
| 79 | +// RoPE. theta_scale se calcula en el HOST: en el shader la potencia se | |
| 80 | +// acumularía con el error de pow() y a posiciones grandes eso se nota. | |
| 81 | +// Una fila es una cabeza de longitud ne0; solo se rotan las primeras nDims. | |
| 82 | +export function ropeShader(wg = 64) { | |
| 83 | + return /* wgsl */` | |
| 84 | +const WG : u32 = ${wg}u; | |
| 85 | +struct P { | |
| 86 | + ne0 : u32, rows : u32, heads : u32, nDims : u32, | |
| 87 | + mode : u32, pad0 : u32, pad1 : u32, pad2 : u32, | |
| 88 | + thetaScale : f32, freqScale : f32, pad3 : f32, pad4 : f32, | |
| 89 | +}; | |
| 90 | +@group(0) @binding(0) var<storage, read> src : array<f32>; | |
| 91 | +@group(0) @binding(1) var<storage, read> pos : array<i32>; | |
| 92 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; | |
| 93 | +@group(0) @binding(3) var<uniform> p : P; | |
| 94 | + | |
| 95 | +@compute @workgroup_size(${wg}) | |
| 96 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 97 | + let pairs = p.nDims / 2u; | |
| 98 | + let total = p.rows * pairs; | |
| 99 | + let idx = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 100 | + if (idx >= total) { return; } | |
| 101 | + | |
| 102 | + let row = idx / pairs; // cabeza dentro del token | |
| 103 | + let pair = idx % pairs; | |
| 104 | + let base = row * p.ne0; | |
| 105 | + let token = row / p.heads; // filas ordenadas [cabeza, token] | |
| 106 | + let theta = f32(pos[token]) * p.freqScale * pow(p.thetaScale, f32(pair)); | |
| 107 | + let c = cos(theta); | |
| 108 | + let s = sin(theta); | |
| 109 | + | |
| 110 | + // AQUÍ está la única diferencia entre los dos modos: qué dos posiciones de | |
| 111 | + // memoria forman el par. NORM son adyacentes, NEOX está a media fila. | |
| 112 | + var i0 : u32; | |
| 113 | + var i1 : u32; | |
| 114 | + if (p.mode == ${ROPE_NEOX}u) { i0 = pair; i1 = pair + pairs; } | |
| 115 | + else { i0 = pair * 2u; i1 = pair * 2u + 1u; } | |
| 116 | + | |
| 117 | + let x0 = src[base + i0]; | |
| 118 | + let x1 = src[base + i1]; | |
| 119 | + dst[base + i0] = x0 * c - x1 * s; | |
| 120 | + dst[base + i1] = x0 * s + x1 * c; | |
| 121 | + | |
| 122 | + // Las dimensiones no rotadas se copian tal cual. Solo lo hace el primer par | |
| 123 | + // de cada fila, para no escribir lo mismo desde varios hilos. | |
| 124 | + if (pair == 0u) { | |
| 125 | + for (var i = p.nDims; i < p.ne0; i = i + 1u) { dst[base + i] = src[base + i]; } | |
| 126 | + } | |
| 127 | +}`; | |
| 128 | +} | |
| 129 | + | |
| 130 | +// Softmax por filas con máscara causal calculada EN EL SHADER: materializar una | |
| 131 | +// máscara [n_q × n_kv] es un tensor entero de ancho de banda tirado. | |
| 132 | +// El centinela es finito (-1e30) y no -inf: si una fila quedara entera | |
| 133 | +// enmascarada, con -inf sale NaN; con -1e30 sale una distribución uniforme, que | |
| 134 | +// es raro pero no envenena el resto de la red. | |
| 135 | +export function softmaxShader(wg = 256) { | |
| 136 | + return /* wgsl */` | |
| 137 | +const WG : u32 = ${wg}u; | |
| 138 | +const NEG_BIG : f32 = -1.0e30; | |
| 139 | +struct P { nKv : u32, nQ : u32, nPast : u32, rows : u32, scale : f32, pad0 : f32, pad1 : f32, pad2 : f32 }; | |
| 140 | +@group(0) @binding(0) var<storage, read> src : array<f32>; | |
| 141 | +@group(0) @binding(1) var<storage, read_write> dst : array<f32>; | |
| 142 | +@group(0) @binding(2) var<uniform> p : P; | |
| 143 | +var<workgroup> scratch : array<f32, ${wg}>; | |
| 144 | + | |
| 145 | +@compute @workgroup_size(${wg}) | |
| 146 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 147 | + @builtin(local_invocation_id) lid : vec3<u32>) { | |
| 148 | + let row = wid.x + wid.y * 65535u; // dos ejes: uno solo topa en 65535 | |
| 149 | + if (row >= p.rows) { return; } | |
| 150 | + let base = row * p.nKv; | |
| 151 | + let qAbs = p.nPast + (row % p.nQ); | |
| 152 | + | |
| 153 | + // Recorrido UNIFORME (iters igual para todos) porque hay barreras dentro. | |
| 154 | + let iters = (p.nKv + WG - 1u) / WG; | |
| 155 | + | |
| 156 | + var acc : f32 = NEG_BIG; | |
| 157 | + for (var it = 0u; it < iters; it = it + 1u) { | |
| 158 | + let k = lid.x + it * WG; | |
| 159 | + if (k < p.nKv && k <= qAbs) { acc = max(acc, src[base + k] * p.scale); } | |
| 160 | + } | |
| 161 | +${reduce('max(scratch[lid.x], scratch[lid.x + off])')} | |
| 162 | + let rowMax = scratch[0]; | |
| 163 | + workgroupBarrier(); // WAR: se va a reutilizar scratch | |
| 164 | + | |
| 165 | + acc = 0.0; | |
| 166 | + for (var it = 0u; it < iters; it = it + 1u) { | |
| 167 | + let k = lid.x + it * WG; | |
| 168 | + if (k < p.nKv) { | |
| 169 | + // exp(x - max) ∈ (0,1]: imposible que desborde, en cualquier precisión. | |
| 170 | + let e = select(0.0, exp(src[base + k] * p.scale - rowMax), k <= qAbs); | |
| 171 | + dst[base + k] = e; | |
| 172 | + acc = acc + e; | |
| 173 | + } | |
| 174 | + } | |
| 175 | +${reduce('scratch[lid.x] + scratch[lid.x + off]')} | |
| 176 | + let inv = 1.0 / scratch[0]; | |
| 177 | + | |
| 178 | + for (var it = 0u; it < iters; it = it + 1u) { | |
| 179 | + let k = lid.x + it * WG; | |
| 180 | + if (k < p.nKv) { dst[base + k] = dst[base + k] * inv; } | |
| 181 | + } | |
| 182 | +}`; | |
| 183 | +} | |
| 184 | + | |
| 185 | +// SwiGLU con gate y up en tensores separados, que es como vienen en el GGUF. | |
| 186 | +// silu(gate) · up, en ese orden. Invertirlo no peta y arruina el modelo. | |
| 187 | +export function swigluShader(wg = 256) { | |
| 188 | + return /* wgsl */` | |
| 189 | +const WG : u32 = ${wg}u; | |
| 190 | +struct P { n : u32, pad0 : u32, pad1 : u32, pad2 : u32 }; | |
| 191 | +@group(0) @binding(0) var<storage, read> gate : array<f32>; | |
| 192 | +@group(0) @binding(1) var<storage, read> up : array<f32>; | |
| 193 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; | |
| 194 | +@group(0) @binding(3) var<uniform> p : P; | |
| 195 | + | |
| 196 | +// x/(1+exp(-x)), no x*exp(x)/(1+exp(x)): la segunda forma desborda con x grande. | |
| 197 | +fn silu(x : f32) -> f32 { return x / (1.0 + exp(-x)); } | |
| 198 | + | |
| 199 | +@compute @workgroup_size(${wg}) | |
| 200 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 201 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 202 | + if (i >= p.n) { return; } // sin barreras: el early-return es legal | |
| 203 | + dst[i] = silu(gate[i]) * up[i]; | |
| 204 | +}`; | |
| 205 | +} | |
| 206 | + | |
| 207 | +// Suma elemento a elemento — la cadena residual. Trivial, pero se acumula 24 | |
| 208 | +// veces: en f16 los incrementos pequeños se pierden por absorción. | |
| 209 | +export function addShader(wg = 256) { | |
| 210 | + return /* wgsl */` | |
| 211 | +const WG : u32 = ${wg}u; | |
| 212 | +struct P { n : u32, pad0 : u32, pad1 : u32, pad2 : u32 }; | |
| 213 | +@group(0) @binding(0) var<storage, read> a : array<f32>; | |
| 214 | +@group(0) @binding(1) var<storage, read> b : array<f32>; | |
| 215 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; | |
| 216 | +@group(0) @binding(3) var<uniform> p : P; | |
| 217 | + | |
| 218 | +@compute @workgroup_size(${wg}) | |
| 219 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 220 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 221 | + if (i >= p.n) { return; } | |
| 222 | + dst[i] = a[i] + b[i]; | |
| 223 | +}`; | |
| 224 | +} |
added js/kernels.ssm.wgsl.js +258 −0
| @@ -0,0 +1,258 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · shaders de la capa SSM (gated delta net) de qwen35. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// 18 de cada 24 bloques del modelo son ESTO, no atención. En vez de una caché KV | |
| 6 | +// que crece con el contexto, llevan un estado recurrente de tamaño FIJO: una | |
| 7 | +// matriz de 128×128 por cabeza que se actualiza token a token. Por eso una | |
| 8 | +// cuenta de memoria que tratara todos los bloques como de atención se queda | |
| 9 | +// larga: el estado entero de las 18 capas es una fracción pequeña de lo que | |
| 10 | +// pesa el modelo. | |
| 11 | +// | |
| 12 | +// La regla, por token, cabeza y secuencia (S es el estado, k/q/v los vectores de | |
| 13 | +// la cabeza, g el decaimiento y β la tasa de escritura): | |
| 14 | +// 1. DECAIMIENTO S ← diag(e^g) · S | |
| 15 | +// 2. LECTURA u = v − Sᵀk | |
| 16 | +// 3. DELTA δ = β · u | |
| 17 | +// 4. ESCRITURA S ← S + k δᵀ | |
| 18 | +// 5. SALIDA o = (1/√128) · Sᵀq ← con el S YA actualizado | |
| 19 | +// | |
| 20 | +// Dos órdenes que no son negociables: el decaimiento va ANTES de leer, y la | |
| 21 | +// salida usa el estado DESPUÉS de escribir. Invertir cualquiera de los dos da un | |
| 22 | +// modelo que genera texto y pierde el hilo, sin ningún error. | |
| 23 | +// | |
| 24 | +// El estado se guarda TRASPUESTO, state[j][i] con j = dimensión de value e | |
| 25 | +// i = dimensión de key, para que cada hilo posea una fila contigua. | |
| 26 | +// | |
| 27 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 28 | + | |
| 29 | +export const SSM_HEAD_DIM = 128; // head_k_dim = head_v_dim = ssm_d_state | |
| 30 | +export const SSM_CONV_K = 4; // qwen35.ssm.conv_kernel | |
| 31 | + | |
| 32 | +// L2-norm por filas. OJO: NO es rmsnorm y no comparte fórmula. | |
| 33 | +// rmsnorm: scale = 1 / sqrt(mean(x²) + eps) ← eps DENTRO de la raíz | |
| 34 | +// l2norm: scale = 1 / max(sqrt(sum(x²)), eps) ← eps como SUELO, fuera | |
| 35 | +// Se aplica a q y k del SSM (a v no). Confundirlas da valores parecidos y una | |
| 36 | +// deriva que crece con la profundidad. | |
| 37 | +export function l2normShader(wg = 128) { | |
| 38 | + return /* wgsl */` | |
| 39 | +const WG : u32 = ${wg}u; | |
| 40 | +struct P { ne0 : u32, rows : u32, eps : f32, pad : u32 }; | |
| 41 | +@group(0) @binding(0) var<storage, read> src : array<f32>; | |
| 42 | +@group(0) @binding(1) var<storage, read_write> dst : array<f32>; | |
| 43 | +@group(0) @binding(2) var<uniform> p : P; | |
| 44 | +var<workgroup> scratch : array<f32, ${wg}>; | |
| 45 | + | |
| 46 | +@compute @workgroup_size(${wg}) | |
| 47 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 48 | + @builtin(local_invocation_id) lid : vec3<u32>) { | |
| 49 | + let row = wid.x + wid.y * 65535u; // dos ejes: uno solo topa en 65535 | |
| 50 | + if (row >= p.rows) { return; } | |
| 51 | + let base = row * p.ne0; | |
| 52 | + var acc = 0.0; | |
| 53 | + for (var c = lid.x; c < p.ne0; c = c + WG) { let v = src[base + c]; acc = acc + v * v; } | |
| 54 | + scratch[lid.x] = acc; | |
| 55 | + workgroupBarrier(); | |
| 56 | + for (var off = WG >> 1u; off > 0u; off = off >> 1u) { | |
| 57 | + if (lid.x < off) { scratch[lid.x] = scratch[lid.x] + scratch[lid.x + off]; } | |
| 58 | + workgroupBarrier(); | |
| 59 | + } | |
| 60 | + let scale = 1.0 / max(sqrt(scratch[0]), p.eps); | |
| 61 | + for (var c = lid.x; c < p.ne0; c = c + WG) { dst[base + c] = src[base + c] * scale; } | |
| 62 | +}`; | |
| 63 | +} | |
| 64 | + | |
| 65 | +// Convolución causal DEPTHWISE de kernel 4, sin bias. Cada canal solo ve su | |
| 66 | +// propia fila de pesos: no hay mezcla entre canales. | |
| 67 | +// y[c][t] = Σ_{r=0..3} buf[c][t+r] · W[c][r] | |
| 68 | +// `buf` es la ventana [3+T] por canal: los 3 primeros vienen del estado del | |
| 69 | +// token anterior. r=0 es el más antiguo y r=3 el actual — los pesos van en | |
| 70 | +// orden temporal directo, NO invertidos como en una convolución de libro. | |
| 71 | +export function ssmConvShader(wg = 64) { | |
| 72 | + return /* wgsl */` | |
| 73 | +const WG : u32 = ${wg}u; | |
| 74 | +const K : u32 = ${SSM_CONV_K}u; | |
| 75 | +struct P { channels : u32, tokens : u32, window : u32, pad : u32 }; | |
| 76 | +@group(0) @binding(0) var<storage, read> buf : array<f32>; // [channels][window] | |
| 77 | +@group(0) @binding(1) var<storage, read> w : array<f32>; // [channels][K] | |
| 78 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; // [tokens][channels] | |
| 79 | +@group(0) @binding(3) var<uniform> p : P; | |
| 80 | + | |
| 81 | +@compute @workgroup_size(${wg}) | |
| 82 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 83 | + let idx = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 84 | + let total = p.channels * p.tokens; | |
| 85 | + if (idx >= total) { return; } | |
| 86 | + let c = idx % p.channels; | |
| 87 | + let t = idx / p.channels; | |
| 88 | + var acc = 0.0; | |
| 89 | + for (var r = 0u; r < K; r = r + 1u) { | |
| 90 | + acc = acc + buf[c * p.window + t + r] * w[c * K + r]; | |
| 91 | + } | |
| 92 | + dst[t * p.channels + c] = acc; | |
| 93 | +}`; | |
| 94 | +} | |
| 95 | + | |
| 96 | +// El núcleo: la regla delta con puerta. Un workgroup por cabeza, un hilo por | |
| 97 | +// dimensión de value. Cada hilo posee la fila j del estado (128 f32 contiguos) | |
| 98 | +// y la recorre tres veces por token: leer, escribir, y proyectar la salida. | |
| 99 | +// | |
| 100 | +// El estado vive en un buffer de storage, no en memoria privada: tiene que | |
| 101 | +// sobrevivir entre tokens de todas formas, y meterlo en `private` sería la | |
| 102 | +// matriz entera por workgroup, con riesgo de volcado a memoria. | |
| 103 | +export function gatedDeltaNetShader(headDim = SSM_HEAD_DIM) { | |
| 104 | + return /* wgsl */` | |
| 105 | +const S : u32 = ${headDim}u; | |
| 106 | +struct P { heads : u32, tokens : u32, kvHeads : u32, pad1 : u32, | |
| 107 | + scale : f32, pad2 : f32, pad3 : f32, pad4 : f32 }; | |
| 108 | +@group(0) @binding(0) var<storage, read> q : array<f32>; // [T][H][S] | |
| 109 | +@group(0) @binding(1) var<storage, read> k : array<f32>; // [T][H][S] | |
| 110 | +@group(0) @binding(2) var<storage, read> v : array<f32>; // [T][H][S] | |
| 111 | +@group(0) @binding(3) var<storage, read> g : array<f32>; // [T][H] | |
| 112 | +@group(0) @binding(4) var<storage, read> beta : array<f32>; // [T][H] | |
| 113 | +@group(0) @binding(5) var<storage, read_write> state : array<f32>; // [H][S][S] (j,i) | |
| 114 | +@group(0) @binding(6) var<storage, read_write> out : array<f32>; // [T][H][S] | |
| 115 | +@group(0) @binding(7) var<uniform> p : P; | |
| 116 | + | |
| 117 | +var<workgroup> shk : array<f32, ${headDim}>; | |
| 118 | +var<workgroup> shq : array<f32, ${headDim}>; | |
| 119 | + | |
| 120 | +@compute @workgroup_size(${headDim}) | |
| 121 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 122 | + @builtin(local_invocation_id) lid : vec3<u32>) { | |
| 123 | + let h = wid.x; // cabeza de VALOR | |
| 124 | + if (h >= p.heads) { return; } | |
| 125 | + let j = lid.x; // esta invocación posee la columna j | |
| 126 | + let row = (h * S + j) * S; // inicio de la fila j del estado | |
| 127 | + | |
| 128 | + // GQA DENTRO DEL SSM. Hay más cabezas de valor que de clave: en el 27B son 48 | |
| 129 | + // contra 16, o sea tres cabezas de valor comparten cada q/k. En el 0.8B son | |
| 130 | + // 16 y 16, y por eso asumir que eran iguales funcionaba ahí y solo ahí — el | |
| 131 | + // modelo grande salía con texto plausible y basura. | |
| 132 | + // | |
| 133 | + // Y el reparto es MÓDULO, no división, que es lo contrario de lo que hace la | |
| 134 | + // GQA de la atención. No es un capricho: el checkpoint original guarda las | |
| 135 | + // cabezas de valor AGRUPADAS bajo su cabeza de clave (v0,v1,v2 de k0, luego | |
| 136 | + // las de k1…), pero el conversor a GGUF las repermuta a orden TESELADO | |
| 137 | + // (v0 de k0, v0 de k1, … v1 de k0, …) para que la difusión barata de ggml | |
| 138 | + // valga. Ese reordenado lo lleva TODO lo que va por cabeza de valor: v, z, | |
| 139 | + // alpha, beta, A_log, dt_bias, la parte v de conv1d y las columnas de | |
| 140 | + // out_proj. Se leen tal cual del fichero; lo único que hay que emparejar | |
| 141 | + // aquí es q/k. | |
| 142 | + // · ggml: ggml_repeat / iq1 = iv1 % n_k_heads | |
| 143 | + // · conversor: _LinearAttentionVReorderBase._reorder_v_heads | |
| 144 | + // Dividir en vez de modular da un modelo que genera palabras del contexto en | |
| 145 | + // bucle: cada cabeza lee la clave de otra, y aun así todo tiene la forma | |
| 146 | + // correcta y nada peta. | |
| 147 | + let hk = h % p.kvHeads; | |
| 148 | + | |
| 149 | + // Bucle SECUENCIAL sobre tokens: la recurrencia no se puede paralelizar en t. | |
| 150 | + for (var t = 0u; t < p.tokens; t = t + 1u) { | |
| 151 | + let vv = (t * p.heads + h) * S; // v, g, beta y la salida van por cabeza de VALOR | |
| 152 | + let vk = (t * p.kvHeads + hk) * S; // q y k, por cabeza de CLAVE | |
| 153 | + shk[j] = k[vk + j]; | |
| 154 | + shq[j] = q[vk + j]; | |
| 155 | + workgroupBarrier(); | |
| 156 | + | |
| 157 | + let gv = exp(g[t * p.heads + h]); | |
| 158 | + let bv = beta[t * p.heads + h]; | |
| 159 | + | |
| 160 | + // Sᵀk con el estado VIEJO. El decaimiento se saca fuera del sumatorio: | |
| 161 | + // g·(Sᵀk) = (g·S)ᵀk, así se ahorra una pasada y es idéntico. | |
| 162 | + var kv = 0.0; | |
| 163 | + for (var i = 0u; i < S; i = i + 1u) { kv = kv + state[row + i] * shk[i]; } | |
| 164 | + let delta = (v[vv + j] - gv * kv) * bv; | |
| 165 | + | |
| 166 | + // Decaimiento y escritura en la misma pasada, y de paso la salida con el | |
| 167 | + // estado YA actualizado. | |
| 168 | + var o = 0.0; | |
| 169 | + for (var i = 0u; i < S; i = i + 1u) { | |
| 170 | + let s = gv * state[row + i] + shk[i] * delta; | |
| 171 | + state[row + i] = s; | |
| 172 | + o = o + s * shq[i]; | |
| 173 | + } | |
| 174 | + out[vv + j] = o * p.scale; | |
| 175 | + workgroupBarrier(); // el token siguiente reescribe shk/shq | |
| 176 | + } | |
| 177 | +}`; | |
| 178 | +} | |
| 179 | + | |
| 180 | +// RMSNorm con puerta: rms(x) · W · silu(z). | |
| 181 | +// El peso se aplica ANTES de multiplicar por silu(z), y silu(z) NO entra en el | |
| 182 | +// cálculo de la media cuadrática. Es rms(x)·W·silu(z), no rms(x·silu(z))·W. | |
| 183 | +export function gatedNormShader(wg = 128) { | |
| 184 | + return /* wgsl */` | |
| 185 | +const WG : u32 = ${wg}u; | |
| 186 | +struct P { ne0 : u32, rows : u32, eps : f32, pad : u32 }; | |
| 187 | +@group(0) @binding(0) var<storage, read> src : array<f32>; | |
| 188 | +@group(0) @binding(1) var<storage, read> w : array<f32>; // [ne0] | |
| 189 | +@group(0) @binding(2) var<storage, read> z : array<f32>; // misma forma que src | |
| 190 | +@group(0) @binding(3) var<storage, read_write> dst : array<f32>; | |
| 191 | +@group(0) @binding(4) var<uniform> p : P; | |
| 192 | +var<workgroup> scratch : array<f32, ${wg}>; | |
| 193 | + | |
| 194 | +@compute @workgroup_size(${wg}) | |
| 195 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 196 | + @builtin(local_invocation_id) lid : vec3<u32>) { | |
| 197 | + let row = wid.x + wid.y * 65535u; // dos ejes: uno solo topa en 65535 | |
| 198 | + if (row >= p.rows) { return; } | |
| 199 | + let base = row * p.ne0; | |
| 200 | + var acc = 0.0; | |
| 201 | + for (var c = lid.x; c < p.ne0; c = c + WG) { let x = src[base + c]; acc = acc + x * x; } | |
| 202 | + scratch[lid.x] = acc; | |
| 203 | + workgroupBarrier(); | |
| 204 | + for (var off = WG >> 1u; off > 0u; off = off >> 1u) { | |
| 205 | + if (lid.x < off) { scratch[lid.x] = scratch[lid.x] + scratch[lid.x + off]; } | |
| 206 | + workgroupBarrier(); | |
| 207 | + } | |
| 208 | + let scale = inverseSqrt(scratch[0] / f32(p.ne0) + p.eps); | |
| 209 | + for (var c = lid.x; c < p.ne0; c = c + WG) { | |
| 210 | + let zc = z[base + c]; | |
| 211 | + dst[base + c] = src[base + c] * scale * w[c] * (zc / (1.0 + exp(-zc))); | |
| 212 | + } | |
| 213 | +}`; | |
| 214 | +} | |
| 215 | + | |
| 216 | +// alpha → g: softplus(alpha + dt_bias) · a. | |
| 217 | +// El softplus de ggml corta en 20: por encima devuelve x tal cual, para no | |
| 218 | +// calcular exp(x) de un número grande. Se replica. | |
| 219 | +// `a` ya viene NEGATIVO en el fichero (guarda −exp(A_log)), así que aquí no se | |
| 220 | +// niega ni se exponencia nada: hacerlo daría un decaimiento explosivo. | |
| 221 | +export function decayGateShader(wg = 64) { | |
| 222 | + return /* wgsl */` | |
| 223 | +const WG : u32 = ${wg}u; | |
| 224 | +struct P { heads : u32, tokens : u32, pad0 : u32, pad1 : u32 }; | |
| 225 | +@group(0) @binding(0) var<storage, read> alpha : array<f32>; // [T][H] | |
| 226 | +@group(0) @binding(1) var<storage, read> dt : array<f32>; // [H] | |
| 227 | +@group(0) @binding(2) var<storage, read> a : array<f32>; // [H], negativo | |
| 228 | +@group(0) @binding(3) var<storage, read_write> dst : array<f32>; // [T][H] | |
| 229 | +@group(0) @binding(4) var<uniform> p : P; | |
| 230 | + | |
| 231 | +fn softplus(x : f32) -> f32 { if (x > 20.0) { return x; } return log(1.0 + exp(x)); } | |
| 232 | + | |
| 233 | +@compute @workgroup_size(${wg}) | |
| 234 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 235 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 236 | + if (i >= p.heads * p.tokens) { return; } | |
| 237 | + let h = i % p.heads; | |
| 238 | + dst[i] = softplus(alpha[i] + dt[h]) * a[h]; | |
| 239 | +}`; | |
| 240 | +} | |
| 241 | + | |
| 242 | +// Sigmoide elemento a elemento — la β del SSM y la puerta de salida de la | |
| 243 | +// atención salen de aquí. | |
| 244 | +export function sigmoidShader(wg = 256) { | |
| 245 | + return /* wgsl */` | |
| 246 | +const WG : u32 = ${wg}u; | |
| 247 | +struct P { n : u32, pad0 : u32, pad1 : u32, pad2 : u32 }; | |
| 248 | +@group(0) @binding(0) var<storage, read> src : array<f32>; | |
| 249 | +@group(0) @binding(1) var<storage, read_write> dst : array<f32>; | |
| 250 | +@group(0) @binding(2) var<uniform> p : P; | |
| 251 | + | |
| 252 | +@compute @workgroup_size(${wg}) | |
| 253 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 254 | + let i = gid.x + gid.y * 65535u * ${wg}u; // dos ejes: uno solo topa en 65535 grupos | |
| 255 | + if (i >= p.n) { return; } | |
| 256 | + dst[i] = 1.0 / (1.0 + exp(-src[i])); | |
| 257 | +}`; | |
| 258 | +} |
added js/kernels.wgsl.js +1142 −0
| @@ -0,0 +1,1142 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · shaders WGSL de pesos cuantizados. Seis tipos. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// La decisión de fondo: los pesos NO se descuantizan en CPU. Se suben tal cual | |
| 6 | +// salen del GGUF y se descuantizan dentro del shader. Eso ahorra la pasada de | |
| 7 | +// CPU, el pico de memoria del doble y, sobre todo, el ancho de banda — que es lo | |
| 8 | +// que limita de verdad un matmul cuantizado. | |
| 9 | +// | |
| 10 | +// El precio es el layout: un bloque Q8_0 son 34 bytes (escala f16 + 32 int8) y | |
| 11 | +// en WGSL un storage buffer se lee como array<u32>. Como 34·i alterna resto 0 y | |
| 12 | +// 2 al dividir por 4, la mitad de los bloques NO empieza en palabra. Se ataca | |
| 13 | +// combinando dos palabras con desplazamientos, igual que llama.cpp. | |
| 14 | +// | |
| 15 | +// Una nota buena: 34·i SIEMPRE es par, así que la escala f16 nunca cruza la | |
| 16 | +// frontera de palabra — basta una carga y un desplazamiento de 0 o 16 bits. Y | |
| 17 | +// `unpack2x16float` es del NÚCLEO de WGSL, así que convertir f16→f32 no | |
| 18 | +// necesita la extensión shader-f16. | |
| 19 | +// | |
| 20 | +// ── Por qué hay UN andamio y seis descodificadores ────────────────────────── | |
| 21 | +// Los seis tipos comparten TODO menos la descodificación: mismo reparto de filas | |
| 22 | +// en dos ejes, mismo teselado de tokens, misma reducción en árbol. Escribir seis | |
| 23 | +// matmuls sería mantener seis veces la misma reducción y que se desincronicen. | |
| 24 | +// Aquí el andamio (`matmulShader`/`dequantShader`) es común y cada tipo aporta | |
| 25 | +// solo un `decode(emit)` que va sacando (índice dentro del bloque, valor). El | |
| 26 | +// andamio decide qué hacer con cada valor: acumularlo contra las activaciones | |
| 27 | +// (matmul) o escribirlo (dequant). | |
| 28 | +// | |
| 29 | +// El orden de las operaciones aritméticas es el de ggml, a propósito: `d1·q − m1` | |
| 30 | +// y no `d·(sc·q − …)`. No es superstición — cambiarlo mueve el último bit y el | |
| 31 | +// test de igualdad exacta contra la referencia deja de poder ser exacto. | |
| 32 | +// | |
| 33 | +// Las rejillas de los i-quants viven en `quant-tables.js` porque son parte del | |
| 34 | +// FORMATO, no de este código. | |
| 35 | +// | |
| 36 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 37 | + | |
| 38 | +export const Q8_BLOCK = 32; | |
| 39 | +export const Q8_BLOCK_BYTES = 34; | |
| 40 | + | |
| 41 | +// Tope de workgroups por eje del despacho. NO es una constante de rendimiento: | |
| 42 | +// pasarse es un error de validación. Las filas se reparten en dos ejes porque la | |
| 43 | +// cabeza de salida son 248.320 y aquí topa en 65.535. El shader la necesita para | |
| 44 | +// recomponer el índice, así que vive aquí y `ops.js` la importa: dos copias que | |
| 45 | +// se desincronicen darían filas a cero sin un solo error. | |
| 46 | +export const AXIS = 65535; | |
| 47 | + | |
| 48 | +// ── Helpers compartidos ───────────────────────────────────────────────────── | |
| 49 | +// `w` es el buffer de pesos cuantizados, declarado por quien incluya esto. | |
| 50 | +export const HELPERS = /* wgsl */` | |
| 51 | +// Byte con signo dentro de una palabra: se sube al tope y se baja con | |
| 52 | +// desplazamiento ARITMÉTICO. Es el idiom correcto, no restar 256. | |
| 53 | +fn get_byte_i32(value: u32, index: u32) -> i32 { | |
| 54 | + return bitcast<i32>(((value >> (index * 8u)) & 0xFFu) << 24u) >> 24u; | |
| 55 | +} | |
| 56 | + | |
| 57 | +// Byte sin signo en un offset CUALQUIERA. Una sola palabra basta: un byte nunca | |
| 58 | +// cruza la frontera. | |
| 59 | +fn load_byte(byte_offset: u32) -> u32 { | |
| 60 | + return (w[byte_offset / 4u] >> ((byte_offset & 3u) * 8u)) & 0xFFu; | |
| 61 | +} | |
| 62 | + | |
| 63 | +// Palabra de 32 bits en un offset de bytes CUALQUIERA, combinando dos palabras. | |
| 64 | +// El «& 31u» no es adorno: con shift==0 el desplazamiento sería de 32 bits, que | |
| 65 | +// en WGSL da un valor indeterminado. Enmascarando, ese caso queda en hi<<0 y el | |
| 66 | +// select lo descarta. Es el bug número uno de esta técnica. | |
| 67 | +fn load_u32_at(byte_offset: u32) -> u32 { | |
| 68 | + let word_idx = byte_offset / 4u; | |
| 69 | + let shift = (byte_offset & 3u) * 8u; | |
| 70 | + let lo = w[word_idx]; | |
| 71 | + let hi = w[word_idx + 1u]; | |
| 72 | + return select((lo >> shift) | (hi << ((32u - shift) & 31u)), lo, shift == 0u); | |
| 73 | +} | |
| 74 | + | |
| 75 | +// Media palabra en un offset PAR. Todos los campos de 16 bits de todos los tipos | |
| 76 | +// caen en offsets pares, así que nunca cruzan la frontera de palabra. | |
| 77 | +fn load_u16_at(byte_offset: u32) -> u32 { | |
| 78 | + return (w[byte_offset / 4u] >> ((byte_offset & 2u) * 8u)) & 0xFFFFu; | |
| 79 | +} | |
| 80 | + | |
| 81 | +// Escala f16 → f32, en un offset par. | |
| 82 | +fn load_scale(byte_offset: u32) -> f32 { | |
| 83 | + return unpack2x16float(load_u16_at(byte_offset))[0]; | |
| 84 | +} | |
| 85 | +`; | |
| 86 | + | |
| 87 | +// Helper exclusivo de Q4_K y Q5_K: seis bits de escala y seis de mínimo, | |
| 88 | +// guardados en 12 bytes para ocho sub-bloques. Los cuatro primeros van | |
| 89 | +// enteros; los cuatro últimos toman los cuatro bits bajos de un sitio y los dos | |
| 90 | +// altos de otro. Es la descodificación más fácil de equivocar del formato. | |
| 91 | +const SCALE_MIN_K4 = /* wgsl */` | |
| 92 | +fn scale_min_k4(sbase: u32, j: u32) -> vec2<u32> { | |
| 93 | + if (j < 4u) { | |
| 94 | + return vec2<u32>(load_byte(sbase + j) & 63u, load_byte(sbase + j + 4u) & 63u); | |
| 95 | + } | |
| 96 | + let a = load_byte(sbase + j + 4u); | |
| 97 | + let b = load_byte(sbase + j - 4u); | |
| 98 | + let c = load_byte(sbase + j); | |
| 99 | + return vec2<u32>((a & 0xFu) | ((b >> 6u) << 4u), (a >> 4u) | ((c >> 6u) << 4u)); | |
| 100 | +} | |
| 101 | +`; | |
| 102 | + | |
| 103 | +// ── Descodificadores por tipo ─────────────────────────────────────────────── | |
| 104 | +// Cada uno recibe `emit(idxExpr, valExpr)` y devuelve WGSL. Dentro del cuerpo | |
| 105 | +// hay dos nombres dados por el andamio: `blk` (offset en bytes del bloque) y el | |
| 106 | +// índice que emite cada valor, relativo al bloque. | |
| 107 | + | |
| 108 | +const DECODERS = { | |
| 109 | + // Sin cuantizar. No es un caso hipotético: llama.cpp deja en f32 o f16 los | |
| 110 | + // tensores cuyo ne[0] no es múltiplo de 256, y basta UNA proyección así para | |
| 111 | + // que el modelo no cargue. Aquí el «bloque» es el propio elemento, y el resto | |
| 112 | + // del andamio (reparto de filas, teselado, reducción) no se entera. | |
| 113 | + F32: { | |
| 114 | + blockElems: 1, | |
| 115 | + blockBytes: 4, | |
| 116 | + helpers: '', | |
| 117 | + decode: (emit) => ` | |
| 118 | +${emit('0u', 'bitcast<f32>(w[blk / 4u])')}`, | |
| 119 | + }, | |
| 120 | + | |
| 121 | + F16: { | |
| 122 | + blockElems: 2, | |
| 123 | + blockBytes: 4, | |
| 124 | + helpers: '', | |
| 125 | + decode: (emit) => ` | |
| 126 | + let pair = unpack2x16float(w[blk / 4u]); | |
| 127 | +${emit('0u', 'pair.x')} | |
| 128 | +${emit('1u', 'pair.y')}`, | |
| 129 | + }, | |
| 130 | + | |
| 131 | + // BF16 — la conversion mas barata que existe: los 16 bits de un bfloat16 SON | |
| 132 | + // la mitad alta de un f32, asi que basta desplazarlos y reinterpretar. Ni | |
| 133 | + // tabla ni aritmetica de exponentes. | |
| 134 | + // | |
| 135 | + // Se lee de dos en dos, como F16, porque el almacen es `array<u32>` y una | |
| 136 | + // palabra trae dos pesos. El de indice 0 esta en la mitad BAJA (little-endian). | |
| 137 | + // | |
| 138 | + // Hace falta para los modelos ternarios: dejan el camino recurrente del SSM | |
| 139 | + // en mas precision que el resto, y ahi es donde aparece este tipo. | |
| 140 | + BF16: { | |
| 141 | + blockElems: 2, | |
| 142 | + blockBytes: 4, | |
| 143 | + helpers: '', | |
| 144 | + decode: (emit) => ` | |
| 145 | + let par = w[blk / 4u]; | |
| 146 | +${emit('0u', 'bitcast<f32>(par << 16u)')} | |
| 147 | +${emit('1u', 'bitcast<f32>(par & 0xFFFF0000u)')}`, | |
| 148 | + }, | |
| 149 | + | |
| 150 | + // 32 pesos, 34 bytes: escala f16 + 32 enteros de 8 bits con signo. | |
| 151 | + Q8_0: { | |
| 152 | + blockElems: Q8_BLOCK, | |
| 153 | + blockBytes: Q8_BLOCK_BYTES, | |
| 154 | + helpers: '', | |
| 155 | + // La escala se saca FUERA del bucle: (Σ q·x)·d en vez de Σ (q·d)·x sería | |
| 156 | + // aún mejor, pero rompería el contrato de `emit`, que entrega valores ya | |
| 157 | + // escalados. Se paga una multiplicación por peso y se gana un andamio único. | |
| 158 | + decode: (emit) => /* wgsl */` | |
| 159 | + let d = load_scale(blk); | |
| 160 | + for (var i = 0u; i < 8u; i = i + 1u) { | |
| 161 | + let q = load_u32_at(blk + 2u + i * 4u); | |
| 162 | + for (var c = 0u; c < 4u; c = c + 1u) { | |
| 163 | +${emit('i * 4u + c', 'f32(get_byte_i32(q, c)) * d')} | |
| 164 | + } | |
| 165 | + }`, | |
| 166 | + }, | |
| 167 | + | |
| 168 | + // 256 pesos, 84 bytes: 16 escalas/mínimos de 4+4 bits, 64 bytes de 2 bits, | |
| 169 | + // y d/dmin al FINAL del bloque (no al principio, como en Q4_K/Q5_K). | |
| 170 | + Q2_K: { | |
| 171 | + blockElems: 256, | |
| 172 | + blockBytes: 84, | |
| 173 | + helpers: '', | |
| 174 | + decode: (emit) => /* wgsl */` | |
| 175 | + let d = load_scale(blk + 80u); | |
| 176 | + let dmin = load_scale(blk + 82u); | |
| 177 | + for (var n = 0u; n < 2u; n = n + 1u) { | |
| 178 | + let qbase = blk + 16u + n * 32u; | |
| 179 | + for (var j = 0u; j < 4u; j = j + 1u) { | |
| 180 | + // El mismo byte de quants se lee CUATRO veces, dos bits cada vez: | |
| 181 | + // j no elige el byte, elige el desplazamiento dentro del byte. | |
| 182 | + let shift = j * 2u; | |
| 183 | + let sca = load_byte(blk + n * 8u + j * 2u); | |
| 184 | + let scb = load_byte(blk + n * 8u + j * 2u + 1u); | |
| 185 | + let dl1 = d * f32(sca & 0xFu); let ml1 = dmin * f32(sca >> 4u); | |
| 186 | + let dl2 = d * f32(scb & 0xFu); let ml2 = dmin * f32(scb >> 4u); | |
| 187 | + let obase = n * 128u + j * 32u; | |
| 188 | + for (var l = 0u; l < 4u; l = l + 1u) { | |
| 189 | + let wa = w[(qbase + l * 4u) / 4u]; | |
| 190 | + let wb = w[(qbase + 16u + l * 4u) / 4u]; | |
| 191 | + for (var c = 0u; c < 4u; c = c + 1u) { | |
| 192 | +${emit('obase + l * 4u + c', 'dl1 * f32((wa >> (c * 8u + shift)) & 3u) - ml1')} | |
| 193 | +${emit('obase + 16u + l * 4u + c', 'dl2 * f32((wb >> (c * 8u + shift)) & 3u) - ml2')} | |
| 194 | + } | |
| 195 | + } | |
| 196 | + } | |
| 197 | + }`, | |
| 198 | + }, | |
| 199 | + | |
| 200 | + // 256 pesos, 144 bytes: d/dmin f16, 12 bytes de escalas de 6 bits, 128 bytes | |
| 201 | + // de nibbles. Los nibbles bajos son la primera mitad de cada grupo de 64 y los | |
| 202 | + // altos la segunda: NO alternan peso a peso. | |
| 203 | + Q4_K: { | |
| 204 | + blockElems: 256, | |
| 205 | + blockBytes: 144, | |
| 206 | + helpers: SCALE_MIN_K4, | |
| 207 | + decode: (emit) => /* wgsl */` | |
| 208 | + let d = load_scale(blk); | |
| 209 | + let dmin = load_scale(blk + 2u); | |
| 210 | + for (var j = 0u; j < 4u; j = j + 1u) { | |
| 211 | + let sm1 = scale_min_k4(blk + 4u, j * 2u); | |
| 212 | + let sm2 = scale_min_k4(blk + 4u, j * 2u + 1u); | |
| 213 | + let d1 = d * f32(sm1.x); let m1 = dmin * f32(sm1.y); | |
| 214 | + let d2 = d * f32(sm2.x); let m2 = dmin * f32(sm2.y); | |
| 215 | + let qbase = blk + 16u + j * 32u; | |
| 216 | + let obase = j * 64u; | |
| 217 | + for (var l = 0u; l < 8u; l = l + 1u) { | |
| 218 | + let ql = w[(qbase + l * 4u) / 4u]; | |
| 219 | + for (var c = 0u; c < 4u; c = c + 1u) { | |
| 220 | + let q = (ql >> (c * 8u)) & 0xFFu; | |
| 221 | +${emit('obase + l * 4u + c', 'd1 * f32(q & 0xFu) - m1')} | |
| 222 | +${emit('obase + 32u + l * 4u + c', 'd2 * f32(q >> 4u) - m2')} | |
| 223 | + } | |
| 224 | + } | |
| 225 | + }`, | |
| 226 | + }, | |
| 227 | + | |
| 228 | + // 256 pesos, 210 bytes. El que desbloquea las mezclas estándar: Q4_K_M, | |
| 229 | + // Q5_K_M y compañía ponen la salida y el embedding en Q6_K, así que SIN este | |
| 230 | + // kernel no carga ni un fichero k-quant de los que publica todo el mundo — | |
| 231 | + // aunque el resto de sus tensores sí tenga kernel. | |
| 232 | + // | |
| 233 | + // Tres diferencias con Q4_K/Q5_K, y las tres importan: | |
| 234 | + // | |
| 235 | + // · 210 NO es múltiplo de 4, así que los bloques quedan desalineados y hay | |
| 236 | + // que leer con `load_byte`/`load_scale`, no con `w[(blk + x) / 4u]` como | |
| 237 | + // hacen sus hermanos. Usar la forma alineada da pesos de otro bloque. | |
| 238 | + // · las escalas son de 8 bits CON SIGNO. Sin signo el modelo carga y genera | |
| 239 | + // texto degenerado, que es mucho peor que un error. | |
| 240 | + // · no hay mínimo: el valor es `d·escala·(q − 32)` y el −32 es entero, así | |
| 241 | + // que no se usa la forma `d·q − m`. | |
| 242 | + // | |
| 243 | + // Dentro de cada mitad de 128 pesos, los cuatro que comparten un byte de `qh` | |
| 244 | + // van a 0, 32, 64 y 96 del destino con escalas is+0, is+2, is+4, is+6. | |
| 245 | + Q6_K: { | |
| 246 | + blockElems: 256, | |
| 247 | + blockBytes: 210, | |
| 248 | + helpers: /* wgsl */` | |
| 249 | +fn load_i8_at(byte_offset: u32) -> i32 { | |
| 250 | + let b = i32(load_byte(byte_offset)); | |
| 251 | + return select(b, b - 256, b > 127); | |
| 252 | +} | |
| 253 | +`, | |
| 254 | + // ⚠️ POR QUÉ ESTO LEE PALABRAS Y NO BYTES, que es la diferencia entre | |
| 255 | + // «correcto» y «usable»: | |
| 256 | + // | |
| 257 | + // La primera versión leía byte a byte con `load_byte`, y lo justifiqué | |
| 258 | + // diciendo que Q6_K solo aparece en unos pocos tensores y no es camino | |
| 259 | + // caliente. **Era falso.** En una mezcla Q4_K_M real, Q6_K es el 38 % del | |
| 260 | + // fichero: el embedding (que también es la proyección de salida) y el | |
| 261 | + // `ffn_down` de TODAS las capas — o sea camino caliente en cada token y en | |
| 262 | + // cada posición del prompt. Medido con un 4B, el prefill caía a ~1/30 del | |
| 263 | + // de un modelo con Q8_0, y el banco lo cazó porque el prefill dejaba de ir | |
| 264 | + // más rápido que la generación, que es imposible si procesa en bloque. | |
| 265 | + // | |
| 266 | + // Ahora cada vuelta trae CUATRO pesos con tres lecturas de 32 bits en vez | |
| 267 | + // de doce de un byte, y las cuatro escalas salen del bucle interno: `is` | |
| 268 | + // solo cambia cada 16 posiciones, así que dentro de un grupo de 4 es | |
| 269 | + // constante. De 128 lecturas de escala por bloque se baja a 32. | |
| 270 | + // | |
| 271 | + // `load_u32_at` sigue siendo obligatorio —no `w[(blk + x) / 4u]`— porque | |
| 272 | + // 210 bytes no es múltiplo de 4 y el bloque arranca desalineado la mitad de | |
| 273 | + // las veces. | |
| 274 | + decode: (emit) => /* wgsl */` | |
| 275 | + let d = load_scale(blk + 208u); | |
| 276 | + for (var n = 0u; n < 2u; n = n + 1u) { | |
| 277 | + let qlb = blk + n * 64u; | |
| 278 | + let qhb = blk + 128u + n * 32u; | |
| 279 | + let scb = blk + 192u + n * 8u; | |
| 280 | + let obase = n * 128u; | |
| 281 | + for (var l4 = 0u; l4 < 32u; l4 = l4 + 4u) { | |
| 282 | + let is = l4 >> 4u; | |
| 283 | + let d1 = d * f32(load_i8_at(scb + is)); | |
| 284 | + let d2 = d * f32(load_i8_at(scb + is + 2u)); | |
| 285 | + let d3 = d * f32(load_i8_at(scb + is + 4u)); | |
| 286 | + let d4 = d * f32(load_i8_at(scb + is + 6u)); | |
| 287 | + let w0 = load_u32_at(qlb + l4); | |
| 288 | + let w32 = load_u32_at(qlb + 32u + l4); | |
| 289 | + let wh = load_u32_at(qhb + l4); | |
| 290 | + for (var c = 0u; c < 4u; c = c + 1u) { | |
| 291 | + let sh = c * 8u; | |
| 292 | + let lo0 = (w0 >> sh) & 0xFFu; | |
| 293 | + let lo32 = (w32 >> sh) & 0xFFu; | |
| 294 | + let h = (wh >> sh) & 0xFFu; | |
| 295 | + let q1 = i32((lo0 & 0xFu) | (((h >> 0u) & 3u) << 4u)) - 32; | |
| 296 | + let q2 = i32((lo32 & 0xFu) | (((h >> 2u) & 3u) << 4u)) - 32; | |
| 297 | + let q3 = i32((lo0 >> 4u) | (((h >> 4u) & 3u) << 4u)) - 32; | |
| 298 | + let q4 = i32((lo32 >> 4u) | (((h >> 6u) & 3u) << 4u)) - 32; | |
| 299 | +${emit('obase + l4 + c', 'd1 * f32(q1)')} | |
| 300 | +${emit('obase + 32u + l4 + c', 'd2 * f32(q2)')} | |
| 301 | +${emit('obase + 64u + l4 + c', 'd3 * f32(q3)')} | |
| 302 | +${emit('obase + 96u + l4 + c', 'd4 * f32(q4)')} | |
| 303 | + } | |
| 304 | + } | |
| 305 | + }`, | |
| 306 | + }, | |
| 307 | + | |
| 308 | + // 256 pesos, 176 bytes: como Q4_K más 32 bytes con el quinto bit. El bit que | |
| 309 | + // le toca a cada peso avanza DOS posiciones por grupo de 64 (u1 <<= 2). | |
| 310 | + Q5_K: { | |
| 311 | + blockElems: 256, | |
| 312 | + blockBytes: 176, | |
| 313 | + helpers: SCALE_MIN_K4, | |
| 314 | + decode: (emit) => /* wgsl */` | |
| 315 | + let d = load_scale(blk); | |
| 316 | + let dmin = load_scale(blk + 2u); | |
| 317 | + for (var j = 0u; j < 4u; j = j + 1u) { | |
| 318 | + let sm1 = scale_min_k4(blk + 4u, j * 2u); | |
| 319 | + let sm2 = scale_min_k4(blk + 4u, j * 2u + 1u); | |
| 320 | + let d1 = d * f32(sm1.x); let m1 = dmin * f32(sm1.y); | |
| 321 | + let d2 = d * f32(sm2.x); let m2 = dmin * f32(sm2.y); | |
| 322 | + let u1 = 1u << (j * 2u); | |
| 323 | + let u2 = 2u << (j * 2u); | |
| 324 | + let qbase = blk + 48u + j * 32u; | |
| 325 | + let obase = j * 64u; | |
| 326 | + for (var l = 0u; l < 8u; l = l + 1u) { | |
| 327 | + let ql = w[(qbase + l * 4u) / 4u]; | |
| 328 | + let qh = w[(blk + 16u + l * 4u) / 4u]; | |
| 329 | + for (var c = 0u; c < 4u; c = c + 1u) { | |
| 330 | + let lo = (ql >> (c * 8u)) & 0xFFu; | |
| 331 | + let hi = (qh >> (c * 8u)) & 0xFFu; | |
| 332 | + let a = (lo & 0xFu) + select(0u, 16u, (hi & u1) != 0u); | |
| 333 | + let b = (lo >> 4u) + select(0u, 16u, (hi & u2) != 0u); | |
| 334 | +${emit('obase + l * 4u + c', 'd1 * f32(a) - m1')} | |
| 335 | +${emit('obase + 32u + l * 4u + c', 'd2 * f32(b) - m2')} | |
| 336 | + } | |
| 337 | + } | |
| 338 | + }`, | |
| 339 | + }, | |
| 340 | + | |
| 341 | + // 256 pesos, 66 bytes. Cada 32 pesos: dos palabras. La primera son cuatro | |
| 342 | + // índices de 8 bits a una rejilla de 256 octetos; la segunda, cuatro paquetes | |
| 343 | + // de 7 bits de signos más 4 bits de escala local en el tope. | |
| 344 | + IQ2_XXS: { | |
| 345 | + blockElems: 256, | |
| 346 | + blockBytes: 66, | |
| 347 | + table: 'IQ2XXS', | |
| 348 | + helpers: '', | |
| 349 | + decode: (emit) => /* wgsl */` | |
| 350 | + let d = load_scale(blk); | |
| 351 | + for (var ib = 0u; ib < 8u; ib = ib + 1u) { | |
| 352 | + let a0 = load_u32_at(blk + 2u + ib * 8u); | |
| 353 | + let a1 = load_u32_at(blk + 6u + ib * 8u); | |
| 354 | + let db = d * (0.5 + f32(a1 >> 28u)) * 0.25; | |
| 355 | + for (var l = 0u; l < 4u; l = l + 1u) { | |
| 356 | + let gi = (a0 >> (l * 8u)) & 0xFFu; | |
| 357 | + // ggml guarda una tabla de 128 bytes de signos; es exactamente el | |
| 358 | + // índice completado a paridad PAR, así que se calcula en vez de subirla. | |
| 359 | + let bits = (a1 >> (l * 7u)) & 127u; | |
| 360 | + let signs = bits | ((countOneBits(bits) & 1u) << 7u); | |
| 361 | + let g0 = tbl[gi * 2u]; | |
| 362 | + let g1 = tbl[gi * 2u + 1u]; | |
| 363 | + let obase = ib * 32u + l * 8u; | |
| 364 | + for (var j = 0u; j < 8u; j = j + 1u) { | |
| 365 | + let gw = select(g0, g1, j >= 4u); | |
| 366 | + let gv = f32((gw >> ((j & 3u) * 8u)) & 0xFFu); | |
| 367 | + let sg = select(1.0, -1.0, (signs & (1u << j)) != 0u); | |
| 368 | +${emit('obase + j', 'db * gv * sg')} | |
| 369 | + } | |
| 370 | + } | |
| 371 | + }`, | |
| 372 | + }, | |
| 373 | + | |
| 374 | + // 256 pesos, 50 bytes. Cada 32 pesos: cuatro índices de 11 bits (8 en `qs`, | |
| 375 | + // 3 en `qh`) a una rejilla de 2048 octetos de valores en {-1,0,1}, más una | |
| 376 | + // escala local de 3 bits y un signo que decide el desplazamiento ±1/8. | |
| 377 | + // PQ2_0 — ternario en ranuras de 2 bits, bloque de 128. Tampoco es un tipo de | |
| 378 | + // llama.cpp. 34 bytes: escala f16 + 32 de cuantizacion. | |
| 379 | + // | |
| 380 | + // ESTE es el formato que encaja con este kernel, y no por el tamaño —ocupa MAS | |
| 381 | + // que el de base 3— sino por como reparte. 128 pesos a 2 bits son 32 bytes | |
| 382 | + // EXACTOS y, con subgrupos de 32 carriles, toca un byte por carril: una carga, | |
| 383 | + // sin etapas y sin divergencia. Y los cuatro pesos de cada carril son | |
| 384 | + // CONSECUTIVOS, asi que sus activaciones entran en una lectura vec4. | |
| 385 | + // | |
| 386 | + // Comparado con IQ1_S, que por bloque hace tres cargas de peso mas DOS | |
| 387 | + // lecturas dispersas de una tabla de rejilla indexada por carril. Aqui el peso | |
| 388 | + // sale de un desplazamiento y una mascara: no hay tabla que leer. | |
| 389 | + // | |
| 390 | + // PTQ1_0 no sirve para esto aunque ocupe menos: guarda cinco trits por byte | |
| 391 | + // en etapas de tamaños distintos (16, 8, y los dos bytes de qh), lo que parte | |
| 392 | + // los 32 carriles en tres caminos con direcciones distintas. | |
| 393 | + PQ2_0: { | |
| 394 | + blockElems: 128, | |
| 395 | + blockBytes: 34, | |
| 396 | + helpers: '', | |
| 397 | + decode: (emit) => /* wgsl */` | |
| 398 | + let d = load_scale(blk); | |
| 399 | + for (var i = 0u; i < 32u; i = i + 1u) { | |
| 400 | + let by = load_byte(blk + 2u + i); | |
| 401 | + for (var c = 0u; c < 4u; c = c + 1u) { | |
| 402 | +${emit('i * 4u + c', 'f32(i32((by >> (c * 2u)) & 3u) - 1) * d')} | |
| 403 | + } | |
| 404 | + }`, | |
| 405 | + // Reparto por carril: el carril `sl` se queda el byte `sl`, que son sus | |
| 406 | + // cuatro pesos. Una carga de peso por carril y por bloque. | |
| 407 | + decodeCarril: (emit, xv = false) => /* wgsl */` | |
| 408 | + let d = load_scale(blk); | |
| 409 | + let by = load_byte(blk + 2u + sl); | |
| 410 | + let obase = sl * 4u; | |
| 411 | +${xv ? ` // Los 4 pesos del carril son consecutivos y obase es multiplo de 4, igual | |
| 412 | + // que k0 = b*128 y toda k del decode: caben en UNA lectura vectorial. | |
| 413 | + let xb = (base_t * params.k${globalThis.__ELFFUSS_X_FIJA === true ? '' : ' + k0 + obase'}) >> 2u; | |
| 414 | + let xv0 = x[xb];` : ''} | |
| 415 | +${Array.from({ length: 4 }, (_, j) => ` { | |
| 416 | +${emit(`obase + ${j}u`, `f32(i32((by >> ${j * 2}u) & 3u) - 1) * d`, j)} | |
| 417 | + }`).join('\n')}`, | |
| 418 | + }, | |
| 419 | + | |
| 420 | + // PTQ1_0 — ternario en base 3, bloque de 128. NO es un tipo de llama.cpp: | |
| 421 | + // lo define un fork de terceros. 28 bytes: qs[24] · qh[2] · escala f16. | |
| 422 | + // | |
| 423 | + // LA DIFERENCIA QUE IMPORTA, y no es el tamaño: NO HAY CODEBOOK. En IQ1_S el | |
| 424 | + // peso sale de una tabla de rejilla indexada por carril —dos lecturas | |
| 425 | + // dependientes y dispersas por bloque— y aquí sale de multiplicar un byte por | |
| 426 | + // una potencia de tres y mirarle los bits de arriba. Cero lecturas de tabla. | |
| 427 | + // | |
| 428 | + // El formato mete CINCO trits en un byte (3^5 = 243 <= 256) con el truco | |
| 429 | + // de siempre: al codificar se escala a 256/243 y al descodificar se recupera | |
| 430 | + // con `(q * pow3[n] * 3) >> 8`, donde el producto por la potencia va en | |
| 431 | + // aritmetica de OCHO bits y envuelve a proposito. | |
| 432 | + // | |
| 433 | + // El orden de salida NO es el de los bytes: por cada grupo, primero los 16 (u | |
| 434 | + // 8) pesos de la potencia 0, luego los de la potencia 1, etc. Las etapas son | |
| 435 | + // {32,16,8} y con qs de 24 bytes dan dos grupos —16 y 8—, o sea 80 + 40 | |
| 436 | + // valores, mas 8 que salen de qh. Total 128. | |
| 437 | + // | |
| 438 | + // VALIDADO CONTRA UN TERCERO, no contra si mismo: este mismo esquema con los | |
| 439 | + // parametros de TQ1_0 (qs de 48 bytes) se reduce al «32 y luego 16» de | |
| 440 | + // upstream, y da 16.384 valores IDENTICOS BIT A BIT a los de gguf-py. La ida | |
| 441 | + // y vuelta contra uno mismo no habria distinguido un orden mal entendido. | |
| 442 | + PTQ1_0: { | |
| 443 | + blockElems: 128, | |
| 444 | + blockBytes: 28, | |
| 445 | + helpers: '', | |
| 446 | + // `blk` aqui SI esta alineado a 4 (28 es multiplo de 4), al reves que IQ1_S. | |
| 447 | + decode: (emit) => /* wgsl */` | |
| 448 | + let d = load_scale(blk + 26u); | |
| 449 | + var p3 = 1u; | |
| 450 | + for (var n = 0u; n < 5u; n = n + 1u) { | |
| 451 | + for (var m = 0u; m < 16u; m = m + 1u) { | |
| 452 | + let q = (load_byte(blk + m) * p3) & 0xFFu; | |
| 453 | +${emit('n * 16u + m', 'f32(i32((q * 3u) >> 8u) - 1) * d')} | |
| 454 | + } | |
| 455 | + p3 = p3 * 3u; | |
| 456 | + } | |
| 457 | + p3 = 1u; | |
| 458 | + for (var n = 0u; n < 5u; n = n + 1u) { | |
| 459 | + for (var m = 0u; m < 8u; m = m + 1u) { | |
| 460 | + let q = (load_byte(blk + 16u + m) * p3) & 0xFFu; | |
| 461 | +${emit('80u + n * 8u + m', 'f32(i32((q * 3u) >> 8u) - 1) * d')} | |
| 462 | + } | |
| 463 | + p3 = p3 * 3u; | |
| 464 | + } | |
| 465 | + p3 = 1u; | |
| 466 | + for (var n = 0u; n < 4u; n = n + 1u) { | |
| 467 | + for (var h = 0u; h < 2u; h = h + 1u) { | |
| 468 | + let q = (load_byte(blk + 24u + h) * p3) & 0xFFu; | |
| 469 | +${emit('120u + n * 2u + h', 'f32(i32((q * 3u) >> 8u) - 1) * d')} | |
| 470 | + } | |
| 471 | + p3 = p3 * 3u; | |
| 472 | + }`, | |
| 473 | + | |
| 474 | + // REPARTO POR CARRIL. Cuesta mas que en PQ2_0 y lo pagan las direcciones: | |
| 475 | + // alli 128 pesos a 2 bits son 32 bytes JUSTOS y toca un byte por carril; aqui | |
| 476 | + // el formato va en tres etapas de tamaños distintos —16 bytes, luego 8, y | |
| 477 | + // aparte los dos de `qh`— asi que los carriles caen en tres sitios. | |
| 478 | + // | |
| 479 | + // Se resuelve con ARITMETICA y no con ramas, para que los 32 carriles emitan | |
| 480 | + // las mismas instrucciones y solo cambien los numeros. Cada carril se queda | |
| 481 | + // 4 pesos consecutivos (obase = 4*sl), que es lo que permite la lectura vec4 | |
| 482 | + // de activaciones, y los saca de UNA palabra de 32 bits: | |
| 483 | + // · carriles 0-19 -> 4 bytes seguidos de qs[0..15], una sola potencia | |
| 484 | + // · carriles 20-29 -> 4 bytes seguidos de qs[16..23], una sola potencia | |
| 485 | + // · carriles 30-31 -> los dos bytes de qh, con DOS potencias | |
| 486 | + // El ultimo caso es el que ensucia: los demas leen cuatro bytes distintos con | |
| 487 | + // la misma potencia y estos leen dos bytes alternos con potencias que cambian | |
| 488 | + // a mitad. De ahi que el techo aqui sea peor que en PQ2_0 aunque el fichero | |
| 489 | + // ocupe menos. | |
| 490 | + // | |
| 491 | + // Las tres direcciones se calculan siempre y `select` elige: en WGSL los dos | |
| 492 | + // brazos de un select se evaluan igual, asi que `sl - 20u` da la vuelta en | |
| 493 | + // los carriles bajos. No importa — ese valor no llega a usarse como | |
| 494 | + // direccion, solo el elegido. | |
| 495 | + decodeCarril: (emit, xv = false) => /* wgsl */` | |
| 496 | + let d = load_scale(blk + 26u); | |
| 497 | + let obase = sl * 4u; | |
| 498 | + // Base de la palabra que le toca a este carril. | |
| 499 | + let baseG = select( | |
| 500 | + select(blk + 24u, blk + 16u + ((sl - 20u) & 1u) * 4u, sl < 30u), | |
| 501 | + blk + (sl & 3u) * 4u, sl < 20u); | |
| 502 | + let w4 = load_u32_at(baseG); | |
| 503 | + // Potencia de tres del carril (para los carriles de qh cambia por peso). | |
| 504 | + let pBase = select(select(2u * (sl - 30u), (sl - 20u) >> 1u, sl < 30u), sl >> 2u, sl < 20u); | |
| 505 | + let deQh = sl >= 30u; | |
| 506 | +${xv ? ` // Los 4 pesos del carril son consecutivos y obase es multiplo de 4, igual | |
| 507 | + // que k0 = b*128 y toda k del decode: una sola lectura vectorial. | |
| 508 | + let xb = (base_t * params.k${globalThis.__ELFFUSS_X_FIJA === true ? '' : ' + k0 + obase'}) >> 2u; | |
| 509 | + let xv0 = x[xb];` : ''} | |
| 510 | +${Array.from({ length: 4 }, (_, j) => ` { | |
| 511 | + let by = (w4 >> (select(${j}u, ${j & 1}u, deQh) * 8u)) & 0xFFu; | |
| 512 | + let pe = pBase + select(0u, ${j >> 1}u, deQh); | |
| 513 | + let p3 = select(select(select(select(1u, 3u, pe >= 1u), 9u, pe >= 2u), 27u, pe >= 3u), 81u, pe >= 4u); | |
| 514 | + let q = (by * p3) & 0xFFu; | |
| 515 | +${emit(`obase + ${j}u`, 'f32(i32((q * 3u) >> 8u) - 1) * d', j)} | |
| 516 | + }`).join('\n')}`, | |
| 517 | + }, | |
| 518 | + | |
| 519 | + IQ1_S: { | |
| 520 | + blockElems: 256, | |
| 521 | + blockBytes: 50, | |
| 522 | + table: 'IQ1S', | |
| 523 | + helpers: '', | |
| 524 | + // Reparto ALTERNATIVO: el carril posee un SUB-GRUPO de 8 pesos en vez de un | |
| 525 | + // bloque entero. Un bloque son 8 sub-bloques x 4 grupos = 32 unidades de 8 | |
| 526 | + // pesos, que encaja EXACTO con los 32 carriles de un subgrupo. | |
| 527 | + // | |
| 528 | + // Por que: con el reparto por bloque, una fila de bpr=20 ocupa 20 carriles de | |
| 529 | + // 32 y emite 8.192 ranuras-peso para 5.120 utiles (62,5%). Repartiendo por | |
| 530 | + // sub-grupo, todos los carriles trabajan en TODOS los bloques: 5.120 ranuras, | |
| 531 | + // todas utiles. El perfil por forma demostro que este kernel esta limitado por | |
| 532 | + // emision, asi que esa utilizacion se traduce casi 1:1 en tiempo (~x1,5). | |
| 533 | + // | |
| 534 | + // Precio: cada carril calcula su propio qh/dl/delta para solo 8 pesos en vez | |
| 535 | + // de para 32, asi que las operaciones por peso suben ~4%. Y sobre todo NO es | |
| 536 | + // bit a bit: cambia que sumandos caen en que carril, o sea la particion de la | |
| 537 | + // suma en coma flotante. Se valida con tolerancia, no con igualdad exacta. | |
| 538 | + // | |
| 539 | + // Exige ancho de workgroup 32 (un subgrupo); ops.js no lo activa si no. | |
| 540 | + decodeCarril: (emit, xv = false) => { | |
| 541 | + // DESENROLLAR EL BUCLE DE 8 (`__ELFFUSS_DESENROLLA`). | |
| 542 | + // | |
| 543 | + // OJO: este comentario decia que «~70% del decode es EMITIR instrucciones». | |
| 544 | + // REFUTADO por una medida interna con marcas de tiempo del dispositivo: | |
| 545 | + // el descuantizador entero es el 8,3% del matmul, y traer activaciones el | |
| 546 | + // 44%. Por eso desenrollar no pagaba: atacaba un 8%. Se conserva el | |
| 547 | + // interruptor porque es | |
| 548 | + // bit a bit exacto y es requisito de la lectura vec4. Este | |
| 549 | + // bucle da 8 vueltas con `j` conocido en compilacion y paga por peso tres | |
| 550 | + // cosas que desaparecen al desenrollar: | |
| 551 | + // · el contador, la comparacion y el salto del bucle, | |
| 552 | + // · `select(g0, g1, j >= 4u)` -> queda g0 o g1, decidido en compilacion, | |
| 553 | + // · `get_byte_i32(gw, j & 3u)` -> desplazamiento por cantidad CONSTANTE | |
| 554 | + // en vez de por cantidad variable. | |
| 555 | + // | |
| 556 | + // Es BIT A BIT identico por construccion: mismos valores, mismo orden de | |
| 557 | + // acumulacion (j ascendente), no toca la particion de la suma entre | |
| 558 | + // carriles. Mismo perfil que izar la guarda, que ya rindio. | |
| 559 | + // | |
| 560 | + // Riesgo real: ocho copias del cuerpo suben la presion de registros y | |
| 561 | + // pueden hundir la ocupancia — asi se perdio la rejilla compartida (x0,44). | |
| 562 | + // Por eso va detras de un interruptor y se mide antes de quedarse. | |
| 563 | + // La lectura vec4 exige indices CONSTANTES, asi que fuerza el desenrollado. | |
| 564 | + const desenrolla = globalThis.__ELFFUSS_DESENROLLA === true || xv; | |
| 565 | + // ORACULO DEL DESCUANTIZADOR — solo medicion, NUNCA en produccion. | |
| 566 | + // X_FIJA y W_FIJA acotan el coste de TRAER datos; este acota el de | |
| 567 | + // TRANSFORMARLOS. Se emite `f32(gw & 1u)` y no una constante a proposito: | |
| 568 | + // `gw` cuelga de g0/g1, o sea de las dos lecturas de `tbl`. Con una | |
| 569 | + // constante el compilador mataria tambien esas lecturas y estariamos | |
| 570 | + // midiendo memoria de rejilla, que W_FIJA YA cuenta — sumar las dos celdas | |
| 571 | + // contaria ese coste dos veces. | |
| 572 | + // Acota la cota CONJUNTA de {extraer el byte + la aritmetica por peso}, | |
| 573 | + // no la de un candidato suelto. Da numeros FALSOS por diseno. | |
| 574 | + // OJO CON LA ETIQUETA: mide MAS que «la aritmetica». Al sustituir `wv`, | |
| 575 | + // `dl` y `delta` quedan muertas y con ellas `d`, asi que el compilador | |
| 576 | + // borra tambien `load_scale`. Mide {una carga por bloque} + {toda la | |
| 577 | + // aritmetica por peso}. `qh` sigue viva porque la usa `gi`. | |
| 578 | + // ESTA CONTENIDO EN W_FIJA, no es disjunto: con `blk` invariante, todo lo | |
| 579 | + // que cuelga de el (incluida esta aritmetica) queda fuera del bucle. Son | |
| 580 | + // ANIDADOS, asi que NO se suman — sumarlos cuenta el mismo coste dos veces | |
| 581 | + // y es lo que produjo el falso «49% explicado». Cotas validas: x <= 26%, | |
| 582 | + // w <= 7%, luego sin explicar >= 67%. | |
| 583 | + const deqPlana = globalThis.__ELFFUSS_DEQ_PLANA === true; | |
| 584 | + const lazo = desenrolla | |
| 585 | + ? Array.from({ length: 8 }, (_, j) => ` { | |
| 586 | + let gw = ${j < 4 ? 'g0' : 'g1'}; | |
| 587 | + let gv = f32(get_byte_i32(gw, ${j % 4}u)); | |
| 588 | +${emit(`obase + ${j}u`, deqPlana ? 'f32(gw & 1u)' : 'dl * (gv + delta)', j)} | |
| 589 | + }`).join('\n') | |
| 590 | + : ` for (var j = 0u; j < 8u; j = j + 1u) { | |
| 591 | + let gw = select(g0, g1, j >= 4u); | |
| 592 | + let gv = f32(get_byte_i32(gw, j & 3u)); | |
| 593 | +${emit('obase + j', deqPlana ? 'f32(gw & 1u)' : 'dl * (gv + delta)')} | |
| 594 | + }`; | |
| 595 | + // ORACULO DE LA CADENA DE LA REJILLA (`__ELFFUSS_GI`) — solo medicion. | |
| 596 | + // | |
| 597 | + // La cadena real es LECTURA -> LECTURA: `load_byte` (y `qh`) producen `gi`, | |
| 598 | + // y `gi` es la DIRECCION de `tbl`. En una ejecucion en orden, la segunda carga no | |
| 599 | + // puede emitirse hasta que vuelve la primera: por bloque se pagan DOS | |
| 600 | + // latencias en serie en vez de una. Ningun oraculo anterior toca eso: | |
| 601 | + // W_FIJA cambia direcciones (trafico) y DEQ_PLANA quita aritmetica. | |
| 602 | + // | |
| 603 | + // Se sustituye `gi` por un hash de REGISTROS (nada de lecturas), de modo que | |
| 604 | + // la carga de `tbl` puede emitirse a la vez que la de los pesos. Tres modos, | |
| 605 | + // que separan tres cosas que la etiqueta «rejilla» confunde: | |
| 606 | + // hash — divergente y distinto por bloque: rompe SOLO el encadenamiento. | |
| 607 | + // unif — igual para los 32 carriles: hash-unif = coste de la DIVERGENCIA | |
| 608 | + // (32 lineas distintas por carril contra una sola difundida). | |
| 609 | + // inv — no depende de `b`, luego es INVARIANTE del bucle y el compilador | |
| 610 | + // puede izar las dos lecturas de `tbl` fuera. hash-inv = trafico de | |
| 611 | + // rejilla por bloque. ADEMAS es el DETECTOR DE IZADO: si inv sale | |
| 612 | + // igual que hash, o el compilador no iza o izar no vale nada. | |
| 613 | + // | |
| 614 | + // TRAMPA CERRADA: si se quita `load_byte` del camino, el compilador la borra | |
| 615 | + // entera y mediriamos «una carga menos», no «una cadena menos». Por eso su | |
| 616 | + // valor se conserva vivo por el lado del VALOR (no de la direccion), sumado | |
| 617 | + // a `dl` enmascarado con `params.pad0`, que vale 0 pero es un UNIFORME que el | |
| 618 | + // compilador no puede plegar. La carga sigue emitiendose y sigue trayendo los | |
| 619 | + // mismos bytes; lo unico que desaparece es que `tbl` la ESPERE. | |
| 620 | + // Cuesta dos operaciones por bloque (mascara y conversion), ~0,3% del ALU. | |
| 621 | + // | |
| 622 | + // Los indices salen de la MISMA rejilla de 2048 entradas y sus bytes siguen | |
| 623 | + // siendo {-1,0,1}, asi que no hay riesgo de desbordar ni de denormales: lo | |
| 624 | + // que sale es NUMERICAMENTE FALSO, pero acotado igual que lo verdadero. | |
| 625 | + const modoGi = globalThis.__ELFFUSS_GI; | |
| 626 | + const SEMILLAS = { | |
| 627 | + hash: 'lid.x * 2246822519u + b * 40503u + row * 2654435761u', | |
| 628 | + unif: 'b * 40503u + row * 2654435761u', | |
| 629 | + inv: 'lid.x * 2246822519u + row * 2654435761u', | |
| 630 | + }; | |
| 631 | + // Sin este aviso, un modo mal escrito generaria el shader NORMAL bajo una | |
| 632 | + // clave de pipeline distinta: dos ramas identicas midiendo x1,00 y una | |
| 633 | + // conclusion («la cadena no pesa») que solo dice que hubo una errata. | |
| 634 | + if (modoGi !== undefined && !(modoGi in SEMILLAS)) { | |
| 635 | + throw new Error(`__ELFFUSS_GI desconocido: «${modoGi}» (hash|unif|inv)`); | |
| 636 | + } | |
| 637 | + // El orden de las tres lineas del control es el de SIEMPRE, byte a byte: en | |
| 638 | + // el oraculo `dl` consume `raw` y tiene que ir detras, pero en produccion no | |
| 639 | + // se mueve ni un espacio para no cambiar el reparto de registros. | |
| 640 | + const nucleo = modoGi === undefined | |
| 641 | + ? ` let dl = d * f32(2u * ((qh >> 12u) & 7u) + 1u); | |
| 642 | + let delta = select(0.125, -0.125, (qh & 0x8000u) != 0u); | |
| 643 | + let gi = load_byte(blk + 2u + ib * 4u + l) | (((qh >> (3u * l)) & 7u) << 8u);` | |
| 644 | + : ` let raw = load_byte(blk + 2u + ib * 4u + l) | (((qh >> (3u * l)) & 7u) << 8u); | |
| 645 | + let gi = (((${SEMILLAS[modoGi]}) * 2654435761u) >> 13u) & 2047u; | |
| 646 | + let dl = d * f32(2u * ((qh >> 12u) & 7u) + 1u) + f32(raw & params.pad0); | |
| 647 | + let delta = select(0.125, -0.125, (qh & 0x8000u) != 0u);`; | |
| 648 | + // IZAR LAS CARGAS INDEPENDIENTES (`__ELFFUSS_IZA_CARGAS`). | |
| 649 | + // | |
| 650 | + // El orden de siempre emite las siete cargas del bloque asi: | |
| 651 | + // load_scale(blk) · load_u16_at(qh) · USA las dos -> PARADA | |
| 652 | + // load_byte(qs) · tbl[gi] x2 -> PARADA · y AL FINAL las dos vec4 de x. | |
| 653 | + // | |
| 654 | + // Cinco de esas siete cargas son INDEPENDIENTES entre si: `load_scale`, | |
| 655 | + // `load_u16_at`, `load_byte` (su direccion sale de blk/ib/l, NO del valor | |
| 656 | + // de qh) y las dos de activaciones (que no dependen de nada del cuerpo). | |
| 657 | + // Y aun asi las tres ultimas se emiten detras de dos esperas evitables, | |
| 658 | + // porque el fuente las escribe despues. | |
| 659 | + // | |
| 660 | + // POR QUE ESTO Y NO OTRA COSA. Las hipotesis anteriores miden trafico, | |
| 661 | + // ALU, registros, ocupancia y encadenamiento; ninguna mide el NUMERO DE | |
| 662 | + // CARGAS EXPUESTAS. Con la aritmetica del bloque, la latencia de esas | |
| 663 | + // siete cargas explicaria la mayor parte de la espera medida, que es el | |
| 664 | + // hueco que ningun oraculo explicaba. | |
| 665 | + // | |
| 666 | + // No cambia NI UNA operacion: mismos valores, mismo orden de acumulacion, | |
| 667 | + // bit a bit identico por construccion. Solo cambia en que orden pide las | |
| 668 | + // cosas. Si el compilador ya reordenaba, esto sale x1,00 y cierra el | |
| 669 | + // angulo — que tambien es un resultado. | |
| 670 | + // | |
| 671 | + // Se deja FUERA de los caminos de oraculo (modoGi definido) a proposito: | |
| 672 | + // esos bancos comparan contra un orden concreto y moverlo les cambiaria el | |
| 673 | + // reparto de registros bajo los pies. | |
| 674 | + const izaCargas = globalThis.__ELFFUSS_IZA_CARGAS === true | |
| 675 | + && xv && modoGi === undefined; | |
| 676 | + | |
| 677 | + // LECTURA COOPERATIVA DEL BLOQUE (`__ELFFUSS_BLOQUE_COOP`). | |
| 678 | + // | |
| 679 | + // El bloque son 50 bytes —escala, 32 de cuantizacion y 16 de qh— y es el | |
| 680 | + // MISMO para los 32 carriles: `blk` sale de la fila y del indice de bloque, | |
| 681 | + // no del carril. Aun asi cada carril hace TRES lecturas dentro de el. Entre | |
| 682 | + // los 32 sobra de largo para traerlo con UNA: 50 bytes son 13 palabras, las | |
| 683 | + // trae un carril cada una y luego se reparten con `subgroupShuffle`, que va | |
| 684 | + // a velocidad de ALU y no de memoria. | |
| 685 | + // | |
| 686 | + // POR QUE SE ESPERA QUE ESTO SI Y EL IZADO NO. Reordenar quito CERO cargas | |
| 687 | + // y no cambió nada medible: el planificador ya solapaba. Pero | |
| 688 | + // la rama `giinv` del oraculo de la cadena, que saca DOS cargas del bucle, | |
| 689 | + // vale -19,3%. Las dos medidas juntas dan un modelo simple: el orden es | |
| 690 | + // gratis y cada instruccion de carga cuesta ~10% del matmul. Aqui se pasa | |
| 691 | + // de tres lecturas de peso a una: -2 cargas, luego la prediccion es ~19%. | |
| 692 | + // Si sale muy por debajo, el modelo de «coste por carga» es falso y hay que | |
| 693 | + // tirarlo entero, no ajustarlo. | |
| 694 | + // | |
| 695 | + // El indice se CLAMPA a la ultima palabra del buffer. `blk` no esta alineado | |
| 696 | + // a 4 (50 no es multiplo de 4, asi que `blk & 3` alterna 0 y 2) y la palabra | |
| 697 | + // 12 del ultimo bloque roza dos bytes mas alla del final. Esos dos bytes no | |
| 698 | + // se usan, pero una lectura fuera de rango podria devolver cero y llevarse | |
| 699 | + // por delante los dos que SI se usan. | |
| 700 | + const bloqueCoop = globalThis.__ELFFUSS_BLOQUE_COOP === true | |
| 701 | + && xv && modoGi === undefined; | |
| 702 | + | |
| 703 | + const comentarioX = ` // Los 8 pesos del carril caen en DOS vec4 completos: obase = ib*32 + l*8 es | |
| 704 | + // multiplo de 8 y k0 = b*256 de 4, luego (k0 + obase) es multiplo de 4 y | |
| 705 | + // toda k del decode (5120, 6144, 17408) tambien. Dos cargas vectoriales en | |
| 706 | + // vez de ocho escalares con zancada de 32 bytes.`; | |
| 707 | + const dirX = `(base_t * params.k${globalThis.__ELFFUSS_X_FIJA === true ? '' : ' + k0 + obase'}) >> 2u`; | |
| 708 | + | |
| 709 | + if (bloqueCoop) { | |
| 710 | + // `rel(r)` = palabra RELATIVA donde cae el byte `blk + r`, y `des(r, m)` | |
| 711 | + // el desplazamiento dentro de ella. Sale de que blk/4 es suelo: | |
| 712 | + // (blk + r)/4 = blk/4 + ((blk&3) + r)/4 | |
| 713 | + const rel = (r) => `((off + ${r}) >> 2u)`; | |
| 714 | + const des = (r, m) => `(((off + ${r}) & ${m}u) * 8u)`; | |
| 715 | + return /* wgsl */` | |
| 716 | + let ib = sl >> 2u; | |
| 717 | + let l = sl & 3u; | |
| 718 | + let obase = ib * 32u + l * 8u; | |
| 719 | +${comentarioX} | |
| 720 | + let xb = ${dirX}; | |
| 721 | + let xv0 = x[xb]; | |
| 722 | + let xv1 = x[xb + 1u]; | |
| 723 | + // UNA lectura de peso para todo el subgrupo: 13 carriles traen una palabra | |
| 724 | + // cada uno y el bloque entero queda repartido entre los registros. | |
| 725 | + let base = blk >> 2u; | |
| 726 | + let off = blk & 3u; | |
| 727 | + let tope = arrayLength(&w) - 1u; | |
| 728 | + let mio = select(0u, w[min(base + sl, tope)], sl < 13u); | |
| 729 | + let pqs = subgroupShuffle(mio, ${rel('2u + ib * 4u + l')}); | |
| 730 | + let pqh = subgroupShuffle(mio, ${rel('34u + ib * 2u')}); | |
| 731 | + let pd = subgroupShuffle(mio, ${rel('0u')}); | |
| 732 | + let gb = (pqs >> ${des('2u + ib * 4u + l', 3)}) & 0xFFu; | |
| 733 | + let qh = (pqh >> ${des('34u + ib * 2u', 2)}) & 0xFFFFu; | |
| 734 | + let d = unpack2x16float((pd >> ${des('0u', 2)}) & 0xFFFFu)[0]; | |
| 735 | + let gi = gb | (((qh >> (3u * l)) & 7u) << 8u); | |
| 736 | + let g0 = tbl[gi * 2u]; | |
| 737 | + let g1 = tbl[gi * 2u + 1u]; | |
| 738 | + let dl = d * f32(2u * ((qh >> 12u) & 7u) + 1u); | |
| 739 | + let delta = select(0.125, -0.125, (qh & 0x8000u) != 0u); | |
| 740 | +${lazo}`; | |
| 741 | + } | |
| 742 | + | |
| 743 | + if (izaCargas) { | |
| 744 | + return /* wgsl */` | |
| 745 | + let ib = sl >> 2u; | |
| 746 | + let l = sl & 3u; | |
| 747 | + let obase = ib * 32u + l * 8u; | |
| 748 | +${comentarioX} | |
| 749 | + // Las CINCO cargas independientes primero, seguidas, sin que ninguna | |
| 750 | + // espere a la anterior. Solo despues empieza lo que depende de ellas. | |
| 751 | + let xb = ${dirX}; | |
| 752 | + let xv0 = x[xb]; | |
| 753 | + let xv1 = x[xb + 1u]; | |
| 754 | + let d = load_scale(blk); | |
| 755 | + let qh = load_u16_at(blk + 34u + ib * 2u); | |
| 756 | + let gb = load_byte(blk + 2u + ib * 4u + l); | |
| 757 | + let gi = gb | (((qh >> (3u * l)) & 7u) << 8u); | |
| 758 | + let g0 = tbl[gi * 2u]; | |
| 759 | + let g1 = tbl[gi * 2u + 1u]; | |
| 760 | + let dl = d * f32(2u * ((qh >> 12u) & 7u) + 1u); | |
| 761 | + let delta = select(0.125, -0.125, (qh & 0x8000u) != 0u); | |
| 762 | +${lazo}`; | |
| 763 | + } | |
| 764 | + | |
| 765 | + return /* wgsl */` | |
| 766 | + let d = load_scale(blk); | |
| 767 | + let ib = sl >> 2u; | |
| 768 | + let l = sl & 3u; | |
| 769 | + let qh = load_u16_at(blk + 34u + ib * 2u); | |
| 770 | +${nucleo} | |
| 771 | + let g0 = tbl[gi * 2u]; | |
| 772 | + let g1 = tbl[gi * 2u + 1u]; | |
| 773 | + let obase = ib * 32u + l * 8u; | |
| 774 | +${xv ? `${comentarioX} | |
| 775 | + let xb = ${dirX}; | |
| 776 | + let xv0 = x[xb]; | |
| 777 | + let xv1 = x[xb + 1u];` : ''} | |
| 778 | +${lazo}`; | |
| 779 | + }, | |
| 780 | + | |
| 781 | + decode: (emit) => /* wgsl */` | |
| 782 | + let d = load_scale(blk); | |
| 783 | + for (var ib = 0u; ib < 8u; ib = ib + 1u) { | |
| 784 | + let qh = load_u16_at(blk + 34u + ib * 2u); | |
| 785 | + let dl = d * f32(2u * ((qh >> 12u) & 7u) + 1u); | |
| 786 | + let delta = select(0.125, -0.125, (qh & 0x8000u) != 0u); | |
| 787 | + for (var l = 0u; l < 4u; l = l + 1u) { | |
| 788 | + let gi = load_byte(blk + 2u + ib * 4u + l) | (((qh >> (3u * l)) & 7u) << 8u); | |
| 789 | + let g0 = tbl[gi * 2u]; | |
| 790 | + let g1 = tbl[gi * 2u + 1u]; | |
| 791 | + let obase = ib * 32u + l * 8u; | |
| 792 | + for (var j = 0u; j < 8u; j = j + 1u) { | |
| 793 | + let gw = select(g0, g1, j >= 4u); | |
| 794 | + let gv = f32(get_byte_i32(gw, j & 3u)); | |
| 795 | +${emit('obase + j', 'dl * (gv + delta)')} | |
| 796 | + } | |
| 797 | + } | |
| 798 | + }`, | |
| 799 | + }, | |
| 800 | +}; | |
| 801 | + | |
| 802 | +// Metadatos por tipo, para quien tenga que reservar buffers o cortar shards. | |
| 803 | +export const QUANT_TYPES = Object.fromEntries( | |
| 804 | + Object.entries(DECODERS).map(([name, d]) => [name, { | |
| 805 | + name, blockElems: d.blockElems, blockBytes: d.blockBytes, table: d.table || null, | |
| 806 | + }])); | |
| 807 | + | |
| 808 | +export function quantInfo(type) { | |
| 809 | + const d = DECODERS[type]; | |
| 810 | + if (!d) throw new Error(`tipo de cuantización no soportado: «${type}»`); | |
| 811 | + return d; | |
| 812 | +} | |
| 813 | + | |
| 814 | +// ── Andamios ──────────────────────────────────────────────────────────────── | |
| 815 | + | |
| 816 | +// Descuantiza un tensor entero a f32. Existe para el test: es el kernel que | |
| 817 | +// permite comparar contra una referencia de CPU peso a peso, que es donde se | |
| 818 | +// caza una descodificación mal hecha. En el forward no se usa — ahí descuantiza | |
| 819 | +// el matmul, sin materializar nada. | |
| 820 | +export function dequantShader(type, workgroupSize = 64) { | |
| 821 | + const d = quantInfo(type); | |
| 822 | + const emit = (idx, val) => ` out[dst + (${idx})] = ${val};`; | |
| 823 | + return /* wgsl */` | |
| 824 | +struct Params { nBlocks: u32, blocksPerRow: u32, rows: u32, k: u32 }; | |
| 825 | +@group(0) @binding(0) var<storage, read> w : array<u32>; | |
| 826 | +@group(0) @binding(1) var<storage, read_write> out : array<f32>; | |
| 827 | +@group(0) @binding(2) var<uniform> params : Params; | |
| 828 | +${d.table ? '@group(0) @binding(3) var<storage, read> tbl : array<u32>;' : ''} | |
| 829 | +${HELPERS}${d.helpers} | |
| 830 | +@compute @workgroup_size(${workgroupSize}) | |
| 831 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 832 | + let b = gid.x + gid.y * ${AXIS}u * ${workgroupSize}u; | |
| 833 | + if (b >= params.nBlocks) { return; } | |
| 834 | + let blk = b * ${d.blockBytes}u; | |
| 835 | + let dst = b * ${d.blockElems}u; | |
| 836 | + {${d.decode(emit)} | |
| 837 | + } | |
| 838 | +}`; | |
| 839 | +} | |
| 840 | + | |
| 841 | +// y[fila] = Σ_k A[fila][k] · x[k], con A cuantizada y x/y en f32. | |
| 842 | +// Un workgroup por fila de salida: cada hilo recorre bloques a saltos y luego se | |
| 843 | +// reduce en árbol por memoria compartida. Es el kernel del bucle de decode, que | |
| 844 | +// es donde el modelo pasa el 99 % del tiempo. | |
| 845 | +// | |
| 846 | +// Con `tokens = 1` esto ES el matvec del decode. Con más, es el matmul del | |
| 847 | +// prefill: un workgroup por (fila de salida, GRUPO de TILE tokens). Las | |
| 848 | +// activaciones van token-major (k contiguo por token), igual que las consume | |
| 849 | +// RoPE, así que no hace falta transponer nada entre operaciones. | |
| 850 | +// Cuantos SUBGRUPOS por workgroup llevan cada uno SU fila. Vive aqui, junto al | |
| 851 | +// shader que lo aplica, y lo llama ops.js para el despacho: si el predicado se | |
| 852 | +// duplicara en los dos sitios y se desincronizaran, saldrian filas a cero sin un | |
| 853 | +// solo error. Ya paso una vez. | |
| 854 | +export function sgFilasPorGrupo(type, workgroupSize, tile, carrilSubbloque, rows, subgroup, sgSize = 32) { | |
| 855 | + if (!subgroup || tile !== 1) return 1; | |
| 856 | + const d = DECODERS[type]; | |
| 857 | + const porCarril = carrilSubbloque && workgroupSize % sgSize === 0 | |
| 858 | + && d && typeof d.decodeCarril === 'function'; | |
| 859 | + if (!porCarril) return 1; | |
| 860 | + const s = Math.max(1, Math.floor(workgroupSize / sgSize)); | |
| 861 | + // `rows` multiplo de S: sin esto el ultimo grupo escribiria fuera de rango. | |
| 862 | + if (s === 1 || (Number.isFinite(rows) && rows % s !== 0)) return 1; | |
| 863 | + return s; | |
| 864 | +} | |
| 865 | + | |
| 866 | +export function matmulShader(type, workgroupSize = 64, tile = 1, subgroup = false, sgSize = 32, carrilSubbloque = false) { | |
| 867 | + const d = quantInfo(type); | |
| 868 | + // Cuántos subgrupos hay en el workgroup. Con 1 (ancho = tamaño de subgrupo), | |
| 869 | + // `subgroupAdd` da la suma entera sin nada más. Con varios (p. ej. 64 hilos = | |
| 870 | + // 2 subgrupos de 32), cada subgrupo suma lo suyo y se combinan los pocos | |
| 871 | + // parciales por memoria compartida con UNA barrera — aun así muchísimo menos | |
| 872 | + // que la reducción en árbol. Más hilos por fila esconden mejor la latencia de | |
| 873 | + // las lecturas dependientes de la rejilla i-quant, que es lo que frena IQ1_S. | |
| 874 | + const numSg = subgroup ? Math.max(1, Math.floor(workgroupSize / sgSize)) : 1; | |
| 875 | + // Solo tiene sentido con un workgroup de 32 carriles (= las 32 unidades de 8 | |
| 876 | + // pesos que tiene un bloque) y en los tipos que aportan `decodeCarril`. | |
| 877 | + const porCarril = carrilSubbloque && workgroupSize % sgSize === 0 | |
| 878 | + && typeof d.decodeCarril === 'function'; | |
| 879 | + // Mismo predicado que usa ops.js. El shader NO conoce `rows`, asi que la | |
| 880 | + // comprobacion de «rows multiplo de S» la hace SOLO ops.js: aqui se pasa | |
| 881 | + // `Infinity` para no fingir que se comprueba algo que no se comprueba. Si | |
| 882 | + // ops.js decide 1 por ese motivo, usa wg=32 y aqui sgFilas sale 1 tambien. | |
| 883 | + const sgFilas = sgFilasPorGrupo(type, workgroupSize, tile, carrilSubbloque, | |
| 884 | + Infinity, subgroup, sgSize); | |
| 885 | + // La lectura vectorial de `x` exige TRES cosas: reparto por carril (los 8 | |
| 886 | + // pesos del carril son contiguos y alineados), guarda izada (tile===1, o sea | |
| 887 | + // decode: en prefill haria falta un vec4 por token) y el interruptor. | |
| 888 | + const xv = globalThis.__ELFFUSS_X_VEC4 !== false && porCarril | |
| 889 | + && tile === 1 && !globalThis.__ELFFUSS_GUARDA_POR_PESO; | |
| 890 | + // Reducción por SUBGRUPO en vez de en árbol. La versión de árbol reduce los | |
| 891 | + // acumuladores de los `workgroupSize` hilos con memoria compartida y una | |
| 892 | + // barrera por paso (6 con 64 hilos). Si el workgroup es EXACTAMENTE un subgrupo | |
| 893 | + // (ops.js lo garantiza fijando el ancho al tamaño de subgrupo del dispositivo, | |
| 894 | + // 32 en muchos adaptadores), `subgroupAdd` hace esa misma suma en una instrucción, sin | |
| 895 | + // barreras ni memoria compartida. En el matvec del decode la reducción pesa, | |
| 896 | + // así que esto va al grano. La numérica es la misma suma (mismo orden no está | |
| 897 | + // garantizado a nivel de bit, pero es una suma de flotantes dentro de la misma | |
| 898 | + // tolerancia que valida la prueba de cuantización). | |
| 899 | + // Un acumulador por token del grupo, en variables SUELTAS y no en un array. | |
| 900 | + // Con array<f32,N> e índice dinámico, el compilador no puede dejarlo en | |
| 901 | + // registros y lo baja a memoria: cada acumulación pasa a ser un acceso, y el | |
| 902 | + // teselado deja de compensar. Desenrollado, son registros de verdad. | |
| 903 | + // El valor se ata a un `let` ANTES de repartirlo entre los acumuladores. Si se | |
| 904 | + // interpolase la expresión dentro de cada línea, un tile de 8 descuantizaría | |
| 905 | + // el mismo peso ocho veces y el teselado costaría más de lo que ahorra. | |
| 906 | + // La guarda de token se IZA cuando no puede ser falsa. Con tile=1 el matmul se | |
| 907 | + // llama siempre con tokens=1 (ops.js: `tile = tokens > 1 ? TILE_PREFILL : 1`), | |
| 908 | + // el despacho lanza ceil(1/1)=1 grupo en z, luego base_t=0 y `0 < 1` es cierto | |
| 909 | + // SIEMPRE. Aun asi se evaluaba una vez POR PESO: 20.510 millones de sumas y | |
| 910 | + // comparaciones por token que no deciden nada. | |
| 911 | + // | |
| 912 | + // No es cosmetica: el perfil por forma dice que este kernel esta limitado por | |
| 913 | + // EMISION de instrucciones (el rendimiento sigue a la utilizacion de carriles, | |
| 914 | + // no es plano como seria si mandaran las transacciones de memoria). Con ~11 | |
| 915 | + // operaciones-carril por peso, quitar una es ~9% del trabajo emitido, y ademas | |
| 916 | + // es el cambio mas limpio posible: no desenrolla, no toca registros, no cambia | |
| 917 | + // el orden de acumulacion. Bit a bit identico por construccion. | |
| 918 | + // | |
| 919 | + // En prefill (tile>1) la guarda SI puede ser falsa —el ultimo grupo de tokens | |
| 920 | + // va incompleto— y se conserva tal cual. | |
| 921 | + // AVISO para quien quiera izar la guarda tambien en prefill: la condicion | |
| 922 | + // natural seria `tokens % tile === 0`, y entonces la clave de pipeline de | |
| 923 | + // ops.js TENDRIA que llevarla. Hoy la clave lleva el `tile` pero no si la | |
| 924 | + // guarda se izo, y no hace falta porque `tile === 1` equivale a | |
| 925 | + // `tokens === 1` (ops.js: `tile = tokens > 1 ? TILE_PREFILL : 1`), donde | |
| 926 | + // base_t = 0 < 1 siempre. Si se relaja esa condicion sin tocar la clave, un | |
| 927 | + // shader compilado para un lote completo se reutilizaria en el ultimo lote | |
| 928 | + // incompleto y descartaria tokens EN SILENCIO. | |
| 929 | + const guardaIzable = tile === 1 && !globalThis.__ELFFUSS_GUARDA_POR_PESO; | |
| 930 | + // ORACULO DEL COSTE DE `x` — solo para medir, NUNCA en produccion. | |
| 931 | + // | |
| 932 | + // Una medida interna de patrones de acceso dice que nuestro acceso a `x` (cada | |
| 933 | + // carril con zancada de 8 flotantes) rinde x0,31 de un acceso coalescido en | |
| 934 | + // cache, y que vectorizarlo daria x4,11. Pero x4,11 sobre el termino de `x` | |
| 935 | + // solo importa si ese termino pesa: sobre el 10% del tiempo no es nada, sobre | |
| 936 | + // el 60% lo cambia todo. Eso no se puede estimar, hay que medirlo. | |
| 937 | + // | |
| 938 | + // Con el interruptor puesto, los 32 carriles leen la MISMA posicion de `x` en | |
| 939 | + // vez de 32 con zancada. El numero de FMA no cambia; lo que desaparece es la | |
| 940 | + // carga divergente (y ademas queda invariante del bucle, asi que el compilador | |
| 941 | + // la iza fuera). La diferencia de tiempo contra el kernel normal ES el coste | |
| 942 | + // del termino de `x`. | |
| 943 | + // | |
| 944 | + // Se lee una posicion FIJA en lugar de quitar la lectura a propósito: sin | |
| 945 | + // ninguna referencia a `x`, `layout:'auto'` deduciria un layout sin el binding | |
| 946 | + // 1 y el bind group dejaria de ser valido — sin lanzar, devolviendo ceros. | |
| 947 | + // Devuelve resultados NUMERICAMENTE FALSOS por diseño. | |
| 948 | + const xFija = globalThis.__ELFFUSS_X_FIJA === true; | |
| 949 | + // OJO CON LA ETIQUETA: esto NO mide «traer pesos» en el sentido de las | |
| 950 | + // instrucciones de carga — esas se siguen emitiendo igual. Al fijar la | |
| 951 | + // direccion, mide el coste del TRAFICO de pesos distintos: fallos de cache | |
| 952 | + // y DRAM. Y CONTIENE a DEQ_PLANA: al perder `blk` el `+ b`, todo lo que | |
| 953 | + // cuelga de `blk` queda invariante del bucle. Que DEQ_PLANA mida MAS que | |
| 954 | + // este (15,5% > 7,4%) es imposible => uno de los dos esta roto, y lo mas | |
| 955 | + // probable es que este salga deprimido porque `blk` constante Y CONOCIDO | |
| 956 | + // deja izar el lado del peso entero. NO sumar los dos: cuenta dos veces. | |
| 957 | + const wFija = globalThis.__ELFFUSS_W_FIJA === true; | |
| 958 | + const xVec4 = globalThis.__ELFFUSS_X_VEC4 === true; | |
| 959 | + const desp = xFija ? '' : ' + kk'; | |
| 960 | + // Con `xv`, los 8 flotantes del carril ya estan en dos vec4 leidos fuera del | |
| 961 | + // bucle, asi que aqui solo queda el FMA. Se usa SWIZZLE (.x/.y/.z/.w) y no | |
| 962 | + // indice: indexar un vec4 declarado con `let` solo es legal con constante, y | |
| 963 | + // el swizzle no tiene esa ambiguedad. `j` solo llega del cuerpo desenrollado. | |
| 964 | + const COMP = ['x', 'y', 'z', 'w']; | |
| 965 | + // ORACULO DE LA CADENA DEL ACUMULADOR (`__ELFFUSS_ACUMS`) — mide, y ademas | |
| 966 | + // PODRIA quedarse si gana (no es bit a bit: cambia la particion de la suma). | |
| 967 | + // | |
| 968 | + // Hoy `acc0` encadena bpr*8 FMA en serie: 160 de profundidad con bpr=20. Cada | |
| 969 | + // FMA tiene que esperar al anterior. Con N acumuladores independientes son N | |
| 970 | + // cadenas de 160/N que pueden solaparse, y al final se refunden. | |
| 971 | + // | |
| 972 | + // Solo tiene sentido en el camino vec4 (decode, reparto por carril), que es | |
| 973 | + // donde `j` es constante de compilacion y hay un unico acumulador de token. | |
| 974 | + // Con N=1 el texto generado es IDENTICO al de produccion, byte a byte: es el | |
| 975 | + // control de la tanda y a la vez la garantia de que el interruptor apagado no | |
| 976 | + // toca nada. | |
| 977 | + // Lastre de registros: N acumuladores vivos de mas, plegados al final por | |
| 978 | + // `params.pad0` (=0 en ejecucion, desconocido para el compilador). Bit a bit | |
| 979 | + // exacto: suma cero. Solo para la escalera de ocupancia. | |
| 980 | + const nlastre = Math.min(32, Math.max(0, (globalThis.__ELFFUSS_LASTRE | 0) || 0)); | |
| 981 | + const declLastre = nlastre > 0 | |
| 982 | + ? '\n' + Array.from({ length: nlastre }, (_, i) => ` var lastre${i} = f32(${i + 1}u);`).join('\n') | |
| 983 | + : ''; | |
| 984 | + const fundeLastre = nlastre > 0 | |
| 985 | + ? `\n acc0 = acc0 + (${Array.from({ length: nlastre }, (_, i) => `lastre${i}`).join(' + ')}) * f32(params.pad0);` | |
| 986 | + : ''; | |
| 987 | + const nacum = xv ? Math.min(8, Math.max(1, (globalThis.__ELFFUSS_ACUMS | 0) || 1)) : 1; | |
| 988 | + const AC = (j) => (nacum > 1 && (j % nacum) !== 0 ? `accb${j % nacum}` : 'acc0'); | |
| 989 | + const declAcum = nacum > 1 | |
| 990 | + ? '\n' + Array.from({ length: nacum - 1 }, (_, i) => ` var accb${i + 1} = 0.0;`).join('\n') | |
| 991 | + : ''; | |
| 992 | + // Refundido en ARBOL y no en cascada: en cascada volveria a crear una cadena | |
| 993 | + // serie de N-1 sumas justo donde se quiere demostrar que las cadenas cuestan. | |
| 994 | + const arbol = (ns) => (ns.length === 1 ? ns[0] | |
| 995 | + : `(${arbol(ns.slice(0, ns.length >> 1))} + ${arbol(ns.slice(ns.length >> 1))})`); | |
| 996 | + const fundeAcum = nacum > 1 | |
| 997 | + ? `\n acc0 = ${arbol(['acc0', ...Array.from({ length: nacum - 1 }, (_, i) => `accb${i + 1}`)])};` | |
| 998 | + : ''; | |
| 999 | + const emit = (idx, val, j) => (xv && j !== undefined | |
| 1000 | + ? [ | |
| 1001 | + ' {', | |
| 1002 | + ` let wv = ${val};`, | |
| 1003 | + ` ${AC(j)} = ${AC(j)} + wv * ${j < 4 ? 'xv0' : 'xv1'}.${COMP[j % 4]};`, | |
| 1004 | + ' }', | |
| 1005 | + ] | |
| 1006 | + : [ | |
| 1007 | + ' {', | |
| 1008 | + ` let wv = ${val};`, | |
| 1009 | + ` let kk = k0 + (${idx});`, | |
| 1010 | + ...(guardaIzable | |
| 1011 | + ? [` acc0 = acc0 + wv * x[base_t * params.k${desp}];`] | |
| 1012 | + : Array.from({ length: tile }, (_, t) => | |
| 1013 | + ` if (base_t + ${t}u < params.tokens) { acc${t} = acc${t} + wv * ` + | |
| 1014 | + `x[(base_t + ${t}u) * params.k${desp}]; }`)), | |
| 1015 | + ' }', | |
| 1016 | + ]).join('\n'); | |
| 1017 | + | |
| 1018 | + return /* wgsl */`${subgroup ? 'enable subgroups;\n' : ''} | |
| 1019 | +const TILE : u32 = ${tile}u; | |
| 1020 | +struct Params { nBlocks: u32, blocksPerRow: u32, rows: u32, k: u32, | |
| 1021 | + tokens: u32, pad0: u32, pad1: u32, pad2: u32 }; | |
| 1022 | +@group(0) @binding(0) var<storage, read> w : array<u32>; | |
| 1023 | +${xv ? '@group(0) @binding(1) var<storage, read> x : array<vec4<f32>>;' : '@group(0) @binding(1) var<storage, read> x : array<f32>;'} | |
| 1024 | +@group(0) @binding(2) var<storage, read_write> y : array<f32>; | |
| 1025 | +@group(0) @binding(3) var<uniform> params : Params; | |
| 1026 | +${d.table ? '@group(0) @binding(4) var<storage, read> tbl : array<u32>;' : ''} | |
| 1027 | +${HELPERS}${d.helpers} | |
| 1028 | +${subgroup ? (numSg > 1 && sgFilas === 1 ? `var<workgroup> sgpart : array<f32, ${numSg}u>;` : '') : `var<workgroup> partial : array<f32, ${workgroupSize}>;`} | |
| 1029 | + | |
| 1030 | +@compute @workgroup_size(${workgroupSize}) | |
| 1031 | +fn main(@builtin(workgroup_id) wid : vec3<u32>, | |
| 1032 | + @builtin(local_invocation_id) lid : vec3<u32>${subgroup && numSg > 1 ? ',\n @builtin(subgroup_invocation_id) sglane : u32' : ''}) { | |
| 1033 | + // Las filas van en dos ejes porque uno solo topa en 65.535 y la cabeza de | |
| 1034 | + // salida son 248.320 filas. El tercer eje son GRUPOS de TILE tokens. | |
| 1035 | + // Carril LOCAL al subgrupo: con varios subgrupos por workgroup, lid.x pasa de | |
| 1036 | + // 31 y el reparto por carril (ib, l) se saldria de rango. Con un subgrupo es | |
| 1037 | + // exactamente lid.x. | |
| 1038 | + ${porCarril ? `let sl = lid.x & ${sgSize - 1}u;` : '// sin reparto por carril no hace falta el indice de carril (ver kernels.wgsl.js)'} | |
| 1039 | + ${sgFilas > 1 | |
| 1040 | + ? `// Una fila por SUBGRUPO: cada punto de la rejilla son ${sgFilas} filas. | |
| 1041 | + let row = (wid.x + wid.y * ${AXIS}u) * ${sgFilas}u + lid.x / ${sgSize}u;` | |
| 1042 | + : `let row = wid.x + wid.y * ${AXIS}u;`} | |
| 1043 | + let base_t = wid.z * TILE; | |
| 1044 | + let bpr = params.blocksPerRow; | |
| 1045 | + | |
| 1046 | +${Array.from({ length: tile }, (_, t) => ` var acc${t} = 0.0;`).join('\n')}${declAcum}${declLastre} | |
| 1047 | + | |
| 1048 | + if (row < params.rows) { | |
| 1049 | +${porCarril | |
| 1050 | + ? ` // Reparto por SUB-GRUPO: todos los carriles avanzan por el MISMO bloque y | |
| 1051 | + // cada uno se ocupa de 8 pesos. Cero carriles ociosos sea cual sea bpr, y de | |
| 1052 | + // paso los 32 carriles leen un tramo CONTIGUO de activaciones en vez de 32 | |
| 1053 | + // tramos dispersos. Ver decodeCarril. | |
| 1054 | + for (var b = 0u; b < bpr; b = b + 1u) {` | |
| 1055 | + : ` for (var b = lid.x; b < bpr; b = b + ${workgroupSize}u) {`} | |
| 1056 | + let blk = (row * bpr${wFija ? '' : ' + b'}) * ${d.blockBytes}u; | |
| 1057 | + let k0 = b * ${d.blockElems}u; | |
| 1058 | + {${porCarril ? d.decodeCarril(emit, xv) : d.decode(emit)} | |
| 1059 | + } | |
| 1060 | + } | |
| 1061 | + }${fundeAcum}${fundeLastre} | |
| 1062 | + | |
| 1063 | + // Reducción por token del grupo. Con subgrupo, una instrucción por token; en | |
| 1064 | + // árbol, memoria compartida y una barrera por paso. El recorrido del árbol es | |
| 1065 | + // constante de compilación, así que las barreras quedan en flujo uniforme. | |
| 1066 | +${subgroup | |
| 1067 | + ? (sgFilas > 1 | |
| 1068 | + ? Array.from({ length: tile }, (_, t) => ` { | |
| 1069 | + let tot${t} = subgroupAdd(acc${t}); | |
| 1070 | + if (sglane == 0u && row < params.rows && base_t + ${t}u < params.tokens) { | |
| 1071 | + y[(base_t + ${t}u) * params.rows + row] = tot${t}; | |
| 1072 | + } | |
| 1073 | + }`).join('\n') | |
| 1074 | + : numSg === 1 | |
| 1075 | + ? Array.from({ length: tile }, (_, t) => ` { | |
| 1076 | + let tot${t} = subgroupAdd(acc${t}); | |
| 1077 | + if (lid.x == 0u && row < params.rows && base_t + ${t}u < params.tokens) { | |
| 1078 | + y[(base_t + ${t}u) * params.rows + row] = tot${t}; | |
| 1079 | + } | |
| 1080 | + }`).join('\n') | |
| 1081 | + : Array.from({ length: tile }, (_, t) => ` { | |
| 1082 | + let s${t} = subgroupAdd(acc${t}); | |
| 1083 | + if (sglane == 0u) { sgpart[lid.x / ${sgSize}u] = s${t}; } | |
| 1084 | + workgroupBarrier(); | |
| 1085 | + if (lid.x == 0u && row < params.rows && base_t + ${t}u < params.tokens) { | |
| 1086 | + var tot${t} = 0.0; | |
| 1087 | + for (var q = 0u; q < ${numSg}u; q = q + 1u) { tot${t} = tot${t} + sgpart[q]; } | |
| 1088 | + y[(base_t + ${t}u) * params.rows + row] = tot${t}; | |
| 1089 | + } | |
| 1090 | + workgroupBarrier(); | |
| 1091 | + }`).join('\n')) | |
| 1092 | + : Array.from({ length: tile }, (_, t) => ` partial[lid.x] = acc${t}; | |
| 1093 | + workgroupBarrier(); | |
| 1094 | + for (var s${t} = ${workgroupSize >> 1}u; s${t} > 0u; s${t} = s${t} >> 1u) { | |
| 1095 | + if (lid.x < s${t}) { partial[lid.x] = partial[lid.x] + partial[lid.x + s${t}]; } | |
| 1096 | + workgroupBarrier(); | |
| 1097 | + } | |
| 1098 | + if (lid.x == 0u && row < params.rows && base_t + ${t}u < params.tokens) { | |
| 1099 | + y[(base_t + ${t}u) * params.rows + row] = partial[0]; | |
| 1100 | + } | |
| 1101 | + workgroupBarrier(); // WAR: el token siguiente reescribe partial`).join('\n')} | |
| 1102 | +}`; | |
| 1103 | +} | |
| 1104 | + | |
| 1105 | +// Busca las filas `ids` de una tabla cuantizada y las deja en f32. | |
| 1106 | +// La tabla de embeddings es de los tensores más grandes del modelo: descuantizarla | |
| 1107 | +// entera para leer unas pocas filas costaría muchas veces lo que se lee. | |
| 1108 | +// | |
| 1109 | +// El grano es el BLOQUE, no el elemento. Sacar un peso suelto de un K-quant | |
| 1110 | +// obligaría a escribir un segundo descodificador «de un solo elemento» por | |
| 1111 | +// tipo, distinto del que usa el matmul — o sea, seis oportunidades más de | |
| 1112 | +// equivocarse en el layout. Descodificando bloques enteros se reutiliza tal cual | |
| 1113 | +// el descodificador ya verificado, y lo único que se paga es descartar los pesos | |
| 1114 | +// del bloque que no hacían falta, que en un embedding es ninguno: se quiere la | |
| 1115 | +// fila entera. | |
| 1116 | +export function gatherShader(type, workgroupSize = 64) { | |
| 1117 | + const d = quantInfo(type); | |
| 1118 | + const emit = (idx, val) => ` dst[base + (${idx})] = ${val};`; | |
| 1119 | + return /* wgsl */` | |
| 1120 | +struct P { dim : u32, tokens : u32, blocksPerRow : u32, pad : u32 }; | |
| 1121 | +@group(0) @binding(0) var<storage, read> w : array<u32>; | |
| 1122 | +@group(0) @binding(1) var<storage, read> ids : array<u32>; | |
| 1123 | +@group(0) @binding(2) var<storage, read_write> dst : array<f32>; | |
| 1124 | +@group(0) @binding(3) var<uniform> p : P; | |
| 1125 | +${d.table ? '@group(0) @binding(4) var<storage, read> tbl : array<u32>;' : ''} | |
| 1126 | +${HELPERS}${d.helpers} | |
| 1127 | +@compute @workgroup_size(${workgroupSize}) | |
| 1128 | +fn main(@builtin(global_invocation_id) gid : vec3<u32>) { | |
| 1129 | + let i = gid.x + gid.y * ${AXIS}u * ${workgroupSize}u; | |
| 1130 | + if (i >= p.tokens * p.blocksPerRow) { return; } | |
| 1131 | + let t = i / p.blocksPerRow; | |
| 1132 | + let b = i % p.blocksPerRow; | |
| 1133 | + let blk = (ids[t] * p.blocksPerRow + b) * ${d.blockBytes}u; | |
| 1134 | + let base = t * p.dim + b * ${d.blockElems}u; | |
| 1135 | + {${d.decode(emit)} | |
| 1136 | + } | |
| 1137 | +}`; | |
| 1138 | +} | |
| 1139 | + | |
| 1140 | +// Los alias `dequantQ8Shader`/`matmulQ8Shader`/`matvecQ8Shader` ya no existen: | |
| 1141 | +// nadie los llamaba una vez que `ops.js` pasa el tipo, y dejarlos puestos habría | |
| 1142 | +// sido una compatibilidad con nada. |
added js/model.js +846 −0
| @@ -0,0 +1,846 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · el modelo: carga de pesos y forward de qwen35. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// Aquí se encadenan las piezas que ya están verificadas una a una. Esa | |
| 6 | +// verificación por piezas NO garantiza que el conjunto funcione: puede fallar el | |
| 7 | +// orden, el layout que espera la siguiente operación, o un residual sumado en el | |
| 8 | +// sitio equivocado. Por eso el forward está escrito para poder pararse en | |
| 9 | +// cualquier capa y comparar contra el volcado de un forward real. | |
| 10 | +// | |
| 11 | +// Dos tipos de bloque, y el reparto sale del propio fichero: | |
| 12 | +// · SSM (18 de 24 en el 0.8B, 48 de 65 en el 27B): qkv fusionado → conv causal | |
| 13 | +// → silu → q/k/v → delta net con estado recurrente → norm con puerta. | |
| 14 | +// · Atención (el resto): Q y puerta INTERCALADOS en el mismo tensor, QK-norm | |
| 15 | +// antes de RoPE, RoPE parcial, GQA, y la puerta multiplicando la salida. | |
| 16 | +// Los dos acaban igual: residual, norm, SwiGLU, residual. | |
| 17 | +// | |
| 18 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 19 | + | |
| 20 | +import { parseGGUF } from './gguf.js'; | |
| 21 | +import { leeRotacion } from './hadamard.js'; | |
| 22 | +import { createOps, ROPE_NEOX, ROPE_NORM } from './ops.js'; | |
| 23 | +import { readHParams, createState } from './state.js'; | |
| 24 | +import { | |
| 25 | + copyIntoShader, convWindowShader, convSaveShader, siluShader, | |
| 26 | +} from './kernels.model.wgsl.js'; | |
| 27 | +import { QUANT_TYPES } from './kernels.wgsl.js'; | |
| 28 | + | |
| 29 | +const MiB = 1024 ** 2; | |
| 30 | + | |
| 31 | +// Sube todos los tensores del fichero al dispositivo, uno por buffer. | |
| 32 | +// PENDIENTE consciente: un tensor por buffer exige que cada uno quepa en | |
| 33 | +// maxStorageBufferBindingSize. En escritorio el límite suele sobrar; en otros | |
| 34 | +// navegadores es mucho menor y la tabla de embeddings, de los tensores más | |
| 35 | +// grandes del modelo, puede no caber. Ahí hará falta que el matmul lea varios shards, que es | |
| 36 | +// trabajo del kernel, no de aquí. Se comprueba y se falla claro en vez de | |
| 37 | +// devolver ceros. | |
| 38 | +// El tamaño de lote del prefill. Es un `let` con gancho SOLO para poder | |
| 39 | +// medirlo: comparar dos valores exige cambiarlo en caliente, dentro de la misma | |
| 40 | +// sesión y alternando el orden. Editando el fichero entre pasadas, lo que se | |
| 41 | +// mueve la medida de una sesión a otra se mezcla con lo que se compara, y luego | |
| 42 | +// no hay forma de separar una cosa de la otra. | |
| 43 | +// 32 y no 128: medido, un lote más corto va algo MÁS rápido (menos posiciones | |
| 44 | +// enmascaradas que se calculan para tirar) y —lo que importa aquí— cada despacho | |
| 45 | +// dura menos, que es media defensa contra el cuelgue. La otra media es | |
| 46 | +// trocear el forward en varios command buffers (ver `cede`/`ctx.corta`). | |
| 47 | +let loteActual = 32; | |
| 48 | +// El reparto de la última carga. Lo consume una prueba interna y puede | |
| 49 | +// consumirlo la UI: es la espera más larga del producto. | |
| 50 | +let medidaCarga = null; | |
| 51 | +export function ultimaCarga() { return medidaCarga; } | |
| 52 | + | |
| 53 | +// Cuántos tensores DEBÍAN subirse en la última carga. No es lo mismo que los del | |
| 54 | +// fichero: la cabeza MTP (`nextn_predict_layers`) no pertenece al forward y no | |
| 55 | +// se sube — en el modelo pequeño son 15 de 335. Un banco que compare contra | |
| 56 | +// `g.tensorCount` falla por construcción, que es lo que pasaba. | |
| 57 | +let subidosEsperados = 0; | |
| 58 | +export function ultimosSubidos() { return subidosEsperados; } | |
| 59 | + | |
| 60 | +export function _setLote(n) { loteActual = Math.max(1, n | 0); } | |
| 61 | +export function _getLote() { return loteActual; } | |
| 62 | + | |
| 63 | +// Cada cuántas capas se le da al dispositivo un respiro real para que el compositor | |
| 64 | +// del sistema pinte. Un forward del 27B son 64 capas; sin trocear, iban todas | |
| 65 | +// en un solo despacho larguísimo y la pantalla se quedaba sin pintar mientras | |
| 66 | +// tanto. Ver `ctx.corta`. | |
| 67 | +let cederCada = 2; | |
| 68 | +export function _setCeder(n) { cederCada = Math.max(1, n | 0); } | |
| 69 | +export function _getCeder() { return cederCada; } | |
| 70 | + | |
| 71 | +// El respiro se cobra por RELOJ, no por capas. Lo que se persigue —que el | |
| 72 | +// compositor del sistema pinte— es un asunto de milisegundos de pared: da igual | |
| 73 | +// si en ese rato han pasado dos capas o cuarenta. Contándolo por capas se pagaba | |
| 74 | +// un frame entero cada dos capas aunque esas dos capas durasen medio frame, y | |
| 75 | +// como un rAF no se puede partir, el prefill acababa cuantizado al refresco del | |
| 76 | +// monitor: el reloj lo marcaba la pantalla y no el modelo. | |
| 77 | +// `cederCada` sigue siendo la granularidad mínima (solo se mira el reloj en esas | |
| 78 | +// capas) y esto es el límite de frecuencia. A 0 se recupera exactamente el | |
| 79 | +// comportamiento anterior, que es lo que usan los bancos para el A/B. | |
| 80 | +let cederMs = 100; | |
| 81 | +export function _setCederMs(ms) { cederMs = Math.max(0, +ms || 0); } | |
| 82 | +export function _getCederMs() { return cederMs; } | |
| 83 | + | |
| 84 | +// Cada cuántas capas se CIERRA y envía el command buffer del prefill. Es otra | |
| 85 | +// cosa que `cederCada`: eso es cuándo se drena la cola y se cede un frame, esto | |
| 86 | +// es solo cuántos submits se parten. Va con gancho porque la nota de al lado | |
| 87 | +// afirmaba que trocear en cada capa es «GRATIS» y eso nadie lo había medido: | |
| 88 | +// una tanda de prefill aprovecha el ancho de banda de pesos 6,6 veces peor que | |
| 89 | +// un token suelto (medido con una prueba interna) y el prefill es justo el único | |
| 90 | +// camino que trocea. A 1 se recupera el comportamiento de siempre. | |
| 91 | +let cortaCada = 1; | |
| 92 | +export function _setCorta(n) { cortaCada = Math.max(1, n | 0); } | |
| 93 | +export function _getCorta() { return cortaCada; } | |
| 94 | +// Cede un frame al bucle de eventos: en el navegador deja que el compositor | |
| 95 | +// del sistema componga; fuera del DOM (tests) basta un turno de macrotarea. | |
| 96 | +// | |
| 97 | +// Y vuelve TAMBIÉN en cuanto se pide parar. No es un adorno: con la pestaña en | |
| 98 | +// segundo plano el navegador deja de dar frames —el rAF no llega hasta que la | |
| 99 | +// pestaña se vuelve a ver—, y un prefill esperando aquí no podría atender un | |
| 100 | +// «para» hasta entonces. Con la señal, parar no depende de que haya pantalla. | |
| 101 | +const nuevoFrame = (senal = null) => new Promise((r) => { | |
| 102 | + if (senal?.aborted) { r(); return; } | |
| 103 | + let id = null, hecho = false; | |
| 104 | + const fin = () => { | |
| 105 | + if (hecho) return; | |
| 106 | + hecho = true; | |
| 107 | + senal?.removeEventListener?.('abort', fin); | |
| 108 | + if (id !== null && typeof cancelAnimationFrame === 'function') cancelAnimationFrame(id); | |
| 109 | + r(); | |
| 110 | + }; | |
| 111 | + senal?.addEventListener?.('abort', fin, { once: true }); | |
| 112 | + if (typeof requestAnimationFrame === 'function') id = requestAnimationFrame(() => fin()); | |
| 113 | + else setTimeout(fin, 0); | |
| 114 | +}); | |
| 115 | + | |
| 116 | +// El error de «se pidió parar». Lleva el NOMBRE estándar, AbortError, para que | |
| 117 | +// quien llama lo distinga de un fallo de verdad sin leer el texto: un turno | |
| 118 | +// parado no es un modelo roto, y enseñarlo como «el modelo falló» sería mentir. | |
| 119 | +export function errorParado(mensaje = 'parado a petición') { | |
| 120 | + if (typeof DOMException === 'function') return new DOMException(mensaje, 'AbortError'); | |
| 121 | + const e = new Error(mensaje); | |
| 122 | + e.name = 'AbortError'; | |
| 123 | + return e; | |
| 124 | +} | |
| 125 | + | |
| 126 | +export async function loadModel(ranged, device, opts = {}) { | |
| 127 | + const onProgress = opts.onProgress || (() => {}); | |
| 128 | + const g = await parseGGUF(ranged); | |
| 129 | + const hp = readHParams(g.meta, g.tensors); | |
| 130 | + const ops = createOps(device, { debug: opts.debug !== false, subgroupSize: opts.subgroupSize || 0 }); | |
| 131 | + const limit = device.limits.maxStorageBufferBindingSize; | |
| 132 | + | |
| 133 | + // Antes de mover un solo byte: que TODOS los tipos del fichero tengan kernel. | |
| 134 | + // Un tipo sin soporte descubierto a mitad del forward sería el modelo entero | |
| 135 | + // ya subido y un error tres capas más abajo; aquí es una línea que dice cuál. | |
| 136 | + const sinKernel = new Map(); | |
| 137 | + for (const t of g.tensors) { | |
| 138 | + if (!QUANT_TYPES[t.typeName]) { | |
| 139 | + if (!sinKernel.has(t.typeName)) sinKernel.set(t.typeName, t.name); | |
| 140 | + } | |
| 141 | + } | |
| 142 | + if (sinKernel.size) { | |
| 143 | + throw new Error('el fichero trae tipos sin kernel: ' + | |
| 144 | + [...sinKernel].map(([k, n]) => `${k} (p.ej. «${n}»)`).join(', ')); | |
| 145 | + } | |
| 146 | + // Las rejillas de los i-quants, subidas antes del primer forward. | |
| 147 | + await ops.quant.prepare(g.tensors.map(t => t.typeName)); | |
| 148 | + | |
| 149 | + const weights = new Map(); | |
| 150 | + let uploaded = 0; | |
| 151 | + // LA CABEZA MTP NO SE SUBE. El fichero trae `nextn_predict_layers` bloques de | |
| 152 | + // mas que el forward: state.js hace `nLayers = block_count - nextn` y nunca los | |
| 153 | + // recorre. En el modelo grande son 15 tensores que se suben al dispositivo, se | |
| 154 | + // quedan ahi y no se ejecutan NUNCA: memoria y tiempo de subida tirados en | |
| 155 | + // cada sesion, sobre un modelo cuya carga ya es la espera mas larga del | |
| 156 | + // producto. | |
| 157 | + // | |
| 158 | + // Se deriva de los METADATOS y no de un «blk.64» escrito a mano: si algun dia | |
| 159 | + // se implementa la especulacion con esa cabeza, basta con quitar este filtro y | |
| 160 | + // los pesos vuelven. Y se descuentan tambien de `total`, porque si no la barra | |
| 161 | + // de progreso no llegaria nunca al 100%. | |
| 162 | + const kNextn = Object.keys(g.meta).find((k) => k.endsWith('.nextn_predict_layers')); | |
| 163 | + const kBloques = Object.keys(g.meta).find((k) => k.endsWith('.block_count')); | |
| 164 | + const nextn = (kNextn && g.meta[kNextn]) || 0; | |
| 165 | + const nBloques = (kBloques && g.meta[kBloques]) || 0; | |
| 166 | + const saltados = nextn > 0 && nBloques > 0 | |
| 167 | + ? new Set(Array.from({ length: nextn }, (_, i) => `blk.${nBloques - nextn + i}.`)) | |
| 168 | + : new Set(); | |
| 169 | + const sobra = (t) => [...saltados].some((pre) => t.name.startsWith(pre)); | |
| 170 | + const suben = saltados.size ? g.tensors.filter((t) => !sobra(t)) : g.tensors; | |
| 171 | + const total = suben.reduce((n, t) => n + t.nBytes, 0); | |
| 172 | + | |
| 173 | + // ── DÓNDE SE VA EL TIEMPO DE CARGA ───────────────────────────────────────── | |
| 174 | + // Medido contra llama.cpp en la misma sesión y el mismo fichero, ellos cargan | |
| 175 | + // x3,5 más rápido que nosotros. Es la espera más larga que paga el usuario y | |
| 176 | + // nadie la había repartido nunca: «la carga tarda» tiene al menos tres causas | |
| 177 | + // que desde fuera se ven idénticas —traer los bytes, subirlos al dispositivo, y el | |
| 178 | + // número de viajes— y sin separarlas no se puede atacar ninguna. | |
| 179 | + // | |
| 180 | + // Se cuentan los TROZOS además del tiempo: este bucle pide un rango por | |
| 181 | + // tensor como mínimo, y un modelo pequeño tiene cientos. Si el tiempo está en | |
| 182 | + // la latencia de cientos de viajes en serie, el arreglo no es un kernel, es | |
| 183 | + // dejar de esperar uno por uno. | |
| 184 | + const ahoraC = () => (typeof performance !== 'undefined' ? performance.now() : Date.now()); | |
| 185 | + const tCarga0 = ahoraC(); | |
| 186 | + let msLeer = 0, msSubir = 0, trozos = 0; | |
| 187 | + | |
| 188 | + // ── TRAMOS: una lectura para MUCHOS tensores ──────────────────────────────── | |
| 189 | + // Esto pedía un rango por tensor. Medido en navegador limpio con el modelo | |
| 190 | + // pequeño: un viaje por tensor, con el 99,9 % del tiempo en LEER, menos del | |
| 191 | + // 1 % en encolar la subida y nada esperando al dispositivo. Y el coste por viaje | |
| 192 | + // apenas dependía de su tamaño, que es la firma de la LATENCIA: no se estaba | |
| 193 | + // llenando el enlace, se estaba esperando cientos de veces de una en una. | |
| 194 | + // | |
| 195 | + // En GGUF los tensores van CONTIGUOS, así que se agrupan en tramos de hasta | |
| 196 | + // TRAMO bytes y cada tramo se trae de una sola lectura; después se reparte en | |
| 197 | + // memoria, que sale gratis (encolar era el 0,1 %). | |
| 198 | + // | |
| 199 | + // Se agrupa SOLO si el tensor empieza justo donde acaba el anterior: si el | |
| 200 | + // fichero trae relleno entre tensores, agrupar a ciegas no daría error, daría | |
| 201 | + // pesos de otro sitio. Y un tensor más grande que TRAMO va en su propio tramo | |
| 202 | + // y se lee a trozos de CHUNK, igual que antes. | |
| 203 | + // Interruptor para poder medir el ANTES y el DESPUÉS en la MISMA sesión: una | |
| 204 | + // razón sacada de comparar dos tiradas no vale, porque entre tiradas los | |
| 205 | + // absolutos se mueven demasiado. A 1 byte cada tensor va en su propio tramo y | |
| 206 | + // se recupera el comportamiento de una lectura por tensor. | |
| 207 | + // El tramo por defecto, y no la mitad: barrido en la misma sesión, dos rondas | |
| 208 | + // por candidato y orden alternado, con una prueba interna. Contra el camino | |
| 209 | + // viejo —un viaje por tensor— agrupar da del orden de x7. Entre candidatos, de | |
| 210 | + // la mitad al valor elegido hay una mejora pequeña que se repite en LAS DOS | |
| 211 | + // rondas; al doble la diferencia cae dentro del ruido y pediría un buffer | |
| 212 | + // transitorio el doble de grande para nada. Ahí la curva ya está saturada: | |
| 213 | + // manda el enlace. | |
| 214 | + const TRAMO = Math.max(1, (globalThis.__ELFFUSS_TRAMO | 0) || 128 * MiB); | |
| 215 | + const CHUNK = 32 * MiB; | |
| 216 | + const tramos = []; | |
| 217 | + for (const t of suben) { | |
| 218 | + if (t.nBytes > limit) { | |
| 219 | + throw new Error(`«${t.name}» son ${(t.nBytes / MiB).toFixed(0)} MiB y el ` + | |
| 220 | + `límite de binding es ${(limit / MiB).toFixed(0)} MiB: hace falta que el ` + | |
| 221 | + `matmul lea varios shards`); | |
| 222 | + } | |
| 223 | + const ult = tramos[tramos.length - 1]; | |
| 224 | + if (ult && t.start === ult.fin && (ult.fin - ult.ini) + t.nBytes <= TRAMO) { | |
| 225 | + ult.fin = t.start + t.nBytes; ult.ts.push(t); | |
| 226 | + } else { | |
| 227 | + tramos.push({ ini: t.start, fin: t.start + t.nBytes, ts: [t] }); | |
| 228 | + } | |
| 229 | + } | |
| 230 | + | |
| 231 | + // Holgura de 4 bytes en el buffer: la descodificación de bloques de 34 lee la | |
| 232 | + // palabra siguiente al recomponer los que no caen alineados. | |
| 233 | + const nuevoBuf = (t) => device.createBuffer({ | |
| 234 | + label: t.name, | |
| 235 | + size: Math.ceil((t.nBytes + 4) / 4) * 4, | |
| 236 | + usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, | |
| 237 | + }); | |
| 238 | + | |
| 239 | + for (const tr of tramos) { | |
| 240 | + const largo = tr.fin - tr.ini; | |
| 241 | + if (largo > TRAMO) { | |
| 242 | + // Tensor suelto demasiado grande: camino de trozos, uno solo en el tramo. | |
| 243 | + const t = tr.ts[0]; | |
| 244 | + const buf = nuevoBuf(t); | |
| 245 | + for (let off = 0; off < t.nBytes; off += CHUNK) { | |
| 246 | + const len = Math.min(CHUNK, t.nBytes - off); | |
| 247 | + const tL = ahoraC(); | |
| 248 | + const raw = new Uint8Array(await ranged.slice(t.start + off, len)); | |
| 249 | + const tS = ahoraC(); msLeer += tS - tL; trozos++; | |
| 250 | + const pad = len % 4 === 0 ? raw : (() => { | |
| 251 | + const p = new Uint8Array(Math.ceil(len / 4) * 4); p.set(raw); return p; | |
| 252 | + })(); | |
| 253 | + device.queue.writeBuffer(buf, off, pad, 0, pad.byteLength); | |
| 254 | + msSubir += ahoraC() - tS; | |
| 255 | + uploaded += len; | |
| 256 | + onProgress(uploaded, total, t.name); | |
| 257 | + } | |
| 258 | + weights.set(t.name, { buf, t }); | |
| 259 | + continue; | |
| 260 | + } | |
| 261 | + | |
| 262 | + const tL = ahoraC(); | |
| 263 | + const span = new Uint8Array(await ranged.slice(tr.ini, largo)); | |
| 264 | + msLeer += ahoraC() - tL; trozos++; | |
| 265 | + // Un tramo corto se leería sin error y dejaría ceros dentro de un peso. | |
| 266 | + if (span.byteLength !== largo) { | |
| 267 | + throw new Error(`tramo incompleto: pedidos ${largo} bytes desde ${tr.ini} ` + | |
| 268 | + `y llegaron ${span.byteLength}`); | |
| 269 | + } | |
| 270 | + for (const t of tr.ts) { | |
| 271 | + const buf = nuevoBuf(t); | |
| 272 | + const tS = ahoraC(); | |
| 273 | + const desde = t.start - tr.ini; | |
| 274 | + const n4 = Math.ceil(t.nBytes / 4) * 4; | |
| 275 | + const pad = new Uint8Array(n4); | |
| 276 | + pad.set(span.subarray(desde, desde + t.nBytes)); | |
| 277 | + device.queue.writeBuffer(buf, 0, pad, 0, n4); | |
| 278 | + msSubir += ahoraC() - tS; | |
| 279 | + uploaded += t.nBytes; | |
| 280 | + onProgress(uploaded, total, t.name); | |
| 281 | + weights.set(t.name, { buf, t }); | |
| 282 | + } | |
| 283 | + } | |
| 284 | + // `onSubmittedWorkDone` se mide aparte: es donde se paga de verdad el trabajo | |
| 285 | + // que `writeBuffer` solo había ENCOLADO. Sin separarlo, subir parecería | |
| 286 | + // gratis y el tiempo aparecería como un hueco sin dueño. | |
| 287 | + const tEspera = ahoraC(); | |
| 288 | + await device.queue.onSubmittedWorkDone(); | |
| 289 | + subidosEsperados = suben.length; | |
| 290 | + medidaCarga = { | |
| 291 | + tensores: suben.length, saltados: g.tensors.length - suben.length, trozos, bytes: total, | |
| 292 | + leerMs: msLeer, subirMs: msSubir, esperaMs: ahoraC() - tEspera, | |
| 293 | + totalMs: ahoraC() - tCarga0, | |
| 294 | + }; | |
| 295 | + console.log(`[engine] carga: ${suben.length} tensores en ${trozos} trozos · ` + | |
| 296 | + `leer ${msLeer.toFixed(0)} ms · encolar ${msSubir.toFixed(0)} ms · ` + | |
| 297 | + `esperar GPU ${medidaCarga.esperaMs.toFixed(0)} ms · total ${medidaCarga.totalMs.toFixed(0)} ms`); | |
| 298 | + | |
| 299 | + // `picoGPU` es el pico de memoria pedida al dispositivo sin reciclar dentro de un | |
| 300 | + // solo forward. Un prefill largo acumula TODOS los intermedios de todas las | |
| 301 | + // capas, y cada uno escala con el número de tokens. | |
| 302 | + return { g, hp, ops, weights, device, bytes: total, picoGPU: () => ops.ctx.picoBytes }; | |
| 303 | +} | |
| 304 | + | |
| 305 | +export function createSession(model, opts = {}) { | |
| 306 | + const { device, hp, ops, weights } = model; | |
| 307 | + // Sonda de diagnostico: cuando esta puesta, cada intermedio con nombre se | |
| 308 | + // ofrece al llamador. Es lo que permite comparar contra el volcado nodo a | |
| 309 | + // nodo de un forward real y localizar el paso exacto donde algo se desvia, | |
| 310 | + // en vez de ver solo que la capa entera no cuadra. | |
| 311 | + const probe = opts.probe || null; | |
| 312 | + let capaActual = -1; | |
| 313 | + // Buffers que una sonda ha pedido CONSERVAR hasta el final del forward. Sin | |
| 314 | + // esto el mecanismo solo servía para la última capa, y de la forma más | |
| 315 | + // traicionera que hay: `ctx.recycleDesde` recicla los intermedios en cuanto | |
| 316 | + // la capa termina —protege los de `tap`, pero no los que se entregan por | |
| 317 | + // `probe`—, así que leer uno después del forward devolvía el trozo de memoria | |
| 318 | + // REUTILIZADO por las capas siguientes. Un banco que sondeó nueve capas sacó | |
| 319 | + // la misma cifra en ocho de ellas, idéntica hasta el decimal, y solo la última | |
| 320 | + // era real. No fallaba nada: contestaba otra cosa. | |
| 321 | + // El contrato: si la sonda devuelve `true`, ese buffer no se recicla. | |
| 322 | + let conservadas = new Set(); | |
| 323 | + const P = (name, buf, n) => { | |
| 324 | + if (probe && probe(name, buf, n, capaActual) === true) conservadas.add(buf); | |
| 325 | + return buf; | |
| 326 | + }; | |
| 327 | + const { quant, nn, ssm: ssmOps, attn, ctx } = ops; | |
| 328 | + const state = createState(device, hp, opts); | |
| 329 | + const W = (name) => { | |
| 330 | + const w = weights.get(name); | |
| 331 | + if (!w) throw new Error('falta el tensor «' + name + '»'); | |
| 332 | + return w; | |
| 333 | + }; | |
| 334 | + const get = (name) => W(name).buf; | |
| 335 | + const has = (name) => weights.has(name); | |
| 336 | + | |
| 337 | + // Una proyección. El tipo de cuantización lo pone el FICHERO, no esta función: | |
| 338 | + // el 0.8B lo trae todo en Q8_0, otros ficheros mezclan varios tipos, y el | |
| 339 | + // forward es el mismo. Este es el único punto donde el modelo toca la | |
| 340 | + // cuantización; de aquí en adelante todo es f32. | |
| 341 | + // ROTACIÓN DE HADAMARD. Si el fichero la declara, las activaciones que entran | |
| 342 | + // a los tensores enumerados hay que girarlas antes del matmul. No aplicarla no | |
| 343 | + // falla: carga, ejecuta y devuelve ruido con cara de respuesta. | |
| 344 | + const rot = leeRotacion((model.g && model.g.meta) || {}); | |
| 345 | + const bufSignos = new Map(); // anchura -> buffer subido una sola vez | |
| 346 | + const signosDe = (ancho) => { | |
| 347 | + if (!bufSignos.has(ancho)) { | |
| 348 | + const v = rot.signos.get(ancho); | |
| 349 | + if (!v) throw new Error(`la rotación no trae signos para la anchura ${ancho}`); | |
| 350 | + // NO se pide al pozo de buffers: `ctx.alloc` entrega memoria reciclable y | |
| 351 | + // `recycle()` la devuelve, así que el mismo buffer acababa siendo el | |
| 352 | + // DESTINO de otra operación dentro del mismo pase — y WebGPU lo rechaza | |
| 353 | + // con «includes writable usage and another usage in the same | |
| 354 | + // synchronization scope», que no dice ni una palabra de reciclaje. Los | |
| 355 | + // signos viven lo que vive el modelo, como los pesos. | |
| 356 | + const buf = device.createBuffer({ | |
| 357 | + label: `signos.${ancho}`, size: v.byteLength, | |
| 358 | + usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, | |
| 359 | + }); | |
| 360 | + device.queue.writeBuffer(buf, 0, v); | |
| 361 | + bufSignos.set(ancho, buf); | |
| 362 | + } | |
| 363 | + return bufSignos.get(ancho); | |
| 364 | + }; | |
| 365 | + // Varios tensores comparten la MISMA activación de entrada (por ejemplo la | |
| 366 | + // proyección fusionada y la puerta, las dos tras la misma norma). Sin memoria | |
| 367 | + // se giraría lo mismo dos veces: correcto y tirado a la basura. | |
| 368 | + let memoRot = new Map(); | |
| 369 | + // Geometría del reordenado de rasgos que pide `gdn_v_grouped`. Solo lo lleva | |
| 370 | + // la salida del SSM: su activación llega por teselas [hd, nk, rep] y el peso | |
| 371 | + // se guardó agrupado [hd, rep, nk]. Los nombres salen de la cabecera, no de | |
| 372 | + // constantes: n_v es el rango del paso temporal y n_k el número de grupos. | |
| 373 | + const meta = (model.g && model.g.meta) || {}; | |
| 374 | + const clave = (suf) => Object.keys(meta).find((k) => k.endsWith(suf)); | |
| 375 | + const nV = Number(meta[clave('.ssm.time_step_rank')] || 0); | |
| 376 | + const nK = Number(meta[clave('.ssm.group_count')] || 0); | |
| 377 | + const permDe = (name, ancho) => { | |
| 378 | + if (!rot || !rot.vGrouped || !name.includes('.ssm_out.')) return null; | |
| 379 | + if (!nV || !nK || nV % nK !== 0 || ancho % nV !== 0) { | |
| 380 | + throw new Error(`geometría de cabezas incompatible con el reordenado: ancho ${ancho}, n_v ${nV}, n_k ${nK}`); | |
| 381 | + } | |
| 382 | + return { hd: ancho / nV, nk: nK, rep: nV / nK }; | |
| 383 | + }; | |
| 384 | + const giraEntrada = async (x, ancho, tokens, perm) => { | |
| 385 | + // La clave lleva el reordenado: `ssm_out` comparte la activación de entrada | |
| 386 | + // con otros tensores pero su transformada NO es la misma, y compartir la | |
| 387 | + // memoria entre los dos daría el resultado del primero que pasara. | |
| 388 | + const k = perm ? `${perm.hd}:${perm.nk}:${perm.rep}` : 'llana'; | |
| 389 | + // La MISMA activación alimenta varios tensores —`nrm` va a siete matmuls en | |
| 390 | + // una capa— y para todos salvo `ssm_out` la rotación es idéntica. Sin | |
| 391 | + // memoria se calcula una vez por matmul: cientos de veces por token, y cada | |
| 392 | + // una escribe su resultado a memoria para que el matmul lo lea de vuelta. | |
| 393 | + // | |
| 394 | + // La memoria estuvo APAGADA por una razón buena: se indexaba por el buffer, | |
| 395 | + // y los buffers se reciclan, así que el que fue una activación podía ser | |
| 396 | + // otra distinta más adelante y la segunda recibía la rotación de la primera. | |
| 397 | + // No fallaba, no avisaba, y el modelo decía ruido. | |
| 398 | + // | |
| 399 | + // Ahora la clave es la MARCA DE REPARTO (`ctx.marcaDe`): el pozo le pone un | |
| 400 | + // número distinto a cada buffer cada vez que lo entrega, de modo que un | |
| 401 | + // buffer reciclado es un valor nuevo y no puede alias con el anterior. | |
| 402 | + // Sin marca —un buffer que no salió del pozo— no se memoriza nada: es | |
| 403 | + // preferible repetir el trabajo a arriesgarse a devolver lo que no es. | |
| 404 | + const marca = ops.ctx.marcaDe?.get(x); | |
| 405 | + if (marca === undefined || globalThis.__ELFFUSS_ROT_MEMO === false) { | |
| 406 | + return await nn.hadamard(x, signosDe(ancho), { rows: tokens, ancho, bloque: rot.bloque, perm }); | |
| 407 | + } | |
| 408 | + const clave = `${marca}:${k}`; | |
| 409 | + // Diagnóstico: sin contar aciertos no se sabe si la memoria sirve. Un x1,00 | |
| 410 | + // puede ser «no hay nada que ahorrar» o «no está acertando», y son cosas | |
| 411 | + // muy distintas. | |
| 412 | + ops.ctx.rotStats = ops.ctx.rotStats || { acierto: 0, fallo: 0 }; | |
| 413 | + if (memoRot.has(clave)) { ops.ctx.rotStats.acierto++; return memoRot.get(clave); } | |
| 414 | + ops.ctx.rotStats.fallo++; | |
| 415 | + const y = await nn.hadamard(x, signosDe(ancho), { rows: tokens, ancho, bloque: rot.bloque, perm }); | |
| 416 | + memoRot.set(clave, y); | |
| 417 | + return y; | |
| 418 | + }; | |
| 419 | + // Cuenta cuántos tensores rotados se han visto de verdad. Si el fichero | |
| 420 | + // declara 401 y el forward toca 12, algo no encaja y hay que enterarse. | |
| 421 | + const rotVistos = new Set(); | |
| 422 | + | |
| 423 | + const mm = async (name, x, rows, k, tokens) => { | |
| 424 | + const w = W(name); | |
| 425 | + let xin = x; | |
| 426 | + if (rot && rot.pesos.has(name)) { | |
| 427 | + rotVistos.add(name); | |
| 428 | + xin = await giraEntrada(x, k, tokens, permDe(name, k)); | |
| 429 | + } | |
| 430 | + return quant.matmul(w.t.typeName, w.buf, xin, rows, k, tokens); | |
| 431 | + }; | |
| 432 | + | |
| 433 | + // Los pesos F32 (normas, ssm_a, dt) se usan tal cual; los cuantizados pasan | |
| 434 | + // por el matmul, que descuantiza dentro del shader. | |
| 435 | + const pipe = ctx.pipeline; | |
| 436 | + const eps = hp.eps; | |
| 437 | + const D = hp.headDim, H = hp.heads, KVH = hp.kvHeads, E = hp.embd; | |
| 438 | + const SH = hp.ssmHeads; // cabezas de CLAVE (q, k) | |
| 439 | + const SV = hp.ssmVHeads; // cabezas de VALOR (v, alpha, beta, salida) | |
| 440 | + const SS = hp.ssmState, CC = hp.convChannels, CK = hp.convKernel; | |
| 441 | + const KEY = SH * SS; // key_dim = value_dim = 2048 en el 0.8B | |
| 442 | + | |
| 443 | + async function gather(idsBuf, tokens) { | |
| 444 | + const w = W('token_embd.weight'); | |
| 445 | + const z = await quant.gather(w.t.typeName, w.buf, idsBuf, E, tokens); | |
| 446 | + // La tabla guarda las filas YA giradas, así que aquí se deshace: h = s ⊙ (H z). | |
| 447 | + // Los signos van DESPUÉS, al revés que en el camino normal — es la inversa, | |
| 448 | + // y confundir el orden no falla, da ruido. | |
| 449 | + if (rot && rot.inversos.has('token_embd.weight')) { | |
| 450 | + rotVistos.add('token_embd.weight'); | |
| 451 | + return await nn.hadamard(z, signosDe(E), { rows: tokens, ancho: E, bloque: rot.bloque, inverso: true }); | |
| 452 | + } | |
| 453 | + return z; | |
| 454 | + } | |
| 455 | + | |
| 456 | + const raw = (label, p, buffers, groups) => ops.dispatchAny(label, p, buffers, groups); | |
| 457 | + | |
| 458 | + async function silu(src, n) { | |
| 459 | + const p = await pipe('silu', siluShader()); | |
| 460 | + const dst = ctx.alloc(n * 4, 'silu'); | |
| 461 | + const params = ctx.uniform([new Uint32Array([n, 0, 0, 0])]); | |
| 462 | + await raw('silu', p, [src, dst, params], Math.ceil(n / 256)); | |
| 463 | + return dst; | |
| 464 | + } | |
| 465 | + | |
| 466 | + // `dstF16` va en la CLAVE del pipeline, no solo en el shader: con una sola | |
| 467 | + // clave, la primera llamada fijaría el compilado y la segunda escribiría con | |
| 468 | + // el tipo de la primera. La caché saldría escrita a medias y sin un error. | |
| 469 | + async function copyInto(src, dst, dstOffset, n, srcOffset = 0, dstF16 = false) { | |
| 470 | + const p = await pipe(`copy_into${dstF16 ? '_h' : ''}`, copyIntoShader(256, dstF16)); | |
| 471 | + const params = ctx.uniform([new Uint32Array([n, dstOffset, srcOffset, 0])]); | |
| 472 | + await raw('copy_into', p, [src, dst, params], Math.ceil(n / 256)); | |
| 473 | + } | |
| 474 | + | |
| 475 | + // Corte contiguo de una fila ancha: q, k y v salen del mismo tensor de 6144. | |
| 476 | + const slice = (src, offset, width, tokens, rowWidth) => | |
| 477 | + attn.strideCopy(src, { headDim: width, heads: 1, tokens, stride: rowWidth, offset }); | |
| 478 | + | |
| 479 | + // El cierre común de los dos tipos de bloque: residual, norm, SwiGLU, residual. | |
| 480 | + async function feedForward(x, layerOut, i, tokens) { | |
| 481 | + const n = tokens * E; | |
| 482 | + const res = await nn.add(x, layerOut, n); | |
| 483 | + // El nombre sale del perfil, no de `has(...)`: si se decidiera por presencia | |
| 484 | + // del tensor, un modelo al que le faltara dejaría de fallar y empezaría a | |
| 485 | + // mentir con una norma menos. | |
| 486 | + const nrm = await nn.rmsnorm(res, get(`blk.${i}.${hp.ffnNorm}.weight`), tokens, E, eps); | |
| 487 | + const gate = await mm(`blk.${i}.ffn_gate.weight`, nrm, hp.ffnLength, E, tokens); | |
| 488 | + const up = await mm(`blk.${i}.ffn_up.weight`, nrm, hp.ffnLength, E, tokens); | |
| 489 | + // La intermedia del FFN lleva sonda. No es simetría con los otros nodos: | |
| 490 | + // las tres matrices del FFN son dos tercios de los pesos del modelo, y si | |
| 491 | + // esta activación es dispersa, las columnas de `ffn_down` que multiplican a | |
| 492 | + // un canal despreciable no hace falta ni LEERLAS. Medir eso exige poder | |
| 493 | + // verla, y sin sonda no se puede. | |
| 494 | + const sw = P('ffn_sw', await nn.swiglu(gate, up, tokens * hp.ffnLength), tokens * hp.ffnLength); | |
| 495 | + const down = await mm(`blk.${i}.ffn_down.weight`, sw, E, hp.ffnLength, tokens); | |
| 496 | + return await nn.add(res, down, n); | |
| 497 | + } | |
| 498 | + | |
| 499 | + async function ssmBlock(x, i, tokens) { | |
| 500 | + capaActual = i; | |
| 501 | + const nrm = P('attn_norm', await nn.rmsnorm(x, get(`blk.${i}.attn_norm.weight`), tokens, E, eps), tokens * E); | |
| 502 | + | |
| 503 | + // qkv fusionado → ventana de conv (transposición + concatenación con el | |
| 504 | + // estado del token anterior) → conv depthwise causal → silu. | |
| 505 | + const qkv = P('qkv', await mm(`blk.${i}.attn_qkv.weight`, nrm, CC, E, tokens), tokens * CC); | |
| 506 | + const st = state.ssm.get(i); | |
| 507 | + const window = CK - 1 + tokens; | |
| 508 | + const pw = await pipe('conv_window', convWindowShader()); | |
| 509 | + const win = ctx.alloc(CC * window * 4, 'convwin'); | |
| 510 | + const pwp = ctx.uniform([new Uint32Array([CC, tokens, CK - 1, window])]); | |
| 511 | + await raw('conv_window', pw, [st.conv, qkv, win, pwp], Math.ceil(CC * window / 256)); | |
| 512 | + | |
| 513 | + const conv = P('conv_raw', await ssmOps.conv(win, get(`blk.${i}.ssm_conv1d.weight`), CC, tokens), tokens * CC); | |
| 514 | + const act = P('conv_silu', await silu(conv, CC * tokens), tokens * CC); | |
| 515 | + | |
| 516 | + // El estado de conv se guarda DESPUÉS de leer la ventana, no antes. | |
| 517 | + const ps = await pipe('conv_save', convSaveShader()); | |
| 518 | + const psp = ctx.uniform([new Uint32Array([CC, tokens, CK - 1, window])]); | |
| 519 | + await raw('conv_save', ps, [win, st.conv, psp], Math.ceil(CC * (CK - 1) / 256)); | |
| 520 | + | |
| 521 | + const qRawS = P('q_conv', await slice(act, 0, KEY, tokens, CC), tokens * KEY); | |
| 522 | + const kRawS = P('k_conv', await slice(act, KEY, KEY, tokens, CC), tokens * KEY); | |
| 523 | + const q = P('q_l2', await ssmOps.l2norm(qRawS, tokens * SH, SS, eps), tokens * KEY); | |
| 524 | + const k = P('k_l2', await ssmOps.l2norm(kRawS, tokens * SH, SS, eps), tokens * KEY); | |
| 525 | + const v = P('v_conv', await slice(act, 2 * KEY, hp.ssmInner, tokens, CC), tokens * hp.ssmInner); | |
| 526 | + | |
| 527 | + // alpha y beta salen de la ENTRADA normalizada, no del qkv ni de la conv. | |
| 528 | + const alpha = P('alpha', await mm(`blk.${i}.ssm_alpha.weight`, nrm, SV, E, tokens), tokens * SV); | |
| 529 | + const gdecay = P('gate', await ssmOps.decayGate(alpha, get(`blk.${i}.ssm_dt.bias`), | |
| 530 | + get(`blk.${i}.ssm_a`), SV, tokens), tokens * SV); | |
| 531 | + const betaRaw = await mm(`blk.${i}.ssm_beta.weight`, nrm, SV, E, tokens); | |
| 532 | + const beta = P('beta', await ssmOps.sigmoid(betaRaw, SV * tokens), tokens * SV); | |
| 533 | + | |
| 534 | + const o = P('gdn_out', await ssmOps.gatedDeltaNet(q, k, v, gdecay, beta, st.state, SV, tokens, SH), tokens * hp.ssmInner); | |
| 535 | + | |
| 536 | + // La puerta del norm final sale de su propia proyección. | |
| 537 | + // | |
| 538 | + // Los tres nodos que van de aquí al residual llevan sonda porque son el | |
| 539 | + // último tramo del bloque donde el recuento de cabezas de VALOR vuelve a | |
| 540 | + // importar: la norma con puerta normaliza por filas de SS sobre tokens×SV. | |
| 541 | + // Sin sonda, un fallo aquí no aparecía como «la norma con puerta está mal», | |
| 542 | + // aparecía como una escalera que se desvía desde el bloque 0 sin decir en | |
| 543 | + // qué operación. | |
| 544 | + const z = P('z', await mm(`blk.${i}.attn_gate.weight`, nrm, hp.ssmInner, E, tokens), tokens * hp.ssmInner); | |
| 545 | + const gn = P('gated_norm', | |
| 546 | + await ssmOps.gatedNorm(o, get(`blk.${i}.ssm_norm.weight`), z, tokens * SV, SS, eps), | |
| 547 | + tokens * hp.ssmInner); | |
| 548 | + const out = P('ssm_out', await mm(`blk.${i}.ssm_out.weight`, gn, E, hp.ssmInner, tokens), tokens * E); | |
| 549 | + return await feedForward(x, out, i, tokens); | |
| 550 | + } | |
| 551 | + | |
| 552 | + async function attnBlock(x, i, tokens, posBuf) { | |
| 553 | + capaActual = i; | |
| 554 | + const nrm = await nn.rmsnorm(x, get(`blk.${i}.attn_norm.weight`), tokens, E, eps); | |
| 555 | + | |
| 556 | + // En qwen35 `attn_q` proyecta al DOBLE —Q y una puerta INTERCALADOS por | |
| 557 | + // cabeza— y hay que partirlo. En llama proyecta a H*D y ya está, así que no | |
| 558 | + // hay nada que partir: el matmul deja [T][H*D], que es justo [T][H][D], la | |
| 559 | + // forma que esperan RoPE y los scores. Ni una copia de por medio. | |
| 560 | + let qRaw, gRaw = null; | |
| 561 | + if (hp.qGate) { | |
| 562 | + const qfull = await mm(`blk.${i}.attn_q.weight`, nrm, 2 * H * D, E, tokens); | |
| 563 | + qRaw = await attn.strideCopy(qfull, { headDim: D, heads: H, tokens, stride: 2 * D, offset: 0 }); | |
| 564 | + gRaw = await attn.strideCopy(qfull, { headDim: D, heads: H, tokens, stride: 2 * D, offset: D }); | |
| 565 | + } else { | |
| 566 | + qRaw = await mm(`blk.${i}.attn_q.weight`, nrm, H * D, E, tokens); | |
| 567 | + } | |
| 568 | + | |
| 569 | + // QK-norm ANTES de RoPE. | |
| 570 | + // | |
| 571 | + // Y el RoPE va en NEOX aunque la referencia use MRoPE intercalado (qwen35 | |
| 572 | + // declara IMROPE, con cuatro secciones de dimensiones). NO es una | |
| 573 | + // simplificación: para texto puro las dos son la MISMA función, y conviene | |
| 574 | + // dejar por qué, porque parece un bug cada vez que se lee. | |
| 575 | + // 1. El MRoPE reparte las dimensiones entre cuatro ejes de posición | |
| 576 | + // (t, h, w y uno extra) — de ahí que sea multimodal. | |
| 577 | + // 2. Con tokens de texto, llama.cpp escribe la MISMA posición en las | |
| 578 | + // cuatro ranuras, así que los cuatro ángulos valen lo mismo y da igual | |
| 579 | + // qué eje toque a cada dimensión. | |
| 580 | + // 3. Los cuatro avanzan en bloque: `indep_sects` sale de `is_vision`, que | |
| 581 | + // es falso aquí, o sea que ninguna sección reinicia su ángulo. | |
| 582 | + // 4. Y el emparejamiento de elementos es literalmente la misma llamada | |
| 583 | + // que el NEOX, `rotate_pairs(n_dims, n_dims/2)`. | |
| 584 | + // Deja de valer en cuanto entre una imagen: ahí las posiciones dejan de ser | |
| 585 | + // iguales y hace falta el MRoPE de verdad. | |
| 586 | + // ⚠️ EL MODO DE RoPE SALE DEL PERFIL, y es el cambio que más miedo da de | |
| 587 | + // toda esta lista: equivocarse NO peta. Sale texto gramatical que se | |
| 588 | + // degrada al crecer el contexto, o sea el fallo más caro de detectar que | |
| 589 | + // hay. qwen35 empareja como NEOX; llama usa NORM porque su conversor a GGUF | |
| 590 | + // ya permuta los pesos. Ver `state.js`, ARQUITECTURAS. | |
| 591 | + const modoRope = hp.ropeMode === 'norm' ? ROPE_NORM : ROPE_NEOX; | |
| 592 | + // La QK-norm tampoco es universal: llama no trae `attn_q_norm` siquiera. | |
| 593 | + const qn = hp.qkNorm | |
| 594 | + ? await nn.rmsnorm(qRaw, get(`blk.${i}.attn_q_norm.weight`), tokens * H, D, eps) | |
| 595 | + : qRaw; | |
| 596 | + const q = await nn.rope(qn, posBuf, | |
| 597 | + { rows: tokens * H, ne0: D, heads: H, nDims: hp.ropeDims, mode: modoRope, freqBase: hp.ropeFreqBase }); | |
| 598 | + | |
| 599 | + const kRaw = await mm(`blk.${i}.attn_k.weight`, nrm, KVH * D, E, tokens); | |
| 600 | + const kn = hp.qkNorm | |
| 601 | + ? await nn.rmsnorm(kRaw, get(`blk.${i}.attn_k_norm.weight`), tokens * KVH, D, eps) | |
| 602 | + : kRaw; | |
| 603 | + const k = await nn.rope(kn, posBuf, | |
| 604 | + { rows: tokens * KVH, ne0: D, heads: KVH, nDims: hp.ropeDims, mode: modoRope, freqBase: hp.ropeFreqBase }); | |
| 605 | + const v = await mm(`blk.${i}.attn_v.weight`, nrm, KVH * D, E, tokens); | |
| 606 | + | |
| 607 | + // A la caché, a partir de nPast: nunca se pisa lo ya cacheado. | |
| 608 | + const cache = state.kv.get(i); | |
| 609 | + const per = KVH * D; | |
| 610 | + // UNA sola fuente de verdad para la precisión de la caché, leída del estado | |
| 611 | + // que la reservó. Escribirla y leerla con precisiones distintas no lanza: | |
| 612 | + // devuelve basura, y por eso el dato no se repite en cuatro sitios. | |
| 613 | + const kvF16 = !!state.kvF16; | |
| 614 | + await copyInto(k, cache.k, state.nPast * per, tokens * per, 0, kvF16); | |
| 615 | + await copyInto(v, cache.v, state.nPast * per, tokens * per, 0, kvF16); | |
| 616 | + | |
| 617 | + const nKv = state.nPast + tokens; | |
| 618 | + const cfg = { headDim: D, heads: H, kvHeads: KVH, tokens, nKv, nPast: state.nPast, kvF16 }; | |
| 619 | + const scores = await attn.scores(q, cache.k, cfg); | |
| 620 | + const probs = await nn.softmax(scores, | |
| 621 | + { rows: H * tokens, nKv, nQ: tokens, nPast: state.nPast, scale: 1 / Math.sqrt(D) }); | |
| 622 | + const att = await attn.combine(probs, cache.v, cfg); | |
| 623 | + | |
| 624 | + // La puerta multiplica la salida ANTES de la proyección — cuando la hay. | |
| 625 | + // En llama la atención va directa a la proyección de salida. | |
| 626 | + let gated = att; | |
| 627 | + if (hp.qGate) { | |
| 628 | + const gsig = await ssmOps.sigmoid(gRaw, tokens * H * D); | |
| 629 | + gated = await attn.mul(att, gsig, tokens * H * D); | |
| 630 | + } | |
| 631 | + const out = await mm(`blk.${i}.attn_output.weight`, gated, E, H * D, tokens); | |
| 632 | + return await feedForward(x, out, i, tokens); | |
| 633 | + } | |
| 634 | + | |
| 635 | + // UNA pasada: la implementación de siempre, intacta. La trocea `forward`. | |
| 636 | + // | |
| 637 | + // `signal` se mira en cada FRONTERA DE CAPA, y parar no rompe el lote a | |
| 638 | + // medias: se deja de grabar, el callback devuelve null y `ctx.batch` cierra y | |
| 639 | + // envía lo grabado por su camino normal (ops.js no sabe nada de parar). Lo que | |
| 640 | + // sí hay que hacer antes de lanzar es esperar al dispositivo: los uniformes del lote | |
| 641 | + // solo se pueden reciclar después de una sincronización —ver `forward`—, y | |
| 642 | + // quien recibe el error va a reciclar. `state.advance` NO se llama: el lote no | |
| 643 | + // terminó, así que nPast sigue donde estaba y lo que se escribió en la caché | |
| 644 | + // por encima queda tapado por la máscara causal. El estado recurrente sí quedó | |
| 645 | + // a medias, y por eso todo turno empieza con `restaura()` o `reset()`. | |
| 646 | + const unaPasada = async (tokenIds, { tap = null, todosLosLogits = false, signal = null } = {}) => { | |
| 647 | + let logitsTokens = 1; | |
| 648 | + let parado = false; | |
| 649 | + const tokens = tokenIds.length; | |
| 650 | + const taps = new Map(); | |
| 651 | + const idsBuf = ctx.alloc(tokens * 4, 'ids'); | |
| 652 | + device.queue.writeBuffer(idsBuf, 0, new Uint32Array(tokenIds)); | |
| 653 | + const posBuf = ctx.alloc(tokens * 4, 'pos'); | |
| 654 | + device.queue.writeBuffer(posBuf, 0, | |
| 655 | + Int32Array.from({ length: tokens }, (_, i) => state.nPast + i)); | |
| 656 | + | |
| 657 | + memoRot = new Map(); // la memoria de rotación vale para UN forward | |
| 658 | + conservadas = new Set(); // y lo que las sondas pidan conservar, también | |
| 659 | + const logits = await ops.batch('forward', async () => { | |
| 660 | + let x = await gather(idsBuf, tokens); | |
| 661 | + // El índice −1 es el embedding, antes de la primera capa. No es un | |
| 662 | + // capricho de simetría: si los ids o la tabla se leen mal, TODAS las | |
| 663 | + // capas se desvían y la escalera señala la 0 sin distinguir «entré mal» | |
| 664 | + // de «la capa 0 calcula mal». Con este ancla esa duda se resuelve. | |
| 665 | + if (tap && tap.has(-1)) taps.set(-1, x); | |
| 666 | + let capaN = 0; | |
| 667 | + // Arranca en «ya toca»: la primera capa de un prefill largo es un buen | |
| 668 | + // momento para dejar pintar, y no depender del reloj del forward anterior. | |
| 669 | + let ultimoRespiro = -Infinity; | |
| 670 | + for (const l of hp.layers) { | |
| 671 | + if (signal?.aborted) { parado = true; break; } | |
| 672 | + // Se recicla lo de CADA capa en cuanto termina, en vez de guardarlo | |
| 673 | + // todo hasta el final del forward. Sin esto el pico de memoria del dispositivo | |
| 674 | + // crecía con capas × tokens, o sea que con un prompt normal llegaba a | |
| 675 | + // pedir varias veces lo que pesa el modelo entero — y el factor empeora | |
| 676 | + // cuantas más capas tiene. | |
| 677 | + const marca = ctx.scratch.length; | |
| 678 | + const previo = x; | |
| 679 | + x = l.kind === 'ssm' | |
| 680 | + ? await ssmBlock(x, l.index, tokens) | |
| 681 | + : await attnBlock(x, l.index, tokens, posBuf); | |
| 682 | + if (tap && tap.has(l.index)) taps.set(l.index, x); | |
| 683 | + // Vivos: la salida de esta capa (entra en la siguiente), la entrada si | |
| 684 | + // el bloque la devolvió tal cual, y cualquier tensor con sonda puesta, | |
| 685 | + // que el llamador va a leer DESPUÉS del forward. | |
| 686 | + ctx.recycleDesde(marca, x, previo, ...taps.values(), ...conservadas); | |
| 687 | + // Trocear el forward para no colgar el ordenador. SOLO en prefill | |
| 688 | + // (tokens>1): el decode es 1 token y nunca colgó, y trocearlo lo | |
| 689 | + // ralentizaría sin motivo. Se corta el command buffer en CADA capa | |
| 690 | + // (barato: solo un submit más) y de vez en cuando se drena la cola y se | |
| 691 | + // cede un frame, para que el compositor tenga su hueco. No cambia la | |
| 692 | + // numérica: el orden de la cola se respeta. Ver ctx.corta. | |
| 693 | + // | |
| 694 | + // El troceo es GRATIS y va en todas las capas; el respiro es CARO (drena | |
| 695 | + // la cola, que mata el solape entre la CPU y el dispositivo, y encima espera | |
| 696 | + // al refresco) y va | |
| 697 | + // limitado por reloj. Ver `cederMs`: antes iba atado al contador de capas | |
| 698 | + // y era lo que fijaba el techo del prefill. | |
| 699 | + if (tokens > 1) { | |
| 700 | + const toca = (capaN + 1) % cortaCada === 0; | |
| 701 | + // El respiro drena la cola; si el pase sigue abierto, lo que drena es | |
| 702 | + // una cola VACÍA —el trabajo ni se ha enviado— y se paga el frame sin | |
| 703 | + // conseguir el hueco que se buscaba. Así que cuando el respiro va a | |
| 704 | + // entrar, se corta aunque no tocase por intervalo. | |
| 705 | + const respira = (capaN + 1) % cederCada === 0 && performance.now() - ultimoRespiro >= cederMs; | |
| 706 | + if (toca || respira) ctx.corta(); | |
| 707 | + capaN++; | |
| 708 | + if (respira) { | |
| 709 | + await device.queue.onSubmittedWorkDone(); | |
| 710 | + await nuevoFrame(signal); | |
| 711 | + ultimoRespiro = performance.now(); | |
| 712 | + } | |
| 713 | + } | |
| 714 | + } | |
| 715 | + // La última frontera: tras la última capa solo queda la cabeza, y unos | |
| 716 | + // logits que nadie va a leer no merecen la espera. | |
| 717 | + if (signal?.aborted) parado = true; | |
| 718 | + if (parado) return null; | |
| 719 | + const nrm = await nn.rmsnorm(x, get('output_norm.weight'), tokens, E, eps); | |
| 720 | + // SOLO EL ÚLTIMO TOKEN. La cabeza es la matriz más grande del modelo | |
| 721 | + // (vocabulario × embedding) y para generar solo hace falta la última fila: | |
| 722 | + // calcularla para todo el prompt costaba cientos de veces más, y se pagaba | |
| 723 | + // por N−1 vectores de logits que se descartan enteros. | |
| 724 | + let entradaCabeza = nrm, tokensCabeza = tokens; | |
| 725 | + if (!todosLosLogits && tokens > 1) { | |
| 726 | + const fila = ctx.alloc(E * 4, 'ultimo'); | |
| 727 | + await copyInto(nrm, fila, 0, E, (tokens - 1) * E); | |
| 728 | + entradaCabeza = fila; tokensCabeza = 1; | |
| 729 | + } | |
| 730 | + const head = has('output.weight') ? 'output.weight' : 'token_embd.weight'; | |
| 731 | + logitsTokens = tokensCabeza; | |
| 732 | + return await mm(head, entradaCabeza, model.g.meta['tokenizer.ggml.tokens'].length, | |
| 733 | + E, tokensCabeza); | |
| 734 | + }); | |
| 735 | + | |
| 736 | + if (parado) { | |
| 737 | + // La espera va ANTES de lanzar, no es opcional: ver arriba. | |
| 738 | + await device.queue.onSubmittedWorkDone(); | |
| 739 | + throw errorParado(); | |
| 740 | + } | |
| 741 | + state.advance(tokens); | |
| 742 | + // `logitsTokens` dice para CUÁNTOS tokens hay logits: casi siempre 1, | |
| 743 | + // aunque `tokens` sea el prompt entero. Sin este dato, quien deduzca el | |
| 744 | + // tamaño del vocabulario dividiendo por `tokens` se equivoca. | |
| 745 | + return { logits, tokens, logitsTokens, taps }; | |
| 746 | + }; | |
| 747 | + | |
| 748 | + // DIAGNÓSTICO DE COBERTURA. El fichero enumera cuántos tensores llevan | |
| 749 | + // rotación; si el forward toca muchos menos, hay un camino que se la salta — | |
| 750 | + // y eso no falla, devuelve ruido. | |
| 751 | + const _rotacion = () => (rot ? { | |
| 752 | + declarados: rot.pesos.size, inversos: rot.inversos.size, | |
| 753 | + aplicados: rotVistos.size, bloque: rot.bloque, | |
| 754 | + faltan: [...rot.pesos, ...rot.inversos].filter((n) => !rotVistos.has(n)), | |
| 755 | + } : null); | |
| 756 | + | |
| 757 | + return { | |
| 758 | + _rotacion, | |
| 759 | + state, | |
| 760 | + hp, | |
| 761 | + | |
| 762 | + // Ejecuta el forward y devuelve los logits del ÚLTIMO token. | |
| 763 | + // `tap` permite pedir el residual de una capa concreta para compararlo con | |
| 764 | + // el oráculo: es la diferencia entre «el texto suena raro» y «el bloque 7 | |
| 765 | + // se desvía y los seis anteriores cuadran». | |
| 766 | + // Prefill TROCEADO. La máscara causal se aplica en el softmax, DESPUÉS de | |
| 767 | + // calcular los scores, así que una pasada de N tokens calcula la matriz | |
| 768 | + // N×N entera y tira la mitad. Troceando, cada lote solo se mide contra lo | |
| 769 | + // que ya hay: para 1347 tokens en lotes de 512 son 1,22 M de posiciones en | |
| 770 | + // vez de 1,81 M, y la diferencia CRECE con la longitud (×1,6 a 2048, ×1,78 | |
| 771 | + // a 4096). Es la parte «superlineal» que la medida del prefill detectó y la | |
| 772 | + // razón de que llama.cpp —que trocea por defecto— fuera 58× más rápido. | |
| 773 | + // | |
| 774 | + // No toca ningún kernel ni la numérica: es la misma maquinaria del decode, | |
| 775 | + // con nPast avanzando entre lotes. Lo que cambia es cuánto trabajo inútil | |
| 776 | + // se hace, no el resultado. | |
| 777 | + // | |
| 778 | + // PARAR: `opts.signal` (un AbortSignal) se mira al entrar, entre lotes y en | |
| 779 | + // cada frontera de capa dentro de un lote. Al entrar no se toca nada; entre | |
| 780 | + // lotes, nPast queda al final del último lote completo; dentro de uno, donde | |
| 781 | + // empezó ese lote. Las tres salidas lanzan un AbortError y dejan el | |
| 782 | + // dispositivo en reposo, así que `recycle()` es seguro justo después. Todo lote terminado | |
| 783 | + // se avisa por `onProgress`, también el último antes del «para»: lo que se | |
| 784 | + // cuenta es trabajo hecho, y nPast lo incluye. | |
| 785 | + async forward(tokenIds, opts = {}) { | |
| 786 | + const senal = opts.signal || null; | |
| 787 | + if (senal?.aborted) throw errorParado(); | |
| 788 | + // 128 y no 512, y la razón NO es la memoria: es que el dispositivo tiene que poder | |
| 789 | + // ATENDER AL ESCRITORIO entre despacho y despacho. El bucle del SSM recorre | |
| 790 | + // todos los tokens del lote DENTRO de un solo despacho, sin ceder; con 512 | |
| 791 | + // ese núcleo corre largo, y el sistema puede matar la sesión gráfica cuando | |
| 792 | + // el compositor no consigue pintar dentro del plazo de su vigilante. | |
| 793 | + // | |
| 794 | + // Trocear más fino además REDUCE trabajo: la máscara causal se aplica en el | |
| 795 | + // softmax, o sea que cada lote calcula su matriz entera; a lotes más cortos, | |
| 796 | + // menos posiciones enmascaradas se calculan para tirarlas. | |
| 797 | + const LOTE = loteActual; | |
| 798 | + // Con `tap` NO se trocea: la referencia contra la que se compara sale de | |
| 799 | + // UNA pasada, y comparar 64 escalones contra tres pasadas concatenadas no | |
| 800 | + // significa nada. Con `todosLosLogits` | |
| 801 | + // tampoco, porque troceando solo sobreviven los del último lote. | |
| 802 | + // `onProgress(hechos, total)` se llama DESPUÉS de cada lote, que es justo | |
| 803 | + // después de esperar a que el dispositivo lo termine. Así lo que se reporta es | |
| 804 | + // trabajo HECHO y no encolado: una barra que avanza por encolado llega al | |
| 805 | + // 100 % y se queda ahí mientras el dispositivo sigue, que es peor que no tenerla. | |
| 806 | + const avisa = typeof opts.onProgress === 'function' ? opts.onProgress : null; | |
| 807 | + if (opts.tap || opts.todosLosLogits || tokenIds.length <= LOTE) { | |
| 808 | + const r = await unaPasada(tokenIds, opts); | |
| 809 | + avisa?.(tokenIds.length, tokenIds.length); | |
| 810 | + return r; | |
| 811 | + } | |
| 812 | + let ultimo = null; | |
| 813 | + for (let i = 0; i < tokenIds.length; i += LOTE) { | |
| 814 | + ultimo = await unaPasada(tokenIds.slice(i, i + LOTE), opts); | |
| 815 | + // ESPERAR a que el lote termine en el dispositivo antes de encolar el siguiente. | |
| 816 | + // Los buffers uniform se reciclan ENTRE lotes (ops.js lo dice: «se | |
| 817 | + // reciclan entre lotes, no dentro»), y eso solo es seguro si hay una | |
| 818 | + // sincronización en medio. El bucle de decode la tiene sin buscarla, | |
| 819 | + // porque lee los logits en cada paso; aquí no había ninguna, así que el | |
| 820 | + // lote siguiente reutilizaba uniformes que el anterior todavía no había | |
| 821 | + // consumido. El resultado no era un error: era OTRO token (197 en vez | |
| 822 | + // de 62), que es la peor forma de fallar porque sale texto plausible. | |
| 823 | + await device.queue.onSubmittedWorkDone(); | |
| 824 | + // El aviso va JUSTO DESPUÉS de esa espera y ANTES de mirar la señal: el | |
| 825 | + // lote ya está hecho y nPast lo incluye, así que se cuenta aunque el | |
| 826 | + // prefill se pare aquí mismo. Callarlo dejaría el progreso un lote por | |
| 827 | + // detrás de lo que de verdad entró. Quien no quiera avisos después de | |
| 828 | + // un «para» los filtra él: el proveedor deja de pasarlos a `onPrefill` | |
| 829 | + // en cuanto nota la señal. | |
| 830 | + avisa?.(Math.min(i + LOTE, tokenIds.length), tokenIds.length); | |
| 831 | + // Y ahora la señal, con el dispositivo parado y nPast al final del último lote | |
| 832 | + // completo. Tras el último lote no se mira: el trabajo ya está hecho y | |
| 833 | + // tirarlo no ahorra nada, así que el forward termina y el «para» lo | |
| 834 | + // nota quien llama en su siguiente comprobación. | |
| 835 | + if (senal?.aborted && i + LOTE < tokenIds.length) throw errorParado(); | |
| 836 | + } | |
| 837 | + // `tokens` se corrige al total: quien lo lea espera cuántos entraron, no | |
| 838 | + // cuántos traía el último lote. | |
| 839 | + return { ...ultimo, tokens: tokenIds.length }; | |
| 840 | + }, | |
| 841 | + | |
| 842 | + | |
| 843 | + recycle: () => ctx.recycle(), | |
| 844 | + destroy: () => state.destroy(), | |
| 845 | + }; | |
| 846 | +} |
added js/ops.js +1344 −0
| @@ -0,0 +1,1344 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · operaciones del motor sobre WebGPU. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// Envuelve los shaders en pipelines reutilizables. Los pipelines se compilan UNA | |
| 6 | +// vez y se cachean: crearlos por llamada mete una compilación de shader en el | |
| 7 | +// bucle de decode, que es un desastre silencioso — no falla, solo va veinte | |
| 8 | +// veces más lento. | |
| 9 | +// | |
| 10 | +// Todo lo que crea recursos va envuelto en scopes de error: en WebGPU un binding | |
| 11 | +// mal alineado no lanza, devuelve ceros, y una capa que devuelve ceros produce | |
| 12 | +// texto plausible sin un solo error en consola. | |
| 13 | +// | |
| 14 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 15 | +import { guard as rawGuard } from './device.js'; | |
| 16 | + | |
| 17 | +// guard() cuesta una ida y vuelta al device timeline por llamada. Imprescindible | |
| 18 | +// al arrancar y en los tests; en el bucle de decode, con 423 operaciones por | |
| 19 | +// token, es el propio diagnostico el que domina el tiempo. | |
| 20 | +async function guard(device, label, fn, on = true) { | |
| 21 | + return on ? await rawGuard(device, label, fn) : await fn(); | |
| 22 | +} | |
| 23 | +import { | |
| 24 | + dequantShader, matmulShader, gatherShader, QUANT_TYPES, AXIS, sgFilasPorGrupo, | |
| 25 | +} from './kernels.wgsl.js'; | |
| 26 | +// Matmul de decode con VARIAS FILAS por workgroup. Existe porque cada fila de | |
| 27 | +// salida se relee la fila ENTERA de activaciones: por token se mueven unos 20,5 | |
| 28 | +// bytes de activacion por cada byte de peso. Ese trafico no puede estar saliendo | |
| 29 | +// de DRAM —la razon medida se pasa del ancho de banda disponible— asi que sale de | |
| 30 | +// cache, y es por lo que el oraculo X_FIJA mide que traer `x` es el termino mayor | |
| 31 | +// del matmul. Con N filas por workgroup ese trafico se divide entre N. | |
| 32 | +import { matmulFilasShader, filasPorGrupo } from './kernels.filas.wgsl.js'; | |
| 33 | +import { matmulGemmShader, soportaGemm, tkPara, TIPOS_GEMM } from './kernels.gemm.wgsl.js'; | |
| 34 | +import { hadamardShader } from './kernels.hadamard.wgsl.js'; | |
| 35 | +import { | |
| 36 | + rmsnormShader, ropeShader, softmaxShader, swigluShader, addShader, | |
| 37 | + ROPE_NORM, ROPE_NEOX, | |
| 38 | +} from './kernels.nn.wgsl.js'; | |
| 39 | +import { | |
| 40 | + l2normShader, ssmConvShader, gatedDeltaNetShader, gatedNormShader, | |
| 41 | + decayGateShader, sigmoidShader, SSM_HEAD_DIM, SSM_CONV_K, | |
| 42 | +} from './kernels.ssm.wgsl.js'; | |
| 43 | +import { | |
| 44 | + strideCopyShader, attnScoresShader, attnCombineShader, mulShader, | |
| 45 | + attnCombineSplitShader, combineReduceShader, bloquesCombine, | |
| 46 | + attnScoresSharedShader, compartidaScores, | |
| 47 | +} from './kernels.attn.wgsl.js'; | |
| 48 | + | |
| 49 | +export { ROPE_NORM, ROPE_NEOX, SSM_HEAD_DIM, SSM_CONV_K }; | |
| 50 | + | |
| 51 | +// Perezoso a proposito: evaluarlo al cargar el modulo ataria este fichero al | |
| 52 | +// navegador y ninguna de las referencias de CPU se podria importar desde Node. | |
| 53 | +let STORAGE_RW = 0; | |
| 54 | +function storageUsage() { | |
| 55 | + if (!STORAGE_RW) { | |
| 56 | + STORAGE_RW = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST; | |
| 57 | + } | |
| 58 | + return STORAGE_RW; | |
| 59 | +} | |
| 60 | + | |
| 61 | +// Tope de workgroups por eje. Viene del shader (que recompone el índice con él), | |
| 62 | +// no de una copia local: dos constantes que se desincronicen darían filas a cero. | |
| 63 | +const DISPATCH_MAX = AXIS; | |
| 64 | + | |
| 65 | +// Tokens por tesela en prefill. Cada peso leído se aplica a este número de | |
| 66 | +// tokens, así que divide el tráfico de memoria de la matriz por otro tanto. | |
| 67 | +// Tokens por tesela en prefill. ERA 8, y ese 8 costaba casi la mitad del | |
| 68 | +// matmul del prefill sin que nadie lo hubiera medido. | |
| 69 | +// | |
| 70 | +// La aritmética del tráfico por token (la cuenta está en la cabecera de | |
| 71 | +// `kernels.filas.wgsl.js`): por cada byte de peso leído se leen unos veinte de | |
| 72 | +// activaciones (`x`). | |
| 73 | +// | |
| 74 | +// Teselar divide el PRIMERO entre `tile` y no toca el segundo: ataca como mucho | |
| 75 | +// el 4,6% del tráfico. Y a cambio APAGA las tres rutas que atacan el 95,4% | |
| 76 | +// restante, las tres por el mismo predicado `tile === 1`: la lectura vec4 de | |
| 77 | +// `x` (medida ×1,135), la guarda de token izada y el reparto de filas entre | |
| 78 | +// subgrupos. Por eso la lectura vec4 solo se notaba en decode: el prefill nunca | |
| 79 | +// la ejecutaba. | |
| 80 | +// | |
| 81 | +// MEDIDO en el 27B con 32 tokens, en dos sesiones distintas y con el orden | |
| 82 | +// alternado: tile=1 da del orden de +94% en las dos. Una medida hecha con otro | |
| 83 | +// trabajo pesado en el mismo dispositivo no vale: la contención arrastra a las | |
| 84 | +// DOS ramas hacia el mismo cuello y comprime las razones hacia 1. | |
| 85 | +// | |
| 86 | +// ⚠️ NO ES BIT A BIT EXACTO: tile=1 cambia de estructura de kernel | |
| 87 | +// (`decodeCarril` en vez de `decode`, reducción por subgrupos), o sea que cambia | |
| 88 | +// la partición de la suma. Desvío medido: 1,3e-6 de la norma contra un límite | |
| 89 | +// de 1e-4. Se valida por tolerancia, no por bytes. | |
| 90 | +// | |
| 91 | +// ⛔ Y AUN ASÍ SIGUE EN 8, porque poner 1 de defecto NO COMPILA. Se probó y | |
| 92 | +// la prueba del forward ni llegó a la numérica: error de COMPILACIÓN del WGSL, | |
| 93 | +// no de precisión. La prueba de unas formas concretas de matmul pasa; el bloque | |
| 94 | +// SSM usa otra que a tile=1 genera shader inválido. O sea: la ganancia es real | |
| 95 | +// para lo medido, y el defecto global no es viable hasta arreglar esa | |
| 96 | +// generación. | |
| 97 | +// | |
| 98 | +// ⚠️ TODO LO DE ARRIBA ES HISTORIA, y el valor dice 1, no 8. El comentario | |
| 99 | +// decía «se revierte a 8» mientras la línea ponía 1, así que durante un tiempo | |
| 100 | +// nadie podía saber qué corría este camino leyendo el fichero. | |
| 101 | +// | |
| 102 | +// Lo que pasó es que el problema se movió de sitio: los dos tipos que usa | |
| 103 | +// producción —Q8_0 en el modelo pequeño y PQ2_0 en el grande— van por el GEMM | |
| 104 | +// teselado (`soportaGemm`), que no mira `tile` para nada. Así que el bloque SSM | |
| 105 | +// ya no llega a la forma que no compilaba, y las pruebas del forward, del modelo | |
| 106 | +// de juguete y del proveedor con el modelo grande pasan con el 1 puesto. | |
| 107 | +// | |
| 108 | +// Pero el camino de `tile` sigue vivo para todo tipo SIN soporte de GEMM | |
| 109 | +// (Q4_K, Q2_K, Q5_K, Q6_K, IQ1_S, IQ2_XXS, F16…), y ahí `tile = 1` significa | |
| 110 | +// `z = tokens`: cada peso se vuelve a leer de memoria global UNA VEZ POR TOKEN | |
| 111 | +// del lote. Con el lote de 32 son 32 relecturas del tensor entero. No muerde en | |
| 112 | +// producción y es un acantilado silencioso para cualquier GGUF de terceros con | |
| 113 | +// un solo tensor grande en Q4_K. | |
| 114 | +// | |
| 115 | +// PENDIENTE, por orden de valor: (1) añadir Q4_K/Q2_K/Q5_K a `TIRADAS` para | |
| 116 | +// sacarlos de aquí —`blockElems` 256 es múltiplo de TK=32, así que encaja—; | |
| 117 | +// (2) arreglar la generación del shader para la forma del bloque SSM a tile=1; | |
| 118 | +// (3) escribir para esos tipos un kernel teselado propio. | |
| 119 | +const TILE_PREFILL = 1; | |
| 120 | + | |
| 121 | +// Contexto compartido por todas las familias de operaciones del mismo device. | |
| 122 | +// Existe para tres cosas que solo se pueden hacer si alguien las coordina: | |
| 123 | +// agrupar todo un forward en UN submit, reciclar buffers entre tokens, y poder | |
| 124 | +// apagar los scopes de error en el bucle de decode. | |
| 125 | +function createContext(device, opts = {}) { | |
| 126 | + const cache = new Map(); | |
| 127 | + const ctx = { | |
| 128 | + device, | |
| 129 | + pass: null, // no null ⇒ se está grabando un lote | |
| 130 | + debug: opts.debug !== false, // scopes de error: sí al arrancar, no al decodificar | |
| 131 | + uniforms: [], // buffers uniform prestados en el lote actual | |
| 132 | + uniformFree: [], | |
| 133 | + scratch: [], | |
| 134 | + scratchFree: new Map(), // tamaño → [buffers] | |
| 135 | + }; | |
| 136 | + | |
| 137 | + // `code` puede ser el WGSL o una FUNCIÓN que lo construya. La diferencia no es | |
| 138 | + // de estilo: con la cadena, el argumento se evalúa ANTES de entrar aquí, así | |
| 139 | + // que el acierto de caché de la primera línea llegaba tarde — el shader se | |
| 140 | + // reconstruía entero en cada operación, miles de veces por pasada, para | |
| 141 | + // tirarlo acto seguido. Con la función, el WGSL solo se arma cuando de verdad | |
| 142 | + // hay que compilarlo. Se admiten las dos formas: hay llamadas que ya traen la | |
| 143 | + // cadena hecha y no tiene sentido envolverlas. | |
| 144 | + ctx.pipeline = async function (key, code) { | |
| 145 | + if (cache.has(key)) return cache.get(key); | |
| 146 | + const p = await guard(device, 'compilar ' + key, async () => { | |
| 147 | + const module = device.createShaderModule({ label: key, code: typeof code === 'function' ? code() : code }); | |
| 148 | + const info = await module.getCompilationInfo?.(); | |
| 149 | + const errs = (info?.messages || []).filter(m => m.type === 'error'); | |
| 150 | + if (errs.length) { | |
| 151 | + throw new Error(errs.map(m => `${key}:${m.lineNum}:${m.linePos} ${m.message}`).join('\n')); | |
| 152 | + } | |
| 153 | + return await device.createComputePipelineAsync({ | |
| 154 | + label: key, layout: 'auto', compute: { module, entryPoint: 'main' }, | |
| 155 | + }); | |
| 156 | + }, true); | |
| 157 | + cache.set(key, p); | |
| 158 | + return p; | |
| 159 | + }; | |
| 160 | + | |
| 161 | + // Solo DIAGNOSTICO: las claves de pipeline ya compiladas. Existe porque el modo | |
| 162 | + // de fallo mas caro de este repo es que dos ramas de un A/B compartan pipeline | |
| 163 | + // —el A/B sale x1,00 y se lee como «no hay ganancia» cuando lo que hay es una | |
| 164 | + // clave incompleta— y desde un test no habia forma de verlo. No toca el camino | |
| 165 | + // de ejecucion: es un lector de las claves del cache. | |
| 166 | + ctx.claves = () => [...cache.keys()]; | |
| 167 | + | |
| 168 | + // Un uniform por operación, SIEMPRE: reutilizar uno dentro del mismo lote | |
| 169 | + // sería una carrera silenciosa. queue.writeBuffer se ordena contra el submit, | |
| 170 | + // así que la segunda escritura pisaría a la primera antes de que el | |
| 171 | + // dispositivo ejecute ninguna de las dos. Se reciclan entre lotes, no dentro. | |
| 172 | + ctx.uniform = function (arrays) { | |
| 173 | + const bytes = arrays.reduce((n, a) => n + a.byteLength, 0); | |
| 174 | + const size = Math.max(16, Math.ceil(bytes / 16) * 16); | |
| 175 | + let buf = ctx.uniformFree.pop(); | |
| 176 | + if (!buf || buf.size < size) { | |
| 177 | + if (buf) buf.destroy(); | |
| 178 | + buf = device.createBuffer({ | |
| 179 | + label: 'params', size: Math.max(size, 64), | |
| 180 | + usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, | |
| 181 | + }); | |
| 182 | + } | |
| 183 | + let off = 0; | |
| 184 | + for (const a of arrays) { device.queue.writeBuffer(buf, off, a); off += a.byteLength; } | |
| 185 | + ctx.uniforms.push(buf); | |
| 186 | + return buf; | |
| 187 | + }; | |
| 188 | + | |
| 189 | + // Buffers de trabajo reciclables. Un forward crea cientos de tensores | |
| 190 | + // intermedios; sin reciclado se asignan y liberan cientos de buffers por | |
| 191 | + // token, que es trabajo del driver por nada. | |
| 192 | + // El pico de memoria prestada SIN reciclar. No es decoración: el pozo solo se | |
| 193 | + // vacía al terminar un token, así que dentro de un prefill de N tokens se | |
| 194 | + // acumulan todos los intermedios de todas las capas, y cada uno escala con N. | |
| 195 | + // Sin este número, «cuánta memoria del dispositivo pide esto» era una suposición. | |
| 196 | + ctx.picoBytes = 0; | |
| 197 | + ctx.vivosBytes = 0; | |
| 198 | + // MARCA DE REPARTO. Cada vez que el pozo entrega un buffer —nuevo o | |
| 199 | + // reciclado— le pone un número distinto. Sirve para que quien quiera | |
| 200 | + // memorizar algo DERIVADO de un buffer tenga una clave que no se pueda alias: | |
| 201 | + // indexar por el buffer en sí es inseguro porque el que fue una activación | |
| 202 | + // puede ser otra distinta más adelante en el mismo forward, y entonces la | |
| 203 | + // memoria devuelve lo que calculó para la anterior. No falla, no avisa, y el | |
| 204 | + // modelo dice ruido. Con la marca, un buffer reciclado es un valor nuevo. | |
| 205 | + let reparto = 0; | |
| 206 | + ctx.marcaDe = new WeakMap(); | |
| 207 | + ctx.alloc = function (bytes, label) { | |
| 208 | + const size = Math.max(4, Math.ceil(bytes / 256) * 256); | |
| 209 | + const free = ctx.scratchFree.get(size); | |
| 210 | + let buf = free && free.pop(); | |
| 211 | + if (!buf) buf = device.createBuffer({ label, size, usage: storageUsage() }); | |
| 212 | + ctx.marcaDe.set(buf, ++reparto); | |
| 213 | + ctx.scratch.push({ buf, size }); | |
| 214 | + ctx.vivosBytes += size; | |
| 215 | + if (ctx.vivosBytes > ctx.picoBytes) ctx.picoBytes = ctx.vivosBytes; | |
| 216 | + return buf; | |
| 217 | + }; | |
| 218 | + | |
| 219 | + // Devuelve al pozo todo lo prestado. Lo llama el modelo al terminar un token. | |
| 220 | + ctx.recycle = function () { | |
| 221 | + for (const b of ctx.uniforms) ctx.uniformFree.push(b); | |
| 222 | + ctx.uniforms = []; | |
| 223 | + for (const { buf, size } of ctx.scratch) { | |
| 224 | + if (!ctx.scratchFree.has(size)) ctx.scratchFree.set(size, []); | |
| 225 | + ctx.scratchFree.get(size).push(buf); | |
| 226 | + } | |
| 227 | + ctx.scratch = []; | |
| 228 | + ctx.vivosBytes = 0; | |
| 229 | + }; | |
| 230 | + | |
| 231 | + // Devuelve al pozo lo prestado A PARTIR de una marca, salvo los buffers que | |
| 232 | + // siguen vivos. Sirve para reciclar ENTRE CAPAS sin esperar al final del | |
| 233 | + // forward: los intermedios de la capa N están muertos en cuanto la capa N ha | |
| 234 | + // producido su salida, y guardarlos hasta el final hacía que el pico creciera | |
| 235 | + // con el número de capas Y con el de tokens a la vez (lineal en los dos, sin | |
| 236 | + // techo). | |
| 237 | + // | |
| 238 | + // Es seguro DENTRO de una misma pasada de cómputo: WebGPU garantiza que los | |
| 239 | + // despachos de una pasada se ejecutan en orden y ven lo que escribieron los | |
| 240 | + // anteriores, así que reutilizar un buffer en la capa N+1 ocurre después de | |
| 241 | + // que la capa N lo haya leído. Lo que NO sería seguro es reciclar entre | |
| 242 | + // envíos distintos sin sincronizar. | |
| 243 | + ctx.recycleDesde = function (marca, ...vivos) { | |
| 244 | + const guardar = new Set(vivos); | |
| 245 | + const quedan = []; | |
| 246 | + for (let i = marca; i < ctx.scratch.length; i++) { | |
| 247 | + const e = ctx.scratch[i]; | |
| 248 | + if (guardar.has(e.buf)) { quedan.push(e); continue; } | |
| 249 | + if (!ctx.scratchFree.has(e.size)) ctx.scratchFree.set(e.size, []); | |
| 250 | + ctx.scratchFree.get(e.size).push(e.buf); | |
| 251 | + ctx.vivosBytes -= e.size; | |
| 252 | + } | |
| 253 | + ctx.scratch.length = marca; | |
| 254 | + for (const e of quedan) ctx.scratch.push(e); | |
| 255 | + }; | |
| 256 | + | |
| 257 | + // Agrupa todo lo que ocurra dentro en UN command encoder y UN submit. Con ~423 | |
| 258 | + // operaciones por token, hacerlo por operación son ~423 sincronizaciones por | |
| 259 | + // token en vez de una, y eso es coste puro de coordinación. | |
| 260 | + ctx.batch = async function (label, fn) { | |
| 261 | + if (ctx.pass) return await fn(); // ya estamos dentro de un lote | |
| 262 | + if (ctx.profile) return await fn(); // perfilando: cada despacho lleva su propio pass | |
| 263 | + if (ctx.debug) { device.pushErrorScope('validation'); } | |
| 264 | + ctx._label = label; | |
| 265 | + ctx._enc = device.createCommandEncoder({ label }); | |
| 266 | + ctx.pass = ctx._enc.beginComputePass(ctx._descPase(label)); | |
| 267 | + let out; | |
| 268 | + try { out = await fn(); } finally { | |
| 269 | + ctx.pass.end(); | |
| 270 | + ctx.pass = null; | |
| 271 | + device.queue.submit([ctx._enc.finish()]); | |
| 272 | + ctx._enc = null; | |
| 273 | + } | |
| 274 | + if (ctx.debug) { | |
| 275 | + const err = await device.popErrorScope(); | |
| 276 | + if (err) throw new Error(`[${label}] ${err.constructor.name}: ${err.message}`); | |
| 277 | + } | |
| 278 | + return out; | |
| 279 | + }; | |
| 280 | + | |
| 281 | + // Cierra el command buffer en curso, lo ENVÍA, y abre otro — para que un | |
| 282 | + // forward largo NO sea un único despacho larguísimo que monopoliza el | |
| 283 | + // dispositivo. Troceado en varios, el dispositivo queda libre un instante entre | |
| 284 | + // ellos y el compositor del sistema puede pintar. Sin eso, un prefill largo | |
| 285 | + // deja al compositor sin pintar dentro del plazo de su vigilante, y el sistema | |
| 286 | + // puede matar la sesión gráfica. Todos los sistemas tienen un vigilante así, | |
| 287 | + // con distinto nombre y distinto plazo. | |
| 288 | + // NO cambia la numérica: el orden de la cola | |
| 289 | + // garantiza que los despachos se ejecutan igual, solo que en varias tandas. | |
| 290 | + // Solo actúa dentro de un batch (si no hay pass abierto, no hace nada). | |
| 291 | + ctx.corta = function () { | |
| 292 | + if (!ctx.pass) return; | |
| 293 | + ctx.pass.end(); | |
| 294 | + device.queue.submit([ctx._enc.finish()]); | |
| 295 | + ctx._enc = device.createCommandEncoder({ label: ctx._label }); | |
| 296 | + ctx.pass = ctx._enc.beginComputePass(ctx._descPase(ctx._label)); | |
| 297 | + }; | |
| 298 | + | |
| 299 | + // ── Perfilado por PASE, con el agrupado INTACTO (solo para medir) ─────────── | |
| 300 | + // El perfilador por despacho de abajo tiene dos límites que lo inhabilitan | |
| 301 | + // para el prefill: | |
| 302 | + // · topa en 2048 operaciones, y una sola pasada del 27B son 1652 despachos: | |
| 303 | + // el prefill de 316 tokens (16.520) no cabe ni de lejos, y pasado el tope | |
| 304 | + // los despachos se ejecutan SIN contarse; | |
| 305 | + // · rompe el agrupado — `ctx.batch` se rinde cuando está puesto — así que lo | |
| 306 | + // que mide ya no es la configuración que corre en producción. | |
| 307 | + // Esto marca los pases que `ctx.batch` y `ctx.corta` ya crean de todas formas | |
| 308 | + // (uno por capa): mismo agrupado, mismo número de submits, mismo troceado. Un | |
| 309 | + // prefill de 316 tokens son 10 pasadas × 65 pases = 650 marcas, y cabe entero. | |
| 310 | + // Es la única medida cuya suma se puede comparar con el reloj de pared. | |
| 311 | + ctx.pases = null; | |
| 312 | + ctx.perfilarPases = function (maxPases = 2048) { | |
| 313 | + maxPases = Math.min(maxPases, 2048); // el device admite 4096 queries | |
| 314 | + const querySet = device.createQuerySet({ type: 'timestamp', count: maxPases * 2 }); | |
| 315 | + const resolve = device.createBuffer({ size: maxPases * 2 * 8, usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC }); | |
| 316 | + const read = device.createBuffer({ size: maxPases * 2 * 8, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); | |
| 317 | + ctx.pases = { querySet, resolve, read, i: 0, vistos: 0, max: maxPases }; | |
| 318 | + }; | |
| 319 | + // El descriptor del pass vive en UN SOLO SITIO y lo llaman `batch` y `corta`. | |
| 320 | + // Si la decisión de «este pass lleva marca» estuviera escrita en los dos, un | |
| 321 | + // día discreparían y la mitad de los pases saldría sin medir sin un solo error. | |
| 322 | + ctx._descPase = function (label) { | |
| 323 | + const pf = ctx.pases; | |
| 324 | + if (!pf) return { label }; | |
| 325 | + pf.vistos++; // se cuenta SIEMPRE, quepa o no | |
| 326 | + if (pf.i >= pf.max) return { label }; // el hueco no se oculta: sale en `omitidos` | |
| 327 | + const idx = pf.i++; | |
| 328 | + return { label, timestampWrites: { querySet: pf.querySet, | |
| 329 | + beginningOfPassWriteIndex: idx * 2, endOfPassWriteIndex: idx * 2 + 1 } }; | |
| 330 | + }; | |
| 331 | + ctx.finProfilePases = async function () { | |
| 332 | + const pf = ctx.pases; if (!pf) return { total: 0, pases: [], vistos: 0, omitidos: 0 }; | |
| 333 | + await device.queue.onSubmittedWorkDone(); | |
| 334 | + const n = Math.min(pf.i, pf.max); | |
| 335 | + const enc = device.createCommandEncoder(); | |
| 336 | + enc.resolveQuerySet(pf.querySet, 0, n * 2, pf.resolve, 0); | |
| 337 | + enc.copyBufferToBuffer(pf.resolve, 0, pf.read, 0, n * 2 * 8); | |
| 338 | + device.queue.submit([enc.finish()]); | |
| 339 | + await pf.read.mapAsync(GPUMapMode.READ); | |
| 340 | + const ts = new BigUint64Array(pf.read.getMappedRange().slice(0)); | |
| 341 | + pf.read.unmap(); | |
| 342 | + const pases = []; | |
| 343 | + let total = 0; | |
| 344 | + for (let k = 0; k < n; k++) { | |
| 345 | + const dt = Number(ts[2 * k + 1] - ts[2 * k]); // nanosegundos | |
| 346 | + pases.push(dt); total += dt; | |
| 347 | + } | |
| 348 | + ctx.pases = null; | |
| 349 | + try { pf.querySet.destroy(); pf.resolve.destroy(); pf.read.destroy(); } catch { /* — */ } | |
| 350 | + return { total, pases, vistos: pf.vistos, omitidos: pf.vistos - n }; | |
| 351 | + }; | |
| 352 | + | |
| 353 | + // ── Perfilado por despacho con timestamp-query (solo para medir) ──────────── | |
| 354 | + // Con esto activo, cada despacho corre en su PROPIO pass con marcas de tiempo | |
| 355 | + // del dispositivo al principio y al final, y `finProfile()` devuelve los nanosegundos | |
| 356 | + // sumados por etiqueta. No es el modo normal (rompe el batching), pero es la | |
| 357 | + // única forma de saber QUÉ kernel se come el tiempo en vez de adivinarlo. | |
| 358 | + ctx.profile = null; | |
| 359 | + // `desde` salta los primeros N despachos SIN medirlos, para poder cubrir una | |
| 360 | + // pasada que no cabe en un solo juego de marcas. El tope de 2048 no es una | |
| 361 | + // elección: un query set admite 4096 marcas y cada despacho gasta dos. Una | |
| 362 | + // pasada del 27B son 2.053 despachos, o sea que se queda a cinco de caber, y | |
| 363 | + // sin esto el reparto de ese modelo era sencillamente inobtenible. | |
| 364 | + // | |
| 365 | + // Dos pasadas con `desde` distinto miden la MISMA secuencia porque el forward | |
| 366 | + // es determinista: el despacho número k es el mismo en las dos. Lo que no se | |
| 367 | + // puede es sumar sus TIEMPOS como si fueran una sola pasada —cada una es una | |
| 368 | + // tanda distinta, con sus propias condiciones—, así que quien las junte tiene | |
| 369 | + // que decir que son dos tandas. | |
| 370 | + ctx.perfilar = function (maxOps = 2000, desde = 0) { | |
| 371 | + maxOps = Math.min(maxOps, 2048); // tope: el device admite 4096 queries = 2048 ops×2 | |
| 372 | + const querySet = device.createQuerySet({ type: 'timestamp', count: maxOps * 2 }); | |
| 373 | + const resolve = device.createBuffer({ size: maxOps * 2 * 8, usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC }); | |
| 374 | + const read = device.createBuffer({ size: maxOps * 2 * 8, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); | |
| 375 | + ctx.profile = { querySet, resolve, read, i: 0, vistos: 0, labels: [], max: maxOps, desde }; | |
| 376 | + }; | |
| 377 | + ctx.finProfile = async function () { | |
| 378 | + const pf = ctx.profile; if (!pf) return { total: 0, porLabel: [] }; | |
| 379 | + await device.queue.onSubmittedWorkDone(); | |
| 380 | + const n = Math.min(pf.i, pf.max); | |
| 381 | + const enc = device.createCommandEncoder(); | |
| 382 | + enc.resolveQuerySet(pf.querySet, 0, n * 2, pf.resolve, 0); | |
| 383 | + enc.copyBufferToBuffer(pf.resolve, 0, pf.read, 0, n * 2 * 8); | |
| 384 | + device.queue.submit([enc.finish()]); | |
| 385 | + await pf.read.mapAsync(GPUMapMode.READ); | |
| 386 | + const ts = new BigUint64Array(pf.read.getMappedRange().slice(0)); | |
| 387 | + pf.read.unmap(); | |
| 388 | + const acum = new Map(), veces = new Map(); | |
| 389 | + let total = 0; | |
| 390 | + for (let k = 0; k < n; k++) { | |
| 391 | + const dt = Number(ts[2 * k + 1] - ts[2 * k]); // nanosegundos | |
| 392 | + const lab = pf.labels[k]; | |
| 393 | + acum.set(lab, (acum.get(lab) || 0) + dt); | |
| 394 | + veces.set(lab, (veces.get(lab) || 0) + 1); | |
| 395 | + total += dt; | |
| 396 | + } | |
| 397 | + ctx.profile = null; | |
| 398 | + try { pf.querySet.destroy(); pf.resolve.destroy(); pf.read.destroy(); } catch { /* — */ } | |
| 399 | + const porLabel = [...acum.entries()] | |
| 400 | + .map(([lab, ns]) => ({ lab, ns, veces: veces.get(lab) })) | |
| 401 | + .sort((a, b) => b.ns - a.ns); | |
| 402 | + // `omitidos` son los que esta tanda NO midió, por cualquier razón. `saltados` | |
| 403 | + // dice cuántos de ellos fueron a propósito (los de antes de `desde`), para | |
| 404 | + // que quien junte dos tandas pueda distinguir «esto lo cubre la otra» de | |
| 405 | + // «esto no lo cubre nadie». Sin esa distinción, un reparto incompleto se | |
| 406 | + // lee igual que uno completo. | |
| 407 | + const desde = pf.desde || 0; | |
| 408 | + const saltados = Math.min(desde, pf.vistos); | |
| 409 | + return { total, porLabel, vistos: pf.vistos, desde, saltados, | |
| 410 | + omitidos: pf.vistos - n, sinCubrir: pf.vistos - n - saltados }; | |
| 411 | + }; | |
| 412 | + | |
| 413 | + return ctx; | |
| 414 | +} | |
| 415 | + | |
| 416 | +// Graba un despacho. Dentro de un lote solo apunta; fuera, abre y cierra su | |
| 417 | +// propio encoder para que las llamadas sueltas de los tests sigan funcionando. | |
| 418 | +async function dispatch(ctx, label, pipe, buffers, x, y = 1, z = 1) { | |
| 419 | + const device = ctx.device; | |
| 420 | + const record = (pass) => { | |
| 421 | + const bg = device.createBindGroup({ | |
| 422 | + layout: pipe.getBindGroupLayout(0), | |
| 423 | + entries: buffers.map((buffer, binding) => ({ binding, resource: { buffer } })), | |
| 424 | + }); | |
| 425 | + pass.setPipeline(pipe); | |
| 426 | + pass.setBindGroup(0, bg); | |
| 427 | + pass.dispatchWorkgroups(x, y, z); | |
| 428 | + }; | |
| 429 | + if (ctx.pass) { record(ctx.pass); return; } | |
| 430 | + // Se cuentan TODOS los despachos que ve el perfilador, quepan o no. Sin esto, | |
| 431 | + // pasado el tope el despacho cae al camino normal y se ejecuta SIN contarse: | |
| 432 | + // la etiqueta que desborda sale BARATA, que es la peor forma de mentir que | |
| 433 | + // puede tener un instrumento. Con `vistos`, `finProfile` devuelve `omitidos` y | |
| 434 | + // el banco puede negarse a publicar un reparto truncado. | |
| 435 | + if (ctx.profile) ctx.profile.vistos++; | |
| 436 | + // Perfilado: cada despacho en su pass con marcas de tiempo del dispositivo. Los que | |
| 437 | + // caen antes de `desde` se ejecutan por el camino normal SIN medirse: es lo | |
| 438 | + // que permite cubrir una pasada más larga que el juego de marcas en dos | |
| 439 | + // tandas. `vistos` ya los ha contado, así que el hueco sigue siendo visible. | |
| 440 | + if (ctx.profile && ctx.profile.vistos > (ctx.profile.desde || 0) | |
| 441 | + && ctx.profile.i < ctx.profile.max) { | |
| 442 | + const pf = ctx.profile; | |
| 443 | + const idx = pf.i++; | |
| 444 | + pf.labels.push(label); | |
| 445 | + const enc = device.createCommandEncoder({ label }); | |
| 446 | + const pass = enc.beginComputePass({ timestampWrites: { | |
| 447 | + querySet: pf.querySet, beginningOfPassWriteIndex: idx * 2, endOfPassWriteIndex: idx * 2 + 1 } }); | |
| 448 | + record(pass); | |
| 449 | + pass.end(); | |
| 450 | + device.queue.submit([enc.finish()]); | |
| 451 | + return; | |
| 452 | + } | |
| 453 | + await guard(device, label, async () => { | |
| 454 | + const enc = device.createCommandEncoder({ label }); | |
| 455 | + const pass = enc.beginComputePass(); | |
| 456 | + record(pass); | |
| 457 | + pass.end(); | |
| 458 | + device.queue.submit([enc.finish()]); | |
| 459 | + }, ctx.debug); | |
| 460 | +} | |
| 461 | + | |
| 462 | +// Reparte `rows` en dos ejes cuando pasan del tope. El shader recompone con | |
| 463 | +// row = wid.x + wid.y * DISPATCH_MAX. | |
| 464 | +// Una fila por workgroup, repartiendo en dos ejes si hacen falta. | |
| 465 | +async function dispatchRows(ctx, label, pipe, buffers, rows) { | |
| 466 | + const [x, y] = rowsToDims(rows); | |
| 467 | + return dispatch(ctx, label, pipe, buffers, x, y, 1); | |
| 468 | +} | |
| 469 | + | |
| 470 | +// N workgroups planos (operaciones elemento a elemento). | |
| 471 | +async function dispatchN(ctx, label, pipe, buffers, groups) { | |
| 472 | + const [x, y] = rowsToDims(groups); | |
| 473 | + return dispatch(ctx, label, pipe, buffers, x, y, 1); | |
| 474 | +} | |
| 475 | + | |
| 476 | +// Tres ejes tal cual, para los kernels cuya rejilla ES tridimensional y no un | |
| 477 | +// contador plano disfrazado. El combine partido reparte (trozo, cabeza KV, | |
| 478 | +// token), y aplanarlo obligaría al shader a deshacer la cuenta con divisiones | |
| 479 | +// que el despacho ya sabe hacer gratis. Se comprueba cada eje contra el tope: | |
| 480 | +// pasarse NO lanza en WebGPU, invalida el command buffer y el pase se ejecuta | |
| 481 | +// sin hacer nada — ya pasó en un banco, que devolvió Infinity sin un error. | |
| 482 | +async function dispatchXYZ(ctx, label, pipe, buffers, x, y, z) { | |
| 483 | + if (x > DISPATCH_MAX || y > DISPATCH_MAX || z > DISPATCH_MAX) { | |
| 484 | + throw new Error(`${label}: la rejilla ${x}x${y}x${z} pasa del tope de ${DISPATCH_MAX} por eje`); | |
| 485 | + } | |
| 486 | + return dispatch(ctx, label, pipe, buffers, x, y, z); | |
| 487 | +} | |
| 488 | + | |
| 489 | +function rowsToDims(rows) { | |
| 490 | + return rows <= DISPATCH_MAX | |
| 491 | + ? [rows, 1] | |
| 492 | + : [DISPATCH_MAX, Math.ceil(rows / DISPATCH_MAX)]; | |
| 493 | +} | |
| 494 | + | |
| 495 | +// ── Operaciones sobre pesos cuantizados ───────────────────────────────────── | |
| 496 | +// Seis tipos con el MISMO andamio de shader (ver kernels.wgsl.js): aquí solo se | |
| 497 | +// eligen el pipeline, el tamaño de bloque y, si el tipo lo pide, la rejilla. | |
| 498 | +export function createQuantOps(device, opts = {}) { | |
| 499 | + const wgQ8 = opts.workgroupSize || 64; | |
| 500 | + // Ancho de subgrupo del dispositivo (0 = sin subgrupos o tamaño variable). Si | |
| 501 | + // lo hay, el matmul reduce con `subgroupAdd` en vez de con barreras. | |
| 502 | + const sgSize = opts.subgroupSize || 0; | |
| 503 | + const ctx = opts.ctx || createContext(device, opts); | |
| 504 | + const get = ctx.pipeline; | |
| 505 | + | |
| 506 | + const info = (type) => { | |
| 507 | + const i = QUANT_TYPES[type]; | |
| 508 | + if (!i) throw new Error(`tipo de cuantización no soportado: «${type}»`); | |
| 509 | + return i; | |
| 510 | + }; | |
| 511 | + | |
| 512 | + // Hilos por fila. Cada hilo se come un bloque entero, así que con bloques de | |
| 513 | + // 256 pesos una fila de 5.120 son 20 bloques: con 64 hilos, 44 se quedarían | |
| 514 | + // mirando. Se baja a la potencia de dos que cubre los bloques que hay. | |
| 515 | + // | |
| 516 | + // Q8_0 se queda clavado en su tamaño de siempre a propósito: es el kernel del | |
| 517 | + // bucle de decode y está medido así. Cambiarlo sin volver a medirlo sería | |
| 518 | + // adivinar. | |
| 519 | + const threadsFor = (type, bpr) => type === 'Q8_0' | |
| 520 | + ? wgQ8 | |
| 521 | + : Math.min(64, Math.max(4, 2 ** Math.ceil(Math.log2(Math.max(1, bpr))))); | |
| 522 | + | |
| 523 | + // Las rejillas de IQ1_S/IQ2_XXS se suben UNA vez por contexto y solo si algún | |
| 524 | + // tensor las pide: son tablas que un modelo todo-Q8_0 no tiene por qué | |
| 525 | + // descargar siquiera, de ahí el import dinámico. | |
| 526 | + const tables = new Map(); | |
| 527 | + async function tableBuf(name) { | |
| 528 | + if (tables.has(name)) return tables.get(name); | |
| 529 | + const mod = await import('./quant-tables.js'); | |
| 530 | + // Sin caso por defecto, un nombre de tabla NUEVO recibiría en silencio la | |
| 531 | + // rejilla de IQ2_XXS: mismo layout de bind group, sin error, y lecturas fuera | |
| 532 | + // de rango acotadas a cero. Un modelo entero saldría mal sin una sola traza. | |
| 533 | + const GRIDS = { IQ1S: mod.IQ1S_GRID, IQ2XXS: mod.IQ2XXS_GRID }; | |
| 534 | + const data = GRIDS[name]; | |
| 535 | + if (!data) throw new Error(`rejilla desconocida: «${name}»`); | |
| 536 | + const buf = device.createBuffer({ | |
| 537 | + label: 'grid_' + name, size: data.byteLength, | |
| 538 | + usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_DST, | |
| 539 | + }); | |
| 540 | + device.queue.writeBuffer(buf, 0, data); | |
| 541 | + tables.set(name, buf); | |
| 542 | + return buf; | |
| 543 | + } | |
| 544 | + | |
| 545 | + return { | |
| 546 | + // Descuantiza un tensor completo a f32. No se usa en el forward — ahí | |
| 547 | + // descuantiza el propio matmul, sin materializar nada. Existe porque es el | |
| 548 | + // kernel que permite comparar peso a peso contra la referencia de CPU, que | |
| 549 | + // es donde se caza una descodificación mal hecha. | |
| 550 | + async dequant(type, wBuf, nBlocks) { | |
| 551 | + const i = info(type); | |
| 552 | + const p = await get(`dequant_${type}`, () => dequantShader(type, wgQ8)); | |
| 553 | + const out = ctx.alloc(nBlocks * i.blockElems * 4, 'dequant.out'); | |
| 554 | + const params = ctx.uniform([new Uint32Array([nBlocks, 0, 0, 0])]); | |
| 555 | + const bufs = [wBuf, out, params]; | |
| 556 | + if (i.table) bufs.push(await tableBuf(i.table)); | |
| 557 | + await dispatchN(ctx, 'dequant', p, bufs, Math.ceil(nBlocks / wgQ8)); | |
| 558 | + return out; | |
| 559 | + }, | |
| 560 | + | |
| 561 | + // Y = A·X con A cuantizada y X token-major (k contiguo por token). | |
| 562 | + // `tokens = 1` es el matvec del decode; más es el prefill. | |
| 563 | + async matmul(type, wBuf, xBuf, rows, k, tokens = 1) { | |
| 564 | + const i = info(type); | |
| 565 | + if (k % i.blockElems !== 0) { | |
| 566 | + throw new Error(`matmul ${type}: k=${k} no es múltiplo de ${i.blockElems}`); | |
| 567 | + } | |
| 568 | + // Dos pipelines del MISMO shader: uno sin teselar para el decode (un | |
| 569 | + // token, teselar solo añadiría ramas muertas) y otro teselado para el | |
| 570 | + // prefill, donde el ahorro de relecturas de peso es todo el asunto. | |
| 571 | + const tile = tokens > 1 | |
| 572 | + ? Math.max(1, Math.min(32, (globalThis.__ELFFUSS_TILE | 0) || TILE_PREFILL)) | |
| 573 | + : 1; | |
| 574 | + const bpr = k / i.blockElems; | |
| 575 | + | |
| 576 | + // ── Camino GEMM: una tesela en memoria compartida y el acumulador en | |
| 577 | + // registros. Es un sustituto del camino de abajo con el MISMO contrato de | |
| 578 | + // entrada y salida, no un modo aparte: lo único que cambia es cómo se | |
| 579 | + // reparte el trabajo. Opt-in mientras se mide. | |
| 580 | + // `TK` (el paso del bucle sobre k) ya NO es el bloque del tipo: se elige | |
| 581 | + // aparte, porque atarlo al formato hundía la ocupación en los tipos de | |
| 582 | + // bloque grande —PQ2_0 son 128— y dejaba fuera del barrido las formas de | |
| 583 | + // 256 hilos. El porqué entero está en `kernels.gemm.wgsl.js`. | |
| 584 | + const Fg = globalThis.__ELFFUSS_GEMM_FORMA || {}; | |
| 585 | + const TKg = tkPara(type, Fg.TK); | |
| 586 | + const puedeGemm = soportaGemm(type, k, TKg); | |
| 587 | + // Un TK pedido A MANO que este tipo no sabe hacer tiene que LANZAR, no | |
| 588 | + // caerse en silencio al camino de siempre. Los otros cuatro números de la | |
| 589 | + // forma ya lanzan —los mira el constructor del shader—, pero TK lo mira | |
| 590 | + // `soportaGemm`, que devuelve un booleano: sin esto, el barrido mediría el | |
| 591 | + // matmul VIEJO y lo escribiría en la tabla como si fuera «GEMM con TK=64». | |
| 592 | + // Un número que no es lo que dice su etiqueta es peor que no tenerlo. | |
| 593 | + if (tokens > 1 && Fg.TK && !puedeGemm && TIPOS_GEMM.has(type)) { | |
| 594 | + throw new Error(`GEMM: TK=${Fg.TK} no vale para «${type}» ` + | |
| 595 | + `(bloque ${i.blockElems}, k=${k}): tiene que dividir al bloque y ser múltiplo de 4`); | |
| 596 | + } | |
| 597 | + // Por debajo de 4 tokens NI SIQUIERA la tesela estrecha alcanza al camino | |
| 598 | + // de uno en uno: medido en el modelo grande, con 2 tokens el viejo gana | |
| 599 | + // casi al doble, con 4 empatan y a partir de 8 el GEMM se despega. El | |
| 600 | + // cruce está en 4 y por eso el umbral es 4 y no «tokens > 1». | |
| 601 | + // | |
| 602 | + // No es un detalle: con 2 o 3 tokens se cae en cuanto hay un turno corto | |
| 603 | + // de conversación, que es de lo más frecuente que hace un chat. | |
| 604 | + const GEMM_DESDE = 4; | |
| 605 | + if (tokens >= GEMM_DESDE && globalThis.__ELFFUSS_GEMM !== false && puedeGemm) { | |
| 606 | + // La forma de la tesela es ajustable para el barrido. Los CINCO números | |
| 607 | + // van en la clave del pipeline: si no fueran, dos formas compartirían el | |
| 608 | + // shader ya compilado y la tabla del barrido saldría plana — el modo de | |
| 609 | + // fallo que en este repo ya produjo una conclusión falsa. TK entró en la | |
| 610 | + // clave a la vez que dejó de venir dado por el tipo: sin él, barrer TK | |
| 611 | + // mediría cuatro veces el mismo shader. | |
| 612 | + // 2×4 en un grupo de 8×8 no es lo que usa ggml-webgpu (4×4): es lo que | |
| 613 | + // salió del barrido aquí. Menos filas por hilo = menos registros vivos = | |
| 614 | + // más ondas residentes, y eso pesa más que el reúso extra que daría un | |
| 615 | + // TM mayor. Medido x2,29 contra x1,55 de 4×4. | |
| 616 | + // | |
| 617 | + // El grupo de 16×8 —128 hilos— salió por delante en un barrido y se | |
| 618 | + // llevó una tanda propia para confirmarlo: empate. La ventaja era ruido. | |
| 619 | + // Se queda 8×8, que hace lo mismo con la mitad de hilos. | |
| 620 | + // | |
| 621 | + // Esa tanda deja además un aviso sobre cómo se lee esta tabla: el MISMO | |
| 622 | + // código no da la misma razón en dos tandas distintas. No solo derivan | |
| 623 | + // los tiempos: deriva la razón. Dos factores medidos en tandas distintas | |
| 624 | + // no se comparan entre sí, ni aunque los dos sean razones. | |
| 625 | + // ── La tesela se ESTRECHA cuando el lote es corto ────────────────── | |
| 626 | + // La tesela cubre `WGN·TN` columnas de token. Con 32 columnas y un | |
| 627 | + // lote de 4 tokens se calculan 32 y se tiran 28, así que un lote de 2 | |
| 628 | + // costaba casi lo mismo que uno de 16 —medido en el modelo grande— y | |
| 629 | + // unas cinco veces lo que cuesta procesar un token solo. | |
| 630 | + // | |
| 631 | + // Eso convertía el GEMM en el camino LENTO justo donde más aparece: un | |
| 632 | + // prompt corto, un turno breve de conversación, o la ventana de una | |
| 633 | + // verificación. Medido, con 4 tokens: estrechar de 32 columnas a 4 lo | |
| 634 | + // deja casi en la mitad. | |
| 635 | + // | |
| 636 | + // Se elige por el número de tokens que de verdad hay. Las formas salen | |
| 637 | + // del mismo barrido que la ancha y todas respetan las guardas del | |
| 638 | + // constructor; la clave del pipeline ya lleva los cinco números, así | |
| 639 | + // que cada ancho compila el suyo y no se pisan. | |
| 640 | + // ⚠️ LA TESELA NO ES UNA PALANCA, y esta medido dos veces por si acaso. | |
| 641 | + // | |
| 642 | + // Se intento cambiar a 2x8 en 16x4 porque un barrido de matmuls | |
| 643 | + // AISLADOS con marcas de tiempo del dispositivo la daba x1,58 sobre esta. | |
| 644 | + // Dos cosas lo tumbaron: | |
| 645 | + // | |
| 646 | + // · el ganador del barrido CAMBIA entre pasadas — la segunda dio 2x4 | |
| 647 | + // en 32x8 como mejor y la supuesta ganadora bajo a x1,12—, o sea | |
| 648 | + // que el x1,58 era ruido. El tiempo de un matmul medido en AISLADO | |
| 649 | + // se mueve demasiado entre pasadas, con el mismo tensor y los mismos | |
| 650 | + // tokens: solo un A/B en la misma sesion sobre el forward completo | |
| 651 | + // decide algo. | |
| 652 | + // · en el PREFILL COMPLETO, con las dos teselas en la MISMA sesion y | |
| 653 | + // emparejado, el efecto es x1,03. Nada. | |
| 654 | + // | |
| 655 | + // O sea que el barrido de teselas viejo | |
| 656 | + // tenia razon, aunque midiera con reloj de pared y con una premisa | |
| 657 | + // equivocada sobre el peso del matmul: su conclusion se sostiene. | |
| 658 | + // | |
| 659 | + // Y de paso queda descartada mi hipotesis de que lo que limita el bucle | |
| 660 | + // interno son las lecturas de memoria compartida por operacion: el | |
| 661 | + // orden por tiempo no coincide en NI UNA posicion con el orden por esa | |
| 662 | + // razon, y la forma con menos lecturas por operacion es de las mas | |
| 663 | + // lentas. | |
| 664 | + const anchoTesela = (n) => (n <= 4 ? { TM: 2, TN: 1, WGM: 16, WGN: 4 } | |
| 665 | + : n <= 8 ? { TM: 2, TN: 1, WGM: 8, WGN: 8 } | |
| 666 | + : n <= 16 ? { TM: 2, TN: 2, WGM: 8, WGN: 8 } | |
| 667 | + : { TM: 2, TN: 4, WGM: 8, WGN: 8 }); | |
| 668 | + const A = anchoTesela(tokens); | |
| 669 | + const G = { | |
| 670 | + TM: Fg.TM || A.TM, TN: Fg.TN || A.TN, WGM: Fg.WGM || A.WGM, WGN: Fg.WGN || A.WGN, TK: TKg, | |
| 671 | + // El tope real del dispositivo, no un 32768 supuesto: así una forma que | |
| 672 | + // no cabe se RECHAZA con un mensaje que dice cuánto pedía, en vez de | |
| 673 | + // reventar la validación de WebGPU con un texto genérico. | |
| 674 | + maxCompartida: device.limits.maxComputeWorkgroupStorageSize, | |
| 675 | + }; | |
| 676 | + const FILAS_WG = G.WGM * G.TM, TOKS_WG = G.WGN * G.TN; | |
| 677 | + // El relleno de la tesela ENTRA EN LA CLAVE. Es una constante del | |
| 678 | + // shader: sin ella en la clave, cambiar `__ELFFUSS_PAD_TESELA` en | |
| 679 | + // caliente devolvería el pipeline ya compilado con el valor viejo, y un | |
| 680 | + // A/B mediría el MISMO shader dos veces creyendo medir dos. Vale para | |
| 681 | + // cualquier interruptor que cambie el WGSL generado. | |
| 682 | + const pad = globalThis.__ELFFUSS_PAD_TESELA === 1 ? 1 : 0; | |
| 683 | + const llano = globalThis.__ELFFUSS_GEMM_PLANO === true ? 1 : 0; | |
| 684 | + const pg = await get(`gemm_${type}_${G.TM}_${G.TN}_${G.WGM}_${G.WGN}_k${G.TK}_p${pad}_f${llano}`, | |
| 685 | + () => matmulGemmShader(type, G)); | |
| 686 | + const y = ctx.alloc(rows * tokens * 4, 'matmul.y'); | |
| 687 | + const params = ctx.uniform([new Uint32Array([rows * bpr, bpr, rows, k, tokens, 0, 0, 0])]); | |
| 688 | + const bufs = [wBuf, xBuf, y, params]; | |
| 689 | + if (i.table) bufs.push(await tableBuf(i.table)); | |
| 690 | + const [gx, gy] = rowsToDims(Math.ceil(rows / FILAS_WG)); | |
| 691 | + await dispatch(ctx, `gemm:${type}:r${rows}b${bpr}`, pg, bufs, | |
| 692 | + gx, gy, Math.ceil(tokens / TOKS_WG)); | |
| 693 | + return y; | |
| 694 | + } | |
| 695 | + | |
| 696 | + // Con subgrupos: el workgroup es EXACTAMENTE un subgrupo (ancho = sgSize) y | |
| 697 | + // la reducción va sin barreras. Sin ellos, el reparto de hilos de siempre. | |
| 698 | + const subgroup = !globalThis.__ELFFUSS_NO_SUBGROUP && sgSize >= 32; | |
| 699 | + // Ancho del workgroup en la ruta de subgrupos = múltiplo del tamaño de | |
| 700 | + // subgrupo. Más ancho = más hilos por fila = mejor se esconde la latencia | |
| 701 | + // de las lecturas dependientes del dequant i-quant. Tunable para A/B. | |
| 702 | + // Subgrupos por workgroup: cada uno lleva SU fila de salida. Sube ondas | |
| 703 | + // residentes sin quitar trabajo a nadie. La clave de pipeline ya lleva `wg`. | |
| 704 | + const sgf = Math.max(1, Math.min(8, (globalThis.__ELFFUSS_SG_FILAS | 0) || 1)); | |
| 705 | + // El ancho se sube SOLO si ESTE tipo va a tomar de verdad la fila por | |
| 706 | + // subgrupo. Aplicarlo a todos cambiaba la zancada del bucle de 32 a 64 en | |
| 707 | + // los cinco tipos sin `decodeCarril`: misma suma, OTRA particion en coma | |
| 708 | + // flotante, y los ultimos bits difieren. No era incorrecto, pero rompia la | |
| 709 | + // igualdad exacta — y el aserto lo achacaba a la reduccion, mandando a | |
| 710 | + // buscar dos veces donde no era. | |
| 711 | + const anchoSg = sgf > 1 && sgFilasPorGrupo(type, sgSize * sgf, tile, | |
| 712 | + globalThis.__ELFFUSS_CARRIL_SUBBLOQUE !== false, rows, subgroup, sgSize) > 1 ? sgf : 1; | |
| 713 | + const mult = subgroup ? Math.max(1, anchoSg, Math.round((globalThis.__ELFFUSS_SG_WG || sgSize) / sgSize)) : 1; | |
| 714 | + const wg = subgroup ? sgSize * mult : threadsFor(type, bpr); | |
| 715 | + // El izado de la guarda entra en la CLAVE: sin esto, al conmutar | |
| 716 | + // `__ELFFUSS_GUARDA_POR_PESO` para el A/B se reutilizaria el pipeline ya | |
| 717 | + // compilado y las dos ramas medirian el mismo shader (x1,00 indistinguible | |
| 718 | + // de «no hay ganancia»). | |
| 719 | + // Reparto por SUB-GRUPO (carril = 8 pesos en vez de un bloque entero), que es | |
| 720 | + // el camino POR DEFECTO. Sube la utilizacion de carriles del bucle de zancada | |
| 721 | + // de 62,5% a 100% con bpr=20, y en un kernel limitado por emision eso se | |
| 722 | + // traduce casi directamente en tiempo: medido +35,8% sobre el reparto por | |
| 723 | + // bloque, muy por encima del ruido de la medida. | |
| 724 | + // | |
| 725 | + // `__ELFFUSS_CARRIL_SUBBLOQUE = false` devuelve el reparto por bloque, que es | |
| 726 | + // lo que usa el A/B; por eso la comparacion es `!== false` y no un booleano | |
| 727 | + // a secas: sin interruptor puesto, gana el camino rapido. | |
| 728 | + const carril = globalThis.__ELFFUSS_CARRIL_SUBBLOQUE !== false; | |
| 729 | + // Filas por workgroup. Devuelve 1 (kernel de siempre) salvo que se cumpla | |
| 730 | + // TODO: interruptor, subgrupos, reparto por carril, decode y `rows` | |
| 731 | + // multiplo. El reparto entra en la CLAVE: sin eso, al conmutar el | |
| 732 | + // interruptor se reutilizaria el pipeline ya compilado y las dos ramas | |
| 733 | + // medirian el mismo shader. | |
| 734 | + const filas = filasPorGrupo(type, wg, tile, carril, rows, subgroup); | |
| 735 | + const p = await get(`matmul_${type}_${wg}_${tile}_${subgroup ? 'sg' : 'tr'}` + | |
| 736 | + (globalThis.__ELFFUSS_GUARDA_POR_PESO ? '_g' : '') + (carril ? '_c' : '') + | |
| 737 | + (globalThis.__ELFFUSS_X_FIJA ? '_x0' : '') + (globalThis.__ELFFUSS_W_FIJA ? '_w0' : '') + (globalThis.__ELFFUSS_DESENROLLA ? '_u' : '') + (globalThis.__ELFFUSS_DEQ_PLANA ? '_dp' : '') + (globalThis.__ELFFUSS_X_VEC4 !== false ? '_v4' : '') + | |
| 738 | + // El izado de cargas TIENE que entrar en la clave. Sin esto, al conmutar | |
| 739 | + // el interruptor para el A/B se reutilizaria el pipeline ya compilado y | |
| 740 | + // las dos ramas medirian el MISMO shader: x1,00 indistinguible de «no hay | |
| 741 | + // ganancia». Ese modo de fallo ya produjo una conclusion falsa aqui. | |
| 742 | + (globalThis.__ELFFUSS_IZA_CARGAS === true ? '_iz' : '') + | |
| 743 | + (globalThis.__ELFFUSS_BLOQUE_COOP === true ? '_bc' : '') + | |
| 744 | + // Los dos oraculos de cadena (la de la rejilla y la del acumulador) van | |
| 745 | + // tambien en la clave. Sin esto, las ramas comparten el | |
| 746 | + // shader ya compilado y el A/B sale x1,00 SIEMPRE — que es justo el modo | |
| 747 | + // de fallo que costo descubrir con la guarda de token. | |
| 748 | + (globalThis.__ELFFUSS_GI ? `_gi${globalThis.__ELFFUSS_GI}` : '') + | |
| 749 | + ((globalThis.__ELFFUSS_ACUMS | 0) > 1 ? `_a${globalThis.__ELFFUSS_ACUMS | 0}` : '') + | |
| 750 | + ((globalThis.__ELFFUSS_LASTRE | 0) > 0 ? `_L${globalThis.__ELFFUSS_LASTRE | 0}` : '') + | |
| 751 | + (filas > 1 ? `_f${filas}` : ''), | |
| 752 | + () => (filas > 1 ? matmulFilasShader(type, filas, sgSize) | |
| 753 | + : matmulShader(type, wg, tile, subgroup, sgSize, carril))); | |
| 754 | + const y = ctx.alloc(rows * tokens * 4, 'matmul.y'); | |
| 755 | + const params = ctx.uniform([new Uint32Array([rows * bpr, bpr, rows, k, tokens, 0, 0, 0])]); | |
| 756 | + const bufs = [wBuf, xBuf, y, params]; | |
| 757 | + if (i.table) bufs.push(await tableBuf(i.table)); | |
| 758 | + // Filas en los dos primeros ejes, tokens en el tercero. Sin esto, la | |
| 759 | + // cabeza de salida (248.320 filas) revienta el tope de 65.535 por eje. | |
| 760 | + // Con N filas por workgroup la rejilla cubre rows/N puntos: el shader hace | |
| 761 | + // `row0 = (wid.x + wid.y*AXIS) * FILAS`. Si esto y el shader se | |
| 762 | + // desincronizaran saldrian filas a CERO sin un solo error. | |
| 763 | + // Con S subgrupos por workgroup la rejilla cubre rows/S puntos. | |
| 764 | + // El MISMO predicado que usa el shader, no una condicion paralela: es lo | |
| 765 | + // que fallo antes, y el sintoma fue que las capas de tipos sin reparto por | |
| 766 | + // carril calculaban solo 1/S de sus filas. | |
| 767 | + const sgFilas = sgFilasPorGrupo(type, wg, tile, carril, rows, subgroup, sgSize); | |
| 768 | + const porGrupo = (filas > 1 ? filas : 1) * sgFilas; | |
| 769 | + const [dx, dy] = rowsToDims(porGrupo > 1 ? Math.ceil(rows / porGrupo) : rows); | |
| 770 | + // Etiqueta DESAGREGADA por forma (rows/bpr). Agregadas bajo `matmul:IQ1_S`, | |
| 771 | + // las 312 matmuls de un decode no dejan ver si el coste es por PESO o por | |
| 772 | + // DESPACHO, ni comparar Gw/s entre formas — que es justo lo que distingue | |
| 773 | + // «limitado por transacciones de memoria» de «limitado por emisión de | |
| 774 | + // instrucciones». No toca el shader ni la clave de pipeline: solo el nombre. | |
| 775 | + await dispatch(ctx, `matmul:${type}:r${rows}b${bpr}`, p, bufs, dx, dy, Math.ceil(tokens / tile)); | |
| 776 | + return y; | |
| 777 | + }, | |
| 778 | + | |
| 779 | + // Filas sueltas de una tabla cuantizada (los embeddings) a f32. | |
| 780 | + async gather(type, wBuf, idsBuf, dim, tokens) { | |
| 781 | + const i = info(type); | |
| 782 | + if (dim % i.blockElems !== 0) { | |
| 783 | + throw new Error(`gather ${type}: dim=${dim} no es múltiplo de ${i.blockElems}`); | |
| 784 | + } | |
| 785 | + const p = await get(`gather_${type}`, () => gatherShader(type, wgQ8)); | |
| 786 | + const bpr = dim / i.blockElems; | |
| 787 | + const dst = ctx.alloc(tokens * dim * 4, 'embd'); | |
| 788 | + const params = ctx.uniform([new Uint32Array([dim, tokens, bpr, 0])]); | |
| 789 | + const bufs = [wBuf, idsBuf, dst, params]; | |
| 790 | + if (i.table) bufs.push(await tableBuf(i.table)); | |
| 791 | + await dispatchN(ctx, 'gather', p, bufs, Math.ceil(tokens * bpr / wgQ8)); | |
| 792 | + return dst; | |
| 793 | + }, | |
| 794 | + | |
| 795 | + // Sube por adelantado las rejillas que vaya a necesitar el modelo, para que | |
| 796 | + // el primer forward no se encuentre una descarga y una subida a media pasada. | |
| 797 | + async prepare(types) { | |
| 798 | + for (const t of new Set(types)) { | |
| 799 | + const i = QUANT_TYPES[t]; | |
| 800 | + if (i && i.table) await tableBuf(i.table); | |
| 801 | + } | |
| 802 | + }, | |
| 803 | + | |
| 804 | + upload(array, label = 'x') { | |
| 805 | + const buf = ctx.alloc(array.byteLength, label); | |
| 806 | + device.queue.writeBuffer(buf, 0, array); | |
| 807 | + return buf; | |
| 808 | + }, | |
| 809 | + ctx, | |
| 810 | + }; | |
| 811 | +} | |
| 812 | + | |
| 813 | +// Vista Q8_0 de lo anterior, con la firma de siempre (sin el tipo delante). | |
| 814 | +// El forward del 0.8B llama por aquí y no se entera de que hay seis tipos. | |
| 815 | +export function createQ8Ops(device, opts = {}) { | |
| 816 | + const q = createQuantOps(device, opts); | |
| 817 | + return { | |
| 818 | + dequant: (wBuf, nBlocks) => q.dequant('Q8_0', wBuf, nBlocks), | |
| 819 | + matmul: (wBuf, xBuf, rows, k, tokens = 1) => q.matmul('Q8_0', wBuf, xBuf, rows, k, tokens), | |
| 820 | + matvec: (wBuf, xBuf, rows, k) => q.matmul('Q8_0', wBuf, xBuf, rows, k, 1), | |
| 821 | + upload: (array, label) => q.upload(array, label), | |
| 822 | + ctx: q.ctx, | |
| 823 | + }; | |
| 824 | +} | |
| 825 | + | |
| 826 | +// ── Operaciones de red ────────────────────────────────────────────────────── | |
| 827 | +export function createNNOps(device, opts = {}) { | |
| 828 | + const ctx = opts.ctx || createContext(device, opts); | |
| 829 | + const get = ctx.pipeline; | |
| 830 | + const WG_NORM = opts.wgNorm || 128; | |
| 831 | + const WG_SM = opts.wgSoftmax || 256; | |
| 832 | + const WG_EW = opts.wgElementwise || 256; | |
| 833 | + const WG_ROPE = opts.wgRope || 64; | |
| 834 | + | |
| 835 | + return { | |
| 836 | + upload(array, label = 'buf') { | |
| 837 | + const buf = ctx.alloc(array.byteLength, label); | |
| 838 | + device.queue.writeBuffer(buf, 0, array); | |
| 839 | + return buf; | |
| 840 | + }, | |
| 841 | + alloc: (bytes, label) => ctx.alloc(bytes, label), | |
| 842 | + ctx, | |
| 843 | + | |
| 844 | + // (x / sqrt(mean(x²) + eps)) · w, por filas de longitud ne0. | |
| 845 | + // Rotación de Hadamard sobre las activaciones, en bloques de `bloque`. | |
| 846 | + // `inverso` elige el orden de los signos: false = s antes de rotar (lo que | |
| 847 | + // va delante de un matmul), true = s después (deshacer el embedding). | |
| 848 | + async hadamard(src, signos, { rows, ancho, bloque = 1024, inverso = false, perm = null }) { | |
| 849 | + if (ancho % bloque !== 0) { | |
| 850 | + throw new Error(`hadamard: el ancho ${ancho} no es múltiplo del bloque ${bloque}`); | |
| 851 | + } | |
| 852 | + const p = await get(`hadamard_${bloque}_${WG_EW}`, () => hadamardShader(bloque, WG_EW)); | |
| 853 | + const dst = ctx.alloc(rows * ancho * 4, 'hadamard.out'); | |
| 854 | + const params = ctx.uniform([ | |
| 855 | + new Uint32Array([ancho, rows, ancho / bloque, inverso ? 1 : 0, | |
| 856 | + perm ? perm.hd : 0, perm ? perm.nk : 0, perm ? perm.rep : 0, | |
| 857 | + globalThis.__ELFFUSS_PERM_INV === true ? 1 : 0]), | |
| 858 | + ]); | |
| 859 | + await dispatchN(ctx, 'hadamard', p, [src, signos, dst, params], rows * (ancho / bloque)); | |
| 860 | + return dst; | |
| 861 | + }, | |
| 862 | + | |
| 863 | + async rmsnorm(src, weight, rows, ne0, eps) { | |
| 864 | + const p = await get('rmsnorm_' + WG_NORM, () => rmsnormShader(WG_NORM)); | |
| 865 | + const dst = ctx.alloc(rows * ne0 * 4, 'rmsnorm.out'); | |
| 866 | + const params = ctx.uniform([ | |
| 867 | + new Uint32Array([ne0, rows]), new Float32Array([eps, 0]), | |
| 868 | + ]); | |
| 869 | + await dispatchRows(ctx, 'rmsnorm', p, [src, weight, dst, params], rows); | |
| 870 | + return dst; | |
| 871 | + }, | |
| 872 | + | |
| 873 | + // RoPE sobre filas [head_dim, heads, tokens]. `mode` decide el pareado: | |
| 874 | + // ROPE_NORM empareja adyacentes, ROPE_NEOX empareja i con i+nDims/2. | |
| 875 | + async rope(src, posBuf, { rows, ne0, heads, nDims, mode, freqBase, freqScale = 1 }) { | |
| 876 | + const p = await get('rope_' + WG_ROPE, () => ropeShader(WG_ROPE)); | |
| 877 | + const dst = ctx.alloc(rows * ne0 * 4, 'rope.out'); | |
| 878 | + // theta_scale en el host: acumular la potencia en el shader arrastra el | |
| 879 | + // error de pow() y a posiciones grandes se nota. | |
| 880 | + const thetaScale = Math.pow(freqBase, -2 / nDims); | |
| 881 | + const params = ctx.uniform([ | |
| 882 | + new Uint32Array([ne0, rows, heads, nDims, mode, 0, 0, 0]), | |
| 883 | + new Float32Array([thetaScale, freqScale, 0, 0]), | |
| 884 | + ]); | |
| 885 | + const total = rows * (nDims / 2); | |
| 886 | + await dispatchN(ctx, 'rope', p, [src, posBuf, dst, params], Math.ceil(total / WG_ROPE)); | |
| 887 | + return dst; | |
| 888 | + }, | |
| 889 | + | |
| 890 | + // Softmax por filas con máscara causal calculada en el shader. | |
| 891 | + async softmax(src, { rows, nKv, nQ, nPast = 0, scale = 1 }) { | |
| 892 | + const p = await get('softmax_' + WG_SM, () => softmaxShader(WG_SM)); | |
| 893 | + const dst = ctx.alloc(rows * nKv * 4, 'softmax.out'); | |
| 894 | + const params = ctx.uniform([ | |
| 895 | + new Uint32Array([nKv, nQ, nPast, rows]), new Float32Array([scale, 0, 0, 0]), | |
| 896 | + ]); | |
| 897 | + await dispatchRows(ctx, 'softmax', p, [src, dst, params], rows); | |
| 898 | + return dst; | |
| 899 | + }, | |
| 900 | + | |
| 901 | + // silu(gate) · up. El orden importa y no avisa si se invierte. | |
| 902 | + async swiglu(gate, up, n) { | |
| 903 | + const p = await get('swiglu_' + WG_EW, () => swigluShader(WG_EW)); | |
| 904 | + const dst = ctx.alloc(n * 4, 'swiglu.out'); | |
| 905 | + const params = ctx.uniform([new Uint32Array([n, 0, 0, 0])]); | |
| 906 | + await dispatchN(ctx, 'swiglu', p, [gate, up, dst, params], Math.ceil(n / WG_EW)); | |
| 907 | + return dst; | |
| 908 | + }, | |
| 909 | + | |
| 910 | + async add(a, b, n) { | |
| 911 | + const p = await get('add_' + WG_EW, () => addShader(WG_EW)); | |
| 912 | + const dst = ctx.alloc(n * 4, 'add.out'); | |
| 913 | + const params = ctx.uniform([new Uint32Array([n, 0, 0, 0])]); | |
| 914 | + await dispatchN(ctx, 'add', p, [a, b, dst, params], Math.ceil(n / WG_EW)); | |
| 915 | + return dst; | |
| 916 | + }, | |
| 917 | + }; | |
| 918 | +} | |
| 919 | + | |
| 920 | +// ── Operaciones de la capa SSM ────────────────────────────────────────────── | |
| 921 | +export function createSSMOps(device, opts = {}) { | |
| 922 | + const ctx = opts.ctx || createContext(device, opts); | |
| 923 | + const get = ctx.pipeline; | |
| 924 | + const S = opts.headDim || SSM_HEAD_DIM; | |
| 925 | + const WG = opts.wg || 128; | |
| 926 | + const WG_EW = opts.wgElementwise || 256; | |
| 927 | + | |
| 928 | + return { | |
| 929 | + async l2norm(src, rows, ne0, eps) { | |
| 930 | + const p = await get('l2norm_' + WG, () => l2normShader(WG)); | |
| 931 | + const dst = ctx.alloc(rows * ne0 * 4, 'l2norm.out'); | |
| 932 | + const params = ctx.uniform([new Uint32Array([ne0, rows]), new Float32Array([eps, 0])]); | |
| 933 | + await dispatchRows(ctx, 'l2norm', p, [src, dst, params], rows); | |
| 934 | + return dst; | |
| 935 | + }, | |
| 936 | + | |
| 937 | + // buf: [channels][window] con window = 3 + tokens. dst: [tokens][channels]. | |
| 938 | + async conv(buf, w, channels, tokens) { | |
| 939 | + const p = await get('ssm_conv', () => ssmConvShader()); | |
| 940 | + const dst = ctx.alloc(channels * tokens * 4, 'conv.out'); | |
| 941 | + const params = ctx.uniform([new Uint32Array([channels, tokens, tokens + SSM_CONV_K - 1, 0])]); | |
| 942 | + await dispatchN(ctx, 'ssm_conv', p, [buf, w, dst, params], Math.ceil(channels * tokens / 64)); | |
| 943 | + return dst; | |
| 944 | + }, | |
| 945 | + | |
| 946 | + // Actualiza `state` EN SITIO y devuelve la salida. El estado sobrevive entre | |
| 947 | + // llamadas: es lo que sustituye a la caché KV en estas capas. | |
| 948 | + // `heads` son las cabezas de VALOR y `kvHeads` las de clave. En el 0.8B | |
| 949 | + // coinciden; en el 27B son 48 contra 16. | |
| 950 | + async gatedDeltaNet(q, k, v, g, beta, state, heads, tokens, kvHeads = heads) { | |
| 951 | + const p = await get('gdn_' + S, () => gatedDeltaNetShader(S)); | |
| 952 | + const out = ctx.alloc(tokens * heads * S * 4, 'gdn.out'); | |
| 953 | + const params = ctx.uniform([ | |
| 954 | + new Uint32Array([heads, tokens, kvHeads, 0]), | |
| 955 | + new Float32Array([1 / Math.sqrt(S), 0, 0, 0]), | |
| 956 | + ]); | |
| 957 | + await dispatchRows(ctx, 'gated_delta_net', p, [q, k, v, g, beta, state, out, params], heads); | |
| 958 | + return out; | |
| 959 | + }, | |
| 960 | + | |
| 961 | + async gatedNorm(src, w, z, rows, ne0, eps) { | |
| 962 | + const p = await get('gated_norm_' + WG, () => gatedNormShader(WG)); | |
| 963 | + const dst = ctx.alloc(rows * ne0 * 4, 'gnorm.out'); | |
| 964 | + const params = ctx.uniform([new Uint32Array([ne0, rows]), new Float32Array([eps, 0])]); | |
| 965 | + await dispatchRows(ctx, 'gated_norm', p, [src, w, z, dst, params], rows); | |
| 966 | + return dst; | |
| 967 | + }, | |
| 968 | + | |
| 969 | + async decayGate(alpha, dt, a, heads, tokens) { | |
| 970 | + const p = await get('decay_gate', () => decayGateShader()); | |
| 971 | + const dst = ctx.alloc(heads * tokens * 4, 'g'); | |
| 972 | + const params = ctx.uniform([new Uint32Array([heads, tokens, 0, 0])]); | |
| 973 | + await dispatchN(ctx, 'decay_gate', p, [alpha, dt, a, dst, params], Math.ceil(heads * tokens / 64)); | |
| 974 | + return dst; | |
| 975 | + }, | |
| 976 | + | |
| 977 | + async sigmoid(src, n) { | |
| 978 | + const p = await get('sigmoid_' + WG_EW, () => sigmoidShader(WG_EW)); | |
| 979 | + const dst = ctx.alloc(n * 4, 'sigmoid.out'); | |
| 980 | + const params = ctx.uniform([new Uint32Array([n, 0, 0, 0])]); | |
| 981 | + await dispatchN(ctx, 'sigmoid', p, [src, dst, params], Math.ceil(n / WG_EW)); | |
| 982 | + return dst; | |
| 983 | + }, | |
| 984 | + | |
| 985 | + upload(array, label = 'buf') { | |
| 986 | + const buf = ctx.alloc(array.byteLength, label); | |
| 987 | + device.queue.writeBuffer(buf, 0, array); | |
| 988 | + return buf; | |
| 989 | + }, | |
| 990 | + alloc: (bytes, label) => ctx.alloc(bytes, label), | |
| 991 | + ctx, | |
| 992 | + }; | |
| 993 | +} | |
| 994 | + | |
| 995 | +// ── Operaciones del bloque de atención ────────────────────────────────────── | |
| 996 | +export function createAttnOps(device, opts = {}) { | |
| 997 | + const ctx = opts.ctx || createContext(device, opts); | |
| 998 | + const get = ctx.pipeline; | |
| 999 | + const WG = opts.wg || 64; | |
| 1000 | + const WG_EW = opts.wgElementwise || 256; | |
| 1001 | + | |
| 1002 | + return { | |
| 1003 | + // Extrae Q o la puerta del tensor intercalado. `offset` 0 = Q, | |
| 1004 | + // `offset` headDim = puerta. | |
| 1005 | + async strideCopy(src, { headDim, heads, tokens, stride, offset }) { | |
| 1006 | + const p = await get('stride_copy_' + WG_EW, () => strideCopyShader(WG_EW)); | |
| 1007 | + const dst = ctx.alloc(headDim * heads * tokens * 4, 'stride.out'); | |
| 1008 | + const params = ctx.uniform([new Uint32Array([headDim, heads, tokens, stride, offset, 0, 0, 0])]); | |
| 1009 | + await dispatchN(ctx, 'stride_copy', p, [src, dst, params], | |
| 1010 | + Math.ceil(headDim * heads * tokens / WG_EW)); | |
| 1011 | + return dst; | |
| 1012 | + }, | |
| 1013 | + | |
| 1014 | + // QKᵀ SIN escalar ni enmascarar: de eso se encarga el softmax. | |
| 1015 | + async scores(q, k, { headDim, heads, kvHeads, tokens, nKv, nPast = 0, kvF16 = false }) { | |
| 1016 | + // La precisión va en la CLAVE del pipeline. Sin ella, la primera llamada | |
| 1017 | + // fijaría el shader y la segunda reutilizaría el compilado para la otra | |
| 1018 | + // precisión: leería la caché con el tipo equivocado y devolvería basura | |
| 1019 | + // sin un solo error. | |
| 1020 | + // Camino con la K COMPARTIDA entre las cabezas que la usan. El de un hilo | |
| 1021 | + // por salida va al 96 % del techo de lectura —no es ineficiente— pero lee | |
| 1022 | + // la K heads/kvHeads veces: con las formas del 27B, seis. Compartirla | |
| 1023 | + // divide los bytes por seis, es EXACTO (mismo producto, mismo orden de | |
| 1024 | + // acumulación) y a contexto largo era el 69 % de lo que el contexto añade | |
| 1025 | + // al token. Las condiciones son del dispositivo y del modelo, no gustos; | |
| 1026 | + // si alguna falla se usa el de siempre, que da lo mismo más despacio. | |
| 1027 | + const grupo = kvHeads > 0 ? heads / kvHeads : 0; | |
| 1028 | + const puedeCompartir = globalThis.__ELFFUSS_SCORES_SHARED !== false && | |
| 1029 | + Number.isInteger(grupo) && grupo >= 1 && | |
| 1030 | + compartidaScores(headDim, grupo) <= device.limits.maxComputeWorkgroupStorageSize && | |
| 1031 | + Math.ceil(nKv / WG) <= 65535; | |
| 1032 | + if (puedeCompartir) { | |
| 1033 | + const pS = await get(`attn_scores_sh_${headDim}_${grupo}_${WG}${kvF16 ? '_h' : ''}`, | |
| 1034 | + () => attnScoresSharedShader({ headDim, grupo, kvF16, wg: WG })); | |
| 1035 | + const dst = ctx.alloc(heads * tokens * nKv * 4, 'scores'); | |
| 1036 | + const params = ctx.uniform([new Uint32Array([headDim, heads, kvHeads, tokens, nKv, 0, 0, 0])]); | |
| 1037 | + await dispatchXYZ(ctx, 'attn_scores_sh', pS, [q, k, dst, params], | |
| 1038 | + Math.ceil(nKv / WG), kvHeads, tokens); | |
| 1039 | + return dst; | |
| 1040 | + } | |
| 1041 | + const p = await get(`attn_scores_${WG}${kvF16 ? '_h' : ''}`, () => attnScoresShader(WG, kvF16)); | |
| 1042 | + const dst = ctx.alloc(heads * tokens * nKv * 4, 'scores'); | |
| 1043 | + const params = ctx.uniform([new Uint32Array([headDim, heads, kvHeads, tokens, nKv, nPast, 0, 0])]); | |
| 1044 | + await dispatchN(ctx, 'attn_scores', p, [q, k, dst, params], | |
| 1045 | + Math.ceil(heads * tokens * nKv / WG)); | |
| 1046 | + return dst; | |
| 1047 | + }, | |
| 1048 | + | |
| 1049 | + // El camino PARTIDO es el normal; el de un hilo por salida se queda como | |
| 1050 | + // respaldo para las formas que el partido no puede atender. A contexto | |
| 1051 | + // largo la diferencia no es un detalle: a 64k de contexto el kernel viejo se | |
| 1052 | + // llevaba el 73 % del tiempo del token, y el partido mide dos ordenes de | |
| 1053 | + // magnitud menos en el mismo sitio. | |
| 1054 | + // | |
| 1055 | + // Tres condiciones para poder usarlo, y las tres son del dispositivo o del | |
| 1056 | + // modelo, no preferencias: | |
| 1057 | + // · un grupo tiene headDim hilos, así que headDim tiene que caber en el | |
| 1058 | + // tope de invocaciones por grupo del dispositivo; | |
| 1059 | + // · las cabezas de consulta tienen que repartirse exactas entre las KV, | |
| 1060 | + // porque un grupo atiende a todas las de una cabeza KV; | |
| 1061 | + // · la memoria compartida de las probabilidades tiene que caber. | |
| 1062 | + // Si alguna falla NO se falla: se usa el camino de siempre, que da el mismo | |
| 1063 | + // resultado más despacio. Un modelo con otra forma tiene que seguir | |
| 1064 | + // corriendo. | |
| 1065 | + async combine(probs, v, { headDim, heads, kvHeads, tokens, nKv, nPast = 0, kvF16 = false }) { | |
| 1066 | + const grupo = kvHeads > 0 ? heads / kvHeads : 0; | |
| 1067 | + const SUB = 64; | |
| 1068 | + const puedePartir = globalThis.__ELFFUSS_COMBINE_SPLIT !== false && | |
| 1069 | + Number.isInteger(grupo) && grupo >= 1 && | |
| 1070 | + headDim <= device.limits.maxComputeInvocationsPerWorkgroup && | |
| 1071 | + grupo * SUB * 4 <= device.limits.maxComputeWorkgroupStorageSize; | |
| 1072 | + if (puedePartir) { | |
| 1073 | + const bloques = bloquesCombine(nKv); | |
| 1074 | + const pS = await get(`attn_combine_split_${headDim}_${grupo}_${SUB}${kvF16 ? '_h' : ''}`, | |
| 1075 | + () => attnCombineSplitShader({ headDim, grupo, subTrozo: SUB, kvF16 })); | |
| 1076 | + const pR = await get(`combine_reduce_${WG_EW}`, () => combineReduceShader(WG_EW)); | |
| 1077 | + const parc = ctx.alloc(tokens * heads * bloques * headDim * 4, 'attn.parc'); | |
| 1078 | + const dst = ctx.alloc(tokens * heads * headDim * 4, 'attn.out'); | |
| 1079 | + const parS = ctx.uniform([new Uint32Array([headDim, heads, kvHeads, tokens, nKv, bloques, 0, 0])]); | |
| 1080 | + const parR = ctx.uniform([new Uint32Array([headDim, heads, tokens, bloques])]); | |
| 1081 | + await dispatchXYZ(ctx, 'attn_combine_split', pS, [probs, v, parc, parS], | |
| 1082 | + bloques, kvHeads, tokens); | |
| 1083 | + await dispatchN(ctx, 'attn_combine_reduce', pR, [parc, dst, parR], | |
| 1084 | + Math.ceil(tokens * heads * headDim / WG_EW)); | |
| 1085 | + return dst; | |
| 1086 | + } | |
| 1087 | + const p = await get(`attn_combine_${WG}${kvF16 ? '_h' : ''}`, () => attnCombineShader(WG, kvF16)); | |
| 1088 | + const dst = ctx.alloc(tokens * heads * headDim * 4, 'attn.out'); | |
| 1089 | + const params = ctx.uniform([new Uint32Array([headDim, heads, kvHeads, tokens, nKv, nPast, 0, 0])]); | |
| 1090 | + await dispatchN(ctx, 'attn_combine', p, [probs, v, dst, params], | |
| 1091 | + Math.ceil(tokens * heads * headDim / WG)); | |
| 1092 | + return dst; | |
| 1093 | + }, | |
| 1094 | + | |
| 1095 | + async mul(a, b, n) { | |
| 1096 | + const p = await get('mul_' + WG_EW, () => mulShader(WG_EW)); | |
| 1097 | + const dst = ctx.alloc(n * 4, 'mul.out'); | |
| 1098 | + const params = ctx.uniform([new Uint32Array([n, 0, 0, 0])]); | |
| 1099 | + await dispatchN(ctx, 'mul', p, [a, b, dst, params], Math.ceil(n / WG_EW)); | |
| 1100 | + return dst; | |
| 1101 | + }, | |
| 1102 | + | |
| 1103 | + upload(array, label = 'buf') { | |
| 1104 | + const buf = ctx.alloc(array.byteLength, label); | |
| 1105 | + device.queue.writeBuffer(buf, 0, array); | |
| 1106 | + return buf; | |
| 1107 | + }, | |
| 1108 | + alloc: (bytes, label) => ctx.alloc(bytes, label), | |
| 1109 | + ctx, | |
| 1110 | + }; | |
| 1111 | +} | |
| 1112 | + | |
| 1113 | +// ── Referencias de CPU para los tests ─────────────────────────────────────── | |
| 1114 | +// Deliberadamente ABURRIDAS y escritas de otra forma que el shader, para que un | |
| 1115 | +// fallo del WGSL no se cancele con el mismo fallo aquí. Los Number de JS son | |
| 1116 | +// dobles, así que estas referencias acumulan en f64 de verdad. | |
| 1117 | + | |
| 1118 | +// La descuantización de referencia de los tipos de peso vive aparte, en un | |
| 1119 | +// módulo que solo usan las pruebas: importarla desde aquí arrastraría las | |
| 1120 | +// rejillas de los i-quants a todo el que solo quiere un rmsnorm. | |
| 1121 | + | |
| 1122 | +export function rmsnormCPU(src, w, rows, ne0, eps) { | |
| 1123 | + const out = new Float64Array(rows * ne0); | |
| 1124 | + for (let r = 0; r < rows; r++) { | |
| 1125 | + let sum = 0; | |
| 1126 | + for (let i = 0; i < ne0; i++) { const v = src[r * ne0 + i]; sum += v * v; } | |
| 1127 | + const scale = 1 / Math.sqrt(sum / ne0 + eps); | |
| 1128 | + for (let i = 0; i < ne0; i++) out[r * ne0 + i] = src[r * ne0 + i] * scale * w[i]; | |
| 1129 | + } | |
| 1130 | + return out; | |
| 1131 | +} | |
| 1132 | + | |
| 1133 | +export function ropeCPU(src, pos, { rows, ne0, heads, nDims, mode, freqBase, freqScale = 1 }) { | |
| 1134 | + const out = Float64Array.from(src); | |
| 1135 | + const pairs = nDims / 2; | |
| 1136 | + for (let r = 0; r < rows; r++) { | |
| 1137 | + const base = r * ne0; | |
| 1138 | + const t = Math.floor(r / heads); | |
| 1139 | + for (let p = 0; p < pairs; p++) { | |
| 1140 | + // Forma cerrada, distinta de la del shader (que usa thetaScale^p). | |
| 1141 | + const theta = pos[t] * freqScale / Math.pow(freqBase, (2 * p) / nDims); | |
| 1142 | + const c = Math.cos(theta), s = Math.sin(theta); | |
| 1143 | + const i0 = mode === ROPE_NEOX ? p : 2 * p; | |
| 1144 | + const i1 = mode === ROPE_NEOX ? p + pairs : 2 * p + 1; | |
| 1145 | + const x0 = src[base + i0], x1 = src[base + i1]; | |
| 1146 | + out[base + i0] = x0 * c - x1 * s; | |
| 1147 | + out[base + i1] = x0 * s + x1 * c; | |
| 1148 | + } | |
| 1149 | + } | |
| 1150 | + return out; | |
| 1151 | +} | |
| 1152 | + | |
| 1153 | +export function softmaxCPU(src, { rows, nKv, nQ, nPast = 0, scale = 1 }) { | |
| 1154 | + const out = new Float64Array(rows * nKv); | |
| 1155 | + for (let r = 0; r < rows; r++) { | |
| 1156 | + const base = r * nKv, qAbs = nPast + (r % nQ); | |
| 1157 | + let max = -Infinity; | |
| 1158 | + for (let k = 0; k <= Math.min(qAbs, nKv - 1); k++) max = Math.max(max, src[base + k] * scale); | |
| 1159 | + let sum = 0; | |
| 1160 | + for (let k = 0; k < nKv; k++) { | |
| 1161 | + const e = k <= qAbs ? Math.exp(src[base + k] * scale - max) : 0; | |
| 1162 | + out[base + k] = e; sum += e; | |
| 1163 | + } | |
| 1164 | + for (let k = 0; k < nKv; k++) out[base + k] /= sum; | |
| 1165 | + } | |
| 1166 | + return out; | |
| 1167 | +} | |
| 1168 | + | |
| 1169 | +export function swigluCPU(gate, up, n) { | |
| 1170 | + const out = new Float64Array(n); | |
| 1171 | + for (let i = 0; i < n; i++) out[i] = (gate[i] / (1 + Math.exp(-gate[i]))) * up[i]; | |
| 1172 | + return out; | |
| 1173 | +} | |
| 1174 | + | |
| 1175 | +// ── Referencias de CPU de la capa SSM ─────────────────────────────────────── | |
| 1176 | +// Escritas siguiendo el bucle de referencia paso a paso (decaimiento explícito, | |
| 1177 | +// tres pasadas separadas), no la forma optimizada del shader: si las dos | |
| 1178 | +// compartieran el atajo algebraico, el test no lo estaría comprobando. | |
| 1179 | + | |
| 1180 | +export function l2normCPU(src, rows, ne0, eps) { | |
| 1181 | + const out = new Float64Array(rows * ne0); | |
| 1182 | + for (let r = 0; r < rows; r++) { | |
| 1183 | + let sum = 0; | |
| 1184 | + for (let i = 0; i < ne0; i++) { const v = src[r * ne0 + i]; sum += v * v; } | |
| 1185 | + const scale = 1 / Math.max(Math.sqrt(sum), eps); // suelo, no eps bajo la raíz | |
| 1186 | + for (let i = 0; i < ne0; i++) out[r * ne0 + i] = src[r * ne0 + i] * scale; | |
| 1187 | + } | |
| 1188 | + return out; | |
| 1189 | +} | |
| 1190 | + | |
| 1191 | +export function ssmConvCPU(buf, w, channels, tokens) { | |
| 1192 | + const window = tokens + SSM_CONV_K - 1; | |
| 1193 | + const out = new Float64Array(channels * tokens); | |
| 1194 | + for (let c = 0; c < channels; c++) { | |
| 1195 | + for (let t = 0; t < tokens; t++) { | |
| 1196 | + let acc = 0; | |
| 1197 | + for (let r = 0; r < SSM_CONV_K; r++) acc += buf[c * window + t + r] * w[c * SSM_CONV_K + r]; | |
| 1198 | + out[t * channels + c] = acc; | |
| 1199 | + } | |
| 1200 | + } | |
| 1201 | + return out; | |
| 1202 | +} | |
| 1203 | + | |
| 1204 | +// `heads` son las de VALOR y `kvHeads` las de CLAVE. El emparejamiento es por | |
| 1205 | +// MÓDULO (cabeza de valor h ↔ cabeza de clave h % kvHeads), no por división: | |
| 1206 | +// las cabezas de valor vienen del fichero en orden TESELADO. Ver la nota larga | |
| 1207 | +// en el shader. Cuando los dos recuentos coinciden da igual, que es el caso del | |
| 1208 | +// 0.8B y la razón de que el fallo solo apareciera en el modelo grande. | |
| 1209 | +export function gatedDeltaNetCPU(q, k, v, g, beta, state, heads, tokens, | |
| 1210 | + S = SSM_HEAD_DIM, kvHeads = heads) { | |
| 1211 | + const st = Float64Array.from(state); // [H][S(j)][S(i)] | |
| 1212 | + const out = new Float64Array(tokens * heads * S); | |
| 1213 | + const scale = 1 / Math.sqrt(S); | |
| 1214 | + for (let t = 0; t < tokens; t++) { | |
| 1215 | + for (let h = 0; h < heads; h++) { | |
| 1216 | + const vv = (t * heads + h) * S, hb = h * S * S; // v, g, beta y salida | |
| 1217 | + const vk = (t * kvHeads + (h % kvHeads)) * S; // q y k | |
| 1218 | + const gv = Math.exp(g[t * heads + h]), bv = beta[t * heads + h]; | |
| 1219 | + // 1) decaimiento, explícito | |
| 1220 | + for (let x = 0; x < S * S; x++) st[hb + x] *= gv; | |
| 1221 | + // 2) u = v − Sᵀk ; 3) δ = β·u | |
| 1222 | + const delta = new Float64Array(S); | |
| 1223 | + for (let j = 0; j < S; j++) { | |
| 1224 | + let dot = 0; | |
| 1225 | + for (let i = 0; i < S; i++) dot += st[hb + j * S + i] * k[vk + i]; | |
| 1226 | + delta[j] = (v[vv + j] - dot) * bv; | |
| 1227 | + } | |
| 1228 | + // 4) escritura | |
| 1229 | + for (let j = 0; j < S; j++) { | |
| 1230 | + for (let i = 0; i < S; i++) st[hb + j * S + i] += k[vk + i] * delta[j]; | |
| 1231 | + } | |
| 1232 | + // 5) salida con el estado YA actualizado | |
| 1233 | + for (let j = 0; j < S; j++) { | |
| 1234 | + let dot = 0; | |
| 1235 | + for (let i = 0; i < S; i++) dot += st[hb + j * S + i] * q[vk + i]; | |
| 1236 | + out[vv + j] = dot * scale; | |
| 1237 | + } | |
| 1238 | + } | |
| 1239 | + } | |
| 1240 | + return { out, state: st }; | |
| 1241 | +} | |
| 1242 | + | |
| 1243 | +export function gatedNormCPU(src, w, z, rows, ne0, eps) { | |
| 1244 | + const out = new Float64Array(rows * ne0); | |
| 1245 | + for (let r = 0; r < rows; r++) { | |
| 1246 | + let sum = 0; | |
| 1247 | + for (let i = 0; i < ne0; i++) { const x = src[r * ne0 + i]; sum += x * x; } | |
| 1248 | + const scale = 1 / Math.sqrt(sum / ne0 + eps); | |
| 1249 | + for (let i = 0; i < ne0; i++) { | |
| 1250 | + const zc = z[r * ne0 + i]; | |
| 1251 | + out[r * ne0 + i] = src[r * ne0 + i] * scale * w[i] * (zc / (1 + Math.exp(-zc))); | |
| 1252 | + } | |
| 1253 | + } | |
| 1254 | + return out; | |
| 1255 | +} | |
| 1256 | + | |
| 1257 | +export function decayGateCPU(alpha, dt, a, heads, tokens) { | |
| 1258 | + const out = new Float64Array(heads * tokens); | |
| 1259 | + const sp = x => (x > 20 ? x : Math.log(1 + Math.exp(x))); | |
| 1260 | + for (let i = 0; i < heads * tokens; i++) out[i] = sp(alpha[i] + dt[i % heads]) * a[i % heads]; | |
| 1261 | + return out; | |
| 1262 | +} | |
| 1263 | + | |
| 1264 | +// Las tres familias compartiendo UN contexto: un solo submit puede abarcar | |
| 1265 | +// operaciones cuantizadas, de red y de SSM, que es lo que hace un forward. | |
| 1266 | +export function createOps(device, opts = {}) { | |
| 1267 | + const ctx = createContext(device, opts); | |
| 1268 | + const shared = { ...opts, ctx }; | |
| 1269 | + const quant = createQuantOps(device, shared); | |
| 1270 | + return { | |
| 1271 | + ctx, | |
| 1272 | + quant, | |
| 1273 | + // Vista Q8_0 de `quant`, para el forward del 0.8B, que no pasa el tipo. | |
| 1274 | + q8: { | |
| 1275 | + dequant: (w, n) => quant.dequant('Q8_0', w, n), | |
| 1276 | + matmul: (w, x, rows, k, tokens = 1) => quant.matmul('Q8_0', w, x, rows, k, tokens), | |
| 1277 | + matvec: (w, x, rows, k) => quant.matmul('Q8_0', w, x, rows, k, 1), | |
| 1278 | + upload: (a, l) => quant.upload(a, l), | |
| 1279 | + ctx, | |
| 1280 | + }, | |
| 1281 | + nn: createNNOps(device, shared), | |
| 1282 | + ssm: createSSMOps(device, shared), | |
| 1283 | + attn: createAttnOps(device, shared), | |
| 1284 | + batch: (label, fn) => ctx.batch(label, fn), | |
| 1285 | + // Despacho generico para los kernels de plomeria del modelo, que no | |
| 1286 | + // pertenecen a ninguna de las tres familias. | |
| 1287 | + dispatchAny: (label, pipe, buffers, groups) => dispatchN(ctx, label, pipe, buffers, groups), | |
| 1288 | + recycle: () => ctx.recycle(), | |
| 1289 | + // Los scopes de error cuestan una ida y vuelta por operacion. Se dejan | |
| 1290 | + // puestos al cargar el modelo y se quitan para el bucle de decode. | |
| 1291 | + setDebug: (on) => { ctx.debug = !!on; }, | |
| 1292 | + }; | |
| 1293 | +} | |
| 1294 | + | |
| 1295 | +// ── Referencias de CPU del bloque de atención ─────────────────────────────── | |
| 1296 | + | |
| 1297 | +export function strideCopyCPU(src, { headDim, heads, tokens, stride, offset }) { | |
| 1298 | + const out = new Float64Array(headDim * heads * tokens); | |
| 1299 | + for (let t = 0; t < tokens; t++) { | |
| 1300 | + for (let h = 0; h < heads; h++) { | |
| 1301 | + for (let d = 0; d < headDim; d++) { | |
| 1302 | + out[(t * heads + h) * headDim + d] = | |
| 1303 | + src[t * heads * stride + h * stride + offset + d]; | |
| 1304 | + } | |
| 1305 | + } | |
| 1306 | + } | |
| 1307 | + return out; | |
| 1308 | +} | |
| 1309 | + | |
| 1310 | +export function attnScoresCPU(q, k, { headDim, heads, kvHeads, tokens, nKv }) { | |
| 1311 | + const out = new Float64Array(heads * tokens * nKv); | |
| 1312 | + const group = heads / kvHeads; | |
| 1313 | + for (let h = 0; h < heads; h++) { | |
| 1314 | + const kvh = Math.floor(h / group); | |
| 1315 | + for (let t = 0; t < tokens; t++) { | |
| 1316 | + for (let j = 0; j < nKv; j++) { | |
| 1317 | + let acc = 0; | |
| 1318 | + for (let d = 0; d < headDim; d++) { | |
| 1319 | + acc += q[(t * heads + h) * headDim + d] * k[(j * kvHeads + kvh) * headDim + d]; | |
| 1320 | + } | |
| 1321 | + out[(h * tokens + t) * nKv + j] = acc; | |
| 1322 | + } | |
| 1323 | + } | |
| 1324 | + } | |
| 1325 | + return out; | |
| 1326 | +} | |
| 1327 | + | |
| 1328 | +export function attnCombineCPU(probs, v, { headDim, heads, kvHeads, tokens, nKv }) { | |
| 1329 | + const out = new Float64Array(tokens * heads * headDim); | |
| 1330 | + const group = heads / kvHeads; | |
| 1331 | + for (let t = 0; t < tokens; t++) { | |
| 1332 | + for (let h = 0; h < heads; h++) { | |
| 1333 | + const kvh = Math.floor(h / group); | |
| 1334 | + for (let d = 0; d < headDim; d++) { | |
| 1335 | + let acc = 0; | |
| 1336 | + for (let j = 0; j < nKv; j++) { | |
| 1337 | + acc += probs[(h * tokens + t) * nKv + j] * v[(j * kvHeads + kvh) * headDim + d]; | |
| 1338 | + } | |
| 1339 | + out[(t * heads + h) * headDim + d] = acc; | |
| 1340 | + } | |
| 1341 | + } | |
| 1342 | + } | |
| 1343 | + return out; | |
| 1344 | +} |
added js/provider.js +1500 −0
| @@ -0,0 +1,1500 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · el adaptador que enchufa el motor al agente de Elffuss. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// El contrato del agente es minúsculo: `load(onProgress)` y `chat(history, | |
| 6 | +// system, onToken) → string`. Todo lo demás es opcional. Este fichero traduce | |
| 7 | +// entre ese contrato y el motor. | |
| 8 | +// | |
| 9 | +// Cuatro detalles del contrato que no son obvios y que se pagan caros: | |
| 10 | +// · El progreso se emite como STRING y la barra de carga le saca el «N %» con | |
| 11 | +// un regex. Sin «%» la barra se queda indeterminada para siempre — le pasa | |
| 12 | +// al proveedor de LiteRT y por eso su carga parece colgada. | |
| 13 | +// · Los errores se le enseñan LITERALES al usuario. Se escriben para humanos. | |
| 14 | +// · Las tool-calls no requieren nada: el agente busca un bloque ```tool en el | |
| 15 | +// texto devuelto. No hay que filtrar los fences ni inventar un API. | |
| 16 | +// · El `system` cambia en CADA turno porque lleva el contexto vivo dentro, así | |
| 17 | +// que no sirve como clave de caché salvo por su prefijo. | |
| 18 | +// | |
| 19 | +// Y uno opcional: `chat()` admite un cuarto argumento, `{ signal, onPrefill }`, | |
| 20 | +// o la señal suelta (o un AbortController), que es como lo llamaban las apps | |
| 21 | +// antes de que existiera ese objeto. Un turno parado RECHAZA con un AbortError | |
| 22 | +// que trae en `.partial` lo que llegó a emitir, y `.porDescarga` a true si no | |
| 23 | +// lo paró quien llamaba sino una descarga (`unload()` o `configure()` a otro | |
| 24 | +// modelo); quien llame tiene que tratarlo como «parado» y no como «el modelo | |
| 25 | +// falló». `abort()` para lo que haya en marcha. | |
| 26 | +// | |
| 27 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 28 | + | |
| 29 | +import { requestDevice, readback } from './device.js'; | |
| 30 | +import { loadModel, createSession, errorParado } from './model.js'; | |
| 31 | + | |
| 32 | +// Contextos a intentar, del pedido hacia abajo por mitades, con un suelo. El | |
| 33 | +// suelo NO es cero a propósito: por debajo de 2048 el modelo no puede ni con su | |
| 34 | +// propio prompt de sistema, así que abrir con 512 sería entregar algo que carga | |
| 35 | +// y no sirve, que es peor que decir que no cabe. | |
| 36 | +const CONTEXTO_MINIMO = 2048; | |
| 37 | +export function escaleraContexto(pedido) { | |
| 38 | + const pasos = []; | |
| 39 | + for (let c = Math.max(CONTEXTO_MINIMO, pedido | 0); c >= CONTEXTO_MINIMO; c = Math.floor(c / 2)) { | |
| 40 | + pasos.push(c); | |
| 41 | + } | |
| 42 | + return pasos; | |
| 43 | +} | |
| 44 | +import { createTokenizer } from './tokenizer.js'; | |
| 45 | +import { sample } from './sample.js'; | |
| 46 | +import { parseGGUF } from './gguf.js'; | |
| 47 | +// El registro va aparte para que la app pueda sondear disponibilidad sin | |
| 48 | +// importarse el motor entero. Ver la cabecera de registro.js. | |
| 49 | +import { MODELS, cachea } from './registro.js'; | |
| 50 | + | |
| 51 | +export let name = 'Elffuss Engine · WebGPU'; | |
| 52 | + | |
| 53 | +let clave = 'qwen35-0.8b'; | |
| 54 | +let ctxEfectivo = 0; // el peldaño de la escalera en el que se abrio la sesion | |
| 55 | + | |
| 56 | +// ── UN SOLO MOTOR PESADO POR NAVEGADOR ────────────────────────────────────── | |
| 57 | +// Cada pestaña cargaba su propia instancia sin enterarse de las demas. Con el | |
| 58 | +// modelo grande, cada una pedía los pesos enteros más su caché KV (que a | |
| 59 | +// contexto completo pesa más de la mitad que los pesos), peleandose por el mismo | |
| 60 | +// dispositivo, y el sintoma medido es brutal: el prefill cae a | |
| 61 | +// una decima parte y acaba yendo MAS LENTO que la generacion, que es imposible | |
| 62 | +// en un motor sano. Desde fuera no parece contencion, parece que el motor es | |
| 63 | +// malo. | |
| 64 | +// | |
| 65 | +// Esto es un CERROJO, no todavia una solucion: impide la segunda instancia | |
| 66 | +// pesada y lo dice con todas las letras. Compartir el motor de verdad —un | |
| 67 | +// SharedWorker con WebGPU dentro, que ya esta comprobado que funciona— es el | |
| 68 | +// paso siguiente y bastante mas grande. | |
| 69 | +// | |
| 70 | +// Solo para modelos GRANDES: dos instancias del pequeño caben de sobra y | |
| 71 | +// bloquearlas seria entorpecer sin motivo. | |
| 72 | +const CERROJO_DESDE = 2 * 1024 * 1024 * 1024; // 2 GB de pesos | |
| 73 | +let soltarCerrojo = null; | |
| 74 | + | |
| 75 | +async function tomarCerrojo(etiqueta) { | |
| 76 | + // Sin la API (navegador viejo) no se bloquea nada: mas vale lento que roto. | |
| 77 | + if (typeof navigator === 'undefined' || !navigator.locks) return true; | |
| 78 | + if (soltarCerrojo) return true; // ya lo tenemos | |
| 79 | + let decidir; | |
| 80 | + const resultado = new Promise(r => { decidir = r; }); | |
| 81 | + navigator.locks.request('elffuss-motor-pesado', { ifAvailable: true }, (cerrojo) => { | |
| 82 | + if (!cerrojo) { decidir(false); return; } // lo tiene otra pestaña | |
| 83 | + decidir(true); | |
| 84 | + // Se mantiene tomado mientras viva la sesion: la promesa no se resuelve | |
| 85 | + // hasta `unload()`. | |
| 86 | + return new Promise(r => { soltarCerrojo = r; }); | |
| 87 | + }).catch(() => decidir(true)); // si la API falla, no estorbar | |
| 88 | + return resultado; | |
| 89 | +} | |
| 90 | +let modelo = null, sesion = null, tk = null, gpu = null, muestreo = null; | |
| 91 | +// ¿Este modelo espera un bloque de razonamiento en el prompt? Se DEDUCE de la | |
| 92 | +// plantilla que trae el propio fichero, no se cablea por nombre de modelo: así | |
| 93 | +// un GGUF sin razonamiento no recibe un bloque que no entiende, y uno nuevo que | |
| 94 | +// sí lo lleve funciona sin tocar nada. | |
| 95 | +let pensante = false; | |
| 96 | +let cargando = null; | |
| 97 | +let descargando = null; // la descarga en curso, si la hay: ver `unload` | |
| 98 | +// Las fichas del bloque de sistema que describe la ranura 'sistema' de la | |
| 99 | +// instantánea. `null` = no hay foto del sistema válida. Se guardan las FICHAS y | |
| 100 | +// no un hash para poder comparar una por una: un hash igual con contenido | |
| 101 | +// distinto contestaría de otra conversación sin dar ningún error. | |
| 102 | +let sistemaFoto = null; | |
| 103 | +let perdida = ''; // motivo si el dispositivo se perdió por debajo | |
| 104 | + | |
| 105 | +// Los tokens que el estado de la sesión YA ha ingerido: prompt del turno | |
| 106 | +// anterior más lo que se le realimentó al generar. Es la clave para no volver a | |
| 107 | +// procesar la conversación entera en cada turno. `null` = el estado no sirve y | |
| 108 | +// hay que reiniciar. Se invalida ANTES de tocar el estado y solo se vuelve a | |
| 109 | +// poner al terminar bien: si un turno revienta a medias, el siguiente reinicia. | |
| 110 | +let consumidos = null; | |
| 111 | + | |
| 112 | +export function configure(key) { | |
| 113 | + if (key && MODELS[key] && key !== clave) { | |
| 114 | + clave = key; | |
| 115 | + if (modelo) unload(); // otro modelo: fuera el anterior | |
| 116 | + return true; | |
| 117 | + } | |
| 118 | + return false; | |
| 119 | +} | |
| 120 | + | |
| 121 | +// ¿Este modelo pide que se le hable en corto? El agente decide hoy por tamaño | |
| 122 | +// de contexto, y eso no basta: a este le CABE el prompt completo y aun así | |
| 123 | +// tarda catorce veces más con él. Se pregunta al proveedor en vez de deducirlo. | |
| 124 | +// Ningún modelo pide ya prompt compacto: recortarlo los dejaba sin saber hacer | |
| 125 | +// tareas. Se mantiene la función porque las apps la llaman con `?.()` y | |
| 126 | +// devolver false es la respuesta correcta, no un hueco. | |
| 127 | +export function prefiereCompacto() { | |
| 128 | + return false; | |
| 129 | +} | |
| 130 | + | |
| 131 | +export function models() { | |
| 132 | + return Object.entries(MODELS).map(([id, m]) => ({ id, label: m.label })); | |
| 133 | +} | |
| 134 | + | |
| 135 | +// Gancho SOLO para los tests: apunta el modelo activo a una URL servida en | |
| 136 | +// local. Sin esto, probar el proveedor exigiría bajar el modelo entero de | |
| 137 | +// Hugging Face en cada ejecución, que es la clase de test que nadie vuelve a correr. | |
| 138 | +export function __setModelForTest(url, bytes = 0) { | |
| 139 | + MODELS[clave] = { ...MODELS[clave], url, bytes }; | |
| 140 | +} | |
| 141 | + | |
| 142 | +// Gancho SOLO para los tests: olvida el prefijo ingerido, de modo que el turno | |
| 143 | +// siguiente reinicie el estado como si fuera el primero. Sin esto, un banco que | |
| 144 | +// corre la MISMA conversación dos veces depende de una rama lateral —que el | |
| 145 | +// prompt de la segunda vuelta sea más corto que lo ya ingerido— para partir | |
| 146 | +// limpio, y entonces no estaría probando lo que dice probar. | |
| 147 | +export function __olvidaPrefijo() { | |
| 148 | + consumidos = null; | |
| 149 | + sistemaFoto = null; // las DOS ranuras, o el banco mediría con la del sistema viva | |
| 150 | +} | |
| 151 | + | |
| 152 | +// Handle de lectura por rangos. Primero OPFS (queda cacheado en disco entre | |
| 153 | +// visitas); si no está disponible, rangos HTTP directos — más lento en la | |
| 154 | +// segunda visita, pero funciona en vez de fallar. | |
| 155 | +async function abrirPorRangos(url, onProgress, cachear = true) { | |
| 156 | + // ABSOLUTA siempre. El almacén puede delegar en el broker compartido, que vive | |
| 157 | + // en OTRO origen: una URL relativa se resolvería contra el suyo y apuntaría a | |
| 158 | + // un fichero que allí no existe. | |
| 159 | + // El reparto se comprueba ANTES de normalizar: `new URL()` sobre un array | |
| 160 | + // hace cosas raras en silencio en vez de fallar. | |
| 161 | + // El reparto devuelve su propio `donde`: decir solo «2 servidores» ocultaba lo | |
| 162 | + // único que hacía falta saber para juzgar el cacheo —si vino del almacén o de | |
| 163 | + // la red—, y sin eso la prueba tenía que deducirlo por el reloj, que es | |
| 164 | + // justamente el instrumento que ya engañó tres veces. | |
| 165 | + if (Array.isArray(url)) return await rangosRepartidos(url, onProgress, cachear); | |
| 166 | + try { url = new URL(url, location.href).href; } catch { /* sin location */ } | |
| 167 | + if (cachear) { | |
| 168 | + try { | |
| 169 | + const store = await import('../runtime/model-store.js'); | |
| 170 | + // SIN guardián aquí. Lo hubo —45 s— de cuando el broker no tenía ninguno | |
| 171 | + // y una petición sin respuesta dejaba la carga colgada para siempre. Ese | |
| 172 | + // guardián ya vive DONDE corresponde: el SDK del broker corta por | |
| 173 | + // inactividad (30 s rearmados con cada mensaje), que es la capa que sabe | |
| 174 | + // distinguir «tarda» de «enmudeció». | |
| 175 | + // | |
| 176 | + // Mantenerlo fuera hacía daño: el plazo se agotaba en toda descarga real, | |
| 177 | + // el motor caía a leer por red, y la del almacén seguía por detrás hasta | |
| 178 | + // guardar. O sea que SÍ se cacheaba, pero por efecto secundario y con la | |
| 179 | + // primera carga el doble de lenta. Un fallo que se disfraza de que todo | |
| 180 | + // va bien es peor que uno que se ve. | |
| 181 | + const ranged = await store.openRanged(url, onProgress); | |
| 182 | + if (ranged) return { ranged, donde: 'disco (OPFS)' }; | |
| 183 | + } catch (e) { | |
| 184 | + console.warn('[engine] almacén no disponible, se lee por red:', e.message); | |
| 185 | + } | |
| 186 | + } | |
| 187 | + | |
| 188 | + onProgress('Leyendo el modelo por partes desde la red…'); | |
| 189 | + const cabeza = await fetch(url, { headers: { Range: 'bytes=0-0' } }); | |
| 190 | + const cr = cabeza.headers.get('content-range'); | |
| 191 | + // Comprobar el 206 y no solo la cabecera: un servidor que ignora el Range | |
| 192 | + // responde 200 con el fichero ENTERO, y aquí eso es el modelo entero en | |
| 193 | + // memoria de golpe — la pestaña se muere sin decir por qué. | |
| 194 | + if (cabeza.status !== 206 || !cr) { | |
| 195 | + throw new Error('El servidor del modelo no admite descargas por partes, y el modelo es demasiado grande para bajarlo entero.'); | |
| 196 | + } | |
| 197 | + const size = +cr.split('/')[1]; | |
| 198 | + return { | |
| 199 | + donde: 'red (sin caché)', | |
| 200 | + ranged: { | |
| 201 | + size, | |
| 202 | + // Se COMPRUEBA que vuelven los bytes pedidos. Un modelo grande son cientos | |
| 203 | + // de peticiones, y basta UNA corta —o un 200 porque el servidor ignoró el Range— para que | |
| 204 | + // esos bytes de menos entren como PESOS: sin error, sin traza, modelo | |
| 205 | + // «cargado» y luego mudo o delirante. En localhost no pasa casi nunca y | |
| 206 | + // por internet sí, o sea que el fallo solo aparecía servido de verdad: el | |
| 207 | + // peor reparto posible entre dónde se prueba y dónde se rompe. | |
| 208 | + // | |
| 209 | + // gguf.js ya hacía esta comprobación para la cabecera («lectura corta: N | |
| 210 | + // de M bytes»). La disciplina estaba escrita en un camino y faltaba en el | |
| 211 | + // otro, que es donde van los gigabytes. | |
| 212 | + async slice(offset, length) { | |
| 213 | + if (length <= 0) return new ArrayBuffer(0); | |
| 214 | + const fin = Math.min(offset + length, size) - 1; | |
| 215 | + const quiero = fin - offset + 1; | |
| 216 | + let ultimo = ''; | |
| 217 | + for (let intento = 0; intento < 3; intento++) { | |
| 218 | + try { | |
| 219 | + const r = await fetch(url, { headers: { Range: `bytes=${offset}-${fin}` } }); | |
| 220 | + // Un 200 aquí significa que el servidor ignoró el Range y viene el | |
| 221 | + // fichero ENTERO, todo a memoria. Se rechaza antes de leerlo. | |
| 222 | + if (r.status !== 206) { ultimo = `respondió ${r.status} y no 206`; continue; } | |
| 223 | + const buf = await r.arrayBuffer(); | |
| 224 | + if (buf.byteLength === quiero) return buf; | |
| 225 | + ultimo = `devolvió ${buf.byteLength} bytes de ${quiero}`; | |
| 226 | + } catch (e) { ultimo = String(e && e.message || e); } | |
| 227 | + } | |
| 228 | + throw new Error(`El servidor del modelo devolvió datos incompletos y los pesos ` + | |
| 229 | + `quedarían corruptos (bytes ${offset}-${fin}: ${ultimo}). Vuelve a intentarlo.`); | |
| 230 | + }, | |
| 231 | + }, | |
| 232 | + }; | |
| 233 | +} | |
| 234 | + | |
| 235 | +// Handle por rangos sobre un modelo REPARTIDO entre varios hosts. Cada | |
| 236 | +// fragmento vive en su propio subdominio, y eso no es capricho: la cuota de | |
| 237 | +// almacenamiento del navegador es POR ORIGEN —cada origen cuenta solo lo | |
| 238 | +// suyo—, así que repartir multiplica el techo. El modelo grande no cabía fiable | |
| 239 | +// en un origen, y en dos entra holgado. | |
| 240 | +// | |
| 241 | +// Hacia arriba se ve UN fichero: mismo {size, slice} que el resto del motor. | |
| 242 | +async function rangosRepartidos(fragmentos, onProgress, cachear = true) { | |
| 243 | + onProgress('Leyendo el modelo repartido entre servidores…'); | |
| 244 | + // Primero el ALMACÉN: cada fragmento lo guarda el broker de su propio origen, | |
| 245 | + // troceado en partes porque el navegador corta un fichero suelto demasiado | |
| 246 | + // grande. Así la segunda visita no vuelve a pedirlo; sin esto, la descarga | |
| 247 | + // entera en cada sesión. | |
| 248 | + // Lo que el almacén SÍ consiguió, por URL. Vale aunque falte algo: lo que hay | |
| 249 | + // aquí no se vuelve a pedir por red. | |
| 250 | + // | |
| 251 | + // Antes esto era todo-o-nada: un `throw` al primer fragmento que fallara, y el | |
| 252 | + // `catch` se bajaba por red los DOS, incluido el que ya estaba entero en | |
| 253 | + // disco, o sea el doble de descarga en cada sesión que fallaba. El desperdicio | |
| 254 | + // no estaba en el broker: estaba aquí. | |
| 255 | + const delAlmacen = new Map(); | |
| 256 | + if (cachear) { | |
| 257 | + try { | |
| 258 | + const { getSharedModel } = await import('../runtime/model-broker.js'); | |
| 259 | + for (const [i, f] of fragmentos.entries()) { | |
| 260 | + onProgress(`Recuperando el modelo · parte ${i + 1} de ${fragmentos.length}…`); | |
| 261 | + try { | |
| 262 | + const blob = await conLatido(latir => getSharedModel(f.url, m => { | |
| 263 | + latir(); | |
| 264 | + if (m?.total) onProgress(`Descargando el modelo · parte ${i + 1}/${fragmentos.length} · ` + | |
| 265 | + `${Math.round(m.loaded / m.total * 100)} %`); | |
| 266 | + }), 60000, 'el almacén compartido'); | |
| 267 | + // El tamaño se comprueba igual que antes; lo que cambia es que un | |
| 268 | + // fragmento malo ya no arrastra a los buenos. | |
| 269 | + if (blob && (!f.bytes || blob.size === f.bytes)) delAlmacen.set(f.url, blob); | |
| 270 | + else console.warn('[engine] fragmento incompleto en el almacén:', f.url); | |
| 271 | + } catch (e) { | |
| 272 | + console.warn('[engine] el almacén no dio', f.url, '→', e.message); | |
| 273 | + } | |
| 274 | + } | |
| 275 | + if (delAlmacen.size === fragmentos.length) { | |
| 276 | + return { | |
| 277 | + ranged: desdeBlobs(fragmentos.map(f => delAlmacen.get(f.url))), | |
| 278 | + donde: `almacén compartido · ${fragmentos.length} servidores`, | |
| 279 | + }; | |
| 280 | + } | |
| 281 | + } catch (e) { | |
| 282 | + // Que el almacén falle NO puede impedir usar el modelo: se cae a leerlo | |
| 283 | + // del servidor, que es más lento pero funciona. | |
| 284 | + console.warn('[engine] almacén no disponible, se lee por red:', e.message); | |
| 285 | + } | |
| 286 | + } | |
| 287 | + // NO paralelizar estas lecturas. Parece la optimización obvia —cientos de | |
| 288 | + // peticiones una detrás de otra para cargar el 27B— y no lo es: varios flujos | |
| 289 | + // a la vez no bajan antes que uno, porque el cuello es el enlace. La única | |
| 290 | + // palanca real sobre el tiempo de carga es no volver a bajarlo: el almacén | |
| 291 | + // de arriba. | |
| 292 | + const trozos = []; | |
| 293 | + let size = 0; | |
| 294 | + for (const f of fragmentos) { | |
| 295 | + // Si el almacén dio ESTE fragmento, se lee de disco y no se toca la red: | |
| 296 | + // ni la sonda de tamaño (que ya lo sabemos) ni los rangos. | |
| 297 | + const blob = delAlmacen.get(f.url); | |
| 298 | + if (blob) { trozos.push({ url: f.url, desde: size, bytes: blob.size, blob }); size += blob.size; continue; } | |
| 299 | + const cab = await fetch(f.url, { headers: { Range: 'bytes=0-0' } }); | |
| 300 | + const cr = cab.headers.get('content-range'); | |
| 301 | + if (cab.status !== 206 || !cr) { | |
| 302 | + throw new Error('Un servidor del modelo no admite descargas por partes: ' + f.url); | |
| 303 | + } | |
| 304 | + const n = +cr.split('/')[1]; | |
| 305 | + // El tamaño DECLARADO se comprueba contra el real. Si un fragmento cambia | |
| 306 | + // de tamaño, las fronteras se desplazan y todo lo que venga detrás se lee | |
| 307 | + // corrido: basura sin un solo error. | |
| 308 | + if (f.bytes && n !== f.bytes) { | |
| 309 | + throw new Error(`Un fragmento del modelo mide ${n} y se esperaban ${f.bytes}.`); | |
| 310 | + } | |
| 311 | + trozos.push({ url: f.url, desde: size, bytes: n }); | |
| 312 | + size += n; | |
| 313 | + } | |
| 314 | + | |
| 315 | + const cual = abs => { // búsqueda binaria del fragmento | |
| 316 | + let lo = 0, hi = trozos.length - 1; | |
| 317 | + while (lo < hi) { const m = (lo + hi + 1) >> 1; if (trozos[m].desde <= abs) lo = m; else hi = m - 1; } | |
| 318 | + return lo; | |
| 319 | + }; | |
| 320 | + const pedir = async (t, desde, cuanto) => { | |
| 321 | + // Fragmento que vino del almacén: se corta el Blob, sin red. | |
| 322 | + if (t.blob) return await t.blob.slice(desde, desde + cuanto).arrayBuffer(); | |
| 323 | + const fin = desde + cuanto - 1; | |
| 324 | + for (let intento = 0; intento < 3; intento++) { | |
| 325 | + const r = await fetch(t.url, { headers: { Range: `bytes=${desde}-${fin}` } }); | |
| 326 | + if (r.status !== 206) continue; | |
| 327 | + const buf = await r.arrayBuffer(); | |
| 328 | + if (buf.byteLength === cuanto) return buf; | |
| 329 | + } | |
| 330 | + throw new Error(`Datos incompletos de ${t.url} (bytes ${desde}-${fin}).`); | |
| 331 | + }; | |
| 332 | + | |
| 333 | + return { | |
| 334 | + // Honesto cuando es mixto: decir «red» con la mitad saliendo de disco | |
| 335 | + // escondería justo lo que acabamos de arreglar. | |
| 336 | + donde: delAlmacen.size | |
| 337 | + ? `mixto · ${delAlmacen.size} del almacén y ${fragmentos.length - delAlmacen.size} por red` | |
| 338 | + : `red · ${fragmentos.length} servidores`, | |
| 339 | + ranged: { | |
| 340 | + size, | |
| 341 | + async slice(offset, length) { | |
| 342 | + // Math.trunc y no |0: esto pasa de 2^31 y el bitwise trunca a 32 bits. | |
| 343 | + const from = Math.max(0, Math.min(size, Math.trunc(offset) || 0)); | |
| 344 | + const want = Math.max(0, Math.min(size - from, Math.trunc(length) || 0)); | |
| 345 | + if (want === 0) return new ArrayBuffer(0); | |
| 346 | + const i0 = cual(from), d0 = from - trozos[i0].desde; | |
| 347 | + if (d0 + want <= trozos[i0].bytes) return await pedir(trozos[i0], d0, want); | |
| 348 | + // A caballo de dos servidores. Pasa poco, pero pasa: los tensores no se | |
| 349 | + // alinean con la frontera del reparto. | |
| 350 | + const out = new Uint8Array(want); | |
| 351 | + let puesto = 0; | |
| 352 | + for (let i = i0; i < trozos.length && puesto < want; i++) { | |
| 353 | + const d = i === i0 ? d0 : 0; | |
| 354 | + const cuanto = Math.min(trozos[i].bytes - d, want - puesto); | |
| 355 | + if (cuanto <= 0) continue; | |
| 356 | + out.set(new Uint8Array(await pedir(trozos[i], d, cuanto)), puesto); | |
| 357 | + puesto += cuanto; | |
| 358 | + } | |
| 359 | + return out.buffer; | |
| 360 | + }, | |
| 361 | + }, | |
| 362 | + }; | |
| 363 | +} | |
| 364 | + | |
| 365 | +// Handle por rangos sobre fragmentos YA guardados en disco. Blob.slice() es | |
| 366 | +// perezoso: no se traga los gigabytes en memoria. | |
| 367 | +function desdeBlobs(ficheros) { | |
| 368 | + const inicio = []; let size = 0; | |
| 369 | + for (const f of ficheros) { inicio.push(size); size += f.size; } | |
| 370 | + const cual = abs => { let lo = 0, hi = inicio.length - 1; | |
| 371 | + while (lo < hi) { const m = (lo + hi + 1) >> 1; if (inicio[m] <= abs) lo = m; else hi = m - 1; } return lo; }; | |
| 372 | + return { | |
| 373 | + size, | |
| 374 | + async slice(offset, length) { | |
| 375 | + const from = Math.max(0, Math.min(size, Math.trunc(offset) || 0)); | |
| 376 | + const want = Math.max(0, Math.min(size - from, Math.trunc(length) || 0)); | |
| 377 | + if (want === 0) return new ArrayBuffer(0); | |
| 378 | + const i0 = cual(from), d0 = from - inicio[i0]; | |
| 379 | + if (d0 + want <= ficheros[i0].size) return await ficheros[i0].slice(d0, d0 + want).arrayBuffer(); | |
| 380 | + const out = new Uint8Array(want); let puesto = 0; | |
| 381 | + for (let i = i0; i < ficheros.length && puesto < want; i++) { | |
| 382 | + const d = i === i0 ? d0 : 0; | |
| 383 | + const cuanto = Math.min(ficheros[i].size - d, want - puesto); | |
| 384 | + if (cuanto <= 0) continue; | |
| 385 | + out.set(new Uint8Array(await ficheros[i].slice(d, d + cuanto).arrayBuffer()), puesto); | |
| 386 | + puesto += cuanto; | |
| 387 | + } | |
| 388 | + return out.buffer; | |
| 389 | + }, | |
| 390 | + }; | |
| 391 | +} | |
| 392 | + | |
| 393 | +// Permite apuntar a un GGUF propio en vez del de Hugging Face. Sirve para | |
| 394 | +// desarrollo (servirlo en local) y para quien quiera autoalojarlo o probar su | |
| 395 | +// propia cuantización sin tocar el código. | |
| 396 | +function modeloActivo() { | |
| 397 | + const m = MODELS[clave]; | |
| 398 | + let url = null; | |
| 399 | + // ?engine-url=… gana sobre el ajuste guardado: así se puede compartir un | |
| 400 | + // enlace que apunta a un modelo concreto sin tocar nada. | |
| 401 | + try { url = new URL(location.href).searchParams.get('engine-url'); } catch { /* — */ } | |
| 402 | + if (url) { try { localStorage.setItem('elffuss.engine.url', url); } catch { /* — */ } } | |
| 403 | + if (!url) { try { url = localStorage.getItem('elffuss.engine.url'); } catch { /* — */ } } | |
| 404 | + return url ? { ...m, url, bytes: 0 } : m; // bytes 0: no comparar tamaños | |
| 405 | +} | |
| 406 | + | |
| 407 | +// Un fallo de una dependencia debe DEGRADAR, no colgar. El almacén compartido | |
| 408 | +// delega en un broker cross-origin cuya petición no lleva timeout: si el broker | |
| 409 | +// recibe la petición y nunca contesta, la promesa no se resuelve NUNCA y la | |
| 410 | +// carga se queda parada sin error, sin log y sin recuperación. Aquí se le pone | |
| 411 | +// un límite y se sigue por otro camino. | |
| 412 | +function conLimite(promesa, ms, queHacer) { | |
| 413 | + return Promise.race([ | |
| 414 | + promesa, | |
| 415 | + new Promise((_, no) => setTimeout(() => no(new Error(queHacer + ': sin respuesta en ' + ms + ' ms')), ms)), | |
| 416 | + ]); | |
| 417 | +} | |
| 418 | + | |
| 419 | +// Igual, pero el reloj se REINICIA con cada señal de vida. Un tope total no | |
| 420 | +// sirve para algo que tarda lo que tarda una descarga: con un tope total sobre | |
| 421 | +// el almacén, una descarga normal agotaba siempre el plazo, caía a leer por red | |
| 422 | +// y nunca llegaba a guardarse. Parecía funcionar solo cuando ya estaba | |
| 423 | +// cacheado de antes, que es el peor disfraz posible. | |
| 424 | +// | |
| 425 | +// Lo que hay que detectar es que el otro lado ENMUDEZCA, no que tarde. | |
| 426 | +function conLatido(hacer, ms, queHacer) { | |
| 427 | + let temporizador, vivo = true; | |
| 428 | + return new Promise((si, no) => { | |
| 429 | + const rearmar = () => { | |
| 430 | + clearTimeout(temporizador); | |
| 431 | + if (!vivo) return; | |
| 432 | + temporizador = setTimeout(() => { vivo = false; no(new Error(queHacer + ': sin señales en ' + ms + ' ms')); }, ms); | |
| 433 | + }; | |
| 434 | + rearmar(); | |
| 435 | + hacer(rearmar).then(v => { vivo = false; clearTimeout(temporizador); si(v); }, | |
| 436 | + e => { vivo = false; clearTimeout(temporizador); no(e); }); | |
| 437 | + }); | |
| 438 | +} | |
| 439 | + | |
| 440 | +export async function load(onProgress = () => {}) { | |
| 441 | + // Una descarga a medias se espera ANTES de mirar `sesion`: `configure()` | |
| 442 | + // descarga sin esperar, y sin esto un `load()` justo detrás vería la sesión | |
| 443 | + // vieja todavía puesta, contestaría «ya está cargado» y la descarga la | |
| 444 | + // destruiría un instante después. | |
| 445 | + if (descargando) await descargando; | |
| 446 | + if (sesion) return; // idempotente: nunca dos motores | |
| 447 | + if (cargando) return cargando; // dos llamadas a la vez: una carga | |
| 448 | + cargando = (async () => { | |
| 449 | + const m = modeloActivo(); | |
| 450 | + try { | |
| 451 | + onProgress('Encendiendo la GPU…'); | |
| 452 | + perdida = ''; | |
| 453 | + gpu = await requestDevice({ label: 'elffuss-engine' }); | |
| 454 | + | |
| 455 | + // El device se comprueba al nacer, pero también se puede morir DESPUÉS: el | |
| 456 | + // proceso gráfico del navegador se reinicia y se lleva por delante los | |
| 457 | + // buffers, y con gigas de pesos dentro eso pasa de verdad. Sin enterarse, | |
| 458 | + // lo siguiente que ocurre es un forward que devuelve ceros o una promesa | |
| 459 | + // que no vuelve nunca: un cuelgue sin causa visible. Aquí se entera, y así | |
| 460 | + // el siguiente turno puede decir qué pasó en vez de quedarse mudo. | |
| 461 | + gpu.device.lost.then(info => { | |
| 462 | + // El estado se anula SIEMPRE, tanto si el dispositivo se cayó solo como si | |
| 463 | + // lo tiramos nosotros. Antes la rama 'destroyed' salía sin registrar nada y | |
| 464 | + // —lo grave— sin anular `sesion` ni `modelo`: la app se quedaba creyendo | |
| 465 | + // que seguía cargada sobre un dispositivo muerto, y el síntoma era | |
| 466 | + // «listo» y después silencio, sin un solo error. Un manejador que solo | |
| 467 | + // ve la muerte accidental y no la deliberada es un punto ciego que | |
| 468 | + // cuesta una tarde de diagnóstico cada vez que aparece. | |
| 469 | + const nuestra = info.reason === 'destroyed'; | |
| 470 | + // `sistemaFoto` también: sus buffers se van con la sesión, y creer que | |
| 471 | + // hay foto cuando ya no existe restauraría basura sin dar error. | |
| 472 | + sesion = null; modelo = null; consumidos = null; sistemaFoto = null; | |
| 473 | + if (nuestra) { console.info('[engine] GPU liberada por nosotros (destroyed)'); return; } | |
| 474 | + perdida = 'Se ha perdido la GPU con el modelo cargado' + | |
| 475 | + (info.message ? ` (${info.message})` : '') + '.'; | |
| 476 | + console.warn('[engine] ' + perdida); | |
| 477 | + }); | |
| 478 | + | |
| 479 | + // ── El cerrojo, ANTES DE MOVER UN BYTE ─────────────────────────────── | |
| 480 | + // ⚠️ Esto estaba al final, justo antes de reservar contexto, con un | |
| 481 | + // comentario que decía «el cerrojo se pide ANTES de reservar contexto». | |
| 482 | + // Era verdad y era inútil: para entonces la pestaña ya se había bajado el | |
| 483 | + // modelo entero y lo había subido al dispositivo. O sea que la segunda pestaña | |
| 484 | + // pagaba la carga completa de un modelo de este tamaño para que al final | |
| 485 | + // se le dijera que no. Peor todavía: durante toda esa carga SÍ había dos | |
| 486 | + // copias peleándose por el dispositivo, que es exactamente lo que el cerrojo | |
| 487 | + // existe para impedir. | |
| 488 | + // | |
| 489 | + // Pedirlo aquí no arriesga quedárselo colgado: cualquier excepción de | |
| 490 | + // esta carga pasa por el `catch` de abajo, que llama a `unload()`, y | |
| 491 | + // `unload()` suelta el cerrojo. | |
| 492 | + if ((m.bytes || 0) >= CERROJO_DESDE && globalThis.__ELFFUSS_SIN_CERROJO !== true) { | |
| 493 | + if (!(await tomarCerrojo(m.label))) { | |
| 494 | + throw new Error( | |
| 495 | + `Ya hay otra pestaña de Elffuss con ${m.label} cargado. Dos copias de ` + | |
| 496 | + `un modelo de este tamaño no caben en la GPU a la vez y las dos van ` + | |
| 497 | + `diez veces más lentas. Cierra la otra pestaña y vuelve a elegirlo aquí.`); | |
| 498 | + } | |
| 499 | + } | |
| 500 | + | |
| 501 | + // Avisar ANTES de bajar, no después: el usuario que no tiene sitio se | |
| 502 | + // entera ahora y no al final de una descarga entera. | |
| 503 | + const apretado = cachea(m) ? await faltaSitio(m.bytes) : null; | |
| 504 | + if (apretado) { | |
| 505 | + throw new Error(`${m.label} necesita unos ${GiB(apretado.necesita)} GiB y el navegador ` + | |
| 506 | + `solo puede guardar ${GiB(apretado.libre)} GiB más. Libera espacio en disco.`); | |
| 507 | + } | |
| 508 | + | |
| 509 | + const { ranged, donde } = await abrirPorRangos(m.url, onProgress, cachea(m)); | |
| 510 | + if (m.bytes && ranged.size !== m.bytes) { | |
| 511 | + console.warn(`[engine] el modelo mide ${ranged.size} y se esperaban ` + | |
| 512 | + `${m.bytes}: el fichero de origen ha cambiado`); | |
| 513 | + } | |
| 514 | + | |
| 515 | + // La cabecera primero: dice cuánto pesa cada tensor y permite dar | |
| 516 | + // progreso REAL durante la subida, que es la parte larga. | |
| 517 | + onProgress('Leyendo el índice del modelo… 0 %'); | |
| 518 | + const info = await parseGGUF(ranged); | |
| 519 | + tk = createTokenizer(info.meta); | |
| 520 | + pensante = /<think>/.test(String(info.meta['tokenizer.chat_template'] || '')); | |
| 521 | + | |
| 522 | + // La etiqueta cambia según de dónde salgan los pesos, y no es cosmética. | |
| 523 | + // Sin caché, esta fase NO es solo «subir»: es bajar los gigabytes y | |
| 524 | + // subirlos según llegan, y el tiempo se lo lleva casi todo la red. Decir | |
| 525 | + // solo «subiendo» mientras alguien espera a que baje el modelo entero | |
| 526 | + // hace que parezca colgado en el paso equivocado. | |
| 527 | + const etiqueta = donde.startsWith('red') | |
| 528 | + ? 'Descargando el modelo y subiéndolo a la GPU' | |
| 529 | + : 'Subiendo el modelo a la GPU'; | |
| 530 | + let ultimo = -1; | |
| 531 | + modelo = await loadModel(ranged, gpu.device, { | |
| 532 | + debug: false, | |
| 533 | + // Ancho de subgrupo del dispositivo: activa la reducción por subgrupos | |
| 534 | + // del matmul (más rápida que la de árbol). 0 si el dispositivo no los tiene. | |
| 535 | + subgroupSize: gpu.subgroupSize || 0, | |
| 536 | + onProgress: (hechos, total) => { | |
| 537 | + const pct = Math.floor(hechos / total * 100); | |
| 538 | + if (pct === ultimo) return; // no inundar la UI con el mismo % | |
| 539 | + ultimo = pct; | |
| 540 | + onProgress(`${etiqueta} · ${pct} %`); | |
| 541 | + }, | |
| 542 | + }); | |
| 543 | + | |
| 544 | + // El contexto se pide ENTERO al abrir la sesión: la caché KV se reserva de | |
| 545 | + // una vez, no crece. A 64k eso es mucha memoria ANTES de que el usuario | |
| 546 | + // escriba nada, y en un dispositivo con menos memoria la reserva falla. | |
| 547 | + // Sin esta escalera, ese fallo deja al usuario sin modelo cuando lo | |
| 548 | + // que quería era un contexto menor — un contexto de 16k sigue siendo | |
| 549 | + // ocho veces el de antes y no se parece en nada a no tener modelo. | |
| 550 | + // | |
| 551 | + // No se adivina por `navigator.deviceMemory` ni por el tamaño del | |
| 552 | + // adaptador: se INTENTA y se baja al fallar, que es el único método que no | |
| 553 | + // depende de un dato declarado que no todos los navegadores exponen. | |
| 554 | + // (el aviso de espacio se da ANTES de descargar; ver `faltaSitio`) | |
| 555 | + let pedido = m.ctx, ultimoFallo = null; | |
| 556 | + for (const c of escaleraContexto(m.ctx)) { | |
| 557 | + try { sesion = createSession(modelo, { contextLen: c }); pedido = c; break; } | |
| 558 | + catch (e) { ultimoFallo = e; } | |
| 559 | + } | |
| 560 | + if (!sesion) throw ultimoFallo || new Error('no se pudo reservar ningún contexto'); | |
| 561 | + ctxEfectivo = pedido; | |
| 562 | + if (pedido !== m.ctx) { | |
| 563 | + console.warn(`[engine] ${m.label}: no cupo un contexto de ${m.ctx}, se abre con ${pedido}`); | |
| 564 | + } | |
| 565 | + name = 'Elffuss Engine · ' + m.label; | |
| 566 | + console.log(`[engine] ${m.label} listo desde ${donde} · ${sesion.state.summary()}`); | |
| 567 | + onProgress('Modelo listo · 100 %'); | |
| 568 | + } catch (e) { | |
| 569 | + await unload(); | |
| 570 | + // El kernel enseña este mensaje TAL CUAL al usuario. | |
| 571 | + throw new Error(mensajeHumano(e, m)); | |
| 572 | + } finally { | |
| 573 | + cargando = null; | |
| 574 | + } | |
| 575 | + })(); | |
| 576 | + return cargando; | |
| 577 | +} | |
| 578 | + | |
| 579 | +// Comprueba que quepa ANTES de empezar a bajar gigas. Sin esto, el disco lleno | |
| 580 | +// se manifiesta como un `Failed to fetch` a mitad de descarga: un mensaje que | |
| 581 | +// culpa a la red de un problema de espacio, después de hacer esperar al usuario. | |
| 582 | +// Visto de verdad con el modelo grande: sin sitio para guardarlo, la descarga | |
| 583 | +// muere y el error que llega arriba habla de red. | |
| 584 | +// | |
| 585 | +// `estimate()` no existe en todos los navegadores y su cuota es orientativa, así | |
| 586 | +// que esto solo AVISA cuando está claro que no cabe; nunca impide intentarlo por | |
| 587 | +// no saberlo. Un falso negativo deja al usuario donde estaba; un falso positivo | |
| 588 | +// le negaría un modelo que sí cabía. | |
| 589 | +async function faltaSitio(bytes) { | |
| 590 | + try { | |
| 591 | + if (!navigator.storage?.estimate || !bytes) return null; | |
| 592 | + const { quota, usage } = await navigator.storage.estimate(); | |
| 593 | + if (!quota) return null; | |
| 594 | + const libre = quota - (usage || 0); | |
| 595 | + // Margen del 5 %: la cuota es una estimación y escribir justo al borde | |
| 596 | + // falla igual, solo que más tarde y peor. | |
| 597 | + return libre < bytes * 1.05 ? { libre, necesita: bytes, quota } : null; | |
| 598 | + } catch { return null; } | |
| 599 | +} | |
| 600 | + | |
| 601 | +const GiB = (n) => (n / 1024 ** 3).toFixed(1); | |
| 602 | + | |
| 603 | +function mensajeHumano(e, m) { | |
| 604 | + const t = String(e?.message || e); | |
| 605 | + // `Failed to fetch` es lo que sale cuando la escritura al almacenamiento | |
| 606 | + // revienta a media descarga, y leerlo como un problema de red manda al | |
| 607 | + // usuario a mirar su wifi en vano. | |
| 608 | + if (/Failed to fetch|NetworkError|QuotaExceeded|exceed.*quota/i.test(t)) { | |
| 609 | + return `No se pudo descargar ${m.label}. Suele ser falta de espacio en disco ` + | |
| 610 | + `—ocupa unos ${GiB(m.bytes || 0)} GiB— o una conexión que se ha cortado. ` + | |
| 611 | + 'Libera espacio y vuelve a intentarlo.'; | |
| 612 | + } | |
| 613 | + if (/límite de binding|maxStorageBufferBindingSize/i.test(t)) { | |
| 614 | + return `Este navegador no deja crear buffers lo bastante grandes para ${m.label}. ` + | |
| 615 | + 'En iPhone el límite es mucho menor que en escritorio.'; | |
| 616 | + } | |
| 617 | + if (/sin WebGPU|no hay adaptador/i.test(t)) { | |
| 618 | + return 'Este navegador no tiene WebGPU disponible. Hace falta Chrome, Edge o Safari 18+.'; | |
| 619 | + } | |
| 620 | + if (/out-of-memory|OutOfMemory/i.test(t)) { | |
| 621 | + return `No hay memoria de GPU suficiente para ${m.label} en este equipo.`; | |
| 622 | + } | |
| 623 | + return `No se pudo cargar ${m.label}: ${t}`; | |
| 624 | +} | |
| 625 | + | |
| 626 | +// Descargar empieza por PARAR. Antes se destruían los buffers con un turno en | |
| 627 | +// marcha —la app llama aquí justo cuando la memoria va justa, que | |
| 628 | +// es cuando más probable es que haya uno— y el forward seguía grabando sobre | |
| 629 | +// memoria ya liberada. Ahora se para el turno, se espera a que suelte el motor | |
| 630 | +// y solo entonces se destruye. | |
| 631 | +// | |
| 632 | +// Se guarda la promesa en `descargando` para que `load()` y los turnos que | |
| 633 | +// lleguen mientras tanto la esperen en vez de ver la sesión vieja. | |
| 634 | +export async function unload() { | |
| 635 | + if (!descargando) descargando = descargar().finally(() => { descargando = null; }); | |
| 636 | + return descargando; | |
| 637 | +} | |
| 638 | + | |
| 639 | +async function descargar() { | |
| 640 | + // Con su propio motivo: el turno parado así no lo pidió quien lo lanzó, y | |
| 641 | + // el error tiene que decirlo (ver «POR QUÉ se paró»). | |
| 642 | + try { await pararTodos('descarga'); } catch { /* parar nunca impide descargar */ } | |
| 643 | + pensante = false; | |
| 644 | + try { sesion?.destroy?.(); } catch { /* mejor esfuerzo */ } | |
| 645 | + try { | |
| 646 | + for (const { buf } of modelo?.weights?.values?.() || []) buf.destroy(); | |
| 647 | + } catch { /* mejor esfuerzo */ } | |
| 648 | + try { gpu?.device?.destroy?.(); } catch { /* mejor esfuerzo */ } | |
| 649 | + sesion = null; modelo = null; tk = null; gpu = null; | |
| 650 | + // Soltar el cerrojo: si no, la pestaña seguiria reservando el modelo grande | |
| 651 | + // despues de descargarlo y ninguna otra podria cargarlo. | |
| 652 | + try { soltarCerrojo?.(); } finally { soltarCerrojo = null; } | |
| 653 | + // Y el rastro del prefijo, o el siguiente turno creería que puede reutilizar | |
| 654 | + // contra un estado que ya no existe. No es teórico: `configure()` llama aquí | |
| 655 | + // al cambiar de modelo y la app llama a `unload()` cuando el | |
| 656 | + // heap se dispara. Un `consumidos` que sobreviva a eso describe tokens que la | |
| 657 | + // sesión NUEVA no ha ingerido, y la reutilización saldría adelante contra un | |
| 658 | + // estado limpio: texto plausible, ningún error, imposible de atribuir. | |
| 659 | + // | |
| 660 | + // Y `sistemaFoto` por la misma razón, agravada: `destroy()` libera los | |
| 661 | + // buffers sombra de las dos ranuras, así que una foto del sistema que | |
| 662 | + // sobreviva a esto apunta a memoria liberada. | |
| 663 | + consumidos = null; | |
| 664 | + sistemaFoto = null; | |
| 665 | +} | |
| 666 | + | |
| 667 | +// {temperature, seed, p, k, maxTokens} o null para volver a voraz. Lo usa el | |
| 668 | +// jurado de rlm.js para pedir varias respuestas distintas del mismo prompt. | |
| 669 | +// | |
| 670 | +// Los campos se copian uno a uno en vez de propagar el objeto: así una clave | |
| 671 | +// desconocida no se cuela hasta el muestreador, donde cambiaría la salida en | |
| 672 | +// silencio. `maxTokens` es el tope de la respuesta. | |
| 673 | +export function setSampling(opts) { | |
| 674 | + if (!opts) { muestreo = null; return; } // null = volver al del registro (o a voraz) | |
| 675 | + // FUSIONA sobre lo que hubiera, no reemplaza. Lo más natural que hace quien | |
| 676 | + // usa esto es acotar solo la longitud —setSampling({maxTokens: 120})— y con | |
| 677 | + // la versión que reemplazaba, esa llamada devolvía en silencio la temperatura | |
| 678 | + // y la semilla a sus valores por defecto. Cambiar el muestreo entero cuando | |
| 679 | + // te han pedido un tope de longitud es de las cosas que cuestan horas de | |
| 680 | + // encontrar, porque no falla: sale otra respuesta y ya. | |
| 681 | + // | |
| 682 | + // Se sigue copiando campo a campo en vez de propagar el objeto: una clave | |
| 683 | + // desconocida no debe colarse hasta el muestreador, donde cambiaría la salida | |
| 684 | + // sin que nadie lo haya pedido. | |
| 685 | + // Se fusiona sobre lo que haya o, si no hay nada, sobre el muestreo que el | |
| 686 | + // REGISTRO declara para el modelo: acotar la longitud de un 27B no debe | |
| 687 | + // devolverlo a voraz en silencio. | |
| 688 | + const a = muestreo || muestreoDelRegistro() || {}; | |
| 689 | + muestreo = { | |
| 690 | + temperature: opts.temperature ?? a.temperature ?? 0, | |
| 691 | + topP: opts.p ?? a.topP ?? 1, | |
| 692 | + topK: opts.k ?? a.topK ?? 0, | |
| 693 | + minP: opts.minP ?? a.minP ?? 0, | |
| 694 | + presence: opts.presence ?? a.presence ?? 0, | |
| 695 | + repeatPenalty: opts.repeatPenalty ?? a.repeatPenalty ?? 1.1, | |
| 696 | + seed: opts.seed ?? a.seed ?? 1, | |
| 697 | + maxTokens: opts.maxTokens ?? a.maxTokens ?? 0, | |
| 698 | + // true/false lo fuerza; null, lo que diga el registro del modelo. | |
| 699 | + // `razonar: null` explícito vuelve a lo del registro; sin la clave, se conserva. | |
| 700 | + razonar: 'razonar' in opts ? (typeof opts.razonar === 'boolean' ? opts.razonar : null) : (a.razonar ?? null), | |
| 701 | + }; | |
| 702 | +} | |
| 703 | + | |
| 704 | +// El gestor del historial del núcleo de agente. Si no está (motor usado suelto, | |
| 705 | +// fuera de Elffuss), se cae a la cola reciente en vez de fallar. | |
| 706 | +async function ajustaHistorial(history, presupuesto) { | |
| 707 | + try { | |
| 708 | + const { packHistoryAsync } = await import('../context.js'); | |
| 709 | + return await packHistoryAsync(history, presupuesto); | |
| 710 | + } catch { return history.slice(-12); } | |
| 711 | +} | |
| 712 | + | |
| 713 | +// ChatML, que es lo que espera esta familia de modelos. La plantilla del GGUF | |
| 714 | +// es Jinja y no se interpreta aquí: se construye el mismo formato a mano. | |
| 715 | +// El bloque de razonamiento VACÍO que abre la plantilla. Se saca a una constante | |
| 716 | +// porque es exactamente lo que hay que poder separar: entra en el estado al | |
| 717 | +// generar, pero NO se reproduce cuando ese turno pasa a ser historia, así que | |
| 718 | +// mientras esté dentro, lo ingerido no puede ser prefijo del prompt siguiente. | |
| 719 | +// Medido: el desfase era de 5 tokens constantes, y son estos. | |
| 720 | +const PENSAR = '<think>\n\n</think>\n\n'; | |
| 721 | +// …y el bloque ABIERTO, para cuando el modelo SÍ razona: la plantilla termina en | |
| 722 | +// «<think>\n» y el modelo escribe su razonamiento, el «</think>» y la respuesta. | |
| 723 | +const ABRIR = '<think>\n'; | |
| 724 | + | |
| 725 | +// ¿Razona ESTE turno? Solo si el modelo es pensante (lo dice su plantilla) y: | |
| 726 | +// · `setSampling({ razonar: true|false })` lo fuerza, o | |
| 727 | +// · si nadie lo pide, lo decide el registro (`razona: true` en el modelo). | |
| 728 | +// Una llamada que acota la respuesta en corto (`maxTokens` explícito por debajo | |
| 729 | +// de RAZONAR_MIN, como el jurado de rlm.js) no razona: con 8 o 120 tokens el | |
| 730 | +// razonamiento se comería el turno entero y saldría vacío. | |
| 731 | +// | |
| 732 | +// Por qué existe: en tareas de agente, MiniCPM5-2B sin razonar se paraba al | |
| 733 | +// segundo paso sin tocar nada, y razonando sí avanzaba. Con el bloque siempre | |
| 734 | +// cerrado, un modelo así casi no podía trabajar. | |
| 735 | +const RAZONAR_MIN = 1024; | |
| 736 | + | |
| 737 | +// El muestreo que el registro declara para el modelo activo (la ficha de su | |
| 738 | +// fabricante), o null si no declara ninguno. Se usa cuando la app no ha fijado | |
| 739 | +// otro con setSampling. Sin esto todo modelo iba en voraz con penalización de | |
| 740 | +// repetición 1,1, que no es lo que recomienda ningún fabricante: el 27B, por | |
| 741 | +// ejemplo, pide 0,7 / 0,8 / k20 / presence 1,5 sin razonar. | |
| 742 | +function muestreoDelRegistro() { | |
| 743 | + const m = MODELS[clave]?.muestreo; | |
| 744 | + return m ? { ...m } : null; | |
| 745 | +} | |
| 746 | +function muestreoEfectivo() { return muestreo || muestreoDelRegistro(); } | |
| 747 | +const PRESUPUESTO_RAZONANDO = 4000; // si el registro no dice otro | |
| 748 | +function razonaEsteTurno() { | |
| 749 | + if (!pensante) return false; | |
| 750 | + const m = muestreoEfectivo(); | |
| 751 | + const pedido = m?.razonar; | |
| 752 | + if (pedido === false) return false; | |
| 753 | + if (m?.maxTokens && m.maxTokens < RAZONAR_MIN && pedido !== true) return false; | |
| 754 | + return pedido === true || !!MODELS[clave]?.razona; | |
| 755 | +} | |
| 756 | +// Tope de la respuesta. Sin razonar, lo de siempre: 512 como mucho. Razonando, | |
| 757 | +// el presupuesto del modelo (o el que pida quien llama): el razonamiento va | |
| 758 | +// DENTRO de esa cuenta, y con 512 MiniCPM ni llegaba a emitir la herramienta. | |
| 759 | +function topeRespuesta(razona) { | |
| 760 | + const pedido = muestreoEfectivo()?.maxTokens || 0; | |
| 761 | + if (razona) return pedido || MODELS[clave]?.presupuesto || PRESUPUESTO_RAZONANDO; | |
| 762 | + // Sin razonar: 512, o el `tope` que declare el modelo (el 27B escribe ficheros | |
| 763 | + // enteros en una respuesta, y 512 los cortaba). | |
| 764 | + const techo = MODELS[clave]?.tope || 512; | |
| 765 | + return Math.min(techo, pedido || techo); | |
| 766 | +} | |
| 767 | + | |
| 768 | +// El bloque de sistema, aparte y con nombre: la ranura 'sistema' de la | |
| 769 | +// instantánea necesita saber cuántas fichas ocupa EXACTAMENTE, y escribir el | |
| 770 | +// formato dos veces sería garantizar que algún día divergen y la foto describe | |
| 771 | +// un punto que no es. | |
| 772 | +function bloqueSistema(system) { return `<|im_start|>system\n${system}<|im_end|>\n`; } | |
| 773 | + | |
| 774 | +function montarPrompt(system, mensajes, { conPensar = true } = {}) { | |
| 775 | + let s = bloqueSistema(system); | |
| 776 | + for (const m of mensajes) { | |
| 777 | + const rol = m.role === 'assistant' ? 'assistant' : 'user'; | |
| 778 | + s += `<|im_start|>${rol}\n${m.content}<|im_end|>\n`; | |
| 779 | + } | |
| 780 | + s += '<|im_start|>assistant\n'; | |
| 781 | + | |
| 782 | + // El bloque de razonamiento lo abre LA PLANTILLA, no el modelo. La del GGUF | |
| 783 | + // termina en «<|im_start|>assistant\n» + «<think>\n» (razonando) o | |
| 784 | + // «<think>\n\n</think>\n\n» (sin razonar). Parar en «assistant\n» deja al | |
| 785 | + // modelo en un estado que NO vio en entrenamiento, y este contestaba con la | |
| 786 | + // parada en el primer token: respuesta vacía, sin error, sin traza. Costó | |
| 787 | + // encontrarlo porque parecía cosa de la cuantización. | |
| 788 | + // | |
| 789 | + // Se manda el bloque CERRADO —sin razonar— a propósito. Razonando escribiría | |
| 790 | + // cientos de tokens antes de la primera palabra útil, y con este modelo cada | |
| 791 | + // token se paga caro; además el cierre suelto que emitiría hay que recortarlo | |
| 792 | + // después. Cerrado, va directo a la respuesta. | |
| 793 | + if (conPensar && pensante) s += PENSAR; | |
| 794 | + return s; | |
| 795 | +} | |
| 796 | + | |
| 797 | +// Cuántos tokens de contexto tiene el modelo elegido. La app lo consulta ANTES | |
| 798 | +// de escribir el prompt para decidir qué le cabe decir: sin esto le mandaba las | |
| 799 | +// instrucciones enteras al 27B —512 de contexto— y el primer mensaje moría con | |
| 800 | +// la caché llena, después de descargar el modelo entero. | |
| 801 | +// Se puede preguntar sin haber cargado nada: es una propiedad del registro. | |
| 802 | +export function contextTokens() { | |
| 803 | + return MODELS[clave]?.ctx || 0; | |
| 804 | +} | |
| 805 | + | |
| 806 | +// ── MEDIDAS POR TURNO ─────────────────────────────────────────────────────── | |
| 807 | +// Hasta ahora el motor no medía NADA: las pruebas cronometraban desde fuera | |
| 808 | +// envolviendo la llamada, y la velocidad de generación había que deducirla | |
| 809 | +// aparte. Eso significa que la cifra que ve el usuario y la que mide una prueba | |
| 810 | +// no podían ser la misma, y que nadie sabía a qué iba su propio equipo. | |
| 811 | +// | |
| 812 | +// Las dos velocidades se cuentan SEPARADAS porque son fenómenos distintos: el | |
| 813 | +// prefill procesa N tokens de golpe y la generación uno a uno, así que mezclarlas | |
| 814 | +// da un número que no significa nada. Y el primer paso del bucle ES el prefill: | |
| 815 | +// `paso === 0` mete el prompt entero y los siguientes un token cada uno. | |
| 816 | +// | |
| 817 | +// `reusados` no es decoración: con la caché de prefijo funcionando, los tokens | |
| 818 | +// PROCESADOS son muchos menos que los del prompt, y sin ese dato el tok/s de | |
| 819 | +// prefill parece un milagro o una mentira según cómo se mire. | |
| 820 | +// | |
| 821 | +// La medida NACE cuando el turno coge el motor con un modelo cargado y se | |
| 822 | +// CIERRA en todas sus salidas, con `enCurso` a false: si acaba bien; si lo | |
| 823 | +// paran, con `abortado`; si falla, con el mensaje en `error`. Un turno parado | |
| 824 | +// en la cola no llegó a coger el motor y no tiene medida: `ultimaMedida()` | |
| 825 | +// sigue siendo la del turno de delante, que puede estar todavía en marcha. | |
| 826 | +const ahora = () => (typeof performance !== 'undefined' ? performance.now() : Date.now()); | |
| 827 | +let medida = null; | |
| 828 | +const oyentes = new Set(); | |
| 829 | +const avisar = (m = medida) => { for (const cb of oyentes) { try { cb(m); } catch { /* un oyente roto no tumba la generación */ } } }; | |
| 830 | + | |
| 831 | +/** La medida del último turno (o el turno en curso). Null si no ha habido ninguno. */ | |
| 832 | +export function ultimaMedida() { return medida; } | |
| 833 | + | |
| 834 | +/** | |
| 835 | + * Qué modelo está activo, para poder ETIQUETAR las medidas. | |
| 836 | + * | |
| 837 | + * Sin esto, una captura del velocímetro no se puede diagnosticar: llegó una con | |
| 838 | + * el prefill mucho mas lento de lo esperable y no habia forma de saber si era | |
| 839 | + * el modelo pequeño o el grande, que rinden en ordenes distintos. Una cifra de velocidad sin el modelo al | |
| 840 | + * lado no significa nada. | |
| 841 | + */ | |
| 842 | +/** | |
| 843 | + * El contexto con el que se ABRIO de verdad la sesion, que no tiene por que ser | |
| 844 | + * el del registro: si no cabe, la escalera baja a la mitad y vuelve a probar. | |
| 845 | + * | |
| 846 | + * Esto se exporta porque el contexto decide cuanta cache KV se reserva —en el | |
| 847 | + * modelo grande son gigas— y por tanto cuanta memoria del dispositivo queda para | |
| 848 | + * trabajar. Dos sesiones del MISMO modelo pueden caer en peldaños distintos | |
| 849 | + * segun la memoria libre de ese momento y rendir muy distinto, y hasta ahora | |
| 850 | + * eso solo se decia en la consola: desde fuera, dos velocidades incomparables | |
| 851 | + * parecian la misma medida. | |
| 852 | + */ | |
| 853 | +export function contextoEfectivo() { return ctxEfectivo; } | |
| 854 | + | |
| 855 | +export function modeloEtiqueta() { | |
| 856 | + const m = MODELS[clave]; | |
| 857 | + return m ? (m.label || clave) : clave; | |
| 858 | +} | |
| 859 | + | |
| 860 | +/** Suscribe a las medidas. Avisa al acabar el prefill, en cada token y al cerrar el turno, acabe como acabe. Devuelve el cancelador. */ | |
| 861 | +export function alMedir(cb) { oyentes.add(cb); return () => oyentes.delete(cb); } | |
| 862 | + | |
| 863 | +// ── TURNOS DE UNO EN UNO, Y PARAR ─────────────────────────────────────────── | |
| 864 | +// El motor tiene UN estado: la caché KV, el recurrente del SSM y las fotos del | |
| 865 | +// prefijo. Dos turnos a la vez lo pisarían el uno al otro sin dar un error — | |
| 866 | +// cada uno avanzando nPast sobre lo que escribió el otro—, así que `chat()` se | |
| 867 | +// pone a la cola detrás del turno anterior y solo empieza cuando ese suelta el | |
| 868 | +// motor. Dos llamadas a la vez dan lo mismo que dos seguidas. | |
| 869 | +// | |
| 870 | +// Parar es un AbortSignal, el mismo contrato que ya usan los otros proveedores | |
| 871 | +// de las apps: `opts.signal` en el cuarto argumento de `chat()`, o la señal | |
| 872 | +// suelta en esa misma posición. Un turno parado RECHAZA con un AbortError que | |
| 873 | +// lleva en `.partial` el texto limpio que llegó a emitir, y después de notarlo | |
| 874 | +// ya no llama a `onToken` ni a `onPrefill` ni una vez más. | |
| 875 | +// | |
| 876 | +// ⚠️ Y quien deja de esperar un turno tiene que PARARLO, con su señal o con | |
| 877 | +// `abort()`. Abandonar la promesa no suelta el motor: el turno sigue hasta el | |
| 878 | +// final y los siguientes se ponen a la cola detrás de él. Un plazo que le gana | |
| 879 | +// la carrera a `chat()` sin parar el turno no ahorra nada, lo convierte en un | |
| 880 | +// atasco: cada llamada siguiente gasta su propio plazo esperando en la cola. | |
| 881 | +// | |
| 882 | +// `ultimoTurno` se resuelve cuando el último turno encolado ha soltado el | |
| 883 | +// motor (o ha renunciado a cogerlo); nunca se rechaza. `turnosVivos` son los | |
| 884 | +// controladores de los turnos encolados o en marcha: es lo que corta `abort()`. | |
| 885 | +let ultimoTurno = Promise.resolve(); | |
| 886 | +const turnosVivos = new Set(); | |
| 887 | + | |
| 888 | +// POR QUÉ se paró. Quien llama tiene que poder distinguir su propio «para» del | |
| 889 | +// que no pidió: `unload()` —la app cuando va justa de memoria, el botón de liberar el modelo— | |
| 890 | +// y `configure()` a otro modelo también paran el turno en marcha, y enseñarle | |
| 891 | +// al usuario «parado a petición» cuando no ha pedido nada es mentirle. El | |
| 892 | +// motivo va en el texto del error y en `.porDescarga`, que es lo que se mira | |
| 893 | +// sin leer texto. Gana la PRIMERA causa: un turno ya parado no cambia de motivo. | |
| 894 | +const PARADO_POR = { | |
| 895 | + peticion: 'turno parado a petición', | |
| 896 | + descarga: 'turno parado: se ha descargado el modelo', | |
| 897 | +}; | |
| 898 | +const causaDe = new WeakMap(); // señal de un turno → por qué se paró | |
| 899 | +function parar(ctl, causa) { | |
| 900 | + if (ctl.signal.aborted) return; | |
| 901 | + causaDe.set(ctl.signal, causa); | |
| 902 | + ctl.abort(); | |
| 903 | +} | |
| 904 | +function errorDeParada(senal, partial) { | |
| 905 | + const causa = causaDe.get(senal) || 'peticion'; | |
| 906 | + const e = errorParado(PARADO_POR[causa]); | |
| 907 | + e.partial = partial; | |
| 908 | + e.porDescarga = causa === 'descarga'; | |
| 909 | + return e; | |
| 910 | +} | |
| 911 | + | |
| 912 | +// La señal, o algo que la lleve dentro (un AbortController). Se reconoce por la | |
| 913 | +// forma y no por la clase: una señal de otro reino —un iframe, un worker— no es | |
| 914 | +// `instanceof` del AbortSignal de esta página y aun así es una señal | |
| 915 | +// perfectamente válida. | |
| 916 | +function senalDe(x) { | |
| 917 | + if (!x || typeof x !== 'object') return null; | |
| 918 | + if (typeof x.aborted === 'boolean') return x; | |
| 919 | + if (x.signal && typeof x.signal.aborted === 'boolean') return x.signal; | |
| 920 | + return null; | |
| 921 | +} | |
| 922 | + | |
| 923 | +// Espera a que el turno de delante suelte el motor, salvo que paren a este | |
| 924 | +// antes: entonces rechaza en el acto, sin esperar a nadie. | |
| 925 | +function esperarTurno(antes, senal) { | |
| 926 | + return new Promise((si, no) => { | |
| 927 | + if (senal.aborted) { no(errorParado()); return; } | |
| 928 | + const fuera = () => no(errorParado()); | |
| 929 | + senal.addEventListener('abort', fuera, { once: true }); | |
| 930 | + antes.then(() => { senal.removeEventListener('abort', fuera); si(); }); | |
| 931 | + }); | |
| 932 | +} | |
| 933 | + | |
| 934 | +/** | |
| 935 | + * Para el turno en marcha y los que esperan en la cola. Resuelve cuando el | |
| 936 | + * motor está en reposo: ningún turno de los que había lo está usando, el | |
| 937 | + * dispositivo ha terminado lo que tenía y el estado es coherente para el siguiente turno. | |
| 938 | + */ | |
| 939 | +export async function abort() { | |
| 940 | + await pararTodos('peticion'); | |
| 941 | +} | |
| 942 | + | |
| 943 | +// Lo de `abort()`, con el motivo dicho: `descargar()` para por 'descarga'. | |
| 944 | +async function pararTodos(causa) { | |
| 945 | + const hasta = ultimoTurno; | |
| 946 | + for (const c of turnosVivos) { try { parar(c, causa); } catch { /* — */ } } | |
| 947 | + await hasta; | |
| 948 | +} | |
| 949 | + | |
| 950 | +/** | |
| 951 | + * Un turno. `onToken` recibe cada ficha generada. | |
| 952 | + * | |
| 953 | + * `opts.onPrefill(hechos, total)` avisa del avance del PREFILL, que es la | |
| 954 | + * espera larga y hasta ahora invisible: con un prompt de arnés en el modelo | |
| 955 | + * grande es la espera más larga del turno y la pantalla no decía nada en todo | |
| 956 | + * ese rato, y una espera sin señal se lee como «se ha colgado». Se llama por | |
| 957 | + * lote terminado en el dispositivo, no por lote encolado. | |
| 958 | + * | |
| 959 | + * `opts.signal` para el turno: ver «TURNOS DE UNO EN UNO, Y PARAR». | |
| 960 | + * | |
| 961 | + * ⚠️ El cuarto argumento acepta TAMBIÉN un AbortSignal suelto, o un | |
| 962 | + * AbortController: Elffuss Code lleva pasando la señal en esa posición desde | |
| 963 | + * antes de que existiera este objeto de opciones, y el motor la ignoraba en | |
| 964 | + * silencio. Romper esa llamada para estrenar un parámetro sería cambiar el | |
| 965 | + * contrato por comodidad mía. | |
| 966 | + */ | |
| 967 | +export async function chat(history, system, onToken = () => {}, opts = {}) { | |
| 968 | + const o = opts && typeof opts.aborted === 'boolean' ? { signal: opts } : (opts || {}); | |
| 969 | + const onPrefill = typeof o.onPrefill === 'function' ? o.onPrefill : null; | |
| 970 | + const tLlamada = ahora(); | |
| 971 | + const externa = senalDe(o.signal); | |
| 972 | + const ctl = new AbortController(); | |
| 973 | + const reenviar = () => parar(ctl, 'peticion'); | |
| 974 | + if (externa?.aborted) parar(ctl, 'peticion'); | |
| 975 | + else externa?.addEventListener?.('abort', reenviar, { once: true }); | |
| 976 | + turnosVivos.add(ctl); | |
| 977 | + const antes = ultimoTurno; | |
| 978 | + let soltar; | |
| 979 | + ultimoTurno = new Promise((r) => { soltar = r; }); | |
| 980 | + try { | |
| 981 | + try { | |
| 982 | + await esperarTurno(antes, ctl.signal); | |
| 983 | + } catch { | |
| 984 | + // Parado mientras esperaba: no llegó a tocar el motor. Su hueco se suelta | |
| 985 | + // cuando lo suelte el de delante; soltarlo ya dejaría colarse al de detrás | |
| 986 | + // mientras el de delante todavía está trabajando. | |
| 987 | + antes.then(soltar); | |
| 988 | + soltar = null; | |
| 989 | + const parado = errorDeParada(ctl.signal, ''); | |
| 990 | + console.log('[engine] turno PARADO en la cola: no llegó a empezar' + | |
| 991 | + (parado.porDescarga ? ' · por descarga' : '')); | |
| 992 | + throw parado; | |
| 993 | + } | |
| 994 | + return await turnoParable(history, system, onToken, { senal: ctl.signal, onPrefill, tLlamada }); | |
| 995 | + } finally { | |
| 996 | + turnosVivos.delete(ctl); | |
| 997 | + externa?.removeEventListener?.('abort', reenviar); | |
| 998 | + soltar?.(); | |
| 999 | + } | |
| 1000 | +} | |
| 1001 | + | |
| 1002 | +// El turno con el motor ya para él solo. Si lo paran, deja todo listo para el | |
| 1003 | +// siguiente ANTES de soltar el motor: el dispositivo en reposo, lo prestado devuelto al | |
| 1004 | +// pozo y la medida cerrada como parada. El estado no hace falta tocarlo: todo | |
| 1005 | +// turno empieza con `restaura()` o con `reset()`, las fotos que el turno va a | |
| 1006 | +// pisar se invalidan antes de su primer forward, y cada foto se vuelve a apuntar | |
| 1007 | +// solo con lo suyo ingerido entero (ver «LO QUE EL TURNO VA A PISAR»). Así un | |
| 1008 | +// turno parado a medias nunca deja una foto que describa algo que no pasó. | |
| 1009 | +async function turnoParable(history, system, onToken, opciones) { | |
| 1010 | + const { senal } = opciones; | |
| 1011 | + // `cerrar` lo pone `turno()` en cuanto nace la medida: es lo que la cierra | |
| 1012 | + // desde aquí cuando el turno sale por un error. | |
| 1013 | + const hecho = { fase: 'entrada', texto: '', prompt: 0, salida: null, cerrar: null }; | |
| 1014 | + try { | |
| 1015 | + return await turno(history, system, onToken, opciones, hecho); | |
| 1016 | + } catch (e) { | |
| 1017 | + // Solo es «parado» si lo pidieron Y el error es el de parar. Un fallo de | |
| 1018 | + // verdad que coincida con un «para» se enseña como el fallo que es. | |
| 1019 | + if (!(senal.aborted && e?.name === 'AbortError')) { | |
| 1020 | + // Un fallo también cierra la medida, con el fallo dentro: si no, se | |
| 1021 | + // quedaría «en curso» para siempre, esperando tokens de un turno que ya | |
| 1022 | + // no existe. | |
| 1023 | + hecho.cerrar?.({ error: String(e?.message || e) }); | |
| 1024 | + throw e; | |
| 1025 | + } | |
| 1026 | + try { await gpu?.device?.queue?.onSubmittedWorkDone?.(); } catch { /* sin dispositivo, nada que esperar */ } | |
| 1027 | + try { sesion?.recycle(); } catch { /* mejor esfuerzo */ } | |
| 1028 | + hecho.cerrar?.({ abortado: true }); | |
| 1029 | + const parado = errorDeParada(senal, limpiarRazonamiento(hecho.texto)); | |
| 1030 | + console.log(`[engine] turno PARADO en ${hecho.fase} · prompt ${hecho.prompt} tokens · ` + | |
| 1031 | + `nPast ${sesion?.state?.nPast ?? '-'} · salieron ${hecho.salida ? hecho.salida.length : 0} tokens · ` + | |
| 1032 | + `devuelto ${parado.partial.length} car.` + (parado.porDescarga ? ' · por descarga' : '')); | |
| 1033 | + throw parado; | |
| 1034 | + } | |
| 1035 | +} | |
| 1036 | + | |
| 1037 | +async function turno(history, system, onToken, { senal, onPrefill, tLlamada }, hecho) { | |
| 1038 | + // Un turno parado antes de empezar no toca nada: ni el estado ni la foto. | |
| 1039 | + if (senal.aborted) throw errorParado(); | |
| 1040 | + // Uno que llegó con una descarga en marcha la espera: cuando le toque, el | |
| 1041 | + // modelo ya no estará y lo dirá con el error de siempre. Se espera DESPUÉS de | |
| 1042 | + // mirar la señal y no antes: la descarga para a todos los turnos que había | |
| 1043 | + // antes que ella y espera a que suelten el motor, así que uno de esos | |
| 1044 | + // esperándola a ella se quedaría colgado para siempre. | |
| 1045 | + if (descargando) { | |
| 1046 | + await descargando; | |
| 1047 | + if (senal.aborted) throw errorParado(); | |
| 1048 | + } | |
| 1049 | + hecho.fase = 'preparación'; | |
| 1050 | + // Antes que nada: si el dispositivo se perdió, decirlo con esas palabras. Si no, el | |
| 1051 | + // usuario ve «El modelo todavía no está cargado» después de haber esperado a | |
| 1052 | + // que cargara, que es la peor manera de contar lo que ha pasado. | |
| 1053 | + if (perdida) throw new Error(perdida + ' Vuelve a elegirlo en el selector para cargarlo otra vez.'); | |
| 1054 | + if (!sesion) throw new Error('El modelo todavía no está cargado.'); | |
| 1055 | + | |
| 1056 | + // ── LA MEDIDA NACE AQUÍ, con el turno ya en el motor ─────────────────────── | |
| 1057 | + // Antes nacía con la cabeza ya ingerida, y eso tenía dos agujeros: un turno | |
| 1058 | + // parado en la preparación o en el prefill no llegaba a tenerla, así que | |
| 1059 | + // `ultimaMedida()` seguía dando la del turno ANTERIOR como si fuera la suya y | |
| 1060 | + // nadie recibía aviso; y uno que fallaba a media respuesta se quedaba «en | |
| 1061 | + // curso» para siempre. Ahora se cierra en todas las salidas: al final de esta | |
| 1062 | + // función si acaba bien, y en `turnoParable` si lo paran o falla. Los campos | |
| 1063 | + // que aún no se saben salen a cero y se rellenan según se conocen. | |
| 1064 | + const m = medida = { | |
| 1065 | + promptTokens: 0, procesados: 0, reusados: 0, | |
| 1066 | + prefillMs: 0, prefillTokS: 0, | |
| 1067 | + genTokens: 0, genMs: 0, genTokS: 0, | |
| 1068 | + ttftMs: 0, totalMs: 0, enCurso: true, abortado: false, error: null, | |
| 1069 | + }; | |
| 1070 | + let msForward = 0, msReadback = 0, msSample = 0, msDecode = 0; | |
| 1071 | + hecho.cerrar = ({ abortado = false, error = null } = {}) => { | |
| 1072 | + if (!m.enCurso) return; | |
| 1073 | + // El reparto del bucle, para que «va lento» tenga una causa y no cuatro | |
| 1074 | + // candidatas indistinguibles. Son acumulados de TODO el turno, prefill | |
| 1075 | + // incluido: el primer `forward` es el prompt entero. | |
| 1076 | + m.reparto = { forwardMs: msForward, readbackMs: msReadback, sampleMs: msSample, decodeMs: msDecode }; | |
| 1077 | + m.totalMs = ahora() - tLlamada; | |
| 1078 | + m.enCurso = false; | |
| 1079 | + m.abortado = abortado; | |
| 1080 | + m.error = error; | |
| 1081 | + avisar(m); | |
| 1082 | + }; | |
| 1083 | + | |
| 1084 | + const ctxLen = sesion.state.ctxLen; | |
| 1085 | + // Sitio reservado para contestar. Un prompt que ocupa el contexto ENTERO | |
| 1086 | + // «cabe» y luego revienta a mitad de la generación, con la respuesta ya | |
| 1087 | + // escrita a medias y perdida: más vale no empezar. | |
| 1088 | + // Razonando, la reserva es el presupuesto entero: si no, una conversación | |
| 1089 | + // larga dejaba 96 fichas para pensar Y responder. | |
| 1090 | + const razona = razonaEsteTurno(); | |
| 1091 | + const topeModo = topeRespuesta(razona); | |
| 1092 | + const RESERVA = razona ? topeModo : 96; | |
| 1093 | + | |
| 1094 | + // El presupuesto de la historia sale del contexto REAL menos lo que ya ocupa | |
| 1095 | + // el sistema. Antes era un 4.000 fijo: en un modelo de 512 eso es pedirle al | |
| 1096 | + // gestor del historial que llene ocho veces lo que hay. | |
| 1097 | + const sistema = tk.encode(montarPrompt(system, [])).length; | |
| 1098 | + if (sistema + RESERVA > ctxLen) { | |
| 1099 | + throw new Error(`las instrucciones ocupan ${sistema} tokens y este modelo solo tiene ` + | |
| 1100 | + `${ctxLen} de contexto: elige un modelo con más contexto para trabajar con herramientas.`); | |
| 1101 | + } | |
| 1102 | + const mensajes = await ajustaHistorial(history, ctxLen - sistema - RESERVA); | |
| 1103 | + if (senal.aborted) throw errorParado(); | |
| 1104 | + // El prompt se arma en DOS PIEZAS. `cabeza` es todo hasta el punto donde se | |
| 1105 | + // fotografía el estado; `cola` es lo que se alimenta después y queda FUERA de | |
| 1106 | + // la foto. Con modelo pensante la cola es el bloque `<think>`; sin él, el | |
| 1107 | + // último token, para que siempre quede algo con lo que sacar los logits. | |
| 1108 | + // | |
| 1109 | + // Se puede partir así porque está comprobado que el tokenizador NO fusiona en | |
| 1110 | + // la juntura: encode(cabeza + cola) === encode(cabeza) + encode(cola), 9 de 9 | |
| 1111 | + // casos en los dos modelos. Si fusionara, el punto de corte no valdría. | |
| 1112 | + const pensar = pensante ? tk.encode(razona ? ABRIR : PENSAR) : []; | |
| 1113 | + const armar = () => { | |
| 1114 | + const base = tk.encode(montarPrompt(system, mensajes, { conPensar: false })); | |
| 1115 | + return pensar.length | |
| 1116 | + ? { cabeza: base, cola: pensar } | |
| 1117 | + : { cabeza: base.slice(0, -1), cola: base.slice(-1) }; | |
| 1118 | + }; | |
| 1119 | + let { cabeza, cola } = armar(); | |
| 1120 | + let ids = cabeza.concat(cola); | |
| 1121 | + // El gestor del historial cuenta en tokens ESTIMADOS (~4 chars/token) y este | |
| 1122 | + // tokenizador es el de verdad, así que puede pasarse. Se tiran turnos viejos | |
| 1123 | + // hasta que quepa, nunca el último: ese es lo que acaba de escribir el usuario. | |
| 1124 | + while (ids.length + RESERVA > ctxLen && mensajes.length > 1) { | |
| 1125 | + mensajes.shift(); | |
| 1126 | + ({ cabeza, cola } = armar()); | |
| 1127 | + ids = cabeza.concat(cola); | |
| 1128 | + } | |
| 1129 | + if (ids.length + RESERVA > ctxLen) { | |
| 1130 | + throw new Error(`tu mensaje ocupa más de lo que cabe en este modelo ` + | |
| 1131 | + `(${ids.length} tokens sobre ${ctxLen}): prueba con uno más corto.`); | |
| 1132 | + } | |
| 1133 | + hecho.prompt = ids.length; | |
| 1134 | + m.promptTokens = ids.length; | |
| 1135 | + | |
| 1136 | + // ── REUTILIZACIÓN DE PREFIJO ─────────────────────────────────────────────── | |
| 1137 | + // Antes esto era `sesion.state.reset()` a secas, y el comentario lo justificaba | |
| 1138 | + // diciendo que el `system` cambia en cada llamada porque lleva el contexto vivo | |
| 1139 | + // dentro. Es cierto EN GENERAL y no lo es para los modelos lentos: los que | |
| 1140 | + // declaran `prefiereCompacto` reciben un prompt sin contexto vivo, estable | |
| 1141 | + // entre turnos. Reiniciando siempre, el turno 5 vuelve a pagar entero lo que ya | |
| 1142 | + // calcularon los turnos 1 a 4, y lo que se repaga crece con cada turno. | |
| 1143 | + // | |
| 1144 | + // La condición para reutilizar es la más estricta posible: que los tokens de | |
| 1145 | + // este turno EMPIECEN EXACTAMENTE por los que el estado ya ingirió. Entonces | |
| 1146 | + // basta alimentar la cola. | |
| 1147 | + // | |
| 1148 | + // Se compara sobre TOKENS y no sobre texto a propósito. Los tokens de la | |
| 1149 | + // respuesta que están en el estado son los que SE MUESTREARON; al rearmar el | |
| 1150 | + // prompt, el texto del asistente se vuelve a codificar, y destokenizar y | |
| 1151 | + // volver a tokenizar NO es la identidad. Comparando texto, esa deriva no se ve | |
| 1152 | + // y contamina en silencio todos los turnos siguientes. | |
| 1153 | + // | |
| 1154 | + // Y ante CUALQUIER divergencia se reinicia ENTERO, nunca a medias: la caché KV | |
| 1155 | + // se podría truncar en una posición, pero el estado recurrente del SSM —48 de | |
| 1156 | + // nuestras 64 capas— no se puede rebobinar, porque es el resultado de haber | |
| 1157 | + // recorrido toda la secuencia. | |
| 1158 | + // ENCENDIDO POR DEFECTO. Estuvo en opt-in hasta que la prueba pasó en LOS DOS | |
| 1159 | + // modelos, 6 asertos de 6 en cada uno: texto idéntico con y sin reutilización, | |
| 1160 | + // reutiliza 2 de 2 turnos posibles, y tocar un mensaje viejo fuerza reinicio | |
| 1161 | + // completo. El 27B se validó aparte del 0.8B a propósito, porque allí la | |
| 1162 | + // instantánea es unas ocho veces mayor (48 capas SSM, y más anchas). | |
| 1163 | + // | |
| 1164 | + // Se conserva la salida de emergencia —ponerlo a false— y no al revés: si esto | |
| 1165 | + // fallara no se vería como un error, se vería como una respuesta que habla de | |
| 1166 | + // otra conversación, y entonces hace falta poder apagarlo sin desplegar. | |
| 1167 | + const quiereReuso = globalThis.__ELFFUSS_PREFIJO !== false; | |
| 1168 | + // El motivo se calcula ANTES de tocar nada: cuando esto no reutilice hay que | |
| 1169 | + // poder saber POR QUÉ sin adivinar. «No reutiliza» tiene causas muy distintas | |
| 1170 | + // —primer turno, la historia se reordenó, el texto del asistente retokenizó | |
| 1171 | + // distinto, el prompt encogió— y desde fuera se ven todas iguales. La primera | |
| 1172 | + // versión no lo decía y el diagnóstico costó decodificar tokens a mano. | |
| 1173 | + // | |
| 1174 | + // La comparación es contra la CABEZA, que es lo que la instantánea describe. | |
| 1175 | + let motivo = 'primer turno'; | |
| 1176 | + if (consumidos) { | |
| 1177 | + if (cabeza.length <= consumidos.length) motivo = `el prompt no crece (${cabeza.length} <= ${consumidos.length})`; | |
| 1178 | + else { | |
| 1179 | + const i = consumidos.findIndex((t, k) => t !== cabeza[k]); | |
| 1180 | + motivo = i === -1 ? 'ok' : `diverge en el token ${i} de ${consumidos.length}`; | |
| 1181 | + } | |
| 1182 | + } | |
| 1183 | + // ── DOS NIVELES DE RESCATE, no uno ──────────────────────────────────────── | |
| 1184 | + // El nivel 1 es el de siempre: el prompt anterior completo es prefijo | |
| 1185 | + // estricto del nuevo, se restaura su foto y no se reprocesa nada. Solo se | |
| 1186 | + // cumple si la conversación crece por el final y NADA de en medio cambia. | |
| 1187 | + // | |
| 1188 | + // En un arnés eso casi nunca pasa: el estado vivo (archivo abierto, árbol, | |
| 1189 | + // tareas) cambia a cada paso, así que el nivel 1 falla y antes eso significaba | |
| 1190 | + // reprocesar el prompt ENTERO, prompt de sistema incluido. Medido: con un | |
| 1191 | + // prompt realista el prefill del modelo grande es la espera mas larga del | |
| 1192 | + // producto, y un | |
| 1193 | + // turno con herramientas lo pagaba en cada paso. | |
| 1194 | + // | |
| 1195 | + // El nivel 2 rescata lo que no cambia: si el bloque de sistema es el mismo | |
| 1196 | + // que describe la ranura 'sistema', se vuelve ahí y se reprocesa solo la | |
| 1197 | + // conversación. En Claw son ~1.300 fichas que se dejan de pagar; en Code, | |
| 1198 | + // ~2.200. | |
| 1199 | + const fichasSistema = tk.encode(bloqueSistema(system)); | |
| 1200 | + // ⚠️ GUARDA, no suposición: que el bloque de sistema sea prefijo de fichas de | |
| 1201 | + // la cabeza no es gratis — el tokenizador podría fusionar en la juntura entre | |
| 1202 | + // el fin del bloque y el primer mensaje. Está comprobado para la juntura | |
| 1203 | + // cabeza/cola (9 de 9) pero NO para esta. Si no es prefijo exacto, el nivel 2 | |
| 1204 | + // se apaga en vez de restaurar un punto que no es el que se cree. | |
| 1205 | + const sistemaEsPrefijo = fichasSistema.length < cabeza.length && | |
| 1206 | + fichasSistema.every((t, k) => t === cabeza[k]); | |
| 1207 | + const mismoSistema = !!sistemaFoto && sistemaFoto.length === fichasSistema.length && | |
| 1208 | + sistemaFoto.every((t, k) => t === fichasSistema[k]); | |
| 1209 | + | |
| 1210 | + let reusa = quiereReuso && motivo === 'ok' && sesion.state.tieneInstantanea('turno'); | |
| 1211 | + if (reusa && !sesion.state.restaura('turno')) reusa = false; // no se pudo: al camino seguro | |
| 1212 | + let yaIngeridos = reusa ? consumidos : null; | |
| 1213 | + let nivel = reusa ? 'turno' : null; | |
| 1214 | + | |
| 1215 | + if (!reusa && quiereReuso && sistemaEsPrefijo && mismoSistema && | |
| 1216 | + sesion.state.tieneInstantanea('sistema') && sesion.state.restaura('sistema')) { | |
| 1217 | + reusa = true; | |
| 1218 | + yaIngeridos = fichasSistema; | |
| 1219 | + nivel = 'sistema'; | |
| 1220 | + motivo += ' → rescatado por el prefijo del sistema'; | |
| 1221 | + } | |
| 1222 | + // ── LO QUE EL TURNO VA A PISAR DEJA DE VALER, Y ANTES DE PISARLO ───────── | |
| 1223 | + // Una foto guarda el estado recurrente en un punto, pero la caché KV de las | |
| 1224 | + // posiciones anteriores a ese punto vive FUERA de la foto: restaurarla da por | |
| 1225 | + // hecho que nadie las ha reescrito. Un turno que reprocesa desde antes de una | |
| 1226 | + // foto las reescribe, y si se para —o falla— a medias, esa foto sigue | |
| 1227 | + // pareciendo válida sobre una caché que ya es de otra conversación. | |
| 1228 | + // Restaurarla después no da ningún error: da texto plausible sacado de una | |
| 1229 | + // mezcla de las dos. | |
| 1230 | + // | |
| 1231 | + // Así que lo que el turno va a pisar se invalida AQUÍ, antes del primer | |
| 1232 | + // forward, y cada foto se vuelve a apuntar solo cuando lo suyo está ingerido | |
| 1233 | + // entero: la del sistema tras su bloque, la del turno tras la cabeza. | |
| 1234 | + // · reinicio: se reprocesa desde la posición 0, así que no sobrevive | |
| 1235 | + // ninguna foto; `reset()` ya invalida la del turno, y la del sistema se | |
| 1236 | + // invalida aquí y se vuelve a tomar en este mismo turno si se puede; | |
| 1237 | + // · nivel 'sistema': se reprocesa desde el fin del bloque de sistema, así | |
| 1238 | + // que la foto del TURNO, que es más larga, y `consumidos` dejan de valer; | |
| 1239 | + // · nivel 'turno': se escribe detrás de las dos fotos y no se pisa nada. | |
| 1240 | + if (!reusa) { | |
| 1241 | + consumidos = null; | |
| 1242 | + sesion.state.reset(); | |
| 1243 | + sistemaFoto = null; | |
| 1244 | + sesion.state.olvidaInstantanea('sistema'); | |
| 1245 | + } else if (nivel === 'sistema') { | |
| 1246 | + consumidos = null; | |
| 1247 | + sesion.state.olvidaInstantanea('turno'); | |
| 1248 | + } | |
| 1249 | + | |
| 1250 | + // ¿Hay que tomar la foto del sistema? Tras un reinicio no queda ninguna —se | |
| 1251 | + // acaba de invalidar—, así que se toma siempre que el bloque sea prefijo | |
| 1252 | + // exacto de lo que se va a procesar ahora. | |
| 1253 | + const tomarFotoSistema = quiereReuso && sistemaEsPrefijo && !reusa; | |
| 1254 | + const entradaCabeza = reusa ? cabeza.slice(yaIngeridos.length) : cabeza; | |
| 1255 | + // Lo PROCESADO de verdad son las dos fases: la cabeza que no se reutilizó más | |
| 1256 | + // la cola. Con la caché de prefijo funcionando esto es mucho menor que | |
| 1257 | + // `promptTokens`, y por eso se informan los dos: sin `reusados`, un prefill | |
| 1258 | + // que va «diez veces más rápido» parece un milagro o un error de medida. | |
| 1259 | + const procesados = entradaCabeza.length + cola.length; | |
| 1260 | + m.procesados = procesados; | |
| 1261 | + m.reusados = yaIngeridos ? yaIngeridos.length : 0; | |
| 1262 | + if (quiereReuso) { | |
| 1263 | + // El NIVEL va en la traza, y no es decoración: «reutilizados 24» puede ser | |
| 1264 | + // el prefijo completo de una conversación corta o el rescate del bloque de | |
| 1265 | + // sistema de una larga, y son dos cosas distintas que hay que poder | |
| 1266 | + // distinguir sin decodificar fichas a mano. Es la misma razón por la que el | |
| 1267 | + // motivo se calcula antes de tocar nada. | |
| 1268 | + console.log('[engine] prefijo: ' + (reusa | |
| 1269 | + ? `REUTILIZADOS ${yaIngeridos.length} tokens (nivel ${nivel}) · solo se procesan ${entradaCabeza.length + cola.length}` | |
| 1270 | + : `reinicio completo · ${ids.length} tokens · ${motivo}`)); | |
| 1271 | + } | |
| 1272 | + | |
| 1273 | + const paradas = new Set([tk.eosId]); | |
| 1274 | + const imEnd = tk.encode('<|im_end|>'); | |
| 1275 | + if (imEnd.length === 1) paradas.add(imEnd[0]); | |
| 1276 | + | |
| 1277 | + const vocab = tk.vocabSize; | |
| 1278 | + const salida = []; | |
| 1279 | + hecho.salida = salida; | |
| 1280 | + let texto = ''; | |
| 1281 | + // El reloj del prefill arranca AQUÍ, antes de la fase 1, y no en el bucle. | |
| 1282 | + // | |
| 1283 | + // Esto estaba mal y lo cazó una prueba interna: el prompt se parte en | |
| 1284 | + // CABEZA (lo que entra en la instantánea, la inmensa mayoría) y COLA, y la | |
| 1285 | + // cabeza se procesa aquí, fuera del bucle. Midiendo solo desde el bucle, un | |
| 1286 | + // prompt de ~780 tokens declaraba «4 tokens procesados», y la velocidad que | |
| 1287 | + // salía de ahí no significaba nada: el tiempo real de los otros ~776 se | |
| 1288 | + // escondía en el hueco entre la llamada y el bucle. Se veía porque el tiempo | |
| 1289 | + // hasta la primera letra era decenas de veces el «prefill». | |
| 1290 | + const tPrefillIni = ahora(); | |
| 1291 | + // ── FASE 1: alimentar hasta el punto de la foto ──────────────────────────── | |
| 1292 | + // Con la señal dentro, y en los DOS tramos cuando se parte para fotografiar el | |
| 1293 | + // sistema: un prompt largo son muchos lotes y muchas capas, y parar tiene que | |
| 1294 | + // poder entrar entre ellos en vez de esperar al final. | |
| 1295 | + hecho.fase = 'prefill'; | |
| 1296 | + if (entradaCabeza.length) { | |
| 1297 | + // El progreso, solo si alguien lo escucha; `desde` es lo ya hecho en un | |
| 1298 | + // tramo anterior, porque se reporta sobre el TOTAL de la cabeza. Y nada | |
| 1299 | + // de progreso con la señal ya dada: `forward` avisa de cada lote | |
| 1300 | + // terminado, también del que acaba justo cuando llega el «para» y del | |
| 1301 | + // último, que no mira la señal; pero el contrato de `chat()` es que tras | |
| 1302 | + // notar el «para» no se llama más a `onPrefill`, así que se filtra aquí. | |
| 1303 | + const opciones = (desde, total) => (onPrefill | |
| 1304 | + ? { signal: senal, onProgress: (h) => { if (!senal.aborted) onPrefill(desde + h, total); } } | |
| 1305 | + : { signal: senal }); | |
| 1306 | + if (tomarFotoSistema) { | |
| 1307 | + // Se parte el forward de la cabeza para poder fotografiar EXACTAMENTE | |
| 1308 | + // después del bloque de sistema. Partirlo no cambia la numérica: el | |
| 1309 | + // estado avanza igual token a token (lo vigila una prueba interna que | |
| 1310 | + // compara troceado contra una sola pasada). | |
| 1311 | + const n = fichasSistema.length; | |
| 1312 | + // El progreso se reporta sobre el TOTAL de la cabeza, no sobre cada | |
| 1313 | + // tramo: al usuario le da igual que por dentro se parta para fotografiar. | |
| 1314 | + const total = entradaCabeza.length; | |
| 1315 | + await sesion.forward(entradaCabeza.slice(0, n), opciones(0, total)); | |
| 1316 | + sesion.recycle(); | |
| 1317 | + sesion.state.instantanea('sistema'); | |
| 1318 | + sistemaFoto = fichasSistema; | |
| 1319 | + if (entradaCabeza.length > n) { | |
| 1320 | + await sesion.forward(entradaCabeza.slice(n), opciones(n, total)); | |
| 1321 | + sesion.recycle(); | |
| 1322 | + } | |
| 1323 | + } else { | |
| 1324 | + await sesion.forward(entradaCabeza, opciones(0, entradaCabeza.length)); | |
| 1325 | + sesion.recycle(); | |
| 1326 | + } | |
| 1327 | + } | |
| 1328 | + // La foto se toma AQUÍ, antes del bloque `<think>`. Lo que describe —la | |
| 1329 | + // cabeza— SÍ es prefijo exacto del prompt del turno siguiente, y eso es lo | |
| 1330 | + // que hacía imposible la reutilización mientras el bloque estaba dentro. | |
| 1331 | + // | |
| 1332 | + // Se apunta ahora y no al final del turno a propósito: si la generación | |
| 1333 | + // revienta a media respuesta, la instantánea sigue describiendo un punto | |
| 1334 | + // anterior y VÁLIDO, así que el turno siguiente puede reutilizar igual. Antes | |
| 1335 | + // había que invalidar por si acaso. | |
| 1336 | + sesion.state.instantanea('turno'); | |
| 1337 | + consumidos = cabeza; | |
| 1338 | + // Se mira DESPUÉS de la foto y de `consumidos`, no antes: la cabeza ya está | |
| 1339 | + // ingerida entera, y apuntarlo deja que el turno siguiente la reutilice | |
| 1340 | + // aunque este se pare aquí mismo. | |
| 1341 | + if (senal.aborted) throw errorParado(); | |
| 1342 | + hecho.fase = 'generación'; | |
| 1343 | + | |
| 1344 | + // ── FASE 2: la cola, que entra en el estado pero NO en la foto ───────────── | |
| 1345 | + let entrada = cola; | |
| 1346 | + | |
| 1347 | + // `maxTokens` por muestreo: el jurado de rlm.js y los tests necesitan acotar | |
| 1348 | + // la respuesta, y con un modelo lento la diferencia entre 8 y 512 tokens es la | |
| 1349 | + // diferencia entre una prueba que se corre y una que no. | |
| 1350 | + // | |
| 1351 | + // El tope de verdad, además, es lo que QUEDA de contexto: con 512 de contexto | |
| 1352 | + // y 512 de tope, una respuesta larga se llevaba por delante la caché a mitad | |
| 1353 | + // de escribirla y el turno entero se perdía como error. | |
| 1354 | + const tope = Math.max(1, Math.min(topeModo, ctxLen - ids.length)); | |
| 1355 | + // Traza de cada turno. No es depuración de usar y tirar: cuando este modelo | |
| 1356 | + // se queda mudo —y se queda— lo ÚNICO que distingue «no le cabía», «le | |
| 1357 | + // pusieron un tope de 0» y «decidió callarse» son estos tres números, y sin | |
| 1358 | + // ellos hay que adivinar. Cuesta una línea de consola por respuesta. | |
| 1359 | + console.log(`[engine] turno: prompt ${ids.length} tokens · contexto ${ctxLen} · ` + | |
| 1360 | + `tope ${tope}${razona ? ' (razonando)' : ''} · muestreo ${muestreo ? JSON.stringify(muestreo) : muestreoDelRegistro() ? 'del registro ' + JSON.stringify(muestreoDelRegistro()) : 'voraz (por defecto)'}`); | |
| 1361 | + // `tLlamada` guarda la entrada a `chat()` para poder dar el tiempo hasta la | |
| 1362 | + // primera letra TAL COMO LO ESPERA UN HUMANO, que incluye la tokenización y el | |
| 1363 | + // montaje del prompt. | |
| 1364 | + let tPrefill = 0; | |
| 1365 | + // ── DÓNDE SE VA EL TIEMPO DE CADA TOKEN ──────────────────────────────────── | |
| 1366 | + // La generación medida de punta a punta salió MUY por debajo de lo que da el | |
| 1367 | + // kernel aislado para el mismo modelo, y el bucle tiene tres sospechosos que | |
| 1368 | + // la medida del kernel suelto no paga nunca: | |
| 1369 | + // | |
| 1370 | + // · el readback trae el vocabulario ENTERO de vuelta a CPU en cada token; | |
| 1371 | + // · `sample` recorre todos esos logits, y con penalización de repetición | |
| 1372 | + // además recorre todo lo emitido hasta ahora; | |
| 1373 | + // · `tk.decode(salida)` redecodifica la secuencia COMPLETA en cada token, | |
| 1374 | + // que es cuadrático en la longitud de la respuesta. | |
| 1375 | + // | |
| 1376 | + // Sin repartirlo, «la generación va lenta» tiene cuatro causas que se ven | |
| 1377 | + // idénticas desde fuera. Cuesta tres relojes por token. Los acumuladores | |
| 1378 | + // nacen con la medida, arriba, para que un turno parado también los cierre. | |
| 1379 | + for (let paso = 0; paso < tope; paso++) { | |
| 1380 | + // Parar se mira en DOS sitios por paso: aquí, antes de encolar trabajo, y | |
| 1381 | + // tras leer los logits, antes de emitir. El segundo es el que garantiza que | |
| 1382 | + // después de notar el «para» no sale ni un token más: la lectura es la | |
| 1383 | + // espera larga del paso, y es justo ahí donde suele llegar. | |
| 1384 | + if (senal.aborted) throw errorParado(); | |
| 1385 | + const tF = ahora(); | |
| 1386 | + const { logits, logitsTokens } = await sesion.forward(entrada, { signal: senal }); | |
| 1387 | + // El forward solo devuelve logits del ÚLTIMO token: antes calculaba los | |
| 1388 | + // 248.320 de CADA token del prompt —la cabeza entera, una vez por token— y | |
| 1389 | + // se descartaban todos menos los del último. | |
| 1390 | + const tR = ahora(); msForward += tR - tF; | |
| 1391 | + const todos = new Float32Array(await readback(gpu.device, logits, 0, logitsTokens * vocab * 4)); | |
| 1392 | + if (senal.aborted) throw errorParado(); | |
| 1393 | + const ultimo = todos.subarray((logitsTokens - 1) * vocab, logitsTokens * vocab); | |
| 1394 | + const tS = ahora(); msReadback += tS - tR; | |
| 1395 | + // Con los tokens ya emitidos, para que la penalización de repetición pueda | |
| 1396 | + // actuar. Sin ellos, el muestreador no sabe que se está repitiendo. | |
| 1397 | + // La semilla CAMBIA en cada token (como en generate()): con la misma en | |
| 1398 | + // todos, cada paso sacaba el mismo cuantil de su distribución y no había azar. | |
| 1399 | + const mu = muestreoEfectivo() || { temperature: 0 }; // (`m` es la medida del turno) | |
| 1400 | + const id = sample(ultimo, { ...mu, seed: (mu.seed || 1) + paso, | |
| 1401 | + previos: ids.concat(salida) }); | |
| 1402 | + msSample += ahora() - tS; | |
| 1403 | + sesion.recycle(); | |
| 1404 | + | |
| 1405 | + // Frontera prefill/generación: el primer paso ha metido `procesados` tokens | |
| 1406 | + // de golpe y ya hay logits leídos, así que aquí acaba el prefill. Se marca | |
| 1407 | + // DESPUÉS del readback a propósito: medir antes daría un prefill | |
| 1408 | + // fantásticamente rápido y un primer token absurdamente lento, porque el | |
| 1409 | + // trabajo del dispositivo se habría contado en el token siguiente. | |
| 1410 | + if (paso === 0) { | |
| 1411 | + tPrefill = ahora(); | |
| 1412 | + m.prefillMs = tPrefill - tPrefillIni; | |
| 1413 | + m.prefillTokS = m.prefillMs > 0 ? procesados / (m.prefillMs / 1000) : 0; | |
| 1414 | + avisar(m); | |
| 1415 | + } | |
| 1416 | + | |
| 1417 | + if (paradas.has(id)) break; | |
| 1418 | + salida.push(id); | |
| 1419 | + // La generación se cuenta desde el FIN del prefill, no desde el principio: | |
| 1420 | + // si no, el primer token arrastra el prompt entero y los tok/s de | |
| 1421 | + // generación de una respuesta corta serían los del prefill disfrazados. | |
| 1422 | + m.genTokens = salida.length; | |
| 1423 | + m.genMs = ahora() - tPrefill; | |
| 1424 | + m.genTokS = m.genMs > 0 ? m.genTokens / (m.genMs / 1000) : 0; | |
| 1425 | + if (!m.ttftMs) m.ttftMs = ahora() - tLlamada; | |
| 1426 | + avisar(m); | |
| 1427 | + | |
| 1428 | + // Se decodifica la secuencia ENTERA y se emite la diferencia: un token puede | |
| 1429 | + // partir un carácter multibyte por la mitad, y decodificarlo suelto daría un | |
| 1430 | + // rombo de reemplazo en mitad de una palabra. | |
| 1431 | + const tD = ahora(); | |
| 1432 | + const nuevo = tk.decode(salida); | |
| 1433 | + if (nuevo.length > texto.length) { | |
| 1434 | + onToken(nuevo.slice(texto.length)); | |
| 1435 | + texto = nuevo; | |
| 1436 | + hecho.texto = texto; | |
| 1437 | + } | |
| 1438 | + msDecode += ahora() - tD; | |
| 1439 | + entrada = [id]; | |
| 1440 | + } | |
| 1441 | + | |
| 1442 | + // El razonamiento se transmite EN CRUDO por onToken —la burbuja de | |
| 1443 | + // pensamiento de Elffuss está hecha para leerse— pero se limpia del texto que | |
| 1444 | + // se devuelve: el agente busca ahí bloques ```tool y no debe ver las marcas. | |
| 1445 | + // Mismo tratamiento que providers/onnx.js, para no inventar otra convención. | |
| 1446 | + const limpio = razona ? limpiarRazonando(texto) : limpiarRazonamiento(texto); | |
| 1447 | + if (razona && !texto.includes('</think>')) { | |
| 1448 | + console.log(`[engine] razonamiento CORTADO por el tope (${tope} tokens) sin llegar a «</think>»: ` + | |
| 1449 | + 'la respuesta queda vacía, no se devuelve el razonamiento como si fuera la respuesta'); | |
| 1450 | + } | |
| 1451 | + // Cierra la traza del turno con lo que SALIÓ. Sin esto, «no aparece burbuja» | |
| 1452 | + // tiene dos causas que se ven idénticas desde fuera y llevan a sitios | |
| 1453 | + // opuestos: que el modelo no emitiera nada, o que emitiera algo que la capa de | |
| 1454 | + // arriba se comió —un bloque ```tool mal formado, por ejemplo, que el agente | |
| 1455 | + // consume sin pintar nada—. Distinguirlas es la diferencia entre culpar al | |
| 1456 | + // motor y culpar al agente, y nos ha costado una tarde entera no poder. | |
| 1457 | + console.log(`[engine] turno: salieron ${salida.length} tokens · ` + | |
| 1458 | + `crudo ${texto.length} car. · devuelto ${limpio.length} car.` + | |
| 1459 | + (texto ? ` · empieza por ${JSON.stringify(texto.slice(0, 80))}` : ' · NADA')); | |
| 1460 | + hecho.cerrar(); | |
| 1461 | + console.log(`[engine] velocidad: prefill ${m.procesados} tok en ` + | |
| 1462 | + `${m.prefillMs.toFixed(0)} ms (${m.prefillTokS.toFixed(1)} tok/s` + | |
| 1463 | + `${m.reusados ? `, ${m.reusados} reusados del prefijo` : ''}) · ` + | |
| 1464 | + `generación ${m.genTokens} tok a ${m.genTokS.toFixed(1)} tok/s · ` + | |
| 1465 | + `primera letra ${m.ttftMs.toFixed(0)} ms`); | |
| 1466 | + return limpio; | |
| 1467 | +} | |
| 1468 | + | |
| 1469 | +// Razonando, la apertura «<think>» va en el PROMPT: la salida trae el | |
| 1470 | +// razonamiento, el «</think>» y la respuesta. Lo que va después del último | |
| 1471 | +// cierre es la respuesta. Y si el tope cortó antes de cerrar, NO hay respuesta: | |
| 1472 | +// devolver el razonamiento a medias como respuesta haría que el agente buscase | |
| 1473 | +// herramientas en lo que el modelo solo estaba pensando. | |
| 1474 | +function limpiarRazonando(txt) { | |
| 1475 | + const i = txt.lastIndexOf('</think>'); | |
| 1476 | + if (i === -1) return ''; | |
| 1477 | + return txt.slice(i + 8).replace(/<\/?think>/g, '').trim(); | |
| 1478 | +} | |
| 1479 | + | |
| 1480 | +function limpiarRazonamiento(txt) { | |
| 1481 | + if (txt.includes('<think>')) { | |
| 1482 | + txt = txt.replace(/<think>[\s\S]*?<\/think>/g, ''); | |
| 1483 | + // Si el tope de tokens cortó el bloque a medias, nos quedamos con lo que | |
| 1484 | + // vino DESPUÉS de la última apertura: devolver un razonamiento sin cerrar | |
| 1485 | + // como si fuera la respuesta es peor que devolver poco. | |
| 1486 | + const i = txt.lastIndexOf('<think>'); | |
| 1487 | + if (i !== -1) txt = txt.slice(i + 7); | |
| 1488 | + } else if (txt.includes('</think>')) { | |
| 1489 | + // Cierre SUELTO, sin apertura. Pasa cuando la apertura va en el PROMPT —que | |
| 1490 | + // es como lo hace la plantilla de estos modelos— y el modelo solo emite el | |
| 1491 | + // cierre. La rama de arriba no lo veía y el razonamiento entero se colaba en | |
| 1492 | + // la respuesta, donde el agente busca bloques ```tool. | |
| 1493 | + txt = txt.slice(txt.lastIndexOf('</think>') + 8); | |
| 1494 | + } | |
| 1495 | + return txt.replace(/<\/?think>/g, '').trim(); | |
| 1496 | +} | |
| 1497 | + | |
| 1498 | +// Gancho de pruebas: el respaldo mixto (almacén + red) se verifica con una | |
| 1499 | +// prueba que necesita llamar a esto directamente. | |
| 1500 | +export { rangosRepartidos as __rangosRepartidos }; |
added js/quant-tables.js +620 −0
| @@ -0,0 +1,620 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 AND MIT | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · rejillas de los i-quants. Copiado de ggml/src/ggml-common.h; no editar a mano. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// Estas tablas son parte del FORMATO, no de un algoritmo: un bloque IQ1_S guarda | |
| 6 | +// indices de 11 bits a iq1s_grid y un IQ2_XXS indices de 8 bits a iq2xxs_grid. | |
| 7 | +// Sin la tabla, los bytes del GGUF no se pueden interpretar. Se copian de | |
| 8 | +// llama.cpp (ggml/src/ggml-common.h). Las TABLAS son de los autores de ggml y | |
| 9 | +// van bajo su licencia MIT, que se reproduce entera; el resto del fichero es | |
| 10 | +// Apache-2.0: | |
| 11 | +// | |
| 12 | +// MIT License | |
| 13 | +// | |
| 14 | +// Copyright (c) 2023-2026 The ggml authors | |
| 15 | +// | |
| 16 | +// Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 17 | +// of this software and associated documentation files (the "Software"), to deal | |
| 18 | +// in the Software without restriction, including without limitation the rights | |
| 19 | +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 20 | +// copies of the Software, and to permit persons to whom the Software is | |
| 21 | +// furnished to do so, subject to the following conditions: | |
| 22 | +// | |
| 23 | +// The above copyright notice and this permission notice shall be included in all | |
| 24 | +// copies or substantial portions of the Software. | |
| 25 | +// | |
| 26 | +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 27 | +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 28 | +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 29 | +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 30 | +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 31 | +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 32 | +// SOFTWARE. | |
| 33 | +// | |
| 34 | +// Cada u64 de ggml se guarda aqui como DOS u32 (lo, hi) para poder subirlo tal | |
| 35 | +// cual a un storage buffer: el byte j de la entrada e es el byte (j&3) de | |
| 36 | +// tbl[2e + (j>>2)], que es exactamente lo que lee el C al castear a uint8_t*. | |
| 37 | +// | |
| 38 | +// El resto del motor es codigo propio, Apache-2.0 (ver LICENSE). | |
| 39 | + | |
| 40 | +export const IQ2XXS_GRID = new Uint32Array([ | |
| 41 | + 0x08080808, 0x08080808, 0x0808082b, 0x08080808, 0x08081919, 0x08080808, 0x08082b08, 0x08080808, | |
| 42 | + 0x08082b2b, 0x08080808, 0x08190819, 0x08080808, 0x08191908, 0x08080808, 0x082b0808, 0x08080808, | |
| 43 | + 0x082b082b, 0x08080808, 0x082b2b08, 0x08080808, 0x082b2b2b, 0x08080808, 0x19080819, 0x08080808, | |
| 44 | + 0x19081908, 0x08080808, 0x19190808, 0x08080808, 0x19192b08, 0x08080808, 0x192b0819, 0x08080808, | |
| 45 | + 0x192b1908, 0x08080808, 0x2b080808, 0x08080808, 0x2b08082b, 0x08080808, 0x2b082b2b, 0x08080808, | |
| 46 | + 0x2b2b082b, 0x08080808, 0x08080819, 0x08080819, 0x08081908, 0x08080819, 0x08190808, 0x08080819, | |
| 47 | + 0x08191919, 0x08080819, 0x19080808, 0x08080819, 0x2b081908, 0x08080819, 0x2b192b08, 0x08080819, | |
| 48 | + 0x08080808, 0x0808082b, 0x0808082b, 0x0808082b, 0x082b082b, 0x0808082b, 0x2b08082b, 0x0808082b, | |
| 49 | + 0x08080819, 0x08081908, 0x08081908, 0x08081908, 0x08190808, 0x08081908, 0x082b0819, 0x08081908, | |
| 50 | + 0x082b1908, 0x08081908, 0x19080808, 0x08081908, 0x1908082b, 0x08081908, 0x19082b08, 0x08081908, | |
| 51 | + 0x192b0808, 0x08081908, 0x2b080819, 0x08081908, 0x2b081908, 0x08081908, 0x2b190808, 0x08081908, | |
| 52 | + 0x2b2b1908, 0x08081908, 0x08080808, 0x08081919, 0x0808082b, 0x08081919, 0x08082b08, 0x08081919, | |
| 53 | + 0x082b0808, 0x08081919, 0x1908192b, 0x08081919, 0x192b2b19, 0x08081919, 0x2b080808, 0x08081919, | |
| 54 | + 0x2b190819, 0x08081919, 0x08082b19, 0x0808192b, 0x08190808, 0x0808192b, 0x19080808, 0x0808192b, | |
| 55 | + 0x2b081908, 0x0808192b, 0x2b2b1908, 0x0808192b, 0x08080808, 0x08082b08, 0x08081919, 0x08082b08, | |
| 56 | + 0x08082b08, 0x08082b08, 0x08191908, 0x08082b08, 0x082b2b08, 0x08082b08, 0x19080819, 0x08082b08, | |
| 57 | + 0x19081908, 0x08082b08, 0x19190808, 0x08082b08, 0x1919082b, 0x08082b08, 0x2b082b08, 0x08082b08, | |
| 58 | + 0x08081908, 0x08082b19, 0x19080808, 0x08082b19, 0x0808082b, 0x08082b2b, 0x08191908, 0x08082b2b, | |
| 59 | + 0x08080819, 0x08190808, 0x08081908, 0x08190808, 0x08190808, 0x08190808, 0x082b0819, 0x08190808, | |
| 60 | + 0x19080808, 0x08190808, 0x192b0808, 0x08190808, 0x2b081908, 0x08190808, 0x2b190808, 0x08190808, | |
| 61 | + 0x2b191919, 0x08190808, 0x08080808, 0x08190819, 0x08082b08, 0x08190819, 0x082b0808, 0x08190819, | |
| 62 | + 0x19190808, 0x08190819, 0x19192b2b, 0x08190819, 0x2b080808, 0x08190819, 0x082b1908, 0x0819082b, | |
| 63 | + 0x19081919, 0x0819082b, 0x08080808, 0x08191908, 0x08082b08, 0x08191908, 0x082b0808, 0x08191908, | |
| 64 | + 0x082b1919, 0x08191908, 0x19082b19, 0x08191908, 0x2b080808, 0x08191908, 0x08192b08, 0x08191919, | |
| 65 | + 0x192b082b, 0x08191919, 0x08080808, 0x0819192b, 0x0819192b, 0x0819192b, 0x08080819, 0x08192b08, | |
| 66 | + 0x08081908, 0x08192b08, 0x08190808, 0x08192b08, 0x19080808, 0x08192b08, 0x2b080819, 0x08192b08, | |
| 67 | + 0x08080808, 0x08192b19, 0x08081919, 0x08192b19, 0x2b2b0808, 0x08192b19, 0x19190819, 0x08192b2b, | |
| 68 | + 0x08080808, 0x082b0808, 0x0808082b, 0x082b0808, 0x08082b2b, 0x082b0808, 0x19081908, 0x082b0808, | |
| 69 | + 0x192b0819, 0x082b0808, 0x2b080808, 0x082b0808, 0x2b08082b, 0x082b0808, 0x082b2b19, 0x082b0819, | |
| 70 | + 0x19082b08, 0x082b0819, 0x08080808, 0x082b082b, 0x0808082b, 0x082b082b, 0x08080819, 0x082b1908, | |
| 71 | + 0x08081908, 0x082b1908, 0x08190808, 0x082b1908, 0x19080808, 0x082b1908, 0x1919192b, 0x082b1908, | |
| 72 | + 0x08080808, 0x082b1919, 0x19080819, 0x082b1919, 0x192b1908, 0x082b1919, 0x2b190808, 0x082b192b, | |
| 73 | + 0x08082b08, 0x082b2b08, 0x082b0808, 0x082b2b08, 0x2b191908, 0x082b2b08, 0x19081908, 0x082b2b2b, | |
| 74 | + 0x08080819, 0x19080808, 0x08081908, 0x19080808, 0x08190808, 0x19080808, 0x08192b08, 0x19080808, | |
| 75 | + 0x082b0819, 0x19080808, 0x082b1908, 0x19080808, 0x19080808, 0x19080808, 0x19082b08, 0x19080808, | |
| 76 | + 0x1919192b, 0x19080808, 0x192b0808, 0x19080808, 0x2b080819, 0x19080808, 0x2b081908, 0x19080808, | |
| 77 | + 0x2b190808, 0x19080808, 0x08080808, 0x19080819, 0x082b0808, 0x19080819, 0x192b0819, 0x19080819, | |
| 78 | + 0x2b080808, 0x19080819, 0x2b081919, 0x19080819, 0x08080819, 0x1908082b, 0x08190808, 0x1908082b, | |
| 79 | + 0x19082b08, 0x1908082b, 0x1919192b, 0x1908082b, 0x192b2b08, 0x1908082b, 0x08080808, 0x19081908, | |
| 80 | + 0x08082b08, 0x19081908, 0x082b0808, 0x19081908, 0x2b080808, 0x19081908, 0x2b192b19, 0x19081908, | |
| 81 | + 0x0819082b, 0x19081919, 0x082b1908, 0x19081919, 0x08080808, 0x1908192b, 0x08080819, 0x19082b08, | |
| 82 | + 0x08081908, 0x19082b08, 0x08190808, 0x19082b08, 0x19080808, 0x19082b08, 0x19081919, 0x19082b08, | |
| 83 | + 0x08080808, 0x19082b19, 0x19192b08, 0x19082b19, 0x192b0819, 0x19082b19, 0x2b08082b, 0x19082b19, | |
| 84 | + 0x19081919, 0x19082b2b, 0x2b190808, 0x19082b2b, 0x08080808, 0x19190808, 0x08082b08, 0x19190808, | |
| 85 | + 0x08190819, 0x19190808, 0x08192b19, 0x19190808, 0x082b0808, 0x19190808, 0x2b080808, 0x19190808, | |
| 86 | + 0x2b082b08, 0x19190808, 0x08081908, 0x19190819, 0x1908082b, 0x19190819, 0x2b2b1908, 0x19190819, | |
| 87 | + 0x2b190819, 0x1919082b, 0x2b190808, 0x19191908, 0x2b19082b, 0x19191908, 0x08082b2b, 0x19191919, | |
| 88 | + 0x08080819, 0x1919192b, 0x19191908, 0x1919192b, 0x08080808, 0x19192b08, 0x08190819, 0x19192b08, | |
| 89 | + 0x08192b19, 0x19192b08, 0x192b1908, 0x19192b08, 0x19080808, 0x19192b19, 0x08082b08, 0x19192b2b, | |
| 90 | + 0x08081908, 0x192b0808, 0x08190808, 0x192b0808, 0x19080808, 0x192b0808, 0x192b2b08, 0x192b0808, | |
| 91 | + 0x08080808, 0x192b0819, 0x19191919, 0x192b0819, 0x08192b08, 0x192b082b, 0x192b0808, 0x192b082b, | |
| 92 | + 0x08080808, 0x192b1908, 0x08081919, 0x192b1908, 0x08190808, 0x192b1919, 0x0819082b, 0x192b1919, | |
| 93 | + 0x2b081908, 0x192b1919, 0x1908082b, 0x192b2b08, 0x08080808, 0x2b080808, 0x0808082b, 0x2b080808, | |
| 94 | + 0x08082b2b, 0x2b080808, 0x19080819, 0x2b080808, 0x2b08082b, 0x2b080808, 0x08081908, 0x2b080819, | |
| 95 | + 0x08192b08, 0x2b080819, 0x19080808, 0x2b080819, 0x08190819, 0x2b08082b, 0x08080819, 0x2b081908, | |
| 96 | + 0x08081908, 0x2b081908, 0x08190808, 0x2b081908, 0x08191919, 0x2b081908, 0x19080808, 0x2b081908, | |
| 97 | + 0x192b0808, 0x2b081908, 0x08080808, 0x2b081919, 0x1908192b, 0x2b081919, 0x2b191908, 0x2b081919, | |
| 98 | + 0x08082b19, 0x2b08192b, 0x19080808, 0x2b08192b, 0x192b0808, 0x2b08192b, 0x0808082b, 0x2b082b08, | |
| 99 | + 0x08081908, 0x2b082b19, 0x08190819, 0x2b082b2b, 0x08081908, 0x2b190808, 0x08190808, 0x2b190808, | |
| 100 | + 0x082b1908, 0x2b190808, 0x19080808, 0x2b190808, 0x2b2b0819, 0x2b190808, 0x0819192b, 0x2b190819, | |
| 101 | + 0x2b080808, 0x2b190819, 0x19081919, 0x2b19082b, 0x08080808, 0x2b191908, 0x082b082b, 0x2b191908, | |
| 102 | + 0x19081908, 0x2b191908, 0x19190819, 0x2b191919, 0x2b080819, 0x2b192b08, 0x082b0808, 0x2b192b19, | |
| 103 | + 0x0808082b, 0x2b2b0808, 0x19190808, 0x2b2b0808, 0x2b081919, 0x2b2b0808, 0x08082b19, 0x2b2b0819, | |
| 104 | + 0x08080808, 0x2b2b082b, 0x08192b08, 0x2b2b1908, 0x19190808, 0x2b2b2b08, 0x08081908, 0x2b2b2b19, | |
| 105 | +]); | |
| 106 | + | |
| 107 | +export const IQ1S_GRID = new Uint32Array([ | |
| 108 | + 0xffffffff, 0xffffffff, 0xffffff01, 0xffffffff, 0xffff0000, 0xffffffff, 0xffff01ff, 0xffffffff, | |
| 109 | + 0xffff0101, 0xffffffff, 0xff00ff00, 0xffffffff, 0xff000000, 0xffffffff, 0xff01ffff, 0xffffffff, | |
| 110 | + 0xff01ff01, 0xffffffff, 0xff0101ff, 0xffffffff, 0xff010101, 0xffffffff, 0x00ff0000, 0xffffffff, | |
| 111 | + 0x0000ff00, 0xffffffff, 0x000000ff, 0xffffffff, 0x00000001, 0xffffffff, 0x00010000, 0xffffffff, | |
| 112 | + 0x01ffffff, 0xffffffff, 0x01ffff01, 0xffffffff, 0x01ff01ff, 0xffffffff, 0x01ff0101, 0xffffffff, | |
| 113 | + 0x01000000, 0xffffffff, 0x0101ffff, 0xffffffff, 0x0101ff01, 0xffffffff, 0x010101ff, 0xffffffff, | |
| 114 | + 0x01010101, 0xffffffff, 0xffff00ff, 0xffffff00, 0xffff0000, 0xffffff00, 0xff00ff00, 0xffffff00, | |
| 115 | + 0xff0000ff, 0xffffff00, 0xff000001, 0xffffff00, 0xff000100, 0xffffff00, 0xff000101, 0xffffff00, | |
| 116 | + 0xff010000, 0xffffff00, 0x00ffff00, 0xffffff00, 0x00ff0001, 0xffffff00, 0x00ff0100, 0xffffff00, | |
| 117 | + 0x0000ff01, 0xffffff00, 0x00000000, 0xffffff00, 0x00000101, 0xffffff00, 0x0001ff00, 0xffffff00, | |
| 118 | + 0x000100ff, 0xffffff00, 0x00010001, 0xffffff00, 0x000101ff, 0xffffff00, 0x01ff0000, 0xffffff00, | |
| 119 | + 0x0100ff00, 0xffffff00, 0x010000ff, 0xffffff00, 0x01000001, 0xffffff00, 0x01010000, 0xffffff00, | |
| 120 | + 0xffffffff, 0xffffff01, 0xffffff01, 0xffffff01, 0xffff01ff, 0xffffff01, 0xffff0101, 0xffffff01, | |
| 121 | + 0xff000000, 0xffffff01, 0xff01ffff, 0xffffff01, 0xff01ff01, 0xffffff01, 0xff0101ff, 0xffffff01, | |
| 122 | + 0xff010101, 0xffffff01, 0x00ff0000, 0xffffff01, 0x0000ff00, 0xffffff01, 0x00000100, 0xffffff01, | |
| 123 | + 0x000100ff, 0xffffff01, 0x00010100, 0xffffff01, 0x01ffffff, 0xffffff01, 0x01ffff01, 0xffffff01, | |
| 124 | + 0x01ff01ff, 0xffffff01, 0x01ff0101, 0xffffff01, 0x0100ff00, 0xffffff01, 0x01000000, 0xffffff01, | |
| 125 | + 0x01000100, 0xffffff01, 0x0101ffff, 0xffffff01, 0x0101ff01, 0xffffff01, 0x010101ff, 0xffffff01, | |
| 126 | + 0x01010101, 0xffffff01, 0xff00ff00, 0xffff00ff, 0xff0000ff, 0xffff00ff, 0xff000001, 0xffff00ff, | |
| 127 | + 0xff010000, 0xffff00ff, 0x00ffff00, 0xffff00ff, 0x00ff0100, 0xffff00ff, 0x00000000, 0xffff00ff, | |
| 128 | + 0x00000101, 0xffff00ff, 0x000100ff, 0xffff00ff, 0x00010000, 0xffff00ff, 0x0100ff00, 0xffff00ff, | |
| 129 | + 0x01000100, 0xffff00ff, 0x01010000, 0xffff00ff, 0xffffff00, 0xffff0000, 0xffff00ff, 0xffff0000, | |
| 130 | + 0xffff0000, 0xffff0000, 0xffff0001, 0xffff0000, 0xff000000, 0xffff0000, 0xff0001ff, 0xffff0000, | |
| 131 | + 0xff000101, 0xffff0000, 0xff010100, 0xffff0000, 0x00ffffff, 0xffff0000, 0x00ff0000, 0xffff0000, | |
| 132 | + 0x00ff0101, 0xffff0000, 0x0000ffff, 0xffff0000, 0x0000ff00, 0xffff0000, 0x000000ff, 0xffff0000, | |
| 133 | + 0x00000000, 0xffff0000, 0x00000001, 0xffff0000, 0x00000100, 0xffff0000, 0x0001ffff, 0xffff0000, | |
| 134 | + 0x0001ff01, 0xffff0000, 0x00010000, 0xffff0000, 0x000101ff, 0xffff0000, 0x00010101, 0xffff0000, | |
| 135 | + 0x01ffff00, 0xffff0000, 0x0100ff00, 0xffff0000, 0x01000000, 0xffff0000, 0x010001ff, 0xffff0000, | |
| 136 | + 0x01000101, 0xffff0000, 0x0101ff00, 0xffff0000, 0x010100ff, 0xffff0000, 0x01010000, 0xffff0000, | |
| 137 | + 0x01010001, 0xffff0000, 0x01010100, 0xffff0000, 0xff0000ff, 0xffff0001, 0xff000100, 0xffff0001, | |
| 138 | + 0x00ffff00, 0xffff0001, 0x00ff00ff, 0xffff0001, 0x0000ffff, 0xffff0001, 0x0000ff01, 0xffff0001, | |
| 139 | + 0x00000000, 0xffff0001, 0x000001ff, 0xffff0001, 0x0001ffff, 0xffff0001, 0x0001ff00, 0xffff0001, | |
| 140 | + 0x00010001, 0xffff0001, 0x00010100, 0xffff0001, 0x01ff0000, 0xffff0001, 0x0100ff00, 0xffff0001, | |
| 141 | + 0x010000ff, 0xffff0001, 0x01000100, 0xffff0001, 0xffffffff, 0xffff01ff, 0xffffff01, 0xffff01ff, | |
| 142 | + 0xffff01ff, 0xffff01ff, 0xffff0101, 0xffff01ff, 0xff000000, 0xffff01ff, 0xff01ffff, 0xffff01ff, | |
| 143 | + 0xff01ff01, 0xffff01ff, 0xff0101ff, 0xffff01ff, 0xff010101, 0xffff01ff, 0x00ff0000, 0xffff01ff, | |
| 144 | + 0x0000ff00, 0xffff01ff, 0x00000001, 0xffff01ff, 0x00010000, 0xffff01ff, 0x01ffffff, 0xffff01ff, | |
| 145 | + 0x01ffff01, 0xffff01ff, 0x01ff01ff, 0xffff01ff, 0x01ff0101, 0xffff01ff, 0x01000000, 0xffff01ff, | |
| 146 | + 0x0101ffff, 0xffff01ff, 0x0101ff01, 0xffff01ff, 0x010101ff, 0xffff01ff, 0x01010101, 0xffff01ff, | |
| 147 | + 0xffff0000, 0xffff0100, 0xff00ff00, 0xffff0100, 0xff0000ff, 0xffff0100, 0xff000100, 0xffff0100, | |
| 148 | + 0xff0100ff, 0xffff0100, 0xff010000, 0xffff0100, 0x00ffff00, 0xffff0100, 0x0000ffff, 0xffff0100, | |
| 149 | + 0x0000ff00, 0xffff0100, 0x00000000, 0xffff0100, 0x0001ff00, 0xffff0100, 0x000100ff, 0xffff0100, | |
| 150 | + 0x00010100, 0xffff0100, 0x0100ff00, 0xffff0100, 0x010000ff, 0xffff0100, 0x01000001, 0xffff0100, | |
| 151 | + 0x01000100, 0xffff0100, 0x01010000, 0xffff0100, 0xffffffff, 0xffff0101, 0xffffff01, 0xffff0101, | |
| 152 | + 0xffff01ff, 0xffff0101, 0xffff0101, 0xffff0101, 0xff000000, 0xffff0101, 0xff01ffff, 0xffff0101, | |
| 153 | + 0xff01ff01, 0xffff0101, 0xff0101ff, 0xffff0101, 0xff010101, 0xffff0101, 0x00ff0000, 0xffff0101, | |
| 154 | + 0x0000ff00, 0xffff0101, 0x00000100, 0xffff0101, 0x0001ff00, 0xffff0101, 0x00010000, 0xffff0101, | |
| 155 | + 0x01ffffff, 0xffff0101, 0x01ffff01, 0xffff0101, 0x01ff0000, 0xffff0101, 0x01ff01ff, 0xffff0101, | |
| 156 | + 0x01ff0101, 0xffff0101, 0x01000000, 0xffff0101, 0x0101ffff, 0xffff0101, 0x0101ff01, 0xffff0101, | |
| 157 | + 0x010101ff, 0xffff0101, 0x01010101, 0xffff0101, 0xff00ffff, 0xff00ffff, 0xff00ff00, 0xff00ffff, | |
| 158 | + 0xff0000ff, 0xff00ffff, 0xff000100, 0xff00ffff, 0xff0100ff, 0xff00ffff, 0xff010000, 0xff00ffff, | |
| 159 | + 0x00ffff00, 0xff00ffff, 0x00ff00ff, 0xff00ffff, 0x0000ffff, 0xff00ffff, 0x00000000, 0xff00ffff, | |
| 160 | + 0x000001ff, 0xff00ffff, 0x0001ff00, 0xff00ffff, 0x000100ff, 0xff00ffff, 0x00010000, 0xff00ffff, | |
| 161 | + 0x00010100, 0xff00ffff, 0x0100ff00, 0xff00ffff, 0x010000ff, 0xff00ffff, 0x01000001, 0xff00ffff, | |
| 162 | + 0x0101ff00, 0xff00ffff, 0x01010000, 0xff00ffff, 0xffffff00, 0xff00ff00, 0xffff00ff, 0xff00ff00, | |
| 163 | + 0xffff0001, 0xff00ff00, 0xffff0100, 0xff00ff00, 0xff00ffff, 0xff00ff00, 0xff00ff01, 0xff00ff00, | |
| 164 | + 0xff000000, 0xff00ff00, 0xff0001ff, 0xff00ff00, 0xff01ff00, 0xff00ff00, 0xff0100ff, 0xff00ff00, | |
| 165 | + 0xff010100, 0xff00ff00, 0x00ff0000, 0xff00ff00, 0x00ff0101, 0xff00ff00, 0x0000ffff, 0xff00ff00, | |
| 166 | + 0x0000ff00, 0xff00ff00, 0x0000ff01, 0xff00ff00, 0x000000ff, 0xff00ff00, 0x00000000, 0xff00ff00, | |
| 167 | + 0x00000001, 0xff00ff00, 0x00000100, 0xff00ff00, 0x0001ffff, 0xff00ff00, 0x00010000, 0xff00ff00, | |
| 168 | + 0x01ff00ff, 0xff00ff00, 0x0100ff01, 0xff00ff00, 0x01000000, 0xff00ff00, 0x0101ff00, 0xff00ff00, | |
| 169 | + 0x010100ff, 0xff00ff00, 0xff00ff00, 0xff00ff01, 0xff0000ff, 0xff00ff01, 0xff000001, 0xff00ff01, | |
| 170 | + 0xff010000, 0xff00ff01, 0x00ffffff, 0xff00ff01, 0x00ff0001, 0xff00ff01, 0x00ff0100, 0xff00ff01, | |
| 171 | + 0x0000ff01, 0xff00ff01, 0x00000000, 0xff00ff01, 0x000001ff, 0xff00ff01, 0x00000101, 0xff00ff01, | |
| 172 | + 0x000100ff, 0xff00ff01, 0x00010001, 0xff00ff01, 0x01ff0000, 0xff00ff01, 0x0100ff00, 0xff00ff01, | |
| 173 | + 0x010000ff, 0xff00ff01, 0x01000001, 0xff00ff01, 0x01010000, 0xff00ff01, 0xffffff00, 0xff0000ff, | |
| 174 | + 0xffff0001, 0xff0000ff, 0xffff0100, 0xff0000ff, 0xff0000ff, 0xff0000ff, 0xff000000, 0xff0000ff, | |
| 175 | + 0xff0001ff, 0xff0000ff, 0xff000100, 0xff0000ff, 0xff01ff00, 0xff0000ff, 0xff010001, 0xff0000ff, | |
| 176 | + 0x00ffff00, 0xff0000ff, 0x00ff0000, 0xff0000ff, 0x00ff0001, 0xff0000ff, 0x00ff01ff, 0xff0000ff, | |
| 177 | + 0x00ff0101, 0xff0000ff, 0x0000ff00, 0xff0000ff, 0x000000ff, 0xff0000ff, 0x00000000, 0xff0000ff, | |
| 178 | + 0x00000001, 0xff0000ff, 0x00000100, 0xff0000ff, 0x0001ff01, 0xff0000ff, 0x00010000, 0xff0000ff, | |
| 179 | + 0x000101ff, 0xff0000ff, 0x01ff00ff, 0xff0000ff, 0x01ff0100, 0xff0000ff, 0x0100ffff, 0xff0000ff, | |
| 180 | + 0x010000ff, 0xff0000ff, 0x01000000, 0xff0000ff, 0x010001ff, 0xff0000ff, 0x01000100, 0xff0000ff, | |
| 181 | + 0x01000101, 0xff0000ff, 0x0101ff00, 0xff0000ff, 0x010100ff, 0xff0000ff, 0x01010000, 0xff0000ff, | |
| 182 | + 0x01010100, 0xff0000ff, 0xffffff01, 0xff000000, 0xffff0000, 0xff000000, 0xffff0101, 0xff000000, | |
| 183 | + 0xff00ff00, 0xff000000, 0xff0000ff, 0xff000000, 0xff000000, 0xff000000, 0xff000001, 0xff000000, | |
| 184 | + 0xff000100, 0xff000000, 0xff01ffff, 0xff000000, 0xff01ff01, 0xff000000, 0xff010000, 0xff000000, | |
| 185 | + 0xff0101ff, 0xff000000, 0xff010101, 0xff000000, 0x00ffff00, 0xff000000, 0x00ff00ff, 0xff000000, | |
| 186 | + 0x00ff0000, 0xff000000, 0x00ff0001, 0xff000000, 0x0000ff00, 0xff000000, 0x0000ff01, 0xff000000, | |
| 187 | + 0x000000ff, 0xff000000, 0x00000000, 0xff000000, 0x00000001, 0xff000000, 0x00000100, 0xff000000, | |
| 188 | + 0x00000101, 0xff000000, 0x0001ff00, 0xff000000, 0x000100ff, 0xff000000, 0x00010000, 0xff000000, | |
| 189 | + 0x00010001, 0xff000000, 0x00010100, 0xff000000, 0x01ffffff, 0xff000000, 0x01ffff01, 0xff000000, | |
| 190 | + 0x01ff00ff, 0xff000000, 0x01ff0000, 0xff000000, 0x01ff01ff, 0xff000000, 0x01ff0101, 0xff000000, | |
| 191 | + 0x0100ffff, 0xff000000, 0x0100ff00, 0xff000000, 0x010000ff, 0xff000000, 0x01000000, 0xff000000, | |
| 192 | + 0x01000001, 0xff000000, 0x01000100, 0xff000000, 0x01000101, 0xff000000, 0x0101ffff, 0xff000000, | |
| 193 | + 0x0101ff01, 0xff000000, 0x01010000, 0xff000000, 0xffffff00, 0xff000001, 0xffff00ff, 0xff000001, | |
| 194 | + 0xffff0000, 0xff000001, 0xffff0001, 0xff000001, 0xff000000, 0xff000001, 0xff000001, 0xff000001, | |
| 195 | + 0xff0001ff, 0xff000001, 0xff000101, 0xff000001, 0xff01ff00, 0xff000001, 0xff010001, 0xff000001, | |
| 196 | + 0x00ffffff, 0xff000001, 0x00ffff01, 0xff000001, 0x00ff00ff, 0xff000001, 0x00ff0000, 0xff000001, | |
| 197 | + 0x00ff01ff, 0xff000001, 0x00ff0101, 0xff000001, 0x0000ff00, 0xff000001, 0x00000000, 0xff000001, | |
| 198 | + 0x00000001, 0xff000001, 0x000001ff, 0xff000001, 0x00000100, 0xff000001, 0x0001ff00, 0xff000001, | |
| 199 | + 0x000100ff, 0xff000001, 0x00010000, 0xff000001, 0x000101ff, 0xff000001, 0x00010100, 0xff000001, | |
| 200 | + 0x00010101, 0xff000001, 0x01ff0001, 0xff000001, 0x01ff0101, 0xff000001, 0x0100ff01, 0xff000001, | |
| 201 | + 0x01000000, 0xff000001, 0x010100ff, 0xff000001, 0x01010100, 0xff000001, 0xff00ff00, 0xff0001ff, | |
| 202 | + 0xff000001, 0xff0001ff, 0xff010000, 0xff0001ff, 0x00ffff00, 0xff0001ff, 0x00ff00ff, 0xff0001ff, | |
| 203 | + 0x00ff0001, 0xff0001ff, 0x00ff0100, 0xff0001ff, 0x0000ffff, 0xff0001ff, 0x00000000, 0xff0001ff, | |
| 204 | + 0x000001ff, 0xff0001ff, 0x00000101, 0xff0001ff, 0x0001ffff, 0xff0001ff, 0x0001ff00, 0xff0001ff, | |
| 205 | + 0x000100ff, 0xff0001ff, 0x00010001, 0xff0001ff, 0x00010100, 0xff0001ff, 0x01ff0000, 0xff0001ff, | |
| 206 | + 0x0100ff00, 0xff0001ff, 0x010000ff, 0xff0001ff, 0x01010000, 0xff0001ff, 0xff00ffff, 0xff000100, | |
| 207 | + 0xff00ff01, 0xff000100, 0xff000000, 0xff000100, 0xff000101, 0xff000100, 0xff01ff00, 0xff000100, | |
| 208 | + 0xff010000, 0xff000100, 0x00ffff01, 0xff000100, 0x00ff00ff, 0xff000100, 0x00ff0000, 0xff000100, | |
| 209 | + 0x00ff01ff, 0xff000100, 0x0000ff00, 0xff000100, 0x000000ff, 0xff000100, 0x00000000, 0xff000100, | |
| 210 | + 0x00000001, 0xff000100, 0x00000100, 0xff000100, 0x00000101, 0xff000100, 0x0001ffff, 0xff000100, | |
| 211 | + 0x00010000, 0xff000100, 0x00010101, 0xff000100, 0x01ff0100, 0xff000100, 0x0100ff00, 0xff000100, | |
| 212 | + 0x0100ff01, 0xff000100, 0x01000000, 0xff000100, 0x010001ff, 0xff000100, 0x0101ff00, 0xff000100, | |
| 213 | + 0x01010001, 0xff000100, 0x01010100, 0xff000100, 0xffff0100, 0xff000101, 0xff000001, 0xff000101, | |
| 214 | + 0xff0100ff, 0xff000101, 0xff010001, 0xff000101, 0x00ff00ff, 0xff000101, 0x00ff0001, 0xff000101, | |
| 215 | + 0x00ff0100, 0xff000101, 0x0000ffff, 0xff000101, 0x0000ff01, 0xff000101, 0x00000000, 0xff000101, | |
| 216 | + 0x000001ff, 0xff000101, 0x0001ff00, 0xff000101, 0x00010001, 0xff000101, 0x00010100, 0xff000101, | |
| 217 | + 0x01ff0000, 0xff000101, 0x0100ff00, 0xff000101, 0x01000001, 0xff000101, 0x01000101, 0xff000101, | |
| 218 | + 0xffffffff, 0xff01ffff, 0xffffff01, 0xff01ffff, 0xffff01ff, 0xff01ffff, 0xffff0101, 0xff01ffff, | |
| 219 | + 0xff000000, 0xff01ffff, 0xff01ffff, 0xff01ffff, 0xff01ff01, 0xff01ffff, 0xff010000, 0xff01ffff, | |
| 220 | + 0xff0101ff, 0xff01ffff, 0xff010101, 0xff01ffff, 0x00ff0000, 0xff01ffff, 0x0000ff00, 0xff01ffff, | |
| 221 | + 0x00000100, 0xff01ffff, 0x0001ff00, 0xff01ffff, 0x00010000, 0xff01ffff, 0x01ffffff, 0xff01ffff, | |
| 222 | + 0x01ffff01, 0xff01ffff, 0x01ff01ff, 0xff01ffff, 0x01ff0101, 0xff01ffff, 0x01000000, 0xff01ffff, | |
| 223 | + 0x0101ffff, 0xff01ffff, 0x0101ff01, 0xff01ffff, 0x01010000, 0xff01ffff, 0x010101ff, 0xff01ffff, | |
| 224 | + 0x01010101, 0xff01ffff, 0xffff0000, 0xff01ff00, 0xff00ff00, 0xff01ff00, 0xff0000ff, 0xff01ff00, | |
| 225 | + 0xff000100, 0xff01ff00, 0xff010000, 0xff01ff00, 0x00ffff01, 0xff01ff00, 0x00ff00ff, 0xff01ff00, | |
| 226 | + 0x00ff0100, 0xff01ff00, 0x00000000, 0xff01ff00, 0x000001ff, 0xff01ff00, 0x00000101, 0xff01ff00, | |
| 227 | + 0x0001ff00, 0xff01ff00, 0x000100ff, 0xff01ff00, 0x00010000, 0xff01ff00, 0x00010001, 0xff01ff00, | |
| 228 | + 0x01ff0000, 0xff01ff00, 0x0100ffff, 0xff01ff00, 0x01000001, 0xff01ff00, 0x01000100, 0xff01ff00, | |
| 229 | + 0x01010000, 0xff01ff00, 0xffffff00, 0xff01ff01, 0xffff01ff, 0xff01ff01, 0xffff0101, 0xff01ff01, | |
| 230 | + 0xff00ff00, 0xff01ff01, 0xff000000, 0xff01ff01, 0xff01ffff, 0xff01ff01, 0xff01ff01, 0xff01ff01, | |
| 231 | + 0xff0101ff, 0xff01ff01, 0xff010101, 0xff01ff01, 0x00ff0000, 0xff01ff01, 0x0000ff00, 0xff01ff01, | |
| 232 | + 0x00000001, 0xff01ff01, 0x00000100, 0xff01ff01, 0x00010000, 0xff01ff01, 0x01ffff00, 0xff01ff01, | |
| 233 | + 0x01ff01ff, 0xff01ff01, 0x01ff0101, 0xff01ff01, 0x0100ff00, 0xff01ff01, 0x01000000, 0xff01ff01, | |
| 234 | + 0x0101ffff, 0xff01ff01, 0x0101ff01, 0xff01ff01, 0x010101ff, 0xff01ff01, 0x01010101, 0xff01ff01, | |
| 235 | + 0xffff0000, 0xff0100ff, 0xff0000ff, 0xff0100ff, 0xff000001, 0xff0100ff, 0xff000100, 0xff0100ff, | |
| 236 | + 0xff010000, 0xff0100ff, 0x00ff00ff, 0xff0100ff, 0x00ff0000, 0xff0100ff, 0x00ff0001, 0xff0100ff, | |
| 237 | + 0x00ff0100, 0xff0100ff, 0x0000ff01, 0xff0100ff, 0x00000000, 0xff0100ff, 0x000001ff, 0xff0100ff, | |
| 238 | + 0x00000101, 0xff0100ff, 0x00010001, 0xff0100ff, 0x01ff0000, 0xff0100ff, 0x0100ff00, 0xff0100ff, | |
| 239 | + 0x010000ff, 0xff0100ff, 0x01000100, 0xff0100ff, 0x0101ff00, 0xff0100ff, 0x01010000, 0xff0100ff, | |
| 240 | + 0xffff0100, 0xff010000, 0xff000000, 0xff010000, 0xff01ff00, 0xff010000, 0xff010100, 0xff010000, | |
| 241 | + 0x00ffffff, 0xff010000, 0x00ff0000, 0xff010000, 0x00ff01ff, 0xff010000, 0x0000ff00, 0xff010000, | |
| 242 | + 0x000000ff, 0xff010000, 0x00000000, 0xff010000, 0x00000100, 0xff010000, 0x0001ff01, 0xff010000, | |
| 243 | + 0x00010000, 0xff010000, 0x000101ff, 0xff010000, 0x01ff0100, 0xff010000, 0x0100ffff, 0xff010000, | |
| 244 | + 0x010000ff, 0xff010000, 0x01000000, 0xff010000, 0x010001ff, 0xff010000, 0x01000101, 0xff010000, | |
| 245 | + 0x0101ff00, 0xff010000, 0x010100ff, 0xff010000, 0x01010001, 0xff010000, 0x01010100, 0xff010000, | |
| 246 | + 0xffff0000, 0xff010001, 0xff00ffff, 0xff010001, 0xff00ff01, 0xff010001, 0xff000100, 0xff010001, | |
| 247 | + 0xff010000, 0xff010001, 0x00ffff00, 0xff010001, 0x00ff0100, 0xff010001, 0x00000000, 0xff010001, | |
| 248 | + 0x0001ffff, 0xff010001, 0x0001ff00, 0xff010001, 0x00010100, 0xff010001, 0x01ff00ff, 0xff010001, | |
| 249 | + 0x01ff0001, 0xff010001, 0x0100ffff, 0xff010001, 0x01000101, 0xff010001, 0xffffffff, 0xff0101ff, | |
| 250 | + 0xffffff01, 0xff0101ff, 0xffff01ff, 0xff0101ff, 0xffff0101, 0xff0101ff, 0xff000000, 0xff0101ff, | |
| 251 | + 0xff01ffff, 0xff0101ff, 0xff01ff01, 0xff0101ff, 0xff0101ff, 0xff0101ff, 0xff010101, 0xff0101ff, | |
| 252 | + 0x00ff0000, 0xff0101ff, 0x0000ff00, 0xff0101ff, 0x000000ff, 0xff0101ff, 0x00010000, 0xff0101ff, | |
| 253 | + 0x01ffffff, 0xff0101ff, 0x01ffff01, 0xff0101ff, 0x01ff01ff, 0xff0101ff, 0x01ff0101, 0xff0101ff, | |
| 254 | + 0x0101ffff, 0xff0101ff, 0x0101ff01, 0xff0101ff, 0x010101ff, 0xff0101ff, 0x01010101, 0xff0101ff, | |
| 255 | + 0xffff0100, 0xff010100, 0xff00ff00, 0xff010100, 0xff0000ff, 0xff010100, 0xff000100, 0xff010100, | |
| 256 | + 0xff010000, 0xff010100, 0x00ff0001, 0xff010100, 0x00ff0100, 0xff010100, 0x0000ff01, 0xff010100, | |
| 257 | + 0x00000000, 0xff010100, 0x0001ff00, 0xff010100, 0x000100ff, 0xff010100, 0x00010001, 0xff010100, | |
| 258 | + 0x00010100, 0xff010100, 0x01ff0000, 0xff010100, 0x0100ffff, 0xff010100, 0x01000001, 0xff010100, | |
| 259 | + 0x01000100, 0xff010100, 0x010100ff, 0xff010100, 0x01010000, 0xff010100, 0xffffffff, 0xff010101, | |
| 260 | + 0xffffff01, 0xff010101, 0xffff01ff, 0xff010101, 0xffff0101, 0xff010101, 0xff01ffff, 0xff010101, | |
| 261 | + 0xff01ff01, 0xff010101, 0xff0101ff, 0xff010101, 0xff010101, 0xff010101, 0x00ff0000, 0xff010101, | |
| 262 | + 0x0000ff00, 0xff010101, 0x00000001, 0xff010101, 0x00000100, 0xff010101, 0x00010000, 0xff010101, | |
| 263 | + 0x01ffffff, 0xff010101, 0x01ffff01, 0xff010101, 0x01ff01ff, 0xff010101, 0x01ff0101, 0xff010101, | |
| 264 | + 0x01000000, 0xff010101, 0x0101ffff, 0xff010101, 0x0101ff01, 0xff010101, 0x010101ff, 0xff010101, | |
| 265 | + 0x01010101, 0xff010101, 0xffff0000, 0x00ffffff, 0xff00ff00, 0x00ffffff, 0xff000001, 0x00ffffff, | |
| 266 | + 0xff010000, 0x00ffffff, 0x00ff0100, 0x00ffffff, 0x0000ff01, 0x00ffffff, 0x00000000, 0x00ffffff, | |
| 267 | + 0x000001ff, 0x00ffffff, 0x00000101, 0x00ffffff, 0x0001ff00, 0x00ffffff, 0x000100ff, 0x00ffffff, | |
| 268 | + 0x00010001, 0x00ffffff, 0x010000ff, 0x00ffffff, 0x01000100, 0x00ffffff, 0x0101ff00, 0x00ffffff, | |
| 269 | + 0x01010001, 0x00ffffff, 0xffffffff, 0x00ffff00, 0xffffff00, 0x00ffff00, 0xffff00ff, 0x00ffff00, | |
| 270 | + 0xffff0001, 0x00ffff00, 0xffff0100, 0x00ffff00, 0xff00ff01, 0x00ffff00, 0xff000000, 0x00ffff00, | |
| 271 | + 0xff000001, 0x00ffff00, 0xff0001ff, 0x00ffff00, 0xff000101, 0x00ffff00, 0xff01ff00, 0x00ffff00, | |
| 272 | + 0xff010001, 0x00ffff00, 0xff010100, 0x00ffff00, 0x00ff0000, 0x00ffff00, 0x00ff01ff, 0x00ffff00, | |
| 273 | + 0x00ff0101, 0x00ffff00, 0x0000ff00, 0x00ffff00, 0x000000ff, 0x00ffff00, 0x00000000, 0x00ffff00, | |
| 274 | + 0x00000001, 0x00ffff00, 0x00000100, 0x00ffff00, 0x00000101, 0x00ffff00, 0x00010000, 0x00ffff00, | |
| 275 | + 0x000101ff, 0x00ffff00, 0x00010101, 0x00ffff00, 0x01ffff00, 0x00ffff00, 0x01ff00ff, 0x00ffff00, | |
| 276 | + 0x01ff0001, 0x00ffff00, 0x0100ffff, 0x00ffff00, 0x0100ff01, 0x00ffff00, 0x01000000, 0x00ffff00, | |
| 277 | + 0x0101ffff, 0x00ffff00, 0x0101ff00, 0x00ffff00, 0x0101ff01, 0x00ffff00, 0xffff0000, 0x00ffff01, | |
| 278 | + 0xff00ff00, 0x00ffff01, 0xff0000ff, 0x00ffff01, 0xff000001, 0x00ffff01, 0xff010000, 0x00ffff01, | |
| 279 | + 0x00ffff00, 0x00ffff01, 0x0000ff01, 0x00ffff01, 0x00000000, 0x00ffff01, 0x00000101, 0x00ffff01, | |
| 280 | + 0x000100ff, 0x00ffff01, 0x00010100, 0x00ffff01, 0x01ff0100, 0x00ffff01, 0x010000ff, 0x00ffff01, | |
| 281 | + 0x01010000, 0x00ffff01, 0xffffff00, 0x00ff00ff, 0xff000000, 0x00ff00ff, 0xff000100, 0x00ff00ff, | |
| 282 | + 0xff010100, 0x00ff00ff, 0x00ff0000, 0x00ff00ff, 0x00ff01ff, 0x00ff00ff, 0x00ff0101, 0x00ff00ff, | |
| 283 | + 0x0000ff00, 0x00ff00ff, 0x000000ff, 0x00ff00ff, 0x00000000, 0x00ff00ff, 0x00000001, 0x00ff00ff, | |
| 284 | + 0x0001ff00, 0x00ff00ff, 0x0001ff01, 0x00ff00ff, 0x00010000, 0x00ff00ff, 0x000101ff, 0x00ff00ff, | |
| 285 | + 0x00010101, 0x00ff00ff, 0x01ffff00, 0x00ff00ff, 0x01ff0001, 0x00ff00ff, 0x01ff0100, 0x00ff00ff, | |
| 286 | + 0x0100ffff, 0x00ff00ff, 0x0100ff01, 0x00ff00ff, 0x01000000, 0x00ff00ff, 0x0101ffff, 0x00ff00ff, | |
| 287 | + 0x0101ff00, 0x00ff00ff, 0x01010100, 0x00ff00ff, 0xffffff00, 0x00ff0000, 0xffffff01, 0x00ff0000, | |
| 288 | + 0xffff0000, 0x00ff0000, 0xffff0101, 0x00ff0000, 0xff00ff00, 0x00ff0000, 0xff0000ff, 0x00ff0000, | |
| 289 | + 0xff000000, 0x00ff0000, 0xff000001, 0x00ff0000, 0xff000100, 0x00ff0000, 0xff01ffff, 0x00ff0000, | |
| 290 | + 0xff010000, 0x00ff0000, 0xff010101, 0x00ff0000, 0x00ffff00, 0x00ff0000, 0x00ff00ff, 0x00ff0000, | |
| 291 | + 0x00ff0000, 0x00ff0000, 0x00ff0001, 0x00ff0000, 0x00ff0100, 0x00ff0000, 0x0000ffff, 0x00ff0000, | |
| 292 | + 0x0000ff00, 0x00ff0000, 0x000000ff, 0x00ff0000, 0x00000000, 0x00ff0000, 0x00000001, 0x00ff0000, | |
| 293 | + 0x000001ff, 0x00ff0000, 0x00000100, 0x00ff0000, 0x0001ff00, 0x00ff0000, 0x000100ff, 0x00ff0000, | |
| 294 | + 0x00010000, 0x00ff0000, 0x00010001, 0x00ff0000, 0x00010100, 0x00ff0000, 0x01ffff01, 0x00ff0000, | |
| 295 | + 0x01ff00ff, 0x00ff0000, 0x01ff0000, 0x00ff0000, 0x01ff01ff, 0x00ff0000, 0x0100ff00, 0x00ff0000, | |
| 296 | + 0x010000ff, 0x00ff0000, 0x01000000, 0x00ff0000, 0x01000001, 0x00ff0000, 0x01000100, 0x00ff0000, | |
| 297 | + 0x01000101, 0x00ff0000, 0x01010000, 0x00ff0000, 0x010101ff, 0x00ff0000, 0x01010101, 0x00ff0000, | |
| 298 | + 0xffffff00, 0x00ff0001, 0xffff0000, 0x00ff0001, 0xffff0100, 0x00ff0001, 0xff0000ff, 0x00ff0001, | |
| 299 | + 0xff000000, 0x00ff0001, 0xff0001ff, 0x00ff0001, 0xff000101, 0x00ff0001, 0xff01ff00, 0x00ff0001, | |
| 300 | + 0xff0100ff, 0x00ff0001, 0xff010100, 0x00ff0001, 0x00ffffff, 0x00ff0001, 0x00ffff01, 0x00ff0001, | |
| 301 | + 0x00ff0000, 0x00ff0001, 0x00ff01ff, 0x00ff0001, 0x0000ffff, 0x00ff0001, 0x0000ff00, 0x00ff0001, | |
| 302 | + 0x0000ff01, 0x00ff0001, 0x00000000, 0x00ff0001, 0x00000001, 0x00ff0001, 0x00000100, 0x00ff0001, | |
| 303 | + 0x0001ff01, 0x00ff0001, 0x00010000, 0x00ff0001, 0x000101ff, 0x00ff0001, 0x01ffff00, 0x00ff0001, | |
| 304 | + 0x01ff0000, 0x00ff0001, 0x01ff0101, 0x00ff0001, 0x010000ff, 0x00ff0001, 0x01000000, 0x00ff0001, | |
| 305 | + 0x0101ff00, 0x00ff0001, 0x010100ff, 0x00ff0001, 0x01010001, 0x00ff0001, 0xffff0000, 0x00ff01ff, | |
| 306 | + 0xff00ff00, 0x00ff01ff, 0xff000000, 0x00ff01ff, 0xff000101, 0x00ff01ff, 0xff010000, 0x00ff01ff, | |
| 307 | + 0x00ffff01, 0x00ff01ff, 0x00ff0100, 0x00ff01ff, 0x0000ffff, 0x00ff01ff, 0x00000000, 0x00ff01ff, | |
| 308 | + 0x000001ff, 0x00ff01ff, 0x0001ff00, 0x00ff01ff, 0x000100ff, 0x00ff01ff, 0x00010001, 0x00ff01ff, | |
| 309 | + 0x00010100, 0x00ff01ff, 0x01ff0000, 0x00ff01ff, 0x0100ff00, 0x00ff01ff, 0x010000ff, 0x00ff01ff, | |
| 310 | + 0x01000001, 0x00ff01ff, 0x01000100, 0x00ff01ff, 0x01010000, 0x00ff01ff, 0xffffff00, 0x00ff0100, | |
| 311 | + 0xffff0000, 0x00ff0100, 0xffff0001, 0x00ff0100, 0xffff0101, 0x00ff0100, 0xff00ffff, 0x00ff0100, | |
| 312 | + 0xff0000ff, 0x00ff0100, 0xff000000, 0x00ff0100, 0xff0001ff, 0x00ff0100, 0xff01ff00, 0x00ff0100, | |
| 313 | + 0xff0100ff, 0x00ff0100, 0xff010001, 0x00ff0100, 0x00ffffff, 0x00ff0100, 0x00ff0000, 0x00ff0100, | |
| 314 | + 0x00ff0101, 0x00ff0100, 0x0000ff00, 0x00ff0100, 0x0000ff01, 0x00ff0100, 0x000000ff, 0x00ff0100, | |
| 315 | + 0x00000000, 0x00ff0100, 0x00000001, 0x00ff0100, 0x00000100, 0x00ff0100, 0x0001ffff, 0x00ff0100, | |
| 316 | + 0x0001ff01, 0x00ff0100, 0x00010000, 0x00ff0100, 0x00010001, 0x00ff0100, 0x00010101, 0x00ff0100, | |
| 317 | + 0x01ff0001, 0x00ff0100, 0x01ff0100, 0x00ff0100, 0x0100ff01, 0x00ff0100, 0x01000000, 0x00ff0100, | |
| 318 | + 0x01000001, 0x00ff0100, 0x010001ff, 0x00ff0100, 0x0101ff00, 0x00ff0100, 0x010100ff, 0x00ff0100, | |
| 319 | + 0x01010001, 0x00ff0100, 0x01010100, 0x00ff0100, 0xff000001, 0x00ff0101, 0x00ff00ff, 0x00ff0101, | |
| 320 | + 0x00ff0001, 0x00ff0101, 0x00ff0100, 0x00ff0101, 0x00000000, 0x00ff0101, 0x000001ff, 0x00ff0101, | |
| 321 | + 0x00000101, 0x00ff0101, 0x000100ff, 0x00ff0101, 0x00010100, 0x00ff0101, 0x010000ff, 0x00ff0101, | |
| 322 | + 0x01010000, 0x00ff0101, 0xffffff00, 0x0000ffff, 0xffff00ff, 0x0000ffff, 0xffff0000, 0x0000ffff, | |
| 323 | + 0xffff0001, 0x0000ffff, 0xffff0100, 0x0000ffff, 0xff00ff01, 0x0000ffff, 0xff000000, 0x0000ffff, | |
| 324 | + 0xff000101, 0x0000ffff, 0xff01ff00, 0x0000ffff, 0xff0100ff, 0x0000ffff, 0xff010100, 0x0000ffff, | |
| 325 | + 0x00ffffff, 0x0000ffff, 0x00ff0000, 0x0000ffff, 0x00ff01ff, 0x0000ffff, 0x0000ff00, 0x0000ffff, | |
| 326 | + 0x000000ff, 0x0000ffff, 0x00000000, 0x0000ffff, 0x00000001, 0x0000ffff, 0x00000100, 0x0000ffff, | |
| 327 | + 0x00010000, 0x0000ffff, 0x000101ff, 0x0000ffff, 0x01ff0001, 0x0000ffff, 0x01ff0100, 0x0000ffff, | |
| 328 | + 0x01000000, 0x0000ffff, 0x010001ff, 0x0000ffff, 0x0101ffff, 0x0000ffff, 0x0101ff00, 0x0000ffff, | |
| 329 | + 0x01010001, 0x0000ffff, 0x01010100, 0x0000ffff, 0xffff0000, 0x0000ff00, 0xffff01ff, 0x0000ff00, | |
| 330 | + 0xffff0100, 0x0000ff00, 0xffff0101, 0x0000ff00, 0xff00ff00, 0x0000ff00, 0xff0000ff, 0x0000ff00, | |
| 331 | + 0xff000000, 0x0000ff00, 0xff000001, 0x0000ff00, 0xff0001ff, 0x0000ff00, 0xff000100, 0x0000ff00, | |
| 332 | + 0xff01ffff, 0x0000ff00, 0xff010000, 0x0000ff00, 0xff010001, 0x0000ff00, 0xff0101ff, 0x0000ff00, | |
| 333 | + 0xff010101, 0x0000ff00, 0x00ffff00, 0x0000ff00, 0x00ff00ff, 0x0000ff00, 0x00ff0000, 0x0000ff00, | |
| 334 | + 0x00ff0001, 0x0000ff00, 0x00ff0100, 0x0000ff00, 0x0000ffff, 0x0000ff00, 0x0000ff00, 0x0000ff00, | |
| 335 | + 0x0000ff01, 0x0000ff00, 0x000000ff, 0x0000ff00, 0x00000000, 0x0000ff00, 0x00000001, 0x0000ff00, | |
| 336 | + 0x000001ff, 0x0000ff00, 0x00000100, 0x0000ff00, 0x00000101, 0x0000ff00, 0x0001ff00, 0x0000ff00, | |
| 337 | + 0x000100ff, 0x0000ff00, 0x00010000, 0x0000ff00, 0x00010001, 0x0000ff00, 0x00010100, 0x0000ff00, | |
| 338 | + 0x01ffff01, 0x0000ff00, 0x01ff0000, 0x0000ff00, 0x0100ff00, 0x0000ff00, 0x010000ff, 0x0000ff00, | |
| 339 | + 0x01000000, 0x0000ff00, 0x01000001, 0x0000ff00, 0x01000100, 0x0000ff00, 0x0101ffff, 0x0000ff00, | |
| 340 | + 0x01010000, 0x0000ff00, 0x01010101, 0x0000ff00, 0xffffff00, 0x0000ff01, 0xffff0001, 0x0000ff01, | |
| 341 | + 0xff00ff01, 0x0000ff01, 0xff000000, 0x0000ff01, 0xff000101, 0x0000ff01, 0xff01ff00, 0x0000ff01, | |
| 342 | + 0xff0100ff, 0x0000ff01, 0x00ffff01, 0x0000ff01, 0x00ff0000, 0x0000ff01, 0x00ff0101, 0x0000ff01, | |
| 343 | + 0x0000ff00, 0x0000ff01, 0x000000ff, 0x0000ff01, 0x00000000, 0x0000ff01, 0x00000001, 0x0000ff01, | |
| 344 | + 0x00000100, 0x0000ff01, 0x0001ff01, 0x0000ff01, 0x00010000, 0x0000ff01, 0x01ff0000, 0x0000ff01, | |
| 345 | + 0x0100ffff, 0x0000ff01, 0x0100ff01, 0x0000ff01, 0x01000000, 0x0000ff01, 0x01000100, 0x0000ff01, | |
| 346 | + 0x01000101, 0x0000ff01, 0x010100ff, 0x0000ff01, 0xffff00ff, 0x000000ff, 0xffff0000, 0x000000ff, | |
| 347 | + 0xff00ff00, 0x000000ff, 0xff0000ff, 0x000000ff, 0xff000000, 0x000000ff, 0xff000001, 0x000000ff, | |
| 348 | + 0xff0001ff, 0x000000ff, 0xff000100, 0x000000ff, 0xff01ff00, 0x000000ff, 0xff010000, 0x000000ff, | |
| 349 | + 0xff0101ff, 0x000000ff, 0xff010101, 0x000000ff, 0x00ffff00, 0x000000ff, 0x00ff00ff, 0x000000ff, | |
| 350 | + 0x00ff0000, 0x000000ff, 0x00ff0001, 0x000000ff, 0x00ff0100, 0x000000ff, 0x00ff0101, 0x000000ff, | |
| 351 | + 0x0000ffff, 0x000000ff, 0x0000ff00, 0x000000ff, 0x000000ff, 0x000000ff, 0x00000000, 0x000000ff, | |
| 352 | + 0x00000001, 0x000000ff, 0x000001ff, 0x000000ff, 0x00000100, 0x000000ff, 0x00000101, 0x000000ff, | |
| 353 | + 0x0001ff00, 0x000000ff, 0x0001ff01, 0x000000ff, 0x000100ff, 0x000000ff, 0x00010000, 0x000000ff, | |
| 354 | + 0x00010001, 0x000000ff, 0x00010100, 0x000000ff, 0x01ffffff, 0x000000ff, 0x01ff01ff, 0x000000ff, | |
| 355 | + 0x01ff0101, 0x000000ff, 0x0100ff00, 0x000000ff, 0x010000ff, 0x000000ff, 0x01000000, 0x000000ff, | |
| 356 | + 0x01000001, 0x000000ff, 0x01000100, 0x000000ff, 0x0101ff00, 0x000000ff, 0x010100ff, 0x000000ff, | |
| 357 | + 0x01010000, 0x000000ff, 0x01010101, 0x000000ff, 0xffffff00, 0x00000000, 0xffffff01, 0x00000000, | |
| 358 | + 0xffff00ff, 0x00000000, 0xffff0000, 0x00000000, 0xffff0001, 0x00000000, 0xffff0100, 0x00000000, | |
| 359 | + 0xff00ffff, 0x00000000, 0xff00ff00, 0x00000000, 0xff00ff01, 0x00000000, 0xff0000ff, 0x00000000, | |
| 360 | + 0xff000000, 0x00000000, 0xff000001, 0x00000000, 0xff000100, 0x00000000, 0xff000101, 0x00000000, | |
| 361 | + 0xff01ff00, 0x00000000, 0xff0100ff, 0x00000000, 0xff010000, 0x00000000, 0xff010001, 0x00000000, | |
| 362 | + 0xff010100, 0x00000000, 0x00ffffff, 0x00000000, 0x00ffff00, 0x00000000, 0x00ffff01, 0x00000000, | |
| 363 | + 0x00ff00ff, 0x00000000, 0x00ff0000, 0x00000000, 0x00ff0001, 0x00000000, 0x00ff01ff, 0x00000000, | |
| 364 | + 0x00ff0100, 0x00000000, 0x0000ffff, 0x00000000, 0x0000ff00, 0x00000000, 0x0000ff01, 0x00000000, | |
| 365 | + 0x000000ff, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000, 0x000001ff, 0x00000000, | |
| 366 | + 0x00000100, 0x00000000, 0x00000101, 0x00000000, 0x0001ffff, 0x00000000, 0x0001ff00, 0x00000000, | |
| 367 | + 0x000100ff, 0x00000000, 0x00010000, 0x00000000, 0x00010001, 0x00000000, 0x000101ff, 0x00000000, | |
| 368 | + 0x00010100, 0x00000000, 0x00010101, 0x00000000, 0x01ffff00, 0x00000000, 0x01ff00ff, 0x00000000, | |
| 369 | + 0x01ff0000, 0x00000000, 0x01ff0100, 0x00000000, 0x01ff0101, 0x00000000, 0x0100ffff, 0x00000000, | |
| 370 | + 0x0100ff00, 0x00000000, 0x010000ff, 0x00000000, 0x01000000, 0x00000000, 0x01000001, 0x00000000, | |
| 371 | + 0x010001ff, 0x00000000, 0x01000100, 0x00000000, 0x0101ff00, 0x00000000, 0x010100ff, 0x00000000, | |
| 372 | + 0x01010000, 0x00000000, 0x01010001, 0x00000000, 0x01010100, 0x00000000, 0xffffffff, 0x00000001, | |
| 373 | + 0xffffff00, 0x00000001, 0xffffff01, 0x00000001, 0xffff00ff, 0x00000001, 0xffff0001, 0x00000001, | |
| 374 | + 0xffff01ff, 0x00000001, 0xffff0100, 0x00000001, 0xff00ff00, 0x00000001, 0xff0000ff, 0x00000001, | |
| 375 | + 0xff000000, 0x00000001, 0xff0001ff, 0x00000001, 0xff000100, 0x00000001, 0xff01ffff, 0x00000001, | |
| 376 | + 0xff01ff00, 0x00000001, 0xff01ff01, 0x00000001, 0xff0100ff, 0x00000001, 0xff010000, 0x00000001, | |
| 377 | + 0xff010001, 0x00000001, 0xff0101ff, 0x00000001, 0xff010100, 0x00000001, 0x00ffff00, 0x00000001, | |
| 378 | + 0x00ff0000, 0x00000001, 0x00ff0001, 0x00000001, 0x00ff01ff, 0x00000001, 0x00ff0100, 0x00000001, | |
| 379 | + 0x00ff0101, 0x00000001, 0x0000ffff, 0x00000001, 0x0000ff00, 0x00000001, 0x0000ff01, 0x00000001, | |
| 380 | + 0x000000ff, 0x00000001, 0x00000000, 0x00000001, 0x00000001, 0x00000001, 0x000001ff, 0x00000001, | |
| 381 | + 0x00000100, 0x00000001, 0x00000101, 0x00000001, 0x0001ff00, 0x00000001, 0x000100ff, 0x00000001, | |
| 382 | + 0x00010000, 0x00000001, 0x00010100, 0x00000001, 0x01ffff01, 0x00000001, 0x01ff0000, 0x00000001, | |
| 383 | + 0x01ff0001, 0x00000001, 0x01ff01ff, 0x00000001, 0x01ff0100, 0x00000001, 0x01ff0101, 0x00000001, | |
| 384 | + 0x0100ff00, 0x00000001, 0x01000000, 0x00000001, 0x01000101, 0x00000001, 0x0101ff01, 0x00000001, | |
| 385 | + 0x01010000, 0x00000001, 0x01010001, 0x00000001, 0x010101ff, 0x00000001, 0x01010100, 0x00000001, | |
| 386 | + 0xffff00ff, 0x000001ff, 0xffff0000, 0x000001ff, 0xffff0001, 0x000001ff, 0xffff0100, 0x000001ff, | |
| 387 | + 0xff00ffff, 0x000001ff, 0xff000000, 0x000001ff, 0xff0001ff, 0x000001ff, 0xff01ff00, 0x000001ff, | |
| 388 | + 0xff010101, 0x000001ff, 0x00ff0000, 0x000001ff, 0x00ff01ff, 0x000001ff, 0x00ff0101, 0x000001ff, | |
| 389 | + 0x0000ff00, 0x000001ff, 0x000000ff, 0x000001ff, 0x00000000, 0x000001ff, 0x00000001, 0x000001ff, | |
| 390 | + 0x000001ff, 0x000001ff, 0x00000100, 0x000001ff, 0x0001ffff, 0x000001ff, 0x0001ff01, 0x000001ff, | |
| 391 | + 0x000100ff, 0x000001ff, 0x00010000, 0x000001ff, 0x01ffff01, 0x000001ff, 0x01ff0100, 0x000001ff, | |
| 392 | + 0x0100ffff, 0x000001ff, 0x0100ff01, 0x000001ff, 0x01000000, 0x000001ff, 0x010001ff, 0x000001ff, | |
| 393 | + 0x0101ff00, 0x000001ff, 0x01010100, 0x000001ff, 0xffffff00, 0x00000100, 0xffffff01, 0x00000100, | |
| 394 | + 0xffff0000, 0x00000100, 0xffff0101, 0x00000100, 0xff00ff00, 0x00000100, 0xff0000ff, 0x00000100, | |
| 395 | + 0xff000000, 0x00000100, 0xff000001, 0x00000100, 0xff000100, 0x00000100, 0xff010000, 0x00000100, | |
| 396 | + 0x00ffff00, 0x00000100, 0x00ff00ff, 0x00000100, 0x00ff0000, 0x00000100, 0x00ff0001, 0x00000100, | |
| 397 | + 0x00ff0100, 0x00000100, 0x0000ffff, 0x00000100, 0x0000ff00, 0x00000100, 0x0000ff01, 0x00000100, | |
| 398 | + 0x000000ff, 0x00000100, 0x00000000, 0x00000100, 0x00000001, 0x00000100, 0x000001ff, 0x00000100, | |
| 399 | + 0x00000100, 0x00000100, 0x00000101, 0x00000100, 0x0001ff00, 0x00000100, 0x000100ff, 0x00000100, | |
| 400 | + 0x00010000, 0x00000100, 0x00010001, 0x00000100, 0x00010100, 0x00000100, 0x01ffff00, 0x00000100, | |
| 401 | + 0x01ff0000, 0x00000100, 0x01ff0100, 0x00000100, 0x0100ff00, 0x00000100, 0x010000ff, 0x00000100, | |
| 402 | + 0x01000000, 0x00000100, 0x01000001, 0x00000100, 0x010001ff, 0x00000100, 0x01000100, 0x00000100, | |
| 403 | + 0x01010000, 0x00000100, 0xffff00ff, 0x00000101, 0xffff01ff, 0x00000101, 0xff000000, 0x00000101, | |
| 404 | + 0xff000101, 0x00000101, 0xff01ffff, 0x00000101, 0xff010000, 0x00000101, 0xff010001, 0x00000101, | |
| 405 | + 0xff010100, 0x00000101, 0x00ff0000, 0x00000101, 0x00ff01ff, 0x00000101, 0x00ff0100, 0x00000101, | |
| 406 | + 0x0000ff00, 0x00000101, 0x00000000, 0x00000101, 0x00000001, 0x00000101, 0x000001ff, 0x00000101, | |
| 407 | + 0x00000100, 0x00000101, 0x0001ff01, 0x00000101, 0x00010000, 0x00000101, 0x000101ff, 0x00000101, | |
| 408 | + 0x00010101, 0x00000101, 0x01ffff00, 0x00000101, 0x01ff0101, 0x00000101, 0x0100ff01, 0x00000101, | |
| 409 | + 0x01000000, 0x00000101, 0x01000001, 0x00000101, 0x010001ff, 0x00000101, 0x01000101, 0x00000101, | |
| 410 | + 0x0101ff00, 0x00000101, 0xffff0000, 0x0001ffff, 0xff0000ff, 0x0001ffff, 0xff000001, 0x0001ffff, | |
| 411 | + 0xff000100, 0x0001ffff, 0xff010000, 0x0001ffff, 0x00ff00ff, 0x0001ffff, 0x0000ffff, 0x0001ffff, | |
| 412 | + 0x00000000, 0x0001ffff, 0x00000001, 0x0001ffff, 0x000001ff, 0x0001ffff, 0x00000101, 0x0001ffff, | |
| 413 | + 0x0001ff00, 0x0001ffff, 0x000100ff, 0x0001ffff, 0x00010001, 0x0001ffff, 0x00010100, 0x0001ffff, | |
| 414 | + 0x01ffff00, 0x0001ffff, 0x01000001, 0x0001ffff, 0x01010000, 0x0001ffff, 0xffffff00, 0x0001ff00, | |
| 415 | + 0xffff00ff, 0x0001ff00, 0xffff0001, 0x0001ff00, 0xffff0100, 0x0001ff00, 0xff00ff01, 0x0001ff00, | |
| 416 | + 0xff000000, 0x0001ff00, 0xff01ff00, 0x0001ff00, 0xff01ff01, 0x0001ff00, 0xff010001, 0x0001ff00, | |
| 417 | + 0xff010100, 0x0001ff00, 0x00ff0000, 0x0001ff00, 0x00ff0100, 0x0001ff00, 0x0000ff00, 0x0001ff00, | |
| 418 | + 0x00000000, 0x0001ff00, 0x00000001, 0x0001ff00, 0x00000100, 0x0001ff00, 0x00010000, 0x0001ff00, | |
| 419 | + 0x00010001, 0x0001ff00, 0x00010101, 0x0001ff00, 0x01ff00ff, 0x0001ff00, 0x01ff0101, 0x0001ff00, | |
| 420 | + 0x0100ff01, 0x0001ff00, 0x01000000, 0x0001ff00, 0x0101ff00, 0x0001ff00, 0x01010001, 0x0001ff00, | |
| 421 | + 0x01010100, 0x0001ff00, 0xff00ff00, 0x0001ff01, 0xff000001, 0x0001ff01, 0xff000100, 0x0001ff01, | |
| 422 | + 0x00ffffff, 0x0001ff01, 0x00ffff00, 0x0001ff01, 0x00ff0001, 0x0001ff01, 0x00000000, 0x0001ff01, | |
| 423 | + 0x00000001, 0x0001ff01, 0x000001ff, 0x0001ff01, 0x0001ffff, 0x0001ff01, 0x01ff0000, 0x0001ff01, | |
| 424 | + 0x0100ff00, 0x0001ff01, 0x01000001, 0x0001ff01, 0x01010000, 0x0001ff01, 0xff00ff00, 0x000100ff, | |
| 425 | + 0xff00ff01, 0x000100ff, 0xff000000, 0x000100ff, 0xff000001, 0x000100ff, 0xff000101, 0x000100ff, | |
| 426 | + 0xff01ff00, 0x000100ff, 0xff010001, 0x000100ff, 0xff010100, 0x000100ff, 0x00ffffff, 0x000100ff, | |
| 427 | + 0x00ffff01, 0x000100ff, 0x00ff0000, 0x000100ff, 0x00ff01ff, 0x000100ff, 0x00ff0101, 0x000100ff, | |
| 428 | + 0x0000ff00, 0x000100ff, 0x000000ff, 0x000100ff, 0x00000000, 0x000100ff, 0x00000001, 0x000100ff, | |
| 429 | + 0x00000100, 0x000100ff, 0x00000101, 0x000100ff, 0x0001ffff, 0x000100ff, 0x0001ff01, 0x000100ff, | |
| 430 | + 0x00010000, 0x000100ff, 0x01ff00ff, 0x000100ff, 0x01ff0000, 0x000100ff, 0x01ff0100, 0x000100ff, | |
| 431 | + 0x0100ffff, 0x000100ff, 0x0100ff01, 0x000100ff, 0x010000ff, 0x000100ff, 0x01000000, 0x000100ff, | |
| 432 | + 0x01000001, 0x000100ff, 0x010001ff, 0x000100ff, 0x01000101, 0x000100ff, 0x0101ff00, 0x000100ff, | |
| 433 | + 0x010100ff, 0x000100ff, 0x01010100, 0x000100ff, 0xffff0000, 0x00010000, 0xffff01ff, 0x00010000, | |
| 434 | + 0xffff0101, 0x00010000, 0xff00ff00, 0x00010000, 0xff000000, 0x00010000, 0xff000001, 0x00010000, | |
| 435 | + 0xff000100, 0x00010000, 0x00ff00ff, 0x00010000, 0x00ff0000, 0x00010000, 0x00ff0001, 0x00010000, | |
| 436 | + 0x00ff0100, 0x00010000, 0x0000ffff, 0x00010000, 0x0000ff00, 0x00010000, 0x000000ff, 0x00010000, | |
| 437 | + 0x00000000, 0x00010000, 0x00000001, 0x00010000, 0x00000100, 0x00010000, 0x0001ff00, 0x00010000, | |
| 438 | + 0x000100ff, 0x00010000, 0x00010000, 0x00010000, 0x00010001, 0x00010000, 0x00010100, 0x00010000, | |
| 439 | + 0x01ff0001, 0x00010000, 0x01ff0100, 0x00010000, 0x01ff0101, 0x00010000, 0x0100ff00, 0x00010000, | |
| 440 | + 0x01000000, 0x00010000, 0x01000001, 0x00010000, 0x01000100, 0x00010000, 0x01000101, 0x00010000, | |
| 441 | + 0x0101ff01, 0x00010000, 0x01010000, 0x00010000, 0x01010001, 0x00010000, 0x010101ff, 0x00010000, | |
| 442 | + 0xffffff01, 0x00010001, 0xffff0100, 0x00010001, 0xff000000, 0x00010001, 0xff01ffff, 0x00010001, | |
| 443 | + 0xff010001, 0x00010001, 0xff0101ff, 0x00010001, 0xff010100, 0x00010001, 0x00ffffff, 0x00010001, | |
| 444 | + 0x00ff0000, 0x00010001, 0x00ff01ff, 0x00010001, 0x00ff0101, 0x00010001, 0x0000ff00, 0x00010001, | |
| 445 | + 0x000000ff, 0x00010001, 0x00000000, 0x00010001, 0x00000001, 0x00010001, 0x000001ff, 0x00010001, | |
| 446 | + 0x00000101, 0x00010001, 0x0001ffff, 0x00010001, 0x00010000, 0x00010001, 0x000101ff, 0x00010001, | |
| 447 | + 0x01ffffff, 0x00010001, 0x01ffff01, 0x00010001, 0x01ff0000, 0x00010001, 0x01ff0101, 0x00010001, | |
| 448 | + 0x010000ff, 0x00010001, 0x01000001, 0x00010001, 0x010001ff, 0x00010001, 0x01000100, 0x00010001, | |
| 449 | + 0x0101ffff, 0x00010001, 0x010100ff, 0x00010001, 0x01010001, 0x00010001, 0x01010101, 0x00010001, | |
| 450 | + 0xff000001, 0x000101ff, 0xff000100, 0x000101ff, 0xff010000, 0x000101ff, 0x00ffff00, 0x000101ff, | |
| 451 | + 0x0000ff01, 0x000101ff, 0x00000000, 0x000101ff, 0x00000101, 0x000101ff, 0x0001ff00, 0x000101ff, | |
| 452 | + 0x00010100, 0x000101ff, 0x01ff0000, 0x000101ff, 0x0100ff00, 0x000101ff, 0x010001ff, 0x000101ff, | |
| 453 | + 0x01010001, 0x000101ff, 0xffffff00, 0x00010100, 0xffff00ff, 0x00010100, 0xff00ffff, 0x00010100, | |
| 454 | + 0xff000000, 0x00010100, 0xff01ff00, 0x00010100, 0xff0100ff, 0x00010100, 0xff010001, 0x00010100, | |
| 455 | + 0xff010100, 0x00010100, 0x00ffffff, 0x00010100, 0x00ffff00, 0x00010100, 0x00ff0000, 0x00010100, | |
| 456 | + 0x00ff0001, 0x00010100, 0x00ff01ff, 0x00010100, 0x0000ff00, 0x00010100, 0x000000ff, 0x00010100, | |
| 457 | + 0x00000000, 0x00010100, 0x00000001, 0x00010100, 0x00000100, 0x00010100, 0x0001ffff, 0x00010100, | |
| 458 | + 0x00010000, 0x00010100, 0x00010101, 0x00010100, 0x01ffff01, 0x00010100, 0x01ff00ff, 0x00010100, | |
| 459 | + 0x01ff0101, 0x00010100, 0x01000000, 0x00010100, 0x0101ff00, 0x00010100, 0x010100ff, 0x00010100, | |
| 460 | + 0x01010000, 0x00010100, 0x01010100, 0x00010100, 0xff00ff00, 0x00010101, 0xff000001, 0x00010101, | |
| 461 | + 0xff0001ff, 0x00010101, 0x00ffff00, 0x00010101, 0x00ff00ff, 0x00010101, 0x00ff0100, 0x00010101, | |
| 462 | + 0x0000ffff, 0x00010101, 0x00000000, 0x00010101, 0x000001ff, 0x00010101, 0x00000101, 0x00010101, | |
| 463 | + 0x000100ff, 0x00010101, 0x00010000, 0x00010101, 0x00010100, 0x00010101, 0x01ff0001, 0x00010101, | |
| 464 | + 0x010000ff, 0x00010101, 0x010001ff, 0x00010101, 0x01000101, 0x00010101, 0x01010001, 0x00010101, | |
| 465 | + 0xffffffff, 0x01ffffff, 0xffffff01, 0x01ffffff, 0xffff01ff, 0x01ffffff, 0xffff0101, 0x01ffffff, | |
| 466 | + 0xff01ffff, 0x01ffffff, 0xff01ff01, 0x01ffffff, 0xff0101ff, 0x01ffffff, 0xff010101, 0x01ffffff, | |
| 467 | + 0x00ff0000, 0x01ffffff, 0x0000ffff, 0x01ffffff, 0x0000ff00, 0x01ffffff, 0x000000ff, 0x01ffffff, | |
| 468 | + 0x00000001, 0x01ffffff, 0x00000100, 0x01ffffff, 0x00010000, 0x01ffffff, 0x01ffffff, 0x01ffffff, | |
| 469 | + 0x01ffff01, 0x01ffffff, 0x01ff01ff, 0x01ffffff, 0x01ff0101, 0x01ffffff, 0x01000000, 0x01ffffff, | |
| 470 | + 0x0101ffff, 0x01ffffff, 0x0101ff01, 0x01ffffff, 0x010101ff, 0x01ffffff, 0x01010101, 0x01ffffff, | |
| 471 | + 0xffff0000, 0x01ffff00, 0xff00ff00, 0x01ffff00, 0xff0000ff, 0x01ffff00, 0xff000001, 0x01ffff00, | |
| 472 | + 0xff000100, 0x01ffff00, 0xff010000, 0x01ffff00, 0x00ffff00, 0x01ffff00, 0x00ff00ff, 0x01ffff00, | |
| 473 | + 0x00ff0100, 0x01ffff00, 0x0000ffff, 0x01ffff00, 0x0000ff01, 0x01ffff00, 0x00000000, 0x01ffff00, | |
| 474 | + 0x00000001, 0x01ffff00, 0x000001ff, 0x01ffff00, 0x00000100, 0x01ffff00, 0x000100ff, 0x01ffff00, | |
| 475 | + 0x00010001, 0x01ffff00, 0x00010100, 0x01ffff00, 0x01ff0000, 0x01ffff00, 0x01ff0100, 0x01ffff00, | |
| 476 | + 0x010000ff, 0x01ffff00, 0x01000001, 0x01ffff00, 0x01000100, 0x01ffff00, 0x01010000, 0x01ffff00, | |
| 477 | + 0xffffffff, 0x01ffff01, 0xffffff01, 0x01ffff01, 0xffff01ff, 0x01ffff01, 0xffff0101, 0x01ffff01, | |
| 478 | + 0xff000000, 0x01ffff01, 0xff01ffff, 0x01ffff01, 0xff01ff01, 0x01ffff01, 0xff0101ff, 0x01ffff01, | |
| 479 | + 0xff010101, 0x01ffff01, 0x0000ff00, 0x01ffff01, 0x000000ff, 0x01ffff01, 0x00000100, 0x01ffff01, | |
| 480 | + 0x00010000, 0x01ffff01, 0x01ffffff, 0x01ffff01, 0x01ffff01, 0x01ffff01, 0x01ff01ff, 0x01ffff01, | |
| 481 | + 0x01ff0101, 0x01ffff01, 0x01000000, 0x01ffff01, 0x0101ffff, 0x01ffff01, 0x0101ff01, 0x01ffff01, | |
| 482 | + 0x010101ff, 0x01ffff01, 0x01010101, 0x01ffff01, 0xff0000ff, 0x01ff00ff, 0xff000100, 0x01ff00ff, | |
| 483 | + 0x00ffff00, 0x01ff00ff, 0x00ff00ff, 0x01ff00ff, 0x0000ff00, 0x01ff00ff, 0x00000000, 0x01ff00ff, | |
| 484 | + 0x00000101, 0x01ff00ff, 0x0001ff00, 0x01ff00ff, 0x000100ff, 0x01ff00ff, 0x00010100, 0x01ff00ff, | |
| 485 | + 0x010000ff, 0x01ff00ff, 0x01000100, 0x01ff00ff, 0xffffff00, 0x01ff0000, 0xffff0100, 0x01ff0000, | |
| 486 | + 0xff00ff01, 0x01ff0000, 0xff000000, 0x01ff0000, 0xff000101, 0x01ff0000, 0xff010001, 0x01ff0000, | |
| 487 | + 0xff010100, 0x01ff0000, 0x00ffffff, 0x01ff0000, 0x00ffff00, 0x01ff0000, 0x00ff0000, 0x01ff0000, | |
| 488 | + 0x00ff01ff, 0x01ff0000, 0x0000ff00, 0x01ff0000, 0x000000ff, 0x01ff0000, 0x00000000, 0x01ff0000, | |
| 489 | + 0x00000001, 0x01ff0000, 0x00000100, 0x01ff0000, 0x00000101, 0x01ff0000, 0x00010000, 0x01ff0000, | |
| 490 | + 0x00010001, 0x01ff0000, 0x000101ff, 0x01ff0000, 0x00010101, 0x01ff0000, 0x01ffff00, 0x01ff0000, | |
| 491 | + 0x01ff00ff, 0x01ff0000, 0x01ff0001, 0x01ff0000, 0x01ff0100, 0x01ff0000, 0x0100ffff, 0x01ff0000, | |
| 492 | + 0x0100ff01, 0x01ff0000, 0x01000000, 0x01ff0000, 0x010001ff, 0x01ff0000, 0x01010001, 0x01ff0000, | |
| 493 | + 0xff00ff00, 0x01ff0001, 0xff000001, 0x01ff0001, 0xff000100, 0x01ff0001, 0xff010000, 0x01ff0001, | |
| 494 | + 0x00ffff00, 0x01ff0001, 0x00ff00ff, 0x01ff0001, 0x00ff0100, 0x01ff0001, 0x00ff0101, 0x01ff0001, | |
| 495 | + 0x0000ffff, 0x01ff0001, 0x00000000, 0x01ff0001, 0x00000100, 0x01ff0001, 0x00000101, 0x01ff0001, | |
| 496 | + 0x0001ff00, 0x01ff0001, 0x00010001, 0x01ff0001, 0x00010101, 0x01ff0001, 0x01ff0000, 0x01ff0001, | |
| 497 | + 0x0100ff00, 0x01ff0001, 0x01000101, 0x01ff0001, 0x010100ff, 0x01ff0001, 0xffffffff, 0x01ff01ff, | |
| 498 | + 0xffffff01, 0x01ff01ff, 0xffff01ff, 0x01ff01ff, 0xffff0101, 0x01ff01ff, 0xff000000, 0x01ff01ff, | |
| 499 | + 0xff01ffff, 0x01ff01ff, 0xff01ff01, 0x01ff01ff, 0xff0101ff, 0x01ff01ff, 0xff010101, 0x01ff01ff, | |
| 500 | + 0x00ffff00, 0x01ff01ff, 0x00ff0000, 0x01ff01ff, 0x0000ff00, 0x01ff01ff, 0x000000ff, 0x01ff01ff, | |
| 501 | + 0x00000100, 0x01ff01ff, 0x00010000, 0x01ff01ff, 0x00010100, 0x01ff01ff, 0x01ffffff, 0x01ff01ff, | |
| 502 | + 0x01ffff01, 0x01ff01ff, 0x01ff01ff, 0x01ff01ff, 0x01ff0101, 0x01ff01ff, 0x01000000, 0x01ff01ff, | |
| 503 | + 0x0101ffff, 0x01ff01ff, 0x0101ff01, 0x01ff01ff, 0x010101ff, 0x01ff01ff, 0x01010101, 0x01ff01ff, | |
| 504 | + 0xffff0000, 0x01ff0100, 0xffff0001, 0x01ff0100, 0xff00ff00, 0x01ff0100, 0xff0000ff, 0x01ff0100, | |
| 505 | + 0xff000001, 0x01ff0100, 0xff010000, 0x01ff0100, 0x00ffff00, 0x01ff0100, 0x00ff00ff, 0x01ff0100, | |
| 506 | + 0x00ff0001, 0x01ff0100, 0x00ff0100, 0x01ff0100, 0x0000ffff, 0x01ff0100, 0x0000ff01, 0x01ff0100, | |
| 507 | + 0x00000000, 0x01ff0100, 0x00000101, 0x01ff0100, 0x0001ff00, 0x01ff0100, 0x000100ff, 0x01ff0100, | |
| 508 | + 0x01ff0000, 0x01ff0100, 0x01000001, 0x01ff0100, 0x01000100, 0x01ff0100, 0x01010000, 0x01ff0100, | |
| 509 | + 0xffffffff, 0x01ff0101, 0xffffff01, 0x01ff0101, 0xffff01ff, 0x01ff0101, 0xffff0101, 0x01ff0101, | |
| 510 | + 0xff000000, 0x01ff0101, 0xff01ffff, 0x01ff0101, 0xff01ff01, 0x01ff0101, 0xff0101ff, 0x01ff0101, | |
| 511 | + 0xff010101, 0x01ff0101, 0x00ff0000, 0x01ff0101, 0x0000ff00, 0x01ff0101, 0x000000ff, 0x01ff0101, | |
| 512 | + 0x00000001, 0x01ff0101, 0x01ffffff, 0x01ff0101, 0x01ffff01, 0x01ff0101, 0x01ff01ff, 0x01ff0101, | |
| 513 | + 0x01ff0101, 0x01ff0101, 0x01000000, 0x01ff0101, 0x0101ffff, 0x01ff0101, 0x0101ff01, 0x01ff0101, | |
| 514 | + 0x010101ff, 0x01ff0101, 0x01010101, 0x01ff0101, 0xffff0000, 0x0100ffff, 0xff00ff00, 0x0100ffff, | |
| 515 | + 0xff000001, 0x0100ffff, 0xff0001ff, 0x0100ffff, 0xff000100, 0x0100ffff, 0xff010000, 0x0100ffff, | |
| 516 | + 0x00ffff00, 0x0100ffff, 0x00ff0001, 0x0100ffff, 0x00ff0100, 0x0100ffff, 0x00000000, 0x0100ffff, | |
| 517 | + 0x000001ff, 0x0100ffff, 0x00000101, 0x0100ffff, 0x00010100, 0x0100ffff, 0x00010101, 0x0100ffff, | |
| 518 | + 0x01ff0000, 0x0100ffff, 0x0100ff00, 0x0100ffff, 0x010000ff, 0x0100ffff, 0x01000001, 0x0100ffff, | |
| 519 | + 0x01000100, 0x0100ffff, 0x01010000, 0x0100ffff, 0xffffff00, 0x0100ff00, 0xffff00ff, 0x0100ff00, | |
| 520 | + 0xffff0001, 0x0100ff00, 0xffff0100, 0x0100ff00, 0xff00ffff, 0x0100ff00, 0xff000000, 0x0100ff00, | |
| 521 | + 0xff0001ff, 0x0100ff00, 0xff000101, 0x0100ff00, 0xff01ff00, 0x0100ff00, 0xff0100ff, 0x0100ff00, | |
| 522 | + 0xff010001, 0x0100ff00, 0xff010100, 0x0100ff00, 0x00ffffff, 0x0100ff00, 0x00ff0000, 0x0100ff00, | |
| 523 | + 0x0000ffff, 0x0100ff00, 0x0000ff00, 0x0100ff00, 0x000000ff, 0x0100ff00, 0x00000000, 0x0100ff00, | |
| 524 | + 0x00000001, 0x0100ff00, 0x00000100, 0x0100ff00, 0x0001ff01, 0x0100ff00, 0x00010000, 0x0100ff00, | |
| 525 | + 0x01ff00ff, 0x0100ff00, 0x01ff0001, 0x0100ff00, 0x0100ff01, 0x0100ff00, 0x01000000, 0x0100ff00, | |
| 526 | + 0x010001ff, 0x0100ff00, 0x0101ff00, 0x0100ff00, 0x010100ff, 0x0100ff00, 0x01010001, 0x0100ff00, | |
| 527 | + 0x01010100, 0x0100ff00, 0xffff0000, 0x0100ff01, 0xff00ff00, 0x0100ff01, 0xff0000ff, 0x0100ff01, | |
| 528 | + 0xff000100, 0x0100ff01, 0xff010000, 0x0100ff01, 0x00ff00ff, 0x0100ff01, 0x00ff0001, 0x0100ff01, | |
| 529 | + 0x00ff0100, 0x0100ff01, 0x0000ffff, 0x0100ff01, 0x0000ff01, 0x0100ff01, 0x00000000, 0x0100ff01, | |
| 530 | + 0x000001ff, 0x0100ff01, 0x00010001, 0x0100ff01, 0x00010100, 0x0100ff01, 0x01ff0000, 0x0100ff01, | |
| 531 | + 0x010000ff, 0x0100ff01, 0x01000001, 0x0100ff01, 0x01010100, 0x0100ff01, 0xffffff00, 0x010000ff, | |
| 532 | + 0xffff00ff, 0x010000ff, 0xffff0001, 0x010000ff, 0xff00ffff, 0x010000ff, 0xff000000, 0x010000ff, | |
| 533 | + 0xff0001ff, 0x010000ff, 0xff010001, 0x010000ff, 0x00ffffff, 0x010000ff, 0x00ff0101, 0x010000ff, | |
| 534 | + 0x0000ff00, 0x010000ff, 0x000000ff, 0x010000ff, 0x00000000, 0x010000ff, 0x00000001, 0x010000ff, | |
| 535 | + 0x000001ff, 0x010000ff, 0x00000100, 0x010000ff, 0x0001ffff, 0x010000ff, 0x0001ff00, 0x010000ff, | |
| 536 | + 0x0001ff01, 0x010000ff, 0x00010000, 0x010000ff, 0x01ff00ff, 0x010000ff, 0x01ff0001, 0x010000ff, | |
| 537 | + 0x0100ff01, 0x010000ff, 0x010000ff, 0x010000ff, 0x01000000, 0x010000ff, 0x010001ff, 0x010000ff, | |
| 538 | + 0x0101ff00, 0x010000ff, 0x01010100, 0x010000ff, 0xffffffff, 0x01000000, 0xffff0000, 0x01000000, | |
| 539 | + 0xffff01ff, 0x01000000, 0xffff0101, 0x01000000, 0xff00ffff, 0x01000000, 0xff00ff00, 0x01000000, | |
| 540 | + 0xff0000ff, 0x01000000, 0xff000000, 0x01000000, 0xff000001, 0x01000000, 0xff000100, 0x01000000, | |
| 541 | + 0xff01ff00, 0x01000000, 0xff010000, 0x01000000, 0xff010100, 0x01000000, 0xff010101, 0x01000000, | |
| 542 | + 0x00ffff00, 0x01000000, 0x00ff00ff, 0x01000000, 0x00ff0000, 0x01000000, 0x00ff0001, 0x01000000, | |
| 543 | + 0x00ff0100, 0x01000000, 0x0000ffff, 0x01000000, 0x0000ff00, 0x01000000, 0x0000ff01, 0x01000000, | |
| 544 | + 0x000000ff, 0x01000000, 0x00000000, 0x01000000, 0x00000001, 0x01000000, 0x000001ff, 0x01000000, | |
| 545 | + 0x00000100, 0x01000000, 0x00000101, 0x01000000, 0x0001ff00, 0x01000000, 0x000100ff, 0x01000000, | |
| 546 | + 0x00010000, 0x01000000, 0x00010001, 0x01000000, 0x00010100, 0x01000000, 0x01ffff00, 0x01000000, | |
| 547 | + 0x01ff0000, 0x01000000, 0x01ff01ff, 0x01000000, 0x0100ff00, 0x01000000, 0x0100ff01, 0x01000000, | |
| 548 | + 0x010000ff, 0x01000000, 0x01000000, 0x01000000, 0x01000001, 0x01000000, 0x01000100, 0x01000000, | |
| 549 | + 0x01000101, 0x01000000, 0x0101ffff, 0x01000000, 0x0101ff01, 0x01000000, 0x01010000, 0x01000000, | |
| 550 | + 0x010101ff, 0x01000000, 0x01010101, 0x01000000, 0xffffff00, 0x01000001, 0xffff00ff, 0x01000001, | |
| 551 | + 0xff00ffff, 0x01000001, 0xff000000, 0x01000001, 0xff000100, 0x01000001, 0xff01ffff, 0x01000001, | |
| 552 | + 0xff010001, 0x01000001, 0xff010100, 0x01000001, 0x00ff0000, 0x01000001, 0x00ff01ff, 0x01000001, | |
| 553 | + 0x00ff0100, 0x01000001, 0x0000ff00, 0x01000001, 0x0000ff01, 0x01000001, 0x00000000, 0x01000001, | |
| 554 | + 0x00000001, 0x01000001, 0x00000100, 0x01000001, 0x00010000, 0x01000001, 0x000101ff, 0x01000001, | |
| 555 | + 0x01ffff01, 0x01000001, 0x01ff00ff, 0x01000001, 0x01ff0100, 0x01000001, 0x01ff0101, 0x01000001, | |
| 556 | + 0x0100ff01, 0x01000001, 0x010000ff, 0x01000001, 0x01000000, 0x01000001, 0x010100ff, 0x01000001, | |
| 557 | + 0x01010001, 0x01000001, 0x01010100, 0x01000001, 0xffff0000, 0x010001ff, 0xff000001, 0x010001ff, | |
| 558 | + 0xff000100, 0x010001ff, 0xff010000, 0x010001ff, 0x00ffff00, 0x010001ff, 0x00ff0001, 0x010001ff, | |
| 559 | + 0x0000ffff, 0x010001ff, 0x0000ff01, 0x010001ff, 0x00000000, 0x010001ff, 0x00000001, 0x010001ff, | |
| 560 | + 0x00000101, 0x010001ff, 0x000100ff, 0x010001ff, 0x00010000, 0x010001ff, 0x01ff0000, 0x010001ff, | |
| 561 | + 0x0100ff00, 0x010001ff, 0x01000001, 0x010001ff, 0x01000100, 0x010001ff, 0x01010000, 0x010001ff, | |
| 562 | + 0xffff00ff, 0x01000100, 0xffff0001, 0x01000100, 0xffff0100, 0x01000100, 0xff00ffff, 0x01000100, | |
| 563 | + 0xff00ff01, 0x01000100, 0xff000000, 0x01000100, 0xff0001ff, 0x01000100, 0xff000101, 0x01000100, | |
| 564 | + 0xff01ffff, 0x01000100, 0xff01ff00, 0x01000100, 0xff0100ff, 0x01000100, 0xff010001, 0x01000100, | |
| 565 | + 0x00ffffff, 0x01000100, 0x00ffff01, 0x01000100, 0x00ff0000, 0x01000100, 0x00ff01ff, 0x01000100, | |
| 566 | + 0x00ff0101, 0x01000100, 0x0000ff00, 0x01000100, 0x000000ff, 0x01000100, 0x00000000, 0x01000100, | |
| 567 | + 0x00000001, 0x01000100, 0x00000100, 0x01000100, 0x0001ff01, 0x01000100, 0x00010000, 0x01000100, | |
| 568 | + 0x00010001, 0x01000100, 0x00010101, 0x01000100, 0x01ffff00, 0x01000100, 0x01ff00ff, 0x01000100, | |
| 569 | + 0x0100ffff, 0x01000100, 0x0100ff01, 0x01000100, 0x01000000, 0x01000100, 0x01000101, 0x01000100, | |
| 570 | + 0x0101ff00, 0x01000100, 0x01010001, 0x01000100, 0xffff0000, 0x01000101, 0xff000000, 0x01000101, | |
| 571 | + 0xff010000, 0x01000101, 0x00ff00ff, 0x01000101, 0x00ff0001, 0x01000101, 0x00ff0100, 0x01000101, | |
| 572 | + 0x0000ffff, 0x01000101, 0x00000000, 0x01000101, 0x000001ff, 0x01000101, 0x0001ff00, 0x01000101, | |
| 573 | + 0x01ff0000, 0x01000101, 0x0100ff00, 0x01000101, 0x010000ff, 0x01000101, 0x01000000, 0x01000101, | |
| 574 | + 0x01000001, 0x01000101, 0xffffffff, 0x0101ffff, 0xffffff01, 0x0101ffff, 0xffff01ff, 0x0101ffff, | |
| 575 | + 0xffff0101, 0x0101ffff, 0xff000000, 0x0101ffff, 0xff01ffff, 0x0101ffff, 0xff01ff01, 0x0101ffff, | |
| 576 | + 0xff0101ff, 0x0101ffff, 0xff010101, 0x0101ffff, 0x00ff0000, 0x0101ffff, 0x0000ff00, 0x0101ffff, | |
| 577 | + 0x000000ff, 0x0101ffff, 0x00000001, 0x0101ffff, 0x00000100, 0x0101ffff, 0x01ffffff, 0x0101ffff, | |
| 578 | + 0x01ffff01, 0x0101ffff, 0x01ff01ff, 0x0101ffff, 0x01ff0101, 0x0101ffff, 0x01000000, 0x0101ffff, | |
| 579 | + 0x0101ffff, 0x0101ffff, 0x0101ff01, 0x0101ffff, 0x010101ff, 0x0101ffff, 0x01010101, 0x0101ffff, | |
| 580 | + 0xffff0000, 0x0101ff00, 0xffff0100, 0x0101ff00, 0xff00ff00, 0x0101ff00, 0xff0000ff, 0x0101ff00, | |
| 581 | + 0xff000001, 0x0101ff00, 0xff000100, 0x0101ff00, 0xff000101, 0x0101ff00, 0x00ff0001, 0x0101ff00, | |
| 582 | + 0x00ff0100, 0x0101ff00, 0x0000ff00, 0x0101ff00, 0x00000000, 0x0101ff00, 0x000001ff, 0x0101ff00, | |
| 583 | + 0x00000101, 0x0101ff00, 0x0001ff00, 0x0101ff00, 0x000100ff, 0x0101ff00, 0x01ff0000, 0x0101ff00, | |
| 584 | + 0x0100ffff, 0x0101ff00, 0x0100ff01, 0x0101ff00, 0x01000001, 0x0101ff00, 0x01000100, 0x0101ff00, | |
| 585 | + 0xffffff01, 0x0101ff01, 0xffff01ff, 0x0101ff01, 0xffff0101, 0x0101ff01, 0xff00ffff, 0x0101ff01, | |
| 586 | + 0xff000100, 0x0101ff01, 0xff01ff01, 0x0101ff01, 0xff0101ff, 0x0101ff01, 0xff010101, 0x0101ff01, | |
| 587 | + 0x00ff0000, 0x0101ff01, 0x0000ff00, 0x0101ff01, 0x00000001, 0x0101ff01, 0x00000100, 0x0101ff01, | |
| 588 | + 0x00010000, 0x0101ff01, 0x01ffffff, 0x0101ff01, 0x01ffff01, 0x0101ff01, 0x01ff01ff, 0x0101ff01, | |
| 589 | + 0x01ff0101, 0x0101ff01, 0x01000000, 0x0101ff01, 0x0101ffff, 0x0101ff01, 0x0101ff01, 0x0101ff01, | |
| 590 | + 0x010101ff, 0x0101ff01, 0x01010101, 0x0101ff01, 0xff000100, 0x010100ff, 0xff010000, 0x010100ff, | |
| 591 | + 0x00ffff00, 0x010100ff, 0x00ff00ff, 0x010100ff, 0x0000ffff, 0x010100ff, 0x000000ff, 0x010100ff, | |
| 592 | + 0x00000000, 0x010100ff, 0x000001ff, 0x010100ff, 0x00000101, 0x010100ff, 0x0001ff00, 0x010100ff, | |
| 593 | + 0x00010000, 0x010100ff, 0x00010001, 0x010100ff, 0x000101ff, 0x010100ff, 0x00010100, 0x010100ff, | |
| 594 | + 0x01ff0000, 0x010100ff, 0xffff0001, 0x01010000, 0xffff0100, 0x01010000, 0xff00ffff, 0x01010000, | |
| 595 | + 0xff00ff01, 0x01010000, 0xff000000, 0x01010000, 0xff0001ff, 0x01010000, 0xff010001, 0x01010000, | |
| 596 | + 0xff010100, 0x01010000, 0x00ffff01, 0x01010000, 0x00ff0000, 0x01010000, 0x0000ff00, 0x01010000, | |
| 597 | + 0x000000ff, 0x01010000, 0x00000000, 0x01010000, 0x00000001, 0x01010000, 0x00000100, 0x01010000, | |
| 598 | + 0x00010000, 0x01010000, 0x00010101, 0x01010000, 0x01ffff00, 0x01010000, 0x01ff00ff, 0x01010000, | |
| 599 | + 0x01ff0000, 0x01010000, 0x01ff0001, 0x01010000, 0x01ff0100, 0x01010000, 0x0100ff01, 0x01010000, | |
| 600 | + 0x01000000, 0x01010000, 0x010001ff, 0x01010000, 0xffff0000, 0x01010001, 0xff00ff00, 0x01010001, | |
| 601 | + 0xff000001, 0x01010001, 0xff000101, 0x01010001, 0xff01ff00, 0x01010001, 0xff010000, 0x01010001, | |
| 602 | + 0x00ff00ff, 0x01010001, 0x00ff0001, 0x01010001, 0x00ff0101, 0x01010001, 0x0000ff01, 0x01010001, | |
| 603 | + 0x00000000, 0x01010001, 0x00000001, 0x01010001, 0x000001ff, 0x01010001, 0x0001ffff, 0x01010001, | |
| 604 | + 0x0001ff01, 0x01010001, 0x01ff0001, 0x01010001, 0x0100ffff, 0x01010001, 0x01000000, 0x01010001, | |
| 605 | + 0x01000001, 0x01010001, 0x01000100, 0x01010001, 0x0101ff00, 0x01010001, 0x010100ff, 0x01010001, | |
| 606 | + 0x01010001, 0x01010001, 0xffffffff, 0x010101ff, 0xffffff01, 0x010101ff, 0xffff01ff, 0x010101ff, | |
| 607 | + 0xffff0101, 0x010101ff, 0xff01ffff, 0x010101ff, 0xff01ff01, 0x010101ff, 0xff0101ff, 0x010101ff, | |
| 608 | + 0xff010101, 0x010101ff, 0x0000ff00, 0x010101ff, 0x000000ff, 0x010101ff, 0x00000001, 0x010101ff, | |
| 609 | + 0x00000100, 0x010101ff, 0x01ffffff, 0x010101ff, 0x01ffff01, 0x010101ff, 0x01ff01ff, 0x010101ff, | |
| 610 | + 0x01ff0101, 0x010101ff, 0x01000000, 0x010101ff, 0x0101ffff, 0x010101ff, 0x0101ff01, 0x010101ff, | |
| 611 | + 0x010101ff, 0x010101ff, 0x01010101, 0x010101ff, 0xffff0000, 0x01010100, 0xff0000ff, 0x01010100, | |
| 612 | + 0xff000100, 0x01010100, 0xff01ff00, 0x01010100, 0xff010000, 0x01010100, 0x00ffff00, 0x01010100, | |
| 613 | + 0x0000ffff, 0x01010100, 0x00000000, 0x01010100, 0x00000101, 0x01010100, 0x0001ff00, 0x01010100, | |
| 614 | + 0x00010001, 0x01010100, 0x00010100, 0x01010100, 0x0100ffff, 0x01010100, 0x01000001, 0x01010100, | |
| 615 | + 0xffffffff, 0x01010101, 0xffffff01, 0x01010101, 0xffff01ff, 0x01010101, 0xffff0101, 0x01010101, | |
| 616 | + 0xff01ffff, 0x01010101, 0xff01ff01, 0x01010101, 0xff0101ff, 0x01010101, 0xff010101, 0x01010101, | |
| 617 | + 0x0000ff00, 0x01010101, 0x000000ff, 0x01010101, 0x00000001, 0x01010101, 0x01ffffff, 0x01010101, | |
| 618 | + 0x01ffff01, 0x01010101, 0x01ff01ff, 0x01010101, 0x01ff0101, 0x01010101, 0x01000000, 0x01010101, | |
| 619 | + 0x0101ffff, 0x01010101, 0x0101ff01, 0x01010101, 0x010101ff, 0x01010101, 0x01010101, 0x01010101, | |
| 620 | +]); |
added js/registro.js +209 −0
| @@ -0,0 +1,209 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · el REGISTRO de modelos: qué hay, dónde vive y cómo se lee. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// Vive aparte del proveedor por una razón concreta: la app necesita SONDEAR si | |
| 6 | +// un modelo está disponible antes de ofrecerlo en el selector, y hacerlo | |
| 7 | +// importando el proveedor entero costaría traerse el motor completo a todo el | |
| 8 | +// que abra la página sin usarlo nunca. | |
| 9 | +// | |
| 10 | +// Tener las URLs en dos sitios ya salió mal una vez: cuando el 27B pasó de ser | |
| 11 | +// un fichero suelto a dos fragmentos en dos hosts, el sondeo de la app se quedó | |
| 12 | +// apuntando a la URL VIEJA, y nada lo habría dicho hasta que esa URL dejara de | |
| 13 | +// responder. Una sola fuente. | |
| 14 | +// | |
| 15 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 16 | + | |
| 17 | +// Registro de modelos. `bytes` no es decorativo: se compara con el | |
| 18 | +// content-length real y avisa si el fichero de origen ha cambiado, porque un | |
| 19 | +// cambio de cuantización aguas arriba altera la salida sin previo aviso. | |
| 20 | +export const MODELS = { | |
| 21 | + // MiniCPM5-2B en Q8_0. | |
| 22 | + // | |
| 23 | + // Entra sin tocar el motor porque su GGUF declara `general.architecture = | |
| 24 | + // llama`, que ya se lee. Es un transformer PURO: las 42 capas son de atención | |
| 25 | + // y las 42 pagan contexto, así que no tiene la ventaja del híbrido —en los | |
| 26 | + // Qwen la mayoría de los bloques son SSM con estado de tamaño fijo— y su | |
| 27 | + // caché KV por ficha es casi la del 27B teniendo diez veces menos parámetros. | |
| 28 | + // | |
| 29 | + // El fichero declara un contexto de 131.072 y aquí se pide 65.536. Lo que | |
| 30 | + // manda no es el modelo, es lo que cuesta su KV: a 131k en f16 no cabe en el | |
| 31 | + // presupuesto de una pestaña, y a 65k sí. Con la KV a 8 bits —no implementada | |
| 32 | + // todavía, hoy solo hay f16 y f32— el contexto declarado sería alcanzable. | |
| 33 | + // | |
| 34 | + // Q8_0 y no algo más pequeño a propósito: es uno de los dos únicos tipos que | |
| 35 | + // entran por el GEMM teselado del prefill. Un Q4_K cae al camino por filas y | |
| 36 | + // paga una relectura de los pesos POR CADA ficha del lote. | |
| 37 | + 'minicpm5-2b': { | |
| 38 | + label: 'MiniCPM5 2B · Q8_0', | |
| 39 | + url: 'https://m1.elffuss.com/minicpm5-2b.q8', | |
| 40 | + bytes: 2679710688, | |
| 41 | + ctx: 65536, | |
| 42 | + // RAZONA, con presupuesto amplio. En tareas de agente, con el razonamiento | |
| 43 | + // cerrado se paraba al segundo paso sin tocar ningún fichero, y razonando sí | |
| 44 | + // avanzaba; darle más presupuesto que este no lo mejoraba. provider.js abre | |
| 45 | + // el bloque y cuenta el razonamiento dentro de este tope. | |
| 46 | + razona: true, | |
| 47 | + presupuesto: 4000, | |
| 48 | + }, | |
| 49 | + | |
| 50 | + 'qwen35-0.8b': { | |
| 51 | + label: 'Qwen3.5 0.8B · Q8_0', | |
| 52 | + url: 'https://huggingface.co/ggml-org/Qwen3.5-0.8B-GGUF/resolve/main/Qwen3.5-0.8B-Q8_0.gguf', | |
| 53 | + bytes: 833592096, | |
| 54 | + // 64k, medido en los dos modelos: la reserva funciona y el prefill NO cambia | |
| 55 | + // (el contexto cuesta memoria, no tiempo — solo se paga por los tokens que | |
| 56 | + // de verdad se procesan). Con la caché en f16 son la mitad de bytes que la | |
| 57 | + // cuenta de antes: el modelo grande pide la mitad de memoria para la misma | |
| 58 | + // ventana. | |
| 59 | + // | |
| 60 | + // Si no cupiera, `provider.js` baja por mitades hasta 2048 en vez de dejar | |
| 61 | + // al usuario sin modelo: un contexto de 16k sigue siendo ocho veces el de | |
| 62 | + // antes y no se parece en nada a no tener modelo. | |
| 63 | + ctx: 65536, | |
| 64 | + }, | |
| 65 | + // El 27B, en dos fragmentos. Es una opción avanzada por lo que CUESTA, no por | |
| 66 | + // lo que falle: la descarga es grande y el prefill de un prompt largo, lento; | |
| 67 | + // el retraso cae entero antes del primer token. llama.cpp no lee su formato, | |
| 68 | + // así que se comprueba internamente por piezas —el formato contra su | |
| 69 | + // definición publicada, la rotación contra la matriz explícita, que se aplique | |
| 70 | + // a todos los tensores que la declaran— y de extremo a extremo: que conteste | |
| 71 | + // con sentido. | |
| 72 | + // | |
| 73 | + // El `bytes` es el del fichero verificado: si el de origen cambia de | |
| 74 | + // cuantización, la salida cambia sin avisar y esto lo caza. | |
| 75 | + 'qwen38-27b': { | |
| 76 | + // El id es el de antes por compatibilidad (las apps lo escriben a mano); el | |
| 77 | + // modelo es el ternario de Prism ML. Frente a las alternativas del mismo | |
| 78 | + // tamaño, su matmul gana porque NO hay codebook: el peso sale de un | |
| 79 | + // desplazamiento y una máscara, no de una tabla de rejilla con gather | |
| 80 | + // disperso por carril. | |
| 81 | + // | |
| 82 | + // Se elige el formato PQ2_0 y no el PTQ1_0 aunque ocupe más: 128 pesos a | |
| 83 | + // 2 bits son 32 bytes JUSTOS y, con subgrupos de 32 carriles, toca un byte | |
| 84 | + // por carril, sin divergencia. El de base 3 reparte en tres etapas de tamaños | |
| 85 | + // distintos y va 1,53x más lento. Y se puede trasladar la medida de calidad | |
| 86 | + // entre los dos porque guardan los MISMOS pesos bit a bit (comprobado en 4 | |
| 87 | + // tensores, 20.480 valores). | |
| 88 | + // | |
| 89 | + // ⚠️ Requiere la rotación de Hadamard sobre las activaciones: el fichero la | |
| 90 | + // declara en sus metadatos y `hadamard.js` la aplica. Un motor que no la | |
| 91 | + // tenga NO falla — carga y devuelve ruido. | |
| 92 | + label: 'Bonsai 27B · ternario', | |
| 93 | + // Servido desde el host del BROKER, no desde la web. Ahí el broker lo lee | |
| 94 | + // en su MISMO origen (sin CORS de por medio) y lo guarda en el almacén de | |
| 95 | + // ese origen, pensado para que las webs de Elffuss no se lo bajen cada una. | |
| 96 | + // Y el host deja leerlo por CORS a las webs de Elffuss, así que desde ellas | |
| 97 | + // el camino directo —sin broker— también funciona. | |
| 98 | + // | |
| 99 | + // Servido desde la propia web era IMPOSIBLE compartirlo: el broker vive en | |
| 100 | + // otro origen y sin CORS su fetch fallaba con «Failed to fetch», sin más | |
| 101 | + // explicación. | |
| 102 | + // REPARTIDO entre dos hosts, y la razón es medible: la cuota del navegador | |
| 103 | + // es POR ORIGEN. En uno solo el modelo entero no cabía fiable; en dos, cada | |
| 104 | + // mitad va sobrada. Y como los dos son subdominios del mismo sitio, lo | |
| 105 | + // guardado puede servir a las demás webs de Elffuss sin volver a bajarlo. | |
| 106 | + // | |
| 107 | + // `bytes` por fragmento NO es decorativo: si uno cambia de tamaño, las | |
| 108 | + // fronteras se desplazan y todo lo que venga detrás se lee corrido — basura | |
| 109 | + // sin un solo error. | |
| 110 | + url: [ | |
| 111 | + { url: 'https://m1.elffuss.com/bonsai-27b.p0', bytes: 3602907136 }, | |
| 112 | + { url: 'https://m2.elffuss.com/bonsai-27b.p1', bytes: 3603261792 }, | |
| 113 | + ], | |
| 114 | + // El tamaño exacto del fichero servido (los dos fragmentos juntos): si | |
| 115 | + // cambia, el motor avisa en cada carga de que el origen ha cambiado. | |
| 116 | + bytes: 7206168928, | |
| 117 | + // 512 era INVIABLE y no por poco: el prompt de sistema de Elffuss son 626 | |
| 118 | + // tokens él solo (medido con este mismo tokenizador), así que la caché KV | |
| 119 | + // reventaba —«la caché se llena»— antes de que el usuario escribiera nada. | |
| 120 | + // El modelo no fallaba: no llegaba a ver la pregunta. | |
| 121 | + // | |
| 122 | + // Subirlo NO cuesta tiempo, cuesta memoria: `ctx` solo dimensiona la caché | |
| 123 | + // KV (cuatro veces más a 2048 que a 512). El prefill lo paga el número de | |
| 124 | + // tokens que se procesan de verdad, que es el mismo. Bajarlo para «ir más | |
| 125 | + // rápido» fue confundir las dos cosas. | |
| 126 | + ctx: 65536, // ver la nota del modelo pequeño: medido, y con red si no cabe | |
| 127 | + // SE CACHEA: el almacén del anfitrión lo guarda entre visitas, y la segunda | |
| 128 | + // carga no vuelve a pedirlo por red. | |
| 129 | + cache: true, | |
| 130 | + // El muestreo de la ficha de Prism para responder SIN razonar (que es como | |
| 131 | + // lo usa el motor): 0,7 / 0,8 / top-k 20 / min-p 0 / presence 1,5, y sin la | |
| 132 | + // penalización de repetición: es lo que recomienda quien lo cuantizó. Y | |
| 133 | + // respuestas de hasta 2000 fichas: escribe ficheros enteros, y 512 los | |
| 134 | + // cortaba. | |
| 135 | + muestreo: { temperature: 0.7, topP: 0.8, topK: 20, minP: 0, presence: 1.5, repeatPenalty: 1 }, | |
| 136 | + tope: 2000, | |
| 137 | + // El prompt compacto ESTUVO aquí y se ha quitado. La razón de ponerlo era | |
| 138 | + // de velocidad: el completo tarda más en procesarse y el usuario espera | |
| 139 | + // mirando una caja quieta. Pero un prompt recortado deja al modelo sin | |
| 140 | + // saber hacer tareas, y un asistente que carga, responde y no sirve para | |
| 141 | + // nada es peor que uno lento — probado en uso real, no en un banco. | |
| 142 | + // | |
| 143 | + // El coste de volver al prompt completo es un primer prefill más largo. | |
| 144 | + // Eso se ataca donde toca: reutilizando el prefijo entre turnos (ya hecho, | |
| 145 | + // ver provider.js) y guardando la foto del estado entre SESIONES, que es lo | |
| 146 | + // que hace que se pague una vez y no cada vez que se abre la web. | |
| 147 | + }, | |
| 148 | +}; | |
| 149 | + | |
| 150 | +// ¿Se puede usar este modelo AHORA? Se pregunta a los ficheros de verdad, con | |
| 151 | +// una petición de un solo byte por fragmento: comprueba de paso que el host | |
| 152 | +// responda, que admita rangos y que el CORS deje leerlo, que es exactamente lo | |
| 153 | +// que hará la carga después. Ofrecer una opción que falla al elegirla es peor | |
| 154 | +// que no ofrecerla. | |
| 155 | +// Todos los ORIGENES donde puede haber pesos guardados. | |
| 156 | +// | |
| 157 | +// Cada fragmento lo guarda el broker de SU PROPIO host (ver `model-broker.js`), | |
| 158 | +// asi que un modelo repartido entre dos servidores ocupa DOS origenes. El panel | |
| 159 | +// de almacenamiento preguntaba solo al broker por defecto y por eso enseñaba | |
| 160 | +// una fraccion: con el 27B guardado en m1 y m2, el contador miraba a un tercer | |
| 161 | +// origen que no tiene nada. Una cifra de ocupacion que no suma donde estan los | |
| 162 | +// bytes es peor que no tenerla, porque parece exacta. | |
| 163 | +export function origenesAlmacen() { | |
| 164 | + // Solo los origenes NUESTROS: un modelo servido desde un tercero (Hugging | |
| 165 | + // Face, por ejemplo) no tiene nuestra pagina de broker, asi que preguntarle | |
| 166 | + // no devolveria nada y ademas costaria la espera entera del timeout, con el | |
| 167 | + // panel colgado por un origen que nunca iba a responder. | |
| 168 | + const NUESTRO = /(^|\.)elffuss\.com$|(^|\.)utopiaia\.com$|^localhost$/; | |
| 169 | + const o = new Set(); | |
| 170 | + for (const m of Object.values(MODELS)) { | |
| 171 | + const urls = Array.isArray(m.url) ? m.url.map(f => f.url) : (m.url ? [m.url] : []); | |
| 172 | + for (const u of urls) { | |
| 173 | + try { | |
| 174 | + const { hostname, origin } = new URL(u); | |
| 175 | + if (NUESTRO.test(hostname)) o.add(origin + '/'); | |
| 176 | + } catch { /* url relativa o rara */ } | |
| 177 | + } | |
| 178 | + } | |
| 179 | + return [...o]; | |
| 180 | +} | |
| 181 | + | |
| 182 | +export async function disponible(id) { | |
| 183 | + const m = MODELS[id]; | |
| 184 | + if (!m) return false; | |
| 185 | + const urls = Array.isArray(m.url) ? m.url.map(f => f.url) : [m.url]; | |
| 186 | + try { | |
| 187 | + const rs = await Promise.all(urls.map(u => | |
| 188 | + fetch(u, { headers: { Range: 'bytes=0-0' }, cache: 'no-store' }))); | |
| 189 | + return rs.every(r => r.ok); | |
| 190 | + } catch { return false; } | |
| 191 | +} | |
| 192 | + | |
| 193 | +// ¿Se guarda este modelo en el navegador? Normalmente lo dice el registro, pero | |
| 194 | +// se puede FORZAR desde fuera con `localStorage['elffuss.engine.cache']` | |
| 195 | +// ('1' enciende, '0' apaga). | |
| 196 | +// | |
| 197 | +// No es un ajuste para usuarios, es un instrumento: el cacheo del 27B solo se | |
| 198 | +// comprueba de verdad en una web servida, y sin este interruptor la única forma | |
| 199 | +// de probarlo sería encendérselo a todo el mundo. Si sale mal, quien lo paga es | |
| 200 | +// quien esté cargando el modelo en ese momento: la descarga entera perdida y | |
| 201 | +// vuelta a empezar por el otro camino. | |
| 202 | +export function cachea(m) { | |
| 203 | + try { | |
| 204 | + const o = localStorage.getItem('elffuss.engine.cache'); | |
| 205 | + if (o === '1') return true; | |
| 206 | + if (o === '0') return false; | |
| 207 | + } catch { /* sin localStorage (worker, sandbox) */ } | |
| 208 | + return m.cache !== false; | |
| 209 | +} |
added js/sample.js +145 −0
| @@ -0,0 +1,145 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · muestreo y bucle de generación. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// El bucle de decode es donde el motor pasa el 99 % del tiempo, y donde falla lo | |
| 6 | +// que un forward suelto no puede detectar: que el estado se arrastre bien entre | |
| 7 | +// llamadas. Un forward aislado empieza con el estado a cero y la caché vacía, así | |
| 8 | +// que valida la matemática pero no la memoria. | |
| 9 | +// | |
| 10 | +// La prueba que sí lo detecta es de consistencia interna: procesar «abc» de una | |
| 11 | +// vez tiene que dar el MISMO resultado que procesar «a», luego «b», luego «c». | |
| 12 | +// Si la caché KV se escribe en el sitio equivocado, si el estado recurrente no | |
| 13 | +// se arrastra o si las posiciones de RoPE se reinician, las dos formas divergen. | |
| 14 | +// | |
| 15 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 16 | + | |
| 17 | +// Muestreo sobre los logits ya en CPU. Se trabaja sobre el último token, que es | |
| 18 | +// el único que interesa al generar. Sigue el ORDEN de llama.cpp, que es la | |
| 19 | +// referencia con la que se mide todo: penalizaciones → top-k → top-p → min-p → | |
| 20 | +// temperatura. La temperatura va AL FINAL: top-p y min-p se calculan sobre la | |
| 21 | +// distribución sin temperatura y la temperatura solo reparte entre los que | |
| 22 | +// sobreviven. Antes iba al principio, y con temperatura < 1 (la ficha del 27B | |
| 23 | +// pide 0,7 con top-p 0,8) el top-p cortaba sobre una distribución más | |
| 24 | +// afilada: sobrevivían menos tokens que en llama.cpp, sin error ninguno. | |
| 25 | +// · temp = 0 → greedy, determinista (tras las penalizaciones). | |
| 26 | +// · repeatPenalty: la de llama.cpp (divide si el logit es positivo y | |
| 27 | +// multiplica si es negativo). Su defecto aquí sigue siendo 1,1 para no | |
| 28 | +// cambiar a los modelos que no declaran muestreo; el llama.cpp actual trae | |
| 29 | +// 1,0, y los modelos con ficha la apagan desde el registro. | |
| 30 | +// · presence: resta fija a todo token que aparezca en la ventana (la ficha | |
| 31 | +// del 27B pide 1,5 sin razonar), como `presence_penalty` de llama.cpp. | |
| 32 | +// · minP: descarta los tokens cuya probabilidad sea menor que minP × la del | |
| 33 | +// más probable. | |
| 34 | +// mulberry32 sobre la semilla: buena mezcla también con semillas consecutivas | |
| 35 | +// (seed + paso), que es como se llama token a token. | |
| 36 | +function uniforme(seed) { | |
| 37 | + let t = ((seed >>> 0) + 0x6D2B79F5) >>> 0; | |
| 38 | + t = Math.imul(t ^ (t >>> 15), t | 1); | |
| 39 | + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); | |
| 40 | + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; | |
| 41 | +} | |
| 42 | + | |
| 43 | +export function sample(logits, opts = {}) { | |
| 44 | + const { temperature = 0, topP = 1, topK = 0, minP = 0, seed = 1, | |
| 45 | + repeatPenalty = 1.1, repeatLastN = 64, presence = 0, previos = null } = opts; | |
| 46 | + const n = logits.length; | |
| 47 | + | |
| 48 | + // PENALIZACIONES, sobre los últimos `repeatLastN` (prompt incluido, como | |
| 49 | + // llama.cpp). La de repetición existe porque el decode voraz sobre un modelo | |
| 50 | + // muy cuantizado entra en bucle («el color es de color, el color es de…»). | |
| 51 | + if (previos && previos.length && (repeatPenalty !== 1 || presence)) { | |
| 52 | + const desde = Math.max(0, previos.length - repeatLastN); | |
| 53 | + const vistos = new Set(); | |
| 54 | + for (let i = desde; i < previos.length; i++) vistos.add(previos[i]); | |
| 55 | + for (const id of vistos) { | |
| 56 | + if (id < 0 || id >= n) continue; | |
| 57 | + if (repeatPenalty !== 1) logits[id] = logits[id] > 0 ? logits[id] / repeatPenalty : logits[id] * repeatPenalty; | |
| 58 | + if (presence) logits[id] -= presence; | |
| 59 | + } | |
| 60 | + } | |
| 61 | + if (temperature <= 0) { | |
| 62 | + let best = 0; | |
| 63 | + for (let i = 1; i < n; i++) if (logits[i] > logits[best]) best = i; | |
| 64 | + return best; | |
| 65 | + } | |
| 66 | + | |
| 67 | + // Se ordena por logit y se corta antes de exponenciar: con 248.320 entradas, | |
| 68 | + // hacerlo al revés cuesta un softmax completo para tirar el 99,9 %. | |
| 69 | + const idx = Array.from({ length: n }, (_, i) => i); | |
| 70 | + idx.sort((a, b) => logits[b] - logits[a]); | |
| 71 | + const keep = topK > 0 ? Math.min(topK, n) : n; | |
| 72 | + | |
| 73 | + // top-p y min-p SIN temperatura. Resta del máximo antes de exp(): sin ella, | |
| 74 | + // logits de 30 desbordan. | |
| 75 | + const max = logits[idx[0]]; | |
| 76 | + const base = new Float64Array(keep); | |
| 77 | + let total = 0; | |
| 78 | + for (let i = 0; i < keep; i++) { base[i] = Math.exp(logits[idx[i]] - max); total += base[i]; } | |
| 79 | + let corte = keep; | |
| 80 | + if (topP < 1) { | |
| 81 | + let acc = 0; | |
| 82 | + for (let i = 0; i < keep; i++) { | |
| 83 | + acc += base[i] / total; | |
| 84 | + if (acc >= topP) { corte = i + 1; break; } | |
| 85 | + } | |
| 86 | + } | |
| 87 | + if (minP > 0) { | |
| 88 | + // base[0] es el más probable (están ordenados): el umbral es relativo a él. | |
| 89 | + const umbral = minP * base[0]; | |
| 90 | + let k = 1; | |
| 91 | + while (k < corte && base[k] >= umbral) k++; | |
| 92 | + corte = k; | |
| 93 | + } | |
| 94 | + | |
| 95 | + // La temperatura, solo entre los supervivientes. | |
| 96 | + const probs = new Float64Array(corte); | |
| 97 | + let sub = 0; | |
| 98 | + for (let i = 0; i < corte; i++) { probs[i] = Math.exp((logits[idx[i]] - max) / temperature); sub += probs[i]; } | |
| 99 | + | |
| 100 | + // Generador propio y con semilla: Math.random() haría irreproducible | |
| 101 | + // cualquier prueba de regresión de generación. Uniforme en [0, 1). | |
| 102 | + // | |
| 103 | + // ⚠️ Antes era un paso de LCG con `(s >>> 8) / 8388608`: el numerador llega a | |
| 104 | + // 2²⁴ y el divisor es 2²³, así que el «uniforme» caía en [0, 2). La mitad de | |
| 105 | + // las veces r > sub, el bucle de abajo se salía sin elegir y devolvía el | |
| 106 | + // ÚLTIMO superviviente: el menos probable (sin top-k, el peor token de todo el | |
| 107 | + // vocabulario). Y semillas consecutivas daban valores correlados. Lo cazó | |
| 108 | + // una prueba al pedir que un token improbable saliera alguna vez. | |
| 109 | + let r = uniforme(seed) * sub; | |
| 110 | + for (let i = 0; i < corte; i++) { | |
| 111 | + r -= probs[i]; | |
| 112 | + if (r <= 0) return idx[i]; | |
| 113 | + } | |
| 114 | + return idx[corte - 1]; | |
| 115 | +} | |
| 116 | + | |
| 117 | +// Genera tokens uno a uno. El prompt entero va en UNA llamada (prefill) y cada | |
| 118 | +// token nuevo en la suya (decode), que es exactamente el patrón real. | |
| 119 | +export async function generate(session, readLogits, promptIds, opts = {}) { | |
| 120 | + const max = opts.maxTokens || 32; | |
| 121 | + const stop = new Set(opts.stopIds || []); | |
| 122 | + const onToken = opts.onToken || (() => {}); | |
| 123 | + const out = []; | |
| 124 | + | |
| 125 | + let ids = promptIds; | |
| 126 | + for (let step = 0; step < max; step++) { | |
| 127 | + const { logits, logitsTokens } = await session.forward(ids); | |
| 128 | + // El forward devuelve logits SOLO del último token salvo que se pidan todos: | |
| 129 | + // deducir el vocabulario dividiendo por el número de tokens del prompt daría | |
| 130 | + // un vocabulario 316 veces más pequeño y una lectura corrida. | |
| 131 | + const vocab = logits.size / 4 / logitsTokens; | |
| 132 | + const all = await readLogits(logits, logitsTokens * vocab); | |
| 133 | + const last = all.subarray((logitsTokens - 1) * vocab, logitsTokens * vocab); | |
| 134 | + // Se le pasan los tokens ya emitidos MÁS el prompt: repetir lo que acaba de | |
| 135 | + // decir el usuario es tan bucle como repetirse a sí mismo. | |
| 136 | + const id = sample(last, { ...opts, seed: (opts.seed || 1) + step, | |
| 137 | + previos: promptIds.concat(out) }); | |
| 138 | + session.recycle(); | |
| 139 | + if (stop.has(id)) break; | |
| 140 | + out.push(id); | |
| 141 | + onToken(id, step); | |
| 142 | + ids = [id]; | |
| 143 | + } | |
| 144 | + return out; | |
| 145 | +} |
added js/state.js +364 −0
| @@ -0,0 +1,364 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · el estado que sobrevive entre tokens. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// En qwen35 son DOS cosas distintas, y esa asimetría es la que hace barato el | |
| 6 | +// contexto largo: | |
| 7 | +// | |
| 8 | +// · 6 capas de atención → caché KV, que CRECE con el contexto. | |
| 9 | +// · 18 capas SSM → estado recurrente de tamaño FIJO (128×128 por cabeza) más | |
| 10 | +// una ventana de convolución de 3 tokens. No crece nunca. | |
| 11 | +// | |
| 12 | +// Cuentas del modelo de 0.8B, sacadas de sus propios metadatos: | |
| 13 | +// · las 6 capas de atención guardan K y V de cada token: la caché KV crece en | |
| 14 | +// línea recta con el contexto; | |
| 15 | +// · las 18 capas SSM guardan una matriz de 128×128 por cabeza: fija; | |
| 16 | +// · la ventana de convolución es otra parte fija, mucho más pequeña. | |
| 17 | +// | |
| 18 | +// O sea: el estado recurrente de las 18 capas cuesta menos que 800 tokens de | |
| 19 | +// caché KV. Una cuenta de KV que supusiera las 24 capas de atención sobraría | |
| 20 | +// por dos órdenes de magnitud. | |
| 21 | +// | |
| 22 | +// PENDIENTE de verdad (no lo disimulo): la caché se reserva entera al abrir la | |
| 23 | +// sesión, con la longitud de contexto que se pida. Para los 262.144 de contexto | |
| 24 | +// que declara el modelo harían falta páginas: la caché de todo ese contexto no | |
| 25 | +// se reserva de una sentada. Con contextos de conversación normales esto sirve | |
| 26 | +// tal cual. | |
| 27 | +// | |
| 28 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 29 | + | |
| 30 | +// Del modulo de shaders, que es texto puro: importar ops.js aqui arrastraria | |
| 31 | +// las globales de WebGPU y state.js dejaria de poder inspeccionarse desde Node. | |
| 32 | +import { SSM_HEAD_DIM } from './kernels.ssm.wgsl.js'; | |
| 33 | + | |
| 34 | +const MiB = 1024 ** 2; | |
| 35 | + | |
| 36 | +export function createState(device, hp, opts = {}) { | |
| 37 | + const ctxLen = opts.contextLen || 2048; | |
| 38 | + if (ctxLen > hp.contextLength) { | |
| 39 | + throw new Error(`contexto ${ctxLen} mayor que el del modelo (${hp.contextLength})`); | |
| 40 | + } | |
| 41 | + const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST; | |
| 42 | + const buf = (bytes, label) => device.createBuffer({ label, size: bytes, usage }); | |
| 43 | + | |
| 44 | + // Se decide AQUÍ y se expone en el estado, para que el shader que escribe la | |
| 45 | + // caché y los que la leen no puedan discrepar. Si uno escribiera f16 y otro | |
| 46 | + // leyera f32, no habría error: habría basura. | |
| 47 | + const kvF16 = opts.kvF16 !== undefined ? !!opts.kvF16 | |
| 48 | + : globalThis.__ELFFUSS_KV_F16 !== false; | |
| 49 | + const bytesKv = kvF16 ? 2 : 4; | |
| 50 | + | |
| 51 | + const kv = new Map(); // índice de capa → {k, v} | |
| 52 | + const ssm = new Map(); // índice de capa → {state, conv} | |
| 53 | + let bytes = 0; | |
| 54 | + | |
| 55 | + for (const l of hp.layers) { | |
| 56 | + if (l.kind === 'attn') { | |
| 57 | + // Media precisión en la caché KV: la mitad de memoria y la mitad de | |
| 58 | + // tráfico al leerla. Es el escalón que va ANTES de cualquier cuantización | |
| 59 | + // —f32 no es siquiera la línea base de la industria, que es f16— y el | |
| 60 | + // único que no plantea preguntas de precisión más allá del redondeo. | |
| 61 | + const per = ctxLen * hp.kvHeads * hp.headDim * bytesKv; | |
| 62 | + kv.set(l.index, { k: buf(per, `k${l.index}`), v: buf(per, `v${l.index}`) }); | |
| 63 | + bytes += per * 2; | |
| 64 | + } else { | |
| 65 | + // Un estado de S_k x S_v por cabeza de VALOR, no de clave. | |
| 66 | + const st = hp.ssmVHeads * hp.ssmState * hp.ssmState * 4; | |
| 67 | + const cv = (hp.convKernel - 1) * hp.convChannels * 4; | |
| 68 | + ssm.set(l.index, { state: buf(st, `s${l.index}`), conv: buf(cv, `c${l.index}`) }); | |
| 69 | + bytes += st + cv; | |
| 70 | + } | |
| 71 | + } | |
| 72 | + | |
| 73 | + // Buffers sombra para las instantáneas del estado recurrente. Se crean UNA vez | |
| 74 | + // por ranura, la primera que se pida, y se reutilizan: crear ~96 buffers | |
| 75 | + // dentro de un turno es de las cosas que se llevan la pestaña por delante. | |
| 76 | + // `past` a -1 significa «esta ranura no tiene instantánea válida». | |
| 77 | + // | |
| 78 | + // Hay RANURAS CON NOMBRE y no una sola, y la razón es la mitad del asunto. La | |
| 79 | + // reutilización de prefijo exige que el prompt anterior COMPLETO sea prefijo | |
| 80 | + // estricto del nuevo, y con una sola foto —tomada al final del prompt | |
| 81 | + // anterior— eso solo se cumple si la conversación crece por el final y nada | |
| 82 | + // de en medio cambia. En un arnés siempre cambia algo en medio (el estado | |
| 83 | + // vivo), así que la foto única no servía nunca: medido x1,00. | |
| 84 | + // | |
| 85 | + // Con dos ranuras hay dos niveles de rescate: | |
| 86 | + // · 'turno' la de siempre: el final del prompt anterior. Caso ideal. | |
| 87 | + // · 'sistema' tomada justo después del prompt de sistema, y SOBREVIVE a | |
| 88 | + // `reset()`. Cuando el prefijo completo falla, se vuelve aquí y | |
| 89 | + // se reprocesa solo la conversación, no las ~1.300-2.200 fichas | |
| 90 | + // del prompt de sistema. | |
| 91 | + // | |
| 92 | + // Coste: cada ranura es una copia del estado recurrente, FIJA: no crece con | |
| 93 | + // el contexto. En el modelo grande es unas ocho veces la del pequeño, y aun | |
| 94 | + // así dos ranuras no llegan al 5 % de lo que pesan sus pesos; se cambian por | |
| 95 | + // no reprocesar el prompt de sistema en cada turno. | |
| 96 | + const ranuras = new Map(); | |
| 97 | + const ranura = (nombre) => { | |
| 98 | + let r = ranuras.get(nombre); | |
| 99 | + if (!r) { r = { sombra: null, past: -1 }; ranuras.set(nombre, r); } | |
| 100 | + return r; | |
| 101 | + }; | |
| 102 | + | |
| 103 | + const state = { | |
| 104 | + ctxLen, | |
| 105 | + nPast: 0, | |
| 106 | + bytes, | |
| 107 | + kv, ssm, | |
| 108 | + // Lo lee el forward para pedir el shader que corresponde. No es decorativo: | |
| 109 | + // escribir y leer la caché con precisiones distintas no da error, da basura. | |
| 110 | + kvF16, | |
| 111 | + | |
| 112 | + // Arrancar una conversación nueva: el estado recurrente vuelve a cero y la | |
| 113 | + // caché KV se olvida. Es OBLIGATORIO entre secuencias — un estado SSM | |
| 114 | + // arrastrado de otra conversación no da error, da respuestas contaminadas. | |
| 115 | + reset() { | |
| 116 | + state.nPast = 0; | |
| 117 | + for (const { state: s, conv } of ssm.values()) { | |
| 118 | + device.queue.writeBuffer(s, 0, new Float32Array(s.size / 4)); | |
| 119 | + device.queue.writeBuffer(conv, 0, new Float32Array(conv.size / 4)); | |
| 120 | + } | |
| 121 | + // La KV no hace falta limpiarla: la máscara causal solo mira hasta nPast. | |
| 122 | + // | |
| 123 | + // La instantánea del TURNO deja de valer: describe un estado que ya no | |
| 124 | + // existe, y restaurarla después de esto devolvería la conversación | |
| 125 | + // ANTERIOR sin dar ningún error. Se invalida aquí y no en quien llama, | |
| 126 | + // que es donde se olvidaría. | |
| 127 | + ranura('turno').past = -1; | |
| 128 | + // ⚠️ La del SYSTEM **no** se invalida, y es a propósito: describe «el | |
| 129 | + // estado después del prompt de sistema», que no depende de la | |
| 130 | + // conversación. Es justo lo que la hace útil — sobrevive al reset y | |
| 131 | + // permite volver ahí en vez de reprocesar el prompt entero. Quien la | |
| 132 | + // invalida es quien cambia el prompt de sistema, comparando fichas | |
| 133 | + // (provider.js), no esta función. | |
| 134 | + }, | |
| 135 | + | |
| 136 | + advance(n) { | |
| 137 | + if (state.nPast + n > ctxLen) { | |
| 138 | + throw new Error(`la caché se llena: ${state.nPast + n} tokens sobre ${ctxLen} de contexto`); | |
| 139 | + } | |
| 140 | + state.nPast += n; | |
| 141 | + }, | |
| 142 | + | |
| 143 | + // ── Fotografiar el estado para poder volver aquí ────────────────────────── | |
| 144 | + // Sirve para no reprocesar la conversación entera en cada turno. Lo que se | |
| 145 | + // copia es SOLO el estado recurrente del SSM, y eso es deliberado: | |
| 146 | + // | |
| 147 | + // · El recurrente NO se rebobina: es el resultado de haber recorrido toda | |
| 148 | + // la secuencia, así que la única forma de volver atrás es tener copia. | |
| 149 | + // · La KV NO se copia. La máscara causal descarta con un CERO EXACTO todo | |
| 150 | + // k > qAbs = nPast + fila — está así en `kernels.nn.wgsl.js` y en | |
| 151 | + // `softmaxCPU`, escritas por separado y coincidentes—, de modo que | |
| 152 | + // restaurar una posición anterior es devolver `nPast` atrás y dejar que | |
| 153 | + // lo viejo se sobrescriba. Es lo mismo en lo que ya se apoya `reset()`. | |
| 154 | + // | |
| 155 | + // La diferencia no es cosmética: copiar la KV costaría mucho más que el | |
| 156 | + // estado recurrente, y además CRECE con el contexto, mientras el estado | |
| 157 | + // recurrente es de tamaño FIJO. Fotografiar una conversación de 200.000 | |
| 158 | + // tokens cuesta exactamente lo mismo que una de 10. | |
| 159 | + instantanea(nombre = 'turno') { | |
| 160 | + const r = ranura(nombre); | |
| 161 | + if (!r.sombra) { | |
| 162 | + r.sombra = new Map(); | |
| 163 | + for (const [i, { state: s, conv }] of ssm) { | |
| 164 | + r.sombra.set(i, { state: buf(s.size, `snap-${nombre}-s${i}`), conv: buf(conv.size, `snap-${nombre}-c${i}`) }); | |
| 165 | + } | |
| 166 | + } | |
| 167 | + const enc = device.createCommandEncoder({ label: `instantanea:${nombre}` }); | |
| 168 | + for (const [i, { state: s, conv }] of ssm) { | |
| 169 | + const d = r.sombra.get(i); | |
| 170 | + enc.copyBufferToBuffer(s, 0, d.state, 0, s.size); | |
| 171 | + enc.copyBufferToBuffer(conv, 0, d.conv, 0, conv.size); | |
| 172 | + } | |
| 173 | + device.queue.submit([enc.finish()]); | |
| 174 | + r.past = state.nPast; | |
| 175 | + return r.past; | |
| 176 | + }, | |
| 177 | + | |
| 178 | + // Devuelve false si no hay instantánea válida, para que quien llame reinicie | |
| 179 | + // en vez de seguir con un estado que no sabe describir. | |
| 180 | + restaura(nombre = 'turno') { | |
| 181 | + const r = ranuras.get(nombre); | |
| 182 | + if (!r || !r.sombra || r.past < 0) return false; | |
| 183 | + const enc = device.createCommandEncoder({ label: `restaura:${nombre}` }); | |
| 184 | + for (const [i, { state: s, conv }] of ssm) { | |
| 185 | + const d = r.sombra.get(i); | |
| 186 | + enc.copyBufferToBuffer(d.state, 0, s, 0, s.size); | |
| 187 | + enc.copyBufferToBuffer(d.conv, 0, conv, 0, conv.size); | |
| 188 | + } | |
| 189 | + device.queue.submit([enc.finish()]); | |
| 190 | + state.nPast = r.past; | |
| 191 | + return true; | |
| 192 | + }, | |
| 193 | + | |
| 194 | + tieneInstantanea(nombre = 'turno') { | |
| 195 | + const r = ranuras.get(nombre); | |
| 196 | + return !!r && r.past >= 0; | |
| 197 | + }, | |
| 198 | + | |
| 199 | + // Cuántas fichas describe una ranura. Hace falta fuera: quien reutiliza | |
| 200 | + // tiene que saber desde qué posición sigue, y adivinarlo sería volver al | |
| 201 | + // fallo de tener la cuenta en dos sitios. | |
| 202 | + pasadoInstantanea(nombre = 'turno') { | |
| 203 | + const r = ranuras.get(nombre); | |
| 204 | + return r ? r.past : -1; | |
| 205 | + }, | |
| 206 | + | |
| 207 | + olvidaInstantanea(nombre) { | |
| 208 | + if (nombre === undefined) { for (const r of ranuras.values()) r.past = -1; return; } | |
| 209 | + const r = ranuras.get(nombre); | |
| 210 | + if (r) r.past = -1; | |
| 211 | + }, | |
| 212 | + | |
| 213 | + summary() { | |
| 214 | + const kvB = [...kv.values()].reduce((n, x) => n + x.k.size + x.v.size, 0); | |
| 215 | + const ssmB = [...ssm.values()].reduce((n, x) => n + x.state.size + x.conv.size, 0); | |
| 216 | + return `${kv.size} capas KV (${(kvB / MiB).toFixed(0)} MiB a ${ctxLen} de contexto, ${kvF16 ? 'f16' : 'f32'}) · ` + | |
| 217 | + `${ssm.size} capas SSM (${(ssmB / MiB).toFixed(1)} MiB fijos)`; | |
| 218 | + }, | |
| 219 | + | |
| 220 | + destroy() { | |
| 221 | + for (const x of kv.values()) { x.k.destroy(); x.v.destroy(); } | |
| 222 | + for (const x of ssm.values()) { x.state.destroy(); x.conv.destroy(); } | |
| 223 | + // Y los buffers sombra de la instantánea, que se crean aparte y aquí no | |
| 224 | + // estaban: en el 27B son una copia entera del estado recurrente, y se | |
| 225 | + // filtrarían en CADA ciclo de descarga y recarga. El detalle que lo hace | |
| 226 | + // peor de lo que parece es QUIÉN llama a esto: la app invoca `unload()` justo cuando | |
| 227 | + // la memoria va justa, así que la fuga aparecería en el peor momento | |
| 228 | + // posible y disfrazada de «el navegador mató la pestaña». | |
| 229 | + // TODAS las ranuras, no una: desde que hay dos, liberar solo la primera | |
| 230 | + // dejaría la otra colgada, y es el mismo tamaño. | |
| 231 | + for (const r of ranuras.values()) { | |
| 232 | + if (!r.sombra) continue; | |
| 233 | + for (const x of r.sombra.values()) { x.state.destroy(); x.conv.destroy(); } | |
| 234 | + r.sombra = null; | |
| 235 | + } | |
| 236 | + ranuras.clear(); | |
| 237 | + }, | |
| 238 | + }; | |
| 239 | + state.reset(); | |
| 240 | + return state; | |
| 241 | +} | |
| 242 | + | |
| 243 | +// Lee los hiperparámetros del GGUF y clasifica los bloques. Todo sale del | |
| 244 | +// fichero: nada cableado, porque el 27B tiene 65 bloques y el 0.8B 24, y el | |
| 245 | +// patrón de atención sale de su propia clave. | |
| 246 | +// Arquitecturas que este motor sabe ejecutar, y QUÉ las diferencia. | |
| 247 | +// | |
| 248 | +// `qwen35` es híbrida: la mayoría de bloques son recurrentes y uno de cada | |
| 249 | +// cuatro es de atención. `llama` es atención pura — y resulta ser un | |
| 250 | +// SUBCONJUNTO, no un camino aparte: el bloque de atención de qwen35 ya hace | |
| 251 | +// casi exactamente lo que pide llama. | |
| 252 | +// | |
| 253 | +// Las diferencias se declaran como DATOS y no como ramas sueltas por el | |
| 254 | +// forward, porque cada rama nueva en el camino de qwen35 es una oportunidad de | |
| 255 | +// romper los dos modelos que hoy están en producción: | |
| 256 | +// | |
| 257 | +// qGate qwen35 proyecta `attn_q` al DOBLE (Q y una puerta intercalados | |
| 258 | +// por cabeza) y multiplica la salida por esa puerta. llama no. | |
| 259 | +// qkNorm qwen35 normaliza Q y K antes de RoPE. llama no trae esos tensores. | |
| 260 | +// ropeMode ⚠️ EL PELIGROSO. qwen35 empareja como NEOX; `llama` usa NORM | |
| 261 | +// (pares adyacentes) porque el conversor a GGUF ya permuta los | |
| 262 | +// pesos. Equivocarse aquí NO peta: da texto gramatical que se | |
| 263 | +// degrada al crecer el contexto, que es la peor forma de fallar. | |
| 264 | +// ffnNorm se llama `post_attention_norm` en qwen35 y `ffn_norm` en llama. | |
| 265 | +// | |
| 266 | +// Los nombres NO se deducen mirando si el tensor existe. Con `has(...)`, un | |
| 267 | +// modelo al que le faltara el tensor dejaría de fallar y empezaría a mentir. | |
| 268 | +const ARQUITECTURAS = { | |
| 269 | + qwen35: { qGate: true, qkNorm: true, ropeMode: 'neox', ffnNorm: 'post_attention_norm', hibrida: true }, | |
| 270 | + llama: { qGate: false, qkNorm: false, ropeMode: 'norm', ffnNorm: 'ffn_norm', hibrida: false }, | |
| 271 | +}; | |
| 272 | + | |
| 273 | +export function readHParams(meta, tensors = null) { | |
| 274 | + const arch = meta['general.architecture']; | |
| 275 | + const perfil = ARQUITECTURAS[arch]; | |
| 276 | + if (!perfil) { | |
| 277 | + throw new Error(`arquitectura no soportada: ${arch} (conocidas: ${Object.keys(ARQUITECTURAS).join(', ')})`); | |
| 278 | + } | |
| 279 | + const g = (k, def) => { | |
| 280 | + const v = meta[`${arch}.${k}`]; | |
| 281 | + if (v === undefined && def === undefined) throw new Error(`falta la clave qwen35.${k}`); | |
| 282 | + return v === undefined ? def : v; | |
| 283 | + }; | |
| 284 | + | |
| 285 | + const nLayersFichero = g('block_count'); | |
| 286 | + // PREDICCIÓN MULTI-TOKEN. El 27B declara nextn_predict_layers=1: el ÚLTIMO | |
| 287 | + // bloque no pertenece al forward, es una cabeza que predice el token n+2. Si | |
| 288 | + // se ejecuta como una capa normal, el modelo genera tokens reales pero | |
| 289 | + // degenerados («if if if if…») — no peta, solo deja de tener sentido. | |
| 290 | + // | |
| 291 | + // Y explica la anomalía que había atribuido a otra cosa: con 65 bloques, la | |
| 292 | + // regla «uno de cada cuatro es atención» daba 16 y el fichero tenía 17. No | |
| 293 | + // había excepción: el 17º era la capa MTP, que no cuenta. | |
| 294 | + const nextn = meta['qwen35.nextn_predict_layers'] || 0; | |
| 295 | + const nLayers = nLayersFichero - nextn; | |
| 296 | + const interval = g('full_attention_interval', 4); | |
| 297 | + const heads = g('attention.head_count'); | |
| 298 | + const kvHeads = g('attention.head_count_kv'); | |
| 299 | + const embd = g('embedding_length'); | |
| 300 | + // head_dim NO es embd/heads en este modelo: 1024/8 = 128, pero el head_dim | |
| 301 | + // real es 256. Sale de su propia clave. | |
| 302 | + const headDim = g('attention.key_length', Math.floor(embd / heads)); | |
| 303 | + | |
| 304 | + // Se clasifica por los tensores que el fichero TIENE, no por una fórmula. | |
| 305 | + // La fórmula es respaldo y coincide exactamente con la de la referencia: | |
| 306 | + // atención cuando (i+1) % interval == 0, recurrente en el resto. El bloque MTP | |
| 307 | + // también trae attn_q, así que entra en este conjunto — da igual, porque el | |
| 308 | + // bucle solo pregunta por los `nLayers` que sí se ejecutan. | |
| 309 | + const attnSet = tensors | |
| 310 | + ? new Set(tensors | |
| 311 | + .map(t => /^blk\.(\d+)\.attn_q\.weight$/.exec(t.name)) | |
| 312 | + .filter(Boolean).map(m => +m[1])) | |
| 313 | + : null; | |
| 314 | + const esAtencion = (i) => attnSet | |
| 315 | + ? attnSet.has(i) | |
| 316 | + : (i + 1) % interval === 0; | |
| 317 | + | |
| 318 | + const layers = []; | |
| 319 | + for (let i = 0; i < nLayers; i++) { | |
| 320 | + layers.push({ index: i, kind: esAtencion(i) ? 'attn' : 'ssm' }); | |
| 321 | + } | |
| 322 | + | |
| 323 | + // DOS recuentos distintos, y confundirlos rompe solo los modelos grandes: | |
| 324 | + // `group_count` son las cabezas de CLAVE (16 en los dos modelos) y | |
| 325 | + // `time_step_rank` las de VALOR (16 en el 0.8B, 48 en el 27B). En el pequeño | |
| 326 | + // coinciden, así que usar uno para todo funciona ahí y solo ahí. | |
| 327 | + const ssmHeads = g('ssm.group_count', 16); | |
| 328 | + const ssmVHeads = g('ssm.time_step_rank', ssmHeads); | |
| 329 | + const ssmState = g('ssm.state_size', SSM_HEAD_DIM); | |
| 330 | + const ssmInner = g('ssm.inner_size', 2048); | |
| 331 | + | |
| 332 | + // Dos supuestos que el motor entero da por ciertos y que aquí se comprueban en | |
| 333 | + // vez de descubrirse como texto raro: que las cabezas de valor son múltiplo de | |
| 334 | + // las de clave (si no, el reparto q/k no está definido) y que la dimensión de | |
| 335 | + // value coincide con la de key (el estado es cuadrado y el shader usa una sola | |
| 336 | + // S para las dos). Los dos se cumplen en el 0.8B y en el 27B. | |
| 337 | + if (ssmVHeads % ssmHeads !== 0) { | |
| 338 | + throw new Error(`cabezas SSM incompatibles: ${ssmVHeads} de valor no es ` + | |
| 339 | + `múltiplo de ${ssmHeads} de clave`); | |
| 340 | + } | |
| 341 | + const headV = ssmInner / ssmVHeads; | |
| 342 | + if (headV !== ssmState) { | |
| 343 | + throw new Error(`el estado SSM no es cuadrado: value_dim ${headV} ` + | |
| 344 | + `(inner ${ssmInner} / ${ssmVHeads} cabezas) contra key_dim ${ssmState}`); | |
| 345 | + } | |
| 346 | + | |
| 347 | + return { | |
| 348 | + arch, ...perfil, nLayers, interval, layers, nextn, nLayersFichero, | |
| 349 | + embd, heads, kvHeads, headDim, | |
| 350 | + ffnLength: g('feed_forward_length'), | |
| 351 | + contextLength: g('context_length'), | |
| 352 | + ropeFreqBase: g('rope.freq_base', 1e7), | |
| 353 | + ropeDims: g('rope.dimension_count', 64), | |
| 354 | + eps: meta[`${arch}.attention.layer_norm_rms_epsilon`] ?? 1e-6, | |
| 355 | + ssmHeads, ssmVHeads, ssmState, ssmInner, | |
| 356 | + convKernel: g('ssm.conv_kernel', 4), | |
| 357 | + // conv_dim = 2·key_dim + value_dim, con key_dim = grupos·estado y | |
| 358 | + // value_dim = inner. En el 0.8B los dos valen 2048 y da 6144; en el 27B el | |
| 359 | + // value_dim son 6144 y da 10240. | |
| 360 | + convChannels: 2 * ssmHeads * ssmState + ssmInner, | |
| 361 | + nAttn: layers.filter(l => l.kind === 'attn').length, | |
| 362 | + nSSM: layers.filter(l => l.kind === 'ssm').length, | |
| 363 | + }; | |
| 364 | +} |
added js/tokenizer.js +277 −0
| @@ -0,0 +1,277 @@ | ||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | |
| 2 | +// Copyright (c) 2026 UtopiaIA | |
| 3 | +// Elffuss Runtime · tokenizador BPE a nivel de byte, leído del propio GGUF. | |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── | |
| 5 | +// El modelo no ve texto, ve enteros. Si el tokenizador difiere del que se usó | |
| 6 | +// para entrenar, el modelo recibe una secuencia que nunca ha visto y responde | |
| 7 | +// peor sin que nada falle: no hay excepción, no hay warning, solo calidad que | |
| 8 | +// baja. Es el mismo patrón de fallo silencioso que el resto del motor, así que | |
| 9 | +// se valida igual — contra el tokenizador de llama.cpp, caso por caso. | |
| 10 | +// | |
| 11 | +// Tres piezas, y las tres tienen su trampa: | |
| 12 | +// 1. PRE-TOKENIZADOR: un regex parte el texto en trozos ANTES del BPE. Es lo | |
| 13 | +// que impide que un merge cruce la frontera entre una palabra y la | |
| 14 | +// puntuación siguiente. Cada familia de modelos usa el suyo; usar el que | |
| 15 | +// no es da tokenizaciones casi correctas. | |
| 16 | +// 2. MAPA BYTE→UNICODE de GPT-2: el BPE opera sobre texto, pero el vocabulario | |
| 17 | +// cubre los 256 bytes. La tabla de OpenAI mueve los bytes no imprimibles a | |
| 18 | +// un hueco de Unicode para que nunca aparezca un carácter de control. El | |
| 19 | +// espacio se convierte en «Ġ», que es por qué el vocabulario está lleno de | |
| 20 | +// ellas. | |
| 21 | +// 3. MERGES: el rango es el ORDEN en el array del GGUF. Siempre se aplica el | |
| 22 | +// par de menor rango de toda la palabra, no el primero que se encuentre. | |
| 23 | +// | |
| 24 | +// Licencia: código propio, Apache-2.0 (ver SPDX arriba y LICENSE). Sin dependencias externas. | |
| 25 | + | |
| 26 | +// Tipos de token de GGUF (llama_token_type). | |
| 27 | +const TYPE_NORMAL = 1, TYPE_CONTROL = 3, TYPE_USER_DEFINED = 4, TYPE_BYTE = 6; | |
| 28 | + | |
| 29 | +// Tabla bytes→unicode de GPT-2. Los 188 bytes imprimibles se quedan donde | |
| 30 | +// están; los otros 68 se desplazan a partir de U+0100, donde no colisionan con | |
| 31 | +// nada real. Así una secuencia de bytes cualquiera es siempre texto válido. | |
| 32 | +function byteMaps() { | |
| 33 | + const bs = []; | |
| 34 | + for (let b = 33; b <= 126; b++) bs.push(b); | |
| 35 | + for (let b = 161; b <= 172; b++) bs.push(b); | |
| 36 | + for (let b = 174; b <= 255; b++) bs.push(b); | |
| 37 | + const direct = new Set(bs); | |
| 38 | + const cs = bs.slice(); | |
| 39 | + let n = 0; | |
| 40 | + for (let b = 0; b < 256; b++) { | |
| 41 | + if (!direct.has(b)) { bs.push(b); cs.push(256 + n); n++; } | |
| 42 | + } | |
| 43 | + const b2u = new Array(256); | |
| 44 | + const u2b = new Map(); | |
| 45 | + for (let i = 0; i < bs.length; i++) { | |
| 46 | + const ch = String.fromCodePoint(cs[i]); | |
| 47 | + b2u[bs[i]] = ch; | |
| 48 | + u2b.set(ch, bs[i]); | |
| 49 | + } | |
| 50 | + return { b2u, u2b }; | |
| 51 | +} | |
| 52 | + | |
| 53 | +const { b2u: BYTE_TO_UNI, u2b: UNI_TO_BYTE } = byteMaps(); | |
| 54 | + | |
| 55 | +// El conjunto de espacios de llama.cpp NO es el `\s` de JavaScript. Barriendo | |
| 56 | +// los 0x110000 code points difieren en DOS: U+0085 (NEL), que llama.cpp cuenta | |
| 57 | +// como espacio y JS no, y U+FEFF (BOM), al revés. Parece anecdótico y no lo es: | |
| 58 | +// un BOM al principio de un fichero cambia la tokenización de todo el trozo | |
| 59 | +// inicial. Por eso la clase va explícita y `\S` se emula negándola. | |
| 60 | +const WS = '\\t\\n\\u000B\\f\\r \\u0085\\u00A0\\u1680\\u2000-\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000'; | |
| 61 | + | |
| 62 | +// Pre-tokenizadores por valor de `tokenizer.ggml.pre`. Parten el texto ANTES del | |
| 63 | +// BPE para que ningún merge cruce de una palabra a la puntuación siguiente. | |
| 64 | +// | |
| 65 | +// Detalles que separan «funciona» de «casi funciona»: | |
| 66 | +// · `\p{N}` es UN dígito, no `\p{N}{1,3}`. Con el de Llama-3 todo el texto | |
| 67 | +// normal sale bien y solo se descuadran los números — el síntoma clásico. | |
| 68 | +// · qwen35 consume marcas combinantes junto a las letras (`[\p{L}\p{M}]+`); | |
| 69 | +// qwen2 no. Copiar el de qwen2 da resultados idénticos en inglés y ASCII y | |
| 70 | +// divergentes en hindi, tailandés, vietnamita o árabe vocalizado. | |
| 71 | +// · `(?i:…)` no existe en JS y la flag `i` global NO sirve: haría insensible | |
| 72 | +// todo el patrón. La expansión a mano es la del propio llama.cpp. | |
| 73 | +// · El orden de las 7 alternativas es semántico (leftmost-first con | |
| 74 | +// retroceso, no leftmost-longest). Consecuencia contraintuitiva: el prefijo | |
| 75 | +// opcional acepta puntuación, así que «!a» es UN token, y « a» también. | |
| 76 | +const CONTRACTIONS = "(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])"; | |
| 77 | +const TAIL = `|\\p{N}| ?[^${WS}\\p{L}%M%\\p{N}]+[\\r\\n]*|[${WS}]*[\\r\\n]+|[${WS}]+(?![^${WS}])|[${WS}]+`; | |
| 78 | + | |
| 79 | +const PRE_PATTERNS = { | |
| 80 | + qwen35: CONTRACTIONS + '|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+' + TAIL.replace('%M%', '\\p{M}'), | |
| 81 | + qwen2: CONTRACTIONS + '|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+' + TAIL.replace('%M%', ''), | |
| 82 | +}; | |
| 83 | +PRE_PATTERNS.default = PRE_PATTERNS.qwen2; | |
| 84 | + | |
| 85 | +export function createTokenizer(meta, opts = {}) { | |
| 86 | + const tokens = meta['tokenizer.ggml.tokens']; | |
| 87 | + const merges = meta['tokenizer.ggml.merges']; | |
| 88 | + if (!tokens) throw new Error('el GGUF no trae tokenizer.ggml.tokens'); | |
| 89 | + const model = meta['tokenizer.ggml.model']; | |
| 90 | + if (model !== 'gpt2') throw new Error('tokenizador no soportado: ' + model); | |
| 91 | + | |
| 92 | + const types = meta['tokenizer.ggml.token_type']; | |
| 93 | + const preName = meta['tokenizer.ggml.pre'] || 'default'; | |
| 94 | + const pattern = opts.pattern || PRE_PATTERNS[preName] || PRE_PATTERNS.default; | |
| 95 | + // La flag `u` es OBLIGATORIA y su ausencia no da error: sin ella `\p{L}` se | |
| 96 | + // lee como la letra «p» seguida de «{L}», falla en silencio y produce una | |
| 97 | + // tokenización distinta que en textos cortos parece casi bien. | |
| 98 | + const re = new RegExp(pattern, 'gu'); | |
| 99 | + | |
| 100 | + const bosId = meta['tokenizer.ggml.bos_token_id']; | |
| 101 | + const eosId = meta['tokenizer.ggml.eos_token_id']; | |
| 102 | + const addBosDefault = meta['tokenizer.ggml.add_bos_token'] ?? false; | |
| 103 | + const addEosDefault = meta['tokenizer.ggml.add_eos_token'] ?? false; | |
| 104 | + | |
| 105 | + // Índices perezosos: materializar 248.320 strings cuesta memoria y tiempo, y | |
| 106 | + // para DECODIFICAR no hacen falta — el array del GGUF ya indexa por posición. | |
| 107 | + let vocab = null; // string → id | |
| 108 | + let ranks = null; // "a\u0000b" → rango | |
| 109 | + let specials = null; // [{text, id}] ordenados por longitud descendente | |
| 110 | + | |
| 111 | + function buildEncode() { | |
| 112 | + if (vocab) return; | |
| 113 | + vocab = new Map(); | |
| 114 | + for (let i = 0; i < tokens.length; i++) vocab.set(tokens.at(i), i); | |
| 115 | + ranks = new Map(); | |
| 116 | + if (merges) { | |
| 117 | + for (let i = 0; i < merges.length; i++) { | |
| 118 | + const m = merges.at(i); | |
| 119 | + // Se parte por el PRIMER espacio: las piezas no pueden contenerlo | |
| 120 | + // (el espacio real viaja como «Ġ»), así que esto no es ambiguo. | |
| 121 | + const sp = m.indexOf(' '); | |
| 122 | + if (sp < 0) continue; | |
| 123 | + ranks.set(m.slice(0, sp) + '\u0000' + m.slice(sp + 1), i); | |
| 124 | + } | |
| 125 | + } | |
| 126 | + // Índice de tokens especiales por PRIMER CARÁCTER. Este vocabulario tiene | |
| 127 | + // cientos de «[PADnnnnnn]», y recorrerlos todos en cada posición del texto | |
| 128 | + // convertiría la codificación en cuadrática. | |
| 129 | + specials = new Map(); | |
| 130 | + if (types) { | |
| 131 | + for (let i = 0; i < types.length; i++) { | |
| 132 | + const t = types[i]; | |
| 133 | + if (t !== TYPE_CONTROL && t !== TYPE_USER_DEFINED) continue; | |
| 134 | + const text = tokens.at(i); | |
| 135 | + if (!text) continue; | |
| 136 | + const k = text[0]; | |
| 137 | + if (!specials.has(k)) specials.set(k, []); | |
| 138 | + specials.get(k).push({ text, id: i }); | |
| 139 | + } | |
| 140 | + // De mayor a menor longitud: si existieran «<|im_start|>» y «<|im|>», hay | |
| 141 | + // que probar el largo primero o se parte el otro por la mitad. | |
| 142 | + for (const list of specials.values()) list.sort((a, b) => b.text.length - a.text.length); | |
| 143 | + } | |
| 144 | + } | |
| 145 | + | |
| 146 | + // Parte el texto en trozos normales y tokens especiales literales. | |
| 147 | + function splitSpecials(text) { | |
| 148 | + const out = []; | |
| 149 | + let i = 0, start = 0; | |
| 150 | + while (i < text.length) { | |
| 151 | + const cands = specials.get(text[i]); | |
| 152 | + let hit = null; | |
| 153 | + if (cands) { for (const s of cands) if (text.startsWith(s.text, i)) { hit = s; break; } } | |
| 154 | + if (hit) { | |
| 155 | + if (i > start) out.push({ text: text.slice(start, i) }); | |
| 156 | + out.push({ id: hit.id }); | |
| 157 | + i += hit.text.length; | |
| 158 | + start = i; | |
| 159 | + } else i++; | |
| 160 | + } | |
| 161 | + if (start < text.length) out.push({ text: text.slice(start) }); | |
| 162 | + return out; | |
| 163 | + } | |
| 164 | + | |
| 165 | + // BPE sobre una palabra ya pasada por el mapa de bytes. Se aplica SIEMPRE el | |
| 166 | + // par de menor rango de toda la palabra; coger el primero que se encuentre da | |
| 167 | + // resultados distintos y plausibles. | |
| 168 | + function bpe(word) { | |
| 169 | + if (word.length < 2) return word; | |
| 170 | + let parts = word.slice(); | |
| 171 | + for (;;) { | |
| 172 | + let best = Infinity, at = -1; | |
| 173 | + for (let i = 0; i < parts.length - 1; i++) { | |
| 174 | + const r = ranks.get(parts[i] + '\u0000' + parts[i + 1]); | |
| 175 | + if (r !== undefined && r < best) { best = r; at = i; } | |
| 176 | + } | |
| 177 | + if (at < 0) break; | |
| 178 | + parts = parts.slice(0, at).concat(parts[at] + parts[at + 1], parts.slice(at + 2)); | |
| 179 | + if (parts.length === 1) break; | |
| 180 | + } | |
| 181 | + return parts; | |
| 182 | + } | |
| 183 | + | |
| 184 | + const enc = new TextEncoder(); | |
| 185 | + const dec = new TextDecoder('utf-8'); | |
| 186 | + | |
| 187 | + // Trozos del pre-tokenizador, CONSERVANDO los huecos entre coincidencias: | |
| 188 | + // llama.cpp también los conserva, y descartarlos perdería texto en silencio. | |
| 189 | + function preSplit(text) { | |
| 190 | + const out = []; | |
| 191 | + re.lastIndex = 0; | |
| 192 | + let last = 0, m; | |
| 193 | + while ((m = re.exec(text)) !== null) { | |
| 194 | + if (m.index > last) out.push(text.slice(last, m.index)); | |
| 195 | + if (m[0].length === 0) { re.lastIndex++; continue; } | |
| 196 | + out.push(m[0]); | |
| 197 | + last = m.index + m[0].length; | |
| 198 | + } | |
| 199 | + if (last < text.length) out.push(text.slice(last)); | |
| 200 | + return out; | |
| 201 | + } | |
| 202 | + | |
| 203 | + function encodeChunk(text, out) { | |
| 204 | + for (const piece of preSplit(text)) { | |
| 205 | + if (!piece) continue; | |
| 206 | + // Texto → bytes UTF-8 → caracteres del mapa de GPT-2. | |
| 207 | + const bytes = enc.encode(piece); | |
| 208 | + const chars = new Array(bytes.length); | |
| 209 | + for (let i = 0; i < bytes.length; i++) chars[i] = BYTE_TO_UNI[bytes[i]]; | |
| 210 | + for (const p of bpe(chars)) { | |
| 211 | + const id = vocab.get(p); | |
| 212 | + if (id !== undefined) { out.push(id); continue; } | |
| 213 | + // Un trozo sin entrada en el vocabulario se parte carácter a carácter: | |
| 214 | + // el vocabulario cubre los 256 bytes, así que siempre hay salida. | |
| 215 | + for (const ch of p) { | |
| 216 | + const single = vocab.get(ch); | |
| 217 | + if (single !== undefined) out.push(single); | |
| 218 | + } | |
| 219 | + } | |
| 220 | + } | |
| 221 | + } | |
| 222 | + | |
| 223 | + return { | |
| 224 | + vocabSize: tokens.length, | |
| 225 | + bosId, eosId, preName, | |
| 226 | + | |
| 227 | + // `special: false` desactiva el reconocimiento de tokens de control en el | |
| 228 | + // texto de entrada — útil para no dejar que un usuario inyecte «<|im_end|>» | |
| 229 | + // escribiéndolo a mano. | |
| 230 | + encode(text, { addBos = addBosDefault, addEos = addEosDefault, special = true } = {}) { | |
| 231 | + buildEncode(); | |
| 232 | + const out = []; | |
| 233 | + if (addBos && bosId !== undefined) out.push(bosId); | |
| 234 | + | |
| 235 | + if (special && specials.size) { | |
| 236 | + for (const part of splitSpecials(text)) { | |
| 237 | + if (part.id !== undefined) out.push(part.id); | |
| 238 | + else encodeChunk(part.text, out); | |
| 239 | + } | |
| 240 | + } else { | |
| 241 | + encodeChunk(text, out); | |
| 242 | + } | |
| 243 | + | |
| 244 | + if (addEos && eosId !== undefined) out.push(eosId); | |
| 245 | + return out; | |
| 246 | + }, | |
| 247 | + | |
| 248 | + // ids → texto. No necesita el índice de codificación, así que decodificar | |
| 249 | + // un modelo recién cargado no paga la construcción del mapa de 248k. | |
| 250 | + decode(ids) { | |
| 251 | + let s = ''; | |
| 252 | + for (const id of ids) { | |
| 253 | + if (id < 0 || id >= tokens.length) continue; | |
| 254 | + s += tokens.at(id); | |
| 255 | + } | |
| 256 | + const bytes = new Uint8Array(s.length * 4); | |
| 257 | + let n = 0; | |
| 258 | + for (const ch of s) { | |
| 259 | + const b = UNI_TO_BYTE.get(ch); | |
| 260 | + if (b !== undefined) { bytes[n++] = b; continue; } | |
| 261 | + // Un carácter fuera del mapa (token especial escrito literal) se | |
| 262 | + // devuelve tal cual en UTF-8. | |
| 263 | + for (const x of enc.encode(ch)) bytes[n++] = x; | |
| 264 | + } | |
| 265 | + return dec.decode(bytes.subarray(0, n)); | |
| 266 | + }, | |
| 267 | + | |
| 268 | + // El texto de UN token, para emitir en streaming. Ojo: un token puede | |
| 269 | + // cortar un carácter multibyte por la mitad, así que quien haga streaming | |
| 270 | + // tiene que acumular bytes, no strings. | |
| 271 | + tokenText(id) { return tokens.at(id); }, | |
| 272 | + tokenType(id) { return types ? types[id] : TYPE_NORMAL; }, | |
| 273 | + isControl(id) { return types ? types[id] === TYPE_CONTROL : false; }, | |
| 274 | + }; | |
| 275 | +} | |
| 276 | + | |
| 277 | +export { TYPE_NORMAL, TYPE_CONTROL, TYPE_USER_DEFINED, TYPE_BYTE }; |
added package.json +23 −0
| @@ -0,0 +1,23 @@ | ||
| 1 | +{ | |
| 2 | + "name": "@elffuss/engine", | |
| 3 | + "version": "0.0.0", | |
| 4 | + "private": true, | |
| 5 | + "description": "Modular WebGPU runtime for GGUF language models in a web page. No dependencies, no build step.", | |
| 6 | + "type": "module", | |
| 7 | + "license": "Apache-2.0 AND MIT", | |
| 8 | + "repository": { "type": "git", "url": "https://github.com/utopia-ia/elffuss-engine" }, | |
| 9 | + "homepage": "https://github.com/utopia-ia/elffuss-engine#readme", | |
| 10 | + "bugs": "https://github.com/utopia-ia/elffuss-engine/issues", | |
| 11 | + "exports": { | |
| 12 | + ".": "./js/provider.js", | |
| 13 | + "./registry": "./js/registro.js", | |
| 14 | + "./gguf": "./js/gguf.js", | |
| 15 | + "./tokenizer": "./js/tokenizer.js", | |
| 16 | + "./sample": "./js/sample.js", | |
| 17 | + "./device": "./js/device.js", | |
| 18 | + "./model": "./js/model.js", | |
| 19 | + "./package.json": "./package.json" | |
| 20 | + }, | |
| 21 | + "files": ["js", "assets", "README.md", "CHANGELOG.md", "LICENSE", "NOTICE"], | |
| 22 | + "sideEffects": false | |
| 23 | +} |