radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+341 -333
View File
@@ -1,68 +1,64 @@
# Architectures — the geometry, and the traps that stay plausible when wrong
# Architectures: geometry and traps
One architecture plugin claims one **(architecture id, quantisation descriptor)** pair — that is the
selection key of `spec.md` §2.4, and it is why a family with two checkpoint formats is two `.so`
files rather than one that branches. `rad-convert` normalises whatever it read (safetensors or GGUF)
into the id an architecture plugin claims.
An architecture plugin claims one **(architecture id, quantisation descriptor)** pair, the
selection key of `spec.md` §2.4, so a family with two checkpoint formats is two `.so` files rather
than one that branches. `rad-convert` normalises what it reads (safetensors or GGUF) into the id a
plugin claims.
| plugin | id | quantisation | what it serves |
|---|---|---|---|
| `arch/llama_fp8` | `llama` | `fp8_e4m3` | the plain LLaMA decoder, from a checkpoint that already holds E4M3 codes and a `weight_scale_inv` plane |
| `arch/llama_dense_fp8` | `llama` | *(empty)* | the same graph from a bf16 checkpoint; `rad-convert` quantises. MiniCPM5-2B |
| `arch/llama_fp8` | `llama` | `fp8_e4m3` | the plain LLaMA decoder, from a checkpoint that holds E4M3 codes and a `weight_scale_inv` plane |
| `arch/llama_dense_fp8` | `llama` | *(empty)* | the same graph from a bf16 checkpoint, linears made block fp8 by a recipe or kept bf16. MiniCPM5-2B |
| `arch/qwen35_bf16` | `qwen35` | *(empty)* | the Qwen3.5/3.6/3.8 dense hybrid, served bf16 |
| `arch/qwen35_fp8` | `qwen35` | `fp8_e4m3` | the same, block-scaled FP8 weights and activations |
| `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed |
| `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert |
| `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank |
| `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector |
| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense (text): two attention classes — sliding-window and proportional-RoPE global (`attention_k_eq_v`) — over one GemmaRMSNorm stream, GELU ffn, two KV groups, softcapped logits, tied scaled embedding; served from a CT-INT4 (QAT w4a16) checkpoint as group-128 int4 codes with an f16 scale. Optional draft head: Google's assistant (`rad-convert --draft-model`), a serial head with no cache of its own (`rad_drafter_shared_kv`) |
| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint — the 26B-A4B MoE (a dense and a routed arm side by side) and the dense sizes without per-layer embeddings — with z-lab's DFlash drafter; routed experts bf16 or block fp8, as the recipe chose |
| `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image GENERATOR: a Qwen3-VL-8B text encoder, a 32-block single-stream DiT and an RGBA VAE, from the diffusers pipeline directory; the DiT and text encoder bf16 or block fp8, as the recipe chose |
| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release, served w4a8. Optional draft head: Google's assistant (`rad-convert --draft-model`), with no cache of its own (`rad_drafter_shared_kv`) |
| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 |
| `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 |
| `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text |
This document is the geometry of each, and the handful of readings that are **arithmetically
silent** — wrong in a way that produces fluent output and no error anywhere.
The traps below are readings that are wrong without any error: the model produces fluent output.
## The rule that applies to all of them
## Common rule
**`head_dim` is READ, never derived.** On the Qwen hybrids `head_dim` is 256 while
`hidden_size / num_attention_heads` is 213, so a derived value makes every downstream shape silently
wrong — the projection widths, the KV page size, the attention kernel's band. `core/engine_bringup.cpp`
takes it from the container's meta and says so at the line that does it.
**`head_dim` is read, never derived.** On the Qwen hybrids `head_dim` is 256 while
`hidden_size / num_attention_heads` is 213, and a derived value silently breaks the projection
widths, the KV page size and the attention kernel's band. `core/engine_bringup.cpp` takes it from
the container's meta.
---
# `llama` — the plain decoder
# `llama`: the plain decoder
`model_type: llama` with `LlamaForCausalLM`, the most widely shared decoder shape there is. Every
layer is full attention; there is no gated delta net, no layer schedule, no output gate and no
per-head q/k norm, which is precisely what separates this plugin from `qwen35_fp8`.
`model_type: llama` with `LlamaForCausalLM`. Every layer is full attention; unlike `qwen35_fp8`
there is no gated delta net, layer schedule, output gate or per-head q/k norm.
MiniCPM5-2B is what it exists for: 42 layers, hidden 2048, 16 query heads over 2 KV heads at
`head_dim` 128, SwiGLU at 6144, RMS norms, full rotary at theta 5e6, an untied 130560-row head, and
no biases anywhere.
MiniCPM5-2B: 42 layers, hidden 2048, 16 query heads over 2 KV heads at `head_dim` 128, SwiGLU at
6144, RMS norms, full rotary at theta 5e6, an untied 130560-row head, no biases.
**Two checkpoint formats, one graph.** OpenBMB publishes MiniCPM5-2B in bf16 and nothing else, so
"MiniCPM5-2B FP8A8" is a statement about what this engine *runs*, not about what the checkpoint
holds. `llama_dense_fp8` declares the empty quantisation descriptor and the recipe
`data/recipes/minicpm5-2b-dspark.recipe` does the work at conversion — libquant's `rtn`, one amax
per 128x128 block, `scale = amax/448` rounded to bf16 — so the container holds the encoding a
checkpoint that shipped fp8 would. Both plugins declare the same ops over the same encoding, and the
kernels lay it out the same way at load, so nothing downstream can tell which one ran. For the same
reason the bf16 checkpoint itself is not served directly: its linears are not the fp8 this plugin
reads.
**Two checkpoint formats, one graph.** OpenBMB publishes MiniCPM5-2B only in bf16, so
`llama_dense_fp8` declares the empty quantisation descriptor and the recipe
`data/recipes/minicpm5-2b-dspark.recipe` quantises at convert (libquant's `rtn`, one amax per
128x128 block, `scale = amax/448` rounded to bf16). The container then holds what an fp8 release
would, both plugins declare the same ops over it, and nothing downstream can tell which one ran. A
container whose linears are left bf16 (`minicpm5-2b-bf16-dspark.recipe`) is read by `gemm_nt`.
What is fp8: `self_attn.{q,k,v,o}_proj` and `mlp.{gate,up,down}_proj`, each with a bf16
`[N/128][K/128]` scale plane. What is not: every norm and the embedding. The lm_head is declared at
whatever the source holds — bf16 from a checkpoint, fp8 where the recipe made it so — and the
selection picks the GEMM that reads it. Both vocabulary edges are row-sharded.
fp8: `self_attn.{q,k,v,o}_proj` and `mlp.{gate,up,down}_proj`, each with a bf16 `[N/128][K/128]`
scale plane. Not fp8: every norm and the embedding. The lm_head is declared at whatever the source
holds (bf16 from a checkpoint, fp8 where the recipe made it so), and the GEMM that reads that
encoding is selected. Both vocabulary edges are row-sharded.
---
# `qwen35` — the hybrid Gated DeltaNet / gated-attention family
# `qwen35`: the hybrid Gated DeltaNet / gated-attention family
Qwen3.5, Qwen3.6 and Qwen3.8 dense models share this architecture; HuggingFace calls it
`model_type: qwen3_5` (`Qwen3_5ForConditionalGeneration`) and GGUF calls it `qwen35`.
Qwen3.5, Qwen3.6 and Qwen3.8 dense models. HuggingFace calls it `model_type: qwen3_5`
(`Qwen3_5ForConditionalGeneration`); GGUF calls it `qwen35`.
## Qwen3.8-27B-FP8, exactly
## Qwen3.8-27B-FP8
```
64 layers, full_attention_interval 4 -> layers 3,7,...,63 are FULL ATTENTION (16 of them)
@@ -82,10 +78,7 @@ quantization: fp8 e4m3, activation_scheme "dynamic", per-weight `weight_scale_in
vision: 27 blocks, hidden 1152, 16 heads -> head_dim 72, patch 16, out_hidden_size 5120
```
### Why this lines up with libr4d
Every geometry above lines up with a libr4d entry point, which is the strongest available evidence
that the kernel-plugin constraint model is the right shape.
### libr4d entry points
| model geometry | libr4d entry point |
|---|---|
@@ -97,11 +90,12 @@ that the kernel-plugin constraint model is the right shape.
| GDN gated norm over an interleaved z | `gdn_gated_norm_had_quant_i8` (`zgrp`/`zblk`) |
| vision head_dim 72 | `attn_vit_h72_bf16` |
## Tensor names — the FP8 safetensors checkpoint
## Tensor names: the FP8 safetensors checkpoint
Sharded one file per layer (`layers-N.safetensors`), plus `outside.safetensors` and
`mtp.safetensors`. Every FP8 weight carries a companion `weight_scale_inv`; the norms, biases,
`A_log`, `dt_bias` and `conv1d` stay bf16.
`mtp.safetensors`. Every FP8 weight has a companion `weight_scale_inv`; the norms, biases, `A_log`,
`dt_bias` and `conv1d` stay bf16. Linear shapes below are `[in, out]`, as the plugins write them;
the safetensors tensors are stored `[out, in]`.
**Full-attention layer** (`model.language_model.layers.N.`):
```
@@ -129,14 +123,14 @@ mlp.{gate,up,down}_proj as above
```
**Model level**: `model.language_model.embed_tokens.weight`, `model.language_model.norm.weight`,
`lm_head.weight` (**not tied** on this model), and the MTP head: `mtp.fc.weight`,
`mtp.norm.weight`, `mtp.pre_fc_norm_embedding.weight`, `mtp.pre_fc_norm_hidden.weight`.
`lm_head.weight` (not tied on this model), and the MTP head: `mtp.fc.weight`, `mtp.norm.weight`,
`mtp.pre_fc_norm_embedding.weight`, `mtp.pre_fc_norm_hidden.weight`.
## The full-attention layer — gated attention
## Full-attention layer: gated attention
`q_proj` produces the query **and a gate, interleaved per head**: for each of the 24 heads the
first 256 elements are the query and the next 256 are the gate, so both are strided views with
pitch 512 rather than a contiguous split.
first 256 elements are the query and the next 256 the gate, so both are strided views with pitch
512.
```
qg = gemm(x, q_proj) [n_tok, 12288]
@@ -151,11 +145,11 @@ o = o * sigmoid(gate) <-- the gate. output_gate_type "swish
out = gemm(o, o_proj)
```
`qk_norm_rope_gate` does the two norms, the rope and the gate extraction in one kernel and takes the
interleaving off the `q_gate` operand's own row pitch, so the projection is declared as it is laid
out rather than converted at load. Declare it first and fall back to the unfused sequence.
`qk_norm_rope_gate` does the two norms, the rope and the gate extraction in one kernel, taking the
interleave from the `q_gate` operand's row pitch, so the projection is declared as laid out rather
than converted at load. Declare it first and fall back to the unfused sequence.
## The linear layer — gated delta net
## Linear layer: gated delta net
```
qkv = gemm(x, in_proj_qkv) [n_tok, 10240]
@@ -171,29 +165,27 @@ o = rmsnorm(o, linear_attn.norm) * silu(z) the gated norm
out = gemm(o, out_proj)
```
`linear_num_value_heads` (48) is three times `linear_num_key_heads` (16), so q and k are shared
across three value heads. libr4d's GDN kernels take `H` and `Hg` separately for exactly this.
`linear_num_value_heads` (48) is three times `linear_num_key_heads` (16), so each q/k head serves
three value heads; libr4d's GDN kernels take `H` and `Hg` separately for this.
## Things that stay plausible when wrong, so get them right
## Traps
- **`q`/`k` use L2 normalisation, not RMS.** Different op, different arithmetic.
- **`A_log` is a log.** In the GGUF conversion `ssm_a` is already `-exp(A_log)`; in *this*
safetensors checkpoint the tensor is named `A_log` and the exponent has **not** been taken. The
converter is the component that decides which convention reaches the kernel, and it must say so.
- **`q`/`k` use L2 normalisation, not RMS.**
- **`A_log` is a log.** In the GGUF conversion `ssm_a` is already `-exp(A_log)`; in this safetensors
checkpoint the tensor is `A_log` with the exponent not taken. The converter decides which
convention reaches the kernel, and must say so.
- **The GDN output gate is `silu` here and `sigmoid` on Qwen4-Exp.** `RMSNormGated` defaults to silu
and every Qwen3.5/3.6 release leaves it there; Qwen4-Exp states `output_gate_type: "sigmoid"` and
means it. A gate of `sigmoid(z)` where the model wants `silu(z)` rescales every value head's
output — a config read, not a kernel to write. `arch/common/rad_block_gdn_fp8.h` refuses anything
but those two names.
- **Two readings the checkpoint cannot settle by inspection.** The rope convention (`neox`, halves,
against `gptj`, adjacent pairs) and which half of each head's `q|gate` pair is the query are both
self-consistent either way, and the sigmoid accepts either half — so no per-op check can reach
them. The MTP head's concat order (hidden-first or embedding-first) is the third of the same kind.
Each is a declared knob at the site that reads it, for the same reason.
and every Qwen3.5/3.6 release keeps it; Qwen4-Exp sets `output_gate_type: "sigmoid"`. The wrong
gate rescales every value head's output. `arch/common/rad_block_gdn_fp8.h` refuses any other
name.
- **Readings no per-op check can settle.** The rope convention (`neox`, halves, against `gptj`,
adjacent pairs), which half of each head's `q|gate` pair is the query (the sigmoid accepts
either), and the MTP head's concat order (hidden-first or embedding-first) are all
self-consistent either way. Each is a declared knob at the site that reads it.
## KV groups
Three of them, which is why hybrid KV groups are first-class rather than an extension:
Three groups, which is why hybrid KV groups are first-class:
| group | kind | geometry |
|---|---|---|
@@ -201,59 +193,52 @@ Three of them, which is why hybrid KV groups are first-class rather than an exte
| GDN recurrent state | `RAD_KV_LINEAR` | 48 layers, 48 states of 128 x 128 |
| GDN conv state | `RAD_KV_CONV` | 48 layers, 2*16 + 48 = 80 heads x 128 = 10240 channels, a rolling `conv_width - 1 + n_spec` window |
**The recurrent state is f32 by default**, which is 48 x 128 x 128 x 4 = 3 MiB a layer and
**144 MiB across the 48 linear layers, per sequence** — and it is what the prefix-cache checkpoint
of `spec.md` §7.3 snapshots. Its read and write are most of what the two GDN kernels do, so halving
its width halves one of the largest kernels after the fp8 GEMMs. libr4d compiles an f16 form and
argues the numerics where the kernel lives — the elements are O(0.1) with no range problem and
f16's eleven mantissa bits put the round-trip error at 5e-4 relative. It is **off by default
anyway**, because it changes generated text without being asked to; nothing about the container
changes between the two, so there is no re-convert. How a speculative step keeps the state it can
roll back is `docs/OPS.md`'s `state_form`.
**The recurrent state is f32**: 48 x 128 x 128 x 4 = 3 MiB per layer, **144 MiB per sequence**
across the 48 linear layers, and it is what the prefix-cache checkpoint of `spec.md` §7.3
snapshots. Its reads and writes dominate the two GDN kernels. libr4d also compiles an f16 form
(elements are O(0.1); the f16 round trip is about 5e-4 relative) that would halve that traffic,
but the plugins declare f32 because f16 changes the generated text. How a speculative step keeps a
state it can roll back is `docs/OPS.md`'s `state_form`.
## FP8
`quant_method: fp8`, `fmt: e4m3`, `activation_scheme: dynamic`, and a `weight_scale_inv` beside
every quantised weight — DeepSeek-style block scaling, 128x128. Activations are quantised at
runtime, which is what "dynamic" means and what makes the activation quantiser an op rather than a
constant. The vision tower's first several blocks are in `modules_to_not_convert` and stay bf16.
every quantised weight: DeepSeek-style 128x128 block scaling. Activations are quantised at runtime
("dynamic"), so the activation quantiser is an op. The vision tower's first several blocks are in
`modules_to_not_convert` and stay bf16.
**libr4d reads those bytes directly, so `rad-convert` COPIES**: no permutation, no repacking, no
dequantisation, and a `.rad` costs what the checkpoint does. That is the whole reason this plugin
family exists — widening a 27B FP8 checkpoint to bf16 doubles the weight bytes; `qwen35_bf16` is the
plugin for a checkpoint that is bf16 to begin with.
The rows are `gemm_fp8a16_nt_m1`, `gemm_fp8a8_nt_m16`, `gemm_fp8a8_gated_nt_m16` and
**libr4d reads those bytes directly, so `rad-convert` copies them**: no permutation, repacking or
dequantisation, and a `.rad` costs what the checkpoint does. Widening a 27B FP8 checkpoint to bf16
would double the weight bytes; `qwen35_bf16` is for checkpoints that are bf16 to begin with. The
rows are `gemm_fp8a16_nt_m1`, `gemm_fp8a8_nt_m16`, `gemm_fp8a8_gated_nt_m16` and
`gemm_fp8a8_tiled`.
**The shipped path is `fp8a8`**, and the reason is a band and not a preference. `dtype` is ONE string
per declared op, so a linear is `fp8a16` or `fp8a8` and cannot be both. `fp8a16` reads a bf16
activation directly and needs no quantise launch, which is strictly better — and its kernel serves
`M <= 1`, which is a single-sequence decode and nothing else. `fp8a8`'s two kernels cover every M
between them, and the price is one `quant_act_fp8` launch per activation that feeds a GEMM — *per
activation*, not per linear, which is why the quantiser is its own struct rather than a step inside
the linear.
**The shipped path is `fp8a8`.** `dtype` is one string per declared op, so a linear is `fp8a16` or
`fp8a8`, not both. `fp8a16` reads the bf16 activation directly with no quantise launch, but its
kernel serves only `M <= 1` (single-sequence decode). `fp8a8`'s two kernels cover every M, at the
price of one `quant_act_fp8` launch per activation that feeds a GEMM. That cost is per activation,
not per linear, which is why the quantiser is its own struct rather than a step inside the linear.
**The scale plane is a WEIGHT operand**: `gemm_nt_q` takes `a, a_scale, b, b_scale`, and `b` and
**The scale plane is a weight operand**: `gemm_nt_q` takes `a, a_scale, b, b_scale`, and `b` and
`b_scale` are two declarations over the planes of one logical weight (`RadWeightDecl::planes`).
Each is placed, moved and sharded on its own — the engine cuts a row-sharded scale plane on its
block boundary exactly as it cuts the codes beside it.
Each is placed, moved and sharded on its own; the engine cuts a row-sharded scale plane on its
block boundary as it cuts the codes.
## `qwen35moe`
This architecture with the MLP replaced by a router plus experts, and *only* that: the gated
attention, the gated delta net, the layer schedule, the rope, the vocabulary edges and the MTP head
are identical, and the places where a routed feed-forward differs are behind one conditional in the
shared source. It is a second translation unit rather than a branch on `n_expert` because the id is
half the selection key — one `.so` cannot claim both, and an operator looking at what is installed
should see two plugins for two architectures.
The same architecture with the MLP replaced by a router plus experts; the gated attention, the
gated delta net, the layer schedule, the rope, the vocabulary edges and the MTP head are identical,
and every difference is behind `#if QWEN35_MOE` in the shared source. It is a second translation
unit rather than a branch on `n_expert` because the id is half the selection key, and one `.so`
cannot claim both ids.
---
# `qwen4exp` — Qwen4-Exp / Qwen3.8-Flash-Next
# `qwen4exp`: Qwen4-Exp / Qwen3.8-Flash-Next
`model_type: qwen4_exp`, a subclass of `Qwen3_5MoeTextModel` — so most of it is composition over the
blocks above. What is genuinely new is small and named: the gated residual, the n-gram/PLE layer,
QSA's indexer, stacked dense expert tensors, GQA 12, and the delta net's sigmoid output gate.
`model_type: qwen4_exp`, a subclass of `Qwen3_5MoeTextModel`, so most of it composes the blocks
above. New: the gated residual, the n-gram/PLE layer, QSA's indexer, stacked dense expert tensors,
GQA 12, and the delta net's sigmoid output gate.
```
48 layers of 12 x (3 x GatedDeltaNet -> MoE, then 1 x QSA -> MoE)
@@ -265,146 +250,116 @@ indexer_n_heads 4 indexer_head_dim 128 indexer_budget 2048 indexer_compress_r
mtp_num_hidden_layers 1 output_gate_type sigmoid
```
**The residual stream is four times as wide, and the blocks do not own their norms.** There is no
`input_layernorm`, no `post_attention_layernorm` and no final `norm` in this checkpoint. In their
place every block has a gated residual connection — a grouped norm over the 10240 stream, a low-rank
data-dependent read gate that mixes the four sub-streams down to 2560, and four data-dependent
scalars that gain the block's output back into all four. 96 of them, plus a 97th with no write half
that collapses the stream for the lm_head. The consequence for the blocks is that they run in their
"input is already normed and quantised" mode and therefore give up two fusions — the residual add
folded into the next norm, and the all-reduce folded into it.
**The residual stream is four times as wide, and the blocks do not own their norms.** The
checkpoint has no `input_layernorm`, `post_attention_layernorm` or final `norm`. Each block has a
gated residual connection instead: a grouped norm over the 10240 stream, a low-rank data-dependent
read gate that mixes the four sub-streams down to 2560, and four data-dependent scalars that add
the block's output back into all four. There are 96, plus a 97th with no write half that collapses
the stream for the lm_head. The blocks run in their "input already normed and quantised" mode and
so give up two fusions: the residual add and the all-reduce folded into the next norm.
**Each weight's storage is the recipe's choice.** The checkpoint is bf16 with no
`quantization_config`, so the descriptor is empty; `rad-convert` quantises by a recipe, and the
plugin reads each weight's encoding from the container and declares the op that reads it:
- block linears (`self_attn.{q,k,v,o}_proj`, `linear_attn.{in_proj_qkv, in_proj_z, out_proj}`,
the shared expert's three): fp8 or int8 (served W8A8);
- routed experts' gate_up and down: fp8, bf16, or one of the four- and five-bit forms of
`docs/MOE-W4.md`;
- each connection's two mixing matrices and the MTP head's `fc_hidden` / `fc_embedding`: E4M3 rows
or bf16. The low-rank width is 320, 2.5 scale blocks, so they are scaled a row group at a time;
- the lm_head: whatever a `logits_gemm` kernel reads;
- bf16: every norm gain, `A_log`, `dt_bias`, `conv1d`, `in_proj_a` and `in_proj_b` (48 rows is not
a whole scale block), the router, `shared_expert_gate` and `embed_tokens`.
**What each weight is stored as is the recipe's decision.** The checkpoint is bf16 throughout and
carries no `quantization_config` at all, so the plugin's descriptor is the empty one: `rad-convert`
quantises by a recipe, and the plugin reads each weight's encoding from the container and declares
the op that reads it. The block linears — `self_attn.{q,k,v,o}_proj`,
`linear_attn.{in_proj_qkv, in_proj_z, out_proj}`, the shared expert's three — are block fp8 or
int8 (served W8A8). Every routed expert's gate_up and down is fp8, bf16, or one of the four- and
five-bit forms of `docs/MOE-W4.md`.
Each connection's two mixing matrices and the MTP head's `fc_hidden` / `fc_embedding` are E4M3 rows
or bf16: the low-rank width is 320, which is 2.5 scale blocks, so they are scaled a row group at a
time rather than block-scaled. The lm_head is whatever a `logits_gemm` kernel reads. Every norm
gain, `A_log`, `dt_bias`, `conv1d`, `in_proj_a` and `in_proj_b` (48 rows is not a whole scale
block), the router, `shared_expert_gate` and `embed_tokens` stay bf16.
`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe` is the served choice: four-bit codebook experts with
ten protected experts left bf16, int8 block linears and lm_head, E4M3 mixing and MTP fc matrices,
and the n-gram table at one fixed E4M3 scale.
**Tensor parallel at two ranks splits every expert's width, unevenly.** `moe_intermediate_size` is
640 = 5 x 128, so an even share at tp2 is 320, which is not a whole number of 128-column blocks —
and the fp8 scale block, the four-bit scale group and the rotation all sit on them. So each rank
takes three blocks of the experts of one parity and two of the other's (`moe_gemm_q`'s two tables in
`docs/OPS.md`), the router stays replicated so both ranks agree on the routing, each rank computes
its slice of every routed expert, and the block's existing end-of-block all-reduce sums the
partials. No all-to-all, no extra collective. The shared expert's 640 columns split the same way,
three blocks on rank 0 and two on rank 1.
**Tensor parallelism splits every expert's width.** `moe_intermediate_size` is 640 = 5 x 128, and
the fp8 scale block, the four-bit scale group and the rotation all sit on 128-column blocks, so an
even tp2 share (320) does not work. Each parity's five blocks are cut contiguously across the
ranks, and the rank taking the extra block alternates with the parity: at tp2 a rank takes three
blocks of the experts of one parity and two of the other's (`moe_gemm_q`'s two tables in
`docs/OPS.md`). The router is replicated, each rank computes its slice of every routed expert, and
the block's existing all-reduce sums the partials: no all-to-all, no extra collective. A world
above the block count is refused at declare, since an empty slice would still join the
all-reduce. The shared expert splits as evenly as whole blocks allow: three blocks on rank 0 and
two on rank 1 at tp2; at tp4, rank 2 `[0, 256)` and one block each on ranks 3, 0 and 1.
**Five blocks do not divide evenly, and an even share is not required.** 5 is odd, so at tp4 an
even share is 160 columns, 1.25 blocks — but the split is TWO SLICES per expert, not one slice a
rank: each parity's blocks are cut contiguously across the ranks and the rank taking the odd block
alternates with the parity, so every rank's share is whole blocks, every block of every expert has
exactly one owner, and each rank still computes a slice of every routed expert. At four ranks and
five blocks an even-parity expert is `[0, 2)` blocks on rank 0, `[2, 3)` on rank 1, `[3, 4)` on
rank 2, `[4, 5)` on rank 3, and each rank's place on the odd parity shifts by one — rank 1 takes the
fat block there instead of rank 0 — so no rank takes the extra block of both parities. A world
above the block count is refused at declare, by name: a rank with an empty slice computes nothing
and still joins the all-reduce. The shared expert's 640 columns split as evenly as whole blocks
allow: five blocks over four ranks is rank 2 `[0, 256)` and one block each on ranks 3, 0 and 1.
**At four ranks the classes are four.** Parity gives the extra block only two places to go, so
ranks 0 and 1 would compute three blocks of every even/odd pair of routed experts and ranks 2 and 3
two, and every block's all-reduce would have 2 and 3 wait. So at four ranks the cut above is made
per class of the expert's number mod 4, the rank's place shifted by the class: rank `r` takes
`[0, 2)` blocks of class `r` and one block of each other class, five blocks of every four experts
on every rank. That is `moe_gemm_q_mod4`, four slice tables where `moe_gemm_q` takes two
(`docs/OPS.md`), and every slice is one a rank already took of some parity. A layer that keeps two
experts plain bf16 has 510 quantised ones, and its first two classes are one expert longer. What
does not divide elsewhere stays apart: the shared expert's extra block is rank 2's and the
**At four ranks the classes are four.** Parity alone would give ranks 0 and 1 three blocks of every
expert pair and ranks 2 and 3 two. So at tp4 the cut is made per class of the expert's number
mod 4: rank `r` takes blocks `[0, 2)` of class `r` and one block of each other class, five blocks
of every four experts on every rank (`moe_gemm_q_mod4`, four slice tables). A layer that keeps two
experts plain bf16 has 510 quantised ones, and its first two classes are one expert longer. The
protected bf16 experts' ten 64-wide tiles go 3, 3, 2, 2.
Expert parallelism — whole experts a rank — is what this replaced, and why it stays replaced: the
recipe protects its bf16 experts in pairs precisely so each rank's quantised count stays even, and
sharding experts by rank breaks that parity property the weight tables rest on.
**Attention splits by KV head, and replicates once the ranks outrun the heads.** There are 2 KV
heads of 256 rows, so each rank declares `n_head_kv 1` and reads one head's row-span of `k_proj` and
`v_proj`. At tp2 that is the ordinary row shard. At tp4 the heads cannot divide four ways, so they
are replicated in rank pairs: ranks {0,1} carry KV head 0, ranks {2,3} carry KV head 1, and both
ranks of a pair hold byte-identical KV weights — more read traffic, no extra VRAM. `n_head` is 12 a
rank at tp2 and 6 at tp4, so gqa is 12 at tp2 and 6 at tp4 and the attention kernel is a different
instantiation (`attn_{prefill,decode}_h256_gqa6_bs4`, the QSA page of 4) than the gqa12 pair tp2
resolves to, not the same kernel over fewer heads. Any world size above the KV head count must be a
multiple of it: 4 is a multiple of 2, 3 and 5 are not, and those widths are refused at declare
time.
Expert parallelism (whole experts per rank) is not used: random routing leaves ranks whole experts
apart and waiting at the all-reduce, and it would break the parity tables, for which the recipe
protects bf16 experts in pairs.
**The fused all-reduce forms are two-rank, except the exact write.** At four ranks `ar_hc_write`
exists on the exact wire only (`ar_hc_write_4rank`, the 4-rank one-shot with the write as its
epilogue), and so does `ar_gather_hc_write` (`ar_gather_hc_write_4rank`, the same with
`moe_gather` as its prologue), which the MoE connections take wherever the step is one MoE pass.
Both are declared over the rows of a decode or verify step — `--max-num-seqs` × (1 +
`--num-speculative-tokens`) — because a one-shot is for those messages, and a step within that
bound takes them wherever its message goes out exact: always with `--tp-wire exact`, and with
`--tp-wire wht6` under `--tp-wire-min-kb`. They run on an all-reduce instance keyed by that bound,
not on the standalone all-reduce's unless the two bounds agree; the wide family's flag, sequence
and slot discipline is what makes either safe on one stream. A prefill chunk, and every message
that goes out lossy, keeps the standalone sequence — `moe_gather` on the MoE connections,
`all_reduce` (whose size bands pick the 4-rank one-shot or two-shot, or ti8 on the lossy wire),
then `hc_write_bf16`. The unfused sequence is declared beside the fused one, so nothing is
unresolved at boot. The attention's own fusion is not a collective and does carry over: the sparse
decode with the output gate and the quantiser in its merge (`attn_paged_gate_quant`) has gqa-6,
page-4 rows. The per-step cost against tp2 on the same cards is unmeasured.
**Attention splits by KV head.** There are 2 KV heads of 256 rows; each rank declares
`n_head_kv 1` and reads one head's row span of `k_proj` and `v_proj`. At tp2 that is the ordinary
row shard. At tp4 the heads are replicated in rank pairs (ranks {0,1} carry KV head 0, {2,3} KV
head 1; both ranks of a pair hold identical KV weights, at no extra VRAM per rank). `n_head` is 12
per rank at tp2 and 6 at tp4, so tp4 resolves a different instantiation
(`attn_{prefill,decode}_h256_gqa6_bs4`, the QSA page of 4) than tp2's gqa12 pair. A world that
neither divides nor is a multiple of the KV head count (3, 5) runs attention on the largest
multiple below it and leaves the other ranks attention-zero; `docs/TP3.md` describes this and the
uneven delta-net head split.
**One collective does generalise, because it has to.** The lm_head is vocab-sharded, so the sampler
gathers the ranks' candidate sets rather than their logits (`core/sample/sampler.cpp`) and an
`all_gather` is on every step's sample path at any world size above one. libr4d shipped a two-rank
form only — one peer flag, a `1 - rank` peer index, a destination stride of `2 * row16` — so the
N-rank gather is a new kernel, not a fallback: at four ranks nothing but the reference
implementation resolves and the engine refuses to serve rather than run a naive gather. It is the
same one-shot push as the N-rank all-reduce with the reduction removed, and it moves the
(u32 id, f32 logit) pairs without ever adding them.
**Fused all-reduce forms at four ranks.** The fused forms are two-rank except on the exact wire:
`ar_hc_write_4rank` (the 4-rank one-shot with the gated-residual write as its epilogue) and
`ar_gather_hc_write_4rank` (the same with `moe_gather` as its prologue, taken by the MoE
connections when the step is one MoE pass). Both are declared over the rows of a decode or verify
step, `--max-num-seqs` x (1 + `--num-speculative-tokens`), and used whenever a step within that
bound sends its message exact: always with `--tp-wire exact`, and with `--tp-wire wht6` under
`--tp-wire-min-kb`. They run on an all-reduce instance keyed by that bound. A prefill chunk, and
every lossy message, uses the standalone sequence: `moe_gather`, `all_reduce` (4-rank one-shot or
two-shot by size, or ti8 on the lossy wire), then `hc_write_bf16`. The unfused sequence is
declared beside the fused one, so nothing is unresolved at boot. The sparse decode's fused output
gate and quantiser (`attn_paged_gate_quant`) has gqa-6, page-4 rows.
**Four-bit experts are what make it fit.** 512 experts of 640 over 48 layers is 112.8 GiB of expert
**Candidate gather.** The lm_head is vocab-sharded, so the sampler gathers the ranks' candidate
sets rather than their logits (`core/sample/sampler.cpp`), and every step at a world above one runs
an `all_gather`. libr4d serves it at 2 ranks (`r4d_ar_gather_2rank.hip`) and at 3, 4 and 8
(`r4d_ar_gather_Nrank.hip`, moving (u32 id, f32 logit) pairs without adding them). Where no device
row resolves, only libref's host gather does, and the serve is refused.
**Four-bit experts are what make it fit.** 512 experts of 640 over 48 layers is 112.5 GiB of expert
weight at E4M3 and twice that at bf16. `--weights-disk-tier` serves what fits neither VRAM nor the
host pool from the container file, but a routed expert is then read a layer at a time and a step is
paced by the drive. At four bits an expert unit is 2.42 MiB instead of 4.69 and the per-rank share
host pool from the container file, but then a routed expert is read a layer at a time and a step is
paced by the drive. At four bits an expert unit is 2.42 MiB instead of 4.69, and the per-rank share
fits VRAM plus a few GiB of pinned host. `docs/MOE-W4.md` is the format.
**PLE / the n-gram embedding is 51B of the model's 180B parameters** — a 320,001,536-row table of
160-dim embeddings, gathered 16 rows a token by a hash of the last three token ids, read once at
layer 1 and injected into the wide stream. Without it this is a 125B model missing a third of its
parameters.
**PLE, the n-gram embedding, is 51B of the model's 180B parameters**: a 320,001,536-row table of
160-dim embeddings, gathered 16 rows per token by a hash of the last three token ids, read once at
layer 1 and injected into the wide stream.
**QSA** picks the best `indexer_budget / indexer_compress_ratio` = 512 blocks of 4 tokens for each
query and attends to those alone. Below `indexer_budget + indexer_compress_ratio - 1` = 2051 tokens
of context every complete block is selected, so QSA is dense causal attention bit for bit — which is
why a prefill below the bound runs the cheaper dense attention, and is the property any change to it
is argued against. `docs/QSA.md` is the decomposition.
of context every complete block is selected and QSA equals dense causal attention bit for bit, so
a prefill below the bound runs the cheaper dense attention, and every change is tested against
that equality. `docs/QSA.md` is the decomposition.
The vision tower is declared when the container carries one and `--mm-max-patches` is not 0
(`arch/common/rad_block_vit.h`, `spec.md` §11).
---
# Two rules about measuring these
# Sample size
**A bisect knob is not a deployment knob.** Several switches here ablate a block or a layer range;
they produce a DIFFERENT MODEL and exist so that a wrong distribution can be attributed to a block
when nothing compares a whole layer against an oracle. A serve that sets one is a serve that is not
running the model, and the plugin says so at declare time. **Knobs are documented where they are
read** — a table of them in a document goes stale silently and ends up naming variables nothing
reads.
**THE SAMPLE SIZE IS PART OF THE RESULT.** Top-1 agreement between two numeric formats is one
Bernoulli trial per prompt, so at p ≈ 0.93 its standard error is 2.8 points at N = 80 and 2.0 at
N = 160 — wide enough that formats which differ by less than that rank in any order. Rank with a
graded statistic that has thousands of samples rather than hundreds (the mean |delta| over the
logits row, or the per-position KL of `radiance --kld-ref`), and confirm any ordering at N ≥ 160
before acting on it.
Top-1 agreement between two numeric formats is one Bernoulli trial per prompt, so at p ≈ 0.93 its
standard error is 2.8 points at N = 80 and 2.0 at N = 160: formats that differ by less than that
rank in any order. Rank with a graded statistic that has thousands of samples (the mean |delta|
over the logits row, or the per-position KL of `radiance --kld-ref`), and confirm any ordering at
N ≥ 160 before acting on it.
---
# `embeddinggemma2` — an embedding model
# `embeddinggemma2`: an embedding model
`arch/embgemma2` declares a POOLED output (`rad_declare_pooled`) and no logits, which makes the
`arch/embgemma2` declares a pooled output (`rad_declare_pooled`) and no logits, which makes the
program an embedding program: the engine runs it with no sampler and no KV cache, carries every
input whole in one step, and returns each sequence's pooled row on `/v1/embeddings`
([GUIDE §5.6](GUIDE.md)). One card (`--tp 1`).
@@ -425,39 +380,41 @@ audio Gemma 4's USM conformer: two stride-2 3 x 3 convolutions over (time, m
embedder -> 512; 4 frames (40 ms) a token, clips cut at 30 s
```
The traps:
Traps:
- **The embedding scale is the bf16 of sqrt(512)**, 22.625, because the reference stores it as a
bf16 buffer. sqrt(512) itself is off by one part in 800 on every embedding.
bf16 buffer. sqrt(512) itself is off by about 1e-4 relative on every embedding.
- **A media row replaces its placeholder's embedding before the per-layer inputs are projected.**
The per-layer input of an image token is computed from its image row, not from the placeholder
id's embedding.
- **The vision rotary is two independent neox rotaries**, one over each half of a head (`qk_norm_rope`
mode `blocks`). `rope` mode `axial` pairs across the halves and is a different function.
- **The vision pooler stores the mean in bf16 before scaling it by sqrt(768)** (`pool_rows`), and
the processor lays each 3 x 3 window's patches out consecutively so the pooler is a mean of nine
An image token's per-layer input is computed from its image row, not from the placeholder id's
embedding.
- **The vision rotary is two independent neox rotaries**, one over each half of a head
(`qk_norm_rope` mode `blocks`). `rope` mode `axial` pairs across the halves and is a different
function.
- **The vision pooler stores the mean in bf16 before scaling it by sqrt(768)** (`pool_rows`). The
processor lays each 3 x 3 window's patches out consecutively, so the pooler is a mean of nine
consecutive rows; attention and both position terms read each patch's own coordinates.
- **The audio subsampler masks its input to the clip's real frames before each convolution**: the
second convolution reads the first one's output at frame 2t's validity (`conv2d`'s `valid`
operand, stride 2), which zeroes the one row past the real ones that the zero padding alone
would not.
operand, stride 2), which zeroes the one row past the real ones that zero padding alone would
not.
- **The audio attention reaches 11 rows back, not 12.** The config says `attention_context_left`
13 and the chunked layout fetches 12 keys behind each block, but the mask transformers applies
keeps a key only when `0 <= q - k < context_left - 1`. Twelve back drifts a few percent a block
and leaves rows at cosine 0.6 by the last one.
13 and the chunked layout fetches 12 keys behind each block, but transformers' mask keeps a key
only when `0 <= q - k < context_left - 1`. Twelve back drifts a few percent per block and leaves
rows at cosine 0.6 by the last one.
- **An audio clip's tokens are ceil(real frames / 4)**, real frames being those whose last sample
is a real one; the processor stages exactly those plus zero frames to whole rows, which
reproduces every row the reference keeps.
is real; the processor stages exactly those plus zero frames to whole rows, which reproduces
every row the reference keeps.
---
# `gemma4` — Gemma 4 text, and its DFlash drafter
# `gemma4`: Gemma 4 text and its DFlash drafter
`arch/gemma4` serves a container converted from Google's bf16 checkpoint (`Gemma4ForConditionalGeneration`
or `Gemma4ForCausalLM`), the recipe choosing what is fp8: gemma-4-26B-A4B-it, and the dense sizes
without per-layer embeddings. The CT-INT4 31B release is `arch/gemma4_bf16`'s. A z-lab DFlash
drafter is merged at convert time (`--draft-model`); the recipes are
`data/recipes/gemma4-26b-a4b-df*.recipe`. The reference is transformers' `modeling_gemma4`.
`arch/gemma4` serves a container converted from Google's bf16 checkpoint
(`Gemma4ForConditionalGeneration` or `Gemma4ForCausalLM`), the recipe choosing what is fp8:
gemma-4-26B-A4B-it, and the dense sizes without per-layer embeddings. The CT-INT4 31B release is
`arch/gemma4_bf16`'s. A z-lab DFlash drafter is merged at convert time (`--draft-model`); the
recipes are `data/recipes/gemma4-26b-a4b-df*.recipe`. The reference is transformers'
`modeling_gemma4`.
```
gemma-4-26B-A4B-it
@@ -478,115 +435,111 @@ DFlash a small Qwen3-shaped block drafter: an anchor and block - 1 mask token
pass over the trunk's hidden states at target_layer_ids; drafts read off the TARGET's head
```
The readings that stay plausible when wrong:
Traps:
- **Proportional rope is not a partial rotary.** The full layers rotate the first 64 frequency
pairs of the 512-wide head at theta^(-2j/512) — the exponent divides by the HEAD — with pair j
channels (j, j + 256), and leave the other 192 pairs at frequency zero. `rope` with
`rotary_dim` 128 pairs (j, j + 64) at theta^(-2j/128): a different function that still produces
pairs of the 512-wide head at theta^(-2j/512) (the exponent divides by the head width), with pair
j at channels (j, j + 256), and leave the other 192 pairs at frequency zero. `rope` with
`rotary_dim` 128 pairs (j, j + 64) at theta^(-2j/128), a different function that still produces
fluent text. The plugin declares a full-width NeoX `rope` whose frequencies past pair 63 are
divided by 1e30 through the YaRN ramp `rope` already carries, a step at 63.5..64.
- **V on a full layer is the un-normed, un-rotated k projection**, RMS-normed with a unit gain, so
the value norm reads `k` before the key norm writes it.
- **The router does not read the feed-forward's input.** It reads the residual stream through a
gainless norm times its own `scale` vector times hidden^-0.5, while the experts read
pre_feedforward_layernorm_2's output. `per_expert_scale` multiplies the weight AFTER the
pre_feedforward_layernorm_2's output. `per_expert_scale` multiplies the weight after the
renormalised top-k.
- **The arms' two post-norms are per arm**, so under tensor parallel each arm's partial sum is
reduced before its norm. The partials share one [2T, hidden] buffer, dense rows first -- each
slice's own run of it when a prefill chunk is cut in two -- so one all-reduce carries both.
reduced before its norm. The partials share one [2T, hidden] buffer, dense rows first (each
slice's own run of it when a prefill chunk is cut in two), so one all-reduce carries both.
- **The embedding scale is sqrt(hidden) rounded to bf16**: 53.0, not 53.066. The drafter reads the
same scaled embedding.
- **The sliding layers' KV group is `RAD_KV_FULL`**, with the window on the attention op. A
`RAD_KV_WINDOW` group is not prefix-cached, so a hit on it reuses nothing and re-prefills; as
FULL the hit is kept. The planner gives every paged group the same block count, so the recycling
a window group would buy is worth nothing here.
`RAD_KV_WINDOW` group is not prefix-cached, so a hit on it reuses nothing and re-prefills. The
planner gives every paged group the same block count, so the recycling a window group would buy
is worth nothing here.
- **The drafter's sliding layers are causal and its full layer is not**, and its logits' softcap
is ignored on purpose: a draft is an argmax and the cap is strictly increasing.
**Tensor parallel.** Heads split by rank, o and down by column with an all-reduce, the vocabulary
by row. The full layers' two KV heads are replicated past two ranks. Routed experts are
expert-parallel, 128 / world whole experts a rank, because a 704-wide expert has no block-aligned
expert-parallel, 128 / world whole experts per rank, because a 704-wide expert has no block-aligned
width split; the router is replicated, so every rank agrees on the routing without a collective.
The drafter's head is vocab-sharded with the trunk's: each rank's top-2 are all-gathered and
`pair_argmax` picks the winner (two a rank, because a row-interleaved `all_gather` moves 16-byte
`pair_argmax` picks the winner (two per rank, because a row-interleaved `all_gather` moves 16-byte
words and one pair is 8 bytes).
**The prefill overlap.** At more than one rank, a prefill chunk of two routed passes or more (4096
tokens, at the 2048-token pass) runs as two slices, and the trunk's all-reduces ride the runtime's
second lane beside the other slice's compute: slice A's attention reduction runs under slice B's
output projection, slice B's under slice A's two arms, and so on through the layer. Attention runs
whole, since it reads every row's keys. The cut is a whole number of routed passes and both slices
are above every row band the sliced kernels have, so the step issues the same kernels over the
same rows and its output is the whole step's, bit for bit. On 4x R9700 the reductions were 47% of
a 20K-token prefill under `--profile-ops`; a model of the measured times puts the overlap at up to
a quarter off an unprofiled prefill. The per-op profile syncs every op, so it cannot show it --
time a prefill without `--profile-ops`. A step that runs whole -- every decode and verify step --
takes the second lane for the dense arm instead, beside the routed arm, which needs nothing of it
until the feed-forward join: at decode the dense arm's GEMMs are a few rows, latency-bound and far
from the bandwidth the experts take, and its reductions stay on lane 0. On two R9700s the sliced
prefill gives the whole chunk's text and logprobs exactly, at 2048- and 8192-token chunks; the
startup notes say which form each step takes.
**Prefill overlap.** At more than one rank on the exact wire, with every join fused, a prefill chunk
of two routed passes or more (4096 tokens at the 2048-token pass) runs as two slices, and the
trunk's all-reduces ride the runtime's second lane beside the other slice's compute (slice A's
attention reduction under slice B's output projection, and so on). Attention runs whole, since it
reads every row's keys. The slices issue the same kernels over the same rows, so the output equals
the whole step's bit for bit. On 4x R9700 the reductions are 47% of a 20K-token prefill under
`--profile-ops`, and the overlap is modelled at up to a quarter off; `--profile-ops` syncs every op
and cannot show it, so time a prefill without it. A step that runs whole (every decode and verify
step) puts the dense arm on the second lane instead, beside the routed arm, with its reductions on
lane 0. The startup notes say which form each step takes.
**The draft head in fp8.** The drafter's head is the widest read on the draft path: the target's
bf16 table, 352 MiB a rank at tp 4, every draft pass. A container converted with the line
bf16 table, 352 MiB per rank at tp 4, every draft pass. A container converted with the line
`dflash.draft_head.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16` (the three `-df` recipes
carry it) stores a block-fp8 copy of the table under that name, and the head reads the copy at
fp8a8 instead -- half the bytes, for 176 MiB a rank more. Drafts are verified, so the coarser
logits can change what is proposed and never what is accepted; `draft_n_accepted` says whether
they propose worse. A container without the copy reads the bf16 table as before, and the startup
note names which head is in use.
carry it) stores a block-fp8 copy under that name, and the head reads it at fp8a8 instead: half
the bytes, for 176 MiB per rank more. Drafts are verified, so the coarser logits can change what is
proposed, never what is accepted; `draft_n_accepted` shows whether they propose worse. Without the
copy the head reads the bf16 table, and the startup note names which head is in use.
**FP8 experts.** The experts are ~90% of the weight bytes, so each projection is served as the
container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up `[1408, 2816]`
is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not — the fp8 grouped GEMM reads K in
whole 128-column blocks — so it stays bf16 unless the checkpoint's experts were padded to 768 before
conversion (zero rows of gate and up, zero columns of down: exact). The fp8 tables are split by
expert parity, so a rank holds an even number of experts.
container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up
`[1408, 2816]` is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not (the fp8 grouped
GEMM reads K in whole 128-column blocks), so it stays bf16 unless the checkpoint's experts were
padded to 768 before conversion (zero rows of gate and up, zero columns of down: exact;
`gemma4-26b-a4b-df-pad768.recipe`). The fp8 tables are split by expert parity, so a rank holds an
even number of experts.
**Kernels.** libr4d serves all of the trunk's attention on its windowed kernels -- the sliding
layers (h256, gqa 2) and the full layers at gqa 8, 4 and 2 (one or two, four, eight ranks) --
plus `pair_argmax` and the fusions: the two sandwich-norm joins (`norm_add_norm`,
`join_add_scale`), `norm_add_norm_route` -- on a layer whose gate_up is block fp8, the attention
join writing the router's input and the experts' fp8 codes from the norm it already takes, in place
of an `rmsnorm` and an `rmsnorm_quant_fp8` -- `expert_scale`, and `attn_paged_qrow`, the sliding
layers' attention reading q where the fused qkv projection left it. The plugin declares each one's
unfused form where nothing serves it -- the rmsnorm / add chain, `embed_lookup` + `mul`, a `cast`
lifting q for `attn_paged` -- and the startup notes say which were taken. libref and libavx do not
declare these ops, so the plugin asks whether one is declared before it asks for it
(`rad_op_declared`), and a deployment without libr4d's device rows -- a CPU-only build, the host
backend -- runs the chains. On a card the fused joins and libr4d's chain differ by the order of
the chain's reductions, not bit for bit: the joins round as the host chain does (tests/r4d_emu).
The drafter's residual add, norm and fp8 quantiser of x are one libr4d `rmsnorm_quant_fp8` launch
an input (ten a draft pass), and the `add` / `rmsnorm` / `quant_act_fp8` chain where nothing serves
it. The sliding layers' attention stays on the windowed kernel because only it reads q in place:
plain `attn_paged` at h256/gqa2 -- the dense 31B's sliding layers -- takes libr4d's h256/gqa2
leg, which rad-kbench times at 0.26-0.71 of the windowed kernel at decode and 0.43-0.67 at
prefill. A drafter head sharded over more than one rank needs `pair_argmax` on the card.
**Kernels.** libr4d serves all of the trunk's attention on its windowed kernels (the sliding layers
at h256, gqa 2, and the full layers at gqa 8, 4 and 2 for one or two, four and eight ranks), plus
`pair_argmax` and the fusions:
**A drafter that is not working still writes fluent text.** Every draft is verified, so a broken
drafter costs speed and nothing else: judge it by `draft_n_accepted` (about a third of `draft_n` on
prose, at about two tokens a step), not by the reply. The trap that showed it: the buffer planner
takes liveness from DECLARATION order, so the tap copy into `dflash_src` is declared at the end of
the layer it taps, where it is issued. Declared once after the trunk, it let the planner share
`dflash_src` with `moe_edn`, which every MoE layer writes, whenever the sizes allowed it
(`--max-num-seqs 16` did): 2% acceptance, slower than no speculation, and nothing in the text to
say so. arch_test holds the two live ranges to overlap.
- the two sandwich-norm joins (`norm_add_norm`, `join_add_scale`);
- `norm_add_norm_route`: on a layer whose gate_up is block fp8, the attention join also writes the
router's input and the experts' fp8 codes from the norm it already takes, in place of an
`rmsnorm` and an `rmsnorm_quant_fp8`;
- `expert_scale`;
- `attn_paged_qrow`, the sliding layers' attention reading q where the fused qkv projection left it.
**Not declared.** The vision tower (`arch/embgemma2` declares Gemma 4's, for an encoder): a container
that carries one is served with `--mm-max-patches 0`. An fp8 attention or dense arm — under a tenth
of the weight bytes, and the dense arm's 2112 is not whole 128-blocks either.
Where nothing serves a fusion the plugin declares its unfused form (the rmsnorm / add chain,
`embed_lookup` + `mul`, a `cast` lifting q for `attn_paged`), and the startup notes say which were
taken. libref and libavx do not declare these ops, so the plugin checks `rad_op_declared` first,
and a deployment without libr4d's device rows (a CPU-only build, the host backend) runs the chains.
On a card the fused joins and libr4d's chain differ in reduction order, not bit for bit; the joins
round as the host chain does (`tests/r4d_emu`). The drafter's residual add, norm and fp8 quantiser
of x are one `rmsnorm_quant_fp8` launch per input (ten per draft pass), or the `add` / `rmsnorm` /
`quant_act_fp8` chain. The sliding layers' attention stays on the windowed kernel because only it
reads q in place; plain `attn_paged` at h256/gqa2 (the dense 31B's sliding layers) takes libr4d's
h256/gqa2 leg, which rad-kbench times at 0.26-0.71 of the windowed kernel at decode and 0.43-0.67
at prefill. A drafter head sharded over more than one rank needs `pair_argmax` on the card.
**A broken drafter still writes fluent text**, since every draft is verified; judge it by
`draft_n_accepted` (about a third of `draft_n` on prose, at about two tokens per step), not by the
reply. The buffer planner takes liveness from declaration order, so the tap copy into `dflash_src`
is declared at the end of the layer it taps, where it is issued. Declared after the trunk, it would
let the planner share `dflash_src` with `moe_edn`, which every MoE layer writes, and acceptance
would collapse silently. arch_test holds the two live ranges to overlap.
**Not declared.** The vision tower (`arch/gemma4_bf16` and `arch/embgemma2` declare Gemma 4's): a
container that carries one is served with `--mm-max-patches 0`. An fp8 attention or dense arm:
under a tenth of the weight bytes, and the dense arm's 2112 is not whole 128-blocks either.
---
# `qwenimage21` — Qwen-Image 2.1 and 2.1-Turbo, an image generator
# `qwenimage21`: Qwen-Image 2.1 and 2.1-Turbo, an image generator
`arch/qwenimage21` declares a GENERATOR (`rad_declare_generator`), which makes the program a
three-pass one the engine drives through `core/gen`: COND once a request (the text encoder over the
prompt and its pictures, then the DiT over that prefix into the KV cache), DENOISE once a step (the
image's latent rows against the cached prefix), DECODE once an image (the VAE). It is served on
`/v1/images/generations` and `/v1/images/edits` ([GUIDE §5.6](GUIDE.md)); fp8 on one or two cards,
bf16 on two. The checkpoint is the diffusers pipeline directory, read as one.
`arch/qwenimage21` declares a generator (`rad_declare_generator`), which makes the program a
three-pass one the engine drives through `core/gen`: COND once per request (the text encoder over
the prompt and its pictures, then the DiT over that prefix into the KV cache), DENOISE once per step
(the image's latent rows against the cached prefix), DECODE once per image (the VAE). It is served
on `/v1/images/generations` and `/v1/images/edits` ([GUIDE §5.6](GUIDE.md)); fp8 on one or two
cards, bf16 on two. The checkpoint is the diffusers pipeline directory, read as one.
```
text Qwen3-VL-8B-Instruct as released: 36 layers of 4096 (32 x 128, 8 kv heads), interleaved
@@ -607,28 +560,83 @@ schedule flow-matching Euler, exponential dynamic shift (0.5 at 256 tokens to 0
shift_terminal 0.02, 40 steps; Turbo: the 8 sigmas model_index.json lists, no guidance
```
The traps:
Traps:
- **The noise is radiance's, not torch's.** A seed is a Philox stream (`abi/rad_philox.h`), element
(k, c) of image row k drawn at k * 64 + c, identical on every card count. Parity against diffusers
means handing diffusers the same latents; a NumPy port of the stream does.
means handing diffusers the same latents; a NumPy port of the stream does that.
- **The conditioning is modulated at t = 0**, not at the step's timestep: the prefix is written once,
and a step that re-modulated it would differ from the reference at every step after the first.
- **The text encoder's output skips the final norm.** Taking the normed output scales every row by
the norm's gain and leaves a picture that is plausible and wrong.
and re-modulating it would differ from the reference at every step after the first.
- **The text encoder's output skips the final norm.** The normed output scales every row by the
norm's gain and gives a plausible, wrong picture.
- **A reference picture is read twice**: by the VAE as RGBA in [-1, 1], and by the vision tower
composited on white, both after PIL's premultiplied Lanczos resize to the 1024x1024 area at its
own aspect, sides rounded to 32. A different resampler changes every token the picture becomes.
- **The Euler step rounds where diffusers does**: x' = bf16(x + bf16(bf16(sigma_next - sigma) * v)),
and guidance bf16(neg + bf16(cfg * bf16(pos - neg))). Unrounded is not more accurate here; it is a
different trajectory.
and guidance bf16(neg + bf16(cfg * bf16(pos - neg))). Unrounded is a different trajectory, not a
more accurate one.
- **The VAE config's `temperal_downsample` is a boolean array**; a reader that drops booleans makes
every level look unscaled.
- **Alpha off the decoder is never exactly 255** (243..255 on an opaque picture). Reading it as
transparency makes every picture the model made a transparent one when it is edited again; the
server's cutoff is alpha 128, the mask's.
- **Alpha off the decoder is never exactly 255** (243..255 on an opaque picture). Read as
transparency, it makes every picture the model made transparent when edited again; the server's
cutoff is alpha 128, the mask's.
Measured against diffusers' own pipeline in bf16, from the same latents (1024x1024, 20 steps, PSNR):
bf16 TP2 33.9 dB for a prompt and 42.2 for an edit, where diffusers differs from itself by 32.6 to
34.4 dB across its own attention kernels; fp8 28.7 to 29.3 and 37.6 to 38.4; Turbo fp8 33.4 and
38.9 at its 8 steps.
Against diffusers' own pipeline in bf16, from the same latents (1024x1024, 20 steps, PSNR): bf16
TP2 33.9 dB for a prompt and 42.2 for an edit, where diffusers differs from itself by 32.6 to 34.4
dB across its own attention kernels; fp8 28.7 to 29.3 and 37.6 to 38.4; Turbo fp8 33.4 and 38.9 at
its 8 steps.
---
# `qwen3asr`: speech to text
`model_type: qwen3_asr` (`Qwen3ASRForConditionalGeneration`), served from the checkpoint as it
ships: Qwen3-ASR 1.7B is a Whisper-style audio encoder, a two-layer projector and a dense Qwen3-1.7B
decoder, all bf16. The reference is transformers' `modeling_qwen3_asr` with its
`Qwen3ASRFeatureExtractor`, which core/mm reproduces (`AudioFamily::Qwen3ASR`).
```
features Whisper log-mel, 128 bins: n_fft 400, hop 160, torch.stft centred with reflected padding,
power spectra, the last frame dropped (n samples -> n / 160 frames), Slaney mel bank and
area norm, log10 floored at the clip's maximum less 8, then (x + 4) / 4; a clip under
8000 samples zero-padded to 8000 first
encoder each second (100 frames) convolved on its own: 3 x Conv2d 3x3 / stride 2 / pad 1, 480
channels, exact gelu, over [mel, time] -> 16 mel x 13 rows a second; 7680 -> 1024 linear
(no bias); sinusoidal positions 0..12 added to every second's rows; 24 pre-LayerNorm
layers, d_model 1024, 16 heads of 64, biased q/k/v/o and FFN 4096 with exact gelu,
bidirectional in blocks of 104 rows (8 s) from the clip's start; LayerNorm
projector 1024 -> 1024, gelu, 1024 -> 2048
decoder 28 layers, hidden 2048, 16 heads over 8 KV heads of 128 (GQA 2), per-head q/k RMS norms,
NeoX rope over the whole head at theta 1e6, SwiGLU 6144, RMS eps 1e-6, vocab 151936,
lm_head tied to the embedding
prompt <|im_start|>system\n{context}<|im_end|>\n<|im_start|>user\n<|audio_start|> pads
<|audio_end|><|im_end|>\n<|im_start|>assistant\n[language English<asr_text>]
```
Traps (each loads and transcribes plausibly when wrong):
- **A second's convolution must not see the next second.** The reference pads every second to 100
frames and convolves the batch; one convolution over the clip with no seam reads one second's
frames into the next's. core/mm stages a whole second as 104 frames whose last four the encoder
reads as zero (`conv2d`'s `valid`, at strides 1, 2 and 4), and the last, shorter second as 8 x
the rows the reference keeps of it, so the rows the tower writes are the rows the reference
keeps and nothing is compacted. The zero frames inside the last second's window are real input
(the reference's padding) and are read: its last kept row depends on them.
- **The kernels are [mel, time]**, so PyTorch's weight is `[cout, cin, mel, time]` with time last,
where `conv2d` convolves (time, width). `t_last` reads it as stored; reading it the other way is a
transposed kernel, which still produces text.
- **The 7680 -> 1024 linear takes channel-major features** (`c * 16 + f`) where the convolution
writes frequency-major ones. Declared as a 1 x 16 convolution over frequency, its weight is
PyTorch's `[1024, 480, 1, 16]`; declared as a GEMM, it would need a permutation the name map has
no form for.
- **Positions restart every second** (`seg_sinusoid`, period 13) and **attention runs in blocks of
104 rows**, the last one short (`attn_dense`'s `block`). Positions counted over the whole clip,
or attention over all of it, is a different model that still writes text.
- **The decoder's positions are the tokens' indices**: plain Qwen3, no M-RoPE; the audio
placeholders count up like text.
A pass carries 30 s (3120 staged frames); `/v1/audio/transcriptions` cuts longer recordings into
clips at their pauses (docs/GUIDE.md §5.14). Against transformers on LibriSpeech test-clean and
test-other clips, the encoder's rows are within 1.1-1.3% relative L2 of the bf16 reference's; on
the one clip where they differed by 5%, the reference itself was 5.3% from a float32 run of the
same model and this engine 0.8%. The transcripts match word for word.
+67 -63
View File
@@ -1,9 +1,10 @@
# Radiance in a container
The repository builds into one Docker image that holds the engine, its plugins, its tools and the
recipes, and nothing else: it is assembled from scratch out of the install tree and exactly the
shared libraries that tree loads. The host needs Docker, an AMD GPU and an `amdgpu` kernel driver
that supports ROCm 10.1. It does not need ROCm itself, a compiler, or ffmpeg.
recipes. It is assembled from scratch out of the install tree, exactly the shared libraries that
tree loads, a static busybox, and `curl`, `jq` and a CA bundle for `hfget.sh`. The host needs
Docker, an AMD GPU and an `amdgpu` kernel driver that supports ROCm 10.1. It does not need ROCm, a
compiler or FFmpeg.
The image is published as [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance),
with its kernels built for `gfx1201`: `docker pull stilldeadcode/radiance`. Build it yourself for
@@ -11,10 +12,10 @@ other cards or another commit. The examples below use `radiance`, the tag a loca
the published image, write `stilldeadcode/radiance` instead.
Besides radiance (Apache-2.0, `/opt/radiance/share/doc/radiance/`), the image holds glibc,
libstdc++, the ROCm runtime, FFmpeg, busybox and a few other libraries, each under its own license,
GPL and LGPL among them. `/usr/share/doc/THIRD-PARTY` in the image lists every one with its exact
version, its license files and where its source is; `docker/licenses.sh` writes it during the build
and stops the build if a file in the image cannot be traced to a package.
libstdc++, the ROCm runtime, FFmpeg, busybox, curl, jq and a few other libraries, each under its own
license, GPL and LGPL among them. `/usr/share/doc/THIRD-PARTY` in the image lists each one with its
version, its license files and its source. `docker/licenses.sh` writes it during the build and fails
the build if a file in the image cannot be traced to a package.
## Build the image
@@ -27,37 +28,37 @@ docker/build.sh -r <commit> # any other commit
docker/build.sh --target build # stop at a stage, tagged radiance-<stage>
```
The context the script sends is `git archive` of the commit, so the image holds exactly what is
committed: no build directory, no uncommitted edit, no model file. It builds with BuildKit
(`docker buildx`), which runs independent stages side by side and caches each one; with `-s` only
the remote machine needs buildx.
The build context is `git archive` of the commit, so the image holds only what is committed: no
build directory, no uncommitted edit, no model file. It builds with BuildKit (`docker buildx`), which
runs independent stages in parallel and caches each one; with `-s` only the remote machine needs
buildx.
The `Dockerfile` has these stages:
The `Dockerfile` stages:
| stage | what it does |
|---|---|
| `ffmpeg` | FFmpeg 8.1 with only the demuxers `core/mm/media.cpp` admits and the decoders their streams carry (still images, H.264, HEVC, VP8, VP9, AV1 through dav1d, MPEG-1/2/4, Theora, FLV/H.263). The distribution's build brings about 200 packages of encoders, filters and display libraries the engine never calls |
| `llvm` | ROCm's `libLLVM` rebuilt from ROCm's own llvm-project, at the exact commit the image's `clang --version` names, with `docker/llvm-vopd-pairing.patch` applied and configured as ROCm ships it. ROCm 10.1's clang does not compile the same source to the same code twice (its VOPD pairing follows heap addresses); the patch makes it repeatable. The library is the only file of the compiler that changes |
| `build` | `rocm/dev-ubuntu-24.04:10.1.0-full` plus cmake, ninja and g++-14. Every device source is compiled by ROCm's clang from `/opt/rocm-repeatable`, a shadow of the ROCm tree whose `libLLVM` is the `llvm` stage's (`-DRAD_HIP_VOPD_REPEATABLE=ON`, `--rocm-path=/opt/rocm`); the HIP runtime and comgr in the image stay ROCm's own. Configures with the kernels compiled for `GPU_TARGETS`, builds, and installs to `/opt/radiance`. Device code is not stored compressed: the engine's AQL backend reads the fat binaries itself and refuses a compressed bundle |
| `test` | `docker/llvm-check.sh`, then `ctest -LE gpu`: every suite that runs without a card. The check recompiles one kernel file four ways -- with pairing off the image's compiler must emit ROCm's device code byte for byte, with pairing on three compiles must agree. The image is only produced if both pass |
| `rootfs` | The install tree, stripped, plus every shared library its binaries and plugins load (resolved by `ldd`, glibc and the ROCm runtime included) in one directory the loader searches by default, and a static busybox. ROCm's `libdrm_amdgpu` carries the card name table compiled in, so no `amdgpu.ids` is needed. Every ELF file is then resolved from inside a chroot of the tree, so the build fails on a library the image lacks |
| `ffmpeg` | FFmpeg 8.1 with only the demuxers `core/mm/media.cpp` admits, the decoders their streams carry (still images, H.264, HEVC, VP8, VP9, AV1 through dav1d, MPEG-1/2/4, Theora, FLV/H.263, and audio) and the three encoders the images API writes (PNG, JPEG, WebP). The distribution's build brings about 200 packages the engine never uses |
| `llvm` | ROCm's `libLLVM` rebuilt from ROCm's llvm-project at the commit the image's `clang --version` names, configured as ROCm ships it, with `docker/llvm-vopd-pairing.patch` applied. ROCm 10.1's clang does not compile the same source to the same code twice (its VOPD pairing follows heap addresses); the patch makes it repeatable. This library is the only compiler file that changes |
| `build` | `rocm/dev-ubuntu-24.04:10.1.0-full` plus cmake, ninja and g++-14. Device code is compiled by ROCm's clang from `/opt/rocm-repeatable`, a shadow of the ROCm tree whose `libLLVM` is the `llvm` stage's (`-DRAD_HIP_VOPD_REPEATABLE=ON`, `--rocm-path=/opt/rocm`); the HIP runtime and comgr in the image are ROCm's own. Configures with kernels for `GPU_TARGETS`, builds, and installs to `/opt/radiance` with the recipes. Device code is not stored compressed: the engine's AQL backend reads the fat binaries itself and refuses a compressed bundle |
| `test` | `docker/llvm-check.sh`, then `ctest -LE 'gpu\|oot'`: every suite that runs without a card. The check recompiles one kernel file four ways: with pairing off, the image's compiler must emit ROCm's device code byte for byte; with pairing on, two compiles must match the build's own object. The image is produced only if both pass |
| `rootfs` | The stripped install tree, every shared library its binaries and plugins load (resolved by `ldd`, glibc and the ROCm runtime included) in one directory the loader searches by default, a static busybox, and `curl`, `jq` and the CA bundle. ROCm's `libdrm_amdgpu` has the card name table compiled in, so no `amdgpu.ids` is needed. Every ELF file is then resolved from inside a chroot of the tree, so the build fails on a library the image lacks |
| `runtime` | `FROM scratch` and the rootfs. This is the image that ships |
The largest files are the LLVM and Clang libraries comgr loads (about 130 MB and 90 MB), which the
HIP runtime cannot initialise a device without. There is no distribution in the shipped image: no
package manager and no shell beyond busybox (`docker exec -it <name> sh`). JPEG XL input is refused
by name, since its decoder needs libjxl.
The largest files are the LLVM and Clang libraries comgr loads (about 130 MB and 90 MB), without
which the HIP runtime cannot initialise a device. The shipped image has no distribution: no package
manager and no shell beyond busybox (`docker exec -it <name> sh`). JPEG XL input is refused by name,
since its decoder needs libjxl.
A build container has no card to enumerate, so the GPU architecture must be named. A bare-metal
`./build.sh` detects it instead. `libr4d` builds for gfx12 targets only; any other target in the
list just gets no RDNA4 kernels.
A build container has no card to enumerate, so the GPU architecture must be named; a bare-metal
`./build.sh` detects it. `libr4d` builds for gfx12 targets only; any other target in the list gets
no RDNA4 kernels.
The ROCm version in the image has to be one the host's kernel driver supports. It is a build
argument (`ROCM_VERSION`, default `10.1.0-full`; from ROCm 10 on, the development image is published
only with the `-full` suffix).
The ROCm version in the image must be one the host's kernel driver supports. It is a build argument
(`ROCM_VERSION`, default `10.1.0-full`; from ROCm 10 on, the development image is published only
with the `-full` suffix).
The GPU suites (`mem_test`, `r4d_selftest`, `kbench`) need the card to themselves. They run from
the `build` stage:
The GPU suites (`mem_test`, `r4d_selftest`, `kbench`, `kbench_moe`) need the card to themselves.
They run from the `build` stage:
```sh
docker/build.sh --target build
@@ -67,14 +68,14 @@ docker run --rm --device /dev/kfd --device /dev/dri --security-opt seccomp=uncon
## Run it
The entrypoint is `radiance`. Every other tool (`rad-convert`, `rad-info`, `rad-kbench`,
`rad-tune`, `rad-schemas`, `rad-tokcheck`) is on `PATH`, and the recipes are in
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
`/opt/radiance/share/radiance/recipes/`.
```sh
docker run --rm -v /srv/models/rad:/models:ro --entrypoint rad-info radiance /models/m.rad
docker run -d --name radiance --network host --init \
docker run -d --name radiance --network host --init --ulimit memlock=-1 \
--device /dev/kfd --device /dev/dri --security-opt seccomp=unconfined \
--group-add "$(getent group render | cut -d: -f3)" \
--group-add "$(getent group video | cut -d: -f3)" \
@@ -82,28 +83,28 @@ docker run -d --name radiance --network host --init \
radiance --model /models/m.rad --tp 2 --host :: --port 8000
```
Every one of these options is needed:
The options:
- **`--device /dev/kfd --device /dev/dri`**, plus the `render` and `video` groups, give the
container the GPUs.
- **`--security-opt seccomp=unconfined`**: Docker's default seccomp profile refuses io_uring.
Qwen3.8-Flash-Next's n-gram embedding table is read from the container through io_uring, so
without this the model cannot serve. The profile also refuses the NUMA binding calls the ROCm
runtime makes for host memory.
- **`--init`**: the engine is not PID 1. It finishes its step and releases the cards on SIGTERM.
- **`--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 past Docker's default memlock limit -- and without the limit raised
`auto` reads it 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.
- **`--network host`**: the server binds the host's addresses directly, IPv4 and IPv6, with no
NAT in front of it.
- `--device /dev/kfd --device /dev/dri`, with the `render` and `video` groups, give the container
the GPUs.
- `--security-opt seccomp=unconfined`: Docker's default seccomp profile refuses io_uring and the
NUMA binding calls the ROCm runtime makes for host memory. Qwen3.8-Flash-Next's n-gram embedding
table is read from the container through io_uring, so without this the model cannot serve.
- `--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
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.
- `--network host`: the server binds the host's addresses directly, IPv4 and IPv6, with no NAT in
front of it.
The image sets `GPU_MAX_ALLOC_PERCENT=100` and `GPU_MAX_HEAP_SIZE=100`. The HIP runtime's defaults
cap one allocation, and the heap, below what the placement plan hands out.
The image sets `GPU_MAX_ALLOC_PERCENT=100` and `GPU_MAX_HEAP_SIZE=100`, because the HIP runtime's
defaults cap one allocation, and the heap, below what the placement plan hands out.
**A plugin of your own** — a kernel library for another card, an architecture, a quantiser — is
mounted and put first on the search path; nothing in the image changes:
A plugin of your own (a kernel library for another card, an architecture, a quantiser) is mounted
and put first on the search path; nothing in the image changes:
```sh
docker run ... -v /srv/radiance-plugins:/plugins:ro \
@@ -122,30 +123,31 @@ the cards the engine runs on.
| 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; idle sessions kept in host memory and on disk |
| `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 |
| `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-paro.yaml` | `qwen3.8-27b-paro-int4.rad` | Qwen3.8-27B ParoQuant int4 (learned rotations) with its DFlash2 drafter and vision tower; the int5 and MXFP4 containers serve from it too |
| `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 |
| `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 |
| `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 |
| `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`) |
The container names are the files the README's model table downloads or converts.
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, and the user and GPU
groups the server runs as. The models directory has to 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, the extents it stored compressed are read through the page cache instead, which
works but loses what the direct reads are for; a container copied into a directory set `chattr +C`
is stored uncompressed. Then:
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
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
@@ -153,6 +155,8 @@ docker compose -f flashnext.yaml logs -f # follow the log
docker compose -f flashnext.yaml down # stop
```
Each model takes both cards and the same port, 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`.
Every model listens on the same port and most take both cards (`flashnext-tp1.yaml`,
`qwen3.8-27b-paro.yaml` and `embeddinggemma2.yaml` take one), 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`.
+1226 -1042
View File
File diff suppressed because it is too large. Load diff
+46 -43
View File
@@ -1,22 +1,21 @@
# Radiance — implementation brief
# Radiance: implementation brief
Read `spec.md` first; it is the design and it is binding. This file is the mechanical part: who
owns what, how it builds, and the conventions that keep ten people's code looking like one
person's.
`spec.md` is the design and it is binding; read it first. This file covers the mechanical part:
where things live, how they build, and the conventions every component follows.
## The host backend is the primary target, not a fallback
## The host backend is a primary target
Everything except the device kernels builds, tests and runs through the **host device backend**:
Everything except the device kernels builds, tests and runs through the host device backend:
`cmake` with no ROCm must configure, build, test and run, and `RAD_HIP_FOUND` gates only the HIP
backend and the device kernels. A machine with no card is a complete development environment for
the core, the tools, the architecture plugins and `libref`, and the suite runs in full there.
## Layout and ownership
## Layout
```
abi/ THE ABI, and all a plugin compiles against. Frozen — do not edit quietly
abi/ the ABI, and all a plugin compiles against. Frozen: change it deliberately
core/rad_internal.h shared internals: logging, Geometry, constraint matching
core/util/ logging, error strings, dtype arithmetic, tensor helpers: the bedrock
core/util/ logging, error strings, dtype arithmetic, tensor helpers
core/device/ device backends: host, and aql (HSA queues the engine writes; HIP for memory)
core/plugin/ plugin loader, kernel registry, op schemas, selector, bucket tables
core/build/ the declare phase: builder, weight manifest, buffer plan, graph dump
@@ -24,33 +23,38 @@ core/runtime/ the run phase: RadCtx, rad_issue, the arena
core/mem/ pools, slab, KV block manager, prefix cache
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
core/sample/ device sampler dispatch, the host reference chain, grammar bitmask
core/text/ tokeniser, chat template, tool parsing, detokenisation
core/mm/ image and video decoding, and the processor that turns frames into patches
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/engine* the thing that ties them together, and `radiance` the binary
libref/ every op, naively, correct, host domain: the fallback and the oracle
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
libavx/ the same vocabulary in x86 SIMD, host domain: the production host kernels,
built on every x86-64 build because an op placed on the host cannot run on libref
built on every x86-64 build because the engine refuses to serve an op that
resolves only to libref (without --debug-accept-reference-kernels)
libquant/ the built-in quantisers rad-convert's recipes name: grids, transforms, rtn, gptq
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
cmake/ rad_add_plugin, and the package config an out-of-tree plugin find_package()s
scripts/ shell harnesses for serving, tracing and profiling a running engine
scripts/ harnesses for serving, tracing and profiling a running engine
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, patched not edited
vendor/ llama.cpp lifts tracked to an upstream commit (vendor/UPSTREAM), changed only
through vendor/patches/; nlohmann/json and cpp-httplib
tests/ ctest
```
Each directory has its own `CMakeLists.txt` and each owner writes only inside their own. The
top-level file already exists; add `add_subdirectory` lines there only if your directory is new.
Each directory has its own `CMakeLists.txt` and builds only what is inside it. A new top-level
directory adds its `add_subdirectory` line to the root `CMakeLists.txt`; `arch/CMakeLists.txt`
adds every architecture directory itself.
## Build
@@ -60,15 +64,16 @@ cmake --build build -j
ctest --test-dir build --output-on-failure
```
Your directory must compile and its tests must pass **before you report done**. A component that
does not build is not a component.
A change is done when its directory compiles and its tests pass.
## Conventions
**No Python in the engine, its tools, its build or its test suite.** This is the project's
founding constraint — `spec.md` opens with it. Tests are C++ and CTest. The one Python file under
`tests/`, `mkgolden.py`, is run by hand against transformers to regenerate the reference numbers in
`tests/mm_golden.h`; nothing in the build or the suite calls it.
**No Python in the engine, its tools, its build or its test suite.** `spec.md` opens with this
constraint. Tests are C++ and CTest. The Python files in the tree are run by hand and nothing in
the build or the suite calls them: `tests/mkgolden.py` and `tests/mklfm2golden.py` regenerate the
reference numbers in `tests/mm_golden.h` and `tests/lfm2_golden.h` from transformers;
`tools/pad_tp.py` and `tools/pad_verify.py` pad a checkpoint for a tensor-parallel width and check
the result; `scripts/cardclock.py` monitors card clocks.
**C ABI at plugin boundaries, C++20 inside.** `abi/` is C and must stay compilable as C.
Everything under `core/` is C++20 and may use the standard library freely.
@@ -76,32 +81,30 @@ Everything under `core/` is C++20 and may use the standard library freely.
**Errors are values.** Return `RAD_OK` or a negative `RAD_E_*`. Do not throw across a function
that a plugin or the run phase can call. `fatal()` is for broken invariants only.
**Nothing unimplemented returns success.** A function you have not written yet returns
`RAD_E_UNSUPPORTED` and logs once at Warn with its own name. A stub that returns 0 is how a
project ends with fluent wrong output and no way to bisect it (`spec.md` §17).
**Nothing unimplemented returns success.** An unwritten function returns `RAD_E_UNSUPPORTED` and
logs once at Warn with its own name. A stub that returns 0 produces fluent wrong output with no way
to bisect it (`spec.md` §17).
**No allocation and no synchronisation on the step path.** The arena is sized at declare. If you
find yourself wanting a `malloc` inside `rad_arch_step` or inside the scheduler's per-step work,
that is a declare-phase bug.
**No allocation and no synchronisation on the step path.** The arena is sized at declare. A
`malloc` needed inside `rad_arch_step` or the scheduler's per-step work is a declare-phase bug.
**`rad_memset_async` refuses `RAD_MEM_HOST` on a card, and the host backend cannot reproduce that.**
**`rad_memset_async` refuses `RAD_MEM_HOST` on a card; the host backend cannot reproduce that.**
`RAD_MEM_HOST` is pageable memory the GPU has never been shown, so the device backend returns
`RAD_E_UNSUPPORTED` naming the rule (`core/device/aql.cpp`). On the host backend every kind of
memory is the same memory, so a memset added to a path that runs on host memory passes in a no-ROCm
build and fails on a card. Use `RAD_MEM_HOST_PINNED` or `RAD_MEM_HOST_MAPPED`, or memset on the
host. `rad_memcpy_async` accepts pageable memory but bounces it through pinned memory and WAITS,
so a pageable copy on the step path is a host stall; `aql_pageable_bytes()` counts them.
`RAD_E_UNSUPPORTED` naming the rule (`core/device/aql.cpp`). On the host backend all memory kinds
are the same memory, so a memset on host memory passes in a no-ROCm build and fails on a card. Use
`RAD_MEM_HOST_PINNED` or `RAD_MEM_HOST_MAPPED`, or memset on the host. `rad_memcpy_async` accepts
pageable memory but bounces it through pinned memory and waits, so a pageable copy on the step path
is a host stall; `aql_pageable_bytes()` counts them.
**Kernel plugins launch with `hipLaunchKernel` and the engine dispatches them.** On a card every
stream is an HSA queue the engine owns and writes AQL packets into itself (`core/device/aql.cpp`);
the executable defines `hipLaunchKernel` and HIP's kernel registration hooks, so a plugin built by
hipcc needs nothing special. What a plugin must NOT do with an engine stream is call any other HIP
stream API: `hipEventRecord` and `hipStreamWaitEvent` are refused by name, and anything else would
be handed to HIP as a stream HIP does not own. Use `rad_event_*` and `rad_memcpy_async`.
stream is an HSA queue the engine owns and writes AQL packets into (`core/device/aql.cpp`). The
executable defines `hipLaunchKernel` and HIP's kernel registration hooks, so a plugin built by
hipcc needs nothing special. A plugin must not call any other HIP stream API on an engine stream:
`hipEventRecord` and `hipStreamWaitEvent` are refused by name, and anything else would hand HIP a
stream it does not own. Use `rad_event_*` and `rad_memcpy_async`.
**Comments explain the decision, not the syntax.** The spec's voice: say why this and not the
obvious alternative, and name the cost when there is one. `libr4d/r4d_rows.cpp` is the model.
Do not write `// increment i`.
**Comments explain the decision, not the syntax.** Say why this and not the obvious alternative,
and name the cost when there is one. `libr4d/r4d_rows.cpp` is the model.
**Naming.** `rad_` prefix on everything with external linkage. Files are named for what they
provide. `snake_case` for functions and variables, `PascalCase` for types.
+4135 -1603
View File
File diff suppressed because it is too large. Load diff
+248 -261
View File
@@ -1,25 +1,27 @@
# The four-bit MoE expert format
Qwen3.8-Flash-Next has 512 experts of 640 over 48 layers. At E4M3 that is **112.8 GiB of expert
weight** against two 32 GB cards. Splitting the experts over the two ranks halves the per-rank
share and the placement planner still refuses 26 GiB. A routed weight can be served from the file
tier (`--weights-disk-tier`), but it is then read a layer at a time and a step is paced by the
drive. Pinned host memory does not close it either on a host with 64 GB of RAM (2 x 34.78 GiB).
So four bits is not an optimisation here. It is what lets the model run from VRAM and host memory:
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.
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
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.
## What is served
Qwen3.8-Flash-Next is served as `w4nl64-i8lm.rad`, built by
`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe` with `CALIB=<dir>` naming the calibration Grams
(below, "Calibration"): the routed experts at `w4nl64a8h` (the w4nl codebook below, an E4M3 scale
a row and group of 64, GPTQ and three sweeps of coordinate descent), ten protected experts bf16,
and the trunk's block linears and the lm_head **int8, served W8A8** -- `gemm_i8a8_nt_m16` /
`gemm_i8a8_tiled` and `logits_gemm_i8` (docs/OPS.md), every quantising producer writing the int8
codes its consumer reads, so an int8 trunk adds no quantiser launch. How each step moved the model, by the engine's KL mode against the
bf16 model over the same 83K positions (docs/TOOLS.md, "The KL mode"):
`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe` with `CALIB=<dir>` naming the calibration Grams (see
"Calibration"):
- routed experts at `w4nl64a8h`: the w4nl codebook, an E4M3 scale per row and group of 64, GPTQ
and three sweeps of coordinate descent;
- ten protected experts bf16;
- the trunk's block linears and the lm_head int8, served W8A8 (`gemm_i8a8_nt_m16` /
`gemm_i8a8_tiled` and `logits_gemm_i8`, `docs/OPS.md`). Every quantising producer writes the int8
codes its consumer reads, so an int8 trunk adds no quantiser launch.
Each row below adds one change to the row above, measured with the engine's KL mode against the
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 |
|---|---|---|---|---|
@@ -27,23 +29,22 @@ bf16 model over the same 83K positions (docs/TOOLS.md, "The KL mode"):
| `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% |
| **+ E4M3 scales a 64, coordinate descent (`w4nl64a8h`) -- served** | **0.0789** | **92.85%** | **0.0239** | **94.57%** |
| + every down projection at five bits (`w5nl64a8h`) -- not served | 0.0717 | 93.34% | 0.0204 | 95.10% |
| **+ E4M3 scales per 64, coordinate descent (`w4nl64a8h`): served** | **0.0789** | **92.85%** | **0.0239** | **94.57%** |
| + every down projection at five bits (`w5nl64a8h`): not served | 0.0717 | 93.34% | 0.0204 | 95.10% |
| a second bf16 implementation (the floor) | 0.0399 | 95.13% | 0.0111 | 96.44% |
The served container's tail: median 0.0037, p99 1.65, p99.9 5.33. **The floor is not zero and is
most of the overall mean**: the tool-documentation system prompts in the corpus are numerically
chaotic, and two bf16 implementations already disagree there at KL 0.142 -- so text and assistant
turns are the slice comparable with other quantisers' published numbers, and the overall mean of
~0.04 is the floor itself rather than a target a quantised model can reach.
most of the overall mean**: the corpus's tool-documentation system prompts are numerically chaotic,
and two bf16 implementations already disagree there at KL 0.142. Text and assistant turns are
therefore the slice comparable with other quantisers' published numbers.
What it costs, two cards, production flags, against `w4nla8h` with the same trunk: decode
15.28 -> 15.32 ms a step (+0.3%), a 26K-token prefill 6539 -> 6442 tokens a second (-1.5%). The
five-bit down projections cost decode +4% and prefill **-19%**: the experts are 8% larger, fewer of
them fit beside the KV cache (137.5 resident a layer against 149), and a prefill streams the rest.
Cost on two cards with production flags, against `w4nla8h` with the same trunk: decode 15.28 ->
15.32 ms per step (+0.3%), a 26K-token prefill 6539 -> 6442 tokens per second (-1.5%). Five-bit
down projections cost decode +4% and prefill -19%: the experts are 8% larger, fewer fit beside the
KV cache (137.5 resident per layer against 149), and a prefill streams the rest.
**Where the rest of the loss is.** Emulated with the experts of some layers left bf16 and the rest
as served (an HF reference with the container's quantisers, which matches the engine to 0.001):
**Where the remaining loss is.** Emulated with some layers' experts left bf16 and the rest as
served (an HF reference with the container's quantisers, matching the engine to 0.001):
| | all: mean KL | all: top-1 | text + assistant | system / user |
|---|---|---|---|---|
@@ -51,31 +52,35 @@ as served (an HF reference with the container's quantisers, which matches the en
| every down projection bf16 | 0.0700 | 93.61% | 0.0203 | 0.2456 |
| layers 16-31 bf16 | 0.0631 | 93.51% | 0.0226 | 0.2064 |
Both are a third of the experts' bytes. Five-bit down projections already take ~80% of what bf16
down projections would; layers 16-31 hold more of the overall mean -- almost all of it on the
chaotic system and user turns -- and text and assistant turns are most sensitive in layers 24-39.
Round-to-nearest experts in one group of eight layers at a time, the rest bf16, put the excess
over the floor at .012, .017, .031, .026, .020 and .009 for layers 0-7 through 40-47.
Both are a third of the experts' bytes. Five-bit down projections already recover ~80% of what bf16
down projections would. Layers 16-31 hold more of the overall mean, almost all of it on the chaotic
system and user turns; text and assistant turns are most sensitive in layers 24-39. With
round-to-nearest experts in one group of eight layers at a time and the rest bf16, the excess over
the floor is .012, .017, .031, .026, .020 and .009 for layers 0-7 through 40-47.
**What did not pay**, measured: GPTQ's act order (no change once the
weight is rotated), its dampening at 0.003 and 0.03 (within 0.4%), a codebook of the layer's own
(Lloyd's fit is the same in every layer) or one refitted at groups of 64 or for the E4M3 grid
(worse), a power-of-two sub-scale a 32 under the 64-wide scale (0.0679 -> 0.0675),
a 256-word two-dimensional codebook a pair of weights (10% less error than the scalar table, for an
LDS lookup a byte), more protected bf16 experts (+4% bytes for 7% less error), and E4M3 scales a 32
(13% less error energy for +13-18% on the expert GEMMs).
Tried without benefit:
**Further quality levers**, in order: five bits on both projections of layers
16-31 (the same +8% as the down projections, ~0.066 expected), and fewer layers at five bits for a
smaller prefill cost. The formats, the kernel and a layer's own choice of form are all in the tree.
- GPTQ's act order (no change once the weight is rotated); its dampening at 0.003 and 0.03 (within
0.4%);
- a codebook per layer (Lloyd's fit is the same in every layer), or one refitted at groups of 64 or
for the E4M3 grid (worse);
- a power-of-two sub-scale per 32 under the 64-wide scale (0.0679 -> 0.0675);
- a 256-word two-dimensional codebook per pair of weights (10% less error than the scalar table,
for an LDS lookup per byte);
- more protected bf16 experts (+4% bytes for 7% less error);
- E4M3 scales per 32 (13% less error energy for +13-18% on the expert GEMMs).
Remaining levers: five bits on both projections of layers 16-31 (+8% bytes, like the down
projections, ~0.066 expected), or fewer layers at five bits for a smaller prefill cost. The
formats, the kernel and per-layer form selection are all implemented.
## The stored plane
Row-major packed nibbles, two's complement `-8..7`, with a **bf16 scale per (row, group of 128
along K)** -- not the fp8 path's 128x128 tile scale, which would spend all sixteen levels on the
largest row in a block. The kernel is `moe_gemm_w4a8` (libr4d), which is the fp8 kernel with the
LDS staging and the scale fold changed: the integers `-8..7` are exact in E4M3, so a code expands
losslessly and the existing fp8 WMMA loop is untouched.
along K)**, not the fp8 path's 128x128 tile scale, which would spend all sixteen levels on the
largest row in a block. The kernel is libr4d's `moe_gemm_w4a8`: the fp8 kernel with the LDS staging
and the scale fold changed. The integers `-8..7` are exact in E4M3, so a code expands losslessly
and the fp8 WMMA loop is unchanged.
The encodings are **not interchangeable**:
@@ -84,55 +89,48 @@ The encodings are **not interchangeable**:
| `i4*bf16[1x128]` | `w4a8` | int4 codes, a bf16 scale per row and group of 128 along K |
| `i4*bf16[1x128]/fwht128` | `w4a8h` | the same, with a 128-wide Walsh-Hadamard along K applied before quantising |
| `affine:codes=u4[1x1],scale=bf16[1x128],table=f32{1x16}/fwht128` | `w4nla8h` | the rotated plane with the codes indexing the `w4nl` codebook (below) |
| `affine:codes=u4[1x1],scale=fp8_e4m3[1x64],scale.1=f32[*x*],table=f32{1x16}/fwht128` | `w4nl64a8h` | the codebook with an E4M3 scale a row and group of **64**, under one fixed f32 (below) -- the same bytes |
| `affine:codes=u4[1x1],scale=fp8_e4m3[1x32],scale.1=f32[*x*],table=f32{1x16}/fwht128` | `w4nl32a8h` | the same at a group of **32**, +0.125 bits a weight |
| `affine:codes=u5[1x1],scale=fp8_e4m3[1x64],scale.1=f32[*x*],table=f32{1x32}/fwht128` | `w5nl64a8h` | `w4nl64a8h` with **five-bit** codes into the 32-level `w5nl` codebook (below), +1 bit a weight |
| `affine:codes=u4[1x1],scale=fp8_e4m3[1x64],scale.1=f32[*x*],table=f32{1x16}/fwht128` | `w4nl64a8h` | the codebook with an E4M3 scale per row and group of **64**, under one fixed f32 (below); the same bytes |
| `affine:codes=u4[1x1],scale=fp8_e4m3[1x32],scale.1=f32[*x*],table=f32{1x16}/fwht128` | `w4nl32a8h` | the same at a group of **32**, +0.125 bits per weight |
| `affine:codes=u5[1x1],scale=fp8_e4m3[1x64],scale.1=f32[*x*],table=f32{1x32}/fwht128` | `w5nl64a8h` | `w4nl64a8h` with **five-bit** codes into the 32-level `w5nl` codebook (below), +1 bit per weight |
The first two have the same planes, extents and byte count and differ only in the transform; the
container says which encoding each expert has. The architecture plugin asks for the first expert's encoding (`rad_weight_encoding`) and
declares the matching kernels, and a kernel that does not read an encoding is not a candidate for
it -- a rotated container cannot be served unrotated. libr4d reorders each row's nibbles into the
order its unpack reads when the experts load; the container holds them in the canonical order. The
activation side is `had_quant_act_fp8` / `gated_had_quant_fp8`, which are the ordinary fp8
quantisers with `r4d_fwht_wave<128>` between the load and the absmax -- free, because that
kernel's mapping (one wave a 128-column group, four consecutive columns a lane) is already the
transform's.
The first two differ only in the transform. The plugin reads the first expert's encoding
(`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.
**The residual factor is not split.** `H` is symmetric, so `<Hw, Ha> = 128 <w, a>`, and the whole
factor of 128 is folded into the **stored weight scale** by the quantiser (`bf16(amax/7) / 128`). The
int8 rotated ops fold `1/sqrt(group)` into each side; these fold nothing at runtime. That the fold
goes entirely into the stored scale rather than being split is normative in `docs/OPS.md`
(*Quantisation and rotation*, the `group` parameter under the `had_*` FP8 forms), which is also
where the cost of splitting it is stated.
**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.
## The w4nl codebook
A Hadamard-rotated expert weight is close to normal, and sixteen evenly spaced levels are not the
best sixteen for a normal value: the outer levels are rarely used and the inner ones are too far
apart. `w4nla8h` keeps everything about the rotated plane -- the bytes a code, the bf16 scale a row
and group of 128, the rotation, the activation quantiser, the GEMM -- and changes only what a code
stands for:
A Hadamard-rotated expert weight is close to normal, for which evenly spaced levels are a poor
choice: the outer ones are rarely used and the inner ones too far apart. `w4nla8h` keeps everything
about the rotated plane (bytes per code, scale grid, rotation, activation quantiser, GEMM) and
changes only what a code stands for:
codes 0..7 1.125 3.25 5.5 8 11 14 18 22
codes 8..15 the same, negated
Lloyd's quantiser fitted to the rotated, amax-normalised experts of Qwen3.8-Flash-Next gives the
same levels in every layer and both projections once each is rounded to E4M3, and every one is
exact in E4M3 -- so the kernel expands a code to the byte the fp8 WMMA reads with no rounding, as
it does `-8..7`. The decode is the same three byte permutes with another four dwords in them: the
table is a kernel argument (`r4d_args.h`, `kW4IntPerm` / `kW4nlPerm`), so both formats are one
code path and the same fifteen VALU per eight weights.
Lloyd's quantiser on the rotated, amax-normalised experts of Qwen3.8-Flash-Next gives these levels
in every layer and both projections once rounded to E4M3, and each is exact in E4M3, so a code
expands to the fp8 WMMA's byte without rounding. The table is a kernel argument (`r4d_args.h`,
`kW4IntPerm` / `kW4nlPerm`), so both formats share one code path: three byte permutes, fifteen VALU
per eight weights.
In libquant it is the named codebook `table=w4nl`, which a recipe pairs with `rule=search` (each
group's scale searched for least error, from 0.70 to 1.10 of amax / 22 and each candidate's
least-squares refit) and `gptq`. **An encoding cannot say what its table holds**, so the codes view
selects the `table` plane beside the codes, and the relayout compares it with the kernel's value
for value before it serves a byte: a container quantised against any other table of the same shape
is refused at load.
group's scale searched over 0.70 to 1.10 of amax / 22, plus each candidate's least-squares refit)
and `gptq`. **An encoding cannot say what its table holds**, so the codes view selects the `table`
plane beside the codes, and the relayout compares it value for value with the kernel's: a container
quantised against any other table of the same shape is refused at load.
Measured as held-out output error (`sqrt(tr(dW H dW^T) / tr(W H W^T))`, the layer's pooled gate_up
Gram and each expert's own down Gram, 6 experts in each of 7 layers), at the same 4.125 bits a
weight:
Held-out output error (`sqrt(tr(dW H dW^T) / tr(W H W^T))`, the layer's pooled gate_up Gram and
each expert's own down Gram, 6 experts in each of 7 layers), at 4.125 bits per weight:
| | gate_up | down |
|---|---|---|
@@ -142,121 +140,112 @@ weight:
| `-8..7` + GPTQ | 0.0629 | 0.0832 |
| `w4nl` + GPTQ | **0.0547** | **0.0720** |
`-8..7` at amax/7, what `w4a8h` containers were converted with, is a further ~10% worse than the
first row. Halving the group to 64 at bf16 scales (+3% of the expert bytes) does less than the
codebook does for nothing -- and at E4M3 scales it costs nothing at all (below).
`-8..7` at amax/7, the scale `w4a8h` containers use, is ~10% worse than the first row. Halving the
group to 64 at bf16 scales (+3% of the expert bytes) does less than the codebook does for free, and
at E4M3 scales it costs no bytes (below).
## Finer groups at the same bytes: E4M3 scales under a fixed 2^-13
## E4M3 scales under a fixed 2^-13
A bf16 scale a 128 is sixteen bits a 128; an E4M3 scale a 64 is the same sixteen. What an E4M3
scale lacks is range, and the experts do not need it: with the rotation's 1/128 folded in, the
scales of Qwen3.8-Flash-Next's routed experts at a 64 sit between 2^-15 and 2^-10.6 (every 37th
expert of eight layers), so under one fixed factor of **2^-13** each is a normal E4M3 value with
four binades to spare either side -- and E4M3's three mantissa bits are the same in every binade,
so a per-row second level would buy range nobody uses and no precision. The factor is libr4d's
`kW4G64Scale`; a container states it as libquant's fixed second level (`scale2=f32 block2=*x*
scale2_value=0.0001220703125`), and the scale view's relayout compares it with the kernel's before
it serves a byte, as the codes view does the table. libquant searches each group's scale **as
stored**: once the second level is known the first is searched again over the E4M3 values it can
take, or the rounding gives back most of what the search won.
A bf16 scale per 128 and an E4M3 scale per 64 both cost sixteen bits per 128 weights. E4M3 lacks
range, which the experts do not need: with the rotation's 1/128 folded in, the per-64 scales of
Qwen3.8-Flash-Next's routed experts sit between 2^-15 and 2^-10.6 (every 37th expert of eight
layers), so under one fixed factor of **2^-13** each is a normal E4M3 value with four binades to
spare either side. E4M3 has three mantissa bits in every binade, so a per-row second level would
add only unused range. The factor is libr4d's `kW4G64Scale`; a container states it as libquant's
fixed second level (`scale2=f32 block2=*x* scale2_value=0.0001220703125`), and the scale view's
relayout checks it against the kernel's. libquant searches each group's scale **as stored**: once
the second level is known, the first is searched again over its E4M3 values, or rounding gives back
most of what the search won.
The kernel stages a 128-wide tile's E4M3 scales as one 16- or 32-bit load, sums each scale group's
WMMA in its own accumulator -- folding a group as it ends would make the next group's WMMA wait on
its results -- and folds them together at the end of the tile. Held-out output error, GPTQ + `w4nl`
(layer 20 and 28's experts):
The kernel loads a 128-wide tile's E4M3 scales in one 16- or 32-bit load and sums each scale
group's WMMA in its own accumulator, folding them at the end of the tile (folding a group as it
ends would stall the next group's WMMA). Held-out output error, GPTQ + `w4nl` (layers 20 and 28):
| | gate_up | down | bits a weight |
| | gate_up | down | bits per weight |
|---|---|---|---|
| bf16 a 128 (`w4nla8h`) | 0.0683 / 0.0708 | 0.0842 / 0.0957 | 4.125 |
| E4M3 a 64 under 2^-13 (`w4nl64a8h`) | 0.0655 / 0.0679 | 0.0807 / 0.0917 | 4.125 |
| E4M3 a 32 under 2^-13 (`w4nl32a8h`) | -- / 0.0632 | -- / 0.0850 | 4.25 |
| bf16 per 128 (`w4nla8h`) | 0.0683 / 0.0708 | 0.0842 / 0.0957 | 4.125 |
| E4M3 per 64 under 2^-13 (`w4nl64a8h`) | 0.0655 / 0.0679 | 0.0807 / 0.0917 | 4.125 |
| E4M3 per 32 under 2^-13 (`w4nl32a8h`) | -- / 0.0632 | -- / 0.0850 | 4.25 |
and three sweeps of coordinate descent after GPTQ (libquant `cd=3`) take another ~2% off either.
What the finer groups cost in the GEMM, against `w4nla8h` at a decode step's 4 tokens and a
2048-token chunk: `w4nl64a8h` +4% / +2% and +7% / +4% (gate_up / down); `w4nl32a8h` +13% / +15%
and +18% / +11% -- the 32-wide form is for the layers that need it, not the model.
Three sweeps of coordinate descent after GPTQ (libquant `cd=3`) take another ~2% off either. GEMM
cost against `w4nla8h`, at a decode step's 4 tokens and a 2048-token chunk (gate_up / down):
`w4nl64a8h` +4% / +2% and +7% / +4%; `w4nl32a8h` +13% / +15% and +18% / +11%. The 32-wide form is
for the layers that need it, not the whole model.
## Five bits where the error is: w5nl64a8h
## Five-bit codes: w5nl64a8h
The 64-wide form at one more bit a weight. libquant's `table=w5nl` is Lloyd's quantiser with
sixteen magnitudes, fitted to the rotated experts at groups of 64 as `w4nl` was -- the same to
three places in every layer and both projections -- and rounded to E4M3 at the top level (30) that
leaves the sixteen distinct and moves them least: 0.8125, 2.5, 4, 5.5, 7.5, 9, 11, 12, 14, 16, 18,
20, 22, 24, 26, 30, then their negatives. The order makes a code's high bit its sign, so the
kernel expands the low four bits exactly as a `w4nl` code -- out of the sixteen magnitudes -- and
sets each byte's sign from a bit plane stored after the row's nibbles. That plane is a dword a 32
elements, transposed so that a shift by m puts the signs of the expansion's output dword m on
E4M3's sign bits at once: two VALU per four weights.
The 64-wide form at one more bit per weight. libquant's `table=w5nl` is Lloyd's quantiser with
sixteen magnitudes, fitted to the rotated experts at groups of 64 as `w4nl` was (the same to three
places in every layer and both projections), and rounded to E4M3 at the top level (30) that keeps
the sixteen distinct and moves them least: 0.8125, 2.5, 4, 5.5, 7.5, 9, 11, 12, 14, 16, 18, 20, 22,
24, 26, 30, then their negatives. A code's high bit is its sign, so the kernel expands the low four
bits exactly as a `w4nl` code (from the sixteen magnitudes) and sets each byte's sign from a bit
plane stored after the row's nibbles. That plane is a dword per 32 elements, transposed so that a
shift by m puts the signs of the expansion's output dword m on E4M3's sign bits at once: two VALU
per four weights.
Held-out output error under the production quantiser (GPTQ, an E4M3 scale a 64 under 2^-13, three
sweeps of coordinate descent), layers 20 and 28:
Held-out output error under the production quantiser (GPTQ, an E4M3 scale per 64 under 2^-13,
three sweeps of coordinate descent), layers 20 and 28:
| | gate_up | down |
|---|---|---|
| `w4nl64a8h` | 0.0638 | 0.0943 |
| `w5nl64a8h` | 0.0335 | 0.0501 |
-- 72% less error energy for 25% more expert bytes on whatever it is applied to. In the GEMM
against `w4nl64a8h`, at a 2048-token chunk: +19% gate_up, +8% down, most of it the extra bytes
streamed. At a decode step the projection reads 25% more from DRAM. (`r4d_selftest --perfmoe` at a
decode step's 4 tokens times one routing again and again, so its experts sit in the 64 MB last-level
cache: there the five-bit gate_up falls out of it and reads 3x slower, which a served decode step,
reading ~3 GB of experts, never sees.)
That is 72% less error energy for 25% more expert bytes wherever it is applied. In the GEMM
against `w4nl64a8h` at a 2048-token chunk: +19% gate_up, +8% down, mostly the extra bytes. At a
decode step the projection reads 25% more from DRAM. (`r4d_selftest --perfmoe` at a decode step's
4 tokens repeats one routing, so its experts sit in the 64 MB last-level cache; there the five-bit
gate_up falls out of it and reads 3x slower, which a served decode step, reading ~3 GB of experts,
never sees.)
Every down projection at five bits (`data/recipes/qwen4exp-w5dn64-i8-hc8m.recipe`) is measured in
"What is served" above: 0.0717 / 93.34% against 0.0789 / 92.85%, for -19% prefill.
Every down projection at five bits (`data/recipes/qwen4exp-w5dn64-i8-hc8m.recipe`) is in the table
under "What is served": 0.0717 / 93.34% against 0.0789 / 92.85%, for -19% prefill.
**WHERE IT GOES IS A PER-PROJECTION, PER-LAYER CHOICE.** The codebook forms at E4M3 scales --
`w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h` -- share the rotated input, the scale views and the
**The form is chosen per projection and per layer.** The codebook forms at E4M3 scales
(`w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h`) share the rotated input, the scale views and the
accumulators and differ only in the GEMM's dtype, so a recipe may put any projection of any layer
in any of them, and the MoE block takes each layer's two from that layer's own experts.
in any of them, and the MoE block reads each layer's two forms from that layer's experts.
## Rotation alone is expected to be worse
## Rotation without GPTQ
A rotation fixes **range**, and a group-128 absmax already handles range. Measured on the 27B,
Hadamard was **2x worse** for RTN int4, and e4m3 activations went 0.02024 -> 0.02254 KL under one.
The rotation is here because it is the substrate an error-feedback packer needs underneath it --
the pair is what gets measured, not this half: a recipe asks for `transform=fwht128` together with
`gptq`, not on its own.
A rotation fixes range, and a group-128 absmax already handles range. On the 27B, Hadamard was 2x
worse for RTN int4, and e4m3 activations went 0.02024 -> 0.02254 KL under one. The rotation is here
as the basis an error-feedback packer quantises in, so a recipe asks for `transform=fwht128`
together with `gptq`, not on its own.
## Calibration, and why it is a separate run
## Calibration
GPTQ needs `H = sum over tokens of x x^T` for the layer's real input. That needs the model
**running**, and a container has to be written before it can be served. So the order is a
bootstrap:
GPTQ needs `H = sum over tokens of x x^T` for the layer's real input, which needs the model
running, and a container must exist before it can be served. One route is a bootstrap:
1. **convert with plain absmax** -- the experts quantised by `rtn`
2. **serve that** with `RADIANCE_CALIB_DIR` set, and push a corpus through prefill
3. **convert again**, the experts quantised by `gptq calib=<dir>`
1. **convert with plain absmax**: the experts quantised by `rtn`;
2. **serve that** with `RADIANCE_CALIB_DIR` set, and push a corpus through prefill;
3. **convert again**, the experts quantised by `gptq calib=<dir>`.
The production recipe takes the second route below instead: its Grams are recorded from the bf16
checkpoint.
A second moment is robust to the small perturbation the first container's error puts on the
activation, which is what makes step 2 valid.
A second moment is robust to the small perturbation the first container's own error puts on the
activation, which is what makes step 2 legitimate.
**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
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
state. That records ~930 tokens per second, ten million tokens in three hours.
**Or calibrate the checkpoint as it ships, with no bootstrap at all.** Converted without a recipe,
Flash-Next is a 335 GiB bf16 container, and `--weights-disk-tier` serves it at two cards by reading
each routed layer's non-resident experts from the container a pass at a time (GUIDE.md §4.3). Its
tap reads the bf16 activation the bf16 experts multiply -- no upstream layer quantised -- and writes
its Hessians in the model's own domain; a rotated recipe's GPTQ reads them rotated into its own.
Whole experts per rank, which a calibration run wants anyway. A step reads about 100 GiB a rank from
the drive and grows only slowly with what it carries -- 50 s at ~32K tokens, 59 s at ~55K -- so
drive it with large prefill steps: `--max-num-batched-tokens 65536 --max-num-seqs 64`, about 96
requests in flight, with a KV pool that holds 64 sequences' recurrent state. That records ~930 tokens a second, ten million tokens in three hours.
**The corpus must look like the traffic.** A few thousand tokens of one repeated sentence gives a
Gram with its energy in a handful of directions, and GPTQ hides its error in the directions the
corpus never excites. Score on Hessians from a held-out slice of the corpus, never on the ones the
weight was fitted to.
**The corpus is what the Hessian is of, so it has to look like the traffic.** A few thousand
tokens of one repeated sentence gives a Gram whose energy sits in a handful of directions, and GPTQ
then hides its error in the directions the corpus never excites -- an in-sample number that says
nothing. Score on Hessians from a held-out slice of the corpus, never on the ones the weight was
fitted to.
**A million tokens is enough for the tap's Hessians; the held-out slice wants more.** The tap pools
a layer's Gram over every expert, and on Flash-Next one recorded from 10M tokens beat one from 1M by
under 1% on 1.8M held-out tokens (GPTQ on gate_up, layers 0-47), with no change on down or under
AutoRound. What the larger corpus does fix is the scoring: the gap between in-sample and held-out
error drops from up to 3% to under 1% on gate_up, and a 113K-token held-out slice put layer 47's
down GPTQ at 0.49x RTN where 1.8M tokens say 0.60x.
**A million tokens is enough for the tap's Hessians; scoring wants more.** On Flash-Next a pooled
Gram from 10M tokens beat one from 1M by under 1% on 1.8M held-out tokens (GPTQ on gate_up, layers
0-47), with no change on down or under AutoRound. The larger held-out slice matters for scoring:
the in-sample/held-out gap drops from up to 3% to under 1% on gate_up, and a 113K-token slice put
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
@@ -276,124 +265,122 @@ CALIB=<calib dir> rad-convert <checkpoint> -o model-gptq.rad \
--quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB'
```
`--reuse` in step 3 copies every weight whose encoding, quantiser and options did not change -- all
but the experts -- from the first container. **The format is a property of the container**: each
`--reuse` in step 3 copies every weight whose encoding, quantiser and options did not change (all
but the experts) from the first container. **The format is a property of the container**: each
expert's encoding is in its entry, the plugin reads it from there, and the recipe that made it is
in the header (`rad-info --recipe`), `calib=` included, so a reader can tell an error-feedback
plane from a plain absmax one.
in the header (`rad-info --recipe`), `calib=` included, so an error-feedback plane can be told from
a plain absmax one.
The files are `gram.r<rank>.<weight stem>.bin`: a 32-byte `RADGRAM2` header (`k`, `rank`, `rows`, `domain`)
then `k*k` f32. `domain` is what the tap summed: 0 for the model's own activation, 128 for the
rotated one a `w4a8h` container's kernel multiplies; libquant brings every file into the domain the
recipe's grid quantises in before summing them, so a bf16 model's Hessians serve a rotated recipe.
**Named after the weight they will pack, minus the expert index**, because that is
the whole protocol between the engine and the quantiser -- `gptq` is given a directory and a weight
name, and strips `.<e>.weight` to find its file. A name of the tap's own
would have made the quantiser carry a per-architecture table.
The files are `gram.r<rank>.<weight stem>.bin`: a 32-byte `RADGRAM2` header (`k`, `rank`, `rows`,
`domain`), then `k*k` f32. `domain` is what the tap summed: 0 for the model's own activation, 128
for the rotated one a `w4a8h` container's kernel multiplies. libquant brings every file into the
domain the recipe's grid quantises in before summing, so a bf16 model's Hessians serve a rotated
recipe. **Files are named after the weight they will pack, minus the expert index**: that is the
whole protocol between the engine and the quantiser. `gptq` is given a directory and a weight name
and strips `.<e>.weight` to find its file, so it needs no per-architecture table.
**`down` gets a Hessian an expert.** A routed expert's `down` input is its own intermediate units,
so channel `i` of one expert has nothing to do with channel `i` of another, and a Gram pooled over a
layer's experts describes none of them: on Flash-Next a typical expert's own profile has a median
cosine of 0.15-0.87 with the pool, and in the last layers the pool *is* one expert. The tap also
sums each local expert's rows into its own Gram -- the same `gram_accum` once an expert over its run
of the sorted rows, into a layer-sized scratch that comes back to the host every pass (640^2 f32 for
256 experts a rank is 10 GB a rank as packed triangles) -- and writes
`gram.r<rank>.blk.L.ffn_down_exps.<e>.bin` beside the pooled file. libquant reads an expert's own
file when it holds at least 4K rows and the layer's otherwise. Fitted to its own Gram, a Flash-Next
expert's down projection comes out 20-55% below round-to-nearest on its own held-out Gram, where the
pooled Gram bought 0-10%; the super experts gain most (layer 47's expert 399: 0.204 rounded, 0.137
pooled, 0.065 own). Under ~2K rows the own fit fits its rows and can lose to rounding, which is why
the threshold: below it sit 0.6% of the routed rows. The per-layer sync it costs roughly
halves a disk-tier recording's throughput, which is why the per-expert sets are recorded from a
million tokens.
**`down` gets a Hessian per expert.** A routed expert's `down` input is its own intermediate units,
so channel `i` means something different in each expert and a Gram pooled over the layer describes
none of them: on Flash-Next a typical expert's own profile has a median cosine of 0.15-0.87 with
the pool, and in the last layers the pool is one expert. The tap also sums each local expert's rows
into its own Gram (`gram_accum` once per expert over its run of the sorted rows, into a
layer-sized scratch copied to the host every pass; 640^2 f32 for 256 experts per rank is 10 GB per
rank over 48 layers as packed triangles) and writes `gram.r<rank>.blk.L.ffn_down_exps.<e>.bin`
beside the pooled file. libquant reads an expert's own file when the ranks' files together hold at
least 4 x K rows (2560 for a 640-wide `down`), and the layer's otherwise, saying so on stderr.
Fitted to its own Gram, a Flash-Next expert's down projection comes out 20-55% below
round-to-nearest on its own held-out Gram, where the pooled Gram bought 0-10%; super experts gain
most (layer 47's expert 399: 0.204 rounded, 0.137 pooled, 0.065 own). Under ~2K rows the own fit
overfits and can lose to rounding, hence the threshold; 0.6% of the routed rows fall below it. The
per-layer sync roughly halves a disk-tier recording's throughput, so the per-expert sets are
recorded from a million tokens.
Three things about the tap worth knowing before reading its numbers:
About the tap's numbers:
- **The gate_up tap is the unsorted activation and loses nothing.** Every token is routed to
exactly `top_k` experts, so the gathered distribution IS the token distribution times `top_k`,
and GPTQ is invariant to a positive scale on H. `top_k` times cheaper for the same matrix.
- **It taps the quantiser's output, not the bf16 before it.** The Hessian wanted is of the operand
the expert GEMM actually contracts -- and under `w4a8h` that is the only form the activation has.
- **Per rank, and the quantiser sums.** Under expert parallelism a rank's `down` input is only the
tokens routed to its own experts. Its gate_up input is the whole token set on every rank, so
summing those double-counts by `world` -- a positive scale, harmless. One rule beats two.
- **The gate_up tap is the unsorted activation and loses nothing.** Every token is routed to exactly
`top_k` experts, so the gathered distribution is the token distribution times `top_k`, and GPTQ is
invariant to a positive scale on H. It is `top_k` times cheaper for the same matrix.
- **It taps the quantiser's output, not the bf16 before it**, because the Hessian wanted is of the
operand the expert GEMM contracts; under `w4a8h` that is the only form the activation has.
- **Files are per rank, and the quantiser sums them.** Under expert parallelism a rank's `down`
input is only the tokens routed to its own experts. Its gate_up input is the whole token set on
every rank, so summing double-counts by `world`, a positive scale that does not matter.
## Protected experts
**A few experts carry a large share of a layer's output, and those are kept plain bf16.** In
Flash-Next's last layers one expert's `down` input holds a sixth of the layer's energy from a third
of a percent of its routing, nearly all of it in one channel (layer 47, expert 445). Four bits cost
it the same *relative* error as any expert -- about 12% of its output under its own profile -- but its
it the same relative error as any expert (about 12% of its output under its own profile), but its
output is that much larger, so the absolute error is too. unsloth's GGUFs upcast the whole layer's
`down` for this (a GGUF type is per tensor, and a tensor is all 512 experts); a container keeps an
expert's encoding per expert, so here only those experts are kept, at ~7 MB each.
encoding per expert, so here only those experts are kept, at about 7 MB each over their four-bit
size.
A recipe names them with a rule ahead of the expert rule, `blk.47.ffn_*_exps.445.weight cast
dtype=bf16`, and the layer serves them apart: the sort places them last (`moe_scatter`'s `protect`),
the four-bit GEMMs serve the other experts, and a bf16 `moe_gemm` pair serves the trailing run of the
offsets, writing the routed rows the four-bit `down` GEMM left zero. Their weights are the layer's
static weights, not expert slots -- a container's experts in a layer are one fixed-size unit each --
so they are always resident and the file tier never reads them. Where every rank holds a slice of
every expert, it holds an even slice of these too -- 320 of the 640 intermediate units at two ranks,
since a bf16 expert has no scale blocks to respect -- and the block's all-reduce sums the partials.
The count must keep the rest even, because the four-bit GEMM takes them as two equal tables by parity.
A recipe names them with a rule ahead of the expert rule,
`blk.47.ffn_*_exps.445.weight cast dtype=bf16`, and the layer serves them apart: the sort places
them last (`moe_scatter`'s `protect`), the four-bit GEMMs serve the other experts, and a bf16
`moe_gemm` pair serves the trailing run of the offsets, writing the routed rows the four-bit `down`
GEMM left zero. Their weights are the layer's static weights, not expert slots (a container's
experts in a layer are one fixed-size unit each), so they are always resident and the file tier
never reads them. Where every rank holds a slice of every expert it holds an even slice of these
too (320 of the 640 intermediate units at two ranks; a bf16 expert has no scale blocks to respect),
and the block's all-reduce sums the partials. The count must leave the rest even, because the
four-bit GEMM takes them as two equal tables by parity.
## The quantiser
`gptq` in libquant (`libquant/lq_gptq.{h,cpp}`), over any grid `rtn` takes. H is damped by 1% of its mean diagonal, inverted, and re-factorised
into the upper triangle `U` with `U^T U = H^-1`; then columns are quantised left to right and each
column's rounding error is pushed into the columns to its right, weighted by `U`. Blocked 128
columns at a time so `U` is streamed once rather than once per row, and parallel over rows because
the recursion is independent in the row index.
`gptq` in libquant (`libquant/lq_gptq.{h,cpp}`), over any grid `rtn` takes. H is damped by 1% of its
mean diagonal, inverted, and re-factorised into the upper triangle `U` with `U^T U = H^-1`; columns
are then quantised left to right and each column's rounding error is pushed into the columns to
its right, weighted by `U`. It works in blocks of 128 columns so `U` is streamed once rather than
once per row, and in parallel over rows, since the recursion is independent in the row index.
**The scale grid is fixed from the weight before any code is chosen** -- the "static groups"
variant. The scales are then exactly the ones `rtn` writes for the same weight, which
`tests/relayout_parity_test.cpp` checks, and the grid does not depend on the order the columns are
visited in.
**The scale grid is fixed from the weight before any code is chosen** (the "static groups"
variant). The scales are then exactly the ones `rtn` writes for the same weight, which
`tests/relayout_parity_test.cpp` checks, and the grid does not depend on column order.
**Cost.** Budget tens of minutes of extra convert time for a 48-layer container, and ~1.3 GB of
factor cache held for its duration. The quantiser is OpenMP-parallel over rows, so the wall time
falls with core count; the cache is a property of the model, not of the machine. The factorisation
is per layer and projection, not per expert: 512 experts share one factor.
factor cache for its duration. The quantiser is OpenMP-parallel over rows, so wall time falls with
core count. A layer's pooled factor is shared by all 512 experts of that projection; a `down`
projection fitted to its own Gram factors per expert, in parallel and uncached.
**A weight with no calibration file is packed the uncalibrated way and says so on stderr** -- so a
typo'd directory is a message, not a silent quality regression.
**A weight with no calibration file is packed the uncalibrated way and says so on stderr**, so a
mistyped directory is a message, not a silent quality loss.
## What is measured
## Tests
- `r4d_selftest --case moe_gemm_w4a8` -- the kernel against an independent host decode of the same
- `r4d_selftest --case moe_gemm_w4a8`: the kernel against an independent host decode of the same
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
- `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.
- `quant_test` -- **GPTQ against the objective it minimises**. The metric is
`||X (W - W')^T||^2 = sum over rows of e H e^T` and *not* rel_l2 on the weight: error feedback
makes the weight worse in the plain sense, deliberately. 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,
which is 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 the `w4nl` codes as their
table entries. 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`) on a source
with outlier channels; 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
- `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
2^-13 refused, a 32-entry table other than `w5nl` refused, and each refusing the others'
encodings. `r4d_selftest --case moe_gemm_w4a8` also checks `w5nl64a8h`'s arranged row bit for
bit against the statement in r4d_layout.cpp, and its inverse. `moe_gemm_q_mod4`'s four classes
are held to `moe_gemm_q`'s stored bytes in every format, and for both ops what the op oracle
reads through the inverse -- codes as their levels, an E4M3 scale times its second level -- is
held to the quantiser's planes.
- `r4d_selftest --case gram_accum` -- the accumulator against an f64 host Gram, **launched twice
over a seeded buffer**, because a kernel that stored instead of adding would agree with any
encodings. `r4d_selftest --case moe_gemm_w4a8` also checks `w5nl64a8h`'s arranged row bit for bit
against the statement in `r4d_layout.cpp`, and its inverse. `moe_gemm_q_mod4`'s four classes are
held to `moe_gemm_q`'s stored bytes in every format, and for both ops what the op oracle reads
through the inverse (codes as their levels, an E4M3 scale times its second level) is held to the
quantiser's planes.
- `r4d_selftest --case gram_accum`: the accumulator against an f64 host Gram, **launched twice over
a seeded buffer**, because a kernel that stored instead of adding would agree with any
single-call oracle.
**The end-to-end quality of a container against the bf16 model** is the engine's KL mode
([TOOLS.md](TOOLS.md#the-kl-mode)): the full-vocabulary KL at every position of a fixed corpus,
its mean and its tail percentiles, and the top-1 agreement. It needs the **full 48-layer
container**: the 4-layer bring-up slice cannot resolve a difference this small -- its residual
probe reads the same to within 1% for fp8, `w4a8`, `w4a8h` and GPTQ alike, which says only that
all four compute the same function.
**End-to-end quality against the bf16 model** is the engine's KL mode
([TOOLS.md](TOOLS.md#the-kl-mode)): the full-vocabulary KL at every position of a fixed corpus, its
mean and tail percentiles, and the top-1 agreement. It needs the **full 48-layer container**: the
4-layer bring-up slice cannot resolve a difference this small (its residual probe reads the same to
within 1% for fp8, `w4a8`, `w4a8h` and GPTQ alike).
+1239 -1281
View File
File diff suppressed because it is too large. Load diff
+248 -291
View File
@@ -1,28 +1,25 @@
# Writing a plugin
Three kinds of plugin extend the engine, each a shared object that exports a handful of C symbols
and links **nothing** of radiance's:
Three kinds of plugin extend the engine, each a shared object that exports a few C symbols and
links nothing of radiance's:
- a **kernel library** implements ops for some hardware — a card, a family of cards, the CPU;
- an **architecture** declares a model: its weights, its buffers, the ops it issues and in what
order;
- a **kernel library** implements ops for some hardware (a card, a family of cards, the CPU);
- an **architecture** declares a model: its weights, its buffers, and the ops it issues in order;
- a **quantiser** turns a checkpoint's weights into the planes of an encoding, for `rad-convert`.
The engine `dlopen`s them, asks what they can do, and calls them. That boundary is the whole design:
a plugin is compiled against the installed `abi/` headers and nothing else, so a third party can
ship one without building the engine. **The plugins radiance ships go through exactly this door.**
libr4d, libref, libavx, libquant and every architecture are built with the same `rad_add_plugin`, can
each be built on their own against an installed radiance, and are found and ranked by what they
declare, never by their names; `ctest -L oot` rebuilds all of them out of tree against an installed
prefix and requires the same result (`tests/oot_plugins.sh`).
A plugin is compiled against the installed `abi/` headers alone, so a third party can ship one
without building the engine. The in-tree plugins (libr4d, libref, libavx, libquant and every
architecture) use the same interface: each is built with `rad_add_plugin`, builds on its own
against an installed radiance, and is found and ranked by what it declares, never by its name.
`ctest -L oot` (`tests/oot_plugins.sh`) rebuilds them out of tree against an installed prefix
(libr4d only when given a HIP compiler) and requires the same result.
Sections 1–9 are the kernel side; §10 is what a library for a card radiance has never seen needs;
§11 and §12 are architectures and quantisers; §13 is building, installing and the search path all
three share.
§1-§9 cover kernel libraries, §10 a library for a new card, §11 and §12 architectures and
quantisers, and §13 building, installing and the search path.
---
## 1. The shape of it
## 1. Kernel library exports
```c
#include "rad_abi.h" /* required */
@@ -37,34 +34,33 @@ const RadPluginInfo* rad_plugin_info(void) {
return &i;
}
int rad_kernel_schema_count(void); /* the ops you DEFINE, if any */
int rad_kernel_schema_count(void); /* the ops you define, if any */
const RadOpSchema* rad_kernel_schema_at(int i);
int rad_kernel_count(void); /* the kernels you IMPLEMENT */
int rad_kernel_count(void); /* the kernels you implement */
const RadKernelInfo* rad_kernel_at(int i);
```
`rad_plugin_abi_version` is checked at load and a mismatch is refused **by name, with both numbers
printed**. Do not hardcode the integer — return the macro, and rebuild when it moves. It moves for
any shape change in a header a plugin compiles against (`rad_abi.h` says which).
A plugin whose `rad_plugin_abi_version` differs from the engine's is refused at load, by name, with
both numbers printed. Return the macro, not the integer, and rebuild when it changes; it changes
with any shape change in a header a plugin compiles against (`rad_abi.h` lists them).
`build_target` is prose for a human: the targets you were compiled for (`"gfx1100"`,
`"gfx11-generic"`, several separated by spaces or commas), `"host"` for CPU kernels — which is what
both in-tree host libraries say — or `""` for a plugin that really is portable. It is printed, not
trusted: what the engine checks is the code objects your library actually carries (§10).
`build_target` is printed, not trusted: the targets the library was built for (`"gfx1100"`,
`"gfx11-generic"`, several separated by spaces or commas), `"host"` for CPU kernels, or `""` for a
portable plugin. The engine checks the code objects the library carries instead (§10).
Five more exports are optional, each looked up by exactly this name:
| symbol | says |
| symbol | meaning |
|---|---|
| `int rad_plugin_open(void)` | called once after load. `RAD_E_UNSUPPORTED` **declines this machine** — the library is unloaded and the rest of the installation carries on; any other negative status refuses it as an error |
| `int rad_plugin_open(void)` | called once after load. `RAD_E_UNSUPPORTED` declines this machine: the library is unloaded and the rest of the installation carries on. Any other negative status is an error |
| `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 out of the way while it runs. 2: each launch ends that itself once the other ranks' bytes have landed, through the `link_gate` parameter (rad_abi.h). Without it only the `all_reduce` op counts as one |
| `int rad_plugin_reference(void)` | nonzero: this library is 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 says so through this, as any library would |
| `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 |
---
## 2. A kernel says what it can serve, not what it is
## 2. Kernel constraints
```c
static const RadConstraint c_gemm[] = {
@@ -85,284 +81,243 @@ static const RadKernelInfo k[] = {{
}};
```
The five operators are `RAD_CEQ`, `RAD_CLE`, `RAD_CGE`, `RAD_CDIV`, `RAD_CIN`. **The engine picks
bucket boundaries out of your `LE`/`GE`/`EQ` values** and resolves once per bucket, because a GEMM
sees one row at decode and thousands in a prefill chunk and they do not want the same kernel
(`spec.md` §2.2). `DIV` and `IN` cut nothing — a divisibility holds at every value in a range, and
set membership is not an interval — so neither can be a band edge.
A kernel declares what it can serve. The operators are `RAD_CEQ`, `RAD_CLE`, `RAD_CGE`, `RAD_CDIV`
and `RAD_CIN`. The engine takes bucket boundaries from the `LE`/`GE`/`EQ` values and resolves once
per bucket, since a GEMM sees one row at decode and thousands in a prefill chunk (`spec.md` §2.2).
`DIV` and `IN` are not intervals, so neither is a band edge.
Two consequences worth internalising:
Declare only the band you serve: the engine believes the claim, and a kernel that claims
`M <= 2048` but is correct only to 64 is wrong. A wrong band shows only at concurrency, where M is
larger, so test the whole concurrency ladder, not C=1 alone.
- **Declare the band you actually serve.** A kernel that claims `M <= 2048` and is correct only to
64 is not slow, it is wrong, and the engine believes you.
- **A band you claim and cannot serve is invisible to a single-sequence bench.** It only shows at
concurrency, where M is larger. Run the whole ladder, not just C=1.
**Machine constraints.** A key starting with `device.` is matched against what the engine measured
about the ranks' cards at launch, not against the op's parameters. `RAD_CEQ(RAD_FACT_P2P, 1)`
(`device.p2p`) says a kernel accesses another card's memory. Where some pair of the ranks' cards
cannot reach each other, the kernel is not selected and the next matching row takes the op; with
none, startup stops and the selection table names the fact (`device.p2p == 1, have 0 -- this
machine, measured at launch`). Every libr4d collective carries it and has a `_host` twin requiring
`device.p2p == 0` that exchanges through pinned host memory, so exactly one of the pair matches any
machine. A machine fact changes no tuning key. A tool selecting without an engine has measured
nothing, so such a kernel is not selected there.
**A constraint can be on the machine instead of the geometry.** A key that starts with `device.`
is matched against what the engine measured about the ranks' cards at launch, not against the
op's parameters. `RAD_CEQ(RAD_FACT_P2P, 1)` (`device.p2p`) is how a kernel says it reads or writes
another card's memory. On a machine where some pair of the ranks' cards cannot reach each other,
such a kernel is not selected. The next row that does not need it takes the op. With no such row,
startup stops and the selection table names the fact (`device.p2p == 1, have 0 -- this machine,
measured at launch`). Every collective in libr4d carries it, and each has a `_host` twin that
requires `device.p2p == 0` and exchanges through pinned host memory, so exactly one of the pair
matches any machine. A machine fact is in no geometry, so
it changes no tuning key. A tool that selects without an engine has measured nothing, and such a
kernel is not selected there either.
`priority` breaks ties **within your plugin**, highest first, a tie going to declaration order.
Between plugins there is no contest: **the hierarchy is absolute.** The first plugin in `--kernels`
order with any matching kernel supplies it, and a later plugin never outbids it however
specialised its kernel — which is exactly what makes a user override an override rather than a
competitor.
**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
kernel supplies it, however specialised a later plugin's kernel is. That makes a user's library an
override rather than a competitor.
---
## 3. Operand extents are a request, not a bound
## 3. Operand extents
`RadArgs.t` is positional, in the op schema's order. Each `RadTensor` carries the extent the
**caller narrowed it to**, which is generally smaller than the buffer.
`RadArgs.t` is positional, in the op schema's order. Each `RadTensor` carries the extent the caller
narrowed it to, generally smaller than the buffer. Size loops and grids from those extents, never
from a declared maximum: otherwise a single-row decode runs over every row of an arena buffer,
reading uninitialised memory and overwriting the next op's input.
> An operand handed over at its declared extent means a single-row decode computed over all 8192
> rows of an arena buffer — reading uninitialised memory and writing over the next op's input.
Where an op takes `cu_seqlens`, derive the sequence count from its own length (`n = len - 1`), not
from a sibling array, and each sequence's rows from `cu[n]` and `cu[n+1]`, which are absolute
offsets into the token operands. This lets the engine pass a sub-range of the step (§8).
Size your loops and your grid from the operands you were given, never from a declared maximum.
Where an op takes `cu_seqlens`, derive the sequence count from **its own length** (`n = len - 1`)
rather than from a sibling array, and derive each sequence's rows from `cu[n]` and `cu[n+1]`, which
are absolute offsets into the token operands. Doing it that way is also what lets the engine hand
you a *sub-range* of the step — see §8.
An **absent optional operand is a null `RadTensor.data`, not a short operand count.** Read the
operand after it and every weight in the model shifts by one. `rad_arg_in()` in `rad_plugin.h` is the
one correct fetch.
An absent optional operand is a null `RadTensor.data`, not a shorter operand count; reading it as
a shorter array shifts every later operand by one. `rad_arg_in()` in `rad_plugin.h` fetches an
operand correctly.
---
## 4. The optional hooks, and what each one buys
## 4. Optional kernel hooks
None are required. Each one is a claim, and the engine will use it.
None are required. Each is a claim the engine acts on.
| hook | says |
| hook | meaning |
|---|---|
| `init` / `fini` | per-resolved-instance state; `RadArgs.instance` hands it back |
| `scratch` | how many bytes you need; the engine provides at least that |
| `layout` | this weight is held in my order, not as the container stores it |
| `relayout` | how to produce that order from the container's planes, run by the loader at load |
| `scratch` | bytes of scratch a launch needs; the engine provides at least that |
| `layout` | the kernel holds this weight in its own order, not as the container stores it |
| `relayout` | produces that order from the container's planes, run by the loader |
| `unrelayout` | the inverse, so a tool holding the stored bytes can read the planes back |
| `opd_shape` | how to size and fill every operand, so a tool can call you cold |
| `replaces` | the chain of conventional ops I compute in one launch |
| `tunables` / `tune_valid` | the axes of my instantiation space, and which combinations are legal at a geometry |
| `describe` | this dispatch, described rather than performed, so a repeated sequence can be replayed as a graph |
| `opd_shape` | how to size and fill every operand, so a tool can call the kernel cold |
| `replaces` | the chain of conventional ops the kernel computes in one launch |
| `tunables` / `tune_valid` | the axes of the instantiation space, and which combinations are legal at a geometry |
`opd_shape` and `unrelayout` are what make your kernel **checkable**. Without them, tools that would
otherwise test you against the reference skip you *by name* rather than guessing — which is the
right outcome, and a quiet one.
`opd_shape` and `unrelayout` make a kernel checkable; without them, tools skip it by name instead
of guessing.
`replaces` is a strong claim and the ABI demands exactness: it means "I stand in for this chain,
and you may check me against it." **A kernel that is merely close to the sequence it names should
publish no hook at all.** In exchange, the engine can recognise that your fused kernel and the
spelled-out chain are alternatives — which is how the Model view draws them as one branch instead
of four sequential nodes.
`replaces` must be exact ("this kernel stands in for this chain; check it against it"). A kernel
that is only close publishes no hook. The claim lets the engine treat the fused kernel and the
chain as alternatives, which the Model view draws as one branch.
`tunables` is what makes your kernel tunable at all; without it, it is one fixed implementation
forever. **You declare the axes and their legal values, not a list of pre-named variants**
(`RadTunable` in `rad_abi.h`): the core takes the cross product, so a ladder cannot end up with a
hole in it that quietly runs the next tile up. `tune_valid` rejects the combinations a product of
independent lists cannot express — a block bound that couples two axes, a `K % (sk * unit)` rule —
and a rejected candidate is reported as skipped, not as a failure. `rad-tune` measures the
survivors at the shapes this model actually issues and writes the cache the selector consults at
declare. The chosen point then arrives as **ordinary parameters**: you read `sk` with the same
`rad_args_geti()` you read `M` with, so there is no variant index and no picker in your launch
adapter. `deflt` is what runs where this machine has no measurement for an instantiation, so it has
to be launchable — the loader checks it appears in `values` and refuses your plugin by name if it
does not.
`describe` buys nothing but speed: null means every issue of your kernel is submitted
individually, which is correct and merely slower, and non-null lets a repeatedly issued sequence
be replayed as a graph instead. It must not allocate, must not synchronise and must not touch the
device: it is called while a run is being RECORDED -- not on every step, and not instead of the
launch, which happens anyway on that pass. It takes the stream, because a launch whose arguments
depend on which stream it goes onto would otherwise be described as something it is not. An op
whose work is a memory copy rather than a launch has nothing to put in a `RadLaunchDesc` and should
leave `describe` null.
`tunables` declares the axes and their legal values (`RadTunable` in `rad_abi.h`), not a list of
named variants. The core takes the cross product, so a ladder has no hole that silently runs the
next tile up. `tune_valid` rejects combinations independent lists cannot express (a bound coupling
two axes, a `K % (sk * unit)` rule); a rejected candidate is reported as skipped, not failed.
`rad-tune` measures the survivors at the shapes the model issues and writes the cache the selector
reads at declare. The chosen point arrives as ordinary parameters, read with `rad_args_geti()` like
`M`, so the launch needs no variant index. `deflt` runs where this machine has no measurement and
must be launchable; the loader refuses the plugin by name if `deflt` is not in `values`.
---
## 5. What a launch may do
On a card the `RadStream` a kernel is handed is a queue the engine writes packets into itself
(`core/device/aql.cpp`), not a `hipStream_t`. The engine binary defines the HIP entry points a
kernel library uses and answers them on its own queues:
On a card the `RadStream` a kernel receives is a queue the engine writes packets into itself
(`core/device/aql.cpp`), not a `hipStream_t`. The engine binary defines these HIP entry points and
serves them on its own queues:
- `hipLaunchKernel`, and therefore `<<<>>>` and `hipLaunchKernelGGL`;
- `hipMemcpyAsync`, `hipMemcpy2DAsync`, `hipMemsetAsync`;
- `hipGetLastError` / `hipPeekAtLastError`, with HIP's own semantics.
- `hipStreamSynchronize` (not from a launch, which must not synchronise);
- `hipMemset`, which runs on the engine's queue for the current device and waits;
- `hipGetLastError` / `hipPeekAtLastError`, with HIP's semantics.
**Nothing else in HIP takes an engine stream.** `hipModuleLaunchKernel`, `hipExtLaunchKernel`,
cooperative launches, `hipLaunchHostFunc`, and any library that launches through them — rocBLAS,
hipBLASLt, MIOpen, a hipRTC module — would hand HIP a queue it has never heard of. Header-only
device code (Composable Kernel's device templates, rocPRIM's block primitives) compiled into your
own `.hip` launches through `hipLaunchKernel` and is fine. `hipEventRecord` and `hipStreamWaitEvent`
on an engine stream are refused by name; ordering between streams is the engine's.
cooperative launches, `hipLaunchHostFunc`, and libraries that launch through them (rocBLAS,
hipBLASLt, MIOpen, hipRTC modules) would hand HIP a queue it does not know. Header-only device code
(Composable Kernel's device templates, rocPRIM's block primitives) compiled into your own `.hip`
launches through `hipLaunchKernel` and works. `hipEventRecord` and `hipStreamWaitEvent` on an engine
stream are refused by name; ordering between streams is the engine's.
The code object is read by the engine too, which puts limits on what a kernel may be:
The engine reads the code object too, which limits a kernel to:
- **no hostcall**: `printf` and `assert` in device code need a buffer the queues do not provide, and
a kernel that takes one is refused at its first launch, by name. `rad_add_plugin` compiles device
code with `-DNDEBUG` outside Debug for this reason;
- **no dynamic stack** — recursion, a variable-length array — since nothing sizes its scratch;
- **no hostcall**: `printf` and `assert` in device code need a buffer the queues do not provide,
and the kernel is refused by name at its first launch. `rad_add_plugin` compiles device code with
`-DNDEBUG` outside Debug for this reason;
- **no dynamic stack** (recursion, a variable-length array), since nothing sizes its scratch;
- **kernel arguments up to 768 bytes**, and static plus dynamic LDS up to 64 KiB a dispatch;
- **an uncompressed fat binary**. `rad_add_plugin` passes `--no-offload-compress`; a toolchain that
compresses anyway is refused at the first launch.
- **an uncompressed fat binary**. `rad_add_plugin` passes `--no-offload-compress`; a compressed one
is refused at the first launch.
A device allocation a kernel needs for itself comes from the `scratch` hook (§4), not `hipMalloc`:
the engine's allocator is the one that knows what the card has left.
Device memory a kernel needs for itself comes from the `scratch` hook (§4), not `hipMalloc`, since
the engine's allocator knows what the card has left.
---
## 6. `rad_plugin.h` is optional, and one part of it is not merely convenience
## 6. `rad_plugin.h`
A plugin that includes only `rad_abi.h` is complete and correct. The helper header is shared
definitions of the dozen things every plugin needs — optional-operand fetch, parameter-with-default,
contiguity, row pitch, narrowing conversions.
A plugin that includes only `rad_abi.h` is complete. The helper header holds what every plugin
needs: the optional-operand fetch, parameters with defaults, row pitch, pointer alignment and the
narrowing conversions.
Use its conversions. **The narrowing conversions define what a result IS**: the reference contract
is f32 accumulation, IEEE round-to-nearest-even, no FMA and no reassociation, and a plugin whose
bf16 rounding truncates instead of rounding to even does not reproduce the reference and therefore
cannot be checked against it.
Use its conversions: they define what a result is. The reference contract is f32 accumulation,
IEEE round-to-nearest-even, no FMA and no reassociation, and a plugin whose bf16 narrowing
truncates cannot be checked against the reference.
---
## 7. Defining a new op
Only if the conventional vocabulary in `docs/OPS.md` genuinely has no name for it. That document
is the op vocabulary and the rules that come with adding to it: what a schema must declare, that
the first plugin in hierarchy order to declare an op **fixes its schema** and a later plugin
declaring it differently is refused at load with both plugins named, and why the refusal is worth
having. It is also mechanically checked against the registries by `ctest -R ops_doc`, which is the
reason the statement lives there and not in a second copy here that can drift away from it.
Only when `docs/OPS.md` has no name for it. That document is the op vocabulary and its rules: what
a schema must declare, and that the first plugin in hierarchy order to declare an op fixes its
schema (a later plugin declaring it differently is refused at load, both named). `ctest -R ops_doc`
checks it against the registries, so the rules live there only.
An op that stays inside `docs/OPS.md` is describable by the reference, and therefore checkable,
even when your kernel cannot describe itself.
An op in `docs/OPS.md` is describable by the reference, and so checkable, even when your kernel
cannot describe itself.
---
## 8. The one contract an architecture plugin gets silently wrong
## 8. Mixed steps in an architecture plugin
If you write an **architecture** plugin with a linear/recurrent block, read `spec.md` §10 before
you write its `step()`.
An **architecture** plugin with a linear or recurrent block must follow `spec.md` §10 in its
`step()`.
A step that carries a prefill chunk beside decode rows is what continuous batching produces
constantly — on an agentic load about a third of all steps, and *none of them prefill-only*,
because every chunk rides with decode rows. The obvious block issues one path for the whole step.
Its decode rows then land on the chunked path, which commits the recurrent state directly and takes
no `num_accepted`: a draft verified there cannot be rolled back, the rejected tokens stay folded
into the state, and the model is conditioned on text it never emitted. **The answer stays fluent
and drifts**, which is why it shows up as concurrent requests disagreeing with the same requests
run alone rather than as anything failing.
Continuous batching produces many steps that carry a prefill chunk beside decode rows. A block that
issues one path for the whole step sends its decode rows down the chunked path, which commits the
recurrent state directly and takes no `num_accepted`. A draft verified there cannot be rolled back:
the rejected tokens stay in the state and the model is conditioned on text it never emitted. The
output stays fluent and drifts, so the symptom is concurrent requests disagreeing with the same
requests run alone.
Issue the recurrent path over `RadBatch::n_seq_decode` sequences and the chunked path over the
rest. The core orders every step decode-first so each half is a contiguous run. It costs no kernel
change, for the reason in §3: `cu_seqlens` holds absolute offsets, so the prefill half is addressed
by passing `cu + n_seq_decode` with the token operands left at their base.
Issue the recurrent path over the first `RadBatch::n_seq_decode` sequences and the chunked path
over the rest; the core orders every step decode-first, so each half is contiguous. No kernel
change is needed (§3): `cu_seqlens` holds absolute offsets, so the prefill half is addressed by
passing `cu + n_seq_decode` with the token operands left at their base.
---
## 9. Checking your work
`rad-kbench` is the answer to "is my library correct, complete and fast", and it needs no model:
`rad-kbench` checks a library for correctness, completeness and speed without a model:
```sh
rad-kbench --kernels mylib,libr4d,libref --report mylib.md --bench
```
It replays a recorded fixture — `kernels.rkb` unless `--fixture` names another, and `data/` holds
a dense one and a routed-MoE one — a recording of libref's answers over a few hundred real model
geometries, and runs every kernel **your** library supplies against it. Your rows are found the
same way the engine finds them — your constraints, your priorities — but they are not *selected*:
every library that has a row for a case is run, so yours appears beside libr4d's rather than
instead of it. The report carries the three columns that matter separately:
It replays a recorded fixture of libref's answers over a few hundred real model geometries
(`kernels.rkb` unless `--fixture` names another; `data/` holds a dense one and a routed-MoE one).
Rows are found as the engine finds them, but every library with a row for a case is run, so yours
appear beside libr4d's. The report covers:
- **correctness**, relative to the recorded reference. The recording keeps the full norm of every
output plus 1024 sampled values, so a kernel that gets the sampled positions right and the total
energy wrong still fails.
- **completeness**, the op-by-library matrix, read off the registries rather than off the run —
so an op your library does not implement is a gap whether or not this fixture exercises it.
- **correctness** against the recording, which keeps every output's full norm plus 1024 sampled
values, so a kernel right at the samples but wrong in total energy fails;
- **completeness**, the op-by-library matrix, read from the registries, so a missing op is a gap
whether or not the fixture exercises it;
- **speed**, timed on the same bytes in the same pass.
Three things it does for you that are easy to get wrong on your own:
It also checks:
- **Red zones.** Every device allocation it hands you has a poisoned 256-byte margin either side,
verified after the launch. An out-of-bounds write is the one fault that otherwise reports as a
pass, because in a harness the bytes past your operand belong to nobody. AMD's device
AddressSanitizer needs `xnack+` and RDNA has none, so this is what there is.
- **Fusion.** A row with `replaces` is run against the chain it names, out of *your* library, and
the outputs compared byte for byte. That is a stronger claim than a tolerance against the
oracle, and it is the claim a fusion actually makes.
- **Divergence.** If your `opd_shape` describes an output differently from libref's, you are told
so by name with both descriptions printed, and the case is counted apart from the failures. Two
libraries can mean different things by one op name; that is a conversation, not a bug in your
arithmetic.
- **red zones**: every device allocation has a poisoned 256-byte margin on each side, verified
after the launch, since in a harness an out-of-bounds write otherwise passes. AMD's device
AddressSanitizer needs `xnack+`, which RDNA lacks;
- **fusion**: a row with `replaces` is run against the chain it names, out of your own library,
and the outputs compared byte for byte;
- **divergence**: an output your `opd_shape` describes differently from libref's is reported by
name with both descriptions and counted apart from the failures.
If your kernel is skipped rather than checked, the report names why. The usual cause is a missing
`opd_shape` (§4) — without it the tool will not invent an extent for you.
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
that refused every other candidate.
- `/graph` on a running server carries the declared graph *and* which declarations the run phase
has actually issued — the way to find a band you resolved for nothing.
- `--debug-accept-reference-kernels` is required to run with a reference fallback in place. Without
it, falling back is a fatal error, on purpose: a reference kernel in production is a correctness
result reported as a performance one.
- `rad-info --plugins` prints every plugin the search path offers, as the engine loads it: kind,
version, what it declares, whether it is a reference, whether its device code runs on this card,
and the file it came from.
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
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,
declarations, whether it is a reference, whether its device code runs on this card, and its file.
---
## 10. A library for a card radiance has never seen
## 10. A library for a new card
The engine holds no opinion about cards. Its own device code — the copies and fills every transfer
runs, the step's bookkeeping, the weight-table patches — is compiled for every AMD GPU family's
generic target (`gfx9-generic`, `gfx9-4-generic`, `gfx10-1-generic`, `gfx10-3-generic`,
`gfx11-generic`, `gfx12-generic`) beside whatever the build targeted, so one engine binary starts on
any of them. What it computes there is whatever kernel library you install.
The engine's own device code (the copies and fills every transfer runs, the step's bookkeeping,
the weight-table patches) is compiled for every AMD GPU family's generic target (`gfx9-generic`,
`gfx9-4-generic`, `gfx10-1-generic`, `gfx10-3-generic`, `gfx11-generic`, `gfx12-generic`) beside
the build's own targets, so one engine binary starts on any of them. What it computes there depends
on the kernel library installed.
**Build for the card, or for its family.** `-DRAD_GPU_TARGETS=gfx942` or `=gfx11-generic` when you
configure; the default is the targets the installed radiance was built for. When a code object is
needed the engine asks the runtime which targets the card accepts, in order — the chip itself, then
its family (`gfx1036`, then `gfx10-3-generic`) — each with the modes the card runs in
(`gfx942:sramecc+:xnack-`), and takes the best fit your fat binary holds: the exact chip over the
family, a code object built for the card's mode over one built for either.
**Targets.** Configure with `-DRAD_GPU_TARGETS=gfx942` or `=gfx11-generic`; the default is the
installed radiance's targets. For each code object the engine asks the runtime which targets the
card accepts, in order (the chip, then its family: `gfx1036`, then `gfx10-3-generic`), each with
the card's modes (`gfx942:sramecc+:xnack-`), and takes the best fit in the fat binary: the chip
over the family, a code object for the card's mode over one for either.
**A library with nothing for this card is left out, not failed.** When a kernel library loads, the
fat binaries its `dlopen` registered are checked against the card the ranks will run on, the same
check its first launch would make. If none fits, its device rows are left out of selection and the
log says what it carries and what the card runs; its host rows stay. So one installation can carry
a library per card. A library that knows at `rad_plugin_open` that it does not serve the machine
can also decline it with `RAD_E_UNSUPPORTED`.
**A library with nothing for this card is left out, not failed.** At load, the fat binaries a
kernel library registered are checked against the ranks' card. If none fits, its device rows are
left out of selection, the log says what it carries and what the card runs, and its host rows stay.
One installation can therefore carry a library per card. A library can also decline from
`rad_plugin_open` with `RAD_E_UNSUPPORTED`.
**Which devices.** Discrete cards are used when there are any, and of those the ones sharing the
first one's architecture; integrated graphics only when it is all there is. `ROCR_VISIBLE_DEVICES`
chooses explicitly. On integrated graphics the device memory is the host's: the budget is bounded by
what the host has available and leaves an eighth of the host's memory to it.
**Devices.** The engine uses the discrete cards if there are any (those with the first one's
architecture), and integrated graphics only when there is nothing else. `ROCR_VISIBLE_DEVICES`
chooses explicitly. On integrated graphics device memory is host memory: the budget is bounded by
what the host has available and leaves an eighth of host memory to the host.
**What the core assumes of a card: nothing about its wave size**, its LDS, its fp8 hardware or its
links — those are your kernels' business. Three things are worth knowing before you start:
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 in it (`docs/OPS.md`; `--debug-graph` lists them). A bf16 model
in the tree issues only ops libref also implements — MiniCPM5-2B is 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 own and have no reference yet: the fp8 models, and a drafter
with a 2-bit head, issue some, and run on a library that implements them.
- **fp8 bytes are OCP E4M3** (`e4m3fn`, bias 7, max 448) everywhere the engine reads them: weights in
a container, the KV cache at `--kv-cache-dtype fp8`, activations between ops. A card whose fp8
is `e4m3fnuz` (gfx942) converts weights in its `relayout` hook — the codes are the same bits but
0x80, the value half, so the scale doubles — and keeps activations and KV in OCP bytes, or
converts at its own boundaries.
architecture issues has a row there (`docs/OPS.md`; `--debug-graph` 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.
- **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
`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.
- **Tensor parallelism is ops you supply.** `all_reduce`, `all_gather` and the fused collectives
are rows in a kernel library like any other; the engine inserts none and assumes no link.
are kernel-library rows like any other; the engine inserts none and assumes no link.
---
@@ -370,10 +325,10 @@ links — those are your kernels' business. Three things are worth knowing befor
An architecture plugin declares a model in two phases (`spec.md` §3): `rad_arch_declare` names
every weight, buffer and op once, against the model's metadata, and `rad_arch_step` issues the ops
for one step. The contract is `abi/rad_builder.h` and `abi/rad_runtime.h`; the helpers every
in-tree architecture is built from — weight declarations, the gated-attention and MoE blocks, the
MTP and DFlash2 drafters — are installed as `<arch/rad_arch.h>` and its siblings, and the in-tree
plugins include them by exactly that spelling.
for one step. The contract is `abi/rad_builder.h` and `abi/rad_runtime.h`. The helpers the in-tree
architectures use (weight declarations, the gated-attention and MoE blocks, the MTP and DFlash2
drafters) are installed as `<arch/rad_arch.h>` and its siblings, and the in-tree plugins include
them by that spelling.
```c
const char* rad_arch_id(void); /* "llama" -- what a container's header names */
@@ -385,43 +340,48 @@ const RadChatFormat* rad_arch_chat_format(const RadModelMeta* meta);
```
`rad_plugin_info` reports `RAD_PLUGIN_ARCH`. The engine picks the plugin whose
`(rad_arch_id, rad_arch_quant)` pair equals the container's — exactly, with no fallback — so one
model family at two weight formats is two plugins. A checkpoint's id is its `config.json`
`model_type` with the underscores removed; `rad-convert --arch ID` overrides it. Every key of the
checkpoint's configuration reaches the plugin in `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.
`(rad_arch_id, rad_arch_quant)` pair equals the container's, with no fallback, so one model family
at two weight formats is two plugins. A checkpoint's id is its `config.json` `model_type` without
underscores; `rad-convert --arch ID` overrides it. Every configuration key reaches the plugin in
`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.
What to know first:
- **Stay inside `docs/OPS.md` and the model runs anywhere.** An op libref implements has a host
fallback, an oracle and a specification every kernel library can be checked against. An op you
invent runs only on a library that implements it.
- **A fusion is an op name.** The engine does not rewrite your graph; a kernel library's
`replaces` declares an equivalence for checking, not a substitution. Ask for a fused op where one
exists and fall back to its parts where it does not resolve — an op no library serves is
declared as `RAD_NULL_HANDLE` (`rad_op_resolved`), which is an error only if it is issued — the
way the in-tree blocks do for `qk_norm_rope_gate`.
- **Ops from `docs/OPS.md` run on any library.** An op libref implements has a host fallback, an
oracle and a specification to check kernel libraries against. An op you invent runs only on a
library that implements it.
- **A fusion is an op name.** The engine does not rewrite your graph, and `replaces` declares an
equivalence for checking, not a substitution. Ask for the fused op and fall back to its parts
where it does not resolve: an op no library serves is declared as `RAD_NULL_HANDLE`
(`rad_op_resolved`) and is an error only if issued. The in-tree blocks do this for
`qk_norm_rope_gate`.
- **Read §8** if the model has a linear or recurrent block.
- **Images go through the Qwen-VL processor** (`core/mm`): patching, the pad-token expansion and
three-part rotary positions are the core's. A vision model with another image pipeline needs a
core change today.
- **Media preprocessing is the core's** (`core/mm`): resizing, patching, placeholder-token
expansion and positions, in three processor families (Qwen-VL, Gemma 4, LFM2-VL) chosen by the
container's `vision_config.model_type`. A vision model with another pipeline needs a core change.
Audio goes through one of two feature extractors, Gemma 4's and Qwen3-ASR's (Whisper's), chosen
by `audio_config.model_type`.
- **A speech model says how it hears**, through the optional
`const RadAudioFormat* rad_arch_audio_format(const RadModelMeta*)` (`RAD_ARCH_AUDIO_FORMAT`): the
tokens around a clip when its config names none, the turn a transcription is asked in, how a
language is forced and named, and where the transcript starts in the reply. That is all
`/v1/audio/transcriptions` knows about a model, so a new speech model is a plugin, not a server
change. Like `rad_arch_chat_format`, the struct grows only at its end, behind its `struct_size`.
---
## 12. Quantiser plugins
A quantiser turns a weight, handed to it in f32, into the planes of an **encoding**
(`abi/rad_encoding.h`) — the numbers, in one canonical row-major arrangement any kernel library can
lay out its own way at load. The contract is `abi/rad_quant.h`:
(`abi/rad_encoding.h`): the numbers in one canonical row-major arrangement, which a kernel library
lays out its own way at load. The contract is `abi/rad_quant.h`:
```c
int rad_quant_count(void);
const RadQuantizerInfo* rad_quant_at(int i); /* name, options, encoding, row_block, quantize, decode */
const RadQuantizerInfo* rad_quant_at(int i); /* name, doc, options, encoding, row_block, quantize, decode */
```
`rad_plugin_info` reports `RAD_PLUGIN_QUANT`. `rad-convert` drives quantisers through a **recipe**,
ordered rules from a weight's logical name to a quantiser and its options:
`rad_plugin_info` reports `RAD_PLUGIN_QUANT`. `rad-convert` drives quantisers through a
**recipe**: ordered rules from a weight's logical name to a quantiser and its options.
```
# PATTERN QUANTISER OPTIONS
@@ -429,21 +389,20 @@ blk.*.ffn_*_exps.*.weight myquant bits=3 group=64
* rtn codes=fp8_e4m3 block=128x128 scale=bf16
```
`rad-convert --list-quantizers` prints every quantiser loaded and the options each takes; an option
a recipe gives that the quantiser does not declare is refused before anything is quantised. Two
plugins naming the same quantiser are refused, both named.
`rad-convert --list-quantizers` prints every loaded quantiser and its options. A recipe option the
quantiser does not declare is refused before anything is quantised. Two plugins naming the same
quantiser are refused, both named.
An encoding whose scheme is `plain` or `affine` is decoded by the core. A scheme of your own is
decoded by your `decode` hook, which the oracle, `rad-kbench` and `rad-convert`'s error report all
read through; answer `RAD_E_UNSUPPORTED` for a scheme you did not write. A container in a new
encoding then needs two more things to SERVE: a kernel library whose `layout` hook accepts it, and an
architecture that declares the weight at it. The in-tree architectures' linear and expert
declarations take the encodings their blocks were written for, so a format that is not one of
those is served by a kernel library and an architecture plugin of its own.
The core decodes the `plain` and `affine` schemes. Your own scheme is decoded by your `decode`
hook, which the oracle, `rad-kbench` and `rad-convert`'s error report use; return
`RAD_E_UNSUPPORTED` for a scheme you did not write. Serving a new encoding also needs a kernel
library whose `layout` hook accepts it and an architecture that declares the weight at it. The
in-tree architectures declare only the encodings their blocks were written for, so another format
needs its own kernel library and architecture plugin.
---
## 13. Building, installing, and the search path
## 13. Building, installing and the search path
```cmake
cmake_minimum_required(VERSION 3.21)
@@ -453,37 +412,35 @@ rad_plugin_defaults() # C++20, an optimising build type unless
rad_add_plugin(mykernels kernels SOURCES rows.cpp HIP_SOURCES kernels.hip)
```
The kind is `kernels`, `architectures` or `quantizers` — the directory the engine loads it from.
`HIP_SOURCES`, not `SOURCES`, for device code: only those are compiled as HIP, for
`RAD_GPU_TARGETS` (§10) or a list you pass as `GPU_TARGETS`, at `-O3 -DNDEBUG` outside Debug,
uncompressed, against the HIP runtime the installed radiance found. `rad_add_plugin` is the same
function radiance builds its own plugins with, deliberately not a copy, and every plugin directory
in radiance's tree opens with these lines guarded by `if(NOT COMMAND rad_add_plugin)`, which is
what lets each be built inside the tree or on its own.
The kind is `kernels`, `architectures` or `quantizers`, the directory the engine loads it from.
Only `HIP_SOURCES` are compiled as HIP: for `RAD_GPU_TARGETS` (§10) or a `GPU_TARGETS` list,
optimised with `-DNDEBUG` outside Debug, uncompressed, against the HIP runtime the installed
radiance found. radiance builds its own plugins with the same `rad_add_plugin`, and every plugin
directory in the tree opens with these lines guarded by `if(NOT COMMAND rad_add_plugin)`, so each
builds inside the tree or on its own.
`find_package` also gives you `RADIANCE_ABI_VERSION`, so you can refuse at configure time rather
than at `dlopen`, and `RADIANCE_HOME`, `RADIANCE_KERNELS_DIR`, `RADIANCE_ARCHITECTURES_DIR` and
`find_package` also sets `RADIANCE_ABI_VERSION` (to refuse at configure time rather than at
`dlopen`), `RADIANCE_HOME`, `RADIANCE_KERNELS_DIR`, `RADIANCE_ARCHITECTURES_DIR` and
`RADIANCE_QUANTIZERS_DIR`. `cmake --install` puts the plugin under the home of the radiance you
built against; set `RAD_PLUGIN_INSTALL_HOME` to install somewhere else. Before installing, the
build tree's own `radiance_home/` is a working home for the plugin alone.
built against; `RAD_PLUGIN_INSTALL_HOME` overrides that. Before installing, the build tree's
`radiance_home/` is a working home for the plugin alone.
**`$RADIANCE_HOME` is a search path**: homes separated by `:`, the first winning. Each may hold any
of `kernels/`, `architectures/` and `quantizers/`; a plugin file an earlier home holds shadows one
of the same name later on. So your own plugins go ahead of an installation without copying it:
**`$RADIANCE_HOME` is a search path**: homes separated by `:`, the first winning. Each may hold
`kernels/`, `architectures/` and `quantizers/`, and a plugin file in an earlier home shadows one of
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 ...
```
and the container image takes one the same way, mounted:
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 you in front of libr4d. An entry matches a
plugin's name or its file (`libr4d`, `r4d`, `libr4d.so` and a path to it are one library), and an
entry that matches nothing is warned about by name. **The list is comma-separated** — the tools
also accept colons, the engine's `--kernels` and `$RADIANCE_KERNELS` do not, so write commas
everywhere. A kernel
library on the search path that the list does not name is not loaded, so name every library you
want, the host library (`libavx`) and the reference (`libref`) included. With no list every library
found loads, a reference library (§1) last.
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
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.
+142 -182
View File
@@ -1,23 +1,20 @@
# QSA — Qwen4-Exp's sparse attention
# QSA: Qwen4-Exp's sparse attention
The full-attention layers of Qwen4-Exp (every fourth: 3, 7, … 47) do not attend to everything. A
small **indexer** scores 4-token blocks of the key history and the attention reads only the best
512 of them, plus the incomplete tail. Attention cost is therefore **constant past 2051 tokens**
instead of linear, which is the whole reason the model is usable at 262144.
The full-attention layers of Qwen4-Exp (every fourth: 3, 7, … 47) do not attend to the whole
history. A small **indexer** scores 4-token blocks of the key history, and the attention reads the
best 512 of them plus the incomplete tail, so attention cost is constant past 2051 tokens.
This file is the decomposition and the argument for its shape. The declaration side is
`arch/common/rad_qsa.h`; the arithmetic is libr4d's `qsa_block_key`, `qsa_score`, `qsa_select`,
`qsa_work` and `qsa_tail_store`; the sparse attention is the *ordinary* `attn_paged`. **Schemas and
per-operand contracts live in `docs/OPS.md`**, which is the mechanically checked document, and are
not repeated here.
The declaration side is `arch/common/rad_qsa.h`. The kernels are libr4d's `qsa_block_key`,
`qsa_score`, `qsa_select`, `qsa_work` and `qsa_tail_store`; the sparse attention is the ordinary
`attn_paged`. Schemas and operand contracts are in `docs/OPS.md`.
## The shape
## Shape
From the checkpoint: `indexer_n_heads` 4, `indexer_kv_heads` 1, `indexer_head_dim` 128,
`indexer_budget` 2048, `indexer_compress_ratio` 4. So `block_topk = 2048 / 4 = 512` blocks.
`rotary_dim` is the main attention's — `head_dim 256 * partial_rotary_factor 0.25 = 64` — applied
to the first 64 of the indexer's 128 dims, from the same cos/sin table the layer's attention uses.
The plugin refuses a checkpoint where that would not fit. Three weights a QSA layer:
`indexer_budget` 2048, `indexer_compress_ratio` 4, so `block_topk = 2048 / 4 = 512` blocks.
`rotary_dim` is the main attention's (`head_dim 256 * partial_rotary_factor 0.25 = 64`), applied to
the first 64 of the indexer's 128 dims from the layer's cos/sin table; the plugin refuses a
checkpoint where it does not fit. Weights per QSA layer:
```
model.language_model.layers.<L>.self_attn.indexer.index_qk_proj.weight [640, 2560]
@@ -27,219 +24,182 @@ model.language_model.layers.<L>.self_attn.indexer.k_layernorm.weight [128]
640 = (4 query heads + 1 key head) x 128.
## What it computes
## Computation
```
qk = index_qk_proj(hidden) [T, 640]
q, raw_k = split(qk, [512, 128]) q -> [T, 4, 128], raw_k -> [T, 128]
q = rope(q_layernorm(q), pos) per query, at the query's OWN position
q = rope(q_layernorm(q), pos) per query, at the query's own position
per complete block b of 4 consecutive key tokens:
pooled = mean over the 4 raw_k, IN f32, cast back to bf16
blk_k_b = rope(k_layernorm(pooled), pos of the block's FIRST token)
pooled = mean over the 4 raw_k, in f32, cast back to bf16
blk_k_b = rope(k_layernorm(pooled), pos of the block's first token)
per query:
score_b = sum over the 4 heads of relu(q_h . blk_k_b) / sqrt(128)
keep = indices of the top min(512, n_blocks) scores
visible = the 4 tokens of every kept block, PLUS the tail
visible = the 4 tokens of every kept block, plus the tail
(the (pos+1) % 4 tokens after the last complete block, attended unconditionally)
```
The q side needs no kernel of its own: the norm and the partial rotation over the query half are
`qk_norm_rope_gate`'s **k side** at `n_head` 0, because that kernel already reads a
`[tokens, heads, head_dim]` input at the operand's own row pitch — exactly this projection's query
half inside its `heads + 1` width. It needs the model's cos/sin table, and is bounded by the same
row count the attention block's fusion is, because above that the rows it would read were never
written this step; with no table it falls back to `rmsnorm` + `rope` over a column slice.
The query side is `qk_norm_rope_gate`'s k side at `n_head` 0, which reads `[tokens, heads,
head_dim]` at the operand's row pitch (the query half of the `heads + 1` projection). It needs the
model's cos/sin table and is bounded by the attention block's fusion row count, above which the
table is not filled; otherwise `rmsnorm` and `rope` run over column slices.
## The one thing the reference hides
## Block keys
**A block key is query-independent and, once its four tokens exist, permanent.** The reference
implementation recomputes every block key inside the per-query loop because it is written for
clarity. An engine must not: a block key is computed ONCE, when token `t` with `t % 4 == 3`
arrives, and cached. That turns "a second KV cache" into something much smaller — **block keys**,
`[n_blocks, 128]` bf16, 64 bytes per *token* per QSA layer, plus **a rolling tail** of at most 3 raw
keys to complete the next block.
A block key is independent of the query and, once its four tokens exist, permanent. The reference
recomputes block keys inside the per-query loop; the engine computes each once, when the token with
`t % 4 == 3` arrives, and caches it. The indexer's cache is **block keys**, `[n_blocks, 128]` bf16
(64 bytes per token per QSA layer), plus **a tail** of at most 3 raw keys for the next block.
12 QSA layers x 64 B = **768 B a token**, against the main KV cache's 2 heads x 256 x 2 (K and V)
x 2 bytes x 12 = 24 KiB a token. **The indexer's cache is 3% of the KV cache.** At 262144 tokens
it is 192 MiB a sequence; at 32768, 24 MiB.
12 QSA layers x 64 B = 768 B per token, about 3% of the main KV cache's 24 KiB per token
(2 heads x 256 x 2 (K and V) x 2 bytes x 12 at bf16): 192 MiB per sequence at 262144 tokens,
24 MiB at 32768.
## The exactness bound
## Exactness bound
With `pos + 1 <= budget + ratio - 1 = 2051` visible tokens there are at most `2051/4 = 512`
complete blocks, the top-k keeps all of them, and the tail is attended unconditionally — so the
selected set is every visible token and **QSA is dense causal attention bit for bit**. It is not an
approximation below the bound; it is the same function. Two things follow. A step that carries more
than one query a sequence — a prefill chunk, or a mixed step — issues the *dense* attention below
the bound, because a dense kernel reads each key once a query *tile* where the sparse path reads a
table a query; at decode there is no tile to amortise over, the two cost the same, and the sparse
path runs at every context. And the bound is the property every change to this subsystem is argued
against — see "Checking it".
With `pos + 1 <= budget + ratio - 1 = 2051` visible tokens there are at most 512 complete blocks,
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").
## How the attention reads a selected set
## Attention over a selected set
The selected tokens are 4-aligned and scattered, and **page size 4 makes the selection a block
table**. If the full-attention KV group is paged at 4, a compress block IS a page and the selected
set IS a paged block table — so sparse attention is "write a 512-entry block table" and call the
existing attention, with no new kernel at all.
With the full-attention KV group paged at 4, a compress block is a page and the selected set is a
paged block table, so sparse attention is the existing `attn_paged` with a 512-entry table.
Nothing structural pins 16: in `r4d_attn_paged_h256_gqa12.hip` the block size is a template
parameter and every use of it is generic, so `C_EQ("block_size", 16)` on an attention row is a
declaration and not a limit. And the way an architecture ASKS for four needs no new mechanism —
`RadKVGroupDecl` deliberately does not carry a block size, because a core that picked its own would
be a core that has to be edited when a kernel changes; it is taken off the resolved kernel's
constraints at declare. **The rows and the `#define` have to agree**: a row that claims 16 against a
kernel compiled at 4 resolves at *declare* and refuses at *issue*, which is a much worse place to
find out.
The page size is a kernel constant. The QSA attention units (`r4d_attn_paged_h256_gqa12.hip`,
`r4d_attn_paged_h256_gqa6_bs4.hip`) build `r4d_attn_paged_gqa8.hip` with `G8_BLOCK_SIZE 4`, and
their rows declare `C_EQ("block_size", 4)`. `RadKVGroupDecl` carries no block size: the core takes
it from the resolved attention kernel, and the plugin asks for 4 through the attention op's
`block_size` parameter. **The rows and the `#define` must agree**: a row claiming 16 against a
kernel compiled at 4 resolves at declare and fails at issue.
**There is no engine change either.** `attn_paged` takes the block table and `seqused_k` as ORDINARY
OPERANDS — `arch/common/rad_block_attn_gated_fp8.h` reads them off the KV group batch — so the
sparse attention is the same op and the same kernel, issued with `sel` in place of the sequence's
table and `qsa_select`'s `seqused` in place of its length. Nothing in `core/` learns what QSA is.
The *declaration* order is the reverse of the issue order and is load-bearing: `attn_paged` declares
`sel` and `seqused` as reads, which is what the buffer plan is computed from, so the arch sets them
on the attention block before `attn.declare()` and declares the indexer after it.
`attn_paged` takes the block table and `seqused_k` as ordinary operands
(`arch/common/rad_block_attn_gated_fp8.h`), so the sparse attention is issued with `sel` in place
of the sequence's table and `qsa_select`'s `seqused` in place of its length. Nothing in `core/`
knows about QSA.
## Where the block keys live, and why it decides everything downstream
Declaration order is the reverse of issue order. `attn_paged` declares `sel` and `seqused` as
reads, and the buffer plan comes from declared reads, so the architecture sets them on the
attention block before `attn.declare()` and declares the indexer after it.
**In a KV group, at one page per compress block, indexed by PAGE ID.** The argument is not storage —
it is that **the selected set then needs no translation at all.** The scorer reads `bk[page_id]`
through a table the manager already maintains, and the top-512 output is a list of page ids, which
is the block table the attention reads.
## Block-key storage
**TWO GROUPS, TWO TABLES, AND EACH OP TAKES THE ONE IT BELONGS TO.** The block keys cannot live in
the attention group's pages — there is no room — so they are their own `RAD_KV_FULL` group, and a
sequence's pages there are *different pages* from its attention pages. What makes that harmless is
that both groups are paged at `ratio`, so **block index `b` means the same thing in both**: the b-th
4-token block of the sequence.
Block keys live **in their own `RAD_KV_FULL` group, one page per compress block, indexed by page
id**. The scorer reads `bk[page_id]` through a table the KV manager already maintains, and the
top-512 output is a list of attention page ids, which is the block table the attention reads.
A sequence's block-key pages differ from its attention pages, but both groups are paged at
`ratio`, so **block index `b` means the same in both**. Each op takes the table of the group it
serves:
| op | table it takes |
|---|---|
| `qsa_score` | the **block-key** group's, because it is gathering block keys |
| `qsa_select` | the **attention** group's, because its output is what the attention reads |
| `qsa_score` | the block-key group's, because it gathers block keys |
| `qsa_select` | the attention group's, because its output is what the attention reads |
Nothing is remapped — the index `b` is the join, and it is the same number on both sides. Getting it
backwards scores one sequence's keys through another's pages. A `RAD_BUF_PERSIST` array indexed by
`(slot, block within the sequence)` would work, be simpler to declare, and put that translation back
in three places.
Swapping them scores one sequence's keys through another's pages. A `RAD_BUF_PERSIST` array
indexed by `(slot, block)` would be simpler to declare but needs a translation in three places.
**The geometry is a container, not an attention shape.** A `RAD_KV_FULL` group stores
`[pages, kv_heads, block_size, 2*head_dim]`, so with `kv_heads = 1`, `block_size = ratio` and
`head_dim = n / (2*ratio)` a page holds exactly `n` contiguous values — one block key — and the
manager allocates exactly one page per `ratio` tokens. Here `head_dim` is `128 / 8 = 16`, and
`2 * head_dim * ratio == n` is the assertion that keeps the fiction honest. No waste. **The group's
page size comes from the first op declared after it that carries a `block_size`**
(`Builder::find_kv_consumer`) — *any* op, not only an attention one — so `qsa_block_key` declaring
`block_size` is what sizes this group, exactly as `attn_paged` sizes the attention group.
A `RAD_KV_FULL` group stores `[pages, kv_heads, block_size, 2*head_dim]`. With `kv_heads = 1`,
`block_size = ratio` and `head_dim = n / (2*ratio)` (here `128 / 8 = 16`), a page holds exactly
one block key of `n` values (`2 * head_dim * ratio == n` is asserted). A group's page size comes
from the first later-declared op with a `block_size` (`Builder::find_kv_consumer`), so the group is
declared immediately before `qsa_block_key`, whose `block_size` sizes it.
## The tail is state, and storing it as scratch fails three ways
## The tail
A block key needs `ratio` consecutive raw keys, and at decode three of them are from earlier steps.
The tail is a `RAD_KV_LINEAR` group with `state_dim` `{ratio + n_spec, head_dim}` bound to every QSA
layer including the MTP head's — and the reason is worth stating as failures, because each
alternative is plausible and produces fluent wrong text.
A block key needs `ratio` consecutive raw keys; at decode three come from earlier steps. The tail
is a `RAD_KV_LINEAR` group with `state_dim` `{ratio + max_spec, head_dim}`, bound to every QSA
layer including the MTP head's. The alternatives all produce fluent wrong text:
| a tail stored as… | what it does | fires when |
| a tail stored as… | what goes wrong | when |
|---|---|---|
| ONE buffer for the whole model | layer L pools layer L-1's raw keys, because `index_qk_proj` is per layer | every decode step, always — three of every four keys in a completing block |
| a plane indexed by the BATCH ROW | a request that outlives an earlier one inherits its keys, because the scheduler orders a step by priority and stable-sorts decode first | any step after a concurrent request retires |
| `ratio` rows indexed `pos % ratio` | a rejected draft restarts the next step at a position this one has already overwritten, so a completed block is REBUILT from a future token's key | any speculative step that straddles a block boundary and does not accept everything |
| one buffer for the whole model | layer L pools layer L-1's raw keys, because `index_qk_proj` is per layer | every decode step: three of every four keys in a completing block |
| a plane indexed by the batch row | a request that outlives an earlier one inherits its keys, because the scheduler orders a step by priority and stable-sorts decode first | any step after a concurrent request retires |
| `ratio` rows indexed `pos % ratio` | a rejected draft restarts the next step at a position this one already overwrote, so a completed block is rebuilt from a future token's key | any speculative step that straddles a block boundary and does not accept everything |
All three are one shape: **the tail is state, and it was stored as scratch.** It is read on a later
step than the one that wrote it, and it is keyed by layer, by sequence and by position — none of
which a shared plane indexed by a step-local row can carry. `cu_seqlens` answers *which sequence a
token belongs to in this step*; it says nothing about where that sequence's keys may live. A KV
group answers all three, and two more things fall out for nothing: the engine ZEROES a slot when it
hands one out, and it checkpoints the state with the rest of the linear state, so a resume onto a
half-built block reads the keys that block was built from and not whatever the last tenant left.
A `RAD_KV_WINDOW` of width `ratio` is the near miss — it holds the last four tokens of the STEP,
which at decode is exactly the block completing, but within a prefill chunk many blocks complete and
their keys are long gone, so the window would have to be as wide as the chunk and is then not a tail.
The tail is read on a later step than the one that wrote it and is keyed by layer, sequence and
position; `cu_seqlens` gives only a token's sequence within the step. A KV group slot is zeroed on
hand-out and checkpointed with the linear state, so a resume onto a half-built block reads the keys
it was built from. A `RAD_KV_WINDOW` of width `ratio` holds only the step's last four tokens, which
is the completing block at decode but not within a prefill chunk.
**Two small ops carry it, and their order is load-bearing rather than tidy.** `qsa_work` gathers the
blocks completing this step into the flat list `qsa_block_key` reads; `qsa_tail_store` writes this
step's keys into the state. **`qsa_work` is issued BEFORE `qsa_tail_store`**, because the gather
reads raw keys that are in the tail from earlier steps and the store is about to overwrite them. A
token at position `p` lands at row `p % ring`, so a completing block's rows are already in order,
and a sequence that completes nothing gets `page = -1` and is skipped — one launch a layer a step,
whatever the batch is doing.
`qsa_work` gathers the blocks completing this step into the flat list `qsa_block_key` reads, and
`qsa_tail_store` writes this step's raw keys into the state. **`qsa_work` is issued before
`qsa_tail_store`**, because the gather reads tail keys the store overwrites. Position `p` lands at
row `p % ring`. The work list has `ceil(T / ratio) + n_seq` items; items past the real count get
`page = -1` and are skipped, so it is one launch per layer per step.
## Selecting per query, which is what prefill needs
## Per-query selection (prefill)
At decode there is one query a sequence, so a per-sequence selection is the right granularity by
accident; at prefill every query in a chunk selects its own set out of one shared history. Both
scoring ops take `cu_seqlens`, so `m` is a QUERY row while the block table stays the sequence's —
`cu_seqlens` is the only operand in a batch that says which sequence a token belongs to. Each query
is then bounded by its own position, `n = min(nc[seq], (pos + 1) / ratio)`, which at decode is
`nc[seq]` itself.
At prefill every query in a chunk selects its own set from one shared history. Both scoring ops
take `cu_seqlens`, so `m` is a query row while the block table stays the sequence's. Each query is
bounded by its own position, `n = min(nc[seq], (pos + 1) / ratio)` (at decode, `nc[seq]`).
**And the attention is issued one row a query.** `attn_paged` indexes its block table and its length
by the ROW, and nothing ever said a row had to be a sequence: a chunk of `T` queries issued as `T`
rows of `q_len` 1, each with its own `sel` and `seqused`, *is* per-query sparse attention. Same op,
same kernel, for the second time. It is chunked at `max_seqs` rows because the decode kernel's
split-KV scratch is sized at declare from `max_seqs * q_len_max`.
The attention is issued **one row per query**: `attn_paged` indexes its block table and length by
row, so `T` queries issued as `T` rows of `q_len` 1, each with its own `sel` and `seqused`, is
per-query sparse attention. Launches are chunked at `max(max_seqs, 256)` rows (the gated form takes
the whole step), because the decode kernel's split-KV scratch is sized at declare from `max_seqs`
and `q_len`.
**The partial page is a position test, and that is a causality rule.** `bt[n] >= 0` would be right
for every case decode can present — a decode query on a block boundary has `bt[nc] == -1`, because the KV
manager has not allocated past the sequence. Mid-chunk the same query has *later tokens of the same
chunk* in `bt[n]`: a live page entirely in its future, which `seqused` would then cover in full. The
rule is the query's position, `(pos + 1) % ratio != 0`.
**The partial page is decided by position.** At decode `bt[nc] == -1` on a block boundary, since
nothing is allocated past the sequence, so `bt[n] >= 0` would work there. Mid-chunk, the same
query finds a later token's live page in `bt[n]`, which `seqused` would then cover. The partial
page is appended only when `(pos + 1) % ratio != 0`.
## What the indexer costs
## Cost
**The indexer is the only part of a decode step that grows with context.** `qsa_score` and
`qsa_select` both scale with the number of compressed blocks in the history and both run once a
layer, so between them they account for the whole of the step-time-against-context curve; every
other op in a hybrid of linear layers and a constant-cost attention is flat to within noise. So the
pair is timed AT LENGTH rather than at a convenient context, and `r4d_selftest --perfqsa` does it
with no model — passing the declared width and the live context separately, because the launch
geometry comes from the declaration and the work from `nc`. Both kernels are shaped by that:
`qsa_score` reads the key history once a query TILE and not once a query row, the tile landing on a
sequence boundary because a sequence contributes exactly `1 + n_spec` rows and `cu` is their
cumulative count; `qsa_select` splits the block list into chunks that each find a local top-k, which
is exact because a chunk's local top-k contains every global top-k member of that chunk — that
argument and its tie rule live in `libr4d/r4d_qsa_select_bf16.hip`, beside the code depending on
them.
The indexer is the only part of a decode step that grows with context: `qsa_score` and
`qsa_select` scale with the number of compressed blocks, once per layer. `r4d_selftest --perfqsa
CTX [M] [iters]` times them at a real context length with no model, passing the declared width and
the live context separately (launch geometry comes from the declaration, work from `nc`).
**The reduction is on the VALU and not the LDS crossbar**, which is a property of the architecture
rather than a measurement: `__shfl_xor` lowers to `ds_bpermute_b32` at any offset, so a shuffle
butterfly queues on the LDS pipe, while DPP performs the exchange as a *modifier on the add* —
`row_xmask` covers XOR offsets 8, 4, 2 and 1 within each row of sixteen and `v_permlanex16_b32`
covers the one that crosses rows. The lanes exchanged and the order of the adds are identical, so it
is bit-identical and not merely equivalent. That reasoning belongs beside the instructions and lives
there: `libr4d/r4d_common.h`'s `r4d_wave_sum`.
- `qsa_score` reads the key history once per 4-row query tile, matching a decode sequence's
`1 + n_spec` rows at depth 3; a tile straddling two sequences is processed per part.
- `qsa_select` splits the block list into chunks that each find a local top-k, exact because a
chunk's local top-k contains every global top-k member in it. The proof and the tie rule are in
`libr4d/r4d_qsa_select_bf16.hip`.
- Wave reductions use DPP (`row_xmask` for XOR offsets 8..1, `v_permlanex16_b32` across rows), not
`__shfl_xor`, which lowers to `ds_bpermute_b32` and queues on the LDS pipe. Same lanes and add
order, so bit-identical (`libr4d/r4d_common.h`, `r4d_wave_sum`).
**Any two forms of the selection kernel must produce the same BYTES**, not the same set. A selected set has
no order, so a kernel is free to put entries above the threshold at the front of the table and the
ties at the back — but the attention accumulates a softmax over the pages *in table order*, and
float addition is not associative. A second implementation reproduces the first's layout slot for
slot or it changes the model's output.
**Any two forms of the selection kernel must produce the same bytes**, not only the same set: the
attention sums its softmax over pages in table order, and float addition is not associative.
**And the caller says how much history there is.** Both ops size their grid from the *declared*
width, because the live count is device data and a grid is a host-side number — so without help a
short prompt launches for the whole `--max-model-len`. The architecture narrows the score operand's column
count to a host-side ceiling the batch already carries, leaving the pitch at the declaration's.
**Every term of that ceiling is slack on purpose**, because an under-estimate drops blocks from the
selection and nothing would say so.
**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`
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.
## Checking it
**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
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.
There is no switch that runs sparse and dense attention over the same tokens, deliberately: above
the bound, dense attention is *not* the attention the checkpoint was trained with, so a knob for it
is a way to make a server quietly serve a different model. `libref`
implements none of the QSA ops either, so there is no reference-plugin comparison for the subsystem
as a whole. What exists instead is what a change here is checked against:
## Checking
- **per-kernel oracles in `r4d_selftest`** — `qsa_block_key` and `qsa_score` against an f64
evaluation of the same formula, `qsa_work` and `qsa_tail_store` against a host walk of the same
batch, `qsa_select` against a host sort, a prefill case for the per-query join, and a
split-vs-unsplit case asserting BIT identity on a fixture whose scores are mostly ties, so the tie
rule rather than the radix decides the answer;
- **`RADIANCE_DEBUG_QSA`**, the only window into a selection: `nc`, `nsel`, `seqused` and the head of
the table, for the first few steps. `nc` above `topk` is blocks being dropped on purpose, which is
what tells QSA doing its job apart from a divergence. It synchronises the stream, so it is an
environment variable and it is off.
There is deliberately no switch that forces dense attention above the bound, where it is not the
model the checkpoint was trained as. libref implements only `qsa_block_key` of the QSA ops, so
there is no whole-subsystem reference comparison. Changes are checked with:
**Count the reach, not the prompt.** The bound is on the context each query sees, so a prompt a few
tokens under it crosses it partway through the decode and is *supposed* to start differing there.
- **`r4d_selftest` oracles**: `qsa_block_key` and `qsa_score` against f64 evaluations,
`qsa_work` and `qsa_tail_store` against a host walk of the batch, `qsa_select` against a host
sort, a prefill case for the per-query join, the wide-launch form against the single-workgroup
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.
**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.
+549 -296
View File
File diff suppressed because it is too large. Load diff
+123 -113
View File
@@ -1,121 +1,124 @@
# Any world size: the attention world, uneven delta-net heads, and nothing padded
# Tensor parallelism at any world size
Radiance shards by dividing: `n_head`, `n_head_kv`, the delta-net head counts and the vocabulary
each split across the world, and a count that does not divide is **refused at declare, by name**
(`share.cpp`, `rad_arch.h`). Four ranks get through for Qwen3.8-Flash-Next by replicating the two
KV heads in rank pairs; three did not: 24 query heads, 2 KV heads, 16 GDN K heads and 48 GDN V
heads have no even share in 3, and replication needs a world that is a multiple of the head count.
Padding the checkpoint offline (`tools/pad_tp.py`: zero heads appended so that 36 / 3 / 18 / 54
divide) served three ranks exactly, at the cost of a second 115 GiB container for every model and
a third of the attention and 2 of 18 delta-net heads computing zeros.
radiance shards by dividing: `n_head`, `n_head_kv` and the delta-net head counts split across the
world, and a count that does not divide is refused at declare, by name (`rad_arch.h`,
`core/format/share.cpp`). Qwen3.8-Flash-Next has 24 query heads, 2 KV heads, 16 GDN K heads and 48
GDN V heads. Four ranks work by replicating each KV head on a pair of ranks; three do not, since
none of the counts divides by 3 and replication needs a world that is a multiple of the KV head
count.
This document describes what replaced it: **the shipped container serves at any world size**, with
no tool and no second file. Two rules, both built from machinery the engine already had.
Two rules let the shipped container serve at any world size, with no second container and no
padded heads: a smaller attention world (§1) and uneven delta-net heads (§2).
## 1. The attention world
`rad_arch.h` `geom_from` handles a world *above* the KV head count by replication, when the world
is a multiple of the count. For a plugin that asks for it (`attn_world_ok`; qwen4exp does) it also
handles a world that is **neither a divisor nor a multiple** of it:
`rad_arch.h` `geom_from` handles a world above the KV head count by replication when the world is
a multiple of the count. For a plugin that passes `attn_world_ok` (qwen4exp does), it also handles
a world that is neither a divisor nor a multiple of the count: attention is served on the largest
multiple of the KV head count below the world (the **attention world**), and the ranks past it are
**attention-zero**.
> attention is served on the largest multiple of the KV head count under the world -- the
> **attention world** -- and the ranks past it are **attention-zero**.
Three ranks over two KV heads give an attention world of 2. Ranks 0 and 1 split the heads as a
two-rank serve does (12 query heads, one KV head, gqa 12, the same kernels). Rank 2 computes no
attention: `rad_block_attn_gated_fp8.h` declares no projections, no attention and no cache store on
it, and zeroes the block's output wire with one `fill` ([OPS.md](OPS.md)). The all-reduce and the
residual after it run as usual, and the zero adds nothing to the reduce. Five ranks over two KV
heads give an attention world of 4 (two replicated pairs) with rank 4 attention-zero; six give
three pairs and no zero rank. A plugin that does not pass `attn_world_ok` is refused at such a
world, by name.
Three ranks over two KV heads: the attention world is 2. Ranks 0 and 1 split the heads exactly as
the two-rank serve does -- 12 query heads, one KV head, gqa 12, the same kernels -- and rank 2
**computes no attention**: `rad_block_attn_gated_fp8.h` declares no projections, no attention and
no cache store on it, and writes the block's output wire to zero with one `fill` (`docs/OPS.md`).
The all-reduce and the residual after it see what they always saw, and the zero adds exactly
nothing to the reduce. Five ranks over two: attention world 4 (two replicated pairs), rank 4
attention-zero. Six: three pairs, no zero rank. A plugin that does not ask is refused at a world
like these, by name, as before.
**The KV groups stay in the same order on every rank.** The scheduler sees one program
KV groups stay in the same order on every rank. The scheduler sees one program
(`core/sched/batch.cpp` indexes `kv_groups[i]` by position) and one block table serves every rank,
so an attention-zero rank declares its attention group like its peers and marks it
`rad_kv_group_zero`: it carves nothing for it, holds the shared table's block count, lends none of
it, and the tiers skip it when they move an entry. Every rank carves the same block count -- each
is planned, asked what it could page (`KVManager::paged_tokens`; a rank whose only paged groups are
zero limits nobody) and capped at the least before any carves.
`rad_kv_group_zero`: it carves nothing for the group, holds the shared table's block count, lends
none of it, and the tiers skip the group when they move an entry. Every rank carves the same block
count: each is planned, asked what it could page (`KVManager::paged_tokens`; a rank whose only
paged groups are zero limits nobody), and capped at the least before any rank carves.
**The attention-zero rank's pools are its own.** The budget resolver derives one split for every
card, the dearest rank's -- and an attention-zero rank's cache costs a fraction of its peers' per
token (at TP3 on Flash-Next it keeps only the QSA block keys: 2.3 GiB at the worst case where an
attention rank's costs 15.2). Under `expert_tiered` with both pools derived, `Engine::plan` gives
such a rank a KV pool that pages exactly the common token count (`KVManager::pool_mib_for_tokens`,
the inverse of `paged_tokens`: the least whole MiB whose paged split reaches the count, exact
because the split is monotone in the budget and its alignment is among the fixed costs) and moves the
difference into its weights pool, no further than every one of its weights resident. Both readers
of the resolved sizes take the rank's own split -- `Pools::configure` and the planner -- so the
grown pool is planned into, and startup refuses a rank whose plan and weights pool disagree, or
whose re-sized KV pool pages fewer tokens than it was sized for. The token count, the carve, the
loan and the attention ranks' pools are unchanged, and `auto` keeps the common split (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 cache does not lend there, and the bytes the rank never
pages are as much its experts' as they are under a lending cache. The condition is the cost, not
the world: a rank is re-split only where its cache costs less per token than the dearest rank's,
which at TP2/TP4 no rank does. A rank that qualifies and keeps the common split names 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 re-split rank whose weights all fit on the card says so
(`its pinned host pool holds no weights`). The log line, and the mover on the third rank:
An attention-zero rank gets pools of its own. The budget resolver derives one split for every card
from the most expensive rank, and an attention-zero rank's cache costs a fraction of its peers' per
token (at TP3 on Flash-Next it keeps only the QSA block keys: 2.3 GiB at the worst case, where an
attention rank's costs 15.2 GiB). Under `expert_tiered`, `Engine::plan` gives such a rank a KV pool
that pages exactly the common token count (`KVManager::pool_mib_for_tokens`, the inverse of
`paged_tokens`: the least whole MiB whose paged split reaches the count; exact because the split is
monotone in the budget and its alignment is among the fixed costs), and moves the difference into
its weights pool, up to all of its weights resident.
- Both readers of the resolved sizes, `Pools::configure` and the planner, take the rank's own
split, so the grown pool is planned into. Startup refuses a rank whose plan and weights pool
disagree, or whose re-sized KV pool pages fewer tokens than it was sized for.
- 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
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
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:
```
kv: rank 2's cache costs 2.27 GiB at the worst case where its dearest peer's costs 15.16 GiB, so its KV pool pages the common 1446302 tokens in 1811 MiB instead of 10881; its weights pool grows 19747 -> 21692 MiB (every weight resident wants 21.18 GiB), and 7125 MiB stay unclaimed
I[2] mover: 25142 slab slots (64 shadow), 0 pinned pool slots
```
The settle check's INFO line on that card names the unclaimed MiB and points at this line rather
than at the budget's `unusable` line alone.
That rank's `mover:` line then reports 0 pinned pool slots. The settle check's INFO line on that
card names the unclaimed MiB and points at the `kv: rank 2 ...` line, not only at the budget's
`unusable` line.
Under a smaller attention world the plain even shard over `world` is the wrong cut for every
attention projection, so the attention ranks declare **spans** (`rad_weight_shard_span`, the same
call the KV replication uses for k/v): q|gate rows and output columns `[attn_rank * n_head,
+n_head)` heads, k/v rows at `kv_off`. When the attention world is the world -- every TP2 and TP4
deployment -- no span is declared and the block declares as it always did.
Under a smaller attention world, the even shard over `world` is the wrong cut for every attention
projection, so the attention ranks declare spans (`rad_weight_shard_span`, the call KV replication
uses for k/v): q|gate rows and output columns over heads `[attn_rank * n_head, +n_head)`, k/v rows
at `kv_off`. When the attention world is the world (every TP2 and TP4 deployment), no span is
declared.
## 2. Uneven delta-net heads
The delta net has no KV-head constraint: its kernels are bound on head *widths* (`head_k`,
`head_v`, the chunk) and take any head count. So 16 K heads over three ranks are **5, 5 and 6**,
each rank's V heads the same multiple of its K heads (48 / 16 = 3: 15, 15, 18), every rank real
heads, nothing padded. The extra head goes to the rank without attention (`remainder_place` in
`rad_arch.h`): it has the time, and the rank that would otherwise hold the extra head AND attention
is the step's slowest. The experts' extra block stays on the parity rotation (`qwen4exp_fp8.cpp`
says why). `qwen4exp` computes the split and `rad_block_gdn_fp8.h` declares it as spans of the
container's rows. Each rank's recurrent state is its own size, so a fresh slot is cleared, a
snapshot taken and a tier entry laid out by each rank's own plan: a slot of the snapshot store or
the tiers is the sum of the ranks' shares, each rank's where the ones before it end.
The delta net has no KV-head constraint: its kernels are bound by head widths (`head_k`, `head_v`,
the chunk) and take any head count. 16 K heads over three ranks are therefore 5, 5 and 6, and each
rank's V heads are the same multiple of its K heads (48 / 16 = 3: 15, 15 and 18). Every rank holds
real heads and nothing is padded.
That needed one thing the span call could not say. `in_proj_qkv|z` is four projections stacked
along dim 0 -- q 2048, k 2048, v 6144, z 6144 rows -- and `rad_weight_shard_span` takes one
`[lo, hi)` applied to every stacked part, which assumes the parts are equal.
**`rad_weight_shard_span_parts`** (an additive export) takes a span per part together with each
part's whole extent in the container; `share.cpp` cuts every part by its own rows. The conv
channels `[q|k|v]`, the `[a|b]` projections, `A_log`, `dt_bias` and the output projection's
columns take the same rank's heads. The even split, when the counts divide, is untouched.
The extra head goes to the rank without attention (`remainder_place` in `rad_arch.h`), which has
the time; a rank holding both the extra head and attention would be the step's slowest. The
experts' extra block stays on the parity rotation (`qwen4exp_fp8.cpp` gives the reason).
`qwen4exp` computes the split and `rad_block_gdn_fp8.h` declares it as spans of the container's
rows. Each rank's recurrent state has its own size, so each rank's own plan clears a fresh slot,
takes a snapshot and lays out a tier entry: a slot of the snapshot store or of the tiers is the sum
of the ranks' shares, each rank's share starting where the previous one ends.
## 3. What this is built from
`in_proj_qkv|z` stacks four projections along dim 0 (q 2048, k 2048, v 6144 and z 6144 rows), and
`rad_weight_shard_span` applies one `[lo, hi)` to every stacked part, which assumes equal parts.
`rad_weight_shard_span_parts` takes a span per part together with each part's whole extent in the
container, and `share.cpp` cuts every part by its own rows. The conv channels `[q|k|v]`, the `[a|b]`
projections, `A_log`, `dt_bias` and the output projection's columns take the same rank's heads.
When the counts divide, the even split is used.
- `rad_weight_shard_span_parts(b, w, lo, hi, total, n)` -- a span per stacked part.
- `rad_kv_group_zero(b, g)` -- this rank keeps no cache for a paged group.
- the `fill` op -- libr4d's `fill_bf16`, libref's `ref_fill`.
## 3. Interfaces
- `rad_weight_shard_span_parts(b, w, lo, hi, total, n)`: a span per stacked part.
- `rad_kv_group_zero(b, g)`: this rank keeps no cache for a paged group.
- The `fill` op: libr4d's `fill_bf16`, libref's `ref_fill`.
- `Geom::attn_world / attn_rank / attn_zero`, set by `geom_from` under `attn_world_ok`;
`GdnFP8::Config::k_first / v_first`, set by the plugin.
- The exports are additive: `RAD_ABI_VERSION` does not move, and a plugin that does not call them
declares as before. `tests/share_test.cpp` holds the per-part cut, `tests/arch_test.cpp` the
three-rank declaration, `tests/mem_test.cpp` the capped carve, the zero group and a tier entry
moved across ranks with unequal shares.
- Both exports are additive: `RAD_ABI_VERSION` is unchanged by them, and a plugin that does not
call them is unaffected.
- Tests: `tests/share_test.cpp` covers the per-part cut, `tests/arch_test.cpp` the three-rank
declaration, and `tests/mem_test.cpp` the capped carve, the zero group and a tier entry moved
across ranks with unequal shares.
**A load check that came with it.** The relayout pool refuses to finish when any staged weight was
never delivered: a slot nothing wrote holds whatever the card had there -- zeros on a card whose
freed memory the driver wipes, garbage after a reset ("VRAM is lost"). The instrument that shows
such a read on any card:
Load check: the relayout pool refuses to finish when any staged weight was never delivered. A slot
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 ...
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 fill
to a thread's allocation ordinals for a bisect (`core/device/dispatch.cpp`).
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
fill to a range of a thread's allocation ordinals, for bisecting (`core/device/dispatch.cpp`).
## 4. Serving
@@ -126,28 +129,34 @@ radiance --model qwen3.8-next-flash-fp8-iq4r-moe.rad --tp 3 --tp-wire exact --ma
--num-speculative-tokens 3 --max-num-batched-tokens 2048
```
The exact all-reduce at three ranks is the wide family's one-shot up to 1 MiB a message (every
decode step) and its two-shot above it (every prefill chunk): reduce-scatter + all-gather, which
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 rows fold in fp32 in ascending rank order, so the band edge between them changes no bits.
`--tp-wire wht6` at three ranks is the four-rank tiered-int8 wire over the same uneven two-shot,
above `--tp-wire-min-kb`; under it, the exact one-shot.
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`
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.
The log says what the geometry did:
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
radiance: qwen4exp: rank 0 takes delta-net K heads [6, 11) of 16 and V heads [18, 33) of 48
radiance: qwen4exp: rank 1 takes delta-net K heads [11, 16) of 16 and V heads [33, 48) of 48
radiance: qwen4exp: rank 2 takes delta-net K heads [0, 6) of 16 and V heads [0, 18) of 48
```
Measured by the contributor on three Radeon AI PRO R9700 (gfx1201, PCIe Gen5 x16) at an earlier
state of this design -- the attention-zero rank then ran its projections on zero weights, and the
extra delta-net head sat on rank 0 -- with the uncensored Flash-Next fine-tune. Hot = 1 / 4 / 8
streams, 8 K prompt, 1 K generated, aggregate tok/s; crowd = 4 streams at 100 K context, per
stream; HumanEval 164 and a 200-question GSM8K subset at temperature 0:
Each rank's delta-net share is a note in its declared graph; `--debug-graph` and the dashboard's
graph view show rank 0's:
```
rank 0 takes delta-net K heads [6, 11) of 16 and V heads [18, 33) of 48
```
Ranks 1 and 2 take K heads [11, 16) and [0, 6), and V heads [33, 48) and [0, 18).
The following was measured by a contributor on three Radeon AI PRO R9700 (gfx1201, PCIe Gen5 x16)
with the uncensored Flash-Next fine-tune, on an earlier revision of this design: the
attention-zero rank still ran its projections on zero weights, and the extra delta-net head sat on
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 |
|---|---|---|---|---|---|
@@ -155,11 +164,12 @@ stream; HumanEval 164 and a 200-question GSM8K subset at temperature 0:
| unpadded, the same file | 2 | 177 / 308 / 377 | 33.8 | 0.884 | 0.915 |
| padded offline | 3 | 182 / 288 / 395 | 43.5 | 0.848 | 0.935 |
Three ranks buy the single stream and the long-context crowd, not the eight-stream aggregate. The
quality rows are within a rerun of each other (HumanEval moves by about 3 of 164 between runs of one
container); unpadded and padded at three ranks gave the same answers on 40 prompts at temperature
0, bit-identical on one -- the head regroup changes the order the all-reduce sums in, and near-ties
flip.
At these settings three ranks were faster than two for a single stream and for the long-context
crowd, but not for the eight-stream aggregate. The quality columns are within run-to-run variation
(HumanEval moves by about 3 of 164 between runs of one container). Unpadded and padded at three
ranks gave the same answers on 40 prompts at temperature 0, bit-identical on one: the head regroup
changes the order the all-reduce sums in, and near-ties flip.
`tools/pad_tp.py` and `tools/pad_verify.py` remain in the tree: they are how a checkpoint is padded
for an engine that has no attention world, and how a pad is verified, and nothing here needs them.
`tools/pad_tp.py` pads a checkpoint for an engine without an attention world (zero heads appended
so that 36 / 3 / 18 / 54 divide, at the cost of a second container and of computing zeros), and
`tools/pad_verify.py` verifies a pad; radiance needs neither.
+189
View File
@@ -0,0 +1,189 @@
# Four ranks on a PCIe fabric: what pays, what doesn't, and how to tell
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.
## The table
| # | 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 |
## Kill levels — which dead ends are actually closed
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 |
|---|---|---|
| **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) |
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.
## 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.
## Interaction diagram
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.
+69 -68
View File
@@ -1,26 +1,25 @@
# Static YaRN
Increasing `--max-model-len` reserves a larger serving window; it does not change
the model's rotary embeddings. A checkpoint trained at 262144 positions can
explicitly request static YaRN for a 524288-token deployment. Whether that extension
preserves useful accuracy must be measured on the model and workload.
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.
One reader takes every architecture's rotary scaling (`yarn_from`,
`arch/common/rad_arch.h`). For the target it reads `text_config.rope_parameters`,
then `rope_parameters`, then the legacy `text_config.rope_scaling` and `rope_scaling`,
in that order; the first object with `rope_type` (or legacy `type`) is authoritative.
A drafter (DFlash2, DSpark) reads its own `draft.rope_parameters` /
`draft.rope_scaling`; it does not inherit the target's scaling. The vision tower keeps
its original axial rotations. A GGUF's `rope.scaling.*` keys are carried in as the
same `rope_scaling` keys when it is read.
Every architecture reads its rotary scaling through one function (`yarn_from`,
`arch/common/rad_arch.h`). For the target it reads `text_config.rope_parameters`, then
`rope_parameters`, then the legacy `text_config.rope_scaling` and `rope_scaling`; the first object
with a `rope_type` (or legacy `type`) key is authoritative. A drafter (DFlash2, DSpark) reads its
own `draft.rope_parameters` / `draft.rope_scaling` and does not inherit the target's scaling. The
vision tower keeps its axial rotary. A GGUF's `rope.scaling.*` keys are read in as the same
`rope_scaling` keys.
**The factor convention is the config's**, as vLLM and transformers read it:
`factor` 2 over `original_max_position_embeddings` 262144 reaches 524288 positions.
The factor convention is the config's, as vLLM and transformers read it: `factor` 2 over
`original_max_position_embeddings` 262144 reaches 524288 positions.
Validated so far: the Qwen3.8 27B and 35B-A3B containers and both Flash-Next
variants at factor 2, with retrieval at ~500K tokens, and TP3 perplexity with
`--rope-scaling` within roughly ±1% of stock at factor 2. The LLaMA plugins read the
same keys and declare the same ops; YaRN there has had no model run.
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
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.
## Metadata
@@ -28,22 +27,21 @@ same keys and declare the same ops; YaRN there has had no model run.
| --- | --- |
| `rope_type` | `yarn`; `default`, absent or legacy `mrope` is no scaling; `linear` divides positions by `factor` |
| `factor` | finite number >= 1, required for YaRN |
| `original_max_position_embeddings` | positive integer, required; the **training** length, not the enlarged deployment/table length |
| `original_max_position_embeddings` | positive integer, required; the training length, not the enlarged deployment or table length |
| `beta_fast`, `beta_slow` | defaults 32 and 1; finite, fast >= slow > 0 |
| `attention_factor` | positive finite cos/sin multiplier; default 1 + 0.1 ln(factor) for factor > 1, otherwise 1 |
| `truncate` | true/1 (default): floor/ceil correction bounds; false/0: retain fractional bounds |
| `truncate` | true/1 (default): floor/ceil correction bounds; false/0: keep fractional bounds |
Every other type -- `llama3`, `longrope`, `dynamic` -- is refused by name at load,
as are the `mscale` and `mscale_all_dim` variants (specify `attention_factor`). A
GGUF that sets llama.cpp's YaRN `attn_factor`, `ext_factor` or log multiplier to
anything but its neutral value is refused when read. Rotary width (including
partial rotary), theta and M-RoPE section selection are unchanged.
Every other type (`llama3`, `longrope`, `dynamic`) is refused by name at load, as are the `mscale`
and `mscale_all_dim` keys (use `attention_factor`). A GGUF that sets llama.cpp's YaRN
`attn_factor`, `ext_factor` or log multiplier to anything but its neutral value is refused when
read. Rotary width (including partial rotary), theta and the M-RoPE sections are unchanged.
## Convert a separate container
## Converting a separate container
Use the original target and drafter checkpoints, the same quantization recipe,
and a **new output path**. `--reuse` is valid only for the same source weights and
recipe; it is not a way to mix weights from different model revisions.
Use the original target and drafter checkpoints, the same recipe, and a new output path. `--reuse`
is valid only for the same source weights and recipe; it cannot mix weights from different model
revisions.
```sh
rad-convert /checkpoints/Qwen3.8-27B-FP8 \
@@ -60,10 +58,9 @@ rad-convert /checkpoints/Qwen3.8-27B-FP8 \
-o /models/qwen3.8-27b-fp8-yarn2.rad
```
Run with `--plan-only` first. `--max-ctx` is the converter's graph bound, not a
replacement for the explicit YaRN metadata or the server's `--max-model-len`.
The bundled `.rad` by itself is not a converter input; keep the source checkpoints.
Check both target and draft settings with `rad-info --meta` after conversion.
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 source checkpoints. After conversion, check the target and draft keys with `rad-info --meta`.
Serve on enough memory for the requested window:
@@ -72,53 +69,57 @@ radiance --model /models/qwen3.8-27b-fp8-yarn2.rad \
--tp 4 --max-model-len 524288 --max-num-seqs 32 --kv-cache-dtype bf16
```
That cache flag controls **both** target and drafter KV. Startup capacity and
successful actual long requests must be checked; the command is not a promise
of concurrency or accuracy. Keep the unmodified model and serving setup until
long-context quality and speed meet the deployment's requirements.
`--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
unmodified model and serving setup until long-context quality and speed meet the deployment's
requirements.
## Serve an existing container: `--rope-scaling`
## Serving an existing container: `--rope-scaling`
The same metadata can be written when the container is loaded instead of converted in:
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
```
`yarn:FACTOR[:ORIG]` sets `rope_type = yarn`, `factor` and `original_max_position_embeddings`
(`ORIG`, default the container's own trained length) in the rotary object the reader above
takes first -- for a Qwen3.8 container that is `text_config.rope_parameters`, which already says
`default`; YaRN written under plain `rope_parameters` would sit behind it and never be read. A
drafter gets the same factor over its own trained length. Over a checkpoint's own YaRN
the factor is replaced, its trained length kept unless `ORIG` is given, and an explicit
`attention_factor` (or `mscale` variant) dropped so the magnitude is derived for the new factor.
`none` takes a checkpoint's YaRN off. A linear or other explicit rotary type is refused rather
than stacked over. The result is resolved and checked exactly as a converted container's is
(`core/format/rope_override.h`, held to `yarn_from` in `tests/yarn_test.cpp`).
`yarn:FACTOR[:ORIG]` (FACTOR above 1) sets `rope_type = yarn`, `factor` and
`original_max_position_embeddings` (`ORIG`, default the container's own trained length) in the
object the reader takes first. For a Qwen3.8 container that is `text_config.rope_parameters`,
which already says `default`; YaRN written under plain `rope_parameters` would never be read. A
drafter gets the same factor over its own trained length.
Startup says what the rotary is (`rope: YaRN factor 2 over 262144 trained positions -- the rotary
reaches 524288`) and warns when `--max-model-len` is past what it covers -- also with no scaling
at all, past the trained length.
Over a checkpoint's own YaRN, the factor is replaced, the trained length is kept unless `ORIG` is
given, and an explicit `attention_factor` (or `mscale` key) is dropped so the magnitude is derived
for the new factor. `none` turns a checkpoint's YaRN off. A `linear` or other explicit rotary type
is refused, not stacked over. The result is resolved and checked as a converted container's is
(`core/format/rope_override.h`, held to `yarn_from` by `tests/yarn_test.cpp`).
The flag is for trying a factor, or serving a container whose source checkpoints are not at hand;
a deployment that settles on one can convert it in as above and drop the flag.
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
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.
## Kernel and test contract
`rope`, `rope_table` and `qsa_block_key` take optional resolved coefficients
`yarn_factor`, `yarn_low`, `yarn_high`, `yarn_magnitude` (docs/OPS.md). Absent factor
is the original path, with the original op identities. With YaRN, `scale` must be 1:
inverse frequencies are blended rather than all positions being divided. Axial
rotary with YaRN is refused. Rebuild the bundled plugins together because their
shared op schemas must match.
`rope`, `rope_table` and `qsa_block_key` take the optional resolved coefficients `yarn_factor`,
`yarn_low`, `yarn_high` and `yarn_magnitude` ([OPS.md](OPS.md)). Without them an op is declared
as for an unscaled rotary, so op identities and tune keys do not change. With YaRN, `scale` must be 1, since YaRN
blends inverse frequencies instead of dividing positions. Axial rotary with YaRN is refused.
Rebuild the bundled plugins together, because their shared op schemas must match.
The math follows the static YaRN formulation (Peng et al.) as vLLM's
`YaRNScalingRotaryEmbedding` implements it. `tests/yarn_test.cpp` pins the
correction bounds to vLLM's integers (14/22, 28/43, 56/85 for rotary widths 64, 128,
256 at factor 2, theta 1e7, 262144 trained positions); `tests/ref_test.cpp` and
`r4d_selftest` compare libref and libr4d against a double-precision evaluation of the
same formula at positions through 524287, within 8 ulp of each angle -- tight where
the ramp sits, loose only in the fastest pairs at long positions, which no f32 rotary
places better than its angle's own ulp. libavx is held to libref by `avx_check`, and
fused versus unfused HIP rotation is checked byte-for-byte separately.
`YaRNScalingRotaryEmbedding` implements it. `tests/yarn_test.cpp` pins the correction bounds to
vLLM's integers (14/22, 28/43, 56/85 for rotary widths 64, 128, 256 at factor 2, theta 1e7, 262144
trained positions). `tests/ref_test.cpp` and `r4d_selftest` compare libref and libr4d against a
double-precision evaluation of the same formula at positions up to 524287, within 8 ulp of each
angle. That bound is tight where the ramp sits and loose only in the fastest pairs at long
positions, where no f32 rotary can do better than the angle's own ulp. `avx_check` holds libavx
to libref, and fused against unfused HIP rotation is checked byte for byte.
+116 -132
View File
@@ -1,21 +1,9 @@
# Research note: measured quant recipes of `unsloth/Qwen3.8-Flash-Next-GGUF`
# Research note: quant recipes of `unsloth/Qwen3.8-Flash-Next-GGUF`
Method: GGUF header reads only (HTTP `Range`), no weight downloads · Verified against published file sizes to 4 significant figures
Method: GGUF header reads only (HTTP `Range`), no weight downloads; sizes verified against the
published file sizes to 4 significant figures.
## TL;DR
- Qwen3.8 Flash Next is **176.94 B total / ~6.04 B active** parameters: 125.74 B "normal"
weights (48 layers, 512-expert MoE, Gated DeltaNet + 12 layers of QSA sparse attention)
plus a **51.20 B n-gram/PLE look-up table** (29 % of all params, 0 FLOPs).
- Unsloth's quants only really compress **two things**: the routed-expert `gate`/`up`
matrices and the n-gram table. Everything else stays at Q8_0/Q6_K/F32 in every build.
- Consequence: **file size has a floor (~72 GB) and per-token traffic has a floor (~3.5 GB)**
that are invisible in the quant name. Q2_K_XL → IQ1_S buys 3 % of per-token bandwidth and
costs 0.6 bpw of expert precision — a bad trade.
- MTP speculative decoding trades **+17 % compute for −38 % weight traffic** per token at
batch 1, and is a net loss at ≥8 concurrent streams.
## Model facts (read from the GGUF KV metadata)
## Model facts (from the GGUF KV metadata)
| | |
|---|---|
@@ -28,35 +16,37 @@ Method: GGUF header reads only (HTTP `Range`), no weight downloads · Verified a
| 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) |
Per-token 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),
`ffn_gate_exps/up_exps/down_exps` 48× as `[2560, 640, 512]`-stacked 3-D tensors (838.86 M
params each).
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").
## Method — how to read a quant recipe without downloading anything
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).
`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), KV pairs, then per tensor
`name`, `n_dims`, `dims[]`, `ggml_type` (u32), `offset` (u64). Name + dims + type *is* the
recipe; the tensor data blobs are never touched.
## Reading a recipe without downloading
Four things that bite:
`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.
1. **Split repos.** In a `gguf-split` "magic" 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 the tensors it holds. So
tensor info must be merged from shards 2…N, and KV (`general.file_type`,
`quantize.imatrix.*`) read from shard 1. A scanner that only reads shard 1 reports zero
tensors.
2. **Don't guess the type enum.** Use the real `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) and
`GGML_QUANT_SIZES` for block 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) is what makes the dtype IDs trustworthy.
4. Parse with an offset pointer into the buffer, not `buf = buf[n:]` per field — that is
quadratic on an 11 MB header and looks exactly like a network hang.
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
@@ -74,9 +64,9 @@ Four things that bite:
| UD-IQ1_M | 176.94 B | 74.54 GB | 3.37 |
| UD-IQ1_S | 176.94 B | 72.55 GB | 3.28 |
`L2`/`L46-47` below = layers given one notch more precision (dynamic "UD/XL" selection).
## Recipe matrix
## The 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
@@ -104,15 +94,14 @@ Four things that bite:
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 for reference: 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.
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 are separate recipes: `mtp-*Q8_0` is Q8_0 throughout (indexer BF16, norms F32);
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/pos-embed in F32.
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
@@ -124,11 +113,11 @@ BF16 or F16 only, with biases/pos-embed in F32.
| 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 with the n-gram table removed
## Sizes without the n-gram table
`per_layer_token_embd.weight` is a single 160 × 320 001 536 tensor — 51.20 B params, i.e. 41 %
as many params as the rest of the model combined. It takes only three settings across the whole
repo: BF16 (102.4 GB), Q8_0 (54.4 GB) and IQ4_NL (28.8 GB).
`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 |
|---|---|---|---|---|---|
@@ -144,13 +133,12 @@ repo: BF16 (102.4 GB), Q8_0 (54.4 GB) and IQ4_NL (28.8 GB).
| 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 % |
Strip the table and the ladder is a genuine 2.8-8.5 bpw spread instead of the flat 3.3-8.5 the
file sizes suggest.
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 actually touched (routed experts at 10/512, embedding and
n-gram tables as look-ups):
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 |
|---|---|---|---|
@@ -167,14 +155,14 @@ n-gram tables as look-ups):
| 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 reproduces Qwen's advertised "6B activated"; 125.74 B reproduces "125B". Two thirds of
the active mass is dense (DeltaNet + gated residual + attention), not expert — so this behaves
like a bandwidth-bound 6 B dense model wearing a 177 B memory footprint, not like a normal MoE.
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 real work (`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**,
of which 82 % is the output projection.
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) |
|---|---|---|
@@ -186,8 +174,8 @@ of which 82 % is the output projection.
## 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). MTP row uses
`shared-Q8_0` draft, llama.cpp's `--spec-draft-n-max 2`, mean accepted length 2.76.
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 |
|---|---|---|---|---|---|
@@ -205,53 +193,51 @@ of which 82 % is the output projection.
## Analysis
1. **Quantisation here is applied to the expert FFNs and the n-gram table; nothing else
matters.** The other 3.6 B params sit at 7-32 bpw in every build and cost 3-4 GB total.
2. **`down_proj` is protected, `gate`/`up` is the sacrifice.** Down never drops below 4.5 bpw
and is still full Q8_0 at Q6_K_XL/Q5_K_XL; at IQ1_S the down tables cost *more* bytes
(22.6 GB) than the gate+up tables (17.2 GB). Sensible — down-projection error is applied
after the nonlinearity and summed across the 10 active experts.
3. **Router is never quantised** (F32 everywhere), nor is the QSA indexer (BF16 everywhere,
20 M params). Both are small and both fail catastrophically when wrong.
4. **Layer 2 is special 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 an identical "important down-expert" set across
Q4_K_XL, Q3_K_XL and IQ4_XS, so the ranking comes from the calibration run, not from a
per-target heuristic.
5. **The 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 offered 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 real constraint.** 51.2 B params at a 4.5 bpw floor = 28.8 GB that
never shrinks, 71 % of the IQ1_S file when combined with the down tables. Nothing in this
repo goes under ~72 GB. It is a pure random look-up (≈ 1.4 KB/token, 2 560 values), so it is
a VRAM cost, not a bandwidth cost — the one component that is genuinely free to park in CPU
RAM or on disk.
7. **MTP is a bandwidth-only trade.** +17 % compute (7.81 vs 6.67 B active params per token)
for −38 % weight traffic. Its hidden cost is that a 3-position verify pass touches ~29 of
512 experts per layer instead of 10, so MTP stops paying the moment concurrency saturates
the experts: unsloth measures Q4_K_XL at 83 → 139 tok/s with 1 user but 216 → 192 tok/s
*worse* with 8 users.
8. **Value points.** Q4_K_XL (5.03 bpw, 111 GB) is the best engineering point. Below it,
each step buys surprisingly little traffic: Q2_K_XL → IQ1_S is 3 % of per-token bandwidth
for 0.6 bpw of expert precision, and IQ1_S additionally under-delivers in practice (1.34×
vs 1.74× modelled) because 1.5 bpw IQ1_S is dequant-bound. Take IQ1_M over IQ1_S if 74.5 GB
fits — 2 GB more for +0.2 bpw. For MTP, use a `shared-*` draft: identical runtime cost,
~1.3 GB less resident weight, and the draft's output projection is then read at the *main*
model's precision.
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.
## What the imatrix says
## The imatrix
`imatrix_unsloth.gguf` (580 MB, in the repo 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`
`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,
being the same input. There is nothing for `blk.48`, `output`, `token_embd` or the n-gram table.
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:
**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 |
|---|---|---|---|
@@ -261,40 +247,38 @@ of it in one or two channels -- up to 208 000x that expert's median channel:
| 46 | 290 | 6.9 % | 0.84 % |
| 30 | 169 | 3.9 % | 0.12 % |
Those are exactly the five layers given Q8_0 down. The next layers by energy share (28, 37, 26:
~4 %) are heavily *routed* experts, energy share equal to routing share, and are not protected. A
super expert is **not harder to quantise relative to its own output** -- scored 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 simply that much larger, so the same relative error is a large
absolute one. A GGUF type is per tensor and a tensor is all 512 experts of a layer, so protecting
one expert costs the whole layer's `down`.
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: the pool *is*
the super expert there); `gate_up` 0.91-0.98. `down`'s input channels are each expert's own
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.
**Against 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), and so
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 -- the super experts
there never fired on its corpus. Open: either the imatrix harness (raw 18K-token chunks, each from
**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 at 9/25 (e368 c191), 14/30 (e169 c72) and 16/32 (e391 c139).
(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 shipped files as published when read (2026-09-30); later uploads
to the repository may differ. They say nothing about the *quality* of each level, which needs a
downstream eval.
- Percentages inside a cell are byte shares of that tensor group.
- 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 over-estimated.
- Mean accepted length 2.76 and 66 % acceptance are from a single unsloth log line
(`shared-Q8_0` draft + `Q4_K_XL`, 4× A100, 8 K input, llama.cpp's `--spec-draft-n-max 2`),
applied to every build here.
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.