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.
C avx2ccpu-inferenceggufinference-enginelinuxllmlocal-llmmixture-of-expertsmoenvmequantizationqwen3simdspeculative-decodingvulkan
Release 2026-10-21: Intel's NPU reads the prompts - Qwen3.5-2B 729 against 477 tok/s, Gemma-4-E2B 508 against 196, Qwen3-4B 333 against 201 (the graphs written by Janas-LLM in OpenVINO's IR, run through Intel's Level Zero driver, Linux); a mixture's Q3_K experts on the GPU, the 3-bit Qwen3-30B-A3B reading at 119.5 tok/s against 98.5 (llama.cpp 114.3), and the expert cache imported in regions below 4 GiB; --prompt-on, --drafts-on and --reply-on choose what runs where; the README's figures of 21 October, faster than llama.cpp on every model compared; the Ana-Net and Janet probes, not final
camauri0821b7a54365
diff --git a/ChangeLog.md b/ChangeLog.mdindex fc90a3e..bf016e0 100644--- a/ChangeLog.md+++ b/ChangeLog.md@@ -2,9 +2,26 @@> Curated, user-facing summary of completed work, newest first.+## [2026-10-21] - Intel's NPU reads the prompts++- **The NPU of Intel's Core Ultra processors reads a prompt's blocks** (Linux; tried on the first generation's, Meteor Lake, "Intel AI Boost"). Janas-LLM writes the NPU's graphs itself, in OpenVINO's IR format, and opens Intel's Level Zero driver when a model opens: nothing is linked against it, and without it nothing changes. The weights it takes are copied in eight bits with a scale for each row and computed in sixteen-bit floats, the norms in 32. A dense model whose layers fit in the NPU's memory, nine in ten at least, goes to it layer by layer, whole - Qwen3, Qwen3.5 and Gemma 4's dense models - each block of the prompt in two halves, the NPU computing a layer on one while the CPU computes the attention, or Qwen3.5's recurrence, on the other; a larger model, or a mixture of experts, gives it the products of the weights that stay in memory. On the development laptop, `janas-bench --prompt 1024 --gen 16 --rounds 2`, the best configuration with the NPU against the best without it (the GPU's fast prompt): Qwen3-0.6B 1,421 tok/s against 974, Qwen3.5-0.8B 1,403 against 950, Qwen3.5-2B 729 against 477, Gemma-4-E2B 508 against 196, Qwen3-4B 333 against 201, Gemma-4-E4B 245 against 129. A reply is written by the CPU as before.+- **On the same NPU, llama.cpp's OpenVINO backend** (build `2b18470`, OpenVINO 2026.4, `GGML_OPENVINO_DEVICE=NPU`): a prompt of 512 tokens of Qwen3-4B read at 120 tok/s, where Janas-LLM read it at 364, and Qwen3-0.6B at 419 against 1,542; it wrote at 5.0 and 12.0 tok/s, all on the NPU, where Janas-LLM wrote on the CPU at 26.6 and 136. The Qwen3.5 models and Gemma 4's did not run on it ("failed to decode prompt batch"), and from 768 tokens of prompt on it stopped on a segmentation fault.+- **The engine takes the NPU by itself only where it reads faster and its answers were measured as close to llama.cpp's as the CPU's**: against llama.cpp's scores on two texts, Italian prose and code, the most likely token agreed at as many positions with the NPU as with the CPU, give or take 7 of 512, on eight models (Qwen3.5-0.8B and 2B, Qwen3-4B, Gemma-4-E2B and E4B, Qwen3-30B-A3B, Qwen3.6-35B-A3B, Qwen3-Next-80B-A3B). On Gemma 4's larger models, product by product, it agreed less (Gemma-4-26B-A4B 363 of 512 against 398): there it reads only when asked. On the mixtures and the dense models too large for it the GPU's fast prompt read faster on this laptop (Qwen3-30B-A3B 133 tok/s against 90-110 with the NPU), and the engine kept the GPU.+- **The NPU is left off where its copies would take the expert cache's memory**: on the mixtures whose experts do not all fit in memory (Qwen3-Next-80B-A3B, Qwen3-Coder-Next, Qwen3.6-35B-A3B) and on Qwen3.8-27B, its eight-bit copies came out of the cache, and Qwen3.8-27B wrote at 1.7 tok/s instead of 4.4. There it opens only when `--prompt-on` names it.+- **The chat shows the NPU being made ready.** The first blocks it reads in a session wait while its weights are copied and its graphs compiled - 7.5 s for Qwen3-0.6B, 17 for Qwen3.5-2B, 24 for Gemma-4-E2B, about 50 for Qwen3-4B and Gemma-4-E4B - and the status line says how far it is ("preparing the NPU 12/25, 8 s"), wherever it happens: while the system message is read ahead, or in a reply; after the reply a line says how long it took. `janas_llm_npu_preparing` (new in `llm.h` and `llm.bi`) gives the same to any program, from another thread while the engine works. A block read while the expert cache still fills goes without the NPU, rather than make graphs that the whole layers drop a moment later (5 s of Qwen3.5-2B's first block).+- **What runs where, by hand**: `--prompt-on`, `--drafts-on` and `--reply-on` in `janas-chat`, `janas-server` and `janas-bench` (and `JANAS_PROMPT_ON`, `JANAS_DRAFTS_ON`, `JANAS_REPLY_ON`) take `auto` (the default), `cpu`, `gpu`, `npu`, two joined by `+` to work in the same pass (`npu+gpu`), or a list apart by commas the engine measures and chooses from (`npu,gpu`); the CPU takes part in every pass, the NPU in prompts only. `/save-config` keeps them. `--npu-int8` reads with eight-bit activations on the dense Qwen3 models, an experiment: Qwen3-4B 387 tok/s against 333, its scores further from the CPU's (a mean difference of 0.60 against 0.33, measured on 20 October).+- **`janas-bench` measures the NPU's configurations**, "+ NPU" and "+ GPU + NPU", prepares it in a warm-up of its own, outside the measures, and says when the engine would not choose it by itself on that model. Its line `NPU:` names the NPU, or says why there is none to use.+- **A mixture's Q3_K experts go to the GPU** in the fast prompt (`q3k_mmid.comp`, one launch for a layer's experts, as Q4_K's, Q6_K's and MXFP4's), and with a whole token on the GPU (`--reply-on gpu`). Unsloth's 3-bit Qwen3-30B-A3B read a prompt of 1,024 tokens at 119.5 tok/s, where it read 98.5 with its experts on the CPU and llama.cpp reads 114.3: the one model of the README's table on which llama.cpp read faster no longer is. Given the CPU's quantized activations the new shader agrees with the CPU's products to their rounding: against llama.cpp's scores of Qwen's Q8_0 the most likely token agreed at 220 and 249 of 256 positions (Italian prose, code), against the exact way's 221 and 245.+- **An expert cache reaches the GPU in regions below 4 GiB**: Mesa's Intel driver passes the size of an imported allocation on to the kernel in 32 bits, and a region of 4 GiB exactly - the second of unsloth's 3-bit Qwen3-30B-A3B, whose slots of 2,236,416 bytes fit 1,920 times 1 MB short of it - went as 0 bytes and was refused: the experts stayed on the CPU, with nothing said. None of the other mixtures measured had such a region. `JANAS_GPU_VERBOSE=1` now says why an import is refused, and where.+- **The fast prompt's distance from the exact way, measured again**, on Qwen3-30B-A3B against llama.cpp's scores of Qwen's Q8_0, Italian prose and code: the most likely token within 5 of 256 positions either way (unsloth's 3-bit file 216 and 246 against the exact way's 221 and 245, Qwen's Q4_K_M 210 and 239 against 207 and 244), the mean difference of the scores within 3%. `docs/features.md` said within 2-3 positions and 2%, from the models and texts measured on 10 October; on these two texts 8 to 27 of the 256 positions change their most likely token with the rounding, and they fell as far as 5 either side.+- **The thread that keeps the NPU awake sleeps while it is not needed**: it woke every half millisecond for as long as the program ran, 2,000 times a second beside the cores writing a reply.+- **`janas_aligned_alloc` asks for a size the alignment divides**, as C11 wants: ThreadSanitizer refused `test_aligned`'s one byte on eight.+- **Two research probes, merged though not final**, both off unless their variables are set: Ana-Net (the experts' down matrices by neuron, `JANAS_Q6_K_PN` from `tools/jns_neurons.c`, each token's neurons read at 6, 4 or 2 bits or not at all, `JANAS_NEURON_LEVELS`; records for the predictor's tests, `JANAS_ANA_*`), and Janet's detectors in place of a model's feed-forward, layer by layer (`model_janet.c`, `JANAS_JANET_*`).+- **The README**: the banner back at the top; one table of the speeds, each engine at its best and the configuration that gave Janas-LLM its figure; the NPU, how it works, and llama.cpp's OpenVINO backend on it; the options that choose what runs where; the measurement notes of 21 October.+## [2026-10-18] - Qwen3.6-35B-A3B's expert cache holds what it has room for-- **An MTP block inside the model's file no longer halves the expert cache.** Qwen3.6-35B-A3B's files carry the block that drafts tokens as a last layer whose experts are in Q8_0, 3,342,336 bytes each against about 2 MB for the model's own, and every slot of the cache was as large as the largest expert: the cache held little more than half the experts its memory had room for. The block's experts now have slots of their own at the end of the same memory, out of the same budget (room for one request, 128 experts, or for all of them when the budget holds every expert), and the model's experts slots of their size; the automatic cache counts the new layout, and nothing changes where the block's experts are no larger. Qwen3.6-35B-A3B Q4_K_M with a 14 GiB cache, `janas-bench --prompt 512 --gen 128 --ctx 4096`, two series of two runs each alternated with the version before: prompt 132-133 tokens/s against 75-81, generation 27.3 against 18.1-18.9, with MTP drafts 39-43 against 32-33, the cache serving 98.6% of the experts against 91-92%. The answers are the same bit for bit (janas-try's fingerprints unchanged). Found by Rendeverance (#34); the fix is written anew.+- **An MTP block inside the model's file no longer halves the expert cache.** Qwen3.6-35B-A3B's files carry the block that drafts tokens as a last layer whose experts are in Q8_0, 3,342,336 bytes each against about 2 MB for the model's own, and every slot of the cache was as large as the largest expert: the cache held little more than half the experts its memory had room for. The block's experts now have slots of their own at the end of the same memory, out of the same budget (room for one request, 128 experts, or for all of them when the budget holds every expert), and the model's experts slots of their size; the automatic cache, `janas_llm_estimate` and `janas_llm_memory` count the new layout, and nothing changes where the block's experts are no larger. Qwen3.6-35B-A3B Q4_K_M with a 14 GiB cache, `janas-bench --prompt 512 --gen 128 --ctx 4096`, two series of two runs each alternated with the version before: prompt 132-133 tokens/s against 75-81, generation 27.3 against 18.1-18.9, with MTP drafts 39-43 against 32-33, the cache serving 98.6% of the experts against 91-92%. The answers are the same bit for bit (janas-try's fingerprints unchanged). Found by Rendeverance (#34); the fix is written anew.- **Windows: no fault freeing a block that starts on a page.** `free` looked for an alignment tag before every block it was given, and read the page before one that began on a page boundary, which may not be mapped: an access violation, seen on Windows on ARM64 (found by Rendeverance, #31). Blocks from the aligned allocator now go back through `janas_aligned_free`, the only one that reads the tag; the asan build uses the tagged blocks on Linux too, so a block given back the wrong way stops the tests (`tests/test_aligned`).- **build.sh stops when a source listing fails**, naming the directory or the file, instead of linking a library short with no message; a library of others with no flags of its own stops it too (found by phaedrus1992, #30).- **The GPU code builds on ARM64 with the Vulkan headers installed**: it included the x86 intrinsics' header for one spin-wait hint.@@ -19,6 +36,16 @@- **test_quant says whether it compared the scalar SiLU with the AVX2 one**: on a CPU without AVX2 and FMA it passed as if a million values had agreed, comparing none (issue #26, reported by phaedrus1992); it prints how many it compared, or that there was nothing to compare with.+## [2026-10-14] - A model's memory, before it opens and while it is open++- **A model's memory, before it opens and while it is open**: `janas_llm_estimate` gives what a model takes whatever its expert cache and what a cache holding all its experts takes, the reckoning `janas_llm_open` makes for its automatic cache; `janas_llm_memory` what an open model holds (resident weights, expert cache, keys and values).+++## [2026-10-14] - A mixture's experts on the GPU beside a shared expert of another type++- **A layer's experts go to the GPU even where its shared expert is of another type.** Where the expert cache holds less than half a mixture's experts, a prompt's experts go to the GPU a layer's group at a time, and a group opens with the layer's shared expert; when its type differed from the routed experts' - Q8_0 beside Qwen3.6-35B-A3B's Q4_K or MXFP4 experts, a plain Q6_K down beside Qwen3-Next's - the whole group stayed on the CPU. Now the CPU computes the shared expert beside the GPU's share. Qwen3.6-35B-A3B Q4_K_M with a 14 GiB cache: the prompt's rows with the GPU 3.7% faster (69.9 tokens/s against 67.3, four runs alternated), the most likely token agreeing with llama.cpp at 197 of 200 positions against 196.++## [2026-10-14] - MXFP4 on the GPU, and the experts of a large cache back on it- **A mixture's experts reach the GPU again when the expert cache holds more than 4 GiB of them.** Since the release of 13 October the memory the GPU reads is given to it in regions that start on 2 MB boundaries, each overlapping the one before, and the overlap was not counted in the 4 GiB a region may take: past the first, a region could come to a little more, which the GPU refused, and the expert cache was then not given to it at all. On an integrated GPU a mixture's experts stayed on the CPU, in the fast prompt and in the block read whole on the GPU, whenever the cache held more than about 4 GiB of experts, depending on the size of an expert: Qwen3.6-35B-A3B's MXFP4_MOE file beyond 4 GiB, its Q4_K_M at six bits beyond 8 GiB. Each region counts its overlap now, and `tests/test_import_regions` checks them.diff --git a/INSTALL.md b/INSTALL.mdindex cd6796f..3a725c6 100644--- a/INSTALL.md+++ b/INSTALL.md@@ -9,6 +9,7 @@ Janas-LLM runs large mixture-of-experts language models on ordinary computers: t- **Memory:** at least 16 GB; 32 GB or more for large models (Qwen3-Next-80B-A3B: about 2 GB of resident weights, plus as much expert cache as the memory allows).- **Disk:** the model on an **NVMe SSD** (the experts are read directly from it while generating).- **GPU (optional):** an integrated or discrete GPU with a **Vulkan 1.3** driver. The engine works fully without one; it measures whether the GPU helps on your machine and uses it only then.+- **NPU (optional, Linux):** the NPU of an Intel Core Ultra, with Intel's NPU driver (below). It reads prompts; the engine measures it as it does the GPU.## Building@@ -26,6 +27,8 @@ The shaders need glslang 15.2 or later (`glslangValidator --version`). Ubuntu 24The GPU also needs its Vulkan driver: Mesa (`mesa-vulkan-drivers` on Debian/Ubuntu) for Intel and AMD, the proprietary driver for NVIDIA. `vulkaninfo --summary` should list your GPU with Vulkan 1.3 or later. When the engine takes none, `janas-bench` and the model's description say why: a build without GPU support (`glslangValidator` missing or older than 15.2: see above, and build again), no Vulkan loader, a GPU whose driver lacks something (named), or the GPU turned off.+The NPU needs nothing at build time: the engine opens Intel's Level Zero driver when a model opens, if it is installed, and goes on without it otherwise. To use it, install the `intel-level-zero-npu` and `intel-driver-compiler-npu` packages of a release of [linux-npu-driver](https://github.com/intel/linux-npu-driver) (1.38.0 was tried, with its packages for Ubuntu 24.04 on Debian 13) and a Level Zero loader, `libze1` (1.32.0 was tried), and add your user to the `render` group (`sudo usermod -aG render $USER`, then log in again), which may open the NPU's device. `janas-bench` names the NPU on its `NPU:` line, or says why there is none to use. `JANAS_NPU_LOADER` names a loader outside the library path, such as one unpacked without installing (`dpkg -x`, with `LD_LIBRARY_PATH` pointing at the driver's libraries); `JANAS_NPU=0` keeps the engine off the NPU. Only the first generation's NPU (Meteor Lake) has been tried.+Then, in the source directory:```shdiff --git a/README.md b/README.mdindex d6c7d7f..e66ef04 100644--- a/README.md+++ b/README.md@@ -2,36 +2,42 @@[]() []() [](https://www.linkedin.com/in/maurizio-cammalleri-80a89a11/) [](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-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 |-|---|---:|---:|---:|---:|-| Qwen3-Next-80B-A3B (48.4 GB, more than the memory) | 62 tok/s | 16 tok/s | 24 tok/s | 2.8 tok/s |-| Qwen3-Coder-Next (48.4 GB, more than the memory) | 66 tok/s | 14 tok/s | 22 tok/s | 2.2 tok/s |-| 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 |-| Qwen3-4B | 193 tok/s | 164 tok/s | 27 tok/s | 18 tok/s |-| Gemma-4-E2B-it | 191 tok/s | 150 tok/s | 38 tok/s | 19 tok/s |-| Qwen3.5-2B | 441 tok/s | 323 tok/s | 52 tok/s | 28 tok/s |-| Qwen3.5-0.8B | 799 tok/s | 519 tok/s | 109 tok/s | 32 tok/s |-| Qwen3-0.6B | 939 tok/s | 670 tok/s | 130 tok/s | 45 tok/s |--The same models from other hands, in the catalog beside them:--| Model | reading 1,024 tokens: Janas-LLM | llama.cpp | writing: Janas-LLM | llama.cpp |-|---|---:|---:|---:|---:|-| Qwen3-30B-A3B, bartowski's Q4_K_M (importance matrix) | 131 tok/s | 122 tok/s | 32 tok/s | 16 tok/s |-| 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 |--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.+```+ ▄███████████▄+▄███████████████▄+███ ▄ █████ ▄ ███ ▄ J A N A S+███▄▄▄█████▄▄▄████+▀█████▄▀▀▀▄█████▀ ▀ a family of tools for artificial intelligence, in C+ █████████████+ █ █ █ █ █ █ █ █+▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀+```-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.+**Qwen3-Next-80B, a 48 GB model, on a laptop with 32 GB of memory: 26 tok/s writing a reply, where llama.cpp manages 3.0, and 68 tok/s reading a prompt, against 18.** On the same laptop (Debian 13 Linux, Intel Core Ultra 9 185H with its integrated Arc GPU and its NPU, 32 GB, an NVMe SSD; the whole machine [below](#the-machine-it-grew-on)) Janas-LLM read a prompt and wrote a reply faster than llama.cpp on every model compared, each at its best (21 October 2026):++| Model | reading 1,024 tokens: Janas-LLM | how | llama.cpp | writing: Janas-LLM | how | llama.cpp |+|---|---:|---|---:|---:|---|---:|+| Qwen3-Next-80B-A3B (48.4 GB, more than the memory) | 68.4 tok/s | GPU, 20 threads | 17.7 tok/s | 26.4 tok/s | CPU, 20 threads | 3.0 tok/s |+| Qwen3-Coder-Next (48.4 GB, more than the memory) | 71.4 tok/s | GPU, 12 threads | 14.0 tok/s | 26.5 tok/s | CPU, 20 threads | 2.9 tok/s |+| Qwen3.6-35B-A3B | 136 tok/s | GPU, 12 threads | 81.8 tok/s | 28.0 tok/s | CPU, 20 threads | 12.1 tok/s |+| Qwen3-30B-A3B | 133 tok/s | GPU, 6 threads | 122 tok/s† | 33.3 tok/s | CPU, 20 threads | 15.0 tok/s† |+| Qwen3-30B-A3B, bartowski's Q4_K_M (importance matrix) | 132 tok/s | GPU, 6 threads | 125 tok/s | 32.3 tok/s | CPU, 20 threads | 15.9 tok/s |+| Qwen3-30B-A3B, unsloth's UD-Q3_K_XL (3 bits) | 120 tok/s | GPU, 12 threads | 114 tok/s | 35.4 tok/s | CPU, 20 threads | 11.3 tok/s |+| Gemma-4-26B-A4B-it | 85.0 tok/s | GPU, 6 threads | 78.0 tok/s | 18.9 tok/s | CPU, 20 threads | 12.6 tok/s |+| Qwen3.8-27B (dense, 17.6 GB) | 31.4 tok/s | GPU, 6 threads | 25.5 tok/s | 4.4 tok/s | CPU, 20 threads | 2.1 tok/s |+| Gemma-4-12B-it | 65.7 tok/s | GPU, 12 threads | 47.6 tok/s | 10.0 tok/s | CPU, 20 threads | 7.4 tok/s |+| Qwen3.5-9B | 122 tok/s | GPU, 6 threads | 80.3 tok/s | 14.5 tok/s | CPU, 20 threads | 8.7 tok/s |+| Gemma-4-E4B-it | 245 tok/s | NPU, 6 threads | 110 tok/s | 19.8 tok/s | CPU, 12 threads | 15.3 tok/s |+| Qwen3-4B | 333 tok/s | NPU, 6 threads | 172 tok/s | 27.9 tok/s | CPU, 20 threads | 17.9 tok/s |+| Qwen3-4B, bartowski's Q4_K_M (importance matrix) | 333 tok/s | NPU, 6 threads | 173 tok/s | 27.8 tok/s | CPU, 20 threads | 18.2 tok/s |+| Gemma-4-E2B-it | 508 tok/s | NPU, 6 threads | 150 tok/s | 37.0 tok/s | CPU, 12 threads | 18.9 tok/s |+| Qwen3.5-2B | 729 tok/s | NPU, 6 threads | 314 tok/s | 53.3 tok/s | CPU, 20 threads | 27.5 tok/s |+| Qwen3.5-0.8B | 1,403 tok/s | NPU, 6 threads | 514 tok/s | 110 tok/s | CPU, 12 threads | 31.1 tok/s |+| Qwen3-0.6B | 1,421 tok/s | NPU, 6 threads | 710 tok/s | 133 tok/s | CPU, 20 threads | 46.0 tok/s |++Janas-LLM's figures are the best of the configurations `janas-bench` measures, and "how" names it: the CPU's threads, with the GPU reading a prompt's blocks (its fast prompt) or the NPU reading them; a reply is written by the CPU. The configuration the engine chose by itself, as a chat runs, was within 1.5% of the best reading and within 2.6% writing, on every model. llama.cpp's are its best on this laptop, with its Vulkan backend on the same GPU; it does not use the NPU, and its OpenVINO backend, which does, is compared under [Intel's NPU](#intels-npu). † llama.cpp's figures of 11 October: the file it read is no longer on this machine. The drafts, which bring a reply sooner (37 tok/s from Qwen3-Next-80B-A3B on 10 October), and how every figure was taken: [How the figures were measured](#how-the-figures-were-measured). On another machine they will be other ones: `janas-bench` measures yours.++**New: Intel's NPU reads the prompts.** On the same laptop's NPU Janas-LLM reads 1,024 tokens of Qwen3.5-2B at 729 tok/s, of Gemma-4-E2B at 508 and of Qwen3-4B at 333, 1.5 to 2.6 times as fast as without it, with answers as close to llama.cpp's as the CPU's. It takes the NPU by itself where it measures faster, and three options choose by hand: [Intel's NPU](#intels-npu), [Choosing what runs where](#choosing-what-runs-where).**Try it** on Linux x86-64 (Ubuntu 22.04, Debian 12 and later):@@ -41,22 +47,11 @@ tar xf janas-linux-x86_64.tar.gz && cd janas./janas-chat # the models it knows: pick one, it is downloaded and checked```-**Or on Windows** 10 (1903 or later) and 11, x86-64: download [janas-windows-x86_64.zip](https://github.com/prabanta-dev/janas/releases/latest/download/janas-windows-x86_64.zip), unpack it, and in a terminal in its `janas` folder run `.\janas-chat`. On the same laptop under Windows 11 (12 October 2026) Janas-LLM wrote as fast as on Linux (Qwen3-4B 25.6 tok/s, Qwen3-30B-A3B 34.2) and read a prompt as fast with the mixture (Qwen3-30B-A3B 132 tok/s) and 1.8 times as fast with the dense model (Qwen3-4B 346 tok/s against 193), whose whole blocks go to the GPU, through Intel's own Windows driver there.+**Or on Windows** 10 (1903 or later) and 11, x86-64: download [janas-windows-x86_64.zip](https://github.com/prabanta-dev/janas/releases/latest/download/janas-windows-x86_64.zip), unpack it, and in a terminal in its `janas` folder run `.\janas-chat`. On the same laptop under Windows 11 (12 October 2026) Janas-LLM wrote as fast as on Linux (Qwen3-4B 25.6 tok/s, Qwen3-30B-A3B 34.2) and read a prompt as fast with the mixture (Qwen3-30B-A3B 132 tok/s) and 1.8 times as fast with the dense model (Qwen3-4B 346 tok/s, against 193 on Linux that week), whose whole blocks go to the GPU, through Intel's own Windows driver there.The models come already converted from [Hugging Face](https://huggingface.co/prabanta-dev); building from the sources: [Getting started](#getting-started).-```- ▄███████████▄-▄███████████████▄-███ ▄ █████ ▄ ███ ▄ J A N A S-███▄▄▄█████▄▄▄████-▀█████▄▀▀▀▄█████▀ ▀ a family of tools for artificial intelligence, in C- █████████████- █ █ █ █ █ █ █ █-▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀-```--Janas is a family of tools for artificial intelligence, written in C with no dependencies beyond the C library. Its first component, **Janas-LLM**, runs large mixture-of-experts language models on ordinary computers, with or without a GPU: the weights stay on disk, the experts each token needs are streamed from an NVMe SSD, and the ones that keep coming back stay in memory. An 80-billion parameter model runs, and answers, on a laptop with 32 GB of RAM.+Janas is a family of tools for artificial intelligence, written in C with no dependencies beyond the C library. Its first component, **Janas-LLM**, runs large mixture-of-experts language models on ordinary computers, on the CPU alone or with a GPU, and with the NPU of Intel's Core Ultra where there is one: the weights stay on disk, the experts each token needs are streamed from an NVMe SSD, and the ones that keep coming back stay in memory. An 80-billion parameter model runs, and answers, on a laptop with 32 GB of RAM.Designed and written by **Maurizio "camauri" Cammalleri**.@@ -73,14 +68,69 @@ Designed and written by **Maurizio "camauri" Cammalleri**.| **Data** | It writes only in `~/.cache/janas` (what it learns about your machine, and the system messages it has read, so as not to read them again) and where you tell it to put a converted model. It does not touch the model files it reads. || **Hardware** | Developed and run on **one** machine (below). On anything else it is untested: it may be slower, it may refuse the model, it may misbehave. |-If something goes wrong, `Ctrl-C` stops a reply and `Ctrl-D` leaves the chat; `--cache <GiB>` puts a hard limit on the memory it takes, and `JANAS_GPU=0` keeps it off the GPU entirely.+If something goes wrong, `Ctrl-C` stops a reply and `Ctrl-D` leaves the chat; `--cache <GiB>` puts a hard limit on the memory it takes, and `JANAS_GPU=0` and `JANAS_NPU=0` keep it off the GPU and off the NPU entirely.++## Intel's NPU++New on 21 October 2026: the NPU of Intel's Core Ultra processors reads the prompts. On the development laptop's (Meteor Lake, "Intel AI Boost"), with `janas-bench --prompt 1024 --gen 16 --rounds 2`, the fastest configuration without the NPU (the GPU's fast prompt included) against the fastest with it:++| Model | reading 1,024 tokens: without the NPU | with it | the NPU made ready in |+|---|---:|---:|---:|+| Qwen3-0.6B | 974 tok/s | **1,421 tok/s** | 7.5 s |+| Qwen3.5-0.8B | 950 tok/s | **1,403 tok/s** | 7.9 s |+| Qwen3.5-2B | 477 tok/s | **729 tok/s** | 17 s |+| Gemma-4-E2B-it | 196 tok/s | **508 tok/s** | 24 s |+| Qwen3-4B | 201 tok/s | **333 tok/s** | 53 s |+| Qwen3-4B, bartowski's Q4_K_M (importance matrix) | 202 tok/s | **333 tok/s** | 46 s |+| Gemma-4-E4B-it | 129 tok/s | **245 tok/s** | 48 s |++On all of them the NPU takes the layers whole (Gemma-4-E4B 41 of its 42). A reply is written as fast as before, by the CPU: its tokens come one at a time, each reading the weights from memory, and the NPU reads the same memory.++**Against llama.cpp on the same NPU.** llama.cpp's OpenVINO backend (build `2b18470`, OpenVINO 2026.4, `GGML_OPENVINO_DEVICE=NPU`) reads and writes on the NPU. From 768 tokens of prompt on it stopped on a segmentation fault, so the two were compared on 512, Janas-LLM with `--prompt-on npu`; the Qwen3.5 models and Gemma 4's did not run on it ("failed to decode prompt batch"):++| Model | reading 512 tokens: Janas-LLM | llama.cpp | writing: Janas-LLM (CPU) | llama.cpp (NPU) |+|---|---:|---:|---:|---:|+| Qwen3-0.6B | 1,542 tok/s | 419 tok/s | 136 tok/s | 12.0 tok/s |+| Qwen3-4B | 364 tok/s | 120 tok/s | 26.6 tok/s | 5.0 tok/s |+| Qwen3-4B, bartowski's Q4_K_M (importance matrix) | 369 tok/s | 121 tok/s | 28.5 tok/s | 4.9 tok/s |+| Qwen3.5-0.8B | 1,325 tok/s | did not run | 111 tok/s | - |+| Qwen3.5-2B | 722 tok/s | did not run | 54.0 tok/s | - |+| Gemma-4-E2B-it | 532 tok/s | did not run | 37.1 tok/s | - |+| Gemma-4-E4B-it | 236 tok/s | did not run | 19.8 tok/s | - |+| Qwen3.5-9B | 64.7 tok/s | did not run | 13.7 tok/s | - |+| Gemma-4-12B-it | 35.2 tok/s | did not run | 10.2 tok/s | - |++**How it works.** The NPU runs graphs its driver compiles. Janas-LLM writes them itself, in OpenVINO's IR format, and opens Intel's Level Zero driver when a model opens: nothing is linked against it, and without it nothing changes. The weights the NPU takes are copied in eight bits, with a scale for each row, and computed in sixteen-bit floats, the norms in 32 bits. A dense model whose layers fit in the NPU's memory, nine in ten at least (about 3.7 GB), goes to it layer by layer, whole, the layers left over to the CPU: each block of the prompt in two halves, the NPU computing a layer on one half while the CPU computes the attention, or Qwen3.5's recurrence, on the other. A larger model, or a mixture of experts, gives it the products of the weights that stay in memory - attention, recurrent layers, shared experts - and leaves the routed experts to the CPU and the GPU. It takes passes of 64 tokens and more: prompts, not a reply's tokens nor the checks of the drafts.++**When the engine uses it.** It measures the NPU among its configurations and keeps it where it reads faster: on this laptop, the dense models whose layers go to it whole. Where it takes products, on the mixtures and the larger dense models, the GPU's fast prompt read faster here (Qwen3-30B-A3B 133 tok/s, against 90-110 with the NPU), and the engine kept the GPU. Against llama.cpp's scores on two texts, Italian prose and code, the most likely token agreed at as many positions with the NPU as with the CPU, give or take 7 of 512, on the eight models checked (Qwen3.5-0.8B and 2B, Qwen3-4B, Gemma-4-E2B and E4B, Qwen3-30B-A3B, Qwen3.6-35B-A3B, Qwen3-Next-80B-A3B). On Gemma 4's larger models, which go product by product, it agreed less (Gemma-4-26B-A4B: 363 against 398): there the NPU reads only when asked, with `--prompt-on npu`. Where the expert cache needs the memory the NPU's eight-bit copies would take - the mixtures whose experts do not all fit in memory, and Qwen3.8-27B, which wrote at 1.7 tok/s instead of 4.4 with them - the NPU is not opened unless `--prompt-on` names it.++**The first prompt waits** while the NPU is made ready, once a session: the weights it takes copied and its graphs compiled, the times in the table above. The chat says how far it has got on its status line ("preparing the NPU 12/25, 8 s") and how long it took; `janas-bench` makes it ready before measuring.++**What it needs.** Linux on an Intel Core Ultra: only the first generation's NPU (Meteor Lake) has been tried, not Lunar Lake's or Arrow Lake's. Intel's NPU driver, the `intel-level-zero-npu` and `intel-driver-compiler-npu` packages of [linux-npu-driver](https://github.com/intel/linux-npu-driver) (1.38.0 here), a Level Zero loader (`libze1`, 1.32.0 here), and your user in the `render` group. `janas-bench` names the NPU on its `NPU:` line, or says why there is none to use; `JANAS_NPU=0` keeps the engine off it, and `JANAS_NPU_LOADER` names a loader outside the library path. The Windows build has no NPU path yet.++## Choosing what runs where++The engine chooses for each kind of pass how many threads to run and whether the GPU and the NPU work beside the CPU, by measuring them on your machine, and keeps what it learns in `~/.cache/janas`. Three options choose by hand, the same in `janas-chat`, `janas-server` and `janas-bench`:++| Option | the passes it sets |+|---|---|+| `--prompt-on <devices>` | reading a prompt: passes of 17 tokens and more, the NPU taking those of 64 and more |+| `--drafts-on <devices>` | checking drafts: passes of 2 to 16 tokens |+| `--reply-on <devices>` | writing a reply: a token at a time |++`<devices>` is `auto` (the default: the engine measures and chooses), `cpu`, `gpu` or `npu`, two joined by `+` to work in the same pass (`npu+gpu`), or a list apart by commas, among which the engine measures and keeps the fastest (`npu,gpu`). The CPU takes part in every pass. The NPU reads prompts only: asked for drafts or a reply it is left out, with a warning, and so is a device the machine does not have. Without `gpu` in `--prompt-on` the GPU's fast prompt, which otherwise reads every prompt's blocks, is off too: `--prompt-on npu` is the NPU and the CPU alone. `--reply-on gpu` gives an integrated GPU a reply's single tokens, which it does not take by itself. A choice holds over `--mode`; `/save-config` keeps it in `janas-chat`, and `JANAS_PROMPT_ON`, `JANAS_DRAFTS_ON` and `JANAS_REPLY_ON` are the same as variables. A device kept out entirely: `--no-gpu` or `JANAS_GPU=0`, and `JANAS_NPU=0`.++```sh+./janas-chat qwen3-4b --prompt-on npu # prompts on the NPU and the CPU, the rest as the engine measures+./janas-bench qwen3.5-2b --prompt-on npu,gpu # both measured for the prompts, the faster kept+```## The machine it grew onEverything in this repository was written and measured on:-- **Linux Debian 13** (trixie), x86-64, kernel 6.12.107; GPU driver Mesa 26.1.6 (Vulkan); built with GCC 14.2-- **Intel Core Ultra 9 185H** (6 performance cores, 8 efficiency, 2 low-power; AVX2, FMA, F16C, AVX-VNNI; integrated Arc GPU)+- **Linux Debian 13** (trixie), x86-64, kernel 6.12.111 (6.12.107 for the figures taken before 21 October); GPU driver Mesa 26.1.6 (Vulkan); NPU driver Intel's linux-npu-driver 1.38.0; built with GCC 14.2+- **Intel Core Ultra 9 185H** (6 performance cores, 8 efficiency, 2 low-power; AVX2, FMA, F16C, AVX-VNNI; integrated Arc GPU; NPU)- **32 GB** of DDR5 RAM- **1 TB NVMe SSD** (about 5.7 GB/s reading)@@ -88,55 +138,21 @@ The Windows build was run on the same laptop under Windows 11 (build 26300), witEverything the engine does is chosen from what it measures, so another machine will make other choices — that part is meant to travel. What has never been tried is the rest: other CPUs (especially without AVX-VNNI, or AMD), discrete GPUs, slower disks, more or less memory. **If you run it somewhere else, the report from `janas-bench` is the single most useful thing you can send back** (see [Helping it run on more hardware](docs/hardware.md#helping-it-run-on-more-hardware)).-## What works now+<a id="what-works-now"></a>-What Janas-LLM runs today, model by model and feature by feature: [docs/features.md](docs/features.md).--On the machine above, with nothing else running, `janas-bench` reports this (measured on 10 October 2026, with the fast prompt the engine uses by default since that day):--| Model | reading a prompt | writing a reply | with drafts, in a chat |-|---|---:|---:|---:|-| Qwen3.5-2B (dense, 1.3 GB) | 395 tok/s | 50 tok/s | **67 tok/s** |-| Qwen3-4B (dense, 2.5 GB) | 220 tok/s | 28 tok/s | see `--draft` below |-| Qwen3.5-9B (dense, 5.7 GB) | 103 tok/s | 14 tok/s | **24 tok/s** |-| Qwen3-30B-A3B (18.6 GB) | 133 tok/s | 34 tok/s | — |-| Qwen3.6-35B-A3B (22.3 GB) | 86 tok/s | 25 tok/s | **34 tok/s** |-| Qwen3-Next-80B-A3B (48.4 GB) | 64 tok/s | 22 tok/s | **37 tok/s** |-| Gemma-4-E2B-it (3.1 GB) | 211 tok/s | 38 tok/s | **52 tok/s** |-| Gemma-4-E4B-it (5.0 GB) | 133 tok/s | 20 tok/s | **32 tok/s** |-| Gemma-4-12B-it (dense, 7.1 GB) | 71 tok/s | 10 tok/s | **14 tok/s** |-| Gemma-4-26B-A4B-it (18.3 GB) | 90 tok/s | 18 tok/s | **26 tok/s** |--Every figure is the **mean of three rounds**, not a best round, of the configuration the engine itself chose for each kind of pass - the one a chat runs: a prompt of 256 tokens, then 64 written. Here the integrated GPU reads every prompt (the fast prompt, below), and the threads the engine settled on were the performance cores' 12 for a prompt and for a single token on nearly every model, all the usable cores (performance and efficiency, not the low-power ones) for a few tokens at once. On another machine the engine may settle on other threads: the first passes of each kind try every core, one thread per performance core and the performance cores' threads, keep the fastest, and later try the others now and then, so that a machine that warms up can change the verdict (on an i9-14900HX every thread replied at less than half the speed of the performance cores' 16). The rounds run in alternating order so that the machine warming up and the cache filling weigh on each setting alike. Expect a few per cent either way between runs, and rather less than these on a first run, while the cache is still filling. Without the GPU (`JANAS_GPU=0`) Qwen3-4B reads the same prompt at 85 tok/s and writes at 27.+## How the figures were measured-The last column is a draft guessing the next tokens and the model checking them, which is the same text at a higher rate — the whole of it is explained under [`--mtp`](docs/chat.md): the Qwen3.5 and Qwen3.6 models' and Qwen3-Next's own prediction block, Gemma 4's assistant (a small drafting model of its own). It is measured on a chat reply: an ordinary question in English ("explain how bread is made at home"), 64 tokens of the answer, sampled as the chat samples. **What the draft is worth depends on the text**: there the drafts survived 74-89% of the time on the Qwen models and Gemma's two larger ones, 63-72% on Gemma's E2B and E4B; on Italian prose Qwen3.5-2B kept about a third of them, and gained next to nothing. One round of 64 tokens is noisy here, a tenth either way between runs. Qwen3-30B-A3B has no such block, nor have the dense Qwen3; the dense Qwen3.5 have one in their original checkpoint, which `hf2jns_mtp` converts ([MODELS.md](MODELS.md#the-fingerprints)).+What Janas-LLM runs today, model by model and feature by feature: [docs/features.md](docs/features.md).-**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 table at the top, on 21 October 2026: `janas-bench --prompt 1024 --gen 16 --rounds 2 --no-mtp --settle 300`, which measures each configuration the engine may choose (6, 12 and 20 threads, with the GPU in the shorter passes or not, with the NPU or not), the best of each column taken, against 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 -r 2 -t 12 -ngl 99`), on the same files the same day. The writing columns are without drafts on both sides. The two tools do not measure in quite the same way (`llama-bench` writes without a prompt before it, `janas-bench` after the 1,024 tokens), and it is one machine.-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).+Qwen3-Next-80B-A3B and Qwen3-Coder-Next are larger than the laptop's memory. 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 `--no-host 1 -lm mmap`, which leave the experts in the file, read through the page cache: 17.7 tok/s reading with the GPU, 3.0 writing on the CPU alone (1.8 with the GPU; its CPU backend read at 12.6). Janas-LLM ran them with no option of its own, the experts it uses most in a cache of 21 GiB and the rest read from the disk.-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.+**The drafts** are tokens guessed ahead that the model checks, all at once: the same text, sooner. They come from the model's own prediction block (the Qwen3.5 and Qwen3.6 models, Qwen3-Next) or from Gemma 4's assistant, a small drafting model of its own; the whole of it is under [`--mtp`](docs/chat.md). Measured on 10 October 2026 on a chat reply - an ordinary question in English ("explain how bread is made at home"), 64 tokens of the answer, sampled as the chat samples - the reply came at 37 tok/s from Qwen3-Next-80B-A3B, 34 from Qwen3.6-35B-A3B, 26 from Gemma-4-26B-A4B, 14 from Gemma-4-12B, 24 from Qwen3.5-9B, 32 from Gemma-4-E4B, 52 from Gemma-4-E2B and 67 from Qwen3.5-2B. What the drafts are worth depends on the text: there 74-89% of them were kept on the Qwen models and on Gemma's two larger ones, 63-72% on E2B and E4B, while on Italian prose Qwen3.5-2B kept about a third and gained next to nothing; and one round of 64 tokens is noisy, a tenth either way. Qwen3-30B-A3B and the dense Qwen3 have no such block (Qwen3-4B can take Qwen3-0.6B as its draft, `--draft`); the dense Qwen3.5 have one in their original checkpoint, which `hf2jns_mtp` converts ([MODELS.md](MODELS.md#the-fingerprints)).-**Try it on an idle machine first.** The expert cache takes the memory that is free when the model is opened, and what is left of the model is read from disk while it answers, so everything else running takes its share. It degrades gently rather than breaking: measured with a browser and an editor open, the same model kept about three quarters of its speed and waited five times longer on the disk. But the first thing you see should be the machine's real speed, and any measurement you mean to send to others has to be taken with the machine to itself.+**The threads.** On the first passes of each kind the engine tries every core, one thread per performance core and the performance cores' threads, keeps the fastest, and tries the others now and then, so that a machine that warms up can change its verdict. Here, on 21 October 2026, it settled on all 20 usable threads for a reply's tokens on 12 of the 17 files and on the performance cores' 12 on the other five, and on 6 to 20 threads for a prompt, beside the GPU or the NPU; on an i9-14900HX every thread replied at less than half the speed of the performance cores' 16.-## Documentation--- [INSTALL.md](INSTALL.md) — what the build needs, how to prepare a model, and the first run-- [ChangeLog.md](ChangeLog.md) — what changed, newest first-- [MODELS.md](MODELS.md) — what a converted model's licence is, and what may be redistributed-- [CONTRIBUTING.md](CONTRIBUTING.md) — how to help, and why code from contributors waits for now-- [src/services](src/services/README.md) — Janas's services, each with its page, in `janas-chat` and in other MCP clients-- [docs/features.md](docs/features.md) — what Janas-LLM runs today, model by model and feature by feature-- [docs/models.md](docs/models.md) — getting a model: `janas-get`, or a GGUF file converted-- [docs/chat.md](docs/chat.md) — using `janas-chat`, its services and tools from MCP servers-- [docs/library.md](docs/library.md) — using it from a program, in C or FreeBASIC-- [docs/serving.md](docs/serving.md) — the model served to MCP clients (`janas-mcp`) and over HTTP (`janas-server`)-- [docs/code-completion.md](docs/code-completion.md) — code completion in VSCodium and VS Code, through `janas-server`-- [docs/tools.md](docs/tools.md) — the converters, checkers and benchmarks-- [docs/hardware.md](docs/hardware.md) — measuring your machine, and helping it run on more hardware-- [docs/reports.md](docs/reports.md) — what testers measured on their own machines-- [AUTHORS](AUTHORS) — who wrote it, and what it owes to others-- [LICENSE](LICENSE) — GNU GPL, version 3 or later+**An idle machine first.** The expert cache takes the memory that is free when the model is opened, and what is left of the model is read from disk while it answers, so everything else running takes its share. It degrades gently rather than breaking: with a browser and an editor open, the same model kept about three quarters of its speed and waited five times longer on the disk. But the first thing you see should be the machine's real speed, and any measurement you mean to send to others has to be taken with the machine to itself.## Getting started@@ -149,51 +165,40 @@ sudo pacman -S vulkan-headers glslang vulkan-tools # the same, Arch./build.sh release test # and run the tests```-## Getting a model--Downloading a model already converted with `janas-get`, or converting a GGUF file yourself, and which files were checked: [docs/models.md](docs/models.md).--## Using the chat+## Documentation+<a id="getting-a-model"></a>+<a id="using-the-chat"></a><a id="janass-services"></a><a id="tools-from-mcp-servers"></a><a id="watching-a-long-prompt"></a>--`janas-chat`: its options and commands, the drafts, Janas's services, tools from MCP servers, a long prompt watched as it is read: [docs/chat.md](docs/chat.md).--## Filling in code--`janas-server` fills in code at an editor's cursor, with a model for code such as Qwen3-Coder-30B-A3B: OpenAI's `/v1/completions` with a `suffix`, and llama.cpp's `/infill`, which llama.vscode asks. The window sent at every keystroke is kept from moving, so that a keystroke reads only what it changed: 1.5-2.2 s a proposal on a laptop, where a window slid a line was read again in 17 s. How to set it up in VSCodium and VS Code, with llama.vscode or Continue, and what was measured: [docs/code-completion.md](docs/code-completion.md).--## Using it from a program-+<a id="filling-in-code"></a>+<a id="using-it-from-a-program"></a><a id="from-c"></a><a id="from-freebasic-and-basic-modern"></a><a id="mcp-servers-from-a-program"></a>+<a id="janas-as-an-mcp-server"></a>+<a id="using-it-over-http"></a>+<a id="measuring-your-machine"></a>+<a id="tools"></a>+<a id="helping-it-run-on-more-hardware"></a>-The library from C and from FreeBASIC and BASIC MODERN, and MCP servers from a program: [docs/library.md](docs/library.md).--## Janas as an MCP server--`janas-mcp`: the model as tools for Claude Code, editors and other MCP clients: [docs/serving.md](docs/serving.md#janas-as-an-mcp-server).--## Using it over HTTP--`janas-server`: an HTTP API that follows OpenAI's, and a chat page to try it from a browser: [docs/serving.md](docs/serving.md#using-it-over-http).--## Measuring your machine--`janas-bench`: what it measures, and the report it leaves: [docs/hardware.md](docs/hardware.md#measuring-your-machine).--## Tools--The converters, checkers and benchmarks built beside the programs: [docs/tools.md](docs/tools.md).--## Helping it run on more hardware--Which machines are wanted most, the one command that tries Janas and writes a report, and what to send: [docs/hardware.md](docs/hardware.md#helping-it-run-on-more-hardware).--What testers measured on their own machines so far: [docs/reports.md](docs/reports.md).+- [INSTALL.md](INSTALL.md) — what the build needs, how to prepare a model, and the first run+- [ChangeLog.md](ChangeLog.md) — what changed, newest first+- [MODELS.md](MODELS.md) — what a converted model's licence is, and what may be redistributed+- [CONTRIBUTING.md](CONTRIBUTING.md) — how to help, and why code from contributors waits for now+- [src/services](src/services/README.md) — Janas's services, each with its page, in `janas-chat` and in other MCP clients+- [docs/features.md](docs/features.md) — what Janas-LLM runs today, model by model and feature by feature+- [docs/models.md](docs/models.md) — getting a model: `janas-get`, or a GGUF file converted, and which files were checked+- [docs/chat.md](docs/chat.md) — `janas-chat`: its options and commands, the drafts, Janas's services, tools from MCP servers, a long prompt watched as it is read+- [docs/library.md](docs/library.md) — using it from a program, in C or in FreeBASIC and BASIC MODERN, and MCP servers from a program+- [docs/serving.md](docs/serving.md) — the model as tools for Claude Code, editors and other MCP clients (`janas-mcp`), and over HTTP, an API that follows OpenAI's with a chat page to try it from a browser (`janas-server`)+- [docs/code-completion.md](docs/code-completion.md) — code filled in at an editor's cursor, in VSCodium and VS Code through `janas-server`: 1.5-2.2 s a proposal on a laptop, where a window slid a line was read again in 17 s+- [docs/tools.md](docs/tools.md) — the converters, checkers and benchmarks built beside the programs+- [docs/hardware.md](docs/hardware.md) — measuring your machine with `janas-bench`, and helping it run on more hardware: the machines wanted most, the one command that tries Janas and writes a report, and what to send+- [docs/reports.md](docs/reports.md) — what testers measured on their own machines+- [AUTHORS](AUTHORS) — who wrote it, and what it owes to others+- [LICENSE](LICENSE) — GNU GPL, version 3 or later## Credits@@ -205,6 +210,7 @@ It stands on the work of others, and says so:- **llama.cpp and ggml** are the reference the engine is checked against (logits, tokens, speed); none of their code is in Janas. The one thing taken from ggml is data that defines a format: the IQ3_S grid, in `src/llm/iq3s_grid.h`, under ggml's MIT licence.- **The Unicode Character Database** gives the tokenizer its tables (`tools/gen_unicode`), and **OpenAI's OpenAPI specification** gives `janas-server` its route table (`tools/openapi_routes`).- **GNU libmicrohttpd, yyjson and Mbed TLS** are compiled into the programs named below.+- **Intel's NPU driver** ([linux-npu-driver](https://github.com/intel/linux-npu-driver)) compiles and runs the NPU's graphs, opened when a model opens if it is installed; Janas-LLM writes the graphs itself in OpenVINO's IR format, and declares the Level Zero functions it calls from the oneAPI Level Zero specification (`src/common/npu_ze.h`): no code of OpenVINO's or of Level Zero's is in Janas.- **`janas-flights`** reads the positions of aircraft from [adsb.lol](https://adsb.lol) (data under the Open Database License) and [adsb.fi](https://adsb.fi), routes from [adsbdb.com](https://www.adsbdb.com) and, with a key of the user's, schedules from [AviationStack](https://aviationstack.com); its tables of places are built from [OurAirports](https://ourairports.com) (public domain), [GeoNames](https://www.geonames.org) (CC BY 4.0) and [Natural Earth](https://www.naturalearthdata.com) (public domain).- **`janas-quakes`** reads the earthquakes from [INGV](https://terremoti.ingv.it) (Istituto Nazionale di Geofisica e Vulcanologia, CC BY 4.0) for Italy and its seas and from the [USGS](https://earthquake.usgs.gov) (public domain) elsewhere, and places from [Nominatim](https://nominatim.org) (© OpenStreetMap contributors, ODbL).- **`janas-weather`** reads forecasts and the sea from [Open-Meteo](https://open-meteo.com) (CC BY 4.0) and [MET Norway](https://api.met.no) (CC BY 4.0), the stations' reports from [aviationweather.gov](https://aviationweather.gov) (NOAA), warnings from [MeteoAlarm](https://meteoalarm.org) (EUMETNET) and the Italian alert levels from the [Dipartimento della Protezione Civile](https://github.com/pcm-dpc/DPC-Bollettini-Criticita-Idrogeologica-Idraulica) (CC BY 4.0). With no place named, the services ask [GeoJS](https://www.geojs.io) or [ipwho.is](https://ipwho.is) where the internet connection is.diff --git a/dist/README-windows.md b/dist/README-windows.mdindex 75cef78..d04552f 100644--- a/dist/README-windows.md+++ b/dist/README-windows.md@@ -1,29 +1,32 @@# Janas for Windows x86-64-**Qwen3-Next-80B, a 48 GB model, on a laptop with 32 GB of memory: 37 tok/s with its own draft block, 24 without, where llama.cpp manages 2.8 on the same laptop.** Reading a prompt of 1,024 tokens: 62 tok/s against 16. Janas-LLM was faster than llama.cpp on every model compared on that laptop (Debian 13 Linux with kernel 6.12.107, Intel Core Ultra 9 185H, its integrated Arc GPU with Mesa 26.1.6, 32 GB of DDR5-5600 memory, an NVMe SSD), measured on 9-11 October 2026:+**Qwen3-Next-80B, a 48 GB model, on a laptop with 32 GB of memory: 26 tok/s writing a reply, where llama.cpp manages 3.0, and 68 tok/s reading a prompt, against 18.** Janas-LLM read and wrote faster than llama.cpp on every model compared on that laptop (Debian 13 Linux with kernel 6.12.111, Intel Core Ultra 9 185H, its integrated Arc GPU with Mesa 26.1.6, 32 GB of DDR5-5600 memory, an NVMe SSD), each at its best without the NPU, which this package does not use, measured on 21 October 2026:| Model | reading 1,024 tokens: Janas-LLM | llama.cpp | writing: Janas-LLM | llama.cpp ||---|---:|---:|---:|---:|-| Qwen3-Next-80B-A3B (48.4 GB, more than the memory) | 62 tok/s | 16 tok/s | 24 tok/s | 2.8 tok/s |-| Qwen3-Coder-Next (48.4 GB, more than the memory) | 66 tok/s | 14 tok/s | 22 tok/s | 2.2 tok/s |-| 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 |-| Qwen3-4B | 193 tok/s | 164 tok/s | 27 tok/s | 18 tok/s |-| Gemma-4-E2B-it | 191 tok/s | 150 tok/s | 38 tok/s | 19 tok/s |-| Qwen3.5-2B | 441 tok/s | 323 tok/s | 52 tok/s | 28 tok/s |-| Qwen3.5-0.8B | 799 tok/s | 519 tok/s | 109 tok/s | 32 tok/s |-| Qwen3-0.6B | 939 tok/s | 670 tok/s | 130 tok/s | 45 tok/s |--The 3-bit Qwen3-30B of the catalog is the one exception: it reads a prompt slower than llama.cpp (100 tok/s against 112), its Q3_K weights not on the GPU's fast prompt yet. On another machine the figures will be other ones: `janas-bench` measures yours (below). How they were taken, and everything else: <https://github.com/prabanta-dev/janas>.+| Qwen3-Next-80B-A3B (48.4 GB, more than the memory) | 68.4 tok/s | 17.7 tok/s | 26.4 tok/s | 3.0 tok/s |+| Qwen3-Coder-Next (48.4 GB, more than the memory) | 71.4 tok/s | 14.0 tok/s | 26.5 tok/s | 2.9 tok/s |+| Qwen3.6-35B-A3B | 136 tok/s | 81.8 tok/s | 28.0 tok/s | 12.1 tok/s |+| Qwen3-30B-A3B | 133 tok/s | 122 tok/s† | 33.3 tok/s | 15.0 tok/s† |+| Qwen3-30B-A3B, bartowski's Q4_K_M (importance matrix) | 132 tok/s | 125 tok/s | 32.1 tok/s | 15.9 tok/s |+| Qwen3-30B-A3B, unsloth's UD-Q3_K_XL (3 bits) | 120 tok/s | 114 tok/s | 35.3 tok/s | 11.3 tok/s |+| Gemma-4-26B-A4B-it | 85.0 tok/s | 78.0 tok/s | 18.9 tok/s | 12.6 tok/s |+| Qwen3.8-27B (dense, 17.6 GB) | 31.4 tok/s | 25.5 tok/s | 4.4 tok/s | 2.1 tok/s |+| Gemma-4-12B-it | 65.7 tok/s | 47.6 tok/s | 10.0 tok/s | 7.4 tok/s |+| Qwen3.5-9B | 122 tok/s | 80.3 tok/s | 14.5 tok/s | 8.7 tok/s |+| Gemma-4-E4B-it | 129 tok/s | 110 tok/s | 19.8 tok/s | 15.3 tok/s |+| Qwen3-4B | 201 tok/s | 172 tok/s | 27.7 tok/s | 17.9 tok/s |+| Qwen3-4B, bartowski's Q4_K_M (importance matrix) | 202 tok/s | 173 tok/s | 27.8 tok/s | 18.2 tok/s |+| Gemma-4-E2B-it | 196 tok/s | 150 tok/s | 36.9 tok/s | 18.9 tok/s |+| Qwen3.5-2B | 477 tok/s | 314 tok/s | 53.3 tok/s | 27.5 tok/s |+| Qwen3.5-0.8B | 950 tok/s | 514 tok/s | 108 tok/s | 31.1 tok/s |+| Qwen3-0.6B | 974 tok/s | 710 tok/s | 129 tok/s | 46.0 tok/s |++Janas-LLM's figures are the best of the configurations `janas-bench` measures without the NPU, the GPU reading a prompt's blocks; llama.cpp's are its best on that laptop, with its Vulkan backend on the same GPU. † llama.cpp's figures of 11 October. On another machine the figures will be other ones: `janas-bench` measures yours (below). How they were taken, and everything else: <https://github.com/prabanta-dev/janas>.Janas-LLM, the inference engine of Janas, runs large language models on ordinary computers, with or without a GPU, mixtures of experts larger than the memory among them: the weights stay on disk, the experts each token needs are read from the SSD and the ones that keep coming back stay in memory. It is written in C and needs nothing but the system's C library; a GPU is used through its Vulkan driver when there is one.-The figures above were measured on Linux. On the same laptop under Windows 11 (build 26300, 12 October 2026), this package wrote as fast (Qwen3-4B 25.6 tok/s, Qwen3-30B-A3B 34.2), read a prompt as fast with the mixture (Qwen3-30B-A3B 132 tok/s) and 1.8 times as fast with the dense model (Qwen3-4B 346 tok/s).+The figures above were measured on Linux. On the same laptop under Windows 11 (build 26300, 12 October 2026), this package wrote as fast (Qwen3-4B 25.6 tok/s, Qwen3-30B-A3B 34.2), read a prompt as fast with the mixture (Qwen3-30B-A3B 132 tok/s) and faster with the dense model (Qwen3-4B 346 tok/s, against 193 on Linux that week), whose whole blocks go to the GPU through Intel's Windows driver.## Startdiff --git a/dist/README.md b/dist/README.mdindex af7a86d..3895e15 100644--- a/dist/README.md+++ b/dist/README.md@@ -1,25 +1,28 @@# Janas for Linux x86-64-**Qwen3-Next-80B, a 48 GB model, on a laptop with 32 GB of memory: 37 tok/s with its own draft block, 24 without, where llama.cpp manages 2.8 on the same laptop.** Reading a prompt of 1,024 tokens: 62 tok/s against 16. Janas-LLM was faster than llama.cpp on every model compared on that laptop (Debian 13 Linux with kernel 6.12.107, Intel Core Ultra 9 185H, its integrated Arc GPU with Mesa 26.1.6, 32 GB of DDR5-5600 memory, an NVMe SSD), measured on 9-11 October 2026:+**Qwen3-Next-80B, a 48 GB model, on a laptop with 32 GB of memory: 26 tok/s writing a reply, where llama.cpp manages 3.0, and 68 tok/s reading a prompt, against 18.** Janas-LLM read and wrote faster than llama.cpp on every model compared on that laptop (Debian 13 Linux with kernel 6.12.111, Intel Core Ultra 9 185H with its integrated Arc GPU, Mesa 26.1.6, and its NPU, 32 GB of DDR5-5600 memory, an NVMe SSD), each at its best, measured on 21 October 2026:| Model | reading 1,024 tokens: Janas-LLM | llama.cpp | writing: Janas-LLM | llama.cpp ||---|---:|---:|---:|---:|-| Qwen3-Next-80B-A3B (48.4 GB, more than the memory) | 62 tok/s | 16 tok/s | 24 tok/s | 2.8 tok/s |-| Qwen3-Coder-Next (48.4 GB, more than the memory) | 66 tok/s | 14 tok/s | 22 tok/s | 2.2 tok/s |-| 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 |-| Qwen3-4B | 193 tok/s | 164 tok/s | 27 tok/s | 18 tok/s |-| Gemma-4-E2B-it | 191 tok/s | 150 tok/s | 38 tok/s | 19 tok/s |-| Qwen3.5-2B | 441 tok/s | 323 tok/s | 52 tok/s | 28 tok/s |-| Qwen3.5-0.8B | 799 tok/s | 519 tok/s | 109 tok/s | 32 tok/s |-| Qwen3-0.6B | 939 tok/s | 670 tok/s | 130 tok/s | 45 tok/s |+| Qwen3-Next-80B-A3B (48.4 GB, more than the memory) | 68.4 tok/s | 17.7 tok/s | 26.4 tok/s | 3.0 tok/s |+| Qwen3-Coder-Next (48.4 GB, more than the memory) | 71.4 tok/s | 14.0 tok/s | 26.5 tok/s | 2.9 tok/s |+| Qwen3.6-35B-A3B | 136 tok/s | 81.8 tok/s | 28.0 tok/s | 12.1 tok/s |+| Qwen3-30B-A3B | 133 tok/s | 122 tok/s† | 33.3 tok/s | 15.0 tok/s† |+| Qwen3-30B-A3B, bartowski's Q4_K_M (importance matrix) | 132 tok/s | 125 tok/s | 32.3 tok/s | 15.9 tok/s |+| Qwen3-30B-A3B, unsloth's UD-Q3_K_XL (3 bits) | 120 tok/s | 114 tok/s | 35.4 tok/s | 11.3 tok/s |+| Gemma-4-26B-A4B-it | 85.0 tok/s | 78.0 tok/s | 18.9 tok/s | 12.6 tok/s |+| Qwen3.8-27B (dense, 17.6 GB) | 31.4 tok/s | 25.5 tok/s | 4.4 tok/s | 2.1 tok/s |+| Gemma-4-12B-it | 65.7 tok/s | 47.6 tok/s | 10.0 tok/s | 7.4 tok/s |+| Qwen3.5-9B | 122 tok/s | 80.3 tok/s | 14.5 tok/s | 8.7 tok/s |+| Gemma-4-E4B-it | 245 tok/s | 110 tok/s | 19.8 tok/s | 15.3 tok/s |+| Qwen3-4B | 333 tok/s | 172 tok/s | 27.9 tok/s | 17.9 tok/s |+| Qwen3-4B, bartowski's Q4_K_M (importance matrix) | 333 tok/s | 173 tok/s | 27.8 tok/s | 18.2 tok/s |+| Gemma-4-E2B-it | 508 tok/s | 150 tok/s | 37.0 tok/s | 18.9 tok/s |+| Qwen3.5-2B | 729 tok/s | 314 tok/s | 53.3 tok/s | 27.5 tok/s |+| Qwen3.5-0.8B | 1,403 tok/s | 514 tok/s | 110 tok/s | 31.1 tok/s |+| Qwen3-0.6B | 1,421 tok/s | 710 tok/s | 133 tok/s | 46.0 tok/s |-The 3-bit Qwen3-30B of the catalog is the one exception: it reads a prompt slower than llama.cpp (100 tok/s against 112), its Q3_K weights not on the GPU's fast prompt yet. On another machine the figures will be other ones: `janas-bench` measures yours (below). How they were taken, and everything else: <https://github.com/prabanta-dev/janas>.+Janas-LLM's figures are the best of the configurations `janas-bench` measures: the GPU reading a prompt's blocks, or on the smaller dense models (Qwen3-4B and smaller, Gemma-4-E2B and E4B) the NPU; llama.cpp's are its best on that laptop, with its Vulkan backend on the same GPU. † llama.cpp's figures of 11 October. On another machine the figures will be other ones: `janas-bench` measures yours (below). How they were taken, and everything else: <https://github.com/prabanta-dev/janas>.Janas-LLM, the inference engine of Janas, runs large language models on ordinary computers, with or without a GPU, mixtures of experts larger than the memory among them: the weights stay on disk, the experts each token needs are read from the SSD and the ones that keep coming back stay in memory. It is written in C and needs nothing but the system's C library; a GPU is used through its Vulkan driver when there is one.@@ -56,6 +59,7 @@ Janas-LLM, the inference engine of Janas, runs large language models on ordinary- Linux on x86-64, with the C library of Ubuntu 22.04, Debian 12 or later.- An NVMe SSD for the models larger than the memory.- A GPU is optional: an integrated one with a Vulkan driver reads the prompts faster (measured on Intel's Arc; others untested).+- An NPU is optional too: the NPU of Intel's Core Ultra reads the prompts of the smaller dense models faster (measured on the first generation's, Meteor Lake), with Intel's NPU driver (linux-npu-driver), a Level Zero loader and the user in the `render` group.It is an experiment, developed and measured on one machine: an Intel CPU with AVX2 and AVX-VNNI. On other processors, GPUs and disks it is untested; the report of `janas-bench` is the most useful thing to send back (<https://github.com/prabanta-dev/janas/issues>).diff --git a/docs/chat.md b/docs/chat.mdindex 64653ea..b3cc430 100644--- a/docs/chat.md+++ b/docs/chat.md@@ -51,6 +51,10 @@ Qwen3.5-0.8B does not take `--head 4`: with it, it answered "3" to "2+3". Gemma| `--no-spec` | no speculative decoding (slower, and the same text: see below) || `--no-markdown` | print the model's marks instead of reading them || `--no-gpu` | never give the GPU work, whatever the mode says |+| `--prompt-on <devices>` | what reads the prompts: `auto` (default: what measures fastest on this machine), `cpu`, `gpu`, `npu`, `npu+gpu` (both in each pass), or a list apart by commas for the engine to choose from, such as `npu,gpu`; the CPU takes part in every pass, the NPU in blocks of 64 tokens and more; a choice wins over `--mode` |+| `--drafts-on <devices>` | the same for the passes that check guessed tokens (2 to 16 at a time) |+| `--reply-on <devices>` | the same for a reply's tokens, one at a time; `gpu` gives an integrated GPU single tokens, which it does not take by default |+| `--npu-int8` | the NPU reads prompts with eight-bit activations (dense Qwen3 models): faster, a little less exact || `--mode auto\|eco\|max` | power mode: `eco` never uses the GPU for speed alone || `--think on\|off\|N` | reasoning before replying, for models that do it; a number: on, at most N tokens of it, then a sentence that closes it and the answer || `--stats` | a line of counters after every reply: speeds, time to the first token, threads, memory |@@ -112,6 +116,8 @@ The chat starts by itself the services of Janas it finds beside it - `janas-flig**The system message is read ahead.** It used to be four thousand tokens with the services' tools, and the first reply waited for all of it. `janas-chat` now reads it as soon as it starts, while you write, and says so: a line in the conversation when it begins, and "reading the tools ahead" with how far it is in the status line, where it is the last thing to be dropped on a narrow window; a message sent before the end waits for it, with "waiting for the tools" and the share, and Ctrl-C leaves the rest to the reply. Once read it is kept in `~/.cache/janas` (2 GiB at most for these files), and the next chat on the same model finds it there: "System message and tools ready". Changing the system message or the tools reads them again.+**The NPU made ready, in sight.** The first blocks the NPU reads in a session wait while it is made ready: the weights it takes copied in eight bits and its graphs compiled, 17 s for Qwen3.5-2B on the development laptop, about 50 s for Qwen3-4B (21 October 2026). The status line says so meanwhile, wherever it happens - while the system message is read ahead, or in a reply -: "preparing the NPU 12/25, 8 s", the graphs made of those to make and the seconds gone; after the reply a line says how long it took, once a session. A program on the library has the same from `janas_llm_npu_preparing`, which may be called from another thread while the engine works.+## Tools from MCP serversThe chat also starts the [Model Context Protocol](https://modelcontextprotocol.io) servers listed in `~/.config/janas/mcp.json` (or in the file `--mcp-config` names), in the format the other clients use, so a configuration can be copied from one of them:diff --git a/docs/features.md b/docs/features.mdindex 36b26c9..6d1ef2d 100644--- a/docs/features.md+++ b/docs/features.md@@ -21,7 +21,9 @@- **`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, Q3_K, IQ4_XS, IQ3_S, IQ4_NL, MXFP4, 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.+- **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, MXFP4, the experts of a mixture in one launch per layer - Q4_K, Q6_K, MXFP4 and, since 21 October 2026, Q3_K - 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 agreed with the exact way's within 2-3 of 256 positions on the models measured on 10 October 2026, the mean difference of the scores within 2%; on 21 October, Qwen3-30B-A3B against llama.cpp's scores of Qwen's Q8_0, on Italian prose and code, within 5 either way (unsloth's 3-bit file 216 and 246 against the exact way's 221 and 245, Qwen's Q4_K_M 210 and 239 against 207 and 244) and the mean difference within 3%: 8 to 27 of a text's 256 positions change their most likely token with the rounding, and they fall on either side. On the development laptop Qwen3-4B read a prompt of 256 tokens at 220 tok/s with it and at 85 without the GPU (10 October 2026), and on 21 October every model compared read a prompt faster than llama.cpp did on the same GPU ([the table](../README.md)). `JANAS_GPU_FAST_PROMPT=0` reads them the exact way.+- **Intel's NPU** (the Core Ultra's, on Linux; since 21 October 2026) reads a prompt's blocks of 64 tokens and more. A dense model whose layers fit in its memory, nine in ten at least, goes to it layer by layer, whole - Qwen3, Qwen3.5 and Gemma 4's dense models - and other models give it the products of the weights that stay in memory; a reply's tokens stay with the CPU. Janas-LLM writes the NPU's graphs itself, in OpenVINO's IR format, and opens Intel's Level Zero driver when a model opens: nothing is linked against it. The engine takes the NPU by itself where it reads faster and its answers measured as close to llama.cpp's as the CPU's (the Qwen models, and Gemma 4's whose layers go whole); where the expert cache cannot hold all of a model's feed-forward weights (the larger mixtures, Qwen3.8-27B) it stays off unless asked, its copies' memory being the cache's. On the development laptop, 1,024 tokens, with it and without: Qwen3-0.6B 1,421 and 974 tok/s, Qwen3.5-0.8B 1,403 and 950, Qwen3.5-2B 729 and 477, Qwen3-4B 333 and 201, Gemma-4-E2B 508 and 196, Gemma-4-E4B 245 and 129; on the mixtures and the dense models too large for it the GPU's fast prompt reads faster there. Its first blocks in a session wait while it is made ready, 7.5 to 53 s, and the chat's status line says so. How it works and what it needs: [the README](../README.md#intels-npu).+- **What runs where, by hand**: `--prompt-on`, `--drafts-on` and `--reply-on` (`auto`, `cpu`, `gpu`, `npu`, `npu+gpu`, or a list the engine chooses from) in `janas-chat`, `janas-server` and `janas-bench` ([docs/chat.md](chat.md)).- **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 (MXFP4, since 14 October 2026, at 66 GB/s where IQ4_NL reads at 73 in the same run: 4% fewer weights a second, a block of it being 17 bytes to IQ4_NL's 18); 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/docs/hardware.md b/docs/hardware.mdindex 30642e1..2126fd5 100644--- a/docs/hardware.md+++ b/docs/hardware.md@@ -6,7 +6,7 @@bin/x86_64-linux/janas-bench qwen3-4b```-It takes the model as `janas-chat` does: a name of the models Janas knows (downloaded, after asking, if it is not there yet), a `.jns` file, or nothing, and then the list to choose from; the model's prediction file comes with it as in the chat (`--no-mtp`: without). Close what you can before running it: it measures the machine you give it, and a browser with thirty tabs is part of the machine. It tries the configurations the machine offers — how many threads, which cores, with and without the GPU — on real passes of the model, keeps the fastest, writes them into `~/.cache/janas` so the next start begins from them, and leaves a report in the current directory. With the fast prompt the GPU reads a prompt's blocks in every configuration, so a row without "+ GPU" is not the CPU alone; the report says so under its table. On the development laptop that report says, among other things (10 October 2026, ten models), that a single token and a prompt go fastest on the performance cores' 12 threads, while a draft check - a few tokens at once - goes fastest on all the usable cores: the kinds of pass want different threads, which is why each is tuned on its own.+It takes the model as `janas-chat` does: a name of the models Janas knows (downloaded, after asking, if it is not there yet), a `.jns` file, or nothing, and then the list to choose from; the model's prediction file comes with it as in the chat (`--no-mtp`: without). Close what you can before running it: it measures the machine you give it, and a browser with thirty tabs is part of the machine. It tries the configurations the machine offers — how many threads, which cores, with and without the GPU and the NPU — on real passes of the model, keeps the fastest, writes them into `~/.cache/janas` so the next start begins from them, and leaves a report in the current directory. With the fast prompt the GPU reads a prompt's blocks in every configuration, so a row without "+ GPU" is not the CPU alone; the report says so under its table. Where there is an Intel NPU, the rows "+ NPU" and "+ GPU + NPU" give it a prompt's blocks of 64 tokens and more; it is made ready before the rows are measured (its weights copied, its graphs compiled), and the report says when the engine would not choose it by itself on that model. On the development laptop that report says, among other things (10 October 2026, ten models), that a single token and a prompt go fastest on the performance cores' 12 threads, while a draft check - a few tokens at once - goes fastest on all the usable cores: the kinds of pass want different threads, which is why each is tuned on its own.## Helping it run on more hardware@@ -42,10 +42,11 @@ The [hardware report form](https://github.com/prabanta-dev/janas/issues/new?temp1. **CPUs without AVX-VNNI**, and **AMD** — the arithmetic has a path for them and it is the least exercised of all.2. **Discrete GPUs** (NVIDIA, AMD, Intel Arc). The GPU support is correct where it was checked - bit for bit on a reply's tokens, and on a prompt as close to the references as the CPU - and it pays where it was measured: on the development laptop's integrated GPU, with the fast prompt, Qwen3-4B reads a prompt 2.6 times faster than without the GPU (85 to 220 tokens/s; before the fast prompt, 83 to 107), and on an RTX 5080 (issue #15) Qwen3-4B read 13% faster and, with the GPU on single tokens too, replied 11-16% faster. From the release of 10 October to that of 13 October a discrete card's results stayed in its own memory, where the CPU never read them (issue #17, corrupted output on a Quadro RTX 5000); fixed since, and checked here on the path such a card takes, not yet on one. Every other card is unknown, and the fast prompt has not been seen working on a discrete one yet (`JANAS_GPU_FAST_PROMPT=0` turns it off if it misbehaves). **Careful:** a GPU driver reset takes the desktop with it. Start with `janas-bench`, not with a long chat.-3. **Machines with 16 GB or less.** The engine is supposed to trade quality for memory on its own — fewer bits per weight, light experts not in memory left out — and the thresholds for that were measured on 32 GB.-4. **Slower disks.** Everything assumes an NVMe SSD; on a SATA disk the engine should still work and simply wait more, but nobody has watched it do so.-5. **Windows on other machines.** The Windows build has run on one laptop, the development one (Windows 11, build 26300), where its tests pass and it is as fast as on Linux; `janas-bench`'s report from any other is welcome.-6. **Other models** of the supported families. A file that will not convert, or converts and then answers nonsense, is a useful bug.+3. **Other NPUs.** Only the first Core Ultra's NPU (Meteor Lake) has been tried; Lunar Lake's and Arrow Lake's should take the same graphs and have not been seen doing it. AMD's and Qualcomm's NPUs are not supported yet.+4. **Machines with 16 GB or less.** The engine is supposed to trade quality for memory on its own — fewer bits per weight, light experts not in memory left out — and the thresholds for that were measured on 32 GB.+5. **Slower disks.** Everything assumes an NVMe SSD; on a SATA disk the engine should still work and simply wait more, but nobody has watched it do so.+6. **Windows on other machines.** The Windows build has run on one laptop, the development one (Windows 11, build 26300), where its tests pass and it is as fast as on Linux; `janas-bench`'s report from any other is welcome.+7. **Other models** of the supported families. A file that will not convert, or converts and then answers nonsense, is a useful bug.**What testers found so far** (every report, with its numbers: [reports.md](reports.md)). On a Radeon 780M (Ryzen 7 255, issue #16) the GPU read Qwen3-4B's prompt 5.2 times faster than the CPU alone (477 against 92 tokens/s, the second with `JANAS_GPU_FAST_PROMPT=0`), and subgroups of 32 (`JANAS_GPU_SG=32`) instead of the 64 the engine chose cost 14% (405 against 470 tokens/s): the default is right there. Its "+ GPU" rows wrote a reply at 10.5 tokens/s against 17.3 on the CPU alone: the GPU was kept awake for the single tokens of a reply, which an integrated GPU does not take, and awake it only took the power the cores need. Since 14 October 2026 it is kept awake only for the passes it takes; on the development laptop's Arc the "+ GPU" rows wrote 2-5% slower than the CPU alone before, and as fast after (Qwen3-4B, two alternated runs each). On a Quadro RTX 5000 (issue #17) the defect above.diff --git a/docs/serving.md b/docs/serving.mdindex 198ba35..84f0ef5 100644--- a/docs/serving.md+++ b/docs/serving.md@@ -19,7 +19,7 @@ What has been run: a probe script speaking each era to it with Qwen3-0.6B and Qwbin/x86_64-linux/janas-server qwen3-next.jns```-`janas-server` puts the model behind an HTTP API that follows [OpenAI's](https://github.com/openai/openai-openapi), on `http://127.0.0.1:8080/v1`, so that a client written for that API can use a model running on this machine. It takes the model options `janas-chat` takes (`--ctx`, `--cache`, `--reserve`, `--mtp`, `--draft`, `--mode`, `--no-gpu`) and these:+`janas-server` puts the model behind an HTTP API that follows [OpenAI's](https://github.com/openai/openai-openapi), on `http://127.0.0.1:8080/v1`, so that a client written for that API can use a model running on this machine. It takes the model options `janas-chat` takes (`--ctx`, `--cache`, `--reserve`, `--mtp`, `--draft`, `--mode`, `--no-gpu`, `--prompt-on`, `--drafts-on`, `--reply-on`, `--npu-int8`) and these:| Option | ||---|---|@@ -32,7 +32,7 @@ bin/x86_64-linux/janas-server qwen3-next.jns| `--test` | serve a chat page for trying it out, on `/test` (below) || `--max-input N` | the longest input a request may have, in tokens, below the context: a longer one gets a 400 (`input_limit_exceeded`) whose error says `input_tokens`, `max_input_tokens`, `excess_tokens` and the parts, and nothing is ever cut to fit || `--warn-input N` | longer inputs are taken, and said on stderr with their parts |-| `--fim-prefix N`, `--fim-suffix N`, `--fim-max N` | completions with a `suffix`, an editor filling in code at its cursor: the tokens before the cursor read at most (2048; 0: all) and the lines after it (8; 0: all); `--fim-max N` the tokens written there at most, whatever the request asks (256; 0: as asked), since an editor asks for thousands and the requests of the next keystrokes wait for them. Over the budget the text before the cursor is cut at a line to three quarters of it, and the start of the window is kept across keystrokes, also when the editor slides its window, so that a keystroke reads only what it changed (see [Filling in code](../README.md#filling-in-code)) |+| `--fim-prefix N`, `--fim-suffix N`, `--fim-max N` | completions with a `suffix`, an editor filling in code at its cursor: the tokens before the cursor read at most (2048; 0: all) and the lines after it (8; 0: all); `--fim-max N` the tokens written there at most, whatever the request asks (256; 0: as asked), since an editor asks for thousands and the requests of the next keystrokes wait for them. Over the budget the text before the cursor is cut at a line to three quarters of it, and the start of the window is kept across keystrokes, also when the editor slides its window, so that a keystroke reads only what it changed (see [code completion](code-completion.md)) || `--metrics FILE`, `--progress S` | JSON lines of what every reply costs, and progress lines while a long prompt is read (see [Watching a long prompt](chat.md#watching-a-long-prompt)); `--verbose` prints progress every 30 s || `--no-mcp` | refuse tools of type `mcp` in `/v1/responses`: no connection leaves the server on a request's word (below) || `--keep N` | conversations kept computed besides the one in use (8; 0: none), so that clients taking turns, or a client's requests on the side for titles and tags, do not have their conversations read again from the start |diff --git a/include/janas/llm.bi b/include/janas/llm.biindex 07cf5db..02c81d5 100644--- a/include/janas/llm.bi+++ b/include/janas/llm.bi@@ -177,6 +177,19 @@ declare function janas_llm_open(byval path as const zstring ptr, _byval p as const janas_llm_params ptr, _byval out as janas_llm ptr ptr) as longdeclare sub janas_llm_close(byval llm as janas_llm ptr)+'' The memory a model would take before opening it (see llm.h): fixed,+'' whatever its expert cache, and experts, a cache holding every expert;+'' either pointer may be 0.+declare function janas_llm_estimate(byval path as const zstring ptr, _+ byval p as const janas_llm_params ptr, _+ byval fixed as ulongint ptr, _+ byval experts as ulongint ptr) as long+'' The memory an open model holds: its resident weights, its expert cache,+'' the keys and values of its context; either pointer may be 0.+declare function janas_llm_memory(byval llm as const janas_llm ptr, _+ byval resident as ulongint ptr, _+ byval cache as ulongint ptr, _+ byval kv as ulongint ptr) as long'' The model's multi-token prediction file beside it (see llm.h), its path'' in out (cap bytes); JANAS_LLM_EOPEN when there is none.declare function janas_llm_find_mtp(byval model_path as const zstring ptr, _@@ -218,6 +231,13 @@ declare function janas_llm_attn_scores(byval llm as const janas_llm ptr) as longdeclare function janas_llm_preload(byval llm as const janas_llm ptr, _byval done as longint ptr, _byval total as longint ptr) as long+'' The NPU's preparation: 1 while its graphs are made (done of total, total+'' 0 when not known ahead, seconds since it began), 0 otherwise (seconds the+'' session's preparations took); callable from another thread.+declare function janas_llm_npu_preparing(byval llm as const janas_llm ptr, _+ byval done as long ptr, _+ byval total as long ptr, _+ byval seconds as double ptr) as long'' Embeddings (models such as Qwen3-Embedding): the vector's length (0: the'' model gives none), and the vector of a text, of unit length.diff --git a/include/janas/llm.h b/include/janas/llm.hindex 9e9963e..2d790f4 100644--- a/include/janas/llm.h+++ b/include/janas/llm.h@@ -144,6 +144,26 @@ JANAS_LLM_API int32_t janas_llm_open(const char *path,janas_llm **out);JANAS_LLM_API void janas_llm_close(janas_llm *llm);+/*+ * The memory a model would take, before opening it, with the parameters+ * janas_llm_open would get (n_ctx, mtp_path; p may be NULL): *fixed, what+ * it needs whatever its expert cache - the resident weights, the keys and+ * values of n_ctx tokens, the attention's partial results, a pass's+ * scratch, an MTP file - and *experts, an expert cache holding every expert+ * (a dense model needs all of it: its feed-forward weights are read at+ * every token, in order). The reckoning janas_llm_open makes for its+ * automatic cache_bytes. Either pointer may be NULL.+ */+JANAS_LLM_API int32_t janas_llm_estimate(const char *path,+ const struct janas_llm_params *p,+ uint64_t *fixed, uint64_t *experts);+/* The memory an open model holds: its resident weights, its expert cache+ (all of it allocated, filled as experts are read), and the keys and+ values of its context with their scales (allocated for all of n_ctx,+ filled as the context grows). Either pointer may be NULL. */+JANAS_LLM_API int32_t janas_llm_memory(const janas_llm *llm, uint64_t *resident,+ uint64_t *cache, uint64_t *kv);+/** The model's multi-token prediction file, looked for beside it: a .jns in* the same directory that fits the model by its header - Gemma 4's@@ -226,6 +246,21 @@ JANAS_LLM_API int32_t janas_llm_attn_scores(const janas_llm *llm);JANAS_LLM_API int32_t janas_llm_preload(const janas_llm *llm, int64_t *done,int64_t *total);+/*+ * The NPU's preparation. The first passes it takes in a session, the+ * blocks of a prompt, wait while it is made ready: the weights it reads+ * copied in eight bits and its graphs compiled, seconds to a minute (about+ * a minute for Qwen3-4B on a Core Ultra 9 185H). 1 while that goes on, with+ * *done of *total graphs made (*total 0 when not known ahead) and *seconds+ * since it began; 0 otherwise, *seconds then the time the session's+ * preparations took. Callable from another thread while the engine works,+ * as janas_llm_preload, so that a front end can show it; without an NPU 0+ * and zeros.+ */+JANAS_LLM_API int32_t janas_llm_npu_preparing(const janas_llm *llm,+ int32_t *done, int32_t *total,+ double *seconds);+/* A short description of the model ("qwen3next, 48 layers, ..."). Writes atmost cap bytes, NUL-terminated; *len gets the full length. */JANAS_LLM_API int32_t janas_llm_describe(const janas_llm *llm, char *buf,diff --git a/src/bench/main.c b/src/bench/main.cindex 58fbc83..e7763bf 100644--- a/src/bench/main.c+++ b/src/bench/main.c@@ -11,6 +11,15 @@* [--prompt <tokens>] [--gen <tokens>] [--ctx <tokens>]* [--cache <GiB>] [--reserve <GiB>]* [--rounds <n>] (default 3, alternating the order)+ * [--no-npu] (without the NPU, as JANAS_NPU=0;+ * with one, its configurations are measured too)+ * [--prompt-on <devices>] [--drafts-on <devices>]+ * [--reply-on <devices>] (as in janas-chat: the+ * devices the engine may choose for each kind of pass;+ * the rows measured are the configurations it may+ * choose for some kind)+ * [--npu-int8] (the NPU's rows with eight-bit+ * activations)* [--settle <seconds>] (after the warm-up, wait up to* that long for the cache's background filling to end:* the configurations measured on a warm cache, as a@@ -44,6 +53,7 @@#include <sys/utsname.h>#include <time.h>+#include "common/devices.h"#include "common/env_names.h"#include "common/model_pick.h"#include "common/sysinfo.h"@@ -53,6 +63,7 @@#include "llm/expert_cache.h"#include "llm/generate.h"#include "llm/gpu.h"+#include "llm/tuner.h"#ifndef JANAS_VERSION#define JANAS_VERSION "unknown"@@ -132,10 +143,13 @@ static int measure(struct janas_llm_model *m, const int32_t *prompt,struct janas_llm_session *s = janas_llm_session_create(m, &o);if (!s || janas_llm_session_append(s, prompt, n_prompt) != 0)return -1;- double t0 = now();+ /* without the NPU's compilations (a matrix's first block, once a+ session): said apart in the report */+ double k0 = janas_llm_model_npu_compile_seconds(m), t0 = now();if (janas_llm_session_prefill(s) != 0)return -1;double t1 = now();+ t0 += janas_llm_model_npu_compile_seconds(m) - k0;for (uint32_t i = 0; i < n_gen; i++) {int32_t t;if (janas_llm_session_next(s, &t) != 0)@@ -197,9 +211,13 @@ int main(int argc, char **argv)"usage: janas-bench [<model>] [--models <dir>] ""[--mtp <file> | --no-mtp] [--prompt <tokens>] ""[--gen <tokens>] [--ctx <tokens>] [--cache <GiB>] "- "[--reserve <GiB>] [--rounds <n>] [--settle <seconds>]\n"+ "[--reserve <GiB>] [--rounds <n>] [--settle <seconds>] "+ "[--no-npu] [--prompt-on <devices>] [--drafts-on <devices>] "+ "[--reply-on <devices>] [--npu-int8]\n""<model>: a .jns file, or a name of the models Janas knows "- "(downloaded if it is not there yet); none: the list\n");+ "(downloaded if it is not there yet); none: the list\n"+ "<devices>: auto (default), cpu, gpu, npu, npu+gpu (both in "+ "each pass), or a list apart by commas to choose from\n");return 2;}struct janas_llm_params p;@@ -212,8 +230,9 @@ int main(int argc, char **argv)const char *model = NULL, *models = NULL;int no_mtp = 0;static const char *const options[] = {- "--mtp", "--no-mtp", "--models", "--prompt", "--gen",- "--ctx", "--rounds", "--cache", "--reserve", "--settle"};+ "--mtp", "--no-mtp", "--models", "--prompt", "--gen",+ "--ctx", "--rounds", "--cache", "--reserve", "--settle",+ "--no-npu", "--prompt-on", "--drafts-on", "--reply-on", "--npu-int8"};for (int i = 1; i < argc; i += 2) {const char *a = argv[i], *v = i + 1 < argc ? argv[i + 1] : NULL;char why[200] = "";@@ -229,6 +248,23 @@ int main(int argc, char **argv)i--;continue;}+ if (strcmp(a, "--no-npu") == 0) {+ setenv("JANAS_NPU", "0", 1); /* read when the model opens */+ i--;+ continue;+ }+ if (strcmp(a, "--npu-int8") == 0) {+ setenv("JANAS_NPU_A8", "1", 1); /* so is this */+ i--;+ continue;+ }+ int dk = janas_devices_option(a, v, why, sizeof why);+ if (dk < 0) {+ fprintf(stderr, "janas-bench: %s\n", why);+ return 2;+ }+ if (dk > 0)+ continue;if (strcmp(a, "--mtp") == 0 && v)p.mtp_path = v;else if (strcmp(a, "--models") == 0 && v)@@ -326,7 +362,24 @@ int main(int argc, char **argv)out("GPU: %s\n", janas_gpu_name(gpu));elseout("GPU: none usable: %s\n", janas_llm_model_gpu_why(m));+ const char *npu = janas_llm_model_npu_name(m);+ if (npu)+ out("NPU: %s\n", npu);+ else+ out("NPU: none usable: %s\n", janas_llm_model_npu_why(m));out("model: %s\n", desc);+ /* the user's devices, as this machine has them (the engine said on+ stderr what it could not take) */+ int on_p = janas_llm_model_devices(m, 2),+ on_d = janas_llm_model_devices(m, 1),+ on_r = janas_llm_model_devices(m, 0);+ if (on_p || on_d || on_r) {+ char dp[64], dd[64], dr[64];+ janas_devices_name(on_p, dp, sizeof dp);+ janas_devices_name(on_d, dd, sizeof dd);+ janas_devices_name(on_r, dr, sizeof dr);+ out("devices: prompts %s, drafts %s, replies %s\n", dp, dd, dr);+ }/* the prompt: the text once, repeated only when more is asked for */struct janas_tokenizer *tok = janas_llm_internal_tokenizer(llm);@@ -391,16 +444,46 @@ int main(int argc, char **argv)}}- int th[16], gp[16];- int nc = janas_llm_model_candidates(m, th, gp, 16);- struct run sum[16];+ int th[JANAS_TUNE_MAX_CANDS], gp[JANAS_TUNE_MAX_CANDS],+ np[JANAS_TUNE_MAX_CANDS];+ int nc = janas_llm_model_candidates(m, th, gp, np, JANAS_TUNE_MAX_CANDS);+ /* the rows: the configurations the engine may choose for some kind of+ pass, every one unless the devices are limited - the NPU's for+ blocks only, the GPU's for replies only where it takes single+ tokens */+ int rows[JANAS_TUNE_MAX_CANDS], n_rows = 0, npu_row = -1;+ int gpu_one = gpu && janas_gpu_min_n(gpu) <= 1;+ for (int c = 0; c < nc; c++) {+ rows[c] = !on_p || on_p >> (gp[c] | np[c] << 1) & 1;+ if (!np[c])+ rows[c] |= (!on_d || on_d >> gp[c] & 1) ||+ ((!gp[c] || gpu_one) && (!on_r || on_r >> gp[c] & 1));+ n_rows += rows[c];+ if (rows[c] && np[c] && npu_row < 0)+ npu_row = c;+ }+ /* the NPU's copies of the weights and its graphs made (and with+ --npu-int8 the scales of the activations taken) before the rows, as+ a chat has them after its first prompt */+ if (npu_row >= 0) {+ out("warming up the NPU...\n");+ janas_llm_model_force(m, npu_row);+ if (measure(m, prompt, n_prompt, n_gen, NULL, &d) != 0) {+ out("generation failed\n");+ return 1;+ }+ janas_llm_model_force(m, -1);+ }+ struct run sum[JANAS_TUNE_MAX_CANDS];memset(sum, 0, sizeof(sum));uint64_t drafted = 0, accepted = 0, drafted_s = 0, accepted_s = 0;/* several rounds, every other one in reverse order: heat and cachedrift affect every configuration alike */- out("measuring %d configurations, %d rounds...\n", nc, rounds);+ out("measuring %d configurations, %d rounds...\n", n_rows, rounds);for (int k = 0; k < rounds * nc; k++) {int c = (k / nc) % 2 ? nc - 1 - k % nc : k % nc;+ if (!rows[c])+ continue;janas_llm_model_force(m, c);struct janas_expert_cache_stats s0, s1;janas_expert_cache_stats(janas_llm_model_cache(m), &s0);@@ -428,8 +511,13 @@ int main(int argc, char **argv)for (int c = 0; c < nc; c++) {const struct run *r = &sum[c];char name[64];+ if (!rows[c])+ continue;snprintf(name, sizeof(name), "%d threads%s", th[c],- gp[c] ? " + GPU" : "");+ gp[c] && np[c] ? " + GPU + NPU"+ : gp[c] ? " + GPU"+ : np[c] ? " + NPU"+ : "");char mt[32] = "", ms[32] = "";if (has_mtp) {snprintf(mt, sizeof(mt), "%.1f tok/s", r->mtp);@@ -444,7 +532,7 @@ int main(int argc, char **argv)GPU of no help where it read the prompt 5.2 times faster) */int cpu_rows = 0;for (int c = 0; c < nc; c++)- cpu_rows += !gp[c];+ cpu_rows += rows[c] && !gp[c];if (cpu_rows && janas_llm_model_gpu_prompts(m))out("note: in every row the GPU reads a prompt's blocks of %d ""tokens or more (the fast prompt); \"+ GPU\" also gives it a "@@ -454,6 +542,28 @@ int main(int argc, char **argv)? ", from 2 tokens on: a reply's single tokens are the ""CPU's in every row": "");+ if (npu_row >= 0)+ out("note: \"+ NPU\": the NPU computes the products of blocks of "+ "%s tokens or more whose weights stay in memory (attention, "+ "recurrent layers, shared experts, a dense model's "+ "feed-forwards; a dense model's layers whole where nine in ten "+ "fit%s), the CPU%s the "+ "rest%s; its preparation (copies of the weights, graphs: %.1f s "+ "in all) is in a warm-up of its own, not in the rows\n",+ getenv("JANAS_NPU_MIN_N") ? getenv("JANAS_NPU_MIN_N") : "64",+ getenv("JANAS_NPU_A8") && atoi(getenv("JANAS_NPU_A8")) > 0+ ? ", with eight-bit activations"+ : "",+ janas_llm_model_gpu_prompts(m) ? " and the GPU's fast prompt" : "",+ janas_llm_model_gpu_prompts(m)+ ? " (--prompt-on npu for the CPU and the NPU alone)"+ : "",+ janas_llm_model_npu_compile_seconds(m));+ if (npu_row >= 0 && !janas_llm_model_npu_auto(m) && !on_p)+ out("note: the engine does not give the NPU this model's blocks by "+ "itself: in products on Gemma 4 the NPU's answers measured below "+ "the CPU's against llama.cpp's (26B-A4B, E2B); --prompt-on npu "+ "asks for it\n");janas_llm_model_force(m, -1);char tune[512];int32_t tn;@@ -465,10 +575,11 @@ int main(int argc, char **argv)int row[3];for (int k = 0; k < 3; k++) {int t = janas_llm_model_threads(m, k),- g = (janas_llm_model_gpu_used(m) >> k) & 1;+ g = (janas_llm_model_gpu_used(m) >> k) & 1,+ u = (janas_llm_model_npu_used(m) >> k) & 1;row[k] = 0;for (int c = 0; c < nc; c++)- if (th[c] == t && gp[c] == g)+ if (rows[c] && th[c] == t && gp[c] == g && np[c] == u)row[k] = c;}out("\nresult: prefill %.1f tok/s, decode %.1f tok/s", sum[row[2]].prefill,diff --git a/src/chat/main.c b/src/chat/main.cindex f640b78..bd6c019 100644--- a/src/chat/main.c+++ b/src/chat/main.c@@ -29,6 +29,7 @@#include <time.h>#include <unistd.h>+#include "common/devices.h"#include "common/env_names.h"#include "common/model_pick.h"#include "common/sysinfo.h"@@ -115,6 +116,39 @@ static struct {atomic_int busy, stop, done, total;} prep;+/*+ * The NPU made ready in sight. The first blocks the NPU reads in a session+ * wait while its weights are copied and its graphs compiled - seconds to a+ * minute, inside janas_llm_chat_next, where the chat draws nothing - so a+ * watcher draws the footer meanwhile, which says how far it is+ * (janas_llm_npu_preparing). Only while the chat is in the engine+ * (in_engine), and under lock, which the chat takes to come out: it never+ * draws beside the chat's own writing, and the footer asks the engine then+ * only what may be asked from aside, as while the system message is read+ * ahead.+ */+static struct {+ pthread_t th;+ int on; /* started, not joined */+ pthread_mutex_t lock;+ atomic_int in_engine, stop;+ const janas_llm *llm;+} watch = {.lock = PTHREAD_MUTEX_INITIALIZER};++/* the chat goes into the engine for a pass that may make the NPU ready,+ and comes out of it: the watcher may draw in between */+static void engine_in(void)+{+ atomic_store(&watch.in_engine, 1);+}++static void engine_out(void)+{+ pthread_mutex_lock(&watch.lock);+ atomic_store(&watch.in_engine, 0);+ pthread_mutex_unlock(&watch.lock);+}+static int prep_pct(void){int t = atomic_load(&prep.total), d = atomic_load(&prep.done);@@ -138,7 +172,7 @@ static void footer(const janas_llm *llm, const janas_llm_chat *c,/* while the system message is read ahead, the chat and the engine'ssettings are the reading thread's: only the cache's filling, whichis made to be watched from aside, is asked */- int reading = atomic_load(&prep.busy);+ int reading = atomic_load(&prep.busy) || atomic_load(&watch.in_engine);struct janas_llm_chat_stats s = {.size = sizeof(s)};int have = c && !reading && janas_llm_chat_stats(c, &s) == JANAS_LLM_OK;int32_t used = 0, most = 0;@@ -156,6 +190,15 @@ static void footer(const janas_llm *llm, const janas_llm_chat *c,foot_add(part, &np, 2, "%d/%d experts", used, most);} else if (!state) /* kept longest: it is what holds the reply back */foot_add(part, &np, 9, "reading the tools ahead %d%%", prep_pct());+ int32_t nd = 0, nt = 0;+ double ns = 0;+ if (janas_llm_npu_preparing(llm, &nd, &nt, &ns) == 1) { /* held back too */+ if (nt > 0)+ foot_add(part, &np, 9, "preparing the NPU %d/%d, %.0f s", (int)nd,+ (int)nt, ns);+ else+ foot_add(part, &np, 9, "preparing the NPU, %.0f s", ns);+ }if (have && s.context_size)foot_add(part, &np, 4, "context %u/%u", s.context_used, s.context_size);/* only where it is on, and only where it means something: it is the one@@ -221,15 +264,22 @@ static const janas_llm_chat *idle_chat;static int footer_idle(void){- static int shown = -2;+ static int shown = -2, shown_npu = -2;int64_t done = 0, total = 0;janas_llm_preload(idle_llm, &done, &total);int pct = total > done ? (int)(100 * done / total) : -1;/* and the reading ahead's share, while it goes */pct = pct * 1000 + (atomic_load(&prep.busy) ? prep_pct() : 999);- if (pct == shown)+ /* and the NPU's preparation, a second at a time */+ int32_t nd = 0;+ double ns = 0;+ int npu = janas_llm_npu_preparing(idle_llm, &nd, NULL, &ns) == 1+ ? (int)nd * 10000 + (int)ns+ : -1;+ if (pct == shown && npu == shown_npu)return 0;shown = pct;+ shown_npu = npu;footer(idle_llm, idle_chat, NULL);return 1;}@@ -308,6 +358,22 @@ static void usage(void)"reading them\n"" --no-gpu never give the GPU work, whatever the mode ""says\n"+ " --prompt-on <devices>\n"+ " what reads the prompts: auto (default: what\n"+ " measures fastest here), cpu, gpu, npu, npu+gpu\n"+ " (both in each pass), or a list apart by commas\n"+ " for the engine to choose from, such as npu,gpu;\n"+ " the CPU takes part in every pass, the NPU in\n"+ " blocks of 64 tokens and more; a choice wins\n"+ " over the mode\n"+ " --drafts-on <devices>\n"+ " the same for the passes that check guessed\n"+ " tokens (2 to 16)\n"+ " --reply-on <devices>\n"+ " the same for a reply's tokens, one at a time\n"+ " --npu-int8 the NPU reads prompts with eight-bit\n"+ " activations: faster, a little less exact\n"+ " (dense Qwen3 models)\n"" --mcp-config <file>\n"" the MCP servers whose tools the model may call\n"" (default ~/.config/janas/mcp.json, in the\n"@@ -622,7 +688,9 @@ static void prep_start(janas_llm_chat *c)return;int32_t d = 0, t = 0;double t0 = now_ms();+ engine_in(); /* the first block: the NPU may be made ready in it */int r = janas_llm_chat_prepare(c, &d, &t);+ engine_out();if (r < 0) {prep_say(T_WARN(&term),"the system message could not be read "@@ -682,6 +750,49 @@ static void prep_wait(const janas_llm *llm, int stop)prep.on = 0;}+static void *watch_main(void *arg)+{+ (void)arg;+ while (!atomic_load(&watch.stop)) {+ struct timespec ts = {0, 250 * 1000 * 1000};+ nanosleep(&ts, NULL);+ if (!atomic_load(&watch.in_engine) ||+ janas_llm_npu_preparing(watch.llm, NULL, NULL, NULL) != 1)+ continue;+ pthread_mutex_lock(&watch.lock);+ if (atomic_load(&watch.in_engine))+ footer(watch.llm, NULL, "");+ pthread_mutex_unlock(&watch.lock);+ }+ return NULL;+}++static void watch_start(const janas_llm *llm)+{+ watch.llm = llm;+ atomic_store(&watch.stop, 0);+ watch.on = pthread_create(&watch.th, NULL, watch_main, NULL) == 0;+}++static void watch_stop(void)+{+ if (!watch.on)+ return;+ atomic_store(&watch.stop, 1);+ pthread_join(watch.th, NULL);+ watch.on = 0;+}++/* janas_llm_chat_next, the watcher free to draw while it runs */+static int32_t engine_next(janas_llm_chat *c, char *buf, int32_t cap,+ int32_t *len)+{+ engine_in();+ int32_t rc = janas_llm_chat_next(c, buf, cap, len);+ engine_out();+ return rc;+}+/** A service's layout in the user's language, asked of the model on the* side (the conversation saved and put back): once a layout and language,@@ -834,21 +945,27 @@ struct chat_opts { /* where the words land: main keeps them, this names them */int *all_tools;int *profile; /* 1: the catalog's fast profile */int *tune; /* 1: measure again (--tune), -1: never (--no-tune) */+ /* --prompt-on, --drafts-on, --reply-on as masks (common/devices.h; 0:+ as the engine chooses) and --npu-int8, put in the engine's variables+ when read, for the next model to open */+ int *devices;+ int *npu_int8;};/* every option, for the nearest to one mistyped: the first N_ALONE standalone, the others take a value */-#define N_ALONE 14+#define N_ALONE 15static const char *const OPTIONS[] = {- "--no-spec", "--stats", "--no-markdown", "--no-gpu",- "--no-preload", "--no-recap", "--no-mtp", "--no-mcp",- "--no-services", "--all-tools", "--mcp-auto", "--mcp-instructions",- "--tune", "--no-tune", "--mtp", "--draft",- "--think", "--mode", "--ctx", "--cache",- "--reserve", "--bits", "--attention", "--system",- "--mcp-config", "--progress", "--temp", "--top-k",- "--top-p", "--min-p", "--seed", "--max",- "--head", "--profile", "--models"};+ "--no-spec", "--stats", "--no-markdown", "--no-gpu",+ "--no-preload", "--no-recap", "--no-mtp", "--no-mcp",+ "--no-services", "--all-tools", "--mcp-auto", "--mcp-instructions",+ "--tune", "--no-tune", "--npu-int8", "--mtp",+ "--draft", "--think", "--mode", "--ctx",+ "--cache", "--reserve", "--bits", "--attention",+ "--system", "--mcp-config", "--progress", "--temp",+ "--top-k", "--top-p", "--min-p", "--seed",+ "--max", "--head", "--profile", "--models",+ "--prompt-on", "--drafts-on", "--reply-on"};#define N_OPTIONS (sizeof OPTIONS / sizeof *OPTIONS)/* v of option a as a whole number or a number within limits; on a@@ -952,6 +1069,11 @@ static int take_options(int n, char **w, struct chat_opts *o, char *why,*o->tune = a[2] == 't' ? 1 : -1;continue;}+ if (strcmp(a, "--npu-int8") == 0) {+ *o->npu_int8 = 1;+ setenv("JANAS_NPU_A8", "1", 1); /* read when the model opens */+ continue;+ }int valued = 0;for (size_t j = N_ALONE; j < N_OPTIONS && !valued; j++)valued = strcmp(a, OPTIONS[j]) == 0;@@ -965,7 +1087,11 @@ static int take_options(int n, char **w, struct chat_opts *o, char *why,return -1;}i++;- if (strcmp(a, "--mtp") == 0)+ if ((k = janas_devices_option(a, v, why, why_len)) != 0) {+ if (k < 0)+ return -1;+ o->devices[k - 1] = janas_devices_mask(v, why, why_len);+ } else if (strcmp(a, "--mtp") == 0)o->mp->mtp_path = v;else if (strcmp(a, "--draft") == 0)o->mp->draft_path = v;@@ -1222,6 +1348,14 @@ static void conf_write(const char *path, const struct chat_opts *o)fprintf(f, "--no-markdown\n");if (!*o->gpu)fprintf(f, "--no-gpu\n");+ for (int k = 0; k < JANAS_DEVICES_OPTIONS; k++)+ if (o->devices[k]) {+ char nm[64];+ janas_devices_name(o->devices[k], nm, sizeof nm);+ fprintf(f, "%s %s\n", janas_devices_options[k], nm);+ }+ if (*o->npu_int8)+ fprintf(f, "--npu-int8\n");if (*o->mcp_config)fprintf(f, "--mcp-config %s\n", *o->mcp_config);if (!*o->mcp)@@ -1481,8 +1615,7 @@ static int show_reply(const janas_llm *llm, janas_llm_chat *c, int markdown,struct janas_md md;md_init(&md, &term, markdown);term_puts(&term, T_MODEL(&term));- while ((rc = janas_llm_chat_next(c, piece, sizeof(piece), &len)) ==- JANAS_LLM_OK) {+ while ((rc = engine_next(c, piece, sizeof(piece), &len)) == JANAS_LLM_OK) {/* the reasoning in grey: the colour changes only where thereasoning starts and ends */int th = janas_llm_chat_thinking(c);@@ -1559,6 +1692,19 @@ static int show_reply(const janas_llm *llm, janas_llm_chat *c, int markdown,sess_seconds += st.output_seconds;}}+ /* the NPU made ready meanwhile: said once, so a slow first reply is+ understood */+ static double npu_said;+ double ns = 0;+ if (term.tty && janas_llm_npu_preparing(llm, NULL, NULL, &ns) == 0 &&+ ns > npu_said + 0.5) {+ term_gap(&term);+ term_printf(&term,+ "%s[the NPU made ready for this model in %.0f s, "+ "once a session]%s\n",+ T_DIM(&term), ns - npu_said, T_RESET(&term));+ npu_said = ns;+ }if (stats) {term_gap(&term);report(c);@@ -1602,13 +1748,14 @@ int main(int argc, char **argv)int gpu = 1; /* the GPU may be given work, if there is one */const char *mcp_config = NULL; /* NULL: the default file */int mcp = 1, mcp_auto = 0, mcp_instructions = 0, services = 1, no_mtp = 0;- int all_tools = 0, profile = 0, tune = 0;+ int all_tools = 0, profile = 0, tune = 0, npu_int8 = 0;+ int devices[JANAS_DEVICES_OPTIONS] = {0, 0, 0};static char mtp_found[4096];struct chat_opts o = {&mp, &cp, &system_arg, &stats, &markdown,&gpu, &mcp_config, &mcp, &mcp_auto, &mcp_instructions,&services, &no_mtp, mtp_found, &all_tools, &profile,- &tune};+ &tune, devices, &npu_int8};/** The settings in layers, each over the one before: the catalog's* profile for the model, the chat's own file, the model's file, the@@ -1852,6 +1999,7 @@ int main(int argc, char **argv)idle_llm = llm;idle_chat = c;line_idle = footer_idle;+ watch_start(llm);} elsefprintf(stderr, "%s\n/help for the commands\n", desc);prep_start(c);@@ -2088,6 +2236,7 @@ int main(int argc, char **argv)footer(llm, c, NULL);}prep_wait(llm, 1);+ watch_stop();failed_clear();free(msg);free(system);diff --git a/src/common/aligned.h b/src/common/aligned.hindex 47dc00f..b6e1b74 100644--- a/src/common/aligned.h+++ b/src/common/aligned.h@@ -72,8 +72,18 @@ static inline void janas_aligned_free(void *p)#else+/* aligned_alloc wants a size that is a multiple of align (C11 7.22.3.1):+ glibc takes any, ThreadSanitizer's interceptor refuses it (test_aligned's+ 1 byte on 8), so the size is rounded up - at most align - 1 bytes more */static inline void *janas_aligned_alloc(size_t align, size_t size){+ if (align && size % align) {+ if (size > SIZE_MAX - align) {+ errno = ENOMEM;+ return NULL;+ }+ size += align - size % align;+ }return aligned_alloc(align, size);}diff --git a/src/common/devices.c b/src/common/devices.cnew file mode 100644index 0000000..b75b620--- /dev/null+++ b/src/common/devices.c@@ -0,0 +1,99 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * devices.c - the devices of a kind of pass, as written (devices.h).+ */+#include "devices.h"++#include <ctype.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++const char *const janas_devices_options[JANAS_DEVICES_OPTIONS] = {+ "--prompt-on", "--drafts-on", "--reply-on"};+const char *const janas_devices_vars[JANAS_DEVICES_OPTIONS] = {+ "JANAS_PROMPT_ON", "JANAS_DRAFTS_ON", "JANAS_REPLY_ON"};++int janas_devices_mask(const char *spec, char *why, size_t len)+{+ if (!spec || !*spec || !strcmp(spec, "auto"))+ return 0;+ int mask = 0;+ const char *p = spec;+ for (;;) {+ /* one alternative: words joined by '+' */+ int combo = 0;+ for (;;) {+ char w[8];+ size_t n = 0;+ while (p[n] && p[n] != '+' && p[n] != ',')+ n++;+ if (n == 0 || n >= sizeof w) {+ snprintf(why, len,+ "\"%s\": an empty or unknown device (cpu, gpu, npu, "+ "joined by + or apart by commas, or auto)",+ spec);+ return -1;+ }+ for (size_t i = 0; i < n; i++)+ w[i] = (char)tolower((unsigned char)p[i]);+ w[n] = 0;+ if (!strcmp(w, "gpu"))+ combo |= JANAS_DEV_GPU;+ else if (!strcmp(w, "npu"))+ combo |= JANAS_DEV_NPU;+ else if (strcmp(w, "cpu")) {+ snprintf(why, len,+ "\"%s\": \"%s\" is not a device (cpu, gpu, npu)", spec,+ w);+ return -1;+ }+ p += n;+ if (*p != '+')+ break;+ p++;+ }+ mask |= 1 << combo;+ if (!*p)+ return mask;+ p++; /* the comma: another alternative follows, or the error */+ }+}++void janas_devices_name(int mask, char *buf, size_t len)+{+ static const char *name[JANAS_DEV_COMBOS] = {"cpu", "gpu", "npu",+ "npu+gpu"};+ size_t o = 0;+ buf[0] = 0;+ if (!mask) {+ snprintf(buf, len, "auto");+ return;+ }+ for (int c = 0; c < JANAS_DEV_COMBOS && o < len; c++)+ if (mask >> c & 1)+ o += (size_t)snprintf(buf + o, len - o, "%s%s", o ? "," : "",+ name[c]);+}++int janas_devices_option(const char *option, const char *spec, char *why,+ size_t len)+{+ for (int k = 0; k < JANAS_DEVICES_OPTIONS; k++) {+ if (strcmp(option, janas_devices_options[k]))+ continue;+ char r[200];+ if (!spec) {+ snprintf(why, len, "%s wants a value", option);+ return -1;+ }+ if (janas_devices_mask(spec, r, sizeof r) < 0) {+ snprintf(why, len, "%s: %s", option, r);+ return -1;+ }+ setenv(janas_devices_vars[k], spec, 1);+ return k + 1;+ }+ return 0;+}diff --git a/src/common/devices.h b/src/common/devices.hnew file mode 100644index 0000000..af20193--- /dev/null+++ b/src/common/devices.h@@ -0,0 +1,38 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * devices.h - the devices a kind of pass may run on, as the user writes+ * them (--prompt-on, --drafts-on, --reply-on; JANAS_PROMPT_ON,+ * JANAS_DRAFTS_ON, JANAS_REPLY_ON): "auto", or alternatives apart by+ * commas, each the devices that work together joined by '+' - "npu",+ * "npu,gpu" (whichever measures faster), "npu+gpu" (both in the same+ * pass), "cpu" (no accelerator). The CPU takes part in every pass.+ */+#ifndef JANAS_COMMON_DEVICES_H+#define JANAS_COMMON_DEVICES_H++#include <stddef.h>++/* a combination of accelerators: their bits; 0 the CPU alone */+enum { JANAS_DEV_GPU = 1, JANAS_DEV_NPU = 2, JANAS_DEV_COMBOS = 4 };++/* The combinations spec allows, bit c for combination c: 0 for "auto" (or+ NULL, empty: any), -1 with the reason in why if it does not read. */+int janas_devices_mask(const char *spec, char *why, size_t len);++/* A mask as the user would write it ("npu,npu+gpu"; "auto" for 0). */+void janas_devices_name(int mask, char *buf, size_t len);++/* The programs' options for them (janas-chat, janas-server, janas-bench),+ in the order of their variables: prompts, drafts, replies. */+#define JANAS_DEVICES_OPTIONS 3+extern const char *const janas_devices_options[JANAS_DEVICES_OPTIONS];+extern const char *const janas_devices_vars[JANAS_DEVICES_OPTIONS];++/* option one of them: spec checked and put in its variable, read when a+ model opens, and its index + 1; another option: 0; a spec that does not+ read: -1, the reason in why. */+int janas_devices_option(const char *option, const char *spec, char *why,+ size_t len);++#endifdiff --git a/src/common/env_names.c b/src/common/env_names.cindex 5c60497..7cd478b 100644--- a/src/common/env_names.c+++ b/src/common/env_names.c@@ -15,12 +15,22 @@ extern char **environ;const char *const JANAS_ENV_NAMES[] = {"JANAS_ALPHAVANTAGE_KEY","JANAS_API_KEY",+ "JANAS_ANA_COARSE",+ "JANAS_ANA_FRAC",+ "JANAS_ANA_FRAMES",+ "JANAS_ANA_FRAMES_MAX",+ "JANAS_ANA_GRADE",+ "JANAS_ANA_GULOW",+ "JANAS_ANA_MODE",+ "JANAS_ANA_STATS",+ "JANAS_ANA_XSTATS","JANAS_ARENA_HUGE","JANAS_ATTN","JANAS_ATTN_FUSE","JANAS_ATTN_SKIPSTAT","JANAS_AVIATIONSTACK_KEY","JANAS_BLOCK_THREADS",+ "JANAS_DRAFTS_ON","JANAS_DRAFT_VOCAB","JANAS_EXPERT_BITS","JANAS_EXPERTS",@@ -59,13 +69,33 @@ const char *const JANAS_ENV_NAMES[] = {"JANAS_ALPHAVANTAGE_KEY","JANAS_GPU_VERBOSE","JANAS_GPU_XCOH","JANAS_HEAD_BITS",+ "JANAS_JANET_FFN",+ "JANAS_JANET_REC",+ "JANAS_JANET_REC_LAYERS","JANAS_KERNELS","JANAS_KV","JANAS_LOCATION","JANAS_METRICS","JANAS_METRICS_EVERY","JANAS_MODELS",+ "JANAS_NEURON_LEVELS","JANAS_NOMINATIM_URL",+ "JANAS_NPU",+ "JANAS_NPU_A8",+ "JANAS_NPU_A8_CALIB",+ "JANAS_NPU_A8_SITES",+ "JANAS_NPU_ALWAYS",+ "JANAS_NPU_AWAKE_US",+ "JANAS_NPU_CACHE",+ "JANAS_NPU_CHECK",+ "JANAS_NPU_LAYERS",+ "JANAS_NPU_LAYERS_MB",+ "JANAS_NPU_LOADER",+ "JANAS_NPU_MAX_MB",+ "JANAS_NPU_MIN_N",+ "JANAS_NPU_SPIN",+ "JANAS_NPU_STATS",+ "JANAS_NPU_TURBO","JANAS_OSRM_URL","JANAS_OVERPASS_URL","JANAS_OVERPASS_URL2",@@ -75,6 +105,8 @@ const char *const JANAS_ENV_NAMES[] = {"JANAS_ALPHAVANTAGE_KEY","JANAS_PREFETCH_PREFILL","JANAS_PREFILL_BLOCK","JANAS_PROGRESS",+ "JANAS_PROMPT_ON",+ "JANAS_REPLY_ON","JANAS_SHA256_C","JANAS_SWA_RING","JANAS_TRACE",diff --git a/src/common/npu.c b/src/common/npu.cnew file mode 100644index 0000000..ee1c345--- /dev/null+++ b/src/common/npu.c@@ -0,0 +1,987 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * npu.c - the NPU of npu.h, through Level Zero loaded at run time.+ *+ * A product is the graph x (f32) -> FP16 -> x w^T -> f32 -> y, with w a+ * constant: INT8 converted to FP16 and multiplied by its row's scale (the+ * compiler folds the dequantization into the product) or FP16. Each product+ * has its graph, a command list recorded once and a fence; begin executes+ * the list on the NPU's one queue, finish waits on the fence.+ *+ * JANAS_NPU_LOADER names the Level Zero loader to open (default+ * libze_loader.so.1): the NPU's driver may need a newer loader than the+ * system's. ZE_INTEL_NPU_CACHE_SIZE, the driver's, is set to 0 unless set.+ */+#include "npu.h"++#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>++#if defined(__linux__)++#include <dlfcn.h>+#include <errno.h>+#include <pthread.h>+#include <stdatomic.h>+#include <sys/stat.h>+#include <unistd.h>++#include "sha256.h"++#include "npu_ir.h"+#include "npu_ze.h"++#define NPU_MAX_ALLOCS 1024++#define ZE_FUNCS(X) \+ X(zeInit, (uint32_t)) \+ X(zeDriverGet, (uint32_t *, ze_driver_handle_t *)) \+ X(zeDriverGetProperties, (ze_driver_handle_t, ze_driver_properties_t *)) \+ X(zeDeviceGet, (ze_driver_handle_t, uint32_t *, ze_device_handle_t *)) \+ X(zeDeviceGetProperties, (ze_device_handle_t, ze_device_properties_t *)) \+ X(zeContextCreate, \+ (ze_driver_handle_t, const ze_simple_desc_t *, ze_context_handle_t *)) \+ X(zeContextDestroy, (ze_context_handle_t)) \+ X(zeDriverGetExtensionFunctionAddress, \+ (ze_driver_handle_t, const char *, void **)) \+ X(zeMemAllocHost, (ze_context_handle_t, const ze_simple_desc_t *, size_t, \+ size_t, void **)) \+ X(zeMemFree, (ze_context_handle_t, void *)) \+ X(zeCommandQueueCreate, \+ (ze_context_handle_t, ze_device_handle_t, \+ const ze_command_queue_desc_t *, ze_command_queue_handle_t *)) \+ X(zeCommandQueueDestroy, (ze_command_queue_handle_t)) \+ X(zeCommandQueueSynchronize, (ze_command_queue_handle_t, uint64_t)) \+ X(zeCommandQueueExecuteCommandLists, \+ (ze_command_queue_handle_t, uint32_t, ze_command_list_handle_t *, \+ ze_fence_handle_t)) \+ X(zeCommandListCreate, \+ (ze_context_handle_t, ze_device_handle_t, \+ const ze_command_list_desc_t *, ze_command_list_handle_t *)) \+ X(zeCommandListDestroy, (ze_command_list_handle_t)) \+ X(zeCommandListClose, (ze_command_list_handle_t)) \+ X(zeCommandListReset, (ze_command_list_handle_t)) \+ X(zeFenceCreate, (ze_command_queue_handle_t, const ze_simple_desc_t *, \+ ze_fence_handle_t *)) \+ X(zeFenceDestroy, (ze_fence_handle_t)) \+ X(zeFenceHostSynchronize, (ze_fence_handle_t, uint64_t)) \+ X(zeFenceReset, (ze_fence_handle_t))++struct janas_npu {+ void *lib;+#define DECL(f, args) ze_result_t(*f) args;+ ZE_FUNCS(DECL)+#undef DECL+ ze_driver_handle_t drv;+ ze_device_handle_t dev;+ ze_context_handle_t ctx;+ ze_command_queue_handle_t q;+ ze_graph_dditable_ext_t *g;+ uint16_t cmajor, cminor;+ uint32_t driver_version;+ char name[256], *cache;+ void *allocs[NPU_MAX_ALLOCS];+ int nallocs;+ struct janas_npu_mm *mms; /* every product, for destroy */+ int products, cached;+ double compile_s;+ /* keeping the NPU awake (janas_npu_keep_awake): a thread runs a tiny+ product on a queue of its own when the NPU has been idle for+ NPU_AWAKE_NS - the kernel suspends it after 10 ms+ (power/autosuspend_delay_ms), and each wake-up cost a product of 256+ x 12288 x 2048 some 5 ms (10.4-11.6 ms after pauses of 20-40 ms,+ 5.4-6.6 without; 20 Oct 2026) */+ ze_command_queue_handle_t kq;+ struct janas_npu_mm *ka;+ pthread_t ka_thread;+ int ka_started;+ atomic_int ka_on, ka_stop;+ /* off, the thread waits here rather than wake every half millisecond:+ 2000 times a second beside the cores writing a reply */+ pthread_mutex_t ka_mx;+ pthread_cond_t ka_cv;+ atomic_llong last_ns; /* the last submission or wait */+};++/* 1 ms: with 4 the NPU still lost speed after pauses of 40 ms (9.1 ms a+ product against 7.0 with 1 and 11.6 without; 20 Oct 2026);+ JANAS_NPU_AWAKE_US to try others */+#define NPU_AWAKE_NS 1000000LL++/* the keep-awake threads (below), stopped by janas_npu_destroy too */+#define NPU_AWAKE_MAX 8+static struct janas_npu *awake_npus[NPU_AWAKE_MAX];+static pthread_mutex_t awake_lock;+static void stop_awake(struct janas_npu *u);++struct janas_npu_mm {+ struct janas_npu *u;+ struct janas_npu_mm *next;+ ze_graph_handle_t graph;+ ze_command_list_handle_t list;+ ze_fence_handle_t fence;+ ze_command_queue_handle_t q; /* where it runs */+ /* a second binding (janas_npu_mm_bind_alt): the same graph, another+ list recorded with other arguments, its own fence */+ ze_command_list_handle_t alt_list;+ ze_fence_handle_t alt_fence;+ int alt_pending;+ uint8_t *blob; /* a graph from the cache: the driver reads it later */+ int pending;+};++static double now(void)+{+ struct timespec t;+ clock_gettime(CLOCK_MONOTONIC, &t);+ return (double)t.tv_sec + (double)t.tv_nsec * 1e-9;+}++struct janas_npu *janas_npu_create(char *err, size_t err_len)+{+ struct janas_npu *u = calloc(1, sizeof(*u));+ if (!u) {+ snprintf(err, err_len, "out of memory");+ return NULL;+ }+ /* the driver's own cache off, its directory not even made (unless the+ caller set its size): Janas keeps its own (janas_npu_set_cache) */+ setenv("ZE_INTEL_NPU_CACHE_SIZE", "0", 0);+ const char *lib = getenv("JANAS_NPU_LOADER");+ if (!lib || !*lib)+ lib = "libze_loader.so.1";+ u->lib = dlopen(lib, RTLD_NOW | RTLD_LOCAL);+ if (!u->lib) {+ snprintf(err, err_len, "no Level Zero loader (%s)", lib);+ free(u);+ return NULL;+ }+#define LOAD(f, args) \+ if (!(*(void **)&u->f = dlsym(u->lib, #f))) { \+ snprintf(err, err_len, "Level Zero loader without " #f); \+ goto fail; \+ }+ ZE_FUNCS(LOAD)+#undef LOAD+ uint32_t n = 1;+ ze_device_properties_t dp = {.stype = ZE_STYPE_DEVICE_PROPERTIES};+ if (u->zeInit(ZE_INIT_FLAG_VPU_ONLY) || u->zeDriverGet(&n, &u->drv) || !n ||+ (n = 1, u->zeDeviceGet(u->drv, &n, &u->dev)) || !n ||+ u->zeDeviceGetProperties(u->dev, &dp) ||+ dp.type != ZE_DEVICE_TYPE_VPU) {+ snprintf(err, err_len,+ "no NPU (driver missing, or no access to "+ "/dev/accel: group render)");+ goto fail;+ }+ memcpy(u->name, dp.name, sizeof u->name - 1);+ ze_driver_properties_t drp = {.stype = ZE_STYPE_DRIVER_PROPERTIES};+ if (!u->zeDriverGetProperties(u->drv, &drp))+ u->driver_version = drp.driverVersion;+ ze_simple_desc_t cd = {.stype = ZE_STYPE_CONTEXT_DESC};+ if (u->zeContextCreate(u->drv, &cd, &u->ctx)) {+ snprintf(err, err_len, "NPU context refused");+ goto fail;+ }+ ze_device_graph_properties_t gp = {.stype =+ ZE_GSTYPE_DEVICE_GRAPH_PROPERTIES};+ if (u->zeDriverGetExtensionFunctionAddress(u->drv, ZE_GRAPH_EXT_NAME,+ (void **)&u->g) ||+ !u->g || u->g->pfnDeviceGetGraphProperties(u->dev, &gp) ||+ gp.graphExtensionVersion < ((1u << 16) | 5u) ||+ !(gp.graphFormatsSupported & ZE_GRAPH_FORMAT_NGRAPH_LITE)) {+ snprintf(err, err_len,+ "NPU driver without its graph compiler "+ "(extension 1.5 and IR input needed)");+ goto fail;+ }+ u->cmajor = gp.compilerMajor, u->cminor = gp.compilerMinor;+ /* turbo (unless JANAS_NPU_TURBO=0): the queue's work at the NPU's+ higher clocks */+ const char *tb = getenv("JANAS_NPU_TURBO");+ ze_command_queue_desc_npu_ext_t qx = {+ .stype = ZE_NSTYPE_COMMAND_QUEUE_DESC_NPU_EXT,+ .turbo = !tb || atoi(tb) > 0};+ ze_command_queue_desc_t qd = {.stype = ZE_STYPE_COMMAND_QUEUE_DESC,+ .pNext = &qx};+ if (u->zeCommandQueueCreate(u->ctx, u->dev, &qd, &u->q) &&+ (qd.pNext = NULL,+ u->zeCommandQueueCreate(u->ctx, u->dev, &qd, &u->q))) {+ snprintf(err, err_len, "NPU queue refused");+ goto fail;+ }+ return u;+fail:+ if (u->ctx)+ u->zeContextDestroy(u->ctx);+ dlclose(u->lib);+ free(u);+ return NULL;+}++void janas_npu_mm_destroy(struct janas_npu_mm *p)+{+ if (!p)+ return;+ struct janas_npu *u = p->u;+ if (p->pending)+ janas_npu_mm_finish(p);+ if (p->alt_pending)+ janas_npu_mm_finish_v(p, 1);+ if (p->alt_fence)+ u->zeFenceDestroy(p->alt_fence);+ if (p->alt_list)+ u->zeCommandListDestroy(p->alt_list);+ for (struct janas_npu_mm **a = &u->mms; *a; a = &(*a)->next)+ if (*a == p) {+ *a = p->next;+ break;+ }+ if (p->fence)+ u->zeFenceDestroy(p->fence);+ if (p->list)+ u->zeCommandListDestroy(p->list);+ if (p->graph)+ u->g->pfnDestroy(p->graph);+ free(p->blob);+ free(p);+}++void janas_npu_destroy(struct janas_npu *u)+{+ if (!u)+ return;+ pthread_mutex_lock(&awake_lock);+ stop_awake(u);+ for (int i = 0; i < NPU_AWAKE_MAX; i++)+ if (awake_npus[i] == u)+ awake_npus[i] = NULL;+ pthread_mutex_unlock(&awake_lock);+ while (u->mms)+ janas_npu_mm_destroy(u->mms);+ for (int i = 0; i < u->nallocs; i++)+ u->zeMemFree(u->ctx, u->allocs[i]);+ u->zeCommandQueueDestroy(u->q);+ if (u->kq)+ u->zeCommandQueueDestroy(u->kq);+ u->zeContextDestroy(u->ctx);+ dlclose(u->lib);+ free(u->cache);+ free(u);+}++int janas_npu_set_cache(struct janas_npu *u, const char *dir)+{+ free(u->cache);+ u->cache = NULL;+ if (!dir || !*dir)+ return 0;+ if (mkdir(dir, 0755) && errno != EEXIST)+ return -1;+ u->cache = strdup(dir);+ return u->cache ? 0 : -1;+}++/* the cache's file of a model: its SHA-256 with the driver's and the+ compiler's versions */+static void cache_path(const struct janas_npu *u, const uint8_t *model,+ size_t bytes, char *path, size_t len)+{+ struct janas_sha256 h;+ char hex[65];+ janas_sha256_init(&h);+ janas_sha256_update(&h, model, bytes);+ janas_sha256_update(&h, &u->driver_version, sizeof u->driver_version);+ janas_sha256_update(&h, &u->cmajor, sizeof u->cmajor);+ janas_sha256_update(&h, &u->cminor, sizeof u->cminor);+ janas_sha256_hex(&h, hex);+ snprintf(path, len, "%s/%s.npu", u->cache, hex);+}++static uint8_t *read_file(const char *path, size_t *bytes)+{+ FILE *f = fopen(path, "rb");+ if (!f)+ return NULL;+ uint8_t *b = NULL;+ long n = fseek(f, 0, SEEK_END) ? -1 : ftell(f);+ if (n > 0 && !fseek(f, 0, SEEK_SET) && (b = malloc((size_t)n)) &&+ fread(b, 1, (size_t)n, f) != (size_t)n) {+ free(b);+ b = NULL;+ }+ fclose(f);+ *bytes = n > 0 ? (size_t)n : 0;+ return b;+}++/* the compiled graph into the cache: written aside, then renamed */+static void cache_store(struct janas_npu *u, ze_graph_handle_t graph,+ const char *path)+{+ size_t n = 0;+ if (u->g->pfnGetNativeBinary(graph, &n, NULL) || !n)+ return;+ uint8_t *b = malloc(n);+ char tmp[4200];+ snprintf(tmp, sizeof tmp, "%s.%d.tmp", path, (int)getpid());+ FILE *f =+ b && !u->g->pfnGetNativeBinary(graph, &n, b) ? fopen(tmp, "wb") : NULL;+ if (f) {+ int ok = fwrite(b, 1, n, f) == n;+ ok = !fclose(f) && ok;+ if (!ok || rename(tmp, path))+ unlink(tmp);+ }+ free(b);+}++const char *janas_npu_name(const struct janas_npu *u)+{+ return u->name;+}++void *janas_npu_alloc(struct janas_npu *u, size_t bytes)+{+ void *p = NULL;+ ze_simple_desc_t hd = {.stype = ZE_STYPE_HOST_MEM_ALLOC_DESC};+ if (u->nallocs >= NPU_MAX_ALLOCS ||+ u->zeMemAllocHost(u->ctx, &hd, (bytes + 4095) & ~(size_t)4095, 4096,+ &p))+ return NULL;+ u->allocs[u->nallocs++] = p;+ return p;+}++void janas_npu_free(struct janas_npu *u, void *p)+{+ for (int i = 0; i < u->nallocs; i++)+ if (u->allocs[i] == p) {+ u->zeMemFree(u->ctx, p);+ u->allocs[i] = u->allocs[--u->nallocs];+ return;+ }+}++/* the graph's arguments, in its order (inputs, then outputs), each rows+ x cols as expected, bound to args */+static int bind(struct janas_npu_mm *p, int nargs, float *const *args,+ const int *rows, const int *cols)+{+ struct janas_npu *u = p->u;+ ze_graph_properties_t pr = {.stype = ZE_GSTYPE_GRAPH_PROPERTIES};+ int say = getenv("JANAS_NPU_STATS") != NULL;+ if (u->g->pfnGetProperties(p->graph, &pr) ||+ pr.numGraphArgs != (uint32_t)nargs) {+ if (say)+ fprintf(stderr, "janas: NPU graph with %u arguments, %d expected\n",+ pr.numGraphArgs, nargs);+ return -1;+ }+ for (uint32_t i = 0; i < (uint32_t)nargs; i++) {+ ze_graph_argument_properties_t ap = {+ .stype = ZE_GSTYPE_GRAPH_ARGUMENT_PROPERTIES};+ if (u->g->pfnGetArgumentProperties(p->graph, i, &ap) ||+ ap.dims[0] != (uint32_t)rows[i] ||+ ap.dims[1] != (uint32_t)cols[i] ||+ u->g->pfnSetArgumentValue(p->graph, i, args[i])) {+ if (say) /* which one, as the driver sees it */+ fprintf(stderr,+ "janas: NPU argument %u of %d (%s, %s): dims %u %u "+ "%u %u, expected %d x %d\n",+ i, nargs, ap.name,+ ap.type == ZE_GRAPH_ARGUMENT_TYPE_INPUT ? "in" : "out",+ ap.dims[0], ap.dims[1], ap.dims[2], ap.dims[3], rows[i],+ cols[i]);+ return -1;+ }+ }+ return 0;+}++static struct janas_npu_mm *from_ir(struct janas_npu *u, struct npu_ir *irp,+ int nargs, float *const *args,+ const int *rows, const int *cols, char *err,+ size_t err_len);++struct janas_npu_mm *janas_npu_graph_create(struct janas_npu *u,+ struct npu_ir *ir, int nargs,+ float *const *args, const int *rows,+ const int *cols, char *err,+ size_t err_len)+{+ return from_ir(u, ir, nargs, args, rows, cols, err, err_len);+}++struct janas_npu_mm *janas_npu_ffn_create(struct janas_npu *u, int m, int d,+ int ff, int act, const int8_t *gq,+ const uint16_t *gs, const int8_t *uq,+ const uint16_t *us, const int8_t *dq,+ const uint16_t *ds, float *x,+ float *y, char *err, size_t err_len)+{+ if (m <= 0 || d <= 0 || ff <= 0 || !gq || !gs || !uq || !us || !dq || !ds ||+ !x || !y || (act != JANAS_NPU_SILU && act != JANAS_NPU_GELU_TANH)) {+ snprintf(err, err_len, "bad feed-forward");+ return NULL;+ }+ struct npu_ir ir;+ npu_ir_begin(&ir, "janas_ffn");+ int xd[2] = {m, d};+ int lx =+ npu_ir_convert(&ir, "x16", npu_ir_param(&ir, "x", "f32", 2, xd), "f16");+ int lf =+ npu_ir_ffn(&ir, "ffn", lx, npu_ir_weights_i8(&ir, "wg", gq, gs, ff, d),+ npu_ir_weights_i8(&ir, "wu", uq, us, ff, d),+ npu_ir_weights_i8(&ir, "wd", dq, ds, d, ff),+ act == JANAS_NPU_GELU_TANH);+ int ly = npu_ir_convert(&ir, "y", lf, "f32");+ npu_ir_result(&ir, ly);+ float *args[2] = {x, y};+ int rows[2] = {m, m}, cols[2] = {d, d};+ return from_ir(u, &ir, 2, args, rows, cols, err, err_len);+}++struct janas_npu_mm *janas_npu_mm_create(struct janas_npu *u, int m, int n,+ int k, int wtype, const void *w,+ const uint16_t *scale, float *x,+ float *y, char *err, size_t err_len)+{+ if (m <= 0 || n <= 0 || k <= 0 || !w || !x || !y ||+ (wtype == JANAS_NPU_I8 && !scale) ||+ (wtype != JANAS_NPU_I8 && wtype != JANAS_NPU_F16)) {+ snprintf(err, err_len, "bad product");+ return NULL;+ }+ struct npu_ir ir;+ npu_ir_begin(&ir, "janas_mm");+ int xd[2] = {m, k}, wd[2] = {n, k}, sd[2] = {n, 1};+ int lx =+ npu_ir_convert(&ir, "x16", npu_ir_param(&ir, "x", "f32", 2, xd), "f16");+ int lw;+ if (wtype == JANAS_NPU_I8) {+ int lq = npu_ir_const(&ir, "wq", "i8", 2, wd, w, (size_t)n * k);+ int ls = npu_ir_const(&ir, "ws", "f16", 2, sd, scale, (size_t)n * 2);+ lw =+ npu_ir_multiply(&ir, "w", npu_ir_convert(&ir, "wc", lq, "f16"), ls);+ } else+ lw = npu_ir_const(&ir, "w", "f16", 2, wd, w, (size_t)n * k * 2);+ int ly = npu_ir_convert(&ir, "y", npu_ir_matmul_tb(&ir, "mm", lx, lw, NULL),+ "f32");+ npu_ir_result(&ir, ly);+ float *args[2] = {x, y};+ int rows[2] = {m, m}, cols[2] = {k, n};+ return from_ir(u, &ir, 2, args, rows, cols, err, err_len);+}++/* a graph written in ir (freed here) compiled - or loaded from the cache -+ with x (m x k floats) and y (m x n floats) bound, its command list+ recorded and a first run made */+static struct janas_npu_mm *from_ir(struct janas_npu *u, struct npu_ir *irp,+ int nargs, float *const *args,+ const int *rows, const int *cols, char *err,+ size_t err_len)+{+ struct npu_ir ir = *irp;+ size_t bytes = 0;+ uint8_t *model = npu_ir_end(&ir)+ ? NULL+ : npu_ir_model(&ir, u->cmajor, u->cminor, &bytes);+ npu_ir_free(&ir);+ struct janas_npu_mm *p = model ? calloc(1, sizeof(*p)) : NULL;+ if (!p) {+ free(model);+ snprintf(err, err_len, "out of memory");+ return NULL;+ }+ p->u = u;+ p->q = u->q;+ ze_graph_desc_2_t gd = {.stype = ZE_GSTYPE_GRAPH_DESC_2,+ .format = ZE_GRAPH_FORMAT_NGRAPH_LITE,+ .inputSize = bytes,+ .pInput = model,+ .pBuildFlags = "",+ .flags = ZE_GRAPH_FLAG_DISABLE_CACHING};+ double t0 = now();+ ze_result_t r = 1;+ char path[4096];+ if (u->cache) {+ cache_path(u, model, bytes, path, sizeof path);+ size_t nb = 0;+ uint8_t *blob = read_file(path, &nb);+ if (blob) {+ ze_graph_desc_2_t nd = gd;+ nd.format = ZE_GRAPH_FORMAT_NATIVE, nd.inputSize = nb;+ nd.pInput = blob, nd.pBuildFlags = NULL;+ r = u->g->pfnCreate2(u->ctx, u->dev, &nd, &p->graph);+ if (r) {+ free(blob);+ unlink(path); /* stale: another driver's */+ } else+ p->blob = blob, u->cached++;+ }+ }+ if (r) {+ r = u->g->pfnCreate2(u->ctx, u->dev, &gd, &p->graph);+ if (!r && u->cache)+ cache_store(u, p->graph, path);+ }+ free(model);+ if (r) {+ snprintf(err, err_len, "NPU compiler refused the product (0x%x)",+ (unsigned)r);+ free(p);+ return NULL;+ }+ u->compile_s += now() - t0;+ u->products++;+ p->next = u->mms, u->mms = p;+ ze_command_list_desc_t ld = {.stype = ZE_STYPE_COMMAND_LIST_DESC};+ ze_simple_desc_t fd = {.stype = ZE_STYPE_FENCE_DESC};+ /* step by step, so that a failure says where */+ int step = 0;+ ze_result_t sr = 0;+ if (bind(p, nargs, args, rows, cols))+ step = 1;+ else if ((sr = u->zeCommandListCreate(u->ctx, u->dev, &ld, &p->list)))+ step = 2;+ else if ((sr = u->g->pfnAppendGraphInitialize(p->list, p->graph, NULL, 0,+ NULL)))+ step = 3;+ else if ((sr = u->zeCommandListClose(p->list)) ||+ (sr = u->zeCommandQueueExecuteCommandLists(u->q, 1, &p->list,+ NULL)) ||+ (sr = u->zeCommandQueueSynchronize(u->q, UINT64_MAX)))+ step = 4;+ else if ((sr = u->zeCommandListReset(p->list)) ||+ (sr = u->g->pfnAppendGraphExecute(p->list, p->graph, NULL, NULL, 0,+ NULL)) ||+ (sr = u->zeCommandListClose(p->list)))+ step = 5;+ else if ((sr = u->zeFenceCreate(u->q, &fd, &p->fence)))+ step = 6;+ if (step) {+ static const char *what[7] = {"",+ "arguments not as expected",+ "no command list",+ "initialization not recorded",+ "initialization failed",+ "run not recorded",+ "no fence"};+ snprintf(err, err_len, "NPU product not set up: %s (0x%x)", what[step],+ (unsigned)sr);+ janas_npu_mm_destroy(p);+ return NULL;+ }+ /* a first run: the NPU's first one after a compilation costs several+ times the next (512 x 1024 x 1024 INT8: 4.9 ms, 2.2, then 0.8-1.3;+ 20 Oct 2026), counted with the compilation */+ t0 = now();+ if (janas_npu_mm_run(p)) {+ snprintf(err, err_len, "NPU product does not run");+ janas_npu_mm_destroy(p);+ return NULL;+ }+ u->compile_s += now() - t0;+ return p;+}++int janas_npu_mm_rebind(struct janas_npu_mm *p, int nargs, float *const *args)+{+ struct janas_npu *u = p->u;+ if (p->pending)+ return -1;+ for (int i = 0; i < nargs; i++)+ if (u->g->pfnSetArgumentValue(p->graph, (uint32_t)i, args[i]))+ return -1;+ /* the arguments are read when the list is recorded (20 Oct 2026: a+ new x set after it ran on the old one): recorded again, ~90 us */+ if (u->zeCommandListReset(p->list) ||+ u->g->pfnAppendGraphExecute(p->list, p->graph, NULL, NULL, 0, NULL) ||+ u->zeCommandListClose(p->list))+ return -1;+ return 0;+}++int janas_npu_mm_bind_alt(struct janas_npu_mm *p, int nargs, float *const *args)+{+ struct janas_npu *u = p->u;+ ze_command_list_desc_t ld = {.stype = ZE_STYPE_COMMAND_LIST_DESC};+ ze_simple_desc_t fd = {.stype = ZE_STYPE_FENCE_DESC};+ if (p->alt_pending)+ return -1;+ for (int i = 0; i < nargs; i++)+ if (u->g->pfnSetArgumentValue(p->graph, (uint32_t)i, args[i]))+ return -1;+ if ((!p->alt_list &&+ u->zeCommandListCreate(u->ctx, u->dev, &ld, &p->alt_list)) ||+ u->zeCommandListReset(p->alt_list) ||+ u->g->pfnAppendGraphExecute(p->alt_list, p->graph, NULL, NULL, 0,+ NULL) ||+ u->zeCommandListClose(p->alt_list) ||+ (!p->alt_fence && u->zeFenceCreate(p->q, &fd, &p->alt_fence)))+ return -1;+ return 0;+}++int janas_npu_mm_begin_v(struct janas_npu_mm *p, int v)+{+ struct janas_npu *u = p->u;+ int *pending = v ? &p->alt_pending : &p->pending;+ ze_command_list_handle_t *l = v ? &p->alt_list : &p->list;+ if (*pending || !*l ||+ u->zeCommandQueueExecuteCommandLists(p->q, 1, l,+ v ? p->alt_fence : p->fence))+ return -1;+ *pending = 1;+ atomic_store(&u->last_ns, (long long)(now() * 1e9));+ return 0;+}++int janas_npu_mm_finish_v(struct janas_npu_mm *p, int v)+{+ struct janas_npu *u = p->u;+ int *pending = v ? &p->alt_pending : &p->pending;+ ze_fence_handle_t f = v ? p->alt_fence : p->fence;+ if (!*pending)+ return -1;+ *pending = 0;+ int r =+ u->zeFenceHostSynchronize(f, UINT64_MAX) || u->zeFenceReset(f) ? -1 : 0;+ atomic_store(&u->last_ns, (long long)(now() * 1e9));+ return r;+}++int janas_npu_mm_begin(struct janas_npu_mm *p)+{+ return janas_npu_mm_begin_v(p, 0);+}++int janas_npu_mm_finish(struct janas_npu_mm *p)+{+ return janas_npu_mm_finish_v(p, 0);+}++/* the threads keeping NPUs awake, stopped at exit: a program that ends+ without janas_npu_destroy left one running while the driver was torn+ down, and crashed on its way out */+static pthread_mutex_t awake_lock = PTHREAD_MUTEX_INITIALIZER;++static void stop_awake(struct janas_npu *u)+{+ if (!u->ka_started)+ return;+ atomic_store(&u->ka_stop, 1);+ pthread_mutex_lock(&u->ka_mx);+ pthread_cond_broadcast(&u->ka_cv);+ pthread_mutex_unlock(&u->ka_mx);+ pthread_join(u->ka_thread, NULL);+ pthread_cond_destroy(&u->ka_cv);+ pthread_mutex_destroy(&u->ka_mx);+ u->ka_started = 0;+}++static void stop_all_awake(void)+{+ pthread_mutex_lock(&awake_lock);+ for (int i = 0; i < NPU_AWAKE_MAX; i++)+ if (awake_npus[i]) {+ stop_awake(awake_npus[i]);+ awake_npus[i] = NULL;+ }+ pthread_mutex_unlock(&awake_lock);+}++static void *keep_awake(void *arg)+{+ struct janas_npu *u = arg;+ const char *e = getenv("JANAS_NPU_AWAKE_US");+ long long idle = e && atol(e) > 0 ? atoll(e) * 1000 : NPU_AWAKE_NS;+ struct timespec nap = {.tv_nsec = idle < 2000000 ? idle / 2 : 1000000};+ while (!atomic_load(&u->ka_stop)) {+ if (!atomic_load(&u->ka_on)) { /* asleep until a pass needs it */+ pthread_mutex_lock(&u->ka_mx);+ while (!atomic_load(&u->ka_on) && !atomic_load(&u->ka_stop))+ pthread_cond_wait(&u->ka_cv, &u->ka_mx);+ pthread_mutex_unlock(&u->ka_mx);+ continue;+ }+ nanosleep(&nap, NULL);+ long long t = (long long)(now() * 1e9);+ if (atomic_load(&u->ka_on) && t - atomic_load(&u->last_ns) > idle &&+ janas_npu_mm_begin(u->ka) == 0)+ janas_npu_mm_finish(u->ka);+ }+ return NULL;+}++int janas_npu_keep_awake(struct janas_npu *u, int on)+{+ int was = atomic_exchange(&u->ka_on, on);+ if (u->ka_started) {+ if (on && !was) { /* the thread asleep: woken */+ pthread_mutex_lock(&u->ka_mx);+ pthread_cond_signal(&u->ka_cv);+ pthread_mutex_unlock(&u->ka_mx);+ }+ return 0;+ }+ if (!on)+ return 0;+ /* the tiny product, its fence moved to a queue of its own */+ char err[64];+ ze_command_queue_desc_t qd = {.stype = ZE_STYPE_COMMAND_QUEUE_DESC};+ ze_simple_desc_t fd = {.stype = ZE_STYPE_FENCE_DESC};+ static const int8_t w[64 * 64];+ static const uint16_t s[64];+ float *x = janas_npu_alloc(u, sizeof(float) * 8 * 64),+ *y = janas_npu_alloc(u, sizeof(float) * 8 * 64);+ int compiled = u->products;+ double cs = u->compile_s;+ if (!x || !y || u->zeCommandQueueCreate(u->ctx, u->dev, &qd, &u->kq) ||+ !(u->ka = janas_npu_mm_create(u, 8, 64, 64, JANAS_NPU_I8, w, s, x, y,+ err, sizeof err))) {+ atomic_store(&u->ka_on, 0);+ return -1;+ }+ u->products = compiled, u->compile_s = cs; /* not the caller's */+ u->zeFenceDestroy(u->ka->fence);+ u->ka->fence = NULL;+ if (u->zeFenceCreate(u->kq, &fd, &u->ka->fence)) {+ atomic_store(&u->ka_on, 0);+ return -1;+ }+ u->ka->q = u->kq;+ pthread_mutex_init(&u->ka_mx, NULL);+ pthread_cond_init(&u->ka_cv, NULL);+ pthread_mutex_lock(&awake_lock);+ static int registered;+ int slot = -1;+ for (int i = 0; i < NPU_AWAKE_MAX && slot < 0; i++)+ if (!awake_npus[i])+ slot = i;+ if (slot < 0 || (!registered && atexit(stop_all_awake)) ||+ pthread_create(&u->ka_thread, NULL, keep_awake, u)) {+ pthread_mutex_unlock(&awake_lock);+ atomic_store(&u->ka_on, 0);+ return -1;+ }+ registered = 1;+ awake_npus[slot] = u;+ u->ka_started = 1;+ pthread_mutex_unlock(&awake_lock);+ return 0;+}++void janas_npu_stats(const struct janas_npu *u, int *products, int *cached,+ double *compile_seconds)+{+ *products = u->products;+ *cached = u->cached;+ *compile_seconds = u->compile_s;+}++#else /* no Level Zero here */++struct janas_npu *janas_npu_create(char *err, size_t err_len)+{+ snprintf(err, err_len, "no NPU support on this system");+ return NULL;+}+void janas_npu_destroy(struct janas_npu *u)+{+ (void)u;+}+const char *janas_npu_name(const struct janas_npu *u)+{+ (void)u;+ return "";+}+void *janas_npu_alloc(struct janas_npu *u, size_t bytes)+{+ (void)u, (void)bytes;+ return NULL;+}+void janas_npu_free(struct janas_npu *u, void *p)+{+ (void)u, (void)p;+}+struct janas_npu_mm *janas_npu_mm_create(struct janas_npu *u, int m, int n,+ int k, int wtype, const void *w,+ const uint16_t *scale, float *x,+ float *y, char *err, size_t err_len)+{+ (void)u, (void)m, (void)n, (void)k, (void)wtype, (void)w, (void)scale;+ (void)x, (void)y;+ snprintf(err, err_len, "no NPU support on this system");+ return NULL;+}+void janas_npu_mm_destroy(struct janas_npu_mm *p)+{+ (void)p;+}+struct janas_npu_mm *janas_npu_graph_create(struct janas_npu *u,+ struct npu_ir *ir, int nargs,+ float *const *args, const int *rows,+ const int *cols, char *err,+ size_t err_len)+{+ (void)u, (void)ir, (void)nargs, (void)args, (void)rows, (void)cols;+ snprintf(err, err_len, "no NPU support on this system");+ return NULL;+}+struct janas_npu_mm *janas_npu_ffn_create(struct janas_npu *u, int m, int d,+ int ff, int act, const int8_t *gq,+ const uint16_t *gs, const int8_t *uq,+ const uint16_t *us, const int8_t *dq,+ const uint16_t *ds, float *x,+ float *y, char *err, size_t err_len)+{+ (void)u, (void)m, (void)d, (void)ff, (void)act, (void)gq, (void)gs;+ (void)uq, (void)us, (void)dq, (void)ds, (void)x, (void)y;+ snprintf(err, err_len, "no NPU support on this system");+ return NULL;+}+int janas_npu_mm_rebind(struct janas_npu_mm *p, int nargs, float *const *args)+{+ (void)p, (void)nargs, (void)args;+ return -1;+}+int janas_npu_mm_bind_alt(struct janas_npu_mm *p, int nargs, float *const *args)+{+ (void)p, (void)nargs, (void)args;+ return -1;+}+int janas_npu_mm_begin_v(struct janas_npu_mm *p, int v)+{+ (void)p, (void)v;+ return -1;+}+int janas_npu_mm_finish_v(struct janas_npu_mm *p, int v)+{+ (void)p, (void)v;+ return -1;+}+int janas_npu_mm_begin(struct janas_npu_mm *p)+{+ (void)p;+ return -1;+}+int janas_npu_mm_finish(struct janas_npu_mm *p)+{+ (void)p;+ return -1;+}+int janas_npu_set_cache(struct janas_npu *u, const char *dir)+{+ (void)u, (void)dir;+ return -1;+}+int janas_npu_keep_awake(struct janas_npu *u, int on)+{+ (void)u, (void)on;+ return -1;+}+void janas_npu_stats(const struct janas_npu *u, int *products, int *cached,+ double *compile_seconds)+{+ (void)u;+ *products = *cached = 0;+ *compile_seconds = 0;+}++#endif++int janas_npu_available(void)+{+ static int known = -1;+ if (known < 0) {+ char err[256];+ struct janas_npu *u = janas_npu_create(err, sizeof err);+ known = u != NULL;+ janas_npu_destroy(u);+ }+ return known;+}++int janas_npu_mm_run(struct janas_npu_mm *p)+{+ return janas_npu_mm_begin(p) ? -1 : janas_npu_mm_finish(p);+}++/* FP16 by hand (round to nearest even), so that this file needs no F16C */+static uint16_t to_f16(float f)+{+ uint32_t b;+ memcpy(&b, &f, 4);+ uint32_t sign = (b >> 16) & 0x8000u, e = (b >> 23) & 0xff,+ mant = b & 0x7fffffu;+ if (e == 0xff)+ return (uint16_t)(sign | 0x7c00u | (mant ? 0x200u : 0));+ int ee = (int)e - 127 + 15;+ if (ee >= 31)+ return (uint16_t)(sign | 0x7c00u);+ if (ee <= 0) {+ if (ee < -10)+ return (uint16_t)sign;+ mant |= 0x800000u;+ int sh = 14 - ee;+ uint32_t v = mant >> sh, rest = mant & ((1u << sh) - 1),+ half = 1u << (sh - 1);+ if (rest > half || (rest == half && (v & 1)))+ v++;+ return (uint16_t)(sign | v);+ }+ uint32_t v = ((uint32_t)ee << 10) | (mant >> 13), rest = mant & 0x1fffu;+ if (rest > 0x1000u || (rest == 0x1000u && (v & 1)))+ v++; /* may carry into the exponent: still right */+ return (uint16_t)(sign | v);+}++static float from_f16(uint16_t h)+{+ uint32_t sign = (uint32_t)(h & 0x8000u) << 16, e = (h >> 10) & 31,+ mant = h & 0x3ffu, b;+ if (e == 0) {+ if (!mant)+ b = sign;+ else {+ e = 127 - 15 + 1;+ while (!(mant & 0x400u))+ mant <<= 1, e--;+ b = sign | (e << 23) | ((mant & 0x3ffu) << 13);+ }+ } else if (e == 31)+ b = sign | 0x7f800000u | (mant << 13);+ else+ b = sign | ((e - 15 + 127) << 23) | (mant << 13);+ float f;+ memcpy(&f, &b, 4);+ return f;+}++void janas_npu_quant_rows(const float *w, size_t n, size_t k, int8_t *q,+ uint16_t *scale)+{+ for (size_t r = 0; r < n; r++) {+ const float *p = w + r * k;+ float a = 0;+ for (size_t t = 0; t < k; t++)+ a = fmaxf(a, fabsf(p[t]));+ /* the scale rounded up, so that no weight is clipped (rows of tiny+ weights get a subnormal FP16 scale) */+ uint16_t sh = to_f16(a / 127.0f);+ if (from_f16(sh) * 127.0f < a)+ sh++;+ float s = from_f16(sh);+ scale[r] = sh;+ for (size_t t = 0; t < k; t++) {+ long v = s > 0 ? lrintf(p[t] / s) : 0;+ q[r * k + t] = (int8_t)(v > 127 ? 127 : v < -127 ? -127 : v);+ }+ }+}diff --git a/src/common/npu.h b/src/common/npu.hnew file mode 100644index 0000000..48bef4e--- /dev/null+++ b/src/common/npu.h@@ -0,0 +1,157 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * npu.h - an optional NPU (Intel's, through Level Zero) for the products of+ * blocks of tokens: y = x w^T with x m x k, w n x k, y m x n, all floats on+ * the caller's side.+ *+ * Level Zero is loaded at run time: without its loader, the NPU's driver or+ * an NPU, janas_npu_create returns NULL and the caller computes on the CPU.+ * Nothing here knows a model: Janas-LLM and Janet hand it matrices.+ *+ * The NPU runs graphs its driver compiles, of fixed shapes. A product is+ * compiled once with its weights inside (as a constant: integer weights+ * passed as an input are dequantized apart and run slower than the CPU),+ * as INT8 with a scale a row or as FP16; the driver keeps its own copy of+ * them, so the caller may free its own. x and y live in memory both sides+ * see (janas_npu_alloc), bound when the product is compiled; x is read as+ * floats and rounded to FP16 by the NPU, y written as floats. The NPU's+ * results are close to the CPU's, not the same bits (FP16 arithmetic).+ *+ * Measured on Meteor Lake (20 Oct 2026, job/tests/c/npu_probe.c): INT8+ * 2.7-3.6 TFLOP/s at 256 x 2048-6144, some 3.4 times the CPU's Q4_K blocks;+ * about 0.45 ms of fixed cost a run, so small products do not pay.+ *+ * One thread at a time per janas_npu.+ */+#ifndef JANAS_COMMON_NPU_H+#define JANAS_COMMON_NPU_H++#include <stddef.h>+#include <stdint.h>++struct janas_npu;+struct janas_npu_mm;++/* Opens the first NPU. NULL with a reason in err when there is none. */+struct janas_npu *janas_npu_create(char *err, size_t err_len);+/* Whether an NPU can be opened here (once a process, the answer kept): for+ a caller that has to plan memory before it opens one. */+int janas_npu_available(void);+/* Releases its products and memory too. */+void janas_npu_destroy(struct janas_npu *u);+const char *janas_npu_name(const struct janas_npu *u);++/* Memory the NPU reads and writes (host memory, 4096-aligned), released by+ janas_npu_free or janas_npu_destroy. NULL on failure. */+void *janas_npu_alloc(struct janas_npu *u, size_t bytes);+void janas_npu_free(struct janas_npu *u, void *p);++enum { JANAS_NPU_F16 = 0, JANAS_NPU_I8 = 1 };++/*+ * Quantizes n rows of k floats to INT8 with a scale a row (symmetric, -127+ * to 127; the scale in FP16, rounded up, so that q s is what the NPU+ * computes and no weight is clipped): q n x k, scale n values. For+ * JANAS_NPU_I8.+ */+void janas_npu_quant_rows(const float *w, size_t n, size_t k, int8_t *q,+ uint16_t *scale);++/*+ * Compiles y = x w^T for x m x k and n rows of weights: JANAS_NPU_I8 with w+ * n x k int8 and scale n FP16 values, or JANAS_NPU_F16 with w n x k FP16+ * (scale NULL). x (m x k floats) and y (m x n floats) from janas_npu_alloc.+ * NULL with a reason in err on failure. It runs once before returning (the+ * first run after a compilation is slow), on whatever x holds.+ */+struct janas_npu_mm *janas_npu_mm_create(struct janas_npu *u, int m, int n,+ int k, int wtype, const void *w,+ const uint16_t *scale, float *x,+ float *y, char *err, size_t err_len);+void janas_npu_mm_destroy(struct janas_npu_mm *p);++/*+ * Any graph written with common/npu_ir.h (taken: freed here), compiled -+ * or loaded from the cache - with its arguments bound: args[i] is the+ * memory (janas_npu_alloc) of its i-th argument, inputs in the order of+ * their parameters then outputs in the order of their results, each+ * rows[i] x cols[i] floats. Runs as a product.+ */+struct npu_ir;+struct janas_npu_mm *janas_npu_graph_create(struct janas_npu *u,+ struct npu_ir *ir, int nargs,+ float *const *args, const int *rows,+ const int *cols, char *err,+ size_t err_len);++enum { JANAS_NPU_SILU = 0, JANAS_NPU_GELU_TANH = 1 };++/*+ * A feed-forward in one run of the NPU: y = down (act(gate x) * up x), x+ * m x d, gate and up ff x d, down d x ff, each INT8 with a scale a row+ * (janas_npu_quant_rows); act SiLU or the tanh form of GELU. One trip+ * instead of a product's for gate and up, the activation on the CPU and+ * another for down - and the intermediate m x ff never leaves the NPU.+ * Runs, waits and frees as a product (janas_npu_mm_begin, _finish,+ * _destroy); x and y as for a product.+ */+struct janas_npu_mm *janas_npu_ffn_create(struct janas_npu *u, int m, int d,+ int ff, int act, const int8_t *gq,+ const uint16_t *gs, const int8_t *uq,+ const uint16_t *us, const int8_t *dq,+ const uint16_t *ds, float *x,+ float *y, char *err, size_t err_len);++/* Its arguments bound to other memory (as at creation: inputs, then+ outputs; janas_npu_alloc), for the runs that follow; not while in+ flight. 0 or -1. */+int janas_npu_mm_rebind(struct janas_npu_mm *p, int nargs, float *const *args);++/*+ * A second binding of the same graph (no second copy of its weights): the+ * arguments are taken when a run is recorded, so a second list recorded+ * with others runs the graph on them - for two halves of a block, one in+ * flight while the CPU prepares the other. Then janas_npu_mm_begin_v(p,+ * 1) and _finish_v(p, 1); variant 0 is the first binding (begin, finish).+ */+int janas_npu_mm_bind_alt(struct janas_npu_mm *p, int nargs,+ float *const *args);+int janas_npu_mm_begin_v(struct janas_npu_mm *p, int v);+int janas_npu_mm_finish_v(struct janas_npu_mm *p, int v);++/* Submits the product (x as it is now); the caller works meanwhile and+ janas_npu_mm_finish waits for y. Several may be in flight; they run in+ the order submitted. 0, or -1 with nothing submitted. */+int janas_npu_mm_begin(struct janas_npu_mm *p);+int janas_npu_mm_finish(struct janas_npu_mm *p);+/* begin and finish */+int janas_npu_mm_run(struct janas_npu_mm *p);++/*+ * Where compiled products are kept between runs: dir (created if missing),+ * a file a product named by the SHA-256 of its graph and weights and of the+ * driver's and compiler's versions, holding the weights too; NULL (the+ * default) keeps nothing. The driver's own cache ($HOME/.cache/+ * ze_intel_npu_cache, up to 4 GB) is never used. 0, or -1 if dir cannot+ * be made.+ */+int janas_npu_set_cache(struct janas_npu *u, const char *dir);++/*+ * While on, the NPU is not let sleep: a thread of the NPU's runs a tiny+ * product whenever it has been idle for 1 ms (the kernel suspends it after+ * 10, and waking it costs a product some 5 ms; its clock also falls after+ * longer pauses). For the passes that use it+ * with work of the CPU's between its products. 0, or -1 if it cannot be+ * kept awake. Products and janas_npu_keep_awake from one thread, as+ * everything here.+ */+int janas_npu_keep_awake(struct janas_npu *u, int on);++/* Products made so far, how many came from the cache, and the seconds spent+ compiling (or loading) them. */+void janas_npu_stats(const struct janas_npu *u, int *products, int *cached,+ double *compile_seconds);++#endifdiff --git a/src/common/npu_ir.c b/src/common/npu_ir.cnew file mode 100644index 0000000..ed4b8c4--- /dev/null+++ b/src/common/npu_ir.c@@ -0,0 +1,391 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * npu_ir.c - the OpenVINO IR writer of npu_ir.h.+ */+#include "npu_ir.h"++#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++static void put(struct npu_ir *g, const char *fmt, ...)+{+ if (g->failed)+ return;+ for (;;) {+ va_list ap;+ va_start(ap, fmt);+ int n = vsnprintf(g->xml + g->len, g->cap - g->len, fmt, ap);+ va_end(ap);+ if (n < 0) {+ g->failed = 1;+ return;+ }+ if ((size_t)n < g->cap - g->len) {+ g->len += (size_t)n;+ return;+ }+ size_t cap = (g->cap + (size_t)n) * 2;+ char *x = realloc(g->xml, cap);+ if (!x) {+ g->failed = 1;+ return;+ }+ g->xml = x, g->cap = cap;+ }+}++static const char *precision(const char *et)+{+ return !strcmp(et, "f32") ? "FP32"+ : !strcmp(et, "f16") ? "FP16"+ : !strcmp(et, "i8") ? "I8"+ : "I64";+}++static void port(struct npu_ir *g, int id, int l, const char *names)+{+ put(g, "<port id=\"%d\" precision=\"%s\"", id, precision(g->et[l]));+ if (names)+ put(g, " names=\"%s\"", names);+ put(g, ">");+ for (int d = 0; d < g->nd[l]; d++)+ put(g, "<dim>%d</dim>", g->dims[l][d]);+ put(g, "</port>");+}++/* a layer of output type et and dims, inputs a[ni] */+static int layer(struct npu_ir *g, const char *type, const char *name,+ const char *data, const char *et, int nd, const int *dims,+ int ni, const int *a, const char *names)+{+ if (g->failed || g->nl >= NPU_IR_LAYERS || nd > NPU_IR_DIMS ||+ g->ne + ni > NPU_IR_LAYERS * 2) {+ g->failed = 1;+ return -1;+ }+ for (int i = 0; i < ni; i++)+ if (a[i] < 0 || a[i] >= g->nl) {+ g->failed = 1;+ return -1;+ }+ int l = g->nl++;+ g->et[l] = et, g->nd[l] = nd, g->ins[l] = ni;+ memcpy(g->dims[l], dims, (size_t)nd * sizeof(int));+ put(g, "<layer id=\"%d\" name=\"%s\" type=\"%s\" version=\"opset1\">%s", l,+ name, type, data ? data : "");+ if (ni) {+ put(g, "<input>");+ for (int i = 0; i < ni; i++) {+ port(g, i, a[i], NULL);+ g->edge[g->ne][0] = a[i], g->edge[g->ne][1] = l;+ g->edge[g->ne++][2] = i;+ }+ put(g, "</input>");+ }+ if (strcmp(type, "Result")) {+ put(g, "<output>");+ port(g, ni, l, names);+ put(g, "</output>");+ }+ put(g, "</layer>\n");+ return l;+}++static void shape(char *s, size_t len, int nd, const int *dims)+{+ size_t o = 0;+ s[0] = 0;+ for (int d = 0; d < nd && o < len; d++)+ o += (size_t)snprintf(s + o, len - o, d ? ",%d" : "%d", dims[d]);+}++void npu_ir_begin(struct npu_ir *g, const char *name)+{+ memset(g, 0, sizeof(*g));+ put(g,+ "<?xml version=\"1.0\"?>\n<net name=\"%s\" version=\"11\">\n"+ "<layers>\n",+ name);+}++int npu_ir_param(struct npu_ir *g, const char *name, const char *et, int nd,+ const int *dims)+{+ char data[160], s[64];+ shape(s, sizeof s, nd, dims);+ snprintf(data, sizeof data, "<data shape=\"%s\" element_type=\"%s\"/>", s,+ et);+ return layer(g, "Parameter", name, data, et, nd, dims, 0, NULL, name);+}++int npu_ir_const(struct npu_ir *g, const char *name, const char *et, int nd,+ const int *dims, const void *p, size_t bytes)+{+ if (g->failed)+ return -1;+ uint8_t *b = realloc(g->bin, g->nbin + bytes);+ if (!b) {+ g->failed = 1;+ return -1;+ }+ g->bin = b;+ memcpy(g->bin + g->nbin, p, bytes);+ char data[200], s[64];+ shape(s, sizeof s, nd, dims);+ snprintf(data, sizeof data,+ "<data element_type=\"%s\" shape=\"%s\" offset=\"%zu\" "+ "size=\"%zu\"/>",+ et, s, g->nbin, bytes);+ g->nbin += bytes;+ return layer(g, "Const", name, data, et, nd, dims, 0, NULL, NULL);+}++int npu_ir_convert(struct npu_ir *g, const char *name, int a, const char *et)+{+ if (a < 0 || a >= g->nl)+ return g->failed = 1, -1;+ char data[64];+ snprintf(data, sizeof data, "<data destination_type=\"%s\"/>", et);+ return layer(g, "Convert", name, data, et, g->nd[a], g->dims[a], 1, &a,+ NULL);+}++int npu_ir_multiply(struct npu_ir *g, const char *name, int a, int b)+{+ if (a < 0 || a >= g->nl)+ return g->failed = 1, -1;+ int in[2] = {a, b};+ return layer(g, "Multiply", name, "<data auto_broadcast=\"numpy\"/>",+ g->et[a], g->nd[a], g->dims[a], 2, in, NULL);+}++int npu_ir_add(struct npu_ir *g, const char *name, int a, int b)+{+ if (a < 0 || a >= g->nl)+ return g->failed = 1, -1;+ int in[2] = {a, b};+ return layer(g, "Add", name, "<data auto_broadcast=\"numpy\"/>", g->et[a],+ g->nd[a], g->dims[a], 2, in, NULL);+}++int npu_ir_binary(struct npu_ir *g, const char *name, const char *type, int a,+ int b)+{+ if (a < 0 || a >= g->nl || b < 0 || b >= g->nl)+ return g->failed = 1, -1;+ int nd = g->nd[a] > g->nd[b] ? g->nd[a] : g->nd[b], dims[NPU_IR_DIMS];+ for (int i = 0; i < nd; i++) { /* aligned to the right, as numpy */+ int ia = i - (nd - g->nd[a]), ib = i - (nd - g->nd[b]);+ int da = ia >= 0 ? g->dims[a][ia] : 1,+ db = ib >= 0 ? g->dims[b][ib] : 1;+ dims[i] = da > db ? da : db;+ }+ int in[2] = {a, b};+ return layer(g, type, name, "<data auto_broadcast=\"numpy\"/>", g->et[a],+ nd, dims, 2, in, NULL);+}++int npu_ir_reduce_mean(struct npu_ir *g, const char *name, int a, int axis)+{+ return npu_ir_reduce(g, name, "ReduceMean", a, axis);+}++int npu_ir_reduce(struct npu_ir *g, const char *name, const char *type, int a,+ int axis)+{+ if (a < 0 || a >= g->nl || axis < 0 || axis >= g->nd[a])+ return g->failed = 1, -1;+ int64_t ax = axis;+ int one = 1, dims[NPU_IR_DIMS];+ char cn[64];+ snprintf(cn, sizeof cn, "%s_axes", name);+ int c = npu_ir_const(g, cn, "i64", 1, &one, &ax, sizeof ax);+ memcpy(dims, g->dims[a], sizeof dims);+ dims[axis] = 1;+ int in[2] = {a, c};+ return layer(g, type, name, "<data keep_dims=\"true\"/>", g->et[a],+ g->nd[a], dims, 2, in, NULL);+}++int npu_ir_fake_quantize(struct npu_ir *g, const char *name, int a, float lo,+ float hi, int levels)+{+ if (a < 0 || a >= g->nl)+ return g->failed = 1, -1;+ char n[4][48], data[64];+ static const char *part[4] = {"il", "ih", "ol", "oh"};+ float v[4] = {lo, hi, lo, hi};+ int in[5] = {a};+ for (int i = 0; i < 4; i++) {+ snprintf(n[i], sizeof n[i], "%s_%s", name, part[i]);+ in[i + 1] = npu_ir_scalar(g, n[i], v[i]);+ }+ snprintf(data, sizeof data,+ "<data levels=\"%d\" auto_broadcast=\"numpy\"/>", levels);+ return layer(g, "FakeQuantize", name, data, g->et[a], g->nd[a], g->dims[a],+ 5, in, NULL);+}++int npu_ir_unary(struct npu_ir *g, const char *name, const char *type, int a)+{+ if (a < 0 || a >= g->nl)+ return g->failed = 1, -1;+ return layer(g, type, name, NULL, g->et[a], g->nd[a], g->dims[a], 1, &a,+ NULL);+}++/* FP16 by hand (round to nearest even) */+static uint16_t half(float f)+{+ uint32_t b;+ memcpy(&b, &f, 4);+ uint32_t sign = (b >> 16) & 0x8000u, e = (b >> 23) & 0xff,+ mant = b & 0x7fffffu;+ int ee = (int)e - 127 + 15;+ if (e == 0xff || ee >= 31)+ return (uint16_t)(sign | 0x7c00u);+ if (ee <= 0)+ return (uint16_t)sign; /* the constants here are not that small */+ uint32_t v = ((uint32_t)ee << 10) | (mant >> 13), rest = mant & 0x1fffu;+ if (rest > 0x1000u || (rest == 0x1000u && (v & 1)))+ v++;+ return (uint16_t)(sign | v);+}++int npu_ir_scalar(struct npu_ir *g, const char *name, float v)+{+ uint16_t h = half(v);+ int one = 1;+ return npu_ir_const(g, name, "f16", 1, &one, &h, 2);+}++int npu_ir_matmul_tb(struct npu_ir *g, const char *name, int a, int b,+ const char *names)+{+ if (a < 0 || a >= g->nl || b < 0 || b >= g->nl || g->nd[a] != 2 ||+ g->nd[b] != 2 || g->dims[a][1] != g->dims[b][1])+ return g->failed = 1, -1;+ int in[2] = {a, b}, dims[2] = {g->dims[a][0], g->dims[b][0]};+ return layer(g, "MatMul", name,+ "<data transpose_a=\"false\" transpose_b=\"true\"/>", g->et[a],+ 2, dims, 2, in, names);+}++void npu_ir_result(struct npu_ir *g, int a)+{+ if (a < 0 || a >= g->nl) {+ g->failed = 1;+ return;+ }+ char name[32];+ snprintf(name, sizeof name, "result_%d", g->nres++);+ layer(g, "Result", name, NULL, g->et[a], g->nd[a], g->dims[a], 1, &a, NULL);+}++int npu_ir_weights_i8(struct npu_ir *g, const char *name, const int8_t *q,+ const uint16_t *s, int rows, int cols)+{+ char nq[48], ns[48], nc[48];+ int wd[2] = {rows, cols}, sd[2] = {rows, 1};+ snprintf(nq, sizeof nq, "%s_q", name);+ snprintf(ns, sizeof ns, "%s_s", name);+ snprintf(nc, sizeof nc, "%s_c", name);+ int lq = npu_ir_const(g, nq, "i8", 2, wd, q, (size_t)rows * cols);+ int ls = npu_ir_const(g, ns, "f16", 2, sd, s, (size_t)rows * 2);+ return npu_ir_multiply(g, name, npu_ir_convert(g, nc, lq, "f16"), ls);+}++int npu_ir_rms_norm(struct npu_ir *g, const char *name, int x, const float *w,+ int d, float eps)+{+ char n[6][48];+ static const char *part[6] = {"sq", "ms", "eps", "rt", "xn", "w"};+ for (int i = 0; i < 6; i++)+ snprintf(n[i], sizeof n[i], "%s_%s", name, part[i]);+ int one = 1;+ int ms = npu_ir_reduce_mean(g, n[1],+ npu_ir_binary(g, n[0], "Multiply", x, x), 1);+ int le = npu_ir_const(g, n[2], "f32", 1, &one, &eps, sizeof eps);+ int rt =+ npu_ir_unary(g, n[3], "Sqrt", npu_ir_binary(g, n[2], "Add", ms, le));+ int xn = npu_ir_binary(g, n[4], "Divide", x, rt);+ int lw = npu_ir_const(g, n[5], "f32", 1, &d, w, sizeof(float) * (size_t)d);+ return npu_ir_binary(g, name, "Multiply", xn, lw);+}++int npu_ir_ffn(struct npu_ir *g, const char *name, int x, int gate, int up,+ int down, int act)+{+ char n[18][48];+ static const char *part[18] = {"g", "u", "sig", "silu", "g2", "g3",+ "c3", "gc3", "gin", "k", "gk", "gt",+ "one", "g1t", "half", "h", "gelu", "gh"};+ for (int i = 0; i < 18; i++)+ snprintf(n[i], sizeof n[i], "%s_%s", name, part[i]);+ int lg = npu_ir_matmul_tb(g, n[0], x, gate, NULL);+ int lu = npu_ir_matmul_tb(g, n[1], x, up, NULL);+ int la;+ if (act == 0) /* g sigmoid(g) */+ la = npu_ir_multiply(g, n[3], lg, npu_ir_unary(g, n[2], "Sigmoid", lg));+ else { /* 0.5 g (1 + tanh(sqrt(2/pi) (g + 0.044715 g^3))) */+ int g3 = npu_ir_multiply(g, n[5], npu_ir_multiply(g, n[4], lg, lg), lg);+ int in = npu_ir_add(+ g, n[8], lg,+ npu_ir_multiply(g, n[7], g3, npu_ir_scalar(g, n[6], 0.044715f)));+ int t = npu_ir_unary(+ g, n[11], "Tanh",+ npu_ir_multiply(g, n[10], in,+ npu_ir_scalar(g, n[9], 0.7978845608f)));+ int one = npu_ir_add(g, n[13], t, npu_ir_scalar(g, n[12], 1.0f));+ la = npu_ir_multiply(+ g, n[16],+ npu_ir_multiply(g, n[17], lg, npu_ir_scalar(g, n[14], 0.5f)), one);+ }+ return npu_ir_matmul_tb(g, name, npu_ir_multiply(g, n[15], la, lu), down,+ NULL);+}++int npu_ir_end(struct npu_ir *g)+{+ put(g, "</layers>\n<edges>\n");+ for (int e = 0; e < g->ne; e++) {+ int f = g->edge[e][0];+ put(g,+ "<edge from-layer=\"%d\" from-port=\"%d\" to-layer=\"%d\" "+ "to-port=\"%d\"/>\n",+ f, g->ins[f], g->edge[e][1], g->edge[e][2]);+ }+ put(g, "</edges>\n</net>\n");+ return g->failed ? -1 : 0;+}++void npu_ir_free(struct npu_ir *g)+{+ free(g->xml);+ free(g->bin);+ memset(g, 0, sizeof(*g));+}++uint8_t *npu_ir_model(const struct npu_ir *g, uint16_t major, uint16_t minor,+ size_t *bytes)+{+ uint64_t sx = g->len, sb = g->nbin;+ uint32_t parts = 2;+ size_t n = 4 + sizeof parts + 8 + sx + 8 + sb, at = 0;+ uint8_t *b = malloc(n);+ if (!b)+ return NULL;+ memcpy(b + at, &major, 2), at += 2;+ memcpy(b + at, &minor, 2), at += 2;+ memcpy(b + at, &parts, sizeof parts), at += sizeof parts;+ memcpy(b + at, &sx, 8), at += 8;+ memcpy(b + at, g->xml, sx), at += sx;+ memcpy(b + at, &sb, 8), at += 8;+ if (sb)+ memcpy(b + at, g->bin, sb);+ *bytes = n;+ return b;+}diff --git a/src/common/npu_ir.h b/src/common/npu_ir.hnew file mode 100644index 0000000..7fae6e4--- /dev/null+++ b/src/common/npu_ir.h@@ -0,0 +1,90 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * npu_ir.h - a small writer of OpenVINO IR (version 11): the XML of a graph+ * and its constants' bytes, the input of the NPU's compiler. Private to+ * npu.c.+ *+ * Layers have one output each; a layer's id is its number, its output+ * port's id its number of inputs, as the IR wants. Element types are IR's+ * names: "f32", "f16", "i8", "i64".+ */+#ifndef JANAS_COMMON_NPU_IR_H+#define JANAS_COMMON_NPU_IR_H++#include <stddef.h>+#include <stdint.h>++#define NPU_IR_LAYERS 160+#define NPU_IR_DIMS 4++struct npu_ir {+ char *xml;+ size_t len, cap;+ uint8_t *bin;+ size_t nbin;+ int nl, ne, failed, nres;+ int nd[NPU_IR_LAYERS], dims[NPU_IR_LAYERS][NPU_IR_DIMS], ins[NPU_IR_LAYERS];+ const char *et[NPU_IR_LAYERS];+ int edge[NPU_IR_LAYERS * 2][3]; /* from, to, to's port */+};++void npu_ir_begin(struct npu_ir *g, const char *name);+int npu_ir_param(struct npu_ir *g, const char *name, const char *et, int nd,+ const int *dims);+/* bytes copied into the constants */+int npu_ir_const(struct npu_ir *g, const char *name, const char *et, int nd,+ const int *dims, const void *p, size_t bytes);+int npu_ir_convert(struct npu_ir *g, const char *name, int a, const char *et);+int npu_ir_multiply(struct npu_ir *g, const char *name, int a, int b);+int npu_ir_add(struct npu_ir *g, const char *name, int a, int b);+/* an element-wise operation of two inputs, numpy broadcast, of opset1:+ "Add", "Subtract", "Multiply", "Divide" (output dims: the larger of+ each) */+int npu_ir_binary(struct npu_ir *g, const char *name, const char *type, int a,+ int b);+/* the mean along one axis, kept as a dimension of 1 */+int npu_ir_reduce_mean(struct npu_ir *g, const char *name, int a, int axis);+/* any reduction of opset1 along one axis, kept: "ReduceMean", "ReduceMax" */+int npu_ir_reduce(struct npu_ir *g, const char *name, const char *type, int a,+ int axis);+/* an element-wise function of opset1: "Sigmoid", "Tanh", "Sqrt", "Abs" */+int npu_ir_unary(struct npu_ir *g, const char *name, const char *type, int a);+/* a's values on levels steps between lo and hi (opset1 FakeQuantize): how+ OpenVINO asks for integer arithmetic */+int npu_ir_fake_quantize(struct npu_ir *g, const char *name, int a, float lo,+ float hi, int levels);+/* a constant of one FP16 number, broadcast against anything */+int npu_ir_scalar(struct npu_ir *g, const char *name, float v);+/* a x b^T for 2-D a (m x k) and b (n x k) */+int npu_ir_matmul_tb(struct npu_ir *g, const char *name, int a, int b,+ const char *names);+void npu_ir_result(struct npu_ir *g, int a);+/* ---- composites ---- */++/* weights of rows x cols in INT8 with an FP16 scale a row, as FP16 */+int npu_ir_weights_i8(struct npu_ir *g, const char *name, const int8_t *q,+ const uint16_t *s, int rows, int cols);+/* x (m x d, f32) normalized by its root mean square, times w (d floats),+ in f32: the sum of squares of a residual with outliers in the tens of+ thousands stays finite (tested to 30000, 20 Oct 2026) */+int npu_ir_rms_norm(struct npu_ir *g, const char *name, int x, const float *w,+ int d, float eps);+/* down (act(x gate^T) * (x up^T)), x FP16 m x d, the three matrices from+ npu_ir_weights_i8 (gate and up ff x d, down d x ff); act 0 SiLU, 1 the+ tanh form of GELU; FP16 out (m x d) */+int npu_ir_ffn(struct npu_ir *g, const char *name, int x, int gate, int up,+ int down, int act);++/* closes the XML; 0, or -1 if any step failed (out of memory or layers) */+int npu_ir_end(struct npu_ir *g);+void npu_ir_free(struct npu_ir *g);++/*+ * The compiler's input: its version, the number of parts (2), then the+ * XML's and the constants' sizes and bytes. Malloc'd, NULL on failure.+ */+uint8_t *npu_ir_model(const struct npu_ir *g, uint16_t major, uint16_t minor,+ size_t *bytes);++#endifdiff --git a/src/common/npu_ze.h b/src/common/npu_ze.hnew file mode 100644index 0000000..828c82f--- /dev/null+++ b/src/common/npu_ze.h@@ -0,0 +1,159 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * npu_ze.h - the part of Level Zero that npu.c calls, declared here so that+ * Janas builds without Level Zero's headers and loads the loader at run time.+ *+ * Layouts and values as in the oneAPI Level Zero specification (core API)+ * and Intel's NPU graph extension ("ZE_extension_graph", 1.5 and later):+ * only the fields and the table entries npu.c uses, the others as padding+ * of the same size. Private to npu.c.+ */+#ifndef JANAS_COMMON_NPU_ZE_H+#define JANAS_COMMON_NPU_ZE_H++#include <stddef.h>+#include <stdint.h>++typedef int32_t ze_result_t; /* 0 success */+typedef struct ze_driver *ze_driver_handle_t;+typedef struct ze_device *ze_device_handle_t;+typedef struct ze_context *ze_context_handle_t;+typedef struct ze_queue *ze_command_queue_handle_t;+typedef struct ze_list *ze_command_list_handle_t;+typedef struct ze_fence *ze_fence_handle_t;+typedef struct ze_graph *ze_graph_handle_t;++#define ZE_INIT_FLAG_VPU_ONLY 2u+#define ZE_DEVICE_TYPE_VPU 5++/* structure types of the core API */+#define ZE_STYPE_DRIVER_PROPERTIES 0x1+#define ZE_STYPE_DEVICE_PROPERTIES 0x3+#define ZE_STYPE_CONTEXT_DESC 0xd+#define ZE_STYPE_COMMAND_QUEUE_DESC 0xe+#define ZE_STYPE_COMMAND_LIST_DESC 0xf+#define ZE_STYPE_FENCE_DESC 0x12+#define ZE_STYPE_HOST_MEM_ALLOC_DESC 0x16++/* the graph extension's */+#define ZE_GSTYPE_DEVICE_GRAPH_PROPERTIES 0x1+#define ZE_GSTYPE_GRAPH_PROPERTIES 0x3+#define ZE_GSTYPE_GRAPH_ARGUMENT_PROPERTIES 0x4+#define ZE_GSTYPE_GRAPH_DESC_2 0xe+#define ZE_GRAPH_FORMAT_NATIVE 0x1+#define ZE_GRAPH_FORMAT_NGRAPH_LITE 0x2+#define ZE_GRAPH_FLAG_DISABLE_CACHING 1u+#define ZE_GRAPH_ARGUMENT_TYPE_INPUT 0+#define ZE_GRAPH_EXT_NAME "ZE_extension_graph"++typedef struct {+ int32_t stype;+ void *pNext;+ int32_t type;+ uint32_t vendorId, deviceId, flags, subdeviceId, coreClockRate;+ uint64_t maxMemAllocSize;+ uint32_t maxHardwareContexts, maxCommandQueuePriority, numThreadsPerEU,+ physicalEUSimdWidth, numEUsPerSubslice, numSubslicesPerSlice, numSlices;+ uint64_t timerResolution;+ uint32_t timestampValidBits, kernelTimestampValidBits;+ uint8_t uuid[16];+ char name[256];+} ze_device_properties_t;++typedef struct {+ int32_t stype;+ void *pNext;+ uint8_t uuid[16];+ uint32_t driverVersion;+} ze_driver_properties_t;++typedef struct {+ int32_t stype;+ const void *pNext;+ uint32_t flags;+} ze_simple_desc_t; /* context, fence and host memory descriptors */++typedef struct {+ int32_t stype;+ const void *pNext;+ uint32_t ordinal, index, flags;+ int32_t mode, priority;+} ze_command_queue_desc_t;++typedef struct {+ int32_t stype;+ const void *pNext;+ uint32_t commandQueueGroupOrdinal, flags;+} ze_command_list_desc_t;++/* the NPU's queue extension ("ZE_extension_command_queue_npu" 1.0): turbo,+ chained to a queue's descriptor */+#define ZE_NSTYPE_COMMAND_QUEUE_DESC_NPU_EXT 0x1+typedef struct {+ int32_t stype;+ const void *pNext;+ _Bool turbo;+} ze_command_queue_desc_npu_ext_t;++typedef struct {+ int32_t stype;+ void *pNext;+ uint32_t graphExtensionVersion;+ uint16_t compilerMajor, compilerMinor;+ int32_t graphFormatsSupported;+ uint32_t maxOVOpsetVersionSupported;+} ze_device_graph_properties_t;++typedef struct {+ int32_t stype;+ const void *pNext;+ int32_t format;+ size_t inputSize;+ const uint8_t *pInput;+ const char *pBuildFlags;+ uint32_t flags;+} ze_graph_desc_2_t;++typedef struct {+ int32_t stype;+ void *pNext;+ uint32_t numGraphArgs;+} ze_graph_properties_t;++typedef struct {+ int32_t stype;+ void *pNext;+ char name[256];+ int32_t type;+ uint32_t dims[5];+ int32_t networkPrecision, networkLayout, devicePrecision, deviceLayout;+} ze_graph_argument_properties_t;++/* the extension's function table, as far as pfnCreate2 (version 1.5) */+typedef struct {+ void *pfnCreate;+ ze_result_t (*pfnDestroy)(ze_graph_handle_t);+ ze_result_t (*pfnGetProperties)(ze_graph_handle_t, ze_graph_properties_t *);+ ze_result_t (*pfnGetArgumentProperties)(ze_graph_handle_t, uint32_t,+ ze_graph_argument_properties_t *);+ ze_result_t (*pfnSetArgumentValue)(ze_graph_handle_t, uint32_t,+ const void *);+ ze_result_t (*pfnAppendGraphInitialize)(ze_command_list_handle_t,+ ze_graph_handle_t, void *, uint32_t,+ void *);+ ze_result_t (*pfnAppendGraphExecute)(ze_command_list_handle_t,+ ze_graph_handle_t, void *, void *,+ uint32_t, void *);+ ze_result_t (*pfnGetNativeBinary)(ze_graph_handle_t, size_t *, uint8_t *);+ ze_result_t (*pfnDeviceGetGraphProperties)(ze_device_handle_t,+ ze_device_graph_properties_t *);+ void *pfnGraphGetArgumentMetadata, *pfnGetArgumentProperties2,+ *pfnGetArgumentProperties3, *pfnQueryNetworkCreate,+ *pfnQueryNetworkDestroy, *pfnQueryNetworkGetSupportedLayers;+ ze_result_t (*pfnBuildLogGetString)(ze_graph_handle_t, uint32_t *, char *);+ ze_result_t (*pfnCreate2)(ze_context_handle_t, ze_device_handle_t,+ const ze_graph_desc_2_t *, ze_graph_handle_t *);+} ze_graph_dditable_ext_t;++#endifdiff --git a/src/common/pool.c b/src/common/pool.cindex 23e25d7..5f70835 100644--- a/src/common/pool.c+++ b/src/common/pool.c@@ -51,8 +51,9 @@ struct done_flag {* the run for the slowest thread. Reading it: a high idle share means the* work does not divide by the threads; the time between runs, which is the* caller working alone, is not here - it is the difference between the wall- * of the whole pass and the sum of this column. Off it costs one test of a- * static variable per run.+ * of the whole pass and the sum of this column - but in gap_s, by the sites+ * of the runs before and after it. Off it costs one test of a static+ * variable per run.*/struct site {janas_pool_fn fn;@@ -63,6 +64,19 @@ struct site {static struct site sites[32];static int n_sites;+/* the caller alone between two runs of a pool, by the sites of the run+ before and the run after: where in a pass the time between runs goes.+ Per pool (struct janas_pool trace_gap): the caller of the experts' reads+ waits for work between its runs, which is not work; the report gives the+ pool that ran most, the one the passes are made of */+struct trace_gaps {+ double s[32][32];+ unsigned long long n[32][32], runs;+};+static unsigned trace_epoch = 1; /* janas_pool_trace_reset: a new count */+static struct janas_pool *traced[8];+static int n_traced;+static pthread_mutex_t traced_lock = PTHREAD_MUTEX_INITIALIZER;/* read by every worker, so atomic: they all decide the same thing, but aplain int written by twenty threads is still a race */static atomic_int trace = -1;@@ -101,6 +115,10 @@ struct janas_pool {struct done_flag *done; /* done[i].run: the last run thread i finished */atomic_int sleepers; /* threads waiting on a condition variable */double work_prev; /* the trace: sum of done[].work, last run */+ double trace_end; /* ... when the last run ended, its site */+ int trace_site;+ unsigned trace_epoch;+ struct trace_gaps *trace_gap; /* allocated by the first traced run */atomic_bool stop;atomic_int spin; /* pause iterations before a worker sleeps */int active; /* threads that take part in the next runs */@@ -219,7 +237,7 @@ struct janas_pool *janas_pool_create(int n_threads, const int *cpus)}static void pool_trace_run(struct janas_pool *p, janas_pool_fn fn,- const char *name, double wall, int active);+ const char *name, double t0, double t1, int active);void janas_pool_run_named(struct janas_pool *p, janas_pool_fn fn, void *arg,const char *name)@@ -259,13 +277,14 @@ void janas_pool_run_named(struct janas_pool *p, janas_pool_fn fn, void *arg,p->runs)cpu_relax();if (tracing())- pool_trace_run(p, fn, name, now() - t0, active);+ pool_trace_run(p, fn, name, t0, now(), active);}/* The trace of one run, from the caller's thread: nothing here is shared. */static void pool_trace_run(struct janas_pool *p, janas_pool_fn fn,- const char *name, double wall, int active)+ const char *name, double t0, double t1, int active){+ double wall = t1 - t0;double w = 0;for (int i = 0; i < active; i++)w += p->done[i].work;@@ -284,6 +303,25 @@ static void pool_trace_run(struct janas_pool *p, janas_pool_fn fn,sites[i].threads += (unsigned long long)active;sites[i].runs++;p->work_prev = w;+ if (!p->trace_gap) {+ pthread_mutex_lock(&traced_lock);+ if (n_traced < 8 && (p->trace_gap = calloc(1, sizeof *p->trace_gap)))+ traced[n_traced++] = p;+ pthread_mutex_unlock(&traced_lock);+ if (!p->trace_gap)+ return;+ }+ struct trace_gaps *g = p->trace_gap;+ if (p->trace_epoch != trace_epoch) /* a new count: from this run on */+ memset(g, 0, sizeof *g);+ else {+ g->s[p->trace_site][i] += t0 - p->trace_end;+ g->n[p->trace_site][i]++;+ }+ g->runs++;+ p->trace_epoch = trace_epoch;+ p->trace_end = t1;+ p->trace_site = i;}void janas_pool_trace_reset(void)@@ -292,6 +330,7 @@ void janas_pool_trace_reset(void)sites[i].wall = sites[i].work = 0;sites[i].runs = sites[i].threads = 0;}+ trace_epoch++;}void janas_pool_trace_report(const char *what, double wall)@@ -326,6 +365,44 @@ void janas_pool_trace_report(const char *what, double wall)}fprintf(stderr, " %-16s %9s %6s %9.1f %7.1f%%\n", "all", "", "", tw * 1e3,off > 0 ? 100 * (off - tk) / off : 0);+ /* the caller alone, by the runs it falls between, in the pool that ran+ most since the reset: the largest */+ struct trace_gaps *g = NULL;+ pthread_mutex_lock(&traced_lock);+ for (int k = 0; k < n_traced; k++)+ if (traced[k]->trace_epoch == trace_epoch &&+ (!g || traced[k]->trace_gap->runs > g->runs))+ g = traced[k]->trace_gap;+ pthread_mutex_unlock(&traced_lock);+ if (!g)+ return;+ double gt = 0;+ for (int a = 0; a < n_sites; a++)+ for (int b = 0; b < n_sites; b++)+ gt += g->s[a][b];+ if (gt <= 0)+ return;+ fprintf(stderr,+ "the caller alone between runs, %.0f ms:\n%-36s %9s %9s "+ "%9s\n",+ gt * 1e3, " after -> before", "times", "ms", "us each");+ static char listed[32][32];+ memset(listed, 0, sizeof listed);+ for (int k = 0; k < 16; k++) {+ int ba = -1, bb = -1;+ for (int a = 0; a < n_sites; a++)+ for (int b = 0; b < n_sites; b++)+ if (g->n[a][b] && !listed[a][b] &&+ (ba < 0 || g->s[a][b] > g->s[ba][bb]))+ ba = a, bb = b;+ if (ba < 0 || g->s[ba][bb] < 0.005 * gt)+ break;+ listed[ba][bb] = 1;+ char pair[64];+ snprintf(pair, sizeof pair, "%s -> %s", sites[ba].name, sites[bb].name);+ fprintf(stderr, " %-34s %9llu %9.1f %9.1f\n", pair, g->n[ba][bb],+ g->s[ba][bb] * 1e3, g->s[ba][bb] * 1e6 / g->n[ba][bb]);+ }}int janas_pool_get_spin(const struct janas_pool *p)@@ -358,6 +435,14 @@ void janas_pool_destroy(struct janas_pool *p){if (!p)return;+ if (p->trace_gap) {+ pthread_mutex_lock(&traced_lock);+ for (int k = 0; k < n_traced; k++)+ if (traced[k] == p)+ traced[k] = traced[--n_traced];+ pthread_mutex_unlock(&traced_lock);+ free(p->trace_gap);+ }pthread_mutex_lock(&p->lock);atomic_store(&p->stop, true);pthread_cond_broadcast(&p->wake);diff --git a/src/common/pool.h b/src/common/pool.hindex 47f7a5f..a979b6e 100644--- a/src/common/pool.h+++ b/src/common/pool.h@@ -35,7 +35,9 @@ int janas_pool_size(const struct janas_pool *p);* used and how much of that thread time was spent at the end of a run* waiting for the slowest. The time between runs - the caller working alone -* is not in the table: it is what the wall of the pass has more than the sum- * of the wall column. Off, it costs one test of a static variable per run.+ * of the wall column; a second table gives it by the sites of the runs it+ * falls between, the largest first. Off, it costs one test of a static+ * variable per run.*/void janas_pool_trace_report(const char *what, double wall);void janas_pool_trace_reset(void);diff --git a/src/common/sysinfo.c b/src/common/sysinfo.cindex cb77cdb..af063cc 100644--- a/src/common/sysinfo.c+++ b/src/common/sysinfo.c@@ -288,4 +288,16 @@ uint64_t janas_mem_total(void)return meminfo("MemTotal");}+uint64_t janas_rss_bytes(void)+{+ FILE *f = fopen("/proc/self/statm", "r");+ if (!f)+ return 0;+ unsigned long long size = 0, resident = 0;+ int ok = fscanf(f, "%llu %llu", &size, &resident) == 2;+ fclose(f);+ long page = sysconf(_SC_PAGESIZE);+ return ok && page > 0 ? (uint64_t)resident * (uint64_t)page : 0;+}+#endif /* !_WIN32 */diff --git a/src/common/sysinfo.h b/src/common/sysinfo.hindex ac2dce2..b9e0bce 100644--- a/src/common/sysinfo.h+++ b/src/common/sysinfo.h@@ -58,4 +58,7 @@ uint64_t janas_mem_available(void);/* Installed memory, in bytes (0 if unknown). */uint64_t janas_mem_total(void);+/* The process's resident memory now, in bytes (0 if unknown). */+uint64_t janas_rss_bytes(void);+#endifdiff --git a/src/common/sysinfo_win.c b/src/common/sysinfo_win.cindex 65f3e8a..f060e7d 100644--- a/src/common/sysinfo_win.c+++ b/src/common/sysinfo_win.c@@ -22,6 +22,7 @@#include <windows.h>#include <cpuid.h>#include <powrprof.h>+#include <psapi.h>#include <stdio.h>#include <stdlib.h>#include <string.h>@@ -291,4 +292,12 @@ uint64_t janas_mem_total(void)return GlobalMemoryStatusEx(&m) ? m.ullTotalPhys : 0;}+uint64_t janas_rss_bytes(void)+{+ PROCESS_MEMORY_COUNTERS pmc = {.cb = sizeof pmc};+ return GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof pmc)+ ? pmc.WorkingSetSize+ : 0;+}+#endif /* _WIN32 */diff --git a/src/llm/api.c b/src/llm/api.cindex 1794614..9af2c19 100644--- a/src/llm/api.c+++ b/src/llm/api.c@@ -20,6 +20,8 @@#include <sys/stat.h>#include <time.h>+#include "common/devices.h"+#include "common/npu.h"#include "common/sysinfo.h"#include "llm/arch.h"#include "llm/attention.h"@@ -27,6 +29,7 @@#include "llm/generate.h"#include "llm/jns.h"#include "llm/model.h"+#include "llm/quant.h"#include "llm/tokenizer.h"#include "llm/chat.h"#include "llm/metrics.h"@@ -199,57 +202,68 @@ static int32_t find_format(janas_llm *llm, const struct janas_jns *j)return rc;}-int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,- janas_llm **out)+/*+ * What a model takes besides its expert cache, from its file's header and+ * metadata, for n_ctx tokens of context: janas_llm_open's estimate, and+ * janas_llm_estimate's, the one same reckoning.+ */+struct mem_need {+ uint64_t resident; /* the resident weights the engine reads in */+ uint64_t experts; /* a cache holding every expert slot */+ uint64_t kv_token; /* keys and values a token of context */+ uint64_t ring_bytes; /* sliding-window layers' rings, all positions */+ uint32_t ring; /* their positions */+ uint64_t attn_part; /* attention's partial results beside the cache */+ uint64_t scratch; /* a pass's scratch */+ uint64_t npu; /* the NPU's copies of its matrices (model_npu.c) */+};++/*+ * The memory the NPU's copies will take, if an NPU is there to use+ * (JANAS_NPU not 0): its matrices - the resident ones a block's products+ * read, and a dense model's feed-forwards - in INT8, within+ * JANAS_NPU_MAX_MB, times 1.3 for what its driver keeps (measured 0.3-1.3+ * on Meteor Lake, 20 Oct 2026), and 128 MB for the compiler. Taken from the+ * expert cache's share: without it the copies came on top of a cache sized+ * to the memory, and Qwen3-Next-80B ran out of it as the NPU's+ * configurations began.+ */+static uint64_t npu_need(const struct janas_jns *j){- struct janas_llm_params p;- janas_llm_params_default(&p);- if (!path || !out)- return janas_api_fail(JANAS_LLM_EINVAL, "no path or no output handle");- double t_open = janas_api_now();- *out = NULL;- if (pp) {- if (pp->size < sizeof(uint32_t) || pp->size > sizeof(p))- return janas_api_fail(JANAS_LLM_EINVAL, "parameters: unknown size");- memcpy(&p, pp, pp->size);- p.size = sizeof(p);+ const char *e = getenv("JANAS_NPU");+ if ((e && atoi(e) <= 0) || !janas_npu_available())+ return 0;+ uint64_t n = 0, r0 = j->h.resident_offset, r1 = r0 + j->h.resident_bytes;+ for (uint64_t i = 0; i < j->h.n_tensor; i++) {+ const struct janas_jns_tensor *t = &j->tensors[i];+ int type = (int)t->type;+ if (t->n_dims != 2 || t->offset < r0 || t->offset >= r1 ||+ !(type == JANAS_Q4_K || type == JANAS_Q5_K || type == JANAS_Q6_K ||+ type == JANAS_Q8_0) ||+ strstr(t->name, "token_embd") || !strcmp(t->name, "output.weight"))+ continue;+ n += t->dims[0] * t->dims[1];}- if (p.n_ctx == 0)- p.n_ctx = 16384;- janas_llm *llm = calloc(1, sizeof(*llm));- if (!llm)- return janas_api_fail(JANAS_LLM_ENOMEM, "out of memory");- llm->gpu_wanted = 1; /* wanted unless the caller says otherwise */+ for (uint32_t l = 0; j->h.n_expert <= 1 && l < j->h.n_layer; l++)+ for (int k = 0; k < 3; k++)+ n += (uint64_t)j->layers[l].m[k].rows * j->layers[l].m[k].cols;+ const char *mb = getenv("JANAS_NPU_MAX_MB");+ uint64_t budget = (uint64_t)(mb && atol(mb) > 0 ? atol(mb) : 4096) << 20;+ if (n > budget)+ n = budget;+ return n ? n / 10 * 13 + ((uint64_t)128 << 20) : 0;+}- /* the tokenizer and the chat format, from the file's metadata */- struct janas_jns j;- char err[256] = "";- if (janas_jns_open(path, &j, err, sizeof(err)) != 0) {- free(llm);- return janas_api_fail(JANAS_LLM_EOPEN, "%s: %s", path, err);- }- char kind[64] = "", pre[64] = "", name[96] = "", arch[32] = "";- janas_jns_meta_str(&j, "tokenizer.ggml.model", kind, sizeof(kind));- janas_jns_meta_str(&j, "tokenizer.ggml.pre", pre, sizeof(pre));- janas_jns_meta_str(&j, "general.name", name, sizeof(name));- janas_jns_meta_str(&j, "general.architecture", arch, sizeof(arch));- int32_t rc = 0;- /* byte-level BPE with Qwen's pre-tokenizers, or Gemma 4's */- int known = (strcmp(kind, "gpt2") == 0 &&- (strcmp(pre, "qwen2") == 0 || strcmp(pre, "qwen35") == 0)) ||- strcmp(kind, "gemma4") == 0;- if (!known)- rc = janas_api_fail(JANAS_LLM_EMODEL, "tokenizer %s/%s not supported",- kind, pre);- else if (!(llm->tok = janas_tokenizer_create(&j, err, sizeof(err))))- rc = janas_api_fail(JANAS_LLM_EMODEL, "tokenizer: %s", err);- else- rc = find_format(llm, &j);- uint64_t resident = j.h.resident_bytes;+static void mem_need(const struct janas_jns *j, uint32_t n_ctx, int mtp_file,+ struct mem_need *e)+{+ char arch[32] = "";+ janas_jns_meta_str(j, "general.architecture", arch, sizeof(arch));+ uint64_t resident = j->h.resident_bytes;/* less Gemma 4's per-layer embeddings, read from the file a row at atime (model_ple.c) */const struct janas_jns_tensor *ple =- janas_jns_tensor(&j, "per_layer_token_embd.weight");+ janas_jns_tensor(j, "per_layer_token_embd.weight");if (ple && ple->bytes < resident)resident -= ple->bytes;/* what the cache would need to hold every slot at once. Not the size of@@ -262,21 +276,21 @@ int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,file with larger experts has slots of its own (expert_cache.hcreate_split), and none is asked of it when the block comes in afile of its own (model_load.c). */- uint32_t n_main = janas_llm_main_layers(&j);- uint64_t experts = janas_expert_cache_room(- &j, p.mtp_path ? n_main : j.h.n_layer, n_main, 3);- if (experts < j.h.experts_bytes)- experts = j.h.experts_bytes;+ uint32_t n_main = janas_llm_main_layers(j);+ uint64_t experts =+ janas_expert_cache_room(j, mtp_file ? n_main : j->h.n_layer, n_main, 3);+ if (experts < j->h.experts_bytes)+ experts = j->h.experts_bytes;/* what a token of context costs: keys and values of the layers thathave them, one byte a number with a scale per position and KV head */- uint32_t n_layer = j.h.n_layer, kv_heads = 0, kv_len = 0, train = 0;+ uint32_t n_layer = j->h.n_layer, kv_heads = 0, kv_len = 0, train = 0;char key[96];snprintf(key, sizeof(key), "%.32s.attention.head_count_kv", arch);- janas_jns_meta_u32(&j, key, &kv_heads);+ janas_jns_meta_u32(j, key, &kv_heads);snprintf(key, sizeof(key), "%.32s.attention.key_length", arch);- janas_jns_meta_u32(&j, key, &kv_len);+ janas_jns_meta_u32(j, key, &kv_len);snprintf(key, sizeof(key), "%.32s.context_length", arch);- janas_jns_meta_u32(&j, key, &train);+ janas_jns_meta_u32(j, key, &train);uint64_t kv_token = (uint64_t)n_layer * kv_heads * (kv_len * 2 + 8);/* hybrids that give one count for all layers (Qwen3-Next, Qwen3.5 and3.6): only every full_attention_interval-th layer has keys and values@@ -288,7 +302,7 @@ int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,if (a && a->rec != JANAS_REC_NONE) {uint32_t interval = 4;snprintf(key, sizeof(key), "%.32s.full_attention_interval", arch);- janas_jns_meta_u32(&j, key, &interval);+ janas_jns_meta_u32(j, key, &interval);if (interval > 0)kv_token = (uint64_t)(n_layer / interval + 1) * kv_heads *(kv_len * 2 + 8);@@ -306,24 +320,24 @@ int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,uint64_t ring_bytes = 0;uint32_t ring = 0;snprintf(key, sizeof(key), "%.32s.attention.sliding_window", arch);- if (janas_jns_meta_u32(&j, key, &window) == 0 && window) {+ if (janas_jns_meta_u32(j, key, &window) == 0 && window) {const char *rg = getenv("JANAS_SWA_RING");- ring = janas_attn_ring_positions(window, janas_llm_prefill_block(&j));- if (ring >= p.n_ctx || (rg && atoi(rg) == 0))+ ring = janas_attn_ring_positions(window, janas_llm_prefill_block(j));+ if (ring >= n_ctx || (rg && atoi(rg) == 0))ring = 0;}snprintf(key, sizeof(key), "%.32s.attention.sliding_window_pattern", arch);- if (janas_jns_meta_bytes(&j, key, &n_pat, &pat) != 0 || n_pat != n_layer)+ if (janas_jns_meta_bytes(j, key, &n_pat, &pat) != 0 || n_pat != n_layer)pat = NULL;snprintf(key, sizeof(key), "%.32s.attention.key_length_swa", arch);- janas_jns_meta_u32(&j, key, &len_swa);+ janas_jns_meta_u32(j, key, &len_swa);/* E2B and E4B: one count of KV heads for both kinds, and the lastshared_kv_layers layers reading earlier layers' keys and values */uint32_t shared = 0;snprintf(key, sizeof(key), "%.32s.attention.shared_kv_layers", arch);- janas_jns_meta_u32(&j, key, &shared);+ janas_jns_meta_u32(j, key, &shared);snprintf(key, sizeof(key), "%.32s.attention.head_count_kv", arch);- int arr = janas_jns_meta_ints(&j, key, &n_arr, &per_layer) == 0 &&+ int arr = janas_jns_meta_ints(j, key, &n_arr, &per_layer) == 0 &&per_layer && n_arr == n_layer;if (arr || (pat && kv_heads)) {uint32_t one = kv_heads;@@ -353,14 +367,14 @@ int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,1.08 GB of partial results in the margin left to other programs */uint32_t n_head = 0;snprintf(key, sizeof(key), "%.32s.attention.head_count", arch);- janas_jns_meta_u32(&j, key, &n_head);+ janas_jns_meta_u32(j, key, &n_head);uint64_t attn_part =n_head && kv_heads && kv_len- ? janas_attn_part_bytes(n_head, kv_heads, kv_len, p.n_ctx)+ ? janas_attn_part_bytes(n_head, kv_heads, kv_len, n_ctx): 0;if (pat && n_head && kv_swa && len_swa)attn_part += janas_attn_part_bytes(n_head, kv_swa, len_swa,- ring ? ring : p.n_ctx) ++ ring ? ring : n_ctx) +ring_bytes;/* and the scratch of a pass, which grows with the prefill block(janas_llm_model_max_block): per token, the rows of its experts (gate,@@ -368,14 +382,14 @@ int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,estimate from the shapes, on the generous side */uint32_t embd = 0, ff = 0, k_used = 1;snprintf(key, sizeof(key), "%.32s.embedding_length", arch);- janas_jns_meta_u32(&j, key, &embd);+ janas_jns_meta_u32(j, key, &embd);snprintf(key, sizeof(key), "%.32s.expert_feed_forward_length", arch);- if (janas_jns_meta_u32(&j, key, &ff) != 0) {+ if (janas_jns_meta_u32(j, key, &ff) != 0) {snprintf(key, sizeof(key), "%.32s.feed_forward_length", arch);const int32_t *ffs = NULL;uint64_t n_ff = 0;- if (janas_jns_meta_u32(&j, key, &ff) != 0 &&- janas_jns_meta_ints(&j, key, &n_ff, &ffs) == 0 && ffs)+ if (janas_jns_meta_u32(j, key, &ff) != 0 &&+ janas_jns_meta_ints(j, key, &n_ff, &ffs) == 0 && ffs)for (uint64_t i = 0; i < n_ff; i++) { /* E2B: the widest */int32_t v;memcpy(&v, ffs + i, sizeof(v));@@ -384,13 +398,84 @@ int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,}}snprintf(key, sizeof(key), "%.32s.expert_used_count", arch);- janas_jns_meta_u32(&j, key, &k_used);- uint64_t blk = janas_llm_prefill_block(&j);+ janas_jns_meta_u32(j, key, &k_used);+ uint64_t blk = janas_llm_prefill_block(j);if (blk < 256)blk = 256;uint64_t scratch =blk * (((uint64_t)k_used + 1) * (3ull * ff + embd) + 32ull * embd) *sizeof(float);+ *e = (struct mem_need){.resident = resident,+ .experts = experts,+ .kv_token = kv_token,+ .ring_bytes = ring_bytes,+ .ring = ring,+ .attn_part = attn_part,+ .scratch = scratch,+ .npu = npu_need(j)};+}++/* What a model needs whatever its expert cache: the resident weights, the+ keys and values of p->n_ctx tokens, the attention's partial results, a+ pass's scratch and the MTP file (with 256 MiB of its own cache). */+static uint64_t mem_fixed(const struct mem_need *e,+ const struct janas_llm_params *p)+{+ uint64_t need = e->resident + (uint64_t)p->n_ctx * e->kv_token ++ e->attn_part + e->scratch + e->npu;+ if (p->mtp_path)+ need += file_size(p->mtp_path) + ((uint64_t)256 << 20);+ return need;+}++int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,+ janas_llm **out)+{+ struct janas_llm_params p;+ janas_llm_params_default(&p);+ if (!path || !out)+ return janas_api_fail(JANAS_LLM_EINVAL, "no path or no output handle");+ double t_open = janas_api_now();+ *out = NULL;+ if (pp) {+ if (pp->size < sizeof(uint32_t) || pp->size > sizeof(p))+ return janas_api_fail(JANAS_LLM_EINVAL, "parameters: unknown size");+ memcpy(&p, pp, pp->size);+ p.size = sizeof(p);+ }+ if (p.n_ctx == 0)+ p.n_ctx = 16384;+ janas_llm *llm = calloc(1, sizeof(*llm));+ if (!llm)+ return janas_api_fail(JANAS_LLM_ENOMEM, "out of memory");+ llm->gpu_wanted = 1; /* wanted unless the caller says otherwise */++ /* the tokenizer and the chat format, from the file's metadata */+ struct janas_jns j;+ char err[256] = "";+ if (janas_jns_open(path, &j, err, sizeof(err)) != 0) {+ free(llm);+ return janas_api_fail(JANAS_LLM_EOPEN, "%s: %s", path, err);+ }+ char kind[64] = "", pre[64] = "", name[96] = "", arch[32] = "";+ janas_jns_meta_str(&j, "tokenizer.ggml.model", kind, sizeof(kind));+ janas_jns_meta_str(&j, "tokenizer.ggml.pre", pre, sizeof(pre));+ janas_jns_meta_str(&j, "general.name", name, sizeof(name));+ janas_jns_meta_str(&j, "general.architecture", arch, sizeof(arch));+ int32_t rc = 0;+ /* byte-level BPE with Qwen's pre-tokenizers, or Gemma 4's */+ int known = (strcmp(kind, "gpt2") == 0 &&+ (strcmp(pre, "qwen2") == 0 || strcmp(pre, "qwen35") == 0)) ||+ strcmp(kind, "gemma4") == 0;+ if (!known)+ rc = janas_api_fail(JANAS_LLM_EMODEL, "tokenizer %s/%s not supported",+ kind, pre);+ else if (!(llm->tok = janas_tokenizer_create(&j, err, sizeof(err))))+ rc = janas_api_fail(JANAS_LLM_EMODEL, "tokenizer: %s", err);+ else+ rc = find_format(llm, &j);+ struct mem_need e;+ mem_need(&j, p.n_ctx, p.mtp_path != NULL, &e);janas_jns_close(&j);if (rc != 0) {janas_tokenizer_destroy(llm->tok);@@ -410,16 +495,36 @@ int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,reserve = (uint64_t)2 << 30;}uint64_t cache = p.cache_bytes;+ int no_npu = 0;if (cache == 0) {- uint64_t avail = janas_mem_available(), need = resident;- need += reserve;- need += (uint64_t)p.n_ctx * kv_token + attn_part + scratch;- if (p.mtp_path)- need += file_size(p.mtp_path) + ((uint64_t)256 << 20);+ uint64_t avail = janas_mem_available(),+ need = mem_fixed(&e, &p) + reserve;cache = avail > need + ((uint64_t)1 << 30) ? avail - need: (uint64_t)1 << 30;- if (cache > experts)- cache = experts;+ /*+ * The NPU's copies come out of the cache's share only where the+ * cache still holds every expert without that memory (a dense+ * model's feed-forwards are its experts): elsewhere the cache needs+ * it more. Qwen3.8-27B wrote 1.7 tokens/s with a cache of 10.9 GiB,+ * 5.4 GiB having gone to copies for an NPU the engine then left+ * alone, the GPU reading its prompts faster; it wrote 4.4 without+ * (21 Oct 2026). There the NPU stays off, unless the user asks it+ * to read the prompts (--prompt-on npu).+ */+ if (e.npu && cache < e.experts) {+ char why[96];+ int on =+ janas_devices_mask(getenv("JANAS_PROMPT_ON"), why, sizeof why);+ if (on <= 0 || !(on & (1 << JANAS_DEV_NPU |+ 1 << (JANAS_DEV_GPU | JANAS_DEV_NPU)))) {+ uint64_t need0 = need - e.npu;+ no_npu = 1;+ cache = avail > need0 + ((uint64_t)1 << 30) ? avail - need0+ : (uint64_t)1 << 30;+ }+ }+ if (cache > e.experts)+ cache = e.experts;}/* compute: every usable core (the tuner picks how many per pass);I/O: the efficiency cores, or unpinned */@@ -443,7 +548,8 @@ int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,.warm = !p.no_preload,.expert_bits = p.expert_bits,.attn_scores = p.attn_scores,- .head_bits = p.head_bits};+ .head_bits = p.head_bits,+ .no_npu = no_npu};llm->m = janas_llm_model_load(path, &mo, err, sizeof(err));if (!llm->m) {janas_tokenizer_destroy(llm->tok);@@ -521,9 +627,9 @@ int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,h16 == 30 ? "BF16" : "F16", d0 / 1e6, d1 / 1e6);llm->cache_bytes = cache;llm->reserve_bytes = reserve;- llm->kv_token = kv_token;- llm->kv_ring = ring;- llm->kv_ring_token = ring ? ring_bytes / ring : 0;+ llm->kv_token = e.kv_token;+ llm->kv_ring = e.ring;+ llm->kv_ring_token = e.ring ? e.ring_bytes / e.ring : 0;llm->n_compute = mo.n_compute;snprintf(llm->arch, sizeof(llm->arch), "%s", arch);snprintf(llm->bits, sizeof(llm->bits), "%s", bits);@@ -533,6 +639,51 @@ int32_t janas_llm_open(const char *path, const struct janas_llm_params *pp,return JANAS_LLM_OK;}+int32_t janas_llm_estimate(const char *path, const struct janas_llm_params *pp,+ uint64_t *fixed, uint64_t *experts)+{+ struct janas_llm_params p;+ janas_llm_params_default(&p);+ if (!path)+ return janas_api_fail(JANAS_LLM_EINVAL, "no path");+ if (pp) {+ if (pp->size < sizeof(uint32_t) || pp->size > sizeof(p))+ return janas_api_fail(JANAS_LLM_EINVAL, "parameters: unknown size");+ memcpy(&p, pp, pp->size);+ p.size = sizeof(p);+ }+ if (p.n_ctx == 0)+ p.n_ctx = 16384;+ struct janas_jns j;+ char err[256] = "";+ if (janas_jns_open(path, &j, err, sizeof(err)) != 0)+ return janas_api_fail(JANAS_LLM_EOPEN, "%s: %s", path, err);+ struct mem_need e;+ mem_need(&j, p.n_ctx, p.mtp_path != NULL, &e);+ janas_jns_close(&j);+ if (fixed)+ *fixed = mem_fixed(&e, &p);+ if (experts)+ *experts = e.experts;+ return 0;+}++int32_t janas_llm_memory(const janas_llm *llm, uint64_t *resident,+ uint64_t *cache, uint64_t *kv)+{+ if (!llm)+ return janas_api_fail(JANAS_LLM_EINVAL, "no model");+ uint64_t r, c, k;+ janas_llm_model_memory(llm->m, &r, &c, &k);+ if (resident)+ *resident = r;+ if (cache)+ *cache = c;+ if (kv)+ *kv = k;+ return 0;+}+void janas_llm_close(janas_llm *llm){if (!llm)@@ -607,6 +758,14 @@ int32_t janas_llm_preload(const janas_llm *llm, int64_t *done, int64_t *total)return JANAS_LLM_OK;}+int32_t janas_llm_npu_preparing(const janas_llm *llm, int32_t *done,+ int32_t *total, double *seconds)+{+ if (!llm)+ return janas_api_fail(JANAS_LLM_EINVAL, "no model");+ return janas_llm_model_npu_preparing(llm->m, done, total, seconds);+}+int32_t janas_llm_set_experts(janas_llm *llm, int32_t n){if (!llm || n < 0)diff --git a/src/llm/gpu.c b/src/llm/gpu.cindex 067db6e..35e5d47 100644--- a/src/llm/gpu.c+++ b/src/llm/gpu.c@@ -37,6 +37,7 @@#include "q80_mmq.h" /* janas_spv_q80_mmq */#include "q5k_mmq.h" /* janas_spv_q5k_mmq */#include "dense_mm.h" /* janas_spv_dense_mm */+#include "q3k_mmid.h" /* janas_spv_q3k_mmid */#include "q4k_mmid.h" /* janas_spv_q4k_mmid */#include "q6kp_mmid.h" /* janas_spv_q6kp_mmid */#include "q6k_mmid.h" /* janas_spv_q6k_mmid */@@ -605,6 +606,12 @@ struct janas_gpu *janas_gpu_create(char *err, size_t err_len)set_err(err, err_len, "cannot create the shaders", r);goto fail;}+ /* a mixture's Q3_K experts (q3k_mmid.comp): without it they stay on+ the CPU, as they all did until 21 Oct 2026 */+ if (make_pipeline(g, janas_spv_q3k_mmid, sizeof(janas_spv_q3k_mmid),+ &g->sm_id3, &g->pipe_id3, 0, NV_PER_GROUP,+ g->sg) != VK_SUCCESS)+ g->pipe_id3 = VK_NULL_HANDLE;/* each product shader made for a single vector too */{const struct {@@ -923,12 +930,14 @@ void janas_gpu_destroy(struct janas_gpu *g)if (g->sm_dm[i])g->vkDestroyShaderModule(g->dev, g->sm_dm[i], NULL);}- for (int i = 0; i < 4; i++) {- VkPipeline pp = i == 3 ? g->pipe_idmx+ for (int i = 0; i < 5; i++) {+ VkPipeline pp = i == 4 ? g->pipe_id3+ : i == 3 ? g->pipe_idmx: i == 2 ? g->pipe_id6s: i ? g->pipe_id6: g->pipe_id4;- VkShaderModule ss = i == 3 ? g->sm_idmx+ VkShaderModule ss = i == 4 ? g->sm_id3+ : i == 3 ? g->sm_idmx: i == 2 ? g->sm_id6s: i ? g->sm_id6: g->sm_id4;@@ -1013,6 +1022,11 @@ size_t janas_gpu_min_n(const struct janas_gpu *g)return g->min_n;}+void janas_gpu_set_min_n(struct janas_gpu *g, size_t n)+{+ g->min_n = n ? n : 1;+}+void janas_gpu_keep_awake(struct janas_gpu *g, int on){if (g)@@ -1136,11 +1150,25 @@ fail:return -1;}+/* an import refused, and where, with JANAS_GPU_VERBOSE */+static int import_refused(const struct janas_gpu *g, const void *p,+ size_t bytes, const char *why, int r)+{+ if (g->verbose)+ fprintf(stderr,+ "gpu: %.2f GB at %p not imported: %s (%d), %d regions\n",+ bytes / 1e9, p, why, r, g->n_reg);+ return -1;+}+int janas_gpu_import(struct janas_gpu *g, const void *p, size_t bytes){+ /* below 4 GiB: Mesa's Intel driver passes an imported allocation's size+ on in 32 bits, and asked the kernel for 0 bytes of a region of 4 GiB+ (unsloth's 3-bit Qwen3-30B-A3B's experts, 21 Oct 2026) */if (g->n_reg == MAX_REGIONS || ((uintptr_t)p | bytes) % 4096 != 0 ||- bytes == 0 || bytes > ((size_t)4 << 30))- return -1;+ bytes == 0 || bytes >= ((size_t)4 << 30))+ return import_refused(g, p, bytes, "regions, alignment or size", 0);/* a discrete GPU (or JANAS_GPU_COPY=1, to test that path) reads a copyin its own memory */if (g->discrete || !g->host_import || getenv("JANAS_GPU_COPY"))@@ -1148,10 +1176,10 @@ int janas_gpu_import(struct janas_gpu *g, const void *p, size_t bytes)struct region *rg = &g->reg[g->n_reg];VkMemoryHostPointerPropertiesEXT hp = {.sType = VK_STRUCTURE_TYPE_MEMORY_HOST_POINTER_PROPERTIES_EXT};- if (g->vkGetMemoryHostPointerPropertiesEXT(- g->dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, p,- &hp) != VK_SUCCESS)- return -1;+ VkResult r = g->vkGetMemoryHostPointerPropertiesEXT(+ g->dev, VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT, p, &hp);+ if (r != VK_SUCCESS)+ return import_refused(g, p, bytes, "host pointer properties", r);VkExternalMemoryBufferCreateInfo eb = {.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT};@@ -1161,8 +1189,8 @@ int janas_gpu_import(struct janas_gpu *g, const void *p, size_t bytes).usage =VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT};- if (g->vkCreateBuffer(g->dev, &bi, NULL, &rg->buf) != VK_SUCCESS)- return -1;+ if ((r = g->vkCreateBuffer(g->dev, &bi, NULL, &rg->buf)) != VK_SUCCESS)+ return import_refused(g, p, bytes, "buffer", r);VkMemoryRequirements req;g->vkGetBufferMemoryRequirements(g->dev, rg->buf, &req);int t = janas_g_mem_type(g, hp.memoryTypeBits & req.memoryTypeBits, 0);@@ -1179,14 +1207,16 @@ int janas_gpu_import(struct janas_gpu *g, const void *p, size_t bytes).allocationSize = bytes,.memoryTypeIndex = (uint32_t)t};if (t < 0 ||- g->vkAllocateMemory(g->dev, &ai, NULL, &rg->mem) != VK_SUCCESS) {+ (r = g->vkAllocateMemory(g->dev, &ai, NULL, &rg->mem)) != VK_SUCCESS) {g->vkDestroyBuffer(g->dev, rg->buf, NULL);- return -1;+ return import_refused(g, p, bytes, t < 0 ? "memory type" : "memory",+ t < 0 ? 0 : r);}- if (g->vkBindBufferMemory(g->dev, rg->buf, rg->mem, 0) != VK_SUCCESS) {+ if ((r = g->vkBindBufferMemory(g->dev, rg->buf, rg->mem, 0)) !=+ VK_SUCCESS) {g->vkDestroyBuffer(g->dev, rg->buf, NULL);g->vkFreeMemory(g->dev, rg->mem, NULL);- return -1;+ return import_refused(g, p, bytes, "binding", r);}rg->host = p;rg->bytes = bytes;@@ -2055,19 +2085,30 @@ static int experts_id(struct janas_gpu *g, struct janas_pool *pool,{if (!mm_on() || g->busy || g->broken || n < 2 || !g->pipe_id4)return -1;- int type = t[0].type;+ /* a group may open with the layer's shared expert (model_ffn.c: its gate+ and up, or its down) in a type of its own - Q8_0 beside the routed+ experts' Q4_K or MXFP4 on Qwen3.6-35B-A3B, a plain Q6_K down beside+ their Q6_K_P ones on Qwen3-Next - which left the whole group to the+ CPU: those first s0 products the CPU computes now, as it does the+ experts the GPU is not given, and the routed experts go to the GPU */+ size_t s0 = 0;+ while (s0 < 2 && s0 + 2 <= n && t[s0].type != t[n - 1].type)+ s0++;+ int type = t[s0].type;if (n * 48 > g->ts.bytes || n > 2 * 128 + 8)return experts_off(g, n, type, "more products than its table");if (!(type == JANAS_Q4_K || type == JANAS_Q6_K ||(type == JANAS_MXFP4 && g->pipe_idmx) ||- (type == JANAS_Q6_K_P && plane_level(&t[0]) == 3)))+ (type == JANAS_Q3_K && g->pipe_id3) ||+ (type == JANAS_Q6_K_P && plane_level(&t[s0]) == 3)))return experts_off(g, n, type, "a type without its shader");- size_t nb = t[0].cols / JANAS_QK, xs = t[0].x_stride ? t[0].x_stride : nb;- const struct janas_block_q8k *x0 = t[0].x, *x1 = t[0].x;- for (size_t i = 0; i < n; i++) {+ const struct janas_matvec_task *t0 = &t[s0];+ size_t nb = t0->cols / JANAS_QK, xs = t0->x_stride ? t0->x_stride : nb;+ const struct janas_block_q8k *x0 = t0->x, *x1 = t0->x;+ for (size_t i = s0; i < n; i++) {size_t nv = t[i].n_vec ? t[i].n_vec : 1;- if (t[i].type != type || t[i].rows != t[0].rows ||- t[i].cols != t[0].cols ||+ if (t[i].type != type || t[i].rows != t0->rows ||+ t[i].cols != t0->cols ||(t[i].x_stride ? t[i].x_stride : nb) != xs ||!janas_gpu_can(g, &t[i])) {if (g->verbose > 1)@@ -2087,26 +2128,26 @@ static int experts_id(struct janas_gpu *g, struct janas_pool *pool,go whole to the GPU as before - shared, the CPU got half of them andthe 4B read a prompt at 111 tokens/s instead of 127 (9 Oct 2026) */int own = 0;- for (size_t i = 1; i < n && !own; i++)- own = t[i].x != t[0].x;+ for (size_t i = s0 + 1; i < n && !own; i++)+ own = t[i].x != t0->x;if (!own)return experts_off(g, n, type, "no expert with tokens of its own");/* a prompt's block only: generating, each expert has a token or afew, and the GPU's share cost the 30B three quarters of its speed */size_t tokens = 0;- for (size_t i = 0; i < n; i++)+ for (size_t i = s0; i < n; i++)tokens += t[i].n_vec ? t[i].n_vec : 1;if (tokens < JANAS_GPU_FAST_N * 2)return -1;- unsigned char on[2 * 128 + 8];- size_t maxnv = experts_pick(t, n, on);+ unsigned char on[2 * 128 + 8] = {0};+ size_t maxnv = experts_pick(t0, n - s0, on + s0);if (maxnv == 0) /* no expert worth the GPU: the CPU's as before */return experts_off(g, n, type, "no expert worth the GPU");/* the activations: one array of vectors xs blocks apart */size_t span = (size_t)(x1 - x0);if (span % xs != 0 || span / xs * nb * GPU_BLOCK > X_STAGE_BYTES)return experts_off(g, n, type, "activations beyond the stage");- for (size_t i = 0; i < n; i++)+ for (size_t i = s0; i < n; i++)if ((size_t)(t[i].x - x0) % xs != 0)return experts_off(g, n, type, "activations off the stride");/* the table: weights, activations, outputs (shared with the GPU) */@@ -2191,6 +2232,7 @@ static int experts_id(struct janas_gpu *g, struct janas_pool *pool,type == JANAS_Q4_K ? g->pipe_id4: type == JANAS_Q6_K ? g->pipe_id6s: type == JANAS_MXFP4 ? g->pipe_idmx+ : type == JANAS_Q3_K ? g->pipe_id3: g->pipe_id6);uint32_t pc[5];janas_g_push_addr(pc, g->ts.addr);@@ -2560,6 +2602,12 @@ size_t janas_gpu_min_n(const struct janas_gpu *g)return (size_t)-1;}+void janas_gpu_set_min_n(struct janas_gpu *g, size_t n)+{+ (void)g;+ (void)n;+}+size_t janas_gpu_few_max(const struct janas_gpu *g){(void)g;diff --git a/src/llm/gpu.h b/src/llm/gpu.hindex a840d7f..88f55dc 100644--- a/src/llm/gpu.h+++ b/src/llm/gpu.h@@ -141,6 +141,9 @@ 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);+/* ... set by the engine: 1 where the user asked for replies on the GPU+ (--reply-on gpu). */+void janas_gpu_set_min_n(struct janas_gpu *g, size_t n);/* 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,diff --git a/src/llm/gpu_impl.h b/src/llm/gpu_impl.hindex 5e93c59..131982c 100644--- a/src/llm/gpu_impl.h+++ b/src/llm/gpu_impl.h@@ -179,8 +179,8 @@ struct janas_gpu {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,Q6_K, MXFP4 */- VkShaderModule sm_id4, sm_id6, sm_id6s, sm_idmx;- VkPipeline pipe_id4, pipe_id6, pipe_id6s, pipe_idmx;+ VkShaderModule sm_id4, sm_id6, sm_id6s, sm_idmx, sm_id3;+ VkPipeline pipe_id4, pipe_id6, pipe_id6s, pipe_idmx, pipe_id3;struct stage ts; /* their table, 3 uvec4 an expert *//* the product shaders made for a single vector (prod_index) */VkShaderModule pm1[N_PROD];diff --git a/src/llm/gpu_token.c b/src/llm/gpu_token.cindex 589cd2c..04b30ee 100644--- a/src/llm/gpu_token.c+++ b/src/llm/gpu_token.c@@ -95,10 +95,12 @@ static const char *check_ffn(const struct janas_gpu *g,return NULL;}int gt = ly->gate.type, dt = ly->down.type;- if (!(gt == JANAS_Q4_K || (gt == JANAS_MXFP4 && g->pipe_idmx)) ||+ if (!(gt == JANAS_Q4_K || (gt == JANAS_MXFP4 && g->pipe_idmx) ||+ (gt == JANAS_Q3_K && g->pipe_id3)) ||ly->up.type != gt ||!(dt == JANAS_Q4_K || dt == JANAS_Q6_K || dt == JANAS_Q6_K_P ||- (dt == JANAS_MXFP4 && g->pipe_idmx)) ||+ (dt == JANAS_MXFP4 && g->pipe_idmx) ||+ (dt == JANAS_Q3_K && g->pipe_id3)) ||ly->gate.rows != md->eff || ly->up.rows != md->eff ||ly->gate.cols != md->dm || ly->up.cols != md->dm ||ly->down.rows != md->dm || ly->down.cols != md->eff)diff --git a/src/llm/gpu_token_moe.c b/src/llm/gpu_token_moe.cindex 4d6707c..16a4640 100644--- a/src/llm/gpu_token_moe.c+++ b/src/llm/gpu_token_moe.c@@ -93,7 +93,9 @@ void janas_gt_rec_experts(struct janas_gpu *g, struct janas_gpu_tok *t,struct push_id pi = {.rows = md->eff, .nb = nbd, .tiles = t->tiles1};janas_g_push_addr(pi.t, B + t->o_tab1);janas_gt_bind(g, bound,- ly->gate.type == JANAS_MXFP4 ? g->pipe_idmx : g->pipe_id4);+ ly->gate.type == JANAS_MXFP4 ? g->pipe_idmx+ : ly->gate.type == JANAS_Q3_K ? g->pipe_id3+ : g->pipe_id4);janas_gt_push(g, &pi, sizeof(pi));g->vkCmdDispatchIndirect(g->cb, t->buf.buf, t->o_ind);janas_g_compute_barrier(g);@@ -111,6 +113,7 @@ void janas_gt_rec_experts(struct janas_gpu *g, struct janas_gpu_tok *t,dt == JANAS_Q4_K ? g->pipe_id4: dt == JANAS_Q6_K ? g->pipe_id6s: dt == JANAS_MXFP4 ? g->pipe_idmx+ : dt == JANAS_Q3_K ? g->pipe_id3: g->pipe_id6);janas_gt_push(g, &pi, sizeof(pi));g->vkCmdDispatchIndirect(g->cb, t->buf.buf, t->o_ind + 16);diff --git a/src/llm/jns.c b/src/llm/jns.cindex 99d8779..860641d 100644--- a/src/llm/jns.c+++ b/src/llm/jns.c@@ -80,6 +80,7 @@ static int type_geometry(uint32_t type, uint64_t *blck, uint64_t *size){13, 256, 176}, /* Q5_K */{14, 256, 210}, /* Q6_K */{214, 256, 82}, /* Q6_K_P, the base plane and the scales */+ {215, 256, 82}, /* Q6_K_PN, the same by neuron */{15, 256, 292}, /* Q8_K */{20, 32, 18}, /* IQ4_NL */{21, 256, 110}, /* IQ3_S */@@ -517,6 +518,10 @@ int janas_jns_parse(const uint8_t *image, size_t bytes, uint64_t file_bytes,mx->cols == 0 || mx->cols % blck ||__builtin_mul_overflow(mx->cols / blck, size, &row_bytes) ||__builtin_mul_overflow(row_bytes, mx->rows, &total) ||+ /* by neuron: a float per output channel first */+ __builtin_add_overflow(+ total, mx->type == 215 ? (uint64_t)mx->cols * 4 : 0,+ &total) ||total != mx->bytes || mx->offset % 256 ||!inside(mx->offset, mx->bytes, 0, ly->slot_bytes)) {janas_jns_close(out);@@ -551,7 +556,8 @@ int janas_jns_parse(const uint8_t *image, size_t bytes, uint64_t file_bytes,}uint64_t total;/* a bare plane: 64 bytes per 256 weights, no scales */- if (ly->m[JANAS_JNS_DOWN].type != 214 ||+ if ((ly->m[JANAS_JNS_DOWN].type != 214 &&+ ly->m[JANAS_JNS_DOWN].type != 215) ||px->type != ly->m[JANAS_JNS_DOWN].type ||px->rows != ly->m[JANAS_JNS_DOWN].rows ||px->cols != ly->m[JANAS_JNS_DOWN].cols || px->cols % 256 ||diff --git a/src/llm/jns.h b/src/llm/jns.hindex d39ba38..21d488c 100644--- a/src/llm/jns.h+++ b/src/llm/jns.h@@ -30,8 +30,11 @@* JANAS_JNS_ALIGN: reading only the first level_bytes[0] of the slot gives* two bits per weight of the down matrix, level_bytes[1] four, the whole slot* the six of Q6_K, bit for bit. A machine short of memory reads the prefix it- * can afford, out of the same file. Version 2 files are read as if their- * three levels were all the whole slot.+ * can afford, out of the same file. The down matrix by neuron+ * (JANAS_Q6_K_PN, tools/jns_neurons.c), its rows the neurons, keeps the same+ * three planes and levels, a float per output channel before its base+ * plane (counted in its bytes). Version 2 files are read as if their three+ * levels were all the whole slot.** Sizes are stored, never derived from products of fields read from the* file; the reader checks every offset and length against the file size withdiff --git a/src/llm/model.c b/src/llm/model.cindex a0b566f..c87e400 100644--- a/src/llm/model.c+++ b/src/llm/model.c@@ -394,11 +394,14 @@ int janas_llm_model_forward(struct janas_llm_model *m, const int32_t *tokens,it depends on the cache, not on the configuration */struct janas_expert_cache_stats c0, c1;janas_expert_cache_stats(m->cache, &c0);- double t0 = now();+ double k0 = janas_llm_model_npu_compile_seconds(m), t0 = now();int r = forward(m, tokens, n, pos0, logits, all_logits);double dt = now() - t0;+ janas_m_npu_pass_end(m);janas_expert_cache_stats(m->cache, &c1);dt -= c1.wait_seconds - c0.wait_seconds;+ /* nor the NPU's first compilation of a matrix: once a session */+ dt -= janas_llm_model_npu_compile_seconds(m) - k0;/* while the cache is still filling in the background, passes are notrepresentative: neither the tuner nor the draft planner may learnfrom them, or a slow start decides the whole session */@@ -459,7 +462,11 @@ 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) */- int gpu = logits ? janas_m_gpu_token(m, pos0, n, all_logits, logits) : -1;+ /* not where the NPU takes this pass's products: then the block goes+ product by product, the NPU's to it, the others as before */+ int gpu = logits && !janas_m_npu_takes(m, n)+ ? 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) */@@ -477,9 +484,18 @@ static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,}return 0;}- for (uint32_t l = 0; l < m->n_layer; l++) {+ /* a dense block's first layers on the NPU, graph by graph, as many as+ it holds (model_npu.c); the others here */+ int npu_layers = janas_m_npu_layers(m, n, pos0);+ if (npu_layers == -2)+ return -1; /* the NPU failed halfway: no state to go on from */+ for (uint32_t l = npu_layers > 0 ? (uint32_t)npu_layers : 0; l < m->n_layer;+ l++) {+ m->ana_layer = l; /* the Ana-Net probe's row */const struct layer *ly = &m->layers[l];janas_m_norm_quant(m, f32(m, ly->attn_norm), 0, n);+ if (m->npu) /* the NPU's calibration (JANAS_NPU_A8=1) */+ janas_m_npu_calib(m, 3, l, m->xn, n, dm, dm);trace_row(m, "attn_norm", m->xn + (size_t)(n - 1) * dm, dm);if (ly->rec)janas_m_rec_layer(m, ly, n);@@ -496,6 +512,8 @@ static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,else if (m->pfb_on && n >= PFB_MIN_N && l + 1 < m->n_layer)janas_m_prefetch_block(m, l, n);janas_m_norm_quant(m, f32(m, ly->ffn_norm), 0, n);+ if (m->npu)+ janas_m_npu_calib(m, 1, l, m->xn, n, dm, dm);trace_row(m, "post_norm", m->xn + (size_t)(n - 1) * dm, dm);if (ly->post_ffn) {/* the FFN's output normalized before the residual: summed@@ -503,7 +521,10 @@ static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,memcpy(m->xres, m->x, (size_t)n * dm * sizeof(float));memset(m->x, 0, (size_t)n * dm * sizeof(float));}- if (ly->pre_norm2) {+ janas_m_janet_rec(m, l, n, 0); /* the Janet probe (model_janet.c) */+ if (janas_m_janet_ffn(m, l, n)) {+ /* Janet's detectors in place of the layer's feed-forward */+ } else if (ly->pre_norm2) {/* Gemma 4's mixture: the dense branch on xn / xq as normedabove, then the experts' branch */size_t bytes = (size_t)n * dm * sizeof(float);@@ -523,6 +544,7 @@ static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,MOE_ALL) != 0) {return -1;}+ janas_m_janet_rec(m, l, n, 1);if (ly->post_ffn) {struct tok_job st = {.m = m, .ly = ly, .w = f32(m, ly->post_ffn), .n = n};@@ -547,7 +569,8 @@ static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,l, sqrt(nn), v[0], v[1], v[2], v[3]);}}- m->ring_hi = pos0 + n; /* the rings hold up to here */+ janas_m_ana_frame(m, n); /* the Ana-Net probe's picture */+ m->ring_hi = pos0 + n; /* the rings hold up to here */double td = now();uint32_t first = all_logits ? 0 : n - 1;/* with an MTP block, every token's final hidden state is kept for it */@@ -563,7 +586,7 @@ static int forward(struct janas_llm_model *m, const int32_t *tokens, uint32_t n,.cols = dm,.n_vec = n - first};if (logits) /* without: the hidden states alone, an embedding */- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, &to, 1);+ janas_m_products(m, janas_m_gpu(m, 0), &to, 1);if (logits && m->softcap > 0.0f) {struct tok_job sc = {.m = m, .n = n - first, .out = logits};janas_pool_run(m->compute, softcap_worker, &sc);@@ -687,7 +710,7 @@ int janas_llm_mtp_draft(struct janas_llm_model *m, const int32_t *tokens,.y = m->dh_logits,.rows = m->dh_n,.cols = m->d_model};- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, &t, 1);+ janas_m_products(m, janas_m_gpu(m, 0), &t, 1);/* the best row and its softmax probability within the head */float *l = m->dh_logits, mx = l[0];uint32_t best = 0;@@ -748,7 +771,7 @@ int janas_llm_mtp_forward(struct janas_llm_model *m, const int32_t *tokens,.rows = dm,.cols = 2 * dm,.n_vec = n};- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, &tp, 1);+ janas_m_products(m, janas_m_gpu(m, 0), &tp, 1);m->phase[JANAS_PH_QKV] += now() - ta;set_rope(m, n, pos0);for (uint32_t j = 0; j < n; j++) {@@ -784,7 +807,7 @@ int janas_llm_mtp_forward(struct janas_llm_model *m, const int32_t *tokens,.rows = m->n_vocab,.cols = dm,.n_vec = n - first};- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, &to, 1);+ janas_m_products(m, janas_m_gpu(m, 0), &to, 1);m->phase[JANAS_PH_OUTPUT] += now() - td;return 0;}diff --git a/src/llm/model.h b/src/llm/model.hindex c4f75f3..7463af8 100644--- a/src/llm/model.h+++ b/src/llm/model.h@@ -53,6 +53,8 @@ struct janas_llm_options {(Q6_K), requantized to four (Q4_K) at load - faster, alittle less accurate; 0 or 6: as in the file(environment JANAS_HEAD_BITS overrides) */+ int no_npu; /* 1: the NPU left off, its copies' memory being the+ expert cache's (janas_llm_open) */};struct janas_llm_model;@@ -69,6 +71,12 @@ uint32_t janas_llm_model_n_ctx(const struct janas_llm_model *m);context never goes past it: without a rope scaling the file carries, textbeyond that length falls apart. */uint32_t janas_llm_model_n_ctx_train(const struct janas_llm_model *m);+/* The memory the model holds: its resident weights as read (a table read+ from the file a row at a time, Gemma 4's per-layer embeddings, is not+ held), its expert cache's arena, and its keys and values with their+ scales. */+void janas_llm_model_memory(const struct janas_llm_model *m, uint64_t *resident,+ uint64_t *cache, uint64_t *kv);/** A place in ~/.cache/janas for something the engine learns about this@@ -287,15 +295,45 @@ int janas_llm_model_gpu_used(const struct janas_llm_model *m);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). */+ (the fast prompt, outside eco mode, unless the user keeps prompts off+ the GPU). */int janas_llm_model_gpu_prompts(const struct janas_llm_model *m);+/* Whether the engine gives the NPU a prompt's blocks by itself, where it+ measures faster: on the models whose answers on the NPU measured at par+ with the CPU's against llama.cpp; on the others only when asked+ (--prompt-on npu). */+int janas_llm_model_npu_auto(const struct janas_llm_model *m);+/* The combinations of devices the user allowed a kind of pass+ (common/devices.h, janas_tune_class), as this machine has them: 0 any+ (the engine's own limits, as janas_llm_model_npu_auto, apart). */+int janas_llm_model_devices(const struct janas_llm_model *m, int cls);/* The compute threads of the configuration the tuner holds best for akind of pass (janas_tune_class: 0 one token, 1 a few, 2 a block, 3 ashort one); 0 unknown. */int janas_llm_model_threads(const struct janas_llm_model *m, int cls);+/* The tuner's candidates: threads, GPU and NPU (npu may be NULL). */int janas_llm_model_candidates(const struct janas_llm_model *m, int *threads,- int *gpu, int max);+ int *gpu, int *npu, int max);+/* As janas_llm_model_gpu_used, for the NPU (looked for at load unless+ JANAS_NPU=0). */+int janas_llm_model_npu_used(const struct janas_llm_model *m);+/* The NPU's name, or NULL when none is used. */+const char *janas_llm_model_npu_name(const struct janas_llm_model *m);+/* Seconds spent making the NPU's graphs so far (a matrix's or a layer's+ first block: its weights prepared, the graph compiled and run once):+ kept out of the tuner's costs, as the waits for the disk are, and out of+ janas-bench's rates. */+double janas_llm_model_npu_compile_seconds(const struct janas_llm_model *m);+/* The NPU's preparation, safe from another thread while the engine works+ (janas_llm_npu_preparing): 1 while it goes on, *done of *total graphs+ made (*total 0: not known ahead), *seconds since it began; 0 after,+ *seconds the session's preparations; 0 and zeros without an NPU. */+int janas_llm_model_npu_preparing(const struct janas_llm_model *m,+ int32_t *done, int32_t *total,+ double *seconds);+/* Without an NPU: why ("" with one). */+const char *janas_llm_model_npu_why(const struct janas_llm_model *m);void janas_llm_model_force(struct janas_llm_model *m, int cand);/*diff --git a/src/llm/model_ana.c b/src/llm/model_ana.cnew file mode 100644index 0000000..15838a3--- /dev/null+++ b/src/llm/model_ana.c@@ -0,0 +1,755 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * model_ana.c - the Ana-Net probe (job/docs/progetto_ana.md; the name is+ * provisional). A fraction of the feed-forward neurons is switched off+ * before the down product, chosen by a score, to measure what each choice+ * costs the answers against a reference. A probe: nothing is saved (the+ * down product still reads every column), and only the CPU's path has it+ * (JANAS_GPU=0).+ *+ * JANAS_ANA_MODE, a pair's neurons (a token through one expert, or through+ * the dense feed-forward) ranked by themselves:+ * mag |h|, the known way;+ * agree how much the neuron's inputs agree: for gate and for up,+ * |sum w x| / sum |w x| (1 when every contribution pulls the same+ * way, near 0 when they cancel), the two multiplied;+ * both |h| times the agreement;+ * magw |h| times the norm of the neuron's column of down: what switching+ * it off takes from the output;+ * bothw magw times the square root of the agreement;+ * random.+ * Or a token's neurons, all its experts' together, ranked by what each+ * gives the output, its expert's weight w (the router's, or the shared+ * expert's gate) in it, so that a light expert loses more neurons than a+ * heavy one:+ * tokmag w |h|; tokw w |h| times the column's norm;+ * tokboth tokw times the square root of the agreement.+ * JANAS_ANA_FRAC: the fraction off (0.4).+ * JANAS_ANA_COARSE=1 (the per-token modes): the choice made on h from gate+ * and up read at two bits a weight (Q4_K's nibbles, Q8_0's bytes, cut to+ * their two high bits), the neurons chosen then computed whole - a+ * predictor that reads a third of gate and up; at the end, how many of the+ * neurons the true choice keeps the two-bit one kept too.+ * JANAS_ANA_GULOW=n (the per-token modes): the n routed experts of least+ * weight in each token have their gate and up read at two bits a weight,+ * as JANAS_ANA_COARSE reads them; the shared expert whole.+ * JANAS_ANA_GRADE=f6,f4,f2 (the per-token modes): of a token's neurons+ * ranked, the first f6 keep all of down, the next f4 down at four bits, the+ * next f2 at two (its bit planes, or Q8_0's bytes cut), the rest off.+ * JANAS_ANA_STATS=file (the per-token modes): for every pair of every token+ * a record - its token, layer, expert (n_expert: the shared one), neurons+ * ff and weight w as five 32-bit words (w a float), then ff floats of h+ * before anything is off, then ff bytes, 1 for a neuron kept - for+ * job/tests/py/ana_stats.py.+ * JANAS_ANA_XSTATS=file (the per-token modes): each token's input to the+ * feed-forward of each layer - its token, layer and width as three 32-bit+ * words, then that many floats - once for every pass that ranks it (a+ * layer's experts in two passes write it twice).+ * JANAS_ANA_FRAMES=dir: for each token computed alone, a picture of the+ * network (dir/frame_NNNNN.ppm, a row a layer, a column a neuron of a pair+ * of the token: red its agreement against the pair's highest, green its+ * magnitude against the pair's largest, blue where it was switched off),+ * the first JANAS_ANA_FRAMES_MAX (32) of them.+ */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "model_impl.h"+#include "quant.h"++enum {+ ANA_MAG = 1,+ ANA_AGREE,+ ANA_BOTH,+ ANA_MAGW,+ ANA_BOTHW,+ ANA_RANDOM,+ ANA_TOKMAG,+ ANA_TOKW,+ ANA_TOKBOTH+};++static const char *const NAMES[] = {"", "mag", "agree", "both",+ "magw", "bothw", "random", "tokmag",+ "tokw", "tokboth"};++static int needs_agree(int mode)+{+ return mode == ANA_AGREE || mode == ANA_BOTH || mode == ANA_BOTHW ||+ mode == ANA_TOKBOTH;+}++static int needs_coln(int mode)+{+ return mode == ANA_MAGW || mode == ANA_BOTHW || mode == ANA_TOKW ||+ mode == ANA_TOKBOTH;+}++int janas_m_ana_init(struct janas_llm_model *m, size_t pairs)+{+ const char *e = getenv("JANAS_ANA_MODE");+ m->ana_mode = 0;+ for (int i = 1; e && i < (int)(sizeof(NAMES) / sizeof(NAMES[0])); i++)+ if (!strcmp(e, NAMES[i]))+ m->ana_mode = i;+ m->ana_tok = m->ana_mode >= ANA_TOKMAG;+ e = getenv("JANAS_ANA_FRAC");+ m->ana_frac = e ? (float)atof(e) : 0.4f;+ if (m->ana_frac < 0.0f)+ m->ana_frac = 0.0f;+ if (m->ana_frac > 0.95f)+ m->ana_frac = 0.95f;+ e = getenv("JANAS_ANA_FRAMES");+ if (e && *e)+ snprintf(m->ana_dir, sizeof(m->ana_dir), "%s", e);+ e = getenv("JANAS_ANA_FRAMES_MAX");+ m->ana_frames_max = e ? atoi(e) : 32;+ e = getenv("JANAS_ANA_GRADE");+ if (m->ana_tok && e &&+ sscanf(e, "%f,%f,%f", &m->ana_grade[0], &m->ana_grade[1],+ &m->ana_grade[2]) == 3) {+ m->ana_frac =+ 1.0f - (m->ana_grade[0] + m->ana_grade[1] + m->ana_grade[2]);+ if (m->ana_frac < 0.0f)+ m->ana_frac = 0.0f;+ if (!(m->ana_level = calloc(pairs * m->ff_buf, 1)))+ return -1;+ }+ e = getenv("JANAS_ANA_GULOW");+ m->ana_gulow = m->ana_tok && e ? atoi(e) : 0;+ if (m->ana_gulow > 0 && !(m->ana_low = calloc(pairs, 1)))+ return -1;+ if (m->ana_gulow > 0)+ fprintf(stderr,+ "ana: gate and up at two bits for the %d experts of "+ "least weight in a token\n",+ m->ana_gulow);+ e = getenv("JANAS_ANA_COARSE");+ if (m->ana_tok && e && atoi(e) &&+ !(m->ana_coarse = calloc(pairs * m->ff_buf, sizeof(float))))+ return -1;+ e = getenv("JANAS_ANA_STATS");+ if (e && *e && m->ana_tok && !(m->ana_stats = fopen(e, "wb")))+ return -1;+ e = getenv("JANAS_ANA_XSTATS");+ if (e && *e && m->ana_tok && !(m->ana_xstats = fopen(e, "wb")))+ return -1;+ if (!m->ana_mode && !m->ana_dir[0])+ return 0;+ m->ana_exp = calloc(pairs, sizeof(uint32_t));+ if (!m->ana_exp)+ return -1;+ if (needs_agree(m->ana_mode) || m->ana_dir[0]) {+ m->ana_agree = calloc(pairs * m->ff_buf, sizeof(float));+ if (!m->ana_agree)+ return -1;+ }+ if (needs_coln(m->ana_mode)) {+ size_t slots = (size_t)m->n_layer * (m->n_expert + 1);+ m->ana_coln = calloc(slots * m->ff_buf, sizeof(float));+ m->ana_coln_ok = calloc(slots, 1);+ if (!m->ana_coln || !m->ana_coln_ok)+ return -1;+ }+ if (m->ana_dir[0]) {+ /* the routed experts of a token and a shared one, or a dense+ feed-forward */+ m->ana_width = m->ff_buf * (m->n_expert > 1 ? m->k + 1 : 1);+ m->ana_frame = calloc((size_t)m->n_layer * m->ana_width, 3);+ if (!m->ana_frame)+ return -1;+ }+ if (m->ana_level)+ fprintf(stderr,+ "ana: down at 6, 4, 2 bits for %.0f%%, %.0f%%, %.0f%% "+ "of a token's neurons\n",+ 100.0 * m->ana_grade[0], 100.0 * m->ana_grade[1],+ 100.0 * m->ana_grade[2]);+ if (m->ana_coarse)+ fprintf(stderr, "ana: the choice made on gate and up at two bits\n");+ fprintf(stderr,+ "ana: %s, %.0f%% of each %s's neurons off%s%s (a probe: the CPU's "+ "path only)\n",+ m->ana_mode ? NAMES[m->ana_mode] : "nothing switched off",+ m->ana_mode ? 100.0 * m->ana_frac : 0.0,+ m->ana_tok ? "token" : "pair",+ m->ana_dir[0] ? ", pictures in " : "", m->ana_dir);+ return 0;+}++void janas_m_ana_free(struct janas_llm_model *m)+{+ if (m->ana_true_kept)+ fprintf(stderr,+ "ana: the two-bit choice kept %.1f%% of the neurons the true "+ "one kept\n",+ 100.0 * (double)m->ana_both_kept / (double)m->ana_true_kept);+ free(m->ana_coarse);+ free(m->ana_level);+ free(m->ana_low);+ m->ana_coarse = NULL;+ m->ana_level = NULL;+ m->ana_low = NULL;+ free(m->ana_agree);+ free(m->ana_frame);+ free(m->ana_exp);+ free(m->ana_coln);+ free(m->ana_coln_ok);+ if (m->ana_stats)+ fclose(m->ana_stats);+ if (m->ana_xstats)+ fclose(m->ana_xstats);+ m->ana_stats = m->ana_xstats = NULL;+ m->ana_agree = m->ana_coln = NULL;+ m->ana_frame = m->ana_coln_ok = NULL;+ m->ana_exp = NULL;+}++/* A run's agreements: for each neuron (a row of gate and of up), for each of+ its pairs, how much the products w x of the token's inputs agree. The+ rows unpacked once for all the run's pairs; neurons split among the+ threads. */+struct agree_job {+ struct janas_llm_model *m;+ const uint8_t *w[2];+ const struct janas_jns_matrix *mx;+ uint32_t a, b;+};++/* A row of gate or up at two bits a weight: Q4_K's nibbles and Q8_0's bytes+ cut to their two high bits, the middle of what those leave; other types+ as they are. tmp: room for the row's blocks. */+static void coarse_row(int type, const uint8_t *w, float *y, uint32_t n,+ uint8_t *tmp)+{+ size_t nb = n / JANAS_QK, bs = janas_qtype_block_size(type);+ memcpy(tmp, w, nb * bs);+ if (type == JANAS_Q4_K) {+ for (size_t b = 0; b < nb; b++) {+ struct janas_block_q4k *k =+ (struct janas_block_q4k *)(tmp + b * bs);+ for (int i = 0; i < JANAS_QK / 2; i++)+ k->qs[i] = (uint8_t)(((k->qs[i] & 0x0C) | 0x01) |+ ((k->qs[i] & 0xC0) | 0x20));+ }+ } else if (type == JANAS_Q8_0) {+ struct janas_block_q8_0 *k = (struct janas_block_q8_0 *)tmp;+ for (size_t b = 0; b < nb * 8; b++)+ for (int i = 0; i < 32; i++)+ k[b].qs[i] = (int8_t)(((uint8_t)k[b].qs[i] & 0xC0) | 0x20);+ }+ janas_dequantize(type, tmp, y, n);+}++static void agree_worker(void *arg, int tid, int n_threads)+{+ struct agree_job *J = arg;+ struct janas_llm_model *m = J->m;+ uint32_t rows = J->mx[0].rows, cols = J->mx[0].cols, dm = m->d_model;+ size_t rb[2];+ for (int p = 0; p < 2; p++)+ rb[p] = (size_t)J->mx[p].cols / JANAS_QK *+ janas_qtype_block_size((int)J->mx[p].type);+ float *row = malloc(4 * (size_t)cols * sizeof(float));+ uint8_t *tmp = malloc(rb[0] > rb[1] ? rb[0] : rb[1]);+ if (!row || !tmp) {+ free(row);+ free(tmp);+ return;+ }+ for (uint32_t j = (uint32_t)tid; j < rows; j += (uint32_t)n_threads) {+ for (int p = 0; p < 2; p++)+ janas_dequantize((int)J->mx[p].type, J->w[p] + j * rb[p],+ row + (size_t)p * cols, cols);+ int two = m->ana_coarse != NULL;+ for (uint32_t g = J->a; m->ana_low && !two && g < J->b; g++)+ two = m->ana_low[g];+ for (int p = 0; two && p < 2; p++)+ coarse_row((int)J->mx[p].type, J->w[p] + j * rb[p],+ row + (size_t)(2 + p) * cols, cols, tmp);+ for (uint32_t g = J->a; two && g < J->b; g++) {+ if (!m->ana_coarse && !m->ana_low[g])+ continue;+ const float *x = m->xn + (size_t)m->pair_tok[m->order[g]] * dm;+ double v[2] = {0, 0};+ for (int p = 0; p < 2; p++)+ for (uint32_t i = 0; i < cols; i++)+ v[p] += (double)row[(size_t)(2 + p) * cols + i] * x[i];+ if (m->ana_coarse) {+ double gs = v[0] / (1.0 + exp(-v[0]));+ m->ana_coarse[(size_t)g * m->ff_buf + j] = (float)(gs * v[1]);+ }+ if (m->ana_low && m->ana_low[g]) {+ /* this pair's gate and up are the two-bit ones */+ m->gate[(size_t)g * m->ff_buf + j] = (float)v[0];+ m->up[(size_t)g * m->ff_buf + j] = (float)v[1];+ }+ }+ if (!m->ana_agree)+ continue;+ for (uint32_t g = J->a; g < J->b; g++) {+ const float *x = m->xn + (size_t)m->pair_tok[m->order[g]] * dm;+ float c[2];+ for (int p = 0; p < 2; p++) {+ const float *w = row + (size_t)p * cols;+ double s = 0, sa = 0;+ for (uint32_t i = 0; i < cols; i++) {+ double v = (double)w[i] * x[i];+ s += v;+ sa += fabs(v);+ }+ c[p] = sa > 0 ? (float)(fabs(s) / sa) : 0.0f;+ }+ m->ana_agree[(size_t)g * m->ff_buf + j] = c[0] * c[1];+ }+ }+ free(row);+ free(tmp);+}++void janas_m_ana_agree(struct janas_llm_model *m, const uint8_t *wg,+ const uint8_t *wu, const struct janas_jns_matrix *mx,+ uint32_t a, uint32_t b)+{+ if ((!m->ana_agree && !m->ana_coarse && !m->ana_low) ||+ mx[0].cols != m->d_model || mx[1].cols != m->d_model ||+ mx[0].rows != mx[1].rows || mx[0].rows > m->ff_buf ||+ !janas_qtype_block_size((int)mx[0].type) ||+ !janas_qtype_block_size((int)mx[1].type))+ return;+ struct agree_job J = {.m = m, .w = {wg, wu}, .mx = mx, .a = a, .b = b};+ janas_pool_run(m->compute, agree_worker, &J);+}++/* The norms of the columns of expert e's down matrix in the current layer+ (rows the model's width, a column a neuron), once: what switching a+ neuron off takes from the output, per unit of |h|. Bit planes unpacked+ with those the cache holds; a type that cannot be unpacked, norms of 1. */+void janas_m_ana_coln(struct janas_llm_model *m, uint32_t e,+ const uint8_t *down, const uint8_t *p1, const uint8_t *p0,+ const struct janas_jns_matrix *mx)+{+ size_t slot = (size_t)m->ana_layer * (m->n_expert + 1) + e;+ if (!m->ana_coln || m->ana_coln_ok[slot] || mx->cols > m->ff_buf)+ return;+ float *out = m->ana_coln + slot * m->ff_buf;+ uint32_t rows = mx->rows, cols = mx->cols, nb = cols / JANAS_QK;+ int planes = mx->type == JANAS_Q6_K_P;+ size_t bs = planes ? sizeof(struct janas_block_q6kp)+ : janas_qtype_block_size((int)mx->type);+ float *y = malloc(cols * sizeof(float));+ double *acc = calloc(cols, sizeof(double));+ if (!y || !acc || !bs) {+ for (uint32_t j = 0; j < cols; j++)+ out[j] = 1.0f;+ } else {+ for (uint32_t r = 0; r < rows; r++) {+ if (planes)+ janas_q6kp_dequantize(+ (const struct janas_block_q6kp *)(down ++ (size_t)r * nb * bs),+ p1 ? p1 + (size_t)r * nb * JANAS_Q6KP_PLANE : NULL,+ p1 && p0 ? p0 + (size_t)r * nb * JANAS_Q6KP_PLANE : NULL, y,+ cols);+ else+ janas_dequantize((int)mx->type, down + (size_t)r * nb * bs, y,+ cols);+ for (uint32_t j = 0; j < cols; j++)+ acc[j] += (double)y[j] * y[j];+ }+ for (uint32_t j = 0; j < cols; j++)+ out[j] = (float)sqrt(acc[j]);+ }+ free(y);+ free(acc);+ m->ana_coln_ok[slot] = 1;+}++/* A fixed pseudo-random number of a neuron of a pair in a layer. */+static float noise(uint32_t layer, size_t g, uint32_t j)+{+ uint64_t z = ((uint64_t)layer << 40) ^ ((uint64_t)g << 20) ^ j;+ z += 0x9E3779B97F4A7C15ull;+ z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;+ z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;+ z ^= z >> 31;+ return (float)(z >> 40) / (float)(1u << 24);+}++/* Neuron j of pair row g by the mode's score (higher: kept). */+static float score(const struct janas_llm_model *m, size_t g, uint32_t j,+ float h)+{+ const float *agree = m->ana_agree ? m->ana_agree + g * m->ff_buf : NULL;+ float a = agree ? agree[j] : 1.0f, mag = fabsf(h);+ float col = 1.0f;+ if (m->ana_coln && m->ana_exp) {+ size_t slot = (size_t)m->ana_layer * (m->n_expert + 1) + m->ana_exp[g];+ col = m->ana_coln[slot * m->ff_buf + j];+ }+ float w = m->ana_tok ? m->pair_w[m->order[g]] : 1.0f;+ switch (m->ana_mode) {+ case ANA_MAG:+ return mag;+ case ANA_AGREE:+ return a;+ case ANA_BOTH:+ return mag * a;+ case ANA_MAGW:+ return mag * col;+ case ANA_BOTHW:+ return mag * col * sqrtf(a);+ case ANA_TOKMAG:+ return w * mag;+ case ANA_TOKW:+ return w * mag * col;+ case ANA_TOKBOTH:+ return w * mag * col * sqrtf(a);+ default:+ return noise(m->ana_layer, g, j);+ }+}++struct ranked {+ float score;+ uint32_t g, j;+};++static int by_score(const void *a, const void *b)+{+ const struct ranked *x = a, *y = b;+ if (x->score != y->score)+ return x->score < y->score ? -1 : 1;+ if (x->g != y->g)+ return x->g < y->g ? -1 : 1;+ return x->j < y->j ? -1 : x->j > y->j ? 1 : 0;+}++/* Pair row g in the picture: red its agreements against the pair's highest,+ green its magnitudes (before any is off) against the largest; blue, its+ neurons switched off, set after. */+static void frame_pair(struct janas_llm_model *m, size_t g, const float *h,+ uint32_t ff)+{+ if (!m->ana_frame || (g + 1) * m->ff_buf > m->ana_width)+ return;+ const float *agree = m->ana_agree ? m->ana_agree + g * m->ff_buf : NULL;+ float big = 0.0f, top = 0.0f;+ for (uint32_t j = 0; j < ff; j++) {+ if (fabsf(h[j]) > big)+ big = fabsf(h[j]);+ if (agree && agree[j] > top)+ top = agree[j];+ }+ uint8_t *px = m->ana_frame ++ ((size_t)m->ana_layer * m->ana_width + g * m->ff_buf) * 3;+ for (uint32_t j = 0; j < ff; j++) {+ px[3 * j] = top > 0 ? (uint8_t)(255.0f * agree[j] / top + 0.5f) : 0;+ px[3 * j + 1] =+ big > 0 ? (uint8_t)(255.0f * sqrtf(fabsf(h[j]) / big) + 0.5f) : 0;+ px[3 * j + 2] = 0;+ }+}++static void frame_off(struct janas_llm_model *m, size_t g, uint32_t j)+{+ if (m->ana_frame && (g + 1) * m->ff_buf <= m->ana_width)+ m->ana_frame[((size_t)m->ana_layer * m->ana_width + g * m->ff_buf + j) *+ 3 ++ 2] = 160;+}++void janas_m_ana_mask(struct janas_llm_model *m, size_t g, float *h,+ uint32_t ff)+{+ uint32_t k = (uint32_t)(m->ana_frac * (float)ff + 0.5f);+ struct ranked *r = NULL;+ if (m->ana_mode && k > 0 && (r = malloc(ff * sizeof(*r)))) {+ for (uint32_t j = 0; j < ff; j++)+ r[j] = (struct ranked){score(m, g, j, h[j]), (uint32_t)g, j};+ qsort(r, ff, sizeof(*r), by_score);+ }+ frame_pair(m, g, h, ff);+ for (uint32_t i = 0; r && i < k; i++) {+ frame_off(m, g, r[i].j);+ h[r[i].j] = 0.0f;+ }+ free(r);+}++static int by_token(const void *a, const void *b)+{+ const uint64_t *x = a, *y = b;+ return *x < *y ? -1 : *x > *y ? 1 : 0;+}++/* The ana_tok modes: the pair rows glist[0 .. n) of this pass grouped by+ token, each token's neurons ranked together - on h, or on the two-bit h+ with JANAS_ANA_COARSE - the fraction of them with the least score+ switched off (and, with JANAS_ANA_GRADE, the others given their levels),+ then every pair's h quantized. Pairs of a token computed in another pass+ (an expert read from the disk while the others ran) are ranked apart. */+static size_t rank_token(struct janas_llm_model *m, const uint64_t *key,+ uint32_t i, uint32_t e, size_t total, int coarse,+ struct ranked *r)+{+ uint32_t stride = m->ff_buf;+ size_t at = 0;+ for (uint32_t q = i; q < e; q++) {+ size_t g = (uint32_t)key[q];+ const float *h =+ coarse ? m->ana_coarse + g * stride : m->h + g * stride;+ for (uint32_t j = 0; j < m->hlen[g]; j++)+ r[at++] = (struct ranked){score(m, g, j, h[j]), (uint32_t)g, j};+ }+ qsort(r, total, sizeof(*r), by_score);+ return at;+}++void janas_m_ana_tok(struct janas_llm_model *m, uint32_t n)+{+ uint32_t stride = m->ff_buf;+ uint64_t *key = malloc(n * sizeof(uint64_t));+ if (key) {+ for (uint32_t i = 0; i < n; i++) {+ size_t g = m->glist[i];+ key[i] = ((uint64_t)m->pair_tok[m->order[g]] << 32) | (uint32_t)g;+ }+ qsort(key, n, sizeof(*key), by_token);+ for (uint32_t i = 0; i < n;) {+ uint32_t tok = (uint32_t)(key[i] >> 32), e = i;+ size_t total = 0;+ while (e < n && (uint32_t)(key[e] >> 32) == tok)+ total += m->hlen[(uint32_t)key[e++]];+ if (m->ana_xstats) {+ uint32_t head[3] = {(uint32_t)(m->ana_base + tok), m->ana_layer,+ m->d_model};+ fwrite(head, sizeof(head), 1, m->ana_xstats);+ fwrite(m->xn + (size_t)tok * m->d_model, sizeof(float),+ m->d_model, m->ana_xstats);+ }+ struct ranked *r = malloc(total * sizeof(*r));+ if (!r) {+ i = e;+ continue;+ }+ for (uint32_t q = i; q < e; q++) {+ size_t g = (uint32_t)key[q];+ frame_pair(m, g, m->h + g * stride, m->hlen[g]);+ }+ size_t k = (size_t)(m->ana_frac * (float)total + 0.5f);+ rank_token(m, key, i, e, total, m->ana_coarse != NULL, r);+ /* with the two-bit choice, how much of the true one it keeps:+ levels mark the true choice's kept neurons for a moment */+ if (m->ana_coarse && m->ana_level == NULL) {+ struct ranked *t = malloc(total * sizeof(*t));+ uint8_t *mark = calloc((size_t)(e - i) * stride, 1);+ if (t && mark) {+ rank_token(m, key, i, e, total, 0, t);+ for (size_t q = k; q < total; q++)+ for (uint32_t z = i; z < e; z++)+ if ((uint32_t)key[z] == t[q].g) {+ mark[(size_t)(z - i) * stride + t[q].j] = 1;+ break;+ }+ for (size_t q = k; q < total; q++)+ for (uint32_t z = i; z < e; z++)+ if ((uint32_t)key[z] == r[q].g) {+ m->ana_both_kept +=+ mark[(size_t)(z - i) * stride + r[q].j];+ break;+ }+ m->ana_true_kept += total - k;+ }+ free(t);+ free(mark);+ }+ /* the levels: from the top, f6, f4 and f2 of the token's+ neurons; the rest, level 0, is what goes off below */+ if (m->ana_level) {+ size_t n6 = (size_t)(m->ana_grade[0] * (float)total + 0.5f),+ n4 = (size_t)(m->ana_grade[1] * (float)total + 0.5f),+ n2 = (size_t)(m->ana_grade[2] * (float)total + 0.5f);+ for (size_t q = 0; q < total; q++) {+ size_t top = total - 1 - q;+ m->ana_level[(size_t)r[q].g * stride + r[q].j] =+ top < n6 ? 3+ : top < n6 + n4 ? 2+ : top < n6 + n4 + n2 ? 1+ : 0;+ }+ }+ /* the record first, with h as it was */+ uint8_t *keep = m->ana_stats ? malloc(stride) : NULL;+ for (uint32_t q = i; keep && q < e; q++) {+ size_t g = (uint32_t)key[q];+ uint32_t ff = m->hlen[g];+ memset(keep, 1, ff);+ for (size_t z = 0; z < k; z++)+ if (r[z].g == g)+ keep[r[z].j] = 0;+ float w = m->pair_w[m->order[g]];+ uint32_t head[5] = {(uint32_t)(m->ana_base + tok), m->ana_layer,+ m->ana_exp[g], ff, 0};+ memcpy(&head[4], &w, sizeof(w));+ fwrite(head, sizeof(head), 1, m->ana_stats);+ fwrite(m->h + g * stride, sizeof(float), ff, m->ana_stats);+ fwrite(keep, 1, ff, m->ana_stats);+ }+ free(keep);+ for (size_t q = 0; q < k; q++) {+ frame_off(m, r[q].g, r[q].j);+ m->h[(size_t)r[q].g * stride + r[q].j] = 0.0f;+ }+ free(r);+ i = e;+ }+ free(key);+ }+ for (uint32_t i = 0; i < n; i++) {+ size_t g = m->glist[i];+ janas_q8k_quantize_det(m->h + g * stride, m->hq + g * stride / JANAS_QK,+ m->hlen[g]);+ }+}++/* The pair rows glist[0 .. n) of this pass whose gate and up go to two+ bits: in each token, its ana_gulow routed experts of least weight. */+void janas_m_ana_lowmark(struct janas_llm_model *m, uint32_t n)+{+ uint64_t *key = malloc(n * sizeof(uint64_t));+ if (!key)+ return;+ uint32_t nk = 0;+ for (uint32_t i = 0; i < n; i++) {+ size_t g = m->glist[i];+ m->ana_low[g] = 0;+ if (m->ana_exp[g] == m->n_expert) /* the shared expert: whole */+ continue;+ /* by token, then by weight (a positive float's bits sort as it) */+ float w = m->pair_w[m->order[g]];+ uint32_t wb;+ memcpy(&wb, &w, sizeof(wb));+ key[nk++] = ((uint64_t)m->pair_tok[m->order[g]] << 40) |+ ((uint64_t)(wb >> 8) << 16) | (g & 0xFFFF);+ }+ qsort(key, nk, sizeof(*key), by_token);+ for (uint32_t i = 0; i < nk;) {+ uint32_t e = i;+ while (e < nk && (key[e] >> 40) == (key[i] >> 40))+ e++;+ for (uint32_t q = i; q < e && q < i + (uint32_t)m->ana_gulow; q++)+ m->ana_low[key[q] & 0xFFFF] = 1;+ i = e;+ }+ free(key);+}++/* Down at fewer bits for the neurons of the run's pairs whose level is 1 or+ 2: their contribution corrected, after the product at full precision,+ by h times the difference of the row read at two or four bits. Q6_K_P:+ its planes; Q8_0: its bytes cut to two or four high bits; other types+ left whole. Rows split among the threads. */+struct grade_job {+ struct janas_llm_model *m;+ const uint8_t *down, *p1, *p0;+ const struct janas_jns_matrix *mx;+ uint32_t a, b;+};++static void cut_q8_0(uint8_t *blocks, size_t nb32, int bits)+{+ struct janas_block_q8_0 *k = (struct janas_block_q8_0 *)blocks;+ uint8_t keep = bits == 4 ? 0xF0 : 0xC0, mid = bits == 4 ? 0x08 : 0x20;+ for (size_t b = 0; b < nb32; b++)+ for (int i = 0; i < 32; i++)+ k[b].qs[i] = (int8_t)(((uint8_t)k[b].qs[i] & keep) | mid);+}++static void grade_worker(void *arg, int tid, int n_threads)+{+ struct grade_job *J = arg;+ struct janas_llm_model *m = J->m;+ uint32_t rows = J->mx->rows, cols = J->mx->cols, nb = cols / JANAS_QK;+ int planes = J->mx->type == JANAS_Q6_K_P, q8 = J->mx->type == JANAS_Q8_0;+ size_t bs = planes ? sizeof(struct janas_block_q6kp)+ : janas_qtype_block_size((int)J->mx->type);+ float *w = malloc(3 * (size_t)cols * sizeof(float));+ uint8_t *tmp = malloc(nb * bs);+ if (!w || !tmp || !(planes || q8)) {+ free(w);+ free(tmp);+ return;+ }+ float *w6 = w, *w4 = w + cols, *w2 = w + 2 * (size_t)cols;+ for (uint32_t r = (uint32_t)tid; r < rows; r += (uint32_t)n_threads) {+ const uint8_t *row = J->down + (size_t)r * nb * bs;+ if (planes) {+ const struct janas_block_q6kp *base =+ (const struct janas_block_q6kp *)row;+ const uint8_t *p1 =+ J->p1 ? J->p1 + (size_t)r * nb * JANAS_Q6KP_PLANE : NULL;+ const uint8_t *p0 = J->p1 && J->p0+ ? J->p0 + (size_t)r * nb * JANAS_Q6KP_PLANE+ : NULL;+ janas_q6kp_dequantize(base, p1, p0, w6, cols);+ janas_q6kp_dequantize(base, p1, NULL, w4, cols);+ janas_q6kp_dequantize(base, NULL, NULL, w2, cols);+ } else {+ janas_dequantize(JANAS_Q8_0, row, w6, cols);+ memcpy(tmp, row, nb * bs);+ cut_q8_0(tmp, (size_t)nb * 8, 4);+ janas_dequantize(JANAS_Q8_0, tmp, w4, cols);+ memcpy(tmp, row, nb * bs);+ cut_q8_0(tmp, (size_t)nb * 8, 2);+ janas_dequantize(JANAS_Q8_0, tmp, w2, cols);+ }+ for (uint32_t g = J->a; g < J->b; g++) {+ const uint8_t *lv = m->ana_level + (size_t)g * m->ff_buf;+ const float *h = m->h + (size_t)g * m->ff_buf;+ double d = 0;+ for (uint32_t j = 0; j < cols; j++)+ if (lv[j] == 2)+ d += (double)h[j] * (w4[j] - w6[j]);+ else if (lv[j] == 1)+ d += (double)h[j] * (w2[j] - w6[j]);+ m->dout[(size_t)g * m->d_model + r] += (float)d;+ }+ }+ free(w);+ free(tmp);+}++void janas_m_ana_grade(struct janas_llm_model *m, const uint8_t *down,+ const uint8_t *p1, const uint8_t *p0,+ const struct janas_jns_matrix *mx, uint32_t a,+ uint32_t b)+{+ if (!m->ana_level || mx->rows != m->d_model || mx->cols > m->ff_buf)+ return;+ struct grade_job J = {+ .m = m, .down = down, .p1 = p1, .p0 = p0, .mx = mx, .a = a, .b = b};+ janas_pool_run(m->compute, grade_worker, &J);+}++void janas_m_ana_frame(struct janas_llm_model *m, uint32_t n)+{+ m->ana_base += n;+ if (!m->ana_frame)+ return;+ if (n == 1 && m->ana_frames < m->ana_frames_max) {+ char path[600];+ snprintf(path, sizeof(path), "%s/frame_%05d.ppm", m->ana_dir,+ m->ana_frames++);+ FILE *f = fopen(path, "wb");+ if (f) {+ fprintf(f, "P6\n%u %u\n255\n", m->ana_width, m->n_layer);+ fwrite(m->ana_frame, 3, (size_t)m->n_layer * m->ana_width, f);+ fclose(f);+ }+ }+ memset(m->ana_frame, 0, (size_t)m->n_layer * m->ana_width * 3);+}diff --git a/src/llm/model_attn.c b/src/llm/model_attn.cindex 905333e..8e27581 100644--- a/src/llm/model_attn.c+++ b/src/llm/model_attn.c@@ -249,9 +249,42 @@ void janas_m_attn_layer(struct janas_llm_model *m, const struct layer *ly,.rows = kvd,.cols = dm,.n_vec = n}};- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, t, (size_t)nt);+ janas_m_products(m, janas_m_gpu(m, 0), t, (size_t)nt);if (nt == 2) /* Gemma 4's full layers: V is K, before K's norm */memcpy(m->vv, m->kk, (size_t)n * kvd * sizeof(float));+ janas_m_attn_core(m, ly, n, pos0, ta);+ if (m->npu) /* the NPU's calibration (JANAS_NPU_A8=1) */+ janas_m_npu_calib(m, 0, m->ana_layer, m->att, n, qd, qd);+ double tc = now();+ /* the output gate (qwen3next) goes with the quantization now */+ struct tok_job tj = {.m = m, .ly = ly, .n = n};+ if (n < 2)+ for (uint32_t j = 0; j < n; j++)+ att_out_tok(m, ly, j);+ else+ janas_pool_run(m->compute, att_out_worker, &tj);+ struct janas_matvec_task to = {.type = (int)ly->wo->type,+ .w = data(m, ly->wo),+ .x = m->attq,+ .y = m->xn,+ .rows = dm,+ .cols = qd,+ .n_vec = n};+ janas_m_products(m, janas_m_gpu(m, 0), &to, 1);+ if (ly->post_attn)+ janas_m_post_norm(m, f32(m, ly->post_attn), n);+ janas_m_residual(m, n);+ m->phase[JANAS_PH_WO] += now() - tc;+}++/* The attention of a block whose q, k and v are in m->q, m->kk and m->vv+ (products done): q's and k's norms, RoPE, the keys and values into the+ cache, the attention into m->att. ta: when the layer began (its q, k and+ v counted with it). */+void janas_m_attn_core(struct janas_llm_model *m, const struct layer *ly,+ uint32_t n, uint32_t pos0, double ta)+{+ uint32_t hd = ly->hd, qd = m->n_head * hd, kvd = ly->n_kv * hd;int8_t *kc = m->kcache + m->kv_off[ly->slot];int8_t *vc = m->vcache + m->kv_off[ly->slot];float *kcs = m->kscale + m->ks_off[ly->slot];@@ -286,25 +319,6 @@ void janas_m_attn_layer(struct janas_llm_model *m, const struct layer *ly,m->q + (size_t)s * qd, kc, kcs, vc, vcs, len, pos0 + s,m->att + (size_t)s * qd);}- double tc = now();- m->phase[JANAS_PH_ATTN] += tc - tb;+ m->phase[JANAS_PH_ATTN] += now() - tb;trace_row(m, "kqv_out", m->att + (size_t)(n - 1) * qd, qd);- /* the output gate (qwen3next) goes with the quantization now */- if (n < 2)- for (uint32_t j = 0; j < n; j++)- att_out_tok(m, ly, j);- else- janas_pool_run(m->compute, att_out_worker, &tj);- struct janas_matvec_task to = {.type = (int)ly->wo->type,- .w = data(m, ly->wo),- .x = m->attq,- .y = m->xn,- .rows = dm,- .cols = qd,- .n_vec = n};- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, &to, 1);- if (ly->post_attn)- janas_m_post_norm(m, f32(m, ly->post_attn), n);- janas_m_residual(m, n);- m->phase[JANAS_PH_WO] += now() - tc;}diff --git a/src/llm/model_ffn.c b/src/llm/model_ffn.cindex a8f94ed..e34c178 100644--- a/src/llm/model_ffn.c+++ b/src/llm/model_ffn.c@@ -38,8 +38,15 @@* e' il 95% della fase, in prefill il 67%, e la cache passa dal 2,7% al 29,5%.** Spenta costa una lettura di variabile per invio: zero misurabile.+ *+ * In piu' (21 ott 2026) il tratto fra il router e i primi esperti, dove il+ * thread principale lavora da solo: scelta degli esperti e ordinamento,+ * apertura della cache (begin), preparazione, in microsecondi a strato; la+ * chiusura (finish, con l'attesa del disco) a parte.*/-static double ex_setup, ex_t1, ex_act, ex_t2, ex_axpy, ex_cache;+static double ex_setup, ex_t1, ex_act, ex_t2, ex_axpy, ex_begin, ex_finish,+ ex_route;+static unsigned long long ex_layers;static int ex_trace = -1;int janas_m_exp_tracing(void)@@ -53,7 +60,8 @@ int janas_m_exp_tracing(void)void janas_m_exp_report(void){- double tot = ex_setup + ex_t1 + ex_act + ex_t2 + ex_axpy + ex_cache;+ double tot =+ ex_setup + ex_t1 + ex_act + ex_t2 + ex_axpy + ex_begin + ex_finish;if (tot <= 0)return;fprintf(stderr,@@ -61,9 +69,20 @@ void janas_m_exp_report(void)"down %.1f%% axpy %.1f%% cache %.1f%% (%.0f ms, matvec ""%.1f%%)\n",100 * ex_setup / tot, 100 * ex_t1 / tot, 100 * ex_act / tot,- 100 * ex_t2 / tot, 100 * ex_axpy / tot, 100 * ex_cache / tot,- tot * 1e3, 100 * (ex_t1 + ex_t2) / tot);- ex_setup = ex_t1 = ex_act = ex_t2 = ex_axpy = ex_cache = 0;+ 100 * ex_t2 / tot, 100 * ex_axpy / tot,+ 100 * (ex_begin + ex_finish) / tot, tot * 1e3,+ 100 * (ex_t1 + ex_t2) / tot);+ if (ex_layers)+ fprintf(stderr,+ "router to experts, a layer: choice and order %.1f us, cache "+ "begin %.1f us, setup %.1f us; cache finish %.1f us (%llu "+ "layers)\n",+ ex_route / ex_layers * 1e6, ex_begin / ex_layers * 1e6,+ ex_setup / ex_layers * 1e6, ex_finish / ex_layers * 1e6,+ ex_layers);+ ex_setup = ex_t1 = ex_act = ex_t2 = ex_axpy = ex_begin = ex_finish = 0;+ ex_route = 0;+ ex_layers = 0;}/* SiLU(gate) * up and its quantization, for the pair rows listed in glist. */@@ -123,6 +142,12 @@ static void act_worker(void *arg, int tid, int n_threads)for (; r < ff; r++)h[r] = janas_silu_mul_det(gt[r], u[r]);}+ if (m->ana_tok) /* the Ana-Net probe: by token, after every pair */+ continue;+ if (m->ana_mode || m->ana_frame) /* the Ana-Net probe */+ janas_m_ana_mask(m, g, h, ff);+ if (m->nskipq && m->nskipq[g]) /* down by neuron reads h itself */+ continue;janas_q8k_quantize_det(h, m->hq + g * stride / JANAS_QK, ff);}}@@ -193,6 +218,8 @@ struct expert_run {const uint8_t *plane[2]; /* the other two planes of down, or NULL */const struct janas_jns_matrix *mx;uint32_t a, b;+ int expert; /* the routed expert's number, -1 the shared one (the Ana-Net+ probe) */};/* Experts are asked of the cache and computed a chunk at a time: 128, a@@ -221,19 +248,37 @@ static void run_experts(struct janas_llm_model *m,uint32_t dm = m->d_model, ff = m->ff_buf;size_t nbd = dm / JANAS_QK, nbf = ff / JANAS_QK;struct janas_matvec_task t1[2 * MAX_RUNS], t2[MAX_RUNS];- uint32_t ng = 0;+ struct janas_neuron_run nr[MAX_RUNS]; /* down by neuron: no product */+ uint32_t ng = 0, n1 = 0, n2 = 0, nn = 0;+ /* one run - a dense model's feed-forward, a shared expert - may go to+ the NPU whole (model_npu.c), the CPU computing the others meanwhile */+ struct janas_m_npu_ffn nf = {0};+ int nf_run = -1;for (uint32_t r = 0; r < n_runs; r++) {uint32_t a = runs[r].a, cnt = runs[r].b - runs[r].a;- for (uint32_t g = a; g < runs[r].b; g++) {+ for (uint32_t g = a; g < runs[r].b; g++)memcpy(m->xg + (size_t)g * nbd,m->xq + (size_t)m->pair_tok[m->order[g]] * nbd,nbd * sizeof(*m->xg));+ if (nf_run < 0 && m->npu &&+ janas_m_npu_ffn_begin(m, runs[r].base, runs[r].plane, runs[r].mx,+ m->xg + (size_t)a * nbd, cnt,+ m->dout + (size_t)a * dm, &nf) == 0) {+ nf_run = (int)r;+ continue;+ }+ for (uint32_t g = a; g < runs[r].b; g++) {m->glist[ng++] = g;m->hlen[g] = runs[r].mx[0].rows;+ if (m->nskipq)+ m->nskipq[g] = runs[r].mx[JANAS_JNS_DOWN].type == JANAS_Q6_K_PN;+ if (m->ana_exp) /* the Ana-Net probe: the pair's expert */+ m->ana_exp[g] =+ runs[r].expert < 0 ? m->n_expert : (uint32_t)runs[r].expert;}for (int p = 0; p < 2; p++) {const struct janas_jns_matrix *mx = &runs[r].mx[p];- t1[2 * r + p] = (struct janas_matvec_task){+ t1[n1++] = (struct janas_matvec_task){.type = (int)mx->type,.w = runs[r].base[p] + mx->offset,.x = m->xg + (size_t)a * nbd,@@ -245,7 +290,22 @@ static void run_experts(struct janas_llm_model *m,.y_stride = ff};}const struct janas_jns_matrix *d = &runs[r].mx[JANAS_JNS_DOWN];- t2[r] = (struct janas_matvec_task){+ if (d->type == JANAS_Q6_K_PN) {+ const uint8_t *w = runs[r].base[2] + d->offset;+ nr[nn++] = (struct janas_neuron_run){+ .scale = (const float *)w,+ .base =+ (const struct janas_block_q6kp *)(w ++ d->cols * sizeof(float)),+ .p1 = runs[r].plane[0],+ .p0 = runs[r].plane[1],+ .rows = d->rows,+ .cols = d->cols,+ .a = a,+ .b = runs[r].b};+ continue;+ }+ t2[n2++] = (struct janas_matvec_task){.type = (int)d->type,.w = runs[r].base[JANAS_JNS_DOWN] + d->offset,.plane = {runs[r].plane[0], runs[r].plane[1]},@@ -259,12 +319,46 @@ static void run_experts(struct janas_llm_model *m,}if (janas_m_exp_tracing())ex_setup += now() - t_enter;- EX_T(ex_t1, janas_gpu_matvec_group(janas_m_gpu(m, 1), m->compute, t1,- 2 * (size_t)n_runs));+ EX_T(ex_t1, janas_m_products(m, janas_m_gpu(m, 1), t1, n1));+ /* the Ana-Net probe: each neuron's agreement, from gate's and up's rows,+ and the norms of down's columns, once an expert */+ if (m->ana_low)+ janas_m_ana_lowmark(m, ng);+ for (uint32_t r = 0;+ (m->ana_agree || m->ana_coarse || m->ana_low) && r < n_runs; r++)+ janas_m_ana_agree(m, runs[r].base[0] + runs[r].mx[0].offset,+ runs[r].base[1] + runs[r].mx[1].offset, runs[r].mx,+ runs[r].a, runs[r].b);+ for (uint32_t r = 0; m->ana_coln && r < n_runs; r++)+ janas_m_ana_coln(+ m, runs[r].expert < 0 ? m->n_expert : (uint32_t)runs[r].expert,+ runs[r].base[2] + runs[r].mx[2].offset, runs[r].plane[0],+ runs[r].plane[1], &runs[r].mx[2]);struct act_job aj = {m, ng};EX_T(ex_act, janas_pool_run(m->compute, act_worker, &aj));- EX_T(ex_t2,- janas_gpu_matvec_group(janas_m_gpu(m, 1), m->compute, t2, n_runs));+ /* the NPU's calibration (JANAS_NPU_A8=1): a dense model's intermediate */+ for (uint32_t i = 0; m->npu && m->n_expert <= 1 && i < ng; i++)+ janas_m_npu_calib(m, 2, m->ana_layer, m->h + (size_t)m->glist[i] * ff,+ 1, m->hlen[m->glist[i]], ff);+ if (m->ana_tok) /* the Ana-Net probe: a token's neurons ranked together */+ janas_m_ana_tok(m, ng);+ if (nn && m->neuron_rank)+ janas_m_neuron_levels(m, ng);+ EX_T(ex_t2, janas_m_neuron_down(m, nr, nn));+ if (n2)+ EX_T(ex_t2, janas_m_products(m, janas_m_gpu(m, 1), t2, n2));+ /* the Ana-Net probe: neurons kept at fewer bits, their down corrected */+ for (uint32_t r = 0; m->ana_level && r < n_runs; r++)+ janas_m_ana_grade(m, runs[r].base[2] + runs[r].mx[2].offset,+ runs[r].plane[0], runs[r].plane[1], &runs[r].mx[2],+ runs[r].a, runs[r].b);+ if (nf_run >= 0 && janas_m_npu_ffn_finish(m, &nf) != 0) {+ /* the NPU failed: that run on the CPU after all */+ int use = m->npu_use;+ m->npu_use = 0;+ run_experts(m, &runs[nf_run], 1);+ m->npu_use = use;+ }}int janas_m_route_rank(struct janas_llm_model *m, uint32_t l, uint32_t n,@@ -498,9 +592,12 @@ int janas_m_moe_block(struct janas_llm_model *m, const struct layer *ly,uint32_t dm = m->d_model, ne = m->n_expert;uint32_t k = part == MOE_SHARED ? 0 : m->k_use;uint32_t np = n * k;+ double t_route = 0;if (k) {struct router_job rj = {m, ly->router16, n};janas_pool_run(m->compute, router_worker, &rj);+ if (janas_m_exp_tracing())+ t_route = now();/* per token: softmax, top-k, normalized weights */struct tok_job tj = {.m = m, .n = n};@@ -550,6 +647,10 @@ int janas_m_moe_block(struct janas_llm_model *m, const struct layer *ly,}double t1 = now();m->phase[JANAS_PH_ROUTER] += t1 - t0;+ if (t_route > 0) {+ ex_route += t1 - t_route;+ ex_layers++;+ }/* experts in chunks: compute those in RAM while the others load; theshared expert, resident, goes with the first of them */@@ -559,7 +660,7 @@ int janas_m_moe_block(struct janas_llm_model *m, const struct layer *ly,uint8_t ready[EXPERT_CHUNK];if (cn) {int rc_b;- EX_T(ex_cache, rc_b = janas_expert_cache_begin(+ EX_T(ex_begin, rc_b = janas_expert_cache_begin(cache, l, distinct + c0, cn, slots, ready));if (rc_b < 0)return -1;@@ -567,7 +668,7 @@ int janas_m_moe_block(struct janas_llm_model *m, const struct layer *ly,for (int pass = 0; pass < 2; pass++) {if (pass == 1 && cn) {int rc_f;- EX_T(ex_cache, rc_f = janas_expert_cache_finish(cache));+ EX_T(ex_finish, rc_f = janas_expert_cache_finish(cache));if (rc_f != 0)return -1;}@@ -579,7 +680,8 @@ int janas_m_moe_block(struct janas_llm_model *m, const struct layer *ly,{NULL, NULL},ly->sh_mx,np,- nt};+ nt,+ -1};for (uint32_t i = 0; i < cn; i++)if ((pass == 0) == (ready[i] != 0)) {uint32_t e = distinct[c0 + i];@@ -595,7 +697,8 @@ int janas_m_moe_block(struct janas_llm_model *m, const struct layer *ly,{pl[0], pl[1]},jl->m,m->count[e],- m->count[e + 1]};+ m->count[e + 1],+ (int)e};}if (nr)run_experts(m, runs, nr);diff --git a/src/llm/model_gpu.c b/src/llm/model_gpu.cindex 5d6871a..f28736e 100644--- a/src/llm/model_gpu.c+++ b/src/llm/model_gpu.c@@ -516,8 +516,8 @@ int janas_m_gpu_token(struct janas_llm_model *m, uint32_t pos, uint32_t n,tok = e && atoi(e) > 0;blocks = b ? atoi(b) > 0 : -1; /* -1: not said */}- int prompt =- janas_gpu_fast_prompt() && n >= JANAS_GPU_FAST_N && blocks != 0;+ int prompt = janas_gpu_fast_prompt() && !m->prompts_off_gpu &&+ n >= JANAS_GPU_FAST_N && blocks != 0;/* A short pass (a chain of drafts to verify) where the tuner chose theGPU for it: the whole pass in one submission, the CPU idle, ratherthan the products by groups beside the CPU - on the developmentdiff --git a/src/llm/model_impl.h b/src/llm/model_impl.hindex 1ee4cb8..4fa0cab 100644--- a/src/llm/model_impl.h+++ b/src/llm/model_impl.h@@ -82,10 +82,20 @@ struct janas_llm_model {int p_cores, p_threads, all_threads;struct janas_tuner tuner;char tune_key[768];- int gpu_use; /* the current pass may use the GPU */- struct janas_gpu *gpu; /* optional, for products over blocks */- int resident_gpu; /* the resident region belongs to the GPU */- int gpu_off; /* weights not shared with it: CPU only */+ int gpu_use; /* the current pass may use the GPU */+ struct janas_gpu *gpu; /* optional, for products over blocks */+ struct janas_m_npu *npu; /* optional (JANAS_NPU=1), model_npu.c */+ int npu_use; /* the current pass may use the NPU */+ char npu_why[160]; /* no NPU: why (janas_llm_model_npu_why) */+ int resident_gpu; /* the resident region belongs to the GPU */+ int gpu_off; /* weights not shared with it: CPU only */+ /* the user keeps prompts off the GPU (--prompt-on cpu, npu): its fast+ prompt, which reads them whatever the tuner chose, does not */+ int prompts_off_gpu;+ /* the user's devices for prompts, drafts, replies (common/devices.h:+ janas_devices_vars' order), as this machine has them; 0 as the+ engine chooses */+ int dev_on[3];/* the experts' arena on the GPU (dense models, and mixtures whoseevery expert fits the cache): 0 not yet, 1 there, -1 not possible;arena_stale when a slot changed since - the GPU's copy no longer@@ -201,6 +211,10 @@ struct janas_llm_model {int base; /* buffer holding the base */int src; /* this call: buffer the tokens start from */uint32_t base_pos, log_n, replay;+ /* the call goes on from the one before it in the same pass (the NPU's+ second half of a block): the state and the convolution's inputs read+ where that one left them, in the other buffer */+ int rec_cont;uint32_t n_ctx_train; /* what the model was trained for, 0 if unsaid *//*@@ -260,6 +274,54 @@ struct janas_llm_model {uint32_t *pair_tok, *pair_exp, *order, *count, *glist;float *pair_w, *gate, *up, *h, *dout;uint32_t *hlen; /* per pair row: the rows of its expert's gate */+ /* the Ana-Net probe (model_ana.c): its mode (0 off), the fraction of a+ pair's neurons switched off, each pair row's agreements (ff_buf floats+ a row), the layer being computed, a token's picture and where it goes */+ int ana_mode, ana_tok; /* ana_tok: the fraction is of a token's neurons */+ float ana_frac;+ float *ana_agree;+ /* each pair row's expert (n_expert: the shared one), and the norms of+ the columns of each layer's experts' down matrices, with whether+ computed yet */+ uint32_t *ana_exp;+ float *ana_coln;+ uint8_t *ana_coln_ok;+ /* JANAS_ANA_STATS: every pair's record, and the tokens done so far */+ FILE *ana_stats, *ana_xstats; /* ana_xstats: JANAS_ANA_XSTATS */+ uint64_t ana_base;+ /* JANAS_ANA_COARSE: each pair row's h from gate and up at two bits, the+ choice made on it; the neurons both choices keep, and the true one's */+ float *ana_coarse;+ uint64_t ana_both_kept, ana_true_kept;+ /* JANAS_ANA_GRADE: the fractions of a token's neurons kept at 6, 4 and 2+ bits of down, and each pair row's levels (3, 2, 1; 0 off) */+ float ana_grade[3];+ uint8_t *ana_level;+ /* JANAS_ANA_GULOW: the routed experts of least weight in a token whose+ gate and up are read at two bits, and each pair row's mark */+ int ana_gulow;+ uint8_t *ana_low;+ uint32_t ana_layer, ana_width;+ /* the Janet probe (model_janet.c): a layer's feed-forward recorded, or+ run by Janet's detectors in its place; NULL when off */+ struct janas_janet *janet;+ uint8_t *ana_frame;+ char ana_dir[512];+ int ana_frames, ana_frames_max;+ /* the experts' down matrix by neuron (model_neurons.c): whether a layer+ has it, whether a token's neurons are ranked into levels and the+ fractions read at 6, 4 and 2 bits, each pair row's levels, a pass's+ scores and its pair rows by token */+ int neuron_down, neuron_rank;+ float neuron_frac[3];+ uint8_t *nlevel;+ float *nscore;+ /* a token's chunks of neurons, each its sum, and its length; the pair+ rows whose h needs no eight-bit copy */+ float *npart;+ size_t npart_len;+ uint8_t *nskipq;+ uint32_t *ntok_first, *ntok_fill, *ntok_list;struct janas_block_q8k *xg, *hq;uint32_t k_use; /* experts used per token, at most k (see set_experts) */int exp_level; /* planes of the experts' down matrix read: 1, 2 or 3 */@@ -389,9 +451,53 @@ struct tok_job {void janas_m_init_tuner(struct janas_llm_model *m);/* Memory the GPU will import collapsed into 2 MB pages (Linux; seemodel_load.c), before the import pins it. */+/* The Ana-Net probe (model_ana.c, JANAS_ANA_*): set up at load (0, or -1+ out of memory), each run's agreements after its gate and up products, a+ pair row's neurons switched off before its down product, a token's+ picture written once its layers are done, freed. */+int janas_m_ana_init(struct janas_llm_model *m, size_t pairs);+void janas_m_ana_agree(struct janas_llm_model *m, const uint8_t *wg,+ const uint8_t *wu, const struct janas_jns_matrix *mx,+ uint32_t a, uint32_t b);+void janas_m_ana_mask(struct janas_llm_model *m, size_t g, float *h,+ uint32_t ff);+void janas_m_ana_coln(struct janas_llm_model *m, uint32_t e,+ const uint8_t *down, const uint8_t *p1, const uint8_t *p0,+ const struct janas_jns_matrix *mx);+void janas_m_ana_tok(struct janas_llm_model *m, uint32_t n);+void janas_m_ana_lowmark(struct janas_llm_model *m, uint32_t n);+void janas_m_ana_grade(struct janas_llm_model *m, const uint8_t *down,+ const uint8_t *p1, const uint8_t *p0,+ const struct janas_jns_matrix *mx, uint32_t a,+ uint32_t b);+void janas_m_ana_frame(struct janas_llm_model *m, uint32_t n);+void janas_m_ana_free(struct janas_llm_model *m);+int janas_m_janet_init(struct janas_llm_model *m);+void janas_m_janet_rec(struct janas_llm_model *m, uint32_t l, uint32_t n,+ int after);+int janas_m_janet_ffn(struct janas_llm_model *m, uint32_t l, uint32_t n);+void janas_m_janet_free(struct janas_llm_model *m);+/* The experts' down matrix by neuron (model_neurons.c): set up at load (0,+ or -1 out of memory), the levels of a pass's neurons, its experts' down+ products, freed. An expert whose down matrix is by neuron, applied to the+ pair rows [a, b): */+struct janas_neuron_run {+ const float *scale; /* each output channel's, after the sum */+ const struct janas_block_q6kp *base;+ const uint8_t *p1, *p0; /* the planes the cache holds, or NULL */+ uint32_t rows, cols; /* neurons, outputs */+ uint32_t a, b;+};+int janas_m_neurons_init(struct janas_llm_model *m, size_t pairs);+void janas_m_neuron_levels(struct janas_llm_model *m, uint32_t ng);+void janas_m_neuron_down(struct janas_llm_model *m,+ const struct janas_neuron_run *runs, uint32_t n);+void janas_m_neurons_free(struct janas_llm_model *m);void janas_m_huge_pages(void *p, uint64_t bytes);-/* The longest region of memory the GPU imports (gpu.c janas_gpu_import). */-#define JANAS_M_REGION_MAX ((uint64_t)4 << 30)+/* The longest region of memory the GPU imports (gpu.c janas_gpu_import): a+ page short of 4 GiB, which Mesa's Intel driver gave the kernel as 0 bytes+ (21 Oct 2026). */+#define JANAS_M_REGION_MAX (((uint64_t)4 << 30) - 4096)/* The next region the GPU imports of bytes, from at: its first byte into*from (at, or the 2 MB boundary before it where huge: memory allocated onone), and its end, returned: bytes, or past at a multiple of unit (unit@@ -409,16 +515,88 @@ int janas_m_gpu_token(struct janas_llm_model *m, uint32_t pos, uint32_t n,void janas_m_apply_candidate(struct janas_llm_model *m, int cand, uint32_t nv);/* Whether the whole token is asked of the GPU (JANAS_GPU_TOKEN=1). */int janas_m_gpu_token_asked(void);+/* model_npu.c: the NPU for the products of blocks (JANAS_NPU=1), opened+ once the resident region is read; janas_m_products runs a group of+ products as janas_gpu_matvec_group does, those the NPU takes there. */+void janas_m_npu_open(struct janas_llm_model *m);+void janas_m_npu_close(struct janas_llm_model *m);+/* Whether the NPU takes products of a pass of n tokens (its candidate has+ it, and n reaches JANAS_NPU_MIN_N). */+int janas_m_npu_takes(const struct janas_llm_model *m, uint32_t n);+/* Whether the tuner may give the NPU the blocks by itself: where its+ answers measured at par with the CPU's (janas_llm_model_npu_auto). */+int janas_m_npu_auto(const struct janas_llm_model *m);+/* The NPU kept awake through a pass of n tokens it takes products of+ (between them the CPU works long enough for it to be suspended), let+ sleep otherwise. */+void janas_m_npu_awake(struct janas_llm_model *m, uint32_t n);+/* A pass is over: a preparation of the NPU's graphs it began, too+ (janas_llm_model_npu_preparing). */+void janas_m_npu_pass_end(struct janas_llm_model *m);+/*+ * A feed-forward run (an expert, a shared expert, a dense model's) on the+ * NPU in one trip: gate, up, the activation and down, its n_vec rows of x+ * (Q8_K) in, n_vec rows of d_model floats out at dout once finished. w:+ * the slots of gate, up and down (each matrix at its mx offset in it),+ * plane: down's planes (Q6_K_P), mx their matrices. 0 with the run in flight+ * (the caller computes the others, then janas_m_npu_ffn_finish), -1 if it stays+ * on the CPU. One at a time.+ */+struct janas_m_npu_ffn {+ struct npu_entry *e;+ float *dout;+ size_t n_vec, d;+};+int janas_m_npu_ffn_begin(struct janas_llm_model *m, const uint8_t *const w[3],+ const uint8_t *const plane[2],+ const struct janas_jns_matrix *mx,+ const struct janas_block_q8k *x, uint32_t n_vec,+ float *dout, struct janas_m_npu_ffn *job);+/* Waits for it and stores its rows; -1 if the NPU failed (the run is then+ the caller's to compute). */+int janas_m_npu_ffn_finish(struct janas_llm_model *m,+ struct janas_m_npu_ffn *job);+/*+ * The block's first layers on the NPU, a graph each (norms, projections,+ * the FFN, the residual), the attention or the recurrence between them on+ * the CPU: for dense models laid out as Qwen3, Qwen3.5 or Gemma 4, when at+ * least nine layers in ten fit the NPU (JANAS_NPU_LAYERS=2: the first ones+ * alone, however few; 0: never). The number of layers done+ * (m->n_layer: all), m->x their output, the caller's loop going on from+ * there; -1 if not done (nothing touched), -2 if the NPU failed halfway+ * (the block cannot be finished).+ */+int janas_m_npu_layers(struct janas_llm_model *m, uint32_t n, uint32_t pos0);+/* The calibration of the NPU's INT8 activations (JANAS_NPU_A8=1): rows of+ width values (stride apart) of an input of layer l's products, at site+ 0 the attention's output (wo), 1 the FFN's norm (gate, up), 2 the FFN's+ intermediate (down), 3 the norm before the attention (q, k, v); their+ channel maxima kept. Nothing outside a calibration's pass. */+void janas_m_npu_calib(struct janas_llm_model *m, int site, uint32_t l,+ const float *x, uint32_t rows, uint32_t width,+ size_t stride);+void janas_m_products(struct janas_llm_model *m, struct janas_gpu *g,+ const struct janas_matvec_task *t, size_t n);uint32_t *janas_m_profile_read(const struct janas_llm_model *m, size_t *used);void janas_m_profile_write(const struct janas_llm_model *m);void janas_m_norm_quant(struct janas_llm_model *m, const float *w,uint32_t first, uint32_t n);void janas_m_residual(struct janas_llm_model *m, uint32_t n);void janas_m_post_norm(struct janas_llm_model *m, const float *w, uint32_t n);+void janas_m_attn_core(struct janas_llm_model *m, const struct layer *ly,+ uint32_t n, uint32_t pos0, double ta);void janas_m_attn_layer(struct janas_llm_model *m, const struct layer *ly,uint32_t n, uint32_t pos0);void janas_m_rec_layer(struct janas_llm_model *m, const struct layer *ly,uint32_t n);+/* Its recurrence on a block whose input products are in m->big and betas+ and alphas in m->ba: the convolution, the state, the gated norm, into+ m->att. ta: when the layer began (its products counted with it). */+void janas_m_rec_core(struct janas_llm_model *m, const struct layer *ly,+ uint32_t n, double ta);+/* Qwen3.5's betas then alphas into m->ba, from n normalized rows of xn. */+void janas_m_rec_ba(struct janas_llm_model *m, const struct layer *ly,+ const float *xn, uint32_t n);void janas_m_embed(struct janas_llm_model *m, int32_t token, float *x);/* sum of exp(l[i] - mx), i < n, vectorized where the CPU can */double janas_m_exp_sum(const float *l, uint32_t n, float mx);@@ -470,7 +648,8 @@ static inline struct janas_gpu *janas_m_gpu(const struct janas_llm_model *m,{if (!m->gpu || m->gpu_off || (arena && m->arena_stale))return NULL;- if (m->gpu_use || (m->tuner.allow_gpu && janas_gpu_fast_prompt()))+ if (m->gpu_use ||+ (m->tuner.allow_gpu && janas_gpu_fast_prompt() && !m->prompts_off_gpu))return m->gpu;return NULL;}diff --git a/src/llm/model_janet.c b/src/llm/model_janet.cnew file mode 100644index 0000000..e45d00f--- /dev/null+++ b/src/llm/model_janet.c@@ -0,0 +1,347 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * model_janet.c - the Janet probe (job/docs/progetto_jnet.md): a model's+ * feed-forward replaced, layer by layer, by Janet's detectors trained to+ * imitate it (job/jnet/lm, jlm ffnfit). A probe: only the CPU's path has it+ * (JANAS_GPU=0), and the detectors run in floats, one token at a time.+ *+ * JANAS_JANET_REC=dir with JANAS_JANET_REC_LAYERS=l1,l2,...: for those+ * layers each token's feed-forward input (the normed state, floats) is+ * appended to dir/x<l>.f32 and its output (what the block adds to the+ * residual) to dir/y<l>.f32, d_model floats a token.+ * JANAS_JANET_FFN=file1,file2,...: Janet feed-forwards (jlm ffnfit's files,+ * each naming its layer) run in place of those layers' own; or the control,+ * a SwiGLU trained the same way (its file "SWIGLUF1").+ *+ * A Janet detector u: the input in K zones of contiguous components, each+ * zone's branch sum m_k = its components times the unit's weights plus an+ * offset; the zones' heights h_k = A_k / (A_k + 1), A_k the sum of the+ * zone's components' sizes (each at most 1); the centre the heights'+ * barycentre of the m_k; the support S the sum of h_k (1 - u_k^2) over the+ * hills that cover the centre (u_k = (centre - m_k) / tolerance); Alpha =+ * gain ((1 + kappa) S - kappa T), T the heights' sum; the unit speaks when+ * Alpha reaches its threshold (and, rectified, the centre is positive) and+ * sends min(Alpha, 1) times the centre to its row of down.+ */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "model_impl.h"++#define JANET_MAX_LAYERS 256+#define JANET_MAX_K 8++/* One layer's Janet feed-forward, as jlm ffnfit writes it (swiglu: the+ control, wa its gate and wd its down, wu its up). */+struct jffn {+ int d, h, K, rectify, in_full, swiglu;+ float *wu;+ float *wa; /* the branches, d rows (by input) of h */+ float *wd; /* the down, h rows (by unit) of d */+ float *inv; /* each unit's inverse tolerance, gain, kappa, threshold */+ float *gain, *kap, *th;+ float *b; /* its K offsets, h rows of K */+};++struct janas_janet {+ char dir[512];+ unsigned char rec[JANET_MAX_LAYERS];+ FILE *fx[JANET_MAX_LAYERS], *fy[JANET_MAX_LAYERS];+ float *xb; /* the residual before a recorded block, blk rows */+ struct jffn *ffn[JANET_MAX_LAYERS];+ float *msum, *out, *yrow; /* a token's branch sums, outputs, its add */+ size_t scratch_h;+ uint64_t rows_rec, rows_run, spoke, units;+};++static void jffn_free(struct jffn *f)+{+ if (!f)+ return;+ free(f->wa), free(f->wd), free(f->inv), free(f->gain), free(f->kap);+ free(f->wu);+ free(f->th), free(f->b), free(f);+}++static int read_floats(FILE *f, float **p, size_t n)+{+ *p = malloc(n * sizeof(float));+ return *p && fread(*p, sizeof(float), n, f) == n ? 0 : -1;+}++/* A file of jlm ffnfit: "JANETFF1", then layer, d, h, K, rectify, in_full+ as 32-bit integers, then the floats. Its layer, or -1. */+static int jffn_load(const char *path, uint32_t dm, struct jffn **out)+{+ FILE *f = fopen(path, "rb");+ if (!f) {+ fprintf(stderr, "janet: %s: cannot open\n", path);+ return -1;+ }+ char magic[8];+ int32_t hd[6];+ struct jffn *j = calloc(1, sizeof(*j));+ if (j && fread(magic, 1, 8, f) == 8 && !memcmp(magic, "SWIGLUF1", 8) &&+ fread(hd, sizeof(int32_t), 3, f) == 3) { /* the control */+ j->swiglu = 1, j->d = hd[1], j->h = hd[2], j->K = 1;+ size_t d = (size_t)j->d, h = (size_t)j->h;+ if ((uint32_t)j->d != dm || j->h < 1 || hd[0] < 0 ||+ hd[0] >= JANET_MAX_LAYERS || read_floats(f, &j->wa, d * h) ||+ read_floats(f, &j->wu, d * h) || read_floats(f, &j->wd, h * d)) {+ fprintf(stderr, "janet: %s: bad shape or short file\n", path);+ fclose(f), jffn_free(j);+ return -1;+ }+ fclose(f);+ *out = j;+ return hd[0];+ }+ if (!j || memcmp(magic, "JANETFF1", 8) ||+ fread(hd, sizeof(int32_t), 6, f) != 6) {+ fprintf(stderr, "janet: %s: not a Janet feed-forward\n", path);+ fclose(f), free(j);+ return -1;+ }+ j->d = hd[1], j->h = hd[2], j->K = hd[3], j->rectify = hd[4];+ j->in_full = hd[5];+ int layer = hd[0];+ size_t d = (size_t)j->d, h = (size_t)j->h;+ if ((uint32_t)j->d != dm || j->K < 1 || j->K > JANET_MAX_K || j->d % j->K ||+ j->h < 1 || layer < 0 || layer >= JANET_MAX_LAYERS ||+ read_floats(f, &j->wa, d * h) || read_floats(f, &j->wd, h * d) ||+ read_floats(f, &j->inv, h) || read_floats(f, &j->gain, h) ||+ read_floats(f, &j->kap, h) || read_floats(f, &j->th, h) ||+ read_floats(f, &j->b, h * j->K)) {+ fprintf(stderr, "janet: %s: bad shape or short file\n", path);+ fclose(f), jffn_free(j);+ return -1;+ }+ fclose(f);+ *out = j;+ return layer;+}++int janas_m_janet_init(struct janas_llm_model *m)+{+ const char *rec = getenv("JANAS_JANET_REC"),+ *ffn = getenv("JANAS_JANET_FFN");+ if ((!rec || !*rec) && (!ffn || !*ffn))+ return 0;+ struct janas_janet *J = calloc(1, sizeof(*J));+ if (!J)+ return -1;+ m->janet = J;+ uint32_t dm = m->d_model;+ if (rec && *rec) {+ snprintf(J->dir, sizeof(J->dir), "%s", rec);+ const char *ls = getenv("JANAS_JANET_REC_LAYERS");+ for (const char *s = ls ? ls : "0"; *s;) {+ char *e;+ long l = strtol(s, &e, 10);+ if (e == s)+ break;+ if (l >= 0 && l < JANET_MAX_LAYERS && (uint32_t)l < m->n_layer) {+ char p[600];+ J->rec[l] = 1;+ snprintf(p, sizeof(p), "%s/x%ld.f32", J->dir, l);+ J->fx[l] = fopen(p, "wb");+ snprintf(p, sizeof(p), "%s/y%ld.f32", J->dir, l);+ J->fy[l] = fopen(p, "wb");+ if (!J->fx[l] || !J->fy[l]) {+ fprintf(stderr, "janet: cannot write in %s\n", J->dir);+ return -1;+ }+ }+ s = *e == ',' ? e + 1 : e;+ }+ J->xb = malloc((size_t)m->blk * dm * sizeof(float));+ if (!J->xb)+ return -1;+ }+ if (ffn && *ffn) {+ char buf[4096];+ snprintf(buf, sizeof(buf), "%s", ffn);+ for (char *t = strtok(buf, ","); t; t = strtok(NULL, ",")) {+ struct jffn *f = NULL;+ int l = jffn_load(t, dm, &f);+ if (l < 0)+ return -1;+ if ((uint32_t)l >= m->n_layer) {+ fprintf(stderr, "janet: %s: layer %d of %u\n", t, l,+ m->n_layer);+ jffn_free(f);+ return -1;+ }+ jffn_free(J->ffn[l]);+ J->ffn[l] = f;+ if ((size_t)f->h > J->scratch_h)+ J->scratch_h = (size_t)f->h;+ if (f->swiglu)+ fprintf(stderr,+ "janet: layer %d's feed-forward by the control, %d "+ "SwiGLU units (%s)\n",+ l, f->h, t);+ else+ fprintf(stderr,+ "janet: layer %d's feed-forward by %d detectors of %d "+ "branches (%s)\n",+ l, f->h, f->K, t);+ }+ J->msum = malloc(J->scratch_h * (JANET_MAX_K + 1) * sizeof(float));+ J->out = malloc(J->scratch_h * sizeof(float));+ J->yrow = malloc((size_t)dm * sizeof(float));+ if (!J->msum || !J->out || !J->yrow)+ return -1;+ }+ return 0;+}++/* The recording around layer l's feed-forward of the n rows: before it+ (after = 0) the inputs written and the residual kept, after it the+ block's output (the residual's change) written. */+void janas_m_janet_rec(struct janas_llm_model *m, uint32_t l, uint32_t n,+ int after)+{+ struct janas_janet *J = m->janet;+ if (!J || l >= JANET_MAX_LAYERS || !J->rec[l])+ return;+ size_t nd = (size_t)n * m->d_model;+ if (!after) {+ fwrite(m->xn, sizeof(float), nd, J->fx[l]);+ memcpy(J->xb, m->x, nd * sizeof(float));+ return;+ }+ for (size_t i = 0; i < nd; i++)+ J->xb[i] = m->x[i] - J->xb[i];+ fwrite(J->xb, sizeof(float), nd, J->fy[l]);+ J->rows_rec += n;+}++/* The control's: silu(gate) times up, its down rows. */+static void swiglu_row(struct janas_janet *J, const struct jffn *f,+ const float *x, float *y)+{+ int d = f->d, h = f->h;+ float *g = J->msum, *u = J->msum + h;+ memset(g, 0, sizeof(float) * 2 * (size_t)h);+ for (int i = 0; i < d; i++) {+ float xi = x[i];+ const float *wg = f->wa + (size_t)i * h, *wu = f->wu + (size_t)i * h;+ for (int k = 0; k < h; k++)+ g[k] += xi * wg[k], u[k] += xi * wu[k];+ }+ for (int k = 0; k < h; k++) {+ float o = (float)(g[k] / (1 + exp(-(double)g[k]))) * u[k];+ const float *w = f->wd + (size_t)k * d;+ for (int i = 0; i < d; i++)+ y[i] += o * w[i];+ }+}++/* One token's Janet feed-forward: from x (d) its output added to y. */+static void jffn_row(struct janas_janet *J, const struct jffn *f,+ const float *x, float *y)+{+ if (f->swiglu) {+ swiglu_row(J, f, x, y);+ return;+ }+ int d = f->d, h = f->h, K = f->K, dz = d / K;+ double hk[JANET_MAX_K], T = 0;+ for (int k = 0; k < K; k++) {+ double A = 0;+ for (int i = k * dz; i < (k + 1) * dz; i++) {+ double ax = fabs((double)x[i]);+ A += f->in_full ? 1 : ax < 1 ? ax : 1;+ }+ hk[k] = A / (A + 1);+ T += hk[k];+ }+ float *ms = J->msum;+ memset(ms, 0, sizeof(float) * (size_t)K * h);+ for (int k = 0; k < K; k++) {+ float *mk = ms + (size_t)k * h;+ for (int i = k * dz; i < (k + 1) * dz; i++) {+ float xi = x[i];+ if (xi == 0)+ continue;+ const float *w = f->wa + (size_t)i * h;+ for (int u = 0; u < h; u++)+ mk[u] += xi * w[u];+ }+ }+ for (int u = 0; u < h; u++) {+ double mk[JANET_MAX_K], xc = 0, S = 0;+ for (int k = 0; k < K; k++) {+ mk[k] = (double)ms[(size_t)k * h + u] + f->b[(size_t)u * K + k];+ xc += hk[k] * mk[k];+ }+ xc = T > 0 ? xc / T : 0;+ for (int k = 0; k < K; k++) {+ double uu = (xc - mk[k]) * f->inv[u];+ S += uu * uu < 1 ? hk[k] * (1 - uu * uu) : 0;+ }+ double A = f->gain[u] * ((1 + f->kap[u]) * S - f->kap[u] * T);+ int speak = A >= f->th[u] && (!f->rectify || xc > 0);+ double cl = A < 0 ? 0 : A > 1 ? 1 : A;+ J->out[u] = speak ? (float)(cl * xc) : 0;+ J->spoke += speak;+ }+ J->units += (uint64_t)h;+ for (int u = 0; u < h; u++) {+ float o = J->out[u];+ if (o == 0)+ continue;+ const float *w = f->wd + (size_t)u * d;+ for (int i = 0; i < d; i++)+ y[i] += o * w[i];+ }+}++/* Layer l's feed-forward by Janet's detectors, when the probe has one for+ it: each of the n rows' output added to the residual; 1 when it ran. */+int janas_m_janet_ffn(struct janas_llm_model *m, uint32_t l, uint32_t n)+{+ struct janas_janet *J = m->janet;+ if (!J || l >= JANET_MAX_LAYERS || !J->ffn[l])+ return 0;+ uint32_t dm = m->d_model;+ for (uint32_t t = 0; t < n; t++) {+ memset(J->yrow, 0, sizeof(float) * dm);+ jffn_row(J, J->ffn[l], m->xn + (size_t)t * dm, J->yrow);+ float *x = m->x + (size_t)t * dm;+ for (uint32_t i = 0; i < dm; i++)+ x[i] += J->yrow[i];+ }+ J->rows_run += n;+ return 1;+}++void janas_m_janet_free(struct janas_llm_model *m)+{+ struct janas_janet *J = m->janet;+ if (!J)+ return;+ if (J->rows_rec)+ fprintf(stderr, "janet: %llu rows recorded in %s (all layers)\n",+ (unsigned long long)J->rows_rec, J->dir);+ if (J->rows_run)+ fprintf(stderr,+ "janet: %llu rows through Janet's feed-forward, %.1f%% of "+ "its detectors speaking\n",+ (unsigned long long)J->rows_run,+ J->units ? 100.0 * (double)J->spoke / (double)J->units : 0);+ for (int l = 0; l < JANET_MAX_LAYERS; l++) {+ if (J->fx[l])+ fclose(J->fx[l]);+ if (J->fy[l])+ fclose(J->fy[l]);+ jffn_free(J->ffn[l]);+ }+ free(J->xb), free(J->msum), free(J->out), free(J->yrow);+ free(J);+ m->janet = NULL;+}diff --git a/src/llm/model_load.c b/src/llm/model_load.cindex 97916c1..9ab1d89 100644--- a/src/llm/model_load.c+++ b/src/llm/model_load.c@@ -739,8 +739,12 @@ struct janas_llm_model *janas_llm_model_load(const char *path,12288): the buffers take the widest */for (uint32_t l = 0; l < m->n_layer; l++) {uint32_t r = m->j.layers[l].m[JANAS_JNS_GATE].rows;+ const struct janas_jns_matrix *dn = &m->j.layers[l].m[JANAS_JNS_DOWN];+ /* by neuron (tools/jns_neurons.c), its rows are the gate's */+ int by_neuron = dn->type == JANAS_Q6_K_PN;if ((r != m->d_ff && m->n_expert > 1) || r % JANAS_QK ||- m->j.layers[l].m[JANAS_JNS_DOWN].rows != m->d_model) {+ (by_neuron ? dn->rows != r || dn->cols != m->d_model+ : dn->rows != m->d_model)) {snprintf(err, err_len, "layer %u: expert shapes differ", l);goto fail;}@@ -1027,6 +1031,18 @@ struct janas_llm_model *janas_llm_model_load(const char *path,m->gate = out_alloc(m, P * ff * sizeof(float));m->up = out_alloc(m, P * ff * sizeof(float));m->h = malloc(P * ff * sizeof(float));+ if (janas_m_ana_init(m, P) != 0) {+ snprintf(err, err_len, "out of memory for the Ana-Net probe");+ goto fail;+ }+ if (janas_m_janet_init(m) != 0) {+ snprintf(err, err_len, "the Janet probe could not start");+ goto fail;+ }+ if (janas_m_neurons_init(m, P) != 0) {+ snprintf(err, err_len, "out of memory for the neurons' levels");+ goto fail;+ }m->dout = out_alloc(m, P * dm * sizeof(float));m->xg = malloc(P * dm / JANAS_QK * sizeof(*m->xg));m->hq = malloc(P * ff / JANAS_QK * sizeof(*m->hq));@@ -1320,6 +1336,12 @@ struct janas_llm_model *janas_llm_model_load(const char *path,for (int i = 0; i < m->n_out; i++)janas_gpu_import(m->gpu, m->out[i].p, m->out[i].bytes);}+ if (o->no_npu)+ snprintf(m->npu_why, sizeof m->npu_why,+ "left off: the expert cache needs the memory its copies "+ "would take (--prompt-on npu asks for it)");+ else+ janas_m_npu_open(m);janas_m_init_tuner(m);return m;@@ -1352,6 +1374,7 @@ void janas_llm_model_free(struct janas_llm_model *m)free(m->use_count);m->use_count = NULL;}+ janas_m_npu_close(m);janas_gpu_tok_destroy(m->gpu, m->gtok);free(m->gtok_layers);free(m->gblk_layers);@@ -1403,6 +1426,9 @@ void janas_llm_model_free(struct janas_llm_model *m)free(m->xres);free(m->xbr);free(m->hlen);+ janas_m_ana_free(m);+ janas_m_janet_free(m);+ janas_m_neurons_free(m);free(m->xq);free(m->attq);free(m->pair_tok);@@ -1767,6 +1793,11 @@ void janas_m_arena_to_gpu(struct janas_llm_model *m)in_place ? " (in place)" : "");} else {m->arena_gpu = -1; /* no room for it: the CPU goes on alone */+ if (getenv("JANAS_GPU_VERBOSE"))+ fprintf(stderr,+ "arena: %.1f GB not imported: the experts stay "+ "on the CPU\n",+ bytes / 1e9);}}diff --git a/src/llm/model_neurons.c b/src/llm/model_neurons.cnew file mode 100644index 0000000..86786fb--- /dev/null+++ b/src/llm/model_neurons.c@@ -0,0 +1,347 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * model_neurons.c - the experts' down matrix by neuron (JANAS_Q6_K_PN,+ * tools/jns_neurons.c): each neuron of a token read at the depth its+ * contribution earns - Ana-Net's Alpha (job/docs/progetto_ana.md; the name+ * is provisional).+ *+ * A token's neurons, all the pairs of the pass together (its routed experts+ * and the shared one), are ranked by w |h|: the expert's weight (the+ * router's, or the shared expert's gate) times the neuron's activation,+ * what the neuron gives the output. The first neuron_frac[0] of them read+ * the three planes of their row of down, the next neuron_frac[1] two, the+ * next neuron_frac[2] the base alone, the rest nothing. The shared expert,+ * resident and by rows, is ranked with the others but computed whole.+ * JANAS_NEURON_LEVELS=f6,f4,f2 sets the fractions; without it every neuron+ * reads all three planes. The planes the cache holds (JANAS_EXPERT_BITS)+ * bound every level.+ */+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "common/pool.h"+#include "model_impl.h"+#include "quant.h"++/* Neurons are summed in chunks of JANAS_PN_CHUNK, each in integers from+ zero, the chunks then added in order: the same sums, bit for bit, whether+ a token comes alone (a chunk a thread) or with others (a block of outputs+ a thread). */+#define NEURON_CHUNK JANAS_PN_CHUNK++int janas_m_neurons_init(struct janas_llm_model *m, size_t pairs)+{+ m->neuron_down = 0;+ for (uint32_t l = 0; l < m->j.h.n_layer; l++)+ if (m->j.layers[l].m[JANAS_JNS_DOWN].type == JANAS_Q6_K_PN)+ m->neuron_down = 1;+ if (!m->neuron_down)+ return 0;+ /* a token alone: k experts' chunks of neurons, each its sum of the+ outputs; and which pair rows need no h in eight bits */+ for (uint32_t l = 0; l < m->j.h.n_layer; l++) {+ const struct janas_jns_matrix *d = &m->j.layers[l].m[JANAS_JNS_DOWN];+ size_t len = (size_t)m->k *+ ((d->rows + NEURON_CHUNK - 1) / NEURON_CHUNK) * d->cols;+ if (d->type == JANAS_Q6_K_PN && len > m->npart_len)+ m->npart_len = len;+ }+ m->npart = malloc(m->npart_len * sizeof(float));+ m->nskipq = calloc(pairs, 1);+ if (!m->npart || !m->nskipq)+ return -1;+ const char *e = getenv("JANAS_NEURON_LEVELS");+ float *f = m->neuron_frac;+ m->neuron_rank = e && sscanf(e, "%f,%f,%f", &f[0], &f[1], &f[2]) == 3 &&+ f[0] >= 0 && f[1] >= 0 && f[2] >= 0 &&+ f[0] + f[1] + f[2] <= 1.0001f && f[0] + f[1] + f[2] > 0.0f;+ if (e && !m->neuron_rank)+ fprintf(stderr,+ "JANAS_NEURON_LEVELS=%s: three fractions, f6,f4,f2, "+ "summing to at most 1; every neuron whole\n",+ e);+ if (!m->neuron_rank)+ return 0;+ m->nlevel = malloc(pairs * m->ff_buf);+ m->nscore = malloc(pairs * m->ff_buf * sizeof(float));+ m->ntok_first = malloc((m->blk + 1) * sizeof(uint32_t));+ m->ntok_fill = malloc(m->blk * sizeof(uint32_t));+ m->ntok_list = malloc(pairs * sizeof(uint32_t));+ if (!m->nlevel || !m->nscore || !m->ntok_first || !m->ntok_fill ||+ !m->ntok_list)+ return -1;+ fprintf(stderr,+ "neurons: down at 6, 4, 2 bits for %.0f%%, %.0f%%, %.0f%% of a "+ "token's neurons, the rest off\n",+ 100.0 * f[0], 100.0 * f[1], 100.0 * f[2]);+ return 0;+}++void janas_m_neurons_free(struct janas_llm_model *m)+{+ free(m->npart);+ free(m->nskipq);+ m->npart = NULL;+ m->nskipq = NULL;+ m->npart_len = 0;+ free(m->nlevel);+ free(m->nscore);+ free(m->ntok_first);+ free(m->ntok_fill);+ free(m->ntok_list);+ m->nlevel = NULL;+ m->nscore = NULL;+ m->ntok_first = m->ntok_fill = m->ntok_list = NULL;+}++/* Rearranges a[0 .. n) so that its k largest come first (1 <= k <= n) and+ returns the least of them: Hoare's selection. */+static float top_k(float *a, long n, long k)+{+ long lo = 0, hi = n - 1, want = k - 1;+ while (lo < hi) {+ float p = a[lo + (hi - lo) / 2];+ long i = lo, j = hi;+ do {+ while (a[i] > p)+ i++;+ while (a[j] < p)+ j--;+ if (i <= j) {+ float t = a[i];+ a[i++] = a[j];+ a[j--] = t;+ }+ } while (i <= j);+ if (want <= j)+ hi = j;+ else if (want >= i)+ lo = i;+ else+ return a[want];+ }+ return a[want];+}++struct level_job {+ struct janas_llm_model *m;+};++/* Token t's pair rows, ntok_list[ntok_first[t] .. [t + 1]): their neurons'+ scores gathered in the token's share of nscore, the thresholds of the+ three levels selected among them, the levels set. */+static void level_token(struct janas_llm_model *m, uint32_t t)+{+ uint32_t stride = m->ff_buf, a = m->ntok_first[t], b = m->ntok_first[t + 1];+ float *s = m->nscore + (size_t)a * stride;+ long n = 0;+ for (uint32_t i = a; i < b; i++) {+ size_t g = m->ntok_list[i];+ float w = fabsf(m->pair_w[m->order[g]]);+ const float *h = m->h + g * stride;+ for (uint32_t j = 0; j < m->hlen[g]; j++)+ s[n++] = w * fabsf(h[j]);+ }+ if (!n)+ return;+ /* the thresholds from one score in step, some 512 of them, where a+ token has more than 1024 neurons: the selection runs on a tenth of+ them or less, and the quotas hold to a couple of hundredths */+ long step = n > 1024 ? n / 512 : 1;+ if (step > 1) {+ long ns = 0;+ for (long i = 0; i < n; i += step)+ s[ns++] = s[i];+ n = ns;+ }+ /* from the top: the k-th largest score of each level's end, each search+ among the ones the last left first */+ long k[3];+ float th[3];+ float c = 0.0f;+ for (int q = 0; q < 3; q++) {+ c += m->neuron_frac[q];+ k[q] = (long)(c * (float)n + 0.5f);+ if (k[q] > n)+ k[q] = n;+ }+ for (int q = 2; q >= 0; q--) {+ long kq = k[q], within = q == 2 ? n : k[q + 1];+ th[q] = kq > 0 ? top_k(s, within, kq) : INFINITY;+ }+ int top = m->exp_level;+ for (uint32_t i = a; i < b; i++) {+ size_t g = m->ntok_list[i];+ float w = fabsf(m->pair_w[m->order[g]]);+ const float *h = m->h + g * stride;+ uint8_t *lv = m->nlevel + g * stride;+ for (uint32_t j = 0; j < m->hlen[g]; j++) {+ float v = w * fabsf(h[j]);+ int l = v <= 0.0f ? 0+ : v >= th[0] ? 3+ : v >= th[1] ? 2+ : v >= th[2] ? 1+ : 0;+ lv[j] = (uint8_t)(l < top ? l : top);+ }+ }+}++static void level_worker(void *arg, int tid, int n_threads)+{+ struct level_job *L = arg;+ for (uint32_t t = (uint32_t)tid; t < L->m->blk; t += (uint32_t)n_threads)+ if (L->m->ntok_first[t + 1] > L->m->ntok_first[t])+ level_token(L->m, t);+}++void janas_m_neuron_levels(struct janas_llm_model *m, uint32_t ng)+{+ uint32_t B = m->blk, *first = m->ntok_first, *fill = m->ntok_fill;+ memset(first, 0, (B + 1) * sizeof(uint32_t));+ for (uint32_t i = 0; i < ng; i++)+ first[m->pair_tok[m->order[m->glist[i]]] + 1]++;+ for (uint32_t t = 0; t < B; t++)+ first[t + 1] += first[t];+ memcpy(fill, first, B * sizeof(uint32_t));+ for (uint32_t i = 0; i < ng; i++) {+ uint32_t g = m->glist[i];+ m->ntok_list[fill[m->pair_tok[m->order[g]]]++] = g;+ }+ struct level_job L = {m};+ if (first[1] == ng) /* a single token: no threads to wake */+ level_token(m, 0);+ else+ janas_pool_run(m->compute, level_worker, &L);+}++/* Neurons [j0, j1) of pair row g, those it reads (a level above 0, h not+ zero) gathered by level, highest first - so that the kernel's branches+ follow one another - and added to y in integers (janas_q6kpn_chunk),+ nbk blocks of 256 outputs from block ob on. */+static void chunk_rows(const struct janas_llm_model *m,+ const struct janas_neuron_run *r, uint32_t g,+ uint32_t j0, uint32_t j1, uint32_t ob, uint32_t nbk,+ float *y)+{+ uint32_t stride = m->ff_buf, n = 0;+ const float *h = m->h + (size_t)g * stride;+ const uint8_t *lv = m->neuron_rank ? m->nlevel + (size_t)g * stride : NULL;+ uint32_t js[JANAS_PN_CHUNK];+ uint8_t ls[JANAS_PN_CHUNK];+ float hs[JANAS_PN_CHUNK];+ for (int l = 3; l >= 1; l--)+ for (uint32_t j = j0; j < j1; j++)+ if ((lv ? lv[j] : m->exp_level) == l && h[j] != 0.0f) {+ js[n] = j;+ ls[n] = (uint8_t)l;+ hs[n++] = h[j];+ }+ for (uint32_t k = 0; n && k < nbk; k++)+ janas_q6kpn_chunk(r->base, r->p1, r->p0, r->rows, js, ls, hs, n, ob + k,+ y + (size_t)k * JANAS_QK);+}++/* A token alone: an item a run and a chunk of its neurons, each neuron's+ row read whole - its planes contiguous - into the chunk's own sum; then+ an item a run and a block of outputs, the chunks' sums added in order,+ times the channels' scales. */+struct alone_job {+ struct janas_llm_model *m;+ const struct janas_neuron_run *runs;+ uint32_t n_runs, chunks;+};++static void tok_worker(void *arg, int tid, int n_threads)+{+ struct alone_job *J = arg;+ for (uint32_t i = (uint32_t)tid; i < J->n_runs * J->chunks;+ i += (uint32_t)n_threads) {+ const struct janas_neuron_run *r = &J->runs[i / J->chunks];+ uint32_t j0 = i % J->chunks * NEURON_CHUNK;+ uint32_t j1 = j0 + NEURON_CHUNK < r->rows ? j0 + NEURON_CHUNK : r->rows;+ float *y = J->m->npart + (size_t)i * r->cols;+ memset(y, 0, r->cols * sizeof(float));+ chunk_rows(J->m, r, r->a, j0, j1, 0, r->cols / JANAS_QK, y);+ }+}++static void sum_worker(void *arg, int tid, int n_threads)+{+ struct alone_job *J = arg;+ struct janas_llm_model *m = J->m;+ uint32_t nb = J->runs[0].cols / JANAS_QK;+ for (uint32_t i = (uint32_t)tid; i < J->n_runs * nb;+ i += (uint32_t)n_threads) {+ uint32_t ri = i / nb, ob = i % nb;+ const struct janas_neuron_run *r = &J->runs[ri];+ float *y = m->dout + (size_t)r->a * m->d_model + (size_t)ob * JANAS_QK;+ memset(y, 0, JANAS_QK * sizeof(float));+ for (uint32_t c = 0; c < J->chunks; c++) {+ const float *p = m->npart + ((size_t)ri * J->chunks + c) * r->cols ++ (size_t)ob * JANAS_QK;+ for (int v = 0; v < JANAS_QK; v++)+ y[v] += p[v];+ }+ const float *sc = r->scale + (size_t)ob * JANAS_QK;+ for (int v = 0; v < JANAS_QK; v++)+ y[v] *= sc[v];+ }+}++/* Tokens together: an item a run and a block of outputs, each pair's+ chunks summed apart and added in order, as for a token alone. */+struct down_job {+ struct janas_llm_model *m;+ const struct janas_neuron_run *runs;+ uint32_t n_runs, nb;+};++static void down_worker(void *arg, int tid, int n_threads)+{+ struct down_job *J = arg;+ struct janas_llm_model *m = J->m;+ for (uint32_t i = (uint32_t)tid; i < J->n_runs * J->nb;+ i += (uint32_t)n_threads) {+ const struct janas_neuron_run *r = &J->runs[i / J->nb];+ uint32_t ob = i % J->nb;+ const float *sc = r->scale + (size_t)ob * JANAS_QK;+ for (uint32_t g = r->a; g < r->b; g++) {+ float *y = m->dout + (size_t)g * m->d_model + (size_t)ob * JANAS_QK;+ float part[JANAS_QK];+ memset(y, 0, JANAS_QK * sizeof(float));+ for (uint32_t j0 = 0; j0 < r->rows; j0 += NEURON_CHUNK) {+ uint32_t j1 =+ j0 + NEURON_CHUNK < r->rows ? j0 + NEURON_CHUNK : r->rows;+ memset(part, 0, sizeof(part));+ chunk_rows(m, r, g, j0, j1, ob, 1, part);+ for (int v = 0; v < JANAS_QK; v++)+ y[v] += part[v];+ }+ for (int v = 0; v < JANAS_QK; v++)+ y[v] *= sc[v];+ }+ }+}++void janas_m_neuron_down(struct janas_llm_model *m,+ const struct janas_neuron_run *runs, uint32_t n)+{+ if (!n)+ return;+ uint32_t chunks = (runs[0].rows + NEURON_CHUNK - 1) / NEURON_CHUNK;+ int alone = (size_t)n * chunks * runs[0].cols <= m->npart_len;+ for (uint32_t r = 0; alone && r < n; r++)+ alone = runs[r].b - runs[r].a == 1;+ if (alone) {+ struct alone_job J = {m, runs, n, chunks};+ janas_pool_run(m->compute, tok_worker, &J);+ janas_pool_run(m->compute, sum_worker, &J);+ return;+ }+ struct down_job J = {m, runs, n, runs[0].cols / JANAS_QK};+ janas_pool_run(m->compute, down_worker, &J);+}diff --git a/src/llm/model_npu.c b/src/llm/model_npu.cnew file mode 100644index 0000000..ad17564--- /dev/null+++ b/src/llm/model_npu.c@@ -0,0 +1,1818 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * model_npu.c - the products of a block on the NPU (common/npu.h): looked+ * for when a model opens, JANAS_NPU=0 to leave it alone; the tuner gives it+ * the blocks where it measures faster.+ *+ * Which, for any model: a product over JANAS_NPU_MIN_N vectors and more+ * (default 64) whose weights stay where they are - in the resident region+ * (attention, recurrent layers, shared experts, the output head), or in the+ * experts' arena once it holds every expert and nothing changes there (a+ * dense model's feed-forwards) - in a type the engine dequantizes, while+ * the copies for the NPU fit JANAS_NPU_MAX_MB (default 4096). The routed+ * experts of a mixture whose experts do not all fit, a few tokens each,+ * stay on the CPU, which computes them while the NPU works. A matrix is+ * compiled the first time a block uses it (INT8, a scale a row, from its+ * rows dequantized), for blocks of the model's largest;+ * JANAS_NPU_CACHE=<dir> keeps the compiled matrices there for the next+ * load. Only in the passes whose tuner candidate has the NPU (npu_use):+ * the tuner and janas-bench weigh it against the CPU and the GPU.+ *+ * x reaches the NPU as the CPU's products see it (its Q8_K blocks expanded+ * to floats); the NPU computes in FP16, so the results are close to the+ * CPU's, not the same bits.+ */+#include <math.h>+#include <stdatomic.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>++#include "common/npu.h"+#include "common/npu_ir.h"+#include "expert_cache.h"+#include "gpu.h"+#include "model_impl.h"+#include "quant.h"++/* the inputs of a layer's products, for INT8 activations: the attention's+ output (wo), the FFN's norm (gate and up), the FFN's intermediate+ (down), a layer's norm before the attention (q, k, v) */+enum { SITE_ATT, SITE_FFN, SITE_MID, SITE_QKV, N_SITES };++#define NPU_SLOTS 4096 /* matrices: an open-addressed table on w */+#define NPU_XBUFS 16 /* inputs, one per distinct width */++struct npu_entry {+ const void *w; /* NULL: free slot */+ const void *plane[2]; /* Q6_K_P: the planes it was compiled with */+ struct janas_npu_mm *mm;+ float *y;+ size_t elems; /* rows x cols, against the budget */+ int bad; /* could not be compiled: CPU */+ int in_arena; /* from the experts' arena: stale when it changes */+};++struct janas_m_npu {+ struct janas_npu *u;+ int block, min_n;+ size_t budget, used; /* bytes of INT8 copies allowed, made */+ /* the experts' arena as seen when this pass began, the cache idle+ (janas_expert_cache_resident says no between its begin and finish,+ where the feed-forwards' products are): NULL if it was not whole or+ not idle; its loads then, and those the arena's matrices were+ compiled at */+ const uint8_t *arena;+ uint64_t arena_bytes, arena_loads, compiled_loads;+ struct npu_entry e[NPU_SLOTS];+ struct {+ size_t cols;+ float *x;+ const struct janas_block_q8k *src; /* what x holds now */+ size_t n_vec;+ } xb[NPU_XBUFS];+ int nx;+ double compile_s;+ uint64_t runs, cpu_fallbacks;+ /* products left to the CPU, by reason: too few vectors, type or+ layout, weights that may change */+ uint64_t no_n, no_type, no_stable;+ /* seconds: inputs expanded, the CPU's share of the groups, waiting for+ the NPU after it, outputs copied (JANAS_NPU_STATS) */+ double t_expand, t_cpu, t_wait, t_copy;+ /* by shape (JANAS_NPU_STATS=2): runs and their wait, and the products+ refused with that shape, by reason (0 vectors, 1 type or layout,+ 2 weights that may change) */+ struct {+ size_t rows, cols;+ int type;+ uint64_t runs, refused[3];+ double wait;+ } sh[32];+ int nsh;+ /* the products' outputs, shared by the matrices of as many rows that+ are never in flight together: by rows and the order among those of+ the same rows in a group (q's, k's and v's, k and v alike); a+ buffer a matrix took 2.3 GB on Qwen3-4B */+ struct {+ size_t rows;+ int ord;+ float *y;+ } yb[64];+ int ny;+ /* the feed-forwards in one run (janas_m_npu_ffn_begin): their input+ and output by width, one in flight */+ struct {+ size_t d;+ float *x, *y;+ } fb[4];+ int nf;+ uint64_t ffn_runs, ffn_refused, y_clash;+ double t_ffn_wait;+ /* seconds spent making the NPU's graphs - the weights dequantized and+ requantized, the graphs written, compiled and run once: kept out of+ the tuner's costs and janas-bench's rates (the first row with the+ NPU measured Qwen3-4B's prompt at 54 tokens/s for 330 with only the+ compilation taken out, 20 Oct 2026) */+ double setup_s;+ /* the preparation as another thread watches it (janas_llm_npu_preparing):+ on from the first graph a pass makes to the pass's end, or through a+ making of the whole layers' graphs; the graphs (or matrices) made of+ those to make (0: not known ahead, the products made as the block+ meets them); when it began; and the microseconds of the session's+ preparations before it */+ atomic_int prep_on, prep_done, prep_total;+ atomic_llong prep_t0_us, prep_us;+ /* whole layers (janas_m_npu_layers): a graph for the first layer's+ norm and input products, then one a layer - its attention's (or+ recurrence's) output in, wo (ssm_out), the residual, the FFN's norm+ and the FFN, the residual, and the next layer's norm and input+ products - the residual between xs[0] and xs[1] by turns; the first+ nl layers, as many as the NPU holds; -1 not possible here, 0 not yet+ made, 1 made */+ int lmode;+ uint32_t nl;+ /* the first layers alone when fewer than nine in ten fit+ (JANAS_NPU_LAYERS=2): slower than the products on all of them where+ measured - Qwen3.5-9B, 17 layers of 32, 55.4 tokens/s against 58.9;+ Gemma 4 E4B holds 41 of 42 (21 Oct 2026) */+ int partial;+ struct janas_npu_mm *lpre, **lg;+ /* the block in two halves of hb rows, each its buffers (the graphs'+ two bindings): while the NPU runs a layer on one, the CPU does the+ attention or the recurrence of the other. An attention layer's+ inputs in q (with the output gates where there are, as m->big holds+ them), k, v; a recurrent one's in big (q|k|v and z, as m->big) and+ hn (the norm, for the betas and alphas the CPU makes) */+ int hb;+ float *xs[2][2], *att[2], *q[2], *k[2], *v[2], *big[2], *hn[2];+ float *ple[2]; /* Gemma 4: a layer's per-layer inputs, ple_dim a row */+ /* INT8 activations (JANAS_NPU_A8=1): a8 0 off, 1 calibrating - the+ blocks the NPU would take run on the CPU's path, which gives each+ product input's channel maxima into amax (janas_m_npu_calib; graphs+ to give them did not fit the NPU's memory beside the others) - 2+ the INT8 graphs; a8_left the blocks still to calibrate on, in_calib+ this pass is one */+ int a8, a8_left, in_calib;+ int a8_sites; /* the sites in INT8 (JANAS_NPU_A8_SITES, bit = site) */+ float **amax;+ uint64_t lmode_loads; /* the arena's loads the graphs were made at */+ uint64_t layer_passes;+ double t_layer_wait, t_layer_attn, layers_compile_s;+};++static void see_arena(struct janas_llm_model *m, struct janas_m_npu *n);+static void layers_free(struct janas_m_npu *n, uint32_t n_layer);++static long long now_us(void)+{+ return (long long)(now() * 1e6);+}++/* a preparation begins, of total graphs (0: not known ahead), or goes on */+static void prep_begin(struct janas_m_npu *n, int total)+{+ if (atomic_load(&n->prep_on))+ return;+ atomic_store(&n->prep_done, 0);+ atomic_store(&n->prep_total, total);+ atomic_store(&n->prep_t0_us, now_us());+ atomic_store(&n->prep_on, 1);+}++static void prep_end(struct janas_m_npu *n)+{+ if (atomic_exchange(&n->prep_on, 0))+ atomic_fetch_add(&n->prep_us, now_us() - atomic_load(&n->prep_t0_us));+}++void janas_m_npu_pass_end(struct janas_llm_model *m)+{+ if (m->npu)+ prep_end(m->npu);+}++int janas_llm_model_npu_preparing(const struct janas_llm_model *m,+ int32_t *done, int32_t *total,+ double *seconds)+{+ struct janas_m_npu *n = m->npu;+ int on = n ? atomic_load(&n->prep_on) : 0;+ if (done)+ *done = n ? atomic_load(&n->prep_done) : 0;+ if (total)+ *total = n ? atomic_load(&n->prep_total) : 0;+ if (seconds)+ *seconds = !n ? 0+ : on ? (double)(now_us() - atomic_load(&n->prep_t0_us)) / 1e6+ : (double)atomic_load(&n->prep_us) / 1e6;+ return on;+}++void janas_m_npu_open(struct janas_llm_model *m)+{+ const char *e = getenv("JANAS_NPU");+ if (e && atoi(e) <= 0) {+ snprintf(m->npu_why, sizeof m->npu_why, "turned off by JANAS_NPU=0");+ return;+ }+ char err[256] = "no memory";+ struct janas_m_npu *n = calloc(1, sizeof(*n));+ if (!n || !(n->u = janas_npu_create(err, sizeof err))) {+ snprintf(m->npu_why, sizeof m->npu_why, "%.150s", err);+ if (e) /* asked for: say why not */+ fprintf(stderr, "janas: NPU not used: %s\n", err);+ free(n);+ return;+ }+ const char *c = getenv("JANAS_NPU_CACHE");+ if (c && *c && janas_npu_set_cache(n->u, c))+ fprintf(stderr, "janas: NPU cache %s not usable\n", c);+ const char *mn = getenv("JANAS_NPU_MIN_N");+ n->min_n = mn && atoi(mn) > 0 ? atoi(mn) : 64;+ n->block = (int)janas_llm_model_max_block(m);+ const char *mb = getenv("JANAS_NPU_MAX_MB");+ n->budget = (size_t)(mb && atol(mb) > 0 ? atol(mb) : 4096) << 20;+ m->npu = n;+ m->npu_why[0] = 0;+ if (getenv("JANAS_NPU_STATS"))+ fprintf(stderr,+ "janas: NPU %s, blocks of %d, products of %d tokens and "+ "more\n",+ janas_npu_name(n->u), n->block, n->min_n);+}++int janas_m_npu_takes(const struct janas_llm_model *m, uint32_t n)+{+ return m->npu && m->npu_use && (int)n >= m->npu->min_n;+}++void janas_m_npu_awake(struct janas_llm_model *m, uint32_t n)+{+ if (!m->npu)+ return;+ int takes = janas_m_npu_takes(m, n);+ janas_npu_keep_awake(m->npu->u, takes);+ if (takes)+ see_arena(m, m->npu);+}++double janas_llm_model_npu_compile_seconds(const struct janas_llm_model *m)+{+ return m->npu ? m->npu->setup_s : 0;+}++const char *janas_llm_model_npu_why(const struct janas_llm_model *m)+{+ return m->npu_why;+}++void janas_m_npu_close(struct janas_llm_model *m)+{+ struct janas_m_npu *n = m->npu;+ if (!n)+ return;+ int np, nc;+ double cs;+ janas_npu_stats(n->u, &np, &nc, &cs);+ if (getenv("JANAS_NPU_STATS"))+ fprintf(stderr,+ "janas: NPU %d matrices (%d from the cache, %.1f s), %llu "+ "products, %llu to the CPU; left to the CPU: %llu too few "+ "vectors, %llu type or layout, %llu weights that may "+ "change\n",+ np, nc, cs, (unsigned long long)n->runs,+ (unsigned long long)n->cpu_fallbacks,+ (unsigned long long)n->no_n, (unsigned long long)n->no_type,+ (unsigned long long)n->no_stable);+ if (getenv("JANAS_NPU_STATS"))+ fprintf(stderr,+ "janas: NPU time: inputs expanded %.2f s, the CPU's share of "+ "the groups %.2f s, waiting for the NPU %.2f s, outputs "+ "copied %.2f s\n",+ n->t_expand, n->t_cpu, n->t_wait, n->t_copy);+ if (getenv("JANAS_NPU_STATS"))+ fprintf(stderr,+ "janas: NPU feed-forwards in one run: %llu (%.2f s waited), "+ "%llu refused; outputs in use twice: %llu\n",+ (unsigned long long)n->ffn_runs, n->t_ffn_wait,+ (unsigned long long)n->ffn_refused,+ (unsigned long long)n->y_clash);+ const char *st = getenv("JANAS_NPU_STATS");+ for (int i = 0; st && atoi(st) >= 2 && i < n->nsh; i++)+ fprintf(stderr,+ "janas: NPU %5zu x %5zu type %3d: %6llu runs, %.2f ms each "+ "waited; refused %llu (vectors) %llu (type, layout) %llu "+ "(weights)\n",+ n->sh[i].rows, n->sh[i].cols, n->sh[i].type,+ (unsigned long long)n->sh[i].runs,+ n->sh[i].runs ? n->sh[i].wait / n->sh[i].runs * 1e3 : 0,+ (unsigned long long)n->sh[i].refused[0],+ (unsigned long long)n->sh[i].refused[1],+ (unsigned long long)n->sh[i].refused[2]);+ if (getenv("JANAS_NPU_STATS") && n->layer_passes)+ fprintf(stderr,+ "janas: NPU whole layers: %u of %u, %llu blocks, %.2f s "+ "waited for the graphs, %.2f s of attention or recurrence on "+ "the CPU, graphs made in %.1f s\n",+ n->nl, m->n_layer, (unsigned long long)n->layer_passes,+ n->t_layer_wait, n->t_layer_attn, n->layers_compile_s);+ layers_free(n, m->n_layer);+ for (size_t i = 0; n->amax && i < (size_t)m->n_layer * N_SITES; i++)+ free(n->amax[i]);+ free(n->amax);+ janas_npu_destroy(n->u);+ free(n);+ m->npu = NULL;+}++/* the types janas_dequantize unpacks (it aborts on any other), and the+ down matrix in planes: every quantization of the catalog's files - Q3_K+ of the 30B in three bits, Q5_1 and Q8_0 of Gemma 4 26B-A4B among them */+static int dequant_type(int type)+{+ switch (type) {+ case JANAS_Q4_K:+ case JANAS_Q5_K:+ case JANAS_Q6_K:+ case JANAS_Q8_0:+ case JANAS_Q3_K:+ case JANAS_Q4_0:+ case JANAS_Q4_1:+ case JANAS_Q5_1:+ case JANAS_IQ4_NL:+ case JANAS_IQ4_XS:+ case JANAS_IQ3_S:+ case JANAS_MXFP4:+ return 1;+ default:+ return 0;+ }+}++static int npu_type(int type)+{+ return dequant_type(type) || type == JANAS_Q6_K_P;+}++static float *xbuf(struct janas_m_npu *n, size_t cols)+{+ for (int i = 0; i < n->nx; i++)+ if (n->xb[i].cols == cols)+ return n->xb[i].x;+ if (n->nx == NPU_XBUFS)+ return NULL;+ float *x = janas_npu_alloc(n->u, sizeof(float) * (size_t)n->block * cols);+ if (!x)+ return NULL;+ memset(x, 0, sizeof(float) * (size_t)n->block * cols);+ n->xb[n->nx].cols = cols, n->xb[n->nx].x = x, n->xb[n->nx].src = NULL;+ n->nx++;+ return x;+}++/* the matrix's entry, compiled on first use; NULL if it stays on the CPU */+/* a matrix's NPU copy given up (the arena changed, or its planes did): the+ slot stays its own, compiled again at its next use */+static void drop(struct janas_m_npu *n, struct npu_entry *e)+{+ janas_npu_mm_destroy(e->mm);+ if (e->mm)+ n->used -= e->elems;+ e->mm = NULL, e->y = NULL, e->bad = 0;+}++/* JANAS_NPU_CHECK=1: each result of the NPU scanned - not finite, and the+ largest magnitude - the first bad one said, with its inputs' largest */+static int checking(void)+{+ static int c = -1;+ if (c < 0) {+ const char *e = getenv("JANAS_NPU_CHECK");+ c = e && atoi(e) > 0;+ }+ return c;+}++static void check(const char *what, size_t rows, size_t cols, const float *x,+ size_t nx, const float *y, size_t ny)+{+ static int said;+ float xm = 0, ym = 0;+ size_t bad = 0;+ for (size_t i = 0; i < nx; i++)+ xm = fabsf(x[i]) > xm ? fabsf(x[i]) : xm;+ for (size_t i = 0; i < ny; i++) {+ if (!isfinite(y[i]))+ bad++;+ else if (fabsf(y[i]) > ym)+ ym = fabsf(y[i]);+ }+ if (bad && said++ < 8)+ fprintf(stderr,+ "janas: NPU %s %zu x %zu: %zu of %zu outputs not finite; "+ "largest input %g, largest finite output %g\n",+ what, rows, cols, bad, ny, xm, ym);+}++static float *ybuf(struct janas_m_npu *n, size_t rows, int ord)+{+ for (int i = 0; i < n->ny; i++)+ if (n->yb[i].rows == rows && n->yb[i].ord == ord)+ return n->yb[i].y;+ if (n->ny == 64)+ return NULL;+ float *y = janas_npu_alloc(n->u, sizeof(float) * (size_t)n->block * rows);+ if (y)+ n->yb[n->ny].rows = rows, n->yb[n->ny].ord = ord, n->yb[n->ny++].y = y;+ return y;+}++static struct npu_entry *entry(struct janas_m_npu *n,+ const struct janas_matvec_task *t, int arena,+ int ord)+{+ size_t h = ((uintptr_t)t->w >> 6) % NPU_SLOTS;+ for (size_t i = 0; i < NPU_SLOTS; i++, h = (h + 1) % NPU_SLOTS) {+ struct npu_entry *e = &n->e[h];+ if (e->w == t->w && e->mm &&+ (t->type != JANAS_Q6_K_P ||+ (e->plane[0] == t->plane[0] && e->plane[1] == t->plane[1])))+ return e;+ if (e->w == t->w && e->bad)+ return NULL;+ if (e->w && e->w != t->w)+ continue;+ if (e->w)+ drop(n, e); /* other planes, or given up: again */+ double t_setup = now();+ e->w = t->w, e->bad = 1, e->in_arena = arena;+ e->plane[0] = t->plane[0], e->plane[1] = t->plane[1];+ e->elems = t->rows * t->cols;+ if (n->used + t->rows * t->cols > n->budget)+ return NULL; /* stays on the CPU for good */+ prep_begin(n, 0);+ float *x = xbuf(n, t->cols);+ size_t rc = t->rows * t->cols;+ float *wf = x ? malloc(sizeof(float) * rc) : NULL;+ int8_t *q = wf ? malloc(rc) : NULL;+ uint16_t *s = q ? malloc(2 * t->rows) : NULL;+ e->y = s ? ybuf(n, t->rows, ord) : NULL;+ if (e->y) {+ if (t->type == JANAS_Q6_K_P) /* at the level in memory */+ janas_q6kp_dequantize(t->w, t->plane[0], t->plane[1], wf, rc);+ else+ janas_dequantize(t->type, t->w, wf, rc);+ janas_npu_quant_rows(wf, t->rows, t->cols, q, s);+ char err[256];+ e->mm = janas_npu_mm_create(n->u, n->block, (int)t->rows,+ (int)t->cols, JANAS_NPU_I8, q, s, x,+ e->y, err, sizeof err);+ if (!e->mm)+ fprintf(stderr, "janas: NPU: %zu x %zu on the CPU: %s\n",+ t->rows, t->cols, err);+ }+ free(wf), free(q), free(s);+ atomic_fetch_add(&n->prep_done, 1);+ e->bad = !e->mm;+ if (e->mm)+ n->used += t->rows * t->cols;+ if (e->bad)+ e->y = NULL;+ n->setup_s += now() - t_setup;+ return e->bad ? NULL : e;+ }+ return NULL;+}++/* weights that stay as they are: the resident region, or the experts'+ arena while it holds every expert (nothing more is loaded into it) */+/* 1: in the resident region, 2: in the arena as this pass found it whole,+ 0: weights that may change */+static int stable(const struct janas_llm_model *m, const struct janas_m_npu *n,+ const void *p)+{+ const uint8_t *w = p, *r = m->resident;+ if (!w)+ return 1; /* a plane not in memory: nothing to read */+ if (w >= r && w < r + m->j.h.resident_bytes)+ return 1;+ return n->arena && w >= n->arena && w < n->arena + n->arena_bytes ? 2 : 0;+}++/* at a pass's start, the cache idle: the arena whole or not, and the+ matrices compiled from it given up if it changed since */+static void see_arena(struct janas_llm_model *m, struct janas_m_npu *n)+{+ n->arena = m->cache ? janas_expert_cache_resident(m->cache, &n->arena_bytes,+ &n->arena_loads)+ : NULL;+ if (!n->arena || n->arena_loads == n->compiled_loads)+ return;+ for (size_t i = 0; i < NPU_SLOTS; i++)+ if (n->e[i].w && n->e[i].in_arena && n->e[i].mm)+ drop(n, &n->e[i]);+ n->compiled_loads = n->arena_loads;+}++static int shape(struct janas_m_npu *n, const struct janas_matvec_task *t)+{+ for (int i = 0; i < n->nsh; i++)+ if (n->sh[i].rows == t->rows && n->sh[i].cols == t->cols &&+ n->sh[i].type == t->type)+ return i;+ if (n->nsh == 32)+ return -1;+ n->sh[n->nsh].rows = t->rows, n->sh[n->nsh].cols = t->cols;+ n->sh[n->nsh].type = t->type;+ return n->nsh++;+}++static void refused(struct janas_m_npu *n, const struct janas_matvec_task *t,+ int why)+{+ int i = t->n_vec > 1 ? shape(n, t) : -1;+ if (i >= 0)+ n->sh[i].refused[why]++;+}++static int eligible(const struct janas_llm_model *m, struct janas_m_npu *n,+ const struct janas_matvec_task *t)+{+ size_t nb = t->cols / JANAS_QK;+ /* the output head stays on the CPU: a chat's prompt asks it for one+ token, and over many (an evaluation's every logit) its INT8 copy+ would add an error no chat has */+ if (m->output && t->w == data(m, m->output))+ return n->no_type++, 0;+ if (!t->w || (int)t->n_vec < n->min_n || (int)t->n_vec > n->block) {+ return refused(n, t, 0), n->no_n++, 0;+ }+ if (!npu_type(t->type) || t->cols % JANAS_QK ||+ (t->x_stride && t->x_stride != nb) ||+ (t->y_stride && t->y_stride != t->rows))+ return refused(n, t, 1), n->no_type++, 0;+ int st = stable(m, n, t->w);+ if (t->type == JANAS_Q6_K_P && st &&+ (stable(m, n, t->plane[0]) == 0 || stable(m, n, t->plane[1]) == 0))+ st = 0;+ if (!st)+ return refused(n, t, 2), n->no_stable++, 0;+ return st;+}++const char *janas_llm_model_npu_name(const struct janas_llm_model *m)+{+ return m->npu ? janas_npu_name(m->npu->u) : NULL;+}++/* the input as floats, once for the tasks that share it; -1 when the+ buffer of that width holds another input a product in flight reads */+static int expand(struct janas_m_npu *n, const struct janas_matvec_task *t)+{+ int i = 0;+ while (n->xb[i].cols != t->cols)+ i++;+ if (n->xb[i].src == t->x && n->xb[i].n_vec == t->n_vec)+ return 0;+ if (n->xb[i].src)+ return -1;+ size_t nb = t->cols / JANAS_QK;+ float *x = n->xb[i].x;+ for (size_t v = 0; v < t->n_vec; v++)+ for (size_t b = 0; b < nb; b++) {+ const struct janas_block_q8k *q = t->x + v * nb + b;+ float *o = x + v * t->cols + b * JANAS_QK;+ for (int k = 0; k < JANAS_QK; k++)+ o[k] = q->d * (float)q->qs[k];+ }+ n->xb[i].src = t->x, n->xb[i].n_vec = t->n_vec;+ return 0;+}++/* the pool's idle workers asleep while the CPU waits for the NPU (unless+ JANAS_NPU_SPIN=1): spinning at their highest clock they slowed it - a+ Qwen3-4B prompt 261 tokens/s spinning, 320 asleep (20 Oct 2026). The+ spin as it was is returned, for npu_loud. */+static int npu_quiet(struct janas_llm_model *m)+{+ static int keep = -1;+ if (keep < 0) {+ const char *e = getenv("JANAS_NPU_SPIN");+ keep = e && atoi(e) > 0;+ }+ int spin = janas_pool_get_spin(m->compute);+ if (!keep)+ janas_pool_set_spin(m->compute, 0);+ return spin;+}++static void npu_loud(struct janas_llm_model *m, int spin)+{+ janas_pool_set_spin(m->compute, spin);+}++void janas_m_products(struct janas_llm_model *m, struct janas_gpu *g,+ const struct janas_matvec_task *t, size_t nt)+{+ /* not beside the whole layers: their graphs hold the NPU's memory+ (the layers after those it holds stay here) */+ struct janas_m_npu *n =+ m->npu_use && m->npu && m->npu->lmode != 1 ? m->npu : NULL;+ if (!n) {+ janas_gpu_matvec_group(g, m->compute, t, nt);+ return;+ }+ enum { MAXT = 64 };+ struct janas_matvec_task cpu[MAXT];+ struct npu_entry *on[MAXT];+ const struct janas_matvec_task *ont[MAXT];+ size_t nc = 0, nn = 0;+ if (nt > MAXT) {+ janas_gpu_matvec_group(g, m->compute, t, nt);+ return;+ }+ for (int i = 0; i < n->nx; i++)+ n->xb[i].src = NULL; /* the engine rewrites its inputs between calls */+ for (size_t i = 0; i < nt; i++) {+ int st = eligible(m, n, &t[i]), ord = 0;+ for (size_t j = 0; st && j < nn; j++)+ ord += ont[j]->rows == t[i].rows;+ struct npu_entry *e = st ? entry(n, &t[i], st == 2, ord) : NULL;+ for (size_t j = 0; e && j < nn; j++)+ if (on[j]->y == e->y) { /* another order than when compiled */+ n->y_clash++;+ e = NULL;+ }+ double te = now();+ int ok = e && expand(n, &t[i]) == 0;+ n->t_expand += now() - te;+ if (ok) {+ if (janas_npu_mm_begin(e->mm) == 0) {+ on[nn] = e, ont[nn++] = &t[i];+ continue;+ }+ n->cpu_fallbacks++;+ }+ cpu[nc++] = t[i];+ }+ double t0 = now();+ if (nc)+ janas_gpu_matvec_group(g, m->compute, cpu, nc);+ double t1 = now();+ n->t_cpu += t1 - t0;+ int spin = nn ? npu_quiet(m) : 0; /* from here the CPU only waits */+ for (size_t i = 0; i < nn; i++) {+ const struct janas_matvec_task *k = ont[i];+ double tw = now();+ int failed = janas_npu_mm_finish(on[i]->mm) != 0;+ double tc = now();+ n->t_wait += tc - tw;+ int si = shape(n, k);+ if (si >= 0)+ n->sh[si].runs++, n->sh[si].wait += tc - tw;+ if (failed) {+ /* the NPU failed: this product on the CPU after all */+ n->cpu_fallbacks++;+ janas_gpu_matvec_group(g, m->compute, k, 1);+ continue;+ }+ if (checking()) {+ int xi = 0;+ while (n->xb[xi].cols != k->cols)+ xi++;+ check("product", k->rows, k->cols, n->xb[xi].x, k->n_vec * k->cols,+ on[i]->y, k->n_vec * k->rows);+ }+ size_t ys = k->y_stride ? k->y_stride : k->rows;+ for (size_t v = 0; v < k->n_vec; v++)+ memcpy(k->y + v * ys, on[i]->y + v * k->rows,+ sizeof(float) * k->rows);+ n->t_copy += now() - tc;+ n->runs++;+ }+ if (nn)+ npu_loud(m, spin);+}++/* ---- a feed-forward in one run ---- */++static int ffn_type(int type, int down)+{+ return dequant_type(type) || (down && type == JANAS_Q6_K_P);+}++static float *fbuf(struct janas_m_npu *n, size_t d, int out)+{+ for (int i = 0; i < n->nf; i++)+ if (n->fb[i].d == d)+ return out ? n->fb[i].y : n->fb[i].x;+ if (n->nf == 4)+ return NULL;+ float *x = janas_npu_alloc(n->u, sizeof(float) * (size_t)n->block * d),+ *y = janas_npu_alloc(n->u, sizeof(float) * (size_t)n->block * d);+ if (!x || !y)+ return NULL;+ memset(x, 0, sizeof(float) * (size_t)n->block * d);+ n->fb[n->nf].d = d, n->fb[n->nf].x = x, n->fb[n->nf++].y = y;+ return out ? y : x;+}++/* a matrix of the run as floats: Q6_K_P at the level of its planes */+static void deq(const struct janas_jns_matrix *mx, const uint8_t *w,+ const uint8_t *const plane[2], float *f)+{+ size_t n = (size_t)mx->rows * mx->cols;+ if (mx->type == JANAS_Q6_K_P)+ janas_q6kp_dequantize((const struct janas_block_q6kp *)w, plane[0],+ plane[1], f, n);+ else+ janas_dequantize((int)mx->type, w, f, n);+}++/* the feed-forward's entry, keyed by its gate's address plus one (no+ matrix of the products starts at an odd address), compiled on first+ use; NULL if it stays on the CPU */+static struct npu_entry *ffn_entry(struct janas_llm_model *m,+ struct janas_m_npu *n,+ const uint8_t *const w[3],+ const uint8_t *const plane[2],+ const struct janas_jns_matrix *mx, int arena)+{+ const void *key = w[0] + 1;+ size_t h = ((uintptr_t)w[0] >> 6) % NPU_SLOTS;+ for (size_t i = 0; i < NPU_SLOTS; i++, h = (h + 1) % NPU_SLOTS) {+ struct npu_entry *e = &n->e[h];+ if (e->w == key && e->mm && e->plane[0] == plane[0] &&+ e->plane[1] == plane[1])+ return e;+ if (e->w == key && e->bad)+ return NULL;+ if (e->w && e->w != key)+ continue;+ if (e->w)+ drop(n, e);+ double t_setup = now();+ size_t d = mx[0].cols, ff = mx[0].rows, nw = d * ff;+ e->w = key, e->bad = 1, e->in_arena = arena;+ e->plane[0] = plane[0], e->plane[1] = plane[1];+ e->elems = 3 * nw;+ if (n->used + e->elems > n->budget)+ return NULL;+ prep_begin(n, 0);+ float *x = fbuf(n, d, 0), *y = fbuf(n, d, 1);+ float *f = x && y ? malloc(sizeof(float) * nw) : NULL;+ int8_t *q[3] = {0};+ uint16_t *s[3] = {0};+ int ok = f != NULL;+ for (int k = 0; ok && k < 3; k++) {+ size_t rows = mx[k].rows, cols = mx[k].cols;+ q[k] = malloc(rows * cols), s[k] = malloc(2 * rows);+ ok = q[k] && s[k];+ if (ok) {+ deq(&mx[k], w[k], plane, f);+ if (checking()) { /* the weights as floats, finite? */+ size_t bad = 0;+ float mxw = 0;+ for (size_t i = 0; i < rows * cols; i++) {+ if (!isfinite(f[i]))+ bad++;+ else if (fabsf(f[i]) > mxw)+ mxw = fabsf(f[i]);+ }+ if (bad)+ fprintf(stderr,+ "janas: NPU feed-forward matrix %d (type %u, "+ "%zu x %zu): %zu weights not finite, largest "+ "%g\n",+ k, mx[k].type, rows, cols, bad, mxw);+ }+ janas_npu_quant_rows(f, rows, cols, q[k], s[k]);+ }+ }+ if (ok) {+ char err[256];+ e->mm = janas_npu_ffn_create(+ n->u, n->block, (int)d, (int)ff,+ m->a->gelu ? JANAS_NPU_GELU_TANH : JANAS_NPU_SILU, q[0], s[0],+ q[1], s[1], q[2], s[2], x, y, err, sizeof err);+ if (!e->mm)+ fprintf(stderr,+ "janas: NPU: feed-forward %zu x %zu on the "+ "CPU: %s\n",+ ff, d, err);+ }+ free(f);+ for (int k = 0; k < 3; k++)+ free(q[k]), free(s[k]);+ atomic_fetch_add(&n->prep_done, 1);+ e->bad = !e->mm;+ if (e->mm)+ n->used += e->elems;+ n->setup_s += now() - t_setup;+ return e->bad ? NULL : e;+ }+ return NULL;+}++int janas_m_npu_ffn_begin(struct janas_llm_model *m, const uint8_t *const w[3],+ const uint8_t *const plane[2],+ const struct janas_jns_matrix *mx,+ const struct janas_block_q8k *x, uint32_t n_vec,+ float *dout, struct janas_m_npu_ffn *job)+{+ struct janas_m_npu *n =+ m->npu_use && m->npu && m->npu->lmode != 1 ? m->npu : NULL;+ job->e = NULL;+ if (!n || (int)n_vec < n->min_n || (int)n_vec > n->block)+ return -1;+ /* the Ana-Net probes and the down by neuron read the intermediate */+ if (m->ana_mode || m->ana_tok || m->ana_agree || m->ana_coarse ||+ m->ana_coln || m->ana_level || m->ana_low || m->ana_frame ||+ m->ana_exp || m->nskipq || m->neuron_down)+ return -1;+ const struct janas_jns_matrix *g = &mx[0], *u = &mx[1], *d = &mx[2];+ if (!ffn_type((int)g->type, 0) || !ffn_type((int)u->type, 0) ||+ !ffn_type((int)d->type, 1) || g->rows != u->rows ||+ g->cols != u->cols || d->cols != g->rows || d->rows != g->cols ||+ g->cols % JANAS_QK || g->rows % JANAS_QK) {+ n->ffn_refused++;+ return -1;+ }+ /* the matrices where they are: each at its offset in its slot */+ const uint8_t *wm[3] = {w[0] + g->offset, w[1] + u->offset,+ w[2] + d->offset};+ int st = stable(m, n, wm[0]);+ if (st && (stable(m, n, wm[1]) != st || stable(m, n, wm[2]) != st ||+ (d->type == JANAS_Q6_K_P &&+ (!stable(m, n, plane[0]) || !stable(m, n, plane[1])))))+ st = 0;+ struct npu_entry *e = st ? ffn_entry(m, n, wm, plane, mx, st == 2) : NULL;+ if (!e) {+ n->ffn_refused++;+ return -1;+ }+ double te = now();+ size_t dm = g->cols, nb = dm / JANAS_QK;+ float *xf = fbuf(n, dm, 0);+ for (uint32_t v = 0; v < n_vec; v++)+ for (size_t b = 0; b < nb; b++) {+ const struct janas_block_q8k *q = x + v * nb + b;+ float *o = xf + v * dm + b * JANAS_QK;+ for (int k = 0; k < JANAS_QK; k++)+ o[k] = q->d * (float)q->qs[k];+ }+ n->t_expand += now() - te;+ if (janas_npu_mm_begin(e->mm))+ return -1;+ job->e = e, job->dout = dout, job->n_vec = n_vec, job->d = dm;+ return 0;+}++int janas_m_npu_ffn_finish(struct janas_llm_model *m,+ struct janas_m_npu_ffn *job)+{+ struct janas_m_npu *n = m->npu;+ if (!job->e)+ return -1;+ double t0 = now();+ int spin = npu_quiet(m);+ int r = janas_npu_mm_finish(job->e->mm);+ npu_loud(m, spin);+ double t1 = now();+ n->t_ffn_wait += t1 - t0;+ if (r == 0) {+ if (checking())+ check("feed-forward", job->d, job->d, fbuf(n, job->d, 0),+ job->n_vec * job->d, fbuf(n, job->d, 1), job->n_vec * job->d);+ memcpy(job->dout, fbuf(n, job->d, 1),+ sizeof(float) * job->n_vec * job->d);+ n->ffn_runs++;+ }+ n->t_copy += now() - t1;+ job->e = NULL;+ return r;+}++/* ---- whole layers ---- */++/* a matrix of the model as floats (malloc'd), Q6_K_P at the level of its+ planes */+static float *deq_matrix(int type, const void *w, const uint8_t *p1,+ const uint8_t *p0, size_t rows, size_t cols)+{+ float *f = malloc(sizeof(float) * rows * cols);+ if (f && type == JANAS_Q6_K_P)+ janas_q6kp_dequantize(w, p1, p0, f, rows * cols);+ else if (f)+ janas_dequantize(type, w, f, rows * cols);+ return f;+}++static float *deq_tensor(const struct janas_llm_model *m,+ const struct janas_jns_tensor *t, size_t *rows,+ size_t *cols)+{+ *cols = t->dims[0], *rows = t->dims[1];+ if (t->type == 0) { /* F32 (Gemma 4's per-layer branch): as it is */+ float *f = malloc(sizeof(float) * *rows * *cols);+ if (f)+ memcpy(f, f32(m, t), sizeof(float) * *rows * *cols);+ return f;+ }+ if (!npu_type((int)t->type) || t->type == JANAS_Q6_K_P)+ return NULL;+ return deq_matrix((int)t->type, data(m, t), NULL, NULL, *rows, *cols);+}++/* dense layer l's FFN from the arena (its expert 0): gate, up, down */+static int deq_ffn(struct janas_llm_model *m, uint32_t l, float *f[3],+ size_t rows[3], size_t cols[3])+{+ uint32_t e0 = 0;+ const uint8_t *slot = NULL;+ const struct janas_jns_layer *jl = &m->j.layers[l];+ f[0] = f[1] = f[2] = NULL;+ if (!m->cache || janas_expert_cache_fetch(m->cache, l, &e0, 1, &slot))+ return -1;+ const uint8_t *pl[2] = {NULL, NULL};+ for (int q = 0; q < m->exp_level - 1; q++)+ if (jl->plane[q].type)+ pl[q] = slot + jl->plane[q].offset;+ for (int k = 0; k < 3; k++) {+ const struct janas_jns_matrix *mx = &jl->m[k];+ rows[k] = mx->rows, cols[k] = mx->cols;+ f[k] = ffn_type((int)mx->type, k == 2)+ ? deq_matrix((int)mx->type, slot + mx->offset, pl[0], pl[1],+ mx->rows, mx->cols)+ : NULL;+ if (!f[k])+ return -1;+ }+ return 0;+}++/* floats into the graph (freed): columns times cs, rows times rs (either+ NULL), then INT8 with a scale a row */+static int weights_f(struct npu_ir *ir, const char *name, float *f, size_t rows,+ size_t cols, const float *cs, const float *rs, int *ok)+{+ if (!f) {+ *ok = 0;+ return -1;+ }+ for (size_t r = 0; (cs || rs) && r < rows; r++)+ for (size_t c = 0; c < cols; c++)+ f[r * cols + c] *= (cs ? cs[c] : 1.0f) * (rs ? rs[r] : 1.0f);+ int8_t *q = malloc(rows * cols);+ uint16_t *s = q ? malloc(2 * rows) : NULL;+ int l = -1;+ if (s) {+ janas_npu_quant_rows(f, rows, cols, q, s);+ l = npu_ir_weights_i8(ir, name, q, s, (int)rows, (int)cols);+ } else+ *ok = 0;+ free(q), free(s), free(f);+ return l;+}++static void col_max(const float *f, size_t rows, size_t cols, float *w)+{+ for (size_t r = 0; f && r < rows; r++)+ for (size_t c = 0; c < cols; c++) {+ float a = fabsf(f[r * cols + c]);+ w[c] = a > w[c] ? a : w[c];+ }+}++/* SmoothQuant (alpha 1/2): s = sqrt(max |x| / max |w|) a channel, x / s+ and w s; the range of x / s returned */+static float smooth(const float *amax, const float *wmax, size_t k, float *s)+{+ float range = 0;+ for (size_t c = 0; c < k; c++) {+ float a = amax[c] > 1e-6f ? amax[c] : 1e-6f,+ w = wmax[c] > 1e-6f ? wmax[c] : 1e-6f, v = sqrtf(a / w);+ v = v < 1e-3f ? 1e-3f : v > 1e3f ? 1e3f : v;+ s[c] = v;+ range = a / v > range ? a / v : range;+ }+ return range;+}++/* x (FP16) on the 256 steps of an INT8 over [-range 128/127, range] */+static int fq(struct npu_ir *ir, const char *name, int x, float range)+{+ return npu_ir_fake_quantize(ir, name, x, -range * 128.0f / 127.0f, range,+ 256);+}++static float *amax(struct janas_m_npu *n, uint32_t l, int site)+{+ return n->amax ? n->amax[(size_t)l * N_SITES + site] : NULL;+}++/* norm then q, k, v of layer lq from x (f32), as results; mode 2 INT8 on+ its calibration */+static void qkv_part(struct npu_ir *ir, struct janas_llm_model *m,+ struct janas_m_npu *n, uint32_t lq, int x, int mode,+ int *ok)+{+ const struct layer *ly = &m->layers[lq];+ size_t d = m->d_model, rows[3] = {0}, cols[3] = {0};+ /* Gemma 4: V is K in its full layers, and its last layers have no K,+ the keys and values of an earlier layer's in the cache */+ const struct janas_jns_tensor *t[3] = {ly->wq, ly->wk, ly->wv};+ float *f[3] = {NULL, NULL, NULL}, *wn = malloc(sizeof(float) * d),+ *s = NULL;+ int bad = !wn;+ for (int i = 0; i < 3; i++)+ if (t[i] && !(f[i] = deq_tensor(m, t[i], &rows[i], &cols[i])))+ bad = 1;+ if (bad || !f[0]) {+ *ok = 0;+ free(wn);+ for (int i = 0; i < 3; i++)+ free(f[i]);+ return;+ }+ memcpy(wn, f32(m, ly->attn_norm), sizeof(float) * d);+ float range = 0;+ if (mode == 2 && !(n->a8_sites & 1 << SITE_QKV))+ mode = 0;+ if (mode == 2) {+ float *wm = calloc(d, sizeof(float));+ s = malloc(sizeof(float) * d);+ for (int i = 0; wm && i < 3; i++)+ col_max(f[i], rows[i], cols[i], wm);+ range = wm && s ? smooth(amax(n, lq, SITE_QKV), wm, d, s) : 0;+ for (size_t c = 0; s && c < d; c++)+ wn[c] /= s[c];+ free(wm);+ }+ int hn = npu_ir_rms_norm(ir, "hn", x, wn, (int)d, m->eps);+ free(wn);+ int h = npu_ir_convert(ir, "hn16", hn, "f16");+ if (mode == 2)+ h = fq(ir, "hnq", h, range);+ static const char *nm[3][3] = {+ {"wq", "q", "q32"}, {"wk", "k", "k32"}, {"wv", "v", "v32"}};+ for (int i = 0; i < 3; i++)+ if (f[i])+ npu_ir_result(+ ir, npu_ir_convert(+ ir, nm[i][2],+ npu_ir_matmul_tb(ir, nm[i][1], h,+ weights_f(ir, nm[i][0], f[i], rows[i],+ cols[i], s, NULL, ok),+ NULL),+ "f32"));+ free(s);+}++/* layer lq's norm and input products from x (f32), as results: an+ attention layer's q (with its output gates where it has them), k, v; a+ recurrent layer's norm in f32 (the CPU's betas and alphas read it) and+ q|k|v and z in one product, as m->big holds them (Qwen3.5) */+static void in_part(struct npu_ir *ir, struct janas_llm_model *m,+ struct janas_m_npu *n, uint32_t lq, int x, int mode,+ int *ok)+{+ const struct layer *ly = &m->layers[lq];+ if (!ly->rec) {+ qkv_part(ir, m, n, lq, x, mode, ok);+ return;+ }+ size_t d = m->d_model, r1, c1, r2, c2;+ float *f1 = deq_tensor(m, ly->ssm_qkv, &r1, &c1),+ *f2 = deq_tensor(m, ly->ssm_z, &r2, &c2);+ float *f = f1 && f2 && c1 == d && c2 == d && r1 + r2 == (size_t)m->qkvz_dim+ ? realloc(f1, sizeof(float) * (r1 + r2) * d)+ : NULL;+ if (!f) {+ free(f1), free(f2);+ *ok = 0;+ return;+ }+ memcpy(f + r1 * d, f2, sizeof(float) * r2 * d);+ free(f2);+ int hn =+ npu_ir_rms_norm(ir, "hn", x, f32(m, ly->attn_norm), (int)d, m->eps);+ npu_ir_result(ir, hn);+ int h = npu_ir_convert(ir, "hn16", hn, "f16");+ npu_ir_result(+ ir, npu_ir_convert(ir, "qkvz32",+ npu_ir_matmul_tb(ir, "qkvz", h,+ weights_f(ir, "wqkvz", f, r1 + r2,+ d, NULL, NULL, ok),+ NULL),+ "f32"));+}++/* the arguments in_part's results go to, half h's, from na on: the next+ na */+static int in_args(const struct janas_llm_model *m, struct janas_m_npu *n,+ uint32_t lq, int h, float **args, int *rows, int *cols,+ int na)+{+ const struct layer *ly = &m->layers[lq];+ int B = n->hb;+ if (ly->rec) {+ args[na] = n->hn[h], rows[na] = B, cols[na++] = (int)m->d_model;+ args[na] = n->big[h], rows[na] = B, cols[na++] = (int)m->qkvz_dim;+ return na;+ }+ int qd = (int)(m->n_head * ly->hd), kvn = (int)(ly->n_kv * ly->hd);+ args[na] = n->q[h], rows[na] = B;+ cols[na++] = m->a->attn_gate ? 2 * qd : qd;+ if (ly->wk)+ args[na] = n->k[h], rows[na] = B, cols[na++] = kvn;+ if (ly->wv)+ args[na] = n->v[h], rows[na] = B, cols[na++] = kvn;+ return na;+}++/* layer l's graph in mode 0 (FP16) or 2 (INT8 activations, SmoothQuant+ from the calibration); arguments: att, x in, x' out, then (unless last:+ the last layer the NPU runs) the next layer's input part out */+static int layer_graph(struct janas_llm_model *m, struct janas_m_npu *n,+ uint32_t l, int mode, int last, char *err,+ size_t err_len)+{+ const struct layer *ly = &m->layers[l];+ int B = n->hb, d = (int)m->d_model,+ qd = ly->rec ? (int)m->d_inner : (int)(m->n_head * ly->hd);+ int ok = 1;+ struct npu_ir ir;+ npu_ir_begin(&ir, "janas_layer");+ int ad[2] = {B, qd}, xd[2] = {B, d}, P = (int)m->ple_dim, pd[2] = {B, P};+ int la = npu_ir_param(&ir, "att", "f32", 2, ad);+ int lx = npu_ir_param(&ir, "x", "f32", 2, xd);+ int lp = P ? npu_ir_param(&ir, "ple", "f32", 2, pd) : -1;+ /* wo */+ size_t orow, ocol;+ float *fo = deq_tensor(m, ly->rec ? ly->ssm_out : ly->wo, &orow, &ocol),+ *so = NULL, ro = 0;+ int q_att = mode == 2 && (n->a8_sites & 1 << SITE_ATT),+ q_ffn = mode == 2 && (n->a8_sites & 1 << SITE_FFN),+ q_mid = mode == 2 && (n->a8_sites & 1 << SITE_MID);+ if (q_att && fo) {+ float *wm = calloc(ocol, sizeof(float)),+ *inv = malloc(sizeof(float) * ocol);+ so = malloc(sizeof(float) * ocol);+ col_max(fo, orow, ocol, wm);+ ro = wm && so && inv ? smooth(amax(n, l, SITE_ATT), wm, ocol, so) : 0;+ for (size_t c = 0; inv && so && c < ocol; c++)+ inv[c] = 1.0f / so[c];+ int one = (int)ocol;+ if (inv)+ la = npu_ir_binary(&ir, "att_s", "Multiply", la,+ npu_ir_const(&ir, "att_inv", "f32", 1, &one, inv,+ sizeof(float) * ocol));+ free(wm), free(inv);+ }+ int a16 = npu_ir_convert(&ir, "a16", la, "f16");+ if (q_att)+ a16 = fq(&ir, "aq", a16, ro);+ int o = npu_ir_matmul_tb(+ &ir, "o", a16, weights_f(&ir, "wo", fo, orow, ocol, so, NULL, &ok),+ NULL);+ free(so);+ int o32 = npu_ir_convert(&ir, "o32", o, "f32");+ if (ly->post_attn) /* Gemma 4: the attention's output normalized */+ o32 = npu_ir_rms_norm(&ir, "on", o32, f32(m, ly->post_attn), d, m->eps);+ int x1 = npu_ir_add(&ir, "x1", lx, o32);+ /* the FFN */+ float *ff[3];+ size_t fr[3], fc[3];+ if (deq_ffn(m, l, ff, fr, fc))+ ok = 0;+ size_t nf = fr[0];+ float *wn = malloc(sizeof(float) * d), *sf = NULL, *sm = NULL, *rinv = NULL,+ rf = 0, rm = 0;+ if (wn)+ memcpy(wn, f32(m, ly->ffn_norm), sizeof(float) * d);+ if (q_ffn && ok && wn) { /* gate's and up's input: the norm's */+ float *wm = calloc((size_t)d, sizeof(float));+ sf = malloc(sizeof(float) * d);+ if (wm && sf) {+ col_max(ff[0], fr[0], fc[0], wm);+ col_max(ff[1], fr[1], fc[1], wm);+ rf = smooth(amax(n, l, SITE_FFN), wm, (size_t)d, sf);+ for (int c = 0; c < d; c++)+ wn[c] /= sf[c];+ } else+ ok = 0;+ free(wm);+ }+ if (q_mid && ok) { /* down's input: the intermediate, through up */+ float *wd = calloc(nf, sizeof(float));+ sm = malloc(sizeof(float) * nf);+ rinv = malloc(sizeof(float) * nf);+ if (wd && sm && rinv) {+ col_max(ff[2], fr[2], fc[2], wd);+ rm = smooth(amax(n, l, SITE_MID), wd, nf, sm);+ for (size_t c = 0; c < nf; c++)+ rinv[c] = 1.0f / sm[c]; /* into up's rows: h / s */+ } else+ ok = 0;+ free(wd);+ }+ int hf = wn ? npu_ir_rms_norm(&ir, "hf", x1, wn, d, m->eps) : -1;+ free(wn);+ int h16 = npu_ir_convert(&ir, "h16", hf, "f16");+ if (q_ffn)+ h16 = fq(&ir, "hq", h16, rf);+ int wg = weights_f(&ir, "fg", ff[0], fr[0], fc[0], sf, NULL, &ok);+ int wu = weights_f(&ir, "fu", ff[1], fr[1], fc[1], sf, rinv, &ok);+ int wdn = weights_f(&ir, "fd", ff[2], fr[2], fc[2], sm, NULL, &ok);+ free(sf), free(sm), free(rinv);+ int lg = npu_ir_matmul_tb(&ir, "g", h16, wg, NULL);+ int lu = npu_ir_matmul_tb(&ir, "u", h16, wu, NULL);+ int act;+ if (!m->a->gelu)+ act = npu_ir_multiply(&ir, "silu", lg,+ npu_ir_unary(&ir, "sig", "Sigmoid", lg));+ else {+ int g3 =+ npu_ir_multiply(&ir, "g3", npu_ir_multiply(&ir, "g2", lg, lg), lg);+ int in =+ npu_ir_add(&ir, "gin", lg,+ npu_ir_multiply(&ir, "gc3", g3,+ npu_ir_scalar(&ir, "c3", 0.044715f)));+ int t = npu_ir_unary(+ &ir, "gt", "Tanh",+ npu_ir_multiply(&ir, "gk", in,+ npu_ir_scalar(&ir, "k", 0.7978845608f)));+ act = npu_ir_multiply(+ &ir, "gelu",+ npu_ir_multiply(&ir, "gh", lg, npu_ir_scalar(&ir, "half", 0.5f)),+ npu_ir_add(&ir, "g1t", t, npu_ir_scalar(&ir, "one", 1.0f)));+ }+ int hm = npu_ir_multiply(&ir, "hm", act, lu);+ if (q_mid)+ hm = fq(&ir, "mq", hm, rm);+ int f = npu_ir_matmul_tb(&ir, "dn", hm, wdn, NULL);+ int f32o = npu_ir_convert(&ir, "f32", f, "f32");+ if (ly->post_ffn) /* Gemma 4: the FFN's output normalized */+ f32o =+ npu_ir_rms_norm(&ir, "fn", f32o, f32(m, ly->post_ffn), d, m->eps);+ int x2 = npu_ir_add(&ir, "x2", x1, f32o);+ if (P && ok) {+ /* the per-layer embeddings' branch (janas_m_ple_layer):+ gelu(gate x) times the layer's inputs, projected back,+ normalized, added */+ size_t gr, gc, pr, pc;+ float *fg = deq_tensor(m, ly->ple_gate, &gr, &gc),+ *fp = deq_tensor(m, ly->ple_proj, &pr, &pc);+ int x16 = npu_ir_convert(&ir, "x2h", x2, "f16");+ int g = npu_ir_matmul_tb(+ &ir, "pg", x16, weights_f(&ir, "wpg", fg, gr, gc, NULL, NULL, &ok),+ NULL);+ /* g sigmoid(1.5958 (g + 0.044715 g^3)): the tanh form, as+ janas_gelu_mul_det */+ int g3 =+ npu_ir_multiply(&ir, "pg3", npu_ir_multiply(&ir, "pg2", g, g), g);+ int z = npu_ir_multiply(+ &ir, "pz",+ npu_ir_add(&ir, "pin", g,+ npu_ir_multiply(&ir, "pgc", g3,+ npu_ir_scalar(&ir, "pc3", 0.044715f))),+ npu_ir_scalar(&ir, "pk", 1.5957691216057308f));+ int gl = npu_ir_multiply(&ir, "pgl", g,+ npu_ir_unary(&ir, "psg", "Sigmoid", z));+ int gi = npu_ir_multiply(&ir, "pgi", gl,+ npu_ir_convert(&ir, "ple16", lp, "f16"));+ int p = npu_ir_matmul_tb(+ &ir, "pp", gi, weights_f(&ir, "wpp", fp, pr, pc, NULL, NULL, &ok),+ NULL);+ int pn =+ npu_ir_rms_norm(&ir, "pn", npu_ir_convert(&ir, "pp32", p, "f32"),+ f32(m, ly->ple_post), d, m->eps);+ x2 = npu_ir_add(&ir, "x3", x2, pn);+ }+ if (ly->out_scale != 1.0f) { /* in f32: it scales the residual itself */+ int one = 1;+ x2 = npu_ir_multiply(&ir, "xs", x2,+ npu_ir_const(&ir, "os", "f32", 1, &one,+ &ly->out_scale, sizeof(float)));+ }+ npu_ir_result(&ir, x2);+ if (!last)+ in_part(&ir, m, n, l + 1, x2, mode, &ok);+ if (!ok) {+ npu_ir_end(&ir);+ npu_ir_free(&ir);+ snprintf(err, err_len, "layer %u: a type the NPU does not take", l);+ return -1;+ }+ float *args[2][10];+ int rows[10], cols[10], na = 0;+ for (int h = 0; h < 2; h++) {+ na = 0;+ args[h][na] = n->att[h], rows[na] = B, cols[na++] = qd;+ args[h][na] = n->xs[h][l % 2], rows[na] = B, cols[na++] = d;+ if (P)+ args[h][na] = n->ple[h], rows[na] = B, cols[na++] = P;+ args[h][na] = n->xs[h][(l + 1) % 2], rows[na] = B, cols[na++] = d;+ if (!last)+ na = in_args(m, n, l + 1, h, args[h], rows, cols, na);+ }+ n->lg[l] = janas_npu_graph_create(n->u, &ir, na, args[0], rows, cols, err,+ err_len);+ if (n->lg[l] && janas_npu_mm_bind_alt(n->lg[l], na, args[1])) {+ snprintf(err, err_len, "layer %u: no second binding", l);+ janas_npu_mm_destroy(n->lg[l]);+ n->lg[l] = NULL;+ return -1;+ }+ return n->lg[l] ? 0 : -1;+}++/* the first layer's norm and input products, in the same modes */+static int first_graph(struct janas_llm_model *m, struct janas_m_npu *n,+ int mode, char *err, size_t err_len)+{+ int B = n->hb, d = (int)m->d_model, ok = 1;+ struct npu_ir ir;+ npu_ir_begin(&ir, "janas_first");+ int xd[2] = {B, d};+ int lx = npu_ir_param(&ir, "x", "f32", 2, xd);+ in_part(&ir, m, n, 0, lx, mode, &ok);+ if (!ok) {+ npu_ir_end(&ir);+ npu_ir_free(&ir);+ snprintf(err, err_len, "the first layer: a type the NPU does not take");+ return -1;+ }+ float *args[2][4];+ int rows[4], cols[4], na = 0;+ for (int h = 0; h < 2; h++) {+ args[h][0] = n->xs[h][0], rows[0] = B, cols[0] = d;+ na = in_args(m, n, 0, h, args[h], rows, cols, 1);+ }+ n->lpre = janas_npu_graph_create(n->u, &ir, na, args[0], rows, cols, err,+ err_len);+ if (n->lpre && janas_npu_mm_bind_alt(n->lpre, na, args[1])) {+ snprintf(err, err_len, "the first layer: no second binding");+ return -1;+ }+ return n->lpre ? 0 : -1;+}++/* the calibration's store: every site's maxima, zero */+static int calib_alloc(struct janas_llm_model *m, struct janas_m_npu *n)+{+ n->amax = calloc((size_t)m->n_layer * N_SITES, sizeof(float *));+ if (!n->amax)+ return -1;+ for (uint32_t l = 0; l < m->n_layer; l++)+ for (int s = 0; s < N_SITES; s++) {+ size_t w = s == SITE_ATT ? m->n_head * m->layers[l].hd+ : s == SITE_MID ? m->j.layers[l].m[0].rows+ : m->d_model;+ if (!(n->amax[(size_t)l * N_SITES + s] = calloc(w, sizeof(float))))+ return -1;+ }+ return 0;+}++/* whether this model's layers can go to the NPU whole: dense, a norm+ before the attention and before the FFN and nothing else, attention with+ its own keys and values (Qwen3's layout), or Qwen3.5's: attention with an+ output gate, and Gated DeltaNet layers whose q|k|v and z are two+ products */+static int layers_fit(const struct janas_llm_model *m)+{+ const struct janas_arch *a = m->a;+ /* Gemma 4's dense models too (sandwich norms, windows, per-layer+ embeddings): its mixture keeps the experts on the CPU */+ int gemma = a->sandwich && a->swa && a->rec == JANAS_REC_NONE;+ if ((a->rec != JANAS_REC_NONE && a->rec != JANAS_REC_Q35) ||+ (a->attn_gate && a->rec != JANAS_REC_Q35) || a->shared_expert ||+ ((a->sandwich || a->swa || m->ple_dim) && !gemma) || m->n_expert > 1 ||+ m->janet || m->pred_fn || !m->cache)+ return 0;+ uint32_t qd = 0;+ for (uint32_t l = 0; l < m->n_layer; l++) {+ const struct layer *ly = &m->layers[l];+ if (!ly->attn_norm || !ly->ffn_norm || ly->pre_norm2 || ly->sh_w[0] ||+ (!gemma && (ly->post_attn || ly->post_ffn || ly->swa)) ||+ (gemma && (!ly->post_attn || !ly->post_ffn)) ||+ (m->ple_dim && (!ly->ple_gate || !ly->ple_proj || !ly->ple_post)))+ return 0;+ if (ly->rec) {+ if (!ly->ssm_qkv || !ly->ssm_z || !ly->ssm_beta || !ly->ssm_alpha ||+ !ly->ssm_out)+ return 0;+ continue;+ }+ /* every attention layer its keys and values, but Gemma's: V is K+ in its full layers, and its last layers share an earlier one's;+ its window layers' heads are narrower than its full layers' */+ if (!ly->wq || !ly->wo || (!gemma && (!ly->wk || !ly->wv)) ||+ (!gemma && qd && m->n_head * ly->hd != qd))+ return 0;+ qd = m->n_head * ly->hd;+ }+ return 1;+}++/* the weights of layer l's input part, and of its graph without it */+static size_t in_elems(const struct janas_llm_model *m, uint32_t l)+{+ const struct layer *ly = &m->layers[l];+ if (ly->rec)+ return (size_t)m->qkvz_dim * m->d_model;+ size_t qd = (size_t)m->n_head * ly->hd, kv = (size_t)ly->n_kv * ly->hd;+ return ((m->a->attn_gate ? 2 : 1) * qd + (ly->wk ? kv : 0) ++ (ly->wv ? kv : 0)) *+ m->d_model;+}++static size_t body_elems(const struct janas_llm_model *m, uint32_t l)+{+ const struct layer *ly = &m->layers[l];+ const struct janas_jns_layer *jl = &m->j.layers[l];+ size_t e = (ly->rec ? (size_t)m->d_inner : (size_t)m->n_head * ly->hd) *+ m->d_model;+ for (int k = 0; k < 3; k++)+ e += (size_t)jl->m[k].rows * jl->m[k].cols;+ if (m->ple_dim) /* the per-layer branch's gate and projection */+ e += 2 * (size_t)m->ple_dim * m->d_model;+ return e;+}++/* how many of the first layers fit the NPU: their INT8 weights within+ JANAS_NPU_LAYERS_MB (default 3700: Qwen3-4B's 36 layers are 3.63 GB, and+ held; a graph beyond what the NPU holds fails, and the layers stop at the+ one before) */+static uint32_t layers_budget(const struct janas_llm_model *m)+{+ const char *e = getenv("JANAS_NPU_LAYERS_MB");+ size_t budget = (size_t)(e && atol(e) > 0 ? atol(e) : 3700) << 20,+ used = in_elems(m, 0);+ uint32_t l = 0;+ while (l < m->n_layer) {+ size_t add = body_elems(m, l) + (l ? in_elems(m, l) : 0);+ if (used + add > budget)+ break;+ used += add, l++;+ }+ return l;+}++static void layers_free(struct janas_m_npu *n, uint32_t n_layer)+{+ janas_npu_mm_destroy(n->lpre);+ n->lpre = NULL;+ for (uint32_t l = 0; n->lg && l < n_layer; l++)+ janas_npu_mm_destroy(n->lg[l]);+ free(n->lg);+ n->lg = NULL;+}++/* the graphs, the first time (or after the arena changed) */+static int layers_make_(struct janas_llm_model *m, struct janas_m_npu *n);++static int layers_make(struct janas_llm_model *m, struct janas_m_npu *n)+{+ double t0 = now();+ int r = layers_make_(m, n);+ n->setup_s += now() - t0;+ prep_end(n);+ return r;+}++static int layers_make_(struct janas_llm_model *m, struct janas_m_npu *n)+{+ char err[256] = "";+ int B = n->hb, d = (int)m->d_model, qd = 0, aw = 0, kvd = 0, rec = 0;+ for (uint32_t l = 0; l < m->n_layer; l++) {+ const struct layer *ly = &m->layers[l];+ int w = ly->rec ? (int)m->d_inner : (int)(m->n_head * ly->hd);+ aw = w > aw ? w : aw;+ if (ly->rec) {+ rec = 1;+ continue;+ }+ int q = (m->a->attn_gate ? 2 : 1) * (int)(m->n_head * ly->hd);+ qd = q > qd ? q : qd;+ if (ly->n_kv * ly->hd > (uint32_t)kvd)+ kvd = (int)(ly->n_kv * ly->hd);+ }+ for (int h = 0; h < 2 && !n->att[1]; h++) {+ n->xs[h][0] = janas_npu_alloc(n->u, sizeof(float) * B * d);+ n->xs[h][1] = janas_npu_alloc(n->u, sizeof(float) * B * d);+ n->att[h] = janas_npu_alloc(n->u, sizeof(float) * B * aw);+ if (qd) {+ n->q[h] = janas_npu_alloc(n->u, sizeof(float) * B * qd);+ n->k[h] = janas_npu_alloc(n->u, sizeof(float) * B * kvd);+ n->v[h] = janas_npu_alloc(n->u, sizeof(float) * B * kvd);+ }+ if (rec) {+ n->big[h] = janas_npu_alloc(n->u, sizeof(float) * B * m->qkvz_dim);+ n->hn[h] = janas_npu_alloc(n->u, sizeof(float) * B * d);+ }+ if (m->ple_dim && !(n->ple[h] = janas_npu_alloc(+ n->u, sizeof(float) * B * m->ple_dim)))+ return -1;+ if (!n->xs[h][0] || !n->xs[h][1] || !n->att[h] ||+ (qd && (!n->q[h] || !n->k[h] || !n->v[h])) ||+ (rec && (!n->big[h] || !n->hn[h])))+ return -1;+ memset(n->xs[h][0], 0, sizeof(float) * B * d);+ memset(n->xs[h][1], 0, sizeof(float) * B * d);+ memset(n->att[h], 0, sizeof(float) * B * aw);+ }+ double w0 = now();+ n->lg = calloc(m->n_layer, sizeof(*n->lg));+ int mode = n->a8 == 2 ? 2 : 0;+ uint32_t want = layers_budget(m), made = 0;+ if (10 * (size_t)want < 9 * (size_t)m->n_layer && !n->partial) {+ if (getenv("JANAS_NPU_STATS"))+ fprintf(stderr,+ "janas: NPU: %u layers of %u would fit: the products "+ "instead\n",+ want, m->n_layer);+ layers_free(n, m->n_layer);+ return -1;+ }+ prep_begin(n, (int)want + 1);+ int rc = n->lg && want ? first_graph(m, n, mode, err, sizeof err) : -1;+ atomic_fetch_add(&n->prep_done, 1);+ while (rc == 0 && made < want) {+ rc = layer_graph(m, n, made, mode, made + 1 == want, err, sizeof err);+ made += rc == 0;+ atomic_fetch_add(&n->prep_done, 1);+ }+ if (rc && made > 0 &&+ (n->partial || 10 * (size_t)made >= 9 * (size_t)m->n_layer)) {+ /* the NPU held fewer than the budget: the layers made, the last+ one's graph again without the next layer's input part */+ if (getenv("JANAS_NPU_STATS"))+ fprintf(stderr, "janas: NPU: %u layers of %u (%s)\n", made, want,+ err[0] ? err : "no memory");+ janas_npu_mm_destroy(n->lg[made - 1]);+ n->lg[made - 1] = NULL;+ rc = layer_graph(m, n, made - 1, mode, 1, err, sizeof err);+ }+ if (rc || !made) {+ fprintf(stderr, "janas: NPU: the layers stay apart: %s\n",+ err[0] ? err+ : !want ? "none fits"+ : "no memory");+ layers_free(n, m->n_layer);+ return -1;+ }+ n->nl = made;+ n->layers_compile_s += now() - w0;+ /* the products' and the FFNs' graphs are not used beside these */+ for (size_t i = 0; i < NPU_SLOTS; i++)+ if (n->e[i].mm)+ drop(n, &n->e[i]);+ n->lmode_loads = n->arena_loads;+ return 0;+}++/* the attention's output gated (Qwen3.5), item = token: as+ att_out_tok does it on the CPU's path, before wo */+struct gate_job {+ struct janas_llm_model *m;+ float *att;+ uint32_t qd, n;+};++static void npu_gate_worker(void *arg, int tid, int n_threads)+{+ struct gate_job *g = arg;+ for (uint32_t j = (uint32_t)tid; j < g->n; j += (uint32_t)n_threads) {+ float *a = g->att + (size_t)j * g->qd;+ const float *q = g->m->qgate + (size_t)j * g->qd;+ for (uint32_t i = 0; i < g->qd; i++)+ a[i] *= sigmoid(q[i]);+ }+}++static void npu_gate(struct janas_llm_model *m, const struct layer *ly,+ float *att, uint32_t n)+{+ struct gate_job g = {m, att, m->n_head * ly->hd, n};+ janas_pool_run(m->compute, npu_gate_worker, &g);+}++/*+ * The NPU's answers against llama.cpp's (llm_eval, blocks of 256, two texts+ * of 256 tokens, the CPU's in brackets; 21 Oct 2026): at par in whole+ * layers - Qwen3.5-0.8B 490 (497), 2B 489 (493), Gemma 4 E2B 487 (490), E4B+ * 491 (495) of 512 - and Qwen's mixtures in products - Qwen3-Next-80B 492+ * (497), Qwen3-30B-A3B 454 (446), Qwen3.6-35B-A3B 485 (485); Gemma 4 in+ * products lost - 26B-A4B 363 (398), E2B 476 (490), the 12B 389 (383).+ * There the tuner leaves the NPU alone unless asked.+ */+int janas_m_npu_auto(const struct janas_llm_model *m)+{+ if (!m->npu)+ return 0;+ if (!m->a->sandwich)+ return 1;+ const char *e = getenv("JANAS_NPU_LAYERS");+ return !(e && atoi(e) <= 0) && layers_fit(m) &&+ 10 * (size_t)layers_budget(m) >= 9 * (size_t)m->n_layer;+}++int janas_llm_model_npu_auto(const struct janas_llm_model *m)+{+ return janas_m_npu_auto(m);+}++static int wait_graph(struct janas_m_npu *n, struct janas_npu_mm *g, int h)+{+ double t0 = now();+ int r = janas_npu_mm_finish_v(g, h);+ n->t_layer_wait += now() - t0;+ return r;+}++int janas_m_npu_layers(struct janas_llm_model *m, uint32_t nt, uint32_t pos0)+{+ struct janas_m_npu *n = m->npu;+ if (!n || !janas_m_npu_takes(m, nt) || (int)nt > n->block || n->lmode < 0)+ return -1;+ if (n->lmode == 0 && !n->lg) {+ const char *e = getenv("JANAS_NPU_LAYERS");+ if ((e && atoi(e) <= 0) || !layers_fit(m)) {+ n->lmode = -1;+ return -1;+ }+ n->partial = e && atoi(e) >= 2;+ /* too few layers fit: the products from the first block on, known+ before the arena is whole (below) */+ if (10 * (size_t)layers_budget(m) < 9 * (size_t)m->n_layer &&+ !n->partial) {+ n->lmode = -1;+ return -1;+ }+ /* INT8 activations: calibrated on the first blocks+ (JANAS_NPU_A8_CALIB, default 1) in FP16, then INT8 graphs */+ const char *a8 = getenv("JANAS_NPU_A8"),+ *ca = getenv("JANAS_NPU_A8_CALIB");+ if (!n->amax && n->a8 == 0 && a8 && atoi(a8) > 0 &&+ m->a->rec == JANAS_REC_NONE && !m->a->attn_gate &&+ !m->a->sandwich && calib_alloc(m, n) == 0) {+ n->a8 = 1;+ n->a8_left = ca && atoi(ca) > 0 ? atoi(ca) : 1;+ /* by default the inputs of q, k, v and of gate, up: on+ Qwen3-4B 299 tokens/s against 268 in FP16, the last token's+ logits 0.60 from the CPU's on average against 0.33; all+ four 307 and 4.32, the attention's output and the+ intermediate needing a scale for each token (20 Oct 2026) */+ const char *si = getenv("JANAS_NPU_A8_SITES");+ n->a8_sites = si ? atoi(si) & 15 : 1 << SITE_QKV | 1 << SITE_FFN;+ }+ }+ /* the pass before was a calibration's: counted, and after the last+ the INT8 graphs */+ if (n->in_calib) {+ n->in_calib = 0;+ if (--n->a8_left <= 0) {+ n->a8 = 2;+ if (getenv("JANAS_NPU_STATS"))+ fprintf(stderr, "janas: NPU calibrated: INT8 activations "+ "from this block\n");+ }+ }+ if (n->a8 == 1) { /* on the CPU's path, the maxima taken on the way */+ n->in_calib = 1;+ m->npu_use = 0;+ return -1;+ }+ /* the FFNs are read in the arena: whole and unchanged since made. While+ it fills - the first blocks after the model opens - a block goes+ without the NPU rather than have it make the products' graphs that+ the whole layers drop once the arena is whole (5 s of Qwen3.5-2B's+ first block in janas-chat, 21 Oct 2026) */+ if (!n->arena) {+ m->npu_use = 0;+ return -1;+ }+ if (n->lmode == 1 && n->arena_loads != n->lmode_loads) {+ layers_free(n, m->n_layer);+ n->lmode = 0;+ }+ if (n->lmode == 0) {+ n->hb = n->block / 2;+ if (layers_make(m, n)) {+ n->lmode = -1;+ return -1;+ }+ n->lmode = 1;+ }+ uint32_t d = m->d_model, hb = (uint32_t)n->hb;+ uint32_t c[2] = {nt < hb ? nt : hb, nt > hb ? nt - hb : 0};+ int H = c[1] ? 2 : 1;+ for (int h = 0; h < H; h++)+ memcpy(n->xs[h][0], m->x + (size_t)h * hb * d,+ sizeof(float) * c[h] * d);+ int rc = 0;+ for (int h = 0; h < H && rc == 0; h++)+ rc = janas_npu_mm_begin_v(n->lpre, h);+ for (int h = 0; h < H; h++)+ if (wait_graph(n, n->lpre, h))+ rc = -1;++ if (rc)+ return -1; /* nothing written yet: the CPU's path from here */+ float *sq = m->q, *sk = m->kk, *sv = m->vv, *sa = m->att, *sb = m->big;+ /* the pool's idle workers asleep at once, not spinning: they wait+ most of the pass for the NPU, and cores spinning at their highest+ clock slowed it (unless JANAS_NPU_SPIN=1) */+ int spin = npu_quiet(m);+ /* layer by layer, half by half: the attention (or recurrence) of half+ h on the CPU while the NPU runs the layer on the other */+ for (uint32_t l = 0; l < n->nl && rc == 0; l++)+ for (int h = 0; h < H && rc == 0; h++) {+ if (l > 0 && wait_graph(n, n->lg[l - 1], h)) {+ rc = -1;+ break;+ }+ const struct layer *ly = &m->layers[l];+ m->att = n->att[h];+ double ta = now();+ if (ly->rec) {+ /* the second half goes on from the state the first left,+ the tokens to replay (if any) already in it */+ m->big = n->big[h];+ janas_m_rec_ba(m, ly, n->hn[h], c[h]);+ uint32_t rp = m->replay;+ if (h)+ m->replay = 0, m->rec_cont = 1;+ janas_m_rec_core(m, ly, c[h], ta);+ m->replay = rp, m->rec_cont = 0;+ } else {+ /* with output gates, q and the gates as m->big holds them:+ the core puts q in m->q, the gates in m->qgate */+ if (m->a->attn_gate)+ m->big = n->q[h];+ else+ m->q = n->q[h];+ m->kk = n->k[h], m->vv = n->v[h];+ if (ly->wk && !ly->wv) /* Gemma 4's full layers: V is K, as+ before K's norm */+ memcpy(n->v[h], n->k[h],+ sizeof(float) * c[h] * ly->n_kv * ly->hd);+ /* the RoPE tables are the block's, row j its token j: the+ second half starts hb rows in (a window layer's tables+ apart) */+ size_t ro = (size_t)h * hb * (ly->n_rot / 2);+ float **rc_ = ly->swa ? &m->rope_cos_swa : &m->rope_cos,+ **rs_ = ly->swa ? &m->rope_sin_swa : &m->rope_sin;+ *rc_ += ro, *rs_ += ro;+ janas_m_attn_core(m, ly, c[h], pos0 + (uint32_t)h * hb, ta);+ *rc_ -= ro, *rs_ -= ro;+ if (m->a->attn_gate)+ npu_gate(m, ly, n->att[h], c[h]);+ }+ n->t_layer_attn += now() - ta;+ if (m->ple_dim) { /* this layer's per-layer inputs, half h's */+ uint32_t P = m->ple_dim, W = m->n_layer * P;+ for (uint32_t j = 0; j < c[h]; j++)+ memcpy(n->ple[h] + (size_t)j * P,+ m->ple + ((size_t)h * hb + j) * W + (size_t)l * P,+ sizeof(float) * P);+ }+ rc = janas_npu_mm_begin_v(n->lg[l], h);+ }+ for (int h = 0; h < H; h++) /* the last layer's, and any in flight */+ for (uint32_t l = 0; l < n->nl; l++)+ janas_npu_mm_finish_v(n->lg[l], h);+ m->q = sq, m->kk = sk, m->vv = sv, m->att = sa, m->big = sb;+ npu_loud(m, spin);+ if (rc) { /* the keys and values of some layers are written: no way+ back to the CPU's path for this block */+ fprintf(stderr, "janas: NPU failed in the middle of a block\n");+ return -2;+ }+ for (int h = 0; h < H; h++)+ memcpy(m->x + (size_t)h * hb * d, n->xs[h][n->nl % 2],+ sizeof(float) * c[h] * d);+ n->layer_passes++;+ return (int)n->nl;+}++void janas_m_npu_calib(struct janas_llm_model *m, int site, uint32_t l,+ const float *x, uint32_t rows, uint32_t width,+ size_t stride)+{+ struct janas_m_npu *n = m->npu;+ if (!n || !n->in_calib || l >= m->n_layer)+ return;+ float *a = amax(n, l, site);+ for (uint32_t r = 0; a && r < rows; r++)+ for (uint32_t c = 0; c < width; c++) {+ float v = fabsf(x[r * stride + c]);+ a[c] = v > a[c] ? v : a[c];+ }+}diff --git a/src/llm/model_ple.c b/src/llm/model_ple.cindex 2cf99d6..51f1336 100644--- a/src/llm/model_ple.c+++ b/src/llm/model_ple.c@@ -280,7 +280,7 @@ static void product(struct janas_llm_model *m, const struct janas_jns_tensor *t,.rows = rows,.cols = cols,.n_vec = n};- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, &tk, 1);+ janas_m_products(m, janas_m_gpu(m, 0), &tk, 1);}/*diff --git a/src/llm/model_rec.c b/src/llm/model_rec.cindex 5b5c62d..e9e46bd 100644--- a/src/llm/model_rec.c+++ b/src/llm/model_rec.c@@ -127,7 +127,8 @@ static void conv_worker(void *arg, int tid, int n_threads)struct janas_llm_model *m = a->m;uint32_t cc = m->conv_ch, ds = m->ds, kd = m->n_kh * ds;size_t sz = (size_t)m->n_rec * (m->d_conv - 1) * cc;- float *src = m->conv_buf + (size_t)m->src * sz ++ float *src = m->conv_buf ++ (size_t)(m->rec_cont ? 1 - m->src : m->src) * sz +(size_t)a->ly->slot * (m->d_conv - 1) * cc;float *dst = m->conv_buf + (size_t)(1 - m->src) * sz +(size_t)a->ly->slot * (m->d_conv - 1) * cc;@@ -173,11 +174,13 @@ static void rec_worker(void *arg, int tid, int n_threads)uint32_t h = it / blocks, r0 = it % blocks * SSM_ROWS;uint32_t g = m->vmap_mod ? h % m->n_kh : h / rf;size_t off = (((size_t)a->ly->slot * nv + h) * ds + r0) * ds;- uint16_t *M = m->ssm_buf + (size_t)m->src * sz + off;+ uint16_t *M =+ m->ssm_buf + (size_t)(m->rec_cont ? 1 - m->src : m->src) * sz + off;uint16_t *D = m->ssm_buf + (size_t)(1 - m->src) * sz + off;for (uint32_t t = 0; t < m->replay + a->n; t++) {if (t == m->replay) {- memcpy(D, M, (size_t)SSM_ROWS * ds * sizeof(uint16_t));+ if (M != D) /* not a call going on from the one before */+ memcpy(D, M, (size_t)SSM_ROWS * ds * sizeof(uint16_t));M = D;}const float *co = m->conv_out + (size_t)t * cc;@@ -243,12 +246,46 @@ static void gate_worker(void *arg, int tid, int n_threads)}}+/* Qwen3.5's betas then alphas: item = token, each dot as one thread alone+ would make it (the same bits whatever the threads) */+struct ba_job {+ struct janas_llm_model *m;+ const struct layer *ly;+ const float *xn;+ uint32_t n;+};++static void ba_worker(void *arg, int tid, int n_threads)+{+ struct ba_job *b = arg;+ struct janas_llm_model *m = b->m;+ uint32_t dm = m->d_model, nv = m->n_vh;+ const float *wb = b->ly->ssm_beta, *wa = b->ly->ssm_alpha;+ for (uint32_t j = (uint32_t)tid; j < b->n; j += (uint32_t)n_threads)+ for (uint32_t h = 0; h < nv; h++) {+ const float *xj = b->xn + (size_t)j * dm;+ m->ba[(size_t)j * 2 * nv + h] =+ janas_dot_f32(wb + (size_t)h * dm, xj, dm);+ m->ba[(size_t)j * 2 * nv + nv + h] =+ janas_dot_f32(wa + (size_t)h * dm, xj, dm);+ }+}++void janas_m_rec_ba(struct janas_llm_model *m, const struct layer *ly,+ const float *xn, uint32_t n)+{+ struct ba_job b = {m, ly, xn, n};+ if (n < 2)+ ba_worker(&b, 0, 1);+ else+ janas_pool_run(m->compute, ba_worker, &b);+}+/* Gated DeltaNet layer on the normalized block in xn / xq; added to x. */void janas_m_rec_layer(struct janas_llm_model *m, const struct layer *ly,uint32_t n){- uint32_t dm = m->d_model, ds = m->ds, nv = m->n_vh, rf = nv / m->n_kh;- uint32_t kd = m->n_kh * ds, cc = m->conv_ch, gsz = 2 * ds + 2 * ds * rf;+ uint32_t dm = m->d_model, nv = m->n_vh, cc = m->conv_ch;size_t nbi = m->d_inner / JANAS_QK;double ta = now();if (m->a->rec == JANAS_REC_Q35) {@@ -269,17 +306,9 @@ void janas_m_rec_layer(struct janas_llm_model *m, const struct layer *ly,.cols = dm,.n_vec = n,.y_stride = m->qkvz_dim}};- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, t, 2);+ janas_m_products(m, janas_m_gpu(m, 0), t, 2);/* beta then alpha per head, as in the grouped layout's order */- const float *wb = ly->ssm_beta, *wa = ly->ssm_alpha;- for (uint32_t j = 0; j < n; j++)- for (uint32_t h = 0; h < nv; h++) {- const float *xj = m->xn + (size_t)j * dm;- m->ba[(size_t)j * 2 * nv + h] =- janas_dot_f32(wb + (size_t)h * dm, xj, dm);- m->ba[(size_t)j * 2 * nv + nv + h] =- janas_dot_f32(wa + (size_t)h * dm, xj, dm);- }+ janas_m_rec_ba(m, ly, m->xn, n);} else if (ly->ssm_qkv) {/* qwen3next as llama.cpp writes it since 2026: q|k|v and z as forqwen35, the betas and alphas fused and grouped as before */@@ -306,7 +335,7 @@ void janas_m_rec_layer(struct janas_llm_model *m, const struct layer *ly,.rows = 2 * nv,.cols = dm,.n_vec = n}};- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, t, 3);+ janas_m_products(m, janas_m_gpu(m, 0), t, 3);} else {struct janas_matvec_task t[2] = {{.type = (int)ly->ssm_in->type,.w = data(m, ly->ssm_in),@@ -322,8 +351,33 @@ void janas_m_rec_layer(struct janas_llm_model *m, const struct layer *ly,.rows = 2 * nv,.cols = dm,.n_vec = n}};- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, t, 2);+ janas_m_products(m, janas_m_gpu(m, 0), t, 2);}+ janas_m_rec_core(m, ly, n, ta);+ double tc = now();+ for (uint32_t j = 0; j < n; j++)+ janas_q8k_quantize(m->att + (size_t)j * m->d_inner, m->attq + j * nbi,+ m->d_inner);+ struct janas_matvec_task to = {.type = (int)ly->ssm_out->type,+ .w = data(m, ly->ssm_out),+ .x = m->attq,+ .y = m->xn,+ .rows = dm,+ .cols = m->d_inner,+ .n_vec = n};+ janas_m_products(m, janas_m_gpu(m, 0), &to, 1);+ trace_row(m, "ssm_out", m->xn + (size_t)(n - 1) * dm, dm);+ for (uint32_t i = 0; i < n * dm; i++)+ m->x[i] += m->xn[i];+ trace_row(m, "residual", m->x + (size_t)(n - 1) * dm, dm);+ m->phase[JANAS_PH_WO] += now() - tc;+}++void janas_m_rec_core(struct janas_llm_model *m, const struct layer *ly,+ uint32_t n, double ta)+{+ uint32_t ds = m->ds, nv = m->n_vh, rf = nv / m->n_kh;+ uint32_t kd = m->n_kh * ds, cc = m->conv_ch, gsz = 2 * ds + 2 * ds * rf;/* per key head g the projection holds q, k, the values and the z gatesof its rf value heads, then per g: rf betas and rf alphas */const float *dt = f32(m, ly->dt_bias), *A = f32(m, ly->ssm_a);@@ -418,22 +472,5 @@ void janas_m_rec_layer(struct janas_llm_model *m, const struct layer *ly,memcpy(lb, m->beta + (size_t)a * nv, (size_t)n * nv * sizeof(float));memcpy(ld, m->decay + (size_t)a * nv, (size_t)n * nv * sizeof(float));}- double tc = now();- m->phase[JANAS_PH_SSM] += tc - tb;- for (uint32_t j = 0; j < n; j++)- janas_q8k_quantize(m->att + (size_t)j * m->d_inner, m->attq + j * nbi,- m->d_inner);- struct janas_matvec_task to = {.type = (int)ly->ssm_out->type,- .w = data(m, ly->ssm_out),- .x = m->attq,- .y = m->xn,- .rows = dm,- .cols = m->d_inner,- .n_vec = n};- janas_gpu_matvec_group(janas_m_gpu(m, 0), m->compute, &to, 1);- trace_row(m, "ssm_out", m->xn + (size_t)(n - 1) * dm, dm);- for (uint32_t i = 0; i < n * dm; i++)- m->x[i] += m->xn[i];- trace_row(m, "residual", m->x + (size_t)(n - 1) * dm, dm);- m->phase[JANAS_PH_WO] += now() - tc;+ m->phase[JANAS_PH_SSM] += now() - tb;}diff --git a/src/llm/model_state.c b/src/llm/model_state.cindex 64ee241..67056a9 100644--- a/src/llm/model_state.c+++ b/src/llm/model_state.c@@ -18,6 +18,8 @@#include "model_impl.h"+#include "expert_cache.h"+struct janas_llm_state {uint32_t n; /* positions 0 .. n - 1 */uint32_t n_slots; /* KV slots (attention layers, the MTP block's) */@@ -407,3 +409,18 @@ struct janas_llm_state *janas_llm_state_read(const struct janas_llm_model *m,}return st;}++void janas_llm_model_memory(const struct janas_llm_model *m, uint64_t *resident,+ uint64_t *cache, uint64_t *kv)+{+ uint64_t r = m->j.h.resident_bytes;+ if (m->ple_tok && m->ple_tok->offset >= m->j.h.resident_offset &&+ m->ple_tok->bytes < r)+ r -= m->ple_tok->bytes;+ uint64_t c = 0;+ if (m->cache)+ janas_expert_cache_arena(m->cache, &c);+ *resident = r;+ *cache = c;+ *kv = 2 * ((uint64_t)m->kv_bytes + m->ks_bytes);+}diff --git a/src/llm/model_tune.c b/src/llm/model_tune.cindex 4727b01..12a47f2 100644--- a/src/llm/model_tune.c+++ b/src/llm/model_tune.c@@ -18,6 +18,7 @@#include "common/pool.h"#include "common/sysinfo.h"#include "deltanet.h"+#include "common/devices.h"#include "tuner.h"#include "gpu.h"#include "matvec.h"@@ -26,6 +27,78 @@#include "model_impl.h"+/* a mask's combinations without the NPU: what they are in the passes it+ does not take */+static int without_npu(int mask)+{+ int out = 0;+ for (int c = 0; c < JANAS_DEV_COMBOS; c++)+ if (mask >> c & 1)+ out |= 1 << (c & ~JANAS_DEV_NPU);+ return out;+}++/*+ * The user's devices for each kind of pass (--prompt-on, --drafts-on,+ * --reply-on; common/devices.h), in on[] in the order of+ * janas_devices_vars, as far as this machine has them and the pass can use+ * them. The NPU takes blocks only (JANAS_TUNE_BLOCK tokens and more): for+ * the other passes a combination with it is the rest of it, said where it+ * was asked for those passes alone. Prompts kept off the GPU keep its fast+ * prompt off them too; replies asked of it give it single tokens, which an+ * integrated one does not take by default. A device that is not here: the+ * engine chooses, and says why.+ */+static void user_devices(struct janas_llm_model *m, int on[])+{+ static const char *const what[JANAS_DEVICES_OPTIONS] = {"prompts", "drafts",+ "replies"};+ int gpu_here = m->gpu && !m->gpu_off,+ have = 1 | (gpu_here ? 1 << JANAS_DEV_GPU : 0) |+ (m->npu ? 1 << JANAS_DEV_NPU : 0) |+ (gpu_here && m->npu ? 1 << (JANAS_DEV_GPU | JANAS_DEV_NPU) : 0);+ for (int k = 0; k < JANAS_DEVICES_OPTIONS; k++) {+ const char *var = janas_devices_vars[k];+ char why[200], nm[64];+ int mask = janas_devices_mask(getenv(var), why, sizeof why), asked = 0;+ if (mask < 0) {+ fprintf(stderr, "janas: %s: %s; the engine chooses\n", var, why);+ mask = 0;+ }+ for (int c = 0; c < JANAS_DEV_COMBOS; c++)+ asked |= mask >> c & 1 ? c : 0;+ janas_devices_name(mask, nm, sizeof nm);+ if (mask && !(mask & have)) {+ fprintf(stderr,+ "janas: %s=%s: not on this machine; the engine chooses\n",+ var, nm);+ if (asked & JANAS_DEV_GPU && !gpu_here)+ fprintf(stderr, "janas: GPU: %s\n",+ m->gpu ? "it cannot share the model's memory"+ : m->gpu_why);+ if (asked & JANAS_DEV_NPU && !m->npu)+ fprintf(stderr, "janas: NPU: %s\n", m->npu_why);+ mask = 0;+ }+ mask &= mask ? have : 0;+ if (k > 0 && asked & JANAS_DEV_NPU && mask) {+ char rest[64];+ mask = without_npu(mask);+ janas_devices_name(mask, rest, sizeof rest);+ fprintf(stderr,+ "janas: %s=%s: the NPU takes passes of %d tokens and more "+ "only; %s on %s\n",+ var, nm, JANAS_TUNE_BLOCK, what[k], rest);+ }+ on[k] = mask;+ }+ m->prompts_off_gpu =+ on[0] &&+ !(on[0] & (1 << JANAS_DEV_GPU | 1 << (JANAS_DEV_GPU | JANAS_DEV_NPU)));+ if (on[2] >> JANAS_DEV_GPU & 1 && janas_gpu_min_n(m->gpu) > 1)+ janas_gpu_set_min_n(m->gpu, 1);+}+/** The tuner's candidates: every usable core - the performance cores with* all their threads and the efficiency cores, not the low-power island,@@ -55,17 +128,24 @@ void janas_m_init_tuner(struct janas_llm_model *m)int block = bt && atoi(bt) > 0 ? atoi(bt) : m->all_threads;if (block > m->all_threads)block = m->all_threads;- for (int gpu = 0; gpu <= (m->gpu && !m->gpu_off ? 1 : 0); gpu++)- for (int i = 0; i < n_opts; i++) {- int dup = 0;- for (int k = 0; k < n; k++)- dup |= c[k].threads == opts[i] && c[k].gpu == gpu;- if (!dup && n < JANAS_TUNE_MAX_CANDS)- c[n++] =- (struct janas_tune_cand){.threads = opts[i], .gpu = gpu};- }+ /* with an NPU every candidate with it too, for blocks only (tuner.c):+ the defaults stay without, unless the user asks for it */+ for (int npu = 0; npu <= (m->npu ? 1 : 0); npu++)+ for (int gpu = 0; gpu <= (m->gpu && !m->gpu_off ? 1 : 0); gpu++)+ for (int i = 0; i < n_opts; i++) {+ int dup = 0;+ for (int k = 0; k < n; k++)+ dup |= c[k].threads == opts[i] && c[k].gpu == gpu &&+ c[k].npu == npu;+ if (!dup && n < JANAS_TUNE_MAX_CANDS)+ c[n++] = (struct janas_tune_cand){+ .threads = opts[i], .gpu = gpu, .npu = npu};+ }+ int on[JANAS_DEVICES_OPTIONS];+ user_devices(m, on);+ memcpy(m->dev_on, on, sizeof m->dev_on);int def[JANAS_TUNE_CLASSES] = {0, 0, 0, 0};- for (int k = 0; k < n; k++) {+ for (int k = 0; k < n && !c[k].npu; k++) {if (!c[k].gpu && c[k].threads == m->all_threads)def[0] = k;if (!c[k].gpu && c[k].threads == block)@@ -79,26 +159,56 @@ void janas_m_init_tuner(struct janas_llm_model *m)of 12 models the fastest blocks were on 6 or 12 threads 11 times,Qwen3.5-2B 318 tokens/s on 6 and 309 on 12 against 272 on 20 (10 Oct2026) */- int fast = m->gpu && !m->gpu_off && janas_gpu_fast_prompt() && !bt;- if (fast)+ /* the same with the NPU asked for blocks: it computes nearly all of+ one too (Qwen3-4B in whole layers, the threads spinning while they+ waited: 270.6 tokens/s on 6 threads, 262.0 on 12, 252.1 on 20; once+ they slept, 325.5 on 6 and 320.4 on 12; 20 Oct 2026) */+ int fast = m->gpu && !m->gpu_off && janas_gpu_fast_prompt() && !bt &&+ !m->prompts_off_gpu,+ npu_asked =+ on[0] & (1 << JANAS_DEV_NPU | 1 << (JANAS_DEV_GPU | JANAS_DEV_NPU));+ if (fast || (npu_asked && !bt))for (int k = 0; k < n; k++)- if (!c[k].gpu && c[k].threads == m->p_threads)+ if (!c[k].gpu && !c[k].npu && c[k].threads == m->p_threads)def[2] = k;const char *ga = getenv("JANAS_GPU_ALWAYS");if (ga && atoi(ga) > 0)for (int k = 0; k < n; k++)- if (c[k].gpu && c[k].threads == block)+ if (c[k].gpu && !c[k].npu && c[k].threads == block)def[1] = def[2] = def[3] = k;+ /* JANAS_NPU_ALWAYS=1: the blocks' default with the NPU (tests: with+ JANAS_TUNE=0 every block then runs with it) */+ const char *na = getenv("JANAS_NPU_ALWAYS");+ if (na && atoi(na) > 0 && m->npu)+ for (int k = 0; k < n; k++)+ if (c[k].npu && c[k].threads == c[def[2]].threads &&+ c[k].gpu == c[def[2]].gpu) {+ def[2] = k;+ break;+ }if (bt && block != c[def[1]].threads && n < JANAS_TUNE_MAX_CANDS) {c[n] = (struct janas_tune_cand){.threads = block, .gpu = 0};def[1] = def[2] = def[3] = n++;}janas_tuner_init(&m->tuner, c, n, def, (tn && atoi(tn) == 0) || bt);janas_tuner_allow_gpu(&m->tuner, 1);- /* a GPU that takes single tokens (a discrete one) is tried for replies- too, and kept only if it measures faster */+ /* a GPU that takes single tokens (a discrete one, or one the user+ asked for replies) is tried for replies too, and kept only if it+ measures faster */int one = m->gpu && !m->gpu_off && janas_gpu_min_n(m->gpu) <= 1;janas_tuner_allow_gpu_one(&m->tuner, one);+ /* the user's devices: prompts' blocks and short turns (no NPU there),+ drafts, replies */+ /* the NPU for blocks by itself only where its answers measured at par+ (janas_m_npu_auto); elsewhere when asked */+ const char *nal = getenv("JANAS_NPU_ALWAYS");+ int blocks = on[0];+ if (m->npu && !blocks && !(nal && atoi(nal) > 0) && !janas_m_npu_auto(m))+ blocks = 1 | (m->gpu && !m->gpu_off ? 1 << JANAS_DEV_GPU : 0);+ janas_tuner_allow(&m->tuner, 2, blocks);+ janas_tuner_allow(&m->tuner, 3, without_npu(on[0]));+ janas_tuner_allow(&m->tuner, 1, on[1]);+ janas_tuner_allow(&m->tuner, 0, on[2]);/* the saved choices of this machine and model; "1g" in the key whenthe GPU may take replies, so that choices saved without it do notstand in for the tries */@@ -110,9 +220,14 @@ void janas_m_init_tuner(struct janas_llm_model *m)cpu, m->p_cores, m->p_threads, m->all_threads,m->gpu && !m->gpu_off ? janas_gpu_name(m->gpu) : "no GPU",one ? " 1g" : "", fast ? " f" : "", name);+ /* the user's devices, when chosen: their own saved choices */+ if ((on[0] || on[1] || on[2]) && w > 0 && (size_t)w < sizeof(m->tune_key))+ w += snprintf(m->tune_key + w, sizeof(m->tune_key) - (size_t)w,+ "on %x%x%x|", on[0], on[1], on[2]);for (int k = 0; k < n && w > 0 && (size_t)w < sizeof(m->tune_key); k++)- w += snprintf(m->tune_key + w, sizeof(m->tune_key) - (size_t)w, "%d%s,",- c[k].threads, c[k].gpu ? "g" : "");+ w += snprintf(m->tune_key + w, sizeof(m->tune_key) - (size_t)w,+ "%d%s%s,", c[k].threads, c[k].gpu ? "g" : "",+ c[k].npu ? "n" : "");janas_tuner_load(&m->tuner, m->tune_key);}@@ -130,6 +245,8 @@ void janas_m_apply_candidate(struct janas_llm_model *m, int cand, uint32_t nv)if (m->own_compute)janas_pool_set_active(m->compute, m->tuner.cand[cand].threads);m->gpu_use = m->tuner.cand[cand].gpu;+ m->npu_use = m->tuner.cand[cand].npu;+ janas_m_npu_awake(m, nv);if (m->gpu) {janas_gpu_keep_awake(m->gpu,m->gpu_use && (nv >= janas_gpu_min_n(m->gpu) ||@@ -159,7 +276,17 @@ int janas_llm_model_threads(const struct janas_llm_model *m, int cls)int janas_llm_model_gpu_prompts(const struct janas_llm_model *m){return m->gpu && !m->gpu_off && m->tuner.allow_gpu &&- janas_gpu_fast_prompt();+ janas_gpu_fast_prompt() && !m->prompts_off_gpu;+}++int janas_llm_model_devices(const struct janas_llm_model *m, int cls)+{+ /* the user's: the tuner's own limits (janas_m_npu_auto) apart */+ return cls == 2 ? m->dev_on[0]+ : cls == 3 ? without_npu(m->dev_on[0])+ : cls == 1 ? m->dev_on[1]+ : cls == 0 ? m->dev_on[2]+ : 0;}int janas_llm_model_gpu_used(const struct janas_llm_model *m)@@ -175,13 +302,24 @@ int janas_llm_model_gpu_used(const struct janas_llm_model *m)return used;}+int janas_llm_model_npu_used(const struct janas_llm_model *m)+{+ int used = 0;+ for (int k = 0; m->npu && k < JANAS_TUNE_CLASSES; k++)+ if (m->tuner.cand[janas_tuner_best(&m->tuner, k)].npu)+ used |= 1 << k;+ return used;+}+int janas_llm_model_candidates(const struct janas_llm_model *m, int *threads,- int *gpu, int max)+ int *gpu, int *npu, int max){int n = m->tuner.n_cand < max ? m->tuner.n_cand : max;for (int i = 0; i < n; i++) {threads[i] = m->tuner.cand[i].threads;gpu[i] = m->tuner.cand[i].gpu;+ if (npu)+ npu[i] = m->tuner.cand[i].npu;}return n;}diff --git a/src/llm/quant.c b/src/llm/quant.cindex 3c4a9c7..31e2ff5 100644--- a/src/llm/quant.c+++ b/src/llm/quant.c@@ -4,6 +4,7 @@* quant.c - quantized block formats and dot-product kernels (see quant.h).*/#include "quant.h"+#include "quant_q6kp.h"#include "vmath.h"#include "iq3s_grid.h"@@ -571,14 +572,6 @@ float janas_q6k_dot_ref(const struct janas_block_q6k *w,return acc;}-/* Byte of weight v in a two-bit plane, and the shift of its bits. */-static inline int q6kp_index(int v, int *shift)-{- int n = v / 128, part = (v % 128) / 32, l = v % 32;- *shift = 2 * part;- return 32 * n + l;-}-void janas_q6k_to_planes(const struct janas_block_q6k *src, size_t nb,struct janas_block_q6kp *base, uint8_t *p1,uint8_t *p0)@@ -624,21 +617,6 @@ void janas_q6kp_to_q6k(const struct janas_block_q6kp *base, const uint8_t *p1,}}-/* Twice the value weight v stands for, at the level the planes give. */-static inline int q6kp_value2(const struct janas_block_q6kp *b,- const uint8_t *a1, const uint8_t *a0, int v,- int level)-{- int sh, i = q6kp_index(v, &sh);- int q = (b->q[i] >> sh) & 3;- if (level >= 2)- q = (q << 2) | ((a1[i] >> sh) & 3);- if (level >= 3)- q = (q << 2) | ((a0[i] >> sh) & 3);- /* the centre of the range the missing bits cover: half a step */- return level == 3 ? 2 * q : level == 2 ? 8 * q + 3 : 32 * q + 15;-}-void janas_q6kp_dequantize(const struct janas_block_q6kp *base,const uint8_t *p1, const uint8_t *p0, float *y,size_t n)@@ -1352,6 +1330,7 @@ size_t janas_qtype_block_size(int type){switch (type) {case JANAS_Q6_K_P:+ case JANAS_Q6_K_PN:return sizeof(struct janas_block_q6kp);case JANAS_Q4_K:return sizeof(struct janas_block_q4k);diff --git a/src/llm/quant.h b/src/llm/quant.hindex e55808c..8a30bab 100644--- a/src/llm/quant.h+++ b/src/llm/quant.h@@ -219,7 +219,16 @@ enum janas_qtype {/* Janas' own, outside the GGUF numbering: the high plane of a Q6_K rowcut into bit planes. Its block size counts that plane alone; the othertwo are JANAS_Q6KP_PLANE bytes each and are passed separately. */- JANAS_Q6_K_P = 214+ JANAS_Q6_K_P = 214,+ /* Janas' own too: a down matrix by neuron, its rows the neurons (each+ its outputs, of the model's width) stored by block of 256 outputs -+ every neuron's block 0, then every neuron's block 1 - in Q6_K's bit+ planes laid out as JANAS_Q6_K_P's, after a float per output channel+ that multiplies the sum (tools/jns_neurons.c): read a neuron at a time,+ at the depth its contribution earns (janas_q6kpn_axpy). The block size+ counts the base plane alone, as JANAS_Q6_K_P's; the matrix's bytes add+ the channels' floats. */+ JANAS_Q6_K_PN = 215};/* Bytes of one 256-weight block of the type, 0 if unsupported. */@@ -346,6 +355,38 @@ void janas_q6kp_to_q6k(const struct janas_block_q6kp *base, const uint8_t *p1,void janas_q6kp_dequantize(const struct janas_block_q6kp *base,const uint8_t *p1, const uint8_t *p0, float *y,size_t n);+/* n floats (n a multiple of JANAS_QK) as Q6_K: each group of 16 its scale,+ chosen among a few near its largest magnitude for the least squared+ error, the block's factor then fitted by least squares (quant_q6k.c). */+void janas_q6k_quantize(const float *x, struct janas_block_q6k *y, size_t n);+/* y[0 .. n) += h times a row of n weights in Q6_K's bit planes read at a+ level - 3 the three planes, 2 the base and p1, 1 the base alone; the+ planes below the level may be NULL - the same values as+ janas_q6kp_dequantize: a row of JANAS_Q6_K_PN, one neuron's outputs. */+void janas_q6kpn_axpy(const struct janas_block_q6kp *base, const uint8_t *p1,+ const uint8_t *p0, int level, float h, float *y,+ size_t n);+/* The same without vector instructions, bit for bit: the reference. */+void janas_q6kpn_axpy_ref(const struct janas_block_q6kp *base,+ const uint8_t *p1, const uint8_t *p0, int level,+ float h, float *y, size_t n);+/* The down by neuron in integers: n <= JANAS_PN_CHUNK neurons of a matrix+ of `rows` neurons stored by block of outputs (block b of neuron j at+ base + b * rows + j, its planes at the same index of p1 and p0), neuron+ i = js[i] read at level lv[i] (1 to 3) with activation h[i]; their block+ b of 256 outputs added to y[0 .. 256). The factors h d sc are+ quantized to eight bits over the chunk, as the products by rows quantize+ their activations, and the sums are exact integers: janas_q6kpn_chunk_ref,+ without vector instructions, gives the same bits. */+#define JANAS_PN_CHUNK 128+void janas_q6kpn_chunk(const struct janas_block_q6kp *base, const uint8_t *p1,+ const uint8_t *p0, size_t rows, const uint32_t *js,+ const uint8_t *lv, const float *h, uint32_t n, size_t b,+ float *y);+void janas_q6kpn_chunk_ref(const struct janas_block_q6kp *base,+ const uint8_t *p1, const uint8_t *p0, size_t rows,+ const uint32_t *js, const uint8_t *lv,+ const float *h, uint32_t n, size_t b, float *y);float janas_q6kp_dot(const struct janas_block_q6kp *w, const uint8_t *p1,const uint8_t *p0, const struct janas_block_q8k *x,size_t nb);diff --git a/src/llm/quant_pn.h b/src/llm/quant_pn.hnew file mode 100644index 0000000..fe6fd45--- /dev/null+++ b/src/llm/quant_pn.h@@ -0,0 +1,206 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * quant_pn.h - the down by neuron in integers (janas_q6kpn_chunk, quant.h),+ * private to quant_q6k.c, which includes it once per instruction set. The+ * includer defines:+ * PN(name) the name with the instruction-set suffix+ * PN_TARGET the function attribute selecting the instructions+ * PN_DOT(acc, u, s) acc + the unsigned bytes u times the signed bytes s,+ * summed four by four into int32 lanes: maddubs, madd+ * and add on AVX2 (the pairs stay under 2 x 127 x 127,+ * never saturating), a single vpdpbusd on AVX-VNNI+ * The sums are exact integers and the float operations the reference's,+ * in its order: every variant gives janas_q6kpn_chunk_ref's bits.+ *+ * A half of the block at a time, each neuron's values on the scale of+ * 0..127 whose 64 is zero (q6kp_value2) are unpacked once into a buffer -+ * one branch on the level a neuron, none inside - then the neurons go four+ * at a time, interleaved so that a 32-bit lane holds the four neurons'+ * values of one output, the four neurons' factors of that output's group+ * of 16 beside them. Unpacking within 128-bit lanes leaves outputs 0-3 and+ * 16-19 in the first register, 4-7 and 20-23 in the second, and so on: the+ * low lanes are one group, the high lanes the next, and the sums are put+ * back in order at the end.+ */++/* Neuron i's values in half nh of the block, 128 bytes, at its level. A+ part's two bits sit at bits 2p and 2p + 1 of the planes' bytes: masked+ in place, then shifted to where they weigh in 2v (bits 5, 3, 1 of the+ base, p1, p0), 8v + 3 or 32v + 15, so that no byte carries into the+ next. */+#define PN_L(pl, m, n) _mm256_slli_epi16(_mm256_and_si256(pl, m), n)+#define PN_R(pl, m, n) _mm256_srli_epi16(_mm256_and_si256(pl, m), n)+#define PN_OR3(a, b, c) _mm256_or_si256(_mm256_or_si256(a, b), c)+#define PN_ST(at, v) _mm256_storeu_si256((__m256i *)(void *)(w + (at)), v)++static inline PN_TARGET __attribute__((always_inline)) void+PN(unpack)(const uint8_t *q, const uint8_t *a1, const uint8_t *a0, int lv,+ uint8_t *w)+{+ const __m256i m0 = _mm256_set1_epi8(0x03), m1 = _mm256_set1_epi8(0x0c);+ const __m256i m2 = _mm256_set1_epi8(0x30),+ m3 = _mm256_set1_epi8((char)0xc0);+ __m256i b = _mm256_loadu_si256((const __m256i *)(const void *)q);+ if (lv >= 3) {+ __m256i x1 = _mm256_loadu_si256((const __m256i *)(const void *)a1);+ __m256i x0 = _mm256_loadu_si256((const __m256i *)(const void *)a0);+ PN_ST(0, PN_OR3(PN_L(b, m0, 5), PN_L(x1, m0, 3), PN_L(x0, m0, 1)));+ PN_ST(32, PN_OR3(PN_L(b, m1, 3), PN_L(x1, m1, 1), PN_R(x0, m1, 1)));+ PN_ST(64, PN_OR3(PN_L(b, m2, 1), PN_R(x1, m2, 1), PN_R(x0, m2, 3)));+ PN_ST(96, PN_OR3(PN_R(b, m3, 1), PN_R(x1, m3, 3), PN_R(x0, m3, 5)));+ } else if (lv == 2) {+ __m256i x1 = _mm256_loadu_si256((const __m256i *)(const void *)a1);+ const __m256i o = _mm256_set1_epi8(3);+ PN_ST(0, PN_OR3(PN_L(b, m0, 5), PN_L(x1, m0, 3), o));+ PN_ST(32, PN_OR3(PN_L(b, m1, 3), PN_L(x1, m1, 1), o));+ PN_ST(64, PN_OR3(PN_L(b, m2, 1), PN_R(x1, m2, 1), o));+ PN_ST(96, PN_OR3(PN_R(b, m3, 1), PN_R(x1, m3, 3), o));+ } else {+ const __m256i o = _mm256_set1_epi8(15);+ PN_ST(0, _mm256_or_si256(PN_L(b, m0, 5), o));+ PN_ST(32, _mm256_or_si256(PN_L(b, m1, 3), o));+ PN_ST(64, _mm256_or_si256(PN_L(b, m2, 1), o));+ PN_ST(96, _mm256_or_si256(PN_R(b, m3, 1), o));+ }+}+#undef PN_L+#undef PN_R+#undef PN_OR3+#undef PN_ST++static PN_TARGET void PN(q6kpn_chunk)(const struct janas_block_q6kp *base,+ const uint8_t *p1, const uint8_t *p0,+ size_t rows, const uint32_t *js,+ const uint8_t *lv, const float *h,+ uint32_t n, size_t b, float *y)+{+ const struct janas_block_q6kp *blk[JANAS_PN_CHUNK];+ const uint8_t *a1[JANAS_PN_CHUNK], *a0[JANAS_PN_CHUNK];+ float u[JANAS_PN_CHUNK], t = 0.0f;+ if (n > JANAS_PN_CHUNK)+ n = JANAS_PN_CHUNK;+ for (uint32_t i = 0; i < n; i++) {+ size_t at = b * rows + js[i];+ blk[i] = base + at;+ a1[i] = lv[i] >= 2 ? p1 + at * JANAS_Q6KP_PLANE : NULL;+ a0[i] = lv[i] >= 3 ? p0 + at * JANAS_Q6KP_PLANE : NULL;+ /* fp16 to float is exact, as the reference's */+ u[i] = h[i] * (_cvtsh_ss(blk[i]->d) * 0.5f);+ if (fabsf(u[i]) > t)+ t = fabsf(u[i]);+ }+ if (!(t > 0.0f))+ return;+ float inv = 127.0f / (t * 128.0f), f = t * 128.0f / 127.0f;++ /* the factors u sc to eight bits - |u inv| <= 127/128 and |sc| <= 128,+ so within -127 .. 127 - by quads: aq[q][g] the four neurons' bytes+ of group g; and each group's sum of them */+ uint32_t nq = (n + 3) / 4;+ uint32_t aq[JANAS_PN_CHUNK / 4][16];+ __m256i s0 = _mm256_setzero_si256(), s1 = _mm256_setzero_si256();+ for (uint32_t q = 0; q < nq; q++) {+ __m128i r[4];+ for (uint32_t k = 0; k < 4; k++) {+ uint32_t i = 4 * q + k;+ if (i >= n) {+ r[k] = _mm_setzero_si128();+ continue;+ }+ __m256 kk = _mm256_set1_ps(u[i] * inv);+ __m128i sc =+ _mm_loadu_si128((const __m128i *)(const void *)blk[i]->scales);+ __m256i lo = _mm256_cvtps_epi32(_mm256_mul_ps(+ kk, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(sc))));+ __m256i hi = _mm256_cvtps_epi32(+ _mm256_mul_ps(kk, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(+ _mm_srli_si128(sc, 8)))));+ s0 = _mm256_add_epi32(s0, lo);+ s1 = _mm256_add_epi32(s1, hi);+ __m256i p =+ _mm256_permute4x64_epi64(_mm256_packs_epi32(lo, hi), 0xd8);+ r[k] = _mm_packs_epi16(_mm256_castsi256_si128(p),+ _mm256_extracti128_si256(p, 1));+ }+ __m128i t0 = _mm_unpacklo_epi8(r[0], r[1]),+ t1 = _mm_unpackhi_epi8(r[0], r[1]);+ __m128i t2 = _mm_unpacklo_epi8(r[2], r[3]),+ t3 = _mm_unpackhi_epi8(r[2], r[3]);+ _mm_storeu_si128((__m128i *)(void *)&aq[q][0],+ _mm_unpacklo_epi16(t0, t2));+ _mm_storeu_si128((__m128i *)(void *)&aq[q][4],+ _mm_unpackhi_epi16(t0, t2));+ _mm_storeu_si128((__m128i *)(void *)&aq[q][8],+ _mm_unpacklo_epi16(t1, t3));+ _mm_storeu_si128((__m128i *)(void *)&aq[q][12],+ _mm_unpackhi_epi16(t1, t3));+ }+ int32_t sum[16];+ _mm256_storeu_si256((__m256i *)(void *)sum, s0);+ _mm256_storeu_si256((__m256i *)(void *)(sum + 8), s1);++ /* a half's values, a row of 128 bytes a neuron; the rows past n of the+ last quad are zero (their factors are) */+ uint8_t w[JANAS_PN_CHUNK * 128];+ for (uint32_t i = n; i < 4 * nq; i++)+ memset(w + (size_t)i * 128, 0, 128);+ const __m256 vf = _mm256_set1_ps(f);+ for (int nh = 0; nh < 2; nh++) {+ for (uint32_t i = 0; i < n; i++)+ PN(unpack)(blk[i]->q + 32 * nh, a1[i] ? a1[i] + 32 * nh : NULL,+ a0[i] ? a0[i] + 32 * nh : NULL, lv[i],+ w + (size_t)i * 128);+ for (int part = 0; part < 4; part++) {+ int g = 8 * nh + 2 * part, v0 = 128 * nh + 32 * part;+ __m256i acc[4] = {_mm256_setzero_si256(), _mm256_setzero_si256(),+ _mm256_setzero_si256(), _mm256_setzero_si256()};+ const uint8_t *wp = w + 32 * part;+ for (uint32_t q = 0; q < nq; q++, wp += 4 * 128) {+ __m256i w0 =+ _mm256_loadu_si256((const __m256i *)(const void *)wp);+ __m256i w1 = _mm256_loadu_si256(+ (const __m256i *)(const void *)(wp + 128));+ __m256i w2 = _mm256_loadu_si256(+ (const __m256i *)(const void *)(wp + 256));+ __m256i w3 = _mm256_loadu_si256(+ (const __m256i *)(const void *)(wp + 384));+ __m256i ab_lo = _mm256_unpacklo_epi8(w0, w1),+ ab_hi = _mm256_unpackhi_epi8(w0, w1);+ __m256i cd_lo = _mm256_unpacklo_epi8(w2, w3),+ cd_hi = _mm256_unpackhi_epi8(w2, w3);+ __m256i c = _mm256_set_m128i(_mm_set1_epi32((int)aq[q][g + 1]),+ _mm_set1_epi32((int)aq[q][g]));+ acc[0] = PN_DOT(acc[0], _mm256_unpacklo_epi16(ab_lo, cd_lo), c);+ acc[1] = PN_DOT(acc[1], _mm256_unpackhi_epi16(ab_lo, cd_lo), c);+ acc[2] = PN_DOT(acc[2], _mm256_unpacklo_epi16(ab_hi, cd_hi), c);+ acc[3] = PN_DOT(acc[3], _mm256_unpackhi_epi16(ab_hi, cd_hi), c);+ }+ /* back in order, less 64 times the factors' sums: outputs 0-15+ of the 32 are group g, 16-31 group g + 1 */+ __m256i z0 = _mm256_set1_epi32(64 * sum[g]),+ z1 = _mm256_set1_epi32(64 * sum[g + 1]);+ __m256i r0 = _mm256_permute2x128_si256(acc[0], acc[1], 0x20);+ __m256i r1 = _mm256_permute2x128_si256(acc[2], acc[3], 0x20);+ __m256i r2 = _mm256_permute2x128_si256(acc[0], acc[1], 0x31);+ __m256i r3 = _mm256_permute2x128_si256(acc[2], acc[3], 0x31);+ float *o = y + v0;+ _mm256_storeu_ps(+ o, _mm256_fmadd_ps(vf,+ _mm256_cvtepi32_ps(_mm256_sub_epi32(r0, z0)),+ _mm256_loadu_ps(o)));+ _mm256_storeu_ps(+ o + 8, _mm256_fmadd_ps(+ vf, _mm256_cvtepi32_ps(_mm256_sub_epi32(r1, z0)),+ _mm256_loadu_ps(o + 8)));+ _mm256_storeu_ps(+ o + 16, _mm256_fmadd_ps(+ vf, _mm256_cvtepi32_ps(_mm256_sub_epi32(r2, z1)),+ _mm256_loadu_ps(o + 16)));+ _mm256_storeu_ps(+ o + 24, _mm256_fmadd_ps(+ vf, _mm256_cvtepi32_ps(_mm256_sub_epi32(r3, z1)),+ _mm256_loadu_ps(o + 24)));+ }+ }+}diff --git a/src/llm/quant_q6k.c b/src/llm/quant_q6k.cnew file mode 100644index 0000000..0c39d0d--- /dev/null+++ b/src/llm/quant_q6k.c@@ -0,0 +1,304 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * quant_q6k.c - Q6_K made from floats, and a row of Q6_K in bit planes added+ * to a vector at the depth asked: what Janas's down matrix by neuron+ * (JANAS_Q6_K_PN, tools/jns_neurons.c) is made of and read with.+ */+#include "quant.h"+#include "quant_q6kp.h"++#include <math.h>+#include <stdlib.h>+#include <string.h>++#if defined(__x86_64__)+#include <immintrin.h>+#endif++/* The integer of x at scale a, within Q6_K's -32 .. 31. */+static int q6(float x, float a)+{+ if (a == 0.0f)+ return 0;+ int q = (int)lrintf(x / a);+ return q < -32 ? -32 : q > 31 ? 31 : q;+}++/* The scale of a group of 16, among a few near its largest magnitude, of+ least squared error. */+static float group_scale(const float *x)+{+ float amax = 0.0f, ext = 0.0f;+ for (int i = 0; i < 16; i++)+ if (fabsf(x[i]) > amax) {+ amax = fabsf(x[i]);+ ext = x[i];+ }+ if (amax == 0.0f)+ return 0.0f;+ /* the largest one at the end of the range on its side: 31 up, 32 down */+ float a0 = ext > 0 ? amax / 31.0f : amax / 32.0f, best = a0;+ double best_err = -1;+ for (int k = -6; k <= 6; k++) {+ float a = a0 * (1.0f + 0.02f * (float)k);+ double err = 0;+ for (int i = 0; i < 16; i++) {+ double e = x[i] - a * (float)q6(x[i], a);+ err += e * e;+ }+ if (best_err < 0 || err < best_err) {+ best_err = err;+ best = a;+ }+ }+ return best;+}++void janas_q6k_quantize(const float *x, struct janas_block_q6k *y, size_t n)+{+ for (size_t b = 0; b < n / JANAS_QK; b++, x += JANAS_QK) {+ float a[16], amax = 0.0f;+ for (int s = 0; s < 16; s++) {+ a[s] = group_scale(x + 16 * s);+ if (a[s] > amax)+ amax = a[s];+ }+ uint16_t d16 = janas_fp32_to_fp16(amax / 127.0f);+ float d = janas_fp16_to_fp32(d16);+ int8_t sc[16];+ int q[JANAS_QK];+ for (int s = 0; s < 16; s++) {+ int v = d > 0 ? (int)lrintf(a[s] / d) : 0;+ sc[s] = (int8_t)(v > 127 ? 127 : v < 0 ? 0 : v);+ }+ /* the values under the factors, then the block's factor by least+ squares, x ~ d (sc q), twice */+ for (int it = 0; it < 3; it++) {+ for (int v = 0; v < JANAS_QK; v++)+ q[v] = q6(x[v], d * sc[v / 16]);+ if (it == 2)+ break;+ double sxu = 0, suu = 0;+ for (int v = 0; v < JANAS_QK; v++) {+ double u = (double)sc[v / 16] * q[v];+ sxu += x[v] * u;+ suu += u * u;+ }+ if (suu > 0 && sxu > 0) {+ d16 = janas_fp32_to_fp16((float)(sxu / suu));+ d = janas_fp16_to_fp32(d16);+ }+ }+ memset(y[b].ql, 0, sizeof(y[b].ql));+ memset(y[b].qh, 0, sizeof(y[b].qh));+ memcpy(y[b].scales, sc, sizeof(sc));+ y[b].d = d16;+ /* the bits where q6k_value (quant.c) reads them */+ for (int v = 0; v < JANAS_QK; v++) {+ int u = q[v] + 32, half = v / 128, part = (v % 128) / 32,+ l = v % 32;+ uint8_t *ql = y[b].ql + 64 * half + (part & 1) * 32 + l;+ *ql |= (uint8_t)((u & 0xf) << (part < 2 ? 0 : 4));+ y[b].qh[32 * half + l] |= (uint8_t)((u >> 4) << (2 * part));+ }+ }+}++/* One block of the row: y += hd times each weight's value, on the scale+ whose 64 is zero, times its group's factor - fused, as the vector one. */+static void axpy_block_ref(const struct janas_block_q6kp *b, const uint8_t *a1,+ const uint8_t *a0, int level, float hd, float *y)+{+ for (int v = 0; v < JANAS_QK; v++)+ y[v] = fmaf(hd * (float)b->scales[v / 16],+ (float)(q6kp_value2(b, a1, a0, v, level) - 64), y[v]);+}++#if defined(__x86_64__)+static int use_avx2, use_pn, use_vnni; /* use_pn: AVX2 and F16C */++/* Resolved before main, as quant.c's kernels; JANAS_KERNELS=avx2 leaves+ AVX-VNNI out here too. */+__attribute__((constructor)) static void q6k_init(void)+{+ __builtin_cpu_init();+ use_avx2 = __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma");+ const char *k = getenv("JANAS_KERNELS");+ use_pn = use_avx2 && __builtin_cpu_supports("f16c");+ use_vnni = use_pn && __builtin_cpu_supports("avxvnni") &&+ !(k && !strcmp(k, "avx2"));+}++/* The same, 32 weights at a time: a byte of a plane holds the two bits of+ four weights 32 apart (q6kp_index), so a part's shift and mask of the+ planes' 32 bytes give 32 consecutive weights; their values, less 64, in+ bytes that never carry; then floats, 8 at a time, times the factor of+ their group of 16. Bit for bit axpy_block_ref. */+__attribute__((target("avx2,fma"))) static void+axpy_block_avx2(const struct janas_block_q6kp *b, const uint8_t *a1,+ const uint8_t *a0, int level, float hd, float *y)+{+ const __m256i m3 = _mm256_set1_epi8(3);+ const __m256i off = _mm256_set1_epi8(level == 3 ? 64+ : level == 2 ? 61+ : 49);+ const __m128i up = _mm_cvtsi32_si128(level == 3 ? 1 : level == 2 ? 3 : 5);+ for (int n = 0; n < 2; n++) {+ __m256i q = _mm256_loadu_si256((const __m256i *)(b->q + 32 * n));+ __m256i p1 = level >= 2+ ? _mm256_loadu_si256((const __m256i *)(a1 + 32 * n))+ : _mm256_setzero_si256();+ __m256i p0 = level >= 3+ ? _mm256_loadu_si256((const __m256i *)(a0 + 32 * n))+ : _mm256_setzero_si256();+ for (int part = 0; part < 4; part++) {+ __m128i sh = _mm_cvtsi32_si128(2 * part);+ __m256i v = _mm256_and_si256(_mm256_srl_epi16(q, sh), m3);+ if (level >= 2)+ v = _mm256_or_si256(+ _mm256_slli_epi16(v, 2),+ _mm256_and_si256(_mm256_srl_epi16(p1, sh), m3));+ if (level >= 3)+ v = _mm256_or_si256(+ _mm256_slli_epi16(v, 2),+ _mm256_and_si256(_mm256_srl_epi16(p0, sh), m3));+ /* 2v - 64, 8v + 3 - 64, 32v + 15 - 64 (q6kp_value2) */+ v = _mm256_sub_epi8(_mm256_sll_epi16(v, up), off);+ int v0 = 128 * n + 32 * part;+ __m256 c0 = _mm256_set1_ps(hd * (float)b->scales[v0 / 16]);+ __m256 c1 = _mm256_set1_ps(hd * (float)b->scales[v0 / 16 + 1]);+ __m128i lo = _mm256_castsi256_si128(v),+ hi = _mm256_extracti128_si256(v, 1);+ __m256 w0 = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(lo));+ __m256 w1 =+ _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(lo, 8)));+ __m256 w2 = _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(hi));+ __m256 w3 =+ _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(hi, 8)));+ float *o = y + v0;+ _mm256_storeu_ps(o, _mm256_fmadd_ps(c0, w0, _mm256_loadu_ps(o)));+ _mm256_storeu_ps(o + 8,+ _mm256_fmadd_ps(c0, w1, _mm256_loadu_ps(o + 8)));+ _mm256_storeu_ps(o + 16,+ _mm256_fmadd_ps(c1, w2, _mm256_loadu_ps(o + 16)));+ _mm256_storeu_ps(o + 24,+ _mm256_fmadd_ps(c1, w3, _mm256_loadu_ps(o + 24)));+ }+ }+}+#endif++void janas_q6kpn_axpy(const struct janas_block_q6kp *base, const uint8_t *p1,+ const uint8_t *p0, int level, float h, float *y, size_t n)+{+ if (level < 1)+ return;+ for (size_t b = 0; b < n / JANAS_QK; b++, y += JANAS_QK) {+ const uint8_t *a1 = level >= 2 ? p1 + b * JANAS_Q6KP_PLANE : NULL;+ const uint8_t *a0 = level >= 3 ? p0 + b * JANAS_Q6KP_PLANE : NULL;+ float hd = h * (janas_fp16_to_fp32(base[b].d) * 0.5f);+#if defined(__x86_64__)+ if (use_avx2) {+ axpy_block_avx2(&base[b], a1, a0, level, hd, y);+ continue;+ }+#endif+ axpy_block_ref(&base[b], a1, a0, level, hd, y);+ }+}++void janas_q6kpn_axpy_ref(const struct janas_block_q6kp *base,+ const uint8_t *p1, const uint8_t *p0, int level,+ float h, float *y, size_t n)+{+ if (level < 1)+ return;+ for (size_t b = 0; b < n / JANAS_QK; b++, y += JANAS_QK)+ axpy_block_ref(&base[b], level >= 2 ? p1 + b * JANAS_Q6KP_PLANE : NULL,+ level >= 3 ? p0 + b * JANAS_Q6KP_PLANE : NULL, level,+ h * (janas_fp16_to_fp32(base[b].d) * 0.5f), y);+}++void janas_q6kpn_chunk_ref(const struct janas_block_q6kp *base,+ const uint8_t *p1, const uint8_t *p0, size_t rows,+ const uint32_t *js, const uint8_t *lv,+ const float *h, uint32_t n, size_t b, float *y)+{+ float u[JANAS_PN_CHUNK], t = 0.0f;+ if (n > JANAS_PN_CHUNK)+ n = JANAS_PN_CHUNK;+ /* the factors' common scale: the largest |h d / 2| times 128, the+ largest magnitude of an eight-bit scale */+ for (uint32_t i = 0; i < n; i++) {+ const struct janas_block_q6kp *w = base + b * rows + js[i];+ u[i] = h[i] * (janas_fp16_to_fp32(w->d) * 0.5f);+ if (fabsf(u[i]) > t)+ t = fabsf(u[i]);+ }+ if (!(t > 0.0f))+ return;+ float inv = 127.0f / (t * 128.0f), f = t * 128.0f / 127.0f;+ int8_t a[JANAS_PN_CHUNK][JANAS_QK / 16];+ int32_t sum[JANAS_QK / 16] = {0};+ for (uint32_t i = 0; i < n; i++) {+ const struct janas_block_q6kp *w = base + b * rows + js[i];+ float k = u[i] * inv;+ for (int g = 0; g < JANAS_QK / 16; g++) { /* within -127 .. 127 */+ long q = lrintf(k * (float)w->scales[g]);+ a[i][g] = (int8_t)q;+ sum[g] += (int32_t)q;+ }+ }+ /* each output: the integer sum over the neurons, less 64 times the+ factors' (the values' zero), times the scale */+ for (int v = 0; v < JANAS_QK; v++) {+ int32_t p = 0;+ for (uint32_t i = 0; i < n; i++) {+ size_t at = b * rows + js[i];+ const uint8_t *x1 = lv[i] >= 2 ? p1 + at * JANAS_Q6KP_PLANE : NULL;+ const uint8_t *x0 = lv[i] >= 3 ? p0 + at * JANAS_Q6KP_PLANE : NULL;+ p += a[i][v / 16] * q6kp_value2(base + at, x1, x0, v, lv[i]);+ }+ y[v] = fmaf(f, (float)(p - 64 * sum[v / 16]), y[v]);+ }+}++#if defined(__x86_64__)+/* The kernel proper: quant_pn.h, once for AVX2 and once for AVX-VNNI. */+#define PN(name) name##_avx2+#define PN_TARGET __attribute__((target("avx2,fma,f16c")))+#define PN_DOT(acc, u, s) \+ _mm256_add_epi32(acc, _mm256_madd_epi16(_mm256_maddubs_epi16(u, s), \+ _mm256_set1_epi16(1)))+#include "quant_pn.h"+#undef PN+#undef PN_TARGET+#undef PN_DOT++#define PN(name) name##_vnni+#define PN_TARGET __attribute__((target("avx2,fma,f16c,avxvnni")))+#define PN_DOT(acc, u, s) _mm256_dpbusd_avx_epi32(acc, u, s)+#include "quant_pn.h"+#undef PN+#undef PN_TARGET+#undef PN_DOT+#endif++void janas_q6kpn_chunk(const struct janas_block_q6kp *base, const uint8_t *p1,+ const uint8_t *p0, size_t rows, const uint32_t *js,+ const uint8_t *lv, const float *h, uint32_t n, size_t b,+ float *y)+{+#if defined(__x86_64__)+ if (use_vnni) {+ q6kpn_chunk_vnni(base, p1, p0, rows, js, lv, h, n, b, y);+ return;+ }+ if (use_pn) {+ q6kpn_chunk_avx2(base, p1, p0, rows, js, lv, h, n, b, y);+ return;+ }+#endif+ janas_q6kpn_chunk_ref(base, p1, p0, rows, js, lv, h, n, b, y);+}diff --git a/src/llm/quant_q6kp.h b/src/llm/quant_q6kp.hnew file mode 100644index 0000000..643436f--- /dev/null+++ b/src/llm/quant_q6kp.h@@ -0,0 +1,36 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * quant_q6kp.h - where a weight's bits sit in Q6_K's bit planes, for quant.c+ * and quant_q6k.c (private to the engine).+ */+#ifndef JANAS_LLM_QUANT_Q6KP_H+#define JANAS_LLM_QUANT_Q6KP_H++#include "quant.h"++/* Byte of weight v in a two-bit plane, and the shift of its bits. */+static inline int q6kp_index(int v, int *shift)+{+ int n = v / 128, part = (v % 128) / 32, l = v % 32;+ *shift = 2 * part;+ return 32 * n + l;+}++/* Weight v of a block from its planes at a level (3: all three, 2: the base+ and a1, 1: the base alone), on a scale of 0..127 whose 64 is zero: the+ centre of the range the missing bits cover, half a step. */+static inline int q6kp_value2(const struct janas_block_q6kp *b,+ const uint8_t *a1, const uint8_t *a0, int v,+ int level)+{+ int sh, i = q6kp_index(v, &sh);+ int q = (b->q[i] >> sh) & 3;+ if (level >= 2)+ q = (q << 2) | ((a1[i] >> sh) & 3);+ if (level >= 3)+ q = (q << 2) | ((a0[i] >> sh) & 3);+ return level == 3 ? 2 * q : level == 2 ? 8 * q + 3 : 32 * q + 15;+}++#endifdiff --git a/src/llm/shaders/q3k_mmid.comp b/src/llm/shaders/q3k_mmid.compnew file mode 100644index 0000000..bf27fba--- /dev/null+++ b/src/llm/shaders/q3k_mmid.comp@@ -0,0 +1,146 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+#version 450+// The fast prompt for a mixture's Q3_K experts (gpu.c experts_id, and a+// mixture's layers whole on the GPU): every expert of a group in one+// dispatch, as q4k_mmid.comp - the workgroup's z the expert, its weights,+// activations and outputs from a table (P.t), tiles of 64 rows by 16+// vectors, each invocation 2 rows by 4 - with the weights read as+// q3k_mmq.comp reads them: a group of 32 is two of 16 with a 6-bit scale+// each (less 32), a weight's three bits two of qs and one of hmask, put+// together unsigned (0-7) from the 110-byte blocks read a word at a time+// and realigned, the -4 taken off with the activations' sums of 16. Until+// 21 Oct 2026 these experts stayed on the CPU: unsloth's 3-bit+// Qwen3-30B-A3B read a prompt at 98 tokens/s where llama.cpp read 114. 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 = 16u, KS = 4u, 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[]; };++// t: the table, 3 uvec4 an expert: (w, x), (y, nv, ys), (p1, p0); then+// from uvec4 tiles on, one a workgroup's z: (expert, first vector)+layout(push_constant) uniform P { uvec2 t; uint rows, nb, tiles; } p;++struct ACache { uint qs[8]; vec2 dsc; }; // a group: three-bit values, d * scale of each 16+struct BCache { int qs[8]; vec2 d8s; float d8; }; // quants, 4 x the sums of 16, d8+shared ACache sa[BM * KS];+shared BCache sb[BN * KS];++// word i (0-27) of the block at byte off from w, realigned+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];+}++void main()+{+ U4 T = U4(p.t);+ uvec4 tl = T.v[p.tiles + gl_WorkGroupID.z];+ uint e = tl.x;+ uvec4 t0 = T.v[3u * e], t1 = T.v[3u * e + 1u];+ uint nv = t1.z, ys = t1.w;+ uint r0 = gl_WorkGroupID.x * BM, v0 = tl.y;+ U1 W = U1(t0.xy);+ U4 X = U4(t0.zw);+ F Y = F(t1.xy);+ uint id = gl_LocalInvocationID.x;+ uint rq = (id % 32u) * 2u, vq = (id / 32u) * 4u;+ float sums[8];+ [[unroll]] for (uint i = 0; i < 8u; 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 (j = 0-3 of one n) share their words+ // of qs (two bits each, shifted by 2j) and of hmask (bit+ // g = 4n + j): each read once+ uint b = g0 / 8u, gb = g0 % 8u, n = gb / 4u; // gb: in the block+ uint off = (r * p.nb + b) * 110u;+ [[unroll]] for (uint t = 0; t < 2u; t++) {+ uint kw = 2u * iqs + t;+ uint q = hword(W, off, 8u + 8u * n + kw), hm = hword(W, off, kw);+ [[unroll]] for (uint k = 0; k < KS; k++)+ sa[k * BM + rl + l].qs[kw] = ((q >> (2u * k)) & 0x03030303u) |+ (((hm >> (gb + k)) & 0x01010101u) << 2);+ }+ if (iqs == 0u) {+ float d = unpackHalf2x16(hword(W, off, 27u) & 0xffffu).x;+ uint s0 = hword(W, off, 24u), s1 = hword(W, off, 25u), s2 = hword(W, off, 26u);+ [[unroll]] for (uint k = 0; k < KS; k++) {+ // scales 2g and 2g + 1: the low four bits from byte+ // i % 8 (its low nibble below 8, high above), the top+ // two from byte 8 + i % 4 at bits 2 (i / 4)+ float sc[2];+ [[unroll]] for (uint h = 0; h < 2u; h++) {+ uint i = 2u * (gb + k) + h, lb = i % 8u;+ uint lo = ((lb < 4u ? s0 : s1) >> (8u * (lb % 4u))) & 0xffu;+ lo = i < 8u ? lo & 15u : lo >> 4;+ uint hi = (s2 >> (8u * (i % 4u) + 2u * (i / 4u))) & 3u;+ sc[h] = float(int(lo | (hi << 4)) - 32);+ }+ sa[k * BM + rl + l].dsc = vec2(d * sc[0], d * sc[1]);+ }+ }+ }+ }+ // activations: 2 invocations a vector and group, each half its quants+ {+ uint k = id / 32u, c = (id % 32u) / 2u, iqs = id % 2u;+ uint v = min(v0 + c, nv - 1u);+ uint g = g0 + k, b = g / 8u, G = g % 8u;+ uint xo = (v * p.nb + 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) {+ uvec4 bs = X.v[xo + 16u + G / 4u];+ uint bw = G % 4u == 0u ? bs.x : G % 4u == 1u ? bs.y : G % 4u == 2u ? bs.z : bs.w;+ sb[k * BN + c].d8s = vec2(4.0 * float(bitfieldExtract(int(bw), 0, 16)),+ 4.0 * float(bitfieldExtract(int(bw), 16, 16)));+ sb[k * BN + c].d8 = uintBitsToFloat(X.v[xo + 18u].x);+ }+ }+ barrier();+ for (uint k = 0; k < KS; k++) {+ ACache ca[2];+ [[unroll]] for (uint r = 0; r < 2u; r++)+ ca[r] = sa[k * BM + rq + r];+ [[unroll]] for (uint c = 0; c < 4u; c++) {+ BCache cb = sb[k * BN + vq + c];+ [[unroll]] for (uint r = 0; r < 2u; r++) {+ int q0 = 0, q1 = 0;+ [[unroll]] for (uint i = 0; i < 4u; i++) {+ q0 += dotPacked4x8EXT(int(ca[r].qs[i]), cb.qs[i]);+ q1 += dotPacked4x8EXT(int(ca[r].qs[i + 4u]), cb.qs[i + 4u]);+ }+ sums[c * 2u + r] += cb.d8 * (ca[r].dsc.x * (float(q0) - cb.d8s.x) ++ ca[r].dsc.y * (float(q1) - cb.d8s.y));+ }+ }+ }+ barrier();+ }+ [[unroll]] for (uint c = 0; c < 4u; c++)+ [[unroll]] for (uint r = 0; r < 2u; r++) {+ uint row = r0 + rq + r, v = v0 + vq + c;+ if (row < p.rows && v < nv)+ Y.v[v * ys + row] = sums[c * 2u + r];+ }+}diff --git a/src/llm/tuner.c b/src/llm/tuner.cindex f638c14..6465929 100644--- a/src/llm/tuner.c+++ b/src/llm/tuner.c@@ -60,9 +60,17 @@ void janas_tuner_init(struct janas_tuner *t, const struct janas_tune_cand *c,/* GPU candidates: only when allowed, and for one token only where theGPU takes single-token products (elsewhere they would differ only by thepower its keep-alive costs) */+/* the user's choice of devices for the class allows this candidate */+static int allowed(const struct janas_tuner *t, int cls, int i)+{+ int combo = (t->cand[i].gpu ? 1 : 0) | (t->cand[i].npu ? 2 : 0);+ return !t->allowed[cls] || (t->allowed[cls] >> combo & 1);+}+static int usable(const struct janas_tuner *t, int cls, int i){- return (!t->cand[i].gpu || (t->allow_gpu && (cls > 0 || t->gpu_one))) &&+ return allowed(t, cls, i) && (!t->cand[i].npu || cls == 2) &&+ (!t->cand[i].gpu || (t->allow_gpu && (cls > 0 || t->gpu_one))) &&(!t->cls[cls].threads || t->cand[i].threads == t->cls[cls].threads);}@@ -72,7 +80,8 @@ static int usable(const struct janas_tuner *t, int cls, int i)can move them */static int retryable(const struct janas_tuner *t, int cls, int i){- return !t->cand[i].gpu || (t->allow_gpu && (cls > 0 || t->gpu_one));+ return allowed(t, cls, i) && (!t->cand[i].npu || cls == 2) &&+ (!t->cand[i].gpu || (t->allow_gpu && (cls > 0 || t->gpu_one)));}/* The default of a class: its own, or once the threads are settled the@@ -80,10 +89,27 @@ static int retryable(const struct janas_tuner *t, int cls, int i)static int class_def(const struct janas_tuner *t, int cls){int def = t->cls[cls].def;+ /* the user's devices: the allowed candidate of the default's threads+ (or the settled ones), else the first allowed */+ if (!allowed(t, cls, def)) {+ int th = t->cls[cls].threads ? t->cls[cls].threads+ : t->cand[def].threads,+ first = -1;+ for (int i = 0; i < t->n_cand; i++)+ if (allowed(t, cls, i) && (!t->cand[i].npu || cls == 2)) {+ if (t->cand[i].threads == th)+ return i;+ if (first < 0)+ first = i;+ }+ if (first >= 0)+ return first;+ }if (!t->cls[cls].threads || t->cand[def].threads == t->cls[cls].threads)return def;for (int i = 0; i < t->n_cand; i++)- if (!t->cand[i].gpu && t->cand[i].threads == t->cls[cls].threads)+ if (!t->cand[i].gpu && !t->cand[i].npu && allowed(t, cls, i) &&+ t->cand[i].threads == t->cls[cls].threads)return i;return def;}@@ -102,6 +128,23 @@ static void settle_threads(struct janas_tuner *t, int cls)t->cls[cls].passes, t->cls[cls].threads);}+const char *janas_tune_devices(const struct janas_tune_cand *c)+{+ return c->gpu && c->npu ? " + GPU + NPU"+ : c->gpu ? " + GPU"+ : c->npu ? " + NPU"+ : "";+}++void janas_tuner_allow(struct janas_tuner *t, int cls, int mask)+{+ if (cls < 0 || cls >= JANAS_TUNE_CLASSES)+ return;+ t->allowed[cls] = mask;+ /* the default among the allowed (a fixed tuner runs it as it is) */+ t->cls[cls].def = class_def(t, cls);+}+void janas_tuner_force(struct janas_tuner *t, int cand){t->forced = cand >= 0 && cand < t->n_cand ? cand : -1;@@ -227,8 +270,8 @@ void janas_tuner_record(struct janas_tuner *t, int cls, int cand,"%d threads%s %.2f ms: %s (%u in a row by other ""threads)\n",cls, t->cls[cls].passes, t->cand[cand].threads,- t->cand[cand].gpu ? " + GPU" : "", 1e3 * sec_per_token,- t->cand[rb].threads, t->cand[rb].gpu ? " + GPU" : "",+ janas_tune_devices(&t->cand[cand]), 1e3 * sec_per_token,+ t->cand[rb].threads, janas_tune_devices(&t->cand[rb]),1e3 * t->cls[cls].cost[rb], won ? "won" : "lost",(unsigned)t->cls[cls].other_wins);if (other && won &&@@ -261,7 +304,7 @@ void janas_tuner_record(struct janas_tuner *t, int cls, int cand,"tune class %d pass %u: %d threads%s %.2f ms against a ""mean of %.2f: a try now\n",cls, t->cls[cls].passes, t->cand[cand].threads,- t->cand[cand].gpu ? " + GPU" : "", 1e3 * sec_per_token,+ janas_tune_devices(&t->cand[cand]), 1e3 * sec_per_token,1e3 * *c);}/* a plain mean over the first tries, then a moving average */@@ -390,7 +433,7 @@ void janas_tuner_report(const struct janas_tuner *t, char *buf, size_t len)int b = janas_tuner_best(t, k);w += (size_t)snprintf(buf + w, len - w, "%s%s: %d threads%s",o ? "; " : "", name[k], t->cand[b].threads,- t->cand[b].gpu ? " + GPU" : "");+ janas_tune_devices(&t->cand[b]));if (t->cls[k].tried[b] >= TRIES && w < len)w += (size_t)snprintf(buf + w, len - w, " (%.1f ms/token)",1e3 * t->cls[k].cost[b]);diff --git a/src/llm/tuner.h b/src/llm/tuner.hindex c368b41..195a71e 100644--- a/src/llm/tuner.h+++ b/src/llm/tuner.h@@ -29,13 +29,17 @@threads for Qwen3.5-2B's prompts, which ran faster on 12 (10 Oct 2026) */#define JANAS_TUNE_CLASSES 4#define JANAS_TUNE_BLOCK 64-#define JANAS_TUNE_MAX_CANDS 8+#define JANAS_TUNE_MAX_CANDS 16struct janas_tune_cand {int threads; /* compute threads (a prefix of the pool) */int gpu; /* the GPU takes part in the products */+ int npu; /* the NPU takes the blocks' products it can (blocks only) */};+/* " + GPU", " + NPU", " + GPU + NPU" or "": a candidate's devices */+const char *janas_tune_devices(const struct janas_tune_cand *c);+struct janas_tuner {struct janas_tune_cand cand[JANAS_TUNE_MAX_CANDS];int n_cand;@@ -43,6 +47,9 @@ struct janas_tuner {int allow_gpu; /* candidates with the GPU may be chosen */int gpu_one; /* ... for one token too (the GPU takes single tokens) */int forced; /* >= 0: every pass uses this candidate (and is measured) */+ /* the combinations of devices a class may use (common/devices.h: bit+ gpu | npu << 1), the user's choice; 0 any */+ int allowed[JANAS_TUNE_CLASSES];struct {double cost[JANAS_TUNE_MAX_CANDS]; /* seconds per token, averaged */uint32_t tried[JANAS_TUNE_MAX_CANDS];@@ -76,6 +83,10 @@ void janas_tuner_record(struct janas_tuner *t, int cls, int cand,/* Every pass on candidate cand (measured all the same), -1 to stop. */void janas_tuner_force(struct janas_tuner *t, int cand);+/* The combinations of devices class cls may use (common/devices.h), 0+ any: the user's --prompt-on, --drafts-on, --reply-on. */+void janas_tuner_allow(struct janas_tuner *t, int cls, int mask);+/* Whether candidates using the GPU may be chosen (energy saving: no). */void janas_tuner_allow_gpu(struct janas_tuner *t, int allow);/* Whether they may be chosen for one token too: only where the GPU takesdiff --git a/src/server/main.c b/src/server/main.cindex 49719a6..c78fa14 100644--- a/src/server/main.c+++ b/src/server/main.c@@ -7,6 +7,7 @@*/#include "server.h"+#include "common/devices.h"#include "common/env_names.h"#include "common/sock.h"#include "common/stop.h"@@ -48,6 +49,19 @@ static void usage(FILE *f)" --draft FILE a small model of the same family, for speed\n"" --mode M auto, eco or max (default auto)\n"" --no-gpu never give the GPU work\n"+ " --prompt-on DEV what reads the prompts: auto (default: what\n"+ " measures fastest here), cpu, gpu, npu, npu+gpu\n"+ " (both in each pass), or a list apart by commas\n"+ " for the engine to choose from (npu,gpu); the\n"+ " CPU takes part in every pass, the NPU in blocks\n"+ " of 64 tokens and more; a choice wins over the\n"+ " mode\n"+ " --drafts-on DEV the same for the passes that check guessed\n"+ " tokens (2 to 16)\n"+ " --reply-on DEV the same for a reply's tokens, one at a time\n"+ " --npu-int8 the NPU reads prompts with eight-bit\n"+ " activations: faster, a little less exact\n"+ " (dense Qwen3 models)\n"" --embedding-model FILE a model for /v1/embeddings (such as\n"" Qwen3-Embedding), run beside the chat model\n"" --think on|off reasoning before replying, for models that do\n"@@ -123,7 +137,8 @@ static const char *const OPTIONS[] = {"--connections", "--max-input", "--warn-input","--fim-prefix", "--fim-suffix", "--fim-max","--metrics", "--progress", "--no-mcp",- "--test", "--verbose"};+ "--test", "--verbose", "--prompt-on",+ "--drafts-on", "--reply-on", "--npu-int8"};/* the value of option argv[*i], read whole within [lo, hi]; a mistakeends the program, as a missing value does */@@ -209,6 +224,8 @@ int main(int argc, char **argv)c->reasoning_budget = -1;for (int i = 1; i < argc; i++) {const char *a = argv[i];+ char dwhy[240];+ int dk;if (!strcmp(a, "--help") || !strcmp(a, "-h")) {usage(stdout);return 0;@@ -252,6 +269,8 @@ int main(int argc, char **argv)c->no_mtp = 1;} else if (!strcmp(a, "--no-gpu")) {c->no_gpu = 1;+ } else if (!strcmp(a, "--npu-int8")) {+ setenv("JANAS_NPU_A8", "1", 1); /* read when the model opens */} else if (!strcmp(a, "--keep")) {c->keep = (int)num(argc, argv, &i, 0, 1 << 20);} else if (!strcmp(a, "--keep-memory")) {@@ -293,6 +312,14 @@ int main(int argc, char **argv)} else if (!strcmp(a, "--verbose")) {c->verbose = 1;setenv("JANAS_PROGRESS", "30", 0); /* unless one is asked */+ } else if (a[0] == '-' && (dk = janas_devices_option(+ a, i + 1 < argc ? argv[i + 1] : NULL,+ dwhy, sizeof dwhy)) != 0) {+ if (dk < 0) {+ fprintf(stderr, "janas-server: %s\n", dwhy);+ return 2;+ }+ i++; /* its value, put in the engine's variable */} else if (a[0] == '-') {char why[200];janas_unknown_word(why, sizeof why, a, "an option", OPTIONS,diff --git a/tests/bench_long.c b/tests/bench_long.cindex 43e85fd..fd9cb0e 100644--- a/tests/bench_long.c+++ b/tests/bench_long.c@@ -20,7 +20,10 @@* JANAS_WARM=1 the machine's profile is preloaded, as janas-chat does; with* BENCH_READY=1 as well, the prompt waits until that preload is done.* BENCH_SAVE=file writes the prompt and the generated tokens (int32), for- * tracing the same sequence again. The experts' bits and count in use are+ * tracing the same sequence again. BENCH_EVERY=n prints the decoding n+ * tokens at a time as well (speed, experts from RAM, misses and time waited+ * per token): how the cache holds up as a reply moves away from its+ * prompt. The experts' bits and count in use are* printed: with little memory the engine lowers them itself (a different* model); BENCH_EXACT=1 keeps all the bits and the model's own count.*/@@ -205,12 +208,35 @@ int main(int argc, char **argv)janas_pool_trace_report("prefill", t1 - t0);janas_pool_trace_reset();janas_expert_cache_reset_stats(c);+ uint32_t every =+ getenv("BENCH_EVERY") ? (uint32_t)atoi(getenv("BENCH_EVERY")) : 0;+ struct janas_expert_cache_stats s0 = {0};+ double ts = now();for (uint32_t i = 0; i < nn; i++) {out[i] = argmax(logits, nv);if (janas_llm_model_decode(m, out[i], np + i, logits) != 0) {fprintf(stderr, "decode failed at %u\n", i);return 1;}+ if (every && ((i + 1) % every == 0 || i + 1 == nn)) {+ struct janas_expert_cache_stats s1;+ janas_expert_cache_stats(c, &s1);+ uint32_t k = (i + 1) % every ? (i + 1) % every : every;+ double te = now();+ uint64_t rq = s1.requests - s0.requests;+ printf("decode tokens %4u-%4u: %.2f token/s, experts %.1f%% from "+ "RAM, %.1f misses and %.2f ms waited a token\n",+ i + 2 - k, i + 1, k / (te - ts),+ rq ? 100.0 *+ (double)((s1.hits - s1.prefetch_used) -+ (s0.hits - s0.prefetch_used)) /+ (double)rq+ : 0,+ (double)(s1.misses - s0.misses) / k,+ (s1.wait_seconds - s0.wait_seconds) / k * 1e3);+ s0 = s1;+ ts = te;+ }}double t2 = now();long long d2 = disk_busy_ms(argv[1]);diff --git a/tests/npu_check.c b/tests/npu_check.cnew file mode 100644index 0000000..ea63545--- /dev/null+++ b/tests/npu_check.c@@ -0,0 +1,240 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * npu_check.c - products on the NPU (common/npu.h) against the CPU in+ * double on the same weights: INT8 (dequantized as the NPU computes) and+ * FP16, a few shapes, two products in flight at once with x shared.+ * Skips (exit 0) when no NPU is usable. Errors relative to the outputs'+ * rms; FP16 arithmetic: some 1e-3 is right, the bound is 1e-2.+ *+ * Usage: npu_check [m n k] (default: the shapes below)+ * NPU_CHECK_CACHE=<dir> keeps the compiled products there (a second run+ * loads them).+ * JANAS_NPU_LOADER=<libze_loader.so.1> for a loader not on the path.+ */+#include <math.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "common/npu.h"++static uint64_t rng = 88172645463325252ull;++static float rnd(void)+{+ rng ^= rng << 13;+ rng ^= rng >> 7;+ rng ^= rng << 17;+ return (float)(rng >> 40) / (float)(1u << 24) - 0.5f;+}++static float h2f(uint16_t h)+{+ uint32_t sign = (uint32_t)(h & 0x8000u) << 16, e = (h >> 10) & 31,+ mant = h & 0x3ffu, b;+ if (!e) {+ float f = ldexpf((float)mant, -24);+ return sign ? -f : f;+ }+ b = sign | ((e - 15 + 127) << 23) | (mant << 13);+ float f;+ memcpy(&f, &b, 4);+ return f;+}++static uint16_t f2h(float f) /* for the FP16 weights: truncation is fine */+{+ uint32_t b;+ memcpy(&b, &f, 4);+ int e = (int)((b >> 23) & 0xff) - 127 + 15;+ if (e <= 0)+ return (uint16_t)((b >> 16) & 0x8000u);+ return (uint16_t)(((b >> 16) & 0x8000u) | ((uint32_t)e << 10) |+ ((b >> 13) & 0x3ffu));+}++/* rms-relative worst error of y (m x n) against x wd^T in double */+static double check(const float *x, const float *wd, const float *y, int m,+ int n, int k)+{+ double worst = 0, ss = 0;+ int rows = m < 32 ? m : 32;+ for (int i = 0; i < rows; i++)+ for (int j = 0; j < n; j++) {+ double s = 0;+ for (int t = 0; t < k; t++)+ s += (double)x[(size_t)i * k + t] * wd[(size_t)j * k + t];+ worst = fmax(worst, fabs(y[(size_t)i * n + j] - s));+ ss += s * s;+ }+ return worst / sqrt(ss / ((double)rows * n) + 1e-30);+}++/* a feed-forward in one run (janas_npu_ffn_create) against the CPU in+ double on the same weights, dequantized as the NPU does; rms-relative+ worst error of y, or -1 if it did not run */+static double check_ffn(struct janas_npu *u, int m, int d, int ff, int act)+{+ char err[256];+ size_t nw = (size_t)ff * d;+ float *w[3];+ int8_t *q[3];+ uint16_t *sc[3];+ int rows[3] = {ff, ff, d}, cols[3] = {d, d, ff};+ for (int k = 0; k < 3; k++) {+ w[k] = malloc(sizeof(float) * nw), q[k] = malloc(nw);+ sc[k] = malloc(2 * (size_t)rows[k]);+ for (size_t i = 0; i < nw; i++)+ w[k][i] = rnd() * 0.15f;+ janas_npu_quant_rows(w[k], rows[k], cols[k], q[k], sc[k]);+ for (size_t i = 0; i < nw; i++) /* as the NPU: FP16 products */+ w[k][i] = h2f(f2h((float)q[k][i] * h2f(sc[k][i / cols[k]])));+ }+ float *x = janas_npu_alloc(u, sizeof(float) * m * d),+ *y = janas_npu_alloc(u, sizeof(float) * m * d);+ for (size_t i = 0; i < (size_t)m * d; i++)+ x[i] = rnd() * 2;+ struct janas_npu_mm *p =+ janas_npu_ffn_create(u, m, d, ff, act, q[0], sc[0], q[1], sc[1], q[2],+ sc[2], x, y, err, sizeof err);+ double worst = -1;+ if (!p)+ printf("FAIL feed-forward %dx%dx%d: %s\n", m, d, ff, err);+ else if (janas_npu_mm_run(p) == 0) {+ double ss = 0;+ worst = 0;+ double *h = malloc(sizeof(double) * ff);+ int rows_checked = m < 16 ? m : 16;+ for (int i = 0; i < rows_checked; i++) {+ const float *xi = x + (size_t)i * d;+ for (int f = 0; f < ff; f++) {+ double g = 0, up = 0;+ for (int t = 0; t < d; t++) {+ g += (double)xi[t] * w[0][(size_t)f * d + t];+ up += (double)xi[t] * w[1][(size_t)f * d + t];+ }+ double a = act == JANAS_NPU_SILU+ ? g / (1 + exp(-g))+ : 0.5 * g *+ (1 + tanh(0.7978845608 *+ (g + 0.044715 * g * g * g)));+ h[f] = a * up;+ }+ for (int o = 0; o < d; o++) {+ double v = 0;+ for (int f = 0; f < ff; f++)+ v += h[f] * w[2][(size_t)o * ff + f];+ worst = fmax(worst, fabs(y[(size_t)i * d + o] - v));+ ss += v * v;+ }+ }+ worst /= sqrt(ss / ((double)rows_checked * d) + 1e-30);+ free(h);+ }+ janas_npu_mm_destroy(p);+ janas_npu_free(u, x);+ janas_npu_free(u, y);+ for (int k = 0; k < 3; k++)+ free(w[k]), free(q[k]), free(sc[k]);+ return worst;+}++int main(int argc, char **argv)+{+ char err[256];+ struct janas_npu *u = janas_npu_create(err, sizeof err);+ if (!u) {+ printf("npu_check: skipped (%s)\n", err);+ return 0;+ }+ printf("NPU: %s\n", janas_npu_name(u));+ const char *cache = getenv("NPU_CHECK_CACHE");+ if (cache && janas_npu_set_cache(u, cache))+ printf("cache %s not usable\n", cache);+ int shapes[][3] = {{256, 2048, 2048}, {64, 512, 1536}, {256, 1000, 768}};+ int ns = 3;+ if (argc == 4) {+ shapes[0][0] = atoi(argv[1]), shapes[0][1] = atoi(argv[2]);+ shapes[0][2] = atoi(argv[3]), ns = 1;+ }+ int failures = 0;+ for (int si = 0; si < ns; si++) {+ int m = shapes[si][0], n = shapes[si][1], k = shapes[si][2];+ float *w = malloc(sizeof(float) * n * k),+ *wd = malloc(sizeof(float) * n * k),+ *w2d = malloc(sizeof(float) * n * k);+ int8_t *q = malloc((size_t)n * k);+ uint16_t *sc = malloc(2 * (size_t)n), *wh = malloc(2 * (size_t)n * k);+ for (size_t i = 0; i < (size_t)n * k; i++)+ w[i] = rnd() * 0.2f * (1 + (float)(i / k % 5));+ janas_npu_quant_rows(w, n, k, q, sc);+ for (size_t i = 0; i < (size_t)n * k; i++) {+ /* the NPU: the integer in FP16 times the FP16 scale, in FP16 */+ uint16_t p = f2h((float)q[i] * h2f(sc[i / k]));+ wd[i] = h2f(p);+ wh[i] = f2h(w[(size_t)n * k - 1 - i]);+ w2d[i] = h2f(wh[i]);+ }+ float *x = janas_npu_alloc(u, sizeof(float) * m * k),+ *y = janas_npu_alloc(u, sizeof(float) * m * n),+ *y2 = janas_npu_alloc(u, sizeof(float) * m * n);+ for (size_t i = 0; i < (size_t)m * k; i++)+ x[i] = rnd() * 2;+ struct janas_npu_mm *p =+ janas_npu_mm_create(u, m, n, k, JANAS_NPU_I8, q,+ sc, x, y, err, sizeof err),+ *p2 = p ? janas_npu_mm_create(+ u, m, n, k, JANAS_NPU_F16, wh, NULL,+ x, y2, err, sizeof err)+ : NULL;+ if (!p || !p2) {+ printf("FAIL %dx%dx%d: %s\n", m, n, k, err);+ failures++;+ } else if (janas_npu_mm_begin(p) || janas_npu_mm_begin(p2) ||+ janas_npu_mm_finish(p) || janas_npu_mm_finish(p2)) {+ printf("FAIL %dx%dx%d: run\n", m, n, k);+ failures++;+ } else {+ double e8 = check(x, wd, y, m, n, k),+ e16 = check(x, w2d, y2, m, n, k);+ int bad = !(e8 < 1e-2) || !(e16 < 1e-2);+ failures += bad;+ printf("%s %dx%dx%d: INT8 %.2e, FP16 %.2e of rms\n",+ bad ? "FAIL" : "ok ", m, n, k, e8, e16);+ /* a second run on new x: the bound arguments are re-read */+ for (size_t i = 0; i < (size_t)m * k; i++)+ x[i] = rnd();+ if (janas_npu_mm_run(p)) {+ printf("FAIL rerun\n");+ failures++;+ } else if (!(check(x, wd, y, m, n, k) < 1e-2)) {+ printf("FAIL rerun %dx%dx%d: x not re-read\n", m, n, k);+ failures++;+ }+ }+ janas_npu_mm_destroy(p);+ janas_npu_mm_destroy(p2);+ janas_npu_free(u, x);+ janas_npu_free(u, y);+ janas_npu_free(u, y2);+ free(w), free(wd), free(w2d), free(q), free(sc), free(wh);+ }+ /* feed-forwards in one run: FP16 inside (the intermediate too), so a+ looser bound than the products' */+ for (int act = 0; act < 2 && argc != 4; act++) {+ double e = check_ffn(u, 256, 512, 1536, act);+ int bad = !(e >= 0 && e < 3e-2);+ failures += bad;+ printf("%s feed-forward 256x512x1536 %s: %.2e of rms\n",+ bad ? "FAIL" : "ok ", act ? "GELU" : "SiLU", e);+ }+ int np, nc;+ double cs;+ janas_npu_stats(u, &np, &nc, &cs);+ printf("%d products (%d from the cache) in %.2f s\n", np, nc, cs);+ janas_npu_destroy(u);+ printf("%s\n", failures ? "npu_check: FAILED" : "npu_check: ok");+ return failures != 0;+}diff --git a/tests/test_import_regions.c b/tests/test_import_regions.cindex 14edc82..6d9168d 100644--- a/tests/test_import_regions.c+++ b/tests/test_import_regions.c@@ -7,7 +7,11 @@* the GPU takes from its first byte, end on a slot, and leave no gap. From* 13 to 14 October 2026 the overlap was not counted, and Qwen3.6-35B-A3B's* MXFP4 experts (slots of 1,671,168 bytes) got a second region of 4 GiB and- * 1.9 MB, which the GPU refused. No GPU needed.+ * 1.9 MB, which the GPU refused. Until 21 October a region could be 4 GiB+ * exactly, which Mesa's Intel driver gave the kernel as 0 bytes: unsloth's+ * 3-bit Qwen3-30B-A3B (slots of 2,236,416 bytes, 1,920 of them 1 MB short+ * of 4 GiB) got one as its second, and its experts stayed off the GPU. No+ * GPU needed.*/#include <stdio.h>@@ -17,13 +21,14 @@ static int failures;static void check(uint64_t unit, uint64_t bytes, int huge){- const uint64_t mb2 = (uint64_t)2 << 20;+ const uint64_t mb2 = (uint64_t)2 << 20, gib4 = (uint64_t)4 << 30;uint64_t at = 0;int n = 0;while (at < bytes) {uint64_t from, end = janas_m_import_next(at, bytes, unit, huge, &from);int bad = from > at || end <= at || end > bytes ||end - from > JANAS_M_REGION_MAX ||+ ((end - from + 4095) & ~(uint64_t)4095) >= gib4 ||(huge && from % mb2 != 0) || (!huge && from != at) ||(end != bytes && (end - at) % unit != 0);if (bad) {@@ -43,16 +48,19 @@ static void check(uint64_t unit, uint64_t bytes, int huge)int main(void){/* the slots of Qwen3.6-35B-A3B MXFP4_MOE, of its Q4_K_M at six bits,- of a page, of 2 MB and around it, of a dense layer's feed-forward */- static const uint64_t units[] = {1671168, 2039808, 4096,- 2097152, 2101248, 2093056,- 157286400, 1179648, 3014656};+ of a page, of 2 MB and around it, of a dense layer's feed-forward, of+ unsloth's 3-bit Qwen3-30B-A3B */+ static const uint64_t units[] = {1671168, 2039808, 4096, 2097152,+ 2101248, 2093056, 157286400, 1179648,+ 3014656, 2236416};for (size_t u = 0; u < sizeof(units) / sizeof(units[0]); u++)for (uint64_t slots = 1; slots <= 40000; slots = slots * 3 + 7)for (int huge = 0; huge < 2; huge++)check(units[u], slots * units[u], huge);/* the arena of the 35B's MXFP4 experts, every slot of its 40 layers */check(1671168, (uint64_t)40 * 256 * 1671168, 1);+ /* and the 3-bit 30B's, its 48 layers' 128 experts and the guard */+ check(2236416, (uint64_t)48 * 128 * 2236416 + 4096, 1);printf("test_import_regions: %s\n", failures ? "FAILED" : "ok");return failures ? 1 : 0;}diff --git a/tests/test_npu.c b/tests/test_npu.cnew file mode 100644index 0000000..3b89b0c--- /dev/null+++ b/tests/test_npu.c@@ -0,0 +1,117 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * test_npu.c - the NPU layer's parts that need no NPU: the rows' INT8+ * quantization (scales in FP16, q s within half a step of the weight) and+ * the IR writer (the compiler's input laid out as the driver reads it).+ * The NPU itself: npu_check.+ */+#include <math.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "common/npu.h"+#include "common/npu_ir.h"++static float h2f(uint16_t h)+{+ uint32_t sign = (uint32_t)(h & 0x8000u) << 16, e = (h >> 10) & 31,+ mant = h & 0x3ffu, b;+ if (!e && !mant)+ b = sign;+ else if (!e) {+ float f = ldexpf((float)mant, -24);+ return sign ? -f : f;+ } else+ b = sign | ((e - 15 + 127) << 23) | (mant << 13);+ float f;+ memcpy(&f, &b, 4);+ return f;+}++int main(void)+{+ int failures = 0;++ /* quantization */+ enum { N = 7, K = 300 };+ float *w = malloc(sizeof(float) * N * K);+ int8_t *q = malloc(N * K);+ uint16_t s[N];+ unsigned r = 12345;+ for (int i = 0; i < N * K; i++) {+ r = r * 1103515245u + 12345u;+ w[i] = ((float)(r >> 8) / (float)(1u << 24) - 0.5f) * (1 + i / K);+ }+ for (int k = 0; k < K; k++)+ w[3 * K + k] = 0; /* a row of zeros */+ w[5 * K + 17] = 1e-6f, w[5 * K + 18] = -3e-5f; /* tiny scale */+ for (int k = 19; k < K; k++)+ w[5 * K + k] = 0;+ for (int k = 0; k < 17; k++)+ w[5 * K + k] = 0;+ janas_npu_quant_rows(w, N, K, q, s);+ for (int i = 0; i < N; i++) {+ float sc = h2f(s[i]), worst = 0;+ for (int k = 0; k < K; k++) {+ float e = fabsf(q[i * K + k] * sc - w[i * K + k]);+ worst = fmaxf(worst, e);+ if (q[i * K + k] == -128)+ failures++, printf("FAIL row %d: -128\n", i);+ }+ float amax = 0;+ for (int k = 0; k < K; k++)+ amax = fmaxf(amax, fabsf(w[i * K + k]));+ /* half a step: the scale rounds up, nothing is clipped */+ float bound = sc * 0.5f * 1.0001f;+ if (sc * 127 < amax)+ failures++, printf("FAIL row %d: scale below the row's max\n", i);+ if (i == 3 && (sc != 0 || worst != 0))+ failures++, printf("FAIL zero row: scale %g\n", sc);+ if (worst > bound)+ failures++, printf("FAIL row %d: error %g > %g\n", i, worst, bound);+ }++ /* the IR writer */+ struct npu_ir g;+ npu_ir_begin(&g, "t");+ int xd[2] = {4, 8}, wd[2] = {3, 8};+ int8_t wq[24] = {0};+ int x = npu_ir_param(&g, "x", "f32", 2, xd);+ int c = npu_ir_const(&g, "w", "i8", 2, wd, wq, sizeof wq);+ int m = npu_ir_matmul_tb(&g, "mm", npu_ir_convert(&g, "x16", x, "f16"),+ npu_ir_convert(&g, "w16", c, "f16"), NULL);+ npu_ir_result(&g, m);+ if (npu_ir_end(&g) || g.nl != 6 || g.ne != 5 || g.nbin != 24)+ failures++, printf("FAIL IR: %d layers, %d edges\n", g.nl, g.ne);+ if (!strstr(g.xml, "<edge from-layer=\"4\" from-port=\"2\" to-layer=\"5\" "+ "to-port=\"0\"/>"))+ failures++, printf("FAIL IR: matmul's edge\n");+ int bad[2] = {3, 9};+ struct npu_ir h;+ npu_ir_begin(&h, "u");+ int a = npu_ir_param(&h, "a", "f16", 2, xd),+ b = npu_ir_param(&h, "b", "f16", 2, bad);+ if (npu_ir_matmul_tb(&h, "mm", a, b, NULL) >= 0 || !npu_ir_end(&h))+ failures++, printf("FAIL IR: mismatched k accepted\n");+ npu_ir_free(&h);+ size_t bytes = 0;+ uint8_t *mb = npu_ir_model(&g, 8, 3, &bytes);+ uint64_t sx, sb;+ uint32_t parts;+ uint16_t maj, min;+ memcpy(&maj, mb, 2), memcpy(&min, mb + 2, 2), memcpy(&parts, mb + 4, 4);+ memcpy(&sx, mb + 8, 8);+ memcpy(&sb, mb + 16 + sx, 8);+ if (!mb || maj != 8 || min != 3 || parts != 2 || sx != g.len || sb != 24 ||+ bytes != 24 + sx + 24)+ failures++, printf("FAIL model layout\n");+ free(mb);+ npu_ir_free(&g);+ free(w);+ free(q);+ printf("%s\n", failures ? "test_npu: FAILED" : "test_npu: ok");+ return failures != 0;+}diff --git a/tests/test_quant.c b/tests/test_quant.cindex 5d96b3f..58d947d 100644--- a/tests/test_quant.c+++ b/tests/test_quant.c@@ -252,6 +252,142 @@ static void test_q6k_planes(void)free(pf);}+/* janas_q6kpn_axpy at every level: with h = 1 on zeros the very floats+ janas_q6kp_dequantize gives, whatever planes lie below the level; with+ any h on any y, y plus h times them. */+static void test_q6kpn_axpy(void)+{+ enum { NB = 16, N = NB * JANAS_QK };+ struct janas_block_q6k *w = malloc(NB * sizeof(*w));+ struct janas_block_q6kp *base = malloc(NB * sizeof(*base));+ uint8_t *p1 = malloc(NB * JANAS_Q6KP_PLANE);+ uint8_t *p0 = malloc(NB * JANAS_Q6KP_PLANE);+ float *ref = malloc(N * sizeof(float)), *y = malloc(N * sizeof(float));+ float *y0 = malloc(N * sizeof(float));++ for (int trial = 0; trial < 20; trial++) {+ unsigned char *p = (unsigned char *)w;+ for (size_t i = 0; i < NB * sizeof(*w); i++)+ p[i] = (unsigned char)rnd();+ for (int b = 0; b < NB; b++)+ w[b].d = janas_fp32_to_fp16(rndf(0.0001f, 0.01f));+ janas_q6k_to_planes(w, NB, base, p1, p0);+ for (int level = 0; level <= 3; level++) {+ const uint8_t *a1 = level >= 2 ? p1 : NULL;+ const uint8_t *a0 = level >= 3 ? p0 : NULL;+ if (level)+ janas_q6kp_dequantize(base, a1, a0, ref, N);+ for (int i = 0; i < N; i++) {+ if (!level)+ ref[i] = 0.0f;+ y[i] = 0.0f;+ }+ janas_q6kpn_axpy(base, p1, p0, level, 1.0f, y, N);+ int bad = 0;+ for (int i = 0; i < N; i++)+ bad += y[i] != ref[i];+ CHECK(!bad, "q6kpn axpy level %d, h = 1: %d of %d floats differ",+ level, bad, N);+ float h = rndf(-2.0f, 2.0f);+ for (int i = 0; i < N; i++)+ y0[i] = y[i] = rndf(-1.0f, 1.0f);+ janas_q6kpn_axpy(base, a1, a0, level, h, y, N);+ bad = 0;+ for (int i = 0; i < N; i++) {+ float want = y0[i] + h * ref[i];+ bad += fabsf(y[i] - want) > 1e-6f * (1.0f + fabsf(want));+ }+ CHECK(!bad, "q6kpn axpy level %d, h = %g: %d of %d floats off",+ level, h, bad, N);+ /* the kernel in use against the reference, bit for bit */+ float *yr = ref;+ for (int i = 0; i < N; i++)+ yr[i] = y0[i] = y[i] = rndf(-1.0f, 1.0f);+ janas_q6kpn_axpy(base, a1, a0, level, h, y, N);+ janas_q6kpn_axpy_ref(base, a1, a0, level, h, yr, N);+ CHECK(!memcmp(y, yr, N * sizeof(float)),+ "q6kpn axpy level %d: kernel and reference differ", level);+ }+ }+ free(w);+ free(base);+ free(p1);+ free(p0);+ free(ref);+ free(y);+ free(y0);+}++/* janas_q6kpn_chunk: the kernel in use against the reference, bit for bit,+ on chunks of 1 to 128 neurons at random levels (JANAS_KERNELS=avx2 tries+ the AVX2 one on a machine with AVX-VNNI); and the reference against the+ float axpy, the same products with factors of eight bits. */+static void test_q6kpn_chunk(void)+{+ enum { NN = 160, NB = 4 };+ struct janas_block_q6k *w = malloc(NN * NB * sizeof(*w));+ struct janas_block_q6kp *base = malloc(NN * NB * sizeof(*base));+ uint8_t *p1 = malloc(NN * NB * JANAS_Q6KP_PLANE);+ uint8_t *p0 = malloc(NN * NB * JANAS_Q6KP_PLANE);+ unsigned char *p = (unsigned char *)w;+ for (size_t i = 0; i < NN * NB * sizeof(*w); i++)+ p[i] = (unsigned char)rnd();+ for (int b = 0; b < NN * NB; b++)+ w[b].d = janas_fp32_to_fp16(rndf(0.0001f, 0.01f));+ janas_q6k_to_planes(w, NN * NB, base, p1, p0);+ double worst = 0;+ for (int trial = 0; trial < 60; trial++) {+ uint32_t js[JANAS_PN_CHUNK], perm[NN];+ uint8_t lv[JANAS_PN_CHUNK];+ float h[JANAS_PN_CHUNK], y0[JANAS_QK], y1[JANAS_QK], y2[JANAS_QK],+ ya[JANAS_QK];+ uint32_t n = trial < 3 ? (uint32_t)trial + 1+ : trial < 6 ? JANAS_PN_CHUNK - (uint32_t)trial + 3+ : 1 + rnd() % JANAS_PN_CHUNK;+ for (uint32_t i = 0; i < NN; i++)+ perm[i] = i;+ for (uint32_t i = 0; i < n; i++) { /* distinct neurons */+ uint32_t k = i + rnd() % (NN - i), t = perm[i];+ perm[i] = perm[k];+ perm[k] = t;+ js[i] = perm[i];+ lv[i] = (uint8_t)(1 + rnd() % 3);+ float g = rndf(-1, 1);+ h[i] = trial % 2 ? g * g * g * 4.0f : rndf(-2.0f, 2.0f);+ }+ size_t b = rnd() % NB;+ for (int v = 0; v < JANAS_QK; v++)+ ya[v] = y0[v] = y1[v] = y2[v] = rndf(-1.0f, 1.0f);+ janas_q6kpn_chunk(base, p1, p0, NN, js, lv, h, n, b, y1);+ janas_q6kpn_chunk_ref(base, p1, p0, NN, js, lv, h, n, b, y2);+ CHECK(!memcmp(y1, y2, sizeof(y1)),+ "q6kpn chunk of %u: kernel and reference differ", n);+ for (uint32_t i = 0; i < n; i++) {+ size_t at = b * NN + js[i]; /* by block of outputs */+ janas_q6kpn_axpy_ref(base + at, p1 + at * JANAS_Q6KP_PLANE,+ p0 + at * JANAS_Q6KP_PLANE, lv[i], h[i], ya,+ JANAS_QK);+ }+ double e = 0, sg = 0;+ for (int v = 0; v < JANAS_QK; v++) {+ e += ((double)y2[v] - ya[v]) * (y2[v] - ya[v]);+ sg += ((double)ya[v] - y0[v]) * (ya[v] - y0[v]);+ }+ double rel = sg > 0 ? sqrt(e / sg) : 0;+ if (rel > worst)+ worst = rel;+ CHECK(rel < 0.02, "q6kpn chunk of %u: %.4f off the float products", n,+ rel);+ }+ printf("q6kpn chunk: factors of eight bits, at most %.4f off the float "+ "products\n",+ worst);+ free(w);+ free(base);+ free(p1);+ free(p0);+}+static void test_matvec(void){enum { ROWS = 1000, COLS = 2048, NB = COLS / JANAS_QK };@@ -422,6 +558,70 @@ static void test_quantize_q4k(void)free(q);}+/* janas_q6k_quantize: every weight read back as the integer nearest to it+ under the scales the block keeps (so its bits sit where Q6_K reads them),+ and less error than the plain way: each group of 16 at its largest+ magnitude over 31, those scales then to the block's eight bits. */+static void test_quantize_q6k(void)+{+ enum { N = 256 * 64 };+ float *x = malloc(N * sizeof(float)), *y = malloc(N * sizeof(float));+ struct janas_block_q6k *q = malloc(N / JANAS_QK * sizeof(*q));+ for (int kind = 0; kind < 2; kind++) {+ double var = 0, err = 0, plain = 0, plain_f = 0;+ for (int i = 0; i < N; i++) {+ /* sum of uniforms ~ Gaussian; its cube is heavy-tailed */+ float g = rndf(-1, 1) + rndf(-1, 1) + rndf(-1, 1) + rndf(-1, 1);+ x[i] = 0.02f * (kind ? g * g * g : g);+ var += (double)x[i] * x[i];+ }+ janas_q6k_quantize(x, q, N);+ janas_q6k_dequantize(q, y, N);+ int far = 0;+ for (int i = 0; i < N; i++) {+ const struct janas_block_q6k *b = &q[i / JANAS_QK];+ float a = janas_fp16_to_fp32(b->d) * b->scales[i % JANAS_QK / 16];+ int k = a != 0.0f ? (int)lrintf(x[i] / a) : 0;+ k = k < -32 ? -32 : k > 31 ? 31 : k;+ far += y[i] != a * k;+ err += ((double)y[i] - x[i]) * (y[i] - x[i]);+ }+ CHECK(!far, "q6k quantize %d: %d weights not the nearest", kind, far);+ for (int b = 0; b < N / JANAS_QK; b++) {+ const float *xb = x + b * JANAS_QK;+ float a[16], amax = 0;+ for (int s = 0; s < 16; s++) {+ a[s] = 0;+ for (int k = 0; k < 16; k++)+ a[s] = fmaxf(a[s], fabsf(xb[16 * s + k]) / 31);+ amax = fmaxf(amax, a[s]);+ }+ float d = janas_fp16_to_fp32(janas_fp32_to_fp16(amax / 127));+ for (int v = 0; v < JANAS_QK; v++) {+ float af = a[v / 16], a8 = d * lrintf(af / d);+ int kf = af > 0 ? (int)lrintf(xb[v] / af) : 0;+ int k8 = a8 > 0 ? (int)lrintf(xb[v] / a8) : 0;+ kf = kf < -32 ? -32 : kf > 31 ? 31 : kf;+ k8 = k8 < -32 ? -32 : k8 > 31 ? 31 : k8;+ plain_f += ((double)af * kf - xb[v]) * (af * kf - xb[v]);+ plain += ((double)a8 * k8 - xb[v]) * (a8 * k8 - xb[v]);+ }+ }+ double rel = sqrt(err / var), rel_plain = sqrt(plain / var);+ printf("q6k quantize, %s weights: relative rms error %.5f (plain "+ "%.5f, with float scales %.5f)\n",+ kind ? "heavy-tailed" : "Gaussian", rel, rel_plain,+ sqrt(plain_f / var));+ CHECK(rel < rel_plain,+ "q6k quantize %d: relative error %.5f, plain "+ "%.5f",+ kind, rel, rel_plain);+ }+ free(x);+ free(y);+ free(q);+}+/* janas_dot_multi on 1 to 17 vectors, both types: equal to the scalarreference for every vector (the kernels group vectors by eight). */static void test_dot_multi(void)@@ -1197,6 +1397,8 @@ int main(void)test_dot();test_dot_q6k();test_q6k_planes();+ test_q6kpn_axpy();+ test_q6kpn_chunk();test_matvec();test_matvec_group();test_matvec_multi();@@ -1209,6 +1411,7 @@ int main(void)test_dot_q3k();test_dot_iq3s();test_quantize_q4k();+ test_quantize_q6k();test_quantize_q8k();test_dequantize();printf("test_quant: kernel %s, %s\n", janas_q4k_kernel_name(),diff --git a/tests/test_tuner.c b/tests/test_tuner.cindex 7c8d0d0..25dde1e 100644--- a/tests/test_tuner.c+++ b/tests/test_tuner.c@@ -4,13 +4,15 @@* test_tuner.c - the self-tuner on simulated costs: it settles on the* fastest candidate, keeps the default on near ties, never picks a GPU* candidate when the GPU is not allowed, tries the others ever more rarely- * while they lose, and its saved choices come back.+ * while they lose, and its saved choices come back; the devices the user+ * allows (common/devices.h) as written and as the tuner keeps to them.*/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>+#include "common/devices.h"#include "llm/tuner.h"static int failures;@@ -231,6 +233,75 @@ int main(void)for (int i = 0; i < 10; i++)CHECK(janas_tuner_pick(&v, 0) == 1, "forced candidate not used");+ /* the user's devices: a class kept to the NPU runs it, slower or not;+ a list chooses among its own; a fixed tuner runs the allowed */+ const struct janas_tune_cand dc[4] = {{.threads = 12},+ {.threads = 12, .gpu = 1},+ {.threads = 12, .npu = 1},+ {.threads = 12, .gpu = 1, .npu = 1}};+ const int dd[JANAS_TUNE_CLASSES] = {0, 0, 0, 0};+ struct janas_tuner d;+ janas_tuner_init(&d, dc, 4, dd, 0);+ janas_tuner_allow_gpu(&d, 1);+ janas_tuner_allow(&d, 2, 1 << JANAS_DEV_NPU);+ int elsewhere = 0;+ for (int i = 0; i < 200; i++) {+ int c = janas_tuner_pick(&d, 2);+ elsewhere += c != 2;+ janas_tuner_record(&d, 2, c, (const double[]){0.5, 0.4, 1.0, 0.9}[c]);+ }+ CHECK(!elsewhere && janas_tuner_best(&d, 2) == 2,+ "npu: %d passes elsewhere, best %d", elsewhere,+ janas_tuner_best(&d, 2));+ janas_tuner_init(&d, dc, 4, dd, 0);+ janas_tuner_allow_gpu(&d, 1);+ janas_tuner_allow(&d, 2, 1 << JANAS_DEV_NPU | 1 << JANAS_DEV_GPU);+ elsewhere = 0;+ for (int i = 0; i < 200; i++) {+ int c = janas_tuner_pick(&d, 2);+ elsewhere += c == 0 || c == 3;+ janas_tuner_record(&d, 2, c, (const double[]){0.3, 1.0, 0.6, 0.2}[c]);+ }+ CHECK(!elsewhere && janas_tuner_best(&d, 2) == 2,+ "npu,gpu: %d passes elsewhere, best %d", elsewhere,+ janas_tuner_best(&d, 2));+ janas_tuner_init(&d, dc, 4, dd, 1);+ janas_tuner_allow(&d, 2, 1 << (JANAS_DEV_GPU | JANAS_DEV_NPU));+ CHECK(janas_tuner_pick(&d, 2) == 3, "fixed, npu+gpu: candidate %d",+ janas_tuner_pick(&d, 2));+ /* the devices as written */+ char why[200], nm[64];+ static const struct {+ const char *spec;+ int mask;+ } specs[] = {{"auto", 0},+ {"", 0},+ {"cpu", 1},+ {"npu", 1 << 2},+ {"NPU+gpu", 1 << 3},+ {"gpu+cpu", 1 << 1},+ {"cpu,npu", 1 | 1 << 2},+ {"npu,gpu,npu+gpu", 1 << 1 | 1 << 2 | 1 << 3},+ {"tpu", -1},+ {"npu,", -1},+ {"+npu", -1},+ {"npu++gpu", -1},+ {"gpu,,npu", -1}};+ for (size_t i = 0; i < sizeof specs / sizeof *specs; i++) {+ int got = janas_devices_mask(specs[i].spec, why, sizeof why);+ CHECK(got == specs[i].mask, "devices \"%s\": %d, want %d",+ specs[i].spec, got, specs[i].mask);+ }+ CHECK(janas_devices_mask(NULL, why, sizeof why) == 0, "devices NULL");+ janas_devices_name(1 << 2 | 1 << 3, nm, sizeof nm);+ CHECK(!strcmp(nm, "npu,npu+gpu"), "name \"%s\"", nm);+ janas_devices_name(0, nm, sizeof nm);+ CHECK(!strcmp(nm, "auto"), "name \"%s\"", nm);+ CHECK(janas_devices_option("--prompt-on", "tpu", why, sizeof why) < 0 &&+ janas_devices_option("--ctx", "4096", why, sizeof why) == 0 &&+ janas_devices_option("--reply-on", NULL, why, sizeof why) < 0,+ "devices options");+printf("test_tuner: %s\n", failures ? "FAILED" : "ok");return failures ? 1 : 0;}diff --git a/tools/jns_neurons.c b/tools/jns_neurons.cnew file mode 100644index 0000000..e01e236--- /dev/null+++ b/tools/jns_neurons.c@@ -0,0 +1,449 @@+/* SPDX-License-Identifier: GPL-3.0-or-later+ Copyright (C) 2026 Maurizio Cammalleri */+/*+ * jns_neurons.c - rewrite a model file with the experts' down matrix by+ * neuron (JANAS_Q6_K_PN, quant.h): a row a neuron, its outputs across the+ * model's width, in Q6_K's three bit planes, so that the engine reads each+ * neuron of a token at the depth its contribution earns - six, four or two+ * bits, or none (model_neurons.c) - where by rows it reads every column.+ *+ * The rows are stored by block of 256 outputs - every neuron's block 0,+ * then every neuron's block 1 - since the engine reads a block of outputs+ * of a chunk of neurons at a time (quant.h janas_q6kpn_chunk): read by+ * neuron, the blocks of a chunk lay 820 bytes apart (Qwen3-4B) and the+ * hardware prefetcher did not follow them.+ *+ * Each output channel is divided by its root mean square over the neurons,+ * kept as a float before the rows (quant.h JANAS_Q6_K_PN) and multiplied+ * back after the sum: the few channels of the residual stream far larger+ * than the others would otherwise set the scales of every group of 16 they+ * fall in, and the others there would lose their bits.+ *+ * Layers whose down matrix is Q6_K, in planes or not, are converted; with+ * --q4k those in Q4_K too, whose six bits then read more bytes than the+ * Q4_K they come from. Each expert's down is unpacked, turned over and+ * quantized again to Q6_K by Janas's own quantizer (janas_q6k_quantize):+ * a second rounding at six bits, so the weights are close to the original+ * ones, not bit for bit. Gate, up, the other layers and the resident+ * weights are copied as they are.+ *+ * Usage: jns_neurons [--q4k] [--threads N] <in.jns> <out.jns>+ */+#include <fcntl.h>+#include <math.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <time.h>+#include <unistd.h>++#include "common/pool.h"+#include "llm/jns.h"+#include "llm/quant.h"++#define ALIGN JANAS_JNS_ALIGN++static uint64_t align_up(uint64_t v, uint64_t a)+{+ return (v + a - 1) / a * a;+}++/* Expert slots are sorted by the offset they have in the source file. */+static const uint64_t *sort_key;++static int by_offset(const void *a, const void *b)+{+ uint64_t x = sort_key[*(const uint32_t *)a];+ uint64_t y = sort_key[*(const uint32_t *)b];+ return x < y ? -1 : x > y ? 1 : 0;+}++static double now(void)+{+ struct timespec ts;+ clock_gettime(CLOCK_MONOTONIC, &ts);+ return ts.tv_sec + ts.tv_nsec * 1e-9;+}++static int write_at(int fd, const void *buf, size_t n, uint64_t off)+{+ const char *p = buf;+ while (n) {+ ssize_t w = pwrite(fd, p, n, (off_t)off);+ if (w <= 0)+ return -1;+ p += w;+ n -= (size_t)w;+ off += (uint64_t)w;+ }+ return 0;+}++static int read_at(int fd, void *buf, size_t n, uint64_t off)+{+ char *p = buf;+ while (n) {+ ssize_t r = pread(fd, p, n, (off_t)off);+ if (r <= 0)+ return -1;+ p += r;+ n -= (size_t)r;+ off += (uint64_t)r;+ }+ return 0;+}++/* Copies n bytes between two files, through a buffer. */+static int copy_region(int in, uint64_t src, int out, uint64_t dst, uint64_t n)+{+ enum { CHUNK = 8u << 20 };+ char *buf = malloc(CHUNK);+ if (!buf)+ return -1;+ while (n) {+ size_t c = n < CHUNK ? (size_t)n : CHUNK;+ if (read_at(in, buf, c, src) || write_at(out, buf, c, dst)) {+ free(buf);+ return -1;+ }+ src += c;+ dst += c;+ n -= c;+ }+ free(buf);+ return 0;+}++/* Whether layer l's down matrix is turned into neurons. */+static int converted(const struct janas_jns_layer *ly, int q4k)+{+ uint32_t t = ly->m[JANAS_JNS_DOWN].type;+ const struct janas_jns_matrix *d = &ly->m[JANAS_JNS_DOWN];+ return (t == JANAS_Q6_K || t == JANAS_Q6_K_P || (q4k && t == JANAS_Q4_K)) &&+ d->rows % JANAS_QK == 0 && d->cols % JANAS_QK == 0;+}++/* The source's down matrix of a slot, rows x cols floats (converted() has+ checked its type). */+static void unpack_down(const struct janas_jns_layer *so, const uint8_t *src,+ float *w)+{+ const struct janas_jns_matrix *d = &so->m[JANAS_JNS_DOWN];+ size_t nb = d->cols / JANAS_QK;+ for (uint32_t r = 0; r < d->rows; r++) {+ float *y = w + (size_t)r * d->cols;+ if (d->type == JANAS_Q6_K_P) {+ const struct janas_block_q6kp *base =+ (const struct janas_block_q6kp *)(src + d->offset) + r * nb;+ janas_q6kp_dequantize(+ base, src + so->plane[0].offset + r * nb * JANAS_Q6KP_PLANE,+ src + so->plane[1].offset + r * nb * JANAS_Q6KP_PLANE, y,+ d->cols);+ } else {+ size_t rb = nb * janas_qtype_block_size((int)d->type);+ janas_dequantize((int)d->type, src + d->offset + r * rb, y,+ d->cols);+ }+ }+}++struct job {+ const struct janas_jns *j;+ const struct janas_jns_layer *ly; /* the new layer table */+ const uint32_t *order;+ const uint64_t *new_off;+ uint64_t *new_sum;+ uint64_t n_slots, max_src, max_slot, total;+ int out;+ double t0;+ uint64_t next, done; /* atomic */+ int failed; /* atomic */+};++/* A slot rewritten: gate and up as they are, down by neuron. */+static int convert_slot(struct job *J, uint32_t s, uint8_t *src, uint8_t *dst,+ float *w, float *t, struct janas_block_q6k *q)+{+ const struct janas_jns *j = J->j;+ uint32_t l = s / j->h.n_expert;+ const struct janas_jns_layer *so = &j->layers[l], *ly = &J->ly[l];+ if (read_at(j->fd, src, so->slot_bytes, j->expert_offset[s]) != 0)+ return -1;+ memset(dst, 0, ly->slot_bytes);+ if (ly->m[JANAS_JNS_DOWN].type != JANAS_Q6_K_PN) {+ memcpy(dst, src, so->slot_bytes);+ } else {+ for (int m = 0; m < 2; m++)+ memcpy(dst + ly->m[m].offset, src + so->m[m].offset,+ so->m[m].bytes);+ const struct janas_jns_matrix *d = &so->m[JANAS_JNS_DOWN];+ uint32_t dm = d->rows, ff = d->cols;+ unpack_down(so, src, w);+ /* each output channel over its root mean square, which goes first:+ the channels of the residual stream far larger than the others+ would set the scales of every group they fall in */+ float *scale = (float *)(dst + ly->m[JANAS_JNS_DOWN].offset);+ for (uint32_t r = 0; r < dm; r++) {+ double ss = 0;+ for (uint32_t c = 0; c < ff; c++)+ ss += (double)w[(size_t)r * ff + c] * w[(size_t)r * ff + c];+ float rms = (float)sqrt(ss / ff);+ scale[r] = rms > 0.0f ? rms : 1.0f;+ }+ for (uint32_t r = 0; r < dm; r++) /* a row a neuron */+ for (uint32_t c = 0; c < ff; c++)+ t[(size_t)c * dm + r] = w[(size_t)r * ff + c] / scale[r];+ size_t nb = (size_t)ff * (dm / JANAS_QK), bpr = dm / JANAS_QK;+ janas_q6k_quantize(t, q, (size_t)ff * dm);+ /* by block of outputs: every neuron's block 0, then every neuron's+ block 1 - what the engine reads together lies together (w, done+ with, holds them) */+ struct janas_block_q6k *qb = (struct janas_block_q6k *)(void *)w;+ for (size_t jn = 0; jn < ff; jn++)+ for (size_t b = 0; b < bpr; b++)+ qb[b * ff + jn] = q[jn * bpr + b];+ janas_q6k_to_planes(+ qb, nb,+ (struct janas_block_q6kp *)(dst + ly->m[JANAS_JNS_DOWN].offset ++ dm * sizeof(float)),+ dst + ly->plane[0].offset, dst + ly->plane[1].offset);+ }+ J->new_sum[s] = janas_crc32(0, dst, (size_t)ly->slot_bytes);+ return write_at(J->out, dst, (size_t)ly->slot_bytes, J->new_off[s]);+}++static void worker(void *arg, int tid, int n_threads)+{+ (void)tid;+ (void)n_threads;+ struct job *J = arg;+ const struct janas_jns *j = J->j;+ size_t floats = 0;+ for (uint32_t l = 0; l < j->h.n_layer; l++) {+ const struct janas_jns_matrix *d = &j->layers[l].m[JANAS_JNS_DOWN];+ if (J->ly[l].m[JANAS_JNS_DOWN].type == JANAS_Q6_K_PN &&+ (size_t)d->rows * d->cols > floats)+ floats = (size_t)d->rows * d->cols;+ }+ uint8_t *src = malloc(J->max_src), *dst = malloc(J->max_slot);+ float *w = malloc((floats ? floats : 1) * sizeof(float));+ float *t = malloc((floats ? floats : 1) * sizeof(float));+ struct janas_block_q6k *q =+ malloc((floats / JANAS_QK + 1) * sizeof(struct janas_block_q6k));+ if (!src || !dst || !w || !t || !q)+ __atomic_store_n(&J->failed, 1, __ATOMIC_RELAXED);+ while (!__atomic_load_n(&J->failed, __ATOMIC_RELAXED)) {+ uint64_t i = __atomic_fetch_add(&J->next, 1, __ATOMIC_RELAXED);+ if (i >= J->n_slots)+ break;+ uint32_t s = J->order[i];+ if (convert_slot(J, s, src, dst, w, t, q) != 0) {+ fprintf(stderr, "\nexpert %u of layer %u: cannot convert\n",+ s % j->h.n_expert, s / j->h.n_expert);+ __atomic_store_n(&J->failed, 1, __ATOMIC_RELAXED);+ break;+ }+ uint64_t done = __atomic_add_fetch(&J->done, 1, __ATOMIC_RELAXED);+ if ((done & 255) == 0 || done == J->n_slots) {+ double dt = now() - J->t0;+ fprintf(stderr, "\r%5.1f%% %.1f GB in %.0f s ",+ 100.0 * (double)done / (double)J->n_slots,+ (double)J->total * (double)done / (double)J->n_slots / 1e9,+ dt);+ }+ }+ free(src);+ free(dst);+ free(w);+ free(t);+ free(q);+}++int main(int argc, char **argv)+{+ int q4k = 0, threads = (int)sysconf(_SC_NPROCESSORS_ONLN), a = 1;+ for (; a < argc && argv[a][0] == '-'; a++) {+ if (!strcmp(argv[a], "--q4k"))+ q4k = 1;+ else if (!strcmp(argv[a], "--threads") && a + 1 < argc)+ threads = atoi(argv[++a]);+ else+ break;+ }+ if (argc - a != 2 || threads < 1) {+ fprintf(+ stderr,+ "usage: jns_neurons [--q4k] [--threads N] <in.jns> <out.jns>\n");+ return 2;+ }+ const char *in = argv[a], *out_path = argv[a + 1];+ struct janas_jns j;+ char err[256];+ if (janas_jns_open(in, &j, err, sizeof(err)) != 0) {+ fprintf(stderr, "%s: %s\n", in, err);+ return 1;+ }+ uint32_t n_layer = j.h.n_layer, n_expert = j.h.n_expert;+ uint64_t n_slots = (uint64_t)n_layer * n_expert;++ /* the new layer table: gate, up and down's base plane first, then its+ other two planes, each level padded to a whole number of pages */+ struct janas_jns_layer *ly = calloc(n_layer, sizeof(*ly));+ uint64_t *new_off = malloc(n_slots * sizeof(uint64_t));+ uint64_t *new_sum = malloc(n_slots * sizeof(uint64_t));+ uint32_t *order = malloc(n_slots * sizeof(uint32_t));+ if (!ly || !new_off || !new_sum || !order)+ return 1;+ uint32_t turned = 0;+ for (uint32_t l = 0; l < n_layer; l++) {+ const struct janas_jns_layer *src = &j.layers[l];+ ly[l] = *src;+ if (!converted(src, q4k))+ continue;+ turned++;+ memset(ly[l].plane, 0, sizeof(ly[l].plane));+ const struct janas_jns_matrix *dn = &src->m[JANAS_JNS_DOWN];+ uint64_t nb = (uint64_t)dn->cols * (dn->rows / JANAS_QK);+ uint64_t off = 0;+ for (int m = 0; m < 3; m++) {+ ly[l].m[m].offset = off;+ if (m == JANAS_JNS_DOWN) {+ ly[l].m[m] = (struct janas_jns_matrix){+ .type = JANAS_Q6_K_PN,+ .rows = dn->cols, /* the neurons */+ .cols = dn->rows, /* the outputs */+ .offset = off,+ .bytes = (uint64_t)dn->rows * sizeof(float) ++ nb * sizeof(struct janas_block_q6kp)};+ }+ off = align_up(off + ly[l].m[m].bytes, 256);+ }+ ly[l].level_bytes[0] = align_up(off, ALIGN);+ for (int p = 0; p < 2; p++) {+ ly[l].plane[p] = ly[l].m[JANAS_JNS_DOWN];+ ly[l].plane[p].offset = ly[l].level_bytes[p];+ ly[l].plane[p].bytes = nb * JANAS_Q6KP_PLANE;+ ly[l].level_bytes[p + 1] =+ align_up(ly[l].plane[p].offset + ly[l].plane[p].bytes, ALIGN);+ }+ ly[l].slot_bytes = ly[l].level_bytes[2];+ }+ if (!turned) {+ fprintf(stderr, "%s: no down matrix to turn into neurons%s\n", in,+ q4k ? "" : " (Q4_K ones only with --q4k)");+ return 1;+ }++ /* header and tables: as the source's, the offsets after the resident+ weights moved by what the slots grew */+ struct janas_jns_header h = j.h;+ h.version = JANAS_JNS_VERSION;+ uint64_t layer_len = (uint64_t)n_layer * sizeof(struct janas_jns_layer);+ uint64_t slot_len = n_slots * sizeof(uint64_t);+ uint64_t dir_len = j.h.n_tensor * sizeof(struct janas_jns_tensor);+ h.layer_table_offset = ALIGN;+ h.expert_table_offset = h.layer_table_offset + layer_len;+ h.expert_sums_offset = h.expert_table_offset + slot_len;+ h.tensor_dir_offset = h.expert_sums_offset + slot_len;+ h.metadata_offset = h.tensor_dir_offset + dir_len;+ h.resident_offset = align_up(h.metadata_offset + h.metadata_bytes, ALIGN);+ h.experts_offset = align_up(h.resident_offset + h.resident_bytes, ALIGN);++ struct janas_jns_tensor *tensors =+ malloc(dir_len ? (size_t)dir_len : (size_t)1);+ if (!tensors)+ return 1;+ memcpy(tensors, j.tensors, (size_t)dir_len);+ int64_t shift = (int64_t)h.resident_offset - (int64_t)j.h.resident_offset;+ for (uint64_t t = 0; t < h.n_tensor; t++)+ tensors[t].offset = (uint64_t)((int64_t)tensors[t].offset + shift);++ /* the experts keep the order they have on disk (co-activation) */+ for (uint64_t i = 0; i < n_slots; i++)+ order[i] = (uint32_t)i;+ sort_key = j.expert_offset;+ qsort(order, (size_t)n_slots, sizeof(uint32_t), by_offset);++ uint64_t at = h.experts_offset;+ for (uint64_t i = 0; i < n_slots; i++) {+ uint32_t s = order[i];+ new_off[s] = at;+ at += ly[s / n_expert].slot_bytes;+ }+ h.experts_bytes = at - h.experts_offset;+ h.file_bytes = at;++ int out = open(out_path, O_WRONLY | O_CREAT | O_TRUNC, 0644);+ if (out < 0) {+ fprintf(stderr, "cannot create %s\n", out_path);+ return 1;+ }+ if (copy_region(j.fd, j.h.resident_offset, out, h.resident_offset,+ h.resident_bytes) != 0) {+ fprintf(stderr, "cannot copy the resident weights\n");+ return 1;+ }++ struct job J = {.j = &j,+ .ly = ly,+ .order = order,+ .new_off = new_off,+ .new_sum = new_sum,+ .n_slots = n_slots,+ .total = h.experts_bytes,+ .out = out,+ .t0 = now()};+ for (uint32_t l = 0; l < n_layer; l++) {+ if (ly[l].slot_bytes > J.max_slot)+ J.max_slot = ly[l].slot_bytes;+ if (j.layers[l].slot_bytes > J.max_src)+ J.max_src = j.layers[l].slot_bytes;+ }+ struct janas_pool *pool = janas_pool_create(threads, NULL);+ if (!pool)+ return 1;+ janas_pool_run(pool, worker, &J);+ janas_pool_destroy(pool);+ fprintf(stderr, "\n");+ if (J.failed || J.done != n_slots)+ return 1;++ /* tables last, with the checksums over what was written */+ uint64_t sum = JANAS_FNV_INIT;+ sum = janas_fnv1a(ly, (size_t)layer_len, sum);+ sum = janas_fnv1a(new_off, (size_t)slot_len, sum);+ sum = janas_fnv1a(new_sum, (size_t)slot_len, sum);+ sum = janas_fnv1a(tensors, (size_t)dir_len, sum);+ h.tables_checksum = sum;+ h.metadata_checksum = janas_crc32(0, j.metadata, (size_t)h.metadata_bytes);+ h.header_checksum = 0;+ h.header_checksum = janas_fnv1a(&h, sizeof(h), JANAS_FNV_INIT);++ uint8_t head[ALIGN];+ memset(head, 0, sizeof(head));+ memcpy(head, &h, sizeof(h));+ if (write_at(out, head, sizeof(head), 0) ||+ write_at(out, ly, (size_t)layer_len, h.layer_table_offset) ||+ write_at(out, new_off, (size_t)slot_len, h.expert_table_offset) ||+ write_at(out, new_sum, (size_t)slot_len, h.expert_sums_offset) ||+ write_at(out, tensors, (size_t)dir_len, h.tensor_dir_offset) ||+ write_at(out, j.metadata, (size_t)h.metadata_bytes,+ h.metadata_offset)) {+ fprintf(stderr, "cannot write the tables\n");+ return 1;+ }+ if (ftruncate(out, (off_t)h.file_bytes) != 0 || close(out) != 0) {+ fprintf(stderr, "cannot close %s\n", out_path);+ return 1;+ }+ printf("%s: %u layers, %u of them with the down matrix by neuron, "+ "%.1f GB\n",+ out_path, n_layer, turned, (double)h.file_bytes / 1e9);+ free(ly);+ free(new_off);+ free(new_sum);+ free(order);+ free(tensors);+ janas_jns_close(&j);+ return 0;+}