Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port

102 upstream commits. Nine conflicts resolved. Fork side of the merge:
- libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it
  from libavx and libref; the device libraries now each carry it).
- plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table
  regenerated, kTableAbi = 42.

Known before the PR: arch_test (MTP lint and pinned graph hashes for
qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
aneinanderandClaude Opus 5.5 committed 2026-11-18 15:06:17 +01:00
commit 4b70a96378
850 files changed
+157819 -58519

No files matched your search

+728 -203
View File
File diff suppressed because it is too large. Load diff
-141
View File
@@ -1,141 +0,0 @@
# Devlog: the decode floor, and the advice that had to die
The story behind `step_ns_decode_best`, `step_ns_decode_recent`, and why the
dashboard shows them without a verdict. Written 2026-10-18, the day all of it
happened. The user-facing explanation is [GUIDE.md §6.1](GUIDE.md#61-the-dashboard); this is the log of
how we got there, including the parts that failed.
## What shipped
Two engine-measured figures on the decode step tile and on `/stats`: the fastest
window of 32 single-sequence decode steps (`best`) and the most recent one
(`recent`), plus `startup_s` (bringup cost) as a raw field. The estimator is
`rad::DecodeFloor` in `core/sched/metrics.h`. No verdict, no restart advice.
## The chain of failures
Every rung below was built, tested, and — for the first and fourth — deployed
before it was refuted. None of them failed because of a coding mistake; each
failed because a premise nobody had measured turned out to be false.
### 1. A raw min over step brackets latched an artifact (deployed, failed live)
The first floor was a plain minimum over host-side decode-step brackets. On a
live TP2 lane it latched **1.16 ms** against a **15.55 ms** mean on the first
request after bringup — and a min never recovers, so the advisory read
"heavily drifted, restart pays back fast" forever.
The artifact: step timing is host-side, and with pipelining on, the next forward
pass is issued behind the current step's commit. Behind a step with long host
work (a prefill chunk, a KV checkpoint save), the decode pass finishes before
its own bracket opens — the bracket holds readback and commit and no GPU work.
It is a real step advancing a real token, so no token-count guard catches it.
### 2. Two plausible guards, refuted by measurement, not built
- *"The bracket is rare — only steps issued ahead are affected."* Refuted:
`engine_steps_ahead_total == engine_steps_decode_total` (27934 == 27934).
With pipelining, issue-ahead is universal.
- *"A zero-token decode step produces the degenerate bracket."* Refuted in
source: `want <= 0` breaks before the bracket opens. The scheduler cannot
make one.
### 3. The predecessor-phase gate: passed every test, failed live
Hypothesis: a decode step timed behind a *prefill* is the confound; gate the
floor on "previous step was also decode-only." Built, passed **38,820** unit
checks, deployed. Floor still latched: **1.34 ms** vs a 15.70 ms mean.
The confound was predecessor *host work*, not predecessor *phase*. Prefill is
one source of long host work; a KV checkpoint save every 256 tokens is another.
A gate on the phase can see neither. This is the most instructive failure of the
day: a test suite can be green, large, and completely blind, because the fixture
runs steps in microseconds and cannot manufacture the degenerate bracket the
test was about.
### 4. Window averaging: fixed the latch, kept the phantom (deployed, failed live)
Averaging a window of single-row steps before the min dilutes a *lone*
degenerate. But they are not rare — ~1.4% of steps — and a min over hundreds of
windows reliably lands on a degenerate-heavy window. The floor sat ~10% below
the true floor: still unreachable, still phantom drift. Simulation showed this
before deployment; the unit tests, again, could not see it.
The fix that worked: reject candidates at the **step level**, before they enter
a window — a step under half the running mean of accepted steps is a degenerate.
The two populations are ~10x apart (degenerates ~9% of a real step, real steps
~96%), so the threshold is the midpoint of a gap, not a tuned constant. Window
1 is recorded by neither figure: the gate needs a window of accepted samples to
judge one, and recording the un-gated first window latches an unreachable floor.
### 5. The advisory itself: right numbers, wrong premise (deployed, removed live)
With a sound floor, the advisory compared it against the browser's per-poll
statistics. Two instruments, different sample counts — a measured **7.7%**
phantom drift on a lane that had not changed. Fixed by having the engine report
both sides (`recent` added), same stream, same window size.
Then the operator watched the live line: *"best 14.89 · restart pays back in
18m56s"* on an engine minutes from its restart, then *"12 minutes"*. His
reductio — "do I restart every 18 minutes?" — was the falsification, and the
instrument agreed immediately:
- `best` held flat at 14.79 ms all session.
- `recent` moved between 15.2 and 16.5 ms — **3% to 11%** — on a healthy lane.
- It **froze** when the lane went idle and **rose** on a fresh short request:
neither context length nor engine age. Operating load.
The payback formula assumes a restart's improvement is permanent. The measured
"drift" was transient, so acting on it pays the 49 s bringup and re-drifts
within minutes. The premise underneath the whole advisory — *step time ratchets
up with engine age* — had zero observations in a full day of watching. Every
excursion was load.
## Why the failures ended in simplification
Each failure removed an interpretation layer rather than adding a mechanism:
- The raw min said "the fastest bracket is the truth." It wasn't; the window
mean replaced it — one statistic instead of a hoped-for exact instrument.
- The phase gate tried to *classify* steps away. Measurement said the
confounder is unclassifiable from phase; the rejection gate just compares
magnitudes — simpler, and it works because the populations are far apart.
- The advisory tried to *decide* for the operator. The data said the signal it
was deciding on is load noise, and no persistence gate or wider band can fix
a premise that does not exist. So the verdict was deleted, not tuned. The
honest artifact is two numbers and a guide section that says what the gap
between them is not.
The temptation at each rung was to add: another gate, another smoothing window,
another confidence band. Every time, the cheaper move — measure the premise
first — was available and was skipped. The day's cost is mostly the price of
fixes built before their premises were probed. The surviving code is the part
that was probed: the estimator (sound, still live) and the raw fields.
## Method notes worth keeping
- **A check that cannot fail is not a check.** The contract test passed at the
same check count after a new field was added — it had silently not covered
it. Proving coverage means deleting the emit line and watching the test name
it. Six vacuous checks were caught this way in one day.
- **Like-for-like means same statistic, same instrument, same operating
condition.** Two of the three failures were comparisons between different
instruments wearing the same units.
- **Score predictions on representative encounters.** The advisory was scored
"working" on one lucky sample at uptime 141 s; the next sample was the
normal behavior. One claim per prediction, or the score means nothing.
- **Comments are load-bearing.** A stale rationale ("the page needs this to
say whether a restart pays back") survived a green suite after the code it
described was deleted; it would have re-taught the phantom to the next
reader. Sweep added code lines per patch for vocabulary the final tree no
longer supports.
## Open question
Whether engine age degrades step time at all is still unmeasured — every
excursion seen was load. The discriminating experiment: restart under steady
sustained load and watch whether `recent` re-lands at the same value within
minutes. If it does, no restart advisory is ever defensible and these two
numbers stay un-advised forever. If a floor genuinely ratchets up and stays
up, that signature gets a threshold, and a verdict can come back — designed
from the observation this time, not from the vocabulary of the design.
+90
View File
@@ -0,0 +1,90 @@
# the diagnose mode: the engine measures itself
A model entry with `diagnose: DIR` in the YAML file (`radiance --config FILE`) starts as a serve
would — same placement, same kernels, same prefix cache — runs a fixed workload on itself instead
of listening, and writes `DIR/diagnose.json` and `DIR/diagnose.md`. The keys are in
[TOOLS.md](TOOLS.md#the-diagnose-mode); this file is what the numbers mean, what makes a run a
measurement, and what is not measured yet.
## What the run does
`core/engine_diagnose.cpp` is the driver; the arithmetic and the report format are
`core/diag/diagnose.{h,cpp}`, which know nothing about the engine and are tested on the host
(`tests/diagnose_test.cpp`). The driver builds requests with no client, hands them to
`Scheduler::add_all` and reads their tokens back from `server::Sink` — the same path the KL mode
takes. The four points, each run once unmeasured and then `diagnose-runs` times:
| point | what it answers |
|---|---|
| decode by category | code, reasoning, prose, json, file_edit and summarization prompts to EOS: time per token by prompt shape, draft acceptance, tokens a step |
| concurrency sweep | 1, 2, 4, 8 streams at once (`diagnose-concurrency`): how TTFT and per-token time give way as the batch fills |
| prefill sweep | a prompt of 1k, 4k, 16k, 64k tokens (`diagnose-prefill`) then decode at that depth: prefill time, prefill tokens/s, and how deep context changes decode |
| interference | a prompt that arrives while streams are running: its TTFT, and the stall of the streams it joined |
A point the engine cannot run — a concurrency above `max-num-seqs`, a prompt the context cannot
hold with its decode — is skipped and said so in the report. It is never reported as a zero.
Per phase the report carries, from the scheduler's step ring and its counters: steps, step time
(median, p95, worst), prefill/decode tokens a step, decode tokens/s, draft positions drafted and
accepted, TTFT, per-token emission interval and its jitter, and each request's own tokens. Every
statistic over an empty set is `null` in the JSON and `–` in the Markdown, with the count beside it.
## What makes a run a measurement
| what would spoil it | what the run does |
|---|---|
| a prefix-cache hit — the second run of a point would measure lookups, not work | every prompt carries a tag unique to its run and stream, the cache is emptied before every run, and each request's `n_cached` is checked afterwards. A hit, or step records the ring overwrote before they were read, makes the verdict `NOT A MEASUREMENT`, lists the reason, and exits non-zero |
| the first time a shape runs (tape recording, code objects, pool growth) | each point runs once unmeasured first, in the same shape |
| `ignore_eos` generating past EOS, where a drafter hits differently | categories stop at the model's EOS; only the concurrency and prefill sweeps use `ignore_eos`, so every stream decodes for the whole run |
| a client-side temperature that a deployment never serves | decode runs at temperature 1 — draft acceptance is tuned on it — with the server's top_k/top_p/min_p and a fixed seed per request. Parity does not need greedy: identical logits sample identical tokens at any temperature |
| the environment | the report lists the engine's configuration knobs **by name only**, from a fixed list (`RADIANCE_HOME`, `RADIANCE_KERNELS`, `OMP_NUM_THREADS`, …) — a value may be a path or a token, and a name that is only a prefix plus a secret suffix is not on the list. The report is pasted into issues, so it carries no path either: the model is named by its architecture and quantisation, and the corpus and baseline are named as such |
The mode warns, in the report, about the settings that make its numbers those of a different
engine: `profile-ops` (recorded passes off, barriers added), `no-prefix-cache` (no lookups or
publishing to pay for), no usable chat
template (raw text, so tokens a step and acceptance are not chat traffic's), and a busy host.
## Reproducibility: whether the numbers repeat
The table above makes a run a measurement. Whether its numbers repeat on the next run, or on another
day, depends on more than the workload, so every report states it in three parts and the Markdown
gathers them under **Reproducibility**. None of them changes the verdict or the exit code: each is
how the engine serves, and its fix makes it a different engine.
| what moves the numbers | what the report carries |
|---|---|
| the runs of one point disagree | `spread_pct`, (max − min) / median, beside every summarised number. `stability` lists each headline number above **5 %** (`diag::kMaxSpreadPct`) — ms a step for every category prompt and concurrency point (not their token rate, which also moves with the text each run samples from its own seed), TTFT and prefill rate for the prefill sweep, the arriving prompt's TTFT — and its verdict is `stable`, `UNSTABLE` or `not judged` (no point with two runs). A category's own summary pools prompts that differ by design, so its stability is judged prompt by prompt (`prompts_summary`) |
| the machine | `conditions`: the build, the host settings that move a step's time (CPU governor and energy preference, kernel, device runtime, THP, IOMMU) and the serving cards (DPM ranges, power cap against its default, voltage offset, runtime PM, link), with the startup report's findings and their fix. A finding at warn level is also a warning of the run. `conditions.fingerprint` hashes all but the findings; with `diagnose-baseline`, `parity.conditions` lists every field that differs between the two reports — informational, since tokens do not depend on clocks |
| the cards' state | each run's `cards`: temperature (edge, junction, memory), power, performance level and current DPM levels before and after it, read between runs only (the SMU answers under its lock). `thermal` gives each card's range over the report and warns when runs started more than 10 °C apart (`diag::kMaxStartTempSpreadC`) or the performance level changed |
| the engine's own adaptivity | `reproducibility` notes it: dynamic placement (the heat engine moves experts as it sees routing, so a run starts with the resident set the runs before it left; `deterministic` pins it), `prefill-interleave auto` (decode-only steps sized by how long a chunk step took), a card at performance level `auto` (clocks chosen by the firmware; a fixed level such as `profile_standard` holds them, below serving clocks), and fewer than 5 runs a point |
For an A/B comparison of two builds: the same `conditions.fingerprint`, `diagnose-runs: 5` or more,
`deterministic` for a MoE model, a fixed `prefill-interleave`, a fixed performance level on the
cards, and both reports `stable`. Then a difference larger than the points' spread is the build's.
## Parity
`diagnose-baseline: FILE` compares every request's tokens with an earlier `diagnose.json` of the
same workload, and fails the run on any difference. Two reports are comparable only if their
`workload.fingerprint` — corpus, tokens, runs, sweeps, context, template, sampling — is the same;
`compare_outputs` refuses rather than compare a different workload. Points only one side ran are
reported as missing, not as equal. A drop in draft acceptance that every request shares is
reported beside the token comparison, since it is not a correctness difference.
## Sequence
1. **Done, host-tested.** The flag, the driver, the step ring, the report with categories, the
concurrency and prefill sweeps, and interference.
1b. Placement, expert-streaming and link counters per phase; the dashboard's Diagnose tab reading
the last report.
2. An issue census: every (op, band, domain, `n`) with calls per step and operand shapes, exported
for `rad-kbench`.
3. Per-dispatch device time in the play path, joined to the op through a record-to-op table made at
recording time, evaluated like `libr4d/isa/tsum.sh` and `libr4d/isa/gaps.sh`.
4. A correctness window: repeat and oracle for chosen ops over a step window rather than the whole
process, with ops that have no `libref` line reported as NOT CHECKED.
Steps 1b to 4 are listed under `not_measured` in every report, so a number that is absent says so
in the artifact itself and never reads as a zero. The mode is host-buildable and its arithmetic is
tested on the host; the numbers it writes on a card are the measurement, and belong with the
hardware they came from.
+56 -67
View File
@@ -72,10 +72,23 @@ docker run --rm --device /dev/kfd --device /dev/dri --security-opt seccomp=uncon
## Run it
The entrypoint is `radiance`. The other installed tools (`rad-convert`, `rad-info`, `rad-kbench`,
`rad-tune`, `rad-schemas`, `rad-tokcheck`) are on `PATH`, and the recipes are in
The entrypoint is `radiance`, which reads its settings from a YAML file named by `--config`
([`docs/GUIDE.md`](GUIDE.md) §4, [`docs/MULTIMODEL.md`](MULTIMODEL.md) §4). The other installed tools (`rad-convert`, `rad-info`, `rad-kbench`,
`rad-tune`, `rad-schemas`, `rad-tokcheck`, `rad-yaml`, and `rad-export`, which runs on the host
since the image has no Python) are on `PATH`, and the recipes are in
`/opt/radiance/share/radiance/recipes/`.
```yaml
# /srv/radiance/radiance.yaml
server:
host: "::"
port: 8000
models:
m:
model: /models/m.rad
tp: 2
```
```sh
docker run --rm -v /srv/models/rad:/models:ro --entrypoint rad-info radiance /models/m.rad
@@ -84,7 +97,8 @@ docker run -d --name radiance --network host --init --ulimit memlock=-1 \
--group-add "$(getent group render | cut -d: -f3)" \
--group-add "$(getent group video | cut -d: -f3)" \
-v /srv/models/rad:/models:ro \
radiance --model /models/m.rad --tp 2 --host :: --port 8000
-v /srv/radiance/radiance.yaml:/etc/radiance/radiance.yaml:ro \
radiance --config /etc/radiance/radiance.yaml
```
The options:
@@ -97,10 +111,10 @@ The options:
- `--init`: an init process runs as PID 1 and forwards SIGTERM to the engine, which finishes its
step and releases the cards.
- `--ulimit memlock=-1`: where no device kernel gathers the n-gram table (a run on the host
backend), `--ngram-placement ram` locks a copy of it in RAM (47.7 GiB for Qwen3.8-Flash-Next, far
backend), `ngram-placement: ram` locks a copy of it in RAM (47.7 GiB for Qwen3.8-Flash-Next, far
past Docker's default memlock limit). Without the limit raised, `auto` reads the table from the
container and `ram` refuses the start. On the cards the copy is pinned memory the cards read,
which the limit does not count. `deploy/compose/common.yaml` sets it.
which the limit does not count. The compose files set it.
- `--network host`: the server binds the host's addresses directly, IPv4 and IPv6, with no NAT in
front of it.
@@ -113,7 +127,7 @@ and put first on the search path; nothing in the image changes:
```sh
docker run ... -v /srv/radiance-plugins:/plugins:ro \
-e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance \
radiance --model /models/m.rad
radiance --config /etc/radiance/radiance.yaml
```
`/plugins` holds any of `kernels/`, `architectures/` and `quantizers/`, built against the same
@@ -123,80 +137,55 @@ the cards the engine runs on.
## Compose
`deploy/compose/` has one file per model and a `common.yaml` that each of them extends:
`deploy/compose/` has two compose files, `tp1.yaml` for one card (`RADIANCE_GPU` names
it) and `tp2.yaml` for two, each with the server's configuration in a file beside it
(`tp1.radiance.yaml`, `tp2.radiance.yaml`). Each runs one container that serves eleven models behind one port and
brings a model onto the cards when a request names it, parking or unloading others to make room
([`docs/MULTIMODEL.md`](MULTIMODEL.md));
[`deploy/compose/README.md`](../deploy/compose/README.md) lists the models of each.
| file | container | what it is |
|---|---|---|
| `flashnext.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | Qwen3.8-Flash-Next, 4-bit codebook experts and an int8 trunk; MTP depth 3; finished conversations kept in host memory (`--prefix-cache-mib`) |
| `flashnext-tp1.yaml` | `qwen3.8-next-flash-fp8-iq4r-moe.rad` | The same on one card: a 42 GiB pinned host pool for the experts that do not fit, 4096-token prefill steps, 4 sequences |
| `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server |
| `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 |
| `ornith-1.5-35b-a3b.yaml` | `ornith-1.5-35b-a3b-fp8.rad` | Ornith-1.5-35B-A3B, FP8, MTP, vision |
| `ornith-1.5-35b-a3b-w4a8.yaml` | `ornith-1.5-35b-a3b-w4a8.rad` | Ornith-1.5-35B-A3B with four-bit experts (GPTQ), a block-FP8 trunk, MTP, vision |
| `ornith-1.5-35b-a3b-w4a8-tp1.yaml` | `ornith-1.5-35b-a3b-w4a8.rad` | The same on one card, every weight in VRAM |
| `ornith-1.5-122b.yaml` | `ornith-1.5-122b-fp8.rad` | Ornith-1.5-122B, FP8, MTP, vision, on four cards with a 3 GiB pinned host pool per card and the vision tower in host memory |
| `ornith-1.5-122b-df2.yaml` | `ornith-1.5-122b-fp8-dflash2.rad` | The same with incoai's DFlash2 drafter in place of the MTP head |
| `ornith-1.5-122b-w4a8.yaml` | `ornith-1.5-122b-w4a8.rad` | Ornith-1.5-122B with four-bit experts (GPTQ), a block-FP8 trunk, MTP, vision, every weight in VRAM on four cards |
| `ornith-1.5-122b-w4a8-df2.yaml` | `ornith-1.5-122b-w4a8-dflash2.rad` | The same with incoai's DFlash2 drafter in place of the MTP head |
| `sage-a1.5.yaml` | `sage-a1.5-fp8.rad` | Sage-A1.5, FP8, MTP, vision |
| `sage-a1.5-tp1.yaml` | `sage-a1.5-fp8.rad` | The same on one card: the expert plane partly in an 8 GiB pinned host pool, one 262,144-token session |
| `sage-a1.5-df2.yaml` | `sage-a1.5-fp8-df2.rad` | Sage-A1.5 with incoai's Qwen3.6-35B-A3B DFlash2 drafter in place of the MTP head, vision |
| `sage-a1.5-mxfp4-df2.yaml` | `sage-a1.5-mxfp4-df2.rad` | The same with the trunk, the experts and the drafter at MXFP4; ten 262,144-token sessions |
| `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower |
| `qwen3.8-27b-mxfp4.yaml` | `qwen3.8-27b-mxfp4.rad` | Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk, its DFlash2 drafter and vision tower |
| `qwen3.8-27b-iqr-v4.yaml` | `qwen3.8-27b-${IQR_V4}.rad` | Qwen3.8-27B in IQR-V4 at the size `IQR_V4` names (default `iq4r-s-v4`), its DFlash2 drafter and vision tower |
| `qwen3.8-27b-paro.yaml` | `qwen3.8-27b-paro-int4.rad` | Qwen3.8-27B ParoQuant int4 (learned rotations) with its DFlash2 drafter and vision tower, on one card; the int5 and MXFP4 containers serve from it too |
| `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 |
| `gemma4-31b-w4a8.yaml` | `gemma4-31b-w4a8.rad` | Gemma 4 31B, int4 trunk with int8 activations, its assistant head as the MTP drafter, vision tower |
| `gemma4-31b-heretic-ara-w4a8.yaml` | `gemma4-31b-heretic-ara-w4a8.rad` | The same for Gemma 4 31B heretic-ara (refusals removed) |
| `gemma4-12b-bf16.yaml` | `gemma4-12b-bf16.rad` | Gemma 4 12B in bf16, its assistant head as the MTP drafter, pictures and audio through the 12B's embedders, on two cards |
| `gemma4-12b-i8g.yaml` | `gemma4-12b-i8g.rad` | The same with the trunk at int8 (i8a8), on one card |
| `nemotron-3.5-bolt-e4b-bf16.yaml` | `nemotron-3.5-bolt-e4b-bf16.rad` | NVIDIA-Nemotron-3.5-Bolt-E4B (Gemma 4 E4B) in bf16 with NVIDIA's DFlash drafter, the vision tower in pinned host memory, on one card |
| `nemotron-3.5-bolt-e4b-i8g.yaml` | `nemotron-3.5-bolt-e4b-i8g.rad` | The same with the trunk at int8 (i8a8) |
| `nemotron-3.5-bolt-e4b-a4.yaml` | `nemotron-3.5-bolt-e4b-a4.rad` | The same with the feed-forward at four bits (GPTQ), attention and layers 19-23 at i8a8 |
| `nemotron-3.5-bolt-74b-w4a8.yaml` | `nemotron-3.5-bolt-74b-w4a8.rad` | NVIDIA-Nemotron-3.5-Bolt-74B-A9B with four-bit experts and a block-FP8 trunk, NVIDIA's LiLiCorr drafter, vision, on two cards |
| `nemotron-3.5-bolt-74b-fp8.yaml` | `nemotron-3.5-bolt-74b-fp8.rad` | NVIDIA-Nemotron-3.5-Bolt-74B-A9B in block FP8 with NVIDIA's LiLiCorr drafter, vision, on four cards |
| `translategemma-27b.yaml` | `translategemma-27b-mxfp4-gptq.rad` | TranslateGemma 27B MXFP4 with its chat template (`gemma3.jinja`) |
| `glm53-flash.yaml` | `glm53-flash-mxfp4.rad` | GLM-5.3-Flash, MXFP4 experts and block-FP8 attention, on eight cards |
| `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter |
| `minicpm5-2b-bf16.yaml` | `minicpm5-2b-bf16.rad` | MiniCPM5-2B in bf16 with its DSpark drafter |
| `embeddinggemma2.yaml` | `embeddinggemma2-bf16.rad` | EmbeddingGemma 2 in bf16: text, image, video and audio embeddings on one card (`RADIANCE_GPU`) |
| `qwen-image-2.1.yaml` | `qwen-image-2.1-fp8.rad` | Qwen-Image 2.1 as block fp8 on two cards: OpenAI's images API, generation and edits |
| `qwen-image-2.1-turbo.yaml` | `qwen-image-2.1-turbo-fp8.rad` | Qwen-Image 2.1 Turbo, the same in 8 steps |
| `krea-2-turbo.yaml`, `krea-2-raw.yaml` | `krea-2-turbo-fp8.rad`, `krea-2-raw-fp8.rad` | Krea 2 Turbo and Raw as block fp8: text to image on one card (`RADIANCE_GPU`) |
| `anima.yaml` | `anima-aesthetic-fp8.rad` | Anima Aesthetic as block fp8: text to image on one card (`RADIANCE_GPU`); the Base and Turbo containers serve the same way |
| `flux-3-klein.yaml` | `flux-3-klein-fp8.rad` | FLUX.3 [klein] as block fp8: generation and edits on one card (`RADIANCE_GPU`); the base container serves the same way |
| `sdxl.yaml` | `illustrious-xl-v2.0-bf16.rad` | Stable Diffusion XL in bf16 (here Illustrious-XL v2.0; any single-file SDXL checkpoint converts the same way): text to image on one card (`RADIANCE_GPU`) |
| `qwen3-asr-1.7b.yaml` | `Qwen3-ASR-1.7B-hf/` (the checkpoint) | Qwen3-ASR 1.7B: `/v1/audio/transcriptions` and live `/v1/realtime`, on one card (`RADIANCE_GPU`) |
| `minimax-h3.yaml` | `minimax-h3-fp8.rad` | MiniMax-H3 as block fp8: video with its stereo soundtrack on `/v1/videos`, two cards and about 39 GiB of pinned host memory |
| `fasth3.yaml` | `fasth3-8-step-v2-fp8.rad` | FastVideo's FastH3 8-Step V2, the same in eight steps |
| `ltx-2.5.yaml` | `ltx-2.5-distilled-fp8.rad` | LTX-2.5 distilled as block fp8: video with its stereo soundtrack on `/v1/videos`, one card (`RADIANCE_GPU`), the text encoder in pinned host memory; the base container serves the same way |
| `minimax-music3.yaml` | `minimax-music3-bf16.rad` | MiniMax-Music3 in bf16: songs from lyrics and a description on `/v1/audio/speech` |
| `breeze-tts2.yaml` | `breeze-tts2-bf16.rad` | Breeze-TTS-2 in bf16: speech on `/v1/audio/speech` and live over `/v1/audio/speech/stream`, on one card (`RADIANCE_GPU`) |
A compose file names its configuration as a compose config (top-level `configs:`, its `file:`
the `.radiance.yaml` beside it), which Compose places in the container at
`/etc/radiance/radiance.yaml`, read-only, where `command: --config /etc/radiance/radiance.yaml`
names it. The configuration is plain radiance YAML: `radiance --config tp2.radiance.yaml --check`
parses and validates it without serving (with `RADIANCE_API_KEY` set, since the file names it),
and Compose substitutes nothing in it, so the port is the
`server.port` the file states (8000), which the compose file's health check asks too. The API key
stays in the container's environment, read through `server.api-key-env`, and never appears in the
configuration. An entry's name under `models:` is the model id a request gives in `model`. Delete
the entries of the containers you do not have; any other model is added as an entry with its keys
from the table in [`README.md`](../README.md#run-without-docker) (a `memory:` key holds for the
whole file). To change a setting, edit the model's entry.
The container names are the files the README's model table downloads or converts.
The entries carry no `priority`, so the model used least recently gives way to the one a request
asks for. Priorities are strict: a model never displaces an idle one of higher priority, so with
priorities on the small models MiniMax-Music3 and Hunyuan3D-2 waited out `scheduler.load-timeout`.
On `tp1.yaml`, Flash-Next pins a 42 GiB expert pool in host memory and the fleet keeps 8 GiB of the
host free; on a host with 61 GB of memory it is unloaded when another model loads and answered its
next request after 17 to 19 s, loaded from its container again (its entry's `prefix-cache-mib: 1024`
keeps its host pins within that host). Qwen-Image's `max-model-len` in both files keeps its cache
grant within the cards beside the other models ([`README.md`](../README.md#run-without-docker)).
Copy the directory to the serving host and fill in `.env` from `.env.example`. It sets the image,
the models directory (mounted read-only at `/models`), the API key, the port, the user and GPU
groups the server runs as, and the card a one-card model uses. The models directory must be on a
the models directory (mounted read-only at `/models`), the API key, the user and GPU
groups the server runs as, and the card `tp1.yaml` runs on. The models directory must be on a
local filesystem that does direct I/O, such as ext4, XFS or btrfs: Qwen3.8-Flash-Next reads its
n-gram table from the container that way. On btrfs with compression on, extents stored compressed
are read through the page cache instead, which works but loses the benefit of direct reads; a
container copied into a directory set `chattr +C` is stored uncompressed. Then:
```sh
docker compose -f flashnext.yaml up -d # start; restarts with the Docker daemon
docker compose -f flashnext.yaml logs -f # follow the log
docker compose -f flashnext.yaml down # stop
docker compose -f tp2.yaml up -d # start; restarts with the Docker daemon
docker compose -f tp2.yaml logs -f # follow the log
docker compose -f tp2.yaml down # stop
```
Every model listens on the same port and most take both cards (`flashnext-tp1.yaml`,
`ornith-1.5-35b-a3b-w4a8-tp1.yaml`, `qwen3.8-27b-paro.yaml`, the `nemotron-3.5-bolt-e4b-*.yaml` files and the files that read `RADIANCE_GPU` take one, the
`ornith-1.5-122b*.yaml` files four, `glm53-flash.yaml` eight), so run one at a time: `down` one before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and
the dashboard page answer without the API key, and the health check fetches `/health` with
busybox's `wget`.
`tp1.yaml` takes the same commands. The two files listen on the same port, so run one at a time:
`down` one before `up` on the other. The server runs as the host user given in `.env`. `/health`,
`/ping` and the dashboard page answer without the API key, and the health check fetches `/health`
with busybox's `wget`.
A container serving MiniMax-H3 also serves ComfyUI's Radiance MiniMax node
(`integrations/comfyui/ComfyUI-Radiance-MiniMax`), a client of `/v1/videos`. With
`--lora-dir /models/loras/h3` in the command, the node's adapter lists show the files under
`lora-dir: /models/loras/h3` in the model's entry, the node's adapter lists show the files under
`$RADIANCE_MODELS/loras/h3`.
+186
View File
@@ -0,0 +1,186 @@
# Flint on radiance
Recursive Flint (39.8B total / ~2.5B active): a 49-layer decoder with 2 dense layers followed by
47 sigmoid-routed MoE layers. The architecture plugin is `arch/flint`; the containers are built
from the BF16 checkpoint with `rad-convert`.
## Status
- **Q4** (`flint-q4.rad`, 19.72 GiB, fits one card): u4 attention, int4 experts, plain int8
dense/shared/head. Served on this build by the same forms as `hyv3_bf16`'s W4 and W8 recipes.
- **IQ8R** (`flint-iq8r.rad`, about 38 GiB, two cards): an IQ8R trunk and rotated int8 experts,
the forms `qwen35moe_w8a8` serves Qwen3.6-35B-A3B with. It replaces the plain int8 "Q8"
container of the 1.17-era port, whose unrotated int8 experts this build does not serve (a
container converted that way is refused by name; convert it again with the IQ8R recipe).
The measurements below were taken on the 1.17-era build with the forms it used then (the plain
int8 Q8 container and that build's plain int8 grouped GEMM); they have not been repeated on this
build. See [Measured](#measured).
## Geometry
| | |
|---|---|
| layers | 49: 2 dense, 47 MoE |
| attention | 32 query / 4 KV heads, head_dim 128, QK RMSNorm per head |
| sink | learned per-head `softmax_offset` on every layer (`attn_paged_sink`) |
| position | RoPE on the 35 sliding layers; NoPE on the 14 full layers |
| window | 513 on the sliding layers |
| FFN | dense `n_ff` 6144; MoE 256 experts, top-6, expert width 512, shared 1024, sigmoid routing, `norm_topk_prob` |
| vocab | 150144, untied head |
| KV | two groups: full (14 layers) and window 513 (35 layers) |
The full layers are `0, 1, 5, 9, ..., 45, 48`; the rest are sliding and carry RoPE.
## Containers and recipes
| file | contents | size |
|---|---|---|
| `flint-q4.rad` | U4 attention, I4 experts, INT8 dense/shared/head, BF16 router/norms/embed | 19.72 GiB |
| `flint-iq8r.rad` | IQ8R attention/dense/shared gate-up, rotated INT8 experts and shared down, INT8 head, BF16 router/norms/sinks/embed | about 38 GiB (not re-measured) |
Recipes: `data/recipes/flint-bf16-q4.recipe` and `data/recipes/flint-iq8r.recipe`.
The plugin reads which form a container holds from layer 0's q projection:
- **Rotated int8 trunk** (IQ8R, or the 128-group rotated int8 form): the norms write
`rmsnorm_had_quant_i8g`'s codes (`ar_rmsnorm_had_quant_i8g` with the fused all-reduce at TP2),
the attention output `had_quant_act_i8g`'s and the gated products `gated_had_quant_i8g`'s, and
every linear reads them at `i8a8h` without a quantiser of its own. The routed experts must be
stored rotated (int8, or a rotated four-bit form with an int8 row); the grouped GEMM
(`moe_gemm_i8a8`) reads the block input's own codes for gate/up and the gated product's, at one
scale a 128, for down.
- **Any other trunk** (bf16, the Q4 recipe's u4 attention, plain int8 linears): each linear reads
the bf16 plane or quantises it itself (`quant_act_i8g` for a plain int8 weight), and four-bit
experts read the block input's E4M3 pair (`moe_gemm_w4a8`).
A rotated trunk over unrotated experts, or rotated int8 experts under an unrotated trunk, is
refused at declare with the recipe to use.
Two non-obvious inputs:
- `data/flint-zero-bias.safetensors`: Flint has no router correction bias. The sigmoid router's
bias is selection-only, so the converter merges 47 x `[256]` zero tensors under
`model.layers.N.mlp.expert_bias`.
- `data/flint-chat-template.jinja`: the checkpoint's template contains `\x00`, which the Jinja
parser rejects. This is the same template without that replace; pass it with `--chat-template`,
or `/v1/chat/completions` answers 501 for want of a template.
## Convert
```bash
export RADIANCE_HOME=$PWD/build/radiance_home
# Q4
./build/bin/rad-convert "$HOME/models/flint" \
--add data/flint-zero-bias.safetensors \
--recipe data/recipes/flint-bf16-q4.recipe \
--chat-template data/flint-chat-template.jinja \
--report 20 --gpus 0,1 -o "$HOME/models/rad/flint-q4.rad"
# IQ8R
./build/bin/rad-convert "$HOME/models/flint" \
--add data/flint-zero-bias.safetensors \
--recipe data/recipes/flint-iq8r.recipe \
--chat-template data/flint-chat-template.jinja \
--report 20 --gpus 0,1 -o "$HOME/models/rad/flint-iq8r.rad"
```
`--plan-only` is the cheap pre-flight: it runs declare and resolves every op against the loaded
kernels before reading the 75 GiB checkpoint.
## Serve
```bash
# Q4, one card
./build/bin/radiance --model "$HOME/models/rad/flint-q4.rad" \
--radiance-home build/radiance_home --max-model-len 262144 --port 8090
# Q4, two cards (long context, expert parallel)
./build/bin/radiance --model "$HOME/models/rad/flint-q4.rad" --tp 2 \
--radiance-home build/radiance_home --max-model-len 262144 --port 8090
# Q4 with the int8 KV cache (about half the cache memory)
./build/bin/radiance --model "$HOME/models/rad/flint-q4.rad" \
--radiance-home build/radiance_home --max-model-len 262144 \
--kv-cache-dtype i8 --port 8090
# IQ8R needs both cards: about 38 GiB of weights
./build/bin/radiance --model "$HOME/models/rad/flint-iq8r.rad" --tp 2 \
--radiance-home build/radiance_home --max-model-len 131072 --port 8090
```
The KV cache is bf16 by default, or with `--kv-cache-dtype i8` the int8 cache: K and V as int8
codes with one f16 scale each per token and head (`2 * head_dim + 4` bytes a token and head).
Both KV groups, the full one and the 513-token window, take it, and the sink attention, the store
and the fused prologue all have rows for both. No other cache dtype is served.
## Measured
Taken on the 1.17-era build, before this port: the "Q8" columns are the plain int8 container
(unrotated int8 linears and experts, served by that build's plain int8 grouped GEMM), which this
build no longer serves; the IQ8R container has not been measured. The Q4 container is the same
recipe, served now by this build's kernels, and has not been re-measured either.
Two R9700s, greedy, warm, prefix cache disabled. Q4 and Q8 both at TP2. The payloads are
1,325 / 8,928 / 26,073 tokens. Tokenizers differ at 26K, so the payload is not the same token
count on both sides.
| context | Q4 prefill | Q4 decode | Q8 prefill | Q8 decode |
|---|---|---|---|---|
| 1.3K | 14,488 | 161.4 | 8,036 | 112.5 |
| 9K | 14,019 | 154.5 | 8,232 | 109.8 |
| 26K | 11,850 | 136.6 | 7,621 | 100.4 |
Reference on the same box, llama-server Q8 (fresh server, `-ngl 999 --jinja`) and Q4 (the
release's GGUF): about 2,364 / 5,359 / ~5,028 tok/s prefill for Q8 at 1.3K / 9K / 26K, ~65-70
tok/s decode, and 2,197 / 5,400 / ~3,290 tok/s prefill for Q4 with 77.7 tok/s decode at 1.3K.
llama.cpp's numbers move with its build and flags; re-measure beside the run being reported.
## Kernels
- **Experts.** IQ8R: `moe_gemm_q` at dtype `i8a8h` (`moe_gemm_i8a8`), rotated int8 weights at a
bf16 scale a (row, 128 of K) against the rotated int8 activation. Q4: `moe_gemm_q` at `w4a8`
(`moe_gemm_w4a8`) against the E4M3 activation. Expert parallel at TP2: each rank holds 128
whole experts a layer. On the 1.17-era build the Q4 w4a8 oracle reported the rows past
`off[n_expert]` as a mismatch (the kernel zeros the dropped tail, the reference computes it);
every live row agreed, and the first bad offset was `live * N`.
- **Sink attention.** `attn_paged_sink` at head_dim 128, gqa 8, on the bf16 or the int8 cache.
A prefill-shaped launch takes the WMMA kernel with the sink folded in: the sink seeds the running
max and one lane's denominator in the log2 domain, and the final reduction adds both lanes.
Decode and verify launches take the scalar kernel with split-KV, whose unsplit store and merge
fold the sink.
- **Residual and all-reduce.** `NormQuantFP8` folds the previous block's delta and its two-rank
all-reduce into the norm (`fuse_ar`), so only the embedding's reduce and the last block's
remain. Flint also sets `shared_fp32_combine` 0: the gather adds the local routed and shared
partials and one collective covers both, which is the TP1 arithmetic. The exact cross-rank
wire is the default; under `--tp-wire wht6` both trunk forms' norms have a 6-bit fused form
(`ar_rmsnorm_had_quant_i8g` and `ar_rmsnorm_quant_fp8` at `wire` 6).
- **NoPE prologue.** At decode heights the 14 full layers use `qkv_norm_rope_kv_store` with
`rotary_dim` 0: the kernel copies the normed head through the rotary stage, so it is the norms
and the store alone. Prefill heights take the standalone norms and `kv_store`, without a
rope on those layers.
## Correctness
On the 1.17-era build (not repeated on this one):
- Needle retrieval at 8K and 32K returned `ZX-417-QQ` exactly, with BF16 and E4M3 KV, including
after the sink-aware WMMA prefill.
- A `get_weather` tool call parsed as `tool_calls` with `{"city":"Paris"}`; reasoning uses
`<think>...</think>`.
- A 250,696-token prompt completed on two cards. On one card, Q4 at 262K fit with that build's
E4M3 KV cache: 19.37 GiB of weights plus an 11.45 GiB cache. The int8 cache of this build takes
a few percent more a token (its two f16 scales a token and head).
On this build, `tests/flint_arch_test.cpp` checks the declared graph and the step of both
containers at one and two ranks on both caches, and `tests/r4d_emu/test_attn.cpp` the sink WMMA
prefill on the bf16 and the int8 cache.
## Known limitations
- **Decode attention.** The scalar sink kernel is the short-context ceiling: ~184 us for a
513-window layer at 1.3K, against ~15 us of KV traffic. A flash-decoding decode form is the
follow-up.
- **No draft head.** Flint has no MTP head. Prompt-lookup speculation is available at serve time
and is workload-dependent.
-153
View File
@@ -1,153 +0,0 @@
# The Gemma 4 31B at w4a8 by GPTQ
The 31B's w4a8 container (`data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe`) rounds the trunk's
four linears to the nearest int4 on a group-128 grid. That moves the model's distribution most
where a reply is most constrained. After a string argument in a tool call, `sku:<|"|>MS-110`, the
bf16 model closes the string (`<|"|>`, probability ~1.0); the rounded trunk prefers `**,` (58%
against 41%), so a streamed call stalls inside the string and the client never sees its end.
`gemma4-31b-dense-bf16-w4a8g-df2.recipe` makes the same container (the same grid, kernels and size)
with the int4 codes chosen by GPTQ against the bf16 model's own activations.
## The route
1. **The Hessians, from the bf16 checkpoint.** arch/gemma4 serves the 31B's bf16 checkpoint as it
ships, and with `RADIANCE_CALIB_DIR` set it sums the Gram of every dense linear's bf16 input over
the corpus it is fed. The files carry the names the w4a8 container gives the weights
(gemma4_bf16's `blk.N.attn_qkv`, `attn_o`, `ffn_gate_up`, `ffn_down`), so the recipe reads them
as they are. o_proj's and down's inputs are split across ranks at `--tp 4`, and each rank writes
its block (`.part`), which libquant places on the diagonal.
2. **The convert.** `CALIB=DIR rad-convert` with the recipe: libquant's `gptq` on the trunk's four
linears, everything else as the -df2 recipe makes it. libquant factors each Hessian through
OpenBLAS's LAPACK where the build finds OpenBLAS (the Docker image has it); without it,
libquant's own single-threaded loops take hours for each 21504-wide down projection.
The w4a8 container's own plugin cannot record them: its linears read int8 activations, which
`gram_accum` does not take, and a quantised container's activations would come through its
quantisers.
## The corpus
Whole conversations, rendered with the model's own chat template (Hugging Face's
`apply_chat_template`, thinking off) as token ids, so the Hessians see the reply format the server
writes: 2.78M tokens in 4,724 conversations, each at most 8192 tokens, of which a tenth is held out
and the other 2.47M tokens (4,252 conversations) is the calibration corpus.
| share | tokens | conversations | from |
|---|---|---|---|
| tool calls | 834K | 2,627 | glaive-function-calling-v2 (Apache-2.0): its functions as tools, its calls as `tool_calls` (the template writes them as `<\|tool_call>call:NAME{k:<\|"\|>v<\|"\|>}<tool_call\|>`), its function responses as tool turns |
| chat | 695K | 730 | UltraChat 200k (MIT) prompts with the served 31B's greedy replies (the round-to-nearest w4a8 container's) |
| code | 417K | 589 | self-oss-instruct-sc2 (ODC-BY) prompts, the 31B's replies |
| math | 417K | 493 | OpenMathInstruct-2 (CC-BY-4.0) prompts, the 31B's replies |
| reasoning | 417K | 285 | rStar-Coder (CC-BY-4.0) prompts, the 31B's replies |
The held-out tenth (305K tokens) is never fitted to; 44.5K tokens of it are the KL mode's corpus
below. BetterBench's corpora, on which the stall is measured, are in neither.
## Running it
```sh
# 1. The Hessians: three slices of 20 layers (60 layers' Grams, ~364 MiB a rank each at --tp 4,
# do not fit beside the bf16 weights), the corpus through prefill once per slice.
for sl in 0:20 20:40 40:60; do
RADIANCE_CALIB_DIR=/calib RADIANCE_CALIB_TOKENS=2300000 RADIANCE_G4_CALIB_LAYERS=$sl \
radiance --model gemma-4-31B-it --tp 4 --no-prefix-cache --num-speculative-tokens 0 \
--max-num-batched-tokens 8192 --max-num-seqs 8 --max-model-len 10240 --kv-cache-dtype bf16
# ...feed the corpus at max_tokens 1 until every rank prints
# radiance: gemma4: rank N wrote the Hessians of layers lo:hi after ... tokens to /calib
done
# 2. The container.
CALIB=/calib rad-convert gemma-4-31B-it --draft-model gemma-4-31B-it-speculator.dflash2 \
--recipe data/recipes/gemma4-31b-dense-bf16-w4a8g-df2.recipe \
--set quantization_config.quant_method=compressed-tensors -o gemma4-31b-dense-w4a8g-df2-qkv.rad
```
On four R9700s each slice took about 25 minutes, the corpus through prefill at ~1,500 tokens a
second with the taps live, and the three wrote 45 GB of Grams. The convert took 75 minutes on a
48-thread EPYC.
## Measuring it
- **KL against the bf16 model.** The engine's KL mode: the bf16 checkpoint (arch/gemma4) records its
full distribution at every position of the held-out 44.5K tokens, and each container is scored
against it with the same flags (`--tp 4`, bf16 KV). That reference is Hugging Face's: on 41 of
its documents (21,407 positions), Transformers' bf16 31B is a mean 0.0195 nats from it (median
0.00001), and at each container's 25 worst positions the two agree.
- **Where it counts: the model's turns.** At system and user positions, text the model never
writes, the bf16 model's own guesses are untrained and often odd (` same` at 1.000 after
`<|tool>declaration`, `---` at 0.997 inside a user's problem statement). Any quantisation moves
them, so they carry most of the mean: of RTN's and Q8's 50 worst positions, 46 are system or
user positions, each a confident bf16 guess that both implementations make. The tables give every
position and the model's own turns apart.
## Results
The containers are the same size (24.9 GB) on the same kernels, so speed does not move; what
moves is how close each is to the bf16 model.
**The stall.** The next token after `sku:<|"|>MS-110` in BetterBench's order request, and
BetterBench's two order requests (a single call, and a round trip) each streamed 20 times, sampled
as BetterBench sends them, `--tp 2`, thinking off:
| | `<|"|>` (the string closes) | `**,` | single calls that stalled | round trips that stalled |
|---|---|---|---|---|
| bf16 (Hugging Face) | ~1.0 | | | |
| RTN (`-df2-qkv`) | 41% | 58% | 10 of 20 | 1 of 20 |
| **GPTQ** | **99.8%** | 0.2% | **0 of 20** | **0 of 20** |
**KL against the bf16 model**, the 44.5K held-out positions (Q8 is the w8a8 container, 38.2 GB):
**every position** (44456 positions)
| | mean KL | median | p99 | over 1 nat | top-1 |
|---|---|---|---|---|---|
| RTN | 0.988 | 0.0039 | 14.81 | 16.7% | 81.9% |
| GPTQ | 0.659 | 0.0020 | 11.15 | 12.8% | 84.5% |
| Q8 | 0.620 | 0.0014 | 12.08 | 11.7% | 85.6% |
**the model's turns** (31975 positions)
| | mean KL | median | p99 | over 1 nat | top-1 |
|---|---|---|---|---|---|
| RTN | 0.341 | 0.0003 | 7.49 | 6.7% | 90.5% |
| GPTQ | 0.251 | 0.0001 | 5.46 | 5.7% | 91.3% |
| Q8 | 0.226 | 0.0001 | 5.28 | 4.8% | 92.3% |
**the model's turns by source** (mean KL / top-1)
| | chat | math | oss | rstar | tool |
|---|---|---|---|---|---|
| RTN | 0.810 / 81.8% | 0.093 / 94.5% | 0.166 / 92.9% | 0.087 / 94.4% | 0.521 / 88.9% |
| GPTQ | 0.572 / 82.7% | 0.062 / 95.4% | 0.134 / 93.4% | 0.067 / 95.2% | 0.396 / 89.7% |
| Q8 | 0.536 / 84.7% | 0.046 / 95.9% | 0.130 / 94.3% | 0.043 / 95.8% | 0.356 / 90.8% |
GPTQ closes 78% of the distance from RTN to Q8 on the model's turns and 89% over every position, on
every source; on tool-call replies the mean falls from 0.521 to 0.396.
**The drafter** (DFlash2, block 8), specbench at 8 users, thinking off, tokens a step:
| | HumanEval | math | qa | question | rag | summarization | translation | all |
|---|---|---|---|---|---|---|---|---|
| RTN | 5.97 | 6.16 | 2.91 | 3.44 | 4.40 | 3.21 | 4.02 | 3.96 |
| **GPTQ** | 5.98 | 6.19 | 3.25 | 3.56 | 4.37 | 3.21 | 4.08 | **4.11** |
(The set's `writing` subset is byte for byte its `question` subset and is left out.) Decode speed
on BetterBench's 7 multi-turn conversations is the same: first turns 159.6 tok/s against 159.8,
3.85 tokens a step against 3.88.
**BetterBench's `tool_call` and `multi_turn` categories at 1-16 users**, sampled at 0.7, `--tp 2`,
thinking off, the two containers served at once and the card pairs swapped for a second run (both
runs given):
| | RTN | GPTQ |
|---|---|---|
| multi-turn: the right tool | 15/18, 15/18 | **18/18, 18/18** |
| multi-turn: a turn after the tool's result | 16/21, 17/21 | **18/18, 18/18** |
| tool calls: a valid call | 16/17, 15/17 | **17/17, 17/17** |
| tool calls: the right tool | 16/17, 15/17 | **17/17, 17/17** |
| weighted decode, tok/s | 176.7, 175.0 | 183.8, 172.1 |
| aggregate at 1 / 2 / 4 / 8 / 16 users, tok/s | 116 / 174 / 252 / 253 / 308, 113 / 175 / 240 / 261 / 314 | 111 / 169 / 240 / 260 / 309, 115 / 168 / 235 / 244 / 299 |
Throughput is level within the runs' noise (about 3%; the sessions differ too, since the calls that
now succeed lead to other turns).
+1366 -868
View File
File diff suppressed because it is too large. Load diff
+18 -5
View File
@@ -21,6 +21,8 @@ core/plugin/ plugin loader, kernel registry, op schemas, selector, bucket t
core/build/ the declare phase: builder, weight manifest, buffer plan, graph dump
core/runtime/ the run phase: RadCtx, rad_issue, the arena
core/mem/ pools, slab, KV block manager, prefix cache
core/kvstream/ streamed KV: the host mirror, the VRAM ring and its bring-up (docs/KV-STREAMING.md)
core/lora/ LoRA adapters loaded beside the base model
core/sched/ scheduler, RadBatch construction, request lifecycle
core/place/ placement planner, the mover, the heat engine
core/sample/ device sampler dispatch, the host reference chain, grammar bitmask
@@ -30,25 +32,36 @@ core/gen/ image generation: the request and the pass driver
core/format/ the .rad reader and writer, safetensors, recipes, the imatrix, the tune cache
core/server/ HTTP: the OpenAI, Anthropic and llama-server endpoints, /metrics, the dashboard
core/diag/ the startup report
core/kld.* the KL mode: --kld-record / --kld-ref
core/fleet/ the YAML file `radiance --config` reads: levels, defaults, the flag table's keys
core/kld.* the KL mode: the kld-record / kld-ref keys
core/engine* the engine that ties them together; core/main.cpp is the `radiance` binary
libref/ every op, naively and correctly, host domain: the oracle and last resort
libr4d/ the RDNA4 (gfx12xx) kernel library: kernels, rows, layouts, fusion claims
libr3d/ the RDNA3/3.5 (gfx11xx) kernel library
libhalo/ the Strix Halo (gfx1151) kernel library
libavx/ the same vocabulary in x86 SIMD, host domain: the production host kernels,
built on every x86-64 build because the engine refuses to serve an op that
resolves only to libref (without --debug-accept-reference-kernels)
resolves only to libref (without debug-accept-reference-kernels)
libquant/ the built-in quantisers rad-convert's recipes name: grids, transforms, rtn, gptq
plugin/spechub/ the draft-coupling ops (`mtp_couple_propose`, `mtp_couple_verify`, `mtp_trav_verify`,
`dflash_couple_propose`, `draft-coupling: on`): schemas and shapes on the host,
launches on the card and in a host reference
arch/<id>/ one architecture plugin per directory
tools/ rad-info, rad-kbench, rad-convert, rad-tune, rad-schemas, rad-tokcheck,
rad-chatparse, rad-gbnf-check
tools/ rad-info, rad-convert, rad-export, rad-kbench, rad-tune, rad-schemas,
rad-tokcheck, rad-yaml, rad-chatparse, rad-gbnf-check
cmake/ rad_add_plugin, and the package config an out-of-tree plugin find_package()s
scripts/ harnesses for serving, tracing and profiling a running engine
dashboard/ the page the engine serves at `/` (React, built by Vite into
core/server/dashboard_page.h)
docker/ the image build (`docker/build.sh`) and its licence collection
deploy/ compose files, chat templates, Grafana dashboards
integrations/ clients of the HTTP API (ComfyUI nodes)
data/ kernels.rkb and kernels_moe.rkb: recorded references rad-kbench replays with
no model. Two, because no one container declares the whole vocabulary.
recipes/: the quantisation recipes of the containers this tree serves
docs/KERNELS.md what rad-kbench last measured, generated and checked in
vendor/ llama.cpp lifts tracked to an upstream commit (vendor/UPSTREAM), changed only
through vendor/patches/; nlohmann/json and cpp-httplib
through vendor/patches/; yyjson and cpp-httplib
tests/ ctest
```
+31
View File
@@ -24,6 +24,37 @@ rotated int8 activations on the `i8a8h` trunk:
The embedding and the head decode the same forms, unrotated. The arithmetic is the int8 grid's
for every form: a narrower code changes the bytes read, not the values multiplied.
## IQ8R at one scale a 256 of K
`data/recipes/q38-27b-iq8r.recipe` is the int8 trunk, at block fp8's size. It keeps IQ8R's
codes and rotation and widens the scale group: a u8 scale per (row, 256 of K) under one bf16 scale
a row (`codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128`), eight bits and
1/256 of a byte a weight plus two bytes a row. The rotation stays 128 wide, and the activations
carry one scale per (token, 256). libr4d reads it with `gemm_iq8r_nt_m16` and `gemm_iq8r_tiled`
behind the 256-group quantisers, whose decode rows have chained forms; `kv-cache-dtype: i8`
([GUIDE §4.4](GUIDE.md)) is the cache that goes with it.
The group is 256 for the prefill: at one scale a 128 the tiled GEMM folds a scale twice as often and
an 8192-token prefill of Qwen3.8-27B runs 11.6% under block fp8's (2407 tok/s against 2724); at 256
it runs 2.4% under (2649 against 2715). The cost is 0.00004 KL (round to nearest: 0.00045 at 128,
0.00049 at 256).
Qwen3.8-27B on two R9700s, KL against bf16 over the 464 091 positions the model writes itself:
| container | KL | top-1 |
|---|---|---|
| block fp8, the published checkpoint | 0.00363 | 97.38% |
| the same on the int8 KV cache | 0.00365 | 97.38% |
| IQ8R by round to nearest from that fp8 checkpoint | 0.00217 | 98.17% |
| IQ8R by round to nearest from bf16 | 0.00049 | |
| IQ8R by GPTQ from bf16 (the recipe) | 0.00039 | 99.19% |
| the same on the int8 KV cache | 0.00043 | 99.18% |
One R9700, ms a decode step: 47.9 at one sequence and 53.6 at eight against block fp8's 48.7 and
53.9, and with the DFlash2 drafter (the recipe's, on the 16-level codebook) 55.0 / 59.9 / 70.4 at 1
/ 4 / 8 sequences against 54.6 / 60.8 / 72.3. Over 24 prompts, four at a time, the drafter lands
12.5 tokens a step against 12.6.
## The quantiser
`gptq` (libquant) over the rotated weight against the calibration Hessians:
+3
View File
@@ -718,9 +718,11 @@ Rows declaring an optional hook (tuning, fusion, weight layout):
| `ref_dflash_couple_propose` | `dflash_couple_propose` |
| `ref_mtp_couple_propose` | `mtp_couple_propose` |
| `ref_mtp_couple_verify` | `mtp_couple_verify` |
| `ref_mtp_trav_verify` | `mtp_trav_verify` |
| `spechub_dflash_couple_propose` | `dflash_couple_propose` |
| `spechub_mtp_couple_propose` | `mtp_couple_propose` |
| `spechub_mtp_couple_verify` | `mtp_couple_verify` |
| `spechub_mtp_trav_verify` | `mtp_trav_verify` |
`libref`: 179 row(s) not reached:
@@ -1073,6 +1075,7 @@ on a marked row is a hole this model falls into.
| `moe_scatter_inv` | | - | device | - | - |
| `mtp_couple_propose` | | - | - | device+host | - |
| `mtp_couple_verify` | | - | - | device+host | - |
| `mtp_trav_verify` | | - | - | device+host | - |
| `mtp_enter` | | host | device | - | host |
| `mul` | | host | device | - | host |
| `mul_weight` | yes | host | device | - | host |
+36 -36
View File
@@ -1,13 +1,13 @@
# KV streaming: host-authoritative KV with a resident VRAM window
A streamed group keeps its whole context in pinned host RAM and only a ring of blocks in VRAM; the
VRAM that frees up goes to experts. `--max-model-len` and `--max-num-seqs` size the host side,
`--kv-resident` the ring. The operator's view is [GUIDE.md](GUIDE.md) §4.4.1; source comments cite
VRAM that frees up goes to experts. `max-model-len` and `max-num-seqs` size the host side,
`kv-resident` the ring. The operator's view is [GUIDE.md](GUIDE.md) §4.4.1; source comments cite
the section numbers below.
Streaming pays only when a step reads far less than the context, which is true of radiance's
indexer-selected attention (the QSA family and GLM-5.3's MLA block) and false of dense attention
(§2). An architecture with no streamed path ignores the flag with one warning (§4.5).
(§2). An architecture with no streamed path ignores the key with one warning (§4.5).
Two views sit over one allocation: the **ring**, `n_slots` blocks deep and `n_layers` stripes,
addressed through a residency map, and the **stage**, the group's context deep and one stripe,
@@ -30,12 +30,12 @@ order copies with events, not syncs (`spec.md` §5.4).
## 2. What bounds a step's read
Qwen3.8-Flash-Next (`arch/qwen4exp_fp8`) at `--tp 2`, fp8 KV, per rank; 12 QSA layers plus the
Qwen3.8-Flash-Next (`arch/qwen4exp_fp8`) at `tp: 2`, int8 KV, per rank; 12 QSA layers plus the
MTP head bind `kv_attn`:
| group | per 4-token block | per token | at 262 144 tokens |
|---|---|---|---|
| `kv_attn` (fp8, 2 kv heads, head_dim 256, 13 layers) | 26.00 KiB | 6.50 KiB | 1.66 GiB |
| `kv_attn` (i8, 2 kv heads, head_dim 256, 13 layers) | 26.20 KiB | 6.55 KiB | 1.67 GiB |
| `kv_qsa_bkey` (bf16, 1 head, head_dim 16) | 3.25 KiB | 0.83 KiB | 208 MiB |
Decode is sparse at every context: the selection keeps `topk = budget / ratio = 512` blocks a row
@@ -43,8 +43,8 @@ Decode is sparse at every context: the selection keeps `topk = budget / ratio =
different: `qsa_score` reads every complete block of `kv_qsa_bkey` each step (208 MiB at 262K), so
that group is dense-read and stays resident (§3.1).
A dense family (Qwen3.8-27B, `arch/qwen35_*`) reads the whole context every step, 16 KiB a token per
rank at fp8, so a ring only subtracts from a read that is already link-bound. It declares no
A dense family (Qwen3.8-27B, `arch/qwen35_*`) reads the whole context every step, 16.1 KiB a token per
rank at i8, so a ring only subtracts from a read that is already link-bound. It declares no
streamed path.
---
@@ -68,7 +68,7 @@ its id space from the context (`kv_context_blocks`) rather than the pool split,
compete for VRAM; it never lends to the expert slab, and the idle tiers never gather it (§4.1).
Refused or charged by name:
- **a window that does not fit** the budget is refused against `--kv-resident` before the split
- **a window that does not fit** the budget is refused against `kv-resident` before the split
(`kvstream_window_fit`), rather than leaving a neighbour with zero blocks;
- **a streamed `RAD_KV_WINDOW` group** is refused: a window bounds its own history;
- **the dense-read floor**: a group read over its whole history every step
@@ -101,7 +101,7 @@ resolve, seeing it resident, would not copy it. `res` is written by `kv_resolve`
A layer's order is **store, then resolve, then attention**, so a block copied in from the mirror
carries this step's tokens; the indexer runs before the store and so cannot resolve. The streamed
store has E4M3 and bf16 rows; a packed cache (`fp8_v4`, `k6_v4`) has none and is ignored (§4.5).
store has int8, E4M3 and bf16 rows.
### 3.4 The resolve
@@ -148,7 +148,7 @@ refusals).
### 3.5 Prefill: the union, and the stage
Above `qsa_exact_to = budget + ratio - 1 = 2051`, prefill is per-query sparse: every row of a chunk
selects its own 512 blocks. One launch's union (`scripts/kv-union.sh`, Flash-Next `--tp 2`):
selects its own 512 blocks. One launch's union (`scripts/kv-union.sh`, Flash-Next `tp: 2`):
| prompt tokens | ring that held | largest union | largest misses of one call |
|---|---|---|---|
@@ -210,11 +210,11 @@ side is `rad_kv_layer_index`, `rad_kv_stage_layer` and `rad_kv_stage_next`, with
`kv_stream_layer`, `kv_resolve_declare`, `kv_resolve_issue` and `kv_stage_*` helpers in
`arch/common/rad_arch.h`.
### 3.7 Flags, report, metrics
### 3.7 Key, report, metrics
`--kv-resident N` is the only switch. The KV report gains the streamed group's two-tier line, and the
`kv-resident: N` is the only setting. The KV report gains the streamed group's two-tier line, and the
startup lines name the ring (and why it was raised), the host mirror, the stage, or which context a
covering flag spans. Metrics: `radiance:kv_resident_blocks`, `radiance:kv_stream_misses_total` and
covering value spans. Metrics: `radiance:kv_resident_blocks`, `radiance:kv_stream_misses_total` and
`radiance:kv_stream_bytes_total{dir="in"}`. A request's end logs each group's cumulative resolves,
lookups and misses with the largest union, misses and claims of one launch (`ctl[10..12]`).
@@ -223,21 +223,21 @@ lookups and misses with the largest union, misses and claims of one launch (`ctl
The mirror is the largest host allocation after the experts' pool: 4.69 GiB a rank for four
204 800-token sequences of Flash-Next. `kvstream_host_gate` checks the mirrors once, before any rank
pins one, against the host tiers still to be pinned after them (the activation arenas and, when
sized, the checkpoint store) plus `--host-headroom-mib`. A refusal names `--max-model-len` and
`--max-num-seqs`, which size the mirror; `--host-pool-mib` sizes the experts' tier and cannot make
sized, the checkpoint store) plus `memory.host-headroom-mib`. A refusal names `max-model-len` and
`max-num-seqs`, which size the mirror; `host-pool-mib` sizes the experts' tier and cannot make
room.
The prefix cache's host tier (`--prefix-cache-mib`) is turned off when a group streams, before
The prefix cache's host tier (`prefix-cache-mib`) is turned off when a group streams, before
anything is sized from it: an entry covers every cached group, and a streamed group's rows are
addressed by the block ids its sequence used, so the entry cannot move to a host slot
(`PrefixCache::demotable`). Prefix hits still work from VRAM; a conversation evicted from VRAM is
prefilled again rather than restored. "Streams" is the engine's answer (`cfg.kv_streams`): the flag
set, the architecture's streamed ops declared and linked for the group with an fp8 or bf16 cache,
prefilled again rather than restored. "Streams" is the engine's answer (`cfg.kv_streams`): the key
set, the architecture's streamed ops declared and linked for the group at its cache dtype,
and a ring under the context. In every other case the host tier is as configured.
### 3.9 What it costs
`--kv-resident` has two floors, applied in `kvstream_ring_shape`/`kvstream_ring` and clamped to the
`kv-resident` has two floors, applied in `kvstream_ring_shape`/`kvstream_ring` and clamped to the
context, and the carve takes the larger:
- **correctness**: one decode step's selection, `max_seqs x (1 + n_spec) x 513` blocks (16 416
@@ -247,16 +247,17 @@ context, and the carve takes the larger:
than the VRAM the ring frees (at 64k of history: 24 576 runs 37.9 tok/s, 8 192 runs 37.1 with 75 %
more misses), and a ring larger than the history buys nothing.
A flag under either is raised with one warning. The raised number is what
A value under either is raised with one warning. The raised number is what
`RadBuildCtx::kv_resident_blocks` carries into the declare, since `kv_resolve` sizes its table from
it. A context under 32 768 tokens cannot stream.
Decode: a miss costs about 0.8 us, and a resolve launch about 4 us of device time, flat across ring
sizes; the twelve a step cannot merge (each follows its layer's store), so streaming costs about 3 %
of decode at `--tp 2` and nothing at `--tp 1`. The identity placement is worth +2 % at 16k. Warming
of decode at `tp: 2` and nothing at `tp: 1`. The identity placement is worth +2 % at 16k. Warming
the ring from the last prefill chunk made decode 3.8 % slower, through slot order.
Capacity is bought in host RAM. Flash-Next fp8, two ranks, `--kv-resident 24576`:
Capacity is bought in host RAM. Flash-Next, two ranks, `kv-resident: 24576`, measured with a
one-byte E4M3 cache (512 bytes a token and head where the int8 row is 516):
| configuration | VRAM KV per card | host RAM per rank |
|---|---|---|
@@ -270,7 +271,7 @@ only the ring does not scale. Prefill comes out 3-5 % above the resident arm, be
cache no longer holds goes to experts that would otherwise be read over the link. The stage copy's
cost is its volume (0.6 GiB a pass at 16k and 45 GiB at 160k, within 0.3 % of the live KV, a
figure the step's own ranges keep however much the prefix cache retains), not its overlap, since it shares the link as an equal (§6.1). Capacity is bought with
`--max-num-seqs`, inside the trained window, so no rope change is needed. Perplexity: 3.994 resident,
`max-num-seqs`, inside the trained window, so no rope change is needed. Perplexity: 3.994 resident,
4.015 with a covering window, 4.014 with a fraction of it.
---
@@ -304,17 +305,17 @@ times; the mirror is the tier); the prefix cache's host tier (§3.8); the expert
gated by `lockable_room`.
3. **The maps**: device `res`, `slot_block`, `slot_state` per layer and a control block, from the KV
pool, carried in the batch.
4. **Report, flag, metrics** (§3.7).
4. **Report, key, metrics** (§3.7).
### 4.3 Device changes
1. `kv_resolve`: a libr4d kernel, a libavx form and the libref oracle (§3.4).
2. `kv_store_streamed` and its prologue fold (§3.3), E4M3 and bf16.
2. `kv_store_streamed` (int8, E4M3 and bf16) and its prologue fold (§3.3; int8 and bf16).
3. The stage copy, a DMA list per layer (§5.3); no kernel.
### 4.4 Arch changes
The gated fp8 attention block (`arch/common/rad_block_attn_gated_fp8.h`) declares the streamed store
The gated attention block (`arch/common/rad_block_attn_gated_fp8.h`) declares the streamed store
beside `kv_store`, issues it instead when the batch hands the group a stream, and issues the resolve
after the store and before each sparse launch. GLM-5.3's MLA block (`rad_block_glm_mla.h`) declares
the same pair and resolves at finish, after its indexer selects.
@@ -324,17 +325,16 @@ the same pair and resolves at finish, after its indexer selects.
A plugin states once, in `RadArchProbe::kv_stream_ok`, that its architecture can stream; the engine
carries it into every declare as `RadBuildCtx::kv_stream_ok`. `qwen4exp_fp8` and `glm5next` set it.
The three streamed-only ops (`kv_store_streamed`, its fold, `kv_resolve`) are declared only when the
architecture can stream and `--kv-resident` asks for a ring (`kvstream_op_gated`, consulted by
architecture can stream and `kv-resident` asks for a ring (`kvstream_op_gated`, consulted by
`Builder::op_declared`), so a model file never knows whether the operator asked, and every
`rad_op_declared` check falls through to the resident path. Fail-safe, with one warning each:
- a group with no `kv_resolve` or no streamed store for its geometry is ignored: without the resolve
the attention would read block ids past the ring; without the store a miss would read zeros. A
declaration with no kernel, or one stating another group's geometry, does not count;
- a packed cache (`fp8_v4`, `k6_v4`) is ignored the same way, naming the layout;
- an architecture whose probe says no turns the flag off at startup.
- an architecture whose probe says no turns the key off at startup.
Without the flag no streamed op is declared and no budget changes. The graph is not byte-identical
Without the key no streamed op is declared and no budget changes. The graph is not byte-identical
to a build without the feature, though: `qsa_select` writes its entry count (`qsa_nsel`,
`selected_count`), an i32 a token, whether or not anything streams.
@@ -344,7 +344,7 @@ to a build without the feature, though: `qsa_select` writes its entry count (`qs
### 5.1 The ring's depth
`--kv-resident` is off by default. When set it is never carved below 32 768 tokens, nor below one
`kv-resident` is off by default. When set it is never carved below 32 768 tokens, nor below one
decode step's selection when that is larger (§3.9), and never above the context; one function,
`kvstream_ring_shape`, gives the budget probe, the carve and the declared `kv_resolve` the same
depth.
@@ -355,9 +355,9 @@ the serial drafter's history pass over a prefill chunk) takes the stage.
### 5.2 There is no streaming switch
`--kv-resident N` is the feature: absent or 0 and nothing streams, set and the ring is N tokens. A
`kv-resident: N` is the feature: absent or 0 and nothing streams, set and the ring is N tokens. A
ring that covers the context does not stream at all (§3.1), so a configuration whose context fits
runs the same path as without the flag.
runs the same path as without the key.
### 5.3 The transport
@@ -410,7 +410,7 @@ whole context resident during prefill (the group would still carve `n_layers x c
### 6.1 The link, the lanes, and the hold
At `--tp 2` the all-reduce, the stage copies and the prefill expert stager share the link. DMA lists
At `tp: 2` the all-reduce, the stage copies and the prefill expert stager share the link. DMA lists
take their share at full rate without a CU slot; an ordinary stream copy would hold one and starve
the kernels. Because the stage list must not yield, it competes as an equal, which is why overlap
recovers only part of its cost (§3.9). A stage moved to lane 1 needs `rad_lane_join(1, 0)` before
@@ -418,14 +418,14 @@ its reader.
### 6.2 The first in-place device write to mapped host memory
`r4d_selftest --case kv_store_streamed_fp8` and `--case kv_store_streamed_bf16` put the mirror in
`r4d_selftest --case kv_store_streamed_i8`, `_fp8` and `_bf16` put the mirror in
mapped pinned memory, run the kernel and compare the bytes the host reads after the sync with
libref's; `scripts/kv-stage-parity-64k.sh` exercises the same write in the served path.
### 6.3 Rank coverage
Every rank resolves the same shared block ids through identically built maps of its own. Only
`--tp 1` and `--tp 2` have run; `--tp 3` and `--tp 4`, the uneven split, the attention-zero ranks
`tp: 1` and `tp: 2` have run; `tp: 3` and `tp: 4`, the uneven split, the attention-zero ranks
and the four-card selftest cases are untested, and the per-rank view (`kvstream_step_view`) is the
path to check first.
+34 -27
View File
@@ -2,7 +2,7 @@
Qwen3.8-Flash-Next has 512 experts of 640 over 48 layers: 112.5 GiB of expert weight at E4M3,
against two 32 GB cards. Split over both ranks, the placement planner still comes up 26 GiB short.
The file tier (`--weights-disk-tier`) can serve routed weights, but it reads them a layer at a time
The file tier (`weights-disk-tier: true`) can serve routed weights, but it reads them a layer at a time
and a step is then paced by the drive; pinned host memory does not close the gap on a 64 GB host.
At four bits an expert unit is 2.42 MiB instead of 4.69, the per-rank share is ~29 GiB, and that
fits VRAM plus a few GiB of pinned host.
@@ -25,7 +25,7 @@ bf16 model over the same 83K positions ([TOOLS.md](TOOLS.md#the-kl-mode)):
| | all: mean KL | all: top-1 | text + assistant: mean KL | text + assistant: top-1 |
|---|---|---|---|---|
| int4 `-8..7`, round to nearest, E4M3 trunk (`qwen4exp-w4-hc8m.recipe`) | 0.1357 | 90.35% | 0.0440 | 92.46% |
| int4 `-8..7`, round to nearest, E4M3 trunk | 0.1357 | 90.35% | 0.0440 | 92.46% |
| `w4nla8h` experts, GPTQ | 0.1098 | 91.36% | 0.0363 | 93.30% |
| + int8 W8A8 trunk | 0.0841 | 92.46% | 0.0277 | 94.07% |
| + int8 lm_head | 0.0830 | 92.84% | 0.0265 | 94.54% |
@@ -97,15 +97,17 @@ The first two differ only in the transform. The plugin reads the first expert's
(`rad_weight_encoding`) and declares the matching kernels; a kernel that does not read an encoding
is not a candidate for it, so a rotated container cannot be served unrotated. The container holds
nibbles in canonical order, and libr4d reorders each row into its unpack order at load. The
activation side is `had_quant_act_fp8` / `gated_had_quant_fp8`: the ordinary fp8 quantisers with
`r4d_fwht_wave<128>` between the load and the absmax, at no cost, since the kernel's mapping (one
wave per 128-column group, four consecutive columns per lane) is already the transform's.
activation side is rotated by the same 128-wide transform between the load and the absmax: on an
int8 trunk `had_quant_act_i8g` and `gated_had_quant_i8g` (the experts read at the `a8i8h` dtypes),
on an E4M3 one `hc_read`'s rotated copy (`rq`). In libr4d the transform is `r4d_fwht_wave<128>`,
at no cost, since the kernel's mapping (one wave per 128-column group, four consecutive columns per
lane) is already the transform's.
**The residual factor is not split.** `H` is symmetric, so `<Hw, Ha> = 128 <w, a>`, and the
quantiser folds the whole factor of 128 into the **stored weight scale** (`bf16(amax/7) / 128`).
The int8 rotated ops fold `1/sqrt(group)` into each side; these fold nothing at runtime. This is
normative in `docs/OPS.md` (*Quantisation and rotation*, the `group` parameter under the `had_*`
FP8 forms), which also states the cost of splitting it.
normative in `docs/OPS.md` (*Quantisation and rotation*, the `group` parameter under the rotated
E4M3 form), which also states the cost of splitting it.
## The w4nl codebook
@@ -227,13 +229,13 @@ A second moment is robust to the small perturbation the first container's error
activation, which is what makes step 2 valid.
**The production recipe calibrates the checkpoint as it ships instead.** Converted without a
recipe, Flash-Next is a 335 GiB bf16 container, which `--weights-disk-tier` serves on two cards by
recipe, Flash-Next is a 335 GiB bf16 container, which `weights-disk-tier` serves on two cards by
reading each routed layer's non-resident experts from the container per pass (GUIDE.md §4.3). Its
tap reads the bf16 activation with no upstream layer quantised and writes Hessians in the model's
own domain, which a rotated recipe's GPTQ rotates into its own; experts are whole per rank. A step
reads about 100 GiB per rank from the drive and grows slowly with what it carries (50 s at ~32K
tokens, 59 s at ~55K), so use large prefill steps: `--max-num-batched-tokens 65536
--max-num-seqs 64`, about 96 requests in flight, and a KV pool that holds 64 sequences' recurrent
tokens, 59 s at ~55K), so use large prefill steps: `max-num-batched-tokens: 65536`,
`max-num-seqs: 64`, about 96 requests in flight, and a KV pool that holds 64 sequences' recurrent
state. That records ~930 tokens per second, ten million tokens in three hours.
**The corpus must look like the traffic.** A few thousand tokens of one repeated sentence gives a
@@ -248,21 +250,23 @@ the in-sample/held-out gap drops from up to 3% to under 1% on gate_up, and a 113
layer 47's down GPTQ at 0.49x RTN where 1.8M tokens say 0.60x.
```sh
# 1. the uncalibrated container: the recipe's expert rule is rtn, int4 g128 rotated
rad-convert <checkpoint> -o model-absmax.rad --recipe data/recipes/qwen4exp-w4.recipe
# 1. the uncalibrated container: a --quant rule rounds the experts to nearest (int4 g128 rotated)
# ahead of the recipe's own expert rule. That rule names calib=$CALIB, and an unset variable is
# refused, so CALIB names a directory here too (an empty one)
CALIB=<empty dir> rad-convert <checkpoint> -o model-absmax.rad \
--recipe data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe \
--quant 'blk.*.ffn_*_exps.*.weight=rtn:codes=i4,group=128,scale=bf16,transform=fwht128'
# 2. the calibration run. Stops at RADIANCE_CALIB_TOKENS (default 65536) and writes once.
# 2. the calibration run, with model-absmax.rad as the model in radiance.yaml. Stops at
# RADIANCE_CALIB_TOKENS (default 65536) and writes once.
RADIANCE_CALIB_DIR=<calib dir> RADIANCE_CALIB_TOKENS=65536 \
radiance --model model-absmax.rad ...
radiance --config radiance.yaml
# ...then drive prompts at max_tokens=1 until it prints
# radiance: calibration wrote layer Hessians after N tokens to <calib dir>
# 3. the calibrated convert: a --quant rule ahead of the recipe's own puts the experts through
# GPTQ against calib=$CALIB (a recipe whose expert rule names calib=$CALIB itself, as the
# production one does, needs no --quant)
# 3. the calibrated convert: the recipe's own expert rule runs GPTQ against calib=$CALIB
CALIB=<calib dir> rad-convert <checkpoint> -o model-gptq.rad \
--recipe data/recipes/qwen4exp-w4.recipe --reuse model-absmax.rad \
--quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB'
--recipe data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe --reuse model-absmax.rad
```
`--reuse` in step 3 copies every weight whose encoding, quantiser and options did not change (all
@@ -295,6 +299,16 @@ overfits and can lose to rounding, hence the threshold; 0.6% of the routed rows
per-layer sync roughly halves a disk-tier recording's throughput, so the per-expert sets are
recorded from a million tokens.
**Unsloth's imatrix sees super experts this corpus does not.** `imatrix_unsloth.gguf` (llama.cpp's
format, 829,440 tokens in raw 18K-token chunks from position 0) records the routed experts per
expert. Its `gate_up` diagonals agree with the 10M-token Grams at every layer (cosine 0.98-0.99),
as do the `down` spikes at layers 46 and 47. At layers 2, 4, 9, 14, 16, 25, 30 and 32 its `down`
spike channels sit at a flat channel's share in radiance's Grams: those super experts never fired
on the chat-templated corpus. Either raw-text chunks trigger what templated traffic does not, or the
two implementations compute those experts differently; it is not settled. Unsloth's GGUFs keep
`down` at Q8_0 in exactly the five layers whose super expert carries the most energy (47, 4, 2, 46,
30).
About the tap's numbers:
- **The gate_up tap is the unsorted activation and loses nothing.** Every token is routed to exactly
@@ -354,18 +368,11 @@ mistyped directory is a message, not a silent quality loss.
planes, both M bands, through the relayout the loader runs.
- `r4d_selftest --case moe_gemm_w4a8_mod4`: the four-class op against the two-class one byte for
byte, and against a host decode with every class at its own geometry and one of classes 1 to 3
the only wide one, as ranks 1 to 3 of four hold them; `--case moe_gemm_fp8a8_mod4` is the same
host decode at block fp8.
the only wide one, as ranks 1 to 3 of four hold them.
- `quant_test`: **GPTQ against the objective it minimises**, `||X (W - W')^T||^2 = sum over rows of
e H e^T`, not rel_l2 on the weight (error feedback deliberately makes the weight worse in the
plain sense). The control is no Hessian at all, under which `gptq` must produce `rtn`'s planes
byte for byte.
- `r4d_selftest --case had_quant_act_fp8`: every format against the exact f32 dot product, the only
way to see whether the quantiser's `fwht_inplace` and the device's `r4d_fwht_wave` are the same
transform, and whether the kernel decodes `w4nl` codes as their table entries. On a source with
outlier channels: 0.2015 (`w4a8`), 0.1307 (`w4a8h`), 0.0991 (`w4nla8h`, round to nearest at
amax / 22), 0.0761 (`w4nl64a8h`), 0.0625 (`w4nl32a8h`) and 0.0469 (`w5nl64a8h`); the negative
control (rotate the activation, not the weight) measures 5.32.
- `relayout_parity_test`: the `w4nla8h` plane's stored bytes pinned, its inverse giving back the
codes and the table, and a container quantised against another sixteen-entry table refused at
relayout; the same for `w4nl64a8h`, `w4nl32a8h` and `w5nl64a8h`, with a second level other than
+29
View File
@@ -0,0 +1,29 @@
# W6NL routed experts: candidate implementation
`w6nl64a8h` is a six-bit scalar codebook for the routed experts' down projection. It is a candidate format, not a claim that six-bit down improves task quality. `data/recipes/qwen4exp-u4-w6nl-bf16ple.recipe` pairs it with U4 trellis gate/up and preserves the existing U5 trunk, protected BF16 experts, BF16 PLE/vision and draft recipe. The format needs this branch's Radiance build; an older build must not be expected to serve it.
## Format
The canonical weight is an affine `u6` code plane with a 64-entry `f32` table, `fp8_e4m3` scales per row per 64 columns and one `f32` scale above them, with the `fwht128` transform. The first 32 table entries are positive E4M3-exact magnitudes and the second 32 their negatives. Bit 5 is sign; bits 0–4 select the magnitude. The fixed upper scale is `2^-13`; the quantizer folds the unnormalised Hadamard's `1/128` into the weight scale.
The container's six-bit codes are packed LSB-first. At load, `libr4d` arranges each row as the permuted low nibbles followed by two bit planes (the high magnitude bit and sign). Both arrangements occupy `6*K/8` code bytes per row. The kernel expands the two 16-entry halves of the magnitude table to E4M3, selects between them and merges sign before the existing FP8 WMMA. The loader checks the entire table, the fixed upper scale, transform and shape; same-width encodings with different semantics are refused.
A trellis gate reads rotated INT8 activations; W6NL down reads a separately quantized rotated E4M3 gated intermediate, like W5NL. The architecture must select that producer and the W6 kernel for the down projection. The BF16 protected experts retain their separate path.
## Codebook pilot
The candidate table is fitted, not derived from the evaluation prompts. `tools/fit_w6nl.py /path/to/original-bf16-checkpoint` reads only selected BF16 safetensor rows; it does not load or serve a model. It samples five experts per layer, 128 rows per expert, and FWHT-rotates weights in groups of 128 before normalising each group of 64 by its absolute maximum. Fit layers are 0, 8, 16, 24, 32, 40 and 47 (2,867,200 weights); separate check layers are 4, 12, 20, 28, 36 and 44 (2,457,600 weights). The script fits a 32-magnitude symmetric grid and chooses distinct E4M3-representable values.
On that separate weight sample, normalised scalar MSE with one globally optimized scale per table was approximately 0.000305 for W5NL and 0.000103 for this W6NL candidate. This is **not** a GPTQ, activation-weighted, KL or task result. It does not establish model quality or prove the candidate's table is optimal.
A separate 41,600-group sample had candidate pre-rounded group scales between 0.136 and 1.160 in E4M3 units under the fixed upper scale, with none subnormal or above the format's maximum. This does not cover every expert; check saturation and fallback reports during actual conversion.
## Checks and limits
The host tests cover W6NL GPTQ on a synthetic BF16-domain Gram, all 64 code values, exact table/scale checks, packing and reference math. The synthetic GPU tests exercise all 64 codes, sorted and token-order inputs, two/four classes and decode/prefill forms; they do not load a model. The U4/W5, U4/W6, U5/W5 and U5/W6 graph declarations are checked for both TP ranks.
A `rad-convert --plan-only` pass over the BF16 checkpoint declared 51,489 weights and estimated about 170.26 GiB for the candidate recipe. The plan used placeholder calibration paths and wrote no model: it validates neither the downloaded Grams nor conversion.
For a synthetic TP2-shaped down-projection latency comparison, run `r4d_selftest /path/to/libr4d.so --perfw6nl M [iters] [experts] [top_k]`. It compares W5NL and W6NL using the same routing and resident, synthetic weights, with automatic and pinned launch forms; byte-parity checks compare launch forms **within** each format, not W5 values to W6 values. Repeated synthetic kernel timing is not end-to-end model throughput.
These tests are not an end-to-end model validation. No full W6 model has been converted or scored; mixed-model inference, model throughput, placement, and speculative parity require separate validation. The main calibration directory must be reassembled and verified before conversion, with the separate draft Gram directory supplied as `MTP_CALIB`.
+939
View File
@@ -0,0 +1,939 @@
# Multi-model serving
One radiance process serves any number of models behind one HTTP endpoint. A YAML file names the
models; requests pick one by their `model` field; the process loads, parks and unloads models as
requests arrive, moving each model's weights between VRAM, pinned host RAM and disk. Models that fit
side by side stay resident together and run concurrently.
This document is the design. Source comments cite its section numbers. `spec.md` is still the engine
specification; this document says where multi-model serving changes it.
---
## 1. Decisions
| Question | Answer |
|---|---|
| Workload | Mixed: co-resident throughput and fast swaps both matter. |
| Process model | **One process, many `Engine`s.** No worker processes (§3.1). |
| Model kinds | Every kind radiance serves: text and vision LLMs, embedders and rerankers, image, video, speech, music and shape generators, ASR. |
| Configuration | **YAML only.** The command-line flags are removed from the server binary; their names live on as YAML keys (§4). Ships as 2.0.0. |
| Hot reload | Yes: SIGHUP or `POST /admin/reload` re-reads the file; changed models drain and reload, the rest keep serving (§10). |
| Memory | Each model has a **fixed** part and **flex** parts. All flex (KV blocks, offloadable experts) draws from one shared pool per card (§6). |
| Flex reclaim | **Strict priority.** A higher-priority model takes flex from a lower one even while it is busy; the victim's running sequences are preempted and recompute when they resume (§6.4). A tiered MoE's expert flex goes back first, to any model (§6.7). |
| Eviction | Pinned models never leave; then lower priority first; ties by least-recently-used weighted by reload cost; optional idle TTL (§8.3). |
| Parking | Per model: what stays in VRAM, and whether a RAM copy is required, allowed or never kept. RAM copies beyond that are kept opportunistically and dropped first under pressure (§7). |
| Cards | The YAML gives each model's TP degree; the scheduler picks the cards (§8.4). |
| Contention | A model leaving VRAM is drained first, bounded by a max wait. Flex reclaim preempts (§6.4). |
| Warm-up | Every model loads once at start, lowest priority first, giving way to requests (§8.6). A parked model can serve while its weights move back (§7.4), and an embedding model serves in place when its cards lack room (§7.5). |
| Shared cards | Concurrent queues: measured against time-sliced steps, which lost everywhere and were removed (§9). |
| Load wait | Requests wait up to a timeout, then 503; streaming clients get SSE keepalive comments meanwhile (§8.2). |
| Adapters | Addressed as `base:adapter` (§5.3). |
| Groups | `together` and `exclusive` co-residency rules (§8.5). |
| Hardware | Discrete multi-card hosts (two R9700 on the test host, §13), unified-memory APUs (gfx1151), and arbitrary public machines. |
---
## 2. Terms
- **Fleet**: the process-level owner of every model, card and budget. One per process.
- **Model entry**: one `models:` item in the YAML. It has a name, a config and a state.
- **Engine**: today's `rad::Engine`, one per *loaded* model entry. It owns its TP ranks, pools,
scheduler and step loop.
- **Card ledger**: the per-card account of VRAM: who holds what, fixed or flex, committed or only
reserved.
- **Fixed**: the bytes a model cannot serve without: non-expert weights, the activation arena, its
queues and staging, and a floor of KV (one sequence at its context bound unless the YAML says
more).
- **Flex**: bytes that make a model faster or wider but that it can give back while serving: KV
blocks above the floor, and expert-slab slots above the planner's floor.
- **Park**: take a model out of VRAM but keep it ready to come back fast: its RAM copy, its compiled
state and its address reservations stay.
---
## 3. Process architecture
### 3.1 Why one process
Process-per-model (the llama-swap shape) was the first idea. It loses on three points:
1. **Queue teardown on a busy card.** On RDNA4, a process exiting while another process keeps the
same card busy can make the MES firmware fail `REMOVE_QUEUE`; the driver then mode1-resets the
card and every process on it loses its VRAM. Unloading by exiting a process is exactly that path.
2. **Shared memory accounting.** Flex lending between models and same-address parking (§7.2) need one
owner of each card's VRAM. Across processes that owner would need IPC handles and a VRAM broker.
3. **Fast swap.** A worker process has to redo plugin loading, kernel selection and code-object loads
on every cold start. In one process they are done once per architecture.
The price: a GPU memory fault, which is not recoverable in-process (spec §17), ends every model at
once. The container's restart policy brings the fleet back (§11).
### 3.2 Shape
```
+-------------------------------------------+
HTTP ----> Front | Fleet |
(one port, | - model entries + state machine (§8.1) |
auth, | - router: model field -> entry (§5) |
routing) | - load queue, eviction, groups (§8) |
| | - card ledgers + flex pools (§6) |
| | - host RAM ledger, park store (§7) |
v +-------------------------------------------+
per-model Front state | owns
(limits, tokenizer, v
template, metrics) Engine A (tp 2, cards 0,1) Engine B (tp 1, card 1) ...
rank threads + stepper rank threads + stepper
```
Every engine keeps its own scheduler, step loop and rank threads, as today. The fleet adds no work to
the step path: it changes budgets between steps through the hooks the engines already poll
(`loan_tick`, `tier_tick`) and it drains and parks engines through explicit calls.
### 3.3 Process-wide state that must become per-engine
What a second `Engine` in the process needed made per-engine, by fix:
| State | Where | Fix |
|---|---|---|
| Kernel registry: load, select log, device facts, instances; `~Engine` closes it for everyone | `core/build/startup.cpp`, `core/plugin/registry.h`, `loader.cpp`, `select.cpp`, `engine.cpp` `~Engine` | Split into a **loaded set** (process service, loaded once, never closed while an engine lives) and a per-engine **selection context** (device facts, code device, log, instances to fini). |
| Arch plugin model state `g_model[MAX_RANKS]`, indexed by TP rank (30 plugins) | `arch/*/*.cpp`, `arch/common/rad_arch.h` | ABI: `RadBuildCtx::slot` and `rad_slot(RadCtx*)`, a process-unique instance slot. Plugins index their state by slot, not rank. A plugin that does not set `RadArchProbe::multi_instance_ok` may back one engine only; the fleet refuses a second engine on it by name. |
| libr4d all-reduce rendezvous `g_rv` and instance cache `g_cache`, keyed without engine identity | `libr4d/r4d_ar_entry.hip` | Kernel `init` receives a `group` parameter (process-unique TP group id) through the existing `RadParam` list; rendezvous and cache are keyed by it. No signature change. |
| libr4d/libr3d split-counter and scratch caches allocated with `hipMalloc`, never freed, some shared across streams | `libr4d/*.hip`, `libr3d/*.hip` | Keyed by stream, released by the kernel's `fini` when the owning engine goes; `s_scratch_pool` becomes per stream. |
| `hc_mix_ctr` four slots per device; `g_rg_blocks` one block per device | `libr4d/r4d_hc_bf16.hip`, `libr4d/r4d_moe.hip` | Pool per device with release on `fini`. |
| Device fault flag, single fault signal, global stall verdict | `core/device/aql.cpp` | Fault domain per card set; stall verdict per engine. A memory fault still ends the process (§11). |
| DMA link gate `held` flag per card | `core/device/aql.cpp` `a_link_hold` | Refcounted holders. |
| Per-thread HSA interrupt signals never destroyed | `core/device/aql.cpp` `thread_signal` | RAII `thread_local` owner. |
| Log rank tags global; no model tag | `core/util/rad_util.cpp` | `thread_local` model tag set on each engine's threads; lines read `[model/r0]`. |
| StallWatch: one last-line clock, one report slot | `core/util/stallwatch.cpp`, `rad_util.cpp` | Per-watch beats; a mutex around the report. |
| `g_signalled` + `sigaction` per `serve()` | `core/engine.cpp` | One process signal hub owned by the fleet. |
| Server built on `run_server`'s stack, one per engine | `core/engine.cpp`, `core/server/*` | One `Front` (§5); engines expose their bridges as objects. |
| `calib_staging` per-rank pinned map, never freed | `arch/common/rad_arch.h` | Keyed by slot, freed on close. |
---
## 4. Configuration
### 4.1 One file
```
radiance --config /etc/radiance/fleet.yaml
radiance --config fleet.yaml --check # parse, validate, plan; serve nothing
```
The server binary takes no other flags (`--help` prints the key reference). The graph dump
(`debug-graph: true`) and the offline modes run one model from a one-model file (§4.4). Every former flag is a YAML key with the same name and no
leading dashes, at the level it belongs to (§4.3). Values keep their meaning, units and validation:
the YAML loader feeds the existing parser, so a key and its flag can never drift.
### 4.2 Example
```yaml
# fleet.yaml
server:
host: "::"
port: 8000
api-key-env: RADIANCE_API_KEY
cards: all # or a list of card indices; models never leave this set
memory:
gpu-headroom-mib: 160 # per card, as before
host-mib: 40960 # pinned host RAM the fleet may hold: parked weights, KV host tier, pools
disk-tier: /var/cache/radiance # prefix-cache disk tier and park files
defaults: # merged under every model; a model's own keys win
kv-cache-dtype: i8
max-model-len: 200000
models:
qwen:
model: /models/qwen3.8-27b-iq8r-dflash.rad
aliases: [default]
tp: 1
priority: 100
pin: true # never leaves VRAM
max-num-seqs: 8
flex:
kv: { min-tokens: 200000, weight: 1 }
park: { ram: required }
flashnext:
model: /models/qwen3.8-next-flash-iqr-v4.rad
tp: 2
priority: 50
placement: expert_tiered
num-speculative-tokens: 3
park: { vram: none, ram: allowed }
ttl: 30m
flux:
model: /models/flux-3-klein-iq8r.rad
tp: 1
priority: 10
park: { ram: never } # reload from disk; never hold RAM for it
embed:
model: /models/embeddinggemma2.rad
tp: 1
priority: 60
max-num-seqs: 64
groups:
rag: { together: [qwen, embed] } # load embed whenever qwen loads, and the reverse
big: { exclusive: [flashnext, flux] } # never resident at the same time
scheduler:
load-timeout: 120s # a request waits this long for its model, then 503
drain-timeout: 30s # a model being evicted gets this long to finish its requests
keepalive: 10s # SSE comment interval for streaming requests waiting on a load
stuck-exit: 60s # a device that advances nothing this long ends the process; 0 never
warm-up: true # fill free VRAM, then host RAM, with models at start (§8.6)
```
### 4.3 Levels
| Level | Keys |
|---|---|
| `server:` | `host`, `port`, `api-key`, `api-key-env`, `allow-host`, `trusted-proxy`, `http-threads`, `read-timeout`, `write-timeout`, `keep-alive-timeout`, `max-body-mib`, `retry-after`, `no-cors`, `live`, `log` (`info`/`debug`/`trace`), `radiance-home`, `kernels`, `download-dir`, `proceed-with-incompatible-configuration`, `debug-accept-reference-kernels` |
| `cards:` | `all` or a list of card indices |
| `memory:` | `gpu-headroom-mib`, `gpu-memory-mib` (per card), `host-mib`, `host-headroom-mib`, `disk-tier` |
| `scheduler:` | `load-timeout`, `drain-timeout`, `keepalive`, `stuck-exit`, `warm-up` |
| `defaults:` / `models.<name>:` | every per-model flag: model source, TP, placement, KV, scheduler, spec decode, LoRA, request defaults and limits, media limits, offline modes, debug; plus the fleet keys `aliases`, `priority`, `pin`, `ttl`, `flex`, `park` |
| `groups:` | `together` / `exclusive` lists |
A key at the wrong level is refused with the level it belongs to. An unknown key is refused with
the closest known key. `served-model-name` is gone: the entry's name is the model id, and `aliases`
adds more.
### 4.4 Single-model use
A one-model YAML is the only way to run one model too. `radiance --model X ...` is refused with a
message that prints the equivalent YAML, so a migration is copy and paste. Offline modes (KL
recording, calibration, the diagnose workload) run from a one-model YAML with the `kld-*` /
`calib-*` / `diagnose` keys on that model;
the process does that job and exits, as today.
### 4.5 Provenance
The startup report keeps its per-option rows. Each row's source is the YAML path it came from
(`models.qwen.max-num-seqs`, `defaults.kv-cache-dtype`) or `auto` for a decision. Global rows print
once; each model's rows print under its name.
---
## 5. The front
### 5.1 Split
`ServerOptions` splits into **ListenOptions** (process: bind, auth, hosts, proxies, CORS, timeouts,
body size, threads) and **ModelFront** (per model: limits, default sampling, template kwargs,
tokenizer, chat template, grammar compiler, modality bridges, metrics, queue). `Deps` moves into
ModelFront. The bridges that `Engine::run_server` builds on its stack become engine-owned objects
the front borrows while the model is loaded.
### 5.2 Routing
1. The router reads the body's `model` before any parsing; multipart bodies (transcriptions) read the
form field. The parsers then run against that model's `ModelFront`.
2. `model` resolves through names and aliases. A request without `model` goes to the model named
`default` (by name or alias); with no such model it is refused.
3. A modality route checks the resolved model serves that modality (an image request to a text model
is a 400 naming what the model serves), so `/v1/images/generations` with no `model` resolves to
the only image model when there is exactly one.
4. The resolved entry is **acquired**: the request holds a reference that keeps the engine from being
parked under it. If the entry is not resident, the request waits on the load (§8.2).
A finished video or shape is answered by the front itself, by its id: the model that made it may be
parked or unloaded the moment it is done, and a poll or a download is no reason to bring it back. It
stays until it expires, as a video kept by its server does.
### 5.3 Adapters
LoRA adapters are addressed `base:adapter`. `/v1/load_lora_adapter` takes `base` explicitly. The
`:` is reserved in model names and aliases. A model's control-vector variant
(`control-vector-variant`, GUIDE §4.10) is addressed and listed the same way, `base:NAME`.
### 5.4 Fleet-wide routes
- `/v1/models` lists every entry and alias with `state` (`resident`, `loading`, `closing`, `parked`,
`cold`, `failed`), `kind`, `tp`, `cards`, and its adapters as `base:adapter` children.
`/admin/fleet` adds `waiting` for a model that waits for room (§8.1).
- `/health` is the process (200 once the front listens); `/health?model=NAME` is that model.
- `/metrics` carries a `model` label on every per-model series, plus fleet series: per-card
committed fixed/flex bytes, parked bytes, loads, parks, evictions and their durations.
- `/stats`, `/sessions` and the dashboard take `?model=`; the dashboard grows a fleet page.
- `/admin/models/NAME/{load,park,unload,pin,unpin}`, `/admin/reload`.
---
## 6. Memory: fixed, flex and the card ledger
### 6.1 Today
Each engine claims its card once: `vram_budget_resolve` splits the free VRAM into a weights pool
(one `hipMalloc`), a KV pool (a VMem reservation committed whole), and the activation arena (one
allocation). Pools are bump-allocated and never shrink. The mover lends unused KV and arena bytes to
the expert slab *at addresses the lender already owns* (`core/place/mover.h`). That lending is the
prototype of flex: it has one borrower (experts) and one model.
### 6.2 Address reservation, physical commit
Every pool of every engine becomes a VMem reservation sized for the engine's *largest* configuration.
Physical memory is committed in granules from the card's ledger and decommitted back to it. Virtual
address space is cheap and stays reserved for the model's whole life, loaded or parked, so:
- **parking keeps addresses**: weights decommitted and later recommitted land at the same device
addresses, so weight tables, residency tables, recorded tapes and plugin pointers stay valid. A
restore is commit plus copy, never a re-publish or re-declare;
- **flex is real**: a KV pool or expert slab grows by committing granules at its top and shrinks by
decommitting them, and the bytes go to another model on the same card.
The fleet requires VMem on every card it shares between models. Where the driver lacks it, a card
can host exactly one model with today's static pools, and the startup report says so; there is no
silent fallback.
### 6.3 Ledger
Per card, the ledger holds `capacity − headroom − already_held` and accounts for every committed
granule as one of:
- **fixed(m)**: model m's fixed part, committed while m is resident;
- **flex(m)**: model m's flex above its floor;
- **transit**: staging for a load or park in flight.
A model is admitted to a card set when `fixed(m) + floor(m)` fits beside the resident models' fixed
parts and floors. Flex is never a reason to refuse a load; it is reclaimed (§6.4).
The flex floor and weight come from the YAML `flex:` block (`kv: {min-tokens, max-tokens, weight}`,
`experts: {min-mib, max-mib}`). The default floor is one sequence at the model's context bound, which
is today's KV minimum.
That bound is worth setting for an image generator. Unset, it is the generator's largest pass
(Qwen-Image 2.1: 33600 rows), so the floor is that many rows of conditioning keys and values, 8.2 GiB
a card at `tp: 2`, which every restore has to find room for. Text-to-image prompts need a few hundred
rows, and `max-model-len: 2048` takes the floor to about 0.5 GiB a card. Set it to cover the longest
conditioning the deployment sends: a 1024 x 1024 reference picture adds about 4600 rows. In the
§13.1 fleet (text-to-image at 768 x 768) this took the sequential plan from 89.8 to 81.9 s.
### 6.4 Reclaim by strict priority
When a model needs granules (a load, or its own flex growth), the ledger takes them in this order:
1. uncommitted capacity;
2. flex of models with **lower priority**, lowest first, idle models before busy ones at equal
priority;
3. eviction of a lower-priority model's fixed part (§8.3).
A model never takes flex from an equal or higher priority model; it waits for them to release it.
Nor does it displace a higher-priority model, even an idle one (§8.3), so a model whose room only
higher-priority models hold waits out `load-timeout`: with priorities on the small models of a
fleet, MiniMax-Music3 and Hunyuan3D-2 did. A fleet in which every model should be reachable gives
its entries no `priority`, and the least recently used gives way.
The one exception is expert flex (§6.7): it grew into memory nobody held, and giving it back costs
an address change per unit, so any model's room comes out of it first, whatever its priority.
Taking flex from a model:
- **expert slots**: units in reclaimed slots drop to their host copy (`Mover::reclaim`, as the KV
lender does today). This is an address change in the residency table, no copy;
- **free KV blocks**: decommitted directly. The block free list is a min-heap, so free blocks
already sit at the top of the pool where decommit reaches them;
- **held KV blocks**: the sequences holding them are **parked**: the scheduler stops them at a step
boundary, publishes their computed prefix into the prefix cache, the idle tier writes those blocks
to pinned host (`TierExec` gather, outside the scheduler lock), and the VRAM blocks are freed. The
sequence goes back to the queue head; on resume, admission restores the prefix from host like any
cache hit and only the uncached tail is recomputed. Linear-state models (GDN, Mamba) park through
the same path with a checkpoint snapshot at the parked boundary.
This replaces recompute-only preemption for reclaim. A prefix-cache hit already restores a host
entry in one batched pass per chain, so a parked sequence costs one D2H and one H2D of its own
blocks.
As built, the sequences holding reclaimed blocks are preempted and recompute when they resume
(`KVManager::set_flex`'s preemption); parking them through the prefix cache is not done (§12).
A reclaim takes from the prefix cache only what the floor lets the fleet have: a cache at its floor
gives nothing however empty it is, so it keeps its conversations. Entries go least recently used
first and stay restorable from their host copies.
### 6.5 Host RAM ledger
One pinned host budget (`memory.host-mib`) covers: parked weight copies (§7), the KV host tier, the
expert host pools of tiered models, and the transit buffers. Unset, it is three quarters of the
host's memory, or of the tightest memory cgroup the process sits in (a container's `--memory`),
whichever is less. The room a load or park may take at a moment is the host's available memory, or
less where such a cgroup leaves less, and a park never leaves less than 8 GiB of it. The KV host tier is shared between
models under the same eviction order as parked weights, so RAM goes to whatever is most likely to be
needed next. Host pinned memory is locked in pieces (`hsa_amd_memory_lock_to_pool`), so the ledger
grants and returns it in pieces too.
A load counts what it will pin before it waits for its VRAM: its pools, the tables placed in host
memory and the buffers startup pins beside them. Other loads and parks leave that room alone until
the load ends, and the load checks once more before it pins. An embedding left to its default goes on
the card when the host cannot hold it, and the VRAM ask includes it then; a placement asked for that
cannot be had fails the load, since pinning past the host's floor gets the process killed by the
kernel.
A load that waits for that room logs `model NAME: waiting for N of host memory to pin (...)` and
shows as `waiting` with `waiting_for: "host memory"` (§8.1). Once every other model is unloaded
and none is coming or going, nothing is left to give memory back, so it logs
`... is not there with every other model unloaded ...` and gives up the wait instead of sleeping
until `load-timeout`.
### 6.6 Unified memory (gfx1151)
On an APU the card ledger and the host ledger are one pool (the budget code already charges pinned
host memory to the VRAM ledger on unified devices). Parking to RAM frees nothing there, so a parked
model keeps its pages and only its *flex* is reclaimable; eviction goes straight to disk. The ledger
reads unified-ness from the device and reports it.
### 6.7 Expert flex
A tiered MoE's claim holds what the host pool cannot (Flash Next on the test host of §13: 23.65 GiB
a card of the 35.97 GiB it could use), and routing reads every other expert over the link or
promotes it into a slot first. The mover already fills slots the KV cache and the activation arena
lend; the fleet is a third lender (`Mover::kLendFleet`):
- at start each rank reserves address space for one slot per pooled expert (`Mover::lendable_bytes`,
no VRAM) and carves it top down like the arena's top, in bytes;
- while the engine is busy (a step in the last 5 s), the step loop asks the broker for a GiB more
(`flex_grow`: free past the headroom, nothing loading, restoring or waiting for room), backs it on
every rank and raises the loan; the next GiB waits until the slab has filled what it holds, so no
VRAM sits empty;
- any model needing room takes it back first (`reclaim_flex`'s first pass, any priority): the units
past the new loan drop to their host copies between steps and the granules are unbacked. The slab
does not grow again for 5 s, so the room is the taker's. A park recalls all of it and unbacks it,
so nothing of it is copied;
- `flex.experts.max-mib` bounds the experts' VRAM on a card, the claim's share included; `0` keeps
the slab at its claim.
When a busy slab finds no free memory (`expert_flex_wanted`), a neighbour on its cards that has been
idle for at least 30 s and thirty times its way back parks just what the slab wants (one neighbour
at a time, each at most once a minute; not a pinned model, not one of higher priority, not one that
may not park in RAM, not a together partner). Its next request restores it and takes the room back
from the slab first. The bar is that high because the neighbour's next request pays a restore, and
the slab's gain (§13.2) is a few percent at one client, more under load.
---
## 7. Parking and restore
### 7.1 What a model holds
| Piece | Resident | Parked | Cold |
|---|---|---|---|
| Arch selection, kernels, code objects, tapes, tokenizer, template | kept | kept | dropped (cheap) |
| VA reservations | kept | kept | released |
| Non-expert weights | VRAM | unmapped; read again from the container | disk |
| Experts | slab + host pool | slab unmapped, read again from the container; host pool kept | disk |
| KV pool | committed | decommitted, and the prefix cache reset: a conversation's next turn prefills again | released |
| Arena, staging, queues | committed | decommitted; queues kept | released |
Queues are kept across a park and an unload: destroying a HW queue next to a busy card is the risky
path (§3.1), so a closed stream's queue stays open for the card's next stream. An open queue holds
about 41 MiB of its card (the context save area), and opening one on a full card can stall the
process for minutes, so the fleet opens queues only while a card has room: eight to a card at the
start, and before each load as many as bring the kept ones back to eight, up to 24 open on a card.
Kept queues are closed in two places, both where no other model has anything on the card: down to
eight when an unload leaves the card empty, and down to four for a model that is short of exactly
their memory after every other model has left (MiniMax-H3 on a 32 GB card). `/admin/fleet` gives
each card's `queues` and `queues_idle`.
### 7.2 Park
An engine's large device allocations (`rad_dev_alloc` of `kPageMin` and up inside an engine's
scope) are reserved address space mapped in 64 MiB chunks (`core/device/paging.cpp`), so a park takes
off exactly what the room needs, card by card: a partial park unmaps only the chunks it takes and the
model stays parked with the rest still on its cards; a later park takes more ("parked further").
1. Stop admitting; drain running requests up to `drain-timeout`; hold the step loop.
2. Recall the expert slab's loans; drop slab units that have another copy; mark the KV cache, empty
slab stretches and the activation arena above its fixed region (transients, dead between steps)
as having nothing to keep (`dev_page_discard`).
3. Page out, cheapest chunks first: nothing to keep (unmapped), the weights pool (unmapped: its
container is its copy, see below), a copy that is still exact (unmapped, or swapped), a copy
exact but for a few dirty blocks (only those copied), then copies: to host memory while the host
budget lasts, then straight to the disk tier (O_DIRECT, four writers). A chunk of any other
allocation the load filled verbatim from the container is first read back and compared with it;
when it matches, nothing is written and the container is its copy.
**Weights come back from the container, never from a copy.** A model loaded from a container marks
its weights pool as refilled by its owner (`dev_page_refilled`): a park unmaps the pool's chunks
with nothing copied, to host memory or to disk, and a restore maps them back empty and hands them to
the engine, which reads every weight with a byte in them from the container again and lays it out
for its kernels at its current address (`Engine::refill_weights`): the load's own sweep and
relayout pool, for those weights only, every write clipped to the memory paged back empty, so the restore
of a fully parked model costs about what its load's read did. The refill holds up to
`Engine::kRefillHost` (4 GiB) of host memory while it runs (staged inputs, output buffers, the
sweep's pinned windows), which the fleet keeps room for before a restore. An expert unit the mover moved into a slab slot is read for that slot (its
residency), and a unit the park dropped from the slab is not read at all. Nothing is written to the
drive for weights, and nothing waits for such a write. A model under runtime adapters (whose
pool is written after the load) keeps the copies described below.
**Host copies are mappings.** Every pageable allocation has a shadow reservation of its size. A
chunk's host copy is pinned host memory mapped at an address (`vmem_commit_host`): at the shadow
while the chunk is on the card, at the chunk's own address while it is out. A park copies the chunk
to the shadow and swaps the two mappings (`vmem_swap`); a chunk whose copy is kept leaves by the
swap alone; a restore copies back through the shadow and swaps again. A parked chunk therefore stays
mapped where the kernels expect it, readable and writable by the card over the link (§7.4).
Copies stay exact across parks for **sealed** memory. The mover calls `dev_page_invalidate` for
every slab slot it writes, which marks the 64 KiB blocks it touched dirty: the copy stays, exact
elsewhere, and the next park rewrites only those blocks.
The `park:` block says what stays:
- `vram:` `none` (default), `statics` (non-expert weights stay), or a size in MiB of the most
first-used weights to keep (the head of the first-use order, which is what progressive warm-up
needs first);
- `ram:` `required` (refuse a park that cannot hold a RAM copy; evict others' opportunistic copies
for it), `allowed` (keep one while RAM is free, drop it first under pressure; the default), or
`never`; a copy of what the park copies, never of the weights, which come from the container;
- `restore:` `auto` (the default: `full`, but a one-step model comes back in place when its cards
lack the room, §7.5), `full` (every byte back on the card before it serves) or `live` (§7.4).
Park or unload: a park that would write more to disk (and read it back) than the model's measured
load takes, or a model whose last page-in plus what this park would write takes more than 1.2x its
load, unloads instead (a model whose container sits in the page cache reloads faster than it
round-trips the disk tier). Waits for room or for requests to drain are not counted: a load waits
for those as well.
### 7.3 Restore
Restore maps device memory for every chunk that is out, at its old address or (for a chunk read in
place from its host copy) at its shadow, then copies back: host copies at once and swapped in, disk
and container copies through one pipeline (eight readers, a ring of sixteen pinned buffers, each
freed when its own copy lands; the drive's rate, 6.9 GB/s on the test host). The weights pool's
chunks come back empty, and the engine reads the weights in them from the container again (§7.2)
before the model serves. Kernels, tapes and tables are untouched because the addresses are.
**Remapping an address needs a full translation flush first.** On kernel 7.1 with gfx1201, copies
into memory mapped again at an address that was mapped before landed nowhere: the chunk read back
its previous owner's bytes or zeros (every disk-tier restore came back corrupted). A map flushes the
cards' translation caches only lightly; unpinning host memory makes the driver flush them in full,
so `dev_settle_maps` pins and unpins one page after a batch of maps (page-in, VMem commits) before
anything writes them. `tests/device_test.cpp` covers the remap, host copies, the disk tier, many
chunks, several allocations of one owner, partial parks and container-backed chunks; each fails
without the flush. `granules_remapped_at_random_never_share_a_page` maps and unmaps granules at
random, so freed pages come back under other addresses: without the flush two live granules shared a
page within 14 to 32 cycles in every run; with it, 23 runs of 3000 cycles found nothing, 20 of them
beside a process polling `rocm-smi` and opening the render nodes, which makes the alias more
frequent.
### 7.4 Serving while it comes back (`park.restore: live`)
With `park: {restore: live}` a restore serves at once (`dev_page_in_live`): everything but the
sealed chunks parked in host memory comes back as in §7.3, and those stay mapped at their own
addresses, read in place over the link. Behind the first requests they move onto the card
(`dev_page_promote`): each is copied to device memory at its shadow while the engine runs, then
the mappings are swapped in a quiet window, a step boundary with every rank's streams drained
(`Engine::run_quiet`); a chunk the engine wrote meanwhile is copied again inside the window. The
fleet counts what is still in host memory as room owed to that card. Promotion that finds no device
memory leaves the rest where it is: the model serves on, slower, partly resident, and the fleet
tries again every 5 s until it is all on the card.
It is not the default, because the link is the bottleneck either way. Measured on the 27B (dense,
decoding, 128 tokens): the first reply after a park takes 5.38 s live against 2.52 s with a full
restore (1.33 s resident). Every decode step reads all the weights still in host memory over the
same link the promotion copies through (it ran at 3 GB/s instead of 27), while a full restore from
host memory already moves them at the link's rate. Live suits a model whose steps read a small part
of what is parked (a tiered MoE's experts: routing touches a few per layer) or that computes long
per byte it reads; a dense decoder is faster restored whole.
Not built: a first step that waits per layer for an upload in first-use order (TTFT
`max(upload, prefill)` instead of the sum; the gain is the first step's compute, large only for long
prompts).
### 7.5 One-step models served in place
An embedding model's request is one step: a pass over the prompt, nothing generated. Such a step
reads each weight once, so reading the weights in place over the link costs it about what a restore
would have cost to move them (EmbeddingGemma2's 1.1 GiB at the link's rate, some 40 ms on the test
host). Waiting for the room costs more: another model's quantum, or a neighbour parked for it.
So a one-step model (`Engine::one_step`) with `park.restore: auto` (the default) that comes back to
cards without room for all of it right now comes back in place: only what is not a sealed chunk
parked in host memory (the KV cache, the arena, written memory) needs room
(`dev_page_out_bytes(owner, live)`), and the weights stay mapped in host memory at their own
addresses, as with `park.restore: live` (§7.4). Unlike a live restore they are not room owed to the
card: the fleet does not hold room for them, a planner counts only what is on the card as what the
model would free, and they move onto the card (`dev_page_promote`) only into free memory, a pass
every 5 s. When the cards do have the room, the model comes back whole, as any other.
---
## 8. Scheduling
### 8.1 States
```
cold --load--> loading --(first layers ready)--> partial --(all ready)--> resident
^ | ^
| evict-to-disk | | restore
+------------------------- parked <---------------park (drain)-----------+ |
+----------------------------------------------+
any --fault/refused load--> failed --(admin load or reload)--> cold
```
`GET /admin/fleet` reports each model's `state`: `cold`, `loading`, `resident`, `closing`,
`parked`, `failed`, or `waiting` for a model that is not serving and waits for room, whatever it was
doing when the wait began (a load, a return from its park). `waiting_for` names the room:
`accelerator` (memory on its cards, §6.3) or `host memory` (memory to pin, §6.5). The number
`waiting` beside them counts the requests queued for the model. The dashboard's history keeps the
state as the figure `s:<id>`: 0 cold, 1 parked, 2 loading or closing, 3 resident, 4 failed,
5 waiting; the page shows `waiting` as "Waiting for room". `vram_bytes_by_card` is what the model
holds on each card now, by card index: its claim and its cache's growth while it serves, what a
park left of it there, or what it has backed so far while it loads.
A wait for room on the cards lasts while their free memory still rises: memory given back is
counted free only as the driver's wipe reaches it, which after the tens of GiB a large model's room
takes is several seconds. When the ledger says the models that may leave do not hold enough, and
none must stay, every model on those cards is parked and then unloaded before the demand fails: a
model also holds memory outside its claim, which comes free only with the model.
### 8.2 Requests for a model that is not resident
The request takes a reference and waits on the entry's load, bounded by `load-timeout` (then 503
with `Retry-After`). A streaming request gets an SSE comment line every `keepalive`, so proxies and
clients keep the connection open. Requests queue per model in arrival order; a model's own
`max-queued-requests` still bounds its queue.
### 8.3 Eviction
When a load needs room, candidates are the resident models without `pin`, sorted by:
1. priority, lowest first;
2. then reload cost × recency: `idle_seconds / restore_seconds`, highest first. `restore_seconds` is
the measured restore time from where the model would go (RAM copy or disk), so a model that comes
back cheaply leaves before one that does not.
A model with an idle `ttl` parks after that long without requests, whether or not room is needed.
Groups bind (§8.5). A busy candidate is drained, bounded by `drain-timeout`.
A model serving requests keeps its cards for a **quantum** after it came on (four times what coming
back costs it, 5-30 s): another model's demand waits instead of evicting it, so a model under load
serves a batch rather than giving its cards back for each request of another. Measured on the c4
plan of §13: 313 s without it, ~230 s with it; aging it out after a waiter's 3 s, or serving
waiters strictly first come first served, were both slower.
A demand whose room is held by something passing (another model's load, restore or park, reserved
room, a model inside its quantum) waits for it rather than failing every request queued for it. A
grant that waits releases the bring-up lock meanwhile, and reserves its room in the same locked
section that found it, so two loads cannot both take it. Two parked models that each need the room
the other's remains hold do not wait on each other: one that has waited 2 s parks the rest of itself
and waits on.
A returning model's room is counted card by card: a model of several ranks that is all out on one
card and mostly still on another needs only its missing part on the second. Asking for the larger
part on every card cannot be met where its own rest still sits, so it waited out the 2 s and parked
the rest of itself to come back (Qwen-Image on §13's seq plan: 5.5 s back, 2.1 s counted per card).
Cold loads beside each other share the drive and the relayout workers, so each took as long as all
of them together (seven models at once: three to twenty times their time alone). One container
sweep over 2 GiB reads at a time, the smallest waiting first; small models never wait.
### 8.4 Card choice
A model asks for `tp: N`. The scheduler picks N cards from `cards:` that minimise evictions (fewest
fixed bytes of lower-priority models displaced), then flex displaced, then prefer cards the model was
resident on before (its RAM copy is per rank and per card's shard; a different card set reuses the
same shards). TP groups that need peer links prefer card sets with P2P. Within an engine's life its
card set is fixed; moving it is an unload and reload.
### 8.5 Groups
- `together: [a, b]`: loading one loads the others; parking one parks the others. A request for any
member waits for all of them.
- `exclusive: [a, b]`: at most one member is resident; loading one parks the others first.
The config check refuses contradictions (a pair both together and exclusive, a together group whose
members cannot fit at once).
### 8.6 Warm-up and host fill
A first request should find its model parked, not cold: a restore from host memory takes a second
or two where a cold load takes the container read and relayout (12.9 s for the 27B).
**Warm-up** (`scheduler.warm-up`, on by default). Once the listener is open, the unpinned models
load one at a time, lowest priority first (later in the file first among equals), so the ones that
matter most are those still on the cards at the end. Each next load waits until the fleet is quiet:
no request waiting, no load, restore or park running. Displacing a warm model later is an unmap:
its weights come back from its container (§7.2). A warm load gives way to everything:
- it takes room only from free memory and from other warm models (a model a request has used
stays, and no parked model unloads for it);
- it does not wait for room, and one that finds none leaves its model cold without an error (a
request that came for it meanwhile asks for it again);
- a request for a warm model makes it an ordinary one.
The warm-up stops for good after a warm load that made another model unload. What a warm load
displaces needs no room elsewhere: a parked model's weights leave by an unmap, and its KV cache and
transients are dropped.
**Host fill.** A parked model whose chunks are only on the drive (a spill, its container) gets
them read into host memory while the fleet is quiet, a GiB at a time
(`dev_page_fill_host`): mapped at the chunks' own addresses, exactly as a park to host memory leaves
them, so its restore copies over the link instead of reading the drive (and a live restore serves
from them in place). The highest priority goes first, then the most recently used. A fill leaves
2 GiB of host room, and room for the refill it runs; these copies have their drive copy, so
`make_host_room` lets them go before anything else. The weights pool's chunks are filled by the
engine (`Engine::fill_host`): host memory is mapped at the chunks (`dev_page_fill_begin`) and the
weights in them are read from the container and laid out into it, as a restore's refill does, with
every write clipped to the batch's chunks (a weight running into the next batch is read for each).
Such a copy is exact until the mover writes the chunk, so a park after the restore keeps it and
leaves by the swap; once written, or dropped for room, the chunk is refilled from the container
again. Nothing of it ever comes from the card.
Parked models also hold pinned host memory that is not weights: the linear-state snapshot store
(4.19 GiB for the 27B, 3.08 GiB for Flash Next), empty once the park has reset the prefix cache.
Under host pressure, and to make room for a fill, a parked model gives it back
(`Engine::release_host_spare`) and its next restore pins it again first: 4 GiB pins in 0.3 s on the
test host, against seconds to read the same GiBs of weights back from the drive. In `make_host_room`
these go after resident models' kept copies and before parked models' host copies.
`GET /admin/fleet` reports `warm_up: {queued, loading, drive_only_bytes}`.
---
## 9. Two models on one card
Two resident models with work on the same card can share it in two ways:
- **concurrent queues**: each engine's stepper submits on its own HW queues and the GPU interleaves
them;
- **time-sliced steps**: a per-card arbiter grants whole steps to one engine at a time, weighted by
priority, with no step issued ahead of the previous one's readback.
Both were built and measured on one R9700 (210 W): MiniCPM5-2B bf16 decoding one
stream, its inter-token latency beside a second workload, twice each, interleaved.
| beside | concurrent p50 / p99 | time-sliced p50 / p99 |
|---|---|---|
| nothing | 12.3 / 12.8 ms | 12.7 / 13.1 ms |
| the 27B IQR-V4 decoding two streams | 25.9 / 27.6 ms | 50.0 / 68.0 ms |
| the 27B prefilling 6K-token prompts | 37.4 / 43.1 ms | 33.1 / 1455 ms |
| Qwen-Image 2.1 generating 1024x1024 (TP 2) | 35.3 / 37.7 ms, 13.1 images/min | 326 / 329 ms, 9.3 images/min |
The interferer's throughput was the same or better under concurrent queues in every row. Taking
turns idles the card between steps and makes the small model wait out the large one's whole step
(a diffusion evaluation, a prefill chunk), so concurrent queues stay and the arbiter is gone; there
is no `co-exec` key.
### 9.1 Two multi-card models on the same cards
A model on more than one card exchanges its ranks' partial sums in collectives, and a block of a
collective on one card finishes only when the same block has run on the other card. A chained
launch (GUIDE §4.6, "Chained launches") holds its wave slots while it waits behind the kernel before
it, and the packet processor launches as far ahead as the card has slots. One engine cannot starve
itself that way: each rank's collective is launched before anything waits behind it. Two engines
on the same cards could. Engine A's collective on card 0 waits for its half on card 1; card 1 is
full of engine B's chained kernels waiting behind B's collective; B's half gets no slot on card 0
beside A's, because a prefill junction launches more blocks than a card runs at once. Nothing
advances from there. Qwen3.8-27B (IQ4R-S-V4) prefilling beside Gemma 4 12B decoding, both TP 2 on
the same two R9700, stopped within 12 s of load, and the process then ignored its stop signal.
So every engine of more than one rank claims its cards when it starts, and on a card with more than
one claim a chained launch keeps its barrier bit while a collective may still run on its queue.
Only the collectives' own blocks then wait on a card for another card, and those are few enough at
decode to leave the other engine its slots. The claim that makes a card shared returns once
everything issued on that card before it has finished, so nothing launched under the old rule is
left. A model alone on its cards, or beside single-card models only, launches as before. A claim
lasts as long as the engine does: a parked model still holds its own.
With the rule the same load ran 200 s without a stop (335 requests), as did both models prefilling
(467 requests) and both decoding (131). What it costs a model while it shares its cards, measured
by forcing it on a model that was alone (medians of three rounds): the 27B's step 20.30 to 20.38 ms
at one stream and 26.7 to 27.1 at four; Qwen3.8-Flash-Next under its draft head 12.46 to 12.56 and
23.3 to 23.3.
---
## 10. Hot reload
SIGHUP or `POST /admin/reload` re-reads the file and validates it completely before touching
anything. Then, per entry:
- unchanged (same normalised key set): untouched;
- changed only in request defaults and limits: applied in place to its `ModelFront`;
- changed otherwise: drained, unloaded, and re-registered as cold (loaded on the next request, or at
once if pinned);
- removed: drained and unloaded; its name answers 404;
- added: registered cold.
`server:` changes other than `log` need a restart and are refused by reload with that reason.
---
## 11. Faults
- **GPU memory fault**: unrecoverable in-process. The handler names the buffer and the model, and the
process exits; the container's restart policy brings the fleet back and pinned models reload.
- **Queue fault or stall**: confined to the engine's card set. Every engine on those cards is marked
failed and refuses its requests by name; engines on other cards keep serving. A failed card set
needs a process restart to recover, which the fleet reports on `/health`.
- **Load failure** (bad file, out of memory, refused plugin): the entry goes `failed` with the error,
its waiting requests get it, and the rest of the fleet is unaffected.
---
## 12. Limitations
Everything §3-§11 describe is built and measured on the test host of §13 (two R9700), except:
- **§7.4** is opt-in: measured slower for a dense decoder. The fleet does not yet choose partial
residency on its own (serving a tiered MoE with its slab in host memory instead of waiting for
room). A dense model serves whole on its cards (the quantum, §8.3); a tiered MoE's expert slab
grows into free VRAM and into the room of an idle neighbour (§6.7). On the test host's 61 GB Flash
Next's own host pool (24 GiB) leaves room in RAM for only a few GiB of other models' parked
copies; the rest restore from the drive.
- A model waiting for room does not start its prefill with part of its weights streamed over the
link (measured in §13.4: it would prefill at 80-90% of its speed, but it needs the KV room it is
waiting for, decode that way runs at a tenth, and a placement is fixed for an engine's life).
- A first step that starts on a model coming back from the drive before every byte has arrived
(layer by layer) is not built: a dense step reads all its weights, so the first token waits for
the drive either way, and the gain is the first step's compute.
- `park.vram` (statics or MiB kept on the card) and `flex.kv.weight` are refused as not acted on.
The disk tier keeps a parked engine (its copies written to `memory.disk-tier` in the background,
its host memory let go under pressure); a model unloaded outright still loads from its container.
- A tiered-MoE cache that lends to its expert slab does not run as flex: it keeps its claim (the
slab grows through the fleet's loan instead, §6.7).
- Unified memory (gfx1151) parks nothing useful: host RAM is the card's memory. Not tested there.
---
## 13. Measured against llama-swap
The test host: two R9700 (32 GB each, PCIe 5.0 behind x8 root ports, 28.8 GB/s measured host to
card), a Ryzen 9 7950X3D with dual-channel DDR5, 61 GB RAM. Seven models configured at once:
EmbeddingGemma2, Unlimited-OCR, MiniCPM5-2B FP8, Qwen-Image 2.1 FP8 (TP 2), Qwen3.8-27B IQ4R-S-V4,
Flash Next FP8/IQ4R (TP 2, tiered experts, 12 GiB host pool a rank) and Hunyuan3D-2. Three workflows
use all of them: docqa (OCR, embed, 27B answer, MiniCPM summary), create (MiniCPM prompt, Qwen-Image
picture, Hunyuan3D mesh, Flash Next critique) and chat (Flash Next, 27B, embed, MiniCPM). llama-swap
v270 runs the same radiance binary, one process per model: in its default mode (one model at a
time), and with its capacity router given per-card budgets and card assignments by hand. The fleet
runs the plain file with `memory.disk-tier` and nothing hand-placed.
| plan | fleet | llama-swap default | llama-swap capacity (hand-placed) |
|---|---|---|---|
| 9 workflows one after another, wall | 168 s | 231 s | 186 s |
| 2 clients x 6 workflows, wall | 133-142 s over 3 runs, none failed | 352 s | 121 s, 1 failed; 207 s, 4 failed |
| 4 clients x 6 workflows, wall | 176-220 s over 3 runs, none failed | 517 s | 163 s, 1 failed (in each of 2 runs) |
| 27B / Flash Next alternating, per request (median) | 3.3 / 1.7 s | 15.1 / 17.8 s | 15.1 / 17.9 s |
The fleet beats llama-swap's default mode on every plan, and its hand-placed capacity mode on the
sequential plan and on swapping (a parked model comes back in 1-3 s instead of a 15-18 s process
start). On the concurrent plans it fails nothing where the capacity mode loses runs (a process
started before the one it replaced had handed its VRAM back), wins two clients against the
capacity mode's slower runs and loses four clients by 10-35%.
The concurrent loss is the first round. From the second round on every workflow runs at or below the
capacity mode's times (docqa 4-7 s, chat 8-16 s, create 20-42 s); the first round is seven cold
loads at once plus the two models that need both cards almost whole (Qwen-Image 2.1, 25 GiB a card,
and Flash Next) taking turns. Races there decide which model waits for which, and the 4-client wall
varies by 25% between runs of the same code: a run where Flash Next's first load waited behind the
27B's sweep, and Qwen-Image's restore read its page file while Flash Next's load filled the drive,
took 220 s; the two before it 176 and 178 s.
What got the concurrent plans here, from 351 s (c4) in the first measurement: a residency quantum
for models serving a batch (§8.3), demands that wait for passing room instead of failing, grants
that wait without the bring-up lock and reserve their room atomically, returning models that give
way to each other instead of deadlocking, park-or-unload by measured page-in and projected writes,
loads held to the host memory floor (one run that pinned past it was killed by the kernel), dirty
blocks instead of whole-chunk invalidation (Flash Next's parks wrote 7-25 GiB each, now megabytes),
the activation arena's transients dropped at a park (Qwen-Image copied 13 GiB of them), and one
large cold sweep at a time, smallest first.
llama-swap's capacity mode needed every model's VRAM and cards worked out by hand, and still lost
runs when a process started before the one it replaced had handed its VRAM back.
### 13.1 Warm starts
The table above starts every system cold. With the warm-up (§8.6) the fleet loads all seven models
once in about 26 s after it starts, and the plans start once it is done. llama-swap's capacity mode
gets the same chance with `hooks.on_startup.preload`: the five models its hand placement keeps
resident at once (27B and Hunyuan3D-2 on card 0, the three small ones on card 1), ready in 22 s.
| plan | fleet, warm | llama-swap capacity, preloaded |
|---|---|---|
| 9 workflows one after another, wall | 78.0 / 78.0 s over 2 runs | 165.3 s |
| 2 clients x 6 workflows, wall | 65.8 / 64.5 s over 2 runs, none failed | 144.5 s, none failed |
| 4 clients x 6 workflows, wall | 109.9 / 110.1 s over 2 runs, none failed | 202.3 s, none failed |
| 27B / Flash Next alternating, 6 rounds, wall | 38.8 s (per request 1.95 / 4.5 s) | |
Warm, every first request finds its model parked: q27, Flash Next and Qwen-Image come back in 2-7 s,
their weights read from the container again at the drive's rate (§7.2), instead of loading for
13-35 s. Parked models' snapshot stores (7.3 GiB for the 27B and Flash Next) go back to the host
under pressure, so a few GiB of parked weights fill into RAM even beside Flash Next's 24 GiB pool.
With the disk-tier copies of the weights an earlier design wrote after every load, the plans took
97.7, 71.8 and 113.9 s; the concurrent plans turn on which of two models waiting for the same cards
comes back first (§8.3), and a schedule where Flash Next and the 27B take turns on card 1 twice
more costs the 2-client plan 20-30 s. Before a returning model's room was counted card by card
(§8.3), Qwen-Image gave way on every return and the 2-client plan took 99.9 / 107.5 s. The fleet
runs Qwen-Image with `max-num-seqs: 4` and `max-model-len: 2048` (§6.3); with neither set its cache
floor was 8.2 GiB a card and the plans took 89.8 / 93.3, 75.5 / 75.5 and 117.0 / 151.3 s. With
`memory.host-mib` at 60% of the host, the default before 75%, they took 81.9 / 82.7, 68.4 / 72.6 and
119.5 / 128.7 s: more parked weights stay in host memory and come back from there, so the
sequential plan reads 308-316 GiB from the drive instead of 334 and its restores page in for 34 s
instead of 39; the 8 GiB host floor held (7.9 GiB available at the lowest). The test host's drive is 94% full (116 GB free), which holds
its writes to about 1.2 GB/s; its reads run at 7.3 GB/s.
### 13.2 Expert flex
Flash Next alone in a two-model fleet (MiniCPM configured, never asked for), its claim 23.65 GiB a
card; with expert flex the slab grew 7 GiB a card into the free memory within the first requests.
Fresh start for each run, runs alternating, 320-token answers, distinct prompts per stream:
| | no expert flex (`max-mib: 0`) | expert flex |
|---|---|---|
| 1 client, decode | 63.8 tok/s | 65.8 tok/s |
| 1 client, first token | 72 ms | 44 ms |
| 4 clients x 6 rounds, median stream | 34.4 / 35.5 tok/s | 40.5 / 40.7 tok/s |
| 4 clients x 6 rounds, slowest stream | 20.1 / 34.3 tok/s | 39.2 / 39.1 tok/s |
| 4 clients x 6 rounds, wall | 29.2 / 24.4 s | 21.6 / 21.2 s |
| mover traffic over one run (rank 0) | 35.0k promotions, 41 GiB in, 34 GiB out | 10.6k promotions, 12.5 GiB in, 4 GiB out |
The single stream is almost all hits already; four streams route to more experts than the claim
holds, and the slab stops trading them over the link. Beside a resident MiniCPM the slab grew into
the 3 GiB left free, MiniCPM parked after 30 s idle while Flash Next was busy and the slab grew to
7 GiB, and MiniCPM's next request took 3.34 GiB back and restored it; both models' temp-0 answers
were identical in every phase.
### 13.3 One-step models in place
One card (`cards: [0]`), the 27B at a 204,800-token context (its claim takes 30.4 GiB of the card)
decoding two streams without pause, and EmbeddingGemma2 with `ttl: 3s`, asked to embed eight chunks
every 4 s, so every request finds it parked. 90 s a run, runs alternating:
| EmbeddingGemma2 `park.restore` | embed latency p50 / p90 / max | 27B, both streams | 27B parked in part |
|---|---|---|---|
| `auto` (in place) | 51 / 53 / 2330 ms; 50 / 53 / 2333 ms | 50.4 / 50.6 tok/s | 2 / 2 times |
| `full` | 2242 / 6083 / 7290 ms; 2113 / 6022 / 6293 ms | 45.4 / 48.2 tok/s | 14 / 15 times |
Coming back whole, EmbeddingGemma2 needs 1.6 GiB the 27B's claim leaves no room for: each request
waits while the busy 27B drains and parks part of its cache, and the 27B takes the room back as soon
as the embedding is done. In place it needs the 0.4 GiB of its cache and arena, comes back in 0.01 s
and embeds in 50 ms with 1.1 GiB read over the link (448 MiB of it moved onto the card into free
memory). The one slow request in place is the first, while both models settle on the card.
### 13.4 Prefill with part of the weights streamed
Whether a model waiting for room could start its prefill with what is off the card streamed over
the link: the 27B alone, `placement: layer_offload` (each step stages the off-card layers onto the
card ahead of the ones that read them), against all weights on the card. One sequence's
204,800-token cache on the card in both, fresh prompt text for each request, two rounds:
| weights off the card | prefill, 2.7K-token prompt | 10.8K | 43K | decode |
|---|---|---|---|---|
| none (14.8 GiB on the card) | 2566 / 2497 tok/s | 2541 / 2481 | 2181 / 2152 | 25 tok/s |
| 4.2 GiB | 2023 | 2178 | 1951 | 3.2 tok/s |
| 7.6 GiB (half) | 1868 / 1856 | 2074 / 2052 | 1890 / 1906 | 2.3 tok/s |
The staging overlaps the compute: a long prefill keeps 85-90% of its speed with half the weights
off the card, a short one 75%, and the cost hardly depends on how much is off (the staging's fixed
cost per step, not the link, sets it). A decode step reads every weight for one token, and runs
at a tenth. Less than half on the card did not plan (the staging slabs of the layer classes did not
fit beside the cache). So a waiting model's prefill could run nearly at speed, but not where it
matters: it needs the cache room it is waiting for (13.9 GiB for one full-length sequence here,
against 7.6 GiB of weights), it would have to change placement while it serves (an engine's plan
is fixed for its life), and its decode after the prefill still waits for the whole restore. Not
built.
+263 -151
View File
@@ -51,9 +51,11 @@ here is such a choice.
carrying the 1/128 (libquant's `transform=fwht128`), met by `had_quant_act_i8g`.
- `w4a8_asym` is the unsigned-nibble-minus-zero-point grid instead of the symmetric one.
- `fp8a8` and `fp8a16` say whether a block-scaled E4M3 weight meets an fp8 or a bf16 activation.
- `fp8a8f32` is `fp8a8` with f32 weight scales on the 128x128 block grid.
- `w5a16` and `w4a16_asym` are ParoQuant's int5 and z-lab's int4 (u5 / u4 codes, an f16 scale and
a u8 zero point per 128 of K) against an f16 activation; `w5a8i8` and `w4a8i8_asym` are the same
- `fp8a8f32` is `fp8a8` with f32 weight scales on the 128x128 block grid. The host libraries
serve these three; libr4d has no row for them, and the engine refuses a block-fp8 weight at
load (`linear_retired` in `arch/common/rad_fp8.h`).
- `w5a16` and `w4a16_asym` are asymmetric int5 and int4 (u5 / u4 codes, an f16 scale and a u8
zero point per 128 of K) against an f16 activation; `w5a8i8` and `w4a8i8_asym` are the same
weights against an int8 activation with an f32 scale per (row, 128 of K).
- `q_dtype` and `kv_dtype` are the same key split in two where attention reads two formats.
- Every op returns `RAD_OK` or a negative `RAD_E_*`. There is no partial success.
@@ -66,7 +68,7 @@ here is such a choice.
`RAD_OK` with the answer to a different function is the one wrong response.
- libref accumulates in f32 (`libref/ref_common.h`). Its double-precision sums are part of the
op's reference: `seg_mean`, `gram_accum`, `logit_rerank`, the normaliser of `sample_logprobs`,
`givens_dense_quant`'s rotation, `ple_gate`'s dot, and the sums of squares of the norms in
`ple_gate`'s dot, and the sums of squares of the norms in
`hc_read`, `mtp_enter`, `ple_gate` and `qsa_block_key`.
## How a schema is written
@@ -204,6 +206,8 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
| `hc_project` | `M`(range) `n` `hc` `scale`:f64 `dtype` | `h`:inout, `v`, `on` |
| `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` |
| `grid_embed` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` |
| `grid_embed_pad` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` |
| `window_order` | `M`(range) `window` | `coord`, `cu` → `idx`, `inv`, `pos`, `cuw` |
| `grid_embed_aa` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` |
| `grid_embed_cpe` | `M`(range) `n` `side` `dtype` `n_prefix`/opt | `x`:inout, `table`w, `coord`, `prefix`w? |
| `add` | `M`(range) `n` `dtype` `div`:f64/opt | `a`, `b` → `y` |
@@ -337,6 +341,29 @@ is `[4, M]` (row, column, grid height, grid width); sampling is bilinear with th
the table's (align_corners), edge taps clamped, the four taps summed in f32 and rounded to `x`'s
dtype before the add.
**`grid_embed_pad`** adds the same table with the same operands in the half-pixel-centre form
(align_corners=False) under grid_sample's `padding_mode="zeros"`: per axis taps at `floor(src)` and
`floor(src) + 1` of `src = (i + 0.5) * side / size - 0.5`, each carrying the hat weight
`(1 - |src - tap|)+`, and a tap whose UNCLAMPED index falls outside `[0, side)` contributes zero
rather than reading a clamped edge. The taps are summed in f32 in `grid_embed`'s order and rounded
the same way. For a grid no larger than the table no tap is ever out of range and the op is
`grid_embed`'s function at the different sample positions; it differs from it materially only when
a grid upsamples past the table, which is the common case for Muse (448 px and larger images).
**`window_order`** computes the window-attention permutation of one encoder pass, entirely from
on-device coordinates: HF's `get_vision_window_index` as a gather-index computation over the packed
pass. `coord` is `[4, P]` i32 (row, column, segment height, segment width per patch) and `cu` is
`[S+1]` i32, the per-frame segment boundaries. Windows of `window` patches partition each segment
(one segment == one frame), scanned window-row-major, ragged at the segment's right and bottom
edges; patches keep raster order within a window and windows never span segments. The outputs are
i32: `idx` `[P]`, slot -> source patch (the gather index: `permuted[slot] = x[src[idx[slot]]]`);
`inv` `[P]`, its inverse, used to undo at the tower's end; `pos` `[2, P]`, each slot's rope
positions `(col + 1, row + 1)`, laid out component-major like the coordinate planes (Muse's rotary
wants the axes swapped and offset by one relative to them, HF's `position_ids.flip(-1) + 1`); and
`cuw` `[P+1]`, the cumulative window boundaries in the permuted order, `n_windows + 1` entries
used. `M` is the patches this pass covers; slots past `M` are the identity. `window` <= 0 makes the
permutation the identity and `cuw = cu`.
**`grid_embed_aa`** is the same addition with SigLIP2's resample, torch's
`F.interpolate(mode="bilinear", align_corners=False, antialias=True)`: per axis a triangle filter on
half-pixel centres, widened by the scale when the grid is smaller than the table, its in-table taps
@@ -381,9 +408,13 @@ is easy to miss.
- `group` absent is a read whose consumer wants bf16. Otherwise the fp8 form of `x` (`q`, `scale`)
comes out of the same pass, quantised from the narrowed `x` rather than the accumulator, so a
fused kernel and the reference agree bit for bit.
- `rotate` adds `rq`/`rscale`: `had_quant_act_fp8` of the same stored `x`, each group rotated by an
unnormalised Hadamard before its absmax, for a consumer whose weight carries the rotation (the
`w4a8h` experts).
- `rotate` adds `rq`/`rscale`: the same stored `x` with each `group` (a power of two that tiles
the row) rotated by an unnormalised Hadamard before its absmax, then E4M3 codes with an f32
scale per group (`amax / 448`), for a consumer whose weight carries the rotation (the `w4a8h`
experts).
- An int8 `q` takes int8 codes (scale absmax / 127, `quant_act_i8g`'s), and `rq` is then int8 too,
`had_quant_act_i8g`'s: the pair has one dtype, so beside int8 block linears the routed experts
read int8 (`moe_gemm_q`'s `a8i8` names). libref, libavx and libr4d serve both.
- `mix` is the mixing matrices' stored format: `bf16`, or `e4m3` (rows of E4M3 codes with f32
scales in each row's own tail, one per 128 columns for `mix_down` and one per quarter row for
`mix_up`). It changes the bytes read, not the arithmetic. The matrices are replicated on every
@@ -459,6 +490,7 @@ of the scalar kernels that serve the rows it cannot read.
|---|---|---|
| `norm_add_norm` | `M`(range) `n` `eps`:f64 `dtype` | `a`, `w_a`w, `x`:inout, `w_y`w → `y` |
| `norm_add_norm_route` | `M`(range) `n` `eps`:f64 `dtype` `mult`:f64 `group` | `a`, `w_a`w, `x`:inout, `w_y`w → `y`; `w_r`w → `r`; `w_e`w → `q`, `qs` |
| `norm_add_norm_route_i8g` | as `norm_add_norm_route` | as `norm_add_norm_route`, `q` int8 |
| `join_add_scale` | `M`(range) `n` `eps`:f64 `dtype` | `d`, `w_d`w, `r`, `w_r`w, `w_j`w, `x`:inout, `s`w, `w_n`w? → `y`? |
| `expert_scale` | `M`(range) `n_expert` `top_k` `dtype` | `ids`, `w_e`w, `ew`:inout |
| `attn_paged_qrow` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `prefill_fp8`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` |
@@ -477,6 +509,10 @@ Gemma's sandwich norms, each one kernel in place of a chain of `rmsnorm`, `add`
per (row, `group` columns) of `amax / 448`, 1 for an all-zero group, the value over it clamped to
±448). `n` is whole groups and `group` is 128. In Gemma 4 it replaces the router's `rmsnorm` and
the experts' `rmsnorm_quant_fp8`.
- `norm_add_norm_route_i8g` is the same with `q`, `qs` = `rmsnorm_had_quant_i8g` of `x` under
`w_e`: int8 codes of the bf16-rounded norm after an unnormalised 128-wide Hadamard over each
group, a scale of `amax / 127` (1 for an all-zero group). For rotated int8 experts it replaces
the router's `rmsnorm` and the experts' `rmsnorm_had_quant_i8g`.
Every value the chain stores is rounded to the activation dtype at the same point, so the fusions
differ from the chain only in the order a sum of squares is added: with the same order they are
@@ -492,7 +528,7 @@ bit for bit.
row pitch: the q part of a fused `[q|k|v]` projection, read where it lies instead of copied into a
dense block by a `cast`. It has its own name because other `attn_paged` kernels refuse a pitched `q`
(libr4d's with `RAD_E_STRIDE`, at the first step), and under `attn_paged` the first library in
`--kernels` wins the op, an order the architecture cannot see. Asked for by name, the op resolves to
`server.kernels` wins the op, an order the architecture cannot see. Asked for by name, the op resolves to
a library that reads the pitch or to nothing, and the architecture copies `q` for `attn_paged` in
the second case. In libr4d the windowed kernels serve it at every height; the split-KV decode kernel
serves it at h256/gqa2 over its decode band (q_len up to 32, ahead of the windowed rows there), and
@@ -500,6 +536,13 @@ at h128/gqa8 up to q_len 16 by reading each kv head for two query groups of 4 (a
then holds each kv head once). Since no host library declares the op, a plugin that asks for it
learns whether a card serves the geometry.
**The windowed kernels read the int8 cache** (`kv_dtype` `i8`, the row under "The KV cache
operand") at every geometry they serve, under `attn_paged`, `attn_paged_qrow`,
`attn_paged_qrow_tree`, the `ahead` pair, `attn_paged_anchor_window` and `attn_paged_sink`. A key's
score is its codes' dot with the query times its K scale, and its V codes enter the sum at its
probability times its V scale; the prefill kernel widens the codes to bf16 (K) and f16 (V), which
holds them exactly. No descales are read.
Tree verification (`rad_drafter_tree`, abi/rad_builder.h) adds one operand to both: the step's
`RadBatch::spec_parent`, `[rows]` i32.
@@ -595,27 +638,16 @@ accumulates only `k2 >= k1`, the half a reader of the symmetric `h` needs, for h
entries below the diagonal are then outside the contract (libr4d adds whole 64-wide tiles, so it
writes some of them).
**Activation widths.** Which width a linear's activation takes follows from the weight. Where the
checkpoint ships E4M3 weights and a block scale plane, every linear is `fp8a8`
(`arch/common/rad_fp8.h`). libr4d's `fp8a16` matvec (`M <= 8`) reads bf16 directly, but it assumes
a weight layout the stored WMMA fragment order does not provide, so it is not used. Where the engine
quantises the activation for an integer weight it is int8: `quant_act_i8` for `w4a8`, `w8a8` and
`w2a8`, `quant_act_i8g` for `i8a8`.
**Activation widths.** Which width a linear's activation takes follows from the weight
(`arch/common/rad_fp8.h`). Where the engine quantises the activation for an integer weight it is
int8: `quant_act_i8` for `w4a8`, `w8a8` and `w2a8`, `quant_act_i8g` for `i8a8`, `had_quant_act_i8g` for `i8a8h`, and for `w4a8i8_asym` and
`w5a8i8` whichever of the last two matches the weight's rotation. The E4M3 activation
(`quant_act_fp8`) is read by a plain-MXFP4 drafter's linears at `mxfp4a8`.
`fp8a8f32` is `fp8a8`'s E4M3 activation against an E4M3 weight whose 128x128 block scales are
f32, read as the checkpoint stores them. A scale that bf16 cannot represent exactly keeps its
value, which `fp8a8`'s bf16 scale plane would round. It applies to `gemm_nt_q` and `moe_gemm_q`
with `group` 128.
libr4d reads both canonical planes in place, with no relayout: `gemm_fp8a8_f32scale` for
`gemm_nt_q` and `moe_gemm_fp8a8_f32scale` for `moe_gemm_q`, `N` and `K` multiples of 128, E4M3
WMMA with the f32 scale product folded per 128 of K, bf16 out. The dense row picks a decode form
(row tiles sharing each weight fragment, several waves on consecutive K blocks) or a row-tile
form by `M`, `N` and `K`; on rows that are not 16-byte aligned it takes the 16x64 tile. The forms
are byte-identical (`tests/r4d_emu/test_fp8f32.cpp`). The grouped row takes equal-width parity
tables (`N_odd = N`, `K_odd = K`), token or sorted activations, and stacked planes or pointer
tables, and runs expert-major: a block per (column span, expert) takes every row of its expert,
each element keeping the 16x64 tile's sequence.
with `group` 128, in the host libraries.
**`group` has different meanings in this table.** A kernel that reads it the other way is wrong,
not slow. `libref/ref_quant.cpp` is the definition.
@@ -629,10 +661,10 @@ not slow. `libref/ref_quant.cpp` is the definition.
- **The `had_*` int8 forms**: `group` is the Walsh–Hadamard rotation width (libr4d's `had`), and
the int8 scale is per row, carrying the `1/sqrt(group)` normalisation. The rotation is what makes
one scale per row viable, so its width and the scale granularity cannot be the same number.
- **The `had_*` fp8 forms** (`had_quant_act_fp8`, `gated_had_quant_fp8`): `group` is both. They
serve a four-bit MoE expert whose scale grid is already one bf16 per (row, 128 of K); a rotation
- **The rotated E4M3 form** (`hc_read`'s `rq`, `rscale`): `group` is both. It
serves a four-bit MoE expert whose scale grid is already one bf16 per (row, 128 of K); a rotation
of the same 128 lines the two up, so the scale is per group, `[M, n/group]` as for
`quant_act_fp8`. They apply no normalisation: `<Hw, Ha> = group * <w, a>`, and the whole factor is
`quant_act_fp8`. It applies no normalisation: `<Hw, Ha> = group * <w, a>`, and the whole factor is
folded into the stored weight scale at convert, where dividing a bf16 by a power of two is exact.
Splitting it as the int8 forms do would round `amax/7/sqrt(group)` into bf16, a ~0.2% error per
group. `n` must be a multiple of `group`.
@@ -641,7 +673,7 @@ not slow. `libref/ref_quant.cpp` is the definition.
(`group <= 0` or `group >= n` is one per row). The scale is `amax / 127` (1 for a zero group) and
each code the value over it rounded to nearest even and clamped to ±127, row-major. They feed the
int8 trunk GEMM (`gemm_nt_q` at `dtype=i8a8`), which folds a scale per K block. The `had_` form
rotates first and, like `had_quant_act_fp8`, folds nothing: its consumer is a weight at
rotates first and, like the rotated E4M3 form, folds nothing: its consumer is a weight at
`dtype=i8a8h`, whose scale carries the whole 1/`group`. It is not interchangeable with the
per-row `had_*` int8 forms, which fold 1/sqrt(`group`) into the activation's scale. `dequant`
inverts `quant_act_i8g`: the scale stream's extent gives the group count and `group` each group's
@@ -663,15 +695,9 @@ and is optional.
|---|---|---|
| `quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` |
| `quant_cols_fp8` | `M` `n` `dtype` | `x` → `y`, `scale` |
| `had_quant_act_fp8` | `M` `n` `group` `dtype` | `x` → `q`, `scale` |
| `givens_dense_quant` | `M` `n` `group` `dtype` `parts` `out`:str | `x`, `tdense`w, `rscale`w → `q`, `scale` |
| `givens_rotate` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `y` |
| `rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
| `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? |
| `swiglu_clamped_quant_fp8` | `M`(range) `n` `limit`:f64 `group` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? |
| `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? |
| `gemm_nt_q_gated_wide` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? (the same fold at every M: the narrow tile to 64 rows, past them the gated prefill tile) |
| `gemm_nt_q_gated_mx` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w, `b_ref`w → `q`, `scale`, `out_bf16`? |
`quant_cols_fp8` is the same E4M3 quantiser with one scale per column over all `M` rows,
`scale[c] = amax_r |x[r, c]| * (1/448)` (1 for an all-zero column), `scale` `[n]` f32: an
@@ -683,61 +709,23 @@ fused width, gate half first) with `gated_quant_fp8`'s pass in the epilogue, so
tensor between them is never written. It is a separate schema, not a flag on `gemm_nt_q`, because
it does not produce that op's `y`. `act` is required here, unlike on the quantiser: an
implementation may compile one gate only, and an optional parameter would let it resolve for
another.
`gemm_nt_q_gated_mx` is the same fold over an OCP-MXFP4 weight (`dtype` `mxfp4a8`, `group` 32), which
`gemm_nt_q` reads with the per-row reference exponent `b_ref` after `b_scale`. A schema of its own
because an op's operand count is fixed for the plugins built against it. `act` `gelu_tanh` is the
GeGLU form, `gemm_nt_q` then `gelu_mul` then `quant_act_fp8`; it writes no `out_bf16`.
`swiglu_clamped_quant_fp8` (device-only) is `swiglu_clamped` then `quant_act_fp8` over its
product in one pass. The product is rounded to bf16 before the quantiser reads it, as the pair
reads it from its bf16 tensor, so the codes, scales and `out_bf16` are the pair's bytes, NaN and
infinite inputs included (`r4d_selftest`). `n` is a multiple of 4, `group` 128, `M` up to 65535,
rows pitched.
another. libr4d's row is `gemm_iqr_gated`: an IQR weight's gate and up rows at up to 16 rows, `act`
`silu`, with `gated_had_quant_i8g`'s pass in the epilogue (rotated int8 codes and an f32 scale per
(row, 128 columns)), byte-identical to the GEMM followed by that quantiser.
`out_bf16` is part of the function, not an optimisation: the unfused pair leaves a bf16 tensor
behind and takes the codes over it, so a layer with a bf16 consumer of the post-norm value must ask
for it. `residual` present is the `fused_add_rms_norm` form.
### ParoQuant rotations
A weight stored with the `givens` transform (`abi/rad_encoding.h`) is `v = w . D . G_1 ... G_S`: a
channel scale `D` and `S` stages of disjoint pairwise rotations applied to each row before
quantisation (ParoQuant, z-lab). The GEMM contracts `<v, x'>` with `x' = x . D^-1 . G_1 ... G_S`,
so the activation takes the same rotation once a token.
- **`givens_dense_quant`** computes `x / rscale`, the rotation, then a block-scaled quantiser per
`group` columns that `out` names: `fp8` is `quant_act_fp8`'s (scale `amax / 448`), `i8` is
`quant_act_i8g`'s (scale `amax / 127`, round to nearest). The rotation is one dense 128 x 128 f16
matrix per (part, group), `tdense` `[parts * n, 128]`, composed from that group's `stages` rounds
of `a' = a cos t + b sin t, b' = b cos t - a sin t`. Each pair lies inside one scale group, so the
matrices belong to the weight: rad-convert composes them once in f64 and stores them as the
weight's `t.dense` table, which the layout hook (`r4d_rad_layout_gdense`) only moves. Consumers
are `gemm_nt_q` at `mxfp4a8` and `m2xfp4` (`out` fp8) and at `w4a8i8_asym` / `w5a8i8` (`out`
i8).
- **`givens_rotate`** is the same rotation stage by stage with no quantiser, `y` in its own dtype
(f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`, whose GEMM serves any `M`
(rows past 64 run as chunks of 64).
A fused projection (gate|up, qkv|z) was rotated per checkpoint tensor, so the activation has
`parts` rotated copies side by side: `q` is `[M, parts * n]` and `scale` `[M, parts * n / group]`;
`pairs` and `angle` stack each part's `stages` rows and `rscale` has one row per part. `gemm_nt_q`'s
`pb1` and `pb2` are the row bounds of the weight's parts: rows `[0, pb1)`, `[pb1, pb2)` and
`[pb2, N)` meet copies 0, 1 and 2 of the wide `a`/`a_scale`. `pb1` absent is one part; `pb2` absent
ends the second part at `N`. The `mxfp4a8` and `m2xfp4` rows and the asymmetric 4- and 5-bit rows
read them; host rows that do not (libavx) refuse a call that names one rather than contract against
the wrong copy.
### Int8 and gated fp8 fusions (device-only)
| op | params | operands |
|---|---|---|
| `had_quant_act_i8g` | `M` `n` `group` `dtype` | `x` → `q`, `scale` |
| `gated_had_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? |
| `gated_had_quant_i8g` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? |
| `rmsnorm_had_quant_i8g` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
| `gate_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate`, `x` → `q`, `scale`, `out_bf16`? |
| `gate_had_quant_i8g` | `M` `n` `group` `dtype` `act`:str/opt | `gate`, `x` → `q`, `scale`, `out_bf16`? |
| `rmsnorm_quant_i8` | `M` `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
| `rmsnorm_quant_i8g` | `M` `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
| `gelu_mul_quant_i8` | `M` `n` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? |
@@ -753,7 +741,13 @@ value, then int8 codes per (row, `group`), byte-identical to the producer follow
one launch for a norm read by three projections (q, k and v), and none between the gated product and
the down projection. `out_bf16` receives the unrotated value, for a bf16 consumer. `n` is a
multiple of `group`. A rotated code read as a plain one, or the reverse, gives a model that runs
and is wrong, so these are separate ops, as `gated_had_quant_fp8` is.
and is wrong, so these are separate ops.
`gate_had_quant_i8g` is `gate_quant_fp8`'s product (the gate in its own operand: a gated
attention's gate is a column slice of the `[q|gate]` projection) with `had_quant_act_i8g`'s
quantiser on its pass, for a gated attention's rotated out projection (`i8a8h`); `out_bf16` is the
unrotated product. `n` is a multiple of 128; `group` is 128, or 256 for an IQ8R out projection (one
scale per 256 columns of a (token, head) row).
`rmsnorm_quant_i8` is `rmsnorm` with `quant_act_i8`'s quantiser on its pass: step-order int8 codes
and one f32 scale per row, what `gemm_nt_q` reads at `dtype=w4a8` and `w8a8`. With `residual` the
@@ -770,14 +764,16 @@ Byte-identical to the same chains ending in `quant_act_i8g`. `n` is a multiple o
decode heights (`w4a16_asym`, `w5a16`) writes the norm output where the unfused norm would, in
place of the branch output it has consumed.
### `dequant_w4` (device-only)
### `dequant_w4`
| op | params | operands |
|---|---|---|
| `dequant_w4` | `N` `K` `group` `dtype` `twos` | `wq`w, `ws`w → `y` |
libr4d's own op: a packed 4-bit fragment-ordered weight back to row-major bf16. libref declares
`dequant`, which is activation-shaped, and nothing else declares `dequant_w4`.
A packed 4-bit fragment-ordered weight back to row-major bf16: eight codes a 32-bit word, the
f16 scale in a scale word's low half and `-(1024 + zero)` as f16 in its high half; `twos` reads
the codes as two's complement with no zero point. libr3d, libref and libavx serve it.
`dequant` is the activation-shaped one.
`twos` selects the symmetric two's-complement nibble over the asymmetric unsigned-nibble-minus-
zero-point grid. The two differ in bit 3, so the wrong one is wrong output, not a refusal.
@@ -794,7 +790,6 @@ may not have arrived.
| `gemm_nt_f32` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` |
| `gemm_nt_bias` | `M`(range) `N` `K` `dtype` `act`/opt | `a`, `b`w, `bias`w, `res`? → `y` |
| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt `split_n`/opt `w_rb`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? |
| `gemm_nt_q_short` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt `split_n`/opt `w_rb`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? (the narrow fp8 row with the short-prompt split rule: N <= 512, K <= 5120 and 41..64 rows run unsplit) |
| `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` |
`nt` is A row-major `[M,K]` times B transposed `[N,K]`, giving `[M,N]`: the layout every weight in
@@ -812,7 +807,7 @@ At `i8a8` they are `quant_act_i8g`'s row-major codes and per-(row, 128 of K) sca
weight with a bf16 scale per (row, 128 of K); at `mxfp4a8`, `quant_act_fp8`'s pair against e2m1
codes with an E8M0 exponent per (row, 32 of K).
At `m2xfp4` -- the `m2xfp4` quantiser's own scheme, not an affine grid -- `b` is that scheme's
At `m2xfp4` (libref only) -- the `m2xfp4` quantiser's own scheme, not an affine grid -- `b` is that scheme's
codes and meta planes concatenated as stored (the codes rows, then the meta rows; the form the
core's selection reader hands out, core/format/encoding.cpp) and `b_scale` the E8M0 plane as at
`mxfp4a8`. The exact element is `e2m1(code) . 2^(e-127) . (1 + k_s/4)`, `k_s` the meta byte's
@@ -831,13 +826,19 @@ weight element (n, k) is `(code - zero) * scale`, one f16 scale and one integer
| dtype | codes | `a`, `a_scale` | group sub-sum `sub` | accumulated |
|---|---|---|---|---|
| w2a8, w4a8_asym | u2, u4 | `quant_act_i8`'s step-order codes, per-row scale; `a_sum` required | `sum(a * code) - zero * a_sum[g][m]`, exact | `(sub * a_scale[m]) * scale` |
| w4a8i8_asym, w5a8i8 | u4, u5 | row-major int8, f32 scale per (row, 128 of K) (`givens_dense_quant`) | `sum(a * (code - zero))`, exact | `(sub * a_scale[m][g]) * scale` |
| w4a16_asym, w5a16 | u4, u5 | a 16-bit activation (`givens_rotate`), no `a_scale` | `sum(a * (code - zero))` in f32, ascending k | `sub * scale` |
| w4a8i8_asym, w5a8i8 | u4, u5 | row-major int8, f32 scale per (row, 128 of K) | `sum(a * (code - zero))`, exact | `(sub * a_scale[m][g]) * scale` |
| w4a16_asym, w5a16 | u4, u5 | a 16-bit activation, no `a_scale` | `sum(a * (code - zero))` in f32, ascending k | `sub * scale` |
`a_sum` is `quant_act_i8`'s `asum`, group-major `[K/group][Mpad]` with `Mpad = ceil(M/16)*16`. The
ParoQuant grids (the four 4- and 5-bit ones) take parts (`pb1`, `pb2`); `w2a8` and `w4a8_asym` do
four 4- and 5-bit grids of the last two lines take parts (`pb1`, `pb2`); `w2a8` and `w4a8_asym` do
not, and none has a bias form.
`pb1` and `pb2` are the row bounds of a fused projection's parts when the activation holds one copy
a part side by side (`a` `[M, parts * K]`, `a_scale` likewise): rows `[0, pb1)`, `[pb1, pb2)` and
`[pb2, N)` meet copies 0, 1 and 2. `pb1` absent is one part; `pb2` absent ends the second part at
`N`. A row that does not read them refuses a call that names one rather than contract against
the wrong copy.
`w_rb` is the weight rows one int8 scale covers, when the weight's form makes it more than one: a
trellis on libquant's `tcq_rb` grid, each value read against its block's largest scale. Absent, 1.
An IQR weight under one f32 scale a row and one f32 factor a 128-K block for all rows (`kRowF32`,
@@ -849,7 +850,7 @@ per-row scale plane holds each block's one value in each row.
`split_n` is the output width whose K split the call takes, when it is a row slice of a wider
linear (a rank's share of a weight whose rows do not divide among the ranks, issued as two slices).
libr4d's narrow fp8a8 and i8a8 kernels pick their K split from N alone, and the split sets the order
libr4d's narrow i8a8 kernels pick their K split from N alone, and the split sets the order
K partials are summed in, so a slice given the whole width sums each output as the whole linear
does and its outputs are the linear's to the bit. Absent, N. The host libraries never split K and
ignore it. libr4d's kernels compute the same products in another order (split-K
@@ -890,7 +891,7 @@ with no adapter row issues neither. `slot` is
an i32 per row naming its adapter's pool slot -- the step batch's `RadBatch::lora_slot` from the
GEMM's first row on; **a row with `slot < 0 || slot >= S` is a base row and neither op touches
it**: `lora_shrink` writes nothing into its `t` row, and `lora_expand` does not read or write its
`y` row at all — so a base row stays bit for bit what the GEMM wrote, where `y + 0` would already
`y` row at all, so a base row stays bit for bit what the GEMM wrote, where `y + 0` would already
have turned a -0 into +0. On an image or video generator's pass every row runs the same adapter,
and `slot` is a run of the core's slot-row table holding that slot's index in every element, so the
GEMM's rows need not be the pass's token rows.
@@ -906,7 +907,7 @@ GEMM's rows need not be the pass's token rows.
`lora_a` is `[S, R, K]` bf16, `t` is `[M, R]` f32.
- `lora_expand`: `y[m, n] = y[m, n] + scale[s, n] · Σ_j t[m, j] · lora_b[s, n, j]`, f32
accumulate, one rounding to `y`'s dtype (`bf16`/`f16`/`f32`, named by `dtype`). `lora_b` is
`[S, N, R]` bf16 and `scale` `[S, N]` f32 — per output column, so a fused projection whose parts
`[S, N, R]` bf16 and `scale` `[S, N]` f32, per output column, so a fused projection whose parts
carry different `alpha / r` is one launch.
- `lora_expand_mm`: `lora_expand` with `t` rounded to bf16 and the sum over `j` in any order,
@@ -944,10 +945,13 @@ the count from `tail`, as a GEMM takes its M from its operands.
| op | params | operands |
|---|---|---|
| `prefetch` | `bytes` | `w`w |
| `prefetch` | `bytes` `blocks`/opt | `w`w |
Reads the first `bytes` of a weight's stored form and writes nothing, so a kernel that streams the
weight next finds those bytes in the on-die cache (64 MB on gfx1201). It is issued beside a
weight next finds those bytes in the on-die cache (64 MB on gfx1201). `blocks` is the number of
workgroups reading where the architecture measured its own (the read holds wave slots and queues
its loads in front of the kernels it runs beside, so the best count depends on them); absent or 0
it is the kernel's `nb` axis. It is issued beside a
collective that leaves the card's memory idle: on the second lane (`rad_lane`), or, where launches
chain (`rad_chain_on`), as its chained form on the same lane right behind the GEMM before the
collective, which waits for that GEMM only and does not hold the collective. A plain read on the
@@ -998,10 +1002,8 @@ ask `rad_kv_block_size()` (`spec.md` §7.2).
Q·Kᵀ with the query rounded to e4m3 after the softmax scale, 2 is P·V with the probabilities rounded
to e4m3, 3 is both, and absent is 0. It is a permission, like `all_reduce` with `exact` 0: libref
and every exact kernel compute the exact form whatever it says, and a lossy kernel matches only the
value it implements. libr4d has lossy rows for the h256/gqa6 prefill band over the fp8, fp8_v4
and k6_v4 caches (`attn_prefill_h256_gqa6_fp8kv_qk8`, `_pv8`, `_qk8pv8`, and the same suffixes on
`attn_prefill_h256_gqa6_fp8v4` and `attn_prefill_h256_gqa6_k6v4`); the engine states it from
`--attn-prefill-fp8`.
value it implements. libhalo has lossy rows for the h256/gqa6 prefill band over its E4M3 caches;
libr4d has none, and no plugin in the tree states the parameter.
`cu_seqlens` is optional and makes the batch ragged: `[n_seq+1]` i32, sequence `s` owning query rows
`[cu[s], cu[s+1])` of the dense `q` and `out` blocks. Absent, every sequence has the same query
@@ -1182,25 +1184,42 @@ Its parameters are the two ops' own, its operands the prologue's followed by `sl
| op | params | operands |
|---|---|---|
| `attn_paged_gate_quant` | `q_len`(range) `head_dim` `gqa` `block_size` `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt:capacity `group` `act` | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `gate` → `q8`, `q8_scale` |
| `attn_paged_gate_had_quant` | `q_len`(range) `head_dim` `gqa` `block_size` `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt:capacity `group` `act` | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `gate` → `q8`, `q8_scale` |
**`attn_paged_gate_quant`** (device-only) is `attn_paged` followed by `gate_quant_fp8` over its
output, finished inside the split-KV merge. A merge row is one (token, head) pair of `head_dim`
columns, which is a `gate_quant_fp8` row, so the merged values are gated (`bf16(sigmoid(gate))`,
rounded before the multiply), rounded, written to `out` and quantised to E4M3 with one scale per 128
columns while still in registers. `r4d_selftest` checks it byte for byte against the pair at both
merge forms and over a bf16 and an E4M3 cache. `block_size` is required rather than derived because
merge forms and over a bf16 and an int8 cache. `block_size` is required rather than derived because
the cache's page size is `attn_paged`'s to answer; the caller passes the value it read. The gated
attention block uses it on the QSA sparse path, where every launch is one query row per sequence
and the decode kernel serves the whole step in one launch. `max_seqs` is a capacity
(`RAD_PROLE_CAPACITY`): the block declares it at the step size, and the activation arena's smaller
declares bound it lower.
**`attn_paged_gate_had_quant`** (device-only) is the same merge with `gate_had_quant_i8g` as its
quantiser, for an out projection stored rotated (dtype `i8a8h`): `out` holds the gated bf16 product
and `q8` the int8 codes of its width-128 Hadamard, one scale per 128 columns. A butterfly's two
results are the same bits whichever thread holds which index, so the merge's two thread maps and the
standalone quantiser agree byte for byte as long as the stages run by ascending stride;
`r4d_selftest` checks that at both merge forms over every cache layout.
### The KV cache operand
`attn_paged` and `kv_store` take the group's cache as operand 1, passed as `RAD_KV(group, layer)`.
`RadKVGroupBatch` carries the slot mapping, the block table and the sequence lengths, but the pool
base belongs to the block manager, not the batch.
**A token's row in a page** is `[block, kv_heads, block_size, row]` with `row =
rad_kv_row_elems(dtype, head_dim)` (abi/rad_builder.h). A bf16 group holds K's `head_dim` elements
and then V's. An int8 group (`RAD_I8`, `kv_dtype` `i8`, `kv-cache-dtype: i8`) holds K's int8 codes,
V's, and then two f16 scales, K's and V's, `2 * head_dim + 4` bytes: a scale is the head's largest
magnitude in that token over 127, rounded to f16 and at most 515, and a code is `rint(x / scale)`
clamped to +-127, so a value is `code * scale`. `kv_store` writes that row and every paged attention
reads it, in libr4d, libavx and libref alike. An E4M3 group (GLM-5.3's latent cache) holds one code
an element at `kv_store`'s `k_scale` / `v_scale`, 1 when absent.
**A streamed group's cache operand is its ring.** Its pool holds `slots` blocks while the block
table names up to `blocks` ids, so the sparse path resolves the selected ids to ring slots first
(`kv_resolve`, under "Sparse attention (QSA)"), and every other op reads the cache as before.
@@ -1211,21 +1230,21 @@ attention, so a block the resolve copies in from the mirror carries this step's
`kv_store` for a streamed group, into both of its copies.
- **`k`, `v`, `slot_mapping`** — as `kv_store`; a negative slot is skipped. `slot / block_size` is
- **`k`, `v`, `slot_mapping`**: as `kv_store`; a negative slot is skipped. `slot / block_size` is
the block and `slot % block_size` the position in it.
- **`host`** — bytes `[blocks, row]`, inout: the layer's authoritative mirror, one block a row in the
- **`host`**: bytes `[blocks, row]`, inout: the layer's authoritative mirror, one block a row in the
cache's layout (`[block, kv_heads, block_size, 2 * head_dim]`, K then V in a slot). Written for every
token with a slot.
- **`kv_cache`** — the ring, `RAD_KV(group, layer)`. Written at `res[block]` only when that is `>= 0`.
- **`res`** — `i32 [blocks]`, in: the residency map. Read, never written; residency is
- **`kv_cache`**: the ring, `RAD_KV(group, layer)`. Written at `res[block]` only when that is `>= 0`.
- **`res`**: `i32 [blocks]`, in: the residency map. Read, never written; residency is
`kv_resolve`'s decision.
The residency test is in the writer because at decode the block a step writes is usually the one
the previous step made resident: a mirror-only writer would leave the ring's copy short of this
step's tokens, and the resolve, seeing the block resident, would not copy it. Both planes share one
byte pitch, so one offset addresses the same element in either. The rows are
`kv_store_streamed_fp8` (`kv_store_fp8`'s conversion) and `kv_store_streamed_bf16` (the value
itself); a packed `fp8_v4`/`k6_v4` cache has none. A map entry outside `[-1, slots)` is a state
`kv_store_streamed_i8` (`kv_store_i8`'s row), `kv_store_streamed_fp8` (`kv_store_fp8`'s
conversion) and `kv_store_streamed_bf16` (the value itself). A map entry outside `[-1, slots)` is a state
fault libref refuses; the device kernel treats it as absent, writes the mirror, and the resolve
refuses the step.
@@ -1256,8 +1275,8 @@ block already holds its token's rotated k one element a lane, so it also writes
the head's v element into the cache at the token's slot. The store reads `k_out`, so the tail adds
only `v`, `slot_mapping` and `kv_cache`; every parameter is one of the two ops' own. It is
byte-identical to the pair at either cache width: the store converts the rotated k exactly as
`k_out` stores it, a bf16 cache takes the values as they are, and the E4M3 conversion rounds each
element on its own.
`k_out` stores it, a bf16 cache takes the values as they are, and the int8 conversion is
`kv_store`'s, a token and head at a time.
Both ops are byte-identical to the kernels they replace, checked in `r4d_selftest` for the
`[q|gate]` form and the K-only form on a strided projection. The check is byte equality, not a
@@ -1269,7 +1288,7 @@ the reference's fold exactly: widths above the head dim contribute zeros, and ad
**`qk_norm_rope_gate_kv_store_streamed`** is that fold with `kv_store_streamed` as the store, taking
the residency map and the host mirror as its last two operands: the rotated k and the v go to the
mirror for every token with a slot and to `kv_cache[res[block]]` only where the block is resident.
The bytes are exactly `qk_norm_rope_gate` then `kv_store_streamed`'s. Rows `_fp8` and `_bf16`. It
The bytes are exactly `qk_norm_rope_gate` then `kv_store_streamed`'s. Rows `_i8` and `_bf16`. It
saves a launch a layer on the decode path. A staged pass waits for its stage copy before this op,
which is the store; a pass the row declines (more than the fused rows, or mixed media positions)
runs the prologue and a separate store.
@@ -1287,7 +1306,7 @@ says which (`libref/ref_gen.cpp`).
|---|---|---|
| `ln_mod` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `s`, `cu_seqlens` → `y` |
| `gate_add` | `M`(range) `n` `dtype` `act`/opt | `y`, `g`, `cu_seqlens`, `x`:inout |
| `ln_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? |
| `ln_mod_had_quant_i8g` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? |
| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `clamp_min`:f64/opt `curve`/opt `dtype` | `t` → `y`, `table`w? |
| `gather_rows2` | `M`(range) `n` `dtype` | `a`, `b`, `idx` → `y` |
| `table_add` | `M`(range) `n` `L` `dtype` | `x`, `t`w → `y` |
@@ -1322,9 +1341,10 @@ source into every listed lane (a repainted picture's latent into each of its ima
`tanh` (the default) or `none`, the gate as it is and not rounded first:
`x = bf16(x + bf16(g[seq] * y))` (MiniMax-H3's last block, whose gates have no tanh). The
roundings are to `x`'s dtype.
- `ln_mod_quant_fp8`: with `gated` 1, `gate_add` first; then `z = ln_mod(x)` and
`(q, scale) = quant_act_fp8(z, group)`, `z` written when bound. Each value is rounded as its own
store would round it, so the bytes are the three ops'.
- `ln_mod_had_quant_i8g` (device-only): with `gated` 1, `gate_add` first; then `z = ln_mod(x)`
and `(q, scale) = had_quant_act_i8g(z, group)`, `group` 128 or 256, `z` (the unrotated norm
output) written when bound. Each value is rounded as its own store would round it, so the bytes
are the three ops'. It feeds a weight stored rotated (`i8a8h`).
- `timestep_embed`: `[cos | sin]` of `t' * f_i`, `f_i = exp(-ln(max_period) * i / (n/2))` in f32,
`t' = scale * t`; with `round` 1, `t' = scale * bf16(bf16(t * scale) / scale)`, the value
diffusers' pipeline hands its transformer; with `round` 2, `t' = scale * bf16(t)` (a pipeline
@@ -1456,6 +1476,8 @@ libref function says which (`libref/ref_audio.cpp`).
| `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt `top_p`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? |
| `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt `clamp`/opt | `codes`, `t0`w, `t1`w → `y` |
| `vq_encode` | `M`(range) `n` `dim` `bins` `dtype` | `x`:inout, `in_w`w, `in_b`w, `cb`w, `out_w`w, `out_b`w → `codes` |
| `vq_euclidean` | `M`(range) `n` `bins` `dtype` | `x`:inout, `cb`w → `codes` |
| `elu` | `M`(range) `n` `dtype` | `x` → `y` |
| `frame_mix_store` | `M`(range) `n_embd` `L` `stride` `rep`/opt `dtype` | `hid`, `logits`w, `scale`w, `lane`, `frame`, `status`, `dst`:inout |
| `end_status` | `M`(range) `end` `rep` | `ids`, `lane`, `status`:inout |
| `ras_pick` | `M`(range) `win` `lo` `hi` `rep`/opt `clear`/opt | `first`, `alt`, `lane`, `hist`:inout → `ids` |
@@ -1511,6 +1533,20 @@ conditional first, then the unconditional) are consecutive rows, `rep` of them a
`x -= out_w cb[code] + out_b` (`out_w` `[n, dim]`, the raw codebook row), rounded once into `x`.
f32 arithmetic. A chain of these over a codec's codebooks, each quantising what the last left, is
its residual quantiser.
- `vq_euclidean`: Mimi's RVQ step (Breeze's reference encoder), after the enclosing split
quantiser's input projection. For each row of `x` `[rows, n]`, choose the nearest row of `cb`
`[bins, n]` by squared Euclidean distance in f32, ties to the lower index; write that index to
`codes` i32 at its own stride, and subtract the chosen centroid from `x`. No normalisation and
no per-codebook projections; the semantic and acoustic residual chains are independent. The
device kernel supports f32, one workgroup a row, `n <= 4096`, `bins <= 65536`.
- `elu`: `y = x >= 0 ? x : expm1(x)`, alpha 1, at each operand's row pitch. In-place use is valid.
The device kernel supports f32 (Breeze's reference encoder).
The reference encoder also uses f32 device forms of ordinary `gemm_nt`, `layernorm` (up to 4096
channels), exact-erf `gelu` and `attn_dense` (causal, head dimension 64, GQA 1, at most 512 rows).
The existing `rope` entry dispatches f32 inputs to the full-head 64-dimensional NeoX form with
one-component positions and no YaRN or Llama-3 scaling. Causal strided `conv1d` supports f32 as
well as bf16; the explicit symmetric `pad` form remains bf16-only.
- `frame_store`: `dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]` for every `k`,
when `frame >= skip` and `status[lane] >= 0`: a frame's codes into its lane's history, each
codebook a row over the lane's frames, so a run of a lane's frames is a block of `n_codes`
@@ -1614,8 +1650,8 @@ bf16 tensor and keeps f32 where it computes in f32; the libref function says whi
| op | params | operands |
|---|---|---|
| `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `z`, `colmap`? |
| `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`?, `colmap`? |
| `rms_mod_quant_i8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`?, `colmap`? |
| `rms_mod_had_quant_i8g` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`?, `colmap`? |
| `flow_x0_step` | `M`(range) `n` `dtype` | `v`, `t`, `sigma`, `sigma_next`, `x`:inout |
| `flow_res_multistep` | `M`(range) `n` `dtype` | `v`, `x0`:inout, `sigma`, `r`, `hb1`, `hb2`, `order`, `x`:inout |
| `patch_unfold` | `M`(range) `C` `pt` `ph` `pw` `mul` `add` `dtype` | `x`, `geom` → `y` |
@@ -1646,10 +1682,14 @@ reads its entry's rows of `s` and `g`.
`colmap` (optional, trailing, i32 one a sequence) maps a sequence to its table row: every `[e]`
above becomes `[colmap[e]]`, so groups that share a modulation cell read one row. With it, `s`
and `g` may hold fewer rows than there are sequences; the map's bound is the issuer's.
- `rms_mod_quant_fp8` is `rms_mod` with the norm chain in bf16, then `quant_act_fp8` of that bf16
row per `group` as `ln_mod_quant_fp8` takes it; `z` written when bound.
- `rms_mod_quant_i8` is the same with `quant_act_i8g` in place of `quant_act_fp8`: symmetric int8
codes with a scale per `group` columns of a row, for the int8 GEMMs. `z` written when bound.
- `rms_mod_quant_i8` is `rms_mod` with the norm chain in bf16, then `quant_act_i8g` of that bf16
row: symmetric int8 codes with a scale per `group` columns of a row, for the int8 GEMMs. `z`
written when bound.
- `rms_mod_had_quant_i8g` (device-only) is the same with `had_quant_act_i8g`'s quantiser: the
bf16 chain rotated by an unnormalised 128-wide Hadamard, then int8 codes with a scale per
`group` columns of a row, `group` 128 or 256 (IQ8R's) and `n` whole groups. `z`, when bound,
receives the unrotated chain. Byte-identical to `rms_mod` and `had_quant_act_i8g`; it pairs only
with a weight stored rotated (`i8a8h`). FLUX.3's and Krea 2's blocks take it on IQ8R linears.
- `flow_x0_step` is MiniMax-H3's sampler step over a lane's rows, all f32, each product and sum
one rounding: the velocity points at the data, so the clean estimate is `d = x + (1 - t) v` and
the step blends toward it, `st = f32(1 - t)`, `d = f32(x + f32(st v))`,
@@ -2213,8 +2253,8 @@ at every size.
| op | params | operands |
|---|---|---|
| `moe_gemm_q` | `M`(range) `N` `K` `n_expert` `top_k` `group` `a_order` `dtype` `N_odd`/opt `K_odd`/opt `parts`/opt | `a`, `a_scale`?, `w`wt, `w_scale`wt, `sorted_tok`, `expert_offset`, `w_odd`wt, `w_odd_scale`wt → `y` |
| `moe_gemm_q_mod4` | `M`(range) `N` `K` `n_expert` `top_k` `group` `a_order` `dtype` `N_1`/opt `K_1`/opt `N_2`/opt `K_2`/opt `N_3`/opt `K_3`/opt `parts`/opt | `a`, `a_scale`?, `w`wt, `w_scale`wt, `sorted_tok`, `expert_offset`, `w_1`wt, `w_1_scale`wt, `w_2`wt, `w_2_scale`wt, `w_3`wt, `w_3_scale`wt → `y` |
| `moe_gemm_q` | `M`(range) `N` `K` `n_expert` `top_k` `group` `a_order` `dtype` `N_odd`/opt `K_odd`/opt `parts`/opt `a_group`/opt | `a`, `a_scale`?, `w`wt, `w_scale`wt, `sorted_tok`, `expert_offset`, `w_odd`wt, `w_odd_scale`wt → `y` |
| `moe_gemm_q_mod4` | `M`(range) `N` `K` `n_expert` `top_k` `group` `a_order` `dtype` `N_1`/opt `K_1`/opt `N_2`/opt `K_2`/opt `N_3`/opt `K_3`/opt `parts`/opt `a_group`/opt | `a`, `a_scale`?, `w`wt, `w_scale`wt, `sorted_tok`, `expert_offset`, `w_1`wt, `w_1_scale`wt, `w_2`wt, `w_2_scale`wt, `w_3`wt, `w_3_scale`wt → `y` |
| `scale_rows` | `M`(range) `n` `act` `dtype` | `x`, `s`, `add`? → `y` |
The arithmetic is the same whether a kernel is handed the tables or the stacked form
@@ -2230,6 +2270,32 @@ gate/up); the output is `max(N, N_odd)` wide, and a narrower class fills the lea
output part and writes zeros after them, so the gated quantiser behind it reads one layout for every
row. The weight list is the even class's codes, its scales, then the odd class's codes and scales.
**`moe_gemm_q` against an int8 activation.** The dtype names the pair: `i8a8` and `i8a8h` are int8
experts (codes row-major, a bf16 scale per (row, `group` of K), `i8a8h` rotated by a 128-wide
Hadamard along K as its activation is), and `w4a8i8`, `w4a8i8h`, `w4nl64a8i8h` and `w4nl32a8i8h` the
four-bit experts of the names without `i8`, same stored planes. `a` is then int8 with an f32 scale
per (row, `a_group` of K): `a_group` defaults to `group` and may be 256 against a `group` of 128,
which is how gate_up reads codes an IQ8R trunk quantised at one scale a 256. Sums are int32 within
a scale group and folded to f32 at its end. The w4nl codebook's levels are not integers at one
int8 unit (1.125 to 22 in eighths is 9 to 176, past int8), so libr4d reads them as the int8 set 6,
17, 29, 42, 58, 74, 95 and 116 times 0.18965 (`r4d_args.h`, `kW4nlI8`): each within 1.2% of its
level and the weight 2.4e-3 of the stored one away in relative L2 over Qwen3.8-Flash-Next's
experts, inside the op's tolerance against libref, which multiplies the stored levels. An exact
read as two int8 halves and two WMMAs took 35 to 42% longer a launch.
**`moe_gemm_q` over IQR experts.** At `i8a8h` an expert may also be an IQR weight (`docs/IQR.md`):
the rotated computed trellis (`tcq_code=mad`) of two to six bits under one f32 scale a row, its
tables' entries each expert's codes at their own width with the code's two constants, and each
expert's row scales and 128-K block factors. libr4d's `moe_gemm_iqr` decodes them where it reads
them: a block serves one run of sorted rows against a group of the expert's 16-row tiles. A run of
one or two rows, which is nearly every run of a decode step, dots each decoded value with its
activation byte and uses no WMMA tile; a longer run transposes each decoded unit once and
multiplies it against every 16-row token tile it reaches. Inside the decode band the grid is
(tile, run) over at most sixteen rows a block; above it a run map in the op's scratch gives a
block up to 64 rows of one expert, so a prefill chunk decodes each expert's tiles about once. A
class's rows are whole trellis runs in each part, so a gate_up split in 128-row blocks between
ranks takes `tcq_rows=128`. The output is the product within f32 rounding.
**`router_sigmoid_topk`** is single-group correction-bias routing, all in f32. The scores are
`p = sigmoid(logits)`; the selection takes the `top_k` largest `p + bias`, ties to the lower
expert, and the weights are the selected `p`, never the biased ranks. With `norm` 1 a weight is
@@ -2276,26 +2342,11 @@ own because `moe_scatter`'s and `moe_gather`'s operand lists are the shared voca
weights; both are byte-identical to the pair they replace, at GLM's shape with f32 routing weights
and the shared arm folded in (`r4d_selftest`).
At `dtype=mxfp4a8`, `w` and `w_odd` are OCP e2m1 codes and `w_scale` and `w_odd_scale` hold one
At `dtype=mxfp4a8` (the host libraries; libr4d has no row), `w` and `w_odd` are OCP e2m1 codes and `w_scale` and `w_odd_scale` hold one
E8M0 exponent per (row, 32 of K), typed `e8m0` or raw `u8`; either way a byte is an exponent, not
an integer multiplier. `a` and `a_scale` are `quant_act_fp8`'s pair, and `group` is that
activation's scale group, independent of the weight's 32-wide grid.
libr4d's `moe_gemm_mxfp4a8` keeps the canonical bytes, including pointer tables of device or
device-mapped host addresses: a wave decodes the packed e2m1 words into exact E4M3 bytes and runs
fp8 WMMA, folding each 32-wide E8M0 exponent into the f32 accumulator. Per 128 of K, each 32-wide
group is a fresh WMMA pair, folded as raw * activation scale * E8M0 scale. It serves `group` 128,
`K` a multiple of 128, 2 to 512 experts, `top_k` up to 32, token or sorted activations, `parts`,
and an odd class narrower in `N` or `K`, with `M` up to 32767; there is no `moe_gemm_q_mod4` row
at this dtype. The form follows the routed rows. The expert-major form, a block per (column block,
expert) that reads each expert slice once, takes up to 511 rows, and at GLM's TP8 slices (288
experts, top 8) gate_up up to 768 and down up to 6143. At those slices the wide prefill form (P64:
jobs of 32 or 64 rows of one expert) takes gate_up from 769 rows and down from 5760, ahead of the
expert-major band. At GLM's TP4 slices the GLM prefill form (jobs of 32 rows of one expert, its
loads a stage ahead) takes from 512 rows; elsewhere the row groups (16 sorted rows a block) serve.
Every form gives the bytes of one per-element sequence, restated on the host by
`tests/r4d_emu/test_moemx.cpp`.
**`moe_gemm_q_mod4`** is the same GEMM over four classes by the expert's number mod 4. `w`/`w_scale`
hold class 0 at `[N, K]` and `w_q`/`w_q_scale` class `q` at `[N_q, K_q]` (defaulting to `N`, `K`);
expert `e` is entry `e / 4` of class `e % 4`, so class `q` holds `ceil((n_expert - q) / 4)` of them.
@@ -2311,7 +2362,8 @@ u4 or u5 codes into an f32 table of 16 or 32 levels, declared as one view over t
`codes,table`, and a scale per (row, group of K): bf16 per 128, or E4M3 per 64 or 32 declared with
its fixed f32 level as `scale,scale.1`. Element (n, k) of an expert is `table[code] * scale`, times
`scale.1` where there is one. The encoding's `fwht128` is in the stored weight and in the
activation `had_quant_act_fp8` writes, so the GEMM applies none. On the host, a view of several
activation its producer writes rotated (`hc_read`'s `rq`, or `had_quant_act_i8g`'s codes at the
`a8i8h` names), so the GEMM applies none. On the host, a view of several
planes is stored in the joined form of `abi/rad_planes.h`; libref's and libavx's hooks accept
exactly the planes `dtype` names (code width and table length, scale dtype and group, `fwht128`)
and refuse any other selection at declare with `RAD_E_DTYPE`. libref computes the form as
@@ -2374,6 +2426,7 @@ wrong.
| `gdn_chunk_scan` | `M`(range) `head_k` `head_v` `chunk`/der `scale`:f64/opt `state_fp16`/opt | `q`,`k`,`v`,`A`,`g`,`beta`,`h0`?,`cu` → `o`, `ht`?; `state_idx`? |
| `gdn_recurrent_update` | `q_len`(range) `head_k` `head_v` `n_head_v`/opt `scale`:f64/opt `eps`:f64/opt `l2_eps`:f64/opt `softplus_thr`:f64/opt `act`:str/opt `state_fp16`/opt `state_form`:str/opt | `q`,`k`,`v`,`a`,`b`,`A_log`w,`dt_bias`w,`state`:inout,`state_idx`,`num_accepted`,`cu`,`z`?,`norm_w`w? → `o`,`o_q`?,`o_scale`? |
| `gdn_conv_recurrent_update` | `q_len`(range) `head_k` `head_v` `conv_width` `n_head_v`/opt `scale`:f64/opt `eps`:f64/opt `l2_eps`:f64/opt `softplus_thr`:f64/opt `act`:str/opt `state_fp16`/opt `state_form`:str/opt | `x`, `conv_w`w, `conv_b`w?, `conv_state`:inout, `conv_idx`, `a`,`b`,`A_log`w,`dt_bias`w,`state`:inout,`state_idx`,`num_accepted`,`cu`,`z`,`norm_w`w → `o`,`o_q`?,`o_scale`? |
| `gdn_conv_recurrent_update_had` | `q_len`(range) `head_k` `head_v` `conv_width` `n_head_v`/opt `scale`:f64/opt `eps`:f64/opt `l2_eps`:f64/opt `softplus_thr`:f64/opt `act`:str/opt `state_fp16`/opt `state_form`:str/opt `group`/opt | `x`, `conv_w`w, `conv_b`w?, `conv_state`:inout, `conv_idx`, `a`,`b`,`A_log`w,`dt_bias`w,`state`:inout,`state_idx`,`num_accepted`,`cu`,`z`,`norm_w`w → `o`,`o_q`,`o_scale` |
| `gdn_gated_rmsnorm` | `M`(range) `channels` `eps`:f64 `act`:str | `x`, `z`, `w`w → `o` |
**`kda_update` is Kimi delta attention with per-channel decay.** Per token and head it
@@ -2490,8 +2543,15 @@ serves the decode shape, where the fused row norm already puts one workgroup on
value head). It is byte-identical to the pair. libr4d rewrites a key head's conv state once every
value head reading it has read it, by an arrival count, so no workgroup waits on another.
**`gdn_conv_recurrent_update_had`** (device-only) is `gdn_conv_recurrent_update` whose `o_q` and
`o_scale`, here required, are `had_quant_act_i8g`'s codes of `o`: int8 after a 128-wide Hadamard
before the per-(token, head) amax, for an out projection stored rotated (`i8a8h`). It is
byte-identical to `gdn_conv_recurrent_update` followed by `had_quant_act_i8g`. `group` 256 is
IQ8R's, one scale per two value heads (`o_scale` `[tokens, n_head_v / 2]`), each head still rotated
on its own.
**The output gate `z` may be a column slice**, on both `gdn_recurrent_update` and
`gdn_gated_rmsnorm`. The fp8 delta-net block projects `[q|k|v|z]` in one GEMM
`gdn_gated_rmsnorm`. The delta-net block projects `[q|k|v|z]` in one GEMM
(`arch/common/rad_block_gdn_fp8.h`), so the gate is the right-hand `n_head_v * head_v` columns of a
wider row and its `(token, head)` rows are not evenly spaced: heads are `head_v` apart inside a
token and the next token is the slice's own stride away. An implementation that reads one pitch off
@@ -2554,7 +2614,6 @@ device code.
| op | params | operands |
|---|---|---|
| `ar_rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
| `ar_rmsnorm_post_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w |
| `ar_rmsnorm_had_quant_i8g` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
| `ar_rmsnorm_quant_i8` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt `sp`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
| `ar_rmsnorm_quant_i8g` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
@@ -2620,7 +2679,9 @@ whole form elsewhere (the host mailbox included), which keeps every promise `sp`
| `embed_lookup` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt `mult`:f64/opt | `tokens`, `wte`w → `x` |
| `embed_lookup_q` | `M`(range) `n_embd` `n_vocab` `dtype` `vocab_offset`/opt `wscale`:f64/opt | `tokens`, `wte`w, `scale`w? → `x`, `ahead`? |
| `logits_gemm` | `M`(range) `n_vocab` `n_embd` `dtype` | `x`, `lm_head`w → `logits` |
| `logits_gemm_vocab` | `M`(range) `n_vocab` `n_embd` `dtype` `vocab_offset` `rows0` `rows1`/opt `rows2`/opt `rows3`/opt | `x`, `w0`w, `s0`w, `ids0`w, `w1`w?, `s1`w?, `ids1`w?, `w2`w?, `s2`w?, `ids2`w?, `w3`w?, `s3`w?, `ids3`w?, `vrow`w → `logits` |
| `ngram_ids` | `M`(range) `heads` `ngram` `eos` | `tok`, `state`:inout, `cu`, `mult`w, `vocab_sizes`w, `offsets`w, `cache_idx`?, `has_init`?, `num_accepted`? → `ids`, `ahead_ids`? |
| `ngram_hint` | `M`(range) `heads` `ngram` `eos` `hist` | `tok`, `pos`, `cu`, `mult`w, `vocab_sizes`w, `offsets`w, `cache_idx`?, `tail`:inout → `ids` |
| `ple_gate` | `M`(range) `n` `hc` `eps`:f64 `dtype` `wadd`:f64/opt `gate_eps`:f64/opt | `k`, `q`, `v`, `w_key`w, `w_query`w, `w_conv`w → `gv`, `gvn` |
| `ple_conv` | `M`(range) `n` `width` `dilation` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `resid`?, `cache_idx`?, `has_init`?, `num_accepted`? → `y` |
| `ple_conv_bias` | `M`(range) `n` `width` `dilation` `dtype` | `x`, `w`w, `conv_state`:inout, `cu`, `resid`?, `cache_idx`?, `has_init`?, `num_accepted`?, `b`w → `y` |
@@ -2629,9 +2690,18 @@ whole form elsewhere (the host mailbox included), which keeps every promise `sp`
`logits_gemm` is separate from `gemm_nt` because `lm_head` is its own access class
(`RAD_ACCESS_VOCAB`) and because the sampler fuses against it: under the distributed top-k a rank
never materialises a full logits row (`spec.md` §9, §13). `M` is one row per sampled position,
`gather_rows` having run first. A quantised head (block fp8, int8 per row and 128 of K) reaches a
`gather_rows` having run first. A quantised head (codes and a scale plane: E4M3 or int8) reaches a
host kernel joined (Weights of several planes, above).
**`logits_gemm_vocab`** (device-only) is `logits_gemm` over a head stored as up to four width
classes of the vocabulary's rows (IQR-V4's vocabulary-weighted head, `docs/IQR.md`): class `i` is a
weight of `rows<i>` rows on this rank (`w<i>` its codes, `s<i>` its scales) and `ids<i>` the global
vocabulary id of each row, whose logit it writes; ids outside `[vocab_offset, vocab_offset +
n_vocab)` are dropped. The classes cover the rank's share of the vocabulary once. `vrow[n_vocab]`
is the inverse: each of the rank's ids' class width in the top four bits and its row in the class's
whole tensor below. libr4d's `logits_gemm_vocab_iqr` decodes every class in one launch over a bf16
`x` it rotates and holds at 16 bits, with f32 logits out.
### `gather_rows`
| op | params | operands |
@@ -2715,7 +2785,7 @@ It is a separate op, not a `dtype` on `embed_lookup`, because the operand list d
operands are positional; an optional scale operand on `embed_lookup` would also move `x` from slot
2 to slot 3 for every caller.
Where it runs is where `--ngram-placement` puts the table: the planner runs an op on the host when
Where it runs is where `ngram-placement` puts the table: the planner runs an op on the host when
every weight operand of it is `Site::Host`, and takes that from the table's placement. The table is
51.2 GB and is never staged a unit at a time (moving a whole unit to use 5 KB is the wrong shape),
so it is read where it lies:
@@ -2786,6 +2856,34 @@ prompt is already known (`RadBatch::n_ahead`, stored in `token_ids` after the st
output depends on it, so a kernel may ignore it; libavx's row hands them to a reader thread that
fills its row cache while the step runs.
### `ngram_hint`
At decode with a serial draft head the same wait has another answer. A verify step's rows are the
token the last verify chose and the head's proposals, and the head proposes one a pass: its
history pass ends at the chosen token, each later round reads the proposal before it. Every row of
the next verify step but its last is therefore known a draft pass or more before `ngram_ids`
hashes it.
`ngram_hint` computes, on a draft pass, `ngram_ids`' hash for each sequence's newest token:
- `hist` 1, the history pass: the sequence's last row is the chosen token. Rows at its position
repeat it (the pass pads a run to the furthest the verify could have committed) and the rows
before them hold the ids committed just before, in order.
- `hist` 0, a later round: the sequence's one row is the proposal before this round's.
`tail` is [slots, 2 * (ngram - 1)] i32: per state slot (`cache_idx`, the row index when absent,
taken modulo `slots`) the `ngram - 1` committed ids up to the chosen token and the same count up
to the newest proposal, each newest last. The history pass takes ids further back than its rows
from the committed half and leaves both halves ending at the chosen token; a round reads and
extends the proposal half. `ids` is [n_seq, heads], a row a sequence; `M` is the sequence count.
The ids are a hint for fetching rows ahead: the plugin gathers them with `embed_lookup_q` at the
end of the draft pass into a buffer nothing reads, which for a table on a drive fills the row
cache while the card drafts, and the verify step's gather then waits for its last row's reads
only. No output of the model depends on them. A tail left by another request names rows nobody
reads, so there is no cold rule, and a sequence with no rows gets its heads' first rows. A library
without the op costs nothing: the plugin declares the hint only where one serves it.
### `ple_gate`
PLE's mixing coefficient is a dot product between the n-gram embedding and the residual stream, one
@@ -2900,10 +2998,11 @@ resolutions of one op. The one exception is `sample_chain` (below).
| `sample_logprobs` | `M`(range) `n_vocab` `k` `vocab_off`/opt | `logits`, `params`? → `stats` |
| `mtp_couple_propose` | `M`(range) `n_vocab` `round` `max_rounds` `q_temp`:f64/opt | `idx`:inout, `val`, `seq_ids`, `draw` → `state`:inout |
| `mtp_couple_verify` | `M`(range) `n_cand` `n_vocab` | `cand_idx`, `cand_val`, `params`, `state` → `token`:inout |
| `mtp_trav_verify` | `M`(range) `n_cand` `n_vocab` | `cand_idx`, `cand_val`, `params`, `state` → `token`:inout, `topo` |
| `dflash_couple_propose` | `M`(range) `steps` `top_k` `rank` `n_vocab` `anchor_stride` `max_rounds` `q_temp`:f64/opt | `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w, `seq_ids`, `draw`, `tokens`:inout → `state`:inout |
`mtp_couple_propose`, `dflash_couple_propose` and `mtp_couple_verify` are the speculative coupling
(`--draft-coupling on`), and nothing else in the engine knows about coupling. Turning coupling on
`mtp_couple_propose`, `dflash_couple_propose`, `mtp_couple_verify` and `mtp_trav_verify` are the
speculative coupling (`draft-coupling: on`), and nothing else in the engine knows about coupling. Turning coupling on
requires a linear chain of drafts: a serial head's rounds, or a block drafter whose architecture
declares the coupled walk (DFlash2); no drafter, or a block drafter without the walk, is refused at
bringup, because neither has a per-round draw to couple. The `spechub` plugin ships every row and
@@ -2923,7 +3022,20 @@ token the target itself drew at that position, and otherwise the token is a draw
residual `(P - Q)+`. Both use 53-bit uniforms at `params.pos`; a row whose state is not bound to
that seed and position keeps the ordinary token. `P` is FP64-normalised where `sample_pick` is
FP32/24-bit, so a coupled row realizes the ideal filtered target law and is **not** seed-identical
to the ordinary pick.
to the ordinary pick. A state whose `blk` is at least 1 is the first row of a block, which the same
op decides together with the rows after it (`draft-verify: block`, Block Verification, arXiv
2403.10444, abi/rad_mtp_block.h): the workgroup of its round-1 row writes the tokens of rows 0 ..
tau and the block's other rows return.
`mtp_trav_verify` replaces `mtp_couple_verify` under `draft-verify: traversal` (Traversal
Verification, arXiv 2505.12398, abi/rad_mtp_traversal.h). Its sixth operand `topo` is `[M, 2]` int32
per sampled row: the parent's row in the step (-1 for a request's first row, the root of its tree)
and the row's own draft token; the rows of a request are contiguous, root first, parents before
children. One workgroup a request, on its root row, decides the whole request: the target's law of
each row as integer masses of a fixed-point exponential, the walk from the last draft back to the
first in FP64, and the tokens of the accepted path and the final token written into `token`. Rows
whose state is not eligible are leaves and keep the ordinary token. Any `n_cand`. The kernel has no
scratch segment. It emits the same law as the row-wise verify and accepts at least as many drafts.
`dflash_couple_propose` is DFlash2's block walk sampled (abi/rad_spechub.h,
`rad_dflash_couple_step`). It runs right after `dflash_select` over the same lattice, one workgroup a
@@ -3180,21 +3292,21 @@ is docs/KV-STREAMING.md §3.4.
The layouts, which the schema cannot state (the op is the same code at every cache layout):
- **`sel`** — `i32 [M, sel_pitch]`, inout: block ids in, ring slots out, below `nsel[q]`; the `-1`
- **`sel`**: `i32 [M, sel_pitch]`, inout: block ids in, ring slots out, below `nsel[q]`; the `-1`
padding past it is untouched.
- **`nsel`** — `i32 [M]`, in: the valid entries of each row. Above `sel_pitch` is refused.
- **`res`** — `i32 [blocks]`, inout: block -> slot, or `-1` absent (`-2` is a claim within a call).
- **`slot_block`** — `i32 [slots]`, inout: slot -> block, or `-1` free. Its extent is the ring the
- **`nsel`**: `i32 [M]`, in: the valid entries of each row. Above `sel_pitch` is refused.
- **`res`**: `i32 [blocks]`, inout: block -> slot, or `-1` absent (`-2` is a claim within a call).
- **`slot_block`**: `i32 [slots]`, inout: slot -> block, or `-1` free. Its extent is the ring the
call may address; the declared `slots` (the carved ring, `RadBuildCtx::kv_resident_blocks` in
blocks) is the ceiling it may not pass.
- **`slot_state`** — `i32 [slots, 2]`, inout: the epoch of the slot's last use, and a two-bit heat
- **`slot_state`**: `i32 [slots, 2]`, inout: the epoch of the slot's last use, and a two-bit heat
counter in `[0, 3]`, bumped on a use (once a slot a call) and halved when the sweep passes.
- **`ctl`** — `i32 [16]`, inout: `[0]` epoch, `[1]` clock hand, `[2]` blocks placed by the last call,
- **`ctl`**: `i32 [16]`, inout: `[0]` epoch, `[1]` clock hand, `[2]` blocks placed by the last call,
`[3]` overflow (latched), u64 misses, lookups and calls from `[4]` (8-byte aligned), and the
largest union `[10]`, placement `[11]` and claim count `[12]` of one call: the measurements a ring
and a claim list are sized from.
- **`host`** — bytes `[blocks, block_bytes]`, in: the layer's mirror, block `b` at `b * block_bytes`.
- **`kv_cache`** — bytes `[slots, block_bytes]`, inout: the layer's ring, `RAD_KV(group, layer)`.
- **`host`**: bytes `[blocks, block_bytes]`, in: the layer's mirror, block `b` at `b * block_bytes`.
- **`kv_cache`**: bytes `[slots, block_bytes]`, inout: the layer's ring, `RAD_KV(group, layer)`.
One call:
@@ -3218,7 +3330,7 @@ One call:
7. **Rewrite** every valid entry as its slot.
- **The ring must hold one call's selection union** (`hits + misses <= slots`): a decode step's is at
most `max_seqs * (1 + n_spec) * (topk + 1)` blocks, the floor `--kv-resident` is raised to, and
most `max_seqs * (1 + n_spec) * (topk + 1)` blocks, the floor `kv-resident` is raised to, and
prefill takes the stage instead. An unplaced miss reverts to `-1`, its entries become slot 0 (a
defined address; a block id would be read past the ring) and `ctl[3]` latches; the caller must
discard the step.
@@ -3314,8 +3426,8 @@ row, the softmax channels and the Hadamard in registers, pitched rows.
`dsa_query` rotates each bf16 query head by the same normalized Walsh-Hadamard transform, rounds
to bf16, and quantises to E4M3 with the same power-of-two scale: `x` `[M, n]`, `q` `[M, n]`,
`scale` `[M, 1]`, token and head flattened into `M`. There is no RoPE and no RMS norm. Unlike
`had_quant_act_fp8`, both the normalization of the rotation and the power-of-two scale are part of
the op. `n` is a power of two up to 256.
the trunk's rotated quantisers (`had_quant_act_i8g`, `hc_read`'s `rq`), both the normalization of
the rotation and the power-of-two scale are part of the op. `n` is a power of two up to 256.
libr4d's `dsa_query_fp8` serves `n` 128, one wave per query head, pitched rows.
+22 -17
View File
@@ -67,7 +67,7 @@ Five more exports are optional, each looked up by exactly this name:
| `void rad_plugin_close(void)` | called once at shutdown |
| `int rad_kernel_concurrent(int i)` | nonzero: kernel `i` touches nothing but its operands and scratch, so independent launches may overlap |
| `int rad_kernel_collective(int i)` | nonzero: kernel `i` exchanges data with the other ranks' cards, so the engine keeps its own bulk link traffic away while it runs. 2: each launch ends that hold itself once the other ranks' bytes have landed, through the `link_gate` parameter (`rad_abi.h`). Without this export only the `all_reduce` op is a collective |
| `int rad_plugin_reference(void)` | nonzero: a **reference implementation**, ranked below every unnamed library, refused for serving unless `--debug-accept-reference-kernels`, and what `rad-kbench` checks the others against. libref declares itself this way |
| `int rad_plugin_reference(void)` | nonzero: a **reference implementation**, ranked below every unnamed library, refused for serving unless `server.debug-accept-reference-kernels`, and what `rad-kbench` checks the others against. libref declares itself this way |
| `int rad_kernel_reference(int i)` | per row: nonzero marks kernel `i` as a reference implementation and 0 as a production one, overriding `rad_plugin_reference` for that library. For a plugin that ships a device row and its host oracle side by side (`plugin/spechub`) |
---
@@ -113,7 +113,7 @@ machine. A machine fact changes no tuning key. A tool selecting without an engin
nothing, so such a kernel is not selected there.
**Priority.** `priority` breaks ties within one plugin, highest first, then declaration order.
Between plugins the hierarchy is absolute: the first plugin in `--kernels` order with any matching
Between plugins the hierarchy is absolute: the first plugin in `server.kernels` order with any matching
kernel supplies it, however specialised a later plugin's kernel is. That makes a user's library an
override rather than a competitor.
@@ -278,11 +278,11 @@ It also checks:
A skipped kernel is reported with the reason, usually a missing `opd_shape` (§4). Other
diagnostics:
- `--debug-selection` prints the selection table: which kernel took each band, and the constraint
- `debug-selection: true` prints the selection table: which kernel took each band, and the constraint
that refused each other candidate;
- `/graph` on a running server returns the declared graph and which declarations the run phase has
issued, which finds a band resolved for nothing;
- `--debug-accept-reference-kernels` is required to serve with a reference fallback; without it a
- `server.debug-accept-reference-kernels: true` is required to serve with a reference fallback; without it a
fallback is fatal, because a reference kernel in production would look like a performance
problem;
- `rad-info --plugins` prints every plugin on the search path as the engine loads it: kind, version,
@@ -318,13 +318,14 @@ what the host has available and leaves an eighth of host memory to the host.
The core assumes nothing about a card's wave size, LDS, fp8 hardware or links. Three points matter:
- **The vocabulary is what you implement.** A model runs on your library when every op its
architecture issues has a row there (`docs/OPS.md`; `--debug-graph` lists them). The bf16 models
architecture issues has a row there (`docs/OPS.md`; `debug-graph: true` lists them). The bf16 models
in the tree issue only ops libref implements (MiniCPM5-2B: 13 model ops and 11 sampler ops), so
libref's host code is the specification and `rad-kbench` the check. Ops `docs/OPS.md` marks
**device-only** are libr4d's and have no reference; the fp8 models and a drafter with a 2-bit
head issue some.
**device-only** are libr4d's and have no reference; the quantised models and a drafter with a
2-bit head issue some.
- **fp8 bytes are OCP E4M3** (`e4m3fn`, bias 7, max 448) wherever the engine reads them: container
weights, the KV cache at `--kv-cache-dtype fp8`, activations between ops. A card whose fp8 is
weights (Flash-Next's mixing matrices, its n-gram table, the codebook experts' scales), GLM-5.3's
latent cache at `kv-cache-dtype: fp8`, activations between ops. A card whose fp8 is
`e4m3fnuz` (gfx942) converts weights in its `relayout` hook (the codes keep their bits except
0x80 and decode to half the value, so the scale doubles) and keeps activations and KV in OCP
bytes, or converts at its own boundaries.
@@ -359,8 +360,9 @@ underscores; `rad-convert --arch ID` overrides it. Every configuration key reach
`RadModelMeta`, and the plugin's name map says which checkpoint tensor each declared weight comes
from, so `rad-convert` needs no knowledge of the model.
A checkpoint whose quantisation was imported weight by weight (GUIDE §3.2: Quark, ParoQuant, GPTQ,
NVFP4) names its producing tool, which no plugin claims; it goes to the family's one quantised
A checkpoint whose quantisation was imported weight by weight (GUIDE §3.2: GPTQ, AutoRound,
compressed-tensors, and the Quark, ParoQuant and NVFP4 releases a recipe re-quantises) names its
producing tool, which no plugin claims; it goes to the family's one quantised
plugin, and two are refused by name. A second quantised plugin that reads only its own containers
says so with `RAD_ARCH_SERVES_IMPORTS(0)` (`qwen35_w8a8` does), and imports keep their plugin.
@@ -402,7 +404,7 @@ says so with `RAD_ARCH_SERVES_IMPORTS(0)` (`qwen35_w8a8` does), and imports keep
at either; the short block proposes `block - (RadDrafterDecl::block - depth)` tokens. A tree
drafter (`rad_drafter_tree`, called first) grows a tree of its own over the shorter pass, at most
`block - 1` nodes, and its short block needs only 2 rows. The builder refuses it without a block
drafter, at or above the drafter's own block, and where it would propose nothing. The engine runs it under `--draft-short-from` (GUIDE §4.6) and reads row `s` of
drafter, at or above the drafter's own block, and where it would propose nothing. The engine runs it under `draft-short-from` (GUIDE §4.6) and reads row `s` of
the proposals at `s * proposal_pitch`; a block drafter's `proposal_pitch` defaults to its
depth (a row holds the whole block's proposals and a short block fills its front) and is refused
below it. The pass's block is `n_tok / n_seq`; a block the plugin has no ops for should fail the
@@ -440,7 +442,7 @@ const RadQuantizerInfo* rad_quant_at(int i); /* name, doc, options, encoding,
```
# PATTERN QUANTISER OPTIONS
blk.*.ffn_*_exps.*.weight myquant bits=3 group=64
* rtn codes=fp8_e4m3 block=128x128 scale=bf16
* rtn codes=i8 group=128 scale=bf16 clamp=sym
```
`rad-convert --list-quantizers` prints every loaded quantiser and its options. A recipe option the
@@ -491,17 +493,20 @@ built against; `RAD_PLUGIN_INSTALL_HOME` overrides that. Before installing, the
the same name later. Your plugins go ahead of an installation without copying it:
```sh
RADIANCE_HOME=$HOME/radiance-plugins:/opt/radiance/share/radiance radiance --model ...
RADIANCE_HOME=$HOME/radiance-plugins:/opt/radiance/share/radiance radiance --config radiance.yaml
```
The same path can be set as `server.radiance-home` in the YAML file instead.
The container image takes one the same way, mounted:
`-v /my/plugins:/plugins -e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance`.
**The kernel hierarchy** is `--kernels` (or `$RADIANCE_KERNELS`), an ordered list of the kernel
libraries to use: `--kernels mykernels,libr4d` puts yours before libr4d. An entry matches a
**The kernel hierarchy** is `server.kernels` in the server's YAML file, `--kernels` on a tool (or
`$RADIANCE_KERNELS` for both), an ordered list of the kernel libraries to use:
`kernels: mykernels,libr4d` puts yours before libr4d. An entry matches a
plugin's name or its file (`libr4d`, `r4d`, `libr4d.so` and a path to it are one library); an entry
matching nothing is warned about by name. Separate entries with commas or colons
(`mykernels:libr4d` is the same list); the engine and every tool read `--kernels` and
`$RADIANCE_KERNELS` by this one rule, and an empty `$RADIANCE_KERNELS` counts as unset. A kernel library the list does not
(`mykernels:libr4d` is the same list); the engine's `kernels` key, every tool's `--kernels` and
`$RADIANCE_KERNELS` follow this one rule, and an empty `$RADIANCE_KERNELS` counts as unset. A kernel library the list does not
name is not loaded, so name every library you want, including the host library (`libavx`) and the
reference (`libref`). With no list every library found loads, a reference library (§1) last.
+12 -8
View File
@@ -166,9 +166,9 @@ git clone https://codeberg.org/StillDeadcode/radiance.git
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
mkdir -p ~/models/rad
curl -L -C - -o ~/models/rad/qwen3.8-next-flash-fp8-iq4r-moe.rad \
https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe/resolve/main/qwen3.8-next-flash-fp8-iq4r-moe.rad
# 114 GiB; -C - resumes after an interruption
curl -L -C - -o ~/models/rad/qwen3.8-next-flash-iqr-v4.rad \
https://huggingface.co/StillDeadcode/qwen3.8-next-flash-iqr-v4/resolve/main/qwen3.8-next-flash-iqr-v4.rad
# 113 GiB; -C - resumes after an interruption
cp .env.example .env && chmod 600 .env
```
@@ -182,9 +182,13 @@ Set these in `.env`:
| `RADIANCE_UID`, `RADIANCE_GID` | `id -u`, `id -g` |
| `RENDER_GID`, `VIDEO_GID` | `getent group render \| cut -d: -f3`, the same for `video` |
`tp2.yaml` serves eleven models from one container, each under its entry's name in the `models:`
block of `tp2.radiance.yaml` beside it. With only Flash-Next's container downloaded, delete every entry there but
`flashnext` (the request below names no model, which a file of one model answers with that one).
```sh
docker compose -f flashnext.yaml up -d
docker compose -f flashnext.yaml logs -f # Ctrl-C once it serves; the container keeps running
docker compose -f tp2.yaml up -d
docker compose -f tp2.yaml logs -f # Ctrl-C once it serves; the container keeps running
```
The startup log must say `device: the 2 cards reach each other's memory directly (peer to peer)`. A
@@ -198,6 +202,6 @@ curl -s localhost:8000/v1/chat/completions -H "Authorization: Bearer $KEY" \
-d '{"messages":[{"role":"user","content":"What is 65 * 3?"}]}'
```
The container restarts with the machine. `docker compose -f flashnext.yaml down` stops it.
[`DOCKER.md`](DOCKER.md) lists the other models' compose files, and [`GUIDE.md`](GUIDE.md) covers
serving flags and the API.
The container restarts with the machine. `docker compose -f tp2.yaml down` stops it.
[`DOCKER.md`](DOCKER.md) covers the compose files and adding other models to them, and
[`GUIDE.md`](GUIDE.md) covers serving flags and the API.
+69 -6
View File
@@ -64,9 +64,68 @@ With `pos + 1 <= budget + ratio - 1 = 2051` visible tokens there are at most 512
the top-k keeps all of them and the tail is always attended, so QSA equals dense causal attention
bit for bit. Below the bound, a step with more than one query per sequence (prefill, mixed or
speculative) issues dense attention, which reads each key once per query tile where the sparse
path reads a table per query. Plain decode (one query per sequence) takes the sparse path at every
context: there is no tile to amortise, and the sparse path stays exercised. The bound is the test
for every change here (see "Checking").
path reads a table per query. Plain decode (one query per sequence) takes the sparse row's launch
at every context: there is no tile to amortise, and the sparse kernel stays exercised. The bound is
the test for every change here (see "Checking").
## Below the bound
At or below the bound the selection does not depend on the scores: every complete block, in
block order, then the partial page. So a step that is *entirely* at or below it scores and selects
at most once for the whole pass, and where nothing reads a selection not at all. The attention
block decides (`AttnGatedFP8::qsa_use`, `arch/common/rad_block_attn_gated_fp8.h`) and hands the
answer to the indexer, which runs first (`QsaIndexer::step`'s `use`):
| the step, at or below the bound | attention (unchanged) | the indexer issues |
|---|---|---|
| several rows a sequence, rounded bound within the budget (a chain verify, a head's history pass, prefill, mixed) | dense, over the block table | per layer: the projection, `qsa_work`, `qsa_block_key`, `qsa_tail_store` |
| one row a sequence (plain decode, a serial head's round) | the sparse row's launch over the sequence's **block table** and `seqused` | the same four |
| several rows a sequence, rounded bound past the budget (the same steps between 1025 and 2047 tokens) | the sparse row a query, over the selection | the first full-attention layer of the pass: everything, as before; every other layer: the same four |
| anything past the bound, a streamed attention group, `RADIANCE_DEBUG_QSA_EAGER` | as before | everything, per layer |
**The attention's kernel never moves.** Which kernel a step's attention runs is decided exactly as
before (dense by the rounded bound, the sparse row otherwise): the dense and the sparse kernel read
the same keys below the bound but sum them in another order, and a verify's rows feed the next
step, so a different kernel at the same context is other text at a near-tie. Only *who makes*
the selection changes, and it is byte for byte the selection each layer made for itself.
**The stateful half always runs.** Block keys and the tail are what later steps score and build
on; only the query side and the scoring are skipped.
**The block table in place of the selection** is exact because of what `qsa_select` writes below
the bound for a row at position `p` of a sequence whose context ends there: `sel` is the table's
first `ceil((p + 1) / ratio)` entries and `seqused` is `p + 1`, the sequence's own. The launch is
the same op and kernel (`attn_paged_gate_quant`, `q_len` 1), its split count does not read the
table's width, and it sums pages in the same order, so the bytes are the selection's. It holds for
a row that is alone in its sequence and at the context's last position, which the architecture
vouches for (`qsa_table_rows`: a plain decode row and a serial head's round on Qwen4-Exp), and it
is taken only when `max_q_len == 1`.
**One selection a pass** (`kQsaOnce`) is exact because below the bound a row has at most `topk`
complete blocks, so `qsa_select` takes every block whose key is not 0 -- any block with a page and
a score that is a number -- and what it writes (the pages in block order, the partial page, the
count, `seqused`) depends on the positions and the block table alone: every layer's scores give the
same bytes. The first full-attention layer of the pass therefore issues its selection exactly as
before (query, scores, `qsa_select`) and every later layer's attention reads that one; the later
layers issue no query, no score and no select. `sel`, `nsel` and `seqused` are the model's buffers,
live across its layers, and nothing else writes them. The MTP head has one such layer and so issues
what it always did.
One consequence is deliberate: a block whose score is not a number (a NaN block key) is dropped
or kept for the whole pass as the first layer's score has it, and is always kept where no
selection is made, as the dense attention always kept it.
**Whether a step is within the bound is the group's exact ceiling.** `max_ctx_len` is rounded up to
1024 tokens so a recorded pass replays (`core/sched/batch.cpp`, `bound_bucket`); by it a 4-row
verify is "past" the budget from 1025 tokens of context on. `RadBatch::kv_used_max_h[group]` is the
exact host ceiling of every row's `position + 1` (context plus this step's rows, the furthest a
row issued ahead can be), and `qsa_within` reads it where the architecture's pass key carries
which side of the bound it is on (`qsa_exact_host`; `qwen4exp_fp8.cpp`, `pass_key`). The cost is
one more recording of each pass kind when a request crosses the bound.
Per chain verify step of Qwen3.8-Flash-Next (12 QSA layers) this removes 36 launches up to 1024
tokens of context and 33 from there to the bound, and 3 a head pass up to 1024 tokens (its rounds
up to the bound).
## Attention over a selected set
@@ -175,15 +234,15 @@ attention sums its softmax over pages in table order, and float addition is not
**The score plane is the one buffer whose size is a product of the deployment's bounds** — a row
of `max_ctx / ratio` floats a query, 512 MiB at a 2048-row step and 256K of context. Under
`--prefill-span`, where every step that mixes sequences fits in a MoE pass
(`RadBuildCtx::max_mixed_tok`), it is declared a pass tall instead of `--max-num-batched-tokens`
`prefill-span`, where every step that mixes sequences fits in a MoE pass
(`RadBuildCtx::max_mixed_tok`), it is declared a pass tall instead of `max-num-batched-tokens`
rows: a wider step is one sequence, scored and selected in windows of the plane's rows, each handed
as a sequence of its own rows. Every operand a query row reads is its own (query, position,
selection), so a row is scored and selected exactly as in one pass, and a row two windows share is
written twice with the same bytes.
**The caller bounds the history.** Both ops size their grid from the declared width (the live count
is device data), so a short prompt would otherwise launch for the whole `--max-model-len`. The
is device data), so a short prompt would otherwise launch for the whole `max-model-len`. The
architecture narrows the score operand's column count to a host-side ceiling from the batch, with
the pitch unchanged. **Every term of the ceiling is generous**, because an underestimate silently
drops blocks.
@@ -203,6 +262,10 @@ with:
form, and split against unsplit at bit identity on mostly-tied scores, so the tie rule decides;
- **`RADIANCE_DEBUG_QSA`**: prints `nc`, `nsel`, `seqused` and the head of the table for the first
few steps. `nc` above `topk` is intended dropping, not a divergence. It synchronises the stream.
- **`RADIANCE_DEBUG_QSA_EAGER`**: every step scores and selects per layer, the issue sequence
before "Below the bound" existed (`tests/arch_test.cpp`'s pinned step hashes are the old ones
under it). Greedy text with and without it must be byte-identical, drafts included: at or below
the bound the two differ only in what is launched, never in a byte the attention reads.
**Count the reach, not the prompt.** The bound is on the context each query sees, so a prompt a
few tokens under it crosses the bound during decode and is expected to start differing there.
-177
View File
@@ -1,177 +0,0 @@
# Spark X2.6 4B IQ8R: recipes, provenance, and validation
`arch/spark25_w8a8` serves Spark X2.6's six dense projections per layer on the `fwht128` rotated
int8 grid. It requires `quantization_config.quant_method=w8a8` and
`quantization_config.fmt=fwht128`; activations use `had_quant_act_i8g` and weights use `gemm_nt_q`
with `dtype=i8a8h`. The embedding and small per-head attention gate stay BF16; norm gains stay
FP32. Calibration is TP=1 so the Gram matrices retain cross-rank terms.
## Recipe choice
The container format does not choose a recipe or change a launcher default. Select one explicitly
when converting a BF16 source checkpoint:
| Allocation | Recipe | Published container size | Measured distribution parity | Performance note |
|---|---|---:|---|---|
| Quality-preferred tested hybrid | `data/recipes/spark-x26-4b-iq8r-keep12.recipe` | 5.67 GiB (6,092,100,608 bytes) | 99.111% top-1 agreement; top-128-plus-tail KL mean 0.000677, p99 0.00923, p99.9 0.04013, max 0.24712 | About 12% less prefill and 17% less decode throughput than full IQ8R in the reported single-card comparison |
| Full IQ8R, explicit speed/size tradeoff | `data/recipes/spark-x26-4b-iq8r.recipe` | 4.52 GiB (4,853,470,208 bytes) | 98.595% top-1 agreement; top-128-plus-tail KL mean 0.004077, p99 0.04960, p99.9 0.34814, max 11.8832; 13 positions exceed 1 nat | Prefill 11.8k / 11.8k / 11.3k tok/s at 1.1k / 4.4k / 9.9k-token prompts; decode 93.7 tok/s at short context and 88.9 tok/s at 4.4k context |
| Source BF16 | no recipe | 8.29 GiB | reference | Baseline |
For the keep12 allocation, six explicit rules cover each projection in layers 12–35. Layers 0–11
have no matching rule and retain their BF16 checkpoint encoding. The output head remains RTN in both
IQ8R recipes; unmatched tensors (including the embedding and attention gate) retain their source
encoding. The full recipe is not quality-preferred and is not applied implicitly. Neither measured
allocation establishes task accuracy or universal quality for all prompts and uses.
The reported KLD values above are **not exact full-vocabulary KL**. They use Radiance's sparse
`--kld-top 128` form: the reference's top 128 token probabilities plus one bucket for all remaining
probability mass, compared with the candidate on the same coarsened support. The 31,391 positions
are from a 32-document held-out evaluation; the keep12 maximum is below one nat on this set, not a
claim about all inputs. Perplexity ratios were 1.00178 (keep12) and 1.00409 (full IQ8R).
## Calibration and evaluation provenance
The published calibration dataset is
[`gostar77/spark-x2.6-4b-iq8r-calibration`](https://huggingface.co/datasets/gostar77/spark-x2.6-4b-iq8r-calibration),
revision `4b622fa2ecca376a02a83ef23ec6dfb3b7cdc52b`. Its `CALIBRATION-MANIFEST.json` records
Spark X2.6 4B, `RADGRAM2`, TP=1, all 36 layers and six projection types. It contains 216 validated
Gram files (21,290,294,016 bytes; about 19.83 GiB) accumulated over 65,660 tokens. The prompts
were 100 selected document beginnings from `swift15-public-corpus`, with selection seed `20261031`
and every fourth candidate wrapped in the Spark chat format. The published dataset is CC BY-SA 4.0;
its `SHA256SUMS` covers the Gram files. The local manifest used for this record is
`/mnt/gostar_data/radiance-builds/hf-publish/spark-x2.6-4b-iq8r-calibration/CALIBRATION-MANIFEST.json`
(SHA-256 `f2225de42cfc885dca2720128143487296a5ba8c33cc797de0bac2b2bcebf007`); its local
`SHA256SUMS` has SHA-256 `f8d14fc575875e33045c2231013e87da52da8db4e21f692c363464d858dbbb18`.
The evaluation manifest is
`/mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/independent-chat-eval.manifest.json`
(SHA-256 `a8528f193986b7267b7ec5b5a447c0d1f5271d5c2f7f004ceb8ba543e5168f4d`). It identifies a
separate held-out source file, `/mnt/gostar_data/radiance-calib/qwen3.8-flash-next-base-w5dn64/corpus/heldout.jsonl`
(source SHA-256 `2c3935512dbf0b09c8fea88be19f7d31447a540de57133a54f97e6e172f15532`), selection seed
`7132026`, and 8 examples each from tools, math, prose, and code. Two high-overlap candidates were
excluded; the manifest describes a sampled 20-gram overlap check against the 100 diverse calibration
documents and the original nine. That check is not proof of zero semantic overlap. Math/tool rows
score assistant continuations; prose/code rows score text after 32 tokens. The resulting local KLD
corpus is `/mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/independent-chat-eval.jsonl`
(SHA-256 `468d9c6037a17475688ba432d804618c10d15288b4d5fe538b7ac4c0ab725ace`).
The recorded matched-reference artifacts are local and were not copied into this repository:
- BF16 sparse reference: `/mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/rowfix-bf16-ref128/`
(`kld.json` SHA-256 `b722b8a956b747dd932413204d9ae0775bd2bd50377f0466134cc922ad83b026`).
- Full IQ8R report and per-row file: `rowfix-diverse-kld.json` and
`rowfix-diverse-kld.json.rows` (report SHA-256
`0f7368c83a3c9a896aa42bcbdf8022db526517f7fc4a9e680747ccd2b66bdee9`).
- Keep12 report and per-row file: `rowfix-keep12-kld.json` and
`rowfix-keep12-kld.json.rows` (report SHA-256
`d6b577c1e6f7fc5c40814744bea22079998562229eaa2b2a892274544a149dbf`).
- `rowfix-keep12-kld.json` records `ref_form: "top-128 + tail"`, reference `rowfix-bf16-ref128`,
`all.positions: 31391`, mean KL `0.0006770557376511436`, maximum KL `0.2471124678850174`, and
99.1112% top-1 agreement. These are coarsened top-128-plus-tail KL values, not exact
full-vocabulary KL. `rowfix-diverse-kld.json` uses the same `rowfix-bf16-ref128` reference and
31,391 positions. The reference metadata records corpus FNV-1a `17d9069a2711c745`; the companion
`.json.rows` files contain the per-position score rows (KL, candidate NLL, reference NLL, top-1
match).
The measured rowfix comparison used Radiance source commit `54f2602367eb96ca08674095f7e32506fd7d752b`
(the build tree points to `/mnt/gostar_data/radiance-worktrees/spark-x2-6`), `libr4d@0.5.0`, TP=1,
BF16 KV, `--max-model-len 4096`, `--max-num-seqs 1`, `--max-num-batched-tokens 128`, no speculation,
and prefix cache disabled. The prerequisite shared prefill correction is #362,
`7480da3d46b0475d9d77966e31284cc19072759`. **Those parity figures are for the tree with #362**;
#363's original `5024aea` ancestry did not contain it. Do not attribute these numbers to standalone
#363 or to a build without #362. A fresh GPU TP2 validation is separate and remains outstanding.
Published container checksums from `/mnt/gostar_data/radiance-builds/hf-publish/SHA256SUMS`
(SHA-256 `3c14ea79cb8b7b3aba8807dd43101aa84110636e914eb2008eb2ba3a387e3d1b`):
| Container | SHA-256 |
|---|---|
| `spark-x2.6-4b-radiance-bf16.rad` | `39694f258a3bb1e8367690a5d26762061226f3166125e929c6e33a4981583b6c` |
| `spark-x2.6-4b-radiance-iq8r-diverse.rad` | `2f6982f12b43d1e7621326c5c05a3764ef62defbbd4f59c708f9db698a14b0e5` |
| `spark-x2.6-4b-radiance-iq8r-keep12.rad` | `5a12f1f4c6cb1b2a545344bcb800cd829dc53de6cefa7a6bd9d4e2ed9fee2740` |
## Sharding alignment
A shard must own whole 128-column scale groups for a column-sharded IQ8R input; the architecture
rejects any computed span whose count is not group-aligned. It splits the FFN in whole 128-channel
units when the model width permits, using a ragged remainder-first partition. For Spark's
10,240-channel FFN there are 80 such units: TP=3 gets 27, 27, and 26 groups (3,456, 3,456, and
3,328 channels), all aligned. TP=3 is **not** categorically unaligned or unsupported. The synthetic
wide fixture checks TP=1..8; actual device support still depends on the selected kernel library and
required collectives. Calibration itself remains TP=1.
## Reproduce matched KLD and tail replays
Use a private output directory; the reference is immutable once recorded. The harness hashes the
checkpoint, executable, corpus, evaluation manifest, and **kernel, architecture and optional quantizer
shared-object inventories** into `run.json`. This includes the architecture graph plugin, not only
`libr4d.so`; an optional source revision is context, not proof that a binary was built from it. The
inventory must remain unchanged during the measurement. These probes accept one explicit home, not
a colon-separated home search path. They replay the same corpus against BF16 once and score each
candidate with fixed chunking/cache/TP flags. A reference `provenance.json` binds the BF16 model bytes,
corpus, runtime/plugins, settings and recorded data files. `--reuse-reference` requires this binding
to match; legacy unbound references must be recorded afresh, not relabelled with the supplied model.
The harness snapshots inputs before recording, checks them immediately afterward before publishing
provenance, and checks them again before publishing the run receipt. These checks detect persistent
changes, not a concurrent change that is reverted between checks; keep inputs immutable throughout.
A retry removes any previous `run.json` before measurement, so retain old receipts separately.
Reports and per-position score files are hashed into the run receipt as well:
```sh
python3 tests/spark25_quality.py \\
--radiance "$BUILD/bin/radiance" --home "$BUILD/radiance_home" \\
--reference "$BF16" \\
--corpus /mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/independent-chat-eval.jsonl \\
--provenance /mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/independent-chat-eval.manifest.json \\
--calibration-manifest /mnt/gostar_data/radiance-builds/hf-publish/spark-x2.6-4b-iq8r-calibration/CALIBRATION-MANIFEST.json \\
--source-root "$PWD" --out "$RUN" \\
--candidate "full=$FULL_IQ8R" --candidate "keep12=$KEEP12"
```
Run that process inside the host's exclusive GPU/device scope for `libr4d`. To replay a candidate's
highest-KL rows, run the following **inside the same kind of device scope**. The tool validates the
report's reference/corpus/model identities, report/row hashes, reference binding, and current runtime,
model and plugin hashes against `run.json`, then starts its own private candidate server with the
scoring run's TP, BF16 KV, model/chunk limits, speculation0 and prefix-cache-off settings. It verifies
the private served ID and the consumed prefix/completion/cache counts. Arbitrary external `--url`
servers are not accepted: a served alias alone cannot prove which checkpoint was loaded.
```sh
python3 tests/spark25_kld_tail.py \\
--run "$RUN/run.json" \\
--reference "$RUN/bf16-top128-ref" --report "$RUN/full-kld.json" \\
--out "$RUN/full-tail-replay.json"
```
The replay compares candidate top-20 log-probabilities with the stored reference top-20 for the
selected rows. The full corpus KLD report remains the top-128-plus-tail metric; top-20 replay is a
focused diagnostic, not a replacement for the full evaluation.
## Reproducible serving QoS smoke
Run this separately for each model, one process/container at a time and under an exclusive device
scope. It reuses the same evaluation prompts, disables prefix caching and speculation, and stores
per-request latency plus p50/p95/max and aggregate generated-token throughput at each concurrency.
These are end-to-end request measurements (prefill plus decode and service overhead), not decode-only
throughput or task scores. Every response must report positive integer prompt usage and exactly
`--max-tokens` generated tokens with a `length` finish (EOS is ignored for this fixed-work smoke).
Missing, zero or short counts fail the run rather than producing a successful throughput receipt.
The prompt file is parsed and hashed from the same byte snapshot and rechecked before receipt; the
private server uses a unique served model ID and is checked for identity and liveness. Requests per
repeat must be at least the largest requested concurrency. This is a client concurrency level, not
proof that requests actually overlapped in a server batch. Runtime/model/plugin hashes are also
checked again before writing the receipt; use a fresh `--out`:
```sh
python3 tests/spark25_qos.py \\
--radiance "$BUILD/bin/radiance" --home "$BUILD/radiance_home" \\
--model "$KEEP12" \\
--prompts /mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/independent-chat-eval.jsonl \\
--source-root "$PWD" --out "$RUN/keep12-qos" \\
--concurrency 1,4,8 --requests 16 --repeats 3 --max-tokens 32
```
Use identical flags, prompt file and `RADIANCE_HOME` for BF16 and full IQ8R; run them sequentially
on the same device allocation. This smoke is a reproducible validation command, not a completed
concurrent/long-context QoS certification. The held-out distribution comparison is not an external
benchmark and does not establish universal model quality.
+228 -79
View File
@@ -3,7 +3,8 @@
Every flag of every tool, with examples. Start with [GUIDE.md](GUIDE.md).
Six binaries and the `rad-export` script are installed beside `radiance`; the shell harnesses
live in `scripts/`:
live in `scripts/`. The tools take command-line flags; the server itself reads only a YAML file
(GUIDE.md §4), and [`rad-yaml`](#rad-yaml) writes that file from a server command line:
| | |
|---|---|
@@ -14,7 +15,8 @@ live in `scripts/`:
| [`rad-tune`](#rad-tune) | benchmark each kernel's tunable space at this model's shapes, on this machine |
| [`rad-schemas`](#rad-schemas) | print and diff the op schemas plugins declare |
| [`rad-tokcheck`](#rad-tokcheck) | compare the tokeniser with its reference encoder and with HuggingFace's ids over real text, and time it |
| [`radiance --kld-*`](#the-kl-mode) | KL divergence of a quantised model against the bf16 one, at every position of a corpus |
| [`radiance`, `kld-*` keys](#the-kl-mode) | KL divergence of a quantised model against the bf16 one, at every position of a corpus |
| [`rad-yaml`](#rad-yaml) | print the server's YAML file for a command line written for an earlier release |
| [`scripts/`](#the-shell-harnesses) | bring a model up, measure it, assert on what comes back |
[`rad-avx-check`](#rad-avx-check), which checks a host kernel library against libref without a GPU,
@@ -26,8 +28,9 @@ the same plugins, in the same hierarchy, through the same declare phase, so they
as the engine does.
Every tool that loads plugins honours `RADIANCE_HOME` and `RADIANCE_KERNELS`, and reads them, and
`--kernels`, as the engine does. A numeric option takes a whole number, as the engine's do: `12k`,
`auto` (where the option does not name it) or an empty value is refused with exit status 2.
`--kernels`, as the engine does with `server.kernels`. A numeric option takes a whole number, as the
engine's keys do: `12k`, `auto` (where the option does not name it) or an empty value is refused
with exit status 2.
---
@@ -42,6 +45,12 @@ rad-info --plugins [--home DIRS]
--vocab print the vocab summary and its normaliser chain, and stop
--profile N print the top N entries of the expert profile (default 20, 0 = all)
--recipe print the recipe the container was converted with, and stop
--unreferenced [N] print the byte ranges of at least N bytes (default 1048576)
that no table and no plane names, one `offset bytes` a line, and
stop: what `rad-convert --in-place --replace` left behind. Nothing
reads them, so `fallocate --punch-hole` gives their disk back.
--planes GLOB print the planes of every weight whose name the glob matches, one
`offset bytes name` a line, and stop
--plugins print every plugin the $RADIANCE_HOME search path offers, as the
engine loads it, and stop
--home DIRS the search path for --plugins (default $RADIANCE_HOME)
@@ -77,7 +86,7 @@ flashnext-w4.rad
The metadata table, the weight directory (grouped by layer and movement unit), the vocab and the
expert profile follow. With `-v`, every weight is listed with its encoding
(`fp8_e4m3*bf16[128x128]`, `i4*bf16[1x128]/fwht128`, `bf16`), its logical shape and what made it:
(`i8*bf16[1x128]`, `i4*bf16[1x128]/fwht128`, `bf16`), its logical shape and what made it:
the checkpoint as it stood, or the quantiser and options of the recipe rule that matched. Totals
are given by encoding and by what made the weight.
@@ -87,6 +96,8 @@ rad-info --vocab m.rad # vocab + normaliser chain
rad-info --recipe m.rad # the recipe, expanded, one rule a line
rad-info -v m.rad | head -40 # every tensor, its encoding, shape and planes
rad-info --profile 0 m.rad # the whole expert-popularity profile
rad-info --unreferenced m.rad # ranges nothing names: `offset bytes` lines
rad-info --planes 'blk.3.ffn_down_exps.*' m.rad # where those weights' planes sit
rad-info --plugins # every plugin on the search path
```
@@ -115,20 +126,29 @@ rad-convert [options] <input> -o <model.rad>
--config DIR config.json, generation_config.json and tokenizer.json from DIR, for a
single-file checkpoint that ships none
--imatrix F llama.cpp imatrix: expert profile, column importances, error weighting
--chat-template F a jinja template baked as the container's chat template, overriding
the checkpoint's own (or its absence)
--set K=V a metadata key, seen by declare and written into the container. Repeatable
--max-tok N the max_tok declare is run at (default 8192)
--max-ctx N the context bound declare is run at. Default: the checkpoint's
training context
--draft-model DIR a drafter that ships as its own repository, merged under `draft.`
--kv-cache-dtype T bf16 | fp8, the cache width declare is run at. Default: the first
at which every op resolves; the container is the same at either
--kv-cache-dtype T bf16 | i8, the cache width declare is run at. Default: the first of
bf16, i8 at which every op resolves; the container is the same at either
--max-spec N the max_spec declare is run at (default 4, or the block a drafter
states; a number given here is used as given). 0 leaves the draft
head out
--reuse FILE copy every weight an earlier container holds identically
--changed FILE with --reuse: checkpoint tensors (one name a line) that differ from
the --reuse container's source; every weight that reads one is converted
--lora FILE|DIR a PEFT adapter merged into the checkpoint tensors it names before they
are converted (W + strength * alpha/r * B @ A). Repeatable
--lora-strength F the strength of every --lora (default 1)
--lora-map FILE with --lora: a JSON map for adapters trained on other module names
--in-place with --reuse: extend that container instead of writing a new one
--replace GLOB with --in-place: write the matching weights again past the end where
their rule changed; the old planes stay as unreachable bytes
--defer GLOB leave the matching weights out, for a later --in-place run to add
--gpus LIST the cards (HIP device numbers, comma separated) quantisers may run on;
large weights then run two at a time. The bytes are the host's
--plan-only declare, plan every weight's encoding, print the plan, and stop
@@ -159,24 +179,28 @@ decides the numbers:
A recipe is an ordered list of rules from a logical weight name to a quantiser and its options.
The first rule whose pattern matches decides. A weight no rule matches keeps the checkpoint's
encoding, which must be one the engine serves as it is: bf16, f16, f32, or block-scaled FP8
(`X.weight` with `X.weight_scale_inv`). Anything else is named and refused.
encoding: plain f32, f16 or bf16, FP8 with a block or per-row scale plane, or Quark's MXFP4
(`core/format/checkpoint.h`, "Trivial"), or an imported form. Anything else is named and refused.
The plugins' declare then judges the planned encodings as the engine will: a block-fp8, MXFP4,
M2XFP4 or ParoQuant trunk weight is refused there by name (`linear_retired`,
`arch/common/rad_fp8.h`), so a release stored that way takes rules that re-quantise it.
```
# PATTERN QUANTISER OPTIONS
blk.*.ffn_*_exps.*.weight gptq codes=i4 group=128 scale=bf16 transform=fwht128 calib=$CALIB
blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
blk.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
blk.*.attn_qg.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
```
A ParoQuant M2XFP4 checkpoint (`quant_method` `paroquant_m2xfp4`) is imported plane by plane: the
codes, exponents and metadata bytes as shipped, the rotations as the encoding's `givens` tables.
codes, exponents and metadata bytes as shipped, the rotations as the encoding's `givens` tables;
a rule re-quantises each weight from that exact dequantisation.
A pattern is a glob over the whole name: `*` crosses dots, `?` is one character. `$NAME` (or
`${NAME}`) in an option is taken from the environment; an unset variable is refused. `--quant`
adds rules ahead of the file's:
`--quant 'output.weight=rtn:codes=fp8_e4m3,block=128x128,scale=bf16'`. A quantiser that declines a
`--quant 'output.weight=rtn:codes=i8,group=128,scale=bf16,clamp=sym'`. A quantiser that declines a
weight leaves it in the checkpoint's encoding; `rtn` declines a rank-1 tensor, so a pattern that
also matches a norm leaves the norm as it is.
@@ -189,8 +213,8 @@ also matches a norm leaves the norm as it is.
| `gptq` | error feedback against the layer's input Hessian (`calib=DIR`, damped by `damp`, default 0.01 of its mean diagonal), scales fixed from the weight first; `act_order=1` quantises the columns by descending input energy and stores the permutation as the encoding's `perm` transform; `cd=N` adds N sweeps of coordinate descent after the loop, every code re-chosen at its conditional optimum against the same Hessian |
| `awq` | each input column scaled by its activation magnitude to a searched power, then a per-block clip search, both against the Hessian; the column scales are the encoding's last scale level |
| `autoround` | sign-gradient descent on a rounding offset per value and a range factor per block, against the Hessian; `iters` steps of N·K² multiply-adds each |
| `paroquant` | a channel scaling and `stages` rounds of Givens pair rotations, learned against the Hessian, then AutoRound on the rotated weight; the encoding's `givens` transform |
| `m2xfp4` | M2XFP's weight-side Sg-EM (arXiv 2601.19213): MXFP4 plus one metadata byte a group of 32, each subgroup of 8's extra mantissa k and the exponent's bias chosen by least squared error; its own scheme `m2xfp4` (spec.md), served by `gemm_nt_q` at dtype m2xfp4. `adaptive=0` pins the bias, `wide=1` widens it to {-2..2} |
| `paroquant` | a channel scaling and `stages` rounds of Givens pair rotations, learned against the Hessian, then AutoRound on the rotated weight; the encoding's `givens` transform, which no architecture plugin of this build serves |
| `m2xfp4` | M2XFP's weight-side Sg-EM (arXiv 2601.19213): MXFP4 plus one metadata byte a group of 32, each subgroup of 8's extra mantissa k and the exponent's bias chosen by least squared error; its own scheme `m2xfp4` (spec.md), which libref's `gemm_nt_q` reads at dtype m2xfp4 and the architecture plugins refuse at declare. `adaptive=0` pins the bias, `wide=1` widens it to {-2..2} |
| `ggml` | `type=` one of llama.cpp's formats (q4_0, q4_1, q5_0, q5_1, q8_0, q2_K..q6_K, iq4_nl, iq4_xs, iq2_xxs, iq2_xs, iq2_s, iq3_xxs, iq3_s, iq1_s, iq1_m), chosen by llama.cpp's own search, imatrix-weighted; the codes are byte for byte llama.cpp's, stored as each type's affine planes. iq2_xxs, iq2_xs and iq1_s need `--imatrix` |
| `cast` | a float weight in another float dtype (`dtype=` f32, bf16, f16, fp8_e4m3, fp8_e5m2), no scale |
| `import` | rad-convert's own, not a plugin: the numbers a quantised release ships, in the spelling the kernels read, instead of quantising again. `codes=uN` makes a symmetric grid's signed codes unsigned under a zero point of 2^(N-1); `zero=` is the zero plane's dtype (u4, u8); `scale=` the scale's (f16, bf16, f32), each shipped scale rounded to nearest; `block=RxC` repeats an FP8 scale shipped per row or per tensor over that block grid. It reads an imported integer grid (GPTQ, CT-INT4) or an FP8 weight with a scale per row or per tensor, refuses any other quantised form by name, and keeps a plain float weight as it is. The run reports per rule how many weights it re-expressed and how many scales the new dtype rounded |
@@ -217,10 +241,11 @@ group=32 scale=u6 scale2=f16 group2=256`; a ternary BitNet weight is `table=tern
A container can hold only what some kernel reads. The converter checks every planned encoding
against the layout hooks of the kernels declare resolved and refuses one that no kernel accepts,
so a grid libquant can write is usable only once a kernel library takes it. libr4d reads the plain
floats; block-scaled fp8 and fp8 rows; int8 block rows (the W8A8 trunk and lm_head), plain or
rotated (`i8*bf16[1x128]/fwht128`); the routed experts as fp8, int4 (`i4*bf16[1x128]/fwht128`) or
the `w4nl`/`w5nl` codebooks under E4M3 scales ([MOE-W4.md](MOE-W4.md)); the dense w4, w8 and mxfp4
GEMM rows; and the 2-bit draft head. Every encoding also decodes through the core, which the
floats; fp8 rows (Flash-Next's mixing and MTP fc matrices, its n-gram table); int8 block rows (the
W8A8 trunk and lm_head), plain or rotated (`i8*bf16[1x128]/fwht128`, IQ8R); the IQR forms
([IQR.md](IQR.md)); the routed experts as int4 (`i4*bf16[1x128]/fwht128`), rotated int8, IQR or
the `w4nl`/`w5nl` codebooks under E4M3 scales ([MOE-W4.md](MOE-W4.md)); the dense w4 and w8 GEMM
rows and the MXFP4 rows a drafter's linears take; and the 2-bit draft head. Every encoding also decodes through the core, which the
converter's error report, the oracle and the quantisers' tests use.
The recipes for the containers this tree serves are in `data/recipes/`. `scripts/convfn.sh` and
@@ -236,30 +261,27 @@ CALIB=<calibration dir> rad-convert <Qwen3.8-Flash-Next checkpoint> \
-o w4nl64-i8lm.rad --recipe data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe \
--home $RADIANCE_HOME -v
# A --quant rule goes ahead of the recipe's: the experts as plain int4 by GPTQ, under a recipe
# whose own expert rule rounds to nearest
# A --quant rule goes ahead of the recipe's: the experts as the rotated int4 plane by GPTQ in
# place of the recipe's own expert rule
CALIB=<calibration dir> rad-convert <Qwen3.8-Flash-Next checkpoint> -o flashnext-w4.rad \
--quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB' \
--recipe data/recipes/qwen4exp-w4-hc8m.recipe --home $RADIANCE_HOME -v
--recipe data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe --home $RADIANCE_HOME -v
# A block-fp8 checkpoint needs no recipe: every weight is kept as it is. It needs no container
# either (`radiance --model` serves the checkpoint directly) unless a tier only a container
# has is wanted (GUIDE §3.4)
rad-convert <Qwen3.8-27B-FP8 checkpoint> -o q38-27b-fp8.rad
# A bf16 checkpoint of the same model, as that release's block fp8 (the recipe's header has the
# --set keys that select the fp8 plugin)
rad-convert <Qwen3.8-27B or a finetune> -o q38-27b-fp8.rad --recipe data/recipes/q38-27b-fp8block-df2.recipe \
--draft-model <DFlash2 checkpoint> --set quantization_config.quant_method=fp8 \
--set quantization_config.fmt=e4m3 --set "quantization_config.weight_block_size=128 128" \
--set quantization_config.activation_scheme=dynamic
# A bf16 Qwen3.8-27B or a finetune in IQ8R with its DFlash2 drafter (the recipe's header has the
# --set keys that select qwen35_w8a8)
rad-convert <Qwen3.8-27B or a finetune> -o q38-27b-iq8r.rad --recipe data/recipes/q38-27b-iq8r-rtn.recipe \
--draft-model <DFlash2 checkpoint> --set quantization_config.quant_method=w8a8 \
--set quantization_config.fmt=fwht128
# Check the plan without writing anything
rad-convert $SRC -o /dev/null --recipe r.recipe --plan-only -v
# Merge a drafter that ships as its own repository
rad-convert <MiniCPM5-2B checkpoint> -o minicpm5-2b-dspark.rad \
--draft-model <MiniCPM5-2B-DSpark checkpoint> --recipe data/recipes/minicpm5-2b-dspark.recipe
# Merge a drafter that ships as its own repository, the trunk and the drafter as IQ8R
rad-convert <MiniCPM5-2B checkpoint> -o minicpm5-2b-iq8r.rad \
--draft-model <MiniCPM5-2B-DSpark checkpoint> --recipe data/recipes/minicpm5-2b-iq8r.recipe
# ...or the trunk as the checkpoint ships it, the drafter IQ8R
rad-convert <MiniCPM5-2B checkpoint> -o minicpm5-2b-bf16.rad \
--draft-model <MiniCPM5-2B-DSpark checkpoint> --recipe data/recipes/minicpm5-2b-bf16-dspark.recipe
# Re-quantise only the experts of an existing container
rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
@@ -275,8 +297,15 @@ rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
declare and written into the container. A weight's storage format is not such a choice (the
encoding is in the container and the plugin reads it there), but the serving plugin is: a
`quantization_config.*` key re-derives the descriptor the plugin is chosen by. A bf16 checkpoint
whose recipe writes Qwen's block fp8 is therefore declared as that format and converted for the
fp8 plugin (`data/recipes/q38-27b-fp8block-df2.recipe` has the keys).
whose recipe writes IQ8R is therefore declared as `w8a8_fwht128` and converted for
`qwen35_w8a8` (`data/recipes/q38-27b-iq8r.recipe` has the keys).
- `--chat-template F` bakes a jinja template as the container's chat template, overriding the
checkpoint's own or standing in for a release that ships none (trailing newlines stripped).
- `--lora` merges a PEFT adapter into the checkpoint tensors it names before conversion, at
`--lora-strength` (default 1) times `alpha / r` where the adapter states one; each merged tensor
joins the `--changed` set, so `--reuse` never copies an unmerged weight. `--lora-map` maps an
adapter trained on other module names (prefixes to strip, and module patterns to their targets,
several targets splitting a fused projection's rows).
- `--max-ctx`: some graphs depend on the context bound. Qwen4-Exp sizes its QSA buffers by it and
refuses a `--max-tok` and context pair whose score plane would pass 2 GiB.
- `--max-spec`: a container carries what the model can serve, so a draft head is written even when
@@ -287,9 +316,9 @@ rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
repository supplies the config and tokenizer the plugin is sized by, and a second tokenizer.json
(with its `tokenizer_config.json` beside it) becomes the container's second vocab section, which
a generator declaring `aux_tokens` reads its prompt through. GUIDE §3.2 has the Anima command.
- `--draft-model` merges a drafter here; the engine refuses the flag. The drafter's tensors go in
under a `draft.` prefix and its config under `draft.` keys. It has no embedding and no `lm_head`
of its own; it uses the target's.
- `--draft-model` merges a drafter here; the server's `draft-model` key refuses and names this.
The drafter's tensors go in under a `draft.` prefix and its config under `draft.` keys. It has
no embedding and no `lm_head` of its own; it uses the target's.
- `--imatrix` supplies the expert-popularity profile the placement planner ranks units by, hands
each quantiser its weight's column importances, and weights the error report.
- `calib=DIR` (`gptq`, `awq`, `autoround`, `paroquant`) is a directory an engine run wrote with
@@ -309,8 +338,23 @@ rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
source bytes, and carry whatever calibration made the old planes. Use `--reuse` only when the
source and the calibration are the same, or name the changed source tensors with `--changed`.
`--in-place` writes new weights past the container's end and the header last; it refuses to
change a weight the container holds or to add an expert, and keeps the old header and length in
`<file>.pre-append`.
add an expert to a layer whose experts it keeps, and keeps the old header and length in
`<file>.pre-append`. A weight the container holds under another encoding or rule is refused
unless a `--replace GLOB` names it: it is then written again past the end and its old planes stay
in the file as unreachable bytes, which a conversion to a new file with `--reuse` drops. A
layer's experts sit in one stride table, so when any of them is written again the layer's others
move with it, their planes copied as they are: one projection of a layer can be requantised
without the other. `rad-info --unreferenced` lists the bytes left behind, and
`fallocate --punch-hole` over those ranges gives their disk back while the file keeps its length.
A further `--reuse` container supplies the planes of a replaced weight it holds as the recipe now
states it, so a projection can be taken from another container without converting it again.
This is how a few weights of a container larger than the free disk are requantised.
- `--defer GLOB` leaves weights out of the container, and their checkpoint tensors unread. A
checkpoint larger than the disk converts in pieces this way: the first run defers every layer
whose tensors are not there yet, and each `--in-place` run after it, with the same recipe and a
shorter `--defer` list, appends the layers that have arrived (a layer's experts as one whole
table). The disk then holds the container and one piece of the checkpoint at a time. A container
with weights left out does not load.
---
@@ -359,7 +403,7 @@ tuned `.rad` loads with the same serve line as the stock one.
embedding has rows is refused.
2. **The recipe** comes from the image (`/opt/radiance/share/radiance/recipes`, copied out once
per image) or from the installed `rad-convert`'s `share/radiance/recipes`. `auto` matches the
base model's name against each recipe's header; when several fit (a bf16 and an fp8 recipe of
base model's name against each recipe's header; when several fit (a bf16 and an IQ8R recipe of
the same model), it names them and asks. The recipe's own usage line supplies the `--set` keys
and says whether a drafter is merged.
3. **rad-convert runs on the CPU.** It opens no GPU, so it is safe beside a running serve. Under
@@ -369,15 +413,15 @@ tuned `.rad` loads with the same serve line as the stock one.
```bash
rad-export ~/outputs/my-run/checkpoint-400 --dry-run # what it would run
rad-export ~/outputs/my-run/checkpoint-400 # adapter -> my-run-checkpoint-400.rad
rad-export ~/exports/merged -o ~/models/mine.rad --recipe q38-27b-fp8block-df2 --draft ~/Qwen3.8-27B-DFlash2
rad-export ~/exports/merged -o ~/models/mine.rad --recipe q38-27b-iq8r-rtn --draft ~/Qwen3.8-27B-DFlash2
```
`~/.config/rad-export/config.json` (or `--config`) pins what auto cannot know -- every key optional:
```json
{"image": "stilldeadcode/radiance", "out_dir": "~/models/rad",
"recipes": {"Qwen3.8-27B": "q38-27b-fp8block-df2"},
"drafts": {"q38-27b-fp8block-df2": "~/models/Qwen3.8-27B-DFlash2"},
"recipes": {"Qwen3.8-27B": "q38-27b-iq8r-rtn"},
"drafts": {"q38-27b-iq8r-rtn": "~/models/Qwen3.8-27B-DFlash2"},
"bases": {"Qwen/Qwen3.8-27B": "~/models/Qwen3.8-27B"}}
```
@@ -570,7 +614,7 @@ section says how with the calibration it was checked against (`tools/kbench_time
| `--max-ctx N` | the deepest context considered: declare runs at it and the attention sweep builds to it (default: the checkpoint's training context for declare, 16384 for the sweep). Attention is swept over depth as well as query length |
| `--max-tok N` | the `max_tok` declare runs at (default 512, small on purpose) |
| `--mm-max-patches N` | the encoder pass declare runs at, so a media tower's kernels are in the graph (default 2048, rounded to whole output rows, when the container carries an encoder; 0 leaves it out) |
| `--kv-cache-dtype T` | `bf16` or `fp8`, the cache width declare runs at, as on the engine (default bf16) |
| `--kv-cache-dtype T` | `bf16` or `i8`, the cache width declare runs at, as on the engine (default bf16) |
| `--num-speculative-tokens N` | draft depth to declare at (default: the container's own); puts the drafter's kernels in the checked graph |
| `--max-cases N` | runs per distinct (op, kernel, library, domain, geometry, operand shapes); 0 means every one (default 4) |
| `--max-bytes MIB` | skip a case whose operands would need more than this, by name (default: half the memory available at start, at most 8192 and at least 512) |
@@ -744,22 +788,24 @@ serves fails in either case: the selector would resolve to it and the step would
## r4d_selftest
```
r4d_selftest <libr4d.so> [--case <row>]
r4d_selftest <libr4d.so> --perf N K M [iters] (and the other --perf* modes in its usage text)
r4d_selftest <libr4d.so> [--case <row>] [--jobs N]
r4d_selftest <libr4d.so> --perfmxd N K M [iters] (and the other --perf* modes in its usage text)
```
With no mode it runs libr4d's catalogue and static checks, then each row's smoke and numeric cases
in a child process of its own, the fusion claims compared byte for byte (ctest runs it as
`r4d_selftest`, labels `slow`, `gpu`); `--case` runs one row in this process, as the reproducer.
The children run `--jobs` at a time on each card (6 by default; at 8 the cards run out of SDMA queues), each seeing every card with its own
first; a row that fails or crashes there runs again alone, and only that run counts. `--jobs 0` runs
every row alone. The run ends with its wall time and its slowest rows.
The `--perf*` modes time rows at one shape on a card. Two that cover the dense GEMMs:
| | |
|---|---|
| `--perf N K M [iters]` | the fp8 decode GEMMs, and the fp8 head (`logits_gemm_fp8`) |
| `--perfmxd N K M [iters]` | the dense OCP-MXFP4 rows (`gemm_mxfp4a8_gemv`, `_decode`, `_nt_m64`, `_tiled`) at one shape, with the weight bandwidth each reaches; at a gate_up shape (N a multiple of 256, K of 128, M up to 64) also the ops after the GEMM, `gated_quant_fp8` (SwiGLU) and `gelu_mul` + `quant_act_fp8` (GeGLU), and the fold that replaces them at both activations, `gemm_mxfp4a8_gated_gemv` (M ≤ 8) or `_gated_gemv_wide` (9..64) |
| `--perfiqr N K M B [iters]` | the IQR row over a B-bit V4 trunk form (B + 10: the head-fed form, a bf16 scale a (row, 128)), then `--perfmxd`'s rows |
| `--perfmxd N K M [iters]` | the dense OCP-MXFP4 rows (`gemm_mxfp4a8_gemv`, `_decode`, `_nt_m64`, `_tiled`) at one shape, with the weight bandwidth each reaches; at a gate_up shape (N a multiple of 256, K of 128, M up to 64) also the ops after the GEMM, `gated_quant_fp8` (SwiGLU) and `gelu_mul` + `quant_act_fp8` (GeGLU) |
`--perfmx` is the MXFP4 expert GEMM (`M`, experts, `top_k`, skew), not the dense rows. `--cold MIB`
times each launch alone behind a cache flush instead of back to back.
`--cold MIB` times each launch alone behind a cache flush instead of back to back.
---
@@ -791,23 +837,65 @@ so the tool can gate a change.
---
## The KL mode
## rad-yaml
```
radiance --model BF16.rad ... --kld-record DIR --kld-corpus CORPUS.jsonl the reference, once
radiance --model QUANT.rad ... --kld-ref DIR [--kld-out REPORT.json] each candidate
rad-yaml FLAGS... print the YAML file these radiance flags configure
```
```sh
rad-yaml --model /models/q.rad --tp 2 --port 8000 > radiance.yaml
radiance --config radiance.yaml
```
The server reads only a YAML file (GUIDE.md §4, MULTIMODEL.md §4). `rad-yaml` takes a command line
in the flag form earlier releases accepted and prints the equivalent file: `server:` and
`memory:` keys at their levels, everything else under one entry in `models:`, named by
`--served-model-name` or else by the container's file name without its extension. `-v` and `-vv`
become `server.log: debug` and `trace`, switches become `key: true`, repeated flags a list, and a
JSON argument a flow mapping. The flags go through the engine's own parser first, so a line the
server would have refused is refused here with the same message, and the file is loaded back
before it is printed. The server prints the same file when it is started with flags. It is built
into the build's `bin/`; `scripts/radiance-flags BIN FLAGS...` uses it to run a server binary from
a flag list.
---
## The KL mode
```yaml
# ref.yaml: the reference, once
models:
bf16:
model: BF16.rad
kld-record: DIR
kld-corpus: CORPUS.jsonl
```
```yaml
# cand.yaml: each candidate (kld-out optional)
models:
quant:
model: QUANT.rad
kld-ref: DIR
kld-out: REPORT.json
```
```sh
radiance --config ref.yaml
radiance --config cand.yaml
```
Measures how far a quantised model is from the one it was quantised from, as the distribution of
the per-position KL(P_bf16 || Q_quant) over the whole vocabulary: mean, median, 99th, 99.9th and
99.99th percentiles and maximum, top-1 agreement (the candidate's argmax is the reference's), and
both models' perplexity on the corpus's own next tokens, overall and per source. It is a mode of
the engine, like `--debug-graph`: it starts as a serve would, with the same placement and kernels,
the engine, like `debug-graph`: it starts as a serve would, with the same placement and kernels,
runs the corpus through prefill instead of listening, and exits.
The reference is computed once. `--kld-record` writes the bf16 model's log-probabilities at every
The reference is computed once. `kld-record` writes the bf16 model's log-probabilities at every
scored position to DIR (f16 over the whole vocabulary, the 16 most likely tokens exactly, and the
tokens themselves). `--kld-ref` runs a candidate over those stored tokens and scores its own f32
tokens themselves). `kld-ref` runs a candidate over those stored tokens and scores its own f32
logits against the stored rows, so a candidate costs one prefill of the corpus. DIR is never
overwritten, and is read only once its `kld.json` exists, which the recording writes last.
@@ -821,44 +909,49 @@ needs many positions: the 99.99th percentile of 83K positions rests on eight of
The mode changes these settings itself:
- Speculation and the prefix cache are off: a drafter writes no scored row, and a prefix hit would
skip positions the reference holds. An explicit `--num-speculative-tokens` above 0 is refused.
skip positions the reference holds. An explicit `num-speculative-tokens` above 0 is refused.
- The step pipeline is off, since the scored rows are copied off the cards after the step.
- The logits buffer holds a row for every token of a step (`RadBuildCtx::max_out_rows`). At
`--max-num-batched-tokens 4096` with a 248320-token vocabulary over two ranks that is about
`max-num-batched-tokens: 4096` with a 248320-token vocabulary over two ranks that is about
2 GiB per rank, plus the same in pinned host memory.
Everything else comes from the command line: run every candidate with the same flags, and the
Everything else comes from the model's entry: run every candidate with the same keys, and the
reference with the exact wire and a bf16 KV cache.
A loaded control vector is applied at the deployment's default: `--control-vector on` scores every
document with the projection, `--control-vector off` without it.
A loaded control vector is applied at the deployment's default: `control-vector: on` scores every
document with the projection, `control-vector: off` without it.
**The sparse reference.** A full row is the vocabulary in f16, so ten million positions of a
248K-token vocabulary would be 5 TB. `--kld-record DIR --kld-top N` keeps, per position, the `N`
248K-token vocabulary would be 5 TB. `kld-record: DIR` with `kld-top: N` keeps, per position, the `N`
most likely tokens exactly (f32 log p) and the mass of every other token, summed from the full row
(one minus the head would cancel to noise on a confident position): 8 bytes a token, 4 KiB a
position at `N` = 512. `--kld-ref` reads the form from the manifest and scores the KL between the
position at `N` = 512. `kld-ref` reads the form from the manifest and scores the KL between the
two distributions coarsened to the reference's `N` tokens and one bucket for the rest. By the
data-processing inequality that is at most the full KL; it loses only how each model spreads the
tail inside the bucket, which is small where the reference's tail mass is small and nothing on a
confident position. The report's `ref_form` says which form a number was scored against, and
numbers from the two forms do not compare.
`--kld-out FILE` writes the report as JSON, and every position's KL, both NLLs and the argmax
`kld-out: FILE` writes the report as JSON, and every position's KL, both NLLs and the argmax
agreement to `FILE.rows` (`[positions, 4]` f32, reference row order), so two candidates can be
compared position by position.
A runtime LoRA adapter (GUIDE.md §4.9.1) is scored the same way: `--lora NAME=DIR --kld-lora NAME`
A runtime LoRA adapter (GUIDE.md §4.9.1) is scored the same way: `lora: {NAME: DIR}` with `kld-lora: NAME`
runs every document through the adapter, against a reference recorded from the merged checkpoint
(or from PEFT itself). `--kld-lora-sources PREFIX` runs only the documents whose `source` starts
(or from PEFT itself). `kld-lora-sources: PREFIX` runs only the documents whose `source` starts
with `PREFIX` through it and the rest as the base, in the same steps. The steps are those of the
all-adapter and all-base runs with the same flags, so each document's rows should be byte for byte
all-adapter and all-base runs with the same keys, so each document's rows should be byte for byte
theirs: that is how a mixed batch is checked.
## The calibration mode
```
radiance --model BF16.rad ... --calib-corpus CORPUS.jsonl --calib-dir DIR [--calib-layers LO:HI]
```yaml
models:
bf16:
model: BF16.rad
calib-corpus: CORPUS.jsonl
calib-dir: DIR
calib-layers: LO:HI # optional
```
Records GPTQ's Hessian, `H = sum over tokens of x x^T`, of the whole input of every linear in a
@@ -869,17 +962,17 @@ flight, its own included, fit the KV pool at once, so none is preempted (a re-pr
its tokens twice), and a run that preempts all the same fails. The corpus is the KL mode's JSONL;
only `prompt` is read.
`--calib-dir` beside `--kld-record` (no `--calib-corpus`) records both in one run: the reference
over `--kld-corpus`, and the Hessians over the same tokens, fed the same way.
`calib-dir` beside `kld-record` (no `calib-corpus`) records both in one run: the reference
over `kld-corpus`, and the Hessians over the same tokens, fed the same way.
Under tensor parallelism a linear split by its input columns (`o_proj`, the delta net's
`out_proj`, `down_proj`) sees only its rank's columns, and a Gram of those is one diagonal block
of H. The tap gathers such an input to its whole width before taking the Gram, so the files hold
the whole matrix at any `--tp`. One rank records each layer (layer modulo the rank count): its card
the whole matrix at any `tp`. One rank records each layer (layer modulo the rank count): its card
sums a step's rows into an f32 scratch (`gram_accum`, upper triangle only), and the host adds the
step's sum into an accumulator of the packed upper triangle. The host holds every recorded input of
its rank, 786 MB a layer at Qwen3.8-27B (50 GB for 64 layers), so a large model is recorded in
several runs over the same corpus, each with its own `--calib-layers`; the run whose range ends at
several runs over the same corpus, each with its own `calib-layers`; the run whose range ends at
the last layer also records the lm_head's input.
The files, written once the corpus is through: `DIR/<checkpoint prefix>.<layer>.<site>.safetensors`
@@ -888,6 +981,16 @@ after row `i-1`'s), with metadata `k`, `rows` and `linears`, the checkpoint line
input (q, k and v share one; so do gate and up). H is the raw sum: divide by `rows` for the mean
second moment.
`qwen4exp` (Qwen3.8-Flash-Next) records its trunk the same way: two inputs a layer, the mixer's (the
delta net's in projection, or q, k and v) and its output projection's, in files named by the
container's weights (`blk.<layer>.ssm_inz.input`, `.ssm_out.input`, `.attn_qkv.input`,
`.attn_output.input`), whose `linears` are the weight names a recipe's rules match. A bf16
container is recorded at any `tp`; an int8 trunk at `tp: 1` from the codes its GEMMs read, with a
`domain` in the metadata when those are rotated. Its routed experts' Grams are the older tap's
(`RADIANCE_CALIB_DIR`, `RADIANCE_CALIB_TOKENS` set to the corpus's token count), which the same
run fills. The quantisers read `gram.r<rank>.<weight>.bin`; a file here is that matrix once its
triangle is mirrored.
```python
import numpy as np, safetensors.numpy as st
t = st.load_file("model.language_model.layers.3.mlp.down_proj.input.safetensors")["hessian_upper"]
@@ -897,6 +1000,52 @@ H = np.zeros((k, k), np.float32); H[np.triu_indices(k)] = t; H = H + np.triu(H,
---
## The diagnose mode
```yaml
# diag.yaml: the model's own keys, plus the mode
models:
quant:
model: M.rad
diagnose: DIR
```
```sh
radiance --config diag.yaml # the workload, the report, and the exit code
```
Runs a fixed workload on the engine instead of serving it — decode by prompt category, a
concurrency sweep, a prefill sweep with decode at each depth, and a prompt arriving into running
streams — and writes `DIR/diagnose.json` and `DIR/diagnose.md`: step times and their spread, tokens
a step, draft positions drafted and accepted, TTFT, per-token emission intervals and jitter, per
request and per phase, with the machine and the settings it ran under. It starts as a serve would
(same placement, same kernels, same prefix cache) and exits, so it can be run on every candidate
build and compared.
| key | default | |
|---|---|---|
| `diagnose: DIR` | — | run the workload and write the report to DIR; `diagnose.json` is the whole report, `diagnose.md` reads it |
| `diagnose-tokens: N` | 256 | tokens a decode stream generates |
| `diagnose-runs: N` | 3 | measured runs of each point, after one unmeasured; median and spread are reported |
| `diagnose-concurrency: LIST` | 1,2,4,8 | stream counts of the concurrency sweep; a count above `max-num-seqs` is skipped and reported |
| `diagnose-prefill: LIST` | 1024,4096,16384,65536 | prompt lengths of the prefill sweep, in tokens; a length the context cannot hold is skipped and reported |
| `diagnose-corpus: FILE` | built-in | JSONL, one `{"category", "messages" or "prompt", "max_tokens"?}` a line: code, reasoning, prose, json, file_edit, summarization |
| `diagnose-baseline: FILE` | — | an earlier `diagnose.json` of the same workload: compare every request's tokens with it and fail the run on any difference |
Every prompt is salted so the prefix cache serves none of it, the cache is emptied before every
run, and each request's cached-token count is checked afterwards: a hit, or step records the ring
overwrote before they were read, makes the verdict `NOT A MEASUREMENT` and the exit code non-zero.
Requests run at temperature 1 with the server's top_k/top_p/min_p and a fixed seed per request, so
two builds of the same model are compared token for token. `diagnose` is a mode of the engine
like `kld-ref`: it cannot be combined with the KL keys, `calib-corpus` or `debug-graph`, and the
file names one model. `diagnose-corpus` and `diagnose-baseline` need it.
The report says in `not_measured` what it does not cover — per-kernel device time, placement and
link counters per phase, op correctness over a step window, and the HTTP path. What the numbers
mean, what makes a run a measurement and what is still missing: [DIAGNOSE.md](DIAGNOSE.md).
---
## The shell harnesses
`scripts/` drives a running engine: bring a model up, measure it, and assert on what comes back
@@ -924,11 +1073,11 @@ Which ones stop a running server:
| | knobs |
|---|---|
| `mcserve.sh` | MiniCPM5-2B + DSpark drafter (`minicpm5-2b-dspark.v2.rad`), left running. `P` `TP` `MLEN` `SEQS` `M` `KVD` `HR` `MNBT` `EXTRA` `EXTRA_ENV` |
| `mcserve.sh` | MiniCPM5-2B IQ8R + DSpark drafter (`minicpm5-2b-iq8r.rad`), left running. `P` `TP` `MLEN` `SEQS` `M` `KVD` `HR` `MNBT` `EXTRA` `EXTRA_ENV` |
| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, left running. `P` `TP` `MLEN` `SEQS` `M` `NS` `HOSTPOOL` `KVD` `HR` `MNBT` `WIRE` `KVHOST` `EXTRA` `EXTRA_ENV` |
| `fnstop.sh` | stops whichever is running and waits for the process to exit |
| `convdspark.sh`, `convfn.sh` | rebuild the containers those two serve; the reference conversions. `convfn.sh` needs `CALIB=<dir>`: the production recipe's expert rule runs GPTQ against the calibration Grams there |
| `hfget.sh` | fetch a checkpoint from Hugging Face with `curl` and `jq`. Resumable; a file changed at the same size is fetched again (`.hfget-manifest`). `radiance --model <owner/name>` runs it too |
| `hfget.sh` | fetch a checkpoint from Hugging Face with `curl` and `jq`. Resumable; a file changed at the same size is fetched again (`.hfget-manifest`). a server whose `model` is `<owner/name>` runs it too |
```sh
scripts/fnserve.sh # defaults: port 8100, tp 2, 200K ctx
+26 -11
View File
@@ -50,13 +50,13 @@ its weights pool, up to all of its weights resident.
- The token count, the carve, the loan and the attention ranks' pools are unchanged.
- Other placements keep the common split (under `auto` a fully resident rank would choose
all_vram while its peers spill).
- `--deterministic` and a device without virtual memory management re-split like any other: the
- `deterministic: true` and a device without virtual memory management re-split like any other: the
cache does not lend there, and the bytes the rank never pages are as much its experts' as under a
lending cache.
- The condition is the cost, not the world: a rank is re-split only when its cache costs less per
token than the most expensive rank's, which at TP2 and TP4 no rank does. A rank that qualifies
but keeps the common split gives the reason on its `kv: rank N's cache costs ...` line.
- The pinned host pool is not re-split: every rank allocates its whole `--host-pool-mib`, and a
- The pinned host pool is not re-split: every rank allocates its whole share of `host-pool-mib`, and a
re-split rank whose weights all fit on the card logs that its pinned host pool holds no weights.
The log line on the third rank:
@@ -114,7 +114,7 @@ Load check: the relayout pool refuses to finish when any staged weight was never
nothing wrote holds whatever the card had there: zeros on a card whose driver wipes freed memory,
garbage after a reset ("VRAM is lost"). To expose such a read on any card:
RADIANCE_DEBUG_POISON_ALLOC=255 radiance --model stock.rad --tp 3 ...
RADIANCE_DEBUG_POISON_ALLOC=255 radiance --config radiance.yaml # model: stock.rad, tp: 3
This fills every fresh device allocation with 0xFF (NaN in every float width) before it is handed
out; the serve must answer exactly as without it. `RADIANCE_DEBUG_POISON_RANGE=lo:hi` narrows the
@@ -122,20 +122,35 @@ fill to a range of a thread's allocation ordinals, for bisecting (`core/device/d
## 4. Serving
```yaml
# radiance.yaml
memory:
gpu-headroom-mib: 96
models:
qwen3.8-next-flash:
model: qwen3.8-next-flash-iqr-v4.rad
tp: 3
tp-wire: exact
max-num-seqs: 8
max-model-len: 262144
placement: expert_tiered
host-pool-mib: 24576
kv-cache-dtype: i8
num-speculative-tokens: 3
max-num-batched-tokens: 2048
```
```sh
radiance --model qwen3.8-next-flash-fp8-iq4r-moe.rad --tp 3 --tp-wire exact --max-num-seqs 8 \
--max-model-len 262144 --placement expert_tiered --host-pool-mib 8192 \
--gpu-headroom-mib 96 --kv-cache-dtype fp8 \
--num-speculative-tokens 3 --max-num-batched-tokens 2048
radiance --config radiance.yaml
```
At three ranks the exact all-reduce is the one-shot up to 1 MiB per message (every decode step) and
the two-shot above it (every prefill chunk). The two-shot is reduce-scatter + all-gather and sends
4/3 of the message per rank instead of twice it. A message rarely divides into thirds (a
2048-wide bf16 row is 256 16-byte words), so the first `words % 3` shards take one word more. Both
fold in fp32 in ascending rank order, so the switch between them changes no bits. `--tp-wire wht6`
fold in fp32 in ascending rank order, so the switch between them changes no bits. `tp-wire: wht6`
at three ranks is the tiered-int8 wire over the same uneven two-shot for messages from
`--tp-wire-min-kb` up, and the exact one-shot below.
`tp-wire-min-kb` up, and the exact one-shot below.
Startup logs the geometry:
@@ -143,7 +158,7 @@ Startup logs the geometry:
radiance: world_size = 3 over n_head_kv = 2: attention on 2 rank(s), rank(s) 2..2 carry no attention and take the delta net's remainder first
```
Each rank's delta-net share is a note in its declared graph; `--debug-graph` and the dashboard's
Each rank's delta-net share is a note in its declared graph; `debug-graph: true` and the dashboard's
graph view show rank 0's:
```
@@ -158,7 +173,7 @@ attention-zero rank still ran its projections on zero weights, and the extra del
rank 0. Hot = 1 / 4 / 8 streams, 8K prompt, 1K generated, aggregate tok/s; crowd = 4 streams at
100K context, per stream; HumanEval 164 and a 200-question GSM8K subset at temperature 0:
| container | `--tp` | hot c1 / c4 / c8 | crowd | HE | GSM8K |
| container | `tp` | hot c1 / c4 / c8 | crowd | HE | GSM8K |
|---|---|---|---|---|---|
| unpadded | 3 | 191 / 309 / 353 | 42.7 | 0.878 | 0.925 |
| unpadded, the same file | 2 | 177 / 308 / 377 | 33.8 | 0.884 | 0.915 |
+49 -189
View File
@@ -1,202 +1,62 @@
# Four ranks on a PCIe fabric: what pays, what doesn't, and how to tell
# Four ranks on a PCIe fabric: what pays and what doesn't
A measured map of every TP4 lever tried on 4×R9700 (PCIe P2P, no NVLink),
with the receipt that decided each one — for anyone attacking the same
terrain on a different card or fabric. The shipped combination here is
span (#78) + the link-hold release (#94) + the four-rank harness (#93);
everything else in the table is either reverted or still open.
All numbers: paired within-session windows, bar ≥0.5% + sign test, geometry
`--prefill-span 2 --tp-wire wht6 --placement all_vram` iq4r MoE unless stated.
Every "dead" row is a *measured* dead — the mechanism, not a guess.
Every TP4 lever tried on 4x R9700 (PCIe Gen5 P2P, no NVLink), and what decided it. Use it before
re-attacking the same ground on another card or fabric. All numbers are paired within-session
windows (bar 0.5% plus a sign test) at `prefill-span: 2`, `tp-wire: wht6`, `placement: all_vram`,
iq4r MoE, unless stated.
Shorthand: `pp` prefill; `c1/c2/c8/c16` concurrency (live streams) 1/2/8/16; `M` rows in a
collective (batch tokens at a step, rows in a MoE launch); `I` `--checkpoint-interval`; `T` tokens
(`T<=25` at most 25 tokens); `ti8` the int8 peer wire (`--tp-wire wht6`'s coding); `FK` the MoE fast
band; `W4` the 4-bit weight format; `iq4r` the shipped MoE quantisation; `hc_write` the fused
all-reduce + residual-write row; `pp64K` a 64 K-token prefill; `QSA` the sparse indexer
(docs/QSA.md); `L0..L3` kill levels, defined under *Kill levels*; `W#`/`R#` the experiment rows of
this table.
Shorthand: `pp` prefill; `c8` eight concurrent streams; `M` rows in a collective; `ti8` the int8
peer wire (`tp-wire: wht6`'s coding); `hc_write` the fused all-reduce + residual-write row.
## The table
## What shipped
| # | Element | What we tried | Result (measured) | Status / PR |
|---|---------|--------------|-------------------|-------------|
| 1 | `--prefill-span 2` (upstream **#78**) | overlap the two half-chunk all-reduces with compute via ti8 lane rows; needed `I=2048` + `all_vram` (placement flips its sign!) | +5…11% pp span-on under `all_vram`; repro of upstream's numbers | **SHIPPED**; receipts posted on #78 |
| 2 | **R2** = `ar_*_4rank` link-hold release (kernel gate `link_gate/early/gate_ctr`) | 4-rank rows answered "keep holding" → all yielding DMA (stager copies, expert prefetch) idled behind every collective; wire the self-release like the 2-rank rows do | **−3.66% c8 when removed** (W16, 2 rounds, per-req agrees) — the whole R-suite carrier | **SHIPPED**, PR **#94** with the number |
| 3 | **R6** 4-rank selftest harness | shipped TP4 width had zero test coverage; wide-collective + fused-write cases at world 4 (+fixed gather oracle indexing) | test-only; it's what lets anything else be proven at TP4 | **SHIPPED**, PR **#93** |
| 4 | **R1** MoE FK four-class band (20→80) | widen expert-GEMM fast band for mixed-class tiles | **inert for W4=4 (iq4r)** — cap only bites 3-bit formats; TP2: provable no-op | REVERTED; PR **#95 closed** in favor of upstream #79 |
| 5 | **R3** fused AR+hc_write prefill rows (`wire==1` band) | fuse residual write into exact-wire AR epilogue | **0 selections** in 121k-line debug-graph boot (wht6 → lossy band; fused row is exact-only); removing whole suite = noise | REVERTED; PR **#96 closed** w/ receipts — *never isolated: measured only inside the exact-wire bundle (row 9), its own territory un-timed* |
| 6 | **W15** MoE per-class grid split | give lossy/exact class tiles their own launch grids | **non-constructible**: "a run's class is not a property of `blockIdx.y`" — all y-siblings of a (tile,run) serve one run | DEAD; its selftest arm (`R4D_PERFMOE4`) and mixed-class cases are on the author's fork, not in this tree |
| 7 | **W17/#100** ti8 fused two-shot + hc_write (`ar_twoshot_hc_write_4rank_ti8`) | delete the standalone hc_write launches from the lossy decode/verify band (new `ti8 1` key, M=26..max_tok) | byte-for-bit ✅ on GPU; row selected ✅; **c8 −0.43%, c16 sign-split — no win**. Launches are cheap here (~4µs floor); epilogue serializes behind AR spin | PR **#100** (closed, branch + byte-for-bit harness kept on the fork), honest-null description; MTP-head declare finding inside |
| 8 | **W18** AR grid 16→32→64 blocks (`R4D_AR_NB_DESIGN`) | hypothesis: 16-block design starves the P2P link | **GB/s FALLS with blocks**: M=2048 34.5→33.7→31.4; M=128 18.4→12.4→7.4. Handshake-bound, not launch-starved | DEAD rungs (images kept); microbench killed it in 3 min |
| 9 | exact wire (`--tp-wire exact`) vs wht6 | exact AR everywhere incl. fused rows | loses −7.6…−8.3% at span-off to wht6; 128 KiB wire floor proven; exact only lives at T≤25 decode | rejected; upstream informed |
| 10 | F1 rank-load balancer | rebalance shard columns to equalize rank work | ~+1.3% at 64K only; **bit-changing output** | not shipped (bit-identity beats 1.3%) |
| 11 | step-graph capture (launch overhead) | replay decode passes as HIP graphs (`libr4d/isa/graphrate.hip` arms) | trunk submit = **backpressure** (device-bound; host hidden) → capture irrelevant for trunk; draft-pass gap real but hidden by other requests at c8+ | closed for trunk; draft-loop variant unmeasured (pays only at c1/c2) |
| 12 | **W19** clean lane | revert R1+R3, keep R2+R6, re-gate | **parity** (c8 +0.45%, c16 −0.08%, noise band) → deletions cost nothing | **SHIPPED = prod** |
| 13 | ti8 gather row (a hypothetical `ar_gather_hc_write_4rank_ti8`; the fused gather row that exists, `ar_gather_hc_write_4rank`, is exact-wire only) | hypothesis: the MoE gather is the last exact-wire (2 B/elem) collective; move it to ti8 like the AR rows | **premise collapsed by code reading**: on the lossy band the MoE boundary runs the unfused triple `moe_gather + ar_twoshot_4rank_ti8 + hc_write` — the gather's all-reduce already rides ti8. The `wire==0` fused row serves exact territory only; what a ti8 gather row would buy there is launch fusion, measured null (row 7) | demoted: companion of the (closed) fused-epilogue line, exact-wire configs only |
| 14 | codec inner-loop (the "22%") | decomposed the ti8 two-shot with `--perfarx` probe kernels: encode-only / encode+push / fold-only, vs the full row, M=2048/4096 | **dead, and the reframe is the prize**: encode = 4% of the row (36 µs of ~900); the P2P push runs at ~60 GB/s = **PCIe Gen5 x16 line rate** — the fabric is saturated, ti8 is already optimal per byte; fold ~200 µs is local-memory work pp doesn't wait on (row 12/13 showed pp isn't link-bound) | CLOSED — no codec win exists; “22% tax” was line-rate physics |
- **`prefill-span: 2`**: overlaps the two half-chunk all-reduces with compute through the second
lane's rows. +5-11% pp, but only with `checkpoint-interval: 2048` and `all_vram` (placement flips
its sign).
- **The four-rank link-hold release** (`ar_*_4rank` rows release the link gate themselves, as the
two-rank rows do). Without it every yielding DMA (stager copies, expert prefetch) idles behind
each collective: removing it costs 3.7% at c8. Any new collective row must honour the gate.
- **Four-rank selftest coverage**: the wide-collective and fused-write cases at world 4.
## Kill levels — which dead ends are actually closed
## What was tried and lost
A dead end is only closed if the code ran where it was meant to run, did the right
thing, and still lost. Rows below say which level killed them; **L0/L1 kills are
implementation gaps, not physics** — a differently-coded version of those is still
fair game, and this is the list to re-attack from.
| level | meaning | rows |
| lever | result | why it is closed |
|---|---|---|
| **L3 mechanism dead** | ran, correct, lost to a measured mechanism | W18 grid (GB/s falls with blocks — handshake-bound), W17 fusion (ran + byte-exact + net-flat; the saved launches are at the 4 µs floor), step-graph capture (trunk submit = backpressure — *but this one is synthetic-evidence only, see below*) |
| **L2 territory dead** | the config that would use it loses as a bundle | exact wire −7.6…−8.3% (row 9) — but it bundles rows 5/13, see L1 |
| **L1 never activated** | declared, never observed serving; never benchmarked in its own territory | **R3 fused rows (row 5): 0 selections on the lossy lane; its exact-wire territory was only ever measured inside W11's bundle, never isolated** · **fused gather row: same story — on the lossy lane `gather_taken()` skips it by design; nobody has booted an exact-wire config and timed it** (`ar_gather_hc_write_4rank`) |
| **L0 never implemented** | the idea died before code | W15 per-class grid (single-launch version non-constructible: "class is not a property of `blockIdx.y`" — a **two-launch split version was never tried**; it only matters for mixed-class formats, not W4) · ti8 one-shot band for 128 KiB–512 KiB (flagged upstream, nobody built it) · draft-pass graph capture (real host gap, unmeasured, pays only at c1/c2) |
| widen the MoE fast band to four classes | no change | the cap only bites 3-bit formats; inert for 4-bit experts |
| fused all-reduce + `hc_write` on the exact-wire band | never selected | `wht6` takes the lossy band, and the fused row is exact-only. Never timed in its own territory |
| per-class grid split for the MoE GEMM | not constructible in one launch | a run's class is not a property of `blockIdx.y`. A two-launch split was never tried |
| fused `ti8` two-shot + `hc_write` | c8 -0.43%, c16 sign-split | the saved launches sit at the ~4 us launch floor; the epilogue serialises behind the all-reduce spin |
| more all-reduce blocks (16 -> 32 -> 64) | GB/s falls (M=2048: 34.5 -> 31.4; M=128: 18.4 -> 7.4) | handshake-bound, not launch-starved |
| `tp-wire: exact` everywhere | -7.6 to -8.3% at span off | exact wins only at decode steps of 25 tokens or fewer, which it already serves |
| rank-load balancer | +1.3% at 64K only | changes output bits; not worth it |
| step-graph capture | none for the trunk | trunk submission is device backpressure, so the host is hidden. Evidence is a synthetic ring, not an engine capture |
| `ti8` MoE gather row | premise false | on the lossy wire the gather's all-reduce already rides `ti8` |
| faster `ti8` codec | none possible | encode is 4% of the row (36 of ~900 us); the peer push runs at ~60 GB/s, PCIe Gen5 x16 line rate. The "22% tax" against exact is the link |
Two caveats on the L3 list, since L3 is the only level that forbids re-trying:
step-graph closure rests on the `graphrate` synthetic ring, not an engine capture —
the engine has no capture path to test, so treat it as strong-suspect, not closed.
And W17's net-flat is solid *at the geometry it ran*; it does not falsify fused
epilogues for configs that sit host-bound (very low concurrency + slow host).
## Instruments (not lanes, but they decide lanes)
`--debug-graph` boot (2 min): which row the config *actually selects* —
killed R3 and W15 premises, and pinned R2's sites — note it lists declared bands, so a row can match on paper while a different row serves the step; confirm against the running step. `--perfar/--perfarx`:
cross-rank row us/launch + GB/s, arms interleaved one loop (drift rule); these two
`r4d_selftest` modes are on the author's fork, not in this tree (which has `--perfops`, `--perfhc`
and the GEMM/MoE ones).
`rad-kbench`: kernel-vs-reference replay. BetterBench (one fixed standard profile):
promotion truth; quick concurrency ladders within windows.
Only a lever that ran correctly and still lost to a measured mechanism is closed for good: the
block count, the `ti8` fusion and the codec. The fused exact-wire rows, the two-launch class split
and draft-pass graph capture were never built or never timed where they would pay.
## Open levers, ranked
1. **Decode-side config**: big steps (interval 4096 / budget 8192) measured
+2…3% c8 and −2…4% pp — a two-flag promotion if the serving mix is
decode-heavy. No new code; already paired twice (rows 12 + W22).
2. exact-wire configs only: the fused gather/write rows (row 13) still have
territory there — on a lossy wire they are launch-fusion rows, not wins.
3. **span_min sweep** — the floor of eight checkpoint intervals (16384 tokens at
I=2048) applies only where routed experts are read from host memory, and was
priced on Flash-Next at TP2; under `all_vram` there is none and every lone
prefill spans. At TP4 with tiered experts the floor is unmeasured. One
boot-flag arm + window.
4. ti8 **one-shot band** for 128 KiB–512 KiB lossy messages (currently every
such message pays two-shot 1.5N + 2 syncs) — flagged upstream on #78.
5. Draft-pass graph capture — only if low-concurrency latency ever matters.
6. **The dense pipelined prefill at TP4** (`qwen35_fp8`, `qwen35_w8a8`, `gemma3`; GUIDE §4.5): a
prefill step of one sequence in two pieces, every block boundary's all-reduce on the second lane
at `overlap` 1, which at four ranks would take this table's `*_4rank_*_lane` rows (row 1). It
runs at two ranks only; enabling it here (`g.world == 2` in both plugins' declare) needs a
timing against the serial step at 18K-64K prompts and the chunk served.
1. **Bigger steps for decode-heavy traffic**: `checkpoint-interval: 4096` with an 8192-token budget
measured +2-3% c8 and -2-4% pp. Two flags, no code. A prefill chunk is
`min(budget, interval x span)`; the engine prints the effective chunk at startup.
2. **Fused gather/write rows for exact-wire configs**, where they still have territory.
3. **The span floor at TP4 with tiered experts**: eight checkpoint intervals, priced on Flash-Next at
TP2 only.
4. **A one-shot `ti8` band for 128-512 KiB messages**, which now pay the two-shot's 1.5N and two
syncs.
5. **Draft-pass graph capture**, if low-concurrency latency matters: the host gap is real at c1/c2
and hidden at c8.
6. **The dense pipelined prefill at four ranks** (`qwen35_fp8`, `qwen35_w8a8`; GUIDE
§4.5). It runs at two ranks only (`g.world == 2` in the plugins' declare); enabling it needs a
timing against the serial step at 18K-64K prompts.
## Interaction diagram
## Instruments
Where each element lives in one decode/prefill step (per layer, TP4):
```
ENGINE LAYER (per step)
span (PR78): prefill step = 2 chunks; chunk A's AR on lane-2
beside chunk B's compute. stager DMA + expert prefetch run
CONCURRENTLY with kernels — unless the link gate is held:
┌────────────────────────────────────────────────────────────┐
│ link gate (R2/#94): collective must release it itself, │
│ else every yielding DMA waits out the whole collective. │
│ any NEW collective row MUST honor it or re-lose the 3.7% │
└────────────────────────────────────────────────────────────┘
KERNEL LAYER (per layer ×8 + MTP head ×2)
attn out ──► AR ──► hc_write ──► router ──► MoE gather ──► hc_write
│ │ │
│ │ └─ MoE boundary: on the lossy wire
│ │ this is the UNFUSED triple (gather +
│ │ ar_twoshot_4rank_ti8 + hc_write) — the
│ │ gather's AR already rides ti8. The fused
│ │ exact rows (R3: 0 selects; ti8 gather:
│ │ launch fusion = row 7 null) serve exact
│ │ W17 fused ti8+write, no win
│ └─ tiny op, 4µs launch floor (perfops) — not attackable
│
├─ ar_twoshot_4rank_ti8 (T≥26 & ≥128KiB: the shipped row)
│ └─ codec (r4d_ar_ti8.h): 4-lane groups, 38B records,
│ own-shard exact + int8 peers. the "22%" is the push at
│ PCIe line rate (row 14, appendix E): no codec lever
│ └─ grid: nb_for rule, design=16 — W18: raising it LOWERS GB/s
├─ exact rows (T≤25 / <128KiB): 1-sync oneshot — already cheapest
└─ one-shot gap: 128KiB–512KiB lossy has no 1-sync form (upstream)
HOST LAYER
no step graph; trunk submit = backpressure (graphrate) → launch-count
fusion structurally unimportant (why W17 measured flat); draft passes
have real host gaps, invisible at c8+ concurrency.
```
Value stack, multiplicative where marked: PR78 overlaps the ARs · R2 unblocks
DMA around them · on the lossy wire the AR and the gather already share the one
codec. The bytes lever is spent, and the codec's push runs at line rate (row 14).
## Appendix A — cross-rank row microbench (`--perfar` on the author's fork, idle cards, 300 iters, arms interleaved one loop)
```
ti8 M=16 nb=rule 33.1 us 14.8 GB/s (under the 131072 B floor: exact one-shot folds it)
ti8 M=128 nb=16 63.4 us 18.4 GB/s
ti8 M=128 nb=32 94.5 us 12.4 GB/s
ti8 M=128 nb=64 156.9 us 7.4 GB/s (64 = R4D_AR_WIDE_MAX_BLOCKS)
ti8 M=2048 nb=16 540.8 us 34.5 GB/s (shipped)
ti8 M=2048 nb=32 554.7 us 33.7 GB/s
ti8 M=2048 nb=64 594.9 us 31.4 GB/s
exact M=2048 rule 830.4 us 37.9 GB/s (control: 2x the bytes, 1.53x the time)
```
Reads: more blocks LOSE (handshake-bound, not launch-starved); the ti8 wire
buys 2x bytes for ~1.53x time — the ~22% fold/push tax lives inside the codec
(appendix E decomposes it).
## Appendix B — host submit cost (`libr4d/isa/graphrate.hip`, 45-dispatch pass)
```
individual 62.4 us (1.39 us a dispatch, +GetLastError churn)
graph 3.6 us (0.08 a dispatch — the floor, unreachable: passes aren't static)
graph+set 21.1 us (~10 moved operand pointers/step)
recap+update 89.5 us (capture 0.48/node + ExecUpdate 63.7 — LOSES vs plain)
full ring 52.9 us == idle ring => trunk submit is BACKPRESSURE, host is hidden
```
Reads: step-graph capture is irrelevant for a trunk that runs ahead of the
device; it can only matter where the host sits on the critical path (MTP
draft passes), and there other requests hide the gap at ≥8 concurrency.
## Appendix C — small-op launch floor (`r4d_selftest --perfops 16 2560`, 500 launches, one sync per stretch)
```
rmsnorm_quant_fp8 4.43 us | rmsnorm_quant_fp8(res) 4.19 | gated_quant_fp8 3.70
quant_act_fp8 4.64 us | rmsnorm_bf16 4.64 | add_bf16 4.03
```
Every elementwise op costs the same ~4-4.6 us regardless of payload: pure
launch/teardown floor at 26-88 GB/s. Fusing two such ops saves the launch,
and a launch saved here demonstrably moves nothing end-to-end (see W17).
## Appendix D — the config surface (`chunk = checkpoint_interval x span`, clamped BEFORE the budget)
The step budget is not the chunk: a prefill chunk is `min(budget, interval x span)` (the engine
prints the effective chunk at boot — read that line before sweeping anything). Measured, paired,
lossy wire, chunk-4096 baseline = shipped:
| arm | pp16K | pp64K | pp128K | c8 | c16 |
|---|---|---|---|---|---|
| chunk 8192 (`I 4096 x span 2`, budget 8192) | -1.7% | -3.7% | -3.0% | +2.0% | +1.0% |
| step 8192 (budget up, chunk clamped unchanged) | -4.1% | -1.3% | -1.3% | +3.1% | +1.0% |
Both directions agree: **bigger steps/chunks trade pp for decode** — on this box pp time hides
behind compute, decode time hides behind stalls, so nothing on the link side moves pp. The step
band is sized by the AR mailbox (`numel` instance bound = budget x width), so raising the budget
extends the device band — but the arch sizes a QSA score plane `budget x max_ctx / 4` and refuses
when it grows past its cap; the flags are coupled, the refusal is named and loud.
## Appendix E — the ti8 codec decomposed (`--perfarx` probe kernels on the author's fork, M=2048 nb=16)
One launch of the shipped row = 909 us. Phase probes: encode into local mailbox **36 us (4%)**;
encode+P2P-push+flag 210 us — the push alone runs ~60 GB/s = **PCIe Gen5 x16 line rate**; fold
(reduce + region-B + out + assemble) 196 us of local-memory work. At the band top (M=4096)
nb=32 beats the rule's nb=16 by 2.3% — inside the don't-bother band.
Reads: the "22% link-efficiency tax" of the lossy wire vs exact is **line-rate physics, not an
implementation defect** — the wire is saturated and per-byte optimal. Encode is irrelevant; the
fold is real but off the critical path (see D: pp isn't link-bound). There is no codec patch to
write; proposals for codec-kernel link wins should be pointed at the push-rate line.
- `debug-graph: true` lists which row each op resolves to. It lists declared bands, so confirm
against the running step.
- `r4d_selftest --perfops` times small ops (every elementwise op costs ~4-4.6 us regardless of
payload); `--perfhc` and the GEMM/MoE modes time the rest.
- `rad-kbench` for kernel-against-reference replay; BetterBench's fixed profile decides promotion.
+38 -20
View File
@@ -1,6 +1,6 @@
# Static YaRN
A larger `--max-model-len` reserves a larger serving window; it does not change the model's rotary
A larger `max-model-len` reserves a larger serving window; it does not change the model's rotary
embedding. A checkpoint trained at 262144 positions can request static YaRN explicitly for a
524288-token deployment. Whether the extension keeps useful accuracy must be measured on the model
and workload.
@@ -17,9 +17,13 @@ The factor convention is the config's, as vLLM and transformers read it: `factor
`original_max_position_embeddings` 262144 reaches 524288 positions.
Validated: the Qwen3.8-27B and Qwen3.6-35B-A3B containers and both Flash-Next variants at factor 2,
with retrieval at about 500K tokens, and TP3 perplexity with `--rope-scaling` within about ±1% of
with retrieval at about 500K tokens, and TP3 perplexity with `rope-scaling` within about ±1% of
the unscaled model at factor 2. The LLaMA plugins read the same keys and declare the same ops, but
YaRN has not been run on a LLaMA model.
YaRN has not been run on a LLaMA model. Muse Glimmer validated at factor 8 over 131072 (a 1M
serving window) with retrieval at 913K tokens -- and, unusually, without any scaling at all
(mechanical window extension to 495K, also retrieval-passing): only its 2048-wide sliding layers
carry rotary and its full-attention layers are NoPE, so the unscaled window is the family's
default recipe (docs/ARCHITECTURES.md, museglimmer).
## Metadata
@@ -44,10 +48,11 @@ is valid only for the same source weights and recipe; it cannot mix weights from
revisions.
```sh
rad-convert /checkpoints/Qwen3.8-27B-FP8 \
rad-convert /checkpoints/Qwen3.8-27B \
--draft-model /checkpoints/Qwen3.8-27B-DFlash2 \
--recipe data/recipes/q38-27b-fp8-df2.recipe \
--reuse /models/qwen3.8-27b-fp8.rad \
--recipe data/recipes/q38-27b-iq8r-rtn.recipe \
--set quantization_config.quant_method=w8a8 --set quantization_config.fmt=fwht128 \
--reuse /models/qwen3.8-27b-iq8r.rad \
--set text_config.rope_parameters.rope_type=yarn \
--set text_config.rope_parameters.factor=2 \
--set text_config.rope_parameters.original_max_position_embeddings=262144 \
@@ -55,32 +60,45 @@ rad-convert /checkpoints/Qwen3.8-27B-FP8 \
--set draft.rope_parameters.factor=2 \
--set draft.rope_parameters.original_max_position_embeddings=262144 \
--max-ctx 524288 --kv-cache-dtype bf16 \
-o /models/qwen3.8-27b-fp8-yarn2.rad
-o /models/qwen3.8-27b-iq8r-yarn2.rad
```
Run it with `--plan-only` first. `--max-ctx` is the converter's graph bound; it replaces neither
the YaRN metadata nor the server's `--max-model-len`. A `.rad` is not a converter input, so keep
the YaRN metadata nor the server's `max-model-len`. A `.rad` is not a converter input, so keep
the source checkpoints. After conversion, check the target and draft keys with `rad-info --meta`.
Serve on enough memory for the requested window:
```sh
radiance --model /models/qwen3.8-27b-fp8-yarn2.rad \
--tp 4 --max-model-len 524288 --max-num-seqs 32 --kv-cache-dtype bf16
```yaml
# radiance.yaml
models:
qwen3.8-27b-iq8r-yarn2:
model: /models/qwen3.8-27b-iq8r-yarn2.rad
tp: 4
max-model-len: 524288
max-num-seqs: 32
kv-cache-dtype: bf16
```
`--kv-cache-dtype` sets both the target's and the drafter's KV cache. Check the startup capacity
and real long requests; the command guarantees neither concurrency nor accuracy. Keep the
```sh
radiance --config radiance.yaml
```
`kv-cache-dtype` sets both the target's and the drafter's KV cache. Check the startup capacity
and real long requests; the configuration guarantees neither concurrency nor accuracy. Keep the
unmodified model and serving setup until long-context quality and speed meet the deployment's
requirements.
## Serving an existing container: `--rope-scaling`
## Serving an existing container: `rope-scaling`
The same metadata can be applied when the container is loaded instead of at conversion:
```sh
radiance --model /models/qwen3.8-next-flash-fp8.rad \
--rope-scaling yarn:2 --max-model-len 409600
```yaml
models:
qwen3.8-next-flash:
model: /models/qwen3.8-next-flash-iqr-v4.rad
rope-scaling: yarn:2
max-model-len: 409600
```
`yarn:FACTOR[:ORIG]` (FACTOR above 1) sets `rope_type = yarn`, `factor` and
@@ -101,11 +119,11 @@ Startup logs the rotary:
rope: YaRN factor 2 over 262144 trained positions -- the rotary reaches 524288; --max-model-len 409600 (--rope-scaling)
```
It warns when `--max-model-len` is past what the rotary covers, and, with no scaling, past the
It warns when `max-model-len` is past what the rotary covers, and, with no scaling, past the
trained length.
Use the flag to try a factor, or to serve a container whose source checkpoints are not at hand. A
deployment that settles on a factor can convert it in as above and drop the flag.
Use the key to try a factor, or to serve a container whose source checkpoints are not at hand. A
deployment that settles on a factor can convert it in as above and drop the key.
## Kernel and test contract
-50
View File
@@ -1,50 +0,0 @@
# DeepSeek-V4.1-Flash: a .rad from the release (no GGUF converter)
The official DeepSeek-V4.1-Flash release converts with `rad-convert` alone: no llama.cpp GGUF is
built as an intermediate, and no separate drafter directory is grafted. The pieces below prepare
and convert the release. Serving the container needs the `deepseek41` architecture plugin, which
this tree does not include yet.
- `data/engram_tables.py` builds the Engram hash tables from the release's own `tokenizer.json` and
`config.json`. It reimplements the tokenizer's ByteLevel decode, the normaliser sequence (NFKC,
NFD, strip marks, lowercase, collapse spaces, sentinel), the PCG64 multipliers and the prime
buckets. Against HF `tokenizers`: 0 mismatched token ids of 129280, compressed vocab 99092, the
release's two Engram layers [1, 14]. It writes `engram-tables.safetensors`.
- `data/imatrix_merge.py` fuses the imatrix entries llama.cpp's converter writes split
(`ffn_gate_exps`, `ffn_up_exps`) into the plugin's fused `ffn_gate_up_*`, summing the two halves
(and those of `shexp`): 1184 entries carried through, 160 fused for 40 layers. IQ1_S refuses a
fused weight without one.
- `data/recipes/deepseek41-ud-iq1s.recipe` is the UD-IQ1_S per-tensor mix as rules for libquant's
`ggml` quantiser, so the release converts to the same encodings the GGUF has.
- `rad-convert --chat-template FILE` bakes a template into the container's vocab section. The
release carries no `chat_template.jinja` and its `tokenizer_config.json` names none, so a
container converted without this flag answers `/v1/chat/completions` with 501. Trailing newlines
are stripped as for a sibling template, and an unreadable or empty file is refused.
## Conversion
```
# 1. the Engram tables, from the release's tokenizer (not a GGUF)
python3 data/engram_tables.py <HF release dir> engram-tables.safetensors
# 2. fuse the imatrix's split gate/up entries
python3 data/imatrix_merge.py imatrix_unsloth.gguf_file imatrix-merged.gguf
# 3. convert, with a chat template for the model baked into the container
rad-convert <HF release dir> --add engram-tables.safetensors \
--recipe data/recipes/deepseek41-ud-iq1s.recipe \
--imatrix imatrix-merged.gguf --tokenizer <HF release dir>/tokenizer.json \
--chat-template chat_template.jinja -o deepseek-v4.1-flash-ud-iq1s.rad
```
From DeepSeek-V4.1-Flash-1017 (fp8 with e8m0 scales per 32x32 block, MXFP4 experts) the plan is
32701 weights, 251.07 GiB, and the container 251.13 GiB. The `deepseek41` plugin serves it on 4x
R9700 at `--tp 4` with its DSpark metadata (block 5, 128 experts, targets 37/38/39) and the Engram
tables baked in. Quality, greedy, thinking off: HumanEval 154/164 = 0.939 (the native UD-IQ1_S
reference 0.963, McNemar p = 0.125), GSM 194/200 = 0.970 (reference 0.960).
## Serving
A container converted with `--chat-template` needs no template at serve time. One converted
without it needs `--override-chat-template FILE`; the file must be a template radiance renders
(the release's own is; llama.cpp-only Jinja, such as `dict()` in a GGUF's template, is not).
@@ -1,284 +0,0 @@
# Research note: quant recipes of `unsloth/Qwen3.8-Flash-Next-GGUF`
Method: GGUF header reads only (HTTP `Range`), no weight downloads; sizes verified against the
published file sizes to 4 significant figures.
## Model facts (from the GGUF KV metadata)
| | |
|---|---|
| architecture | `qwen4exp` |
| layers / hidden | 48 / 2560 |
| attention | 36 × Gated DeltaNet (linear, v_head_dim 128, conv kernel 4) + 12 × QSA sparse attention (layers 3, 7, … 47; 24 heads, 2 KV heads, index_topk 512, 8 heads × 128) |
| MoE | 512 routed experts, 10 activated, + 1 shared expert; expert intermediate 640 |
| PLE / n-gram | n-gram size 3, 16 heads (8 per n-gram), 20 M vocab per head, head dim 160, injected at layer 1 |
| context | 262 144 native, `attn_type_vector` marks 36 linear / 12 full layers |
| draft | 1 MTP layer (`blk.48`, `nextn.*`), 3.88 B params self-contained / 2.61 B shared |
| quantisation | imatrix-driven: `quantize.imatrix.file = imatrix_unsloth.gguf`, 926 entries of 1224 tensors, 45 calibration chunks (absent only in the BF16 build) |
176.94 B parameters in total: 125.74 B of model weights and a 51.20 B n-gram/PLE look-up table
(29%, no FLOPs). About 6.04 B are active per token (see "Active parameters").
Tensor census: 1224 tensors; `blk.N` names appear 48× (layers), attn_q/k/v/o and `indexer.*` 12×
(QSA layers), `attn_qkv`/`attn_gate`/`ssm_*` 36× (DeltaNet layers), and
`ffn_gate_exps/up_exps/down_exps` 48× as `[2560, 640, 512]`-stacked 3-D tensors (838.86 M params
each).
## Reading a recipe without downloading
`GET` the first ~1 MB of each `.gguf` with a `Range` header and parse the header: magic `GGUF`,
version, `n_tensors` (u64), `n_kv` (u64), the KV pairs, then per tensor `name`, `n_dims`, `dims[]`,
`ggml_type` (u32), `offset` (u64). Name, dims and type are the recipe; the tensor data is never
read.
Pitfalls:
1. **Split repos.** In a `gguf-split` layout the **first shard has `n_tensors = 0`** and carries
only metadata (≈ 11 MB, mostly tokenizer arrays); every data shard repeats 3 KV pairs plus the
tensor-info table for its own tensors. Merge tensor info from shards 2…N, and read KV
(`general.file_type`, `quantize.imatrix.*`) from shard 1. A scanner that reads only shard 1
reports zero tensors.
2. **Use the real type enum.** `GGMLQuantizationType` values: F32 0, F16 1, Q4_0 2, Q8_0 8, Q2_K 10,
Q4_K 12, Q5_K 13, Q6_K 14, IQ2_XXS 16, IQ3_XXS 18, IQ1_S 19, IQ4_NL 20, IQ3_S 21, IQ2_S 22,
IQ4_XS 23, IQ1_M 29, BF16 30; block sizes from `GGML_QUANT_SIZES`. A wrong enum silently
mislabels the whole table.
3. **Validate.** Compute `Σ ⌈n/block⌉ · type_size` over all tensors and compare with the published
shard sizes. Agreement to 4 significant figures across all 11 builds (e.g. 354.02 GB computed vs
354.03 GB published) confirms the type IDs.
4. Parse with an offset into the buffer, not `buf = buf[n:]` per field, which is quadratic on an
11 MB header and looks like a network hang.
## File sizes
| build | params | size | avg bpw |
|---|---|---|---|
| BF16 | 176.94 B | 354.03 GB | 16.01 |
| Q8_0 | 176.94 B | 188.23 GB | 8.51 |
| UD-Q6_K_XL | 176.94 B | 169.17 GB | 7.65 |
| UD-Q5_K_XL | 176.94 B | 158.29 GB | 7.16 |
| UD-Q4_K_XL | 176.94 B | 111.33 GB | 5.03 |
| UD-Q3_K_XL | 176.94 B | 89.99 GB | 4.07 |
| UD-IQ4_XS | 176.94 B | 93.68 GB | 4.24 |
| UD-Q2_K_XL | 176.94 B | 78.87 GB | 3.57 |
| UD-IQ3_XXS | 176.94 B | 81.96 GB | 3.71 |
| UD-IQ1_M | 176.94 B | 74.54 GB | 3.37 |
| UD-IQ1_S | 176.94 B | 72.55 GB | 3.28 |
## Recipe matrix
`L2`/`L46-47` = layers given one notch more precision (the dynamic "UD/XL" selection).
| weight group (count, params) | BF16 | Q8_0 | Q6_K_XL | Q5_K_XL | Q4_K_XL | Q3_K_XL | IQ4_XS | Q2_K_XL | IQ3_XXS | IQ1_M | IQ1_S |
|---|---|---|---|---|---|---|---|---|---|---|---|
| n-gram/PLE table `per_layer_token_embd` (1, 51.2 B) | BF16 | Q8_0 | Q8_0 | Q8_0 | IQ4_NL | IQ4_NL | IQ4_NL | IQ4_NL | IQ4_NL | IQ4_NL | IQ4_NL |
| experts gate+up (96, 80.5 B) | BF16 | Q8_0 | Q6_K +L2 Q8_0 | Q5_K +L2 Q6_K | Q4_K +L2 Q5_K | IQ3_XXS +L2 IQ4_XS | IQ3_S +L2 IQ4_XS | IQ2_XS +L2 IQ3_XXS | IQ2_S +L2 IQ3_S | IQ1_M/IQ2_XXS† | IQ1_S/IQ2_XXS† |
| experts down (48, 40.3 B) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q5_1 +L2,4,30,46-47 Q8_0 | IQ4_NL +same 5 Q8_0 | IQ4_NL +same 5 Q8_0 | IQ4_NL | IQ4_NL | IQ4_NL | IQ4_NL |
| shared expert gate/up (96) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q5_K +L2 Q6_K | Q6_K +L2 Q8_0 | Q5_K +L2 Q6_K | Q5_K +L2 Q6_K |
| shared expert down (48) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 |
| MoE router `ffn_gate_inp{,_shexp}` (96) | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 |
| `token_embd` (1, 636 M) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q5_K | Q6_K | Q4_K | Q4_K |
| `output` (lm_head) (1, 636 M) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q6_K | Q6_K | Q4_K | Q6_K | Q4_K | Q4_K |
| QSA attn q (12) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q5_K | Q6_K | Q5_K | Q5_K |
| QSA attn k, v (24) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q6_K | Q6_K | Q5_K | Q5_K |
| QSA attn o (12) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q5_K | Q6_K | Q5_K | Q5_K |
| QSA `indexer.q/k_proj` (24) | BF16 | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** |
| DeltaNet `attn_qkv`, `attn_gate` (72) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q5_K +L2 Q6_K | Q6_K +L2 Q8_0 | Q5_K +L2 Q6_K | Q5_K +L2 Q6_K |
| DeltaNet `ssm_out` (36) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q6_K | Q6_K | Q6_K | Q6_K |
| DeltaNet `ssm_alpha`, `ssm_beta` (72) | BF16 | Q8_0 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 |
| gated-residual `hc_*_{up,down}` (388) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 |
| gated-residual `hc_*_inject` (192) | BF16 | Q8_0 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 |
| PLE projections `ple_key`/`ple_value` (L1) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 |
| all norms, biases, `ssm_a`, `ssm_dt`, `ssm_conv1d`, `ple_norm_*` | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 |
† IQ1_M: gate/up = IQ2_XXS at L1-4, 6, 9, 14, 16, 24-25, 30-32, 35, 37-43, 45-47 and IQ1_M on
the other 24. IQ1_S: IQ2_XXS at L1-2, 4, 14, 16, 25, 30, 32, 37, 39, 42, 45-47 (14 tensors),
IQ1_S on the other 34.
Type bpw: Q4_K 4.50, Q5_K 5.50, Q5_1 6.00, Q6_K 6.56, Q8_0 8.50, IQ1_S 1.56, IQ1_M 1.75,
IQ2_XXS 2.06, IQ2_XS 2.31, IQ2_S 2.56, IQ3_XXS 3.06, IQ3_S 3.44, IQ4_NL 4.50, IQ4_XS 4.25.
MTP drafts have their own recipes: `mtp-*Q8_0` is Q8_0 throughout (indexer BF16, norms F32);
`mtp-*Q4_K_M` is stock llama.cpp Q4_K_M (Q4_K base, `output`/`attn_v`/`ffn_down*`/`hc_ffn_down`
upcast to Q6_K/Q8_0, and the `[320, 10240]` up-projections fall to **Q5_0** because 320 is not a
multiple of the 256-element K-quant block). `mmproj-*` is a 0.449 B `clip` vision tower, BF16 or
F16 only, with biases and position embeddings in F32.
## Where the bytes go
| category (params) | Q8_0 | Q4_K_XL | IQ4_XS | Q2_K_XL | IQ1_S |
|---|---|---|---|---|---|
| experts gate+up (80.5 B, 46 %) | 8.50 bpw / 85.6 GB | 4.52 / 45.5 | 3.45 / 34.8 | 2.33 / 23.4 | 1.71 / 17.2 |
| experts down (40.3 B, 23 %) | 8.50 / 42.8 | 6.26 / 31.5 | 4.92 / 24.7 | 4.50 / 22.6 | 4.50 / 22.6 |
| n-gram table (51.2 B, 29 %) | 8.50 / 54.4 | 4.50 / 28.8 | 4.50 / 28.8 | 4.50 / 28.8 | 4.50 / 28.8 |
| everything else (5 B, 2 %) | 8.96 / 4.1 | 9.04 / 4.2 | 9.04 / 4.2 | 6.92 / 3.2 | 6.91 / 3.2 |
| share of file that is n-gram + expert down | 51 % | 54 % | 57 % | 65 % | 71 % |
## Sizes without the n-gram table
`per_layer_token_embd.weight` is a single 160 × 320 001 536 tensor: 51.20 B params, 41 % as many
as the rest of the model combined. It takes only three settings across the repository: BF16
(102.4 GB), Q8_0 (54.4 GB) and IQ4_NL (28.8 GB).
| build | file | n-gram table | rest of model | rest bpw (÷ 125.74 B) | n-gram share |
|---|---|---|---|---|---|
| BF16 | 354.02 | 102.40 | **251.62 GB** | 16.01 | 28.9 % |
| Q8_0 | 188.21 | 54.40 | **133.81 GB** | 8.51 | 28.9 % |
| UD-Q6_K_XL | 169.15 | 54.40 | **114.75 GB** | 7.30 | 32.2 % |
| UD-Q5_K_XL | 158.28 | 54.40 | **103.88 GB** | 6.61 | 34.4 % |
| UD-Q4_K_XL | 111.32 | 28.80 | **82.52 GB** | 5.25 | 25.9 % |
| UD-Q3_K_XL | 89.98 | 28.80 | **61.18 GB** | 3.89 | 32.0 % |
| UD-IQ4_XS | 93.67 | 28.80 | **64.87 GB** | 4.13 | 30.7 % |
| UD-Q2_K_XL | 78.86 | 28.80 | **50.06 GB** | 3.19 | 36.5 % |
| UD-IQ3_XXS | 81.95 | 28.80 | **53.15 GB** | 3.38 | 35.1 % |
| UD-IQ1_M | 74.53 | 28.80 | **45.73 GB** | 2.91 | 38.6 % |
| UD-IQ1_S | 72.54 | 28.80 | **43.74 GB** | 2.78 | 39.7 % |
Without the table the builds span 2.8-8.5 bpw, not the 3.3-8.5 the file sizes suggest.
## Active parameters
Per forward, counting only tensors touched (routed experts at 10/512, embedding and n-gram tables
as look-ups):
| component | active/token | in file | fraction used |
|---|---|---|---|
| routed experts (10 of 512 × 48 layers) | 2 359 M | 120.80 B | 1.95 % |
| DeltaNet qkv + gate (36 layers) | 1 510 M | 1.51 B | 100 % |
| gated residual / hyper-connection | 641 M | 0.64 B | 100 % |
| lm_head (`output`) | 636 M | 0.64 B | 100 % |
| QSA full attention (12 layers) | 598 M | 0.60 B | 100 % |
| DeltaNet state/out (36 layers) | 568 M | 0.57 B | 100 % |
| shared expert | 236 M | 0.24 B | 100 % |
| MoE router | 63 M | 0.06 B | 100 % |
| PLE projections, QSA indexer, α/β, norms | 61 M | 0.06 B | 100 % |
| n-gram table | ≈ 0 (2 560 values) | 51.20 B | 5e-6 % |
| token embedding | ≈ 0 (1 row) | 0.64 B | 2e-4 % |
| **total** | **6.671 B** incl. lm_head / **6.036 B** excl. | 176.94 B | **3.77 %** |
6.036 B matches Qwen's advertised "6B activated" and 125.74 B its "125B". Two thirds of the active
parameters are dense (DeltaNet, gated residual, attention), not experts, so per-token cost is that
of a bandwidth-bound 6 B dense model with a 177 B memory footprint.
Per draft step the MTP head adds 139.7 M of compute (`attn` 49.8 M, 10 experts 49.2 M, `eh_proj`
13.1 M, gated residual 13.1 M, `hc_head` 6.6 M, shared expert 4.9 M, router/indexer 3.3 M) plus the
636 M output projection: **0.776 B active and 0.83 GB read per draft token**, 82 % of it the output
projection.
| | active params | weight bytes read (Q4_K_XL) |
|---|---|---|
| target, 1 forward | 6.671 B | 6.33 GB |
| MTP draft, 1 draft step | 0.776 B | 0.83 GB |
| 1 MTP cycle (verify 3 positions + 2 draft steps) | 21.56 B | 10.91 GB |
| per accepted token (mean length 2.76) | **7.81 B** | **3.95 GB** |
## Weight traffic per token (batch 1)
`step(P) = experts_touched(P) + dense + lm_head`, with `experts_touched(P) = 512·(1 − (1 −
10/512)^P)` (P=1 → 10.0, P=2 → 19.8, P=3 → 29.4 experts per layer). The MTP columns use the
`shared-Q8_0` draft, llama.cpp's `--spec-draft-n-max 2`, and mean accepted length 2.76.
| build | no MTP | MTP cycle | MTP per token | traffic ratio | measured speedup |
|---|---|---|---|---|---|
| BF16 | 13.47 GB | 25.49 GB | 9.23 GB | 1.46× | – |
| Q8_0 | 7.30 | 13.83 | 5.01 | 1.46× | – |
| UD-Q6_K_XL | 6.96 | 12.77 | 4.63 | 1.51× | – |
| UD-Q5_K_XL | 6.75 | 12.14 | 4.40 | 1.53× | – |
| **UD-Q4_K_XL** | **6.33** | **10.91** | **3.95** | **1.60×** | **1.67×** (83 → 139 tok/s) |
| UD-Q3_K_XL | 5.77 | 9.23 | 3.35 | 1.72× | – |
| UD-IQ4_XS | 5.84 | 9.45 | 3.42 | 1.71× | – |
| UD-Q2_K_XL | 4.44 | 7.21 | 2.61 | 1.70× | – |
| UD-IQ3_XXS | 4.95 | 8.15 | 2.95 | 1.68× | – |
| UD-IQ1_M | 4.35 | 6.96 | 2.52 | 1.72× | – |
| **UD-IQ1_S** | **4.31** | **6.84** | **2.48** | **1.74×** | **1.34×** (90 → 121 tok/s) |
## Analysis
1. **Only the expert FFNs and the n-gram table are compressed hard.** Everything else stays at
Q4_K or better, mostly Q8_0/Q6_K/F32: the other 3.6 B params sit at 7-32 bpw and cost 3-4 GB in
every build, a floor on both file size and per-token traffic that the quant name does not show.
2. **`down_proj` is protected, `gate`/`up` gives way.** Down never drops below 4.5 bpw and stays
Q8_0 at Q6_K_XL/Q5_K_XL; at IQ1_S the down tables cost more bytes (22.6 GB) than gate+up
(17.2 GB). Down-projection error is applied after the nonlinearity and summed across the 10
active experts.
3. **The router is never quantised** (F32 everywhere), nor is the QSA indexer (BF16 everywhere,
20 M params). Both are small and both fail badly when wrong.
4. **Layer 2 is upgraded in every build** (one notch up, plus attention/shared-expert upcasts at the
aggressive levels); it is adjacent to layer 1, where the n-gram/PLE signal is injected. Layers 2,
4, 30, 46, 47 form the same "important down-expert" set across Q4_K_XL, Q3_K_XL and IQ4_XS, so
the ranking comes from the calibration run, not a per-target heuristic.
5. **Names understate size at the bottom.** UD-Q3_K_XL (90.0 GB) is smaller than UD-IQ4_XS
(93.7 GB), and UD-Q2_K_XL (78.9 GB) smaller than UD-IQ3_XXS (82.0 GB). Each pair is one tier with
two codebooks; the IQ variant buys accuracy with size (IQ3_S 3.44 vs IQ3_XXS 3.06, IQ2_S 2.56 vs
IQ2_XS 2.31 bpw).
6. **The n-gram table is the binding constraint on size.** 51.2 B params at a 4.5 bpw floor is
28.8 GB in every build below Q5_K_XL, 71 % of the IQ1_S file together with the down tables;
nothing in the repository is under ~72 GB. It is a random look-up (≈ 1.4 KB per token,
2 560 values), so it costs memory, not bandwidth, and is the one component that can live in CPU
RAM or on disk at no speed cost.
7. **MTP trades compute for bandwidth.** +17 % compute (7.81 vs 6.67 B active params per token) for
−38 % weight traffic at batch 1. A 3-position verify pass touches ~29 of 512 experts per layer
instead of 10, so MTP stops paying once concurrency saturates the experts: unsloth measures
Q4_K_XL at 83 → 139 tok/s with 1 user but 216 → 192 tok/s with 8.
8. **Value points.** Q4_K_XL (5.03 bpw, 111 GB) is the best balance. Below it each step saves little
traffic: Q2_K_XL → IQ1_S saves 3 % of per-token bandwidth for 0.6 bpw of expert precision, and
IQ1_S also under-delivers in practice (1.34× vs 1.74× modelled) because 1.5 bpw IQ1_S is
dequant-bound. Prefer IQ1_M over IQ1_S if 74.5 GB fits (2 GB more for +0.2 bpw). For MTP, use a
`shared-*` draft: the same runtime cost, ~1.3 GB less resident weight, and the draft's output
projection read at the main model's precision.
## The imatrix
`imatrix_unsloth.gguf` (580 MB, in the repository as `imatrix_unsloth.gguf_file`) is llama.cpp's
GGUF imatrix: per weight, `in_sum2` (the sum of the input's squares, per input channel) and `counts`
(tokens seen). 45 chunks of 18 432 tokens = **829 440 tokens** from one file,
`unsloth_calibration_Qwen3.8-Flash-Next.txt`. The routed experts are recorded **per expert**
(`in_sum2` is `[K, 512]`, `counts` `[512]`); `ffn_gate_exps` and `ffn_up_exps` are byte-identical,
having the same input. There is nothing for `blk.48`, `output`, `token_embd` or the n-gram table.
**The Q8_0 down layers are the layers that host a super expert.** One expert in each of a few layers
carries a large share of the layer's `down` input energy from a sliver of its tokens, all of it in
one or two channels, up to 208 000x that expert's median channel:
| layer | expert | share of the layer's down-input energy | share of its routing |
|---|---|---|---|
| 47 | 445 | 30.5 % | 0.38 % |
| 4 | 108 | 24.1 % | 0.13 % |
| 2 | 322 | 10.3 % | 0.25 % |
| 46 | 290 | 6.9 % | 0.84 % |
| 30 | 169 | 3.9 % | 0.12 % |
These are the five layers given Q8_0 down. The next layers by energy share (28, 37, 26: ~4 %) are
heavily routed experts whose energy share equals their routing share, and are not protected. A
super expert is not harder to quantise relative to its own output: against its own imatrix
profile, int4 g128 costs it the same ~12 % relative output error as an ordinary expert and E4M3 the
same 2.6 %. Its output is larger, so the same relative error is a large absolute one. A GGUF type is
per tensor and a tensor holds all 512 experts of a layer, so protecting one expert costs the whole
layer's `down`.
**A pooled down profile describes no expert.** A typical expert's own `down` input profile has a
median cosine of 0.15-0.87 with the layer's pooled one (0.15 at layer 4, 0.20 at 47, where the pool
is the super expert); `gate_up` 0.91-0.98. `down`'s input channels are each expert's own
intermediate units, so channel `i` of one expert has nothing to do with channel `i` of another.
**Compared with radiance's 10M-token Grams** (recorded from the bf16 model over ten million tokens
of its calibration corpus, pooled per layer; [MOE-W4.md](MOE-W4.md), "Calibration"): the `gate_up`
diagonals agree at every layer (cosine 0.98-0.99, the same top channels at the same shares), as do
the `down` spikes at layers 46 and 47 (channels 218 and 635). At layers 2, 4, 9, 14, 16, 25, 30 and
32 the spike channels sit at a flat channel's share in radiance's Grams: those super experts never
fired on its corpus. Open question: either the imatrix harness (raw 18K-token chunks, each from
position 0, special tokens as plain text) triggers what chat-templated traffic does not, or the two
implementations compute those experts differently.
**The expert stack repeats every 16 layers in the middle of the model.** Per-expert routing counts
correlate 0.76-0.93 between layer L and L+16 for L in 8..23, and ~0 between neighbours; the same
(expert, channel) spikes appear at 9/25 (e368 c191), 14/30 (e169 c72) and 16/32 (e391 c139).
## Caveats
- These are the recipes of the files as published on 2026-09-30; later uploads may differ. They say
nothing about the quality of each level, which needs a downstream evaluation.
- Traffic numbers assume batch 1 and independent routing across positions; real expert usage is
skewed, so distinct-expert counts (and hence MTP cost) are slightly overestimated.
- Mean accepted length 2.76 and 66 % acceptance come from a single unsloth log line (`shared-Q8_0`
draft + `Q4_K_XL`, 4× A100, 8K input, llama.cpp's `--spec-draft-n-max 2`) and are applied to
every build here.