Skip to content

armgit / janas

Public Imported from GitHub
0

37 tok/s from Qwen3-Next-80B (48 GB) on a 32 GB laptop, 24 without drafts vs 2.8 for llama.cpp; reading 62 vs 16 tok/s. Faster than llama.cpp on all 13 models compared in Q4_K_M. LLMs bigger than your RAM, pure C, CPU or GPU.

Release 2026-10-13: the GPU's products of 2 to 8 vectors faster (Q4_K, Q6_K, Q5_K, IQ4_XS), Qwen3.8-27B reading prompts whole on the GPU (30.6 tok/s), a qwen3.5 model's drafts verifiable on the GPU (JANAS_GPU_SHORT=1)

camauri092e33a44b1e
diff --git a/ChangeLog.md b/ChangeLog.md
index ac85c55..ce11efe 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -2,8 +2,26 @@
> Curated, user-facing summary of completed work, newest first.
+## [2026-10-13] - The GPU's passes of a few tokens
+
+- **Qwen3.8-27B's drafts verified on the GPU a little faster, 7.7 tokens/s in two runs against 7.6 and 7.0** (`JANAS_GPU_SHORT=1`, 64 tokens of code): no chain longer than the GPU's shaders of a few vectors take (a ninth token doubled the pass: 854 ms against 437 for 5), and the recurrent layers' betas and decays read their inputs a quarter as often (3.7 ms a pass of 8 tokens where they took 13.5), with the same results to the bit.
+- **Qwen3.8-27B writes 7.6 tokens/s with its drafts verified on the GPU (`JANAS_GPU_SHORT=1`), against 6.3 on the CPU alone** (64 tokens of code, in a series with each build alternated; the figures depend on the length and on the chains the planner chooses): the GPU's products of 2 to 8 vectors on Q5_K and IQ4_XS weights - two thirds of what the model reads - now take the lanes on the vectors too (`q5k_mvd`, `iq4xs_mvd`), a pass of 8 tokens 482.9 ms where it took 509.6, with the same results as the CPU to the bit. On 17408 x 5120, 2 to 8 vectors: Q5_K 1.23-1.38 ms against 1.48-1.54, IQ4_XS 1.85-1.96 against 2.36-2.42.
+- **Qwen3.8-27B reads a prompt 19% faster on the GPU, 22.7 tokens/s against 19.0 in blocks of 100 tokens (`janas-bench`, 1,024 tokens: 30.6 against 26.4; llama.cpp 25.6), and with `JANAS_GPU_SHORT=1` writes 8.7 tokens/s with its drafts against 7.0 on the CPU** (128 tokens of code): two of its down matrices are IQ4_NL, in blocks of 32, which had kept every pass of the model off the GPU's single submission; such a layer now takes its activation in both layouts there, as a mixture's shared expert already did. Its logits as close to the reference as before (top-1 197/200, mean |diff| 0.095; the CPU 195/200, 0.098).
+- **Qwen3.5-9B with its MTP block writes 24.2 tokens/s with its chains of drafts verified whole on the GPU, against 20.0 on the CPU** (`JANAS_GPU_SHORT=1`, still asked for only): the Gated DeltaNet layers' state is replayed and logged on the GPU as on the CPU, in the same log, so that a pass of drafts goes to the GPU in one submission and the next pass replays there the tokens kept. A short block's betas and decays have a shader of their own, a workgroup a row, where one workgroup took the whole block. A pass of 7.7 tokens: Qwen3.5-0.8B 49.6 to 38.8 ms, 2B 53.7 to 42.4, 9B 161.3 to 132.0. The 9B's logits as close to the reference as the CPU's (top-1 243/256 in blocks of 8, mean |diff| 0.098; the CPU 373/400, 0.099); the text not the CPU's, as the GPU's norms and sums go in their own order.
+- **The GPU's products of 2 to 8 vectors on Q4_K weights take 12-25% longer than one vector's, where they took 21-98% longer** (`q4k_mvd`; 17408 x 5120: 0.83, 0.85 and 0.92 ms for 2, 4 and 8 vectors against 0.74 for one): the lanes of a subgroup take the vectors instead of the rows, so that a row's block is read 128 contiguous bytes at a time and its words reach every vector as scalar operands. The shaders before put a row on a lane, and each of their loads touched eight rows: the development laptop's GPU read the weights so at some 50 GB/s against 68. Qwen3-4B with its whole pass on the GPU, ms a token in blocks of 2 / 4 / 8 tokens (a draft chain's verification): 30.0 / 17.2 / 11.1 against 30.9 / 23.0 / 12.7, the same results bit for bit; at 8 tokens the GPU now takes 28% less than the CPU (15.5). On where a subgroup is 8 lanes (Intel); `JANAS_GPU_MVD=0` leaves it out.
+- **The same for Q6_K weights** (`q6k_mvd`), whose 210-byte blocks start on a word or two bytes past one: each lane loads the words around its part of the block and shifts them into place. Qwen3-4B's output (151936 x 2560): 7.1 ms for 2 vectors and 7.6 for 8, where it took 10.1 and 16.9, and 9.6 for a single vector. Qwen3-4B with its whole pass on the GPU, now 28.3 / 16.0 / 9.5 ms a token in blocks of 2 / 4 / 8: from 4 tokens up the GPU takes less than the CPU (17.1 at 4, 15.5 at 8), the same results bit for bit.
+- **Products of 9 to 63 vectors dispatched with the vectors' groups first**: the groups of the same rows go out together and those after the first find the weights in the L3. 16 vectors of a 17408 x 5120 Q4_K matrix: 1.53 ms instead of 2.06, bit for bit as before.
+- **`q4k_mv`, a Q4_K product of a row an invocation with a third fewer instructions**, behind `JANAS_GPU_MV=1` while it is measured: no faster up to 8 vectors, faster beyond (16 vectors 1.22 ms against 1.53).
+- **`bench_gemm` puts the weights where the engine has them** (`BENCH_MEM=huge2m`: 2 MB pages; `driver`: the GPU driver's memory). A correction to earlier figures: on a GPU sharing the host's memory the products of a single vector go to the CPU (`JANAS_GPU_MIN_N`), so `bench_gemm`'s "GPU" times for one vector were the CPU's; the GPU's own for 17408 x 5120 is 0.74 ms.
+- **Fixed on the way**: the server's store, reading its conversations back from disk with none there, gave `qsort` a null list (harmless in practice, undefined in C; found by the UndefinedBehaviorSanitizer suite).
+
+
## [2026-10-12] - janas-bench takes a model by name
+- **The GPU's products of a few vectors on IQ4_XS, IQ3_S and IQ4_NL weights a fifth to a third faster**: their table of levels (the IQ3_S grid) read from the workgroup's shared memory instead of a constant array; on 8 vectors of a 17408 x 5120 matrix, IQ4_XS 3.73 to 2.65 ms, IQ3_S 3.57 to 2.67, IQ4_NL 4.35 to 3.46, the results the CPU's to the bit.
+- **The memory a GPU sharing the host's imports starts on 2 MB boundaries, collapsed into huge pages before it is pinned**: on the development laptop's GPU such memory reads at 71.6 GB/s against 59.6, and the CPU reads it as fast as before. No change yet on prompts or replies, where the GPU is bound by its clock and the CPU writes the tokens; it is for the passes the GPU would read whole.
+- **Qwen3.8-27B in the catalog** (`qwen3.8-27b`): unsloth's UD-Q4_K_XL, dense, its multi-token prediction block inside the file; converted already on Hugging Face (`prabanta-dev/Qwen3.8-27B-JNS`), its fingerprints in MODELS.md, a row in the README's table.
+- **IQ4_XS, IQ3_S and IQ4_NL weights in a prompt's products on the GPU** (the fast prompt's tiles, as Q4_K, Q5_K, Q6_K, Q3_K and Q8_0 already were): unsloth's UD files mix these types in, and they went through the slow path one vector at a time. `bench_gemm` 2048 x 6144: 260-600 GMAC/s, every output as the CPU's to within 7 parts in 10 million of the largest (`bench_gemm` now checks the GPU against the CPU output by output). Qwen3.8-27B UD-Q4_K_XL reads a prompt of 1,024 tokens at 26.4 tok/s where it read 18.7, against 25.6 for llama.cpp with Vulkan; it writes at 4.4 tok/s against 2.1 (12 October 2026, the development laptop). Its answers against llama.cpp's: the most likely token the same at 194 of 200 positions through the GPU's blocks, 195 token by token.
- **`janas-bench` takes the model as `janas-chat` does**: a name of the models Janas knows (`janas-bench qwen3-4b`), downloaded after asking if it is not there yet; with no model, the list to choose from; a `.jns` file as before. The model's prediction file comes with it as in the chat - the one the catalog names, or for another file the one beside it - so the drafts are measured as the chat uses them; `--no-mtp` leaves it out, `--models` says where the models are. Both programs share one way of finding a model (`src/common/model_pick.c`).
## [2026-10-12] - Janas on Windows
diff --git a/MODELS.md b/MODELS.md
index 12ec880..0286e75 100644
--- a/MODELS.md
+++ b/MODELS.md
@@ -113,6 +113,13 @@ aaf42c8b7c3cab2bf3d69c355048d4a0ee9973d48f16c731c0520ee914699223 Qwen3.5-2B-Q4_
e40ec6c58ef2390c7a4ce8c9b7b6b384ed4e55c9980f646d1c98e83e2c018115 qwen3.5-9b-q4km.jns (gguf2jns)
```
+**Qwen3.8-27B**, dense, from [`unsloth/Qwen3.8-27B-GGUF`](https://huggingface.co/unsloth/Qwen3.8-27B-GGUF) at revision `4ca72078`, unsloth's UD-Q4_K_XL mix (Q4_K, Q5_K, Q6_K and Q8_0 with IQ4_XS, IQ3_S, IQ4_NL and Q3_K); its multi-token prediction block is in the GGUF, and so in the converted file. Converted in one step:
+
+```
+3f227079003add2511437e5b1e94812e363385225bf6a9b47b0054a72bc8b01e Qwen3.8-27B-UD-Q4_K_XL.gguf
+138d1db3af7e48d3bd36a428f7a81dfd8813434521aced84459c546e4830ab5b qwen3.8-27b-ud-q4kxl.jns (gguf2jns)
+```
+
**Qwen3-30B-A3B**, from [`Qwen/Qwen3-30B-A3B-GGUF`](https://huggingface.co/Qwen/Qwen3-30B-A3B-GGUF):
```
@@ -212,7 +219,7 @@ The same tensors from shards on disk give the same bytes. A private or gated rep
**The converter, always. The weights, only when their licence plainly allows it.** In order:
-1. **Models under Apache 2.0, MIT or a similar licence.** Every model Janas supports today is under **Apache 2.0** and none is gated: Qwen3-Next (including Qwen3-Coder-Next), Qwen3.5 and Qwen3.6, and Qwen3 MoE — checked on their pages, not in their files. Converted files may be published, and when they are, they carry:
+1. **Models under Apache 2.0, MIT or a similar licence.** Every model Janas supports today is under **Apache 2.0** and none is gated: Qwen3-Next (including Qwen3-Coder-Next), Qwen3.5, Qwen3.6 and Qwen3.8-27B, and Qwen3 MoE — checked on their pages, not in their files. Converted files may be published, and when they are, they carry:
- a link to the original model and to its licence;
- the original `LICENSE` and, where there is one, the `NOTICE`;
- a statement of what was changed (the list above) and which version of the tools did it;
diff --git a/README.md b/README.md
index ed42aac..a050221 100644
--- a/README.md
+++ b/README.md
@@ -2,7 +2,7 @@
[![Status: experimental](https://img.shields.io/badge/status-experimental-orange.svg)]() [![Platform: Linux | Windows x86-64](https://img.shields.io/badge/platform-Linux%20%7C%20Windows%20x86--64-lightgrey.svg)]() [![LinkedIn](https://img.shields.io/badge/LinkedIn-Maurizio%20Cammalleri-0077B5?logo=linkedin)](https://www.linkedin.com/in/maurizio-cammalleri-80a89a11/) [![Substack](https://img.shields.io/badge/Substack-Maurizio%20Cammalleri-FF6719?logo=substack)](https://cammalleri.substack.com/)
-**37 tok/s from Qwen3-Next-80B (a 48 GB model) on a laptop with 32 GB of memory, 24 without drafts, where llama.cpp manages 2.8; reading a prompt, 62 tok/s against 16.** Janas-LLM was faster than llama.cpp on every model compared on the same laptop (Debian 13 Linux, Intel Core Ultra 9 185H, its integrated Arc GPU, 32 GB, an NVMe SSD; 9-11 October 2026; the whole machine [below](#the-machine-it-grew-on)):
+**37 tok/s from Qwen3-Next-80B (a 48 GB model) on a laptop with 32 GB of memory, 24 without drafts, where llama.cpp manages 2.8; reading a prompt, 62 tok/s against 16.** Janas-LLM was faster than llama.cpp on every model compared on the same laptop (Debian 13 Linux, Intel Core Ultra 9 185H, its integrated Arc GPU, 32 GB, an NVMe SSD; 9-12 October 2026; the whole machine [below](#the-machine-it-grew-on)):
| Model | reading 1,024 tokens: Janas-LLM | llama.cpp | writing: Janas-LLM | llama.cpp |
|---|---:|---:|---:|---:|
@@ -11,6 +11,7 @@
| Qwen3.6-35B-A3B | 104 tok/s | 79 tok/s | 19 tok/s | 12 tok/s |
| Qwen3-30B-A3B | 135 tok/s | 122 tok/s | 32 tok/s | 15 tok/s |
| Gemma-4-26B-A4B-it | 84 tok/s | 76 tok/s | 18 tok/s | 12 tok/s |
+| Qwen3.8-27B (dense, 17.6 GB) | 30.6 tok/s | 25.6 tok/s | 4.4 tok/s | 2.1 tok/s |
| Gemma-4-12B-it | 65 tok/s | 46 tok/s | 9.9 tok/s | 7.1 tok/s |
| Qwen3.5-9B | 111 tok/s | 78 tok/s | 14 tok/s | 8.7 tok/s |
| Gemma-4-E4B-it | 122 tok/s | 109 tok/s | 20 tok/s | 15 tok/s |
@@ -28,7 +29,7 @@ The same models from other hands, in the catalog beside them:
| Qwen3-30B-A3B, unsloth's UD-Q3_K_XL (3 bits) | 100 tok/s | **112 tok/s** | 36 tok/s | 11 tok/s |
| Qwen3-4B, bartowski's Q4_K_M (importance matrix) | 191 tok/s | 160 tok/s | 26 tok/s | 18 tok/s |
-One exception: the 3-bit Qwen3-30B reads a prompt slower than llama.cpp, since its Q3_K weights do not go to the GPU's fast prompt yet; it writes three times as fast.
+Qwen3.8-27B: llama.cpp measured on 12 October 2026 (`llama-bench -r 2`), Janas-LLM on 13 October (`janas-bench --prompt 1024 --gen 16`, two rounds), once its prompt went whole to the GPU in one submission: 30.6 tok/s, where it read 26.4 the day before and 18.7 before the GPU's tiles for the IQ4_XS, IQ3_S and IQ4_NL weights of unsloth's UD mix. One exception: the 3-bit Qwen3-30B reads a prompt slower than llama.cpp, since its Q3_K weights do not go to the GPU's fast prompt yet; it writes three times as fast.
How they were measured, and the speeds with the drafts: [What works now](#what-works-now). On another machine the figures will be other ones: `janas-bench` measures yours.
@@ -112,7 +113,7 @@ The last column is a draft guessing the next tokens and the model checking them,
**This column was wrong until 26 September 2026**, and higher: it measured the block continuing a paragraph that repeated itself, which a model copies and the block guesses almost every time - 107 tok/s for Qwen3.5-2B, 26 for Qwen3.5-9B. The MoE figures of the time (29 and 30) happened to be lower than today's; the ChangeLog has the details.
-The comparison with llama.cpp at the top of this page was measured so: llama.cpp (build `2b18470` of 18 September 2026) with its Vulkan backend on the same integrated GPU, everything on it (`llama-bench -p 1024 -n 16 -ngl 99 -t 12`; the largest model otherwise, below), against `janas-bench --prompt 1024 --gen 16` on the same files the same days (9-11 October 2026; llama.cpp's best configuration, Janas-LLM's own choice; on 11 October three rounds each, `llama-bench -r 3` and `janas-bench --rounds 3`, for Qwen3-0.6B, Qwen3.5-0.8B, Qwen3.6-35B-A3B and the models from other hands; Qwen3-Coder-Next as Qwen3-Next-80B, below).
+The comparison with llama.cpp at the top of this page was measured so: llama.cpp (build `2b18470` of 18 September 2026) with its Vulkan backend on the same integrated GPU, everything on it (`llama-bench -p 1024 -n 16 -ngl 99 -t 12`; the largest model otherwise, below), against `janas-bench --prompt 1024 --gen 16` on the same files the same days (9-12 October 2026; llama.cpp's best configuration, Janas-LLM's own choice; on 11 October three rounds each, `llama-bench -r 3` and `janas-bench --rounds 3`, for Qwen3-0.6B, Qwen3.5-0.8B, Qwen3.6-35B-A3B and the models from other hands; Qwen3-Coder-Next as Qwen3-Next-80B, below).
On Qwen3-Next-80B-A3B, whose file is larger than this laptop's 30 GB, llama.cpp with its usual build ran out of memory as soon as the GPU took part, even with the experts left on the CPU (`-ngl 99 -ncmoe 48`): its CPU backend copies the weights into memory of its own to repack them, and the Vulkan backend copies those it leaves to the CPU into buffers the system cannot reclaim. It ran with a build without repacking (`GGML_CPU_REPACK=OFF`) and two options more, `--no-host 1 -lm mmap`, which leave the experts in the file, read through the page cache: 16 tok/s reading with the GPU, and 2.8 writing on the CPU alone (with the GPU, 2.0); these are its two figures in the table. Janas-LLM ran the same model with no option of its own, the experts it uses most in a cache of about 19 GB and the rest read from the disk. Janas-LLM's figures are one round each; the writing column is without drafts on both sides. The two tools do not measure in exactly the same way (`llama-bench` writes without a prompt before it; `janas-bench` after the 1,024 tokens), and it is one machine. llama.cpp's own CPU backend did worse on this laptop than its Vulkan one at reading (Qwen3-4B 70 tok/s on 20 threads) and as well at writing.
diff --git a/dist/README-windows.md b/dist/README-windows.md
index e8a4d90..4962d12 100644
--- a/dist/README-windows.md
+++ b/dist/README-windows.md
@@ -9,6 +9,7 @@
| Qwen3.6-35B-A3B | 104 tok/s | 79 tok/s | 19 tok/s | 12 tok/s |
| Qwen3-30B-A3B | 135 tok/s | 122 tok/s | 32 tok/s | 15 tok/s |
| Gemma-4-26B-A4B-it | 84 tok/s | 76 tok/s | 18 tok/s | 12 tok/s |
+| Qwen3.8-27B (dense, 17.6 GB) | 26.4 tok/s | 25.6 tok/s | 4.4 tok/s | 2.1 tok/s |
| Gemma-4-12B-it | 65 tok/s | 46 tok/s | 9.9 tok/s | 7.1 tok/s |
| Qwen3.5-9B | 111 tok/s | 78 tok/s | 14 tok/s | 8.7 tok/s |
| Gemma-4-E4B-it | 122 tok/s | 109 tok/s | 20 tok/s | 15 tok/s |
diff --git a/dist/README.md b/dist/README.md
index 2b35434..0e3084d 100644
--- a/dist/README.md
+++ b/dist/README.md
@@ -9,6 +9,7 @@
| Qwen3.6-35B-A3B | 104 tok/s | 79 tok/s | 19 tok/s | 12 tok/s |
| Qwen3-30B-A3B | 135 tok/s | 122 tok/s | 32 tok/s | 15 tok/s |
| Gemma-4-26B-A4B-it | 84 tok/s | 76 tok/s | 18 tok/s | 12 tok/s |
+| Qwen3.8-27B (dense, 17.6 GB) | 26.4 tok/s | 25.6 tok/s | 4.4 tok/s | 2.1 tok/s |
| Gemma-4-12B-it | 65 tok/s | 46 tok/s | 9.9 tok/s | 7.1 tok/s |
| Qwen3.5-9B | 111 tok/s | 78 tok/s | 14 tok/s | 8.7 tok/s |
| Gemma-4-E4B-it | 122 tok/s | 109 tok/s | 20 tok/s | 15 tok/s |
diff --git a/docs/features.md b/docs/features.md
index 0186473..1e29538 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -21,7 +21,7 @@
- **`janas-bench`:** measures the machine, fills its profile and writes a report.
- **Faster replies** from drafts the model verifies, so the text is exactly the one it would have written: from the model's own multi-token prediction block where it has one, from the conversation where it does not, or from a small model of the same family given with `--draft`.
- **Optional GPU** (Vulkan 1.3, integrated or discrete), used only where the engine measures that it helps, for every quantized type the CPU reads. A reply's tokens are identical with and without it; a prompt is read with the fast prompt (next).
-- **The fast prompt**, on by default since 10 October 2026: a prompt's blocks go to the GPU's tiled products (Q4_K, Q5_K, Q6_K, Q8_0, the experts of a mixture in one launch per layer, f32 and bf16 weights), and on the dense Qwen3 and Qwen3.5 models the whole block - every layer, attention, Qwen3.5's recurrent layers - goes to the GPU in one submission while the CPU rests, and on the Qwen3 and Qwen3.6 mixtures a layer a submission, the CPU only sorting the router's choice and reading the next layer's experts ahead (where the expert cache holds half the experts or more; `JANAS_GPU_MOE=0` or `1` decides instead): on a laptop the CPU working beside the GPU takes the power the GPU would use. They round the sums group by group, so a prompt is not read to the bit as the CPU reads it; against the references the most likely token agrees as often as the exact way (within 2-3 of 256 on every model measured, the mean difference of the scores within 2%). On the development laptop Qwen3-4B reads the table's prompt (below) at 220 tok/s with it and at 85 without the GPU, and every model compared reads faster than llama.cpp does on the same GPU. `JANAS_GPU_FAST_PROMPT=0` reads them the exact way.
+- **The fast prompt**, on by default since 10 October 2026: a prompt's blocks go to the GPU's tiled products (Q4_K, Q5_K, Q6_K, Q8_0, Q3_K, IQ4_XS, IQ3_S, IQ4_NL, the experts of a mixture in one launch per layer, f32 and bf16 weights), and on the dense Qwen3 and Qwen3.5 models the whole block - every layer, attention, Qwen3.5's recurrent layers - goes to the GPU in one submission while the CPU rests, and on the Qwen3 and Qwen3.6 mixtures a layer a submission, the CPU only sorting the router's choice and reading the next layer's experts ahead (where the expert cache holds half the experts or more; `JANAS_GPU_MOE=0` or `1` decides instead): on a laptop the CPU working beside the GPU takes the power the GPU would use. They round the sums group by group, so a prompt is not read to the bit as the CPU reads it; against the references the most likely token agrees as often as the exact way (within 2-3 of 256 on every model measured, the mean difference of the scores within 2%). On the development laptop Qwen3-4B reads the table's prompt (below) at 220 tok/s with it and at 85 without the GPU, and every model compared but one reads faster than llama.cpp does on the same GPU (the exception: unsloth's 3-bit Qwen3-30B, whose Q3_K experts stay on the CPU). `JANAS_GPU_FAST_PROMPT=0` reads them the exact way.
- **Experts read ahead** when the expert cache is too small for the model: the next layer's router is applied early and the experts it picks that are not in memory are read from disk while the current layer computes. It turns itself on only when the cache misses many experts a token (Qwen3-Next-80B with a 4 GiB cache: +6%) and changes no result. A long prompt is read the same way, block by block: the next layer's router is applied to the whole block and the experts most of its tokens will want are read while the current layer computes; on after a block that missed many experts. Qwen3-Next-80B reading 4,096 tokens: 36.8 to 42.0 tokens/s with a 4 GiB cache, 48.5 to 50.0 with 16 GiB (the 256 tokens written after it 1.4% slower, the cache holding other experts); Qwen3-30B-A3B, whose experts all fit, even. `JANAS_PREFETCH_PREFILL=0` turns it off.
- **Light experts not in memory are left out** when the expert cache holds less than a fifth of the experts: an expert the router weighs below 0.8/k of a token (0.95/k under a tenth), and that would have to be read from disk, is not read and not computed, and the token's other experts take its share — the cache-conditional routing of Skliar et al. (TMLR 2025). Until 8 October 2026 the engine dropped the lightest experts whether in memory or not (six of ten, or eight). Qwen3-Next-80B, four bits, 400 tokens against llama.cpp, most likely token agreeing and tokens/s: with a 2 GiB cache all ten 393 at 11.0, six 383 at 20.9, now 380 at 26.4; with 4 GiB 393 at 20.7, six 383 at 27.6, now 384 at 27.7, with the mean logit difference 0.36 against 0.53; on Italian prose with 8 GiB 382 at 18.7, eight 361 at 21.4, now 372 at 23.7. On Qwen3-30B-A3B and Qwen3.6-35B-A3B with caches of 9% and 18% of their experts (1.5-3.5 GiB), on code and Italian prose, it was faster than the old way every time, by 9-37% (Qwen3-30B-A3B with 3 GiB: 28.7 tokens/s against 24.4, 381 tokens agreeing of 400 against 377), with a mean logit difference as low or lower in seven of the eight; it agreed on fewer most likely tokens in two (Italian, 64 tokens: 47 against 54 on the 30B with 3 GiB). `/experts n` (or `0`) asks for a number of experts and turns it off.
- **Every weight type near the memory's speed**, and the same results to the bit on every path (AVX2, AVX-VNNI, GPU) for a reply's tokens (and for a prompt with `JANAS_GPU_FAST_PROMPT=0`). `tests/bench_kernels` measures each type's product on its own: writing a token, on 12 threads of the development laptop, Q8_0 84 GB/s, Q6_K 73, Q4_K 69, the other 4- and 5-bit types 59-68, Q3_K 61 (48 until 9 October 2026, when its unpacking went through the stack), IQ3_S 25, against the 81 GB/s the memory gives; and a token of Qwen3-Next-80B-A3B, Qwen3.6-35B-A3B, Qwen3-30B-A3B or a 27B, phase by phase, reads its weights at 59-62 GB/s on average. Until 6 October 2026 the Q3_K, IQ4_XS and IQ3_S products were six to thirteen times slower than that (their kernels converted a scale by calling a function), which made unsloth's UD files, which mix those types in, write at half their speed: Qwen3.8-27B UD-Q4_K_XL went from 1.7 tokens/s to 3.6.
diff --git a/src/common/catalog.c b/src/common/catalog.c
index 8d692b7..09647b6 100644
--- a/src/common/catalog.c
+++ b/src/common/catalog.c
@@ -131,6 +131,22 @@ const struct janas_model_entry janas_catalog[] = {
"67f31f57dbc78ca8c02ef5e3aa137c5df3836a3decda20b6ea057d004089c361",
.ram_gb = 8,
.fast = "--head 4"},
+ /* unsloth's UD mix (Q4_K, Q5_K, Q6_K, Q8_0 with IQ4_XS, IQ3_S, IQ4_NL
+ and Q3_K), its multi-token prediction block inside the GGUF; the
+ Qwen team publishes no GGUF of its own (12 Oct 2026) */
+ {.name = "qwen3.8-27b",
+ .what = "Qwen3.8-27B, dense, unsloth's UD mix, with its MTP block",
+ .repo = "unsloth/Qwen3.8-27B-GGUF",
+ .parts = {"Qwen3.8-27B-UD-Q4_K_XL.gguf"},
+ .part_sha =
+ {"3f227079003add2511437e5b1e94812e363385225bf6a9b47b0054a72bc8b01e"},
+ .gguf_gb = 17.56,
+ .out = "qwen3.8-27b-ud-q4kxl.jns",
+ .jns_repo = "prabanta-dev/Qwen3.8-27B-JNS",
+ .jns_gb = 17.56,
+ .flat_sha =
+ "138d1db3af7e48d3bd36a428f7a81dfd8813434521aced84459c546e4830ab5b",
+ .ram_gb = 32},
{.name = "qwen3-30b-a3b",
.what = "Qwen3-30B-A3B, mixture of experts",
.repo = "Qwen/Qwen3-30B-A3B-GGUF",
diff --git a/src/common/env_names.c b/src/common/env_names.c
index d1831a9..5c60497 100644
--- a/src/common/env_names.c
+++ b/src/common/env_names.c
@@ -37,10 +37,15 @@ const char *const JANAS_ENV_NAMES[] = {"JANAS_ALPHAVANTAGE_KEY",
"JANAS_GPU_DEVICE",
"JANAS_GPU_EXPERTS",
"JANAS_GPU_FULL_N",
+ "JANAS_GPU_HUGE",
+ "JANAS_GPU_SHORT",
+ "JANAS_GPU_NV",
"JANAS_GPU_KEEPALIVE_US",
"JANAS_GPU_MIN_N",
"JANAS_GPU_FAST_PROMPT",
"JANAS_GPU_MOE",
+ "JANAS_GPU_MV",
+ "JANAS_GPU_MVD",
"JANAS_GPU_ARENA_INPLACE",
"JANAS_GPU_EXPERT_MIN",
"JANAS_GPU_EXPERT_SHARE",
diff --git a/src/llm/expert_cache.c b/src/llm/expert_cache.c
index 357da78..a16caae 100644
--- a/src/llm/expert_cache.c
+++ b/src/llm/expert_cache.c
@@ -477,8 +477,12 @@ struct janas_expert_cache *janas_expert_cache_create(const struct janas_jns *j,
c->head = c->tail = NONE;
c->fd = janas_reopen_read(j->fd, 1);
- size_t arena_bytes = n_slots * slot_bytes + JANAS_ARENA_GUARD;
- c->arena = aligned_alloc(JANAS_JNS_ALIGN, arena_bytes);
+ /* on 2 MB boundaries, for a GPU that imports it (model_load.c
+ janas_m_huge_pages) */
+ size_t arena_bytes =
+ (n_slots * slot_bytes + JANAS_ARENA_GUARD + JANAS_HUGE_PAGE - 1) /
+ JANAS_HUGE_PAGE * JANAS_HUGE_PAGE;
+ c->arena = aligned_alloc(JANAS_HUGE_PAGE, arena_bytes);
c->where = malloc(n_keys * sizeof(int32_t));
c->key = malloc(n_slots * sizeof(int64_t));
c->prev = malloc(n_slots * sizeof(int32_t));
diff --git a/src/llm/expert_cache.h b/src/llm/expert_cache.h
index 7885173..d31c70e 100644
--- a/src/llm/expert_cache.h
+++ b/src/llm/expert_cache.h
@@ -72,6 +72,8 @@ const uint8_t *janas_expert_cache_resident(struct janas_expert_cache *c,
slot (JANAS_ARENA_GUARD): the GPU's shaders read a few bytes beyond a
matrix (Q6_K: 4), and the last slot's had nowhere to go. */
#define JANAS_ARENA_GUARD 4096
+/* the boundary of the memory a GPU may import: a huge page */
+#define JANAS_HUGE_PAGE ((size_t)2 << 20)
const uint8_t *janas_expert_cache_arena(const struct janas_expert_cache *c,
uint64_t *bytes);
uint64_t janas_expert_cache_loads(const struct janas_expert_cache *c);
diff --git a/src/llm/generate.c b/src/llm/generate.c
index f826027..92ffc4c 100644
--- a/src/llm/generate.c
+++ b/src/llm/generate.c
@@ -12,7 +12,7 @@
#include <string.h>
#include <time.h>
-#define MAX_SPEC_K 16
+#define MAX_SPEC_K JANAS_GEN_MAX_K
/* passes without drafting before spec_auto retries: doubles after every
retry that still does not pay, back to the minimum when one does */
#define AUTO_RETRY_MIN 32
@@ -177,6 +177,16 @@ static int plan_lookup(const struct planner *p, int avail, double per_draft)
return best;
}
+/* At most k drafts, and no more than the pass the model holds worth
+ asking for takes (janas_llm_model_pass_cap: the GPU's shaders of a few
+ vectors): the planner's line through the costs it has measured cannot
+ see the step past them, and paid for one pass to learn it. */
+static int drafts_cap(const struct janas_llm_model *m, int k)
+{
+ uint32_t cap = janas_llm_model_pass_cap(m);
+ return cap > 1 && k > (int)cap - 1 ? (int)cap - 1 : k;
+}
+
static int plan_drafts(const struct planner *p, const float *survs, int avail)
{
double expect = 1.0, best_rate = 1.0 / pass_cost(p, 1);
@@ -897,7 +907,7 @@ int janas_llm_session_next(struct janas_llm_session *s, int32_t *token)
int copies =
o->spec_mode == JANAS_SPEC_LOOKUP || o->spec_mode == JANAS_SPEC_DRAFT;
if (o->spec_mode == JANAS_SPEC_LOOKUP && s->off_left == 0 && !probe) {
- nd = lookup_draft(s->hist, s->n, o->spec_k, block + 1);
+ nd = lookup_draft(s->hist, s->n, drafts_cap(m, o->spec_k), block + 1);
if (nd > 0) {
int want = plan_lookup(&s->pl, nd, 0.0);
if (!want && s->st.passes % 16 == 0)
@@ -906,7 +916,7 @@ int janas_llm_session_next(struct janas_llm_session *s, int32_t *token)
}
}
if (o->spec_mode == JANAS_SPEC_DRAFT && s->off_left == 0 && !probe) {
- int want = plan_lookup(&s->pl, o->spec_k, s->pl.dcost);
+ int want = plan_lookup(&s->pl, drafts_cap(m, o->spec_k), s->pl.dcost);
if (!want && s->st.passes % 16 == 0)
want = 1;
if (want > 0) {
@@ -924,7 +934,8 @@ int janas_llm_session_next(struct janas_llm_session *s, int32_t *token)
}
}
if (s->mtp && drafts_wanted && s->off_left == 0 && !probe) {
- nd = plan ? plan_drafts(&s->pl, s->msurv, s->n_mdraft) : s->n_mdraft;
+ nd = plan ? plan_drafts(&s->pl, s->msurv, drafts_cap(m, s->n_mdraft))
+ : s->n_mdraft;
/* one pass in sixteen drafts anyway, as the copies do: a pass of
two tokens timed once while the disk was busy made the planner
refuse every draft, and with none its cost was never timed again
@@ -968,6 +979,14 @@ int janas_llm_session_next(struct janas_llm_session *s, int32_t *token)
s->n_kv = pos + (uint32_t)acc + 1;
s->st.new_tokens += (uint32_t)acc + 1;
int settling_now = janas_llm_model_settling(s->m);
+ for (int i = 0; i < nd; i++) {
+ s->st.pos_tried[i]++;
+ s->st.pos_won[i] += i < acc;
+ }
+ if (!settling_now) {
+ s->st.pass_count[nd + 1]++;
+ s->st.pass_seconds[nd + 1] += dt;
+ }
if ((plan || copies) && !settling_now) {
double *tt = &s->pl.t[nd + 1];
*tt = *tt > 0 ? 0.8 * *tt + 0.2 * dt : dt;
@@ -1032,7 +1051,8 @@ int janas_llm_session_next(struct janas_llm_session *s, int32_t *token)
/* the MTP rows of the new tokens always (the block's KV cache must stay
complete for later turns), drafts only when generation goes on */
if (s->mtp) {
- if (mtp_step(m, s->hist, pos, (uint32_t)acc, o->spec_k,
+ if (mtp_step(m, s->hist, pos, (uint32_t)acc,
+ plan ? drafts_cap(m, o->spec_k) : o->spec_k,
s->off_left == 0 && !is_stop(o, t), o->spec_min_conf,
plan ? &s->pl : NULL, s->hrow, s->mdraft, s->msurv,
&s->n_mdraft) != 0)
diff --git a/src/llm/generate.h b/src/llm/generate.h
index 2f98a48..957ee1c 100644
--- a/src/llm/generate.h
+++ b/src/llm/generate.h
@@ -25,6 +25,8 @@ enum janas_spec_mode {
};
#define JANAS_GEN_MAX_STOP 4
+/* the longest chain of drafts a pass verifies (spec_k) */
+#define JANAS_GEN_MAX_K 16
struct janas_gen_options {
int spec_mode; /* enum janas_spec_mode */
@@ -75,6 +77,12 @@ struct janas_gen_stats {
A bin the planner never finds worth trying stays empty, so this says
what it has actually learned. */
uint32_t cal_tried[10], cal_won[10];
+ /* by position in the chain (0: the first draft), the drafts verified and
+ those accepted; by the tokens in a pass (1: no drafts), the passes and
+ their seconds - what the planner weighs, as it turned out */
+ uint32_t pos_tried[JANAS_GEN_MAX_K], pos_won[JANAS_GEN_MAX_K];
+ uint32_t pass_count[JANAS_GEN_MAX_K + 2];
+ double pass_seconds[JANAS_GEN_MAX_K + 2];
};
/*
diff --git a/src/llm/gpu.c b/src/llm/gpu.c
index 0ac5c71..db22a87 100644
--- a/src/llm/gpu.c
+++ b/src/llm/gpu.c
@@ -30,6 +30,9 @@
#include "q6kp_mmq.h" /* janas_spv_q6kp_mmq */
#include "q6k_mmq.h" /* janas_spv_q6k_mmq */
#include "q3k_mmq.h" /* janas_spv_q3k_mmq */
+#include "iq4xs_mmq.h" /* janas_spv_iq4xs_mmq */
+#include "iq3s_mmq.h" /* janas_spv_iq3s_mmq */
+#include "iq4nl_mmq.h" /* janas_spv_iq4nl_mmq */
#include "q80_mmq.h" /* janas_spv_q80_mmq */
#include "q5k_mmq.h" /* janas_spv_q5k_mmq */
#include "dense_mm.h" /* janas_spv_dense_mm */
@@ -42,6 +45,11 @@
#include "q6k_row.h" /* janas_spv_q6k_row */
#include "q6kp_row.h" /* janas_spv_q6kp_row */
#include "q6ka_row.h" /* janas_spv_q6ka_row */
+#include "q4k_mv.h" /* janas_spv_q4k_mv */
+#include "q4k_mvd.h" /* janas_spv_q4k_mvd */
+#include "q6k_mvd.h" /* janas_spv_q6k_mvd */
+#include "q5k_mvd.h" /* janas_spv_q5k_mvd */
+#include "iq4xs_mvd.h" /* janas_spv_iq4xs_mvd */
static double now(void)
{
@@ -327,8 +335,7 @@ VkResult janas_g_make_pipeline(struct janas_gpu *g, const uint32_t *code,
size_t bytes, VkShaderModule *sm,
VkPipeline *pipe, uint32_t kind)
{
- return janas_g_make_pipeline_nv(g, code, bytes, sm, pipe, kind,
- NV_PER_GROUP);
+ return janas_g_make_pipeline_nv(g, code, bytes, sm, pipe, kind, g->nvg);
}
static VkResult make_pipeline(struct janas_gpu *g, const uint32_t *code,
@@ -388,7 +395,7 @@ uint32_t janas_g_make_pipeline_sg(struct janas_gpu *g, const uint32_t *code,
if (!g->sg_control || sg < g->sg_min || sg > g->sg_max ||
(sg & (sg - 1)) != 0)
sg = g->sg;
- return make_pipeline(g, code, bytes, sm, pipe, kind, NV_PER_GROUP, sg) ==
+ return make_pipeline(g, code, bytes, sm, pipe, kind, g->nvg, sg) ==
VK_SUCCESS
? sg
: 0;
@@ -397,6 +404,13 @@ uint32_t janas_g_make_pipeline_sg(struct janas_gpu *g, const uint32_t *code,
struct janas_gpu *janas_gpu_create(char *err, size_t err_len)
{
struct janas_gpu *g = calloc(1, sizeof(*g));
+ /* vectors a product's workgroup takes (JANAS_GPU_NV, being measured:
+ with 8 the compiler spills the products' registers) */
+ if (g) {
+ const char *nve = getenv("JANAS_GPU_NV");
+ g->nvg = nve && atoi(nve) > 0 && atoi(nve) <= 16 ? (uint32_t)atoi(nve)
+ : NV_PER_GROUP;
+ }
if (!g) {
snprintf(err, err_len, "out of memory");
return NULL;
@@ -527,6 +541,15 @@ struct janas_gpu *janas_gpu_create(char *err, size_t err_len)
(r = make_pipeline(g, janas_spv_q3k_mmq, sizeof(janas_spv_q3k_mmq),
&g->sm_mm3, &g->pipe_mm3, 0, NV_PER_GROUP, g->sg)) !=
VK_SUCCESS ||
+ (r = make_pipeline(g, janas_spv_iq4xs_mmq, sizeof(janas_spv_iq4xs_mmq),
+ &g->sm_mmx4, &g->pipe_mmx4, 0, NV_PER_GROUP,
+ g->sg)) != VK_SUCCESS ||
+ (r = make_pipeline(g, janas_spv_iq3s_mmq, sizeof(janas_spv_iq3s_mmq),
+ &g->sm_mmi3, &g->pipe_mmi3, 0, NV_PER_GROUP,
+ g->sg)) != VK_SUCCESS ||
+ (r = make_pipeline(g, janas_spv_iq4nl_mmq, sizeof(janas_spv_iq4nl_mmq),
+ &g->sm_mmn4, &g->pipe_mmn4, 0, NV_PER_GROUP,
+ g->sg)) != VK_SUCCESS ||
(r = make_pipeline(g, janas_spv_q80_mmq, sizeof(janas_spv_q80_mmq),
&g->sm_mm80, &g->pipe_mm80, 0, NV_PER_GROUP,
g->sg)) != VK_SUCCESS ||
@@ -630,6 +653,32 @@ struct janas_gpu *janas_gpu_create(char *err, size_t err_len)
goto fail;
}
}
+ /* Q4_K on a few vectors, a row an invocation (JANAS_GPU_MV=1, being
+ measured) */
+ if ((r = janas_g_make_pipeline_nv(
+ g, janas_spv_q4k_mv, sizeof(janas_spv_q4k_mv), &g->sm_mv,
+ &g->pipe_mv, 0, MV_NV)) != VK_SUCCESS) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
+ /* ... and Q4_K, Q6_K, Q5_K and IQ4_XS on 2 to 8 with the lanes on
+ the vectors, where a subgroup is 8 lanes, one a vector */
+ if (g->sg == 8 &&
+ ((r = janas_g_make_pipeline_nv(
+ g, janas_spv_q4k_mvd, sizeof(janas_spv_q4k_mvd), &g->sm_mvd,
+ &g->pipe_mvd, 0, 8)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline_nv(
+ g, janas_spv_q6k_mvd, sizeof(janas_spv_q6k_mvd), &g->sm_mvd6,
+ &g->pipe_mvd6, 0, 8)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline_nv(
+ g, janas_spv_q5k_mvd, sizeof(janas_spv_q5k_mvd), &g->sm_mvd5,
+ &g->pipe_mvd5, 0, 8)) != VK_SUCCESS ||
+ (r = janas_g_make_pipeline_nv(
+ g, janas_spv_iq4xs_mvd, sizeof(janas_spv_iq4xs_mvd),
+ &g->sm_mvdx4, &g->pipe_mvdx4, 0, 8)) != VK_SUCCESS)) {
+ set_err(err, err_len, "cannot create the shaders", r);
+ goto fail;
+ }
}
for (uint32_t k = 0; k < 4; k++)
if ((r = janas_g_make_pipeline(
@@ -755,6 +804,26 @@ void janas_gpu_destroy(struct janas_gpu *g)
g->vkDestroyPipeline(g->dev, g->rp_q6ka, NULL);
if (g->rm_q6ka)
g->vkDestroyShaderModule(g->dev, g->rm_q6ka, NULL);
+ if (g->pipe_mv)
+ g->vkDestroyPipeline(g->dev, g->pipe_mv, NULL);
+ if (g->sm_mv)
+ g->vkDestroyShaderModule(g->dev, g->sm_mv, NULL);
+ if (g->pipe_mvd)
+ g->vkDestroyPipeline(g->dev, g->pipe_mvd, NULL);
+ if (g->sm_mvd)
+ g->vkDestroyShaderModule(g->dev, g->sm_mvd, NULL);
+ if (g->pipe_mvd6)
+ g->vkDestroyPipeline(g->dev, g->pipe_mvd6, NULL);
+ if (g->sm_mvd6)
+ g->vkDestroyShaderModule(g->dev, g->sm_mvd6, NULL);
+ if (g->pipe_mvd5)
+ g->vkDestroyPipeline(g->dev, g->pipe_mvd5, NULL);
+ if (g->sm_mvd5)
+ g->vkDestroyShaderModule(g->dev, g->sm_mvd5, NULL);
+ if (g->pipe_mvdx4)
+ g->vkDestroyPipeline(g->dev, g->pipe_mvdx4, NULL);
+ if (g->sm_mvdx4)
+ g->vkDestroyShaderModule(g->dev, g->sm_mvdx4, NULL);
for (int i = 0; i < 2; i++) {
if (g->rp_tile[i])
g->vkDestroyPipeline(g->dev, g->rp_tile[i], NULL);
@@ -790,6 +859,12 @@ void janas_gpu_destroy(struct janas_gpu *g)
g->vkDestroyPipeline(g->dev, g->pipe_mm6s, NULL);
if (g->pipe_mm3)
g->vkDestroyPipeline(g->dev, g->pipe_mm3, NULL);
+ if (g->pipe_mmx4)
+ g->vkDestroyPipeline(g->dev, g->pipe_mmx4, NULL);
+ if (g->pipe_mmi3)
+ g->vkDestroyPipeline(g->dev, g->pipe_mmi3, NULL);
+ if (g->pipe_mmn4)
+ g->vkDestroyPipeline(g->dev, g->pipe_mmn4, NULL);
if (g->pipe_mm80)
g->vkDestroyPipeline(g->dev, g->pipe_mm80, NULL);
if (g->pipe_mm5)
@@ -816,6 +891,12 @@ void janas_gpu_destroy(struct janas_gpu *g)
g->vkDestroyShaderModule(g->dev, g->sm_mm6s, NULL);
if (g->sm_mm3)
g->vkDestroyShaderModule(g->dev, g->sm_mm3, NULL);
+ if (g->sm_mmx4)
+ g->vkDestroyShaderModule(g->dev, g->sm_mmx4, NULL);
+ if (g->sm_mmi3)
+ g->vkDestroyShaderModule(g->dev, g->sm_mmi3, NULL);
+ if (g->sm_mmn4)
+ g->vkDestroyShaderModule(g->dev, g->sm_mmn4, NULL);
if (g->sm_mm80)
g->vkDestroyShaderModule(g->dev, g->sm_mm80, NULL);
if (g->sm_mm6)
@@ -1413,12 +1494,75 @@ static int mm_on(void)
return on;
}
+/* q4k_mv for Q4_K on 2 to JANAS_GPU_FAST_N - 1 vectors (JANAS_GPU_MV=1;
+ off by default while it is measured) */
+static int mv_on(void)
+{
+ static int on = -1;
+ if (on < 0)
+ on = getenv("JANAS_GPU_MV") && atoi(getenv("JANAS_GPU_MV")) > 0;
+ return on;
+}
+
+/* q4k_mvd, q6k_mvd, q5k_mvd and iq4xs_mvd for Q4_K, Q6_K, Q5_K and IQ4_XS
+ on 2 to 8 vectors (JANAS_GPU_MVD=0 leaves them out) */
+static int mvd_on(void)
+{
+ static int on = -1;
+ if (on < 0)
+ on = !getenv("JANAS_GPU_MVD") || atoi(getenv("JANAS_GPU_MVD")) > 0;
+ return on;
+}
+
+/* The shader of a type with the lanes on the vectors (2 to 8 vectors), or
+ none. */
+static VkPipeline mvd_pipe(const struct janas_gpu *g, int type)
+{
+ return type == JANAS_Q4_K ? g->pipe_mvd
+ : type == JANAS_Q6_K ? g->pipe_mvd6
+ : type == JANAS_Q5_K ? g->pipe_mvd5
+ : type == JANAS_IQ4_XS ? g->pipe_mvdx4
+ : VK_NULL_HANDLE;
+}
+
+size_t janas_gpu_few_max(const struct janas_gpu *g)
+{
+ return g->pipe_mvd && mvd_on() ? 8 : 0;
+}
+
+/* Whether bytes from a lie within one 4 GB of the address space (the high
+ word the same throughout), as q4k_mv's and q4k_mvd's addressing needs. */
+static int in_4g(VkDeviceAddress a, size_t bytes)
+{
+ return bytes == 0 || (a >> 32) == ((a + bytes - 1) >> 32);
+}
+
+/* Whether a pipeline is one of the shaders of a row an invocation
+ (*_matvec.comp, q4k_mv.comp), which take the groups of vectors on
+ workgroup x and the rows on y. */
+static int vectors_first(const struct janas_gpu *g, VkPipeline p)
+{
+ if (p == g->pipe || p == g->pipe6 || p == g->pipe6p || p == g->pipe5 ||
+ p == g->pipe80 || p == g->pipex4 || p == g->pipe3 || p == g->pipei3 ||
+ p == g->pipe_mv || p == g->pipe_mvd || p == g->pipe_mvd6 ||
+ p == g->pipe_mvd5 || p == g->pipe_mvdx4)
+ return 1;
+ for (int k = 0; k < 4; k++)
+ if (p == g->pipe32[k])
+ return 1;
+ for (int i = 0; i < N_PROD; i++)
+ if (p == g->pp1[i])
+ return 1;
+ return 0;
+}
+
/* A product the fast prompt's shaders take. */
static int fast_type(const struct janas_matvec_task *t)
{
return t->type == JANAS_Q4_K || t->type == JANAS_Q6_K ||
t->type == JANAS_Q8_0 || t->type == JANAS_Q5_K ||
- t->type == JANAS_Q3_K ||
+ t->type == JANAS_Q3_K || t->type == JANAS_IQ4_XS ||
+ t->type == JANAS_IQ3_S || t->type == JANAS_IQ4_NL ||
(t->type == JANAS_Q6_K_P && plane_level(t) == 3);
}
@@ -1438,7 +1582,7 @@ int janas_g_record_task(struct janas_gpu *g, VkPipeline *bound,
size_t nb = t->cols / JANAS_QK, nv = t->n_vec ? t->n_vec : 1;
/* a single vector: a subgroup per row where there is such a shader
(rows_wg rows a workgroup), else the shader made for one vector */
- uint32_t nvg = NV_PER_GROUP, rows_wg = ROWS_PER_GROUP;
+ uint32_t nvg = g->nvg, rows_wg = ROWS_PER_GROUP;
int pk = prod_index(t->type);
/* up to row_nv vectors (JANAS_GPU_ROW_NV, 0 to 8; 4 by default) a row
shader takes them, its variant for 2, 4 or 8 (kv), where the
@@ -1448,6 +1592,11 @@ int janas_g_record_task(struct janas_gpu *g, VkPipeline *bound,
row_nv =
getenv("JANAS_GPU_ROW_NV") ? atoi(getenv("JANAS_GPU_ROW_NV")) : 4;
int kv = nv <= 2 ? 0 : nv <= 4 ? 1 : 2;
+ const struct region *rg = janas_g_find_region(g, t->w, read_bytes(t, rows));
+ if (!rg)
+ return -1;
+ VkDeviceAddress wa =
+ rg->addr + (VkDeviceAddress)((const uint8_t *)t->w - rg->host);
if (t->type == JANAS_Q4_K_T || t->type == JANAS_Q6_K_AT) {
VkPipeline rp = g->rp_tile[t->type == JANAS_Q6_K_AT];
if (nv != 1 || !rp)
@@ -1463,6 +1612,17 @@ int janas_g_record_task(struct janas_gpu *g, VkPipeline *bound,
want = rp;
nvg = nv == 1 ? 1 : 2u << kv;
rows_wg = 64 / g->sg;
+ } else if (nv > 1 && nv <= 8 && mvd_pipe(g, t->type) && mvd_on() &&
+ in_4g(wa, read_bytes(t, rows)) &&
+ in_4g(xa, nv * nb * GPU_BLOCK)) {
+ want = mvd_pipe(g, t->type);
+ nvg = 8;
+ rows_wg = MVD_ROWS;
+ } else if (t->type == JANAS_Q4_K && nv > 1 && nv < JANAS_GPU_FAST_N &&
+ g->pipe_mv && mv_on() && in_4g(wa, read_bytes(t, rows)) &&
+ in_4g(xa, nv * nb * GPU_BLOCK)) {
+ want = g->pipe_mv;
+ nvg = MV_NV;
} else if (nv == 1 && pk >= 0 && g->rp[pk] && nb <= 128 &&
!getenv("JANAS_GPU_NO_ROW")) {
want = g->rp[pk];
@@ -1491,6 +1651,21 @@ int janas_g_record_task(struct janas_gpu *g, VkPipeline *bound,
want = g->pipe_mm3;
nvg = 64;
rows_wg = 64;
+ } else if (t->type == JANAS_IQ4_XS && nv >= JANAS_GPU_FAST_N &&
+ g->pipe_mmx4 && mm_on()) {
+ want = g->pipe_mmx4;
+ nvg = 64;
+ rows_wg = 64;
+ } else if (t->type == JANAS_IQ3_S && nv >= JANAS_GPU_FAST_N &&
+ g->pipe_mmi3 && mm_on()) {
+ want = g->pipe_mmi3;
+ nvg = 64;
+ rows_wg = 64;
+ } else if (t->type == JANAS_IQ4_NL && nv >= JANAS_GPU_FAST_N &&
+ g->pipe_mmn4 && mm_on()) {
+ want = g->pipe_mmn4;
+ nvg = 64;
+ rows_wg = 64;
} else if (t->type == JANAS_Q5_K && nv >= JANAS_GPU_FAST_N && g->pipe_mm5 &&
mm_on()) {
want = g->pipe_mm5;
@@ -1512,11 +1687,6 @@ int janas_g_record_task(struct janas_gpu *g, VkPipeline *bound,
g->vkCmdBindPipeline(g->cb, VK_PIPELINE_BIND_POINT_COMPUTE, want);
*bound = want;
}
- const struct region *rg = janas_g_find_region(g, t->w, read_bytes(t, rows));
- if (!rg)
- return -1;
- VkDeviceAddress wa =
- rg->addr + (VkDeviceAddress)((const uint8_t *)t->w - rg->host);
struct push pc = {.rows = (uint32_t)rows,
.nb = (uint32_t)nb,
.nv = (uint32_t)nv,
@@ -1539,8 +1709,16 @@ int janas_g_record_task(struct janas_gpu *g, VkPipeline *bound,
}
g->vkCmdPushConstants(g->cb, g->pl, VK_SHADER_STAGE_COMPUTE_BIT, 0,
sizeof(pc), &pc);
- g->vkCmdDispatch(g->cb, (uint32_t)((rows + rows_wg - 1) / rows_wg),
- (uint32_t)((nv + nvg - 1) / nvg), 1);
+ /* the shaders of a row an invocation take the vectors' groups on x and
+ the rows on y: the groups of the same rows go out together, and those
+ after the first find the weights in the L3 (Q4_K 17408 x 5120, 16
+ vectors: 1.24 ms instead of 2.06, 13 Oct 2026); the others, rows on x */
+ uint32_t gr = (uint32_t)((rows + rows_wg - 1) / rows_wg),
+ gv = (uint32_t)((nv + nvg - 1) / nvg);
+ if (vectors_first(g, want))
+ g->vkCmdDispatch(g->cb, gv, gr, 1);
+ else
+ g->vkCmdDispatch(g->cb, gr, gv, 1);
return 0;
}
@@ -1572,8 +1750,9 @@ static int record_product(struct janas_gpu *g, VkPipeline *bound, int type,
janas_g_push_addr(pc.y, ya);
g->vkCmdPushConstants(g->cb, g->pl, VK_SHADER_STAGE_COMPUTE_BIT, 0,
sizeof(pc), &pc);
+ /* q4k_matvec and q6k_matvec: the rows on workgroup y */
g->vkCmdDispatch(
- g->cb, (uint32_t)((rows + ROWS_PER_GROUP - 1) / ROWS_PER_GROUP), 1, 1);
+ g->cb, 1, (uint32_t)((rows + ROWS_PER_GROUP - 1) / ROWS_PER_GROUP), 1);
return 0;
}
@@ -2275,6 +2454,12 @@ size_t janas_gpu_min_n(const struct janas_gpu *g)
return (size_t)-1;
}
+size_t janas_gpu_few_max(const struct janas_gpu *g)
+{
+ (void)g;
+ return 0;
+}
+
int janas_gpu_dense_mm(struct janas_gpu *g, int bf16, const void *w,
const float *x, float *y, size_t rows, size_t cols,
size_t n, float scale)
diff --git a/src/llm/gpu.h b/src/llm/gpu.h
index 24985af..945b567 100644
--- a/src/llm/gpu.h
+++ b/src/llm/gpu.h
@@ -141,5 +141,10 @@ unsigned janas_gpu_subgroup(const struct janas_gpu *g);
discrete GPU (single tokens too), 2 on an integrated one;
JANAS_GPU_MIN_N sets it. */
size_t janas_gpu_min_n(const struct janas_gpu *g);
+/* The most vectors the shaders with the lanes on the vectors take
+ (*_mvd.comp: subgroups of 8 lanes, JANAS_GPU_MVD=0 leaves them out),
+ beyond which a product goes to the slower shaders of many vectors: 8,
+ or 0 without them. */
+size_t janas_gpu_few_max(const struct janas_gpu *g);
#endif
diff --git a/src/llm/gpu_impl.h b/src/llm/gpu_impl.h
index 2dc0b4e..73b2f56 100644
--- a/src/llm/gpu_impl.h
+++ b/src/llm/gpu_impl.h
@@ -34,6 +34,8 @@
#define Y_STAGE_BYTES ((size_t)32 << 20)
#define ROWS_PER_GROUP 64 /* local_size_x of the shader */
#define NV_PER_GROUP 8 /* its NV */
+#define MV_NV 8 /* q4k_mv's */
+#define MVD_ROWS 32 /* q4k_mvd's rows a workgroup */
#define GPU_BLOCK 320 /* a Q8_K block in the shader's layout */
#define SHARE_SLOTS 64
#define MAX_GROUP 64
@@ -149,10 +151,13 @@ struct janas_gpu {
VkPipeline pipe32[4];
VkPipeline pipex4, pipe3, pipei3; /* IQ4_XS, Q3_K, IQ3_S */
/* Q4_K on many vectors in tiles (q4k_mm.comp), MM_ROWS x MM_VECS */
- VkShaderModule sm_mm, sm_mm6, sm_mm6s, sm_mm80, sm_mm5, sm_mm3, sm_dm[2];
+ VkShaderModule sm_mm, sm_mm6, sm_mm6s, sm_mm80, sm_mm5, sm_mm3, sm_mmx4,
+ sm_mmi3, sm_mmn4,
+ sm_dm[2]; /* sm_mmx4 IQ4_XS, mmi3 IQ3_S, mmn4 IQ4_NL */
VkPipeline pipe_mm, pipe_mm6, pipe_mm6s, pipe_mm80, pipe_mm5, pipe_mm3,
- pipe_dm[2];
+ pipe_mmx4, pipe_mmi3, pipe_mmn4, pipe_dm[2];
int only_fast; /* janas_gpu_set_only_fast */
+ uint32_t nvg; /* vectors a product's workgroup takes (NV_PER_GROUP) */
/* a mixture's experts in one dispatch (experts_id): Q4_K, Q6_K_P */
VkShaderModule sm_id4, sm_id6, sm_id6s;
VkPipeline pipe_id4, pipe_id6, pipe_id6s;
@@ -172,6 +177,11 @@ struct janas_gpu {
[k] up to 2 << k of them; [][3] the aligned Q6_K */
VkShaderModule rmv[3][4];
VkPipeline rpv[3][4];
+ VkShaderModule sm_mv; /* q4k_mv, MV_NV vectors (JANAS_GPU_MV=1) */
+ VkPipeline pipe_mv;
+ /* q4k_mvd, q6k_mvd, q5k_mvd, iq4xs_mvd: 2-8 vectors, subgroups of 8 */
+ VkShaderModule sm_mvd, sm_mvd6, sm_mvd5, sm_mvdx4;
+ VkPipeline pipe_mvd, pipe_mvd6, pipe_mvd5, pipe_mvdx4;
VkCommandPool cp;
VkCommandBuffer cb;
VkFence fence;
diff --git a/src/llm/gpu_token.c b/src/llm/gpu_token.c
index 2f7c5ae..a1a0563 100644
--- a/src/llm/gpu_token.c
+++ b/src/llm/gpu_token.c
@@ -29,6 +29,8 @@
#include "gdn_l2.h" /* janas_spv_gdn_l2 */
#include "gdn_rec.h" /* janas_spv_gdn_rec */
#include "gdn_gate.h" /* janas_spv_gdn_gate */
+#include "gdn_ba.h" /* janas_spv_gdn_ba */
+#include "gdn_act.h" /* janas_spv_gdn_act */
#include "moe_topk.h" /* janas_spv_moe_topk */
#include "moe_gather.h" /* janas_spv_moe_gather */
#include "moe_combine.h" /* janas_spv_moe_combine */
@@ -43,9 +45,14 @@ static uint32_t att_sg(void)
const char *e = getenv("JANAS_GPU_ATT_SG");
return e ? (uint32_t)atoi(e) : 16;
}
-static const char *const ph_name[PH_N] = {
- "norm+quant", "q k v", "q k norm+rope", "attention", "attn merge",
- "wo", "gate+up", "act", "down", "output"};
+static const char *const ph_name[PH_N] = {"norm+quant", "q k v",
+ "q k norm+rope", "attention",
+ "attn merge", "wo",
+ "gate+up", "act",
+ "down", "output",
+ "ssm q k v z", "ssm beta+alpha",
+ "ssm conv", "ssm recurrence",
+ "ssm gate"};
int janas_gpu_shares_host(const struct janas_gpu *g)
{
return g && !g->broken && !g->discrete && g->host_import &&
@@ -85,8 +92,6 @@ static const char *check_ffn(const struct janas_gpu *g,
for (int i = 0; i < 3; i++)
if (!janas_gpu_can(g, f[i]))
return "a feed-forward weight the GPU cannot compute";
- if (janas_g_x_in_32(ly->down.type))
- return "a down matrix in blocks of 32";
return NULL;
}
int dt = ly->down.type;
@@ -238,7 +243,7 @@ struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
t->o_yd = take(&at, nb * md->dm * 4);
t->o_rope = take(&at, nb * md->n_rot * 4);
t->o_logits = take(&at, nb * md->n_vocab * 4);
- t->o_pos = take(&at, 16);
+ t->o_pos = take(&at, 32); /* janas_gpu_tok_run's five words */
t->o_part = take(&at, t->part_floats * 4);
t->o_xnf = take(&at, nb * md->dm * 4);
t->o_hid = take(&at, nb * md->dm * 4);
@@ -247,9 +252,19 @@ struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
if (md->n_rec) {
t->o_mix = take(&at, nb * md->conv_ch * 4);
t->o_z = take(&at, nb * md->d_inner * 4);
- t->o_conv = take(&at, nb * md->conv_ch * 4);
+ t->o_conv =
+ take(&at, (nb + JANAS_GPU_TOK_MAX_REPLAY) * md->conv_ch * 4);
t->o_ba = take(&at, nb * 2 * md->nv * 4);
t->o_att = take(&at, nb * md->d_inner * 4);
+ t->o_bd = take(&at, nb * 2 * md->nv * 4);
+ /* the log where the GPU reads and writes it: then the blocks short
+ enough to be logged (a chain of drafts) may come here too */
+ size_t lr = (size_t)md->n_rec * md->log_rows;
+ t->log_ok = md->log_mixed && md->log_beta && md->log_decay &&
+ md->log_rows >= JANAS_GPU_TOK_MAX_REPLAY &&
+ janas_gt_addr_of(g, md->log_mixed, lr * md->conv_ch * 4) &&
+ janas_gt_addr_of(g, md->log_beta, lr * md->nv * 4) &&
+ janas_gt_addr_of(g, md->log_decay, lr * md->nv * 4);
}
uint32_t ne = md->n_expert;
if (ne) {
@@ -273,13 +288,22 @@ struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
t->o_tab1 = take(&at, (t->tiles1 + 2 * (np / 16 + ne)) * 16);
t->o_tab2 = take(&at, (t->tiles2 + np / 16 + ne) * 16);
t->o_ind = take(&at, 32);
- t->o_hf = take(&at, nb * md->ff * 4);
- t->o_h32 = take(&at, nb * md->ff / JANAS_QK * 320);
t->cnt = calloc(ne + 1, sizeof(uint32_t));
t->fill = calloc(ne, sizeof(uint32_t));
t->ids = calloc(ne, sizeof(uint32_t));
t->slots = calloc(ne, sizeof(*t->slots));
}
+ /* a down matrix in blocks of 32 - a shared expert's Q8_0, a dense
+ layer's IQ4_NL (unsloth's UD files mix it in) - takes the activation
+ as floats, quantized then into both layouts (janas_gt_rec_ffn) */
+ int d32 = 0;
+ for (uint32_t l = 0; l < md->n_layer; l++)
+ d32 |= janas_g_x_in_32(ne ? md->layers[l].sh_down.type
+ : md->layers[l].down.type);
+ if (d32) {
+ t->o_hf = take(&at, nb * md->ff * 4);
+ t->o_h32 = take(&at, nb * md->ff / JANAS_QK * 320);
+ }
if (md->n_rec || ne) {
t->par = calloc((size_t)md->n_layer * PAR_N, sizeof(size_t));
if (!t->par || (ne && (!t->cnt || !t->fill || !t->ids || !t->slots))) {
@@ -329,6 +353,10 @@ struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
janas_g_make_pipeline(g, janas_spv_gdn_gate,
sizeof(janas_spv_gdn_gate), &t->sm_gg, &t->p_gg,
0) != VK_SUCCESS ||
+ janas_g_make_pipeline(g, janas_spv_gdn_ba, sizeof(janas_spv_gdn_ba),
+ &t->sm_gb, &t->p_gb, 0) != VK_SUCCESS ||
+ janas_g_make_pipeline(g, janas_spv_gdn_act, sizeof(janas_spv_gdn_act),
+ &t->sm_gx, &t->p_gx, 0) != VK_SUCCESS ||
!g->pipe_dm[0])) ||
(ne && (janas_g_make_pipeline(g, janas_spv_moe_topk,
sizeof(janas_spv_moe_topk), &t->sm_tk,
@@ -338,10 +366,10 @@ struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
&t->p_ga, 0) != VK_SUCCESS ||
janas_g_make_pipeline(g, janas_spv_moe_combine,
sizeof(janas_spv_moe_combine), &t->sm_cb,
- &t->p_cb, 0) != VK_SUCCESS ||
- janas_g_make_pipeline(g, janas_spv_silu_mul,
+ &t->p_cb, 0) != VK_SUCCESS)) ||
+ (d32 && janas_g_make_pipeline(g, janas_spv_silu_mul,
sizeof(janas_spv_silu_mul), &t->sm_sm,
- &t->p_sm, 0) != VK_SUCCESS))) {
+ &t->p_sm, 0) != VK_SUCCESS)) {
fail(err, err_len, "cannot create the token's buffers or shaders");
janas_gpu_tok_destroy(g, t);
return NULL;
@@ -399,10 +427,11 @@ void janas_gpu_tok_destroy(struct janas_gpu *g, struct janas_gpu_tok *t)
all += t->ph_ns[i];
if (t->tokens) {
fprintf(stderr,
- "gpu token profile, %llu tokens, %.2f ms a token "
- "(%.2f ms from submission to fence, %.2f ms copying the "
- "logits):\n",
- (unsigned long long)t->tokens, all / t->tokens * 1e-6,
+ "gpu token profile, %llu passes of %.1f tokens, %.2f ms "
+ "a pass (%.2f ms from submission to fence, %.2f ms "
+ "copying the logits):\n",
+ (unsigned long long)t->tokens,
+ (double)t->pass_tokens / t->tokens, all / t->tokens * 1e-6,
t->wall_ns / t->tokens * 1e-6,
t->copy_ns / t->tokens * 1e-6);
for (int i = 0; i < PH_N; i++)
@@ -419,18 +448,18 @@ void janas_gpu_tok_destroy(struct janas_gpu *g, struct janas_gpu_tok *t)
g->vkFreeCommandBuffers(g->dev, g->cp, 1, &t->cb[n][a][h]);
janas_gt_free_segments(g, t, &t->seg_cb[n][a][h]);
}
- VkPipeline p[13] = {t->p_nq, t->p_qk, t->p_at, t->p_am, t->p_gc,
+ VkPipeline p[15] = {t->p_nq, t->p_qk, t->p_at, t->p_am, t->p_gc,
t->p_gs, t->p_gl, t->p_gr, t->p_gg, t->p_tk,
- t->p_ga, t->p_cb, t->p_sm};
- VkShaderModule s[13] = {t->sm_nq, t->sm_qk, t->sm_at, t->sm_am, t->sm_gc,
+ t->p_ga, t->p_cb, t->p_sm, t->p_gb, t->p_gx};
+ VkShaderModule s[15] = {t->sm_nq, t->sm_qk, t->sm_at, t->sm_am, t->sm_gc,
t->sm_gs, t->sm_gl, t->sm_gr, t->sm_gg, t->sm_tk,
- t->sm_ga, t->sm_cb, t->sm_sm};
+ t->sm_ga, t->sm_cb, t->sm_sm, t->sm_gb, t->sm_gx};
free(t->par);
free(t->cnt);
free(t->fill);
free(t->ids);
free(t->slots);
- for (int i = 0; i < 13; i++) {
+ for (int i = 0; i < 15; i++) {
if (p[i])
g->vkDestroyPipeline(g->dev, p[i], NULL);
if (s[i])
@@ -503,7 +532,7 @@ static int record(struct janas_gpu *g, struct janas_gpu_tok *t,
if (g->vkBeginCommandBuffer(g->cb, &bb) != VK_SUCCESS)
return -1;
VkPipeline bound = VK_NULL_HANDLE;
- t->prof = n == 1 && seg < 0;
+ t->prof = seg < 0; /* a pass in one submission, of any length */
if (t->qp && t->prof) {
t->n_ts = 0;
g->vkCmdResetQueryPool(g->cb, t->qp, 0, MAX_TS);
@@ -640,10 +669,19 @@ int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
const struct janas_gpu_tok_model *md, const float *x,
const float *cs, const float *sn, uint32_t pos,
uint32_t n, int all, float *logits, float *hidden,
- uint32_t src, uint32_t dst)
+ uint32_t src, uint32_t dst, uint32_t replay,
+ uint32_t log_row)
{
- if (!t || g->busy || g->broken || n < 1 || n > t->nb || pos + n > md->cap ||
- (md->n_rec && n + 1 < md->d_conv))
+ if (!t || g->busy || g->broken || n < 1 || n > t->nb || pos + n > md->cap)
+ return -1;
+ /* a replay, or a block to log, needs the log on the GPU */
+ int logs = log_row != UINT32_MAX;
+ if (md->n_rec &&
+ (replay > JANAS_GPU_TOK_MAX_REPLAY ||
+ ((replay || logs) && !t->log_ok) ||
+ (logs && log_row + n > md->log_rows) || (replay && src == dst)))
+ return -1;
+ if (!md->n_rec && (replay || logs))
return -1;
uint32_t nch = runs_for(t, pos + n);
if ((size_t)n * janas_gt_part_tok(t, md, nch) > t->part_floats)
@@ -656,9 +694,10 @@ int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
memcpy(r + half * sizeof(float), sn + (size_t)j * half,
half * sizeof(float));
}
- /* the position, then the halves of the recurrent state to read and to
- write, read by the shaders at run time */
- uint32_t pw[3] = {pos, src, dst};
+ /* the position, the halves of the recurrent state to read and to
+ write, the tokens to replay, the log's row: read by the shaders at
+ run time */
+ uint32_t pw[5] = {pos, src, dst, replay, log_row};
memcpy(t->buf.map + t->o_pos, pw, sizeof(pw));
janas_gt_sync_range(g, t, t->o_x, (size_t)n * md->dm * sizeof(float), 1);
janas_gt_sync_range(g, t, t->o_rope, (size_t)n * md->n_rot * sizeof(float),
@@ -667,9 +706,12 @@ int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
int ai = all == 1 && n == 1 ? 0 : all, hi = hidden != NULL;
struct timespec w0, w1;
clock_gettime(CLOCK_MONOTONIC, &w0);
+ /* a failure once the GPU has started: with a replay the base it
+ updates in place is no longer the state the CPU would replay on */
+ int failed = replay ? -2 : -1;
if (md->n_expert) {
if (janas_gt_run_segments(g, t, md, n, first, ai, hi, nch) != 0)
- return -1;
+ return failed;
} else {
VkCommandBuffer *cb = &t->cb[n][ai][hi];
if (*cb && t->cb_nch[n][ai][hi] != nch) {
@@ -683,7 +725,7 @@ int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
t->cb_nch[n][ai][hi] = nch;
}
if (janas_gt_submit_wait(g, cb) != 0)
- return -1;
+ return failed;
}
clock_gettime(CLOCK_MONOTONIC, &w1);
size_t lb = (size_t)(n - first) * md->n_vocab * 4;
@@ -698,7 +740,7 @@ int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
}
struct timespec w2;
clock_gettime(CLOCK_MONOTONIC, &w2);
- if (t->qp && n == 1 && t->n_ts > 1) {
+ if (t->qp && t->prof && t->n_ts > 1) {
uint64_t ts[MAX_TS];
if (g->vkGetQueryPoolResults(g->dev, t->qp, 0, t->n_ts, sizeof(ts), ts,
sizeof(uint64_t),
@@ -707,6 +749,7 @@ int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
t->ph_ns[t->ph_of[i]] +=
(double)(ts[i] - ts[i - 1]) * g->ts_period;
t->tokens++;
+ t->pass_tokens += n;
t->wall_ns += (double)(w1.tv_sec - w0.tv_sec) * 1e9 +
(double)(w1.tv_nsec - w0.tv_nsec);
t->copy_ns += (double)(w2.tv_sec - w1.tv_sec) * 1e9 +
@@ -754,8 +797,11 @@ int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
const struct janas_gpu_tok_model *md, const float *x,
const float *cs, const float *sn, uint32_t pos,
uint32_t n, int all, float *logits, float *hidden,
- uint32_t src, uint32_t dst)
+ uint32_t src, uint32_t dst, uint32_t replay,
+ uint32_t log_row)
{
+ (void)replay;
+ (void)log_row;
(void)n;
(void)all;
(void)g;
diff --git a/src/llm/gpu_token.h b/src/llm/gpu_token.h
index c02d5de..a1df0cb 100644
--- a/src/llm/gpu_token.h
+++ b/src/llm/gpu_token.h
@@ -74,6 +74,13 @@ struct janas_gpu_tok_model {
int vmap_mod;
uint16_t *ssm_state;
float *conv_state;
+ /* their log (the model's, model_impl.h): per recurrent layer log_rows
+ rows of conv_ch floats (the convolution's inputs) and of nv floats
+ (betas, decays), what a call replays of the last one when that one's
+ last tokens were taken back (rejected drafts); NULL: blocks short
+ enough to be logged stay on the CPU */
+ float *log_mixed, *log_beta, *log_decay;
+ uint32_t log_rows;
/* a mixture (n_expert > 1, 0 for a dense model): k experts a token, of
eff rows each; ff above is the shared expert's (eff without one).
Its layers run one at a time, the CPU between two of them: the
@@ -93,6 +100,10 @@ struct janas_gpu_tok_model {
struct janas_gpu_tok;
+/* The most tokens of the last call a block replays before its own (see
+ janas_gpu_tok_run): a chain of drafts is shorter. */
+#define JANAS_GPU_TOK_MAX_REPLAY 16
+
/* Buffers and shaders for a model of that shape; NULL (the GPU cannot, or
out of memory) with the reason in err. */
struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
@@ -116,15 +127,22 @@ uint32_t janas_gpu_tok_block_at(const struct janas_gpu_tok *t,
* the last token (all 0), of every token (1) or of none (2) into logits;
* with hidden, the final hidden states (n x dm: the last norm's output, an
* MTP block's input) there. The recurrent layers read their state from
- * half src and write it to half dst (the same for a block's later pieces).
- * 0, or -1 with nothing changed but the cache rows pos .. pos + n - 1 (the
- * caller runs the block on the CPU then).
+ * half src and write it to half dst (the same for a block's later pieces);
+ * first they replay the first replay tokens (at most
+ * JANAS_GPU_TOK_MAX_REPLAY) of the log on half src in place, as the CPU
+ * does when a call starts before the end of the last one (src is then the
+ * base); with log_row other than UINT32_MAX they log the block's tokens
+ * from that row of the log on.
+ * 0; -1 with nothing changed but the cache rows pos .. pos + n - 1 (the
+ * caller runs the block on the CPU then); -2 the GPU failed after it had
+ * started, with the state no longer what it was.
*/
int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
const struct janas_gpu_tok_model *md, const float *x,
const float *cs, const float *sn, uint32_t pos,
uint32_t n, int all, float *logits, float *hidden,
- uint32_t src, uint32_t dst);
+ uint32_t src, uint32_t dst, uint32_t replay,
+ uint32_t log_row);
/* Whether the GPU reads the host's memory in place (an integrated GPU with
the host-memory import, not JANAS_GPU_COPY): what the token needs. */
diff --git a/src/llm/gpu_token_impl.h b/src/llm/gpu_token_impl.h
index 14b3e78..ee33e09 100644
--- a/src/llm/gpu_token_impl.h
+++ b/src/llm/gpu_token_impl.h
@@ -43,26 +43,35 @@ struct push_am {
};
/* the Gated DeltaNet shaders (gdn_*.comp) */
struct push_gconv {
- uint32_t mixed[2], out[2], w[2], state[2], pos[2];
- uint32_t cc, d, hs, so;
+ uint32_t mixed[2], out[2], w[2], state[2], pos[2], log[2];
+ uint32_t cc, d, hs, so, n;
};
struct push_gcst {
- uint32_t mixed[2], state[2], pos[2];
+ uint32_t mixed[2], state[2], pos[2], log[2];
uint32_t cc, d, hs, so, n;
};
struct push_gl2 {
- uint32_t x[2];
+ uint32_t x[2], pos[2];
uint32_t cc;
float eps;
+ uint32_t n;
};
struct push_grec {
- uint32_t co[2], ba[2], att[2], state[2], pos[2], dt[2], a[2];
+ uint32_t co[2], att[2], state[2], pos[2], lb[2], ld[2], bd[2];
uint32_t cc, nv, nkh, n, hs, so, vmap_mod;
float scale;
};
+struct push_gba { /* gdn_ba.comp */
+ uint32_t w[2], x[2], y[2], dt[2], a[2];
+ uint32_t rows, cols, n, ys;
+};
+struct push_gact { /* gdn_act.comp */
+ uint32_t ba[2], bd[2], dt[2], a[2];
+ uint32_t nv, n;
+};
struct push_ggate {
- uint32_t att[2], z[2], w[2], q256[2], q32[2];
- uint32_t d;
+ uint32_t att[2], z[2], w[2], q256[2], q32[2], bd[2], lb[2], ld[2], pos[2];
+ uint32_t d, nv;
float eps;
};
struct push_dm { /* gpu.c's dense_mm.comp */
@@ -109,7 +118,12 @@ _Static_assert(offsetof(struct push_qk, pos) % 8 == 0, "push layout");
_Static_assert(offsetof(struct push_at, pos) % 8 == 0, "push layout");
_Static_assert(offsetof(struct push_am, pos) % 8 == 0, "push layout");
_Static_assert(sizeof(struct push_grec) <= JANAS_G_PUSH_BYTES, "push size");
+_Static_assert(sizeof(struct push_ggate) <= JANAS_G_PUSH_BYTES, "push size");
_Static_assert(sizeof(struct push_cb) <= JANAS_G_PUSH_BYTES, "push size");
+/* The most tokens of a block whose beta and alpha gdn_ba.comp makes (more:
+ dense_mm.comp's tiles) */
+#define GBA_MAX_N 16
+#define GBA_RW 4 /* its rows a workgroup (gdn_ba.comp RW) */
/* The most tokens a block takes (the model's own blocks: model.h
JANAS_LLM_MAX_BLOCK), and the memory the attention's runs may take for
them. */
@@ -129,6 +143,14 @@ enum {
PH_ACT,
PH_DOWN,
PH_OUT,
+ /* a Gated DeltaNet layer: its products (q|k|v and z), beta and alpha,
+ the convolution (with its state and the q and k norms), the
+ recurrence, the gate (its output product counts as wo) */
+ PH_SSM_PROD,
+ PH_SSM_BA,
+ PH_SSM_CONV,
+ PH_SSM_REC,
+ PH_SSM_GATE,
PH_N
};
#define MAX_TS 1024
@@ -149,14 +171,16 @@ struct janas_gpu_tok {
uint32_t n_ts; /* written this token */
uint8_t ph_of[MAX_TS]; /* the phase each timestamp closes */
double ph_ns[PH_N];
- double wall_ns; /* submission to the fence, as the CPU sees it */
- double copy_ns; /* the logits copied out */
- uint64_t tokens;
+ double wall_ns; /* submission to the fence, as the CPU sees it */
+ double copy_ns; /* the logits copied out */
+ uint64_t tokens; /* with profiling: passes measured */
+ uint64_t pass_tokens; /* ... and their tokens */
VkShaderModule sm_nq, sm_qk, sm_at, sm_am;
VkPipeline p_nq, p_qk, p_at, p_am;
- /* qwen3.5's recurrent layers */
- VkShaderModule sm_gc, sm_gs, sm_gl, sm_gr, sm_gg;
- VkPipeline p_gc, p_gs, p_gl, p_gr, p_gg;
+ /* qwen3.5's recurrent layers (sm_gb: the betas and decays of a short
+ block, sm_gx: those of a long one's raw dot products) */
+ VkShaderModule sm_gc, sm_gs, sm_gl, sm_gr, sm_gg, sm_gb, sm_gx;
+ VkPipeline p_gc, p_gs, p_gl, p_gr, p_gg, p_gb, p_gx;
size_t *par; /* per layer: its parameters' offsets in buf (PAR_*) */
struct stage buf; /* every intermediate, one allocation */
/* offsets into buf, each nb tokens' worth */
@@ -167,9 +191,11 @@ struct janas_gpu_tok {
size_t o_x, o_x1, o_q256, o_q32, o_qkv, o_ywo, o_gu, o_h, o_yd, o_rope,
o_logits, o_pos;
/* qwen3.5: the normalized input (f32), q|k|v and z of the recurrent
- layers, their convolution's output, beta and alpha, their raw
- output, the query's gates, the final hidden states */
- size_t o_xnf, o_mix, o_z, o_conv, o_ba, o_att, o_gate, o_hid;
+ layers, their convolution's output (the replayed tokens' rows
+ first), beta and alpha, their raw output, the betas and decays used
+ (for the log), the query's gates, the final hidden states */
+ size_t o_xnf, o_mix, o_z, o_conv, o_ba, o_att, o_bd, o_gate, o_hid;
+ int log_ok; /* the model's log is where the GPU reads and writes */
/* a mixture: a submission a layer ([n][all][hidden], n_layer + 1 of
them, each recorded for the runs in seg_nch), its shaders; the
router's logits (n_expert + 1 a token), the pairs' experts and
@@ -184,8 +210,8 @@ struct janas_gpu_tok {
VkPipeline p_tk, p_ga, p_cb, p_sm;
size_t o_r, o_pe, o_pw, o_shw, o_sh, o_xg, o_egu, o_eh, o_dout, o_gt, o_inv,
o_tab1, o_tab2, o_ind;
- /* a shared expert's activation as floats and in blocks of 32, for a
- down matrix in blocks of 32 */
+ /* a dense layer's or a shared expert's activation as floats and in
+ blocks of 32, where a down matrix is in blocks of 32 */
size_t o_hf, o_h32;
uint32_t tiles1, tiles2;
uint32_t n_seg; /* n_layer + 1 */
diff --git a/src/llm/gpu_token_rec.c b/src/llm/gpu_token_rec.c
index fa0197c..aa53a81 100644
--- a/src/llm/gpu_token_rec.c
+++ b/src/llm/gpu_token_rec.c
@@ -85,7 +85,11 @@ size_t janas_gt_part_tok(const struct janas_gpu_tok *t,
}
/* A Gated DeltaNet layer (qwen3.5) on the block normalized in q256 / q32
- and XNF: its output into YWO, as model_rec.c's janas_m_rec_layer. */
+ and XNF: its output into YWO, as model_rec.c's janas_m_rec_layer. The
+ tokens of the last call to replay first (the position buffer's word 3)
+ come from the layer's log, and the block's go to it (word 4): the
+ convolution and its norm take a + n rows, so their dispatches have room
+ for JANAS_GPU_TOK_MAX_REPLAY more. */
int janas_gt_rec_gdn(struct janas_gpu *g, struct janas_gpu_tok *t,
const struct janas_gpu_tok_model *md,
const struct janas_gpu_tok_layer *ly, uint32_t l,
@@ -95,53 +99,102 @@ int janas_gt_rec_gdn(struct janas_gpu *g, struct janas_gpu_tok *t,
CONV = B + t->o_conv, BA = B + t->o_ba, ATT = B + t->o_att,
POS = B + t->o_pos;
const size_t *pr = t->par + (size_t)l * PAR_N;
- uint32_t cc = md->conv_ch;
+ uint32_t cc = md->conv_ch, rows = n + JANAS_GPU_TOK_MAX_REPLAY;
+ /* the layer's log: log_rows rows a layer (0 without one: never read
+ then, the position buffer replaying and logging nothing) */
+ size_t lr = (size_t)md->n_rec * md->log_rows;
+ VkDeviceAddress
+ LM = t->log_ok ? janas_gt_addr_of(g, md->log_mixed, lr * cc * 4) +
+ (VkDeviceAddress)ly->slot * md->log_rows * cc * 4
+ : 0,
+ LB = t->log_ok
+ ? janas_gt_addr_of(g, md->log_beta, lr * md->nv * 4) +
+ (VkDeviceAddress)ly->slot * md->log_rows * md->nv * 4
+ : 0,
+ LD = t->log_ok
+ ? janas_gt_addr_of(g, md->log_decay, lr * md->nv * 4) +
+ (VkDeviceAddress)ly->slot * md->log_rows * md->nv * 4
+ : 0,
+ BD = B + t->o_bd;
/* q|k|v (the convolution's channels) and z */
if (janas_gt_rec_product(g, t, bound, &ly->ssm_qkv, 0, MIX, n, cc) != 0 ||
janas_gt_rec_product(g, t, bound, &ly->ssm_z, 0, Z, n, md->d_inner) !=
0)
return -1;
- /* beta then alpha, per token, from the normalized input at f32 */
- struct push_dm pd = {.rows = 2 * md->nv,
- .cols = md->dm,
- .nv = n,
- .ys = 2 * md->nv,
- .scale = 1.0f};
- janas_g_push_addr(pd.w, B + pr[PAR_BA]);
- janas_g_push_addr(pd.x, B + t->o_xnf);
- janas_g_push_addr(pd.y, BA);
- janas_gt_bind(g, bound, g->pipe_dm[0]);
- janas_gt_push(g, &pd, sizeof(pd));
- g->vkCmdDispatch(g->cb, (2 * md->nv + 63) / 64, (n + 63) / 64, 1);
+ janas_gt_stamp(g, t, PH_SSM_PROD);
+ /* the betas and decays, per token, from the normalized input at f32:
+ a short block a row a workgroup (gdn_ba.comp), a longer one in
+ dense_mm.comp's tiles, made betas and decays by gdn_act.comp; into
+ BD either way */
+ if (n <= GBA_MAX_N) {
+ struct push_gba pb = {
+ .rows = 2 * md->nv, .cols = md->dm, .n = n, .ys = 2 * md->nv};
+ janas_g_push_addr(pb.w, B + pr[PAR_BA]);
+ janas_g_push_addr(pb.x, B + t->o_xnf);
+ janas_g_push_addr(pb.y, BD);
+ janas_g_push_addr(pb.dt, B + pr[PAR_DT]);
+ janas_g_push_addr(pb.a, B + pr[PAR_A]);
+ janas_gt_bind(g, bound, t->p_gb);
+ janas_gt_push(g, &pb, sizeof(pb));
+ g->vkCmdDispatch(g->cb, (2 * md->nv + GBA_RW - 1) / GBA_RW, (n + 7) / 8,
+ 1);
+ } else {
+ struct push_dm pd = {.rows = 2 * md->nv,
+ .cols = md->dm,
+ .nv = n,
+ .ys = 2 * md->nv,
+ .scale = 1.0f};
+ janas_g_push_addr(pd.w, B + pr[PAR_BA]);
+ janas_g_push_addr(pd.x, B + t->o_xnf);
+ janas_g_push_addr(pd.y, BA);
+ janas_gt_bind(g, bound, g->pipe_dm[0]);
+ janas_gt_push(g, &pd, sizeof(pd));
+ g->vkCmdDispatch(g->cb, (2 * md->nv + 63) / 64, (n + 63) / 64, 1);
+ janas_g_compute_barrier(g);
+ struct push_gact px = {.nv = md->nv, .n = n};
+ janas_g_push_addr(px.ba, BA);
+ janas_g_push_addr(px.bd, BD);
+ janas_g_push_addr(px.dt, B + pr[PAR_DT]);
+ janas_g_push_addr(px.a, B + pr[PAR_A]);
+ janas_gt_bind(g, bound, t->p_gx);
+ janas_gt_push(g, &px, sizeof(px));
+ g->vkCmdDispatch(g->cb, (n * 2 * md->nv + 255) / 256, 1, 1);
+ }
janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_SSM_BA);
/* the convolution, then the state it leaves, the q and k heads' norms */
uint32_t hs_c = md->n_rec * (md->d_conv - 1) * cc,
so_c = ly->slot * (md->d_conv - 1) * cc;
VkDeviceAddress CS = janas_gt_addr_of(g, md->conv_state, (size_t)hs_c * 8);
- struct push_gconv pc = {.cc = cc, .d = md->d_conv, .hs = hs_c, .so = so_c};
+ struct push_gconv pc = {
+ .cc = cc, .d = md->d_conv, .hs = hs_c, .so = so_c, .n = n};
janas_g_push_addr(pc.mixed, MIX);
janas_g_push_addr(pc.out, CONV);
janas_g_push_addr(pc.w, B + pr[PAR_CONV]);
janas_g_push_addr(pc.state, CS);
janas_g_push_addr(pc.pos, POS);
+ janas_g_push_addr(pc.log, LM);
janas_gt_bind(g, bound, t->p_gc);
janas_gt_push(g, &pc, sizeof(pc));
- g->vkCmdDispatch(g->cb, cc / 256, n, 1);
+ g->vkCmdDispatch(g->cb, cc / 256, rows, 1);
janas_g_compute_barrier(g);
struct push_gcst ps = {
.cc = cc, .d = md->d_conv, .hs = hs_c, .so = so_c, .n = n};
janas_g_push_addr(ps.mixed, MIX);
janas_g_push_addr(ps.state, CS);
janas_g_push_addr(ps.pos, POS);
+ janas_g_push_addr(ps.log, LM);
janas_gt_bind(g, bound, t->p_gs);
janas_gt_push(g, &ps, sizeof(ps));
g->vkCmdDispatch(g->cb, cc / 256, 1, 1);
- struct push_gl2 pl = {.cc = cc, .eps = md->eps};
+ struct push_gl2 pl = {.cc = cc, .eps = md->eps, .n = n};
janas_g_push_addr(pl.x, CONV);
+ janas_g_push_addr(pl.pos, POS);
janas_gt_bind(g, bound, t->p_gl);
janas_gt_push(g, &pl, sizeof(pl));
- g->vkCmdDispatch(g->cb, 2 * md->nkh, n, 1);
+ g->vkCmdDispatch(g->cb, 2 * md->nkh, rows, 1);
janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_SSM_CONV);
/* the recurrence, then each head's norm, gate and quantization */
uint32_t hs_s = md->n_rec * md->nv * md->ds * md->ds,
so_s = ly->slot * md->nv * md->ds * md->ds;
@@ -154,30 +207,37 @@ int janas_gt_rec_gdn(struct janas_gpu *g, struct janas_gpu_tok *t,
.vmap_mod = (uint32_t)md->vmap_mod,
.scale = 1.0f / sqrtf((float)md->ds)};
janas_g_push_addr(pg.co, CONV);
- janas_g_push_addr(pg.ba, BA);
janas_g_push_addr(pg.att, ATT);
janas_g_push_addr(pg.state,
janas_gt_addr_of(g, md->ssm_state, (size_t)hs_s * 4));
janas_g_push_addr(pg.pos, POS);
- janas_g_push_addr(pg.dt, B + pr[PAR_DT]);
- janas_g_push_addr(pg.a, B + pr[PAR_A]);
+ janas_g_push_addr(pg.lb, LB);
+ janas_g_push_addr(pg.ld, LD);
+ janas_g_push_addr(pg.bd, BD);
janas_gt_bind(g, bound, t->p_gr);
janas_gt_push(g, &pg, sizeof(pg));
g->vkCmdDispatch(g->cb, md->nv * (md->ds / 16), 1, 1);
janas_g_compute_barrier(g);
- struct push_ggate pq = {.d = md->d_inner, .eps = md->eps};
+ janas_gt_stamp(g, t, PH_SSM_REC);
+ struct push_ggate pq = {.d = md->d_inner, .nv = md->nv, .eps = md->eps};
janas_g_push_addr(pq.att, ATT);
janas_g_push_addr(pq.z, Z);
janas_g_push_addr(pq.w, B + pr[PAR_NORM]);
janas_g_push_addr(pq.q256, B + t->o_q256);
janas_g_push_addr(pq.q32, B + t->o_q32);
+ janas_g_push_addr(pq.bd, BD);
+ janas_g_push_addr(pq.lb, LB);
+ janas_g_push_addr(pq.ld, LD);
+ janas_g_push_addr(pq.pos, POS);
janas_gt_bind(g, bound, t->p_gg);
janas_gt_push(g, &pq, sizeof(pq));
g->vkCmdDispatch(g->cb, md->d_inner / JANAS_QK, n, 1);
janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_SSM_GATE);
if (janas_gt_rec_product(g, t, bound, &ly->ssm_out, 0, YWO, n, 0) != 0)
return -1;
janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_WO);
return 0;
}
@@ -309,8 +369,9 @@ static void rec_quant(struct janas_gpu *g, struct janas_gpu_tok *t,
/* A feed-forward on the block normalized in q256: gate and up (the n
tokens' gates, then their ups), SiLU(gate) up quantized, down into out
(a dense layer's, or a mixture's shared expert). A down matrix in blocks
- of 32 (a shared expert's Q8_0) takes the activation as floats quantized
- into both layouts, the experts' shader making only the one of 256. */
+ of 32 (a shared expert's Q8_0, a dense layer's IQ4_NL) takes the
+ activation as floats quantized into both layouts, the activation's
+ shader making only the one of 256. */
int janas_gt_rec_ffn(struct janas_gpu *g, struct janas_gpu_tok *t,
VkPipeline *bound, const struct janas_matvec_task *gate,
const struct janas_matvec_task *up,
diff --git a/src/llm/model.c b/src/llm/model.c
index ba7237a..9fbe267 100644
--- a/src/llm/model.c
+++ b/src/llm/model.c
@@ -459,9 +459,18 @@ static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,
set_rope(m, n, pos0);
/* a token (or, with JANAS_GPU_BLOCK=1, a block) on the GPU, whole,
where it can (model_gpu.c) */
- if (logits && janas_m_gpu_token(m, pos0, n, all_logits, logits) == 0) {
+ int gpu = logits ? janas_m_gpu_token(m, pos0, n, all_logits, logits) : -1;
+ if (gpu == -2)
+ return -1; /* the GPU failed after replaying on the base in place:
+ no state to go on from (base_pos stays invalid) */
+ if (gpu == 0) {
m->ring_hi = pos0 + n;
- if (m->a->rec) { /* a long block (model_gpu.c): as at the end */
+ if (m->a->rec && n <= JANAS_LLM_MAX_BLOCK) {
+ /* replayed and logged by the GPU: as at the end */
+ m->base = m->src;
+ m->base_pos = pos0;
+ m->log_n = n;
+ } else if (m->a->rec) { /* a long block: as at the end */
m->base = 1 - m->src;
m->base_pos = pos0 + n;
m->log_n = 0;
diff --git a/src/llm/model.h b/src/llm/model.h
index 0c63e8f..8823a32 100644
--- a/src/llm/model.h
+++ b/src/llm/model.h
@@ -272,6 +272,12 @@ void janas_llm_model_tuning(const struct janas_llm_model *m, char *buf,
* part worth telling anybody.
*/
int janas_llm_model_gpu_used(const struct janas_llm_model *m);
+/* The most tokens a pass of drafts is worth (0: no limit): where the
+ passes of a few tokens go whole to the GPU, as many as its shaders of a
+ few vectors take (janas_gpu_few_max) - one more sends every product to
+ the shaders of many vectors, and Qwen3.8-27B's pass of 9 tokens took
+ 855 ms against 437 for one of 5 (13 Oct 2026). */
+uint32_t janas_llm_model_pass_cap(const struct janas_llm_model *m);
/* Whether the GPU reads the prompts' blocks whatever the tuner chooses
(the fast prompt, outside eco mode). */
int janas_llm_model_gpu_prompts(const struct janas_llm_model *m);
diff --git a/src/llm/model_gpu.c b/src/llm/model_gpu.c
index 639b161..0ca9bce 100644
--- a/src/llm/model_gpu.c
+++ b/src/llm/model_gpu.c
@@ -426,6 +426,10 @@ static int build(struct janas_llm_model *m, char *err, size_t len)
.vmap_mod = m->vmap_mod,
.ssm_state = m->ssm_buf,
.conv_state = m->conv_buf,
+ .log_mixed = m->a->rec ? m->log_mixed : NULL,
+ .log_beta = m->a->rec ? m->log_beta : NULL,
+ .log_decay = m->a->rec ? m->log_decay : NULL,
+ .log_rows = JANAS_LLM_MAX_BLOCK,
.n_expert = moe ? m->n_expert : 0,
.k = moe ? m->k_use : 0,
.eff = eff,
@@ -460,6 +464,28 @@ static int build(struct janas_llm_model *m, char *err, size_t len)
return m->gtok ? 0 : -1;
}
+/* The passes of a few tokens (a chain of drafts) whole on the GPU, asked
+ for (JANAS_GPU_SHORT=1): see janas_m_gpu_token. */
+static int shorts_on(void)
+{
+ static int on = -1;
+ if (on < 0)
+ on = getenv("JANAS_GPU_SHORT") && atoi(getenv("JANAS_GPU_SHORT")) > 0;
+ return on;
+}
+
+uint32_t janas_llm_model_pass_cap(const struct janas_llm_model *m)
+{
+ /* where such passes go whole to the GPU: asked for, the tuner's choice
+ for them (class 1, 2 to 16 tokens) the GPU, the token's shaders not
+ refused, a dense model or a recurrent one (janas_m_gpu_token) */
+ if (!shorts_on() || !m->gpu || m->gpu_off || m->gtok_state < 0 ||
+ m->n_expert > 1 || m->tuner.n_cand <= 0 ||
+ !m->tuner.cand[janas_tuner_best(&m->tuner, 1)].gpu)
+ return 0;
+ return (uint32_t)janas_gpu_few_max(m->gpu);
+}
+
int janas_m_gpu_token(struct janas_llm_model *m, uint32_t pos, uint32_t n,
int all, float *logits)
{
@@ -482,12 +508,30 @@ int janas_m_gpu_token(struct janas_llm_model *m, uint32_t pos, uint32_t n,
}
int prompt =
janas_gpu_fast_prompt() && n >= JANAS_GPU_FAST_N && blocks != 0;
- if (!prompt && !(tok && (n == 1 || blocks > 0)))
+ /* A short pass (a chain of drafts to verify) where the tuner chose the
+ GPU for it: the whole pass in one submission, the CPU idle, rather
+ than the products by groups beside the CPU - on the development
+ laptop's integrated GPU the CPU's work beside it took the power its
+ clock needed (670-840 MHz against ~1050), and Qwen3-4B's passes of
+ 8 and 16 tokens ran at 12.7 and 10.1 ms a token whole against 27.5
+ and 17.5 by groups and 15.5 and 14.5 on the CPU alone (13 Oct 2026).
+ Dense models for now (a mixture's layers need the CPU's routing);
+ a recurrent model's too, the GPU replaying and logging its state as
+ the CPU does.
+ Asked for only (JANAS_GPU_SHORT=1): with drafts it lost on Qwen3-4B,
+ 22-23 tokens/s against 28-32 on the CPU, a pass of 2 tokens costing
+ 78-92 ms against 46 - some 40 ms a pass besides reading the weights -
+ and the text not the same as without drafts (the GPU's norms and
+ attention sum in its own order; 13 Oct 2026). */
+ int short_pass = shorts_on() && m->gpu_use && n >= 2 &&
+ n <= JANAS_LLM_MAX_BLOCK && m->n_expert <= 1;
+ if (!prompt && !short_pass && !(tok && (n == 1 || blocks > 0)))
return -1;
- /* a recurrent model: blocks that need no log (longer than a draft's)
- and replay nothing - the state read whole from one half, written to
- the other, as forward() expects of such a block */
- if (m->a->rec && (n <= JANAS_LLM_MAX_BLOCK || m->replay))
+ /* a recurrent model: the GPU replays first what forward() asks (the
+ m->replay tokens of the last call that were kept, at most
+ JANAS_GPU_TOK_MAX_REPLAY) and logs a block short enough to be taken
+ back, as the CPU's path does, in the same log */
+ if (m->a->rec && m->replay > JANAS_GPU_TOK_MAX_REPLAY)
return -1;
const char *why = not_for_gpu(m);
if (why) {
@@ -522,25 +566,30 @@ int janas_m_gpu_token(struct janas_llm_model *m, uint32_t pos, uint32_t n,
return -1;
/* the recurrent state: the first piece from half src to the other,
the later ones on that one in place; each piece at least the
- convolution's rows of state long. With an MTP block or a drafting
- model, every token's final hidden state */
+ convolution's rows of state long. The first replays, every piece of
+ a block short enough logs its tokens at its row. With an MTP block
+ or a drafting model, every token's final hidden state */
uint32_t src = m->src, dst = 1 - m->src, rows = m->a->rec ? m->d_conv : 1;
+ int logged = m->a->rec && n <= JANAS_LLM_MAX_BLOCK;
float *hid = m->mtp || m->asst ? m->hid : NULL;
for (uint32_t j = 0, k; j < n; j += k) {
uint32_t nb = janas_gpu_tok_block_at(m->gtok, &m->gtok_md, pos + j);
k = n - j < nb ? n - j : nb;
if (n - j - k > 0 && n - j - k + 1 < rows)
k -= rows; /* the last piece long enough */
- if (janas_gpu_tok_run(m->gpu, m->gtok, &m->gtok_md,
- m->x + (size_t)j * m->d_model,
- m->rope_cos + (size_t)j * half,
- m->rope_sin + (size_t)j * half, pos + j, k,
- j + k < n ? 2
- : all ? 1
- : 0,
- logits, hid ? hid + (size_t)j * m->d_model : NULL,
- j ? dst : src, dst) != 0)
- return -1;
+ int rc = janas_gpu_tok_run(
+ m->gpu, m->gtok, &m->gtok_md, m->x + (size_t)j * m->d_model,
+ m->rope_cos + (size_t)j * half, m->rope_sin + (size_t)j * half,
+ pos + j, k,
+ j + k < n ? 2
+ : all ? 1
+ : 0,
+ logits, hid ? hid + (size_t)j * m->d_model : NULL, j ? dst : src,
+ dst, j ? 0 : m->replay, logged ? j : UINT32_MAX);
+ /* -2, or any failure after a first piece that replayed: the base
+ was updated in place, the CPU cannot replay on it again */
+ if (rc != 0)
+ return rc == -2 || (j && m->replay) ? -2 : -1;
}
return 0;
}
diff --git a/src/llm/model_impl.h b/src/llm/model_impl.h
index a6cba0a..26a248c 100644
--- a/src/llm/model_impl.h
+++ b/src/llm/model_impl.h
@@ -269,11 +269,12 @@ struct janas_llm_model {
is left out, not read (see skip_misses); 0: never. And how many were */
float miss_skip;
uint64_t skip_asked, skip_left;
- /* the products' output buffers, whole pages, shared with the GPU */
+ /* the products' output buffers and the recurrent state and log, whole
+ pages, shared with the GPU */
struct janas_out_buf {
float *p;
size_t bytes;
- } out[16];
+ } out[24];
int n_out;
int warm_use; /* preload the most used experts, and count them */
uint32_t *use_count; /* experts used this session, n_layer * n_expert */
@@ -381,9 +382,14 @@ struct tok_job {
};
void janas_m_init_tuner(struct janas_llm_model *m);
+/* Memory the GPU will import collapsed into 2 MB pages (Linux; see
+ model_load.c), before the import pins it. */
+void janas_m_huge_pages(void *p, uint64_t bytes);
int janas_m_gpu_import(struct janas_llm_model *m, const uint8_t *p,
uint64_t bytes, uint64_t unit);
void janas_m_arena_to_gpu(struct janas_llm_model *m);
+/* A block on the GPU whole (model_gpu.c): 0; -1, the CPU to run it; -2,
+ the GPU failed after replaying on the base in place, the state lost. */
int janas_m_gpu_token(struct janas_llm_model *m, uint32_t pos, uint32_t n,
int all, float *logits);
void janas_m_apply_candidate(struct janas_llm_model *m, int cand);
diff --git a/src/llm/model_load.c b/src/llm/model_load.c
index 5f0425b..8133fe3 100644
--- a/src/llm/model_load.c
+++ b/src/llm/model_load.c
@@ -7,6 +7,7 @@
#define _GNU_SOURCE
#include "model.h"
+#include <errno.h>
#include <math.h>
#include <pthread.h>
#include <sched.h>
@@ -698,8 +699,11 @@ struct janas_llm_model *janas_llm_model_load(const char *path,
(m->resident = janas_gpu_alloc(m->gpu, m->j.h.resident_bytes)))
m->resident_gpu = 1;
}
+ /* on 2 MB boundaries: see janas_m_huge_pages */
if (!m->resident)
- m->resident = aligned_alloc(4096, m->j.h.resident_bytes);
+ m->resident = aligned_alloc(
+ JANAS_HUGE_PAGE, (m->j.h.resident_bytes + JANAS_HUGE_PAGE - 1) /
+ JANAS_HUGE_PAGE * JANAS_HUGE_PAGE);
if (!m->resident) {
snprintf(err, err_len, "out of memory for the resident region");
goto fail;
@@ -1037,10 +1041,14 @@ struct janas_llm_model *janas_llm_model_load(const char *path,
m->conv_out = malloc(R * m->conv_ch * sizeof(float));
m->beta = malloc(R * m->n_vh * sizeof(float));
m->decay = malloc(R * m->n_vh * sizeof(float));
+ /* the log too, which the GPU writes for a chain of drafts it
+ verifies and reads back to replay the tokens kept */
m->log_mixed =
- malloc((size_t)m->n_rec * L * m->conv_ch * sizeof(float));
- m->log_beta = malloc((size_t)m->n_rec * L * m->n_vh * sizeof(float));
- m->log_decay = malloc((size_t)m->n_rec * L * m->n_vh * sizeof(float));
+ out_alloc(m, (size_t)m->n_rec * L * m->conv_ch * sizeof(float));
+ m->log_beta =
+ out_alloc(m, (size_t)m->n_rec * L * m->n_vh * sizeof(float));
+ m->log_decay =
+ out_alloc(m, (size_t)m->n_rec * L * m->n_vh * sizeof(float));
if (!m->ssm_buf || !m->conv_buf || !m->ba || !m->mixed ||
!m->conv_out || !m->beta || !m->decay || !m->log_mixed ||
!m->log_beta || !m->log_decay) {
@@ -1188,8 +1196,9 @@ struct janas_llm_model *janas_llm_model_load(const char *path,
flushed out of the CPU's caches before the GPU reads it */
if (m->resident_gpu)
janas_gpu_flush(m->gpu, m->resident, m->j.h.resident_bytes);
- else if (janas_m_gpu_import(m, m->resident, m->j.h.resident_bytes, 0) !=
- 0)
+ else if (janas_m_huge_pages(m->resident, m->j.h.resident_bytes),
+ janas_m_gpu_import(m, m->resident, m->j.h.resident_bytes, 0) !=
+ 0)
m->gpu_off = 1;
if (m->mtp_res && janas_gpu_import(m->gpu, m->mtp_res,
m->mtp_j.h.resident_bytes) != 0)
@@ -1438,6 +1447,52 @@ uint64_t janas_llm_model_warm(const struct janas_llm_model *m, double *seconds)
begins, so that no tensor straddles two and each stays in reach */
#define GPU_REGION_MAX ((uint64_t)4 << 30)
+/*
+ * Memory the GPU imports, collapsed into huge pages first: the GPU's own
+ * page tables map it in 2 MB pages only where it is on them and the region
+ * starts on a 2 MB boundary, and it reads such memory a fifth faster than
+ * memory in 4 KB pages - 71.6 GB/s against 59.6 on the development laptop,
+ * where the CPU reads both alike (13 Oct 2026; memory the kernel had already
+ * put on huge pages, but not from a 2 MB boundary, read as 4 KB pages). A
+ * request, collapsed once, before the import pins the pages; nothing is
+ * asked of the kernel while the model answers (see expert_cache.c on huge
+ * pages asked for on first touch). JANAS_GPU_HUGE=0: not asked.
+ */
+void janas_m_huge_pages(void *p, uint64_t bytes)
+{
+#if defined(__linux__)
+#ifndef MADV_COLLAPSE
+#define MADV_COLLAPSE 25
+#endif
+ const char *e = getenv("JANAS_GPU_HUGE");
+ if (e && atoi(e) == 0)
+ return;
+ uintptr_t a = ((uintptr_t)p + JANAS_HUGE_PAGE - 1) &
+ ~(uintptr_t)(JANAS_HUGE_PAGE - 1);
+ uintptr_t end = ((uintptr_t)p + bytes) & ~(uintptr_t)(JANAS_HUGE_PAGE - 1);
+ /* in pieces: the kernel refuses a range holding pages never written
+ (a cache's slots not yet loaded), and the pieces already on huge
+ pages cost nothing */
+ const uintptr_t piece = (uintptr_t)32 << 20;
+ size_t done = 0, tried = 0;
+ struct timespec t0, t1;
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+ for (uintptr_t at = a; at < end; at += piece, tried++) {
+ uintptr_t to = at + piece < end ? at + piece : end;
+ done += madvise((void *)at, to - at, MADV_COLLAPSE) == 0;
+ }
+ clock_gettime(CLOCK_MONOTONIC, &t1);
+ if (getenv("JANAS_GPU_VERBOSE") && tried)
+ fprintf(stderr,
+ "huge pages: %.2f GB, %zu of %zu pieces collapsed in %.2f s\n",
+ (end - a) / 1e9, done, tried,
+ (t1.tv_sec - t0.tv_sec) + 1e-9 * (t1.tv_nsec - t0.tv_nsec));
+#else
+ (void)p;
+ (void)bytes;
+#endif
+}
+
static uint64_t resident_cut(const struct janas_llm_model *m, uint64_t from)
{
uint64_t base = m->j.h.resident_offset, best = from;
@@ -1462,10 +1517,16 @@ int janas_m_gpu_import(struct janas_llm_model *m, const uint8_t *p,
end = resident_cut(m, at);
if (end > bytes)
end = bytes;
- /* the regions are whole pages: the last one's length rounded up
- (the allocations are) */
- uint64_t len = (end - at + 4095) & ~(uint64_t)4095;
- if (janas_gpu_import(m->gpu, p + at, len) != 0)
+ /* each region from a 2 MB boundary (the memory is allocated on
+ one), overlapping the one before by what it takes: the GPU maps
+ only such regions in huge pages (janas_m_huge_pages); whole
+ pages, the last one's length rounded up (the allocations are) */
+ uint64_t from = at;
+ if (((uintptr_t)p & (JANAS_HUGE_PAGE - 1)) == 0 &&
+ !(getenv("JANAS_GPU_HUGE") && atoi(getenv("JANAS_GPU_HUGE")) == 0))
+ from = at / JANAS_HUGE_PAGE * JANAS_HUGE_PAGE;
+ uint64_t len = (end - from + 4095) & ~(uint64_t)4095;
+ if (janas_gpu_import(m->gpu, p + from, len) != 0)
return -1;
at = end;
}
@@ -1567,7 +1628,8 @@ void janas_m_arena_to_gpu(struct janas_llm_model *m)
if (getenv("JANAS_GPU_VERBOSE"))
fprintf(stderr, "arena: %.1f GB in the GPU driver's memory%s\n",
bytes / 1e9, in_place ? " (in place)" : "");
- } else if (janas_m_gpu_import(m, a, bytes, slot) == 0) {
+ } else if (janas_m_huge_pages((void *)a, bytes),
+ janas_m_gpu_import(m, a, bytes, slot) == 0) {
m->arena_gpu = 1;
m->arena_loads = loads;
m->arena_in_place = in_place;
diff --git a/src/llm/shaders/b32_matvec.comp b/src/llm/shaders/b32_matvec.comp
index 25b1dd2..36f9b76 100644
--- a/src/llm/shaders/b32_matvec.comp
+++ b/src/llm/shaders/b32_matvec.comp
@@ -49,12 +49,15 @@ uint spread5(uint b)
return ((b & 1u) << 4) | ((b & 2u) << 11) | ((b & 4u) << 18) | ((b & 8u) << 25);
}
+/* the table in the workgroup's shared memory: a constant array read at a
+ varying index is far slower on some GPUs (iq4xs_matvec.comp) */
+shared uint T[16];
+
/* each byte of w through the IQ4_NL table */
uint iq4(uint w)
{
- return (uint(IQ4[w & 15u]) & 0xffu) | ((uint(IQ4[(w >> 8) & 15u]) & 0xffu) << 8) |
- ((uint(IQ4[(w >> 16) & 15u]) & 0xffu) << 16) |
- ((uint(IQ4[(w >> 24) & 15u]) & 0xffu) << 24);
+ return T[w & 15u] | (T[(w >> 8) & 15u] << 8) | (T[(w >> 16) & 15u] << 16) |
+ (T[(w >> 24) & 15u] << 24);
}
float hsum8(float a[8])
@@ -64,12 +67,19 @@ float hsum8(float a[8])
void main()
{
+ if (gl_LocalInvocationID.x < 16u)
+ T[gl_LocalInvocationID.x] = uint(IQ4[gl_LocalInvocationID.x]) & 0xffu;
+ barrier();
U1 W = U1(p.w);
U4 X = U4(p.x);
F Y = F(p.y);
uint lane = gl_SubgroupInvocationID;
- uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
- uint v0 = gl_WorkGroupID.y * NV;
+ /* workgroup y: 64 rows; x: a group of NV vectors, so that the groups
+ of the same rows go out together and the weights the first reads
+ from memory the others find in the L3 */
+ uint grow = gl_WorkGroupID.y * 64u + gl_LocalInvocationID.x;
+ uint row = min(grow, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.x * NV;
uint xo[NV];
for (uint v = 0; v < NV; v++)
xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
@@ -137,7 +147,7 @@ void main()
xo[v] += 20u;
}
}
- if (gl_GlobalInvocationID.x < p.rows)
+ if (grow < p.rows)
for (uint v = 0; v < NV; v++)
if (v0 + v < p.nv) {
float r = hsum8(acc[v]);
diff --git a/src/llm/shaders/gdn_act.comp b/src/llm/shaders/gdn_act.comp
new file mode 100644
index 0000000..def860b
--- /dev/null
+++ b/src/llm/shaders/gdn_act.comp
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// A Gated DeltaNet layer's betas and decays from the raw dot products of a
+// long block (dense_mm.comp's: per token the nv b, then the nv a): beta =
+// sigmoid(b), decay = exp(softplus(a + dt[h]) A[h]), as gdn_ba.comp makes
+// them for a short one, into bd (the same layout). A thread a number.
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 256) in;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer F { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer W { float v[]; };
+
+// ba, bd: n rows of 2 nv; dt, A: nv
+layout(push_constant) uniform P { uvec2 ba, bd, dt, a; uint nv, n; } p;
+
+void main()
+{
+ uint i = gl_GlobalInvocationID.x;
+ if (i >= p.n * 2u * p.nv)
+ return;
+ uint r = i % (2u * p.nv);
+ float s = F(p.ba).v[i], y;
+ if (r < p.nv) {
+ y = 1.0 / (1.0 + exp(-s));
+ } else {
+ float al = s + F(p.dt).v[r - p.nv];
+ float sp = al > 20.0 ? al : log(1.0 + exp(al));
+ y = exp(sp * F(p.a).v[r - p.nv]);
+ }
+ W(p.bd).v[i] = y;
+}
diff --git a/src/llm/shaders/gdn_ba.comp b/src/llm/shaders/gdn_ba.comp
new file mode 100644
index 0000000..366428d
--- /dev/null
+++ b/src/llm/shaders/gdn_ba.comp
@@ -0,0 +1,76 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// A Gated DeltaNet layer's beta and decay for a short block (a chain of
+// drafts): the dot product of row r of w (f32, 2 nv x cols: the nv betas'
+// rows, then the nv alphas') with token t's normalized input x (cols
+// floats), then for a beta's row sigmoid of it, for an alpha's
+// exp(softplus(it + dt[h]) A[h]) - what gdn_rec.comp takes (y: per token
+// the nv betas then the nv decays). dense_mm.comp's tiles of 64 rows by 64
+// tokens leave such a block one workgroup, which walks the row 16 columns
+// a barrier: 25 ms a pass of 8 tokens on Qwen3.5-9B (13 Oct 2026). Here a
+// workgroup takes RW rows and up to NT tokens (y), each thread every 256th
+// column of them for all the tokens, the sums then added across the
+// workgroup; a token's inputs are read once for the RW rows (a workgroup a
+// row read them 96 times a layer on Qwen3.8-27B: 13 ms a pass of 8
+// tokens). Not the CPU's order of the sums.
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_arithmetic : require
+
+layout(local_size_x = 256) in;
+layout(constant_id = 0) const uint NV = 8; // unused
+layout(constant_id = 1) const uint SG = 8; // unused
+const uint NT = 8u; // tokens a workgroup
+const uint RW = 4u; // rows a workgroup (the host's GBA_RW)
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer F { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer W { float v[]; };
+
+// w: rows x cols; x: n rows of cols; y: n rows of ys floats; dt, A: nv
+layout(push_constant) uniform P { uvec2 w, x, y, dt, a; uint rows, cols, n, ys; } p;
+
+shared float part[RW * NT * 32u]; /* a subgroup's sums: up to 32 subgroups */
+
+void main()
+{
+ uint r0 = gl_WorkGroupID.x * RW, t0 = gl_WorkGroupID.y * NT, id = gl_LocalInvocationID.x;
+ F Wt = F(p.w), X = F(p.x);
+ uint nt = min(NT, p.n - t0);
+ float acc[RW * NT];
+ for (uint i = 0; i < RW * NT; i++)
+ acc[i] = 0.0;
+ for (uint c = id; c < p.cols; c += 256u) {
+ float xv[NT];
+ for (uint k = 0; k < NT; k++)
+ xv[k] = k < nt ? X.v[(t0 + k) * p.cols + c] : 0.0;
+ for (uint j = 0; j < RW; j++) {
+ float w = Wt.v[min(r0 + j, p.rows - 1u) * p.cols + c];
+ for (uint k = 0; k < NT; k++)
+ acc[j * NT + k] = fma(w, xv[k], acc[j * NT + k]);
+ }
+ }
+ for (uint i = 0; i < RW * NT; i++) {
+ float s = subgroupAdd(acc[i]);
+ if (subgroupElect())
+ part[i * 32u + gl_SubgroupID] = s;
+ }
+ barrier();
+ uint r = r0 + id / NT, k = id % NT;
+ if (id < RW * NT && r < p.rows && k < nt) {
+ float s = 0.0;
+ for (uint i = 0; i < gl_NumSubgroups; i++)
+ s += part[id * 32u + i];
+ uint nv = p.rows / 2u;
+ float y;
+ if (r < nv) {
+ y = 1.0 / (1.0 + exp(-s)); /* beta */
+ } else {
+ float al = s + F(p.dt).v[r - nv];
+ float sp = al > 20.0 ? al : log(1.0 + exp(al));
+ y = exp(sp * F(p.a).v[r - nv]); /* the decay */
+ }
+ W(p.y).v[(t0 + k) * p.ys + r] = y;
+ }
+}
diff --git a/src/llm/shaders/gdn_conv.comp b/src/llm/shaders/gdn_conv.comp
index f5ac916..c39e998 100644
--- a/src/llm/shaders/gdn_conv.comp
+++ b/src/llm/shaders/gdn_conv.comp
@@ -4,10 +4,13 @@
// A Gated DeltaNet layer of the whole block on the GPU (gpu_token.c), its
// first step: the causal convolution of the q|k|v channels, then SiLU, as
// model_rec.c's conv_head does - out[t][c] = SiLU(sum over i < d of
-// w[i][c] x in(t - d + 1 + i, c)), in(s) the block's row s (mixed) or, for
-// s < 0, row d - 1 + s of the layer's convolution state (the half the
-// position buffer names: its word 1). A thread a channel, a workgroup row
-// of 256 channels per token.
+// w[i][c] x in(t - d + 1 + i, c)) for the a + n rows of the call: the a
+// tokens of the last call to replay (the position buffer's word 3, their
+// inputs the log's rows 0 .. a - 1), then the block's n (mixed); in(s) for
+// s < 0 is row d - 1 + s of the layer's convolution state (the half the
+// position buffer's word 1 names). A thread a channel, a workgroup row of
+// 256 channels per row; the rows past a + n (the dispatch's room for a
+// replay) do nothing.
#extension GL_EXT_buffer_reference : require
#extension GL_EXT_buffer_reference_uvec2 : require
@@ -17,21 +20,25 @@ layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer R {
layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer W { float v[]; };
layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer RP { uint v[]; };
-// mixed: n rows of cc; out: likewise; w: d rows of cc; state: two halves of
-// hs floats, this layer's (d - 1) rows of cc at so in each
-layout(push_constant) uniform P { uvec2 mixed, out_, w, state, pos; uint cc, d, hs, so; } p;
+// mixed: n rows of cc; log: the layer's logged rows, cc floats each; out:
+// a + n rows of cc; w: d rows of cc; state: two halves of hs floats, this
+// layer's (d - 1) rows of cc at so in each
+layout(push_constant) uniform P { uvec2 mixed, out_, w, state, pos, log_; uint cc, d, hs, so, n; } p;
void main()
{
uint c = gl_WorkGroupID.x * 256u + gl_LocalInvocationID.x, t = gl_WorkGroupID.y;
- if (c >= p.cc)
+ uint a = RP(p.pos).v[3];
+ if (c >= p.cc || t >= a + p.n)
return;
- R M = R(p.mixed), Wt = R(p.w), S = R(p.state);
+ R M = R(p.mixed), L = R(p.log_), Wt = R(p.w), S = R(p.state);
uint base = RP(p.pos).v[1] * p.hs + p.so;
float s = 0.0;
for (uint i = 0; i < p.d; i++) {
int r = int(t) - int(p.d) + 1 + int(i);
- float x = r >= 0 ? M.v[uint(r) * p.cc + c] : S.v[base + uint(int(p.d) - 1 + r) * p.cc + c];
+ float x = r >= int(a) ? M.v[uint(r - int(a)) * p.cc + c]
+ : r >= 0 ? L.v[uint(r) * p.cc + c]
+ : S.v[base + uint(int(p.d) - 1 + r) * p.cc + c];
s = i == 0u ? x * Wt.v[c] : fma(x, Wt.v[i * p.cc + c], s);
}
W(p.out_).v[t * p.cc + c] = s / (1.0 + exp(-s));
diff --git a/src/llm/shaders/gdn_cstate.comp b/src/llm/shaders/gdn_cstate.comp
index a59840f..410ff10 100644
--- a/src/llm/shaders/gdn_cstate.comp
+++ b/src/llm/shaders/gdn_cstate.comp
@@ -1,10 +1,16 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2026 Maurizio Cammalleri */
#version 450
-// After gdn_conv.comp: the layer's convolution state for the next call,
-// the block's last d - 1 rows of mixed (n >= d - 1), into the half the
-// position buffer's word 2 names. Apart from gdn_conv.comp, which may still
-// read the state when the two halves are one (a later piece of a block).
+// After gdn_conv.comp: the layer's convolution state, the last d - 1 rows
+// of the inputs - the state the call starts from (the half the position
+// buffer's word 1 names), then the a logged rows it replays (word 3), then
+// its n rows of mixed - for the next call: after the a rows into the half
+// it started from (the base, in place: a call that replays starts from the
+// base), after all of them into the half word 2 names; any n, as short as
+// a draft's. Then the call's rows of mixed into the log, from row word 4 on
+// (none if it is all ones), the old rows read first. Apart from
+// gdn_conv.comp, which reads the state and the log before. A thread a
+// channel.
#extension GL_EXT_buffer_reference : require
#extension GL_EXT_buffer_reference_uvec2 : require
@@ -14,16 +20,43 @@ layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer R {
layout(buffer_reference, std430, buffer_reference_align = 4) buffer S { float v[]; };
layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer RP { uint v[]; };
-layout(push_constant) uniform P { uvec2 mixed, state, pos; uint cc, d, hs, so, n; } p;
+layout(push_constant) uniform P { uvec2 mixed, state, pos, log_; uint cc, d, hs, so, n; } p;
+
+/* Row r of the call's inputs, the state's d - 1 rows first: the state,
+ the log's a rows, the block's n. */
+float input_row(uint r, uint c, uint a, uint base)
+{
+ uint d1 = p.d - 1u;
+ if (r < d1)
+ return S(p.state).v[base + r * p.cc + c];
+ if (r < d1 + a) /* the log is written below: read as writable too */
+ return S(p.log_).v[(r - d1) * p.cc + c];
+ return R(p.mixed).v[(r - d1 - a) * p.cc + c];
+}
void main()
{
uint c = gl_WorkGroupID.x * 256u + gl_LocalInvocationID.x;
if (c >= p.cc)
return;
- R M = R(p.mixed);
S St = S(p.state);
- uint base = RP(p.pos).v[2] * p.hs + p.so;
+ RP PS = RP(p.pos);
+ uint a = PS.v[3], lrow = PS.v[4];
+ uint src = PS.v[1] * p.hs + p.so, dst = PS.v[2] * p.hs + p.so;
+ /* both states read before either is written: the halves may be one */
+ float nb[7], nd[7];
+ for (uint k = 0; k + 1u < p.d; k++) {
+ nb[k] = input_row(a + k, c, a, src);
+ nd[k] = input_row(a + p.n + k, c, a, src);
+ }
+ if (a > 0u)
+ for (uint k = 0; k + 1u < p.d; k++)
+ St.v[src + k * p.cc + c] = nb[k];
for (uint k = 0; k + 1u < p.d; k++)
- St.v[base + k * p.cc + c] = M.v[(p.n - p.d + 1u + k) * p.cc + c];
+ St.v[dst + k * p.cc + c] = nd[k];
+ if (lrow != 0xffffffffu) {
+ S L = S(p.log_);
+ for (uint t = 0; t < p.n; t++)
+ L.v[(lrow + t) * p.cc + c] = R(p.mixed).v[t * p.cc + c];
+ }
}
diff --git a/src/llm/shaders/gdn_gate.comp b/src/llm/shaders/gdn_gate.comp
index f879459..d6dd0b6 100644
--- a/src/llm/shaders/gdn_gate.comp
+++ b/src/llm/shaders/gdn_gate.comp
@@ -6,6 +6,10 @@
// normalized by its RMS and the weights w (ds), times SiLU(z), then
// quantized to Q8_K as norm_quant.comp does (q256, and q32 if set). A
// workgroup per block of 256 (two heads) and token (y), a number a thread.
+// The first workgroup of each token also logs the token's beta and decay of
+// each head as gdn_rec.comp used them (bd: 2 nv a token) into lb and ld
+// (the layer's log, nv a row) at row (the position buffer's word 4) + y,
+// where that word is not all ones.
#extension GL_EXT_buffer_reference : require
#extension GL_KHR_shader_subgroup_arithmetic : require
#extension GL_KHR_shader_subgroup_basic : require
@@ -16,9 +20,11 @@ layout(local_size_x = 256) in;
layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer F { float v[]; };
layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer U { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer W { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer RP { uint v[]; };
// att, z: n rows of d floats; w: ds floats
-layout(push_constant) uniform P { uvec2 att, z, w, q256, q32; uint d; float eps; } p;
+layout(push_constant) uniform P { uvec2 att, z, w, q256, q32, bd, lb, ld, pos; uint d, nv; float eps; } p;
shared float sq_[256];
shared float hs_[2];
@@ -46,6 +52,12 @@ void main()
{
uint t = gl_LocalInvocationID.x, b = gl_WorkGroupID.x, j = gl_WorkGroupID.y;
uint e = 256u * b + t, o = j * p.d + e;
+ uint lrow = RP(p.pos).v[4];
+ if (b == 0u && t < p.nv && lrow != 0xffffffffu) {
+ F BD = F(p.bd);
+ W(p.lb).v[(lrow + j) * p.nv + t] = BD.v[j * 2u * p.nv + t];
+ W(p.ld).v[(lrow + j) * p.nv + t] = BD.v[j * 2u * p.nv + p.nv + t];
+ }
U Q = U(p.q256), Q32 = U(p.q32);
float a = F(p.att).v[o];
sq_[t] = a * a;
diff --git a/src/llm/shaders/gdn_l2.comp b/src/llm/shaders/gdn_l2.comp
index 554e6fb..1dfdc52 100644
--- a/src/llm/shaders/gdn_l2.comp
+++ b/src/llm/shaders/gdn_l2.comp
@@ -3,8 +3,9 @@
#version 450
// After gdn_conv.comp: each q and k head (the first 2 n_kh of the
// convolution's heads of ds = 128 channels) over its L2 norm, x / sqrt(sum
-// x^2 + eps), in place. A workgroup per head (x) and token (y), a channel a
-// thread.
+// x^2 + eps), in place. A workgroup per head (x) and row (y) - the a rows
+// replayed (the position buffer's word 3) and the call's n - a channel a
+// thread; a whole workgroup past a + n leaves at once.
#extension GL_EXT_buffer_reference : require
#extension GL_EXT_buffer_reference_uvec2 : require
#extension GL_KHR_shader_subgroup_basic : require
@@ -13,14 +14,17 @@
layout(local_size_x = 128) in;
layout(buffer_reference, std430, buffer_reference_align = 4) buffer F { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer RP { uint v[]; };
-layout(push_constant) uniform P { uvec2 x; uint cc; float eps; } p;
+layout(push_constant) uniform P { uvec2 x, pos; uint cc; float eps; uint n; } p;
shared float sg_part[64];
void main()
{
uint i = gl_LocalInvocationID.x, h = gl_WorkGroupID.x, t = gl_WorkGroupID.y;
+ if (t >= RP(p.pos).v[3] + p.n)
+ return; /* the same for the whole workgroup: before any barrier */
F X = F(p.x);
uint o = t * p.cc + h * 128u + i;
float v = X.v[o];
diff --git a/src/llm/shaders/gdn_rec.comp b/src/llm/shaders/gdn_rec.comp
index 0570639..685c6dd 100644
--- a/src/llm/shaders/gdn_rec.comp
+++ b/src/llm/shaders/gdn_rec.comp
@@ -7,11 +7,18 @@
// (key head g), v and the head's beta and decay -
// x = M[r] decay, sk = x . k, d = (v[r] - sk) beta, y = x + d k,
// out[r] = (y . q) scale, M[r] = y at sixteen bits.
-// beta = sigmoid(b), decay = exp(softplus(a + dt[h]) A[h]) from the raw b
-// and a (ba: per token, the nv b then the nv a). The row stays in registers
-// for the whole block: eight threads a row, sixteen numbers each, sixteen
-// rows a workgroup. The state is read from the half the position buffer's
-// word 1 names and written to the one its word 2 does.
+// The row stays in registers for the whole block: eight threads a row,
+// sixteen numbers each (their q and k read four at a time), sixteen rows a
+// workgroup. The state is read from the half the position buffer's word 1
+// names and written to the one its word 2 does.
+// A call that starts before the end of the last one first replays the a
+// tokens of it that were kept (the position buffer's word 3): their rows of
+// the convolution come first, their beta and decay from the log (lb, ld:
+// the layer's, nv a row), their outputs are not wanted, and the state after
+// them goes back into the half it was read from (the base: a call that
+// replays starts from it); then the call's n tokens, their beta and decay
+// from bd (gdn_ba.comp or gdn_act.comp: per token the nv betas, then the nv
+// decays).
#extension GL_EXT_buffer_reference : require
#extension GL_EXT_buffer_reference_uvec2 : require
#extension GL_EXT_control_flow_attributes : require
@@ -21,15 +28,17 @@
layout(local_size_x = 128) in;
layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer R { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer R4 { vec4 v[]; };
layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer W { float v[]; };
layout(buffer_reference, std430, buffer_reference_align = 4) buffer U { uint v[]; };
layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer RP { uint v[]; };
-// co: n rows of cc (q heads, k heads at kd, v at 2 kd); ba: n rows of 2 nv;
+// co: a + n rows of cc (q heads, k heads at kd, v at 2 kd), on 16 bytes;
// att: n rows of nv ds; state: two halves of hs sixteen-bit numbers, this
-// layer's nv ds ds at so; dt, A: nv floats
+// layer's nv ds ds at so; lb, ld: the log's betas and decays, nv a row; bd:
+// n rows of 2 nv
layout(push_constant) uniform P {
- uvec2 co, ba, att, state, pos, dt, a;
+ uvec2 co, att, state, pos, lb, ld, bd;
uint cc, nv, nkh, n, hs, so, vmap_mod;
float scale;
} p;
@@ -39,7 +48,8 @@ void main()
uint t = gl_LocalInvocationID.x, lane = t % 8u, rl = t / 8u;
uint h = gl_WorkGroupID.x / 8u, r = (gl_WorkGroupID.x % 8u) * 16u + rl;
uint kd = p.nkh * 128u, g = p.vmap_mod != 0u ? h % p.nkh : h / (p.nv / p.nkh);
- R CO = R(p.co), BA = R(p.ba);
+ R CO = R(p.co);
+ R4 CO4 = R4(p.co);
W O = W(p.att);
U S = U(p.state);
RP PS = RP(p.pos);
@@ -53,29 +63,43 @@ void main()
x[2u * i] = f.x;
x[2u * i + 1u] = f.y;
}
- float dtv = R(p.dt).v[h], av = R(p.a).v[h];
- for (uint j = 0; j < p.n; j++) {
- float b = BA.v[j * 2u * p.nv + h], al = BA.v[j * 2u * p.nv + p.nv + h] + dtv;
- float beta = 1.0 / (1.0 + exp(-b));
- float sp = al > 20.0 ? al : log(1.0 + exp(al));
- float dec = exp(sp * av);
- uint qo = j * p.cc + g * 128u + e0, ko = qo + kd;
+ uint ar = PS.v[3]; /* the tokens replayed */
+ for (uint j = 0; j < ar + p.n; j++) {
+ float beta, dec;
+ if (j < ar) {
+ beta = R(p.lb).v[j * p.nv + h];
+ dec = R(p.ld).v[j * p.nv + h];
+ } else {
+ uint jn = (j - ar) * 2u * p.nv + h;
+ beta = R(p.bd).v[jn];
+ dec = R(p.bd).v[jn + p.nv];
+ }
+ /* the token's q and k, sixteen numbers each, a vec4 at a time */
+ uint qo = (j * p.cc + g * 128u + e0) / 4u, ko = qo + kd / 4u;
+ vec4 kv[4], qv[4];
+ [[unroll]] for (uint m = 0; m < 4u; m++) {
+ kv[m] = CO4.v[ko + m];
+ qv[m] = CO4.v[qo + m];
+ }
float sk = 0.0;
[[unroll]] for (uint i = 0; i < 16u; i++) {
x[i] *= dec;
- sk = fma(x[i], CO.v[ko + i], sk);
+ sk = fma(x[i], kv[i / 4u][i % 4u], sk);
}
sk = subgroupClusteredAdd(sk, 8u);
float d = (CO.v[j * p.cc + 2u * kd + h * 128u + r] - sk) * beta;
float sq = 0.0;
[[unroll]] for (uint i = 0; i < 16u; i++) {
- float y = fma(d, CO.v[ko + i], x[i]);
- sq = fma(y, CO.v[qo + i], sq);
+ float y = fma(d, kv[i / 4u][i % 4u], x[i]);
+ sq = fma(y, qv[i / 4u][i % 4u], sq);
x[i] = unpackHalf2x16(packHalf2x16(vec2(y, 0.0))).x;
}
sq = subgroupClusteredAdd(sq, 8u);
- if (lane == 0u)
- O.v[j * p.nv * 128u + h * 128u + r] = sq * p.scale;
+ if (lane == 0u && j >= ar)
+ O.v[(j - ar) * p.nv * 128u + h * 128u + r] = sq * p.scale;
+ if (j + 1u == ar) /* the base, past the replayed tokens: in place */
+ [[unroll]] for (uint i = 0; i < 8u; i++)
+ S.v[src + i] = packHalf2x16(vec2(x[2u * i], x[2u * i + 1u]));
}
[[unroll]] for (uint i = 0; i < 8u; i++)
S.v[dst + i] = packHalf2x16(vec2(x[2u * i], x[2u * i + 1u]));
diff --git a/src/llm/shaders/iq3s_matvec.comp b/src/llm/shaders/iq3s_matvec.comp
index 3482ac2..f00b652 100644
--- a/src/llm/shaders/iq3s_matvec.comp
+++ b/src/llm/shaders/iq3s_matvec.comp
@@ -139,14 +139,25 @@ uint signed4(uint g, uint s)
return r;
}
+/* the grid in the workgroup's shared memory: a constant array read at a
+ varying index is far slower on some GPUs (iq4xs_matvec.comp) */
+shared uint GS[512];
+
void main()
{
+ for (uint i = gl_LocalInvocationID.x; i < 512u; i += 64u)
+ GS[i] = GRID[i];
+ barrier();
U1 W = U1(p.w);
U4 X = U4(p.x);
F Y = F(p.y);
uint lane = gl_SubgroupInvocationID;
- uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
- uint v0 = gl_WorkGroupID.y * NV;
+ /* workgroup y: 64 rows; x: a group of NV vectors, so that the groups
+ of the same rows go out together and the weights the first reads
+ from memory the others find in the L3 */
+ uint grow = gl_WorkGroupID.y * 64u + gl_LocalInvocationID.x;
+ uint row = min(grow, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.x * NV;
uint xo[NV];
for (uint v = 0; v < NV; v++)
xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
@@ -173,7 +184,7 @@ void main()
for (uint k = 0; k < 8u; k++) {
uint idx = byte_at(wd, 2u + 8u * g + k) | (((qh >> k) & 1u) << 8);
uint sg = byte_at(wd, 74u + 4u * g + k / 2u) >> (4u * (k & 1u));
- q[8u * g + k] = signed4(GRID[idx], sg & 15u);
+ q[8u * g + k] = signed4(GS[idx], sg & 15u);
}
sc[g] = 1 + 2 * int((byte_at(wd, 106u + g / 2u) >> (4u * (g & 1u))) & 15u);
}
@@ -195,7 +206,7 @@ void main()
xo[v] += 20u;
}
}
- if (gl_GlobalInvocationID.x < p.rows)
+ if (grow < p.rows)
for (uint v = 0; v < NV; v++)
if (v0 + v < p.nv)
Y.v[(v0 + v) * p.ys + row] = acc[v];
diff --git a/src/llm/shaders/iq3s_mmq.comp b/src/llm/shaders/iq3s_mmq.comp
new file mode 100644
index 0000000..a1090a1
--- /dev/null
+++ b/src/llm/shaders/iq3s_mmq.comp
@@ -0,0 +1,232 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri
+ The table GRID below is the IQ3_S grid of ggml (ggml/src/ggml-common.h,
+ iq3s_grid), copied as data from src/llm/iq3s_grid.h: it defines the
+ format. Copyright (c) 2023-2026 The ggml authors, under the MIT licence
+ (see the ggml repository). */
+#version 450
+// The fast prompt for IQ3_S: the tiling of q4k_mmq.comp, as iq4xs_mmq.comp.
+// A group of 32 weights has one scale, 1 + 2 x a nibble; four weights are a
+// grid entry of four levels (a 9-bit index: qs[8 g + k], its ninth bit bit
+// k of qh[g]) each with its sign (bit e of signs[4 g + e / 8]), as
+// iq3s_matvec.comp decodes them; the levels are signed, so no correction
+// with the activations' sums. A block is 110 bytes: every other one starts
+// 2 bytes off a 4-byte boundary, and its bytes are read one by one. NOT bit
+// for bit with the CPU: rounded group by group.
+#extension GL_EXT_control_flow_attributes : require
+#extension GL_EXT_integer_dot_product : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 128) in;
+layout(constant_id = 0) const uint NV = 8; // unused: the table's constants
+layout(constant_id = 1) const uint SG = 8;
+
+const uint BM = 64u, BN = 64u, KS = 4u;
+const uint WM = 32u, WN = 32u, TM = 2u, TN = 2u, WARP = 32u;
+const uint WNITER = (WM * WN) / (WARP * TM * TN); // 8
+const uint WSUBN = WN / WNITER; // 4
+const uint XB = 20u;
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+struct ACache { uint qs[8]; float dsc; }; // a group: its levels as bytes, d * scale
+struct BCache { int qs[8]; float d8; }; // quants, d8
+shared ACache sa[BM * KS];
+shared BCache sb[BN * KS];
+
+const uint GRID[512] = uint[512](
+ 0x01010101u, 0x01010103u, 0x01010105u, 0x0101010bu, 0x0101010fu, 0x01010301u,
+ 0x01010303u, 0x01010305u, 0x01010309u, 0x0101030du, 0x01010501u, 0x01010503u,
+ 0x0101050bu, 0x01010707u, 0x01010901u, 0x01010905u, 0x0101090bu, 0x0101090fu,
+ 0x01010b03u, 0x01010b07u, 0x01010d01u, 0x01010d05u, 0x01010f03u, 0x01010f09u,
+ 0x01010f0fu, 0x01030101u, 0x01030103u, 0x01030105u, 0x01030109u, 0x01030301u,
+ 0x01030303u, 0x0103030bu, 0x01030501u, 0x01030507u, 0x0103050fu, 0x01030703u,
+ 0x0103070bu, 0x01030909u, 0x01030d03u, 0x01030d0bu, 0x01030f05u, 0x01050101u,
+ 0x01050103u, 0x0105010bu, 0x0105010fu, 0x01050301u, 0x01050307u, 0x0105030du,
+ 0x01050503u, 0x0105050bu, 0x01050701u, 0x01050709u, 0x01050905u, 0x0105090bu,
+ 0x0105090fu, 0x01050b03u, 0x01050b07u, 0x01050f01u, 0x01050f07u, 0x01070107u,
+ 0x01070303u, 0x0107030bu, 0x01070501u, 0x01070505u, 0x01070703u, 0x01070707u,
+ 0x0107070du, 0x01070909u, 0x01070b01u, 0x01070b05u, 0x01070d0fu, 0x01070f03u,
+ 0x01070f0bu, 0x01090101u, 0x01090307u, 0x0109030fu, 0x01090503u, 0x01090509u,
+ 0x01090705u, 0x01090901u, 0x01090907u, 0x01090b03u, 0x01090f01u, 0x010b0105u,
+ 0x010b0109u, 0x010b0501u, 0x010b0505u, 0x010b050du, 0x010b0707u, 0x010b0903u,
+ 0x010b090bu, 0x010b090fu, 0x010b0d0du, 0x010b0f07u, 0x010d010du, 0x010d0303u,
+ 0x010d0307u, 0x010d0703u, 0x010d0b05u, 0x010d0f03u, 0x010f0101u, 0x010f0105u,
+ 0x010f0109u, 0x010f0501u, 0x010f0505u, 0x010f050du, 0x010f0707u, 0x010f0b01u,
+ 0x010f0b09u, 0x03010101u, 0x03010103u, 0x03010105u, 0x03010109u, 0x03010301u,
+ 0x03010303u, 0x03010307u, 0x0301030bu, 0x0301030fu, 0x03010501u, 0x03010505u,
+ 0x03010703u, 0x03010709u, 0x0301070du, 0x03010b09u, 0x03010b0du, 0x03010d03u,
+ 0x03010f05u, 0x03030101u, 0x03030103u, 0x03030107u, 0x0303010du, 0x03030301u,
+ 0x03030309u, 0x03030503u, 0x03030701u, 0x03030707u, 0x03030903u, 0x03030b01u,
+ 0x03030b05u, 0x03030f01u, 0x03030f0du, 0x03050101u, 0x03050305u, 0x0305030bu,
+ 0x0305030fu, 0x03050501u, 0x03050509u, 0x03050705u, 0x03050901u, 0x03050907u,
+ 0x03050b0bu, 0x03050d01u, 0x03050f05u, 0x03070103u, 0x03070109u, 0x0307010fu,
+ 0x03070301u, 0x03070307u, 0x03070503u, 0x0307050fu, 0x03070701u, 0x03070709u,
+ 0x03070903u, 0x03070d05u, 0x03070f01u, 0x03090107u, 0x0309010bu, 0x03090305u,
+ 0x03090309u, 0x03090703u, 0x03090707u, 0x03090905u, 0x0309090du, 0x03090b01u,
+ 0x03090b09u, 0x030b0103u, 0x030b0301u, 0x030b0307u, 0x030b0503u, 0x030b0701u,
+ 0x030b0705u, 0x030b0b03u, 0x030d0501u, 0x030d0509u, 0x030d050fu, 0x030d0909u,
+ 0x030d090du, 0x030f0103u, 0x030f0107u, 0x030f0301u, 0x030f0305u, 0x030f0503u,
+ 0x030f070bu, 0x030f0903u, 0x030f0d05u, 0x030f0f01u, 0x05010101u, 0x05010103u,
+ 0x05010107u, 0x0501010bu, 0x0501010fu, 0x05010301u, 0x05010305u, 0x05010309u,
+ 0x0501030du, 0x05010503u, 0x05010507u, 0x0501050fu, 0x05010701u, 0x05010705u,
+ 0x05010903u, 0x05010907u, 0x0501090bu, 0x05010b01u, 0x05010b05u, 0x05010d0fu,
+ 0x05010f01u, 0x05010f07u, 0x05010f0bu, 0x05030101u, 0x05030105u, 0x05030301u,
+ 0x05030307u, 0x0503030fu, 0x05030505u, 0x0503050bu, 0x05030703u, 0x05030709u,
+ 0x05030905u, 0x05030b03u, 0x05050103u, 0x05050109u, 0x0505010fu, 0x05050503u,
+ 0x05050507u, 0x05050701u, 0x0505070fu, 0x05050903u, 0x05050b07u, 0x05050b0fu,
+ 0x05050f03u, 0x05050f09u, 0x05070101u, 0x05070105u, 0x0507010bu, 0x05070303u,
+ 0x05070505u, 0x05070509u, 0x05070703u, 0x05070707u, 0x05070905u, 0x05070b01u,
+ 0x05070d0du, 0x05090103u, 0x0509010fu, 0x05090501u, 0x05090507u, 0x05090705u,
+ 0x0509070bu, 0x05090903u, 0x05090f05u, 0x05090f0bu, 0x050b0109u, 0x050b0303u,
+ 0x050b0505u, 0x050b070fu, 0x050b0901u, 0x050b0b07u, 0x050b0f01u, 0x050d0101u,
+ 0x050d0105u, 0x050d010fu, 0x050d0503u, 0x050d0b0bu, 0x050d0d03u, 0x050f010bu,
+ 0x050f0303u, 0x050f050du, 0x050f0701u, 0x050f0907u, 0x050f0b01u, 0x07010105u,
+ 0x07010303u, 0x07010307u, 0x0701030bu, 0x0701030fu, 0x07010505u, 0x07010703u,
+ 0x07010707u, 0x0701070bu, 0x07010905u, 0x07010909u, 0x0701090fu, 0x07010b03u,
+ 0x07010d07u, 0x07010f03u, 0x07030103u, 0x07030107u, 0x0703010bu, 0x07030309u,
+ 0x07030503u, 0x07030507u, 0x07030901u, 0x07030d01u, 0x07030f05u, 0x07030f0du,
+ 0x07050101u, 0x07050305u, 0x07050501u, 0x07050705u, 0x07050709u, 0x07050b01u,
+ 0x07070103u, 0x07070301u, 0x07070309u, 0x07070503u, 0x07070507u, 0x0707050fu,
+ 0x07070701u, 0x07070903u, 0x07070907u, 0x0707090fu, 0x07070b0bu, 0x07070f07u,
+ 0x07090107u, 0x07090303u, 0x0709030du, 0x07090505u, 0x07090703u, 0x07090b05u,
+ 0x07090d01u, 0x07090d09u, 0x070b0103u, 0x070b0301u, 0x070b0305u, 0x070b050bu,
+ 0x070b0705u, 0x070b0909u, 0x070b0b0du, 0x070b0f07u, 0x070d030du, 0x070d0903u,
+ 0x070f0103u, 0x070f0107u, 0x070f0501u, 0x070f0505u, 0x070f070bu, 0x09010101u,
+ 0x09010109u, 0x09010305u, 0x09010501u, 0x09010509u, 0x0901050fu, 0x09010705u,
+ 0x09010903u, 0x09010b01u, 0x09010f01u, 0x09030105u, 0x0903010fu, 0x09030303u,
+ 0x09030307u, 0x09030505u, 0x09030701u, 0x0903070bu, 0x09030907u, 0x09030b03u,
+ 0x09030b0bu, 0x09050103u, 0x09050107u, 0x09050301u, 0x0905030bu, 0x09050503u,
+ 0x09050707u, 0x09050901u, 0x09050b0fu, 0x09050d05u, 0x09050f01u, 0x09070109u,
+ 0x09070303u, 0x09070307u, 0x09070501u, 0x09070505u, 0x09070703u, 0x0907070bu,
+ 0x09090101u, 0x09090105u, 0x09090509u, 0x0909070fu, 0x09090901u, 0x09090f03u,
+ 0x090b010bu, 0x090b010fu, 0x090b0503u, 0x090b0d05u, 0x090d0307u, 0x090d0709u,
+ 0x090d0d01u, 0x090f0301u, 0x090f030bu, 0x090f0701u, 0x090f0907u, 0x090f0b03u,
+ 0x0b010105u, 0x0b010301u, 0x0b010309u, 0x0b010505u, 0x0b010901u, 0x0b010909u,
+ 0x0b01090fu, 0x0b010b05u, 0x0b010d0du, 0x0b010f09u, 0x0b030103u, 0x0b030107u,
+ 0x0b03010bu, 0x0b030305u, 0x0b030503u, 0x0b030705u, 0x0b030f05u, 0x0b050101u,
+ 0x0b050303u, 0x0b050507u, 0x0b050701u, 0x0b05070du, 0x0b050b07u, 0x0b070105u,
+ 0x0b07010fu, 0x0b070301u, 0x0b07050fu, 0x0b070909u, 0x0b070b03u, 0x0b070d0bu,
+ 0x0b070f07u, 0x0b090103u, 0x0b090109u, 0x0b090501u, 0x0b090705u, 0x0b09090du,
+ 0x0b0b0305u, 0x0b0b050du, 0x0b0b0b03u, 0x0b0b0b07u, 0x0b0d0905u, 0x0b0f0105u,
+ 0x0b0f0109u, 0x0b0f0505u, 0x0d010303u, 0x0d010307u, 0x0d01030bu, 0x0d010703u,
+ 0x0d010707u, 0x0d010d01u, 0x0d030101u, 0x0d030501u, 0x0d03050fu, 0x0d030d09u,
+ 0x0d050305u, 0x0d050709u, 0x0d050905u, 0x0d050b0bu, 0x0d050d05u, 0x0d050f01u,
+ 0x0d070101u, 0x0d070309u, 0x0d070503u, 0x0d070901u, 0x0d09050bu, 0x0d090907u,
+ 0x0d090d05u, 0x0d0b0101u, 0x0d0b0107u, 0x0d0b0709u, 0x0d0b0d01u, 0x0d0d010bu,
+ 0x0d0d0901u, 0x0d0f0303u, 0x0d0f0307u, 0x0f010101u, 0x0f010109u, 0x0f01010fu,
+ 0x0f010501u, 0x0f010505u, 0x0f01070du, 0x0f010901u, 0x0f010b09u, 0x0f010d05u,
+ 0x0f030105u, 0x0f030303u, 0x0f030509u, 0x0f030907u, 0x0f03090bu, 0x0f050103u,
+ 0x0f050109u, 0x0f050301u, 0x0f05030du, 0x0f050503u, 0x0f050701u, 0x0f050b03u,
+ 0x0f070105u, 0x0f070705u, 0x0f07070bu, 0x0f070b07u, 0x0f090103u, 0x0f09010bu,
+ 0x0f090307u, 0x0f090501u, 0x0f090b01u, 0x0f0b0505u, 0x0f0b0905u, 0x0f0d0105u,
+ 0x0f0d0703u, 0x0f0f0101u);
+
+
+/* byte i from byte off of w */
+uint wbyte(U1 W, uint off, uint i)
+{
+ uint a = off + i;
+ return (W.v[a >> 2] >> (8u * (a & 3u))) & 0xffu;
+}
+
+/* the four levels of a grid entry, each negated where its sign bit is set
+ (bits 0-3 of s), as signed bytes */
+uint signed4(uint g, uint s)
+{
+ uint r = 0u;
+ [[unroll]] for (uint i = 0; i < 4u; i++) {
+ int v = int((g >> (8u * i)) & 0xffu);
+ if (((s >> i) & 1u) != 0u)
+ v = -v;
+ r |= (uint(v) & 0xffu) << (8u * i);
+ }
+ return r;
+}
+
+void main()
+{
+ U4 X = U4(p.x);
+ U1 W = U1(p.w);
+ F Y = F(p.y);
+ uint id = gl_LocalInvocationID.x;
+ uint r0 = gl_WorkGroupID.x * BM, v0 = gl_WorkGroupID.y * BN;
+ uint warp = id / WARP, tiw = id % WARP;
+ uint tiwr = tiw % (WM / TM), tiwc = tiw / (WM / TM);
+ uint warp_r = warp % (BM / WM), warp_c = warp / (BM / WM);
+ float sums[WNITER * TN * TM];
+ [[unroll]] for (uint i = 0; i < WNITER * TN * TM; i++) sums[i] = 0.0;
+ uint ngroups = p.nb * 8u;
+ for (uint g0 = 0; g0 < ngroups; g0 += KS) {
+ // weights: 4 invocations a row, 2 words each of the group's 8
+ {
+ uint iqs = id % 4u, rl = id / 4u;
+ [[unroll]] for (uint l = 0; l < BM; l += 32u) {
+ uint r = min(r0 + rl + l, p.rows - 1u);
+ // the 4 groups staged are in one block (g0 is a multiple of 4)
+ uint b = g0 / 8u, gb = g0 % 8u;
+ uint off = (r * p.nb + b) * 110u;
+ [[unroll]] for (uint k = 0; k < KS; k++) {
+ uint g = gb + k, qh = wbyte(W, off, 66u + g);
+ [[unroll]] for (uint t = 0; t < 2u; t++) {
+ uint kw = 2u * iqs + t;
+ uint idx = wbyte(W, off, 2u + 8u * g + kw) | (((qh >> kw) & 1u) << 8);
+ uint sg = wbyte(W, off, 74u + 4u * g + kw / 2u) >> (4u * (kw & 1u));
+ sa[k * BM + rl + l].qs[kw] = signed4(GRID[idx], sg & 15u);
+ }
+ if (iqs == 0u) {
+ float d = unpackHalf2x16(wbyte(W, off, 0u) | (wbyte(W, off, 1u) << 8)).x;
+ uint sc = (wbyte(W, off, 106u + g / 2u) >> (4u * (g & 1u))) & 15u;
+ sa[k * BM + rl + l].dsc = d * float(1 + 2 * int(sc));
+ }
+ }
+ }
+ }
+ // activations: 2 invocations a vector, each half a group's quants
+ {
+ uint iqs = id % 2u, c = id / 2u;
+ uint v = min(v0 + c, p.nv - 1u);
+ [[unroll]] for (uint k = 0; k < KS; k++) {
+ uint g = g0 + k, b = g / 8u, G = g % 8u;
+ uint xo = (v * p.xs + b) * XB;
+ uvec4 q = X.v[xo + 2u * G + iqs];
+ sb[k * BN + c].qs[4u * iqs] = int(q.x);
+ sb[k * BN + c].qs[4u * iqs + 1u] = int(q.y);
+ sb[k * BN + c].qs[4u * iqs + 2u] = int(q.z);
+ sb[k * BN + c].qs[4u * iqs + 3u] = int(q.w);
+ if (iqs == 0u)
+ sb[k * BN + c].d8 = uintBitsToFloat(X.v[xo + 18u].x);
+ }
+ }
+ barrier();
+ for (uint k = 0; k < KS; k++) {
+ ACache ca[TM];
+ [[unroll]] for (uint cr = 0; cr < TM; cr++)
+ ca[cr] = sa[k * BM + warp_r * WM + tiwr * TM + cr];
+ [[unroll]] for (uint wsic = 0; wsic < WNITER; wsic++)
+ [[unroll]] for (uint cc = 0; cc < TN; cc++) {
+ BCache cb = sb[k * BN + warp_c * WN + wsic * WSUBN + tiwc * TN + cc];
+ [[unroll]] for (uint cr = 0; cr < TM; cr++) {
+ int q = 0;
+ [[unroll]] for (uint i = 0; i < 8u; i++)
+ q += dotPacked4x8EXT(int(ca[cr].qs[i]), cb.qs[i]);
+ sums[(wsic * TN + cc) * TM + cr] += cb.d8 * ca[cr].dsc * float(q);
+ }
+ }
+ }
+ barrier();
+ }
+ [[unroll]] for (uint wsic = 0; wsic < WNITER; wsic++)
+ [[unroll]] for (uint cc = 0; cc < TN; cc++)
+ [[unroll]] for (uint cr = 0; cr < TM; cr++) {
+ uint row = r0 + warp_r * WM + tiwr * TM + cr;
+ uint v = v0 + warp_c * WN + wsic * WSUBN + tiwc * TN + cc;
+ if (row < p.rows && v < p.nv)
+ Y.v[v * p.ys + row] = sums[(wsic * TN + cc) * TM + cr];
+ }
+}
diff --git a/src/llm/shaders/iq4nl_mmq.comp b/src/llm/shaders/iq4nl_mmq.comp
new file mode 100644
index 0000000..57135e4
--- /dev/null
+++ b/src/llm/shaders/iq4nl_mmq.comp
@@ -0,0 +1,131 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// The fast prompt for IQ4_NL: q80_mmq.comp's tiling and activations (blocks
+// of 32), a group's weights its 16 bytes of nibbles through the sixteen
+// signed levels of IQ4_NL (weights 0-15 the low nibbles, 16-31 the high),
+// its scale the block's d. A block is 18 bytes, so its words are read
+// realigned. NOT bit for bit with the CPU: rounded group by group.
+#extension GL_EXT_control_flow_attributes : require
+#extension GL_EXT_integer_dot_product : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 128) in;
+layout(constant_id = 0) const uint NV = 8; // unused: the table's constants
+layout(constant_id = 1) const uint SG = 8;
+
+const uint BM = 64u, BN = 64u, BK = 32u, KS = 4u;
+const uint WM = 32u, WN = 32u, TM = 2u, TN = 2u, WARP = 32u;
+const uint WNITER = (WM * WN) / (WARP * TM * TN); // 8
+const uint WSUBN = WN / WNITER; // 4
+const uint XB = 20u; // uvec4 an activations' block
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+// w: the first row (rows of nb * 8 blocks of 34 bytes); x: vector v, block
+// b at uvec4 (v * xs + b) * 20; y: row r of vector v at y[v * ys + r]
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+struct ACache { int qs[8]; float d; }; // a group: its 32 levels, d
+struct BCache { int qs[8]; float d; }; // a group: quants, its d32
+shared ACache sa[BM * KS];
+shared BCache sb[BN * KS];
+
+// word i of the 32-bit words from byte off of w, off even
+uint hword(U1 W, uint off, uint i)
+{
+ uint a = (off >> 2) + i;
+ return (off & 2u) != 0u ? (W.v[a] >> 16) | (W.v[a + 1u] << 16) : W.v[a];
+}
+
+const int IQ4[16] = int[16](-127, -104, -83, -65, -49, -35, -22, -10,
+ 1, 13, 25, 38, 53, 69, 89, 113);
+
+/* each byte of w (a nibble) through the IQ4_NL table */
+uint iq4(uint w)
+{
+ return (uint(IQ4[w & 15u]) & 0xffu) | ((uint(IQ4[(w >> 8) & 15u]) & 0xffu) << 8) |
+ ((uint(IQ4[(w >> 16) & 15u]) & 0xffu) << 16) |
+ ((uint(IQ4[(w >> 24) & 15u]) & 0xffu) << 24);
+}
+
+void main()
+{
+ U4 X = U4(p.x);
+ U1 W1 = U1(p.w);
+ F Y = F(p.y);
+ uint id = gl_LocalInvocationID.x;
+ uint r0 = gl_WorkGroupID.x * BM, v0 = gl_WorkGroupID.y * BN;
+ uint warp = id / WARP, tiw = id % WARP;
+ uint tiwr = tiw % (WM / TM), tiwc = tiw / (WM / TM);
+ uint warp_r = warp % (BM / WM), warp_c = warp / (BM / WM);
+ float sums[WNITER * TN * TM];
+ [[unroll]] for (uint i = 0; i < WNITER * TN * TM; i++) sums[i] = 0.0;
+ uint ngroups = p.nb * 8u;
+ for (uint g0 = 0; g0 < ngroups; g0 += KS) {
+ // weights: 4 invocations a row, 2 words each of the group's 8
+ {
+ uint iqs = id % 4u, rl = id / 4u;
+ [[unroll]] for (uint l = 0; l < BM; l += 32u) {
+ uint r = min(r0 + rl + l, p.rows - 1u);
+ [[unroll]] for (uint k = 0; k < KS; k++) {
+ uint off = (r * ngroups + g0 + k) * 18u;
+ [[unroll]] for (uint t = 0; t < 2u; t++) {
+ uint kw = 2u * iqs + t, q = hword(W1, off + 2u, kw & 3u);
+ sa[k * BM + rl + l].qs[kw] =
+ int(iq4(kw < 4u ? q & 0x0f0f0f0fu : (q >> 4) & 0x0f0f0f0fu));
+ }
+ if (iqs == 0u)
+ sa[k * BM + rl + l].d = unpackHalf2x16(hword(W1, off, 0u) & 0xffffu).x;
+ }
+ }
+ }
+ // activations: 2 invocations a vector, each half a group's quants
+ {
+ uint iqs = id % 2u, c = id / 2u;
+ uint v = min(v0 + c, p.nv - 1u);
+ [[unroll]] for (uint k = 0; k < KS; k++) {
+ uint g = g0 + k, b = g / 8u, j = g % 8u;
+ uint xo = (v * p.xs + b) * XB;
+ uvec4 q = X.v[xo + 2u * j + iqs];
+ sb[k * BN + c].qs[4u * iqs] = int(q.x);
+ sb[k * BN + c].qs[4u * iqs + 1u] = int(q.y);
+ sb[k * BN + c].qs[4u * iqs + 2u] = int(q.z);
+ sb[k * BN + c].qs[4u * iqs + 3u] = int(q.w);
+ if (iqs == 0u) {
+ uvec4 dq = X.v[xo + 18u + j / 4u];
+ uint dw = j % 4u == 0u ? dq.x : j % 4u == 1u ? dq.y : j % 4u == 2u ? dq.z : dq.w;
+ sb[k * BN + c].d = uintBitsToFloat(dw);
+ }
+ }
+ }
+ barrier();
+ for (uint k = 0; k < KS; k++) {
+ ACache ca[TM];
+ [[unroll]] for (uint cr = 0; cr < TM; cr++)
+ ca[cr] = sa[k * BM + warp_r * WM + tiwr * TM + cr];
+ [[unroll]] for (uint wsic = 0; wsic < WNITER; wsic++)
+ [[unroll]] for (uint cc = 0; cc < TN; cc++) {
+ BCache cb = sb[k * BN + warp_c * WN + wsic * WSUBN + tiwc * TN + cc];
+ [[unroll]] for (uint cr = 0; cr < TM; cr++) {
+ int q = 0;
+ [[unroll]] for (uint i = 0; i < 8u; i++)
+ q += dotPacked4x8EXT(ca[cr].qs[i], cb.qs[i]);
+ sums[(wsic * TN + cc) * TM + cr] += ca[cr].d * cb.d * float(q);
+ }
+ }
+ }
+ barrier();
+ }
+ [[unroll]] for (uint wsic = 0; wsic < WNITER; wsic++)
+ [[unroll]] for (uint cc = 0; cc < TN; cc++)
+ [[unroll]] for (uint cr = 0; cr < TM; cr++) {
+ uint row = r0 + warp_r * WM + tiwr * TM + cr;
+ uint v = v0 + warp_c * WN + wsic * WSUBN + tiwc * TN + cc;
+ if (row < p.rows && v < p.nv)
+ Y.v[v * p.ys + row] = sums[(wsic * TN + cc) * TM + cr];
+ }
+}
diff --git a/src/llm/shaders/iq4xs_matvec.comp b/src/llm/shaders/iq4xs_matvec.comp
index c712fb1..8b7721a 100644
--- a/src/llm/shaders/iq4xs_matvec.comp
+++ b/src/llm/shaders/iq4xs_matvec.comp
@@ -33,22 +33,34 @@ int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
int dp4(uvec4 a, uvec4 b) { return dp(a.x, b.x) + dp(a.y, b.y) + dp(a.z, b.z) + dp(a.w, b.w); }
uvec4 bc(uvec4 xr[NX], uint k) { return subgroupBroadcast(xr[k / SG], k % SG); }
+/* The table in the workgroup's shared memory: a constant array read at a
+ varying index is far slower on some GPUs (on the development laptop's,
+ IQ4_XS on 8 vectors 3.73 -> 2.67 ms; a table of 256 entries, both
+ nibbles of a byte in one read, was slower again: 2.98, 12 Oct 2026). */
+shared uint T[16];
+
/* each byte of w (a nibble) through the IQ4_NL table */
uint iq4(uint w)
{
- return (uint(IQ4[w & 15u]) & 0xffu) | ((uint(IQ4[(w >> 8) & 15u]) & 0xffu) << 8) |
- ((uint(IQ4[(w >> 16) & 15u]) & 0xffu) << 16) |
- ((uint(IQ4[(w >> 24) & 15u]) & 0xffu) << 24);
+ return T[w & 15u] | (T[(w >> 8) & 15u] << 8) | (T[(w >> 16) & 15u] << 16) |
+ (T[(w >> 24) & 15u] << 24);
}
void main()
{
+ if (gl_LocalInvocationID.x < 16u)
+ T[gl_LocalInvocationID.x] = uint(IQ4[gl_LocalInvocationID.x]) & 0xffu;
+ barrier();
U1 W = U1(p.w);
U4 X = U4(p.x);
F Y = F(p.y);
uint lane = gl_SubgroupInvocationID;
- uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
- uint v0 = gl_WorkGroupID.y * NV;
+ /* workgroup y: 64 rows; x: a group of NV vectors, so that the groups
+ of the same rows go out together and the weights the first reads
+ from memory the others find in the L3 */
+ uint grow = gl_WorkGroupID.y * 64u + gl_LocalInvocationID.x;
+ uint row = min(grow, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.x * NV;
uint xo[NV];
for (uint v = 0; v < NV; v++)
xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
@@ -85,7 +97,7 @@ void main()
xo[v] += 20u;
}
}
- if (gl_GlobalInvocationID.x < p.rows)
+ if (grow < p.rows)
for (uint v = 0; v < NV; v++)
if (v0 + v < p.nv)
Y.v[(v0 + v) * p.ys + row] = acc[v];
diff --git a/src/llm/shaders/iq4xs_mmq.comp b/src/llm/shaders/iq4xs_mmq.comp
new file mode 100644
index 0000000..b2b96c8
--- /dev/null
+++ b/src/llm/shaders/iq4xs_mmq.comp
@@ -0,0 +1,134 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// The fast prompt for IQ4_XS: the tiling of q4k_mmq.comp, as q3k_mmq.comp.
+// A group of 32 weights has one 6-bit scale (less 32); a weight is a nibble
+// through the sixteen signed levels of IQ4_NL (iq4xs_matvec.comp), so the
+// products need no correction with the activations' sums. A block is 136
+// bytes, 34 words: d and scales_h, scales_l, then group g's 16 bytes
+// holding its weights 0-15 (low nibbles) and 16-31 (high). NOT bit for bit
+// with the CPU: rounded group by group.
+#extension GL_EXT_control_flow_attributes : require
+#extension GL_EXT_integer_dot_product : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 128) in;
+layout(constant_id = 0) const uint NV = 8; // unused: the table's constants
+layout(constant_id = 1) const uint SG = 8;
+
+const uint BM = 64u, BN = 64u, KS = 4u;
+const uint WM = 32u, WN = 32u, TM = 2u, TN = 2u, WARP = 32u;
+const uint WNITER = (WM * WN) / (WARP * TM * TN); // 8
+const uint WSUBN = WN / WNITER; // 4
+const uint XB = 20u;
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+struct ACache { uint qs[8]; float dsc; }; // a group: its levels as bytes, d * scale
+struct BCache { int qs[8]; float d8; }; // quants, d8
+shared ACache sa[BM * KS];
+shared BCache sb[BN * KS];
+
+const int IQ4[16] = int[16](-127, -104, -83, -65, -49, -35, -22, -10,
+ 1, 13, 25, 38, 53, 69, 89, 113);
+
+/* each byte of w (a nibble) through the IQ4_NL table */
+uint iq4(uint w)
+{
+ return (uint(IQ4[w & 15u]) & 0xffu) | ((uint(IQ4[(w >> 8) & 15u]) & 0xffu) << 8) |
+ ((uint(IQ4[(w >> 16) & 15u]) & 0xffu) << 16) |
+ ((uint(IQ4[(w >> 24) & 15u]) & 0xffu) << 24);
+}
+
+void main()
+{
+ U4 X = U4(p.x);
+ U1 W = U1(p.w);
+ F Y = F(p.y);
+ uint id = gl_LocalInvocationID.x;
+ uint r0 = gl_WorkGroupID.x * BM, v0 = gl_WorkGroupID.y * BN;
+ uint warp = id / WARP, tiw = id % WARP;
+ uint tiwr = tiw % (WM / TM), tiwc = tiw / (WM / TM);
+ uint warp_r = warp % (BM / WM), warp_c = warp / (BM / WM);
+ float sums[WNITER * TN * TM];
+ [[unroll]] for (uint i = 0; i < WNITER * TN * TM; i++) sums[i] = 0.0;
+ uint ngroups = p.nb * 8u;
+ for (uint g0 = 0; g0 < ngroups; g0 += KS) {
+ // weights: 4 invocations a row, 2 words each of the group's 8
+ {
+ uint iqs = id % 4u, rl = id / 4u;
+ [[unroll]] for (uint l = 0; l < BM; l += 32u) {
+ uint r = min(r0 + rl + l, p.rows - 1u);
+ // the 4 groups staged are in one block (g0 is a multiple of
+ // 4): words 0-3 of a group are the low nibbles of its 4 words
+ // of qs, words 4-7 the high
+ uint b = g0 / 8u, gb = g0 % 8u;
+ uint off = (r * p.nb + b) * 34u;
+ [[unroll]] for (uint k = 0; k < KS; k++)
+ [[unroll]] for (uint t = 0; t < 2u; t++) {
+ uint kw = 2u * iqs + t;
+ uint q = W.v[off + 2u + 4u * (gb + k) + (kw & 3u)];
+ sa[k * BM + rl + l].qs[kw] =
+ iq4(kw < 4u ? q & 0x0f0f0f0fu : (q >> 4) & 0x0f0f0f0fu);
+ }
+ if (iqs == 0u) {
+ uint w0 = W.v[off], sl = W.v[off + 1u];
+ float d = unpackHalf2x16(w0).x;
+ uint sh = w0 >> 16;
+ [[unroll]] for (uint k = 0; k < KS; k++) {
+ uint g = gb + k;
+ uint ls = ((sl >> (8u * (g / 2u) + 4u * (g & 1u))) & 15u) |
+ (((sh >> (2u * g)) & 3u) << 4);
+ sa[k * BM + rl + l].dsc = d * float(int(ls) - 32);
+ }
+ }
+ }
+ }
+ // activations: 2 invocations a vector, each half a group's quants
+ {
+ uint iqs = id % 2u, c = id / 2u;
+ uint v = min(v0 + c, p.nv - 1u);
+ [[unroll]] for (uint k = 0; k < KS; k++) {
+ uint g = g0 + k, b = g / 8u, G = g % 8u;
+ uint xo = (v * p.xs + b) * XB;
+ uvec4 q = X.v[xo + 2u * G + iqs];
+ sb[k * BN + c].qs[4u * iqs] = int(q.x);
+ sb[k * BN + c].qs[4u * iqs + 1u] = int(q.y);
+ sb[k * BN + c].qs[4u * iqs + 2u] = int(q.z);
+ sb[k * BN + c].qs[4u * iqs + 3u] = int(q.w);
+ if (iqs == 0u)
+ sb[k * BN + c].d8 = uintBitsToFloat(X.v[xo + 18u].x);
+ }
+ }
+ barrier();
+ for (uint k = 0; k < KS; k++) {
+ ACache ca[TM];
+ [[unroll]] for (uint cr = 0; cr < TM; cr++)
+ ca[cr] = sa[k * BM + warp_r * WM + tiwr * TM + cr];
+ [[unroll]] for (uint wsic = 0; wsic < WNITER; wsic++)
+ [[unroll]] for (uint cc = 0; cc < TN; cc++) {
+ BCache cb = sb[k * BN + warp_c * WN + wsic * WSUBN + tiwc * TN + cc];
+ [[unroll]] for (uint cr = 0; cr < TM; cr++) {
+ int q = 0;
+ [[unroll]] for (uint i = 0; i < 8u; i++)
+ q += dotPacked4x8EXT(int(ca[cr].qs[i]), cb.qs[i]);
+ sums[(wsic * TN + cc) * TM + cr] += cb.d8 * ca[cr].dsc * float(q);
+ }
+ }
+ }
+ barrier();
+ }
+ [[unroll]] for (uint wsic = 0; wsic < WNITER; wsic++)
+ [[unroll]] for (uint cc = 0; cc < TN; cc++)
+ [[unroll]] for (uint cr = 0; cr < TM; cr++) {
+ uint row = r0 + warp_r * WM + tiwr * TM + cr;
+ uint v = v0 + warp_c * WN + wsic * WSUBN + tiwc * TN + cc;
+ if (row < p.rows && v < p.nv)
+ Y.v[v * p.ys + row] = sums[(wsic * TN + cc) * TM + cr];
+ }
+}
diff --git a/src/llm/shaders/iq4xs_mvd.comp b/src/llm/shaders/iq4xs_mvd.comp
new file mode 100644
index 0000000..fa9b297
--- /dev/null
+++ b/src/llm/shaders/iq4xs_mvd.comp
@@ -0,0 +1,100 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// IQ4_XS weights times 2 to 8 Q8_K vectors with the lanes on the vectors,
+// as q4k_mvd.comp: lane v of a subgroup of 8 is vector v, and a subgroup
+// takes R rows one after the other. Lane i reads group i's 16 bytes of
+// nibbles of a row's block - the subgroup 128 contiguous bytes - and turns
+// them into IQ4_NL's levels through the table in shared memory (as
+// iq4xs_matvec.comp), once for all the vectors; the levels reach every
+// lane's dot products through subgroupBroadcast. iq4xs_matvec puts a row
+// on a lane, and its loads of the weights touch eight rows each. A block is
+// 136 bytes, its nibbles from byte 8: words, read four at a time. As
+// janas_iq4xs_dot_ref: each group's integer dot times its scale (ls - 32),
+// the block's exact integer sum in one fma - the CPU's result bit for bit.
+// Subgroups of 8 lanes; workgroup x: a group of 8 vectors, y: the rows (32
+// a workgroup, gpu_impl.h MVD_ROWS).
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_ballot : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+#extension GL_EXT_control_flow_attributes : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 8; /* unused: the lanes are the vectors */
+layout(constant_id = 1) const uint SG = 8;
+const uint R = 4; /* rows a subgroup */
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+const int IQ4[16] = int[16](-127, -104, -83, -65, -49, -35, -22, -10,
+ 1, 13, 25, 38, 53, 69, 89, 113);
+shared uint T[16];
+
+/* the uvec4 at byte lo of the 4 GB whose high word is hi: neither buffer
+ crosses a 4 GB boundary (the host checks) */
+uvec4 at(uint lo, uint hi) { return U4(uvec2(lo, hi)).v[0]; }
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+/* each byte of w (a nibble) through the IQ4_NL table */
+uint iq4(uint w)
+{
+ return T[w & 15u] | (T[(w >> 8) & 15u] << 8) | (T[(w >> 16) & 15u] << 16) |
+ (T[(w >> 24) & 15u] << 24);
+}
+
+void main()
+{
+ if (gl_LocalInvocationID.x < 16u)
+ T[gl_LocalInvocationID.x] = uint(IQ4[gl_LocalInvocationID.x]) & 0xffu;
+ barrier();
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID;
+ uint row0 = (gl_WorkGroupID.y * (64u / SG) + gl_SubgroupID) * R;
+ uint v = gl_WorkGroupID.x * SG + lane, vv = min(v, p.nv - 1u);
+ /* this lane's vector: its blocks from byte xl */
+ uint xl = p.x.x + vv * p.xs * 320u;
+ float acc[R];
+ for (uint r = 0; r < R; r++)
+ acc[r] = 0.0;
+ for (uint b = 0; b < p.nb; b++) {
+ /* the vector's block: 256 quants (group g: 2g, 2g + 1), the scale */
+ uvec4 xq[16];
+ for (uint k = 0; k < 16u; k++)
+ xq[k] = at(xl + b * 320u + 16u * k, p.x.y);
+ float d8 = uintBitsToFloat(at(xl + b * 320u + 288u, p.x.y).x);
+ for (uint r = 0; r < R; r++) {
+ uint row = min(row0 + r, p.rows - 1u);
+ U1 B = U1(uvec2(p.w.x + (row * p.nb + b) * 136u, p.w.y));
+ /* d and scales_h, scales_l: every lane the same */
+ uint w0 = B.v[0], sl = B.v[1];
+ /* group lane's nibbles: weights 0-15 low, 16-31 high */
+ uvec4 q = uvec4(B.v[2u + 4u * lane], B.v[3u + 4u * lane],
+ B.v[4u + 4u * lane], B.v[5u + 4u * lane]);
+ uvec4 lo = uvec4(iq4(q.x & 0x0f0f0f0fu), iq4(q.y & 0x0f0f0f0fu),
+ iq4(q.z & 0x0f0f0f0fu), iq4(q.w & 0x0f0f0f0fu));
+ uvec4 hi = uvec4(iq4((q.x >> 4) & 0x0f0f0f0fu), iq4((q.y >> 4) & 0x0f0f0f0fu),
+ iq4((q.z >> 4) & 0x0f0f0f0fu), iq4((q.w >> 4) & 0x0f0f0f0fu));
+ uint sh = w0 >> 16;
+ int isum = 0;
+ [[unroll]] for (uint g = 0; g < 8u; g++) {
+ uvec4 l = subgroupBroadcast(lo, g), u = subgroupBroadcast(hi, g);
+ uvec4 a = xq[2u * g], e = xq[2u * g + 1u];
+ int dg = dp(l.x, a.x) + dp(l.y, a.y) + dp(l.z, a.z) + dp(l.w, a.w) +
+ dp(u.x, e.x) + dp(u.y, e.y) + dp(u.z, e.z) + dp(u.w, e.w);
+ uint ls = ((sl >> (8u * (g >> 1) + 4u * (g & 1u))) & 15u) |
+ (((sh >> (2u * g)) & 3u) << 4);
+ isum += (int(ls) - 32) * dg;
+ }
+ float d = unpackHalf2x16(w0).x;
+ acc[r] = fma(d * d8, float(isum), acc[r]);
+ }
+ }
+ if (v < p.nv)
+ for (uint r = 0; r < R; r++)
+ if (row0 + r < p.rows)
+ Y.v[v * p.ys + row0 + r] = acc[r];
+}
diff --git a/src/llm/shaders/q3k_matvec.comp b/src/llm/shaders/q3k_matvec.comp
index 5218aea..5b2e68b 100644
--- a/src/llm/shaders/q3k_matvec.comp
+++ b/src/llm/shaders/q3k_matvec.comp
@@ -40,8 +40,12 @@ void main()
U4 X = U4(p.x);
F Y = F(p.y);
uint lane = gl_SubgroupInvocationID;
- uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
- uint v0 = gl_WorkGroupID.y * NV;
+ /* workgroup y: 64 rows; x: a group of NV vectors, so that the groups
+ of the same rows go out together and the weights the first reads
+ from memory the others find in the L3 */
+ uint grow = gl_WorkGroupID.y * 64u + gl_LocalInvocationID.x;
+ uint row = min(grow, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.x * NV;
uint xo[NV];
for (uint v = 0; v < NV; v++)
xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
@@ -98,7 +102,7 @@ void main()
xo[v] += 20u;
}
}
- if (gl_GlobalInvocationID.x < p.rows)
+ if (grow < p.rows)
for (uint v = 0; v < NV; v++)
if (v0 + v < p.nv)
Y.v[(v0 + v) * p.ys + row] = acc[v];
diff --git a/src/llm/shaders/q4k_matvec.comp b/src/llm/shaders/q4k_matvec.comp
index 1eca167..cdba94d 100644
--- a/src/llm/shaders/q4k_matvec.comp
+++ b/src/llm/shaders/q4k_matvec.comp
@@ -37,8 +37,12 @@ void main()
U4 W = U4(p.w), X = U4(p.x);
F Y = F(p.y);
uint lane = gl_SubgroupInvocationID;
- uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
- uint v0 = gl_WorkGroupID.y * NV;
+ /* workgroup y: 64 rows; x: a group of NV vectors, so that the groups
+ of the same rows go out together and the weights the first reads
+ from memory the others find in the L3 */
+ uint grow = gl_WorkGroupID.y * 64u + gl_LocalInvocationID.x;
+ uint row = min(grow, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.x * NV;
uint xo[NV];
for (uint v = 0; v < NV; v++)
xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
@@ -83,7 +87,7 @@ void main()
xo[v] += 20u;
}
}
- if (gl_GlobalInvocationID.x < p.rows)
+ if (grow < p.rows)
for (uint v = 0; v < NV; v++)
if (v0 + v < p.nv)
Y.v[(v0 + v) * p.ys + row] = acc[v] - accm[v];
diff --git a/src/llm/shaders/q4k_mv.comp b/src/llm/shaders/q4k_mv.comp
new file mode 100644
index 0000000..6742160
--- /dev/null
+++ b/src/llm/shaders/q4k_mv.comp
@@ -0,0 +1,120 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Q4_K weights times NV Q8_K vectors (a chain of drafts, a short block),
+// one row per invocation, with as few instructions per multiply-add as the
+// layout allows: a block is taken a quarter at a time (sub-blocks 2c and
+// 2c + 1), its nibbles unpacked once for all the vectors; the activations
+// of a quarter come two vectors to a load of eight lanes (lane i: vector
+// 2m + i / 4, uvec4 i % 4 of the quarter) and reach the dot products as
+// scalar operands (subgroupBroadcast with a constant lane); the sums of 32
+// activations that the minimums weigh are made by the lanes in parallel,
+// four to a lane. The buffers of the weights and of the activations never
+// cross a 4 GB boundary (the host checks), so an address is its low word
+// plus an offset. The same integer sums and float operations as the CPU
+// kernels (janas_q4k_dot_ref): bit for bit. NV even; subgroups of 8 lanes
+// or more (beyond 8 the loads repeat).
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_ballot : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+#extension GL_EXT_control_flow_attributes : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 8;
+layout(constant_id = 1) const uint SG = 8;
+const uint NM = NV / 2u; /* loads of a quarter: two vectors each */
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+
+// w: the first row; x: vector v, block b at uvec4 (v * xs + b) * 20;
+// y: row r of vector v at y[v * ys + r]
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+/* the uvec4 at byte lo of the 4 GB whose high word is hi */
+uvec4 at(uint lo, uint hi) { return U4(uvec2(lo, hi)).v[0]; }
+
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+int dp4(uvec4 a, uvec4 b) { return dp(a.x, b.x) + dp(a.y, b.y) + dp(a.z, b.z) + dp(a.w, b.w); }
+
+void main()
+{
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID % 8u;
+ /* workgroup y: 64 rows; x: a group of NV vectors, so that the groups
+ of the same rows go out together and the weights the first reads
+ from memory the others find in the L3 */
+ uint grow = gl_WorkGroupID.y * 64u + gl_LocalInvocationID.x;
+ uint row = min(grow, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.x * NV;
+ /* this lane's share of each load of the activations: vector
+ 2m + lane / 4, uvec4 lane % 4 (of a quarter, or of the tail) */
+ uint xl[NM];
+ for (uint m = 0; m < NM; m++)
+ xl[m] = p.x.x + (min(v0 + 2u * m + lane / 4u, p.nv - 1u) * p.xs * 20u + lane % 4u) * 16u;
+ float acc[NV], accm[NV];
+ for (uint v = 0; v < NV; v++) {
+ acc[v] = 0.0;
+ accm[v] = 0.0;
+ }
+ uint wl = p.w.x + row * p.nb * 144u;
+ for (uint b = 0; b < p.nb; b++, wl += 144u) {
+ uvec4 hd = at(wl, p.w.y);
+ /* the scales and minimums of sub-blocks 0-3 and 4-7, a byte each */
+ uint sc03 = hd.y & 0x3f3f3f3fu, mn03 = hd.z & 0x3f3f3f3fu;
+ uint sc47 = (hd.w & 0x0f0f0f0fu) | ((hd.y >> 2) & 0x30303030u);
+ uint mn47 = ((hd.w >> 4) & 0x0f0f0f0fu) | ((hd.z >> 2) & 0x30303030u);
+ int isum[NV];
+ for (uint v = 0; v < NV; v++)
+ isum[v] = 0;
+ [[unroll]] for (uint c = 0; c < 4u; c++) {
+ uvec4 xr[NM];
+ for (uint m = 0; m < NM; m++)
+ xr[m] = at(xl[m] + b * 320u + 64u * c, p.x.y);
+ uvec4 q0 = at(wl + 16u + 32u * c, p.w.y), q1 = at(wl + 32u + 32u * c, p.w.y);
+ uvec4 l0 = q0 & 0x0f0f0f0fu, l1 = q1 & 0x0f0f0f0fu;
+ uvec4 h0 = (q0 >> 4) & 0x0f0f0f0fu, h1 = (q1 >> 4) & 0x0f0f0f0fu;
+ uint scw = c < 2u ? sc03 : sc47;
+ int sl = int(bitfieldExtract(scw, int(16u * (c & 1u)), 8));
+ int sh = int(bitfieldExtract(scw, int(16u * (c & 1u) + 8u), 8));
+ for (uint v = 0; v < NV; v++) {
+ uint m = v / 2u, o = 4u * (v % 2u);
+ int dl = dp4(l0, subgroupBroadcast(xr[m], o)) +
+ dp4(l1, subgroupBroadcast(xr[m], o + 1u));
+ int dh = dp4(h0, subgroupBroadcast(xr[m], o + 2u)) +
+ dp4(h1, subgroupBroadcast(xr[m], o + 3u));
+ isum[v] += dl * sl + dh * sh;
+ }
+ }
+ /* the tail of a vector's block, uvec4 16-19: the sums of 16 quants
+ two a word, then the scale; a lane adds its word's halves (lanes
+ 4h and 4h + 1: the sums of 32 of sub-blocks 0-3 and 4-7 of vector
+ 2m + h; lane 4h + 2 has its scale) */
+ ivec4 ps[NM];
+ uint d8w[NM];
+ for (uint m = 0; m < NM; m++) {
+ uvec4 t = at(xl[m] + b * 320u + 256u, p.x.y);
+ ps[m] = bitfieldExtract(ivec4(t), 0, 16) + (ivec4(t) >> 16);
+ d8w[m] = t.x;
+ }
+ int mn[8];
+ for (uint s = 0; s < 8u; s++)
+ mn[s] = int(bitfieldExtract(s < 4u ? mn03 : mn47, int(8u * (s & 3u)), 8));
+ vec2 dd = unpackHalf2x16(hd.x);
+ for (uint v = 0; v < NV; v++) {
+ uint m = v / 2u, o = 4u * (v % 2u);
+ ivec4 p0 = subgroupBroadcast(ps[m], o), p1 = subgroupBroadcast(ps[m], o + 1u);
+ float d8 = uintBitsToFloat(subgroupBroadcast(d8w[m], o + 2u));
+ int imin = mn[0] * p0.x + mn[1] * p0.y + mn[2] * p0.z + mn[3] * p0.w +
+ mn[4] * p1.x + mn[5] * p1.y + mn[6] * p1.z + mn[7] * p1.w;
+ acc[v] = fma(dd.x * d8, float(isum[v]), acc[v]);
+ accm[v] = fma(dd.y * d8, float(imin), accm[v]);
+ }
+ }
+ if (grow < p.rows)
+ for (uint v = 0; v < NV; v++)
+ if (v0 + v < p.nv)
+ Y.v[(v0 + v) * p.ys + row] = acc[v] - accm[v];
+}
diff --git a/src/llm/shaders/q4k_mvd.comp b/src/llm/shaders/q4k_mvd.comp
new file mode 100644
index 0000000..8f60e57
--- /dev/null
+++ b/src/llm/shaders/q4k_mvd.comp
@@ -0,0 +1,97 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Q4_K weights times 2 to 8 Q8_K vectors with the lanes on the vectors:
+// lane v of a subgroup of 8 is vector v, and a subgroup takes R rows one
+// after the other. A row's block is read as q4k_row reads it, 128
+// contiguous bytes a load (lane i: the block's i-th 16 bytes of nibbles),
+// and its words reach every lane's dot products as scalar operands
+// (subgroupBroadcast with a constant lane); each lane keeps its vector's
+// block of activations in registers for the R rows. q4k_matvec and q4k_mv
+// put a row on a lane instead, and their loads of the weights touch eight
+// rows each: on the development laptop's GPU they read 8 vectors of a
+// 17408 x 5120 matrix in 1.03-1.10 ms, this in 0.91, and 2 vectors in 0.81
+// where q4k_row takes 0.73 for one (13 Oct 2026). The same integer sums and
+// float operations as the CPU kernels (janas_q4k_dot_ref): bit for bit.
+// Subgroups of 8 lanes. Workgroup x: a group of 8 vectors; y: the rows.
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_ballot : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+#extension GL_EXT_control_flow_attributes : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 8; /* unused: the lanes are the vectors */
+layout(constant_id = 1) const uint SG = 8;
+const uint R = 4; /* rows a subgroup: 32 a workgroup (gpu_impl.h MVD_ROWS) */
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+/* the uvec4 at byte lo of the 4 GB whose high word is hi: neither buffer
+ crosses a 4 GB boundary (the host checks), so an address is its low word
+ plus an offset */
+uvec4 at(uint lo, uint hi) { return U4(uvec2(lo, hi)).v[0]; }
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+
+void main()
+{
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID;
+ uint row0 = (gl_WorkGroupID.y * (64u / SG) + gl_SubgroupID) * R;
+ uint v = gl_WorkGroupID.x * SG + lane, vv = min(v, p.nv - 1u);
+ /* this lane's vector: its blocks from byte xl */
+ uint xl = p.x.x + vv * p.xs * 320u;
+ float acc[R], accm[R];
+ for (uint r = 0; r < R; r++) {
+ acc[r] = 0.0;
+ accm[r] = 0.0;
+ }
+ for (uint b = 0; b < p.nb; b++) {
+ /* the vector's block: 256 quants, the sums of 16, the scale */
+ uvec4 xq[16];
+ for (uint k = 0; k < 16u; k++)
+ xq[k] = at(xl + b * 320u + 16u * k, p.x.y);
+ uvec4 t0 = at(xl + b * 320u + 256u, p.x.y), t1 = at(xl + b * 320u + 272u, p.x.y);
+ float d8 = uintBitsToFloat(at(xl + b * 320u + 288u, p.x.y).x);
+ ivec4 ps0 = bitfieldExtract(ivec4(t0), 0, 16) + (ivec4(t0) >> 16);
+ ivec4 ps1 = bitfieldExtract(ivec4(t1), 0, 16) + (ivec4(t1) >> 16);
+ int ps[8] = int[8](ps0.x, ps0.y, ps0.z, ps0.w, ps1.x, ps1.y, ps1.z, ps1.w);
+ for (uint r = 0; r < R; r++) {
+ uint row = min(row0 + r, p.rows - 1u);
+ uint wl = p.w.x + (row * p.nb + b) * 144u;
+ uvec4 hd = at(wl, p.w.y);
+ uvec4 q = at(wl + 16u + 16u * lane, p.w.y);
+ uvec4 lo = q & 0x0f0f0f0fu, hi = (q >> 4) & 0x0f0f0f0fu;
+ uint sc03 = hd.y & 0x3f3f3f3fu, mn03 = hd.z & 0x3f3f3f3fu;
+ uint sc47 = (hd.w & 0x0f0f0f0fu) | ((hd.y >> 2) & 0x30303030u);
+ uint mn47 = ((hd.w >> 4) & 0x0f0f0f0fu) | ((hd.z >> 2) & 0x30303030u);
+ int isum = 0, imin = 0;
+ [[unroll]] for (uint c = 0; c < 4u; c++) {
+ /* sub-blocks 2c (low nibbles) and 2c + 1 (high): lanes 2c and
+ 2c + 1 hold their halves */
+ int dl = 0, dh = 0;
+ for (uint h = 0; h < 2u; h++) {
+ uvec4 l = subgroupBroadcast(lo, 2u * c + h), u = subgroupBroadcast(hi, 2u * c + h);
+ uvec4 a = xq[4u * c + h], e = xq[4u * c + 2u + h];
+ dl += dp(l.x, a.x) + dp(l.y, a.y) + dp(l.z, a.z) + dp(l.w, a.w);
+ dh += dp(u.x, e.x) + dp(u.y, e.y) + dp(u.z, e.z) + dp(u.w, e.w);
+ }
+ uint scw = c < 2u ? sc03 : sc47;
+ isum += dl * int(bitfieldExtract(scw, int(16u * (c & 1u)), 8)) +
+ dh * int(bitfieldExtract(scw, int(16u * (c & 1u) + 8u), 8));
+ }
+ for (uint s = 0; s < 8u; s++)
+ imin += int(bitfieldExtract(s < 4u ? mn03 : mn47, int(8u * (s & 3u)), 8)) * ps[s];
+ vec2 dd = unpackHalf2x16(hd.x);
+ acc[r] = fma(dd.x * d8, float(isum), acc[r]);
+ accm[r] = fma(dd.y * d8, float(imin), accm[r]);
+ }
+ }
+ if (v < p.nv)
+ for (uint r = 0; r < R; r++)
+ if (row0 + r < p.rows)
+ Y.v[v * p.ys + row0 + r] = acc[r] - accm[r];
+}
diff --git a/src/llm/shaders/q5k_matvec.comp b/src/llm/shaders/q5k_matvec.comp
index db8536d..1fd4eda 100644
--- a/src/llm/shaders/q5k_matvec.comp
+++ b/src/llm/shaders/q5k_matvec.comp
@@ -35,8 +35,12 @@ void main()
U4 W = U4(p.w), X = U4(p.x);
F Y = F(p.y);
uint lane = gl_SubgroupInvocationID;
- uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
- uint v0 = gl_WorkGroupID.y * NV;
+ /* workgroup y: 64 rows; x: a group of NV vectors, so that the groups
+ of the same rows go out together and the weights the first reads
+ from memory the others find in the L3 */
+ uint grow = gl_WorkGroupID.y * 64u + gl_LocalInvocationID.x;
+ uint row = min(grow, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.x * NV;
uint xo[NV];
for (uint v = 0; v < NV; v++)
xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
@@ -87,7 +91,7 @@ void main()
xo[v] += 20u;
}
}
- if (gl_GlobalInvocationID.x < p.rows)
+ if (grow < p.rows)
for (uint v = 0; v < NV; v++)
if (v0 + v < p.nv)
Y.v[(v0 + v) * p.ys + row] = acc[v] - accm[v];
diff --git a/src/llm/shaders/q5k_mvd.comp b/src/llm/shaders/q5k_mvd.comp
new file mode 100644
index 0000000..1b192e4
--- /dev/null
+++ b/src/llm/shaders/q5k_mvd.comp
@@ -0,0 +1,99 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Q5_K weights times 2 to 8 Q8_K vectors with the lanes on the vectors, as
+// q4k_mvd.comp (the same layout but for the fifth bits): lane v of a
+// subgroup of 8 is vector v, a subgroup takes R rows one after the other,
+// lane i reads the block's i-th 16 bytes of nibbles and the 16 bytes of
+// fifth bits of its positions (qh, half i & 1), sets them in, and the words
+// reach every lane's dot products through subgroupBroadcast. A block is 176
+// bytes, eleven times 16: every load is aligned. The same integer sums and
+// float operations as janas_q5k_dot_ref: the CPU's result bit for bit.
+// Subgroups of 8 lanes. Workgroup x: a group of 8 vectors; y: the rows.
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_ballot : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+#extension GL_EXT_control_flow_attributes : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 8; /* unused: the lanes are the vectors */
+layout(constant_id = 1) const uint SG = 8;
+const uint R = 4; /* rows a subgroup: 32 a workgroup (gpu_impl.h MVD_ROWS) */
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+/* the uvec4 at byte lo of the 4 GB whose high word is hi: neither buffer
+ crosses a 4 GB boundary (the host checks), so an address is its low word
+ plus an offset */
+uvec4 at(uint lo, uint hi) { return U4(uvec2(lo, hi)).v[0]; }
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+
+void main()
+{
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID;
+ uint row0 = (gl_WorkGroupID.y * (64u / SG) + gl_SubgroupID) * R;
+ uint v = gl_WorkGroupID.x * SG + lane, vv = min(v, p.nv - 1u);
+ /* this lane's vector: its blocks from byte xl */
+ uint xl = p.x.x + vv * p.xs * 320u;
+ float acc[R], accm[R];
+ for (uint r = 0; r < R; r++) {
+ acc[r] = 0.0;
+ accm[r] = 0.0;
+ }
+ for (uint b = 0; b < p.nb; b++) {
+ /* the vector's block: 256 quants, the sums of 16, the scale */
+ uvec4 xq[16];
+ for (uint k = 0; k < 16u; k++)
+ xq[k] = at(xl + b * 320u + 16u * k, p.x.y);
+ uvec4 t0 = at(xl + b * 320u + 256u, p.x.y), t1 = at(xl + b * 320u + 272u, p.x.y);
+ float d8 = uintBitsToFloat(at(xl + b * 320u + 288u, p.x.y).x);
+ ivec4 ps0 = bitfieldExtract(ivec4(t0), 0, 16) + (ivec4(t0) >> 16);
+ ivec4 ps1 = bitfieldExtract(ivec4(t1), 0, 16) + (ivec4(t1) >> 16);
+ int ps[8] = int[8](ps0.x, ps0.y, ps0.z, ps0.w, ps1.x, ps1.y, ps1.z, ps1.w);
+ for (uint r = 0; r < R; r++) {
+ uint row = min(row0 + r, p.rows - 1u);
+ uint wl = p.w.x + (row * p.nb + b) * 176u;
+ uvec4 hd = at(wl, p.w.y);
+ uvec4 q = at(wl + 48u + 16u * lane, p.w.y);
+ /* bit s of qh[l]: the fifth bit of weight 32 s + l; this lane's
+ positions are 16 (lane & 1) on, its sub-blocks lane & ~1 (low
+ nibbles) and lane | 1 (high) */
+ uvec4 qh = at(wl + 16u + 16u * (lane & 1u), p.w.y);
+ uint sb = lane & ~1u;
+ uvec4 lo = (q & 0x0f0f0f0fu) | (((qh >> sb) & 0x01010101u) << 4);
+ uvec4 hi = ((q >> 4) & 0x0f0f0f0fu) | (((qh >> (sb + 1u)) & 0x01010101u) << 4);
+ uint sc03 = hd.y & 0x3f3f3f3fu, mn03 = hd.z & 0x3f3f3f3fu;
+ uint sc47 = (hd.w & 0x0f0f0f0fu) | ((hd.y >> 2) & 0x30303030u);
+ uint mn47 = ((hd.w >> 4) & 0x0f0f0f0fu) | ((hd.z >> 2) & 0x30303030u);
+ int isum = 0, imin = 0;
+ [[unroll]] for (uint c = 0; c < 4u; c++) {
+ /* sub-blocks 2c (low nibbles) and 2c + 1 (high): lanes 2c and
+ 2c + 1 hold their halves */
+ int dl = 0, dh = 0;
+ for (uint h = 0; h < 2u; h++) {
+ uvec4 l = subgroupBroadcast(lo, 2u * c + h), u = subgroupBroadcast(hi, 2u * c + h);
+ uvec4 a = xq[4u * c + h], e = xq[4u * c + 2u + h];
+ dl += dp(l.x, a.x) + dp(l.y, a.y) + dp(l.z, a.z) + dp(l.w, a.w);
+ dh += dp(u.x, e.x) + dp(u.y, e.y) + dp(u.z, e.z) + dp(u.w, e.w);
+ }
+ uint scw = c < 2u ? sc03 : sc47;
+ isum += dl * int(bitfieldExtract(scw, int(16u * (c & 1u)), 8)) +
+ dh * int(bitfieldExtract(scw, int(16u * (c & 1u) + 8u), 8));
+ }
+ for (uint s = 0; s < 8u; s++)
+ imin += int(bitfieldExtract(s < 4u ? mn03 : mn47, int(8u * (s & 3u)), 8)) * ps[s];
+ vec2 dd = unpackHalf2x16(hd.x);
+ acc[r] = fma(dd.x * d8, float(isum), acc[r]);
+ accm[r] = fma(dd.y * d8, float(imin), accm[r]);
+ }
+ }
+ if (v < p.nv)
+ for (uint r = 0; r < R; r++)
+ if (row0 + r < p.rows)
+ Y.v[v * p.ys + row0 + r] = acc[r] - accm[r];
+}
diff --git a/src/llm/shaders/q6k_matvec.comp b/src/llm/shaders/q6k_matvec.comp
index 326ccf0..9f24489 100644
--- a/src/llm/shaders/q6k_matvec.comp
+++ b/src/llm/shaders/q6k_matvec.comp
@@ -35,8 +35,12 @@ void main()
U4 X = U4(p.x);
F Y = F(p.y);
uint lane = gl_SubgroupInvocationID;
- uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
- uint v0 = gl_WorkGroupID.y * NV;
+ /* workgroup y: 64 rows; x: a group of NV vectors, so that the groups
+ of the same rows go out together and the weights the first reads
+ from memory the others find in the L3 */
+ uint grow = gl_WorkGroupID.y * 64u + gl_LocalInvocationID.x;
+ uint row = min(grow, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.x * NV;
uint xo[NV];
for (uint v = 0; v < NV; v++)
xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
@@ -111,7 +115,7 @@ void main()
xo[v] += 20u;
}
}
- if (gl_GlobalInvocationID.x < p.rows)
+ if (grow < p.rows)
for (uint v = 0; v < NV; v++)
if (v0 + v < p.nv)
Y.v[(v0 + v) * p.ys + row] = acc[v];
diff --git a/src/llm/shaders/q6k_mvd.comp b/src/llm/shaders/q6k_mvd.comp
new file mode 100644
index 0000000..6d76ad0
--- /dev/null
+++ b/src/llm/shaders/q6k_mvd.comp
@@ -0,0 +1,121 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// Q6_K weights times 2 to 8 Q8_K vectors with the lanes on the vectors, as
+// q4k_mvd.comp: lane v of a subgroup of 8 is vector v, a subgroup takes R
+// rows one after the other, each lane keeps its vector's block of
+// activations in registers. A Q6_K block is 210 bytes (ql 128, qh 64,
+// scales 16, d 2), so a block starts on an even byte, and on a word or two
+// bytes past one: lane j = 4n + 2h + kk loads the five words around its 16
+// bytes of ql (positions 16kk .. 16kk + 15 of half n, quarters h and h + 2)
+// and the five around its 16 bytes of qh, and shifts them by 16 bits where
+// the block starts two bytes past a word; the bytes of a load all lie in
+// one block, so a load of the subgroup touches the block's few lines only. Its 32 weights
+// (sub-blocks 8n + 2h + kk and that + 4) reach every lane's dot products as
+// scalar operands, already less 32 (-32 .. 31, made a byte at a time). The
+// integer sums as the CPU's (janas_q6k_dot_ref): scale x ((q - 32) x a),
+// then one fma with d x d8; bit for bit. The scales are taken plus 128
+// (their sign bit flipped: 0 .. 255, which the GPU multiplies in one
+// instruction, a signed one in three), and 128 x the sum of the dot
+// products comes off at the end. Subgroups of 8 lanes; workgroup x: a
+// group of 8 vectors, y: the rows (32 a workgroup, gpu_impl.h MVD_ROWS).
+#extension GL_EXT_integer_dot_product : require
+#extension GL_KHR_shader_subgroup_basic : require
+#extension GL_KHR_shader_subgroup_ballot : require
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+#extension GL_EXT_control_flow_attributes : require
+
+layout(local_size_x = 64) in;
+layout(constant_id = 0) const uint NV = 8; /* unused: the lanes are the vectors */
+layout(constant_id = 1) const uint SG = 8;
+const uint R = 4; /* rows a subgroup */
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer F { float v[]; };
+layout(push_constant) uniform P { uvec2 w, x, y; uint rows, nb, nv, xs, ys; } p;
+
+/* the uvec4 at byte lo of the 4 GB whose high word is hi: neither buffer
+ crosses a 4 GB boundary (the host checks) */
+uvec4 at(uint lo, uint hi) { return U4(uvec2(lo, hi)).v[0]; }
+int dp(uint a, uint b) { return dotPacked4x8EXT(int(a), int(b)); }
+
+/* The 16 bytes at byte c (c even): the five words from the word below c,
+ shifted by 16 bits where c is two bytes past a word (m all ones), with no
+ branch. */
+uvec4 bytes16(uint c, uint hi)
+{
+ U1 B = U1(uvec2(c & ~3u, hi));
+ uvec4 w = uvec4(B.v[0], B.v[1], B.v[2], B.v[3]);
+ uvec4 n = uvec4(w.yzw, B.v[4]);
+ uint m = 0u - ((c >> 1) & 1u);
+ return (w & ~m) | (((w >> 16) | (n << 16)) & m);
+}
+
+/* Four weights 0 .. 63 a word, less 32: -32 .. 31 as bytes (no borrow from
+ one byte to the next: each is 128 more while the 32 is taken). */
+uint less32(uint q) { return ((q | 0x80808080u) - 0x20202020u) ^ 0x80808080u; }
+
+void main()
+{
+ F Y = F(p.y);
+ uint lane = gl_SubgroupInvocationID;
+ uint row0 = (gl_WorkGroupID.y * (64u / SG) + gl_SubgroupID) * R;
+ uint v = gl_WorkGroupID.x * SG + lane, vv = min(v, p.nv - 1u);
+ uint xl = p.x.x + vv * p.xs * 320u;
+ /* this lane's part of a block: half n, quarters h and h + 2, positions
+ 16kk .. 16kk + 15; its bytes of ql and of qh */
+ uint n = lane >> 2, h = (lane >> 1) & 1u, kk = lane & 1u;
+ uint oql = 64u * n + 32u * h + 16u * kk, oqh = 128u + 32u * n + 16u * kk;
+ float acc[R];
+ for (uint r = 0; r < R; r++)
+ acc[r] = 0.0;
+ for (uint b = 0; b < p.nb; b++) {
+ /* the vector's block: 256 quants, the sums of 16, the scale */
+ uvec4 xq[16];
+ for (uint k = 0; k < 16u; k++)
+ xq[k] = at(xl + b * 320u + 16u * k, p.x.y);
+ float d8 = uintBitsToFloat(at(xl + b * 320u + 288u, p.x.y).x);
+ for (uint r = 0; r < R; r++) {
+ uint row = min(row0 + r, p.rows - 1u);
+ uint c0 = p.w.x + (row * p.nb + b) * 210u;
+ uvec4 ql = bytes16(c0 + oql, p.w.y), qh = bytes16(c0 + oqh, p.w.y);
+ /* the 16 scales and d: bytes 192 .. 209, every lane the same */
+ uvec4 scv = bytes16(c0 + 192u, p.w.y);
+ uint dw = U1(uvec2((c0 + 208u) & ~3u, p.w.y)).v[0] >> (8u * (c0 & 2u));
+ /* the scales plus 128 */
+ uint sc[4] = uint[4](scv.x ^ 0x80808080u, scv.y ^ 0x80808080u, scv.z ^ 0x80808080u,
+ scv.w ^ 0x80808080u);
+ /* this lane's 32 weights, less 32: quarter h (low nibbles) and h + 2 */
+ uvec4 wl, wh;
+ for (uint k = 0; k < 4u; k++) {
+ wl[k] = less32((ql[k] & 0x0f0f0f0fu) | ((qh[k] << (4u - 2u * h)) & 0x30303030u));
+ wh[k] = less32(((ql[k] >> 4) & 0x0f0f0f0fu) | ((qh[k] >> (2u * h)) & 0x30303030u));
+ }
+ int isum = 0, dsum = 0;
+ [[unroll]] for (uint j = 0; j < 8u; j++) {
+ /* lane j's sub-blocks g (quarter h) and g + 4 (quarter h + 2) */
+ uint gn = j >> 2, gh = (j >> 1) & 1u, gk = j & 1u;
+ uint g = 8u * gn + 2u * gh + gk;
+ uvec4 l = subgroupBroadcast(wl, j), u = subgroupBroadcast(wh, j);
+ uvec4 a0 = xq[g], a1 = xq[g + 4u];
+ /* chains, so that each sum is the next dot product's
+ accumulator */
+ int d0 = dp(l.w, a0.w) + (dp(l.z, a0.z) + (dp(l.y, a0.y) + dp(l.x, a0.x)));
+ int d1 = dp(u.w, a1.w) + (dp(u.z, a1.z) + (dp(u.y, a1.y) + dp(u.x, a1.x)));
+ uint c0s = bitfieldExtract(sc[g >> 2], int(8u * (g & 3u)), 8);
+ uint c1s = bitfieldExtract(sc[(g + 4u) >> 2], int(8u * ((g + 4u) & 3u)), 8);
+ isum += int(c0s) * d0 + int(c1s) * d1;
+ dsum += d0 + d1;
+ }
+ isum -= dsum << 7;
+ float d = unpackHalf2x16(dw & 0xffffu).x;
+ acc[r] = fma(d * d8, float(isum), acc[r]);
+ }
+ }
+ if (v < p.nv)
+ for (uint r = 0; r < R; r++)
+ if (row0 + r < p.rows)
+ Y.v[v * p.ys + row0 + r] = acc[r];
+}
diff --git a/src/llm/shaders/q6kp_matvec.comp b/src/llm/shaders/q6kp_matvec.comp
index 04722b2..79e4eb4 100644
--- a/src/llm/shaders/q6kp_matvec.comp
+++ b/src/llm/shaders/q6kp_matvec.comp
@@ -41,8 +41,12 @@ void main()
U4 X = U4(p.x);
F Y = F(p.y);
uint lane = gl_SubgroupInvocationID;
- uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
- uint v0 = gl_WorkGroupID.y * NV;
+ /* workgroup y: 64 rows; x: a group of NV vectors, so that the groups
+ of the same rows go out together and the weights the first reads
+ from memory the others find in the L3 */
+ uint grow = gl_WorkGroupID.y * 64u + gl_LocalInvocationID.x;
+ uint row = min(grow, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.x * NV;
uint xo[NV];
for (uint v = 0; v < NV; v++)
xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
@@ -126,7 +130,7 @@ void main()
xo[v] += 20u;
}
}
- if (gl_GlobalInvocationID.x < p.rows)
+ if (grow < p.rows)
for (uint v = 0; v < NV; v++)
if (v0 + v < p.nv)
Y.v[(v0 + v) * p.ys + row] = acc[v];
diff --git a/src/llm/shaders/q8_0_matvec.comp b/src/llm/shaders/q8_0_matvec.comp
index 78f8b31..abfcb67 100644
--- a/src/llm/shaders/q8_0_matvec.comp
+++ b/src/llm/shaders/q8_0_matvec.comp
@@ -39,8 +39,12 @@ void main()
U4 X = U4(p.x);
F Y = F(p.y);
uint lane = gl_SubgroupInvocationID;
- uint row = min(gl_GlobalInvocationID.x, p.rows - 1u);
- uint v0 = gl_WorkGroupID.y * NV;
+ /* workgroup y: 64 rows; x: a group of NV vectors, so that the groups
+ of the same rows go out together and the weights the first reads
+ from memory the others find in the L3 */
+ uint grow = gl_WorkGroupID.y * 64u + gl_LocalInvocationID.x;
+ uint row = min(grow, p.rows - 1u);
+ uint v0 = gl_WorkGroupID.x * NV;
uint xo[NV];
for (uint v = 0; v < NV; v++)
xo[v] = min(v0 + v, p.nv - 1u) * p.xs * 20u;
@@ -83,7 +87,7 @@ void main()
xo[v] += 20u;
}
}
- if (gl_GlobalInvocationID.x < p.rows)
+ if (grow < p.rows)
for (uint v = 0; v < NV; v++)
if (v0 + v < p.nv)
Y.v[(v0 + v) * p.ys + row] =
diff --git a/src/llm/shaders/silu_mul.comp b/src/llm/shaders/silu_mul.comp
index 82ada65..2c1a123 100644
--- a/src/llm/shaders/silu_mul.comp
+++ b/src/llm/shaders/silu_mul.comp
@@ -1,9 +1,9 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2026 Maurizio Cammalleri */
#version 450
-// h = SiLU(gate) * up as floats, n values (gpu_token.c: a shared expert
-// whose down matrix is in blocks of 32, quantized afterwards by
-// norm_quant.comp into both layouts). The GPU's exp: NOT bit for bit with
+// h = SiLU(gate) * up as floats, n values (gpu_token_rec.c: a dense
+// layer's or a shared expert's feed-forward whose down matrix is in blocks
+// of 32, quantized afterwards by norm_quant.comp into both layouts). The GPU's exp: NOT bit for bit with
// the CPU.
#extension GL_EXT_buffer_reference : require
#extension GL_EXT_buffer_reference_uvec2 : require
diff --git a/src/server/store.c b/src/server/store.c
index 502e669..e141378 100644
--- a/src/server/store.c
+++ b/src/server/store.c
@@ -176,7 +176,8 @@ struct srv_store *srv_store_open(size_t cap, const char *dir, char *err,
}
struct loaded l = {0};
int skipped = srv_disk_load(st->disk, take, &l);
- qsort(l.e, l.n, sizeof(*l.e), by_seq);
+ if (l.n) /* none: l.e is NULL, which qsort may not be given */
+ qsort(l.e, l.n, sizeof(*l.e), by_seq);
for (size_t i = 0; i < l.n; i++) {
struct entry *e = l.e[i];
e->prev = st->tail;
diff --git a/tests/bench_gemm.c b/tests/bench_gemm.c
index 1bbd9f6..6ddc905 100644
--- a/tests/bench_gemm.c
+++ b/tests/bench_gemm.c
@@ -8,15 +8,23 @@
* all of them, so beyond a few tokens the product is bound by arithmetic and
* the figure of merit is multiply-accumulates per second.
*
- * Usage: bench_gemm [rows cols q4k|q6k|q3k|q6kp1|q6kp2|q6kp3 threads [gpu]]
+ * Usage: bench_gemm [rows cols
+ * q4k|q5k|q6k|q3k|q80|iq4xs|iq3s|iq4nl|q6kp1|q6kp2|q6kp3 threads [gpu|gpufew]]
* q6kpL is Q6_K in bit planes with L of the three planes in memory.
* Defaults: 12288 x 2048 Q4_K (Qwen3-Next ssm_in), 12 threads on CPUs 0-11.
* gpu: the products of a prompt's blocks on the GPU (the fast prompt's
* tiled shaders, *_mmq.comp), 64 to 512 vectors, the weights imported.
+ * BENCH_MEM=huge2m puts the weights on 2 MB pages before the GPU imports
+ * them, as the engine does; BENCH_MEM=driver in memory allocated by the
+ * GPU's driver (default: pages of 4 KB).
*/
+#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#if defined(__linux__)
+#include <sys/mman.h>
+#endif
#include <time.h>
#include "common/pool.h"
@@ -31,6 +39,47 @@ static double now(void)
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
+#ifndef MADV_COLLAPSE
+#define MADV_COLLAPSE 25
+#endif
+
+/* where the weights go (BENCH_MEM): 0 pages of 4 KB, 1 the GPU driver's
+ memory, 2 pages of 2 MB */
+static int mem_kind;
+static struct janas_gpu *gpu;
+
+/* bytes of weights rounded up to whole pages of their kind */
+static size_t whole(size_t bytes)
+{
+ size_t al = mem_kind == 2 ? (size_t)2 << 20 : 4096;
+ return (bytes + al - 1) / al * al;
+}
+
+static uint8_t *weights(size_t bytes)
+{
+ if (mem_kind == 1)
+ return janas_gpu_alloc(gpu, bytes);
+ return aligned_alloc(mem_kind == 2 ? (size_t)2 << 20 : 4096, bytes);
+}
+
+/* Written weights collapsed into 2 MB pages, then imported (pinned): the
+ engine's way (janas_m_huge_pages); the driver's memory needs no import. */
+static int to_gpu(uint8_t *p, size_t bytes)
+{
+#if defined(__linux__)
+ const size_t piece = (size_t)32 << 20;
+ if (mem_kind == 2)
+ for (size_t at = 0; at < bytes; at += piece)
+ madvise(p + at, bytes - at < piece ? bytes - at : piece,
+ MADV_COLLAPSE);
+#endif
+ if (mem_kind == 1) {
+ janas_gpu_flush(gpu, p, bytes);
+ return 0;
+ }
+ return janas_gpu_import(gpu, p, bytes);
+}
+
int main(int argc, char **argv)
{
size_t rows = argc > 1 ? (size_t)atol(argv[1]) : 12288;
@@ -42,6 +91,16 @@ int main(int argc, char **argv)
type = JANAS_Q6_K;
else if (!strcmp(kind, "q3k"))
type = JANAS_Q3_K;
+ else if (!strcmp(kind, "q5k"))
+ type = JANAS_Q5_K;
+ else if (!strcmp(kind, "q80"))
+ type = JANAS_Q8_0;
+ else if (!strcmp(kind, "iq4xs"))
+ type = JANAS_IQ4_XS;
+ else if (!strcmp(kind, "iq3s"))
+ type = JANAS_IQ3_S;
+ else if (!strcmp(kind, "iq4nl"))
+ type = JANAS_IQ4_NL;
else if (!strncmp(kind, "q6kp", 4)) {
type = JANAS_Q6_K_P;
level = kind[4] ? kind[4] - '0' : 3;
@@ -49,21 +108,36 @@ int main(int argc, char **argv)
return 2;
}
int threads = argc > 4 ? atoi(argv[4]) : 12;
- int on_gpu = argc > 5 && !strcmp(argv[5], "gpu");
+ /* gpufew: the products of a few vectors on the GPU (a chain of drafts) */
+ int few = argc > 5 && !strcmp(argv[5], "gpufew");
+ int on_gpu = argc > 5 && (!strcmp(argv[5], "gpu") || few);
int cpus[256];
for (int i = 0; i < threads && i < 256; i++)
cpus[i] = i;
+ const char *bm = getenv("BENCH_MEM");
+ mem_kind = !bm ? 0
+ : !strcmp(bm, "driver") ? 1
+ : !strcmp(bm, "huge2m") ? 2
+ : 0;
+ if (on_gpu || mem_kind == 1) {
+ char err[200];
+ gpu = janas_gpu_create(err, sizeof(err));
+ if (!gpu) {
+ fprintf(stderr, "bench_gemm: no GPU: %s\n", err);
+ return 1;
+ }
+ }
struct janas_pool *pool = janas_pool_create(threads, cpus);
janas_pin_current_thread(0);
size_t nb = cols / JANAS_QK, bsz = janas_qtype_block_size(type);
size_t nvmax = on_gpu ? 512 : 64;
- /* page-sized and whole pages: what the GPU imports */
- size_t wbytes = (rows * nb * bsz + 4 + 4095) / 4096 * 4096;
- uint8_t *w = aligned_alloc(4096, wbytes);
- size_t plane_bytes = (rows * nb * JANAS_Q6KP_PLANE + 4095) / 4096 * 4096;
+ /* aligned and whole pages: what the GPU imports */
+ size_t wbytes = whole(rows * nb * bsz + 4);
+ uint8_t *w = weights(wbytes);
+ size_t plane_bytes = whole(rows * nb * JANAS_Q6KP_PLANE);
uint8_t *pl[2] = {NULL, NULL};
for (int i = 0; i < level - 1; i++) {
- pl[i] = aligned_alloc(4096, plane_bytes);
+ pl[i] = weights(plane_bytes);
if (!pl[i])
return 1;
for (size_t j = 0; j < plane_bytes; j++)
@@ -72,18 +146,33 @@ int main(int argc, char **argv)
struct janas_block_q8k *x = malloc(nvmax * nb * sizeof(*x));
float *xf = malloc(cols * sizeof(float));
float *y = malloc(nvmax * rows * sizeof(float));
- if (!pool || !w || !x || !xf || !y)
+ float *yc = malloc(nvmax * rows * sizeof(float));
+ if (!pool || !w || !x || !xf || !y || !yc)
return 1;
srand(1);
for (size_t i = 0; i < wbytes; i++)
w[i] = (uint8_t)rand();
- for (size_t b = 0; b < rows * nb; b++) {
- if (type == JANAS_Q6_K_P) {
+ /* blocks of 32 weights: eight to a block of 256 */
+ for (size_t b = 0;
+ b < rows * nb * (type == JANAS_IQ4_NL || type == JANAS_Q8_0 ? 8 : 1);
+ b++) {
+ if (type == JANAS_Q8_0) {
+ ((struct janas_block_q8_0 *)w)[b].d = janas_fp32_to_fp16(0.001f);
+ } else if (type == JANAS_Q5_K) {
+ ((struct janas_block_q5k *)w)[b].d = janas_fp32_to_fp16(0.001f);
+ ((struct janas_block_q5k *)w)[b].dmin = janas_fp32_to_fp16(0.0005f);
+ } else if (type == JANAS_IQ4_NL) {
+ ((struct janas_block_iq4nl *)w)[b].d = janas_fp32_to_fp16(0.001f);
+ } else if (type == JANAS_IQ3_S) {
+ ((struct janas_block_iq3s *)w)[b].d = janas_fp32_to_fp16(0.001f);
+ } else if (type == JANAS_Q6_K_P) {
((struct janas_block_q6kp *)w)[b].d = janas_fp32_to_fp16(0.001f);
} else if (type == JANAS_Q6_K) {
((struct janas_block_q6k *)w)[b].d = janas_fp32_to_fp16(0.001f);
} else if (type == JANAS_Q3_K) {
((struct janas_block_q3k *)w)[b].d = janas_fp32_to_fp16(0.001f);
+ } else if (type == JANAS_IQ4_XS) {
+ ((struct janas_block_iq4xs *)w)[b].d = janas_fp32_to_fp16(0.001f);
} else {
((struct janas_block_q4k *)w)[b].d = janas_fp32_to_fp16(0.001f);
((struct janas_block_q4k *)w)[b].dmin = janas_fp32_to_fp16(0.0005f);
@@ -94,28 +183,30 @@ int main(int argc, char **argv)
xf[i] = (float)((double)rand() / RAND_MAX) - 0.5f;
janas_q8k_quantize(xf, x + v * nb, cols);
}
- double mb =
- (rows * nb * bsz + (size_t)(level ? level - 1 : 0) * plane_bytes) / 1e6;
- struct janas_gpu *gpu = NULL;
- if (on_gpu) {
- char err[200];
- gpu = janas_gpu_create(err, sizeof(err));
- if (!gpu || janas_gpu_import(gpu, w, wbytes) != 0 ||
- (pl[0] && janas_gpu_import(gpu, pl[0], plane_bytes) != 0) ||
- (pl[1] && janas_gpu_import(gpu, pl[1], plane_bytes) != 0)) {
- fprintf(stderr, "bench_gemm: no GPU: %s\n", gpu ? "import" : err);
- return 1;
- }
+ double mb = (rows * nb * bsz + (size_t)(level ? level - 1 : 0) * rows * nb *
+ JANAS_Q6KP_PLANE) /
+ 1e6;
+ if (on_gpu &&
+ (to_gpu(w, wbytes) != 0 || (pl[0] && to_gpu(pl[0], plane_bytes) != 0) ||
+ (pl[1] && to_gpu(pl[1], plane_bytes) != 0))) {
+ fprintf(stderr, "bench_gemm: the GPU cannot read the weights\n");
+ return 1;
}
- printf("%s %zu x %zu (%.1f MB), %s\n", kind, rows, cols, mb,
- on_gpu ? janas_gpu_name(gpu) : "CPU");
+ printf("%s %zu x %zu (%.1f MB), %s, weights in %s\n", kind, rows, cols, mb,
+ on_gpu ? janas_gpu_name(gpu) : "CPU",
+ mem_kind == 1 ? "the GPU driver's memory"
+ : mem_kind == 2 ? "2 MB pages"
+ : "4 KB pages");
if (!on_gpu)
printf("%d threads\n", threads);
size_t nvs_cpu[] = {1, 2, 4, 8, 16, 32, 64},
- nvs_gpu[] = {64, 128, 256, 512};
- size_t *nvs = on_gpu ? nvs_gpu : nvs_cpu,
- n_nvs = on_gpu ? sizeof(nvs_gpu) / sizeof(*nvs_gpu)
- : sizeof(nvs_cpu) / sizeof(*nvs_cpu);
+ nvs_gpu[] = {64, 128, 256, 512}, nvs_few[] = {1, 2, 4, 8, 9, 16};
+ size_t *nvs = few ? nvs_few
+ : on_gpu ? nvs_gpu
+ : nvs_cpu,
+ n_nvs = few ? sizeof(nvs_few) / sizeof(*nvs_few)
+ : on_gpu ? sizeof(nvs_gpu) / sizeof(*nvs_gpu)
+ : sizeof(nvs_cpu) / sizeof(*nvs_cpu);
for (size_t k = 0; k < n_nvs; k++) {
size_t nv = nvs[k];
struct janas_matvec_task t = {.type = type,
@@ -148,14 +239,33 @@ int main(int argc, char **argv)
"%5.1f GB/s, sum %.17g\n",
nv, dt * 1e3, dt * 1e3 / nv, rows * cols * nv / dt / 1e9,
mb / 1e3 / dt, sum);
+ if (on_gpu) {
+ /* the GPU's outputs against the CPU's, one by one: the largest
+ difference over the largest output */
+ struct janas_matvec_task tc = t;
+ tc.y = yc;
+ janas_matvec_q4k_group(pool, &tc, 1);
+ double dmax = 0, ymax = 0;
+ for (size_t i = 0; i < nv * rows; i++) {
+ double d = fabs((double)y[i] - yc[i]);
+ dmax = d > dmax ? d : dmax;
+ ymax = fabs(yc[i]) > ymax ? fabs(yc[i]) : ymax;
+ }
+ printf(" against the CPU: largest difference %.3g, %.3g of "
+ "the largest output\n",
+ dmax, ymax > 0 ? dmax / ymax : 0);
+ }
}
- janas_gpu_destroy(gpu);
+ janas_gpu_destroy(gpu); /* the driver's memory with it */
janas_pool_destroy(pool);
- free(w);
- free(pl[0]);
- free(pl[1]);
+ if (mem_kind != 1) {
+ free(w);
+ free(pl[0]);
+ free(pl[1]);
+ }
free(x);
free(xf);
free(y);
+ free(yc);
return 0;
}
diff --git a/tests/bench_kernels.c b/tests/bench_kernels.c
index 02623e6..d61aa67 100644
--- a/tests/bench_kernels.c
+++ b/tests/bench_kernels.c
@@ -10,18 +10,27 @@
* to convert their scale through a function call (6 Oct 2026).
*
* Usage: bench_kernels [MiB [threads [first_cpu]]]
+ * BENCH_MEM=driver puts the weights in memory allocated by the GPU's driver
+ * (the memory a GPU sharing the host's reads fastest), BENCH_MEM=huge2m in
+ * ordinary memory aligned to 2 MB and collapsed into huge pages: the CPU's
+ * speed on each, against malloc's (13 Oct 2026).
* Defaults: 256 MiB of weights per type, 12 threads on CPUs 0-11; the
* single core is first_cpu (default 2).
* The weights are random bytes below 0x7c, so that every fp16 scale is a
* finite number; the speed of a kernel does not depend on the values.
*/
+#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#if defined(__linux__)
+#include <sys/mman.h>
+#endif
#include <time.h>
#include "common/pool.h"
#include "llm/matvec.h"
+#include "llm/gpu.h"
#include "llm/quant.h"
static double now(void)
@@ -31,6 +40,25 @@ static double now(void)
return ts.tv_sec + ts.tv_nsec * 1e-9;
}
+#ifndef MADV_COLLAPSE
+#define MADV_COLLAPSE 25
+#endif
+
+/* where the weights go (BENCH_MEM): malloc, the GPU driver, 2 MB pages */
+static struct janas_gpu *gpu;
+static int mem_kind; /* 0 malloc, 1 driver, 2 huge2m */
+
+static unsigned char *weights(size_t bytes)
+{
+ if (mem_kind == 1)
+ return janas_gpu_alloc(gpu, bytes);
+ if (mem_kind == 2) {
+ size_t al = (size_t)2 << 20;
+ return aligned_alloc(al, (bytes + al - 1) / al * al);
+ }
+ return malloc(bytes);
+}
+
static const struct {
const char *name;
int type;
@@ -65,6 +93,19 @@ int main(int argc, char **argv)
fprintf(stderr, "usage: bench_kernels [MiB [threads [first_cpu]]]\n");
return 2;
}
+ const char *bm = getenv("BENCH_MEM");
+ mem_kind = !bm ? 0
+ : !strcmp(bm, "driver") ? 1
+ : !strcmp(bm, "huge2m") ? 2
+ : 0;
+ if (mem_kind == 1) {
+ char err[200];
+ gpu = janas_gpu_create(err, sizeof err);
+ if (!gpu) {
+ fprintf(stderr, "bench_kernels: no GPU: %s\n", err);
+ return 1;
+ }
+ }
int cpus[256];
for (int i = 0; i < nt; i++)
cpus[i] = i;
@@ -83,14 +124,17 @@ int main(int argc, char **argv)
for (int k = 0; k < 8; k++)
janas_q8k_quantize(v + k * cols, x + k * nb, cols);
printf("GB/s of weights, %zu MiB a type, 2048 columns; 1 core (CPU %d) "
- "and %d threads\n",
- mib, one, nt);
+ "and %d threads; weights in %s\n",
+ mib, one, nt,
+ mem_kind == 1 ? "the GPU driver's memory"
+ : mem_kind == 2 ? "2 MB pages"
+ : "malloc's memory");
printf("%-7s %8s %8s %8s %8s | %8s %8s %8s %8s\n", "type", "1x1", "1x2",
"1x4", "1x8", "Nx1", "Nx2", "Nx4", "Nx8");
for (size_t k = 0; k < sizeof TYPES / sizeof *TYPES; k++) {
size_t bs = janas_qtype_block_size(TYPES[k].type);
size_t rows = (mib << 20) / (nb * bs), bytes = rows * nb * bs;
- unsigned char *w = malloc(bytes);
+ unsigned char *w = weights(bytes);
float *y = malloc(8 * rows * sizeof(float));
if (!w || !y) {
fprintf(stderr, "bench_kernels: out of memory\n");
@@ -98,6 +142,10 @@ int main(int argc, char **argv)
}
for (size_t i = 0; i < bytes; i++)
w[i] = (unsigned char)(rand() % 0x7c);
+#if defined(__linux__)
+ if (mem_kind == 2)
+ madvise(w, bytes, MADV_COLLAPSE);
+#endif
printf("%-7s", TYPES[k].name);
for (int p = 0; p < 2; p++) {
for (size_t i = 0; i < 4; i++) {
@@ -116,12 +164,14 @@ int main(int argc, char **argv)
printf(p ? "\n" : " |");
}
fflush(stdout);
- free(w);
+ if (mem_kind != 1)
+ free(w); /* the driver's goes with the GPU */
free(y);
}
free(x);
free(v);
janas_pool_destroy(single);
janas_pool_destroy(many);
+ janas_gpu_destroy(gpu);
return 0;
}
diff --git a/tests/llm_eval.c b/tests/llm_eval.c
index 437b340..e45deed 100644
--- a/tests/llm_eval.c
+++ b/tests/llm_eval.c
@@ -5,9 +5,14 @@
* the logits with a reference (llama.cpp dump: float32 x n_tokens x n_vocab).
*
* Usage: llm_eval <model.jns> <tokens.int32> [reference.logits]
- * [cache_MiB] [compute_cpus] [io_cpus] [block=B] [dump=F]
+ * [cache_MiB] [compute_cpus] [io_cpus] [block=B] [reject=R]
+ * [dump=F]
* With block=B the tokens are also run in blocks of B (the prefill path) and
* the logits compared with the token-by-token ones: they must be identical.
+ * With reject=R (R < B) each block but the last keeps only its first B - R
+ * tokens and the next starts after them, as when the last R tokens of a
+ * chain of drafts are rejected: a recurrent model then replays the kept
+ * tokens of its log on the state before the block.
* With dump=F the logits are written to F in the reference format.
* Reports, per position, whether the most likely token agrees, the largest and
* mean absolute logit difference, and the time per token.
@@ -143,10 +148,17 @@ int main(int argc, char **argv)
"%.1f token/s), cold cache: %.1f%% of experts from RAM\n",
n, dt, dt / n * 1e3, t2 / (n - n / 2) * 1e3, (n - n / 2) / t2,
100.0 * st.hits / (st.requests ? st.requests : 1));
- int block = 0;
- for (int i = 7; i < argc; i++)
+ int block = 0, reject = 0;
+ for (int i = 7; i < argc; i++) {
if (strncmp(argv[i], "block=", 6) == 0)
block = atoi(argv[i] + 6);
+ if (strncmp(argv[i], "reject=", 7) == 0)
+ reject = atoi(argv[i] + 7);
+ }
+ if (reject < 0 || (block > 0 && reject >= block)) {
+ fprintf(stderr, "reject=R wants 0 <= R < B\n");
+ return 2;
+ }
if (block > 0) {
/* token by token, keeping every logit row, then the same in blocks */
size_t nn = n < 256 ? n : 256;
@@ -157,8 +169,8 @@ int main(int argc, char **argv)
double pb0[JANAS_PH_COUNT], pb1[JANAS_PH_COUNT];
janas_llm_model_phases(m, pb0);
double tb = now(), maxd = 0, sumd = 0, rsum = 0;
- size_t same = 0, top = 0, rtop = 0;
- for (size_t p0 = 0; p0 < nn; p0 += (size_t)block) {
+ size_t same = 0, top = 0, rtop = 0, passes = 0;
+ for (size_t p0 = 0, kept; p0 < nn; p0 += kept) {
uint32_t b =
(uint32_t)(nn - p0 < (size_t)block ? nn - p0 : (size_t)block);
if (janas_llm_model_forward(m, tokens + p0, b, (uint32_t)p0, blk,
@@ -166,7 +178,11 @@ int main(int argc, char **argv)
fprintf(stderr, "block forward failed at %zu\n", p0);
return 1;
}
- for (uint32_t j = 0; j < b; j++) {
+ passes++;
+ /* the last block keeps all its tokens, the others b - reject:
+ the positions after them come again in the next block */
+ kept = p0 + b >= nn ? b : b - (uint32_t)reject;
+ for (uint32_t j = 0; j < kept; j++) {
const float *a = seq + (p0 + j) * nv, *c = blk + (size_t)j * nv;
int eq = 1;
for (uint32_t i = 0; i < nv; i++) {
@@ -192,6 +208,10 @@ int main(int argc, char **argv)
double tbs = now() - tb;
janas_llm_model_phases(m, pb1);
print_phases("blocks", pb0, pb1, nn);
+ if (reject)
+ printf("blocks of %d keeping %d: %zu passes, the kept tokens "
+ "replayed by the next\n",
+ block, block - reject, passes);
printf(
"blocks of %d: %zu/%zu positions bit-identical to token by token, "
"max |diff| %g; %.1f ms/token in blocks (%.1f token/s)\n",
diff --git a/tests/llm_gen.c b/tests/llm_gen.c
index 44c5cb0..d152730 100644
--- a/tests/llm_gen.c
+++ b/tests/llm_gen.c
@@ -66,6 +66,37 @@ static void report(const char *name, const struct janas_gen_stats *s)
printf("\n");
}
+/* By position in the chain: how often the draft there was accepted, of all
+ verified there and of those whose predecessor was accepted; and by the
+ tokens in a pass, its mean time against a pass of one in the run without
+ drafts (plain). */
+static void report_chain(const struct janas_gen_stats *s,
+ const struct janas_gen_stats *plain)
+{
+ if (!s->pos_tried[0])
+ return;
+ printf("chain, position: accepted/verified (%%, %% given the one "
+ "before):");
+ for (int i = 0; i < JANAS_GEN_MAX_K && s->pos_tried[i]; i++) {
+ uint32_t before = i ? s->pos_won[i - 1] : s->pos_tried[0];
+ printf(" %d: %u/%u (%.0f%%, %.0f%%)", i + 1, s->pos_won[i],
+ s->pos_tried[i], 100.0 * s->pos_won[i] / s->pos_tried[i],
+ before ? 100.0 * s->pos_won[i] / before : 0.0);
+ }
+ printf("\n");
+ double one = plain->pass_count[1]
+ ? plain->pass_seconds[1] / plain->pass_count[1]
+ : 0;
+ printf("pass, tokens: passes, ms (x a pass of one):");
+ for (int n = 1; n < JANAS_GEN_MAX_K + 2; n++)
+ if (s->pass_count[n]) {
+ double t = s->pass_seconds[n] / s->pass_count[n];
+ printf(" %d: %u, %.1f (%.2f)", n, s->pass_count[n], t * 1e3,
+ one > 0 ? t / one : 0.0);
+ }
+ printf("\n");
+}
+
int main(int argc, char **argv)
{
if (argc < 6) {
@@ -214,8 +245,8 @@ int main(int argc, char **argv)
printf(" %d", a[i]);
printf("\n");
printf("first tokens:");
- for (int i = 0; i < 12 && i < na; i++)
- printf(" %d", a[i]);
+ for (int i = 0; i < 12 && i < nb; i++)
+ printf(" %d", b[i]);
printf("\n");
report("normal", &sa);
report(draft ? "draft"
@@ -223,11 +254,19 @@ int main(int argc, char **argv)
: (on.spec_auto ? "lookup+a" : "lookup"),
&sb);
report_calibration(&sb);
+ report_chain(&sb, &sa);
int same = na == nb && memcmp(a, b, (size_t)na * sizeof(int32_t)) == 0;
- printf("tokens identical: %s (%d and %d); speed-up %.2fx\n",
- same ? "yes" : "NO", na, nb,
- (sb.new_tokens / sb.decode_seconds) /
- (sa.new_tokens / sa.decode_seconds));
+ /* where they part: on the CPU the drafts never change the text, on
+ the GPU its sums in another order may (its quality is measured
+ against a reference instead, llm_eval) */
+ int first = 0;
+ while (first < na && first < nb && a[first] == b[first])
+ first++;
+ printf("tokens identical: %s (%d and %d", same ? "yes" : "NO", na, nb);
+ if (!same)
+ printf(", the first difference at token %d", first);
+ printf("); speed-up %.2fx\n", (sb.new_tokens / sb.decode_seconds) /
+ (sa.new_tokens / sa.decode_seconds));
free(a);
free(b);
char tune[512];