Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
@@ -0,0 +1,334 @@
|
||||
# Architectures — the geometry, and the traps that stay plausible when wrong
|
||||
|
||||
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.
|
||||
|
||||
| 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/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 |
|
||||
|
||||
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 rule that applies to all of them
|
||||
|
||||
**`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.
|
||||
|
||||
---
|
||||
|
||||
# `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`.
|
||||
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
# `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.8-27B-FP8, exactly
|
||||
|
||||
```
|
||||
64 layers, full_attention_interval 4 -> layers 3,7,...,63 are FULL ATTENTION (16 of them)
|
||||
the other 48 are GATED DELTA NET
|
||||
hidden_size 5120 intermediate_size 17408 vocab_size 248320
|
||||
num_attention_heads 24 num_key_value_heads 4 head_dim 256 -> GQA 6
|
||||
attn_output_gate true -> gated attention
|
||||
partial_rotary_factor 0.25 -> RoPE over 64 of the 256 head dims
|
||||
mrope_interleaved true, mrope_section [11, 11, 10] -> MROPE, not plain rope
|
||||
rope_theta 1e7 rms_norm_eps 1e-6 max_position_embeddings 262144
|
||||
|
||||
linear_num_key_heads 16 linear_key_head_dim 128
|
||||
linear_num_value_heads 48 linear_value_head_dim 128 -> GDN GQA 3:1
|
||||
linear_conv_kernel_dim 4 mamba_ssm_dtype float32 output_gate_type swish
|
||||
mtp_num_hidden_layers 1 tie_word_embeddings false
|
||||
quantization: fp8 e4m3, activation_scheme "dynamic", per-weight `weight_scale_inv`
|
||||
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.
|
||||
|
||||
| model geometry | libr4d entry point |
|
||||
|---|---|
|
||||
| head_dim 256, GQA 6, paged block 16 | `attn_prefill_h256_gqa6_*`, `attn_decode_h256_gqa6_*` |
|
||||
| linear k128 / v128, chunk 64 | `gdn_chunk_scan_k128_v128_c64_bf16`, `gdn_kkt_solve_k128_c64_bf16` |
|
||||
| conv width 4, k128 | `gdn_conv_prep_w4_h128_bf16`, `gdn_conv_update_w4_h128_bf16` |
|
||||
| recurrent state fp32 | `gdn_recurrent_update_k128_v128_bf16_fp32state` |
|
||||
| gated attention, interleaved q/gate | `qk_norm_rope_gate` (reads the q/gate interleave off the operand's row pitch) |
|
||||
| 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
|
||||
|
||||
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.
|
||||
|
||||
**Full-attention layer** (`model.language_model.layers.N.`):
|
||||
```
|
||||
input_layernorm.weight post_attention_layernorm.weight
|
||||
self_attn.q_proj.weight (+_scale_inv) [5120, 12288] = 24 heads x 256 x 2, query and GATE
|
||||
self_attn.k_proj.weight (+_scale_inv) [5120, 1024]
|
||||
self_attn.v_proj.weight (+_scale_inv) [5120, 1024]
|
||||
self_attn.o_proj.weight (+_scale_inv) [6144, 5120]
|
||||
self_attn.q_norm.weight [256] self_attn.k_norm.weight [256]
|
||||
mlp.{gate,up}_proj.weight (+_scale_inv) [5120, 17408]
|
||||
mlp.down_proj.weight (+_scale_inv) [17408, 5120]
|
||||
```
|
||||
|
||||
**Linear (GDN) layer**:
|
||||
```
|
||||
input_layernorm.weight post_attention_layernorm.weight
|
||||
linear_attn.in_proj_qkv.weight (+_scale_inv) [5120, 10240] = 2*16*128 + 48*128
|
||||
linear_attn.in_proj_z.weight (+_scale_inv) [5120, 6144] = 48*128
|
||||
linear_attn.in_proj_a.weight [5120, 48]
|
||||
linear_attn.in_proj_b.weight [5120, 48]
|
||||
linear_attn.conv1d.weight [10240, 1, 4]
|
||||
linear_attn.A_log [48] linear_attn.dt_bias [48] linear_attn.norm.weight [128]
|
||||
linear_attn.out_proj.weight (+_scale_inv) [6144, 5120]
|
||||
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`.
|
||||
|
||||
## The 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.
|
||||
|
||||
```
|
||||
qg = gemm(x, q_proj) [n_tok, 12288]
|
||||
k, v = gemm(x, k_proj), gemm(x, v_proj) [n_tok, 1024]
|
||||
q = rmsnorm(view(qg, off 0, pitch 512), q_norm) per head, over 256
|
||||
k = rmsnorm(k, k_norm) per head
|
||||
gate = view(qg, off 256, pitch 512)
|
||||
q, k = mrope(q, k, positions, sections [11,11,10], rotary dims 64 of 256)
|
||||
o = attn_paged(q, k, v) scale = 1/sqrt(256)
|
||||
o = o * sigmoid(gate) <-- the gate. output_gate_type "swish" names the
|
||||
GDN gate, not this one; this one is a sigmoid
|
||||
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.
|
||||
|
||||
## The linear layer — gated delta net
|
||||
|
||||
```
|
||||
qkv = gemm(x, in_proj_qkv) [n_tok, 10240]
|
||||
z = gemm(x, in_proj_z) [n_tok, 6144]
|
||||
b = sigmoid(gemm(x, in_proj_b)) [n_tok, 48] -> beta
|
||||
a = gemm(x, in_proj_a) [n_tok, 48]
|
||||
g = softplus(a + dt_bias) * A_log_term
|
||||
conv = silu(causal_conv1d(qkv, conv1d, conv_state)) depthwise, width 4, 10240 channels
|
||||
q,k,v = strided views of conv: q at 0 (16x128), k at 2048 (16x128), v at 4096 (48x128)
|
||||
q, k = l2_norm(q), l2_norm(k) <-- L2, NOT rmsnorm
|
||||
o = delta rule: chunked scan at prefill, recurrent update at decode
|
||||
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.
|
||||
|
||||
## Things that stay plausible when wrong, so get them right
|
||||
|
||||
- **`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.
|
||||
- **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.
|
||||
|
||||
## KV groups
|
||||
|
||||
Three of them, which is why hybrid KV groups are first-class rather than an extension:
|
||||
|
||||
| group | kind | geometry |
|
||||
|---|---|---|
|
||||
| full attention | `RAD_KV_FULL` | 16 layers, head_dim 256, 4 KV heads; block size from the resolved kernel |
|
||||
| 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`.
|
||||
|
||||
## 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.
|
||||
|
||||
**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
|
||||
`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 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.
|
||||
|
||||
## `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.
|
||||
|
||||
---
|
||||
|
||||
# `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.
|
||||
|
||||
```
|
||||
48 layers of 12 x (3 x GatedDeltaNet -> MoE, then 1 x QSA -> MoE)
|
||||
hidden_size 2560 hc_count 4 -> the residual stream is 10240
|
||||
512 experts of 640 at top-10, plus a shared expert of 640
|
||||
24 query heads, 2 KV heads, head_dim 256 -> GQA 12
|
||||
vocab 248320 max_position_embeddings 262144
|
||||
indexer_n_heads 4 indexer_head_dim 128 indexer_budget 2048 indexer_compress_ratio 4
|
||||
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.
|
||||
|
||||
**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 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.
|
||||
|
||||
**Four-bit experts are what make it fit.** 512 experts of 640 over 48 layers is 112.8 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
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
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
|
||||
|
||||
**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.
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
# 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 7.2. It does not need ROCm itself, 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
|
||||
other cards or another commit. The examples below use `radiance`, the tag a local build gets; with
|
||||
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.
|
||||
|
||||
## Build the image
|
||||
|
||||
```sh
|
||||
docker/build.sh # HEAD, tagged radiance:<version>, radiance:<commit>, radiance:latest
|
||||
docker/build.sh -s gpu-host # stream the commit over ssh; gpu-host builds and keeps the image
|
||||
docker/build.sh -j 8 # cap compile jobs (a device kernel takes 2-3 GB under hipcc)
|
||||
docker/build.sh -t 'gfx1200;gfx1201' # GPU architectures to compile kernels for (default gfx1201)
|
||||
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 `Dockerfile` has three 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 |
|
||||
| `build` | `rocm/dev-ubuntu-24.04:7.2.4` plus cmake, ninja and g++-14. 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` | `ctest -LE gpu`: every suite that runs without a card. The image is only produced if they 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, `amdgpu.ids`, and a static busybox. 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 single file is comgr (about 150 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.
|
||||
|
||||
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.
|
||||
|
||||
The ROCm version in the image has to be one the host's kernel driver supports. It is a build
|
||||
argument (`ROCM_VERSION`, default 7.2.4).
|
||||
|
||||
The GPU suites (`mem_test`, `r4d_selftest`, `kbench`) need the card to themselves. They run from
|
||||
the `build` stage:
|
||||
|
||||
```sh
|
||||
docker/build.sh --target build
|
||||
docker run --rm --device /dev/kfd --device /dev/dri --security-opt seccomp=unconfined \
|
||||
radiance-build ctest --test-dir /build -L gpu --output-on-failure
|
||||
```
|
||||
|
||||
## 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
|
||||
`/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 \
|
||||
--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)" \
|
||||
-v /srv/models/rad:/models:ro \
|
||||
radiance --model /models/m.rad --tp 2 --host :: --port 8000
|
||||
```
|
||||
|
||||
Every one of these options is needed:
|
||||
|
||||
- **`--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.
|
||||
- **`--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.
|
||||
|
||||
**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 \
|
||||
-e RADIANCE_HOME=/plugins:/opt/radiance/share/radiance \
|
||||
radiance --model /models/m.rad
|
||||
```
|
||||
|
||||
`/plugins` holds any of `kernels/`, `architectures/` and `quantizers/`, built against the same
|
||||
radiance version (`docs/PLUGIN.md` §13). The engine in the image starts on any AMD GPU family: the
|
||||
image's `GPU_TARGETS` are what its bundled kernel library, libr4d, is compiled for, not a limit on
|
||||
the cards the engine runs on.
|
||||
|
||||
## Compose
|
||||
|
||||
`deploy/compose/` has one file per model and a `common.yaml` that each of them extends:
|
||||
|
||||
| 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-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-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 |
|
||||
| `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 |
|
||||
|
||||
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`), a writable state directory (`/data`, where
|
||||
the prefix cache's disk tier lives), the API key, the port, and the user and GPU groups the server
|
||||
runs as. Then:
|
||||
|
||||
```sh
|
||||
docker compose -f flashnext.yaml up -d # start; restarts with the Docker daemon
|
||||
docker compose -f flashnext.yaml logs -f # follow the log
|
||||
docker compose -f flashnext.yaml down # stop
|
||||
```
|
||||
|
||||
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`, so the files it writes under `/data`
|
||||
belong to that user. `/health`, `/ping` and the dashboard page answer without the API key, and the
|
||||
health check fetches `/health` with busybox's `wget`.
|
||||
+1267
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,107 @@
|
||||
# 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.
|
||||
|
||||
## The host backend is the primary target, not a fallback
|
||||
|
||||
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
|
||||
|
||||
```
|
||||
abi/ THE ABI, and all a plugin compiles against. Frozen — do not edit quietly
|
||||
core/rad_internal.h shared internals: logging, Geometry, constraint matching
|
||||
core/util/ logging, error strings, dtype arithmetic, tensor helpers: the bedrock
|
||||
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
|
||||
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/text/ tokeniser, chat template, tool parsing, detokenisation
|
||||
core/mm/ image and video decoding, and the processor that turns frames into patches
|
||||
core/format/ the .rad reader and writer, safetensors, recipes, the imatrix, the tune cache
|
||||
core/server/ HTTP, OpenAI-compatible endpoints, /metrics, the dashboard
|
||||
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
|
||||
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
|
||||
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
|
||||
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
|
||||
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.
|
||||
|
||||
## Build
|
||||
|
||||
```sh
|
||||
cmake -S . -B build -G Ninja # host backend; no ROCm required
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
**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.
|
||||
|
||||
**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).
|
||||
|
||||
**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.
|
||||
|
||||
**`rad_memset_async` refuses `RAD_MEM_HOST` on a card, and 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.
|
||||
|
||||
**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`.
|
||||
|
||||
**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`.
|
||||
|
||||
**Naming.** `rad_` prefix on everything with external linkage. Files are named for what they
|
||||
provide. `snake_case` for functions and variables, `PascalCase` for types.
|
||||
+1851
File diff suppressed because it is too large.
Load diff
+394
@@ -0,0 +1,394 @@
|
||||
# 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.
|
||||
|
||||
## 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"):
|
||||
|
||||
| | all: mean KL | all: top-1 | text + assistant: mean KL | text + assistant: top-1 |
|
||||
|---|---|---|---|---|
|
||||
| int4 `-8..7`, round to nearest, E4M3 trunk (`qwen4exp-w4-hc8m.recipe`) | 0.1357 | 90.35% | 0.0440 | 92.46% |
|
||||
| `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% |
|
||||
| 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.
|
||||
|
||||
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.
|
||||
|
||||
**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):
|
||||
|
||||
| | all: mean KL | all: top-1 | text + assistant | system / user |
|
||||
|---|---|---|---|---|
|
||||
| served | 0.0789 | 92.85% | 0.0239 | 0.2732 |
|
||||
| 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.
|
||||
|
||||
**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).
|
||||
|
||||
**Further quality levers**, in order: five bits on both projections of layers
|
||||
16-31 (the same +8% as the down projections, ~0.066 expected); fewer layers at five bits for a
|
||||
smaller prefill cost; and `--expert-vs-cache-ratio`, which buys the residency back with KV
|
||||
capacity. The formats, the kernel and a layer's own choice of form are all in the tree.
|
||||
|
||||
## 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.
|
||||
|
||||
The encodings are **not interchangeable**:
|
||||
|
||||
| encoding | kernel dtype | what it means |
|
||||
|---|---|---|
|
||||
| `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 |
|
||||
|
||||
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 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 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:
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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:
|
||||
|
||||
| | gate_up | down |
|
||||
|---|---|---|
|
||||
| `-8..7`, scale amax/8 | 0.0889 | 0.1048 |
|
||||
| `-8..7`, searched scale | 0.0849 | 0.1005 |
|
||||
| `w4nl`, searched scale | 0.0755 | 0.0896 |
|
||||
| `-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).
|
||||
|
||||
## Finer groups at the same bytes: 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.
|
||||
|
||||
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):
|
||||
|
||||
| | gate_up | down | bits a 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 |
|
||||
|
||||
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.
|
||||
|
||||
## Five bits where the error is: 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.
|
||||
|
||||
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:
|
||||
|
||||
| | 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.)
|
||||
|
||||
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.
|
||||
|
||||
**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
|
||||
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.
|
||||
|
||||
## Rotation alone is expected to be worse
|
||||
|
||||
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.
|
||||
|
||||
## Calibration, and why it is a separate run
|
||||
|
||||
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:
|
||||
|
||||
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 own error puts on the
|
||||
activation, which is what makes step 2 legitimate.
|
||||
|
||||
**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, and `--expert-vs-cache-ratio 0.5` so the cache share holds 64 sequences'
|
||||
recurrent state. That records ~930 tokens a second, ten million tokens in three hours.
|
||||
|
||||
**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.
|
||||
|
||||
```sh
|
||||
# 1. the uncalibrated container: the recipe's expert rule is rtn, int4 g128 rotated
|
||||
rad-convert <checkpoint> -o model-absmax.rad --recipe data/recipes/qwen4exp-w4.recipe
|
||||
|
||||
# 2. the calibration run. Stops at RADIANCE_CALIB_TOKENS (default 65536) and writes once.
|
||||
RADIANCE_CALIB_DIR=<calib dir> RADIANCE_CALIB_TOKENS=65536 \
|
||||
radiance --model model-absmax.rad ...
|
||||
# ...then drive prompts at max_tokens=1 until it prints
|
||||
# radiance: calibration wrote layer Hessians after N tokens to <calib dir>
|
||||
|
||||
# 3. the calibrated convert: a --quant rule ahead of the recipe's own puts the experts through
|
||||
# GPTQ against calib=$CALIB (a recipe whose expert rule names calib=$CALIB itself, as the
|
||||
# production one does, needs no --quant)
|
||||
CALIB=<calib dir> rad-convert <checkpoint> -o model-gptq.rad \
|
||||
--recipe data/recipes/qwen4exp-w4.recipe --reuse model-absmax.rad \
|
||||
--quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB'
|
||||
```
|
||||
|
||||
`--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.
|
||||
|
||||
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.
|
||||
|
||||
**`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.
|
||||
|
||||
Three things about the tap worth knowing before reading its 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.
|
||||
|
||||
## 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
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
## 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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
## What is measured
|
||||
|
||||
- `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.
|
||||
- `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
|
||||
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.
|
||||
- `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.
|
||||
+1405
File diff suppressed because it is too large.
Load diff
+473
@@ -0,0 +1,473 @@
|
||||
# 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:
|
||||
|
||||
- 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 **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`).
|
||||
|
||||
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. The shape of it
|
||||
|
||||
```c
|
||||
#include "rad_abi.h" /* required */
|
||||
#include "rad_plugin.h" /* optional helpers -- see §6 */
|
||||
|
||||
uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
|
||||
const RadPluginInfo* rad_plugin_info(void) {
|
||||
static const RadPluginInfo i = {
|
||||
RAD_PLUGIN_KERNEL, "mykernels", "0.1", "a GEMM or two", "gfx1100",
|
||||
};
|
||||
return &i;
|
||||
}
|
||||
|
||||
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 */
|
||||
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).
|
||||
|
||||
`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).
|
||||
|
||||
Four more exports are optional, each looked up by exactly this name:
|
||||
|
||||
| symbol | says |
|
||||
|---|---|
|
||||
| `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 |
|
||||
| `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_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 |
|
||||
|
||||
---
|
||||
|
||||
## 2. A kernel says what it can serve, not what it is
|
||||
|
||||
```c
|
||||
static const RadConstraint c_gemm[] = {
|
||||
RAD_CLE("M", 64), /* M <= 64 */
|
||||
RAD_CDIV("K", 128), /* K divisible by 128 */
|
||||
RAD_CIN("dtype", "fp8a8 w4a8") /* dtype in that set */
|
||||
};
|
||||
|
||||
static const RadKernelInfo k[] = {{
|
||||
.name = "mygemm_m64", .op = "gemm_nt_q", .family = "gemm",
|
||||
.computes = "row-major A times column-major B, fp8 in, bf16 out",
|
||||
.shape = "M<=64, K%128==0",
|
||||
.dtypes = "fp8a8, w4a8",
|
||||
.domain = RAD_DOMAIN_DEVICE,
|
||||
.priority = 50,
|
||||
.constraints = c_gemm, .n_constraints = 3,
|
||||
.launch = my_launch,
|
||||
}};
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
Two consequences worth internalising:
|
||||
|
||||
- **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.
|
||||
|
||||
`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.
|
||||
|
||||
---
|
||||
|
||||
## 3. Operand extents are a request, not a bound
|
||||
|
||||
`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.
|
||||
|
||||
> 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.
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 4. The optional hooks, and what each one buys
|
||||
|
||||
None are required. Each one is a claim, and the engine will use it.
|
||||
|
||||
| hook | says |
|
||||
|---|---|
|
||||
| `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 |
|
||||
| `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` 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.
|
||||
|
||||
`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.
|
||||
|
||||
`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.
|
||||
|
||||
---
|
||||
|
||||
## 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:
|
||||
|
||||
- `hipLaunchKernel`, and therefore `<<<>>>` and `hipLaunchKernelGGL`;
|
||||
- `hipMemcpyAsync`, `hipMemcpy2DAsync`, `hipMemsetAsync`;
|
||||
- `hipGetLastError` / `hipPeekAtLastError`, with HIP's own 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.
|
||||
|
||||
The code object is read by the engine too, which puts limits on what a kernel may be:
|
||||
|
||||
- **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;
|
||||
- **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.
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 6. `rad_plugin.h` is optional, and one part of it is not merely convenience
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 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.
|
||||
|
||||
An op that stays inside `docs/OPS.md` is describable by the reference, and therefore checkable,
|
||||
even when your kernel cannot describe itself.
|
||||
|
||||
---
|
||||
|
||||
## 8. The one contract an architecture plugin gets silently wrong
|
||||
|
||||
If you write an **architecture** plugin with a linear/recurrent block, read `spec.md` §10 before
|
||||
you write 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.
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 9. Checking your work
|
||||
|
||||
`rad-kbench` is the answer to "is my library correct, complete and fast", and it needs no 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:
|
||||
|
||||
- **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.
|
||||
- **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:
|
||||
|
||||
- **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.
|
||||
|
||||
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.
|
||||
|
||||
- `--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.
|
||||
|
||||
---
|
||||
|
||||
## 10. A library for a card radiance has never seen
|
||||
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
**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`.
|
||||
|
||||
**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; `--vram-kv-mib` and
|
||||
`--vram-weights-mib` state the pools outright.
|
||||
|
||||
**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 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.
|
||||
- **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.
|
||||
|
||||
---
|
||||
|
||||
## 11. Architecture plugins
|
||||
|
||||
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.
|
||||
|
||||
```c
|
||||
const char* rad_arch_id(void); /* "llama" -- what a container's header names */
|
||||
const char* rad_arch_quant(void); /* optional: "" unquantised, or the descriptor served */
|
||||
int rad_arch_declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx);
|
||||
void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch);
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); /* optional */
|
||||
const RadChatFormat* rad_arch_chat_format(const RadModelMeta* meta); /* optional */
|
||||
```
|
||||
|
||||
`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.
|
||||
|
||||
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`.
|
||||
- **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.
|
||||
|
||||
---
|
||||
|
||||
## 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`:
|
||||
|
||||
```c
|
||||
int rad_quant_count(void);
|
||||
const RadQuantizerInfo* rad_quant_at(int i); /* name, 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:
|
||||
|
||||
```
|
||||
# PATTERN QUANTISER OPTIONS
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
## 13. Building, installing, and the search path
|
||||
|
||||
```cmake
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(mykernels LANGUAGES CXX HIP) # CXX alone for a host-only plugin
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults() # C++20, an optimising build type unless one was asked for
|
||||
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.
|
||||
|
||||
`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
|
||||
`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.
|
||||
|
||||
**`$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:
|
||||
|
||||
```sh
|
||||
RADIANCE_HOME=$HOME/radiance-plugins:/opt/radiance/share/radiance radiance --model ...
|
||||
```
|
||||
|
||||
and 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: `--kernels
|
||||
mykernels,libr4d` puts you in front. An entry matches a plugin's name or its file stem, and **the
|
||||
list is comma-separated** — the tools also accept colons, the engine's `--kernels` and
|
||||
`$RADIANCE_KERNELS` do not, so write commas everywhere. A library on the search path that nobody
|
||||
named loads after everything named, and a reference library (§1) after that.
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
# 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.
|
||||
|
||||
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 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:
|
||||
|
||||
```
|
||||
model.language_model.layers.<L>.self_attn.indexer.index_qk_proj.weight [640, 2560]
|
||||
model.language_model.layers.<L>.self_attn.indexer.q_layernorm.weight [128]
|
||||
model.language_model.layers.<L>.self_attn.indexer.k_layernorm.weight [128]
|
||||
```
|
||||
|
||||
640 = (4 query heads + 1 key head) x 128.
|
||||
|
||||
## What it computes
|
||||
|
||||
```
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
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
|
||||
(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 one thing the reference hides
|
||||
|
||||
**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.
|
||||
|
||||
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.
|
||||
|
||||
## The 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".
|
||||
|
||||
## How the attention reads 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.
|
||||
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
## Where the block keys live, and why it decides everything downstream
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
| 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 |
|
||||
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
## The tail is state, and storing it as scratch fails three ways
|
||||
|
||||
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 tail stored as… | what it does | fires 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 |
|
||||
|
||||
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.
|
||||
|
||||
**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.
|
||||
|
||||
## Selecting per query, which is what prefill needs
|
||||
|
||||
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.
|
||||
|
||||
**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 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`.
|
||||
|
||||
## What the indexer costs
|
||||
|
||||
**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 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`.
|
||||
|
||||
**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.
|
||||
|
||||
**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.
|
||||
|
||||
## Checking it
|
||||
|
||||
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:
|
||||
|
||||
- **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.
|
||||
|
||||
**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.
|
||||
+626
@@ -0,0 +1,626 @@
|
||||
# Radiance — tools reference
|
||||
|
||||
Every flag of every tool, with examples. For getting started, read [GUIDE.md](GUIDE.md) first.
|
||||
|
||||
Six binaries are installed beside `radiance`, plus the shell harnesses in `scripts/`:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| [`rad-info`](#rad-info) | print what a `.rad` container holds. Loads no plugins |
|
||||
| [`rad-convert`](#rad-convert) | safetensors or GGUF in, `.rad` out, quantised by a recipe |
|
||||
| [`rad-kbench`](#rad-kbench) | correctness, completeness and speed of every kernel library |
|
||||
| [`rad-tune`](#rad-tune) | benchmark each kernel's tunable space at this model's shapes, on this machine |
|
||||
| [`rad-schemas`](#rad-schemas) | print and diff the op schemas plugins declare |
|
||||
| [`rad-tokcheck`](#rad-tokcheck) | hold the tokeniser to its reference encoder and to HuggingFace's ids over real text, and time it |
|
||||
| [`radiance --kld-*`](#the-kl-mode) | KL divergence of a quantised model against the bf16 one, at every position of a corpus |
|
||||
| [`scripts/`](#the-shell-harnesses) | bring a model up, measure it, assert on what comes back |
|
||||
|
||||
Three of them — `rad-convert`, `rad-kbench`, `rad-tune` — **are the engine's startup with a
|
||||
different last step**. They load the same plugins in the same hierarchy and run the same declare
|
||||
phase. A tool that resolved kernels differently from the engine would be a tool whose answers are
|
||||
about a different program.
|
||||
|
||||
Every tool that loads plugins honours `RADIANCE_HOME` and `RADIANCE_KERNELS`.
|
||||
|
||||
---
|
||||
|
||||
## rad-info
|
||||
|
||||
```
|
||||
rad-info [options] <model.rad>
|
||||
|
||||
-v, --verbose list every tensor, not just the per-unit summary
|
||||
--meta print the metadata table and stop
|
||||
--vocab print the vocab summary and its normaliser chain, and stop
|
||||
--profile N print the top N entries of the expert profile (default 20, 0 = all)
|
||||
--recipe print the recipe the container was converted with, and stop
|
||||
```
|
||||
|
||||
This is the tool you reach for when something is wrong, so it is written for reading: aligned
|
||||
columns, byte counts in human units, and every number that could mislead labelled with what it
|
||||
actually counts. **It opens the container read-only and loads no plugins** — a container names no
|
||||
kernel library, so there is nothing to load.
|
||||
|
||||
```sh
|
||||
rad-info flashnext-w4.rad
|
||||
```
|
||||
|
||||
```
|
||||
flashnext-w4.rad
|
||||
format RAD2, 166.4 GiB, little-endian
|
||||
architecture qwen4exp
|
||||
model Qwen3.8-Flash-Next
|
||||
source quant (none)
|
||||
recipe 14 line(s) -- --recipe prints it
|
||||
created by rad-convert ...
|
||||
|
||||
section offset bytes count
|
||||
strings 256 1.2 MiB -
|
||||
metadata 1258752 8.4 KiB 214
|
||||
directory ...
|
||||
planes ...
|
||||
encodings ...
|
||||
data ... 166.1 GiB ...
|
||||
```
|
||||
|
||||
Every weight is listed with its **encoding** — `fp8_e4m3*bf16[128x128]`, `i4*bf16[1x128]/fwht128`,
|
||||
`bf16` — its logical shape, and what made it: the checkpoint as it stood, or the quantiser and
|
||||
options of the recipe rule that matched. The totals are by encoding and by quantiser.
|
||||
|
||||
```sh
|
||||
rad-info --meta m.rad # the metadata table alone
|
||||
rad-info --vocab m.rad # vocab + normaliser chain
|
||||
rad-info --recipe m.rad # the recipe, expanded, one rule a line
|
||||
rad-info -v m.rad | head -40 # every tensor, its encoding, shape and planes
|
||||
rad-info --profile 0 m.rad # the whole expert-popularity profile
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## rad-convert
|
||||
|
||||
```
|
||||
rad-convert [options] <input> -o <model.rad>
|
||||
|
||||
<input> a .gguf, a .safetensors, an index.json, or a checkpoint directory
|
||||
-o, --out FILE the container to write
|
||||
--recipe FILE the quantisation recipe (below)
|
||||
--quant RULE 'PATTERN=QUANTISER:key=value,...', ahead of the recipe's rules. Repeatable
|
||||
--list-quantizers every quantiser loaded and the options it takes
|
||||
--arch ID override the architecture id from the checkpoint
|
||||
--home DIR $RADIANCE_HOME
|
||||
--kernels A:B kernel plugin hierarchy, first wins. Default $RADIANCE_KERNELS
|
||||
--tokenizer F tokenizer.json; its declared chain is baked instead of being
|
||||
reconstructed from a pre-tokenizer name
|
||||
--imatrix F llama.cpp imatrix: expert profile, column importances, error weighting
|
||||
--set K=V a metadata key, seen by declare AND written into the container. Repeatable
|
||||
--max-tok N the max_tok declare is run at (default 8192)
|
||||
--max-ctx N the context bound declare is run at. Default: the checkpoint's
|
||||
training context
|
||||
--draft-model DIR a SECOND checkpoint: a drafter that ships as its own repository
|
||||
--kv-cache-dtype T bf16 | fp8, the cache width declare is run at. Default: the first
|
||||
at which every op resolves; the container is the same at either
|
||||
--max-spec N the max_spec declare is run at (default 4, or the block a drafter
|
||||
states). 0 leaves the draft head out
|
||||
--reuse FILE copy every weight an earlier container holds identically
|
||||
--in-place with --reuse: extend that container instead of writing a new one
|
||||
--plan-only declare, plan every weight's encoding, print the plan, then STOP
|
||||
--report N the worst N quantisation errors to print (default 20)
|
||||
-v, --verbose
|
||||
```
|
||||
|
||||
### What it does
|
||||
|
||||
A container holds each weight as the **canonical planes of its encoding** — codes, scales, zero
|
||||
points, a codebook — row-major, and no kernel library is named anywhere in it. The kernels
|
||||
rearrange those planes into their own layouts when the model loads, so a kernel library can change
|
||||
any layout it has without a reconvert. What rad-convert decides is the *numbers*:
|
||||
|
||||
1. Reads the checkpoint's `config.json` (or GGUF metadata).
|
||||
2. Loads the architecture, kernel and quantiser plugins and runs **declare** — the same phase the
|
||||
engine runs. The architecture plugin's name map says which checkpoint tensors make each declared
|
||||
weight; `rad_weight_encoding` answers each one with the encoding the **recipe** gives it.
|
||||
3. Every op resolves, and every resolved kernel's `layout` hook is asked about the planned encoding.
|
||||
A recipe nothing can serve is refused here, before a byte is written.
|
||||
4. Writes each logical weight once: the checkpoint's own bytes where no rule matches, or the planes
|
||||
the matching rule's quantiser writes, a block of rows at a time.
|
||||
5. Measures every quantised weight against its source through the core's decoder and prints the
|
||||
worst, imatrix-weighted when `--imatrix` is given.
|
||||
6. Bakes in the tokeniser, the chat template, the metadata, the recipe and any draft head.
|
||||
|
||||
### Recipes
|
||||
|
||||
Ordered rules from a logical weight name to a quantiser and its options. **The first rule whose
|
||||
pattern matches decides**; a weight no rule matches keeps the checkpoint's encoding, which has to be
|
||||
one the engine serves as it is — bf16, f16, f32, or block-scaled FP8 (`X.weight` with
|
||||
`X.weight_scale_inv`). Anything else is named and refused.
|
||||
|
||||
```
|
||||
# PATTERN QUANTISER OPTIONS
|
||||
blk.*.ffn_*_exps.*.weight gptq codes=i4 group=128 scale=bf16 transform=fwht128 calib=$CALIB
|
||||
blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4
|
||||
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
```
|
||||
|
||||
A pattern is a glob over the whole name (`*` crosses dots, `?` is one character). `$NAME` in an
|
||||
option is the environment's, and an unset one is refused. `--quant` adds rules on the command line,
|
||||
ahead of the file's: `--quant 'output.weight=rtn:codes=fp8_e4m3,block=128x128,scale=bf16'`.
|
||||
A quantiser that declines a weight — `rtn` declines a rank-1 tensor, so a pattern that happens to
|
||||
match a norm keeps the norm as it is — leaves it to the checkpoint's encoding.
|
||||
|
||||
`rad-convert --list-quantizers` prints every quantiser and its options. The built-in set is
|
||||
`libquant`:
|
||||
|
||||
| quantiser | |
|
||||
|---|---|
|
||||
| `rtn` | round to nearest on a grid; the scale of each block chosen by `rule` |
|
||||
| `gptq` | error feedback against the layer's input Hessian (`calib=DIR`, damped by `damp`, default 0.01 of its mean diagonal), scales fixed from the weight first; `act_order=1` quantises the columns by descending input energy and stores the permutation as the encoding's `perm` transform; `cd=N` adds N sweeps of coordinate descent after the loop, every code re-chosen at its conditional optimum against the same Hessian |
|
||||
| `awq` | each input column scaled by its activation magnitude to a searched power, then a per-block clip search, both against the Hessian; the column scales are the encoding's last scale level |
|
||||
| `autoround` | sign-gradient descent on a rounding offset a value and a range factor a block, against the Hessian; `iters` steps of N·K² multiply-adds each |
|
||||
| `paroquant` | a channel scaling and `stages` rounds of Givens pair rotations, learned against the Hessian, then AutoRound on the rotated weight; the encoding's `givens` transform |
|
||||
| `ggml` | `type=` one of llama.cpp's formats -- q4_0, q4_1, q5_0, q5_1, q8_0, q2_K..q6_K, iq4_nl, iq4_xs, iq2_xxs, iq2_xs, iq2_s, iq3_xxs, iq3_s, iq1_s, iq1_m -- by llama.cpp's own search, imatrix-weighted, the codes byte for byte llama.cpp's, stored as each type's affine planes; iq2_xxs, iq2_xs and iq1_s need `--imatrix` |
|
||||
| `cast` | a float weight in another float dtype (`dtype=` f32, bf16, f16, fp8_e4m3, fp8_e5m2), no scale |
|
||||
|
||||
and the grid options every quantiser but `ggml` and `cast` takes:
|
||||
|
||||
| option | |
|
||||
|---|---|
|
||||
| `codes` | `i2`..`i8`, `i16`, `i32` symmetric; `u1`..`u8`, `u16` with `zero=`; `fp8_e4m3`, `fp8_e5m2`, `fp6_e2m3`, `fp6_e3m2`, `fp4_e2m1` |
|
||||
| `table` | a codebook the codes index instead: `nf4`, `iq4nl`, `w4nl`, `w5nl`, `binary` (one bit), `ternary`, or the values, `;`-separated |
|
||||
| `group=N` / `block=RxC` | where the scales sit; `*` is a whole extent |
|
||||
| `scale` | f32, bf16, f16, fp8_e4m3, e8m0; under `scale2` also an integer sub-scale, u4..u8, i6, i8 |
|
||||
| `scale2`, `group2` / `block2` | a second scale level the first is relative to (default the whole tensor) |
|
||||
| `scale2_value` | the second level fixed at this value, exact in `scale2`'s dtype, for every block of it |
|
||||
| `zero` | an integer zero point a block, making the grid asymmetric |
|
||||
| `transform=fwhtN` | rotate each row by the Hadamard first |
|
||||
| `rule` | `absmax`, `mx` (the OCP shared exponent), `fixed` (`scale_value=`), `search` (least squared error over candidates and their refits, imatrix-weighted) |
|
||||
| `clamp` | a signed code's range, `full` or `sym` |
|
||||
|
||||
So MXFP4 is `codes=fp4_e2m1 group=32 scale=e8m0`, NVFP4 `codes=fp4_e2m1 group=16 scale=fp8_e4m3
|
||||
scale2=f32`, NF4 `table=nf4 group=64`, a K-quant-like grid `codes=i4 group=32 scale=u6 scale2=f16
|
||||
group2=256`, and a ternary BitNet weight `table=ternary`.
|
||||
|
||||
**A container can hold only what some kernel reads.** The converter checks every planned encoding
|
||||
against the layout hooks of the kernels declare resolved and refuses one nothing accepts, so a
|
||||
grid libquant can write is a container's only once a kernel library takes it. libr4d reads the
|
||||
plain floats; block-scaled fp8 and fp8 rows; int8 block rows (the W8A8 trunk and lm_head); the
|
||||
routed experts as fp8, int4 (`i4*bf16[1x128]/fwht128`) or the `w4nl`/`w5nl` codebooks under E4M3
|
||||
scales ([MOE-W4.md](MOE-W4.md)); the dense w4, w8 and mxfp4 GEMM rows; and the 2-bit draft head.
|
||||
Every encoding decodes through the core all the same, which is what the converter's error report,
|
||||
the oracle and these quantisers' tests read it with.
|
||||
|
||||
The recipes for the containers this tree serves are in `data/recipes/`, and the conversions of
|
||||
record in `scripts/convfn.sh` and `scripts/convdspark.sh` use them.
|
||||
|
||||
### Examples
|
||||
|
||||
```sh
|
||||
# Flash-Next as it is served (w4nl64-i8lm.rad): codebook experts by GPTQ against the calibration
|
||||
# Grams in $CALIB, an int8 trunk (docs/MOE-W4.md, "What is served"). The recipe's expert rule
|
||||
# reads calib=$CALIB, and an unset variable is refused
|
||||
CALIB=<calibration dir> rad-convert <Qwen3.8-Flash-Next checkpoint> \
|
||||
-o w4nl64-i8lm.rad --recipe data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe \
|
||||
--home $RADIANCE_HOME -v
|
||||
|
||||
# A rule given on the command line goes ahead of the recipe's: here the experts at plain int4 by
|
||||
# GPTQ, under a recipe whose own expert rule rounds to nearest
|
||||
CALIB=<calibration dir> rad-convert <Qwen3.8-Flash-Next checkpoint> -o flashnext-w4.rad \
|
||||
--quant 'blk.*.ffn_*_exps.*.weight=gptq:codes=i4,group=128,scale=bf16,transform=fwht128,calib=$CALIB' \
|
||||
--recipe data/recipes/qwen4exp-w4-hc8m.recipe --home $RADIANCE_HOME -v
|
||||
|
||||
# A block-fp8 checkpoint needs no recipe: every weight is kept as it is. It needs no container
|
||||
# either -- `radiance --model` serves the checkpoint directly -- unless a tier only a container
|
||||
# has is wanted (GUIDE §3.4)
|
||||
rad-convert <Qwen3.8-27B-FP8 checkpoint> -o q38-27b-fp8.rad
|
||||
|
||||
# Check the plan without writing 166 GiB
|
||||
rad-convert $SRC -o /dev/null --recipe r.recipe --plan-only -v
|
||||
|
||||
# Merge a drafter that ships as its own repository
|
||||
rad-convert <MiniCPM5-2B checkpoint> -o minicpm5-2b-dspark.rad \
|
||||
--draft-model <MiniCPM5-2B-DSpark checkpoint> --recipe data/recipes/minicpm5-2b-dspark.recipe
|
||||
|
||||
# Re-quantise only the experts of an existing container
|
||||
rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
|
||||
```
|
||||
|
||||
### The flags that catch people
|
||||
|
||||
**`--tokenizer`.** Pass it for a GGUF. Without it the tokeniser chain is reconstructed from a
|
||||
pre-tokeniser *name*, which is a guess; a safetensors checkpoint's `tokenizer.json` is found beside
|
||||
it. Also make sure a `chat_template.jinja` sits beside `tokenizer_config.json` in the checkpoint —
|
||||
newer repos moved the template out of the JSON, and the symptom of missing it is `chat is 501`.
|
||||
|
||||
**`--set K=V` is how a convert-time choice that must also hold at serve time is stated once.** The
|
||||
key is handed to declare *and* written into the container. What a weight is stored as is not such a
|
||||
choice: the encoding is in the container, and the plugin reads it from there.
|
||||
|
||||
**`--max-ctx`.** Some architectures' graphs depend on the context bound: Qwen4-Exp sizes its QSA
|
||||
buffers by it, and refuses a `--max-tok` and context pair whose score plane would pass 2 GiB.
|
||||
Default is the checkpoint's training context.
|
||||
|
||||
**`--max-spec`.** A *container* carries what the model can serve, so a draft head is written even
|
||||
when this run would not have drafted. `0` leaves it out.
|
||||
|
||||
**`--draft-model` here is real** — unlike on the engine, where it is refused. This is where a
|
||||
drafter gets merged: its tensors go in under a `draft.` prefix and its config under `draft.` keys.
|
||||
It has no embedding and no `lm_head` of its own because it uses the target's.
|
||||
|
||||
**`--imatrix`** supplies the expert-popularity profile, which the placement planner ranks units by,
|
||||
hands each quantiser its weight's column importances, and weights the error report.
|
||||
|
||||
**`calib=DIR`** (`gptq`, `awq`, `autoround`, `paroquant`) is a directory an engine run wrote with
|
||||
`RADIANCE_CALIB_DIR` — each layer's Gram matrices, of the input in the domain the kernel multiplies
|
||||
it in: a container that stores a weight rotated records the rotated input, and a recipe that rotates
|
||||
the same weight reads it as it stands. A weight with nothing there is quantised the uncalibrated
|
||||
way and says so; `awq`, `autoround` and `paroquant` take the imatrix's diagonal instead when
|
||||
`--imatrix` gives one. The three-step calibrated recipe is in [MOE-W4.md](MOE-W4.md).
|
||||
|
||||
**`autoround` and `paroquant` are slow by construction.** AutoRound's 200 default steps each cost
|
||||
N·K² multiply-adds — on a 16-core Zen 5 at ~2.5 TFLOP/s that is minutes for a 17408-wide down
|
||||
projection and most of a working day for a 27B dense model. `iters=50` is a quarter of it.
|
||||
|
||||
**`--reuse` / `--in-place`** match a weight on its encoding, quantiser, options and shape. Whatever
|
||||
calibration made the old planes is carried with them: pass `--reuse` only when the source and the
|
||||
calibration are the same.
|
||||
|
||||
---
|
||||
|
||||
## rad-kbench
|
||||
|
||||
It checks every kernel every loaded library supplies against `libref`'s answers, benchmarks them,
|
||||
and writes a report. It is meant for out-of-tree authors as much as for this repo.
|
||||
|
||||
```
|
||||
rad-kbench [options] replay the recorded fixture (no model)
|
||||
rad-kbench -m <model.rad> [options] check against a real container
|
||||
rad-kbench -m <model.rad> --record FILE record a new fixture
|
||||
```
|
||||
|
||||
### The three modes
|
||||
|
||||
**Replay (no `-m`)** — seconds, on any machine, with no model and no weights present. The
|
||||
geometries, the seeds the inputs are drawn from, and `libref`'s answers reduced to a norm and a
|
||||
sample are checked in as `data/kernels.rkb`. This is what `ctest` runs.
|
||||
|
||||
```sh
|
||||
rad-kbench --home $RADIANCE_HOME --max-cases 1
|
||||
rad-kbench --home $RADIANCE_HOME --max-cases 1 --fixture $RADIANCE_HOME/kernels_moe.rkb
|
||||
```
|
||||
|
||||
There are **two** fixtures because a recording is of *one* container and no container declares the
|
||||
whole op vocabulary: `kernels.rkb` is a dense model with a block drafter and gqa 6; `kernels_moe.rkb`
|
||||
is a routed MoE with an MTP head and gqa 8.
|
||||
|
||||
Note that the replay also regression-tests `libref` itself — which a live oracle never can, since a
|
||||
live comparison moves both sides together and reports agreement.
|
||||
|
||||
**Against a container (`-m`)** — weight operands are read *from it*: each weight's canonical
|
||||
planes, which the kernel under test gets through its own `layout`/`relayout` hooks and the oracle
|
||||
gets decoded. That is a test of the artifact and of the layout hooks, and it is the only way to get
|
||||
one.
|
||||
|
||||
```sh
|
||||
rad-kbench -m flashnext-w4.rad --home $RADIANCE_HOME --bench --report kbench.md
|
||||
```
|
||||
|
||||
**Recording (`--record`)** — runs the oracle once and checks in what it produced. Weights are
|
||||
**drawn from a seed, not read from the container**, because a reference nothing can reproduce is
|
||||
not one. The recording carries each weight's encoding and the planes the operand takes, so a replay
|
||||
draws the same planes, every library lays them out its own way, and the reference reads what they
|
||||
decode to.
|
||||
|
||||
```sh
|
||||
rad-kbench -m model.rad --max-cases 1 --record data/kernels.rkb
|
||||
rad-kbench -m moe.rad --max-cases 1 --record data/kernels_moe.rkb
|
||||
```
|
||||
|
||||
### Flags
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `--fixture FILE` | the recording to replay (default `$RADIANCE_HOME/kernels.rkb`) |
|
||||
| `--record FILE` | with `-m`: write a fixture |
|
||||
| `-m, --model FILE` | the `.rad` to read weight operands from |
|
||||
| `--home DIR`, `--kernels A:B` | plugin home and hierarchy |
|
||||
| `--op NAME` | check only this op (repeatable prefix match) |
|
||||
| `--ref NAME` | the oracle plugin's name (default `libref`) |
|
||||
| `--seed N` | base seed; every case derives its own, so changing a filter does not change any other case's inputs |
|
||||
| `--tol X` | override every tolerance (for bisecting, **not** for passing) |
|
||||
| `--max-ctx N` | the deepest context considered: declare runs at it and the attention sweep builds to it (default: the checkpoint's training context for declare, 16384 for the sweep). Attention is swept over depth as well as query length |
|
||||
| `--max-tok N` | the `max_tok` declare runs at (default 512, small on purpose) |
|
||||
| `--kv-cache-dtype T` | `bf16` or `fp8`, the cache width declare runs at, as on the engine (default bf16) |
|
||||
| `--max-cases N` | runs per distinct (op, kernel, geometry, tuned point); 0 means every one (default 4) |
|
||||
| `--max-bytes MIB` | **skip a case whose operands would need more than this**, by name (default: half the memory free at start, at most 8192 and at least 512) |
|
||||
| `--no-fusion` | skip the fusion oracle |
|
||||
| `--bench` | time each case that passes, on the same bytes |
|
||||
| `--bench-iters N`, `--bench-reps N` | launches per rep (20), timed reps (3) |
|
||||
| `--bench-warm-ms N` | untimed launches before each timed window (default 500) |
|
||||
| `--report FILE` | write the markdown report |
|
||||
| `--analysis FILE` | splice in a fragment from `tools/kbench-analysis.sh` |
|
||||
| `--num-speculative-tokens N` | draft depth to declare at |
|
||||
| `-v` | print every case, not only failures |
|
||||
|
||||
### Things that will bite you
|
||||
|
||||
**`--max-bytes` matters on a loaded machine.** One case holds every operand as host floats, again
|
||||
as the kernel's dtype, and again per library on the device. Without the cap a small machine is
|
||||
killed by the OOM killer with no indication which op it died on. The default is taken from the
|
||||
memory free when the run starts, which a server started later does not respect; if a server is
|
||||
running on the same box, pass something small explicitly:
|
||||
|
||||
```sh
|
||||
rad-kbench --home $RADIANCE_HOME --max-cases 1 --max-bytes 1024
|
||||
```
|
||||
|
||||
**`--bench` is cache-warm.** It cannot rank a bandwidth-bound kernel the way production runs it.
|
||||
Read the caveat the report prints about the GB/s column.
|
||||
|
||||
**`--max-cases`.** A 62-layer model presents the same kernel at the same shape sixty times and only
|
||||
the weights differ. The default of 4 is not a sample of anything interesting; `--max-cases 1` is
|
||||
what the fixtures are recorded at.
|
||||
|
||||
**Fusion claims are checked byte for byte.** A kernel that declares the chain it replaces is run
|
||||
against that chain, out of its own plugin, and the outputs compared with `memcmp`. That claim is
|
||||
what makes a fused kernel *substitutable* rather than a second numerical path.
|
||||
|
||||
**A kernel that does not read a weight's encoding is a skip, not a failure.** Its layout hook
|
||||
answers `RAD_E_DTYPE` for an encoding it does not take, and the report names the kernel, the
|
||||
operand and the encoding. A fixture in another format version does not load at all — record it
|
||||
again.
|
||||
|
||||
---
|
||||
|
||||
## rad-tune
|
||||
|
||||
```
|
||||
rad-tune -m <model.rad> [options]
|
||||
|
||||
-m, --model FILE the .rad whose declared graph supplies the shapes
|
||||
--home DIR $RADIANCE_HOME; the cache is written to <home>/tune/<machine>.tune
|
||||
--kernels A:B kernel plugin hierarchy, first wins
|
||||
--op NAME tune only ops whose name starts with NAME
|
||||
--machine KEY override the machine key (for writing a cache for another box)
|
||||
--reps N timing reps, median reported (default 5)
|
||||
--iters N launches per rep (default 32)
|
||||
--max-tok N the max_tok declare is run at (default 8192)
|
||||
--tp N tensor-parallel width to declare at (default 1)
|
||||
--num-speculative-tokens N
|
||||
--dry-run list what would be measured and stop
|
||||
-v, --verbose print every candidate, not just the winner
|
||||
```
|
||||
|
||||
Kernels declare **tunable axes** rather than named variants. `rad-tune` walks that space at this
|
||||
model's actual shapes on this actual machine, and writes the winner per (op, geometry) to
|
||||
`$RADIANCE_HOME/tune/<machine>.tune`. The engine's selector reads that cache at startup.
|
||||
|
||||
```sh
|
||||
rad-tune -m model.rad --home $RADIANCE_HOME --tp 2
|
||||
rad-tune -m model.rad --op gemm --dry-run # what would be measured
|
||||
rad-tune -m model.rad --op attn_paged -v # every candidate
|
||||
```
|
||||
|
||||
**Declare at the shapes you serve.** Two things decide that and both are flags here:
|
||||
|
||||
- **`--tp N`** — a sharded deployment halves every sharded N. A declare at world size 1 measures a
|
||||
program no `--tp 2` serve ever runs.
|
||||
- **`--num-speculative-tokens N`** — this is what puts the *drafter's* kernels in the measured graph
|
||||
at all. The default is the container's own depth. The drafter's shapes appear in no other model's
|
||||
tuning table, so nothing else covers them.
|
||||
|
||||
At `--tp > 1` every rank declares at once, on its own thread and its own device, exactly as the
|
||||
engine does: a collective's `init` is a rendezvous, so declaring rank 0 alone at world size 2 does
|
||||
not fail — it *hangs*.
|
||||
|
||||
**Prove the variants beat the default before trusting a cache.** `RADIANCE_TUNE` pins a kernel's
|
||||
axes for a comparison; it is an instrument, not a deployment setting.
|
||||
|
||||
---
|
||||
|
||||
## rad-schemas
|
||||
|
||||
```
|
||||
rad-schemas libref.so print one plugin's vocabulary
|
||||
rad-schemas libr4d.so libref.so diff them, in hierarchy order
|
||||
```
|
||||
|
||||
The first plugin in hierarchy order to declare an op **fixes its schema**, and a later plugin
|
||||
declaring the same op differently is refused at load with both plugins named. That rule is right:
|
||||
arguments are positional, so two disagreeing schemas make the same call mean different things
|
||||
depending on which plugin won selection — silent numerical garbage rather than a diagnosable
|
||||
failure.
|
||||
|
||||
But "refused at load" is a poor place to find out, because the message names one op and you have to
|
||||
guess the rest. This prints all of them at once, so a new plugin can be conformed to the vocabulary
|
||||
before it is ever loaded beside another.
|
||||
|
||||
**It links no core at all**, deliberately: it `dlopen`s plugins and reads their static schema
|
||||
tables, so it works on a plugin the engine cannot even load — which is exactly when you need it.
|
||||
|
||||
```sh
|
||||
rad-schemas $RADIANCE_HOME/kernels/libr4d.so $RADIANCE_HOME/kernels/libref.so
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## rad-tokcheck
|
||||
|
||||
```
|
||||
rad-tokcheck [options] <tokenizer.json> <corpus-file>...
|
||||
|
||||
--hf-dir DIR compare against HuggingFace ids in DIR/<corpus basename>.ids
|
||||
(little-endian int32, encode(text, add_special_tokens=False))
|
||||
--no-ref skip the reference encoder, which is slow
|
||||
--user encode with parse_special off, as the server does for user content
|
||||
--turns N turns in the multi-turn measurement (default 40, 0 skips it)
|
||||
--repeat N timing repeats, best taken (default 3)
|
||||
--context N ids shown either side of a difference (default 6)
|
||||
```
|
||||
|
||||
Three questions, per corpus file: does the encoder produce the ids the reference encoder in
|
||||
`tools/tokref` produces (llama.cpp's splitters and `std::regex`, a string-keyed merge); does it
|
||||
produce the ids HuggingFace `tokenizers` produces, read from files made elsewhere so that nothing
|
||||
here needs Python; and how fast is it -- MB/s for both encoders, and what re-tokenising a growing
|
||||
conversation costs with the segment cache and without it. Any difference is printed with the ids
|
||||
and the text around it, and makes the exit status non-zero, so it can gate a change.
|
||||
|
||||
---
|
||||
|
||||
## The KL mode
|
||||
|
||||
```
|
||||
radiance --model BF16.rad ... --kld-record DIR --kld-corpus CORPUS.jsonl the yardstick, once
|
||||
radiance --model QUANT.rad ... --kld-ref DIR [--kld-out REPORT.json] each candidate
|
||||
```
|
||||
|
||||
How far a quantised model is from the one it was quantised from, as the distribution of the
|
||||
per-position **KL(P_bf16 || Q_quant)** over the whole vocabulary: mean, median, 99th, 99.9th and
|
||||
99.99th percentiles and maximum, the top-1 agreement (the candidate's argmax is the reference's),
|
||||
and both models' perplexity on the corpus's own next tokens -- overall and per source. A mode of
|
||||
the engine rather than a tool, like `--debug-graph`: it starts exactly as a serve would, with the
|
||||
same placement and kernels, then runs the corpus through prefill instead of listening, and exits.
|
||||
|
||||
**The reference is computed once.** `--kld-record` writes the bf16 model's log-probabilities at
|
||||
every scored position to DIR -- f16 over the whole vocabulary, the 16 most likely tokens exactly,
|
||||
and the tokens themselves -- and `--kld-ref` runs a candidate over those stored tokens, scoring its
|
||||
own f32 logits against the stored row. A candidate costs one prefill of the corpus. DIR is never
|
||||
written over, and is read only once its `kld.json` exists, which the recording writes last.
|
||||
|
||||
**The corpus** is JSONL, one `{"prompt", "score_from", "source"}` a line: `prompt` is tokenised
|
||||
with control tokens recognised, as a rendered chat template is; positions `[score_from, n - 1)`
|
||||
are scored; `source` is the report's grouping. The corpus the Flash-Next numbers in
|
||||
[MOE-W4.md](MOE-W4.md) were measured on is disjoint from the calibration corpus, so a calibrated
|
||||
quantiser is not scored on the text it was fitted to. Positions are what the tail needs: the
|
||||
99.99th percentile of 83K positions rests on eight of them.
|
||||
|
||||
**What the mode changes for itself.** Speculation and the prefix cache are off (a drafter writes
|
||||
no scored row; a prefix hit would skip positions the reference holds), the step pipeline is off
|
||||
(the scored rows are copied off the cards after the step), and the logits buffer holds a row for
|
||||
every token of a step (`RadBuildCtx::max_out_rows`) -- `--max-num-batched-tokens 4096` is 2 GiB
|
||||
of it a rank, plus the same in pinned host memory. Everything else is the command line's: run
|
||||
every candidate with the same flags, and the reference with an exact wire and a bf16 KV cache.
|
||||
|
||||
`--kld-out FILE` writes the report as JSON and every position's KL, both NLLs and the argmax
|
||||
agreement to `FILE.rows` (`[positions, 4]` f32, reference row order), so two candidates can be
|
||||
compared position by position.
|
||||
|
||||
---
|
||||
|
||||
## The shell harnesses
|
||||
|
||||
`scripts/` drives a **running** engine: bring a model up, measure it, and assert on what comes back
|
||||
over the wire. They are versioned with the engine because a measurement is only reproducible if the
|
||||
thing that took it is — and because what each one encodes is an argument (why a window is sampled
|
||||
the way it is, which counter is the honest one) that is expensive to reconstruct from the number.
|
||||
[scripts/README.md](../scripts/README.md) has a line on each.
|
||||
|
||||
The scripts that start a server or a conversion expect the build at
|
||||
`$HOME/workspace/radiance/build` and the containers under `$HOME/models/rad/`; every default is an
|
||||
environment override, listed in each script's header. The ones that only attach to a live server
|
||||
need nothing but `curl` and `jq`. Scripts resolve each other by `$(dirname "$0")`.
|
||||
|
||||
**Which ones restart the server.** `fnserve.sh`, `mcserve.sh`, `fnstop.sh`, `fntrace.sh`,
|
||||
`dprofd.sh`, `mctrace.sh`, `mcagent.sh` and `mcdecl.sh` all `pkill` a running engine, whatever port
|
||||
it is on. `oracle.sh` starts its own server and stops whatever listens on its port (`P`, default
|
||||
8302). Everything else — `cstep2.sh`, `ident.sh`, `tierident.sh`, `tiercross.sh`, `mctools.sh`,
|
||||
`mcstream.sh`, `hfget.sh`, `convfn.sh`, `convdspark.sh`, `fnpf.sh`, `fnconc.sh`, `fndrop.sh`,
|
||||
`apikeys.sh`, `diskstall.py` — leaves a live serve alone.
|
||||
`fndrop.sh` is the one to read the description of first: it leaves the PROCESS alone and
|
||||
deliberately disconnects clients from it, which is not the same promise.
|
||||
|
||||
### Bringing a model up
|
||||
|
||||
| | knobs |
|
||||
|---|---|
|
||||
| `mcserve.sh` | MiniCPM5-2B + DSpark drafter (`minicpm5-2b-dspark.v2.rad`), left running. `P` `TP` `MLEN` `SEQS` `M` `KVD` `HR` `MNBT` `EXTRA` `EXTRA_ENV` |
|
||||
| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. `P` `TP` `MLEN` `SEQS` `M` `RATIO` `NS` `HOSTPOOL` `KVD` `HR` `MNBT` `WIRE` `KVHOST` `KVDIR` `KVDISK` `EXTRA` `EXTRA_ENV` |
|
||||
| `fnstop.sh` | stops whichever is running and **waits for the process to go** |
|
||||
| `convdspark.sh`, `convfn.sh` | rebuild the containers those two serve. The conversions of record. `convfn.sh` needs `CALIB=<dir>`: the production recipe's expert rule runs GPTQ against the calibration Grams there |
|
||||
| `hfget.sh` | fetch a checkpoint from Hugging Face with `curl` and `jq`. Resumable |
|
||||
|
||||
```sh
|
||||
scripts/fnserve.sh # defaults: port 8100, tp 2, 200K ctx, ratio 0.82
|
||||
P=8100 MLEN=131072 SEQS=4 scripts/fnserve.sh # override
|
||||
scripts/fnstop.sh
|
||||
```
|
||||
|
||||
Both print the endpoints and exit with the server still up. Read their headers — `fnserve.sh` in
|
||||
particular carries the whole `--expert-vs-cache-ratio` argument with the measurements behind it.
|
||||
|
||||
### Measuring a server that is already up
|
||||
|
||||
These attach to a running server and never restart one, so they can be pointed at a live
|
||||
deployment. `P` selects the port.
|
||||
|
||||
| | what it answers | knobs |
|
||||
|---|---|---|
|
||||
| `fnpf.sh` | prefill throughput, with a fresh nonce per rep so the prefix cache cannot answer for work that was never done | `P` `N` `REPS` `BPT` |
|
||||
| `fnconc.sh` | what a long prefill costs the requests already running beside it — both halves on one clock, alone then contended, with the warm pass discarded | `P` `C` `DEC` `PROMPT` |
|
||||
| `fndrop.sh` | whether a client going away mid-request takes anything with it. Drop points are derived from one timed request, and every answer is checked against a reference | `P` `LONG` `GEN` |
|
||||
| `apikeys.sh` | whether the server does what oai.cpp says about request keys: every rejected one refused by name, every inert one accepted, every accepted one honoured | `P` |
|
||||
| `cstep2.sh` | steady-state decode ms/step at concurrency | `P` `LEVELS` `MT` `WIN` |
|
||||
| `ident.sh` | run-to-run reproducibility at a fixed configuration: one hash per (temperature, question) | `P` |
|
||||
| `diskstall.py` | what restoring a conversation from the disk tier costs: the returning request's time to first token, and the longest stall it puts on a stream decoding beside it | `--port` `--session` `--fill` |
|
||||
|
||||
`fndrop.sh` exists because a disconnect reaps a request at an arbitrary point in the step loop, and
|
||||
every other harness here waits for its requests, so none of them can see what holds a reference
|
||||
across that point. Surviving is not the whole test: a server that stays up and then answers
|
||||
differently has a freed slot feeding a live sequence. Note its own caveat — one diverged hash is not
|
||||
a finding, it is an instruction to run it again.
|
||||
|
||||
`ident.sh` does not expect a speculative run to match a non-speculative one byte for byte: the
|
||||
split-K count is chosen from M, so the two take different reduction orders and a long answer can
|
||||
flip a near-tie. A divergence within the first sentence or two is a defect.
|
||||
|
||||
```sh
|
||||
P=8100 LEVELS="1 2 4 8" scripts/cstep2.sh
|
||||
```
|
||||
|
||||
```
|
||||
C steps tok tok/step ms/step accept%
|
||||
1 812 900 1.108 29.820 74.2
|
||||
2 ...
|
||||
```
|
||||
|
||||
`cstep2.sh` waits until exactly C sequences are running before sampling and re-checks at the end: a
|
||||
window whose edges carry fewer than C describes no concurrency at all.
|
||||
|
||||
### Measuring with a server of its own
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `dprofd.sh` | per-op device timing at depth and concurrency, on the 27B dense model with its DFlash2 drafter. **Difference two dumps**, both taken after prefill ended |
|
||||
| `fntrace.sh` | a Flash-Next prefill under `rocprofv3`, with the link counters from `/stats` across the same request |
|
||||
| `mctrace.sh` | a MiniCPM5-2B decode trace under `rocprofv3`, formatted for `libr4d/isa/tsum.sh` |
|
||||
| `oracle.sh` | every op compared against libref on the operands the model actually issued; reads for a MISMATCH and for the NOT CHECKED lines that name what cannot be compared. `OPS` `MAXN` `FROM`/`TO` `TOL` `M` |
|
||||
|
||||
### Regression checks against a live server
|
||||
|
||||
These cover what `tests/chat_test.cpp` structurally cannot: the server, the wire format, and a real
|
||||
model's output.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `tierident.sh` | does a session that left VRAM come back byte for byte, both halves? `P` `H` `N` `TO_HOST` `TO_DISK` `FILL` |
|
||||
| `tiercross.sh` | the same with **two** sessions in flight — the only way to see one being served the other's context |
|
||||
| `mctools.sh` | the tool-call shapes hardest to parse — an array argument, two calls in one reply, prose before a call, plain chat with tools available. Asserts `finish_reason` and that no `<function`/`<param`/CDATA marker reaches content |
|
||||
| `mcstream.sh` | tool-call replies **streamed**, asserting on raw SSE fragments. Content cannot be retracted once sent, so a repair applied at the end is not a fix — this is the check that sees the difference |
|
||||
| `mcagent.sh` | what speculation is worth on an agentic workload (chat + tools, a constrained decode) |
|
||||
| `mcdecl.sh` | how often the drafter actually proposes. `draft_acceptance_ratio` is conditional on having drafted, so it reads healthy while tokens-per-step collapses; blocks-per-step separates the two |
|
||||
|
||||
> **They are not all read-only.** `tierident.sh`, `tiercross.sh`, `mctools.sh` and `mcstream.sh`
|
||||
> talk to a server already running (port 8100 unless `P` says otherwise) and leave it alone.
|
||||
> `mcagent.sh` and `mcdecl.sh` **start and stop servers of their own** — and `mcserve.sh`, which
|
||||
> they call, begins with `pkill -f "bin/radianc[e]"`, so they will take down any radiance you have
|
||||
> running. Check before you run one on a box that is serving.
|
||||
|
||||
```sh
|
||||
scripts/mctools.sh && scripts/mcstream.sh
|
||||
```
|
||||
|
||||
### One more, in `tools/`
|
||||
|
||||
`tools/kbench-analysis.sh` produces the static-and-dynamic-analysis fragment that
|
||||
`rad-kbench --analysis` splices into its report. `tools/ops_doc_check.sh` is the `ops_doc` test:
|
||||
it holds `docs/OPS.md` to what the registries actually declare.
|
||||
@@ -0,0 +1,300 @@
|
||||
# Research note: measured 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
|
||||
|
||||
## 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)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| architecture | `qwen4exp` |
|
||||
| layers / hidden | 48 / 2560 |
|
||||
| attention | 36 × Gated DeltaNet (linear, v_head_dim 128, conv kernel 4) + 12 × QSA sparse attention (layers 3, 7, … 47; 24 heads, 2 KV heads, index_topk 512, 8 heads × 128) |
|
||||
| MoE | 512 routed experts, 10 activated, + 1 shared expert; expert intermediate 640 |
|
||||
| PLE / n-gram | n-gram size 3, 16 heads (8 per n-gram), 20 M vocab per head, head dim 160, injected at layer 1 |
|
||||
| context | 262 144 native, `attn_type_vector` marks 36 linear / 12 full layers |
|
||||
| draft | 1 MTP layer (`blk.48`, `nextn.*`), 3.88 B params self-contained / 2.61 B shared |
|
||||
| quantisation | imatrix-driven: `quantize.imatrix.file = imatrix_unsloth.gguf`, 926 entries of 1224 tensors, 45 calibration chunks (absent only in the BF16 build) |
|
||||
|
||||
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).
|
||||
|
||||
## Method — how to read a quant recipe without downloading anything
|
||||
|
||||
`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.
|
||||
|
||||
Four things that bite:
|
||||
|
||||
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.
|
||||
|
||||
## File sizes
|
||||
|
||||
| build | params | size | avg bpw |
|
||||
|---|---|---|---|
|
||||
| BF16 | 176.94 B | 354.03 GB | 16.01 |
|
||||
| Q8_0 | 176.94 B | 188.23 GB | 8.51 |
|
||||
| UD-Q6_K_XL | 176.94 B | 169.17 GB | 7.65 |
|
||||
| UD-Q5_K_XL | 176.94 B | 158.29 GB | 7.16 |
|
||||
| UD-Q4_K_XL | 176.94 B | 111.33 GB | 5.03 |
|
||||
| UD-Q3_K_XL | 176.94 B | 89.99 GB | 4.07 |
|
||||
| UD-IQ4_XS | 176.94 B | 93.68 GB | 4.24 |
|
||||
| UD-Q2_K_XL | 176.94 B | 78.87 GB | 3.57 |
|
||||
| UD-IQ3_XXS | 176.94 B | 81.96 GB | 3.71 |
|
||||
| UD-IQ1_M | 176.94 B | 74.54 GB | 3.37 |
|
||||
| UD-IQ1_S | 176.94 B | 72.55 GB | 3.28 |
|
||||
|
||||
`L2`/`L46-47` below = layers given one notch more precision (dynamic "UD/XL" selection).
|
||||
|
||||
## The recipe matrix
|
||||
|
||||
| weight group (count, params) | BF16 | Q8_0 | Q6_K_XL | Q5_K_XL | Q4_K_XL | Q3_K_XL | IQ4_XS | Q2_K_XL | IQ3_XXS | IQ1_M | IQ1_S |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| n-gram/PLE table `per_layer_token_embd` (1, 51.2 B) | BF16 | Q8_0 | Q8_0 | Q8_0 | IQ4_NL | IQ4_NL | IQ4_NL | IQ4_NL | IQ4_NL | IQ4_NL | IQ4_NL |
|
||||
| experts gate+up (96, 80.5 B) | BF16 | Q8_0 | Q6_K +L2 Q8_0 | Q5_K +L2 Q6_K | Q4_K +L2 Q5_K | IQ3_XXS +L2 IQ4_XS | IQ3_S +L2 IQ4_XS | IQ2_XS +L2 IQ3_XXS | IQ2_S +L2 IQ3_S | IQ1_M/IQ2_XXS† | IQ1_S/IQ2_XXS† |
|
||||
| experts down (48, 40.3 B) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q5_1 +L2,4,30,46-47 Q8_0 | IQ4_NL +same 5 Q8_0 | IQ4_NL +same 5 Q8_0 | IQ4_NL | IQ4_NL | IQ4_NL | IQ4_NL |
|
||||
| shared expert gate/up (96) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q5_K +L2 Q6_K | Q6_K +L2 Q8_0 | Q5_K +L2 Q6_K | Q5_K +L2 Q6_K |
|
||||
| shared expert down (48) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 |
|
||||
| MoE router `ffn_gate_inp{,_shexp}` (96) | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 |
|
||||
| `token_embd` (1, 636 M) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q5_K | Q6_K | Q4_K | Q4_K |
|
||||
| `output` (lm_head) (1, 636 M) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q6_K | Q6_K | Q4_K | Q6_K | Q4_K | Q4_K |
|
||||
| QSA attn q (12) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q5_K | Q6_K | Q5_K | Q5_K |
|
||||
| QSA attn k, v (24) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q6_K | Q6_K | Q5_K | Q5_K |
|
||||
| QSA attn o (12) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q5_K | Q6_K | Q5_K | Q5_K |
|
||||
| QSA `indexer.q/k_proj` (24) | BF16 | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** | **BF16** |
|
||||
| DeltaNet `attn_qkv`, `attn_gate` (72) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q5_K +L2 Q6_K | Q6_K +L2 Q8_0 | Q5_K +L2 Q6_K | Q5_K +L2 Q6_K |
|
||||
| DeltaNet `ssm_out` (36) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q6_K | Q6_K | Q6_K | Q6_K |
|
||||
| DeltaNet `ssm_alpha`, `ssm_beta` (72) | BF16 | Q8_0 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 |
|
||||
| gated-residual `hc_*_{up,down}` (388) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 |
|
||||
| gated-residual `hc_*_inject` (192) | BF16 | Q8_0 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 |
|
||||
| PLE projections `ple_key`/`ple_value` (L1) | BF16 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 | Q8_0 |
|
||||
| all norms, biases, `ssm_a`, `ssm_dt`, `ssm_conv1d`, `ple_norm_*` | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 | F32 |
|
||||
|
||||
† IQ1_M: gate/up = IQ2_XXS at L1-4, 6, 9, 14, 16, 24-25, 30-32, 35, 37-43, 45-47 and IQ1_M on
|
||||
the other 24. IQ1_S: IQ2_XXS at L1-2, 4, 14, 16, 25, 30, 32, 37, 39, 42, 45-47 (14 tensors),
|
||||
IQ1_S on the other 34.
|
||||
|
||||
Type bpw 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.
|
||||
|
||||
MTP drafts are separate 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.
|
||||
|
||||
## Where the bytes go
|
||||
|
||||
| category (params) | Q8_0 | Q4_K_XL | IQ4_XS | Q2_K_XL | IQ1_S |
|
||||
|---|---|---|---|---|---|
|
||||
| experts gate+up (80.5 B, 46 %) | 8.50 bpw / 85.6 GB | 4.52 / 45.5 | 3.45 / 34.8 | 2.33 / 23.4 | 1.71 / 17.2 |
|
||||
| experts down (40.3 B, 23 %) | 8.50 / 42.8 | 6.26 / 31.5 | 4.92 / 24.7 | 4.50 / 22.6 | 4.50 / 22.6 |
|
||||
| n-gram table (51.2 B, 29 %) | 8.50 / 54.4 | 4.50 / 28.8 | 4.50 / 28.8 | 4.50 / 28.8 | 4.50 / 28.8 |
|
||||
| everything else (5 B, 2 %) | 8.96 / 4.1 | 9.04 / 4.2 | 9.04 / 4.2 | 6.92 / 3.2 | 6.91 / 3.2 |
|
||||
| share of file that is n-gram + expert down | 51 % | 54 % | 57 % | 65 % | 71 % |
|
||||
|
||||
## Sizes with the n-gram table removed
|
||||
|
||||
`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).
|
||||
|
||||
| build | file | n-gram table | rest of model | rest bpw (÷ 125.74 B) | n-gram share |
|
||||
|---|---|---|---|---|---|
|
||||
| BF16 | 354.02 | 102.40 | **251.62 GB** | 16.01 | 28.9 % |
|
||||
| Q8_0 | 188.21 | 54.40 | **133.81 GB** | 8.51 | 28.9 % |
|
||||
| UD-Q6_K_XL | 169.15 | 54.40 | **114.75 GB** | 7.30 | 32.2 % |
|
||||
| UD-Q5_K_XL | 158.28 | 54.40 | **103.88 GB** | 6.61 | 34.4 % |
|
||||
| UD-Q4_K_XL | 111.32 | 28.80 | **82.52 GB** | 5.25 | 25.9 % |
|
||||
| UD-Q3_K_XL | 89.98 | 28.80 | **61.18 GB** | 3.89 | 32.0 % |
|
||||
| UD-IQ4_XS | 93.67 | 28.80 | **64.87 GB** | 4.13 | 30.7 % |
|
||||
| UD-Q2_K_XL | 78.86 | 28.80 | **50.06 GB** | 3.19 | 36.5 % |
|
||||
| UD-IQ3_XXS | 81.95 | 28.80 | **53.15 GB** | 3.38 | 35.1 % |
|
||||
| UD-IQ1_M | 74.53 | 28.80 | **45.73 GB** | 2.91 | 38.6 % |
|
||||
| UD-IQ1_S | 72.54 | 28.80 | **43.74 GB** | 2.78 | 39.7 % |
|
||||
|
||||
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.
|
||||
|
||||
## Active parameters
|
||||
|
||||
Per forward, counting only tensors actually touched (routed experts at 10/512, embedding and
|
||||
n-gram tables as look-ups):
|
||||
|
||||
| component | active/token | in file | fraction used |
|
||||
|---|---|---|---|
|
||||
| routed experts (10 of 512 × 48 layers) | 2 359 M | 120.80 B | 1.95 % |
|
||||
| DeltaNet qkv + gate (36 layers) | 1 510 M | 1.51 B | 100 % |
|
||||
| gated residual / hyper-connection | 641 M | 0.64 B | 100 % |
|
||||
| lm_head (`output`) | 636 M | 0.64 B | 100 % |
|
||||
| QSA full attention (12 layers) | 598 M | 0.60 B | 100 % |
|
||||
| DeltaNet state/out (36 layers) | 568 M | 0.57 B | 100 % |
|
||||
| shared expert | 236 M | 0.24 B | 100 % |
|
||||
| MoE router | 63 M | 0.06 B | 100 % |
|
||||
| PLE projections, QSA indexer, α/β, norms | 61 M | 0.06 B | 100 % |
|
||||
| n-gram table | ≈ 0 (2 560 values) | 51.20 B | 5e-6 % |
|
||||
| token embedding | ≈ 0 (1 row) | 0.64 B | 2e-4 % |
|
||||
| **total** | **6.671 B** incl. lm_head / **6.036 B** excl. | 176.94 B | **3.77 %** |
|
||||
|
||||
6.036 B 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.
|
||||
|
||||
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.
|
||||
|
||||
| | active params | weight bytes read (Q4_K_XL) |
|
||||
|---|---|---|
|
||||
| target, 1 forward | 6.671 B | 6.33 GB |
|
||||
| MTP draft, 1 draft step | 0.776 B | 0.83 GB |
|
||||
| 1 MTP cycle (verify 3 positions + 2 draft steps) | 21.56 B | 10.91 GB |
|
||||
| per accepted token (mean length 2.76) | **7.81 B** | **3.95 GB** |
|
||||
|
||||
## Weight traffic per token (batch 1)
|
||||
|
||||
`step(P) = experts_touched(P) + dense + lm_head`, with `experts_touched(P) = 512·(1 − (1 −
|
||||
10/512)^P)` (P=1 → 10.0, P=2 → 19.8, P=3 → 29.4 experts per layer). MTP row uses
|
||||
`shared-Q8_0` draft, llama.cpp's `--spec-draft-n-max 2`, mean accepted length 2.76.
|
||||
|
||||
| build | no MTP | MTP cycle | MTP per token | traffic ratio | measured speedup |
|
||||
|---|---|---|---|---|---|
|
||||
| BF16 | 13.47 GB | 25.49 GB | 9.23 GB | 1.46× | – |
|
||||
| Q8_0 | 7.30 | 13.83 | 5.01 | 1.46× | – |
|
||||
| UD-Q6_K_XL | 6.96 | 12.77 | 4.63 | 1.51× | – |
|
||||
| UD-Q5_K_XL | 6.75 | 12.14 | 4.40 | 1.53× | – |
|
||||
| **UD-Q4_K_XL** | **6.33** | **10.91** | **3.95** | **1.60×** | **1.67×** (83 → 139 tok/s) |
|
||||
| UD-Q3_K_XL | 5.77 | 9.23 | 3.35 | 1.72× | – |
|
||||
| UD-IQ4_XS | 5.84 | 9.45 | 3.42 | 1.71× | – |
|
||||
| UD-Q2_K_XL | 4.44 | 7.21 | 2.61 | 1.70× | – |
|
||||
| UD-IQ3_XXS | 4.95 | 8.15 | 2.95 | 1.68× | – |
|
||||
| UD-IQ1_M | 4.35 | 6.96 | 2.52 | 1.72× | – |
|
||||
| **UD-IQ1_S** | **4.31** | **6.84** | **2.48** | **1.74×** | **1.34×** (90 → 121 tok/s) |
|
||||
|
||||
## Analysis
|
||||
|
||||
1. **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.
|
||||
|
||||
## What the imatrix says
|
||||
|
||||
`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`
|
||||
(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.
|
||||
|
||||
**The Q8_0 down layers are the layers that host a super expert.** One expert in each of a few
|
||||
layers carries a large share of the layer's `down` input energy from a sliver of its tokens, all
|
||||
of it in one or two channels -- up to 208 000x that expert's median channel:
|
||||
|
||||
| layer | expert | share of the layer's down-input energy | share of its routing |
|
||||
|---|---|---|---|
|
||||
| 47 | 445 | 30.5 % | 0.38 % |
|
||||
| 4 | 108 | 24.1 % | 0.13 % |
|
||||
| 2 | 322 | 10.3 % | 0.25 % |
|
||||
| 46 | 290 | 6.9 % | 0.84 % |
|
||||
| 30 | 169 | 3.9 % | 0.12 % |
|
||||
|
||||
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`.
|
||||
|
||||
**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
|
||||
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
|
||||
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).
|
||||
|
||||
## 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.
|
||||
- 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.
|
||||
Reference in new issue
Block a user