Skip to content

armgit / janas

Public Imported from GitHub
0

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

Release 2026-10-11: a mixture's prompt layer by layer on the GPU, its experts read ahead (Qwen3.6-35B-A3B +19%); models downloaded already converted from Hugging Face; a binary package built by GitHub Actions; the tuner leaves cores another program has taken

camauriab26273211e5
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..424f648
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,119 @@
+# SPDX-License-Identifier: GPL-3.0-or-later
+# Copyright (C) 2026 Maurizio Cammalleri
+#
+# The binary package of Janas for Linux x86-64: built on Ubuntu 22.04, so
+# that it runs with the C library of Ubuntu 22.04, Debian 12 and later;
+# tested; packed as janas-linux-x86_64.tar.gz with the SHA-256 of every
+# file. A tag v* publishes it as that tag's release (the name never
+# changes, so releases/latest/download/janas-linux-x86_64.tar.gz is always
+# the newest); run by hand, it only builds the package and keeps it as an
+# artifact of the run. The shaders' compiler and the Vulkan headers are
+# Khronos's own, at fixed versions: Ubuntu 22.04's are from 2022.
+name: release
+
+on:
+ push:
+ tags: ['v*']
+ workflow_dispatch:
+
+permissions:
+ contents: write
+
+env:
+ GLSLANG_VERSION: 16.6.0
+ GLSLANG_SHA256: 2c34071f56ecf39d16233294d3739cf43f981fd39080f2fd9dccb782101191ce
+ VULKAN_HEADERS_TAG: vulkan-sdk-1.4.363.0
+ VULKAN_HEADERS_COMMIT: 6802bb4733b63ed5efd3adb308a6c885ef180ea1
+ PACKAGE: janas-linux-x86_64
+
+jobs:
+ linux-x86_64:
+ runs-on: ubuntu-22.04
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: The shaders' compiler and the Vulkan headers
+ run: |
+ set -euo pipefail
+ mkdir -p "$RUNNER_TEMP/khronos"
+ cd "$RUNNER_TEMP/khronos"
+ curl -fsSL -o glslang.tar.gz \
+ "https://github.com/KhronosGroup/glslang/releases/download/$GLSLANG_VERSION/glslang-$GLSLANG_VERSION-linux-x86_64-release.tar.gz"
+ echo "$GLSLANG_SHA256 glslang.tar.gz" | sha256sum -c -
+ mkdir glslang && tar xzf glslang.tar.gz -C glslang
+ echo "$RUNNER_TEMP/khronos/glslang/bin" >> "$GITHUB_PATH"
+ git clone -q --depth 1 --branch "$VULKAN_HEADERS_TAG" \
+ https://github.com/KhronosGroup/Vulkan-Headers.git
+ test "$(git -C Vulkan-Headers rev-parse HEAD)" = "$VULKAN_HEADERS_COMMIT"
+ echo "CPATH=$RUNNER_TEMP/khronos/Vulkan-Headers/include" >> "$GITHUB_ENV"
+
+ - name: Build
+ run: |
+ set -euo pipefail
+ glslangValidator --version | head -1
+ ./build.sh release build 2>&1 | tee build.log
+ # the GPU's support must be in: without it the package would
+ # run on the CPU alone without a word
+ if grep -q "building without GPU support" build.log; then
+ echo "the build left the GPU out"; exit 1
+ fi
+
+ - name: Test
+ run: ./build.sh release test
+
+ - name: Pack
+ run: |
+ set -euo pipefail
+ B=bin/x86_64-linux
+ P="$PACKAGE/janas"
+ mkdir -p "$P/services" "$P/lib" "$P/include/janas" "$P/docs"
+ for f in janas-chat janas-server janas-get janas-bench janas-mcp \
+ gguf2jns jns_planes hf2jns_mtp jns_check; do
+ install -m 755 "$B/$f" "$P/"
+ done
+ for s in src/services/*/; do
+ s=$(basename "$s")
+ [ "$s" = common ] && continue
+ install -m 755 "$B/janas-$s" "$P/services/"
+ # each service's page, its links made to point beside it
+ install -m 644 "src/services/$s/README.md" "$P/services/janas-$s.md"
+ done
+ sed -E 's#\(([a-z]+)/README\.md\)#(janas-\1.md)#g' \
+ src/services/README.md > "$P/services/README.md"
+ install -m 755 "$B/libjanas_llm.so" "$B/libjanas_mcp.so" "$P/lib/"
+ install -m 644 include/janas/* "$P/include/janas/"
+ install -m 644 docs/*.md "$P/docs/"
+ install -m 644 dist/README.md "$P/README.md"
+ install -m 644 LICENSE ChangeLog.md MODELS.md "$P/"
+ # nothing but programs, libraries and text: no script of any kind
+ if find "$P" -type f \( -name '*.sh' -o -name '*.py' \) | grep -q .; then
+ echo "a script in the package"; exit 1
+ fi
+ # the newest C library the programs ask for
+ find "$P" -type f -perm -u+x ! -name '*.so' -print0 |
+ xargs -0 -n 1 objdump -T | grep -o 'GLIBC_[0-9.]*' |
+ sort -V | uniq | tail -1
+ (cd "$P" && find . -type f ! -name SHA256SUMS -print0 | sort -z |
+ xargs -0 sha256sum > SHA256SUMS)
+ tar -C "$PACKAGE" -czf "$PACKAGE.tar.gz" janas
+ sha256sum "$PACKAGE.tar.gz" > "$PACKAGE.tar.gz.sha256"
+ cat "$PACKAGE.tar.gz.sha256"
+
+ - name: Keep the package (run by hand)
+ if: github.event_name == 'workflow_dispatch'
+ uses: actions/upload-artifact@v4
+ with:
+ name: ${{ env.PACKAGE }}
+ path: |
+ ${{ env.PACKAGE }}.tar.gz
+ ${{ env.PACKAGE }}.tar.gz.sha256
+
+ - name: Publish the release (a tag)
+ if: startsWith(github.ref, 'refs/tags/v')
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ gh release create "$GITHUB_REF_NAME" \
+ "$PACKAGE.tar.gz" "$PACKAGE.tar.gz.sha256" \
+ --title "Janas $GITHUB_REF_NAME" \
+ --notes "Janas for Linux x86-64 (Ubuntu 22.04, Debian 12 and later). Unpack it and start: ./janas-get list, then ./janas-chat <model>. What changed: ChangeLog.md. The SHA-256 of every file: SHA256SUMS in the package."
diff --git a/ChangeLog.md b/ChangeLog.md
index 7301576..28d65b6 100644
--- a/ChangeLog.md
+++ b/ChangeLog.md
@@ -2,6 +2,21 @@
> Curated, user-facing summary of completed work, newest first.
+## [2026-10-11] - Models downloaded already converted
+
+- **`janas-get` downloads the `.jns` files themselves**, from the project's repositories on Hugging Face (`prabanta-dev/<model>-JNS`): no conversion on your machine, half the room on disk, every file checked against the same fingerprints of MODELS.md. `--from-gguf` keeps the old way (the original GGUF, converted here), and `janas-get` takes it by itself where a converted file is not on Hugging Face; `janas-get hf:<owner>/<repo>/<file.jns>` takes any `.jns`. `janas-get list` shows the size of the converted files.
+
+## [2026-10-10] - The tuner leaves cores another program has taken
+
+- **The threads move as soon as they turn slow.** With another program busy on the efficiency cores, Qwen3.5-2B's tokens on 20 threads took 680-850 ms each against 22 on 6 or 12, and the tuner moved them only after 645 tokens: the 6 and 12 took the tries in turn and each counted only its own wins, and the first try came 128 passes in. Now a pass of the choice twice as slow as its mean brings a try at once, a try twice as fast moves the threads, wins by any other threads count together, and the next try comes 16 passes after one that won. A reply of 3,000 tokens under that load: 584 s before, 57 s now; without it, nothing moves (38 s, the same threads). `JANAS_TUNE_TRACE=1` prints the tuner's tries and moves.
+
+## [2026-10-10] - A mixture's prompt layer by layer on the GPU
+
+- **A mixture's prompt blocks read on the GPU alone, a layer a submission** (qwen3moe, qwen35moe, integrated GPUs). Each layer is one submission - attention or Gated DeltaNet, norms, shared expert, router and its choice of experts - and between two of them the CPU only sorts the router's choice by expert, asks the expert cache for their slots and has the next layer's experts read ahead while the GPU computes; the experts' products, their activation and each token's weighted sum stay on the GPU. Reading 1,024 tokens on the development laptop: Qwen3.6-35B-A3B at four bits, 59% of its experts in the cache, 85.6 -> 101.9 tok/s, the cache finding 96% of the experts it is asked for instead of 87%. Against Qwen's Q8_0 the most likely token agrees as often (250 against 249 of 256 on code, 234 against 238 and 234 against 234 on Italian), the mean difference equal or smaller. Qwen3-30B-A3B, its experts all in memory, comes out even (130.6 against 130.0 over three runs each), with the CPU free during the prompt.
+- **On by itself where the memory allows it**: where the expert cache holds half a model's experts or more - the 30B and the 35B on a 32 GB machine, larger models on larger ones. A smaller cache keeps the way the experts were shared between CPU and GPU, not measured below that yet; so do experts whose down matrices are plain Q6_K (Qwen3-Coder-30B-A3B read 116.9 tok/s that way instead of 131.5). bartowski's Qwen3-30B-A3B came out even (127.0 against 128.4). `JANAS_GPU_MOE=1` takes any mixture, `0` none. The CPU-only engine is unchanged.
+- **The experts' shader on the GPU reads Q6_K in planes at four and two bits too**, not only at six: a model whose experts are read at fewer bits (`--bits 4`, Qwen3.6-35B-A3B on a 32 GB machine) gets its experts' down products on the GPU.
+- **`janas-bench --settle <seconds>`** waits after the warm-up for the expert cache's background filling to end before measuring.
+
## [2026-10-10] - Prompts read on the GPU, faster than llama.cpp on the same GPU
- **The fast prompt, on by default.** A prompt's blocks go to the GPU's tiled products - Q4_K, Q5_K, Q6_K (plain and in planes), Q8_0, f32 and bf16 weights, a mixture's experts in one launch per layer, the GPU taking 60% of their tokens while the CPU computes the rest - and on the dense Qwen3 and Qwen3.5 models the whole block, every layer, goes to the GPU in one submission while the CPU rests. They round the sums group by group, so a prompt is no longer 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). A reply's tokens are as before. `JANAS_GPU_FAST_PROMPT=0` reads prompts the exact way.
diff --git a/README.md b/README.md
index 7a127df..6a4e31d 100644
--- a/README.md
+++ b/README.md
@@ -66,7 +66,7 @@ Everything the engine does is chosen from what it measures, so another machine w
- **`janas-bench`:** measures the machine, fills its profile and writes a report.
- **Faster replies** from drafts the model verifies, so the text is exactly the one it would have written: from the model's own multi-token prediction block where it has one, from the conversation where it does not, or from a small model of the same family given with `--draft`.
- **Optional GPU** (Vulkan 1.3, integrated or discrete), used only where the engine measures that it helps, for every quantized type the CPU reads. A reply's tokens are identical with and without it; a prompt is read with the fast prompt (next).
-- **The fast prompt**, on by default since 10 October 2026: a prompt's blocks go to the GPU's tiled products (Q4_K, Q5_K, Q6_K, Q8_0, the experts of a mixture in one launch per layer, f32 and bf16 weights), and on the dense Qwen3 and Qwen3.5 models the whole block - every layer, attention, Qwen3.5's recurrent layers - goes to the GPU in one submission while the CPU rests: on a laptop the CPU working beside the GPU takes the power the GPU would use. They round the sums group by group, so a prompt is not read to the bit as the CPU reads it; against the references the most likely token agrees as often as the exact way (within 2-3 of 256 on every model measured, the mean difference of the scores within 2%). On the development laptop Qwen3-4B reads the table's prompt (below) at 220 tok/s with it and at 85 without the GPU, and every model compared reads faster than llama.cpp does on the same GPU. `JANAS_GPU_FAST_PROMPT=0` reads them the exact way.
+- **The fast prompt**, on by default since 10 October 2026: a prompt's blocks go to the GPU's tiled products (Q4_K, Q5_K, Q6_K, Q8_0, the experts of a mixture in one launch per layer, f32 and bf16 weights), and on the dense Qwen3 and Qwen3.5 models the whole block - every layer, attention, Qwen3.5's recurrent layers - goes to the GPU in one submission while the CPU rests, and on the Qwen3 and Qwen3.6 mixtures a layer a submission, the CPU only sorting the router's choice and reading the next layer's experts ahead (where the expert cache holds half the experts or more; `JANAS_GPU_MOE=0` or `1` decides instead): on a laptop the CPU working beside the GPU takes the power the GPU would use. They round the sums group by group, so a prompt is not read to the bit as the CPU reads it; against the references the most likely token agrees as often as the exact way (within 2-3 of 256 on every model measured, the mean difference of the scores within 2%). On the development laptop Qwen3-4B reads the table's prompt (below) at 220 tok/s with it and at 85 without the GPU, and every model compared reads faster than llama.cpp does on the same GPU. `JANAS_GPU_FAST_PROMPT=0` reads them the exact way.
- **Experts read ahead** when the expert cache is too small for the model: the next layer's router is applied early and the experts it picks that are not in memory are read from disk while the current layer computes. It turns itself on only when the cache misses many experts a token (Qwen3-Next-80B with a 4 GiB cache: +6%) and changes no result. A long prompt is read the same way, block by block: the next layer's router is applied to the whole block and the experts most of its tokens will want are read while the current layer computes; on after a block that missed many experts. Qwen3-Next-80B reading 4,096 tokens: 36.8 to 42.0 tokens/s with a 4 GiB cache, 48.5 to 50.0 with 16 GiB (the 256 tokens written after it 1.4% slower, the cache holding other experts); Qwen3-30B-A3B, whose experts all fit, even. `JANAS_PREFETCH_PREFILL=0` turns it off.
- **Light experts not in memory are left out** when the expert cache holds less than a fifth of the experts: an expert the router weighs below 0.8/k of a token (0.95/k under a tenth), and that would have to be read from disk, is not read and not computed, and the token's other experts take its share — the cache-conditional routing of Skliar et al. (TMLR 2025). Until 8 October 2026 the engine dropped the lightest experts whether in memory or not (six of ten, or eight). Qwen3-Next-80B, four bits, 400 tokens against llama.cpp, most likely token agreeing and tokens/s: with a 2 GiB cache all ten 393 at 11.0, six 383 at 20.9, now 380 at 26.4; with 4 GiB 393 at 20.7, six 383 at 27.6, now 384 at 27.7, with the mean logit difference 0.36 against 0.53; on Italian prose with 8 GiB 382 at 18.7, eight 361 at 21.4, now 372 at 23.7. On Qwen3-30B-A3B and Qwen3.6-35B-A3B with caches of 9% and 18% of their experts (1.5-3.5 GiB), on code and Italian prose, it was faster than the old way every time, by 9-37% (Qwen3-30B-A3B with 3 GiB: 28.7 tokens/s against 24.4, 381 tokens agreeing of 400 against 377), with a mean logit difference as low or lower in seven of the eight; it agreed on fewer most likely tokens in two (Italian, 64 tokens: 47 against 54 on the 30B with 3 GiB). `/experts n` (or `0`) asks for a number of experts and turns it off.
- **Every weight type near the memory's speed**, and the same results to the bit on every path (AVX2, AVX-VNNI, GPU) for a reply's tokens (and for a prompt with `JANAS_GPU_FAST_PROMPT=0`). `tests/bench_kernels` measures each type's product on its own: writing a token, on 12 threads of the development laptop, Q8_0 84 GB/s, Q6_K 73, Q4_K 69, the other 4- and 5-bit types 59-68, Q3_K 61 (48 until 9 October 2026, when its unpacking went through the stack), IQ3_S 25, against the 81 GB/s the memory gives; and a token of Qwen3-Next-80B-A3B, Qwen3.6-35B-A3B, Qwen3-30B-A3B or a 27B, phase by phase, reads its weights at 59-62 GB/s on average. Until 6 October 2026 the Q3_K, IQ4_XS and IQ3_S products were six to thirteen times slower than that (their kernels converted a scale by calling a function), which made unsloth's UD files, which mix those types in, write at half their speed: Qwen3.8-27B UD-Q4_K_XL went from 1.7 tokens/s to 3.6.
@@ -135,7 +135,7 @@ sudo pacman -S vulkan-headers glslang vulkan-tools # the same, Arch
## Getting a model
-**The short way: `janas-get`.** One command downloads a model from Hugging Face, checks the SHA-256 of every file against [MODELS.md](MODELS.md), converts it and makes its prediction file beside it (an MTP block, Gemma 4's assistant, or for Qwen3-4B the small Qwen3-0.6B that guesses its tokens), which the chat then finds by itself. The models go to `~/.local/share/janas/models`, or wherever `JANAS_MODELS` or `--dir` says:
+**The short way: `janas-get`.** One command downloads a model already converted, from the project's own repositories on Hugging Face ([prabanta-dev](https://huggingface.co/prabanta-dev)), with its prediction file (an MTP block, Gemma 4's assistant, or for Qwen3-4B the small Qwen3-0.6B that guesses its tokens), which the chat then finds by itself, and checks the SHA-256 of every file against [MODELS.md](MODELS.md). The models go to `~/.local/share/janas/models`, or wherever `JANAS_MODELS` or `--dir` says:
```sh
bin/x86_64-linux/janas-get list # the models it knows
@@ -143,7 +143,7 @@ bin/x86_64-linux/janas-get gemma-4-e4b # into ~/.local/share/janas/mod
bin/x86_64-linux/janas-chat ~/.local/share/janas/models/gemma-4-e4b-it-q4km.jns
```
-A download stopped halfway resumes where it stopped, a file already there is checked rather than fetched again, and the GGUF goes once converted (`--keep` keeps it). Any other GGUF: `janas-get hf:<owner>/<repo>/<file.gguf>`, checked against the SHA-256 Hugging Face lists for it. The memory column of `janas-get list` is the smallest machine each model is meant for. The rest of this section is the same by hand.
+A download stopped halfway resumes where it stopped, and a file already there is checked rather than fetched again. `--from-gguf` takes the other way: the original GGUF the catalog names, downloaded and converted on your machine to the very same fingerprints (the GGUF goes once converted, `--keep` keeps it); `janas-get` takes it by itself where a converted file is not on Hugging Face. Any other file: `janas-get hf:<owner>/<repo>/<file.jns|file.gguf>`, checked against the SHA-256 Hugging Face lists for it. The memory column of `janas-get list` is the smallest machine each model is meant for. The rest of this section is the same by hand.
Janas reads its own format, `.jns`, converted from a **Q4_K_M** GGUF (Q3_K, IQ3_S, IQ4_NL, IQ4_XS, Q4_0, Q4_1 and Q5_1 convert too, and so do unsloth's "UD" files made of them; IQ2 and IQ1 types, not yet). Keep both in `models/` next to the sources — the tools take a path, so anywhere works, but that is where these examples put them, and where the project keeps its own.
diff --git a/dist/README.md b/dist/README.md
new file mode 100644
index 0000000..0a4e5f2
--- /dev/null
+++ b/dist/README.md
@@ -0,0 +1,59 @@
+# 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 was faster than llama.cpp on every model compared on that laptop (Intel Core Ultra 9 185H, its integrated Arc GPU, 32 GB of memory, an NVMe SSD), measured on 9 and 10 October 2026:
+
+| Model | reading a prompt: Janas | llama.cpp | writing: Janas | llama.cpp |
+|---|---:|---:|---:|---:|
+| Qwen3-0.6B | 938 tok/s | 687 tok/s | 131 tok/s | 44 tok/s |
+| Qwen3.5-2B | 441 tok/s | 323 tok/s | 52 tok/s | 28 tok/s |
+| Qwen3-4B | 193 tok/s | 164 tok/s | 27 tok/s | 18 tok/s |
+| Qwen3.5-9B | 111 tok/s | 78 tok/s | 14 tok/s | 8.7 tok/s |
+| Qwen3-30B-A3B | 135 tok/s | 122 tok/s | 32 tok/s | 15 tok/s |
+| Qwen3.6-35B-A3B | 88 tok/s | 78 tok/s | 20 tok/s | 11 tok/s |
+| Qwen3-Next-80B-A3B (48.4 GB, more than the memory) | 62 tok/s | 16 tok/s | 24 tok/s | 2.8 tok/s |
+| Gemma-4-E2B-it | 191 tok/s | 150 tok/s | 38 tok/s | 19 tok/s |
+| Gemma-4-E4B-it | 122 tok/s | 109 tok/s | 20 tok/s | 15 tok/s |
+| Gemma-4-12B-it | 65 tok/s | 46 tok/s | 9.9 tok/s | 7.1 tok/s |
+| Gemma-4-26B-A4B-it | 84 tok/s | 76 tok/s | 18 tok/s | 12 tok/s |
+
+Qwen3-0.6B in one round, the others as the project's README gives them. 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 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.
+
+## Start
+
+```sh
+./janas-get list # the models it knows, their size, the memory they want
+./janas-get qwen3-4b # downloads it, checked, into ~/.local/share/janas/models
+./janas-chat qwen3-4b # and talk to it
+```
+
+`./janas-chat` with no model shows the list and downloads the one you choose, after asking. The models come already converted from Hugging Face ([prabanta-dev](https://huggingface.co/prabanta-dev)), each file checked against the fingerprints of `MODELS.md`.
+
+## What is here
+
+| | |
+|---|---|
+| `janas-chat` | a chat in the terminal: line editor, history, the reasoning shown apart, a context that slides instead of ending, the tools of MCP servers and of Janas's own services |
+| `janas-server` | the model served over HTTP with an API that follows OpenAI's: chat completions (tools, JSON schemas), completions, responses, embeddings, and llama.cpp's route for filling in code in editors |
+| `janas-get` | downloads a model of the catalog, checked; `--from-gguf` converts the original GGUF here instead |
+| `janas-bench` | measures what this machine does with a model, every configuration the engine can use, and fills the profile it starts from next time |
+| `janas-mcp` | the model as an MCP server for other clients (Claude Code, an editor): a question to it, the embedding of a text |
+| `gguf2jns` | converts a GGUF file (Q4_K_M and the other types `MODELS.md` lists) to the `.jns` file Janas reads |
+| `jns_planes` | cuts the experts of a converted mixture into bit planes, so that fewer bits can be read when the memory is short |
+| `hf2jns_mtp` | makes a model's multi-token prediction block from its original checkpoint |
+| `jns_check` | what a `.jns` file says about itself: architecture, sizes, types, licence |
+| `services/` | Janas's services, which bring data of the world to a model: flights, weather, maps, prices, earthquakes, Wikipedia, GitHub, git, this computer. `janas-chat` starts them by itself; any other MCP client can use them. See `services/README.md` |
+| `lib/`, `include/` | `libjanas_llm` and `libjanas_mcp` with their C headers and FreeBASIC bindings, for programs of your own; the programs above do not need them |
+
+## Needs
+
+- 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).
+
+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>).
+
+## Licence
+
+Janas is under the GNU General Public License, version 3 or later: `LICENSE`. The models are not part of it and keep their own licences: `MODELS.md`.
diff --git a/src/bench/main.c b/src/bench/main.c
index 9197ab6..d5207f1 100644
--- a/src/bench/main.c
+++ b/src/bench/main.c
@@ -11,6 +11,10 @@
* [--gen <tokens>] [--ctx <tokens>] [--cache <GiB>]
* [--reserve <GiB>]
* [--rounds <n>] (default 3, alternating the order)
+ * [--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
+ * chat runs after its first minutes)
*
* The prompt is prose that does not repeat itself (only a prompt longer
* than the text repeats it, and the report says so). The drafts of the
@@ -179,7 +183,8 @@ int main(int argc, char **argv)
if (argc < 2 || argv[1][0] == '-') {
fprintf(stderr, "usage: janas-bench <model.jns> [--mtp <file>] "
"[--prompt <tokens>] [--gen <tokens>] [--ctx <tokens>] "
- "[--cache <GiB>] [--reserve <GiB>] [--rounds <n>]\n");
+ "[--cache <GiB>] [--reserve <GiB>] [--rounds <n>] "
+ "[--settle <seconds>]\n");
return 2;
}
struct janas_llm_params p;
@@ -188,9 +193,10 @@ int main(int argc, char **argv)
p.n_ctx = 4096;
uint32_t n_prompt = 256, n_gen = 64;
int rounds = 3;
- static const char *const options[] = {"--mtp", "--prompt", "--gen",
- "--ctx", "--rounds", "--cache",
- "--reserve"};
+ long long settle = 0;
+ static const char *const options[] = {"--mtp", "--prompt", "--gen",
+ "--ctx", "--rounds", "--cache",
+ "--reserve", "--settle"};
for (int i = 2; i < argc; i += 2) {
const char *a = argv[i], *v = i + 1 < argc ? argv[i + 1] : NULL;
char why[200] = "";
@@ -210,6 +216,8 @@ int main(int argc, char **argv)
else
rounds = x < 1000 ? (int)x : 1000;
}
+ } else if (strcmp(a, "--settle") == 0) {
+ janas_word_int(v, 0, 86400, &settle, why, sizeof why);
} else if (strcmp(a, "--cache") == 0 || strcmp(a, "--reserve") == 0) {
if (janas_word_real(v, 0, 1 << 20, &r, why, sizeof why) == 0)
*(a[2] == 'c' ? &p.cache_bytes : &p.reserve_bytes) =
@@ -310,6 +318,30 @@ int main(int argc, char **argv)
out("generation failed\n");
return 1;
}
+ if (settle > 0) {
+ /* the filling runs while nobody asks: wait until it has stopped
+ (not filling, and no expert more for 3 s: it may not have
+ resumed yet when first asked) */
+ struct timespec t0, t1, nap = {.tv_sec = 1};
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+ uint64_t last = janas_llm_model_warm_done(m);
+ int still = 0;
+ do {
+ nanosleep(&nap, NULL);
+ clock_gettime(CLOCK_MONOTONIC, &t1);
+ uint64_t now_in = janas_llm_model_warm_done(m);
+ still =
+ janas_llm_model_settling(m) || now_in != last ? 0 : still + 1;
+ last = now_in;
+ } while (still < 3 && t1.tv_sec - t0.tv_sec < settle);
+ out("waited %lld s for the cache's filling (%llu experts in)%s\n",
+ (long long)(t1.tv_sec - t0.tv_sec), (unsigned long long)last,
+ still < 3 ? ", not over" : "");
+ if (measure(m, prompt, n_prompt, n_gen, NULL, &d) != 0) {
+ out("generation failed\n");
+ return 1;
+ }
+ }
int th[16], gp[16];
int nc = janas_llm_model_candidates(m, th, gp, 16);
diff --git a/src/chat/main.c b/src/chat/main.c
index 8cf2de1..cfe7cbd 100644
--- a/src/chat/main.c
+++ b/src/chat/main.c
@@ -241,7 +241,7 @@ static void usage(void)
"usage: janas-chat [model] [options]\n"
" model a .jns file, or a name of the catalog (none: the\n"
" list, to choose one; a model not here yet is\n"
- " downloaded and converted, after asking)\n"
+ " downloaded, after asking)\n"
" --profile <quality|fast>\n"
" quality (default): answers as the file gives\n"
" them; fast: also what was measured faster on\n"
diff --git a/src/chat/mcp_chat.c b/src/chat/mcp_chat.c
index 0df645f..db39139 100644
--- a/src/chat/mcp_chat.c
+++ b/src/chat/mcp_chat.c
@@ -381,8 +381,8 @@ int mcpc_start(const char *path)
int mcpc_start_services(void)
{
- /* beside the program: bin/x86_64-linux/janas-chat-asan has
- janas-flights-asan beside it */
+ /* in services/ beside the program (the binary package), else beside
+ it: bin/x86_64-linux/janas-chat-asan has janas-flights-asan there */
char self[4096];
ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
if (n <= 0)
@@ -399,9 +399,12 @@ int mcpc_start_services(void)
for (size_t k = 0; k < n_servers; k++)
taken |= strcmp(servers[k].name, SERVICES[i].name) == 0;
char path[4200];
- snprintf(path, sizeof path, "%s/janas-%s%s", self, SERVICES[i].name,
- suffix);
struct stat st;
+ snprintf(path, sizeof path, "%s/services/janas-%s%s", self,
+ SERVICES[i].name, suffix);
+ if (stat(path, &st) != 0 || !(st.st_mode & S_IXUSR))
+ snprintf(path, sizeof path, "%s/janas-%s%s", self, SERVICES[i].name,
+ suffix);
if (taken || stat(path, &st) != 0 || !(st.st_mode & S_IXUSR))
continue;
const char *argv[] = {path};
diff --git a/src/chat/models.c b/src/chat/models.c
index aecc36c..fc5c9d6 100644
--- a/src/chat/models.c
+++ b/src/chat/models.c
@@ -73,8 +73,8 @@ static void list(const char *dir)
fprintf(stderr,
"%2d. %s%s\n %s; %.1f GB to download, %d GB of "
"memory or more\n",
- ++k, m->name, is_file(p) ? " (here)" : "", m->what, m->gguf_gb,
- m->ram_gb);
+ ++k, m->name, is_file(p) ? " (here)" : "", m->what,
+ m->jns_repo ? m->jns_gb : m->gguf_gb, m->ram_gb);
}
fputc('\n', stderr);
}
@@ -218,10 +218,18 @@ int chat_model_resolve(const char *arg, struct chat_model *cm)
if (is_file(cm->path))
return 0;
char q[512];
- snprintf(q, sizeof(q),
- "%s is not here: download it (%.1f GB, and about %.0f GB free "
- "while it is converted) with its prediction file?",
- m->name, m->gguf_gb, m->gguf_gb * 2.0 + 0.5);
+ /* converted already, from Hugging Face (janas-get); the catalog's
+ GGUF converted here only where that file is missing there */
+ if (m->jns_repo)
+ snprintf(q, sizeof(q),
+ "%s is not here: download it (%.1f GB) with its prediction "
+ "file?",
+ m->name, m->jns_gb);
+ else
+ snprintf(q, sizeof(q),
+ "%s is not here: download it (%.1f GB, and about %.0f GB "
+ "free while it is converted) with its prediction file?",
+ m->name, m->gguf_gb, m->gguf_gb * 2.0 + 0.5);
if (!chat_ask_yes(q))
return -1;
if (fetch(m, cm->dir) != 0 || !is_file(cm->path)) {
diff --git a/src/common/catalog.c b/src/common/catalog.c
index dd5269d..8d692b7 100644
--- a/src/common/catalog.c
+++ b/src/common/catalog.c
@@ -32,6 +32,8 @@ const struct janas_model_entry janas_catalog[] = {
{"ac2d97712095a558e31573f62f466a3f9d93990898b0ec79d7c974c1780d524a"},
.gguf_gb = 0.40,
.out = "qwen3-0.6b-q4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3-0.6B-JNS",
+ .jns_gb = 0.40,
.flat_sha =
"9174da760919b16b9f3a4ae8738c2d53605412f40bb2c0fe68d60174bf8a4fb5",
.ram_gb = 2,
@@ -44,6 +46,8 @@ const struct janas_model_entry janas_catalog[] = {
{"7485fe6f11af29433bc51cab58009521f205840f5b4ae3a32fa7f92e8534fdf5"},
.gguf_gb = 2.5,
.out = "qwen3-4b-q4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3-4B-JNS",
+ .jns_gb = 2.50,
.flat_sha =
"e8ed44bdd3c612ce3ec1204a4b9db671115efab4a2ada384c70cf6492d430291",
.jns_sha =
@@ -63,6 +67,8 @@ const struct janas_model_entry janas_catalog[] = {
{"fbe1d5edd4ce802ae3ae7c7e4ab7d09789d697fdac1fc7929f8df4ca3c41bae3"},
.gguf_gb = 2.5,
.out = "qwen3-4b-bq4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3-4B-JNS",
+ .jns_gb = 2.50,
.flat_sha =
"aa4f0bc6033a206ba5ac51dcdd799299d369019d5614dc08a6baa0bda6123098",
.jns_sha =
@@ -79,6 +85,8 @@ const struct janas_model_entry janas_catalog[] = {
{"bd258782e35f7f458f8aced1adc053e6e92e89bc735ba3be89d38a06121dc517"},
.gguf_gb = 0.53,
.out = "qwen3.5-0.8b-q4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3.5-0.8B-JNS",
+ .jns_gb = 0.53,
.flat_sha =
"75a3b62c4a10cad87a7ce64bf89485cfcc564fa949f2c5af8c7051615dc26124",
.ram_gb = 2,
@@ -93,6 +101,8 @@ const struct janas_model_entry janas_catalog[] = {
{"aaf42c8b7c3cab2bf3d69c355048d4a0ee9973d48f16c731c0520ee914699223"},
.gguf_gb = 1.28,
.out = "qwen3.5-2b-q4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3.5-2B-JNS",
+ .jns_gb = 1.33,
.flat_sha =
"286118ea3ad1903890a593582e22bed82859bf7c38b0ff9ed043050e5bd572a6",
.extra = JANAS_EXTRA_HF2JNS,
@@ -110,6 +120,8 @@ const struct janas_model_entry janas_catalog[] = {
{"03b74727a860a56338e042c4420bb3f04b2fec5734175f4cb9fa853daf52b7e8"},
.gguf_gb = 5.68,
.out = "qwen3.5-9b-q4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3.5-9B-JNS",
+ .jns_gb = 5.83,
.flat_sha =
"e40ec6c58ef2390c7a4ce8c9b7b6b384ed4e55c9980f646d1c98e83e2c018115",
.extra = JANAS_EXTRA_HF2JNS,
@@ -127,6 +139,8 @@ const struct janas_model_entry janas_catalog[] = {
{"0d003f6662faee786ed5da3e31b29c978de5ae5d275c8794c606a7f3c01aa8f5"},
.gguf_gb = 18.6,
.out = "qwen3-30b-a3b-q4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3-30B-A3B-JNS",
+ .jns_gb = 18.56,
.flat_sha =
"6906de51f2923b3be3a83eb040eaaeb090cba3389e9217648abe08bd678376e9",
.jns_sha =
@@ -148,6 +162,8 @@ const struct janas_model_entry janas_catalog[] = {
{"f1b8111d3e49a0238fcaa77ec9ee24eb9805266b5e85bf8e54c12dedb02cf4ff"},
.gguf_gb = 13.8,
.out = "qwen3-30b-a3b-udq3kxl.jns",
+ .jns_repo = "prabanta-dev/Qwen3-30B-A3B-JNS",
+ .jns_gb = 13.83,
.flat_sha =
"7a77e62a3d6b1df321f455472e0b970a09eb3534ec76982a6e169087d4897656",
.ram_gb = 8,
@@ -165,6 +181,8 @@ const struct janas_model_entry janas_catalog[] = {
{"a015794bfb1d69cb03dbb86b185fb2b9b339f757df5f8f9dd9ebdab8f6ed5d32"},
.gguf_gb = 18.6,
.out = "qwen3-30b-a3b-bq4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3-30B-A3B-JNS",
+ .jns_gb = 18.63,
.flat_sha =
"c2089d293f10d2e0fdabbb7ea6f17d6834f3027480de987fb6dd718e301eaa04",
.jns_sha =
@@ -179,6 +197,8 @@ const struct janas_model_entry janas_catalog[] = {
{"b46fedd33e0bfb0cae308aa3c158d0a4b2c4a1d2185a1ed6f093cdaf39064772"},
.gguf_gb = 22.3,
.out = "qwen3.6-35b-a3b-q4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3.6-35B-A3B-JNS",
+ .jns_gb = 22.29,
.flat_sha =
"31772037300f332d712f4ef8dd5e7251c7cd76cf6b9dab33b089394b7c079fb2",
.jns_sha =
@@ -193,6 +213,8 @@ const struct janas_model_entry janas_catalog[] = {
{"d103b2733ec1012a52d01edda66b7e5c24ae50508c9f99f5297ea459ef3c061a"},
.gguf_gb = 48.4,
.out = "qwen3-next-80b-a3b-q4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3-Next-80B-A3B-Instruct-JNS",
+ .jns_gb = 49.35,
.flat_sha =
"fa9a50dd910de4e78064ecff17aef43286694277eea3a89a57e9921ca2bfd2da",
.jns_sha =
@@ -219,6 +241,8 @@ const struct janas_model_entry janas_catalog[] = {
"249c768cc5f130dc731567d6edcbdacc48e14dec9e02c5dbe2b2185d2c5bdb2b"},
.gguf_gb = 48.4,
.out = "qwen3-coder-next-q4km.jns",
+ .jns_repo = "prabanta-dev/Qwen3-Coder-Next-JNS",
+ .jns_gb = 48.41,
.flat_sha =
"5912d964247002473eff1811058b4ffadf7b9bb47ae336c486cdf2964de68382",
.jns_sha =
@@ -233,6 +257,8 @@ const struct janas_model_entry janas_catalog[] = {
{"06507c7b42688469c4e7298b0a1e16deff06caf291cf0a5b278c308249c3e439"},
.gguf_gb = 0.64,
.out = "qwen3-embedding-0.6b-q8.jns",
+ .jns_repo = "prabanta-dev/Qwen3-Embedding-0.6B-JNS",
+ .jns_gb = 0.64,
.flat_sha =
"1e8eb8cbeba7a1a657354d259c5730bb79f6087160a9ca8da901bd08bdbe943f",
.ram_gb = 2,
@@ -245,6 +271,8 @@ const struct janas_model_entry janas_catalog[] = {
{"740185b21d22ceb83a11c3aa62ad5842ef32c70f6096d756bbee85a1e4ec34b8"},
.gguf_gb = 3.1,
.out = "gemma-4-e2b-it-q4km.jns",
+ .jns_repo = "prabanta-dev/gemma-4-E2B-it-JNS",
+ .jns_gb = 3.21,
.flat_sha =
"1f18e08878df41f377d563b38048d41841c7973ddea845cd9672fcf23cbd864b",
.extra = JANAS_EXTRA_GGUF,
@@ -263,6 +291,8 @@ const struct janas_model_entry janas_catalog[] = {
{"85a896a047553e842f25297ee5b031d64ff30147d9c4af17b1e4b394cd1fab87"},
.gguf_gb = 5.0,
.out = "gemma-4-e4b-it-q4km.jns",
+ .jns_repo = "prabanta-dev/gemma-4-E4B-it-JNS",
+ .jns_gb = 5.08,
.flat_sha =
"7ec828e9bdc1ada2eda907e93b87072f3180f2e8cba5ccedcd360d1a53858675",
.extra = JANAS_EXTRA_GGUF,
@@ -281,6 +311,8 @@ const struct janas_model_entry janas_catalog[] = {
{"0a270ec9fe6b34f4a0d33992b6135117b484ebc4766ab76b51d4ae8c457e4c42"},
.gguf_gb = 7.1,
.out = "gemma-4-12b-it-q4km.jns",
+ .jns_repo = "prabanta-dev/gemma-4-12B-it-JNS",
+ .jns_gb = 7.59,
.flat_sha =
"cae09e04598891dea6e9cd93fb496fbde08d822ac35de4ff45dbfab1ea25c4dd",
.extra = JANAS_EXTRA_GGUF,
@@ -299,6 +331,8 @@ const struct janas_model_entry janas_catalog[] = {
{"f2c28b3dc4776931ac6f879e11f203dec637ea0f14267a86ec8f6165f63f293f"},
.gguf_gb = 16.9,
.out = "gemma-4-26b-a4b-it-udq4km.jns",
+ .jns_repo = "prabanta-dev/gemma-4-26B-A4B-it-JNS",
+ .jns_gb = 18.76,
.flat_sha =
"35c3845bbc21de52bf630d3c7455b4bb5379c34487b5925e020ec2e573931666",
.extra = JANAS_EXTRA_GGUF,
diff --git a/src/common/catalog.h b/src/common/catalog.h
index d730103..421d128 100644
--- a/src/common/catalog.h
+++ b/src/common/catalog.h
@@ -28,8 +28,13 @@ struct janas_model_entry {
const char *parts[JANAS_CATALOG_PARTS]; /* its file(s), the first given to
gguf2jns */
const char *part_sha[JANAS_CATALOG_PARTS];
- double gguf_gb; /* download */
- const char *out; /* the .jns, beside the downloads */
+ double gguf_gb; /* download */
+ const char *out; /* the .jns, beside the downloads */
+ /* the same .jns (and the extra file), converted and checked, on
+ Hugging Face: what janas-get downloads unless --from-gguf; its
+ size with the extra file */
+ const char *jns_repo;
+ double jns_gb;
const char *flat_sha; /* what gguf2jns writes (the .jns itself when
there are no planes) */
const char *jns_sha; /* what jns_planes writes, NULL: one step */
diff --git a/src/common/env_names.c b/src/common/env_names.c
index d132aa7..d1831a9 100644
--- a/src/common/env_names.c
+++ b/src/common/env_names.c
@@ -40,6 +40,7 @@ const char *const JANAS_ENV_NAMES[] = {"JANAS_ALPHAVANTAGE_KEY",
"JANAS_GPU_KEEPALIVE_US",
"JANAS_GPU_MIN_N",
"JANAS_GPU_FAST_PROMPT",
+ "JANAS_GPU_MOE",
"JANAS_GPU_ARENA_INPLACE",
"JANAS_GPU_EXPERT_MIN",
"JANAS_GPU_EXPERT_SHARE",
@@ -75,6 +76,7 @@ const char *const JANAS_ENV_NAMES[] = {"JANAS_ALPHAVANTAGE_KEY",
"JANAS_TRANSITOUS_URL",
"JANAS_TUNE",
"JANAS_TUNE_THREADS",
+ "JANAS_TUNE_TRACE",
"JANAS_URING",
"JANAS_URING_BATCH",
"JANAS_URING_DEEP",
diff --git a/src/get/main.c b/src/get/main.c
index 683e61a..333836c 100644
--- a/src/get/main.c
+++ b/src/get/main.c
@@ -1,21 +1,24 @@
/* SPDX-License-Identifier: GPL-3.0-or-later
Copyright (C) 2026 Maurizio Cammalleri */
/*
- * janas-get - a model ready for Janas in one command: downloaded from
- * Hugging Face, checked, converted, its prediction file made beside it,
- * every file compared with the fingerprints of MODELS.md.
+ * janas-get - a model ready for Janas in one command: its .jns file, and
+ * its prediction file, downloaded already converted from Hugging Face
+ * (prabanta-dev/<model>-JNS), every file compared with the fingerprints
+ * of MODELS.md. With --from-gguf, or where the converted file is not on
+ * Hugging Face, the GGUF the catalog names is downloaded and converted
+ * here instead, to the same fingerprints.
*
* janas-get list
- * janas-get <model> [--dir DIR] [--keep] [--no-mtp]
- * janas-get hf:<owner>/<repo>/<file.gguf> [--dir DIR] [--keep]
+ * janas-get <model> [--dir DIR] [--no-mtp] [--from-gguf [--keep]]
+ * janas-get hf:<owner>/<repo>/<file.jns|file.gguf> [--dir DIR] [--keep]
*
* The models go where janas-chat looks for them (janas_models_dir: the
* environment's JANAS_MODELS, or ~/.local/share/janas/models), unless
* --dir says otherwise. A model with a draft in the catalog brings it.
*
* A download stopped halfway resumes where it stopped; a file already
- * there is checked, not fetched again. The GGUF goes once converted,
- * unless --keep.
+ * there is checked, not fetched again. A GGUF goes once converted, unless
+ * --keep.
*/
#include <stdio.h>
#include <stdlib.h>
@@ -32,13 +35,17 @@ static void usage(void)
{
fprintf(stderr,
"usage: janas-get list\n"
- " janas-get <model> [--dir DIR] [--keep] [--no-mtp]\n"
- " janas-get hf:<owner>/<repo>/<file.gguf> [--dir DIR] "
- "[--keep]\n"
- " --dir DIR where the models go (default: JANAS_MODELS, or\n"
- " ~/.local/share/janas/models)\n"
- " --keep keep the downloaded GGUF once converted\n"
- " --no-mtp without the model's prediction file or draft\n");
+ " janas-get <model> [--dir DIR] [--no-mtp] [--from-gguf "
+ "[--keep]]\n"
+ " janas-get hf:<owner>/<repo>/<file.jns|file.gguf> "
+ "[--dir DIR] [--keep]\n"
+ " --dir DIR where the models go (default: JANAS_MODELS, or\n"
+ " ~/.local/share/janas/models)\n"
+ " --no-mtp without the model's prediction file or draft\n"
+ " --from-gguf download the original GGUF and convert it here\n"
+ " (by default the file comes converted, from\n"
+ " Hugging Face's prabanta-dev)\n"
+ " --keep keep the downloaded GGUF once converted\n");
}
static void list(void)
@@ -46,11 +53,13 @@ static void list(void)
printf("%-22s %8s %7s %s\n", "model", "download", "memory", "");
for (int i = 0; i < janas_catalog_n; i++) {
const struct janas_model_entry *m = &janas_catalog[i];
- printf("%-22s %6.1f GB %4d GB %s\n", m->name, m->gguf_gb, m->ram_gb,
- m->what);
+ printf("%-22s %6.1f GB %4d GB %s\n", m->name,
+ m->jns_repo ? m->jns_gb : m->gguf_gb, m->ram_gb, m->what);
}
- printf("\nFingerprints and licences: MODELS.md. Any other GGUF: "
- "janas-get hf:<owner>/<repo>/<file.gguf>\n");
+ printf("\nDownloaded converted from Hugging Face (prabanta-dev); "
+ "--from-gguf converts here.\nFingerprints and licences: "
+ "MODELS.md. Any other file: janas-get "
+ "hf:<owner>/<repo>/<file.jns|file.gguf>\n");
}
static int exists(const char *path)
@@ -83,17 +92,15 @@ static int convert(const char *first, const char *out)
return get_run("gguf2jns", argv) == 0 ? 0 : -1;
}
-static int from_catalog(const struct janas_model_entry *m, const char *dir,
- int keep, int no_mtp)
+/* The catalog's GGUF downloaded and converted here, its prediction file
+ made beside it: the way before the converted files were on Hugging
+ Face, and the one --from-gguf takes */
+static int from_gguf(const struct janas_model_entry *m, const char *dir,
+ int keep, int no_mtp)
{
char out[4096], first[4096], flat[4200];
snprintf(out, sizeof(out), "%s/%s", dir, m->out);
get_local(first, sizeof(first), dir, m->parts[0]);
- if (m->ram_gb &&
- janas_mem_total() < (uint64_t)m->ram_gb * (1ull << 30) * 85 / 100)
- printf("note: %s is meant for machines with %d GB of memory or "
- "more; this one has %.1f GB\n",
- m->name, m->ram_gb, (double)janas_mem_total() / (1ull << 30));
int have = exists(out) &&
get_same(out, m->jns_sha ? m->jns_sha : m->flat_sha) == 1;
if (have) {
@@ -114,7 +121,7 @@ static int from_catalog(const struct janas_model_entry *m, const char *dir,
}
printf("== %s: downloading\n", m->name);
for (int p = 0; p < JANAS_CATALOG_PARTS && m->parts[p]; p++)
- if (get_fetch(m->repo, m->parts[p], dir, m->part_sha[p]) != 0)
+ if (get_fetch(m->repo, m->parts[p], dir, m->part_sha[p], 0) != 0)
return 1;
snprintf(flat, sizeof(flat), "%s.flat", out);
const char *conv = m->jns_sha ? flat : out;
@@ -145,7 +152,7 @@ static int from_catalog(const struct janas_model_entry *m, const char *dir,
} else if (m->extra == JANAS_EXTRA_GGUF) {
char src[4096];
printf("== its assistant\n");
- if (get_fetch(m->repo, m->extra_src, dir, m->extra_src_sha) != 0)
+ if (get_fetch(m->repo, m->extra_src, dir, m->extra_src_sha, 0) != 0)
return 1;
get_local(src, sizeof(src), dir, m->extra_src);
if (convert(src, xout) != 0 ||
@@ -166,8 +173,77 @@ static int from_catalog(const struct janas_model_entry *m, const char *dir,
return 0;
}
-/* hf:<owner>/<repo>/<path>: any GGUF, checked against the SHA-256 Hugging
- Face lists, converted in one step */
+/* Room for bytes in dir: 0, or -1 having said so. */
+static int room(const struct janas_model_entry *m, const char *dir, double need)
+{
+ struct statvfs vf;
+ if (statvfs(dir, &vf) == 0 &&
+ (double)vf.f_bavail * (double)vf.f_frsize < need) {
+ fprintf(stderr,
+ "janas-get: %s needs about %.0f GB free in %s; there are "
+ "%.0f\n",
+ m->name, need / 1e9, dir,
+ (double)vf.f_bavail * (double)vf.f_frsize / 1e9);
+ return -1;
+ }
+ return 0;
+}
+
+/* A file of the model already here and the one MODELS.md names. */
+static int have(const char *dir, const char *file, const char *sha)
+{
+ char path[4096];
+ snprintf(path, sizeof(path), "%s/%s", dir, file);
+ if (!exists(path) || get_same(path, sha) != 1)
+ return 0;
+ printf("%s: already here, fingerprint checked\n", path);
+ return 1;
+}
+
+/* The model as the catalog lists it: converted, from Hugging Face; where
+ it is not there (nothing downloaded yet), by the GGUF. 0, or 1. */
+static int from_catalog(const struct janas_model_entry *m, const char *dir,
+ int keep, int no_mtp, int gguf)
+{
+ if (m->ram_gb &&
+ janas_mem_total() < (uint64_t)m->ram_gb * (1ull << 30) * 85 / 100)
+ printf("note: %s is meant for machines with %d GB of memory or "
+ "more; this one has %.1f GB\n",
+ m->name, m->ram_gb, (double)janas_mem_total() / (1ull << 30));
+ if (gguf || !m->jns_repo)
+ return from_gguf(m, dir, keep, no_mtp);
+ const char *sha = m->jns_sha ? m->jns_sha : m->flat_sha;
+ int extra = m->extra != JANAS_EXTRA_NONE && !no_mtp;
+ if (!have(dir, m->out, sha)) {
+ if (room(m, dir, m->jns_gb * 1.05e9) != 0)
+ return 1;
+ printf("== %s: downloading, converted (%s)\n", m->name, m->jns_repo);
+ int r = get_fetch(m->jns_repo, m->out, dir, sha, 1);
+ if (r == -2) {
+ printf(" not on Hugging Face yet (or unreachable): from the "
+ "GGUF instead\n");
+ return from_gguf(m, dir, keep, no_mtp);
+ }
+ if (r != 0)
+ return 1;
+ }
+ if (extra && !have(dir, m->extra_out, m->extra_sha)) {
+ printf("== its %s\n",
+ m->extra == JANAS_EXTRA_GGUF ? "assistant" : "MTP block");
+ int r = get_fetch(m->jns_repo, m->extra_out, dir, m->extra_sha, 1);
+ if (r == -2) {
+ printf(" not on Hugging Face yet (or unreachable): made "
+ "here\n");
+ return from_gguf(m, dir, keep, no_mtp);
+ }
+ if (r != 0)
+ return 1;
+ }
+ return 0;
+}
+
+/* hf:<owner>/<repo>/<path>: any .jns, or any GGUF converted in one step,
+ checked against the SHA-256 Hugging Face lists */
static int from_hf(const char *spec, const char *dir, int keep)
{
char repo[512];
@@ -183,6 +259,18 @@ static int from_hf(const char *spec, const char *dir, int keep)
const char *path = b + 1;
char local[4096], out[4200];
get_local(local, sizeof(local), dir, path);
+ size_t pl = strlen(path);
+ if (pl > 4 && strcmp(path + pl - 4, ".jns") == 0) {
+ printf("== %s: downloading (not in the catalog: checked against the "
+ "SHA-256 Hugging Face lists)\n",
+ path);
+ if (get_fetch(repo, path, dir, NULL, 0) != 0)
+ return 1;
+ printf("\nReady: %s (no fingerprint to compare: not in MODELS.md)\n"
+ "Chat with it: janas-chat %s\n",
+ local, local);
+ return 0;
+ }
snprintf(out, sizeof(out), "%s", local);
char *dot = strrchr(out, '.');
if (dot && strcmp(dot, ".gguf") == 0)
@@ -194,7 +282,7 @@ static int from_hf(const char *spec, const char *dir, int keep)
printf("== %s: downloading (not in the catalog: checked against the "
"SHA-256 Hugging Face lists)\n",
path);
- if (get_fetch(repo, path, dir, NULL) != 0 || convert(local, out) != 0)
+ if (get_fetch(repo, path, dir, NULL, 0) != 0 || convert(local, out) != 0)
return 1;
if (!keep)
remove(local);
@@ -213,7 +301,7 @@ int main(int argc, char **argv)
}
static char home_dir[4096];
const char *dir = NULL;
- int keep = 0, no_mtp = 0;
+ int keep = 0, no_mtp = 0, gguf = 0;
for (int i = 2; i < argc; i++) {
if (strcmp(argv[i], "--dir") == 0 && i + 1 < argc)
dir = argv[++i];
@@ -221,6 +309,8 @@ int main(int argc, char **argv)
keep = 1;
else if (strcmp(argv[i], "--no-mtp") == 0)
no_mtp = 1;
+ else if (strcmp(argv[i], "--from-gguf") == 0)
+ gguf = 1;
else {
usage();
return 2;
@@ -253,12 +343,12 @@ int main(int argc, char **argv)
argv[1]);
return 2;
}
- int r = from_catalog(m, dir, keep, no_mtp);
+ int r = from_catalog(m, dir, keep, no_mtp, gguf);
const struct janas_model_entry *d =
m->draft && !no_mtp ? janas_catalog_find(m->draft) : NULL;
if (r == 0 && d) {
printf("== its draft, %s\n", d->name);
- r = from_catalog(d, dir, keep, 1);
+ r = from_catalog(d, dir, keep, 1, gguf);
}
if (r == 0)
printf("\nReady: %s/%s\nChat with it: janas-chat %s\n", dir, m->out,
diff --git a/src/get/steps.c b/src/get/steps.c
index cb68297..eab8af9 100644
--- a/src/get/steps.c
+++ b/src/get/steps.c
@@ -60,14 +60,15 @@ int get_same(const char *file, const char *want)
}
int get_fetch(const char *repo, const char *path, const char *dir,
- const char *want)
+ const char *want, int quiet)
{
char local[4096], err[512], listed[65], got[65];
get_local(local, sizeof(local), dir, path);
uint64_t size = 0;
if (janas_hf_info(repo, NULL, path, &size, listed, err, sizeof(err)) != 0) {
- fprintf(stderr, "janas-get: %s\n", err);
- return -1;
+ if (!quiet)
+ fprintf(stderr, "janas-get: %s\n", err);
+ return -2;
}
/* the repository may have been changed since MODELS.md was written:
then its file is not the one the fingerprints are of */
diff --git a/src/get/steps.h b/src/get/steps.h
index 792bad4..bcbc8aa 100644
--- a/src/get/steps.h
+++ b/src/get/steps.h
@@ -14,9 +14,11 @@ void get_local(char *out, size_t len, const char *dir, const char *path);
/* File path of repo downloaded into dir (resumed if part of it is there),
its SHA-256 checked against want (NULL: the one Hugging Face lists). 0,
- or -1 having said why. */
+ -1 having said why, or -2 when Hugging Face does not list the file
+ (nothing written: the caller may take another way, quiet says nothing
+ then). */
int get_fetch(const char *repo, const char *path, const char *dir,
- const char *want);
+ const char *want, int quiet);
/* 1 when file's SHA-256 is want; 0 when it is another, -1 unreadable. */
int get_same(const char *file, const char *want);
diff --git a/src/llm/gpu.c b/src/llm/gpu.c
index 6de8e39..e450c61 100644
--- a/src/llm/gpu.c
+++ b/src/llm/gpu.c
@@ -87,9 +87,12 @@ int janas_g_make_stage(struct janas_gpu *g, struct stage *s, size_t bytes,
{
VkBufferCreateInfo bi = {.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.size = bytes,
+ /* indirect: a mixture's dispatches whose
+ size the CPU writes (gpu_token.c) */
.usage =
VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
- VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT};
+ VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
+ VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT};
if (g->vkCreateBuffer(g->dev, &bi, NULL, &s->buf) != VK_SUCCESS)
return -1;
VkMemoryRequirements req;
diff --git a/src/llm/gpu_impl.h b/src/llm/gpu_impl.h
index 07f841e..ee0ec44 100644
--- a/src/llm/gpu_impl.h
+++ b/src/llm/gpu_impl.h
@@ -80,6 +80,7 @@
X(vkCmdBindPipeline) \
X(vkCmdPushConstants) \
X(vkCmdDispatch) \
+ X(vkCmdDispatchIndirect) \
X(vkCmdPipelineBarrier) \
X(vkCmdCopyBuffer) \
X(vkWaitForFences) \
diff --git a/src/llm/gpu_token.c b/src/llm/gpu_token.c
index e0853ec..2f7c5ae 100644
--- a/src/llm/gpu_token.c
+++ b/src/llm/gpu_token.c
@@ -2,7 +2,9 @@
Copyright (C) 2026 Maurizio Cammalleri */
/*
* gpu_token.c - a whole token on the GPU with one submission (see
- * gpu_token.h).
+ * gpu_token.h): its buffers and shaders, the checks, the commands of a
+ * block and their submission. The commands' pieces are in gpu_token_rec.c,
+ * a mixture's in gpu_token_moe.c (gpu_token_impl.h).
*/
#include "gpu_token.h"
@@ -13,7 +15,7 @@
#include <string.h>
#include <time.h>
-#include "gpu_impl.h"
+#include "gpu_token_impl.h"
#include "quant.h"
#if defined(JANAS_GPU_SPV) && __has_include(<vulkan/vulkan.h>)
@@ -27,67 +29,10 @@
#include "gdn_l2.h" /* janas_spv_gdn_l2 */
#include "gdn_rec.h" /* janas_spv_gdn_rec */
#include "gdn_gate.h" /* janas_spv_gdn_gate */
-
-/* The push constants of each shader, laid out as its GLSL block. */
-struct push_nq {
- uint32_t x[2], add[2], w[2], xo[2], q256[2], q32[2], xn[2];
- uint32_t d;
- float eps;
-};
-struct push_qk {
- uint32_t qkv[2], qn[2], kn[2], rope[2], kc[2], vc[2], ks[2], vs[2];
- uint32_t n_head, n_kv, hd, n_rot, cap, qs;
- float eps;
- uint32_t pad, pos[2]; /* the position's buffer, 8-byte aligned */
-};
-struct push_at {
- uint32_t q[2], kc[2], vc[2], ks[2], vs[2], part[2];
- uint32_t n_head, n_kv, hd, cap, nch;
- float scale;
- uint32_t qs, ps;
- uint32_t pos[2]; /* the position's buffer */
-};
-struct push_am {
- uint32_t part[2], q256[2], q32[2];
- uint32_t hd, nch, ps, gs;
- uint32_t pos[2]; /* 8-byte aligned, as the GLSL block puts it */
- uint32_t gate[2];
-};
-/* the Gated DeltaNet shaders (gdn_*.comp) */
-struct push_gconv {
- uint32_t mixed[2], out[2], w[2], state[2], pos[2];
- uint32_t cc, d, hs, so;
-};
-struct push_gcst {
- uint32_t mixed[2], state[2], pos[2];
- uint32_t cc, d, hs, so, n;
-};
-struct push_gl2 {
- uint32_t x[2];
- uint32_t cc;
- float eps;
-};
-struct push_grec {
- uint32_t co[2], ba[2], att[2], state[2], pos[2], dt[2], a[2];
- uint32_t cc, nv, nkh, n, hs, so, vmap_mod;
- float scale;
-};
-struct push_ggate {
- uint32_t att[2], z[2], w[2], q256[2], q32[2];
- uint32_t d;
- float eps;
-};
-struct push_dm { /* gpu.c's dense_mm.comp */
- uint32_t w[2], x[2], y[2];
- uint32_t rows, cols, nv, ys;
- float scale;
-};
-/* The attention's positions a run (attn_decode.comp C), and the shapes its
- shared memory takes: the query heads of a KV head times hd, and times a
- run. */
-#define ATT_RUN 128
-#define ATT_MAXQ 2048
-#define ATT_MAXS 1024
+#include "moe_topk.h" /* janas_spv_moe_topk */
+#include "moe_gather.h" /* janas_spv_moe_gather */
+#include "moe_combine.h" /* janas_spv_moe_combine */
+#include "silu_mul.h" /* janas_spv_silu_mul */
/* The attention's first step in subgroups of 16 where the size may be
chosen (JANAS_GPU_ATT_SG=n another): twice the lanes a hardware thread
@@ -98,89 +43,9 @@ static uint32_t att_sg(void)
const char *e = getenv("JANAS_GPU_ATT_SG");
return e ? (uint32_t)atoi(e) : 16;
}
-struct push_ac {
- uint32_t g[2], u[2], x[2];
- uint32_t blocks;
-};
-_Static_assert(sizeof(struct push_qk) <= JANAS_G_PUSH_BYTES, "push size");
-_Static_assert(sizeof(struct push_at) <= JANAS_G_PUSH_BYTES, "push size");
-/* the uvec2 members where GLSL puts them: on 8 bytes */
-_Static_assert(offsetof(struct push_qk, pos) % 8 == 0, "push layout");
-_Static_assert(offsetof(struct push_at, pos) % 8 == 0, "push layout");
-_Static_assert(offsetof(struct push_am, pos) % 8 == 0, "push layout");
-_Static_assert(sizeof(struct push_grec) <= JANAS_G_PUSH_BYTES, "push size");
-/* The most tokens a block takes (the model's own blocks: model.h
- JANAS_LLM_MAX_BLOCK), and the memory the attention's runs may take for
- them. */
-#define TOK_MAX_BLOCK 256
-#define TOK_PART_BUDGET ((size_t)64 << 20)
-
-/* JANAS_GPU_TOKEN_PROFILE=1: the GPU's own timestamps after each phase of
- the token, summed per phase and printed when the model is closed */
-enum {
- PH_NORM,
- PH_QKV,
- PH_ROPE,
- PH_ATTN,
- PH_MERGE,
- PH_WO,
- PH_GATEUP,
- PH_ACT,
- PH_DOWN,
- PH_OUT,
- PH_N
-};
static const char *const ph_name[PH_N] = {
"norm+quant", "q k v", "q k norm+rope", "attention", "attn merge",
"wo", "gate+up", "act", "down", "output"};
-#define MAX_TS 1024
-
-struct janas_gpu_tok {
- /* its own command buffers, one per number of tokens n (1 .. nb) and
- logits of the last token, of all or of none ([n][all]: 0, 1, 2),
- each recorded once:
- the position is read from the buffer at o_pos, so every block of n
- tokens submits the same commands */
- uint32_t nb;
- /* [n][all][hidden wanted] */
- VkCommandBuffer cb[TOK_MAX_BLOCK + 1][3][2];
- uint32_t cb_nch[TOK_MAX_BLOCK + 1][3]
- [2]; /* the runs each was recorded for */
- int prof; /* timestamps in the commands being recorded (n = 1) */
- VkQueryPool qp; /* timestamps, if profiling */
- uint32_t n_ts; /* written this token */
- uint8_t ph_of[MAX_TS]; /* the phase each timestamp closes */
- double ph_ns[PH_N];
- double wall_ns; /* submission to the fence, as the CPU sees it */
- double copy_ns; /* the logits copied out */
- uint64_t tokens;
- VkShaderModule sm_nq, sm_qk, sm_at, sm_am;
- VkPipeline p_nq, p_qk, p_at, p_am;
- /* qwen3.5's recurrent layers */
- VkShaderModule sm_gc, sm_gs, sm_gl, sm_gr, sm_gg;
- VkPipeline p_gc, p_gs, p_gl, p_gr, p_gg;
- size_t *par; /* per layer: its parameters' offsets in buf (PAR_*) */
- struct stage buf; /* every intermediate, one allocation */
- /* offsets into buf, each nb tokens' worth */
- uint32_t nch; /* the attention's runs of positions, for the cache */
- size_t part_floats; /* room for the runs of a block, floats */
- uint32_t rec_nch; /* the runs a token of the block being recorded has */
- size_t o_part;
- size_t o_x, o_x1, o_q256, o_q32, o_qkv, o_ywo, o_gu, o_h, o_yd, o_rope,
- o_logits, o_pos;
- /* qwen3.5: the normalized input (f32), q|k|v and z of the recurrent
- layers, their convolution's output, beta and alpha, their raw
- output, the query's gates, the final hidden states */
- size_t o_xnf, o_mix, o_z, o_conv, o_ba, o_att, o_gate, o_hid;
-};
-
-/* A recurrent layer's parameters copied into buf: beta then alpha (2 nv x
- dm), the convolution (d_conv x conv_ch), dt, A (nv), the norm (ds) */
-enum { PAR_BA, PAR_CONV, PAR_DT, PAR_A, PAR_NORM, PAR_N };
-
-static void sync_range(struct janas_gpu *g, struct janas_gpu_tok *t, size_t off,
- size_t bytes, int flush);
-
int janas_gpu_shares_host(const struct janas_gpu *g)
{
return g && !g->broken && !g->discrete && g->host_import &&
@@ -188,8 +53,8 @@ int janas_gpu_shares_host(const struct janas_gpu *g)
}
/* The GPU's address of host memory in one of its regions, 0 if none. */
-static VkDeviceAddress addr_of(const struct janas_gpu *g, const void *p,
- size_t bytes)
+VkDeviceAddress janas_gt_addr_of(const struct janas_gpu *g, const void *p,
+ size_t bytes)
{
const struct region *rg = janas_g_find_region(g, p, bytes);
return rg ? rg->addr + (VkDeviceAddress)((const uint8_t *)p - rg->host) : 0;
@@ -208,6 +73,44 @@ static int fail(char *err, size_t len, const char *why)
return -1;
}
+/* Whether a layer's feed-forward is one the GPU computes: a dense one's
+ weights where it reads them, a mixture's experts of the types its
+ *_mmid shaders take and its shared expert's weights. NULL, or why not. */
+static const char *check_ffn(const struct janas_gpu *g,
+ const struct janas_gpu_tok_model *md,
+ const struct janas_gpu_tok_layer *ly)
+{
+ if (!md->n_expert) {
+ const struct janas_matvec_task *f[3] = {&ly->gate, &ly->up, &ly->down};
+ for (int i = 0; i < 3; i++)
+ if (!janas_gpu_can(g, f[i]))
+ return "a feed-forward weight the GPU cannot compute";
+ if (janas_g_x_in_32(ly->down.type))
+ return "a down matrix in blocks of 32";
+ return NULL;
+ }
+ int dt = ly->down.type;
+ if (ly->gate.type != JANAS_Q4_K || ly->up.type != JANAS_Q4_K ||
+ !(dt == JANAS_Q4_K || dt == JANAS_Q6_K || dt == JANAS_Q6_K_P) ||
+ 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)
+ return "experts of a type or shape the GPU's shaders do not take";
+ if (!ly->router16)
+ return "a mixture's layer without its router";
+ if (ly->sh_gate_w.type) {
+ const struct janas_matvec_task *s[3] = {&ly->sh_gate_w, &ly->sh_up,
+ &ly->sh_down};
+ for (int i = 0; i < 3; i++)
+ if (!janas_gpu_can(g, s[i]))
+ return "a shared expert's weight the GPU cannot compute";
+ if (ly->sh_gate_w.rows != md->ff || ly->sh_up.rows != md->ff ||
+ ly->sh_down.cols != md->ff || ly->sh_down.rows != md->dm)
+ return "a shared expert of another shape";
+ }
+ return NULL;
+}
+
/* Whether the model's pieces are all where the GPU can read them. */
static int check_model(const struct janas_gpu *g,
const struct janas_gpu_tok_model *md, char *err,
@@ -220,25 +123,36 @@ static int check_model(const struct janas_gpu *g,
md->n_head / md->n_kv * md->hd > ATT_MAXQ ||
md->n_head / md->n_kv * ATT_RUN > ATT_MAXS)
return fail(err, len, "a shape the token's shaders do not take");
+ if (md->n_expert && (md->n_expert > 512 || md->k == 0 || md->k > 16 ||
+ md->k > md->n_expert || md->eff % JANAS_QK ||
+ !md->fetch || !g->pipe_id4 || !g->pipe_id6 ||
+ !g->pipe_id6s || !g->pipea || !g->pipe_dm[0]))
+ return fail(err, len, "a mixture the token's shaders do not take");
if (md->n_rec &&
(md->ds != 128 || md->conv_ch % 256 || md->d_inner % 256 ||
md->d_inner != md->nv * md->ds || md->nv > 64 || !md->nkh ||
md->nv % md->nkh || md->d_conv < 2 || md->d_conv > 8 ||
md->d_inner > md->dm * 4 ||
md->conv_ch != 2 * md->nkh * md->ds + md->d_inner ||
- !addr_of(g, md->ssm_state,
- 2 * (size_t)md->n_rec * md->nv * md->ds * md->ds * 2) ||
- !addr_of(g, md->conv_state,
- 2 * (size_t)md->n_rec * (md->d_conv - 1) * md->conv_ch * 4)))
+ !janas_gt_addr_of(g, md->ssm_state,
+ 2 * (size_t)md->n_rec * md->nv * md->ds * md->ds *
+ 2) ||
+ !janas_gt_addr_of(g, md->conv_state,
+ 2 * (size_t)md->n_rec * (md->d_conv - 1) *
+ md->conv_ch * 4)))
return fail(err, len,
"recurrent layers the token's shaders do not take");
for (uint32_t l = 0; l < md->n_layer; l++) {
const struct janas_gpu_tok_layer *ly = &md->layers[l];
+ const char *why = check_ffn(g, md, ly);
+ if (why) {
+ snprintf(err, len, "layer %u: %s", l, why);
+ return -1;
+ }
if (ly->rec) {
- const struct janas_matvec_task *r[6] = {&ly->ssm_qkv, &ly->ssm_z,
- &ly->ssm_out, &ly->gate,
- &ly->up, &ly->down};
- for (int i = 0; i < 6; i++)
+ const struct janas_matvec_task *r[3] = {&ly->ssm_qkv, &ly->ssm_z,
+ &ly->ssm_out};
+ for (int i = 0; i < 3; i++)
if (!janas_gpu_can(g, r[i])) {
snprintf(err, len,
"layer %u: a weight the GPU cannot compute "
@@ -246,16 +160,14 @@ static int check_model(const struct janas_gpu *g,
l, i, r[i]->type);
return -1;
}
- if (janas_g_x_in_32(ly->down.type))
- return fail(err, len, "a down matrix in blocks of 32");
- if (!addr_of(g, ly->attn_norm, md->dm * 4) ||
- !addr_of(g, ly->ffn_norm, md->dm * 4))
+ if (!janas_gt_addr_of(g, ly->attn_norm, md->dm * 4) ||
+ !janas_gt_addr_of(g, ly->ffn_norm, md->dm * 4))
return fail(err, len, "a norm out of the GPU's reach");
continue;
}
- const struct janas_matvec_task *t[7] = {
- &ly->wq, &ly->wk, &ly->wv, &ly->wo, &ly->gate, &ly->up, &ly->down};
- for (int i = 0; i < 7; i++)
+ const struct janas_matvec_task *t[4] = {&ly->wq, &ly->wk, &ly->wv,
+ &ly->wo};
+ for (int i = 0; i < 4; i++)
if (!janas_gpu_can(g, t[i])) {
snprintf(err, len,
"layer %u: a weight the GPU cannot compute (product "
@@ -265,21 +177,21 @@ static int check_model(const struct janas_gpu *g,
}
if (md->gated_q && (ly->wq.type == JANAS_Q6_K_P || ly->wq.plane[0]))
return fail(err, len, "a gated query in planes");
- if (janas_g_x_in_32(ly->down.type))
- return fail(err, len, "a down matrix in blocks of 32");
size_t cache = (size_t)md->n_kv * md->cap * md->hd;
- if (!addr_of(g, ly->attn_norm, md->dm * 4) ||
- !addr_of(g, ly->ffn_norm, md->dm * 4) ||
- !addr_of(g, ly->q_norm, md->hd * 4) ||
- !addr_of(g, ly->k_norm, md->hd * 4) || !addr_of(g, ly->kc, cache) ||
- !addr_of(g, ly->vc, cache) ||
- !addr_of(g, ly->ks, (size_t)md->n_kv * md->cap * 4) ||
- !addr_of(g, ly->vs, (size_t)md->n_kv * md->cap * 4))
+ if (!janas_gt_addr_of(g, ly->attn_norm, md->dm * 4) ||
+ !janas_gt_addr_of(g, ly->ffn_norm, md->dm * 4) ||
+ !janas_gt_addr_of(g, ly->q_norm, md->hd * 4) ||
+ !janas_gt_addr_of(g, ly->k_norm, md->hd * 4) ||
+ !janas_gt_addr_of(g, ly->kc, cache) ||
+ !janas_gt_addr_of(g, ly->vc, cache) ||
+ !janas_gt_addr_of(g, ly->ks, (size_t)md->n_kv * md->cap * 4) ||
+ !janas_gt_addr_of(g, ly->vs, (size_t)md->n_kv * md->cap * 4))
return fail(err, len,
"a norm or the KV cache out of the GPU's "
"reach");
}
- if (!janas_gpu_can(g, &md->output) || !addr_of(g, md->out_norm, md->dm * 4))
+ if (!janas_gpu_can(g, &md->output) ||
+ !janas_gt_addr_of(g, md->out_norm, md->dm * 4))
return fail(err, len, "the output head out of the GPU's reach");
(void)kvd;
return 0;
@@ -313,6 +225,7 @@ struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
size_t full = (size_t)md->n_head * t->nch * (md->hd + 2);
t->part_floats = TOK_PART_BUDGET / 4 > full ? TOK_PART_BUDGET / 4 : full;
t->nb = TOK_MAX_BLOCK;
+ t->n_seg = md->n_layer + 1;
size_t nb = t->nb;
t->o_x = take(&at, nb * md->dm * 4);
t->o_x1 = take(&at, nb * md->dm * 4); /* the residual's other buffer */
@@ -337,16 +250,49 @@ struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
t->o_conv = take(&at, nb * md->conv_ch * 4);
t->o_ba = take(&at, nb * 2 * md->nv * 4);
t->o_att = take(&at, nb * md->d_inner * 4);
+ }
+ uint32_t ne = md->n_expert;
+ if (ne) {
+ /* the pairs of a block of nb tokens, k each; at most a tile of 16
+ of them per expert more than if they were all whole tiles */
+ size_t np = nb * md->k, nbd = md->dm / JANAS_QK,
+ nbf = md->eff / JANAS_QK;
+ t->o_r = take(&at, nb * (ne + 1) * 4);
+ t->o_pe = take(&at, np * 4);
+ t->o_pw = take(&at, np * 4);
+ t->o_shw = take(&at, nb * 4);
+ t->o_sh = take(&at, nb * md->dm * 4);
+ t->o_xg = take(&at, np * nbd * 320);
+ t->o_egu = take(&at, np * md->eff * 2 * 4);
+ t->o_eh = take(&at, np * nbf * 320);
+ t->o_dout = take(&at, np * md->dm * 4);
+ t->o_gt = take(&at, np * 4);
+ t->o_inv = take(&at, np * 4);
+ t->tiles1 = 3 * 2 * ne;
+ t->tiles2 = 3 * ne;
+ t->o_tab1 = take(&at, (t->tiles1 + 2 * (np / 16 + ne)) * 16);
+ t->o_tab2 = take(&at, (t->tiles2 + np / 16 + ne) * 16);
+ t->o_ind = take(&at, 32);
+ t->o_hf = take(&at, nb * md->ff * 4);
+ t->o_h32 = take(&at, nb * md->ff / JANAS_QK * 320);
+ t->cnt = calloc(ne + 1, sizeof(uint32_t));
+ t->fill = calloc(ne, sizeof(uint32_t));
+ t->ids = calloc(ne, sizeof(uint32_t));
+ t->slots = calloc(ne, sizeof(*t->slots));
+ }
+ if (md->n_rec || ne) {
t->par = calloc((size_t)md->n_layer * PAR_N, sizeof(size_t));
- if (!t->par) {
+ if (!t->par || (ne && (!t->cnt || !t->fill || !t->ids || !t->slots))) {
fail(err, err_len, "out of memory");
janas_gpu_tok_destroy(g, t);
return NULL;
}
for (uint32_t l = 0; l < md->n_layer; l++) {
+ size_t *pr = t->par + (size_t)l * PAR_N;
+ if (ne)
+ pr[PAR_R] = take(&at, (size_t)(ne + 1) * md->dm * 4);
if (!md->layers[l].rec)
continue;
- size_t *pr = t->par + (size_t)l * PAR_N;
pr[PAR_BA] = take(&at, 2 * (size_t)md->nv * md->dm * 4);
pr[PAR_CONV] = take(&at, (size_t)md->d_conv * md->conv_ch * 4);
pr[PAR_DT] = take(&at, md->nv * 4);
@@ -383,7 +329,19 @@ struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
janas_g_make_pipeline(g, janas_spv_gdn_gate,
sizeof(janas_spv_gdn_gate), &t->sm_gg, &t->p_gg,
0) != VK_SUCCESS ||
- !g->pipe_dm[0]))) {
+ !g->pipe_dm[0])) ||
+ (ne && (janas_g_make_pipeline(g, janas_spv_moe_topk,
+ sizeof(janas_spv_moe_topk), &t->sm_tk,
+ &t->p_tk, 0) != VK_SUCCESS ||
+ janas_g_make_pipeline(g, janas_spv_moe_gather,
+ sizeof(janas_spv_moe_gather), &t->sm_ga,
+ &t->p_ga, 0) != VK_SUCCESS ||
+ janas_g_make_pipeline(g, janas_spv_moe_combine,
+ sizeof(janas_spv_moe_combine), &t->sm_cb,
+ &t->p_cb, 0) != VK_SUCCESS ||
+ janas_g_make_pipeline(g, janas_spv_silu_mul,
+ sizeof(janas_spv_silu_mul), &t->sm_sm,
+ &t->p_sm, 0) != VK_SUCCESS))) {
fail(err, err_len, "cannot create the token's buffers or shaders");
janas_gpu_tok_destroy(g, t);
return NULL;
@@ -402,7 +360,22 @@ struct janas_gpu_tok *janas_gpu_tok_create(struct janas_gpu *g,
memcpy(t->buf.map + pr[PAR_DT], ly->dt, md->nv * 4);
memcpy(t->buf.map + pr[PAR_A], ly->ssm_a, md->nv * 4);
memcpy(t->buf.map + pr[PAR_NORM], ly->ssm_norm, md->ds * 4);
- sync_range(g, t, pr[PAR_BA], pr[PAR_NORM] + md->ds * 4 - pr[PAR_BA], 1);
+ janas_gt_sync_range(g, t, pr[PAR_BA],
+ pr[PAR_NORM] + md->ds * 4 - pr[PAR_BA], 1);
+ }
+ /* a mixture's routers, as f32 (the CPU's f16 weights exactly), the
+ shared expert's gate after them */
+ for (uint32_t l = 0; ne && l < md->n_layer; l++) {
+ const struct janas_gpu_tok_layer *ly = &md->layers[l];
+ size_t o = t->par[(size_t)l * PAR_N + PAR_R], n = (size_t)ne * md->dm;
+ float *r = (float *)(t->buf.map + o);
+ for (size_t i = 0; i < n; i++)
+ r[i] = janas_fp16_to_fp32(ly->router16[i]);
+ if (ly->sh_gate)
+ memcpy(r + n, ly->sh_gate, md->dm * 4);
+ else
+ memset(r + n, 0, md->dm * 4);
+ janas_gt_sync_range(g, t, o, (n + md->dm) * 4, 1);
}
const char *pe = getenv("JANAS_GPU_TOKEN_PROFILE");
if (pe && atoi(pe) > 0 && g->ts_period > 0) {
@@ -441,15 +414,23 @@ void janas_gpu_tok_destroy(struct janas_gpu *g, struct janas_gpu_tok *t)
}
for (uint32_t n = 0; n <= TOK_MAX_BLOCK; n++)
for (int a = 0; a < 3; a++)
- for (int h = 0; h < 2; h++)
+ for (int h = 0; h < 2; h++) {
if (t->cb[n][a][h])
g->vkFreeCommandBuffers(g->dev, g->cp, 1, &t->cb[n][a][h]);
- VkPipeline p[9] = {t->p_nq, t->p_qk, t->p_at, t->p_am, t->p_gc,
- t->p_gs, t->p_gl, t->p_gr, t->p_gg};
- VkShaderModule s[9] = {t->sm_nq, t->sm_qk, t->sm_at, t->sm_am, t->sm_gc,
- t->sm_gs, t->sm_gl, t->sm_gr, t->sm_gg};
+ janas_gt_free_segments(g, t, &t->seg_cb[n][a][h]);
+ }
+ VkPipeline p[13] = {t->p_nq, t->p_qk, t->p_at, t->p_am, t->p_gc,
+ t->p_gs, t->p_gl, t->p_gr, t->p_gg, t->p_tk,
+ t->p_ga, t->p_cb, t->p_sm};
+ VkShaderModule s[13] = {t->sm_nq, t->sm_qk, t->sm_at, t->sm_am, t->sm_gc,
+ t->sm_gs, t->sm_gl, t->sm_gr, t->sm_gg, t->sm_tk,
+ t->sm_ga, t->sm_cb, t->sm_sm};
free(t->par);
- for (int i = 0; i < 9; i++) {
+ free(t->cnt);
+ free(t->fill);
+ free(t->ids);
+ free(t->slots);
+ for (int i = 0; i < 13; i++) {
if (p[i])
g->vkDestroyPipeline(g->dev, p[i], NULL);
if (s[i])
@@ -464,8 +445,8 @@ void janas_gpu_tok_destroy(struct janas_gpu *g, struct janas_gpu_tok *t)
/* Bytes [off, off + bytes) of the token's buffer out of the CPU's caches
(flush) or reloaded from memory (!flush), where it is not coherent. */
-static void sync_range(struct janas_gpu *g, struct janas_gpu_tok *t, size_t off,
- size_t bytes, int flush)
+void janas_gt_sync_range(struct janas_gpu *g, struct janas_gpu_tok *t,
+ size_t off, size_t bytes, int flush)
{
if (t->buf.coherent)
return;
@@ -482,74 +463,6 @@ static void sync_range(struct janas_gpu *g, struct janas_gpu_tok *t, size_t off,
g->vkInvalidateMappedMemoryRanges(g->dev, 1, &mr);
}
-/* A timestamp closing phase ph (with profiling on). */
-static void stamp(struct janas_gpu *g, struct janas_gpu_tok *t, int ph)
-{
- if (!t->qp || !t->prof || t->n_ts >= MAX_TS)
- return;
- g->vkCmdWriteTimestamp(g->cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, t->qp,
- t->n_ts);
- t->ph_of[t->n_ts++] = (uint8_t)ph;
-}
-
-static void bind(struct janas_gpu *g, VkPipeline *bound, VkPipeline p)
-{
- if (*bound != p) {
- g->vkCmdBindPipeline(g->cb, VK_PIPELINE_BIND_POINT_COMPUTE, p);
- *bound = p;
- }
-}
-
-static void push(struct janas_gpu *g, const void *pc, size_t bytes)
-{
- g->vkCmdPushConstants(g->cb, g->pl, VK_SHADER_STAGE_COMPUTE_BIT, 0,
- (uint32_t)bytes, pc);
-}
-
-/* x (+ add, then stored at xo) normalized by w (0: not), quantized into
- q256 and q32: a workgroup per block of 256 values. */
-static void rec_norm_quant(struct janas_gpu *g, struct janas_gpu_tok *t,
- VkPipeline *bound, VkDeviceAddress x,
- VkDeviceAddress add, VkDeviceAddress w,
- VkDeviceAddress xo, VkDeviceAddress xn, uint32_t d,
- float eps, uint32_t n)
-{
- struct push_nq pc = {.d = d, .eps = eps};
- janas_g_push_addr(pc.xn, xn);
- janas_g_push_addr(pc.x, x);
- janas_g_push_addr(pc.add, add);
- janas_g_push_addr(pc.w, w);
- janas_g_push_addr(pc.xo, xo);
- janas_g_push_addr(pc.q256, t->buf.addr + t->o_q256);
- janas_g_push_addr(pc.q32, t->buf.addr + t->o_q32);
- bind(g, bound, t->p_nq);
- push(g, &pc, sizeof(pc));
- g->vkCmdDispatch(g->cb, d / JANAS_QK, n, 1); /* y: the vector */
- janas_g_compute_barrier(g);
-}
-
-/* A product of the task's weights with n quantized vectors (from byte xoff
- of the q256 or q32 layout, cols / 256 blocks apart), into y (ys floats
- apart; 0: rows). */
-static int rec_product(struct janas_gpu *g, struct janas_gpu_tok *t,
- VkPipeline *bound, const struct janas_matvec_task *w,
- size_t xoff, VkDeviceAddress y, uint32_t n, size_t ys)
-{
- struct janas_matvec_task k = *w;
- k.n_vec = n;
- k.x_stride = 0;
- k.y_stride = 0;
- VkDeviceAddress xa =
- t->buf.addr + xoff + (janas_g_x_in_32(k.type) ? t->o_q32 : t->o_q256);
- return janas_g_record_task(g, bound, &k, k.rows, xa, y, ys ? ys : k.rows);
-}
-
-/* The commands of a block of n tokens into g->cb (the caller points it at
- the block's buffer): every layer, then the output head for the tokens
- from first on (none if first is n); the position of the first token
- comes from the buffer.
- A single token takes the layers' GPU copies (JANAS_GPU_REPACK), a block
- the weights as they are (the copies' shaders take one vector). */
/* The runs of ATT_RUN positions npos positions take, rounded up to a power
of two (so that a prompt's blocks record their commands again only a few
times), at most the cache's. */
@@ -561,115 +474,20 @@ static uint32_t runs_for(const struct janas_gpu_tok *t, uint32_t npos)
return r < t->nch ? r : t->nch;
}
-/* A token's runs, floats, at nch runs a head. */
-static size_t part_tok(const struct janas_gpu_tok *t,
- const struct janas_gpu_tok_model *md, uint32_t nch)
-{
- (void)t;
- return (size_t)md->n_head * nch * (md->hd + 2);
-}
-
-/* A Gated DeltaNet layer (qwen3.5) on the block normalized in q256 / q32
- and XNF: its output into YWO, as model_rec.c's janas_m_rec_layer. */
-static int rec_gdn(struct janas_gpu *g, struct janas_gpu_tok *t,
- const struct janas_gpu_tok_model *md,
- const struct janas_gpu_tok_layer *ly, uint32_t l,
- VkPipeline *bound, VkDeviceAddress YWO, uint32_t n)
-{
- VkDeviceAddress B = t->buf.addr, MIX = B + t->o_mix, Z = B + t->o_z,
- CONV = B + t->o_conv, BA = B + t->o_ba, ATT = B + t->o_att,
- POS = B + t->o_pos;
- const size_t *pr = t->par + (size_t)l * PAR_N;
- uint32_t cc = md->conv_ch;
- /* q|k|v (the convolution's channels) and z */
- if (rec_product(g, t, bound, &ly->ssm_qkv, 0, MIX, n, cc) != 0 ||
- rec_product(g, t, bound, &ly->ssm_z, 0, Z, n, md->d_inner) != 0)
- return -1;
- /* beta then alpha, per token, from the normalized input at f32 */
- struct push_dm pd = {.rows = 2 * md->nv,
- .cols = md->dm,
- .nv = n,
- .ys = 2 * md->nv,
- .scale = 1.0f};
- janas_g_push_addr(pd.w, B + pr[PAR_BA]);
- janas_g_push_addr(pd.x, B + t->o_xnf);
- janas_g_push_addr(pd.y, BA);
- bind(g, bound, g->pipe_dm[0]);
- push(g, &pd, sizeof(pd));
- g->vkCmdDispatch(g->cb, (2 * md->nv + 63) / 64, (n + 63) / 64, 1);
- janas_g_compute_barrier(g);
- /* the convolution, then the state it leaves, the q and k heads' norms */
- uint32_t hs_c = md->n_rec * (md->d_conv - 1) * cc,
- so_c = ly->slot * (md->d_conv - 1) * cc;
- VkDeviceAddress CS = addr_of(g, md->conv_state, (size_t)hs_c * 8);
- struct push_gconv pc = {.cc = cc, .d = md->d_conv, .hs = hs_c, .so = so_c};
- janas_g_push_addr(pc.mixed, MIX);
- janas_g_push_addr(pc.out, CONV);
- janas_g_push_addr(pc.w, B + pr[PAR_CONV]);
- janas_g_push_addr(pc.state, CS);
- janas_g_push_addr(pc.pos, POS);
- bind(g, bound, t->p_gc);
- push(g, &pc, sizeof(pc));
- g->vkCmdDispatch(g->cb, cc / 256, n, 1);
- janas_g_compute_barrier(g);
- struct push_gcst ps = {
- .cc = cc, .d = md->d_conv, .hs = hs_c, .so = so_c, .n = n};
- janas_g_push_addr(ps.mixed, MIX);
- janas_g_push_addr(ps.state, CS);
- janas_g_push_addr(ps.pos, POS);
- bind(g, bound, t->p_gs);
- push(g, &ps, sizeof(ps));
- g->vkCmdDispatch(g->cb, cc / 256, 1, 1);
- struct push_gl2 pl = {.cc = cc, .eps = md->eps};
- janas_g_push_addr(pl.x, CONV);
- bind(g, bound, t->p_gl);
- push(g, &pl, sizeof(pl));
- g->vkCmdDispatch(g->cb, 2 * md->nkh, n, 1);
- janas_g_compute_barrier(g);
- /* the recurrence, then each head's norm, gate and quantization */
- uint32_t hs_s = md->n_rec * md->nv * md->ds * md->ds,
- so_s = ly->slot * md->nv * md->ds * md->ds;
- struct push_grec pg = {.cc = cc,
- .nv = md->nv,
- .nkh = md->nkh,
- .n = n,
- .hs = hs_s,
- .so = so_s,
- .vmap_mod = (uint32_t)md->vmap_mod,
- .scale = 1.0f / sqrtf((float)md->ds)};
- janas_g_push_addr(pg.co, CONV);
- janas_g_push_addr(pg.ba, BA);
- janas_g_push_addr(pg.att, ATT);
- janas_g_push_addr(pg.state, addr_of(g, md->ssm_state, (size_t)hs_s * 4));
- janas_g_push_addr(pg.pos, POS);
- janas_g_push_addr(pg.dt, B + pr[PAR_DT]);
- janas_g_push_addr(pg.a, B + pr[PAR_A]);
- bind(g, bound, t->p_gr);
- push(g, &pg, sizeof(pg));
- g->vkCmdDispatch(g->cb, md->nv * (md->ds / 16), 1, 1);
- janas_g_compute_barrier(g);
- struct push_ggate pq = {.d = md->d_inner, .eps = md->eps};
- janas_g_push_addr(pq.att, ATT);
- janas_g_push_addr(pq.z, Z);
- janas_g_push_addr(pq.w, B + pr[PAR_NORM]);
- janas_g_push_addr(pq.q256, B + t->o_q256);
- janas_g_push_addr(pq.q32, B + t->o_q32);
- bind(g, bound, t->p_gg);
- push(g, &pq, sizeof(pq));
- g->vkCmdDispatch(g->cb, md->d_inner / JANAS_QK, n, 1);
- janas_g_compute_barrier(g);
- if (rec_product(g, t, bound, &ly->ssm_out, 0, YWO, n, 0) != 0)
- return -1;
- janas_g_compute_barrier(g);
- return 0;
-}
-
+/* The commands of a block of n tokens into g->cb (the caller points it at
+ the block's buffer): every layer, then the output head for the tokens
+ from first on (none if first is n); the position of the first token
+ comes from the buffer.
+ A single token takes the layers' GPU copies (JANAS_GPU_REPACK), a block
+ the weights as they are (the copies' shaders take one vector).
+ A mixture's block goes in n_layer + 1 submissions, seg the one recorded
+ (-1: a dense model's, all of it): submission s takes layer s - 1's
+ experts, then layer s up to its router's choice, the last one the final
+ norm and the output head. */
static int record(struct janas_gpu *g, struct janas_gpu_tok *t,
const struct janas_gpu_tok_model *md, uint32_t n,
- uint32_t first, int hid)
+ uint32_t first, int hid, int seg)
{
- uint32_t qd = md->n_head * md->hd, kvd = md->n_kv * md->hd;
- size_t qs = qd + 2 * kvd;
const struct janas_gpu_tok_layer *layers =
n > 1 && md->blayers ? md->blayers : md->layers;
const struct janas_matvec_task *output =
@@ -677,9 +495,7 @@ static int record(struct janas_gpu *g, struct janas_gpu_tok *t,
/* the residual: read from X, the sum with a layer's output written to
XN, the two swapped (every block starts from o_x, the same commands) */
VkDeviceAddress B = t->buf.addr, X = B + t->o_x, XN = B + t->o_x1, SW,
- QKV = B + t->o_qkv, YWO = B + t->o_ywo, GU = B + t->o_gu,
- H = B + t->o_h, YD = B + t->o_yd, ROPE = B + t->o_rope,
- POS = B + t->o_pos;
+ YWO = B + t->o_ywo, YD = B + t->o_yd, XNF = B + t->o_xnf;
if (g->vkResetCommandBuffer(g->cb, 0) != VK_SUCCESS)
return -1;
VkCommandBufferBeginInfo bb = {
@@ -687,170 +503,66 @@ static int record(struct janas_gpu *g, struct janas_gpu_tok *t,
if (g->vkBeginCommandBuffer(g->cb, &bb) != VK_SUCCESS)
return -1;
VkPipeline bound = VK_NULL_HANDLE;
- size_t cache = (size_t)md->n_kv * md->cap * md->hd;
- t->prof = n == 1;
+ t->prof = n == 1 && seg < 0;
if (t->qp && t->prof) {
t->n_ts = 0;
g->vkCmdResetQueryPool(g->cb, t->qp, 0, MAX_TS);
- stamp(g, t, PH_N); /* the start */
+ janas_gt_stamp(g, t, PH_N); /* the start */
}
- for (uint32_t l = 0; l < md->n_layer; l++) {
+ uint32_t nl = md->n_layer;
+ for (uint32_t l = 0; l < nl; l++) {
const struct janas_gpu_tok_layer *ly = &layers[l];
+ int on = seg < 0 || seg == (int)l;
+ /* a mixture: the previous layer's experts first, into YD */
+ if (on && l && md->n_expert)
+ janas_gt_rec_experts(g, t, md, &layers[l - 1], &bound, YD, n);
/* the previous layer's feed-forward added, then this one's norm */
- rec_norm_quant(g, t, &bound, X, l ? YD : 0,
- addr_of(g, ly->attn_norm, md->dm * 4), l ? XN : 0,
- ly->rec ? B + t->o_xnf : 0, md->dm, md->eps, n);
+ if (on) {
+ janas_gt_rec_norm_quant(
+ g, t, &bound, X, l ? YD : 0,
+ janas_gt_addr_of(g, ly->attn_norm, md->dm * 4), l ? XN : 0,
+ ly->rec ? XNF : 0, md->dm, md->eps, n);
+ janas_gt_stamp(g, t, PH_NORM);
+ }
if (l)
SW = X, X = XN, XN = SW;
- stamp(g, t, PH_NORM);
- if (ly->rec) {
- if (rec_gdn(g, t, md, ly, l, &bound, YWO, n) != 0)
+ if (on) {
+ if ((ly->rec ? janas_gt_rec_gdn(g, t, md, ly, l, &bound, YWO, n)
+ : janas_gt_rec_attn(g, t, md, ly, &bound, n)) != 0)
return -1;
- goto ffn;
+ janas_gt_rec_norm_quant(
+ g, t, &bound, X, YWO,
+ janas_gt_addr_of(g, ly->ffn_norm, md->dm * 4), XN,
+ md->n_expert ? XNF : 0, md->dm, md->eps, n);
+ janas_gt_stamp(g, t, PH_NORM);
}
- /* q, k and v of each token side by side, qs floats a token; a
- gated query (qwen3.5) head by head, its gates apart */
- if (md->gated_q) {
- size_t rb = (size_t)(md->dm / JANAS_QK) *
- janas_qtype_block_size(ly->wq.type);
- for (uint32_t h = 0; h < md->n_head; h++) {
- struct janas_matvec_task q = ly->wq, gt = ly->wq;
- q.rows = gt.rows = md->hd;
- q.w = (const uint8_t *)ly->wq.w + (size_t)2 * h * md->hd * rb;
- gt.w = (const uint8_t *)q.w + (size_t)md->hd * rb;
- if (rec_product(g, t, &bound, &q, 0,
- QKV + (size_t)h * md->hd * 4, n, qs) != 0 ||
- rec_product(g, t, &bound, &gt, 0,
- B + t->o_gate + (size_t)h * md->hd * 4, n,
- qd) != 0)
- return -1;
- }
- } else if (rec_product(g, t, &bound, &ly->wq, 0, QKV, n, qs) != 0)
- return -1;
- if (rec_product(g, t, &bound, &ly->wk, 0, QKV + (size_t)qd * 4, n,
- qs) != 0 ||
- rec_product(g, t, &bound, &ly->wv, 0, QKV + (size_t)(qd + kvd) * 4,
- n, qs) != 0)
- return -1;
- janas_g_compute_barrier(g);
- stamp(g, t, PH_QKV);
- struct push_qk pq = {.n_head = md->n_head,
- .n_kv = md->n_kv,
- .hd = md->hd,
- .n_rot = md->n_rot,
- .cap = md->cap,
- .qs = (uint32_t)qs,
- .eps = md->eps};
- janas_g_push_addr(pq.pos, POS);
- janas_g_push_addr(pq.qkv, QKV);
- janas_g_push_addr(pq.qn, addr_of(g, ly->q_norm, md->hd * 4));
- janas_g_push_addr(pq.kn, addr_of(g, ly->k_norm, md->hd * 4));
- janas_g_push_addr(pq.rope, ROPE);
- janas_g_push_addr(pq.kc, addr_of(g, ly->kc, cache));
- janas_g_push_addr(pq.vc, addr_of(g, ly->vc, cache));
- janas_g_push_addr(pq.ks, addr_of(g, ly->ks, cache / md->hd * 4));
- janas_g_push_addr(pq.vs, addr_of(g, ly->vs, cache / md->hd * 4));
- bind(g, &bound, t->p_qk);
- push(g, &pq, sizeof(pq));
- g->vkCmdDispatch(g->cb, md->n_head + md->n_kv, n, 1);
- janas_g_compute_barrier(g);
- stamp(g, t, PH_ROPE);
- /* the attention: runs of positions per KV head, then joined; token
- j of the block sees positions 0 .. pos + j, the block's own keys
- and values written above */
- struct push_at pa = {.n_head = md->n_head,
- .n_kv = md->n_kv,
- .hd = md->hd,
- .cap = md->cap,
- .nch = t->rec_nch,
- .scale = md->attn_scale,
- .qs = (uint32_t)qs,
- .ps = (uint32_t)part_tok(t, md, t->rec_nch)};
- janas_g_push_addr(pa.pos, POS);
- janas_g_push_addr(pa.q, QKV);
- janas_g_push_addr(pa.kc, addr_of(g, ly->kc, cache));
- janas_g_push_addr(pa.vc, addr_of(g, ly->vc, cache));
- janas_g_push_addr(pa.ks, addr_of(g, ly->ks, cache / md->hd * 4));
- janas_g_push_addr(pa.vs, addr_of(g, ly->vs, cache / md->hd * 4));
- janas_g_push_addr(pa.part, B + t->o_part);
- bind(g, &bound, t->p_at);
- push(g, &pa, sizeof(pa));
- g->vkCmdDispatch(g->cb, md->n_kv * t->rec_nch, n, 1);
- janas_g_compute_barrier(g);
- stamp(g, t, PH_ATTN);
- /* the runs joined and the output quantized for wo, a workgroup a
- block of 256 */
- struct push_am pm = {.hd = md->hd,
- .nch = t->rec_nch,
- .ps = (uint32_t)part_tok(t, md, t->rec_nch),
- .gs = qd};
- janas_g_push_addr(pm.gate, md->gated_q ? B + t->o_gate : 0);
- janas_g_push_addr(pm.part, B + t->o_part);
- janas_g_push_addr(pm.q256, B + t->o_q256);
- janas_g_push_addr(pm.q32, B + t->o_q32);
- janas_g_push_addr(pm.pos, POS);
- bind(g, &bound, t->p_am);
- push(g, &pm, sizeof(pm));
- g->vkCmdDispatch(g->cb, qd / JANAS_QK, n, 1);
- janas_g_compute_barrier(g);
- stamp(g, t, PH_MERGE);
- /* the output projection */
- if (rec_product(g, t, &bound, &ly->wo, 0, YWO, n, 0) != 0)
- return -1;
- janas_g_compute_barrier(g);
- stamp(g, t, PH_WO);
- ffn:
- rec_norm_quant(g, t, &bound, X, YWO,
- addr_of(g, ly->ffn_norm, md->dm * 4), XN, 0, md->dm,
- md->eps, n);
SW = X, X = XN, XN = SW;
- stamp(g, t, PH_NORM);
- /* the feed-forward: gate, up (the n tokens' gates, then their ups),
- SiLU(gate) up quantized, down */
- VkDeviceAddress UP = GU + (size_t)n * md->ff * 4;
- if (rec_product(g, t, &bound, &ly->gate, 0, GU, n, 0) != 0 ||
- rec_product(g, t, &bound, &ly->up, 0, UP, n, 0) != 0)
+ if (on &&
+ (md->n_expert ? janas_gt_rec_router(g, t, md, ly, l, &bound, n)
+ : janas_gt_rec_ffn(g, t, &bound, &ly->gate, &ly->up,
+ &ly->down, n, YD)) != 0)
return -1;
- janas_g_compute_barrier(g);
- stamp(g, t, PH_GATEUP);
- struct push_ac ac = {.blocks = n * md->ff / JANAS_QK};
- janas_g_push_addr(ac.g, GU);
- janas_g_push_addr(ac.u, UP);
- janas_g_push_addr(ac.x, H);
- bind(g, &bound, g->pipea);
- push(g, &ac, sizeof(ac));
- g->vkCmdDispatch(g->cb, n * md->ff / JANAS_QK, 1, 1);
- janas_g_compute_barrier(g);
- stamp(g, t, PH_ACT);
- struct janas_matvec_task dn = ly->down;
- if (janas_g_record_task(
- g, &bound,
- &(struct janas_matvec_task){.type = dn.type,
- .w = dn.w,
- .plane = {dn.plane[0], dn.plane[1]},
- .rows = dn.rows,
- .cols = dn.cols,
- .n_vec = n},
- dn.rows, H, YD, dn.rows) != 0)
- return -1;
- janas_g_compute_barrier(g);
- stamp(g, t, PH_DOWN);
}
/* the last feed-forward added, the final norm, the output head for
tokens first .. n - 1 (none: the residual left in X, the next block's
keys and values already in the cache) */
- if (first < n || hid) {
- rec_norm_quant(g, t, &bound, X, YD,
- addr_of(g, md->out_norm, md->dm * 4), 0,
- hid ? B + t->o_hid : 0, md->dm, md->eps, n);
- }
- if (first < n) {
- if (rec_product(g, t, &bound, output,
- (size_t)first * (md->dm / JANAS_QK) * 320,
- B + t->o_logits, n - first, 0) != 0)
- return -1;
+ if (seg < 0 || seg == (int)nl) {
+ if (md->n_expert)
+ janas_gt_rec_experts(g, t, md, &layers[nl - 1], &bound, YD, n);
+ if (first < n || hid) {
+ janas_gt_rec_norm_quant(
+ g, t, &bound, X, YD,
+ janas_gt_addr_of(g, md->out_norm, md->dm * 4), 0,
+ hid ? B + t->o_hid : 0, md->dm, md->eps, n);
+ }
+ if (first < n) {
+ if (janas_gt_rec_product(g, t, &bound, output,
+ (size_t)first * (md->dm / JANAS_QK) * 320,
+ B + t->o_logits, n - first, 0) != 0)
+ return -1;
+ }
+ janas_gt_stamp(g, t, PH_OUT);
}
- stamp(g, t, PH_OUT);
VkMemoryBarrier mb = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER,
.srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT,
.dstAccessMask = VK_ACCESS_HOST_READ_BIT};
@@ -873,10 +585,57 @@ uint32_t janas_gpu_tok_block_at(const struct janas_gpu_tok *t,
{
if (!t)
return 0;
- size_t n = t->part_floats / part_tok(t, md, runs_for(t, pos + t->nb));
+ size_t n =
+ t->part_floats / janas_gt_part_tok(t, md, runs_for(t, pos + t->nb));
return n < 1 ? 1 : n > t->nb ? t->nb : (uint32_t)n;
}
+/* A command buffer for cb, allocated, and the commands of segment seg of a
+ block of n tokens recorded into it: 0, or -1 with *cb NULL. */
+int janas_gt_make_cb(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, VkCommandBuffer *cb,
+ uint32_t n, uint32_t first, int hi, uint32_t nch, int seg)
+{
+ VkCommandBufferAllocateInfo ca = {
+ .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
+ .commandPool = g->cp,
+ .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
+ .commandBufferCount = 1};
+ if (g->vkAllocateCommandBuffers(g->dev, &ca, cb) != VK_SUCCESS) {
+ *cb = VK_NULL_HANDLE;
+ return -1;
+ }
+ VkCommandBuffer keep = g->cb;
+ g->cb = *cb; /* the helpers record into g->cb */
+ t->rec_nch = nch;
+ int rc = record(g, t, md, n, first, hi, seg);
+ g->cb = keep;
+ if (rc != 0) {
+ g->vkFreeCommandBuffers(g->dev, g->cp, 1, cb);
+ *cb = VK_NULL_HANDLE;
+ return -1;
+ }
+ return 0;
+}
+
+int janas_gt_submit_wait(struct janas_gpu *g, const VkCommandBuffer *cb)
+{
+ VkSubmitInfo sub = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
+ .commandBufferCount = 1,
+ .pCommandBuffers = cb};
+ pthread_mutex_lock(&g->qlock);
+ VkResult r = g->vkQueueSubmit(g->queue, 1, &sub, g->fence);
+ pthread_mutex_unlock(&g->qlock);
+ if (r == VK_SUCCESS)
+ r = g->vkWaitForFences(g->dev, 1, &g->fence, VK_TRUE, UINT64_MAX);
+ if (r != VK_SUCCESS) {
+ g->broken = 1;
+ return -1;
+ }
+ g->vkResetFences(g->dev, 1, &g->fence);
+ return 0;
+}
+
int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
const struct janas_gpu_tok_model *md, const float *x,
const float *cs, const float *sn, uint32_t pos,
@@ -887,7 +646,7 @@ int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
(md->n_rec && n + 1 < md->d_conv))
return -1;
uint32_t nch = runs_for(t, pos + n);
- if ((size_t)n * part_tok(t, md, nch) > t->part_floats)
+ if ((size_t)n * janas_gt_part_tok(t, md, nch) > t->part_floats)
return -1;
uint32_t half = md->n_rot / 2, first = all == 1 ? 0 : all == 2 ? n : n - 1;
memcpy(t->buf.map + t->o_x, x, (size_t)n * md->dm * sizeof(float));
@@ -901,62 +660,40 @@ int janas_gpu_tok_run(struct janas_gpu *g, struct janas_gpu_tok *t,
write, read by the shaders at run time */
uint32_t pw[3] = {pos, src, dst};
memcpy(t->buf.map + t->o_pos, pw, sizeof(pw));
- sync_range(g, t, t->o_x, (size_t)n * md->dm * sizeof(float), 1);
- sync_range(g, t, t->o_rope, (size_t)n * md->n_rot * sizeof(float), 1);
- sync_range(g, t, t->o_pos, sizeof(pw), 1);
+ janas_gt_sync_range(g, t, t->o_x, (size_t)n * md->dm * sizeof(float), 1);
+ janas_gt_sync_range(g, t, t->o_rope, (size_t)n * md->n_rot * sizeof(float),
+ 1);
+ janas_gt_sync_range(g, t, t->o_pos, sizeof(pw), 1);
int ai = all == 1 && n == 1 ? 0 : all, hi = hidden != NULL;
- VkCommandBuffer *cb = &t->cb[n][ai][hi];
- if (*cb && t->cb_nch[n][ai][hi] != nch) {
- /* recorded for other runs: again (a few times in a context) */
- g->vkFreeCommandBuffers(g->dev, g->cp, 1, cb);
- *cb = VK_NULL_HANDLE;
- }
- if (!*cb) {
- VkCommandBufferAllocateInfo ca = {
- .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
- .commandPool = g->cp,
- .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY,
- .commandBufferCount = 1};
- if (g->vkAllocateCommandBuffers(g->dev, &ca, cb) != VK_SUCCESS) {
- *cb = VK_NULL_HANDLE;
+ struct timespec w0, w1;
+ clock_gettime(CLOCK_MONOTONIC, &w0);
+ if (md->n_expert) {
+ if (janas_gt_run_segments(g, t, md, n, first, ai, hi, nch) != 0)
return -1;
- }
- VkCommandBuffer keep = g->cb;
- g->cb = *cb; /* the helpers record into g->cb */
- t->rec_nch = nch;
- t->cb_nch[n][ai][hi] = nch;
- int rc = record(g, t, md, n, first, hi);
- g->cb = keep;
- if (rc != 0) {
+ } else {
+ VkCommandBuffer *cb = &t->cb[n][ai][hi];
+ if (*cb && t->cb_nch[n][ai][hi] != nch) {
+ /* recorded for other runs: again (a few times in a context) */
g->vkFreeCommandBuffers(g->dev, g->cp, 1, cb);
*cb = VK_NULL_HANDLE;
- return -1;
}
- }
- VkSubmitInfo sub = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
- .commandBufferCount = 1,
- .pCommandBuffers = cb};
- struct timespec w0, w1;
- clock_gettime(CLOCK_MONOTONIC, &w0);
- pthread_mutex_lock(&g->qlock);
- VkResult r = g->vkQueueSubmit(g->queue, 1, &sub, g->fence);
- pthread_mutex_unlock(&g->qlock);
- if (r == VK_SUCCESS)
- r = g->vkWaitForFences(g->dev, 1, &g->fence, VK_TRUE, UINT64_MAX);
- if (r != VK_SUCCESS) {
- g->broken = 1;
- return -1;
+ if (!*cb) {
+ if (janas_gt_make_cb(g, t, md, cb, n, first, hi, nch, -1) != 0)
+ return -1;
+ t->cb_nch[n][ai][hi] = nch;
+ }
+ if (janas_gt_submit_wait(g, cb) != 0)
+ return -1;
}
clock_gettime(CLOCK_MONOTONIC, &w1);
- g->vkResetFences(g->dev, 1, &g->fence);
size_t lb = (size_t)(n - first) * md->n_vocab * 4;
if (lb) {
- sync_range(g, t, t->o_logits, lb, 0);
+ janas_gt_sync_range(g, t, t->o_logits, lb, 0);
memcpy(logits, t->buf.map + t->o_logits, lb);
}
if (hidden) {
size_t hb = (size_t)n * md->dm * 4;
- sync_range(g, t, t->o_hid, hb, 0);
+ janas_gt_sync_range(g, t, t->o_hid, hb, 0);
memcpy(hidden, t->buf.map + t->o_hid, hb);
}
struct timespec w2;
diff --git a/src/llm/gpu_token.h b/src/llm/gpu_token.h
index 3454c38..c02d5de 100644
--- a/src/llm/gpu_token.h
+++ b/src/llm/gpu_token.h
@@ -9,6 +9,8 @@
* For now the dense attention models (qwen3's shape: q and k norms, NeoX
* RoPE, an eight-bit KV cache, SiLU feed-forward), and qwen3.5's (Gated
* DeltaNet layers between them, the query with an output gate) for blocks,
+ * both with a mixture of experts too (qwen3moe, qwen35moe: a submission a
+ * layer, the CPU sorting the router's choice in between),
* on a GPU that shares the host's memory: the weights, the experts' arena and
* the KV cache are the CPU's own memory, imported, so the CPU's passes (a
* prompt in blocks) and the GPU's tokens read and write the same cache. The
@@ -39,6 +41,17 @@ struct janas_gpu_tok_layer {
struct janas_matvec_task ssm_qkv, ssm_z, ssm_out;
const float *ssm_beta, *ssm_alpha, *conv_w, *dt, *ssm_a, *ssm_norm;
uint32_t slot;
+ /* a mixture's layer (the model's n_expert > 1): the router (n_expert x
+ dm, f16) and the shared expert's gate (dm floats, or NULL); gate, up
+ and down the experts' types and shapes, with no weights - those come
+ from the model's slots (janas_gpu_tok_model fetch): off, each
+ matrix's bytes into a slot, poff the down matrix's two bare planes'
+ (Q6_K_P: 0, a plane the cache does not hold); sh_gate_w, sh_up, sh_down
+ the shared expert (type 0: none) */
+ const uint16_t *router16;
+ const float *sh_gate;
+ size_t off[3], poff[2];
+ struct janas_matvec_task sh_gate_w, sh_up, sh_down;
};
struct janas_gpu_tok_model {
@@ -61,6 +74,21 @@ struct janas_gpu_tok_model {
int vmap_mod;
uint16_t *ssm_state;
float *conv_state;
+ /* a mixture (n_expert > 1, 0 for a dense model): k experts a token, of
+ eff rows each; ff above is the shared expert's (eff without one).
+ Its layers run one at a time, the CPU between two of them: the
+ router's choice read, its experts' slots asked of fetch (0, or -1:
+ the block goes to the CPU), the pairs given to routed (or NULL) */
+ uint32_t n_expert, k, eff;
+ int (*fetch)(void *ctx, uint32_t layer, const uint32_t *ids, size_t n,
+ const uint8_t **slots);
+ void (*routed)(void *ctx, uint32_t layer, uint32_t n, uint32_t k,
+ const uint32_t *ids);
+ /* reads every expert of the layer that is not in the cache, while the
+ caller goes on (or NULL): a block of many tokens chooses nearly all
+ of them, so none is read for nothing */
+ void (*prefetch)(void *ctx, uint32_t layer);
+ void *ctx;
};
struct janas_gpu_tok;
diff --git a/src/llm/gpu_token_impl.h b/src/llm/gpu_token_impl.h
new file mode 100644
index 0000000..14b3e78
--- /dev/null
+++ b/src/llm/gpu_token_impl.h
@@ -0,0 +1,262 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * gpu_token_impl.h - the insides of the whole token on the GPU (private to
+ * gpu_token.c, gpu_token_rec.c and gpu_token_moe.c): the shaders' push
+ * constants, the token's buffers and the helpers that record its commands.
+ * Only with the GPU in the build.
+ */
+#ifndef JANAS_LLM_GPU_TOKEN_IMPL_H
+#define JANAS_LLM_GPU_TOKEN_IMPL_H
+
+#include "gpu_impl.h"
+#include "gpu_token.h"
+
+#if defined(JANAS_GPU_SPV) && __has_include(<vulkan/vulkan.h>)
+
+#include <stddef.h>
+
+/* The push constants of each shader, laid out as its GLSL block. */
+struct push_nq {
+ uint32_t x[2], add[2], w[2], xo[2], q256[2], q32[2], xn[2];
+ uint32_t d;
+ float eps;
+};
+struct push_qk {
+ uint32_t qkv[2], qn[2], kn[2], rope[2], kc[2], vc[2], ks[2], vs[2];
+ uint32_t n_head, n_kv, hd, n_rot, cap, qs;
+ float eps;
+ uint32_t pad, pos[2]; /* the position's buffer, 8-byte aligned */
+};
+struct push_at {
+ uint32_t q[2], kc[2], vc[2], ks[2], vs[2], part[2];
+ uint32_t n_head, n_kv, hd, cap, nch;
+ float scale;
+ uint32_t qs, ps;
+ uint32_t pos[2]; /* the position's buffer */
+};
+struct push_am {
+ uint32_t part[2], q256[2], q32[2];
+ uint32_t hd, nch, ps, gs;
+ uint32_t pos[2]; /* 8-byte aligned, as the GLSL block puts it */
+ uint32_t gate[2];
+};
+/* the Gated DeltaNet shaders (gdn_*.comp) */
+struct push_gconv {
+ uint32_t mixed[2], out[2], w[2], state[2], pos[2];
+ uint32_t cc, d, hs, so;
+};
+struct push_gcst {
+ uint32_t mixed[2], state[2], pos[2];
+ uint32_t cc, d, hs, so, n;
+};
+struct push_gl2 {
+ uint32_t x[2];
+ uint32_t cc;
+ float eps;
+};
+struct push_grec {
+ uint32_t co[2], ba[2], att[2], state[2], pos[2], dt[2], a[2];
+ uint32_t cc, nv, nkh, n, hs, so, vmap_mod;
+ float scale;
+};
+struct push_ggate {
+ uint32_t att[2], z[2], w[2], q256[2], q32[2];
+ uint32_t d;
+ float eps;
+};
+struct push_dm { /* gpu.c's dense_mm.comp */
+ uint32_t w[2], x[2], y[2];
+ uint32_t rows, cols, nv, ys;
+ float scale;
+};
+/* a mixture's (moe_*.comp, and gpu.c's *_mmid.comp) */
+struct push_tk {
+ uint32_t r[2], pe[2], pw[2], shw[2];
+ uint32_t ne, rs, k, n, sh;
+};
+struct push_ga {
+ uint32_t src[2], dst[2], tok[2];
+ uint32_t nb;
+};
+struct push_cb {
+ uint32_t dout[2], pw[2], inv[2], sh[2], shw[2], y[2];
+ uint32_t dm, k, has_sh;
+};
+struct push_id {
+ uint32_t t[2];
+ uint32_t rows, nb, tiles;
+};
+struct push_sm {
+ uint32_t g[2], u[2], h[2];
+ uint32_t n;
+};
+/* The attention's positions a run (attn_decode.comp C), and the shapes its
+ shared memory takes: the query heads of a KV head times hd, and times a
+ run. */
+#define ATT_RUN 128
+#define ATT_MAXQ 2048
+#define ATT_MAXS 1024
+
+struct push_ac {
+ uint32_t g[2], u[2], x[2];
+ uint32_t blocks;
+};
+_Static_assert(sizeof(struct push_qk) <= JANAS_G_PUSH_BYTES, "push size");
+_Static_assert(sizeof(struct push_at) <= JANAS_G_PUSH_BYTES, "push size");
+/* the uvec2 members where GLSL puts them: on 8 bytes */
+_Static_assert(offsetof(struct push_qk, pos) % 8 == 0, "push layout");
+_Static_assert(offsetof(struct push_at, pos) % 8 == 0, "push layout");
+_Static_assert(offsetof(struct push_am, pos) % 8 == 0, "push layout");
+_Static_assert(sizeof(struct push_grec) <= JANAS_G_PUSH_BYTES, "push size");
+_Static_assert(sizeof(struct push_cb) <= JANAS_G_PUSH_BYTES, "push size");
+/* The most tokens a block takes (the model's own blocks: model.h
+ JANAS_LLM_MAX_BLOCK), and the memory the attention's runs may take for
+ them. */
+#define TOK_MAX_BLOCK 256
+#define TOK_PART_BUDGET ((size_t)64 << 20)
+
+/* JANAS_GPU_TOKEN_PROFILE=1: the GPU's own timestamps after each phase of
+ the token, summed per phase and printed when the model is closed */
+enum {
+ PH_NORM,
+ PH_QKV,
+ PH_ROPE,
+ PH_ATTN,
+ PH_MERGE,
+ PH_WO,
+ PH_GATEUP,
+ PH_ACT,
+ PH_DOWN,
+ PH_OUT,
+ PH_N
+};
+#define MAX_TS 1024
+
+struct janas_gpu_tok {
+ /* its own command buffers, one per number of tokens n (1 .. nb) and
+ logits of the last token, of all or of none ([n][all]: 0, 1, 2),
+ each recorded once:
+ the position is read from the buffer at o_pos, so every block of n
+ tokens submits the same commands */
+ uint32_t nb;
+ /* [n][all][hidden wanted] */
+ VkCommandBuffer cb[TOK_MAX_BLOCK + 1][3][2];
+ uint32_t cb_nch[TOK_MAX_BLOCK + 1][3]
+ [2]; /* the runs each was recorded for */
+ int prof; /* timestamps in the commands being recorded (n = 1) */
+ VkQueryPool qp; /* timestamps, if profiling */
+ uint32_t n_ts; /* written this token */
+ uint8_t ph_of[MAX_TS]; /* the phase each timestamp closes */
+ double ph_ns[PH_N];
+ double wall_ns; /* submission to the fence, as the CPU sees it */
+ double copy_ns; /* the logits copied out */
+ uint64_t tokens;
+ VkShaderModule sm_nq, sm_qk, sm_at, sm_am;
+ VkPipeline p_nq, p_qk, p_at, p_am;
+ /* qwen3.5's recurrent layers */
+ VkShaderModule sm_gc, sm_gs, sm_gl, sm_gr, sm_gg;
+ VkPipeline p_gc, p_gs, p_gl, p_gr, p_gg;
+ size_t *par; /* per layer: its parameters' offsets in buf (PAR_*) */
+ struct stage buf; /* every intermediate, one allocation */
+ /* offsets into buf, each nb tokens' worth */
+ uint32_t nch; /* the attention's runs of positions, for the cache */
+ size_t part_floats; /* room for the runs of a block, floats */
+ uint32_t rec_nch; /* the runs a token of the block being recorded has */
+ size_t o_part;
+ size_t o_x, o_x1, o_q256, o_q32, o_qkv, o_ywo, o_gu, o_h, o_yd, o_rope,
+ o_logits, o_pos;
+ /* qwen3.5: the normalized input (f32), q|k|v and z of the recurrent
+ layers, their convolution's output, beta and alpha, their raw
+ output, the query's gates, the final hidden states */
+ size_t o_xnf, o_mix, o_z, o_conv, o_ba, o_att, o_gate, o_hid;
+ /* a mixture: a submission a layer ([n][all][hidden], n_layer + 1 of
+ them, each recorded for the runs in seg_nch), its shaders; the
+ router's logits (n_expert + 1 a token), the pairs' experts and
+ weights, the shared expert's weights and output, the activations in
+ the experts' order, their gates and ups, activations and outputs,
+ each row's token, each pair's row, the tables of the gate and up
+ products and of the down ones (their tiles from uvec4 tiles1 and
+ tiles2 on), the two dispatches' sizes */
+ VkCommandBuffer *seg_cb[TOK_MAX_BLOCK + 1][3][2];
+ uint32_t seg_nch[TOK_MAX_BLOCK + 1][3][2];
+ VkShaderModule sm_tk, sm_ga, sm_cb, sm_sm;
+ VkPipeline p_tk, p_ga, p_cb, p_sm;
+ size_t o_r, o_pe, o_pw, o_shw, o_sh, o_xg, o_egu, o_eh, o_dout, o_gt, o_inv,
+ o_tab1, o_tab2, o_ind;
+ /* a shared expert's activation as floats and in blocks of 32, for a
+ down matrix in blocks of 32 */
+ size_t o_hf, o_h32;
+ uint32_t tiles1, tiles2;
+ uint32_t n_seg; /* n_layer + 1 */
+ /* the CPU's side: the experts' counts and fill, those chosen, their
+ slots */
+ uint32_t *cnt, *fill, *ids;
+ const uint8_t **slots;
+};
+
+/* A recurrent layer's parameters copied into buf: beta then alpha (2 nv x
+ dm), the convolution (d_conv x conv_ch), dt, A (nv), the norm (ds); a
+ mixture's router as f32 (n_expert rows, then the shared expert's gate) */
+enum { PAR_BA, PAR_CONV, PAR_DT, PAR_A, PAR_NORM, PAR_R, PAR_N };
+
+/* The GPU's address of host memory in one of its regions, 0 if none. */
+VkDeviceAddress janas_gt_addr_of(const struct janas_gpu *g, const void *p,
+ size_t bytes);
+/* Bytes [off, off + bytes) of the token's buffer out of the CPU's caches
+ (flush) or reloaded from memory (!flush), where it is not coherent. */
+void janas_gt_sync_range(struct janas_gpu *g, struct janas_gpu_tok *t,
+ size_t off, size_t bytes, int flush);
+/* A command buffer for cb, allocated, and the commands of segment seg of a
+ block of n tokens recorded into it (gpu_token.c): 0, or -1 with *cb
+ NULL. */
+int janas_gt_make_cb(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, VkCommandBuffer *cb,
+ uint32_t n, uint32_t first, int hi, uint32_t nch, int seg);
+int janas_gt_submit_wait(struct janas_gpu *g, const VkCommandBuffer *cb);
+
+/* gpu_token_rec.c: the commands, recorded into g->cb */
+void janas_gt_stamp(struct janas_gpu *g, struct janas_gpu_tok *t, int ph);
+void janas_gt_bind(struct janas_gpu *g, VkPipeline *bound, VkPipeline p);
+void janas_gt_push(struct janas_gpu *g, const void *pc, size_t bytes);
+void janas_gt_rec_norm_quant(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkPipeline *bound, VkDeviceAddress x,
+ VkDeviceAddress add, VkDeviceAddress w,
+ VkDeviceAddress xo, VkDeviceAddress xn, uint32_t d,
+ float eps, uint32_t n);
+int janas_gt_rec_product(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkPipeline *bound, const struct janas_matvec_task *w,
+ size_t xoff, VkDeviceAddress y, uint32_t n, size_t ys);
+size_t janas_gt_part_tok(const struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, uint32_t nch);
+int janas_gt_rec_gdn(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md,
+ const struct janas_gpu_tok_layer *ly, uint32_t l,
+ VkPipeline *bound, VkDeviceAddress YWO, uint32_t n);
+int janas_gt_rec_attn(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md,
+ const struct janas_gpu_tok_layer *ly, VkPipeline *bound,
+ uint32_t n);
+int janas_gt_rec_ffn(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkPipeline *bound, const struct janas_matvec_task *gate,
+ const struct janas_matvec_task *up,
+ const struct janas_matvec_task *down, uint32_t n,
+ VkDeviceAddress out);
+
+/* gpu_token_moe.c: a mixture's layers */
+int janas_gt_rec_router(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md,
+ const struct janas_gpu_tok_layer *ly, uint32_t l,
+ VkPipeline *bound, uint32_t n);
+void janas_gt_rec_experts(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md,
+ const struct janas_gpu_tok_layer *ly,
+ VkPipeline *bound, VkDeviceAddress YD, uint32_t n);
+void janas_gt_free_segments(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkCommandBuffer **seg);
+int janas_gt_run_segments(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, uint32_t n,
+ uint32_t first, int ai, int hi, uint32_t nch);
+
+#endif
+#endif
diff --git a/src/llm/gpu_token_moe.c b/src/llm/gpu_token_moe.c
new file mode 100644
index 0000000..f95279c
--- /dev/null
+++ b/src/llm/gpu_token_moe.c
@@ -0,0 +1,271 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * gpu_token_moe.c - a mixture's layers in the whole token on the GPU
+ * (gpu_token_impl.h): its router's choice made on the GPU, sorted on the
+ * CPU between two submissions, its experts' products and their sum.
+ */
+#include "gpu_token_impl.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "quant.h"
+
+#if defined(JANAS_GPU_SPV) && __has_include(<vulkan/vulkan.h>)
+
+/* A mixture's submissions for one block shape, freed (n_layer + 1 of
+ them, the array too). */
+void janas_gt_free_segments(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkCommandBuffer **seg)
+{
+ if (!*seg)
+ return;
+ for (uint32_t s = 0; s < t->n_seg; s++)
+ if ((*seg)[s])
+ g->vkFreeCommandBuffers(g->dev, g->cp, 1, &(*seg)[s]);
+ free(*seg);
+ *seg = NULL;
+}
+
+/* A mixture's layer l up to its router's choice, on the block normalized
+ in q256 and XNF: the shared expert into SH, the router's logits, then
+ each token's experts and weights (PE, PW, SHW), for the CPU to read. */
+int janas_gt_rec_router(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md,
+ const struct janas_gpu_tok_layer *ly, uint32_t l,
+ VkPipeline *bound, uint32_t n)
+{
+ VkDeviceAddress B = t->buf.addr;
+ uint32_t ne = md->n_expert;
+ if (ly->sh_gate_w.type &&
+ janas_gt_rec_ffn(g, t, bound, &ly->sh_gate_w, &ly->sh_up, &ly->sh_down,
+ n, B + t->o_sh) != 0)
+ return -1;
+ struct push_dm pd = {.rows = ne + (ly->sh_gate ? 1 : 0),
+ .cols = md->dm,
+ .nv = n,
+ .ys = ne + 1,
+ .scale = 1.0f};
+ janas_g_push_addr(pd.w, B + t->par[(size_t)l * PAR_N + PAR_R]);
+ janas_g_push_addr(pd.x, B + t->o_xnf);
+ janas_g_push_addr(pd.y, B + t->o_r);
+ janas_gt_bind(g, bound, g->pipe_dm[0]);
+ janas_gt_push(g, &pd, sizeof(pd));
+ g->vkCmdDispatch(g->cb, (pd.rows + 63) / 64, (n + 63) / 64, 1);
+ janas_g_compute_barrier(g);
+ struct push_tk pk = {
+ .ne = ne, .rs = ne + 1, .k = md->k, .n = n, .sh = ly->sh_gate != NULL};
+ janas_g_push_addr(pk.r, B + t->o_r);
+ janas_g_push_addr(pk.pe, B + t->o_pe);
+ janas_g_push_addr(pk.pw, B + t->o_pw);
+ janas_g_push_addr(pk.shw, B + t->o_shw);
+ janas_gt_bind(g, bound, t->p_tk);
+ janas_gt_push(g, &pk, sizeof(pk));
+ g->vkCmdDispatch(g->cb, (n + 63) / 64, 1, 1);
+ janas_g_compute_barrier(g);
+ return 0;
+}
+
+/* A mixture's experts on the block whose router chose them (plan wrote
+ their tables and sizes): the activations gathered in the experts'
+ order, gate and up, the activation, down, then each token's weighted
+ sum (and the shared expert) into YD. */
+void janas_gt_rec_experts(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md,
+ const struct janas_gpu_tok_layer *ly,
+ VkPipeline *bound, VkDeviceAddress YD, uint32_t n)
+{
+ VkDeviceAddress B = t->buf.addr;
+ uint32_t np = n * md->k, nbd = md->dm / JANAS_QK, nbf = md->eff / JANAS_QK;
+ struct push_ga pg = {.nb = nbd};
+ janas_g_push_addr(pg.src, B + t->o_q256);
+ janas_g_push_addr(pg.dst, B + t->o_xg);
+ janas_g_push_addr(pg.tok, B + t->o_gt);
+ janas_gt_bind(g, bound, t->p_ga);
+ janas_gt_push(g, &pg, sizeof(pg));
+ g->vkCmdDispatch(g->cb, np, 1, 1);
+ janas_g_compute_barrier(g);
+ 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, 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);
+ struct push_ac ac = {.blocks = np * nbf};
+ janas_g_push_addr(ac.g, B + t->o_egu);
+ janas_g_push_addr(ac.u, B + t->o_egu + (size_t)np * md->eff * 4);
+ janas_g_push_addr(ac.x, B + t->o_eh);
+ janas_gt_bind(g, bound, g->pipea);
+ janas_gt_push(g, &ac, sizeof(ac));
+ g->vkCmdDispatch(g->cb, np * nbf, 1, 1);
+ janas_g_compute_barrier(g);
+ pi = (struct push_id){.rows = md->dm, .nb = nbf, .tiles = t->tiles2};
+ janas_g_push_addr(pi.t, B + t->o_tab2);
+ janas_gt_bind(g, bound,
+ ly->down.type == JANAS_Q4_K ? g->pipe_id4
+ : ly->down.type == JANAS_Q6_K ? g->pipe_id6s
+ : g->pipe_id6);
+ janas_gt_push(g, &pi, sizeof(pi));
+ g->vkCmdDispatchIndirect(g->cb, t->buf.buf, t->o_ind + 16);
+ janas_g_compute_barrier(g);
+ struct push_cb pc = {
+ .dm = md->dm, .k = md->k, .has_sh = ly->sh_gate_w.type != 0};
+ janas_g_push_addr(pc.dout, B + t->o_dout);
+ janas_g_push_addr(pc.pw, B + t->o_pw);
+ janas_g_push_addr(pc.inv, B + t->o_inv);
+ janas_g_push_addr(pc.sh, B + t->o_sh);
+ janas_g_push_addr(pc.shw, B + t->o_shw);
+ janas_g_push_addr(pc.y, YD);
+ janas_gt_bind(g, bound, t->p_cb);
+ janas_gt_push(g, &pc, sizeof(pc));
+ g->vkCmdDispatch(g->cb, md->dm / JANAS_QK, n, 1);
+ janas_g_compute_barrier(g);
+}
+
+/* An entry of a *_mmid table: weights, activations, outputs (ys floats
+ apart), vectors, and the down matrix's bare planes (or 0). */
+static void table_entry(uint32_t *e, VkDeviceAddress w, VkDeviceAddress x,
+ VkDeviceAddress y, uint32_t nv, uint32_t ys,
+ VkDeviceAddress p0, VkDeviceAddress p1)
+{
+ janas_g_push_addr(e, w);
+ janas_g_push_addr(e + 2, x);
+ janas_g_push_addr(e + 4, y);
+ e[6] = nv;
+ e[7] = ys;
+ janas_g_push_addr(e + 8, p0);
+ janas_g_push_addr(e + 10, p1);
+}
+
+/*
+ * Between two of a mixture's submissions, on the CPU: layer l's choice (n
+ * tokens, k experts each) read back and sorted by expert, as model_ffn.c
+ * does - each row's token, each pair's row - the experts' slots asked of
+ * the model, the tables of the products and the sizes of their dispatches
+ * written. 0, or -1 (an expert unreadable, or out of the GPU's reach).
+ */
+static int plan(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, uint32_t l, uint32_t n)
+{
+ const struct janas_gpu_tok_layer *ly = &md->layers[l];
+ uint32_t k = md->k, ne = md->n_expert, np = n * k, nd = 0;
+ uint32_t nbd = md->dm / JANAS_QK, nbf = md->eff / JANAS_QK;
+ janas_gt_sync_range(g, t, t->o_pe, (size_t)np * 4, 0);
+ const uint32_t *pe = (const uint32_t *)(t->buf.map + t->o_pe);
+ uint32_t *cnt = t->cnt, *gt = (uint32_t *)(t->buf.map + t->o_gt),
+ *inv = (uint32_t *)(t->buf.map + t->o_inv);
+ memset(cnt, 0, (ne + 1) * sizeof(*cnt));
+ for (uint32_t p = 0; p < np; p++) {
+ if (pe[p] >= ne)
+ return -1;
+ cnt[pe[p] + 1]++;
+ }
+ if (md->routed)
+ md->routed(md->ctx, l, n, k, pe);
+ for (uint32_t e = 0; e < ne; e++) {
+ if (cnt[e + 1])
+ t->ids[nd++] = e;
+ cnt[e + 1] += cnt[e];
+ t->fill[e] = cnt[e];
+ }
+ for (uint32_t p = 0; p < np; p++) {
+ uint32_t r = t->fill[pe[p]]++;
+ gt[r] = p / k;
+ inv[p] = r;
+ }
+ if (md->fetch(md->ctx, l, t->ids, nd, t->slots) != 0)
+ return -1;
+ VkDeviceAddress B = t->buf.addr;
+ uint32_t *t1 = (uint32_t *)(t->buf.map + t->o_tab1),
+ *t2 = (uint32_t *)(t->buf.map + t->o_tab2);
+ uint32_t n1 = 0, n2 = 0; /* tiles */
+ size_t gb = (size_t)md->eff * nbd * janas_qtype_block_size(JANAS_Q4_K),
+ db =
+ (size_t)md->dm * nbf * janas_qtype_block_size(ly->down.type) + 4,
+ pb = (size_t)md->dm * nbf * JANAS_Q6KP_PLANE;
+ for (uint32_t i = 0; i < nd; i++) {
+ uint32_t e = t->ids[i], a = cnt[e], nv = cnt[e + 1] - a;
+ const uint8_t *s = t->slots[i];
+ VkDeviceAddress wg = janas_gt_addr_of(g, s + ly->off[0], gb),
+ wu = janas_gt_addr_of(g, s + ly->off[1], gb),
+ wd = janas_gt_addr_of(g, s + ly->off[2], db), p0 = 0,
+ p1 = 0;
+ /* the planes the cache holds (none, one or both: level 1 to 3) */
+ if (ly->down.type == JANAS_Q6_K_P &&
+ ((ly->poff[0] &&
+ !(p0 = janas_gt_addr_of(g, s + ly->poff[0], pb))) ||
+ (ly->poff[1] && !(p1 = janas_gt_addr_of(g, s + ly->poff[1], pb)))))
+ return -1;
+ if (!wg || !wu || !wd)
+ return -1;
+ VkDeviceAddress x = B + t->o_xg + (VkDeviceAddress)a * nbd * 320;
+ table_entry(t1 + 12 * (2 * i), wg, x,
+ B + t->o_egu + (VkDeviceAddress)a * md->eff * 4, nv,
+ md->eff, 0, 0);
+ table_entry(t1 + 12 * (2 * i + 1), wu, x,
+ B + t->o_egu + ((VkDeviceAddress)np + a) * md->eff * 4, nv,
+ md->eff, 0, 0);
+ table_entry(t2 + 12 * i, wd,
+ B + t->o_eh + (VkDeviceAddress)a * nbf * 320,
+ B + t->o_dout + (VkDeviceAddress)a * md->dm * 4, nv, md->dm,
+ p0, p1);
+ for (uint32_t v = 0; v < nv; v += 16) {
+ uint32_t *u = t1 + 4 * (t->tiles1 + n1);
+ u[0] = 2 * i, u[1] = v, u[2] = u[3] = 0;
+ u[4] = 2 * i + 1, u[5] = v, u[6] = u[7] = 0;
+ n1 += 2;
+ u = t2 + 4 * (t->tiles2 + n2++);
+ u[0] = i, u[1] = v, u[2] = u[3] = 0;
+ }
+ }
+ uint32_t *ind = (uint32_t *)(t->buf.map + t->o_ind);
+ ind[0] = (md->eff + 63) / 64, ind[1] = 1, ind[2] = n1;
+ ind[4] = (md->dm + 63) / 64, ind[5] = 1, ind[6] = n2;
+ janas_gt_sync_range(g, t, t->o_gt, (size_t)np * 4, 1);
+ janas_gt_sync_range(g, t, t->o_inv, (size_t)np * 4, 1);
+ janas_gt_sync_range(g, t, t->o_tab1, ((size_t)t->tiles1 + n1) * 16, 1);
+ janas_gt_sync_range(g, t, t->o_tab2, ((size_t)t->tiles2 + n2) * 16, 1);
+ janas_gt_sync_range(g, t, t->o_ind, 32, 1);
+ return 0;
+}
+
+/* A mixture's block: its n_layer + 1 submissions, each recorded once for
+ its shape and runs, the CPU's plan between two of them. 0, or -1. */
+int janas_gt_run_segments(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, uint32_t n,
+ uint32_t first, int ai, int hi, uint32_t nch)
+{
+ VkCommandBuffer **seg = &t->seg_cb[n][ai][hi];
+ if (*seg && t->seg_nch[n][ai][hi] != nch)
+ janas_gt_free_segments(g, t, seg); /* recorded for other runs: again */
+ if (!*seg) {
+ *seg = calloc(t->n_seg, sizeof(**seg));
+ if (!*seg)
+ return -1;
+ t->seg_nch[n][ai][hi] = nch;
+ }
+ /* a block whose tokens choose some 4 times each expert or more: those
+ few that no token takes are under 2% (e^-4) */
+ int ahead = md->prefetch && (size_t)n * md->k >= 4 * (size_t)md->n_expert;
+ for (uint32_t s = 0; s < t->n_seg; s++) {
+ if (s && plan(g, t, md, s - 1, n) != 0)
+ return -1;
+ /* layer s's experts read while the GPU computes up to its router's
+ choice, as the CPU's path reads the next layer's (model_ffn.c
+ janas_m_prefetch_block): without, the GPU waited for each
+ layer's reads, and on Qwen3.6-35B, whose experts do not all fit,
+ the cache found 79% of them instead of 87% and the prompt was
+ no faster (10 Oct 2026) */
+ if (ahead && s + 1 < t->n_seg)
+ md->prefetch(md->ctx, s);
+ if (!(*seg)[s] && janas_gt_make_cb(g, t, md, &(*seg)[s], n, first, hi,
+ nch, (int)s) != 0)
+ return -1;
+ if (janas_gt_submit_wait(g, &(*seg)[s]) != 0)
+ return -1;
+ }
+ return 0;
+}
+
+#endif
diff --git a/src/llm/gpu_token_rec.c b/src/llm/gpu_token_rec.c
new file mode 100644
index 0000000..fa0197c
--- /dev/null
+++ b/src/llm/gpu_token_rec.c
@@ -0,0 +1,364 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+/*
+ * gpu_token_rec.c - the commands of the whole token on the GPU, recorded
+ * into g->cb (gpu_token_impl.h): norms, products, a layer's attention or
+ * Gated DeltaNet, a feed-forward.
+ */
+#include "gpu_token_impl.h"
+
+#include <math.h>
+#include <stdlib.h>
+
+#include "quant.h"
+
+#if defined(JANAS_GPU_SPV) && __has_include(<vulkan/vulkan.h>)
+
+/* A timestamp closing phase ph (with profiling on). */
+void janas_gt_stamp(struct janas_gpu *g, struct janas_gpu_tok *t, int ph)
+{
+ if (!t->qp || !t->prof || t->n_ts >= MAX_TS)
+ return;
+ g->vkCmdWriteTimestamp(g->cb, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, t->qp,
+ t->n_ts);
+ t->ph_of[t->n_ts++] = (uint8_t)ph;
+}
+
+void janas_gt_bind(struct janas_gpu *g, VkPipeline *bound, VkPipeline p)
+{
+ if (*bound != p) {
+ g->vkCmdBindPipeline(g->cb, VK_PIPELINE_BIND_POINT_COMPUTE, p);
+ *bound = p;
+ }
+}
+
+void janas_gt_push(struct janas_gpu *g, const void *pc, size_t bytes)
+{
+ g->vkCmdPushConstants(g->cb, g->pl, VK_SHADER_STAGE_COMPUTE_BIT, 0,
+ (uint32_t)bytes, pc);
+}
+
+/* x (+ add, then stored at xo) normalized by w (0: not), quantized into
+ q256 and q32: a workgroup per block of 256 values. */
+void janas_gt_rec_norm_quant(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkPipeline *bound, VkDeviceAddress x,
+ VkDeviceAddress add, VkDeviceAddress w,
+ VkDeviceAddress xo, VkDeviceAddress xn, uint32_t d,
+ float eps, uint32_t n)
+{
+ struct push_nq pc = {.d = d, .eps = eps};
+ janas_g_push_addr(pc.xn, xn);
+ janas_g_push_addr(pc.x, x);
+ janas_g_push_addr(pc.add, add);
+ janas_g_push_addr(pc.w, w);
+ janas_g_push_addr(pc.xo, xo);
+ janas_g_push_addr(pc.q256, t->buf.addr + t->o_q256);
+ janas_g_push_addr(pc.q32, t->buf.addr + t->o_q32);
+ janas_gt_bind(g, bound, t->p_nq);
+ janas_gt_push(g, &pc, sizeof(pc));
+ g->vkCmdDispatch(g->cb, d / JANAS_QK, n, 1); /* y: the vector */
+ janas_g_compute_barrier(g);
+}
+
+/* A product of the task's weights with n quantized vectors (from byte xoff
+ of the q256 or q32 layout, cols / 256 blocks apart), into y (ys floats
+ apart; 0: rows). */
+int janas_gt_rec_product(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkPipeline *bound, const struct janas_matvec_task *w,
+ size_t xoff, VkDeviceAddress y, uint32_t n, size_t ys)
+{
+ struct janas_matvec_task k = *w;
+ k.n_vec = n;
+ k.x_stride = 0;
+ k.y_stride = 0;
+ VkDeviceAddress xa =
+ t->buf.addr + xoff + (janas_g_x_in_32(k.type) ? t->o_q32 : t->o_q256);
+ return janas_g_record_task(g, bound, &k, k.rows, xa, y, ys ? ys : k.rows);
+}
+
+/* A token's runs, floats, at nch runs a head. */
+size_t janas_gt_part_tok(const struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md, uint32_t nch)
+{
+ (void)t;
+ return (size_t)md->n_head * nch * (md->hd + 2);
+}
+
+/* A Gated DeltaNet layer (qwen3.5) on the block normalized in q256 / q32
+ and XNF: its output into YWO, as model_rec.c's janas_m_rec_layer. */
+int janas_gt_rec_gdn(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md,
+ const struct janas_gpu_tok_layer *ly, uint32_t l,
+ VkPipeline *bound, VkDeviceAddress YWO, uint32_t n)
+{
+ VkDeviceAddress B = t->buf.addr, MIX = B + t->o_mix, Z = B + t->o_z,
+ CONV = B + t->o_conv, BA = B + t->o_ba, ATT = B + t->o_att,
+ POS = B + t->o_pos;
+ const size_t *pr = t->par + (size_t)l * PAR_N;
+ uint32_t cc = md->conv_ch;
+ /* q|k|v (the convolution's channels) and z */
+ if (janas_gt_rec_product(g, t, bound, &ly->ssm_qkv, 0, MIX, n, cc) != 0 ||
+ janas_gt_rec_product(g, t, bound, &ly->ssm_z, 0, Z, n, md->d_inner) !=
+ 0)
+ return -1;
+ /* beta then alpha, per token, from the normalized input at f32 */
+ struct push_dm pd = {.rows = 2 * md->nv,
+ .cols = md->dm,
+ .nv = n,
+ .ys = 2 * md->nv,
+ .scale = 1.0f};
+ janas_g_push_addr(pd.w, B + pr[PAR_BA]);
+ janas_g_push_addr(pd.x, B + t->o_xnf);
+ janas_g_push_addr(pd.y, BA);
+ janas_gt_bind(g, bound, g->pipe_dm[0]);
+ janas_gt_push(g, &pd, sizeof(pd));
+ g->vkCmdDispatch(g->cb, (2 * md->nv + 63) / 64, (n + 63) / 64, 1);
+ janas_g_compute_barrier(g);
+ /* the convolution, then the state it leaves, the q and k heads' norms */
+ uint32_t hs_c = md->n_rec * (md->d_conv - 1) * cc,
+ so_c = ly->slot * (md->d_conv - 1) * cc;
+ VkDeviceAddress CS = janas_gt_addr_of(g, md->conv_state, (size_t)hs_c * 8);
+ struct push_gconv pc = {.cc = cc, .d = md->d_conv, .hs = hs_c, .so = so_c};
+ janas_g_push_addr(pc.mixed, MIX);
+ janas_g_push_addr(pc.out, CONV);
+ janas_g_push_addr(pc.w, B + pr[PAR_CONV]);
+ janas_g_push_addr(pc.state, CS);
+ janas_g_push_addr(pc.pos, POS);
+ janas_gt_bind(g, bound, t->p_gc);
+ janas_gt_push(g, &pc, sizeof(pc));
+ g->vkCmdDispatch(g->cb, cc / 256, n, 1);
+ janas_g_compute_barrier(g);
+ struct push_gcst ps = {
+ .cc = cc, .d = md->d_conv, .hs = hs_c, .so = so_c, .n = n};
+ janas_g_push_addr(ps.mixed, MIX);
+ janas_g_push_addr(ps.state, CS);
+ janas_g_push_addr(ps.pos, POS);
+ janas_gt_bind(g, bound, t->p_gs);
+ janas_gt_push(g, &ps, sizeof(ps));
+ g->vkCmdDispatch(g->cb, cc / 256, 1, 1);
+ struct push_gl2 pl = {.cc = cc, .eps = md->eps};
+ janas_g_push_addr(pl.x, CONV);
+ janas_gt_bind(g, bound, t->p_gl);
+ janas_gt_push(g, &pl, sizeof(pl));
+ g->vkCmdDispatch(g->cb, 2 * md->nkh, n, 1);
+ janas_g_compute_barrier(g);
+ /* the recurrence, then each head's norm, gate and quantization */
+ uint32_t hs_s = md->n_rec * md->nv * md->ds * md->ds,
+ so_s = ly->slot * md->nv * md->ds * md->ds;
+ struct push_grec pg = {.cc = cc,
+ .nv = md->nv,
+ .nkh = md->nkh,
+ .n = n,
+ .hs = hs_s,
+ .so = so_s,
+ .vmap_mod = (uint32_t)md->vmap_mod,
+ .scale = 1.0f / sqrtf((float)md->ds)};
+ janas_g_push_addr(pg.co, CONV);
+ janas_g_push_addr(pg.ba, BA);
+ janas_g_push_addr(pg.att, ATT);
+ janas_g_push_addr(pg.state,
+ janas_gt_addr_of(g, md->ssm_state, (size_t)hs_s * 4));
+ janas_g_push_addr(pg.pos, POS);
+ janas_g_push_addr(pg.dt, B + pr[PAR_DT]);
+ janas_g_push_addr(pg.a, B + pr[PAR_A]);
+ janas_gt_bind(g, bound, t->p_gr);
+ janas_gt_push(g, &pg, sizeof(pg));
+ g->vkCmdDispatch(g->cb, md->nv * (md->ds / 16), 1, 1);
+ janas_g_compute_barrier(g);
+ struct push_ggate pq = {.d = md->d_inner, .eps = md->eps};
+ janas_g_push_addr(pq.att, ATT);
+ janas_g_push_addr(pq.z, Z);
+ janas_g_push_addr(pq.w, B + pr[PAR_NORM]);
+ janas_g_push_addr(pq.q256, B + t->o_q256);
+ janas_g_push_addr(pq.q32, B + t->o_q32);
+ janas_gt_bind(g, bound, t->p_gg);
+ janas_gt_push(g, &pq, sizeof(pq));
+ g->vkCmdDispatch(g->cb, md->d_inner / JANAS_QK, n, 1);
+ janas_g_compute_barrier(g);
+ if (janas_gt_rec_product(g, t, bound, &ly->ssm_out, 0, YWO, n, 0) != 0)
+ return -1;
+ janas_g_compute_barrier(g);
+ return 0;
+}
+
+/* A layer's attention on the block normalized in q256 / q32: q, k and v,
+ their norms and RoPE (the keys and values into the cache), the
+ attention in runs of positions, joined, then wo into YWO. */
+int janas_gt_rec_attn(struct janas_gpu *g, struct janas_gpu_tok *t,
+ const struct janas_gpu_tok_model *md,
+ const struct janas_gpu_tok_layer *ly, VkPipeline *bound,
+ uint32_t n)
+{
+ uint32_t qd = md->n_head * md->hd, kvd = md->n_kv * md->hd;
+ size_t qs = qd + 2 * kvd;
+ size_t cache = (size_t)md->n_kv * md->cap * md->hd;
+ VkDeviceAddress B = t->buf.addr, QKV = B + t->o_qkv, YWO = B + t->o_ywo,
+ ROPE = B + t->o_rope, POS = B + t->o_pos;
+ /* q, k and v of each token side by side, qs floats a token; a
+ gated query (qwen3.5) head by head, its gates apart */
+ if (md->gated_q) {
+ size_t rb =
+ (size_t)(md->dm / JANAS_QK) * janas_qtype_block_size(ly->wq.type);
+ for (uint32_t h = 0; h < md->n_head; h++) {
+ struct janas_matvec_task q = ly->wq, gt = ly->wq;
+ q.rows = gt.rows = md->hd;
+ q.w = (const uint8_t *)ly->wq.w + (size_t)2 * h * md->hd * rb;
+ gt.w = (const uint8_t *)q.w + (size_t)md->hd * rb;
+ if (janas_gt_rec_product(g, t, bound, &q, 0,
+ QKV + (size_t)h * md->hd * 4, n,
+ qs) != 0 ||
+ janas_gt_rec_product(g, t, bound, &gt, 0,
+ B + t->o_gate + (size_t)h * md->hd * 4, n,
+ qd) != 0)
+ return -1;
+ }
+ } else if (janas_gt_rec_product(g, t, bound, &ly->wq, 0, QKV, n, qs) != 0)
+ return -1;
+ if (janas_gt_rec_product(g, t, bound, &ly->wk, 0, QKV + (size_t)qd * 4, n,
+ qs) != 0 ||
+ janas_gt_rec_product(g, t, bound, &ly->wv, 0,
+ QKV + (size_t)(qd + kvd) * 4, n, qs) != 0)
+ return -1;
+ janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_QKV);
+ struct push_qk pq = {.n_head = md->n_head,
+ .n_kv = md->n_kv,
+ .hd = md->hd,
+ .n_rot = md->n_rot,
+ .cap = md->cap,
+ .qs = (uint32_t)qs,
+ .eps = md->eps};
+ janas_g_push_addr(pq.pos, POS);
+ janas_g_push_addr(pq.qkv, QKV);
+ janas_g_push_addr(pq.qn, janas_gt_addr_of(g, ly->q_norm, md->hd * 4));
+ janas_g_push_addr(pq.kn, janas_gt_addr_of(g, ly->k_norm, md->hd * 4));
+ janas_g_push_addr(pq.rope, ROPE);
+ janas_g_push_addr(pq.kc, janas_gt_addr_of(g, ly->kc, cache));
+ janas_g_push_addr(pq.vc, janas_gt_addr_of(g, ly->vc, cache));
+ janas_g_push_addr(pq.ks, janas_gt_addr_of(g, ly->ks, cache / md->hd * 4));
+ janas_g_push_addr(pq.vs, janas_gt_addr_of(g, ly->vs, cache / md->hd * 4));
+ janas_gt_bind(g, bound, t->p_qk);
+ janas_gt_push(g, &pq, sizeof(pq));
+ g->vkCmdDispatch(g->cb, md->n_head + md->n_kv, n, 1);
+ janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_ROPE);
+ /* the attention: runs of positions per KV head, then joined; token
+ j of the block sees positions 0 .. pos + j, the block's own keys
+ and values written above */
+ struct push_at pa = {.n_head = md->n_head,
+ .n_kv = md->n_kv,
+ .hd = md->hd,
+ .cap = md->cap,
+ .nch = t->rec_nch,
+ .scale = md->attn_scale,
+ .qs = (uint32_t)qs,
+ .ps = (uint32_t)janas_gt_part_tok(t, md, t->rec_nch)};
+ janas_g_push_addr(pa.pos, POS);
+ janas_g_push_addr(pa.q, QKV);
+ janas_g_push_addr(pa.kc, janas_gt_addr_of(g, ly->kc, cache));
+ janas_g_push_addr(pa.vc, janas_gt_addr_of(g, ly->vc, cache));
+ janas_g_push_addr(pa.ks, janas_gt_addr_of(g, ly->ks, cache / md->hd * 4));
+ janas_g_push_addr(pa.vs, janas_gt_addr_of(g, ly->vs, cache / md->hd * 4));
+ janas_g_push_addr(pa.part, B + t->o_part);
+ janas_gt_bind(g, bound, t->p_at);
+ janas_gt_push(g, &pa, sizeof(pa));
+ g->vkCmdDispatch(g->cb, md->n_kv * t->rec_nch, n, 1);
+ janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_ATTN);
+ /* the runs joined and the output quantized for wo, a workgroup a
+ block of 256 */
+ struct push_am pm = {.hd = md->hd,
+ .nch = t->rec_nch,
+ .ps = (uint32_t)janas_gt_part_tok(t, md, t->rec_nch),
+ .gs = qd};
+ janas_g_push_addr(pm.gate, md->gated_q ? B + t->o_gate : 0);
+ janas_g_push_addr(pm.part, B + t->o_part);
+ janas_g_push_addr(pm.q256, B + t->o_q256);
+ janas_g_push_addr(pm.q32, B + t->o_q32);
+ janas_g_push_addr(pm.pos, POS);
+ janas_gt_bind(g, bound, t->p_am);
+ janas_gt_push(g, &pm, sizeof(pm));
+ g->vkCmdDispatch(g->cb, qd / JANAS_QK, n, 1);
+ janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_MERGE);
+ /* the output projection */
+ if (janas_gt_rec_product(g, t, bound, &ly->wo, 0, YWO, n, 0) != 0)
+ return -1;
+ janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_WO);
+ return 0;
+}
+
+/* x (n vectors of d floats) quantized as it is, into the q256 and q32
+ layouts at q256 and q32: norm_quant.comp with no norm. */
+static void rec_quant(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkPipeline *bound, VkDeviceAddress x,
+ VkDeviceAddress q256, VkDeviceAddress q32, uint32_t d,
+ uint32_t n)
+{
+ struct push_nq pc = {.d = d};
+ janas_g_push_addr(pc.x, x);
+ janas_g_push_addr(pc.q256, q256);
+ janas_g_push_addr(pc.q32, q32);
+ janas_gt_bind(g, bound, t->p_nq);
+ janas_gt_push(g, &pc, sizeof(pc));
+ g->vkCmdDispatch(g->cb, d / JANAS_QK, n, 1);
+ janas_g_compute_barrier(g);
+}
+
+/* A feed-forward on the block normalized in q256: gate and up (the n
+ tokens' gates, then their ups), SiLU(gate) up quantized, down into out
+ (a dense layer's, or a mixture's shared expert). A down matrix in blocks
+ of 32 (a shared expert's Q8_0) takes the activation as floats quantized
+ into both layouts, the experts' shader making only the one of 256. */
+int janas_gt_rec_ffn(struct janas_gpu *g, struct janas_gpu_tok *t,
+ VkPipeline *bound, const struct janas_matvec_task *gate,
+ const struct janas_matvec_task *up,
+ const struct janas_matvec_task *down, uint32_t n,
+ VkDeviceAddress out)
+{
+ VkDeviceAddress B = t->buf.addr, GU = B + t->o_gu, H = B + t->o_h, XA = H;
+ VkDeviceAddress UP = GU + (size_t)n * gate->rows * 4;
+ if (janas_gt_rec_product(g, t, bound, gate, 0, GU, n, 0) != 0 ||
+ janas_gt_rec_product(g, t, bound, up, 0, UP, n, 0) != 0)
+ return -1;
+ janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_GATEUP);
+ if (janas_g_x_in_32(down->type)) {
+ struct push_sm ps = {.n = n * gate->rows};
+ janas_g_push_addr(ps.g, GU);
+ janas_g_push_addr(ps.u, UP);
+ janas_g_push_addr(ps.h, B + t->o_hf);
+ janas_gt_bind(g, bound, t->p_sm);
+ janas_gt_push(g, &ps, sizeof(ps));
+ g->vkCmdDispatch(g->cb, (ps.n + 255) / 256, 1, 1);
+ janas_g_compute_barrier(g);
+ rec_quant(g, t, bound, B + t->o_hf, H, B + t->o_h32, gate->rows, n);
+ XA = B + t->o_h32;
+ } else {
+ struct push_ac ac = {.blocks = n * gate->rows / JANAS_QK};
+ janas_g_push_addr(ac.g, GU);
+ janas_g_push_addr(ac.u, UP);
+ janas_g_push_addr(ac.x, H);
+ janas_gt_bind(g, bound, g->pipea);
+ janas_gt_push(g, &ac, sizeof(ac));
+ g->vkCmdDispatch(g->cb, n * gate->rows / JANAS_QK, 1, 1);
+ janas_g_compute_barrier(g);
+ }
+ janas_gt_stamp(g, t, PH_ACT);
+ if (janas_g_record_task(g, bound,
+ &(struct janas_matvec_task){
+ .type = down->type,
+ .w = down->w,
+ .plane = {down->plane[0], down->plane[1]},
+ .rows = down->rows,
+ .cols = down->cols,
+ .n_vec = n},
+ down->rows, XA, out, down->rows) != 0)
+ return -1;
+ janas_g_compute_barrier(g);
+ janas_gt_stamp(g, t, PH_DOWN);
+ return 0;
+}
+
+#endif
diff --git a/src/llm/model_gpu.c b/src/llm/model_gpu.c
index 661ccd2..639b161 100644
--- a/src/llm/model_gpu.c
+++ b/src/llm/model_gpu.c
@@ -8,7 +8,9 @@
* For the dense attention models of qwen3's shape, and qwen3.5's (Gated
* DeltaNet layers between them) for a prompt's blocks only, on a GPU that
* reads the host's memory in place, with the feed-forward weights (the
- * experts' arena) on it already.
+ * experts' arena) on it already; their mixtures too (qwen3moe, qwen35moe),
+ * a layer a submission, the router's choice sorted and the experts asked
+ * of the cache on the CPU between two of them.
*/
#include "model.h"
@@ -36,8 +38,47 @@ static const char *not_for_gpu(const struct janas_llm_model *m)
m->a->sandwich || m->a->gelu || m->kv16 || m->softcap > 0.0f ||
m->ple_dim)
return "an architecture the token's shaders do not take yet";
- if (m->n_expert != 1 || !m->cache)
- return "not a dense model";
+ if (!m->cache)
+ return "no feed-forward weights";
+ if (m->n_expert > 1) {
+ /* by itself where the cache holds half the experts or more - the
+ memory the machine has: measured against the experts shared with
+ the CPU (gpu.c experts_id), a prompt of 1,024 tokens, 10 Oct
+ 2026: Qwen3-30B-A3B, all in the cache, even (130.6 and 130.0
+ tokens/s, three runs each); Qwen3.6-35B-A3B at four bits, 59% of
+ them, 85.6 -> 101.9 (the next layer's read ahead: without, 86.6
+ -> 87.6). A smaller cache not measured yet. JANAS_GPU_MOE=1 takes any
+ mixture, 0 none */
+ const char *e = getenv("JANAS_GPU_MOE");
+ uint64_t all = (uint64_t)m->n_layer * m->n_expert,
+ held = janas_expert_cache_slots(m->cache);
+ if (e && atoi(e) <= 0)
+ return "a mixture, JANAS_GPU_MOE=0";
+ if (!e && held * 2 < all) {
+ static char why[128];
+ snprintf(why, sizeof why,
+ "a mixture whose cache holds %.0f%% of its experts, "
+ "under half (JANAS_GPU_MOE=1 takes it)",
+ 100.0 * (double)held / (double)all);
+ return why;
+ }
+ /* nor experts whose down matrices are plain Q6_K (q6k_mmid.comp):
+ Qwen3-Coder-30B-A3B read a prompt of 1,024 tokens at 116.9
+ tokens/s instead of 131.5 (10 Oct 2026) */
+ if (!e && m->j.layers[0].m[JANAS_JNS_DOWN].type == JANAS_Q6_K)
+ return "a mixture whose experts' down matrices are plain Q6_K, "
+ "slower whole on the GPU (JANAS_GPU_MOE=1 takes it)";
+ /* a mixture: the router's choice whole (no expert left out for
+ not being in memory), no scale of its own per expert, a layer's
+ experts all in the cache at once */
+ if (m->miss_skip > 0)
+ return "experts left out when not in memory";
+ if (janas_expert_cache_slots(m->cache) < m->n_expert)
+ return "an expert cache smaller than a layer's experts";
+ for (uint32_t l = 0; l < m->n_layer; l++)
+ if (m->layers[l].exp_scale || !m->layers[l].router16)
+ return "a mixture the token's shaders do not take yet";
+ }
if (m->arena_gpu != 1 || m->arena_stale)
return "the feed-forward weights are not on the GPU";
for (uint32_t l = 0; l < m->n_layer; l++) {
@@ -200,6 +241,47 @@ static int repack(struct janas_llm_model *m, int tiles)
return 0;
}
+/* A mixture's experts for the GPU (gpu_token.h fetch): read into the cache
+ if they are not in it. */
+static int gtok_fetch(void *ctx, uint32_t layer, const uint32_t *ids, size_t n,
+ const uint8_t **slots)
+{
+ struct janas_llm_model *m = ctx;
+ if (n > janas_expert_cache_slots(m->cache))
+ return -1;
+ return janas_expert_cache_fetch(m->cache, layer, ids, n, slots);
+}
+
+/* ... and the router's choice, for those who watch it and for the counts
+ that warm the cache, as model_ffn.c gives them (an expert counted once a
+ block) */
+static void gtok_routed(void *ctx, uint32_t layer, uint32_t n, uint32_t k,
+ const uint32_t *ids)
+{
+ struct janas_llm_model *m = ctx;
+ if (m->route_fn)
+ m->route_fn(m->route_ctx, layer, n, k, ids);
+ if (m->use_count) {
+ uint8_t seen[4096] = {0}; /* n_expert <= 4096, checked at load */
+ for (uint32_t p = 0; p < n * k; p++)
+ if (!seen[ids[p]]) {
+ seen[ids[p]] = 1;
+ m->use_count[(size_t)layer * m->n_expert + ids[p]]++;
+ }
+ }
+}
+
+/* ... and the experts of a layer read ahead, all of them (a prompt's block
+ asks for nearly all), where the cache can read ahead */
+static void gtok_prefetch(void *ctx, uint32_t layer)
+{
+ struct janas_llm_model *m = ctx;
+ uint32_t ids[4096]; /* n_expert <= 4096, checked at load */
+ for (uint32_t e = 0; e < m->n_expert; e++)
+ ids[e] = e;
+ janas_expert_cache_prefetch(m->cache, layer, ids, m->n_expert, m->n_expert);
+}
+
/* The layers described for the GPU, the KV cache imported: 0, or -1. */
static int build(struct janas_llm_model *m, char *err, size_t len)
{
@@ -221,14 +303,16 @@ static int build(struct janas_llm_model *m, char *err, size_t len)
snprintf(err, len, "out of memory");
return -1;
}
- uint32_t ff = 0;
+ uint32_t ff = 0, eff = 0;
+ int moe = m->n_expert > 1;
for (uint32_t l = 0; l < m->n_layer; l++) {
const struct layer *ly = &m->layers[l];
const struct janas_jns_layer *jl = &m->j.layers[l];
struct janas_gpu_tok_layer *g = &m->gtok_layers[l];
uint32_t e0 = 0;
- const uint8_t *slot;
- if (janas_expert_cache_fetch(m->cache, l, &e0, 1, &slot) != 0) {
+ const uint8_t *slot = NULL;
+ if (moe) { /* the experts' slots are asked block by block */
+ } else if (janas_expert_cache_fetch(m->cache, l, &e0, 1, &slot) != 0) {
snprintf(err, len, "the feed-forward of layer %u unreadable", l);
return -1;
}
@@ -256,19 +340,49 @@ static int build(struct janas_llm_model *m, char *err, size_t len)
}
for (int p = 0; p < 3; p++) {
const struct janas_jns_matrix *mx = &jl->m[p];
+ /* a mixture's: the type and shape, the weights in each slot at
+ offset */
struct janas_matvec_task t = {.type = (int)mx->type,
- .w = slot + mx->offset,
+ .w = moe ? NULL : slot + mx->offset,
.rows = mx->rows,
.cols = mx->cols};
+ g->off[p] = mx->offset;
if (p == 2) /* the down matrix's planes the cache holds */
for (int q = 0; q < m->exp_level - 1; q++)
- if (jl->plane[q].type)
- t.plane[q] = slot + jl->plane[q].offset;
+ if (jl->plane[q].type) {
+ if (moe)
+ g->poff[q] = jl->plane[q].offset;
+ else
+ t.plane[q] = slot + jl->plane[q].offset;
+ }
*(p == 0 ? &g->gate : p == 1 ? &g->up : &g->down) = t;
}
- if (l == 0)
- ff = g->gate.rows;
- if (g->gate.rows != ff || g->up.rows != ff || g->down.cols != ff) {
+ if (moe) {
+ g->router16 = ly->router16;
+ g->sh_gate = ly->sh_gate;
+ if (ly->sh_w[0]) {
+ struct janas_matvec_task *s[3] = {&g->sh_gate_w, &g->sh_up,
+ &g->sh_down};
+ for (int p = 0; p < 3; p++)
+ *s[p] = (struct janas_matvec_task){
+ .type = (int)ly->sh_mx[p].type,
+ .w = ly->sh_w[p] + ly->sh_mx[p].offset,
+ .rows = ly->sh_mx[p].rows,
+ .cols = ly->sh_mx[p].cols};
+ }
+ }
+ /* a mixture: its experts' width, and its shared expert's (the
+ feed-forward the token's buffers are made for) */
+ uint32_t lff =
+ moe && g->sh_gate_w.type ? g->sh_gate_w.rows : g->gate.rows;
+ if (l == 0) {
+ ff = lff;
+ eff = g->gate.rows;
+ }
+ if (lff != ff || g->gate.rows != eff || g->up.rows != eff ||
+ g->down.cols != eff ||
+ (moe && g->sh_gate_w.type &&
+ (g->sh_up.rows != ff || g->sh_down.cols != ff))) {
snprintf(err, len, "feed-forwards of different widths");
return -1;
}
@@ -311,10 +425,20 @@ static int build(struct janas_llm_model *m, char *err, size_t len)
.d_inner = m->d_inner,
.vmap_mod = m->vmap_mod,
.ssm_state = m->ssm_buf,
- .conv_state = m->conv_buf};
+ .conv_state = m->conv_buf,
+ .n_expert = moe ? m->n_expert : 0,
+ .k = moe ? m->k_use : 0,
+ .eff = eff,
+ .fetch = moe ? gtok_fetch : NULL,
+ .routed = moe ? gtok_routed : NULL,
+ .prefetch = moe && janas_expert_cache_can_prefetch(m->cache)
+ ? gtok_prefetch
+ : NULL,
+ .ctx = m};
free(m->gblk_layers);
m->gblk_layers = NULL;
- if (getenv("JANAS_GPU_REPACK") && atoi(getenv("JANAS_GPU_REPACK")) > 0) {
+ if (!moe && getenv("JANAS_GPU_REPACK") &&
+ atoi(getenv("JANAS_GPU_REPACK")) > 0) {
/* the blocks keep the weights as they are: the copy's shaders take
a single vector */
m->gblk_layers = malloc(m->n_layer * sizeof(*m->gblk_layers));
@@ -370,16 +494,21 @@ int janas_m_gpu_token(struct janas_llm_model *m, uint32_t pos, uint32_t n,
/* the arena may reach the GPU later: wait for it, say nothing */
if (m->gtok_state == 0 && m->arena_gpu == 0 && m->gpu && !m->gpu_off)
return -1;
- if (m->gtok_state == 0 && tok) /* asked for, not by itself */
+ /* asked for, not by itself; or JANAS_GPU_VERBOSE */
+ if (m->gtok_state == 0 && (tok || getenv("JANAS_GPU_VERBOSE")))
fprintf(stderr, "janas: no whole token on the GPU: %s\n", why);
m->gtok_state = -1;
return -1;
}
+ /* a dense model's feed-forward is where the cache put it when built;
+ a mixture asks for its experts' slots block by block */
if (m->gtok_state == 0 ||
- janas_expert_cache_loads(m->cache) != m->gtok_loads) {
+ (m->n_expert == 1 &&
+ janas_expert_cache_loads(m->cache) != m->gtok_loads) ||
+ (m->n_expert > 1 && m->gtok_md.k != m->k_use)) {
char err[160];
if (build(m, err, sizeof(err)) != 0) {
- if (tok)
+ if (tok || getenv("JANAS_GPU_VERBOSE"))
fprintf(stderr, "janas: no whole token on the GPU: %s\n", err);
m->gtok_state = -1;
return -1;
diff --git a/src/llm/shaders/moe_combine.comp b/src/llm/shaders/moe_combine.comp
new file mode 100644
index 0000000..1877b29
--- /dev/null
+++ b/src/llm/shaders/moe_combine.comp
@@ -0,0 +1,34 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// A mixture's output for each token (gpu_token.c): the weighted sum of its
+// k experts' outputs - pair j k + i weight pw, its row inv in dout, dm
+// floats a row - plus, with a shared expert, its output sh times its
+// weight shw. Into y, dm floats a token, which the next norm adds to the
+// residual. A workgroup a block of 256 values of a token. NOT bit for bit
+// with the CPU: the residual added once, after the sum.
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 256) in;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer F { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer FO { float v[]; };
+
+layout(push_constant) uniform P { uvec2 dout, pw, inv, sh, shw, y; uint dm, k, has_sh; } p;
+
+void main()
+{
+ uint j = gl_WorkGroupID.y, d = gl_WorkGroupID.x * 256u + gl_LocalInvocationID.x;
+ F DO = F(p.dout), PW = F(p.pw);
+ U1 INV = U1(p.inv);
+ float s = 0.0;
+ for (uint i = 0u; i < p.k; i++) {
+ uint q = j * p.k + i;
+ s += PW.v[q] * DO.v[INV.v[q] * p.dm + d];
+ }
+ if (p.has_sh != 0u)
+ s += F(p.shw).v[j] * F(p.sh).v[j * p.dm + d];
+ FO(p.y).v[j * p.dm + d] = s;
+}
diff --git a/src/llm/shaders/moe_gather.comp b/src/llm/shaders/moe_gather.comp
new file mode 100644
index 0000000..ac865a4
--- /dev/null
+++ b/src/llm/shaders/moe_gather.comp
@@ -0,0 +1,26 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// A mixture's activations in the experts' order (gpu_token.c): row g of
+// dst is the quantized vector of token tok[g] of src, nb blocks of 320
+// bytes a vector (the product shaders' layout). A workgroup a row.
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+
+layout(buffer_reference, std430, buffer_reference_align = 16) readonly buffer U4 { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 16) writeonly buffer U4O { uvec4 v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer U1 { uint v[]; };
+
+layout(push_constant) uniform P { uvec2 src, dst, tok; uint nb; } p;
+
+void main()
+{
+ uint g = gl_WorkGroupID.x, words = p.nb * 20u; // 320 bytes = 20 uvec4
+ uint t = U1(p.tok).v[g];
+ U4 S = U4(p.src);
+ U4O D = U4O(p.dst);
+ for (uint i = gl_LocalInvocationID.x; i < words; i += 64u)
+ D.v[g * words + i] = S.v[t * words + i];
+}
diff --git a/src/llm/shaders/moe_topk.comp b/src/llm/shaders/moe_topk.comp
new file mode 100644
index 0000000..9e59d04
--- /dev/null
+++ b/src/llm/shaders/moe_topk.comp
@@ -0,0 +1,70 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// A mixture's routing on the GPU for a prompt's block (gpu_token.c), as
+// model_ffn.c route_tok: per token, the softmax of its ne router logits,
+// the k largest (the first of equals), each weight divided by the sum of
+// the k; logit ne, the shared expert's gate (if sh), through a sigmoid, 1
+// without one. One invocation a token. NOT bit for bit with the CPU: the
+// GPU's exp, the router's sums in another order.
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 64) in;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer F { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer FO { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer UO { uint v[]; };
+
+// r: the logits, rs floats a token; pe, pw: expert and weight of pair
+// j k + i; shw: the shared expert's weight of each token
+layout(push_constant) uniform P { uvec2 r, pe, pw, shw; uint ne, rs, k, n, sh; } p;
+
+const uint MAXK = 16u, MAXW = 16u; // k <= 16, ne <= 512
+
+void main()
+{
+ uint j = gl_GlobalInvocationID.x;
+ if (j >= p.n)
+ return;
+ F R = F(p.r);
+ uint base = j * p.rs;
+ float mx = R.v[base];
+ for (uint e = 1u; e < p.ne; e++)
+ mx = max(mx, R.v[base + e]);
+ float sum = 0.0;
+ for (uint e = 0u; e < p.ne; e++)
+ sum += exp(R.v[base + e] - mx);
+ uint taken[MAXW];
+ for (uint i = 0u; i < MAXW; i++)
+ taken[i] = 0u;
+ uint ids[MAXK];
+ float w[MAXK], wsum = 0.0;
+ for (uint i = 0u; i < p.k; i++) {
+ uint best = 0u;
+ float bv = 0.0;
+ bool any = false;
+ for (uint e = 0u; e < p.ne; e++) {
+ if ((taken[e / 32u] & (1u << (e % 32u))) != 0u)
+ continue;
+ float v = R.v[base + e];
+ if (!any || v > bv) {
+ bv = v;
+ best = e;
+ any = true;
+ }
+ }
+ taken[best / 32u] |= 1u << (best % 32u);
+ ids[i] = best;
+ w[i] = exp(bv - mx) / sum;
+ wsum += w[i];
+ }
+ UO PE = UO(p.pe);
+ FO PW = FO(p.pw);
+ for (uint i = 0u; i < p.k; i++) {
+ PE.v[j * p.k + i] = ids[i];
+ PW.v[j * p.k + i] = w[i] / wsum;
+ }
+ FO SHW = FO(p.shw);
+ SHW.v[j] = p.sh != 0u ? 1.0 / (1.0 + exp(-R.v[base + p.ne])) : 1.0;
+}
diff --git a/src/llm/shaders/q6kp_mmid.comp b/src/llm/shaders/q6kp_mmid.comp
index 6df64ed..1c30177 100644
--- a/src/llm/shaders/q6kp_mmid.comp
+++ b/src/llm/shaders/q6kp_mmid.comp
@@ -2,9 +2,11 @@
Copyright (C) 2026 Maurizio Cammalleri */
#version 450
// The fast prompt for a mixture's experts whose down matrices are Q6_K in
-// planes at level 3: as q4k_mmid.comp, the weights staged as q6kp_mmq.comp
-// does (the table's third uvec4 the two bare planes). NOT bit for bit with
-// the CPU.
+// planes: as q4k_mmid.comp, the weights staged as q6kp_mmq.comp does (the
+// table's third uvec4 the two bare planes). At level 3 both planes; at 2
+// (p0 0) and 1 (p1 0 too) the missing bits zero and the centre of the
+// values they stand for in place of 32 (q6kp_matvec.comp's c / 2: 30.5,
+// 24.5). NOT bit for bit with the CPU.
#extension GL_EXT_control_flow_attributes : require
#extension GL_EXT_integer_dot_product : require
#extension GL_EXT_buffer_reference : require
@@ -47,6 +49,8 @@ void main()
uvec4 t2 = T.v[3u * e + 2u];
U4 X = U4(t0.zw);
U1 W = U1(t0.xy), P1 = U1(t2.xy), P0 = U1(t2.zw);
+ bool h1 = t2.x != 0u || t2.y != 0u, h0 = t2.z != 0u || t2.w != 0u;
+ float cen = h0 ? 32.0 : h1 ? 30.5 : 24.5;
F Y = F(t1.xy);
uint id = gl_LocalInvocationID.x;
uint rq = (id % 32u) * 2u, vq = (id / 32u) * 4u;
@@ -66,7 +70,8 @@ void main()
uint pw = (r * p.nb + b) * 16u;
[[unroll]] for (uint u = 0; u < 2u; u++) {
uint i = 8u * n + 2u * iqs + u;
- uint h = hword(W, off, i), a1 = P1.v[pw + i], a0 = P0.v[pw + i];
+ uint h = hword(W, off, i), a1 = h1 ? P1.v[pw + i] : 0u,
+ a0 = h0 ? P0.v[pw + i] : 0u;
[[unroll]] for (uint k = 0; k < KS; k++) {
uint hsh = 2u * k;
sa[k * BM + rl + l].qs[2u * iqs + u] =
@@ -99,8 +104,8 @@ void main()
if (iqs == 0u) {
uvec4 bs = X.v[xo + 16u + j / 4u];
uint bw = j % 4u == 0u ? bs.x : j % 4u == 1u ? bs.y : j % 4u == 2u ? bs.z : bs.w;
- sb[k * BN + c].d8s = vec2(32.0 * float(bitfieldExtract(int(bw), 0, 16)),
- 32.0 * float(bitfieldExtract(int(bw), 16, 16)));
+ sb[k * BN + c].d8s = vec2(cen * float(bitfieldExtract(int(bw), 0, 16)),
+ cen * float(bitfieldExtract(int(bw), 16, 16)));
sb[k * BN + c].d8 = uintBitsToFloat(X.v[xo + 18u].x);
}
}
diff --git a/src/llm/shaders/silu_mul.comp b/src/llm/shaders/silu_mul.comp
new file mode 100644
index 0000000..82ada65
--- /dev/null
+++ b/src/llm/shaders/silu_mul.comp
@@ -0,0 +1,25 @@
+/* SPDX-License-Identifier: GPL-3.0-or-later
+ Copyright (C) 2026 Maurizio Cammalleri */
+#version 450
+// h = SiLU(gate) * up as floats, n values (gpu_token.c: a shared expert
+// whose down matrix is in blocks of 32, quantized afterwards by
+// norm_quant.comp into both layouts). The GPU's exp: NOT bit for bit with
+// the CPU.
+#extension GL_EXT_buffer_reference : require
+#extension GL_EXT_buffer_reference_uvec2 : require
+
+layout(local_size_x = 256) in;
+
+layout(buffer_reference, std430, buffer_reference_align = 4) readonly buffer F { float v[]; };
+layout(buffer_reference, std430, buffer_reference_align = 4) writeonly buffer FO { float v[]; };
+
+layout(push_constant) uniform P { uvec2 g, u, h; uint n; } p;
+
+void main()
+{
+ uint i = gl_GlobalInvocationID.x;
+ if (i >= p.n)
+ return;
+ float gv = F(p.g).v[i];
+ FO(p.h).v[i] = gv / (1.0 + exp(-gv)) * F(p.u).v[i];
+}
diff --git a/src/llm/tuner.c b/src/llm/tuner.c
index 7157b24..f638c14 100644
--- a/src/llm/tuner.c
+++ b/src/llm/tuner.c
@@ -18,6 +18,19 @@
#define RETRY_EVERY 128 /* passes between tries of an alternative, at first */
#define RETRY_MAX 1024 /* at most, after tries that changed nothing */
#define RESETTLE_WINS 3 /* tries in a row won by other threads: theirs */
+#define DECISIVE 0.5 /* ... or one try this much faster than the choice */
+#define RETRY_WON 16 /* passes to the next try after one that won */
+
+/* JANAS_TUNE_TRACE=1: the threads settled, every try of an alternative
+ after that (against the choice's mean) and the threads moved, on
+ stderr: what a long chat does, which the tests only simulate */
+static int tracing(void)
+{
+ static int on = -1;
+ if (on < 0)
+ on = getenv("JANAS_TUNE_TRACE") && atoi(getenv("JANAS_TUNE_TRACE")) > 0;
+ return on;
+}
int janas_tune_class(uint32_t n_tokens)
{
@@ -84,6 +97,9 @@ static void settle_threads(struct janas_tuner *t, int cls)
if (usable(t, cls, i) && t->cls[cls].tried[i] < TRIES)
return;
t->cls[cls].threads = t->cand[janas_tuner_best(t, cls)].threads;
+ if (tracing())
+ fprintf(stderr, "tune class %d pass %u: threads settled on %d\n", cls,
+ t->cls[cls].passes, t->cls[cls].threads);
}
void janas_tuner_force(struct janas_tuner *t, int cand)
@@ -178,31 +194,53 @@ void janas_tuner_record(struct janas_tuner *t, int cls, int cand,
{
if ((t->fixed && t->forced < 0) || t->cls[cls].passes <= WARM_PASSES)
return;
- /* a try that beats the choice clearly: tries often again, until the
- averages settle which is better (one pass alone may be luck) */
int rb = t->cls[cls].retry_best;
if (rb >= 0 && cand == t->cls[cls].retry_cand) {
- if (sec_per_token < t->cls[cls].cost[rb] * MARGIN) {
+ int th = t->cls[cls].threads, other = th && t->cand[cand].threads != th,
+ won = sec_per_token < t->cls[cls].cost[rb] * MARGIN;
+ /*
+ * A try that beats the choice clearly: the next one soon, until the
+ * averages settle which is better (one pass alone may be luck).
+ * Other threads, faster in try after try - whichever of them, as
+ * the tries take the candidates in turn - or one twice as fast:
+ * theirs from now on. The threads are settled by the first tries,
+ * and the machine can turn their verdict round: a laptop that
+ * warms up (Qwen3.5-2B settled on 20 threads for its tokens, which
+ * then took 28.1 ms against 18.9 on 12), or another program on the
+ * efficiency cores - 20 threads took 680-850 ms a token against 22
+ * on 6 or 12, and counted per candidate, the 6 and 12 taking the
+ * tries in turn, the wins moved the threads only after 645 tokens,
+ * some 450 s (10 Oct 2026). Their mean starts again from this
+ * pass: the old one was made at another time.
+ */
+ if (won) {
t->cls[cls].retry_gap = RETRY_EVERY;
- t->cls[cls].retry_at = t->cls[cls].passes + RETRY_EVERY;
+ t->cls[cls].retry_at = t->cls[cls].passes + RETRY_WON;
t->cls[cls].retry_best = -1;
- t->cls[cls].wins[cand]++;
- } else {
- t->cls[cls].wins[cand] = 0;
}
- /*
- * Other threads, faster in try after try: theirs from now on. The
- * threads are settled by the first tries, and a laptop that warms
- * up turns the comparison round - Qwen3.5-2B settled on 20 threads
- * for its tokens, which then took 28.1 ms against 18.9 on 12 (10
- * Oct 2026). Their mean starts again from this pass: the old one
- * was made at another time.
- */
- int th = t->cls[cls].threads;
- if (th && t->cand[cand].threads != th &&
- t->cls[cls].wins[cand] >= RESETTLE_WINS) {
+ t->cls[cls].wins[cand] = won ? t->cls[cls].wins[cand] + 1 : 0;
+ if (other)
+ t->cls[cls].other_wins = won ? t->cls[cls].other_wins + 1 : 0;
+ if (tracing())
+ fprintf(stderr,
+ "tune class %d pass %u: try %d threads%s %.2f ms against "
+ "%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" : "",
+ 1e3 * t->cls[cls].cost[rb], won ? "won" : "lost",
+ (unsigned)t->cls[cls].other_wins);
+ if (other && won &&
+ (t->cls[cls].wins[cand] >= RESETTLE_WINS ||
+ t->cls[cls].other_wins >= RESETTLE_WINS ||
+ sec_per_token < t->cls[cls].cost[rb] * DECISIVE)) {
+ if (tracing())
+ fprintf(stderr, "tune class %d pass %u: threads %d -> %d\n",
+ cls, t->cls[cls].passes, th, t->cand[cand].threads);
t->cls[cls].threads = t->cand[cand].threads;
- t->cls[cls].wins[cand] = 0;
+ memset(t->cls[cls].wins, 0, sizeof(t->cls[cls].wins));
+ t->cls[cls].other_wins = 0;
t->cls[cls].cost[cand] = sec_per_token;
t->cls[cls].tried[cand] = TRIES;
t->cls[cls].last[cand] = t->cls[cls].passes;
@@ -211,6 +249,21 @@ void janas_tuner_record(struct janas_tuner *t, int cls, int cand,
}
double *c = &t->cls[cls].cost[cand];
uint32_t n = t->cls[cls].tried[cand];
+ /* the choice suddenly twice as slow as its mean (another program took
+ its cores): the next try at once, not at its turn - the 128 passes
+ before the first one cost some 140 s of a 3,000-token chat at 760
+ ms a token, against 22 on 6 threads (10 Oct 2026) */
+ if (rb < 0 && n >= TRIES && sec_per_token > 2 * *c &&
+ t->cls[cls].retry_at > t->cls[cls].passes) {
+ t->cls[cls].retry_at = t->cls[cls].passes;
+ if (tracing())
+ fprintf(stderr,
+ "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,
+ 1e3 * *c);
+ }
/* a plain mean over the first tries, then a moving average */
*c = n == 0 ? sec_per_token
: n < TRIES ? (*c * n + sec_per_token) / (n + 1)
diff --git a/src/llm/tuner.h b/src/llm/tuner.h
index d87af62..c368b41 100644
--- a/src/llm/tuner.h
+++ b/src/llm/tuner.h
@@ -9,12 +9,12 @@
* each candidate a few times, keeps the fastest, and now and then tries the
* others again to follow the machine's state (heat, power source). The
* number of threads is settled by the first tries, and moves only when
- * other threads win several tries in a row, each a fresh pass against the
- * choice's recent mean: a pass costs more as the context grows, so a
- * candidate's old mean, made at short context, must not decide - which
- * moved chats onto fewer cores than they could use - but a laptop that
- * warms up can turn the first tries' verdict round. The choices are saved
- * per machine and model, so the next start begins from them.
+ * other threads win several tries in a row, or one by half or more, each
+ * a fresh pass against the choice's recent mean: a pass costs more as the
+ * context grows, so a candidate's old mean, made at short context, must not
+ * decide - which moved chats onto fewer cores than they could use - but a
+ * laptop that warms up can turn the first tries' verdict round. The choices are
+ * saved per machine and model, so the next start begins from them.
*/
#ifndef JANAS_LLM_TUNER_H
#define JANAS_LLM_TUNER_H
@@ -47,9 +47,10 @@ struct janas_tuner {
double cost[JANAS_TUNE_MAX_CANDS]; /* seconds per token, averaged */
uint32_t tried[JANAS_TUNE_MAX_CANDS];
uint32_t last[JANAS_TUNE_MAX_CANDS]; /* pass of the last try */
- /* tries in a row each candidate won against the choice (one with
- other threads takes the threads over at RESETTLE_WINS) */
- uint8_t wins[JANAS_TUNE_MAX_CANDS];
+ /* tries in a row won against the choice by each candidate, and by
+ any with other threads (their threads taken over when either
+ reaches RESETTLE_WINS, or at once by a try twice as fast) */
+ uint8_t wins[JANAS_TUNE_MAX_CANDS], other_wins;
uint32_t passes;
int def; /* the default candidate */
/* the next try of an alternative, the passes until the one after,
diff --git a/src/services/README.md b/src/services/README.md
index 4507979..861be97 100644
--- a/src/services/README.md
+++ b/src/services/README.md
@@ -28,7 +28,7 @@ What every service does the same way:
## In janas-chat
-`janas-chat` starts by itself the services it finds beside it (in the same directory as the program) and runs without asking the calls of the tools that only read. A tool that changes something - `janas-git`'s commit, pull, push, switch - says so (MCP's `readOnlyHint` false), and its call is shown whole and asked of you every time, with `--mcp-auto` too; on a pipe it is not run. Their tools are not written into the system message: it holds a catalog, a line a service, and the model opens a service when a question needs it, getting its instructions and tools then (`--all-tools` writes them all at the start instead). A call shows as a dimmed line. Nothing to configure, nothing to name: ask your question.
+`janas-chat` starts by itself the services it finds in `services/` beside it (the binary package) or beside it (in the same directory as the program, as the build leaves them) and runs without asking the calls of the tools that only read. A tool that changes something - `janas-git`'s commit, pull, push, switch - says so (MCP's `readOnlyHint` false), and its call is shown whole and asked of you every time, with `--mcp-auto` too; on a pipe it is not run. Their tools are not written into the system message: it holds a catalog, a line a service, and the model opens a service when a question needs it, getting its instructions and tools then (`--all-tools` writes them all at the start instead). A call shows as a dimmed line. Nothing to configure, nothing to name: ask your question.
- `/mcp` lists the servers running, the services marked as Janas's.
- `--no-services` starts none of them; `--no-mcp` no server at all.
diff --git a/tests/bench_gemm.c b/tests/bench_gemm.c
index f89ecb6..8086f98 100644
--- a/tests/bench_gemm.c
+++ b/tests/bench_gemm.c
@@ -8,9 +8,11 @@
* all of them, so beyond a few tokens the product is bound by arithmetic and
* the figure of merit is multiply-accumulates per second.
*
- * Usage: bench_gemm [rows cols q4k|q6k|q6kp1|q6kp2|q6kp3 threads]
+ * Usage: bench_gemm [rows cols q4k|q6k|q6kp1|q6kp2|q6kp3 threads [gpu]]
* q6kpL is Q6_K in bit planes with L of the three planes in memory.
* Defaults: 12288 x 2048 Q4_K (Qwen3-Next ssm_in), 12 threads on CPUs 0-11.
+ * gpu: the products of a prompt's blocks on the GPU (the fast prompt's
+ * tiled shaders, *_mmq.comp), 64 to 512 vectors, the weights imported.
*/
#include <stdio.h>
#include <stdlib.h>
@@ -18,6 +20,7 @@
#include <time.h>
#include "common/pool.h"
+#include "llm/gpu.h"
#include "llm/matvec.h"
#include "llm/quant.h"
@@ -44,18 +47,21 @@ int main(int argc, char **argv)
return 2;
}
int threads = argc > 4 ? atoi(argv[4]) : 12;
+ int on_gpu = argc > 5 && !strcmp(argv[5], "gpu");
int cpus[256];
for (int i = 0; i < threads && i < 256; i++)
cpus[i] = i;
struct janas_pool *pool = janas_pool_create(threads, cpus);
janas_pin_current_thread(0);
size_t nb = cols / JANAS_QK, bsz = janas_qtype_block_size(type);
- size_t nvmax = 64;
- uint8_t *w = aligned_alloc(64, rows * nb * bsz);
- size_t plane_bytes = rows * nb * JANAS_Q6KP_PLANE;
+ size_t nvmax = on_gpu ? 512 : 64;
+ /* page-sized and whole pages: what the GPU imports */
+ size_t wbytes = (rows * nb * bsz + 4 + 4095) / 4096 * 4096;
+ uint8_t *w = aligned_alloc(4096, wbytes);
+ size_t plane_bytes = (rows * nb * JANAS_Q6KP_PLANE + 4095) / 4096 * 4096;
uint8_t *pl[2] = {NULL, NULL};
for (int i = 0; i < level - 1; i++) {
- pl[i] = aligned_alloc(64, plane_bytes);
+ pl[i] = aligned_alloc(4096, plane_bytes);
if (!pl[i])
return 1;
for (size_t j = 0; j < plane_bytes; j++)
@@ -67,7 +73,7 @@ int main(int argc, char **argv)
if (!pool || !w || !x || !xf || !y)
return 1;
srand(1);
- for (size_t i = 0; i < rows * nb * bsz; i++)
+ for (size_t i = 0; i < wbytes; i++)
w[i] = (uint8_t)rand();
for (size_t b = 0; b < rows * nb; b++) {
if (type == JANAS_Q6_K_P) {
@@ -86,10 +92,27 @@ int main(int argc, char **argv)
}
double mb =
(rows * nb * bsz + (size_t)(level ? level - 1 : 0) * plane_bytes) / 1e6;
- printf("%s %zu x %zu (%.1f MB), %d threads\n", kind, rows, cols, mb,
- threads);
- size_t nvs[] = {1, 2, 4, 8, 16, 32, 64};
- for (size_t k = 0; k < sizeof(nvs) / sizeof(nvs[0]); k++) {
+ struct janas_gpu *gpu = NULL;
+ if (on_gpu) {
+ char err[200];
+ gpu = janas_gpu_create(err, sizeof(err));
+ if (!gpu || janas_gpu_import(gpu, w, wbytes) != 0 ||
+ (pl[0] && janas_gpu_import(gpu, pl[0], plane_bytes) != 0) ||
+ (pl[1] && janas_gpu_import(gpu, pl[1], plane_bytes) != 0)) {
+ fprintf(stderr, "bench_gemm: no GPU: %s\n", gpu ? "import" : err);
+ return 1;
+ }
+ }
+ printf("%s %zu x %zu (%.1f MB), %s\n", kind, rows, cols, mb,
+ on_gpu ? janas_gpu_name(gpu) : "CPU");
+ if (!on_gpu)
+ printf("%d threads\n", threads);
+ size_t nvs_cpu[] = {1, 2, 4, 8, 16, 32, 64},
+ nvs_gpu[] = {64, 128, 256, 512};
+ size_t *nvs = on_gpu ? nvs_gpu : nvs_cpu,
+ n_nvs = on_gpu ? sizeof(nvs_gpu) / sizeof(*nvs_gpu)
+ : sizeof(nvs_cpu) / sizeof(*nvs_cpu);
+ for (size_t k = 0; k < n_nvs; k++) {
size_t nv = nvs[k];
struct janas_matvec_task t = {.type = type,
.w = w,
@@ -99,17 +122,30 @@ int main(int argc, char **argv)
.rows = rows,
.cols = cols,
.n_vec = nv};
- janas_matvec_q4k_group(pool, &t, 1); /* warm-up */
int reps = (int)(200 / nv) + 5;
- double t0 = now();
- for (int r = 0; r < reps; r++)
+ if (on_gpu) {
+ janas_gpu_matvec_group(gpu, pool, &t, 1); /* warm-up */
+ reps = (int)(2048 / nv) + 5;
+ } else
janas_matvec_q4k_group(pool, &t, 1);
+ double t0 = now();
+ for (int r = 0; r < reps; r++) {
+ if (on_gpu)
+ janas_gpu_matvec_group(gpu, pool, &t, 1);
+ else
+ janas_matvec_q4k_group(pool, &t, 1);
+ }
double dt = (now() - t0) / reps;
+ /* the outputs' sum, to tell two versions of a shader apart */
+ double sum = 0;
+ for (size_t i = 0; i < nv * rows; i++)
+ sum += y[i];
printf("n %2zu: %8.3f ms, %7.3f ms per vector, %6.1f GMAC/s, "
- "%5.1f GB/s\n",
+ "%5.1f GB/s, sum %.17g\n",
nv, dt * 1e3, dt * 1e3 / nv, rows * cols * nv / dt / 1e9,
- mb / 1e3 / dt);
+ mb / 1e3 / dt, sum);
}
+ janas_gpu_destroy(gpu);
janas_pool_destroy(pool);
free(w);
free(pl[0]);
diff --git a/tests/test_get_catalog.c b/tests/test_get_catalog.c
index 5656f9c..ec040d9 100644
--- a/tests/test_get_catalog.c
+++ b/tests/test_get_catalog.c
@@ -66,6 +66,17 @@ int main(void)
digest(models, m->name, m->jns_sha);
digest(models, m->name, m->extra_src_sha);
digest(models, m->name, m->extra_sha);
+ /* the converted file on Hugging Face: the project's own
+ organization, a repository of the model's name, its size */
+ if (m->jns_repo &&
+ (strncmp(m->jns_repo, "prabanta-dev/", 13) != 0 ||
+ strlen(m->jns_repo) < 18 ||
+ strcmp(m->jns_repo + strlen(m->jns_repo) - 4, "-JNS") != 0 ||
+ m->jns_gb <= 0)) {
+ printf("FAIL %s: converted file at %s, %.2f GB\n", m->name,
+ m->jns_repo, m->jns_gb);
+ failures++;
+ }
if (!m->flat_sha || (m->extra != JANAS_EXTRA_NONE && !m->extra_sha)) {
printf("FAIL %s: a fingerprint missing\n", m->name);
failures++;
diff --git a/tests/test_tuner.c b/tests/test_tuner.c
index cd71290..7c8d0d0 100644
--- a/tests/test_tuner.c
+++ b/tests/test_tuner.c
@@ -195,6 +195,37 @@ int main(void)
run(&t, (const double[]){1.0, 0.6, 0.9, 0.9}, 5000);
CHECK(janas_tuner_best(&t, 2) == 1, "warmed up: best %d, want 1",
janas_tuner_best(&t, 2));
+
+ /* another program takes the efficiency cores: 20 threads 30 times
+ slower, 6 and 12 alike - the first try moves the threads (it took
+ 645 passes, the 6 and 12 taking the tries in turn, 10 Oct 2026) */
+ janas_tuner_init(&t, cand, 4, def, 0);
+ janas_tuner_allow_gpu(&t, 0);
+ run(&t, (const double[]){1.0, 1.2, 0.8, 0.9}, 40);
+ int slow = 0, i30;
+ for (i30 = 0; i30 < 2000 && janas_tuner_best(&t, 2) == 2; i30++) {
+ int c = janas_tuner_pick(&t, 2);
+ slow += c == 2;
+ janas_tuner_record(&t, 2, c, (const double[]){0.9, 0.9, 27, 0.9}[c]);
+ }
+ CHECK(janas_tuner_best(&t, 2) != 2 && slow < 5,
+ "20 threads 30 times slower: best %d after %d passes, %d slow",
+ janas_tuner_best(&t, 2), i30, slow);
+
+ /* ... 6 and 12 both a third faster, not twice: their wins count
+ together, the next try soon after one won */
+ janas_tuner_init(&t, cand, 4, def, 0);
+ janas_tuner_allow_gpu(&t, 0);
+ run(&t, (const double[]){1.0, 1.2, 0.8, 0.9}, 40);
+ slow = 0;
+ for (i30 = 0; i30 < 2000 && janas_tuner_best(&t, 2) == 2; i30++) {
+ int c = janas_tuner_pick(&t, 2);
+ slow += c == 2;
+ janas_tuner_record(&t, 2, c, (const double[]){0.6, 0.6, 0.8, 0.9}[c]);
+ }
+ CHECK(janas_tuner_best(&t, 2) != 2 && i30 < 400,
+ "6 and 12 a third faster: best %d after %d passes",
+ janas_tuner_best(&t, 2), i30);
/* forced: always that candidate */
janas_tuner_force(&v, 1);
for (int i = 0; i < 10; i++)