Merge upstream main (v1.12 -> v1.15.1, 408 commits) into the SYCL port

Conflicts from the old m2xfp branch take upstream's version. Two libxe2 fixes the merge needs:
- rad_plugin_abi_layout: the plugin now exports the ABI layout hash the loader checks.
- gemm_nt_q_w4a16: upstream 492d33c sends bf16 activations to the w4a16 GEMM (the separate cast
  is gone); the fast kernel took only f16, so every call fell back to the exact path (decode
  ~2.5 tok/s). A bf16 activation is narrowed to f16 (round to nearest even) into a workspace first,
  the dropped cast bit for bit; decode back to ~57 tok/s on one request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-02 00:25:57 +01:00
commit 7580ec3d17
937 files changed
+285776 -8914

No files matched your search

+546 -48
View File
@@ -11,13 +11,18 @@ plugin claims.
| `arch/llama_dense_fp8` | `llama` | *(empty)* | the same graph from a bf16 checkpoint, linears made block fp8 by a recipe or kept bf16. MiniCPM5-2B |
| `arch/qwen35_bf16` | `qwen35` | *(empty)* | the Qwen3.5/3.6/3.8 dense hybrid, served bf16 |
| `arch/qwen35_fp8` | `qwen35` | `fp8_e4m3` | the same, block-scaled FP8 weights and activations |
| `arch/hyv3_bf16` | `hyv3` | *(empty)* | Tencent Hy-Memory-30B-A3B BF16 safetensors; BF16, W4, W8A8, block-FP8 or MXFP4 weights by recipe; TP1/2, BF16 KV |
| `arch/hyv3_fp8` | `hyv3` | `fp8` | Tencent Hy-Memory-30B-A3B-FP8; imported per-tensor E4M3 weights, one dense layer then sigmoid-routed MoE; TP1/2, BF16 or static-scaled E4M3 KV |
| `arch/hyv3_gguf` | `hyv3` | `gguf_ftype_15` | llama.cpp Hy-Memory Q4_K_M GGUF, dequantized and recipe-converted to native Radiance weights; TP1/2 |
| `arch/qwen35_w8a8` | `qwen35` | `w8a8_fwht128` | `qwen35_fp8` with an int8 trunk: i8 weights with a bf16 scale per 128 of K, rotated by a 128-wide Hadamard, against int8 activations under the same rotation (`data/recipes/q38-27b-w8a8-df2.recipe`) |
| `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed |
| `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert |
| `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert, or Qwen's FP8 release as it ships |
| `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Pictures through its vision tower (`arch/common/rad_block_glm_vision.h`); bf16 KV |
| `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank |
| `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector |
| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`), or RedHatAI's DFlash2 speculator (`arch/common/rad_block_dflash2.h`) |
| `arch/nomicbert` | `nomicbert` | *(empty)* | nomic-embed-text-v2-moe: a bidirectional post-norm encoder, 12 layers with 8 experts at top 2 on every second layer, mean-pooled to one vector an input |
| `arch/nemotron35_embed` | `mistral3` | *(empty)* | Nemotron 3.5 Embed 1B/8B and Rerank 8B: native BF16 bidirectional text/image retrieval with a Pixtral tower, TP1 ([geometry and contracts](#nemotron35_embed-embedding-models)) |
| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense, and the E2B/E4B form at one rank, with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`), or RedHatAI's DFlash2 speculator (`arch/common/rad_block_dflash2.h`) |
| `arch/gemma3` | `gemma3` | *(empty)* | Gemma 3 dense text (TranslateGemma 27B) from the bf16 checkpoint: sliding-window and global attention at one head geometry, GemmaRMSNorm, GELU ffn; linears bf16, or int8, MXFP4 or asymmetric int4 over an activation scaled per (row, 128), as the recipe stores them. Optional DFlash2 drafter (`rad-convert --draft-model`) |
| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 |
| `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 |
@@ -29,7 +34,8 @@ plugin claims.
| `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text |
| `arch/minimaxmusic3` | `minimaxmusic3` | *(empty)* | MiniMax-Music3, songs from a description and lyrics: a Qwen3-8B frame model, a depth decoder, a flow-matching DiT and a DAC vocoder, from the diffusers pipeline directory, bf16 |
| `arch/breeze` | `breeze` | *(empty)* | Breeze-TTS-2, speech from text and a description of the voice: a T5Gemma 2 text encoder, a Qwen3 backbone with a 16-codebook depth decoder and the Qwen3-TTS 12 Hz codec, from the release directory, bf16, one card |
| `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`) |
| `arch/fishomni` | `fishomni` | `bsgemm-moe` | Fish Audio drama-3, speech from text with speaker tags and inline direction, its voices cloned from reference clips: the Qwen3.5-35B-A3B backbone with its routed experts block fp8 at f32 scales and everything else bf16, a 13-layer codebook tower over the backbone's full-attention cache, and Fish S2's modified DAC, encoder and decoder (`codec.pth`, read as data); from the release directory, two cards |
| `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text, between keyframes or from reference media: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`), or the DiT's per-token linears int8, served w8a8 (`minimax-h3-w8a8.recipe`); a curve-form checkpoint, whose timestep embeddings ship as a table, by the `minimax-h3-curve-*` recipes |
| `arch/ltx2` | `ltx2` | *(empty)* | LTX-2.5 (base and distilled), a video with its stereo soundtrack from text or from text and a first frame: Gemma 4's language model and two text connectors, the duration head, a dual-stream audio-video DiT with four-way guidance, the causal video VAE (tiled past the default canvas) or the diffusion decoder, the audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; bf16 or block fp8, one card |
The traps below are readings that are wrong without any error: the model produces fluent output.
@@ -228,7 +234,9 @@ Three groups, which is why hybrid KV groups are first-class:
across the 48 linear layers, and it is what the prefix-cache checkpoint of `spec.md` §7.3
snapshots. Its reads and writes dominate the two GDN kernels. libr4d also compiles an f16 form
(elements are O(0.1); the f16 round trip is about 5e-4 relative) that would halve that traffic,
but the plugins declare f32 because f16 changes the generated text. How a speculative step keeps a
but the plugins declare f32 because f16 changes the generated text; `--state-cache-dtype f16`
declares f16 for a deployment that accepts the loss (GUIDE §4.4: on Qwen3.8-27B MXFP4, mean KL
+0.9..+2.2 %, decode +10 % at sixteen streams without speculation). How a speculative step keeps a
state it can roll back is `docs/OPS.md`'s `state_form`.
## FP8
@@ -283,6 +291,67 @@ head (393 against 282 tok/s on two R9700s). `sage-a1.5-mxfp4-df2.rad` is the sam
the experts and the drafter's linears at MXFP4. `--num-speculative-tokens auto` takes the depth the
drafter states.
## `hyv3`
`arch/hyv3_bf16` supports the Tencent BF16 safetensors checkpoint, and `arch/hyv3_fp8` supports
Tencent's FP8 checkpoint. Both use the same graph: 48 layers, with a dense first
MLP followed by 47 layers routing top-8 of 128 experts. The routed and shared MLP widths are both
768 in the checkpoint tensors. Attention applies per-head Q/K RMSNorm before NeoX RoPE. Routing selects
with sigmoid scores plus the correction bias, but normalizes the selected unbiased scores and
multiplies them by 2.826. Routed and shared BF16 outputs are reduced independently at TP2, then added
in FP32 and rounded once to BF16 before the residual add. At TP1 the existing ungated gather
preserves those two arm roundings and folds their addition; the plugin prepares one shared ones
plane for the whole step. Each residual add except the final one folds into the following norm,
which normalizes the BF16-rounded sum. The final norm still reads a materialized residual stream.
Convert the public FP8 checkpoint with
`data/recipes/hy-memory-30b-a3b-fp8.recipe`; it preserves the E4M3 codes and expands the checkpoint's
scalar F32 scales to the 128x128 F32 scale planes the GEMMs read. Norms and the router projection
are widened to F32. Linear activations use Radiance's dynamic FP8 quantization; the checkpoint's
static `.input_scale` calibration scalars are ignored, so numerical parity with vendor quantization
is not established. The checkpoint index includes scalar per-layer K/V descales from
`kv_cache_scales.safetensors`; conversion carries them into metadata for `kv_store` and paged
attention. Use `--kv-cache-dtype fp8` for the checkpoint's static-scaled E4M3 cache, or `bf16` for a
higher-precision cache. The plugin refuses the unrelated `fp8_v4` and `k6_v4` cache layouts.
The vendor FP8-source import and static-scaled FP8 KV path have structural/unit coverage only;
an end-to-end conversion and serving run of Tencent's FP8 checkpoint is not yet validated.
This is distinct from the BF16-derived block-FP8 artifact tested below.
The BF16 checkpoint can be converted without quantizing any weights, or with
`data/recipes/hy-memory-30b-a3b-bf16-w4.recipe`, which quantizes attention projections, the first
dense MLP and routed experts to INT4. Shared MLPs, router, norms, embeddings and the output head stay
BF16. At decode the asymmetric linear W4 kernel narrows BF16 activations to F16 on load;
above 64 rows its tiled path uses dynamic INT8 activations. The signed-I4 expert path uses
block-scaled E4M3 activations. BF16-source block-FP8 and MXFP4 recipes quantize experts and regular
linears; the W8 recipe quantizes regular linears and the output head while routed experts remain
BF16. Use TP2 at serve time if one device cannot hold the model and cache.
The local llama.cpp Q4_K_M source is supported by `arch/hyv3_gguf` and
`data/recipes/hy-memory-30b-a3b-gguf-q4k-to-w4.recipe`. It decodes Q4_K/Q6_K source tensors and
re-quantizes them to native Radiance encodings; this adds loss to an already-quantized checkpoint.
The GGUF's `hunyuan-dense` pre-tokenizer name is not in Radiance's tokenizer table, so pass the
matching BF16 repository's `tokenizer.json` with `--tokenizer`. Prefer the BF16 source recipe when
available. Both the BF16 W4 and GGUF-to-W4 artifacts passed a short TP2 generation smoke test; the
BF16-source W8, block-FP8 and MXFP4 variants did too. These checks establish basic loading and
inference only, not numerical parity or broad quality.
The plugins declare the native OpenAI tool-call format: an outer `<tool_calls>` section,
`<tool_call>NAME<tool_sep>` calls, and tagged `<arg_key>`/`<arg_value>` arguments. The parser and
grammar preserve that section in non-streaming and streaming responses and accept replayed
OpenAI tool results through the checkpoint's chat template. When `reasoning_effort` is `low` or
`high`, the template opens `<think>` in the generation prompt and the parser returns that block
as reasoning rather than answer text. The default template effort is `no_think`.
Architecture tests cover geometry, GGUF tensor maps, dense-to-MoE scheduling, TP1/TP2 graph lint,
and FP32 combine order; checkpoint tests cover Q4_K/Q6_K block decoding. Numerical parity against Tencent/llama.cpp
remains untested.
Decode on the full-GPTQ W4 model, TP1 on one R9700 (10,030-token prompt, 2,000 generated tokens,
greedy, no drafter): 76.6 tok/s before the per-128 I4 expert packing, the one-row W4/W5 epilogue,
the in-GEMM BF16 narrowing, the fused Q/K norm + RoPE + KV store and the residual and shared-expert
folds; 109.6 tok/s with them, prefill unchanged (7,876 to 7,927 tok/s). The answer is byte-identical,
and on an eight-document teacher-forced corpus the two builds agree at every top-1 (mean KL 7.6e-8).
## `qwen35_w8a8`
The dense build again, behind `#if QWEN35_W8A8`, for a container `data/recipes/q38-27b-w8a8-df2.recipe`
@@ -306,6 +375,14 @@ a plain int8 trunk is refused.
take `had_quant_act_i8g` from the bf16 plane, and so does every linear where the ops are not
declared (libref and libavx). The MLP's gated fold is an fp8a8 tile over E4M3 codes, so an int8
gate_up runs the pair.
- **Narrower codes on the same grid.** A trunk linear stored as uN with a zero point, uN indexing
an int8 scalar codebook or a vector codebook of int8 codewords, or a bitshift trellis's codes,
each under a scale per (row, 128) and fwht128, or a computed trellis (libquant's `tcq_code=mad`,
its constants in a `trellis.mad` plane) under one f32 scale a row and one a 128-K block for all
rows (`scale.col`; a view of `scale,scale.col`), stays at its codes' width in VRAM: libr4d's
`gemm_iqr` rows decode it where they read it, and `embed_lookup_iqr` and `logits_gemm_iqr` do the
same for such an embedding and head. The IQR recipes (`data/recipes/q38-27b-iq{2..8}r*.recipe`,
[`docs/IQR.md`](IQR.md)) store 2.5 to 8 bits a weight on the int8 trunk's activation path.
- **It declines imported checkpoints** (`RAD_ARCH_SERVES_IMPORTS(0)`). An imported quantisation
goes to the family's one quantised plugin, and a second one would refuse every Quark, ParoQuant,
GPTQ or NVFP4 Qwen3.8 release; they stay with `qwen35_fp8`.
@@ -350,6 +427,13 @@ plugin reads each weight's encoding from the container and declares the op that
- bf16: every norm gain, `A_log`, `dt_bias`, `conv1d`, `in_proj_a` and `in_proj_b` (48 rows is not
a whole scale block), the router, `shared_expert_gate` and `embed_tokens`.
Qwen's own `Qwen3.8-Flash-Next-FP8` converts without a recipe too. Its `quantization_config`
(`quant_method: fp8`, no `fmt`) is block-scaled E4M3, descriptor `fp8_e4m3`; no `qwen4exp` plugin
claims it, so each weight is read as it ships and this plugin serves it: the routed experts (MTP
head's included) at block FP8 with their bf16 `weight_scale_inv`, the n-gram table's 128 FP8
shards under its one `ngram_embedding.weight_scale`, and every other weight bf16. A recipe applies
to it as to the bf16 checkpoint, with each FP8 weight read through its scales.
**The attention cache takes `--kv-cache-dtype fp8_v4` or `k6_v4`.** The QSA layers' cache (and the
MTP head's layer, which shares it) is then declared at head_dim 200 or 176, a token's quantised row
over two, and read by the gqa12 rows (gqa6 with 4-token pages at four ranks) of those layouts
@@ -447,12 +531,12 @@ the blocks share, places them and issues the step's order.
|---|---|---|
| `rad_block_glm_mhc.h` | `ManifoldConn` | the four-stream residual's read and write |
| `rad_block_glm_kda.h` | `GlmKda`, `KdaState` | the 34 linear layers and their recurrence |
| `rad_block_glm_mla.h` | `GlmMla`, `MlaLatent` | the 11 sparse MLA layers and their absorbed core |
| `rad_block_glm_mla.h` | `GlmMla`, `MlaLatent` | the 11 sparse MLA layers, in the head form or the row form |
| `rad_block_glm_indexer.h` | `GlmIndexer`, `DsaCache` | the DSA indexer, its key cache and selection |
| `rad_block_glm_router.h` | `GlmRouter` | the correction-bias router, through `MoeFP8` |
| `rad_block_glm_mtp.h` | `GlmMtp` | the draft head around the plugin's layer 45 |
| `rad_block_glm_vision.h` | `GlmVision`, `MediaRows` | the tower, and its rows over the embeddings |
| `rad_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the split threshold, the column split of a replicated f32 projection |
| `rad_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the one row rule, the split thresholds, the column split of a replicated f32 projection |
```
45 layers, hidden 4096, vocab 154880 (embedding and lm_head separate, bf16)
@@ -548,45 +632,64 @@ at eight ranks each card holds 22.06 GiB of them, 19.67 GiB the routed experts.
layer's latent, index and tail for every row and runs its MoE on the proposal rows only.
**Tensor parallelism.** At 1, 2, 4 or 8 ranks; declare refuses any other. `tests/glm5next_test.cpp`
declares and steps the whole plugin at 1, 4 and 8, against pinned graph and step hashes at 1 and
8, the connection, router and index-gate splits at 1, 2, 4 and 8, the indexer's row split at 2
and 8, the row rule at every world, each issue's operand count against the loaded kernel
libraries' schemas, and every declared weight against the served container's names and encodings.
declares and steps the whole plugin at 1 and 8 against pinned graph and step hashes (the head form,
the row form), the connection, router and index-gate splits at 1, 2, 4 and 8,
the indexer's row split at 2 and 8, the MLA row split at 1, 2, 4 and 8, the row rule at every
world, each issue's operand count against the loaded kernel libraries' schemas, and every declared
weight against the served container's names and encodings.
One row rule (`GlmTp::run_rows`): from a pass of `GlmTp::kSplitRows` = 256 rows, a replicated
piece of work splits by rows over the ranks instead, each rank taking one run of ceil(T / world)
rows rounded up to whole 16-byte words of the row it gathers, because an `all_gather` moves whole
words: multiples of four rows for the indexer's one i32 length a row. The last run may be short;
a rank whose run lies wholly past a small step takes the first run and computes dead rows, so
every plane it gathers is written (`GlmTp::run_of`). The indexer also splits a smaller step, from
16 rows once rows x live blocks reach 2^18 (`GlmTp::kSplitWork`). Below the thresholds, as in
decode, the collective costs more than it saves and every rank runs the replicated form.
One row rule (`GlmTp::run_rows`): from a pass of `GlmTp::kSplitRows` = 256 rows, a replicated or
head-split piece of work splits by rows over the ranks instead, each rank taking one run of
ceil(T / world) rows rounded up to whole 16-byte words of the row it gathers, because an
`all_gather` moves whole words: whole rows for the MLA's 4096-wide bf16 output, multiples of four
rows for the indexer's one i32 length a row. The last run may be short; a rank whose run lies
wholly past a small step takes the first run and computes dead rows, so every plane it gathers is
written (`GlmTp::run_of`). The indexer alone also splits a smaller step, from 16 rows once rows x
live blocks reach 2^18 (`GlmTp::kSplitWork`). Below the thresholds, as in decode, the collective
costs more than it saves and every rank runs the replicated or head-split form.
- The routed and the shared experts split their 2048 width into equal contiguous slices, 256 a
rank at eight; each rank computes its slice of every expert, and the block's all-reduce sums
them. The dense feed-forward splits its 12288 the same way.
- MLA splits by whole heads: the rows of q_b and kv_b (8 heads a rank at eight) and the columns
of o. q_a, kv_a and the latent are replicated.
of o. q_a, kv_a and the latent are replicated. Under `--tp-attn-split rows`
(RadBuildCtx::tp_attn_rows, docs/GUIDE.md §4.7), from the threshold, it splits by rows instead
(`GlmMla::Form::rows`): each rank takes its run under the row rule, the last run shorter,
through q_b, absorption, attention with all 64 heads (`mla_attn_rows_bf16`, docs/OPS.md),
expansion and o, and an `all_gather` of whole runs takes the all-reduce's place. The latent
cache and the DSA selection are whole on every rank, so nothing is exchanged before the
attention. Each rank sends its run to seven peers, half the bytes of the two-shot all-reduce,
and the gather shares that all-reduce's exchange instance. The price is q_b, kv_b and o at full
width on every rank, 120 MiB a layer and 1.29 GiB a card over the 11 trunk layers (the MTP layer
keeps its heads), about 0.1 GiB of activations besides. The head form is the default because
the row form is not bit-identical to it, and this model turns that into a measurable
divergence: against the head form over a 66,657-position corpus of English, German and code at
eight ranks the row form scores a mean KL of 0.038 (median 0.010, p99 0.357, top-1 agreement
91.9 %). The projections are not the cause (q_b and o give the head form's bytes, and o summed
as eight rank partials leaves the KL where it is); the attention's rounding is: the rows kernel
parts from the paired tile in about 0.1 % of every row's outputs by one bf16 step, and the
16-head tile, which parts in the same share of every second row only, halves the KL. On eight
R9700 at Gen5 links the row form prefills a 20k-token prompt at 5,016 tok/s against 4,246 in
the head form (+18 %) and a 64k-token one at 4,975 against 4,117 (+21 %); decode is unchanged.
- KDA splits its 64 heads, with them the q/k/v rows, the convolution taps and the state; the two
rank-128 projections into the gates are replicated.
- The indexer's key side is replicated: every rank keeps the whole index cache and its tail. Its
query side splits by rows from the threshold: each rank scores its run under the row rule,
R = 4 * ceil(T / (4 * ranks)) query rows (`DsaCache::part_rows`), against the whole cache
(`dsa_score` with `row_part`, the last run's rows past the step scoring `-inf`) and selects for
the rows of its run that exist, under the bounds the scorer rebased to the run's first row
(`cu_part`, docs/OPS.md); two `all_gather`s lay the runs' page tables and lengths end to end,
513 and 1 i32 a row, 8 MiB a layer at a 4096-row chunk. The run's queries are all a rank needs,
so the query projection, its quantiser and the head gates run on the run's rows too, and the
gates need no gather; the bf16 projection stays on the step's rows where a run would be 64 rows
or fewer, the skinny band whose split count a tuned configuration may set. Each row's selection
is the same kernels' answer to the same operands, so the joined table is bit-identical to one
rank's and MLA reads it unchanged. The scoring grows with the context (every row scores every
complete block of its sequence), so this is where long prompts gain: the score plane shrinks to
one run (256 MiB to 32 MiB at 64k of context and a 4096-row chunk). A smaller step splits too
from 16 rows once rows x live blocks reach 2^18 (`GlmTp::kSplitWork`): eight sequences
verifying five drafts from about 22k of context, where the scoring of 48 rows outweighs the two
gathers; a single sequence's decode never does, and below both thresholds the indexer runs
whole.
R = 4 * ceil(T / (4 * ranks)) query rows (`DsaCache::part_rows`), against the whole cache (`dsa_score` with `row_part`,
the last run's rows past the step scoring `-inf`) and selects for the rows of its run that exist,
under the bounds the scorer rebased to the run's first row (`cu_part`, docs/OPS.md); two
`all_gather`s lay the runs' page tables and lengths end to end, 513 and 1 i32 a row, 8 MiB a layer
at a 4096-row chunk. The run's queries are all a rank needs, so the query projection, its
quantiser and the head gates run on the run's rows too, and the gates need no gather; the bf16
projection stays on the step's rows where a run would be 64 rows or fewer, the skinny band whose
split count a tuned configuration may set. Each row's selection is the same kernels' answer to
the same operands, so the joined table is bit-identical to one rank's and MLA reads it unchanged.
The scoring grows with the context (every row scores every complete block of its sequence), so
this is where long prompts gain: the score plane shrinks to one run (256 MiB to 32 MiB at 64k of
context and a 4096-row chunk). A smaller step splits too from 16 rows once rows x live blocks
reach 2^18 (`GlmTp::kSplitWork`): eight sequences verifying five drafts from about 22k of
context, where the scoring of 48 rows outweighs the two gathers; a single sequence's decode never
does, and below both thresholds the indexer runs whole.
- The vocabulary is row-sharded, 19360 rows a rank at eight; the embedding's all-reduce is exact.
- The f32 projections (the router's 288 x 4096, the index head gates' 32 x 4096, each
connection's mHC projection of 24 x 16384) are replicated. From a pass of 256 rows
@@ -769,6 +872,184 @@ Traps:
---
# `nemotron35_embed`: embedding models
Native BF16 [Nemotron 3.5 Embed 1B](https://huggingface.co/nvidia/Nemotron-3.5-Embed-1B-BF16)
and [8B](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16) are bidirectional multimodal
encoders, selected by `(mistral3, "")` with noncausal Mistral3/Ministral3 checks. They declare
pooled output and no language-generation head. CPU (`libavx`, with `libref` as the oracle) and
RDNA4 (`libr4d`) serve BF16 at TP1; quantized planes, TP>1, drafting and audio are rejected.
[GUIDE §5.6](GUIDE.md#56-completions-embeddings-images-tokenising) covers serving and retrieval inputs.
| Checkpoint | Pinned revision | Text geometry | Default vector |
|---|---|---|---:|
| 1B BF16 | `e24ca1e346bcc53572bd7bdc02b3e8ebf66c197c` | 16 layers, hidden 2048, FFN 6144, 24 Q / 8 KV heads | 2048 |
| 8B BF16 | `781e779ee4ca9c2d2a4f38321993556baeab49a1` | 34 layers, hidden 4096, FFN 14336, 32 Q / 8 KV heads | 4096 |
Both have 128-wide text heads. The 1B query width is 3072, independently of its hidden width.
Each uses its own checkpoint weights and embedding space. The vision tower is Pixtral: 24 layers,
hidden 1024, 16 heads of width 64, 14-pixel patches and a learned 2x2 patch merger/projector.
**Numerical contracts.** Native safetensors mapping fuses QKV and gate/up without changing
precision. Attention is bidirectional over each complete input and isolated across inputs.
Pooling is the valid-token mean; dimensional truncation precedes L2 normalization.
Ministral rounds the weightless norm before applying its BF16 gain. Its rotary rounds cos/sin
and individual products to BF16, with model-local YaRN magnitude and position-dependent query
scaling, including the position-16384 seam. Shared rotary defaults remain unchanged. Pixtral
preserves axial height/width rotary, channel-major patch merging, exact GELU and BF16 seams.
Only actual `[IMG]` rows receive image embeddings; separator embeddings remain ordinary tokens
and participate in pooling. The model-specific operation laws are in [OPS.md](OPS.md).
**Context and images.** The maximum is 32768 total encoded tokens per input, including prefixes,
image placeholders and separators. The backbone's 262144 positional slots do not establish a
larger supported embedding context. Inputs are never silently truncated. Configured per-input,
combined-token, sequence-slot and image-pass budgets remain separate limits.
The default longest edge is 1120, without initial enlargement. Reference PIL bicubic resizing
aligns dimensions to 28, followed by CLIP normalization and raster 14x14 patches. The default
maximum square has 6400 patches and must fit one encoder pass. The published 1540-pixel option
and larger image settings are not validated by this port.
**Verification.** Stored tiny fixtures cover issued graphs, exact preprocessing/token identity,
BF16 seams, ragged multimodal inputs, invalid shapes and both head geometries. The regular C++
suite needs neither Python nor downloaded checkpoints. Opt-in R9700 entries are
`nemotron35_device_test_card` and `r4d_bf16_capacity_test_card`; the latter uses over 8 GiB VRAM
to cross actual activation-offset boundaries, with bounded host staging.
The offline native oracle uses CPU torch 2.14.1, matching torchvision 0.29.1, Transformers 5.20.0
and Pillow 13.0.0, explicitly selecting PIL preprocessing and never running remote model code:
```sh
HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 python tests/mknemotron35realreference.py \
/models/Nemotron-3.5-Embed-1B-BF16 /tmp/nemotron-reference.json --extended
RAD_NEMOTRON_REAL_FIXTURE=/tmp/nemotron-reference.json RAD_NEMOTRON_DEVICE=1 \
RADIANCE_HOME="$PWD/build/radiance_home" RAD_TEST_CPU_BUDGET=0 OMP_WAIT_POLICY=passive \
build/tests/engine_e2e_test nemotron35_real
```
Use the corresponding native checkpoint for 8B; omit `RAD_NEMOTRON_DEVICE` for CPU execution.
`RAD_NEMOTRON_DEVICE_INDEX=1` selects another physical card. Run large checks sequentially; 8B
needs roughly 20 GB available host memory. Tiny gates are relative L2 <=.01 and cosine >=.9995.
Native gates are cosine >=.9995, normalized L2 <=.032, norm error <=1e-5 and pairwise-score error
<=.005, fixed before candidate evaluation. The full-model bound accounts for audited BF16
backend sensitivity: eager-vs-SDPA alone reached 2.805% normalized L2 on the 8B samples.
Individual/batched vectors must agree within L2 <=1e-5; native ranking margins >.01 must retain
their ordering. These gates are not bitwise or broad retrieval-quality guarantees.
CPU/R9700 comparisons cover both variants; the extended 1B corpus reaches 1924 tokens with
English/Spanish/Japanese retrieval groups. Separate synthetic capacity checks cover a complete
32768-token input, four full 1B inputs in one 131072-token step and a default maximum image.
They do not establish native accuracy at maximum context/resolution. Native INT8/Q8, GGUF and
TP2 remain unimplemented.
**Nemotron 3.5 Rerank 8B.** The same plugin recognizes the native
`Mistral3ForSequenceClassification` checkpoint, pinned at
`f88f8d9104726747791283ab156d2fcdb29e90a7`. It uses its own weights, the 8B text/vision
geometry above under `model.*`, and a bias-free `language_model.score.weight` [1,4096] head. Native
pooling stores the masked sum in BF16 before division, then stores the mean in BF16.
The separate `seg_mean_bf16_sum` operation preserves this seam without changing
embedding pooling. `logits_gemm` projects the mean and BF16 head to an FP32 scalar;
this is pooled output, with no generation sampler or KV cache. The endpoints return
raw logits, including negative values, rather than normalized embeddings.
The supported per-pair context remains 32768, including query/document prefixes and
images. The native training template requires text queries and at most one image
per document. The image, context and configured capacity distinctions above apply.
Stored tiny reranker fixtures and the opt-in native reference generator are
`tests/mknemotron35rerankgolden.py` and `tests/mknemotron35rerankrealreference.py`.
Both are offline tools; runtime/build/tests never download a checkpoint or execute
remote model code. CPU component gates include exact BF16 pool results and scalar
error <=.01 for the tiny text/image graphs. Native validation uses raw-score error
and ranking gates rather than embedding cosine tolerances.
```sh
python3 tests/mknemotron35rerankrealreference.py /models/Nemotron-3.5-Rerank-8B-BF16 /tmp/rerank-reference.json --sdpa-audit
RAD_NEMOTRON_RERANK_REAL_FIXTURE=/tmp/rerank-reference.json \
RAD_NEMOTRON_DEVICE=1 RADIANCE_HOME="$PWD/build/radiance_home" \
build/tests/engine_e2e_test nemotron35_rerank_real
```
Download the pinned revision above; an optional local `asset-manifest.json` is verified
when present. Standard Hugging Face revision metadata is also recognized; absent metadata
is recorded as unknown. The full-model gates are raw-score maximum absolute error <=.05,
RMSE <=.02, individual/batched difference <=1e-5 and preserved ranking for native margins
>.10. Omit `RAD_NEMOTRON_DEVICE` for CPU execution, as above.
---
# `nomicbert`: an embedding model
`arch/nomicbert` declares a pooled output (`rad_declare_pooled`) and no logits, so it is an
embedding program like `embgemma2`: no sampler, no KV cache, one step per input, and the pooled
row on `/v1/embeddings` ([GUIDE §5.6](GUIDE.md)). One card (`--tp 1`).
```
text 12 layers, hidden 768, ffn 3072, vocab 250048, 12 heads of 64, type vocab 1
trained to 2048 positions; 475M parameters
post-norm block: a = out_proj(attn(rope(Wqkv h + b))) + b_out; h = LN1(h + a)
even layers: dense MLP, fc2(gelu(fc1 h + b1)) + b2, exact gelu
odd layers (1, 3, 5, 7, 9, 11): 8 experts at top 2, softmax weights,
no renormalisation, no shared expert
fused Wqkv [q|k|v], no GQA, non-causal, scale 1/sqrt(64) = 0.125
NeoX rotary over all 64 dimensions, theta 1e4, on q and k only, no position table
embeddings: word + token_type, then emb_ln; no final norm
mean over every real token, cast to the f32 pooled buffer; the server L2-normalises
```
Block order: attention on the raw stream, then LN1, the feed-forward on LN1's output, then LN2
over that output plus the feed-forward's. The checkpoint's shared `experts.bias` is not applied,
and the plugin does not map it. A container that sets
`prenorm`, `causal`, interleaved, partial or scaled rotary, a gelu variant, renormalised routing
or a shared expert is refused at declare.
**Tensor names.** `N` is a layer; even layers are dense and odd layers are routed. `E` is an
expert. Norms and biases stay f32; the token-type table is bf16 because `table_add`'s device row
reads a bf16 table. The token embedding, linears, router and expert tables are bf16.
| container | checkpoint | shape | map |
|---|---|---|---|
| `token_embd.weight` | `embeddings.word_embeddings.weight` | [250048, 768] | copy |
| `token_type.weight` | `embeddings.token_type_embeddings.weight` | [1, 768] | copy |
| `emb_ln.*` | `emb_ln.*` | [768] | copy |
| `blk.N.attn_norm.*`, `blk.N.ffn_norm.*` | `encoder.layers.N.norm1.*`, `encoder.layers.N.norm2.*` | [768] | copy |
| `blk.N.attn_qkv.*`, `blk.N.attn_out.*` | `encoder.layers.N.attn.Wqkv.*`, `encoder.layers.N.attn.out_proj.*` | [2304, 768]/[2304], [768, 768]/[768] | copy |
| `blk.N.ffn_fc1.*`, `blk.N.ffn_fc2.*` (even N) | `encoder.layers.N.mlp.fc1.*`, `encoder.layers.N.mlp.fc2.*` | [3072, 768]/[3072], [768, 3072]/[768] | copy |
| `blk.N.ffn_router.weight` (odd N) | `encoder.layers.N.mlp.router.layer.weight` | [8, 768] | copy |
| `blk.N.ffn_exp_w1.E.weight` (odd N) | `encoder.layers.N.mlp.experts.mlp.w1` | [3072, 768] | slice E |
| `blk.N.ffn_exp_w2.E.weight` (odd N) | `encoder.layers.N.mlp.experts.mlp.w2` | [768, 3072] | slice E, transpose |
| not declared (odd N) | `encoder.layers.N.mlp.experts.bias` | [768] | not mapped |
The checkpoint stores `w1` and `w2` as one stacked tensor each, `[24576, 768]`; expert `E` is rows
`[E * 3072, (E + 1) * 3072)`, and `w2`'s block is transposed to `[768, 3072]` for the grouped GEMM.
Every expert has two group slots, one for each projection. Nothing else is mapped: there is no
final norm, no pooler, no position table and no output head.
**The recipe.** The checkpoint is f32 (1.9 GB).
```sh
rad-convert <checkpoint dir> --recipe data/recipes/nomic-embed-v2-moe-bf16.recipe \
-o nomic-embed-v2-moe-bf16.rad
```
It writes a 959 MB container (907 MiB of weights). The checkpoint directory must contain
`tokenizer.json`. The recipe casts the token embedding, the token-type table, the attention,
dense MLP and expert weights to bf16 and leaves the norms and biases f32.
**Verified.** On 20 texts against a pure-float32 reference, on a gfx1201 card: mean cosine
0.99995, min 0.99983; libavx and libref agree with it to 4 decimals. Against the same reference a
Q8_0 quantisation of the model scores a mean of 0.9994 and a Q6_K one 0.9944 (min 0.990), so
vectors stored from a Q6_K server differ by about 0.006.
**Measured.** On one gfx1201 card, short texts take 2 ms a request at one client, 3854 requests/s
at 64 concurrent clients and 4400 texts/s for a batch of 32 in one request; a 1354-character text
takes 3 ms; about 1.2 GB of VRAM. On 24 CPU cores libavx has a median 18 ms a text.
**Not verified.** Inputs above 512 tokens against a device reference, other precisions, and tensor
parallel (the model is served on one card).
---
# `gemma4`: Gemma 4 text and its DFlash drafter
`arch/gemma4` serves a container converted from Google's bf16 checkpoint
@@ -950,6 +1231,17 @@ the whole 128-row scale blocks that cover its share of the columns and an `all_g
them, with `gemm_nt_q`'s `split_n` keeping every output the unsplit fc's to the bit. The recipe is
`gemma4-31b-dense-bf16-w4a8-df2.recipe`.
**The 31B by GPTQ.** `arch/gemma4_bf16`'s linears read int8 activations, which the Gram tap
(`gram_accum`) does not take, so the 31B's Hessians come from this plugin serving the bf16
checkpoint. With `RADIANCE_CALIB_DIR` set it taps each layer's dense linears, the routed arm aside:
rank 0 writes q|k|v's and gate|up's inputs whole, and each rank writes its columns of o's and
down's inputs as `<stem>.part`, all under the names `gemma4_bf16`'s container gives those weights
(`blk.N.attn_qkv`, `ffn_gate_up`, `attn_o`, `ffn_down`), so
`data/recipes/gemma4-31b-dense-bf16-w4a8g-df2.recipe` reads them as written. The prefill overlap
and the fused arms are off while it runs. `RADIANCE_G4_CALIB_LAYERS=lo:hi` takes a slice of layers:
the 31B's four taps a layer are ~364 MiB a rank at four ranks, and its 60 layers do not fit beside
the weights in one pass. docs/GEMMA4-31B-GPTQ.md has the corpus, the run and what it changes.
**The 31B's junctions at four ranks.** At two ranks every junction carries the all-reduce in front
of it (`ar_rmsnorm_quant_i8`). At four it does too, in steps of up to 16 rows (decode, and a DFlash
or DFlash2 verify), on libr4d's `ar_rmsnorm_quant_i8_4rank`, in a form chosen by height. Every form
@@ -973,6 +1265,16 @@ step at tp 4 then has two standalone reductions (the embedding's and the last fe
it had 121. `r4d_selftest --case ar_rmsnorm_quant_i8_4rank` checks every form on four cards, and
the startup note says which forms a deployment takes.
**Junctions on the int8 grids with a scale per (row, 128).** A trunk at i8a8, or at asymmetric int4
or int5 (`codes=u4|u5 zero=u8 group=128 scale=f16`), reads `quant_act_i8g`'s pair. Its junctions
are libr4d's `_i8g` twins of the three above (`rmsnorm_quant_i8g`, `gelu_mul_quant_i8g`, and at two
ranks `ar_rmsnorm_quant_i8g`; at four the all-reduce in front of each is issued apart), so the
prefill overlap runs on these trunks too. An int4 or int5 linear reads an f16 copy of its input up
to 64 rows (`w4a16_asym`, `w5a16`): in such a step each junction also writes the bf16 norm output
into `h`, where the unfused norm would, the linear casts it as before, and the feed-forward keeps
`gelu_mul`. `r4d_selftest --case rmsnorm_quant_i8g` (and `gelu_mul_quant_i8g`,
`ar_rmsnorm_quant_i8g`) holds each to its chain.
**Weight reads beside the all-reduces.** At more than one rank, on decode and verify steps of up to
16 rows that carry no prompt rows, the 31B reads the next GEMM's leading weight bytes into the
on-die cache (libr4d `prefetch`) while an all-reduce leaves the card's memory idle: gate_up's first
@@ -983,6 +1285,31 @@ chained form right behind the GEMM before the reduction, otherwise it rides the
reads change no value; on 4x R9700 the 31B with DFlash2 decoded 15% faster with them, and without
a drafter about 2%.
**The E2B/E4B form.** `arch/gemma4_bf16` serves Gemma 4's small dense form (tested on
NVIDIA-Nemotron-3.5-Bolt-E4B, `deploy/compose/nemotron-3.5-bolt-e4b-bf16.yaml`, and on Google's
gemma-4-E2B-it) at one rank:
- KV-shared layers: from layer `n_layer - num_kv_shared_layers` on, a layer projects q only and
attends over the cache of the last earlier layer of its class that keeps one (E4B: sliding layers
read 22, full layers 23). Shared layers are not bound to a KV group, so their pages hold nothing.
- Double-wide MLP (`use_double_wide_mlp`, E2B): those same layers have 2 * `intermediate_size` in
both projections. Each layer declares its own weight shapes and op widths, and the two widths keep
a pair of activation buffers each.
- Per-layer embeddings (`hidden_size_per_layer_input`): a token table scaled by sqrt(width), plus
the normed projection of the scaled embedding, mixed at 2^-0.5. Each layer runs a branch after
its feed-forward: gate, gelu times its slice, projection, norm, add. On a w4a8 or w8a8 trunk
the junction closes that branch instead of the feed-forward. Image positions read the pad
token's row of the table, as the reference does. The branch is not split across ranks, so a
deployment at more than one rank is refused.
- The global class may keep its own v (`attention_k_eq_v` 0) and leave
`num_global_key_value_heads` null; it then takes `num_key_value_heads`.
- The vision tower's clipped linears (`use_clipped_linears`) clamp each projection's input and
output to the bounds the checkpoint stores (`rad_block_gemma4_vision.h`).
NVIDIA's DFlash drafter states `dflash_config.causal: false`, with every layer sliding; that flag
sets the sliding layers' causality. The recipes are `gemma4-e4b-bf16-df`, `-w8a8-df`, `-w4a8` and
`-w4a8-df`. The bf16 container's KL to HF bf16 is 0.0015 with bf16 KV and 0.014 with fp8 KV, so
the compose file serves bf16 KV.
**FP8 experts.** The experts are ~90% of the weight bytes, so each projection is served as the
container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up
`[1408, 2816]` is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not (the fp8 grouped
@@ -1088,11 +1415,26 @@ above), which matters little for translation prompts, whose shared prefix is a l
A linear reading the same activation as the one before it (k and v after q, up after gate) reuses
its codes. On every trunk the q and k norms and both rotaries are one `qkv_norm_rope` at `v_norm` 0.
On an MXFP4 trunk each junction (the branch's post-norm, the residual add, the next norm and the
next linear's E4M3 quantiser) is one `ar_rmsnorm_post_quant_fp8` at two ranks on the exact wire,
the branch's all-reduce in the same launch, or a post-norm and `rmsnorm_quant_fp8` otherwise; a
w4a8 / w8a8 trunk takes `gemma4_bf16`'s fused junctions; an i8a8 or asymmetric-int4 trunk runs the
chain. Where a row is missing the plugin declares the chain, and the startup notes say which form
each took. Under calibration no junction is fused (below).
next linear's E4M3 quantiser) is one `ar_rmsnorm_post_quant_fp8` at two ranks, the branch's
all-reduce in the same launch, or a post-norm and `rmsnorm_quant_fp8` otherwise; a w4a8 / w8a8
trunk takes `gemma4_bf16`'s fused junctions; an i8a8 or asymmetric-int4 trunk runs the chain.
Where a row is missing the plugin declares the chain, and the startup notes say which form each
took. Under calibration no junction is fused (below).
The two fused all-reduce junctions (`ar_rmsnorm_post_quant_fp8`, and `ar_rmsnorm_quant_i8` on a
w4a8 / w8a8 trunk's int8 junction) send the exact wire only, and are byte-identical to
`all_reduce` followed by the chain. Under `--tp-wire wht6` they are declared all the same and taken
per step where the message goes out exact anyway (`ar_wire_is_exact`: a decode step of a few rows,
under `--tp-wire-min-kb`); a wider step keeps the lossy all-reduce, unfused, so a lossy-wire
deployment's decode takes one launch a junction instead of three (all-reduce, post-norm,
junction). A fused step is the unfused exact step bit for bit.
**Pipelined prefill.** At two ranks an MXFP4 trunk with the fused fp8 junctions prefills a prompt
of 1024 tokens or more in two pieces, the junctions and all-reduces of one beside the other's
compute (GUIDE §4.5). The window KV group's `seqused` counts from its
rebased first block, so the first piece's bound is computed on the card (`sub_i32`: the group's
`seqused` less the second piece's rows), not taken from its position. The gain needs 1024-row
pieces: serve at `--max-num-batched-tokens 2048`.
**Calibration.** Serve a calibration container (int8, `translategemma-27b-i8a8.recipe`: KL 0.003
against bf16, and it fits two 32 GB cards) with `RADIANCE_CALIB_DIR` set, push a corpus of the
@@ -1601,16 +1943,158 @@ codes. Whisper large-v3 transcribes radiance's speech word for word.
---
# `fishomni`: Fish Audio drama-3, speech
`arch/fishomni` declares an audio generator in its chunked form with one branch a request
(`rad_declare_audio_generator`, `branches` 1, `voc_chunk`): PROMPT runs the backbone over the
whole prompt and the codebook tower over every prompt row, FRAME draws one frame of every speech in
flight and runs the backbone over its embedding, VOCODE plays a lane's newest frames, sixteen at
most. It is served on `/v1/audio/speech` and `/v1/audio/speech/stream` ([GUIDE §5.15](GUIDE.md)),
on two cards. The checkpoint is the release directory; its codec, `codec.pth`, is read with it as
checkpoint tensors under `codec.` (a `torch.save` archive, read as data and never unpickled:
`core/format/torch_zip.h`).
```
backbone Qwen3.5-35B-A3B's language model, unchanged: 40 layers of 2048, three gated delta-net
layers to one gated attention layer (16 q / 2 kv heads of 256, NeoX rotary on 64 dims
at theta 1e7), 256 experts of 512 at top-8 and a gated shared expert of 512, (1 + w)
norms but the delta net's output norm. Only the routed experts are fp8 (E4M3 at an f32
scale a 128 x 128 block, `quant_method: bsgemm-moe`); the rest is bf16. A prompt row is
a token; a frame's row is bf16(bf16(E_lm[248099 + c0] + E_cb[4096 + c1]) / sqrt 2):
code 0 through its semantic token, code 1 through section 1 of the codebook table
head the main token over 4097 candidates only, the end of speech (248046) and the 4096
semantic tokens in id order: the lm_head's rows for them, replicated (the full head is
never declared)
tower 13 layers bound as layers 40..52 of the backbone's full-attention KV group, causal over
the whole sequence at the backbone's positions: 4 shared layers that inject code 0, then
one a codebook, layer k injecting code k - 1 and its head drawing code k (4096 outputs).
A layer is m = eh_proj([enorm(e); hnorm(h)]), a pre-norm block (q, gate, k, v from
wqkv's rows [Q 4096 | G 4096 | K 512 | V 512], (1 + w) q/k norms, GPT-J rotary on 64
dims at 1e7, attention * sigmoid(gate), SwiGLU 6144), a final (1 + w) norm. The first
shared layer also adds the input frame's codes 2..9, embedded and summed in f32
sampling temperature 1.0, top-p 0.9 over the whole candidate set, then the top-k: the main
token uncapped (256) and each head 30, as SGLang-Omni draws; a semantic first draw
among the lane's last 16 picks is redrawn at 1.0 / 0.95 / 30 (`ras_pick`)
codec Fish S2's modified DAC decoder: ten raw codebook rows of 8 (one of 4096, nine of 1024,
codes 1..9 clamped to 1023), each through its own weight-normed 1x1 projection to 1024
and summed; 8 layers of 1024 (16 heads of 64, GPT-J rotary on all 64 at theta 1e4,
causal over 128 frames, plain RMS norms at 1e-5, layer scales); twice a transposed
conv k2 s2 and a ConvNeXt block; a causal conv k7 to 1536; four blocks of snake, a
weight-normed causal transposed conv (8, 8, 4, 2) and three residual units (dilations
1, 3, 9); snake and a conv k7 to one channel, tanh: 2048 samples a frame, 44.1 kHz mono
encoder the codec's, for a reference clip (mono 44.1 kHz, padded to whole frames): a causal
weight-normed conv k7 to 64; four blocks of three residual units (snake, conv k7 at
dilations 1, 3, 9, snake, conv k1) and a snake and a causal conv of kernel two strides
(2, 4, 8, 8), doubling the channels; after the last a 4-layer transformer (window 512
rows); snake, conv k3; twice a causal conv k2 s2 (plain weights) and a ConvNeXt block;
the 8-layer pre-quantiser transformer (window 128 frames); the semantic codebook's
nearest code by cosine, then nine residual steps (`vq_encode`): ten codes a frame
```
The passes, which shift the tower by a row against the reference's loop:
- **PROMPT** runs the backbone over the prompt and leaves its last row's final-norm hidden state in
the lane, then runs the tower over every row, teacher-forced: each row's label is the row after
it, which in a text prompt is text, so every layer's code embedding is zero (the
concatenation's embedding half is filled with zeros once). With references the codec's encoder
first turns the request's clips into frames, written into a code plane at the prompt rows that
name them (`RadAudioGenBatch::ref_frame`); a frame's row is embedded as a made frame's is, a row
before a frame is labelled with it, a frame's row carries its own codes 2..9, and the window of
main picks starts with the prompt's last 16 rows. The last row's tower pass belongs to the first
frame; FRAME 0 writes its cache rows again.
- **FRAME j** draws the main token from the hidden state of the row before the frame's (the
prompt's last for frame 0), runs the tower at THAT row's position, cache slot and context
(`RadAudioGenBatch::prev_slot`, `prev_pos`, `prev_used`) drawing codes 1..9, stores the frame,
and runs the backbone over its embedding at the frame's own row.
Traps (each still speaks, wrongly):
- **The experts' scale planes are f32**, not the bf16 of Qwen3.6-35B-A3B-FP8: the expert format is
read per layer (`MoeFP8::probe`), served as fp8a8f32.
- **The tower's wqkv is blocked, `[Q | G | K | V]`**, not the backbone's per-head `[q_h | gate_h]`
pairs; its rotary is GPT-J's adjacent pairs, not the backbone's halves; its q/k norms run with
`(1 + w)` although its config says `attention_qk_norm: false` (the exporter never wrote it).
- **`eh_proj` reads `[enorm(e); hnorm(h)]`**, the embedding half first.
- **Two masks.** A layer's code embedding is the label frame's, zero when the label is text; the
input frame's codes 2..9 go into the first shared layer only, zero when the input row is text.
The layers that inject code 0 read it by candidate, with the table's row 0 again in front: the
end of speech's code 0 is clamped to 0, as fish-speech clamps it.
- **The tower attends over the whole sequence**, prompt rows included, from 13 caches of its own;
it is not an 11-position depth decoder (`max_seq_len` 11 is left over from S2).
- **The candidates' softmax is over the 4097 only**, top-p over all of them and the top-k cut after
it; a full-vocabulary softmax keeps a different nucleus.
- **The codec's residual codebooks have 1024 entries** and the heads 4096 outputs: codes are clamped
at 1023 at decode (`rvq_embed`'s `clamp`). Its weight norm is per output channel for the convs
and per INPUT channel for the transposed convs (`[in, out, k]`), folded at convert.
- **The encoder's transformer window is 512 rows**, not the 128 frames of the quantiser's: the
window comes from `getattr` on a `functools.partial` config, which has no such attribute, so
fish-speech's default of 512 holds. Both its transformers and the codec's convolutions are
causal, so a clip right-padded to whole frames encodes its frames as the clip alone would.
- **The reference prompt is tokenised a literal at a time**: the instruction's closing `:` and the
first header's `\n\n` are one token when the two are joined. A transcript's speaker tag must
follow `Text: ` directly, so white space before it moves behind it.
- **The input is written as fish-speech's server writes it**: each speaker's turn
`<|speaker:N|> ` and its text stripped, turns joined by a newline, untagged text speaker 0's.
The same two turns joined by a space are spoken through far less often: for one two-line script,
at fish-speech's sampling, one seed in six spoke both lines, against seven in ten with the
newline.
Against fish-speech's own PyTorch code (the CPU path: experts fp8, dequantised per forward, so
W8A16 where radiance runs W8A8), teacher-forced with radiance's codes over a 34-row prompt and 80
frames: the prompt's token ids are identical; the backbone's hidden state is 5.3% from the
reference's (relative L2, median over the frames; cosine at least 0.993), the experts' fp8
activations most of it; the main token's candidate logits 3.6% (KL 0.013 nats a frame, the same
argmax in 92.5% of frames); the nine heads' logits 1.35% (KL 0.007, the same argmax 93% of the time)
over the 79 frames that are spoken. Through the codec, radiance's chunked bf16 decode is 35.4 dB SNR
from the reference's whole-utterance bf16 decode of the same codes. Qwen3-ASR transcribes
radiance's speech word for word.
The encoder against fish-speech's codec encoding the same clip (11.6 s, 250 frames) on the CPU:
radiance's bf16 encoder gives the f32 reference's semantic code in 99.2% of the frames, and its
residual codes in 97.6% (the first) down to 81.2% (the ninth); fish-speech's own bf16 encode gives
95.6% and 94.0% down to 71.2% against the same f32. The reference prompt's token ids are
fish-speech's. Cloning, scored by median F0 and Qwen3-ASR over eight seeds a case, the reference
clips drama-3's own takes of invented sentences: without a reference a sentence's eight takes are
eight voices (116 to 251 Hz); with a reference of a 188 Hz voice they come out at 175 to 210 Hz,
of a 200 Hz voice at 197 to 250 Hz, of a 108 Hz voice at 96 to 122 Hz; two references tagged as
speakers 0 and 1 voice a two-line exchange's turns at 193 to 210 Hz and 109 to 140 Hz. Every take
but one is transcribed word for word (the miss is "I'm" for "I am"). A 12 s clip adds 0.12 s
before a stream's first audio.
The sampling is not fish-speech's server's (temperature 0.7, top-p 0.7, top-k 30 for every draw).
At those the model falls silent after a tag or a speaker's line and does not come back, the failure
vLLM-Omni's recipe and SGLang-Omni's notes describe; SGLang-Omni's comment puts it on the main
token's top-k cap, and the counts bear it out. Ten seeds each of four short scripts (an aside in
`<whisper>`, two two-speaker exchanges, a plain sentence), complete by Qwen3-ASR, and stuck (run to
the 400-frame limit in silence):
| temperature, top-p, top-k (main / heads) | complete | stuck |
|---|---|---|
| 0.7, 0.7, 30 / 30 (fish-speech's server) | 28 / 40 | 8 / 40 |
| 1.0, 0.9, 30 / 30 (Fish Audio's model card) | 35 / 40 | 2 / 40 |
| 1.0, 0.9, 256 / 30 (SGLang-Omni) | 36 / 40 | 0 / 40 |
The four misses at the last setting are a take that ended before the line after the whisper (twice),
a second speaker's single word, and one word the recogniser misheard; the whispered line itself is
spoken in all ten. A take still pauses a second or so around an aside.
On two R9700s a sentence is made at 0.30 of the time it plays (3.67 s of speech in 1.08 s, 13.5 ms
a frame with the codec), a paragraph at 0.29 (11.6 s in 3.34 s); a stream's first audio comes
0.23 s after the request; four paragraphs at once make 50.4 s of speech in 5.15 s.
---
# `minimaxh3`: MiniMax-H3, video with sound
`arch/minimaxh3` declares a video generator (`rad_declare_video_generator`), which makes the
program a four-pass one the engine drives through `core/gen/video_driver.h`: VCOND runs the text
encoder and the refiner over the prompt and computes every step's modulation, VSTEP is one
denoising step of one request's packed sequence, ADECODE plays the soundtrack, VDECODE decodes
one temporal chunk of frames. A request is a lane; two hold state at once (one denoising, one
conditioned and waiting). It is served on `/v1/videos` ([GUIDE §5.16](GUIDE.md)), block fp8 on two
cards with `--vision-tower-placement ram`. The checkpoint is the diffusers pipeline directory,
read as one; only workflow t2va is served.
program one the engine drives through `core/gen/video_driver.h`: VCOND runs the text encoder and
the refiner over the prompt and computes every step's modulation, VSTEP is one denoising step of
one request's packed sequence, ADECODE plays the soundtrack, VDECODE decodes one temporal chunk of
frames; with keyframes or reference media, VENCODE and AENCODE first run each through the video or
the audio VAE's encoder into the lane. A request is a lane; two hold state at once (one denoising,
one conditioned and waiting). It is served on `/v1/videos` ([GUIDE §5.16](GUIDE.md)), block fp8 or
int8 on two cards with `--vision-tower-placement ram`. The checkpoint is the diffusers pipeline
directory, read as one; the workflows t2va, i2va, l2va, fl2va and ref2va are served.
```
text Qwen3-VL-32B's language model: 64 layers of 5120 (64 q / 8 kv heads of 128, ff 25600,
@@ -1643,6 +2127,16 @@ VAE 2 2 2), each followed by the mean of three AMP blocks (k 3/7/11, dilat
channel, clamped. 800 samples a latent, 32 kHz, each stereo channel its own sequence
length 24 fps; a video of n chunks is 17 n + 5 frames over 5 n + 2 latent frames, n 7..20
(5.17 to 14.4 s); the soundtrack is round-half-even(frames x 40 / 24) latents a channel
encoders the video VAE's: six levels of two causal 3x3x3 residual blocks (GroupNorm 32), four
strided downsamplers, 17-frame clips to 5 latent frames, reflect padding; the audio
VAE's: a DAC encoder (strides 2 4 4 5 5) and a causal attention block, 800 samples a
latent, a channel at a time. Latents normalised as the decoders read them
pack with references the sequence is [text | keyframes | references | soundtrack | video]
(arch/minimaxh3/rad_ref2va_pack.h, ComfyUI's PackedLayout): a reference in its own
latent grid on a clock before the video's, a keyframe at its frame of the video. Their
rows take a timestep pinned at max(t, 0.999) (1.0 for sound), and the sampler steps only
the last two segments. Each segment is its own attention sink; a run of segments with
the same modulation is one group of the modulation table, eight at most
```
Traps:
@@ -1654,10 +2148,14 @@ Traps:
embedding reads t in [0, 1] as it is, not scaled to 1000.
- **The grid's second half is linspace's from the end**: torch computes `linspace(1, 0, N)` half
from each end in f32, which `gen::video_schedule` reproduces.
- **The packed rows' positions are f64 rounded to f32**: a latent frame spans 5/3 x (1, 4, 4, 4,
- **The packed rows' positions are f64 rounded to f32** (ComfyUI's arithmetic, tested against its
own numbers in tests/data/ref2va): a latent frame spans 5/3 x (1, 4, 4, 4,
4)[i mod 5] time units from `n_text`, the spatial axes are each side's latents over the square
root of the frame's area, centred on the unit interval, times 32, and the soundtrack's two
channels sit at the two ends of the width axis.
- **The video encoder's shortcut convolves the block's raw input**, before norm1 normalises it in
place; and the audio encoder's attention block feeds its qkv from norm1 but its projection
from norm3. Either swapped shrinks every latent after it.
- **A tile is blended with its neighbours as they were decoded**: the vertical blend reads the
original tile above, and the horizontal blend the original tile to the left, not the blended
ones. Chunks keep frames [3, 20) of their 28 and blend their last 5 linearly into the next
+14 -2
View File
@@ -133,6 +133,10 @@ the cards the engine runs on.
| `ornith-1.5-35b-a3b.yaml` | `ornith-1.5-35b-a3b-fp8.rad` | Ornith-1.5-35B-A3B, FP8, MTP, vision |
| `ornith-1.5-35b-a3b-w4a8.yaml` | `ornith-1.5-35b-a3b-w4a8.rad` | Ornith-1.5-35B-A3B with four-bit experts (GPTQ), a block-FP8 trunk, MTP, vision |
| `ornith-1.5-35b-a3b-w4a8-tp1.yaml` | `ornith-1.5-35b-a3b-w4a8.rad` | The same on one card, every weight in VRAM |
| `ornith-1.5-122b.yaml` | `ornith-1.5-122b-fp8.rad` | Ornith-1.5-122B, FP8, MTP, vision, on four cards with a 3 GiB pinned host pool per card and the vision tower in host memory |
| `ornith-1.5-122b-df2.yaml` | `ornith-1.5-122b-fp8-dflash2.rad` | The same with incoai's DFlash2 drafter in place of the MTP head |
| `ornith-1.5-122b-w4a8.yaml` | `ornith-1.5-122b-w4a8.rad` | Ornith-1.5-122B with four-bit experts (GPTQ), a block-FP8 trunk, MTP, vision, every weight in VRAM on four cards |
| `ornith-1.5-122b-w4a8-df2.yaml` | `ornith-1.5-122b-w4a8-dflash2.rad` | The same with incoai's DFlash2 drafter in place of the MTP head |
| `sage-a1.5.yaml` | `sage-a1.5-fp8.rad` | Sage-A1.5, FP8, MTP, vision |
| `sage-a1.5-tp1.yaml` | `sage-a1.5-fp8.rad` | The same on one card: the expert plane partly in an 8 GiB pinned host pool, one 262,144-token session |
| `sage-a1.5-df2.yaml` | `sage-a1.5-fp8-df2.rad` | Sage-A1.5 with incoai's Qwen3.6-35B-A3B DFlash2 drafter in place of the MTP head, vision |
@@ -143,6 +147,9 @@ the cards the engine runs on.
| `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 |
| `gemma4-31b-w4a8.yaml` | `gemma4-31b-w4a8.rad` | Gemma 4 31B, int4 trunk with int8 activations, its assistant head as the MTP drafter, vision tower |
| `gemma4-31b-heretic-ara-w4a8.yaml` | `gemma4-31b-heretic-ara-w4a8.rad` | The same for Gemma 4 31B heretic-ara (refusals removed) |
| `nemotron-3.5-bolt-e4b-bf16.yaml` | `nemotron-3.5-bolt-e4b-bf16.rad` | NVIDIA-Nemotron-3.5-Bolt-E4B (Gemma 4 E4B) in bf16 with NVIDIA's DFlash drafter, the vision tower in pinned host memory, on one card |
| `nemotron-3.5-bolt-e4b-i8g.yaml` | `nemotron-3.5-bolt-e4b-i8g.rad` | The same with the trunk at int8 (i8a8) |
| `nemotron-3.5-bolt-e4b-a4.yaml` | `nemotron-3.5-bolt-e4b-a4.rad` | The same with the feed-forward at four bits (GPTQ), attention and layers 19-23 at i8a8 |
| `translategemma-27b.yaml` | `translategemma-27b-mxfp4-gptq.rad` | TranslateGemma 27B MXFP4 with its chat template (`gemma3.jinja`) |
| `glm53-flash.yaml` | `glm53-flash-mxfp4.rad` | GLM-5.3-Flash, MXFP4 experts and block-FP8 attention, on eight cards |
| `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter |
@@ -178,7 +185,12 @@ docker compose -f flashnext.yaml down # stop
```
Every model listens on the same port and most take both cards (`flashnext-tp1.yaml`,
`ornith-1.5-35b-a3b-w4a8-tp1.yaml`, `qwen3.8-27b-paro.yaml` and the files that read `RADIANCE_GPU` take one, `glm53-flash.yaml`
eight), so run one at a time: `down` one before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and
`ornith-1.5-35b-a3b-w4a8-tp1.yaml`, `qwen3.8-27b-paro.yaml`, the `nemotron-3.5-bolt-e4b-*.yaml` files and the files that read `RADIANCE_GPU` take one, the
`ornith-1.5-122b*.yaml` files four, `glm53-flash.yaml` eight), so run one at a time: `down` one before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and
the dashboard page answer without the API key, and the health check fetches `/health` with
busybox's `wget`.
A container serving MiniMax-H3 also serves ComfyUI's Radiance MiniMax node
(`integrations/comfyui/ComfyUI-Radiance-MiniMax`), a client of `/v1/videos`. With
`--lora-dir /models/loras/h3` in the command, the node's adapter lists show the files under
`$RADIANCE_MODELS/loras/h3`.
+153
View File
@@ -0,0 +1,153 @@
# The Gemma 4 31B at w4a8 by GPTQ
The 31B's w4a8 container (`data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe`) rounds the trunk's
four linears to the nearest int4 on a group-128 grid. That moves the model's distribution most
where a reply is most constrained. After a string argument in a tool call, `sku:<|"|>MS-110`, the
bf16 model closes the string (`<|"|>`, probability ~1.0); the rounded trunk prefers `**,` (58%
against 41%), so a streamed call stalls inside the string and the client never sees its end.
`gemma4-31b-dense-bf16-w4a8g-df2.recipe` makes the same container (the same grid, kernels and size)
with the int4 codes chosen by GPTQ against the bf16 model's own activations.
## The route
1. **The Hessians, from the bf16 checkpoint.** arch/gemma4 serves the 31B's bf16 checkpoint as it
ships, and with `RADIANCE_CALIB_DIR` set it sums the Gram of every dense linear's bf16 input over
the corpus it is fed. The files carry the names the w4a8 container gives the weights
(gemma4_bf16's `blk.N.attn_qkv`, `attn_o`, `ffn_gate_up`, `ffn_down`), so the recipe reads them
as they are. o_proj's and down's inputs are split across ranks at `--tp 4`, and each rank writes
its block (`.part`), which libquant places on the diagonal.
2. **The convert.** `CALIB=DIR rad-convert` with the recipe: libquant's `gptq` on the trunk's four
linears, everything else as the -df2 recipe makes it. libquant factors each Hessian through
OpenBLAS's LAPACK where the build finds OpenBLAS (the Docker image has it); without it,
libquant's own single-threaded loops take hours for each 21504-wide down projection.
The w4a8 container's own plugin cannot record them: its linears read int8 activations, which
`gram_accum` does not take, and a quantised container's activations would come through its
quantisers.
## The corpus
Whole conversations, rendered with the model's own chat template (Hugging Face's
`apply_chat_template`, thinking off) as token ids, so the Hessians see the reply format the server
writes: 2.78M tokens in 4,724 conversations, each at most 8192 tokens, of which a tenth is held out
and the other 2.47M tokens (4,252 conversations) is the calibration corpus.
| share | tokens | conversations | from |
|---|---|---|---|
| tool calls | 834K | 2,627 | glaive-function-calling-v2 (Apache-2.0): its functions as tools, its calls as `tool_calls` (the template writes them as `<\|tool_call>call:NAME{k:<\|"\|>v<\|"\|>}<tool_call\|>`), its function responses as tool turns |
| chat | 695K | 730 | UltraChat 200k (MIT) prompts with the served 31B's greedy replies (the round-to-nearest w4a8 container's) |
| code | 417K | 589 | self-oss-instruct-sc2 (ODC-BY) prompts, the 31B's replies |
| math | 417K | 493 | OpenMathInstruct-2 (CC-BY-4.0) prompts, the 31B's replies |
| reasoning | 417K | 285 | rStar-Coder (CC-BY-4.0) prompts, the 31B's replies |
The held-out tenth (305K tokens) is never fitted to; 44.5K tokens of it are the KL mode's corpus
below. BetterBench's corpora, on which the stall is measured, are in neither.
## Running it
```sh
# 1. The Hessians: three slices of 20 layers (60 layers' Grams, ~364 MiB a rank each at --tp 4,
# do not fit beside the bf16 weights), the corpus through prefill once per slice.
for sl in 0:20 20:40 40:60; do
RADIANCE_CALIB_DIR=/calib RADIANCE_CALIB_TOKENS=2300000 RADIANCE_G4_CALIB_LAYERS=$sl \
radiance --model gemma-4-31B-it --tp 4 --no-prefix-cache --num-speculative-tokens 0 \
--max-num-batched-tokens 8192 --max-num-seqs 8 --max-model-len 10240 --kv-cache-dtype bf16
# ...feed the corpus at max_tokens 1 until every rank prints
# radiance: gemma4: rank N wrote the Hessians of layers lo:hi after ... tokens to /calib
done
# 2. The container.
CALIB=/calib rad-convert gemma-4-31B-it --draft-model gemma-4-31B-it-speculator.dflash2 \
--recipe data/recipes/gemma4-31b-dense-bf16-w4a8g-df2.recipe \
--set quantization_config.quant_method=compressed-tensors -o gemma4-31b-dense-w4a8g-df2-qkv.rad
```
On four R9700s each slice took about 25 minutes, the corpus through prefill at ~1,500 tokens a
second with the taps live, and the three wrote 45 GB of Grams. The convert took 75 minutes on a
48-thread EPYC.
## Measuring it
- **KL against the bf16 model.** The engine's KL mode: the bf16 checkpoint (arch/gemma4) records its
full distribution at every position of the held-out 44.5K tokens, and each container is scored
against it with the same flags (`--tp 4`, bf16 KV). That reference is Hugging Face's: on 41 of
its documents (21,407 positions), Transformers' bf16 31B is a mean 0.0195 nats from it (median
0.00001), and at each container's 25 worst positions the two agree.
- **Where it counts: the model's turns.** At system and user positions, text the model never
writes, the bf16 model's own guesses are untrained and often odd (` same` at 1.000 after
`<|tool>declaration`, `---` at 0.997 inside a user's problem statement). Any quantisation moves
them, so they carry most of the mean: of RTN's and Q8's 50 worst positions, 46 are system or
user positions, each a confident bf16 guess that both implementations make. The tables give every
position and the model's own turns apart.
## Results
The containers are the same size (24.9 GB) on the same kernels, so speed does not move; what
moves is how close each is to the bf16 model.
**The stall.** The next token after `sku:<|"|>MS-110` in BetterBench's order request, and
BetterBench's two order requests (a single call, and a round trip) each streamed 20 times, sampled
as BetterBench sends them, `--tp 2`, thinking off:
| | `<|"|>` (the string closes) | `**,` | single calls that stalled | round trips that stalled |
|---|---|---|---|---|
| bf16 (Hugging Face) | ~1.0 | | | |
| RTN (`-df2-qkv`) | 41% | 58% | 10 of 20 | 1 of 20 |
| **GPTQ** | **99.8%** | 0.2% | **0 of 20** | **0 of 20** |
**KL against the bf16 model**, the 44.5K held-out positions (Q8 is the w8a8 container, 38.2 GB):
**every position** (44456 positions)
| | mean KL | median | p99 | over 1 nat | top-1 |
|---|---|---|---|---|---|
| RTN | 0.988 | 0.0039 | 14.81 | 16.7% | 81.9% |
| GPTQ | 0.659 | 0.0020 | 11.15 | 12.8% | 84.5% |
| Q8 | 0.620 | 0.0014 | 12.08 | 11.7% | 85.6% |
**the model's turns** (31975 positions)
| | mean KL | median | p99 | over 1 nat | top-1 |
|---|---|---|---|---|---|
| RTN | 0.341 | 0.0003 | 7.49 | 6.7% | 90.5% |
| GPTQ | 0.251 | 0.0001 | 5.46 | 5.7% | 91.3% |
| Q8 | 0.226 | 0.0001 | 5.28 | 4.8% | 92.3% |
**the model's turns by source** (mean KL / top-1)
| | chat | math | oss | rstar | tool |
|---|---|---|---|---|---|
| RTN | 0.810 / 81.8% | 0.093 / 94.5% | 0.166 / 92.9% | 0.087 / 94.4% | 0.521 / 88.9% |
| GPTQ | 0.572 / 82.7% | 0.062 / 95.4% | 0.134 / 93.4% | 0.067 / 95.2% | 0.396 / 89.7% |
| Q8 | 0.536 / 84.7% | 0.046 / 95.9% | 0.130 / 94.3% | 0.043 / 95.8% | 0.356 / 90.8% |
GPTQ closes 78% of the distance from RTN to Q8 on the model's turns and 89% over every position, on
every source; on tool-call replies the mean falls from 0.521 to 0.396.
**The drafter** (DFlash2, block 8), specbench at 8 users, thinking off, tokens a step:
| | HumanEval | math | qa | question | rag | summarization | translation | all |
|---|---|---|---|---|---|---|---|---|
| RTN | 5.97 | 6.16 | 2.91 | 3.44 | 4.40 | 3.21 | 4.02 | 3.96 |
| **GPTQ** | 5.98 | 6.19 | 3.25 | 3.56 | 4.37 | 3.21 | 4.08 | **4.11** |
(The set's `writing` subset is byte for byte its `question` subset and is left out.) Decode speed
on BetterBench's 7 multi-turn conversations is the same: first turns 159.6 tok/s against 159.8,
3.85 tokens a step against 3.88.
**BetterBench's `tool_call` and `multi_turn` categories at 1-16 users**, sampled at 0.7, `--tp 2`,
thinking off, the two containers served at once and the card pairs swapped for a second run (both
runs given):
| | RTN | GPTQ |
|---|---|---|
| multi-turn: the right tool | 15/18, 15/18 | **18/18, 18/18** |
| multi-turn: a turn after the tool's result | 16/21, 17/21 | **18/18, 18/18** |
| tool calls: a valid call | 16/17, 15/17 | **17/17, 17/17** |
| tool calls: the right tool | 16/17, 15/17 | **17/17, 17/17** |
| weighted decode, tok/s | 176.7, 175.0 | 183.8, 172.1 |
| aggregate at 1 / 2 / 4 / 8 / 16 users, tok/s | 116 / 174 / 252 / 253 / 308, 113 / 175 / 240 / 261 / 314 | 111 / 169 / 240 / 260 / 309, 115 / 168 / 235 / 244 / 299 |
Throughput is level within the runs' noise (about 3%; the sessions differ too, since the calls that
now succeed lead to other turns).
+785 -42
View File
File diff suppressed because it is too large. Load diff
+14
View File
@@ -88,6 +88,20 @@ to bisect it (`spec.md` §17).
**No allocation and no synchronisation on the step path.** The arena is sized at declare. A
`malloc` needed inside `rad_arch_step` or the scheduler's per-step work is a declare-phase bug.
**Kernel scratch is per lane, each region sized by what its lane may issue.** In-order launch lets
every op on one stream share one scratch region; a second lane is a second stream and gets a second
region once the architecture names any buffer to `rad_buf_concurrent` (`Program::scratch_regions`).
Region 0 holds the program's largest device scratch (`Program::scratch_bytes`). Region 1 holds the
largest device scratch of an op the second lane may issue (`Program::scratch_bytes_lane1`, computed
in `Builder::finish_buffer_liveness`): by `Ctx::lane1_`'s rule 3 such an op touches only
concurrent buffers, so an op with any other transient buffer never runs there, and one with no
transient buffer counts. `Arena::init` takes both sizes, `arena_plan_bytes` charges both to the VRAM
budget, and startup prints them (`arena: ... device + ... scratch + ... for the second lane = ...`).
A lane-1 request larger than region 1 comes from an op that breaks rule 3 in its buffers too, so
`Ctx::issue` fails the step naming the kernel (`RAD_E_SCRATCH`) rather than let it overrun the
region. On Qwen3.8-27B with its DFlash2 drafter region 1 is 0 B against region 0's 50 MiB a card
at speculation 7 (17 MiB without speculation).
**`rad_memset_async` refuses `RAD_MEM_HOST` on a card; the host backend cannot reproduce that.**
`RAD_MEM_HOST` is pageable memory the GPU has never been shown, so the device backend returns
`RAD_E_UNSUPPORTED` naming the rule (`core/device/aql.cpp`). On the host backend all memory kinds
+171
View File
@@ -0,0 +1,171 @@
# IQR: integer quantisation on the rotated int8 grid
IQ8R (`StillDeadcode/qwen3.8-27b-iq8r`) is Qwen3.8-27B with every trunk linear rotated by the
128-wide Hadamard (`transform=fwht128`), quantised to int8 with a bf16 scale per (row, 128 of K) by GPTQ
against the calibration Hessians, and served at `i8a8h`: the norm and gated producers write the
rotated int8 activation codes the GEMM reads (`qwen35_w8a8`). IQ6R .. IQ2R keep that recipe --
GPTQ, the rotation, integer codes, int8 activations -- and spend fewer bits on the weights.
## The formats
Every IQR weight is on IQ8R's grid: a value is an int8 times the scale of its group. A container
stores it narrower, and VRAM holds it at the same width: libr4d's IQR rows decode each code to its
int8 value where the weight is read (`r4d_iqr.h`; `gemm_iqr_nt_m64` up to 64 rows, `gemm_iqr_tiled`
for a prefill, `embed_lookup_iqr` and `logits_gemm_iqr` for the embedding and the head), with
rotated int8 activations on the `i8a8h` trunk:
| form | encoding | decoded as |
|---|---|---|
| signed | `iN*bf16[1x128]/fwht128`, N = 2..7 | sign extension |
| asymmetric | `uN*bf16[1x128]-uN[1x128]/fwht128` | code - zero |
| scalar codebook | `affine:codes=uN[1x1],scale=bf16[1x128],table=i8{1x2^N}/fwht128` | the entry |
| vector codebook | `affine:codes=uM[1x4],scale=bf16[1x128],grid=i8{E x 4}/fwht128` | the codeword's 4 values |
The embedding and the head decode the same forms, unrotated. The arithmetic is the int8 grid's
for every form: a narrower code changes the bytes read, not the values multiplied.
## The quantiser
`gptq` (libquant) over the rotated weight against the calibration Hessians:
- the codebooks are integer Lloyd tables (`data/codebooks/iqr-scalar.txt`) and k-means vector
codebooks (`iqr-vq2-4x256.txt`, `iqr-vq3-4x4096.txt`), fitted to the rotated weights;
- `rule=search` scales; `dyn=1` chooses a group's scale when GPTQ reaches it;
- `cd=N` coordinate descent after the loop, per code or, for a vector grid, per codeword;
- the head is fitted by GPTQ too, against the head's input Hessian.
Measured on layer 3 (output error, relative): the scalar codebook beats a uniform grid by 12-25% at
two to five bits; the asymmetric grid wins at six. A 256 x 4 vector codebook with one descent pass
has 19% less error than the scalar 2-bit codebook with eight; the 4096 x 4 one 13% less than scalar
3-bit.
## Where the bits go
The KL a quantised band of layers contributes adds up across bands to within a few percent, so a
mix is chosen by a model: KL = floor + sum over bands of share x (KL of the band's grid - floor).
On the 4-bit trunk the eight bands of eight layers carry 9, 4, 8, 11, 13, 12, 16 and 28 % of the KL:
the last layers are the most sensitive, and the projections of a layer about equally so. The
embedding and the head are cheap to keep wide (1.27B parameters each, 0.047 bpw a bit) and costly
to narrow at the higher sizes: a 4-bit embedding by round to nearest costs IQ8R +0.00058 KL, a 6-bit
one +0.00003.
The 2-bit trunk's bands weigh the same way (12, 6, 7, 8, 10, 10, 17 and 31 %, measured by raising
one band of the 256 x 4 trunk to four bits). `rule=search` per group and a narrower scale group do
nothing at two bits (the vector codebook's error is the same at groups of 128 and 64): the bits
go to wider codebooks instead, and each half bit of a 4-wide codebook halves the error (256, 512,
1024 and 4096 codewords: 2.125 to 3.125 bits a weight with the scale).
## Results
Qwen3.8-27B against the competition's private tiers 1 + 2 (mean KL to the bf16 model's top-512,
bpw over the text model's 26.9B parameters, embedding and head included):
| recipe | bpw | KL mean | top-1 | the GGUF at that size | its bpw | its KL |
|---|---:|---:|---:|---|---:|---:|
| `q38-27b-iq6r-l` | 6.935 | 0.00092 | 98.91% | UD-Q6_K_L | 7.089 | 0.00129 |
| `q38-27b-iq6r` | 6.375 | 0.00123 | 98.73% | UD-Q6_K | 6.431 | 0.00194 |
| `q38-27b-iq6r-s` | 6.061 | 0.00151 | 98.48% | UD-Q5_K_XL | 6.102 | 0.00268 |
| `q38-27b-iq5r` | 5.420 | 0.00300 | 98.00% | UD-Q5_K_S | 5.444 | 0.00428 |
| `q38-27b-iq5r-s` | 5.075 | 0.00426 | 97.66% | UD-Q4_K_XL | 5.115 | 0.00608 |
| `q38-27b-iq4r-l` | 4.780 | 0.00609 | 97.19% | UD-Q4_K_M | 4.790 | 0.00820 |
| `q38-27b-iq4r` | 4.457 | 0.00904 | 96.56% | UD-Q4_K_S | 4.461 | 0.01057 |
| `q38-27b-iq4r-s` | 4.137 | 0.01327 | 95.50% | UD-IQ4_XS | 4.132 | 0.01499 |
| `q38-27b-iq3r-l` | 3.798 | 0.01887 | 94.78% | UD-Q3_K_XL | 3.803 | 0.02403 |
| `q38-27b-iq3r` | 3.459 | 0.03043 | 93.59% | UD-IQ3_S | 3.474 | 0.03473 |
| `q38-27b-iq3r-s` | 3.148 | 0.04469 | 92.29% | UD-IQ3_XXS | 3.145 | 0.05052 |
| `q38-27b-iq2r-l` | 2.790 | 0.06937 | 90.32% | UD-Q2_K_XL | 2.816 | 0.07920 |
| `q38-27b-iq2r` | 2.469 | 0.12234 | 87.02% | UD-IQ2_S | 2.487 | 0.12976 |
IQ6R is also below UD-Q6_K_L (7.089 bpw, 0.00129) and IQ5R below UD-Q5_K_M (5.773, 0.00328). By
source, IQ4R's lead over UD-Q4_K_S is widest on agent traces and reasoning (0.71 to 0.74 of its
KL; on the 256K agentic traces 0.00595 against 0.00822) and narrowest on chat, Wikipedia and long
fiction (wildchat 0.99, wikimedia 0.98, pg19 0.95).
A base convert (one grid over the whole trunk) is one GPTQ pass over the bf16 checkpoint, 35 to
100 minutes on 16 threads. A recipe converted from scratch costs one such pass; the mixes were
assembled from the bases instead (`rad-convert --reuse` with every base, which copies each weight
whose options match a base's), a few minutes each.
## IQR-V2: a trellis down each GPTQ column
IQR-V2 keeps the rotation, GPTQ, the int8 grid and the int8 activations, and changes what a code
is: the trunk's codes are a bitshift trellis (QTIP's) of 2^12 states run down each column of the
rotated weight (`tcq=12`). A row's value is the table entry of its state, the state being the last
12 bits of the column's codes; a run of 256 rows (`tcq_rows`) is tail-biting, so no bits go to a
start state. Down a column every row shares the column's H_ii, so the Viterbi's metric is GPTQ's
own objective for that column, and GPTQ's feedback to the later columns stays exact. The tables
are 4096 integers in -127..127 (`data/codebooks/iqr-tcq-L12-k2..k7.txt`), trained by Lloyd
iterations on Viterbi paths over the rotated weights; the scale is E4M3 per (row, 128) under one
f32 for the tensor (`scale=fp8_e4m3 scale2=f32 block2=*x*`), which the trellis was searched against
at the bf16 of their product. The GEMM walks each column's states in the tile and reads their
values from the table in LDS (`gemm_iqr`), so V2 serves on the `i8a8h` trunk at its codes' width.
On layer 3 the trellis has 21-29% less output error than V1's best grid at every rate from 2 to 6
bits. The mixes are chosen as V1's by band shares, over 24 units (8 bands x gate_up / down / the
attention or delta-net projections) and the k = 2 .. 7 trellises plus int8, by an exact Pareto
merge. The embedding is a rotated trellis too (unrotated at load); the head stays V1's scalar
GPTQ table, where a trellis clipped its outliers.
| recipe | bpw | KL mean | top-1 | V1 at that size | its bpw | its KL | KL |
|---|---:|---:|---:|---|---:|---:|---:|
| `q38-27b-iq8r-v2` | 8.040 | 0.00047 | 99.18% | IQ8R | 8.505 | 0.00046 | +2% |
| `q38-27b-iq7r-v2` | 7.418 | 0.00061 | 99.11% | -- | | | |
| `q38-27b-iq6r-l-v2` | 6.937 | 0.00073 | 99.05% | IQ6R-L | 6.935 | 0.00092 | -21% |
| `q38-27b-iq6r-v2` | 6.375 | 0.00094 | 98.92% | IQ6R | 6.375 | 0.00123 | -24% |
| `q38-27b-iq6r-s-v2` | 6.062 | 0.00115 | 98.78% | IQ6R-S | 6.061 | 0.00151 | -24% |
| `q38-27b-iq5r-v2` | 5.423 | 0.00204 | 98.34% | IQ5R | 5.420 | 0.00300 | -32% |
| `q38-27b-iq5r-s-v2` | 5.076 | 0.00273 | 98.07% | IQ5R-S | 5.075 | 0.00426 | -36% |
| `q38-27b-iq4r-l-v2` | 4.784 | 0.00377 | 97.78% | IQ4R-L | 4.780 | 0.00609 | -38% |
| `q38-27b-iq4r-v2` | 4.457 | 0.00562 | 97.29% | IQ4R | 4.457 | 0.00904 | -38% |
| `q38-27b-iq4r-s-v2` | 4.130 | 0.00832 | 96.67% | IQ4R-S | 4.137 | 0.01327 | -37% |
| `q38-27b-iq3r-l-v2` | 3.798 | 0.01198 | 96.04% | IQ3R-L | 3.798 | 0.01887 | -37% |
| `q38-27b-iq3r-v2` | 3.458 | 0.01880 | 95.06% | IQ3R | 3.459 | 0.03043 | -38% |
| `q38-27b-iq3r-s-v2` | 3.145 | 0.02798 | 93.75% | IQ3R-S | 3.148 | 0.04469 | -37% |
| `q38-27b-iq2r-l-v2` | 2.792 | 0.04698 | 92.03% | IQ2R-L | 2.790 | 0.06937 | -32% |
| `q38-27b-iq2r-v2` | 2.467 | 0.07303 | 90.15% | IQ2R | 2.469 | 0.12234 | -40% |
IQ4R-L-V2 is below the official FP8 checkpoint (8.766 bpw, 0.00389) at 55% of its size, and IQ7R-V2
is below UD-Q6_K_XL (7.417 bpw, 0.00114) at the same size. IQ8R-V2 holds IQ8R's KL in 5% fewer
bits.
## IQR-V3: a computed trellis under one scale a row
IQR-V3 keeps V2's tail-biting trellis inside GPTQ and changes the code and the scale. A state's
value is computed from the state instead of read from a table (`tcq_code=mad`): with
h = (st * A + B) mod 2^32 from the low 24 bits of each factor, the value is
bytesum(h & 0x3F3F3F3F) - 126, a near-Gaussian int8 (A = 0xB5297B, B = 0x2545F491, stored as the
`trellis.mad` plane beside the table they generate). A reader needs a multiply-add, a mask and one
byte-sum dot product a value and no table, so the trellis grows to 2^16 states (`tcq=16`; 2^15 at
two bits) at no decode cost. The scale is one f32 a row (`block=1x* scale=f32`), applied after the
K loop, with the codes searched at a gain over the row's absmax that rises with the width
(`tcq_gain`: 1.04 at two bits, 1.08, 1.12, 1.16, then 1.24 at six and seven), and higher for the
projections the attention heads feed (`attn_output`, `ssm_out`: 1.36, 1.5 and 1.6 at five, six and
seven bits). GPTQ's damping is 0.01.
The GEMM decodes in the tile (`gemm_iqr`). At one token the GEMV dots each value's hash with its
activation byte repeated in all four bytes, so a 4-bit `ffn_gate_up` takes 0.58 of FP8's time
(V2 0.80), and a decoder layer's trunk GEMMs at 2048 tokens take 1.00-1.06x FP8's (V2
1.19-1.21x), since one scale a row folds as FP8's block scale does. The mixes are chosen as V2's,
from the k = 2 .. 7 bases and IQ8R's int8 grid at V2's sizes; IQ8R-V3 is IQ8R-V2's container, the
int8 grid both share.
| recipe | bpw | KL mean | top-1 | V2 at that size | its bpw | its KL | KL |
|---|---:|---:|---:|---|---:|---:|---:|
| `q38-27b-iq8r-v3` | 8.040 | 0.00047 | 99.18% | IQ8R-V2 | 8.040 | 0.00047 | 0% |
| `q38-27b-iq7r-v3` | 7.420 | 0.00060 | 99.12% | IQ7R-V2 | 7.418 | 0.00061 | -2% |
| `q38-27b-iq6r-l-v3` | 6.939 | 0.00072 | 99.04% | IQ6R-L-V2 | 6.937 | 0.00073 | -2% |
| `q38-27b-iq6r-v3` | 6.372 | 0.00088 | 98.93% | IQ6R-V2 | 6.375 | 0.00094 | -6% |
| `q38-27b-iq6r-s-v3` | 6.049 | 0.00106 | 98.83% | IQ6R-S-V2 | 6.062 | 0.00115 | -8% |
| `q38-27b-iq5r-v3` | 5.422 | 0.00182 | 98.38% | IQ5R-V2 | 5.423 | 0.00204 | -11% |
| `q38-27b-iq5r-s-v3` | 5.064 | 0.00249 | 98.15% | IQ5R-S-V2 | 5.076 | 0.00273 | -9% |
| `q38-27b-iq4r-l-v3` | 4.783 | 0.00342 | 97.86% | IQ4R-L-V2 | 4.784 | 0.00377 | -9% |
| `q38-27b-iq4r-v3` | 4.458 | 0.00512 | 97.45% | IQ4R-V2 | 4.457 | 0.00562 | -9% |
| `q38-27b-iq4r-s-v3` | 4.131 | 0.00762 | 96.90% | IQ4R-S-V2 | 4.130 | 0.00832 | -8% |
| `q38-27b-iq3r-l-v3` | 3.798 | 0.01129 | 96.16% | IQ3R-L-V2 | 3.798 | 0.01198 | -6% |
| `q38-27b-iq3r-v3` | 3.459 | 0.01698 | 95.35% | IQ3R-V2 | 3.458 | 0.01880 | -10% |
| `q38-27b-iq3r-s-v3` | 3.145 | 0.02584 | 94.02% | IQ3R-S-V2 | 3.145 | 0.02798 | -8% |
| `q38-27b-iq2r-l-v3` | 2.786 | 0.04241 | 92.62% | IQ2R-L-V2 | 2.792 | 0.04698 | -10% |
| `q38-27b-iq2r-v3` | 2.465 | 0.06807 | 90.54% | IQ2R-V2 | 2.467 | 0.07303 | -7% |
The design, the per-weight and GEMM measurements and the comparison with V1 and V2 are in the
IQR-V3 technical report (radiance.stilldeadco.de/whitepapers/iqr-v3.pdf).
+9 -95
View File
@@ -21,7 +21,7 @@ pass reached; the Rows nothing ran section lists the rest.
| library | version | domain | rows | run | ops | graph | cases | pass | fail | worst rel_l2 | median us |
|---|---|---|---|---|---|---|---|---|---|---|---|
| `libavx` | 0.1.0 | host | 100 | 42 of 100 | 100 of 147 | 43 of 43 | 734 | 734 | 0 | 9.01e-04 | 78.91 |
| `libr4d` | 0.5.0 | device | 287 | 48 of 287 | 142 of 147 | 43 of 43 | 734 | 734 | 0 | 4.27e-03 | 12.78 |
| `libr4d` | 0.5.0 | device | 291 | 48 of 291 | 142 of 147 | 43 of 43 | 734 | 734 | 0 | 4.27e-03 | 12.78 |
| `libref` (oracle) | 0.1.0 | host | 123 | 42 of 123 | 123 of 147 | 43 of 43 | 734 | 734 | 0 | 0.00e+00 | - |
Rows declaring an optional hook (tuning, fusion, weight layout):
@@ -34,7 +34,7 @@ Rows declaring an optional hook (tuning, fusion, weight layout):
## Rows nothing ran
132 of 510 declared row(s) were reached by a case in this pass.
132 of 514 declared row(s) were reached by a case in this pass.
`libavx`: 58 row(s) not reached:
@@ -99,7 +99,7 @@ Rows declaring an optional hook (tuning, fusion, weight layout):
| `avx_silu` | `silu` |
| `avx_softmax` | `softmax` |
`libr4d`: 239 row(s) not reached:
`libr4d`: 243 row(s) not reached:
| kernel | op |
|---|---|
@@ -280,6 +280,8 @@ Rows declaring an optional hook (tuning, fusion, weight layout):
| `hc_write_bf16` | `hc_write` |
| `join_add_scale_bf16` | `join_add_scale` |
| `kv_store_bf16` | `kv_store` |
| `kv_store_streamed_bf16` | `kv_store_streamed` |
| `kv_store_streamed_fp8` | `kv_store_streamed` |
| `l2norm_chan_bf16` | `l2norm_chan` |
| `lane_gather_w32` | `lane_gather` |
| `lane_store_w32` | `lane_store` |
@@ -313,6 +315,8 @@ Rows declaring an optional hook (tuning, fusion, weight layout):
| `qk_norm_rope_gate` | `qk_norm_rope_gate` |
| `qk_norm_rope_gate_kv_store_bf16` | `qk_norm_rope_gate_kv_store` |
| `qk_norm_rope_gate_kv_store_fp8` | `qk_norm_rope_gate_kv_store` |
| `qk_norm_rope_gate_kv_store_streamed_fp8` | `qk_norm_rope_gate_kv_store_streamed` |
| `qk_norm_rope_gate_kv_store_streamed_bf16` | `qk_norm_rope_gate_kv_store_streamed` |
| `qkv_norm_rope_bf16` | `qkv_norm_rope` |
| `qsa_block_key_bf16` | `qsa_block_key` |
| `qsa_score_bf16` | `qsa_score` |
@@ -507,6 +511,7 @@ on a marked row is a hole this model falls into.
| `hc_write` | | host | device | host |
| `join_add_scale` | | - | device | - |
| `kv_store` | yes | host | device | host |
| `kv_store_streamed` | | host | device | host |
| `l2norm_chan` | | - | device | host |
| `lane_gather` | | - | device | host |
| `lane_store` | | - | device | host |
@@ -534,6 +539,7 @@ on a marked row is a hole this model falls into.
| `qk_norm_rope` | | host | device | host |
| `qk_norm_rope_gate` | | - | device | - |
| `qk_norm_rope_gate_kv_store` | | - | device | - |
| `qk_norm_rope_gate_kv_store_streamed` | | - | device | - |
| `qkv_norm_rope` | | - | device | - |
| `qsa_block_key` | | host | device | host |
| `qsa_score` | | - | device | host |
@@ -4390,95 +4396,3 @@ A sanitised replay of the whole fixture. Host code only -- see the note in the
- 0 report(s)
## The M2XFP4 GEMMs
Hand-written section, 2026-10-20, beside the generated report above. The M2
analogue of the OCP-MXFP4 x fp8 stack (arXiv 2601.19213 §4.4.2, the paper's
weight-side Sg-EM): two rows, `gemm_m2xfp4a8_decode` (M <= 128, the decode band)
and `gemm_m2xfp4a8_tiled` (prefill), at the quantiser-own encoding `m2xfp4` --
one more plane than MXFP4, everything else the OCP rows' plumbing.
**Encoding and decode.** Per group of 32 columns the weight carries the MXFP4
planes -- e2m1 codes and an E8M0 exponent whose adaptive bias b in {-1,0,1} the
quantiser already folded into the stored byte -- plus one meta byte holding four
two-bit subgroup multipliers, subgroup s covering columns [8s, 8s+8). The exact
weight is `e2m1mag[c&7] . sign(c) . 2^(scale-127) . (1 + k_s/4)`. The fold of the
OCP rows applies unchanged (`r4d_mxfp4.h`): `d = Wref[n] - E8M0[n][blk]` against
the row-maximum reference goes through a table, `2^(Wref[n]-127)` once in the
epilogue -- Wref is still the row's largest exponent byte, so d >= 0 holds for
every block, and the largest element any table cell then holds is the x1.75
magnitude 10.5 . 2^-d, an e4m3 normal at every d >= 0. `r4d_m2xfp4.h`'s
`kM2xfp4Mag[16][4][2]` is the mxfp4 table with the second index: its k = 0 rows
are `kMxfp4Mag` byte for byte; k = 1, 2 are exact wherever the product is normal;
k = 3 rounds the odd-mantissa magnitudes (1.5, 3, 6 land on the tie's even side,
2.5, 5, 10 scaled) -- at most 2^-4.4 relative on those elements, accepted here
because the CPU decode and the reference stay exact. The unpack is the same four
v_perm_b32 per eight weights, one table row [d][k_s].
**Memory organization.** The relayout (`r4d_layout.cpp`, m2xfp4) stores the codes
in the skinny kernels' WMMA fragment order and appends the meta plane to the same
stored blob in the exponent plane's [K/32][N] order and row pitch -- one byte per
(weight row, 32 of K), read beside the exponent byte with the staging geometry
the scales already use, so the weight stream grows by one byte per sixteen. The
weight operand takes the container's `codes` and `meta` planes; `bscale` and
`bref` are the OCP rows' own arrangements and derivations. Split-K, the
last-arriver reduction, the scratch contract, the concurrency promise (counters
keyed on the output) and the ks/bk/nt and tn tunables are the OCP rows', with
this row's own state.
**Coverage.** `r4d_emu_m2xfp4` holds the table to arithmetic over every
(d, k, magnitude) cell and the unpack to it over every code, then runs both
kernels against an f64 reference of the exact decode at the FP8 WMMA's tolerance
(both activation scale grids, a zero block, both K slabs, the one-fragment form
and the split law). `r4d_selftest --case gemm_m2xfp4a8_decode` (and `_tiled`)
runs the rows on the card through their own relayout, including parts and both
grids, at the tolerance above plus the k = 3 margin (4e-2 rel_l2).
The same encoding is served on the host by libref's and libavx's `gemm_nt_q`
m2 arms (the concatenated canonical planes; ref_gemm.cpp's gemm_m2), which the
row checker holds to the quantiser's own decode.
**Speed.** rad-kbench reaches the rows: `data/kernels_m2xfp4_m{1,8,16,128}.rkb`
are recorded from a skeleton of an m2xfp4 27B container (weights drawn from
seeds, one file a --max-tok pass, replayed together; the mx side comes from
`--record-rows` over the same cases, which re-encodes the weight between the
mx/m2 families -- tools/rad_kbench.cpp's reencode_gemmx_weight). The numbers
below are `--timing-only --report` cold medians, each launch reading its rotated
weights from memory, gfx1201:
| shape | M | mxfp4 us | m2 us | delta |
|---|---|---|---|---|
| N=1024 K=5120 | 1 | 11.3 | 13.3 | +17.5% |
| N=1024 K=5120 | 16 | 13.9 | 15.8 | +13.8% |
| N=1024 K=5120 | 128 | 44.3 | 44.7 | +0.8% |
| N=5120 K=6144 | 1 | 32.1 | 38.3 | +19.2% |
| N=5120 K=6144 | 16 | 34.1 | 40.2 | +17.9% |
| N=5120 K=6144 | 128 | 100.9 | 104.5 | +3.6% |
| N=5120 K=17408 | 1 | 78.5 | 86.7 | +10.5% |
| N=5120 K=17408 | 16 | 89.7 | 100.5 | +12.0% |
| N=5120 K=17408 | 128 | 211.2 | 222.8 | +5.5% |
| N=12288 K=5120 | 1 | 56.4 | 59.3 | +5.3% |
| N=12288 K=5120 | 128 | 113.8 | 124.7 | +9.6% |
| N=16384 K=5120 | 64 | 94.6 | 103.0 | +8.9% |
| N=16384 K=5120 | 128 | 156.8 | 169.1 | +7.8% |
| N=34816 K=5120 | 1 | 150.1 | 167.8 | +11.8% |
| N=34816 K=5120 | 16 | 157.1 | 173.8 | +10.7% |
| N=34816 K=5120 | 64 | 206.2 | 223.1 | +8.2% |
| N=34816 K=5120 | 128 | 354.7 | 370.5 | +4.4% |
An earlier harness that drove the row's own ABI launch with the meta plane as a
separate 5-6 MiB buffer measured +0.7-3.6% at M <= 16: that buffer sat warm in
L2, and in the engine -- and in a cold kbench pass, where the meta rides the
weight blob and rotates with it -- the M <= 16 premium is 5-19% instead. Past
the DTM 1 -> 2 band switch at M = 17 the extra byte hides again (0.4-10%); the
whole-M-ladder fixtures carry 1, 2, 4, 8, 9, 16, 18, 36, 64, 65, 128.
One tuning attempt was made at the M >= 64 points where the delta exceeds 8%:
staging the slab's exponent and meta bytes into LDS once (wide coalesced loads
replacing the duplicated scalar global reads the unpack loop makes). It was
reverted: the W-stage's paired-row store writes one row past sW for the last
row pair -- a latent out-of-bounds LDS store the original layout absorbed --
and beside newly staged LDS it corrupts the staged bytes; guarding that slot
changed the error without removing it, and the residual mismatch stayed
undiagnosed. The numbers above are the unmodified kernel.
+437
View File
@@ -0,0 +1,437 @@
# KV streaming: host-authoritative KV with a resident VRAM window
A streamed group keeps its whole context in pinned host RAM and only a ring of blocks in VRAM; the
VRAM that frees up goes to experts. `--max-model-len` and `--max-num-seqs` size the host side,
`--kv-resident` the ring. The operator's view is [GUIDE.md](GUIDE.md) §4.4.1; source comments cite
the section numbers below.
Streaming pays only when a step reads far less than the context, which is true of radiance's
indexer-selected attention (the QSA family and GLM-5.3's MLA block) and false of dense attention
(§2). An architecture with no streamed path ignores the flag with one warning (§4.5).
Two views sit over one allocation: the **ring**, `n_slots` blocks deep and `n_layers` stripes,
addressed through a residency map, and the **stage**, the group's context deep and one stripe,
addressed by block id. The allocation is `max(ring, stage)`, never the sum (§3.1). A pass's view
follows from its phase and row shape, both already in the pass key.
---
## 1. Why the idle tiers are not the stream
The VRAM paged pool (`core/mem/kv.{h,cpp}`) is where a live sequence's KV lives. The idle tiers
(`core/mem/kvtier.*`, `core/runtime/tierexec.*`) copy a finished conversation's blocks to pinned
host memory and back on a prefix-cache hit: a hot cache whose unit is a published prefix entry,
moved between identical layouts on publish and admission, in memory no kernel dereferences.
Streaming needs many small, per-launch, selection-driven copies with a residency map, so it is a
module of its own (§4.1). It keeps the tiers' two rules: never block the host on the step path, and
order copies with events, not syncs (`spec.md` §5.4).
---
## 2. What bounds a step's read
Qwen3.8-Flash-Next (`arch/qwen4exp_fp8`) at `--tp 2`, fp8 KV, per rank; 12 QSA layers plus the
MTP head bind `kv_attn`:
| group | per 4-token block | per token | at 262 144 tokens |
|---|---|---|---|
| `kv_attn` (fp8, 2 kv heads, head_dim 256, 13 layers) | 26.00 KiB | 6.50 KiB | 1.66 GiB |
| `kv_qsa_bkey` (bf16, 1 head, head_dim 16) | 3.25 KiB | 0.83 KiB | 208 MiB |
Decode is sparse at every context: the selection keeps `topk = budget / ratio = 512` blocks a row
(`docs/QSA.md`), so a step reads about 13 MiB of `kv_attn` whatever the history. The indexer is
different: `qsa_score` reads every complete block of `kv_qsa_bkey` each step (208 MiB at 262K), so
that group is dense-read and stays resident (§3.1).
A dense family (Qwen3.8-27B, `arch/qwen35_*`) reads the whole context every step, 16 KiB a token per
rank at fp8, so a ring only subtracts from a read that is already link-bound. It declares no
streamed path.
---
## 3. The contracts
### 3.1 One id space, two depths
The paged pool is block-id indexed and layer-major: layer `i` at `base + i * layer_stride`, block
`b` at `b * layer_bytes_per_block`, and a slot is `block_table[bi] * block_size + pos % block_size`.
Nothing indirects, so a block id outside the pool corrupts the next layer with fluent text.
`KVGroupPlan` therefore carries two depths: `n_blocks`, the id space (the context), which the
allocator, refcounts, block table, prefix cache and every `id < n_blocks` guard count; and
`n_slots`, the blocks the device pool backs. `pool_blocks()` is `n_slots` (or `n_blocks`),
`streamed()` is `n_slots < n_blocks`, and `layer_stride()` uses `n_slots`. Only addressing moves.
The pool is one reservation of `max(ring, stage)` (`kv_pool_bytes`, `kv_ceiling_bytes`), and
`carve()` writes `n_blocks`, `n_slots` and `depth` together (`kvstream_apply`). A streamed group takes
its id space from the context (`kv_context_blocks`) rather than the pool split, so it does not
compete for VRAM; it never lends to the expert slab, and the idle tiers never gather it (§4.1).
Refused or charged by name:
- **a window that does not fit** the budget is refused against `--kv-resident` before the split
(`kvstream_window_fit`), rather than leaving a neighbour with zero blocks;
- **a streamed `RAD_KV_WINDOW` group** is refused: a window bounds its own history;
- **the dense-read floor**: a group read over its whole history every step
(`rad_kv_group_dense_read`, an indexer's block keys) cannot stream, and while a sibling streams
its carve is `max_seqs` full contexts, since the sibling's mirror holds that many (`kvstream_dense`).
With nothing streaming the floor is off;
- **the maps** are reserved from the KV pool before `carve()`, which the budget probe cannot do, so
`kvstream_maps_charged()` charges them in both paths and the carve adds back what was reserved.
A ring that covers the group's context is not a streamed group: no mirror, maps, stage or resolve,
and a null `RadKVStream`, decided at startup.
### 3.2 The host mirror
The mirror is `RAD_MEM_HOST_MAPPED`, so a kernel reads it over the link in place, and laid out like
the pool: layer `l`'s row for block `b` is at `host + l * host_layer_stride + b * block_bytes`, with
`block_bytes` both the resolve's row pitch and the length of every copy into the ring. It is
`n_blocks * bytes_per_block`, zeroed at bring-up, and kept per rank, each rank with its own maps in
its own pool (`kvstream_step_view`). It is the first in-place device writer of mapped host memory,
so its coherence is pinned by a test (§6.2).
### 3.3 The writer maintains both copies
`kv_store_streamed`, and its fold into the prologue `qk_norm_rope_gate_kv_store_streamed`, writes
the host mirror always and the ring slot only when `res[block] >= 0`. A slot never goes stale, so
nothing needs invalidating, not on a rejected draft and not on a restore. The residency test must
be in the writer: at decode the block a step writes is usually the one the previous step made
resident, so a mirror-only writer would leave the ring's copy short of this step's tokens and the
resolve, seeing it resident, would not copy it. `res` is written by `kv_resolve` alone.
A layer's order is **store, then resolve, then attention**, so a block copied in from the mirror
carries this step's tokens; the indexer runs before the store and so cannot resolve. The streamed
store has E4M3 and bf16 rows; a packed cache (`fp8_v4`, `k6_v4`) has none and is ignored (§4.5).
### 3.4 The resolve
`qsa_select` writes pool page ids into `sel`, and `attn_paged` uses each entry as a raw pool index.
`sel` is the only place the sparse path names KV storage, so `kv_resolve`, between select and
attention, is the one op streaming adds: it makes every selected block resident, copying misses in
from the mirror, and rewrites `sel` as ring slots. Its operands, parameters and control block are in
docs/OPS.md ("kv_resolve"); `libref/ref_kvstream.cpp` is the serial definition.
The order is a contract, so every implementation places the same blocks in the same slots:
1. bump the epoch;
2. one lookup per valid entry: a hit stamps its slot and bumps its two-bit heat counter once a
call; a miss claims its map entry once (`-1 -> -2`), so the map is its own set;
3. the miss list in ascending block id, never first-appearance order;
4. one victim per miss: the block's own slot when free (a context shorter than the ring stays at
identity, and the attention's adjacent ids read adjacent slots), else a free slot, else a CLOCK
sweep over the heat counter that never takes a slot this call stamped;
5. re-point both maps;
6. copy each placed block as bytes;
7. rewrite every valid entry as its slot.
Step 3 makes the resolve deterministic; a device implementation sorts its claim list rather than
scanning `blocks`, so a launch costs its selection, not the cache.
**Overflow.** The ring must hold the call's selection union. When it cannot, the unplaced claims
revert to `-1`, `ctl[3]` latches and their entries become slot 0, a defined address (a block id
there would be read past the ring). The engine copies each group's `ctl` behind the step's last
resolve and reads it at the commit, so the step path never waits; a newly latched overflow fails
every request prefilling in that step, naming the ring and the union, and clears the latch.
**State and recording.** The epoch, hand, heat and counters live between calls, so two launches
must never overlap (the row is not in `rad_kernel_concurrent`). The op is recordable: its addresses
and pitches are fixed from bring-up. `Ctx::pass_key` keys a streamed group by the memory its view
names (`kvstream_view_key`), never by the view's address, which the builder's rotating Out slots
change every step.
**Three implementations.** `libref/ref_kvstream.cpp` is the oracle; `libavx/avx_kvstream.cpp`
follows it step for step and vectorises only the rewrite and the copy; `libr4d/r4d_kv_resolve.hip`
is the card's row, checked against libref by `r4d_selftest --case kv_resolve` (hits, ascending
misses, eviction, free before live, second chance, saturation, overflow, 2052 claims, the copy, the
refusals).
### 3.5 Prefill: the union, and the stage
Above `qsa_exact_to = budget + ratio - 1 = 2051`, prefill is per-query sparse: every row of a chunk
selects its own 512 blocks. One launch's union (`scripts/kv-union.sh`, Flash-Next `--tp 2`):
| prompt tokens | ring that held | largest union | largest misses of one call |
|---|---|---|---|
| 3 958 | 2 048 blocks | 990 | 976 |
| 16 048 | 4 096 | 4 000 | 1 024 |
| 66 131 | 16 384 | 14 608 | 1 024 |
| 133 331 | 32 768 | 23 429 | 1 024 |
The union is 70-100 % of the history and grows with it, so no ring sized for decode (at most 513
blocks a row) serves prefill. Prefill therefore takes the **stage**: one layer's whole history at
block-id addressing, filled from the mirror per layer, with no selection awareness and no resolve.
A prompt below `qsa_exact_to` runs dense attention, which reads block ids from the table; it stages
the same way.
### 3.5.1 The aliased stage and the ordering rule
Every layer of the stage aliases offset 0 of one allocation. The operand resolution accepts that:
a `RAD_KV` operand is bounded by `off + layer_stride <= bytes`, which a one-layer pool satisfies at
`off = 0` for every layer (`a_streamed_groups_layers_may_all_alias_one_pool_slot`). The aliasing is
the binding's `depth` (1 = every layer at offset 0), not a rewritten `layer_slot`: that table is also
the host mirror's row (`rad_kv_layer_index`), so collapsing it would write every layer into one
mirror row.
The KV operand is external memory, so the buffer plan never sees it, and the hazard pass sees the
same range for every aliased layer. The order rests on the stage's barriers alone, stated beside
the code in `core/kvstream/stage.h`: the copy of layer L lands before L's store, L's store and
attention follow, and the copy of L+1 starts after every attention launch of L. What breaks it:
taking the ride before all of L's chunked attention launches, waiting after the store instead of
before it, moving the copy to lane 1 without a join, replaying a recorded pass without re-running
the arm and submit (`Ctx::tape_kv_stage` does), or a binding that moves between passes sharing a
key.
A staged pass reads the pool by block id, while `kv_store_streamed` writes the ring only where the
map names a slot (none before the group's first decode), so a staged pass also stores at identity
(`AttnGatedFP8::store_stage_identity`, GLM's plain store), after the mirror writer.
**Volume.** A layer's copy moves only the blocks the step's own block tables name, not the whole
context allocation: its list carries one range per run of those ids (`kvstream_runs`), read every
step after the step's blocks are ensured (`kvstream_step_runs`). The ranges must never miss a block
the pass reads: the attention would read whatever the previous layer left, which is wrong text, not
a fault. They cover every read because the pass reaches the stage only through the step's tables,
the stage is identity-addressed as the mirror row is, and a prefix hit's cached blocks are in the
hit's table. Gaps of up to 16 blocks are copied through, and past 256 ranges the smallest gaps are,
so a fragmented table stays one short list. Blocks the prefix cache retains for other
conversations are not copied: they often hold the low ids, and a new sequence takes ids above them,
so a bound on the highest id a step names (or on the highest held one, as before) would still copy
every retained conversation, and each later prefill paid for all of them. A step whose sequences
are not known, or whose trunk pass takes the ring, copies up to `KVManager::held_top_blocks`.
### 3.6 The ABI surface
`RadKVStream` (`abi/rad_runtime.h`) is one group's fixed view: the mirror, the per-layer residency
maps (`res`, `slot_block`, `slot_state`), the shared control block, `block_bytes`,
`host_layer_stride`, the ring's `slots` and `host_bytes`. `RadKVGroupBatch` carries a trailing
`const RadKVStream* stream`, null for a resident group: a pointer, because the view is fixed at
bring-up while the batch is rebuilt every step. The build side is `RadBuildCtx::kv_resident_blocks`
(the ring in tokens), `RadBuildCtx::kv_stream_ok` and `RadArchProbe::kv_stream_ok` (§4.5). The arch
side is `rad_kv_layer_index`, `rad_kv_stage_layer` and `rad_kv_stage_next`, with the
`kv_stream_layer`, `kv_resolve_declare`, `kv_resolve_issue` and `kv_stage_*` helpers in
`arch/common/rad_arch.h`.
### 3.7 Flags, report, metrics
`--kv-resident N` is the only switch. The KV report gains the streamed group's two-tier line, and the
startup lines name the ring (and why it was raised), the host mirror, the stage, or which context a
covering flag spans. Metrics: `radiance:kv_resident_blocks`, `radiance:kv_stream_misses_total` and
`radiance:kv_stream_bytes_total{dir="in"}`. A request's end logs each group's cumulative resolves,
lookups and misses with the largest union, misses and claims of one launch (`ctl[10..12]`).
### 3.8 The host-RAM budget and the gate
The mirror is the largest host allocation after the experts' pool: 4.69 GiB a rank for four
204 800-token sequences of Flash-Next. `kvstream_host_gate` checks the mirrors once, before any rank
pins one, against the host tiers still to be pinned after them (the activation arenas and, when
sized, the checkpoint store) plus `--host-headroom-mib`. A refusal names `--max-model-len` and
`--max-num-seqs`, which size the mirror; `--host-pool-mib` sizes the experts' tier and cannot make
room.
The prefix cache's host tier (`--prefix-cache-mib`) is turned off when a group streams, before
anything is sized from it: an entry covers every cached group, and a streamed group's rows are
addressed by the block ids its sequence used, so the entry cannot move to a host slot
(`PrefixCache::demotable`). Prefix hits still work from VRAM; a conversation evicted from VRAM is
prefilled again rather than restored. "Streams" is the engine's answer (`cfg.kv_streams`): the flag
set, the architecture's streamed ops declared and linked for the group with an fp8 or bf16 cache,
and a ring under the context. In every other case the host tier is as configured.
### 3.9 What it costs
`--kv-resident` has two floors, applied in `kvstream_ring_shape`/`kvstream_ring` and clamped to the
context, and the carve takes the larger:
- **correctness**: one decode step's selection, `max_seqs x (1 + n_spec) x 513` blocks (16 416
tokens at two sequences and speculation 3); a request under it could not be served from the
selection table;
- **cost**: **32 768 tokens** (`kStreamFloorTokens`). Below about 24 576 tokens the misses cost more
than the VRAM the ring frees (at 64k of history: 24 576 runs 37.9 tok/s, 8 192 runs 37.1 with 75 %
more misses), and a ring larger than the history buys nothing.
A flag under either is raised with one warning. The raised number is what
`RadBuildCtx::kv_resident_blocks` carries into the declare, since `kv_resolve` sizes its table from
it. A context under 32 768 tokens cannot stream.
Decode: a miss costs about 0.8 us, and a resolve launch about 4 us of device time, flat across ring
sizes; the twelve a step cannot merge (each follows its layer's store), so streaming costs about 3 %
of decode at `--tp 2` and nothing at `--tp 1`. The identity placement is worth +2 % at 16k. Warming
the ring from the last prefill chunk made decode 3.8 % slower, through slot order.
Capacity is bought in host RAM. Flash-Next fp8, two ranks, `--kv-resident 24576`:
| configuration | VRAM KV per card | host RAM per rank |
|---|---|---|
| resident, 2 x 204 800 | 1.43 GiB, one conversation retained | - |
| resident, 4 x 204 800 | 1.53 GiB, 25 % of the four conversations | - |
| streamed, 2 x 204 800 | ring 144 MiB, stage 200 MiB (pool 200 MiB), indexer 300 MiB: 618 MiB | 2.34 GiB |
| streamed, 4 x 204 800 | ring 144, stage 400, indexer 600: 1 232 MiB, all four funded | 4.69 GiB |
Per retained token: 6.00 KiB of mirror (host), 0.83 KiB of indexer and 0.50 KiB of stage (VRAM);
only the ring does not scale. Prefill comes out 3-5 % above the resident arm, because the VRAM the
cache no longer holds goes to experts that would otherwise be read over the link. The stage copy's
cost is its volume (0.6 GiB a pass at 16k and 45 GiB at 160k, within 0.3 % of the live KV, a
figure the step's own ranges keep however much the prefix cache retains), not its overlap, since it shares the link as an equal (§6.1). Capacity is bought with
`--max-num-seqs`, inside the trained window, so no rope change is needed. Perplexity: 3.994 resident,
4.015 with a covering window, 4.014 with a fraction of it.
---
## 4. Architecture
### 4.1 The module
`core/kvstream/` holds the feature; the existing files make one call at each seam.
| file | owns |
|---|---|
| `plan.h`, `.cpp` | the policy: which group streams, the ring's floors, the sizes, which ops a group needs. Arithmetic only. |
| `bind.h`, `.cpp` | the layout: both views over a plan, `layer_slot` kept as the mirror's row, the per-pass view, `kvstream_step_view`, `kvstream_view_key`. |
| `stage.h`, `.cpp` | the driver: per pass and layer, the copy of the layer's live blocks from the mirror into the stage on the DMA engine (§5.3). |
| `mirror.h`, `.cpp` | the mirror and the maps: sizes, allocation, initialisation, release, the window cap and the counters. `KVManager` holds one `KVStreamStore` and delegates. |
| `carve.h`, `.cpp` | the carve's part: windows and the dense-read floor leaving the budget first, the window-fit refusal, `n_blocks`/`n_slots`/`depth`, the maps' charge, the report line. |
| `bringup.h`, `.cpp` | the engine side: the group, the refusals (§4.5), the floors, the host-RAM gate, the startup lines. |
Only `stage.cpp` and `mirror.cpp` touch a device. Deliberately left alone: the block ids, refcounts
and free lists (the stage addresses every block identically, and a prefix hit adopts the same ids);
`TierExec` (a gather of one layer from a one-layer pool would copy the last staged layer `n_layers`
times; the mirror is the tier); the prefix cache's host tier (§3.8); the expert stager and mover; and
`qsa_select`.
### 4.2 Core changes
1. **The carve split**: `n_slots` beside `n_blocks`, `layer_stride()` over `n_slots`, ids still in
`[0, n_blocks)`.
2. **The host mirror**: `n_blocks * bytes_per_block` of mapped pinned memory a streamed group and rank,
gated by `lockable_room`.
3. **The maps**: device `res`, `slot_block`, `slot_state` per layer and a control block, from the KV
pool, carried in the batch.
4. **Report, flag, metrics** (§3.7).
### 4.3 Device changes
1. `kv_resolve`: a libr4d kernel, a libavx form and the libref oracle (§3.4).
2. `kv_store_streamed` and its prologue fold (§3.3), E4M3 and bf16.
3. The stage copy, a DMA list per layer (§5.3); no kernel.
### 4.4 Arch changes
The gated fp8 attention block (`arch/common/rad_block_attn_gated_fp8.h`) declares the streamed store
beside `kv_store`, issues it instead when the batch hands the group a stream, and issues the resolve
after the store and before each sparse launch. GLM-5.3's MLA block (`rad_block_glm_mla.h`) declares
the same pair and resolves at finish, after its indexer selects.
### 4.5 The capability gate
A plugin states once, in `RadArchProbe::kv_stream_ok`, that its architecture can stream; the engine
carries it into every declare as `RadBuildCtx::kv_stream_ok`. `qwen4exp_fp8` and `glm5next` set it.
The three streamed-only ops (`kv_store_streamed`, its fold, `kv_resolve`) are declared only when the
architecture can stream and `--kv-resident` asks for a ring (`kvstream_op_gated`, consulted by
`Builder::op_declared`), so a model file never knows whether the operator asked, and every
`rad_op_declared` check falls through to the resident path. Fail-safe, with one warning each:
- a group with no `kv_resolve` or no streamed store for its geometry is ignored: without the resolve
the attention would read block ids past the ring; without the store a miss would read zeros. A
declaration with no kernel, or one stating another group's geometry, does not count;
- a packed cache (`fp8_v4`, `k6_v4`) is ignored the same way, naming the layout;
- an architecture whose probe says no turns the flag off at startup.
Without the flag no streamed op is declared and no budget changes. The graph is not byte-identical
to a build without the feature, though: `qsa_select` writes its entry count (`qsa_nsel`,
`selected_count`), an i32 a token, whether or not anything streams.
---
## 5. The stage copy's transport, and the ring's depth
### 5.1 The ring's depth
`--kv-resident` is off by default. When set it is never carved below 32 768 tokens, nor below one
decode step's selection when that is larger (§3.9), and never above the context; one function,
`kvstream_ring_shape`, gives the budget probe, the carve and the declared `kv_resolve` the same
depth.
`kv_pass_view` picks a pass's view: a decode pass of at most `1 + n_spec` rows a sequence takes the
ring; every other pass (prefill, a mixed step, and a decode-classified pass wider than that, such as
the serial drafter's history pass over a prefill chunk) takes the stage.
### 5.2 There is no streaming switch
`--kv-resident N` is the feature: absent or 0 and nothing streams, set and the ring is N tokens. A
ring that covers the context does not stream at all (§3.1), so a configuration whose context fits
runs the same path as without the flag.
### 5.3 The transport
The copy of layer L+1 is one `rad_xp_list` on the card's prefetch DMA queue, riding (`rad_ride`) on
the compute stream after every attention launch of layer L, so it starts once L is done with the
aliased buffer and crosses the link under L's out projection and L+1's projections, holding no CU
slot. The compute stream waits for it before L+1's store through an event the list completes
(`rad_event_dma`): the list writes 0 to the event's completion word, armed with a 1 in stream order
by the weight-table patch dispatch the ride completes on. A host-side arm could race a wait still
queued for layer L, and an event record cannot be used, since a record completes by reaching 0.
The list passes `RAD_XP_NO_YIELD`: the compute stream waits on it, so yielding the link to a hold
whose release is behind that wait would deadlock. A backend with no DMA queue copies on the compute
stream in the same order. The arch seams are `kv_stage_wait` before the store and `kv_stage_next`
after the attention (`arch/common/rad_arch.h`).
### 5.4 What is not reused
The transport is the expert prefetch's; the policy is not. The prefetch patches weight-table entries
and is sized for experts, and a late prefetch is simply unused, while a stage copy cannot be skipped
and must be waited on. They do not compete: the prefetch is decode-only and the stage prefill-shaped.
Rejected alternatives: carving the stage from the arena's lent top (a KV base inside another owner's
pool, lent per step while the carve is per bring-up); a full `n_layers`-deep buffer lent to the
experts between requests (1.66 GiB at 262K during prefill, and reclaiming it is a host wait); the
whole context resident during prefill (the group would still carve `n_layers x context`).
---
## 6. Failure modes and the tests that hold them
| failure mode | what prevents it | test |
|---|---|---|
| a block id read as an address past the ring | the resolve rewrites every entry; overflow writes slot 0, latches, fails the request | `tests/ref_test.cpp` `kv_resolve_*`; `r4d_selftest --case kv_resolve` |
| a streamed plan without a mirror or maps | `kvstream_apply` refuses | `a_streamed_group_is_refused_at_carve_without_its_host_copy` |
| a pool whose depth disagrees with its id space | `n_blocks`, `n_slots` and `depth` written together | `a_streamed_group_addresses_its_context_but_backs_only_the_resident_window` |
| a streamed window group, or a window that does not fit | refused by name | `a_streamed_window_group_is_refused_by_name` |
| a ring under one decode step's selection | raised at startup | `a_ring_below_one_decode_step_s_selection_is_raised_to_the_ceiling` |
| a covering ring paying for streaming | `streams()` false, null `RadKVStream` | `a_ring_that_covers_the_context_streams_nothing_and_the_engine_pays_nothing`; `scripts/kv-parity.sh` |
| a wide decode-classified pass resolving a ring it cannot fit | `kv_pass_view` takes the stage | `a_decode_pass_wider_than_a_verify_stages_instead_of_resolving_the_ring` |
| a mirror nothing writes | the store must resolve to a kernel for the group's geometry | `a_declared_streamed_store_with_no_kernel_is_not_a_streamed_path`; `a_packed_cache_warns_that_the_layout_has_no_writer_and_serves_non_streamed`; `a_resolve_declared_for_another_group_does_not_enable_streaming` |
| the flag honoured with no streamed path | the capability gate | `a_model_whose_architecture_declares_no_streamed_ops_ignores_the_flag`; `a_streamed_op_exists_only_for_a_capable_architecture_and_a_ring` |
| a stage reading the previous layer's bytes | the ordering rule (§3.5.1) | `a_streamed_groups_layers_may_all_alias_one_pool_slot`; `scripts/kv-stage-parity-64k.sh` |
| a stage copying less than the pass reads | the ranges of the step's own tables | `the_stage_ranges_cover_every_block_a_table_names`; `scripts/kv-stage-parity-64k.sh` |
| a stage copying what other conversations hold | the ranges of the step's own tables | `the_stage_ranges_leave_out_blocks_no_table_of_the_step_names` |
| a stage list's mark reused while the list still polls it, both cards stopped | the signal pool holds a mark until its list's engine is past the poll | `device_test` `a_dma_lists_mark_stays_out_of_the_pool_until_the_engine_has_read_it` |
| maps leaving the pool short of the probe | `kvstream_maps_charged` in both paths | `a_streamed_groups_maps_are_charged_before_the_pool_is_sized` |
| a dense-read sibling funded for one sequence | the `kvstream_dense` floor | `a_dense_read_groups_floor_holds_every_sequence_while_a_sibling_streams` |
| a recorded pass replayed against another view | `kvstream_view_key`; fixed addresses | `Ctx::pass_key`'s static assertion on `RadKVGroupBatch` |
| the copy moved to another lane or re-issued from the host | §3.5.1 and §5.3 | reviewed, not tested |
### 6.1 The link, the lanes, and the hold
At `--tp 2` the all-reduce, the stage copies and the prefill expert stager share the link. DMA lists
take their share at full rate without a CU slot; an ordinary stream copy would hold one and starve
the kernels. Because the stage list must not yield, it competes as an equal, which is why overlap
recovers only part of its cost (§3.9). A stage moved to lane 1 needs `rad_lane_join(1, 0)` before
its reader.
### 6.2 The first in-place device write to mapped host memory
`r4d_selftest --case kv_store_streamed_fp8` and `--case kv_store_streamed_bf16` put the mirror in
mapped pinned memory, run the kernel and compare the bytes the host reads after the sync with
libref's; `scripts/kv-stage-parity-64k.sh` exercises the same write in the served path.
### 6.3 Rank coverage
Every rank resolves the same shared block ids through identically built maps of its own. Only
`--tp 1` and `--tp 2` have run; `--tp 3` and `--tp 4`, the uneven split, the attention-zero ranks
and the four-card selftest cases are untested, and the per-rank view (`kvstream_step_view`) is the
path to check first.
### 6.4 The draft model
The MTP head binds the same `kv_attn` group. A verify step issues one selection a row and takes the
ring, which is why the decode bound counts `1 + n_spec` rows (§3.9), and a decode-classified pass
wider than that stages (§5.1). Whether the drafter should share the residency map with the trunk
is open.
+433 -49
View File
@@ -190,6 +190,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
| op | params | operands |
|---|---|---|
| `rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`, `w`w? → `y` (no gain operand: a gain of one) |
| `rmsnorm_rows` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`, `w`w? → `y` (the same norm; at n <= 256 with 1024+ rows a wave a row, byte-identical) |
| `rmsnorm_p` | `M`(range) `n` `eps`:f64 `dtype` | `x` → `y` |
| `rmsnorm_add` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`, `w`w → `y`, `residual_out` |
| `hc_enter` | `M`(range) `n` `hc` `dtype` | `x` → `h` |
@@ -211,11 +212,15 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
| `mul_weight` | `M`(range) `n` `dtype` `scalar`/opt | `x`, `w`w → `y` (w one element or one row) |
| `act_mul` | `M`(range) `n` `act` `dtype` | `a`, `b` → `y` (act(a)·b, two operands) |
| `seg_mean` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (one mean row a segment) |
| `seg_softmax_pool` | `M`(range) `n` `dtype` | `score`, `v`, `cu_seqlens` → `y` (one softmax-weighted row a segment) |
| `seg_mean_bf16_sum` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (BF16 sum, then BF16 quotient) |
| `pool_rows` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean row a window of k rows) |
| `pool_cols` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean column a window of k columns) |
| `relu` | `M`(range) `n` `dtype` | `x` → `y` |
| `clamp` | `M`(range) `n` `dtype` | `x`, `lo`w, `hi`w → `y` |
| `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` `t_last`/opt `act`/opt | `x`, `w`w, `cu_seqlens`, `valid`? → `y`; `b`w? |
| `conv2d_unfold` | `M`(range) `width` `cin` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `t_last`/opt `dtype` | `x`, `cu_seqlens`, `valid`? → `y` |
| `pixtral_merge` | `M`(range) `n` `merge` `dtype` | `x`, `coord` → `y` |
| `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y`; `b`w? |
| `rel_sinusoid` | `M`(range) `n` `max_timescale`:f64/opt `dtype` | → `y` |
| `gelu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gelu·up, tanh approx) |
@@ -288,10 +293,30 @@ rounded to `y`'s dtype before the product, as the unfused pair stores it.
`[cu[s], cu[s+1])`, summed in double and rounded once. `M` is the step's token count and bands the
op; the segment count is `cu_seqlens`' length less one. An empty segment is a zero row.
**`seg_softmax_pool`** is `seg_mean` with learned weights: row `s` of `y` is `v`'s rows
`[cu[s], cu[s+1])` summed with the softmax of their `score`s (one a row of `v`, f32, the maximum
subtracted) as the weights, the sum in f32 and rounded once. It is a query reading its few
candidates: clef's joint schema head routes each question over its options this way, the scores
the options' dot products with the question. `M` bands the op as `seg_mean`'s does, and an empty
segment is a zero row.
**`seg_mean_bf16_sum`** preserves the two BF16 stores of Nemotron 3.5 Rerank's masked
mean: sum the segment in f32, round the sum to BF16, divide by its valid-token count,
then round the quotient to BF16. Input and output are BF16; cumulative lengths are
int32, begin at zero, end at the active input row count and describe nonempty segments.
Pitched rows are supported. This is a separate operation so `seg_mean` and existing
embedding models keep their one-rounding contract.
**`pool_rows`** is a vision pooler over windows laid out consecutively: row `r` of `y` is the mean
of `x`'s rows `[r*k, r*k + k)`, summed in f32 and rounded to `y`'s dtype, then times `mult` and
rounded again (the unfused pair stores the mean). `M` is the input row count, a multiple of `k`.
**`pool_cols`** pools along a row instead: column `c` of row `m` of `y` is the mean of `x[m]`'s
columns `[c*k, c*k + k)`, with the same f32 sum, the same two roundings and the same optional
`mult`. `n` is the input width, a multiple of `k`; `y` has `n / k` columns. MiniMax-H3's audio
encoder pools its attention block's features this way (an `adaptive_avg_pool1d` over the feature
axis).
**`fill`** writes `y = value` over the extent (`value` 0 when absent). A rank issues it where it
computes nothing but a downstream reader still expects a defined buffer: an attention-zero rank's
block (`docs/TP3.md`) is one `fill` of its output wire before the all-reduce. A wire shared across
@@ -457,7 +482,25 @@ at h128/gqa8 up to q_len 16 by reading each kv head for two query groups of 4 (a
then holds each kv head once). Since no host library declares the op, a plugin that asks for it
learns whether a card serves the geometry.
libref has no row for any of them, deliberately. An architecture asks for a fusion and declares
Tree verification (`rad_drafter_tree`, abi/rad_builder.h) adds one operand to both: the step's
`RadBatch::spec_parent`, `[rows]` i32.
| op | params | operands |
|---|---|---|
| `attn_paged_tree` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `prefill_fp8`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `spec_parent` |
| `attn_paged_qrow_tree` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `prefill_fp8`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `spec_parent` |
A row whose `spec_parent` is -2 is an ordinary causal row. Any other row is a node of its sequence's
verify block, and its entry names its parent by row within the sequence's rows (`cu_seqlens`), -1
for the block's first row, every parent before its child. Inside the block (keys from
`seqused - q_len` on) such a row sees itself and its ancestors only; before it, every key as an
ordinary row does, except that a window is measured from the block's first position plus the row's
depth, the position its token takes once its path is committed. Causal layers only. libref serves
`attn_paged_tree`; libr4d `attn_paged_qrow_tree` at h256/gqa2 on the split-KV decode kernel and at
every geometry of the windowed kernels, to 64 rows a block.
Of the ops above, libref serves only `attn_paged_tree`, which is not a fusion but `attn_paged`'s
tree form. It has no row for any of the fusions, deliberately. An architecture asks for a fusion and declares
the chain where it does not resolve (`rad_op_resolved`); a reference row would make it resolve
everywhere, so a model loaded without the serving library would resolve to the reference and be
refused at serve, instead of running the chain on libr4d or libavx. libr4d declares them with
@@ -505,7 +548,7 @@ second of a clip apart and attends in windows of eight seconds:
| `rmsnorm_had_quant_i8` | `M`(range) `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
| `gated_had_quant_i8` | `M`(range) `n` `group` `dtype` `act`:str/opt `mode`/opt | `a`, `b`? → `q`, `scale` |
| `dequant` | `M`(range) `n` `group` `dtype` | `q`, `scale` → `y` |
| `gram_accum` | `M`(range) `n` `group` `dtype` | `a`, `a_scale`?, `h`:inout |
| `gram_accum` | `M`(range) `n` `group` `dtype` `upper`/opt | `a`, `a_scale`?, `h`:inout |
**`gram_accum`** characterises a quantiser's output:
`h[k1][k2] += sum over rows of dequant(a)[m][k1] * dequant(a)[m][k2]`, the Hessian a GPTQ packer
@@ -515,7 +558,10 @@ block. It is not `gemm_nt` with a transposed operand: that op contracts the last
and this one the first. It is the one op here that no forward pass issues; it runs under a
calibration flag and its result is read at convert time, in another process, through a file.
`dtype` says how `a` is read: `fp8a8` is E4M3 codes with an f32 dequant scale per (row, `group`
columns) in `a_scale`; `bf16` is a plain activation with no `a_scale` and no grouping.
columns) in `a_scale`; `bf16` is a plain activation with no `a_scale` and no grouping. `upper` 1
accumulates only `k2 >= k1`, the half a reader of the symmetric `h` needs, for half the work; the
entries below the diagonal are then outside the contract (libr4d adds whole 64-wide tiles, so it
writes some of them).
**Activation widths.** Which width a linear's activation takes follows from the weight. Where the
checkpoint ships E4M3 weights and a block scale plane, every linear is `fp8a8`
@@ -592,6 +638,8 @@ and is optional.
| `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? |
| `swiglu_clamped_quant_fp8` | `M`(range) `n` `limit`:f64 `group` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? |
| `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? |
| `gemm_nt_q_gated_wide` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? (the same fold at every M: the narrow tile to 64 rows, past them the gated prefill tile) |
| `gemm_nt_q_gated_mx` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w, `b_ref`w → `q`, `scale`, `out_bf16`? |
`quant_cols_fp8` is the same E4M3 quantiser with one scale per column over all `M` rows,
`scale[c] = amax_r |x[r, c]| * (1/448)` (1 for an all-zero column), `scale` `[n]` f32: an
@@ -605,6 +653,11 @@ it does not produce that op's `y`. `act` is required here, unlike on the quantis
implementation may compile one gate only, and an optional parameter would let it resolve for
another.
`gemm_nt_q_gated_mx` is the same fold over an OCP-MXFP4 weight (`dtype` `mxfp4a8`, `group` 32), which
`gemm_nt_q` reads with the per-row reference exponent `b_ref` after `b_scale`. A schema of its own
because an op's operand count is fixed for the plugins built against it. `act` `gelu_tanh` is the
GeGLU form, `gemm_nt_q` then `gelu_mul` then `quant_act_fp8`; it writes no `out_bf16`.
`swiglu_clamped_quant_fp8` (device-only) is `swiglu_clamped` then `quant_act_fp8` over its
product in one pass. The product is rounded to bf16 before the quantiser reads it, as the pair
reads it from its bf16 tensor, so the codes, scales and `out_bf16` are the pair's bytes, NaN and
@@ -629,7 +682,8 @@ so the activation takes the same rotation once a token.
of `a' = a cos t + b sin t, b' = b cos t - a sin t`. Each pair lies inside one scale group, so the
matrices belong to the weight: rad-convert composes them once in f64 and stores them as the
weight's `t.dense` table, which the layout hook (`r4d_rad_layout_gdense`) only moves. Consumers
are `gemm_nt_q` at `mxfp4a8` (`out` fp8) and at `w4a8i8_asym` / `w5a8i8` (`out` i8).
are `gemm_nt_q` at `mxfp4a8` and `m2xfp4` (`out` fp8) and at `w4a8i8_asym` / `w5a8i8` (`out`
i8).
- **`givens_rotate`** is the same rotation stage by stage with no quantiser, `y` in its own dtype
(f16), for the 16-bit-activation weights `w5a16` and `w4a16_asym`, whose GEMM serves any `M`
(rows past 64 run as chunks of 64).
@@ -639,9 +693,9 @@ A fused projection (gate|up, qkv|z) was rotated per checkpoint tensor, so the ac
`pairs` and `angle` stack each part's `stages` rows and `rscale` has one row per part. `gemm_nt_q`'s
`pb1` and `pb2` are the row bounds of the weight's parts: rows `[0, pb1)`, `[pb1, pb2)` and
`[pb2, N)` meet copies 0, 1 and 2 of the wide `a`/`a_scale`. `pb1` absent is one part; `pb2` absent
ends the second part at `N`. The `mxfp4a8` rows and the asymmetric 4- and 5-bit rows read them;
host rows that do not (libavx) refuse a call that names one rather than contract against the wrong
copy.
ends the second part at `N`. The `mxfp4a8` and `m2xfp4` rows and the asymmetric 4- and 5-bit rows
read them; host rows that do not (libavx) refuse a call that names one rather than contract against
the wrong copy.
### Int8 and gated fp8 fusions (device-only)
@@ -653,7 +707,9 @@ copy.
| `rmsnorm_had_quant_i8g` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
| `gate_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate`, `x` → `q`, `scale`, `out_bf16`? |
| `rmsnorm_quant_i8` | `M` `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
| `rmsnorm_quant_i8g` | `M` `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
| `gelu_mul_quant_i8` | `M` `n` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? |
| `gelu_mul_quant_i8g` | `M` `n` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? |
`gelu_mul_quant_i8` is `gelu_mul` with `rmsnorm_quant_i8`'s quantiser on its pass, byte-identical
to the pair.
@@ -674,6 +730,14 @@ multiplies the sum after it, together a sandwich-norm model's residual junction
→ `scale` → `rmsnorm` → `quant_act_i8`). Byte-identical to that chain: every intermediate the chain
stores is rounded to bf16, and both sums of squares take `rmsnorm`'s partition.
`rmsnorm_quant_i8g` and `gelu_mul_quant_i8g` are `rmsnorm_quant_i8` and `gelu_mul_quant_i8` with
`quant_act_i8g`'s quantiser instead: row-major int8 codes and an f32 scale per (row, 128 columns),
`scale` `[M, n / 128]`, what `gemm_nt_q` reads at `dtype=i8a8`, `w4a8i8_asym` and `w5a8i8`.
Byte-identical to the same chains ending in `quant_act_i8g`. `n` is a multiple of 128. On
`rmsnorm_quant_i8g`, `out_bf16` may be `x`'s own buffer: a junction whose next linear reads bf16 at
decode heights (`w4a16_asym`, `w5a16`) writes the norm output where the unfused norm would, in
place of the branch output it has consumed.
### `dequant_w4` (device-only)
| op | params | operands |
@@ -697,7 +761,8 @@ may not have arrived.
| `gemm_nt` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` |
| `gemm_nt_f32` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` |
| `gemm_nt_bias` | `M`(range) `N` `K` `dtype` `act`/opt | `a`, `b`w, `bias`w, `res`? → `y` |
| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt `split_n`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? |
| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt `split_n`/opt `w_rb`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? |
| `gemm_nt_q_short` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt `split_n`/opt `w_rb`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? (the narrow fp8 row with the short-prompt split rule: N <= 512, K <= 5120 and 41..64 rows run unsplit) |
| `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` |
`nt` is A row-major `[M,K]` times B transposed `[N,K]`, giving `[M,N]`: the layout every weight in
@@ -719,9 +784,8 @@ At `m2xfp4` -- the `m2xfp4` quantiser's own scheme, not an affine grid -- `b` is
codes and meta planes concatenated as stored (the codes rows, then the meta rows; the form the
core's selection reader hands out, core/format/encoding.cpp) and `b_scale` the E8M0 plane as at
`mxfp4a8`. The exact element is `e2m1(code) . 2^(e-127) . (1 + k_s/4)`, `k_s` the meta byte's
two-bit field over subgroups of eight columns (libquant's `lq_m2xfp.cpp`); the host rows take the
weight's group at that eight and fold the multiplier into the scale stream, libr4d's rows fold it
into their staging table. `b_ref` is the mxfp4 grid's, accepted and ignored.
two-bit field over subgroups of eight columns (libquant's `lq_m2xfp.cpp`). `b_ref` is the same
reference exponent plane as at `mxfp4a8`.
`a_sum` removes an asymmetric grid's zero point and `b_ref` is the per-row reference exponent an
MXFP4 kernel folds its block exponents against. `b_ref` is derived from `b_scale` and does not
@@ -742,6 +806,15 @@ weight element (n, k) is `(code - zero) * scale`, one f16 scale and one integer
ParoQuant grids (the four 4- and 5-bit ones) take parts (`pb1`, `pb2`); `w2a8` and `w4a8_asym` do
not, and none has a bias form.
`w_rb` is the weight rows one int8 scale covers, when the weight's form makes it more than one: a
trellis on libquant's `tcq_rb` grid, each value read against its block's largest scale. Absent, 1.
An IQR weight under one f32 scale a row and one f32 factor a 128-K block for all rows (`kRowF32`,
a computed trellis's form) needs none: `gemm_iqr_*` fold the block's factor with the activation's
per-128 scale and take the row's in the epilogue.
A kernel may then fold one scale a block of rows: libr4d's `gemm_iqr_tiled` does (its form says
how many), as do `gemm_i8a8_rb8_tiled` and `gemm_i8a8_rb32_tiled` for an int8 weight whose
per-row scale plane holds each block's one value in each row.
`split_n` is the output width whose K split the call takes, when it is a row slice of a wider
linear (a rank's share of a weight whose rows do not divide among the ranks, issued as two slices).
libr4d's narrow fp8a8 and i8a8 kernels pick their K split from N alone, and the split sets the order
@@ -860,8 +933,14 @@ as the weight's GEMM stored them and claims no form. It changes no value.
| `attn_local_rel` | `M`(range) `head_dim` `n_head` `left` `right` `softcap`:f64 `cu_div`/opt `dtype` | `q`, `k`, `v`, `relk`, `pds`w, `cu_seqlens` → `out` |
| `sam_attn` | `M`(range) `head_dim` `n_head` `grid_h` `grid_w` `window` `scale`:f64 `dtype` | `q`, `k`, `v`, `cu_seqlens`, `out`, `rel_pos_h`w, `rel_pos_w`w |
| `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout |
| `kv_store_streamed` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout, `res`, `host`:inout |
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` |
| `rope_rows` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` (the same rotation; at 64+ rows and 4+ heads one angle a (token, pair), byte-identical) |
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` |
| `position_scale` | `M`(range) `n` `original` `beta`:f64 `dtype` | `x`:inout, `positions` |
| `embed_attn` | `M`(range) `head_dim` `gqa` `causal` `max_seqlen`/opt `dtype` `scale`:f64/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
| `ministral_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `qkv`:inout, `pos` |
| `pixtral_rope` | `M`(range) `head_dim` `n_head` `theta`:f64 `dtype` | `qkv`:inout, `coord` |
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? |
| `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `v_norm`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w |
| `qkv_norm_rope_kv_store` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` `v_norm`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w, `slot_mapping`, `kv_cache`:inout |
@@ -976,6 +1055,42 @@ prefix of the full-width table: at `head_dim 512, rotary_dim 128`, frequency `i
ladders), and the head past `rotary_dim` is untouched either way. `rope_table` takes `head_dim` for
the same reason: its angles must stay `rope`'s exactly.
**`position_scale`** multiplies query row `r` by
`1 + beta * log(1 + floor(positions[r] / original))`, rounding the multiplier to the input's
dtype before multiplying. It takes a pitched `[M, n]` query view and nonnegative i32 positions;
columns outside that view (keys and values in a fused QKV buffer) are unchanged. `original` must
be positive and `beta` finite and nonnegative. It currently has host rows for bf16 and f32 only.
It implements Ministral 3's query scaling after RoPE; it is independent of YaRN's cos/sin
magnitude and does not change existing `rope` behavior.
**`embed_attn`** serves complete noncausal segments of at most 32768 rows. QK dot products
are rounded to the activation dtype, multiplied by `scale` (default `1/sqrt(head_dim)`) and
rounded again. Softmax is float32; its probabilities are rounded to the activation dtype before
the value product. This reproduces the eager BF16 materialization boundaries used by the
Nemotron reference. `causal` must be zero. Existing `attn_dense` semantics are unchanged.
**`ministral_rope`** rotates the Q and K heads of fused QKV rows with NeoX pairing and the
resolved YaRN frequency ladder. Cosine/sine are rounded to the activation dtype, as are each
of the two products before addition/subtraction, matching Ministral's BF16 rotary expression.
V heads are unchanged. Active rows come from the issued tensor views; `M` is the capacity band.
This separate operation preserves every existing `rope` implementation and schema.
**`pixtral_rope`** rotates Q and K of `[M, 3 * n_head * head_dim]` fused QKV rows, leaving V
unchanged. `coord` is `[2, M]` nonnegative i32 `(height, width)` patch coordinates. The head
dimension must be divisible by four. NeoX pairs `(i, i + head_dim/2)` use the height ladder
`theta^(-4j/head_dim)` for `i = j < head_dim/4`, then the width ladder
`theta^(-(4j+2)/head_dim)` for `i = j + head_dim/4`. In BF16, cos/sin and each product are
rounded before the addition, as in Transformers. Host rows support BF16 and f32. This is a
separate contract from `rope`'s existing axial mode, whose two ladders are identical.
**`pixtral_merge`** packs `[M, n]` raster patch rows into `[M / merge^2, n * merge^2]` rows.
`coord` is `[4, M]` i32 `(row, column, height, width)` patch coordinates; it must describe whole
raster grids, each side divisible by `merge`. Images may have different widths. One output row
is a merged spatial cell with columns `(channel, dy, dx)`, matching PyTorch `unfold`; values
are copied exactly. The complete coordinates are validated before writing, so invalid grids
leave the output unchanged. Host rows support BF16 and f32. Automatic random shape fixtures
cannot supply this coupled coordinate grid; callers must provide a valid grid fixture.
**`qk_norm_rope`** RMS-norms each q and k head of a fused `[q | k | v]` row against its gain (plus
`wadd`), rounds, and rotates in place. `positions` is read as `rope` reads it, integer or f32.
@@ -1042,30 +1157,33 @@ declares bound it lower.
`RadKVGroupBatch` carries the slot mapping, the block table and the sequence lengths, but the pool
base belongs to the block manager, not the batch.
**`kv_dtype` `fp8_v4` and `k6_v4`** (device-only) are the quantised layouts of
`--kv-cache-dtype` (`RadBuildCtx::kv_quant`). A head's dims are grouped by 32, each group with an
f16 scale (its absmax over the largest code, clamped so every code decodes finite in f16),
codes two's complement. A token's row in a head, at
head_dim HD:
**A streamed group's cache operand is its ring.** Its pool holds `slots` blocks while the block
table names up to `blocks` ids, so the sparse path resolves the selected ids to ring slots first
(`kv_resolve`, under "Sparse attention (QSA)"), and every other op reads the cache as before.
Such a group is written by `kv_store_streamed`. A layer's order is store, then resolve, then
attention, so a block the resolve copies in from the mirror carries this step's tokens.
| bytes | `fp8_v4` (25 HD / 16) | `k6_v4` (22 HD / 16) |
|---|---|---|
| K | [0, HD): E4M3, as `fp8_e4m3` | [0, HD/2): the codes' low four bits; [HD/2, 3HD/4): their high two bits, a word per 16 dims whose byte j holds dims 2j, 2j+1 in bits 0-3 and 8+2j, 9+2j in bits 4-7 |
| V | [HD, 3HD/2): int4 codes, dim d in the nibble at bit 4 (d mod 2) of byte d/2 | [3HD/4, 5HD/4): the same |
| scales | [3HD/2, 25HD/16): V's (absmax / 7) | [5HD/4, 21HD/16): K's (absmax / 31); [21HD/16, 22HD/16): V's |
### `kv_store_streamed`
The group is declared at `RAD_F8E4M3` with head_dim the row's bytes / 2, so the core sizes pages
as it does for fp8, and the cache operand's last extent is the row. The ops take the model's
head_dim. libr4d's rows are `kv_store_fp8v4` / `kv_store_k6v4`,
`qk_norm_rope_gate_kv_store_fp8v4` / `_k6v4` (byte-identical to the prologue and the store, as at
the other widths), `attn_prefill_h256_gqa6_{fp8v4,k6v4}` and `attn_decode_h256_gqa6_{fp8v4,k6v4}`,
which widen the codes to f16 in a tile's staging, and the same kernels at Qwen3.8-Flash-Next's
ratios over 4-token pages: `attn_{prefill,decode,decode_gq}_h256_gqa12_{fp8v4,k6v4}` and
`attn_{prefill,decode,decode_gq}_h256_gqa6_bs4_{fp8v4,k6v4}`, the `decode_gq` rows with the output
gate and quantiser in the split-KV merge. `r4d_selftest` holds the stores to an exactly
representable set and the attention rows to its inline oracle.
`kv_store` for a streamed group, into both of its copies.
### `qk_norm_rope_gate` (device-only)
- **`k`, `v`, `slot_mapping`** — as `kv_store`; a negative slot is skipped. `slot / block_size` is
the block and `slot % block_size` the position in it.
- **`host`** — bytes `[blocks, row]`, inout: the layer's authoritative mirror, one block a row in the
cache's layout (`[block, kv_heads, block_size, 2 * head_dim]`, K then V in a slot). Written for every
token with a slot.
- **`kv_cache`** — the ring, `RAD_KV(group, layer)`. Written at `res[block]` only when that is `>= 0`.
- **`res`** — `i32 [blocks]`, in: the residency map. Read, never written; residency is
`kv_resolve`'s decision.
The residency test is in the writer because at decode the block a step writes is usually the one
the previous step made resident: a mirror-only writer would leave the ring's copy short of this
step's tokens, and the resolve, seeing the block resident, would not copy it. Both planes share one
byte pitch, so one offset addresses the same element in either. The rows are
`kv_store_streamed_fp8` (`kv_store_fp8`'s conversion) and `kv_store_streamed_bf16` (the value
itself); a packed `fp8_v4`/`k6_v4` cache has none. A map entry outside `[-1, slots)` is a state
fault libref refuses; the device kernel treats it as absent, writes the mirror, and the resolve
refuses the step.
| op | params | operands |
|---|---|---|
@@ -1087,6 +1205,7 @@ rank-2 view can express, which would otherwise take `heads` `rmsnorm` launches p
| op | params | operands |
|---|---|---|
| `qk_norm_rope_gate_kv_store` | `M` `head_dim` `n_head` `n_head_kv` `rot` `q_dtype` `eps`:f64/opt `wadd`:f64/opt `cs_f32`/opt `pos_i64`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q_gate`?, `k`, `cos_sin`, `positions`, `q_w`w?, `k_w`w → `q_out`?, `k_out`, `gate_out`?; `v`, `slot_mapping`, `kv_cache`:inout |
| `qk_norm_rope_gate_kv_store_streamed` | `M` `head_dim` `n_head` `n_head_kv` `rot` `q_dtype` `eps`:f64/opt `wadd`:f64/opt `cs_f32`/opt `pos_i64`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q_gate`?, `k`, `cos_sin`, `positions`, `q_w`w?, `k_w`w → `q_out`?, `k_out`, `gate_out`?; `v`, `slot_mapping`, `kv_cache`:inout, `res`, `host`:inout |
**`qk_norm_rope_gate_kv_store`** is the prologue followed by `kv_store` in one launch: each k head's
block already holds its token's rotated k one element a lane, so it also writes that element and
@@ -1103,6 +1222,14 @@ accepts, but a rotated element is a difference of two products, so where those n
ULP becomes a few percent and the transcript moves within a few dozen steps. The kernel reproduces
the reference's fold exactly: widths above the head dim contribute zeros, and adding 0.0f is exact.
**`qk_norm_rope_gate_kv_store_streamed`** is that fold with `kv_store_streamed` as the store, taking
the residency map and the host mirror as its last two operands: the rotated k and the v go to the
mirror for every token with a slot and to `kv_cache[res[block]]` only where the block is resident.
The bytes are exactly `qk_norm_rope_gate` then `kv_store_streamed`'s. Rows `_fp8` and `_bf16`. It
saves a launch a layer on the decode path. A staged pass waits for its stage copy before this op,
which is the store; a pass the row declines (more than the fused rows, or mixed media positions)
runs the prologue and a separate store.
## Image generation
The ops a diffusion image generator declares (`rad_declare_generator`, `abi/rad_builder.h`): a
@@ -1117,7 +1244,7 @@ says which (`libref/ref_gen.cpp`).
| `ln_mod` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `s`, `cu_seqlens` → `y` |
| `gate_add` | `M`(range) `n` `dtype` `act`/opt | `y`, `g`, `cu_seqlens`, `x`:inout |
| `ln_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? |
| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `dtype` | `t` → `y` |
| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `clamp_min`:f64/opt `curve`/opt `dtype` | `t` → `y`, `table`w? |
| `gather_rows2` | `M`(range) `n` `dtype` | `a`, `b`, `idx` → `y` |
| `table_add` | `M`(range) `n` `L` `dtype` | `x`, `t`w → `y` |
| `mix_rows` | `M`(range) `n` `k` `dtype` | `x`, `w`w → `y` |
@@ -1158,7 +1285,13 @@ source into every listed lane (a repainted picture's latent into each of its ima
`t' = scale * t`; with `round` 1, `t' = scale * bf16(bf16(t * scale) / scale)`, the value
diffusers' pipeline hands its transformer; with `round` 2, `t' = scale * bf16(t)` (a pipeline
that hands the transformer `t` in bf16 and scales it inside, Krea 2's); with `round` 3,
`t' = bf16(scale * bf16(t))` (the scaling also in bf16, FLUX's). `t` is f32 `[M]`.
`t' = bf16(scale * bf16(t))` (the scaling also in bf16, FLUX's). `t` is f32 `[M]`. With
`clamp_min`, each `t` is first raised to it, `t = max(t, clamp_min)`: MiniMax-H3's pinned
references take a near-clean timestep whatever the step's. With `curve` = G > 0 and the `table`
weight (f32 `[G, n]`), `y[m]` is instead interpolated linearly between the table's two rows
around `clamp01(max(t[m], clamp_min)) * (G - 1)` (the lower row at most `G - 2`): the timestep
embedding a curve-form checkpoint ships precomputed, in place of the sinusoid and its MLP.
`scale`, `max_period` and `round` do not apply there, and `n` need not be even.
- `gather_rows2`: `y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]`, zeros past either source.
- `table_add`: `y[r, l n + c] = x[r, c] + t[l, c]` for each of `L` rows of the weight `t` `[L, n]`,
the sum f32 and rounded once: a modulation shared by every block plus each block's own learned
@@ -1272,14 +1405,16 @@ libref function says which (`libref/ref_audio.cpp`).
| op | params | operands |
|---|---|---|
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt `stride`/opt `pad`/opt `cu_div`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
| `conv_t1d` | `M`(range) `cin` `cout` `stride` `dtype` `pad`/opt `k`/opt | `x`, `w`w, `b`w, `cu_seqlens` → `y` |
| `snake` | `M`(range) `n` `dtype` `log`/opt | `x`, `alpha`w → `y`; `beta`w? |
| `snake_aa` | `M`(range) `n` `ratio` `k` `log`/opt `dtype` | `x`, `alpha`w, `beta`w, `f_up`w, `f_down`w, `cu_seqlens` → `y` |
| `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? |
| `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt | `codes`, `t0`w, `t1`w → `y` |
| `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt `top_p`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? |
| `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt `clamp`/opt | `codes`, `t0`w, `t1`w → `y` |
| `vq_encode` | `M`(range) `n` `dim` `bins` `dtype` | `x`:inout, `in_w`w, `in_b`w, `cb`w, `out_w`w, `out_b`w → `codes` |
| `frame_mix_store` | `M`(range) `n_embd` `L` `stride` `rep`/opt `dtype` | `hid`, `logits`w, `scale`w, `lane`, `frame`, `status`, `dst`:inout |
| `end_status` | `M`(range) `end` `rep` | `ids`, `lane`, `status`:inout |
| `ras_pick` | `M`(range) `win` `lo` `hi` `rep`/opt `clear`/opt | `first`, `alt`, `lane`, `hist`:inout → `ids` |
| `frame_store` | `M`(range) `n_codes` `stride` `rep`/opt `skip`/opt | `codes`, `lane`, `frame`, `status`, `dst`:inout |
| `resample_nearest` | `M`(range) `n` `dtype` | `x` → `y` |
| `fourier_embed` | `M`(range) `n` `round`/opt `dtype` | `t`, `w`w → `y` |
@@ -1291,6 +1426,7 @@ libref function says which (`libref/ref_audio.cpp`).
| `iota` | `M`(range) `start` `step` `period`/opt | → `y` |
| `cu_repeat` | `M`(range) `mult` | `len` → `y` |
| `int_affine` | `M`(range) `src` `mul` `add` | `x` → `y` |
| `sub_i32` | `M`(range) | `x`, `s` → `y` |
**Frames.** A lane is one piece; a frame is one step of its language model, whose branches (the
conditional first, then the unconditional) are consecutive rows, `rep` of them a lane.
@@ -1303,14 +1439,34 @@ conditional first, then the unconditional) are consecutive rows, `rep` of them a
`cond_k` > 0 only the entries where `c` reaches its `cond_k`-th largest value are. The `k`
largest `g` (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and drawn by
inverse CDF in descending `g`, `u = rad_philox_uniform_s(seed, 2^32 + frame, stream)`
(`abi/rad_philox.h`); the pick goes to every one of the lane's `rep` slots. `logits`
`[rep n, n_vocab]` f32 or bf16, `seed` `[n, 2]` u32 low word first, `frame` `[n]`.
(`abi/rad_philox.h`); the pick goes to every one of the lane's `rep` slots. With `top_p` < 1
(Fish Audio's draw) the kept list is cut first: over the softmax of every candidate's `g / temp`
(its normaliser summed in index order), a kept rank whose inclusive cumulative probability in
descending `g` exceeds `top_p` is dropped, rank 0 never, so the nucleus is taken over the whole
distribution and the `k` cut applies after it. `logits` `[rep n, n_vocab]` f32 or bf16, `seed`
`[n, 2]` u32 low word first, `frame` `[n]`.
- `ras_pick`: Fish Audio's repetition-aware sampling, a choice between two draws of each lane:
`ids[rep i] = alt[rep i]` when `first[rep i]` is in `[lo, hi)` and the lane's window holds it,
else `first[rep i]`. The window `hist` `[lanes, win]` i32 is the lane's last `win` picks, oldest
first, -1 empty (`clear` 1 empties it first, for a piece's first pick); the pick then enters it
and the oldest leaves. A pick outside `[lo, hi)` (an end of speech) is never redrawn.
- `end_status`: `status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]`.
- `rvq_embed`: `codes` is code-major `[n_codes, rows]`, read at the operand's own strides (a block
of a wider plane is a view);
`y = bf16(bf16(t0[c_0 + off0] + bf16(sum_k t1[c_k + (k - 1) vocab])) * scale)`, or with `round` 1
one f32 sum of every codebook's row in codebook order, times `scale`, rounded once to `y`'s dtype.
A first code outside `t0` leaves its row unwritten; a later code outside `t1` adds nothing.
With `clamp` n > 0 a code above `n - 1` reads row `n - 1` (before `off0` and the codebook's
offset; a negative code still reads nothing): a codec whose codebooks are smaller than the heads
that write its codes, as Fish Audio's 1024-entry residual codebooks under 4096-way heads.
- `vq_encode`: one step of a residual vector quantiser with factorised, L2-normalised codes (DAC's,
as Fish Audio's codec encodes a reference): per row of `x` `[rows, n]`, `e = in_w x + in_b`
(`in_w` `[dim, n]`, a 1x1 convolution's weight); the code is the row of `cb` `[bins, dim]` of
greatest cosine with `e`, `(e / max(|e|, 1e-12)) . (cb_c / max(|cb_c|, 1e-12))`, the lower index
on a tie (0 when no score is above -inf), written to `codes[i]` at the operand's own stride; then
`x -= out_w cb[code] + out_b` (`out_w` `[n, dim]`, the raw codebook row), rounded once into `x`.
f32 arithmetic. A chain of these over a codec's codebooks, each quantising what the last left, is
its residual quantiser.
- `frame_store`: `dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]` for every `k`,
when `frame >= skip` and `status[lane] >= 0`: a frame's codes into its lane's history, each
codebook a row over the lane's frames, so a run of a lane's frames is a block of `n_codes`
@@ -1325,6 +1481,8 @@ conditional first, then the unconditional) are consecutive rows, `rep` of them a
`y[j] = (src[j] < 0 ? 0 : x[src[j]]) mul[j] + add[j]` over three lists of integers of one length
(`src` -1 a constant): the shapes and bounds a model derives from a pass's device geometry, such
as a decoder's volume at each of its scales.
- `sub_i32`: `y[i] = x[i] - s[0]`, int32: a device length less a device offset (a pipelined
prefill's first piece takes its KV group's `seqused` less the second piece's rows).
**Windows.** The denoiser runs over windows of frames, each entry of a window step a lane's latent
in a state buffer `stride` rows a lane (`lat_cu` bounds each entry's rows, `win_lane` names its
@@ -1351,7 +1509,20 @@ input reads zero outside it.
- `conv1d`: PyTorch's `[cout, cin, k]` weight, `k` odd, dilation `dil` and padding
`dil (k - 1) / 2` a side, or with `causal` 1 (any `k`) `dil (k - 1)` on the left; `res` is added
after the bias, then `act` `none`, `tanh` or `clamp`, `min(max(y, -1), 1)` (BigVGAN's output
clamp; a NaN stays NaN). f32 accumulation, one rounding.
clamp; a NaN stays NaN). f32 accumulation, one rounding. A `stride` s > 1 comes in two forms.
A causal one (the reach `dil (k - 1) + 1` at least s) pads `dil (k - 1) + 1 - s` on the left
and keeps every s-th row: output row `o` of a sequence reads input rows `o s - pad + t dil`,
and sequence `e`'s rows `[cu[e], cu[e+1])` become `[cu[e] / s, cu[e+1] / s)`, so every bound is
a multiple of s; `res` and `y` have the output's rows (a causal codec encoder's downsampling,
as Fish Audio's). `cu_div` reads the bounds in units that many input rows apart, as the other
encoder ops do: sequence `e` is input rows `[cu[e] / cu_div, cu[e+1] / cu_div)`, each bound a
multiple of `cu_div` times the stride, so one bounds array in samples serves every rate of an
encoder. A non-causal one takes an explicit `pad` (bf16 rows only, the audio encoder's
downsample): `k` is any size, the op is one sequence `cu_seqlens` = `[0, rows of x]`, output
row `m` reads `x[m s + tap dil - pad]` with zeros outside, PyTorch's zero-padded strided conv
exactly (`k = 2 s`, `pad = ceil(s / 2)` gives `M / s` rows), and `y` has
`(rows + 2 pad - dil (k - 1) - 1) / s + 1` rows exactly. An explicit `pad` without a stride,
and an even `k` with neither a causal nor a stride, are refused.
- `conv_t1d`: PyTorch's `[cin, cout, k]` transposed weight, any `k` of at least a stride (two
strides by default), padding `pad` (`(k - stride) / 2` by default, which needs `k - stride` even;
0 is the causal form, whose full output's last `k - stride` rows are dropped; it may exceed a
@@ -1398,12 +1569,17 @@ bf16 tensor and keeps f32 where it computes in f32; the libref function says whi
| op | params | operands |
|---|---|---|
| `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `z` |
| `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? |
| `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `z`, `colmap`? |
| `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`?, `colmap`? |
| `rms_mod_quant_i8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`?, `colmap`? |
| `flow_x0_step` | `M`(range) `n` `dtype` | `v`, `t`, `sigma`, `sigma_next`, `x`:inout |
| `flow_res_multistep` | `M`(range) `n` `dtype` | `v`, `x0`:inout, `sigma`, `r`, `hb1`, `hb2`, `order`, `x`:inout |
| `patch_unfold` | `M`(range) `C` `pt` `ph` `pw` `mul` `add` `dtype` | `x`, `geom` → `y` |
| `vtile_gather` | `M`(range) `n` `tile` `overlap` `frames` `period` `n_reg` `dtype` | `x`, `reg`w, `geom` → `y` |
| `vtile_stitch` | `M`(range) `tile` `overlap` `scale` `pt` `skip` `keep` `blend` `period` `mean` `std` | `x`, `geom`, `prev`:inout → `y` |
| `vtile_plan` | `M`(range) `tile` `overlap` `ratio` | `geom` → `y` |
| `vtile_crop` | `M`(range) `tile` `overlap` `ratio` `dtype` | `x`, `geom` → `y` |
| `vtile_join` | `M`(range) `tile` `overlap` `n` `dtype` | `x`, `geom` → `y` |
| `grid_pos3` | `M`(range) `T` `H` `W` `period` `scale`:f64 | → `y` |
**The transformer.** `cu_seqlens` partitions the rows into entries as for `ln_mod`, and each row
@@ -1423,14 +1599,26 @@ reads its entry's rows of `s` and `g`.
`eps`. Without `w` the norm has no gain and rounds once, `n2 = bf16((x - mean) rsqrt(var +
eps))` (FLUX.3's LayerNorm without an affine). `norm` `none` takes no norm and no gain,
`n2 = x`, and refuses `w` (LTX-2's text keys and values, modulated as they are).
`colmap` (optional, trailing, i32 one a sequence) maps a sequence to its table row: every `[e]`
above becomes `[colmap[e]]`, so groups that share a modulation cell read one row. With it, `s`
and `g` may hold fewer rows than there are sequences; the map's bound is the issuer's.
- `rms_mod_quant_fp8` is `rms_mod` with the norm chain in bf16, then `quant_act_fp8` of that bf16
row per `group` as `ln_mod_quant_fp8` takes it; `z` written when bound.
- `rms_mod_quant_i8` is the same with `quant_act_i8g` in place of `quant_act_fp8`: symmetric int8
codes with a scale per `group` columns of a row, for the int8 GEMMs. `z` written when bound.
- `flow_x0_step` is MiniMax-H3's sampler step over a lane's rows, all f32, each product and sum
one rounding: the velocity points at the data, so the clean estimate is `d = x + (1 - t) v` and
the step blends toward it, `st = f32(1 - t)`, `d = f32(x + f32(st v))`,
`r = f32(sigma_next / sigma)`, `x = f32(f32(r x) + f32(f32(1 - r) d))`. `t` (the timestep the
transformer was conditioned on), `sigma` and `sigma_next` (the schedule's entries) are one f32
value each; `v` is f32 or bf16, `x` f32.
- `flow_res_multistep` is the same sampler's second-order form (k-diffusion's `res_multistep` at
eta 0, DPM-Solver++ 2M): with the clean estimate `d = f32(x + f32(sigma v))`, the step also
takes the previous step's estimate `x0`, `x = f32(f32(f32(r x) + f32(hb1 d)) + f32(hb2 x0))`,
then writes `d` to `x0` for the next step (`x` and `x0` f32). With `order` below 1.5 it is the
Euler step `x = f32(f32(r x) + f32(f32(1 - r) d))`, which a step with no previous estimate on its
grid takes (core/gen/video_driver.cpp's `stage_sched` has the coefficients, `hb1 + hb2 = 1 - r`).
`sigma`, `r`, `hb1`, `hb2` and `order` are one f32 value each; `v` f32 or bf16.
**The decoder** runs over a request's latent geometry, which `geom`, i32 on the device, carries
(the parameters are fixed at declare). `mul`, `add`, `mean` and `std` are space-separated lists
@@ -1490,6 +1678,38 @@ written.
`axial` then reads as f32 positions. MiniMax-H3: `T` 7, `H` 16, `W` 16, `period` 1797,
`scale` `2 pi`.
**The tiled encoder** encodes a one-frame media larger than a tile as vae.py's `tiled_encode` does
(`comfy/ldm/minimax/vae.py`): the pixel plane is cut into tiles, each goes through the encoder
alone (the per-level ops, issued per tile), and the tiles' moments are blended into one latent
plane. These three ops are the plan, the cut and the blend. Their axis split is the decoder's rule
above, except that an axis no longer than a tile is one tile `[0, L)`, short if need be.
MiniMax-H3: `tile` 16 latents, `overlap` 4, `ratio` 16. An `M` in a shape below is that operand's
row count, read from the operand; the ranged `M` argument is a ceiling only.
- `vtile_plan`: the plan for one frame of `geom` = `(clip, H, W)` pixels, split in latent units
over the spatial axes and numbered row-major over (row band, column band). Row `t` of the i32
`y [M, 22]`: the tile's first pixel `(y0, x0)` at [0] [1], its pixel extent `(th, tw)` at
[2] [3] (`tile ratio`, except a lone short tile), and level `L`'s volume
`(1, th / 2^min(L, 4), tw / 2^min(L, 4))` at `3 L + 4` for `L = 0..5` (levels 4 and 5 share a
size).
- `vtile_crop`: the frame's pixel plane `x [>= H W, 3]` (pixel `(Y, X)` at row `Y W + X`) cut into
the plan's tiles: `y [M, 3]` holds the tiles' pixels tile-major, each tile's rows in plane
order; `M` is the tiles' pixel count, more than the plane's since the tiles overlap.
- `vtile_join`: the tiles' `n`-channel moments (`vtile_crop`'s row layout at latent extent)
blended into the canvas `y [M, n]` of `geom` = `(clip, lat_h, lat_w)` in latent units, `M`
`lat_h lat_w`. As in the stitch, position `(Y, X)` belongs to the tile `(i, j)` whose range
`[start_i, start_{i+1})` holds it, at `(ly, lx)` within it, `T(i, j, ly, lx)` that tile's
value; unlike the stitch, the neighbours are read unblended. `rd`, `wa` and `wb` are the
stitch's, rounding to `x`'s dtype:
V = rd(rd(T(i-1, j, ly + tile - ev, lx) wa(ly, ev)) + rd(T(i, j, ly, lx) wb(ly, ev)))
when i > 0 and ly < ev = ov_y[i-1], else T(i, j, ly, lx)
y[(Y, X)] = rd(rd(T(i, j-1, ly, lx + tile - eh) wa(lx, eh)) + rd(V wb(lx, eh)))
when j > 0 and lx < eh = ov_x[j-1], else V
Only a lone tile is short, and it has no neighbour, so a neighbour is always `tile` long on the
blended axis.
### Video sparse attention
MiniMax-H3's step-distilled form (FastH3) was trained with FastVideo's video sparse attention: a
@@ -1587,7 +1807,7 @@ pass starts from. Each op rounds once into its output (`libref/ref_video.cpp`).
| op | params | operands |
|---|---|---|
| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` `tpad`/opt `tpre`/opt | `x`, `w`w, `b`w, `geom`, `res`? → `y` |
| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` `stride`/opt `stride_t`/opt `causal`/opt `pad`/opt `reflect`/opt `tpad`/opt `tpre`/opt | `x`, `w`w, `b`w, `geom`, `res`? → `y` |
| `group_norm` | `M`(range) `n` `groups` `eps`:f64 `act` `dtype` | `x`, `w`w, `b`w, `mod`?, `stats`:inout → `y` |
| `tconv_dw` | `M`(range) `n` `k` `dtype` | `x`, `w`w, `b`w, `geom` → `y` |
| `resize_bilinear` | `M`(range) `n` `dtype` | `x`, `geom` → `y` |
@@ -1599,10 +1819,10 @@ innermost (NDHWC). `geom` is the request's volume, i32 on the device (the parame
declare). An output holds at least the rows the volume writes; rows past them are not written.
Every op honours its activation operands' row pitches. `rd` is a rounding into the output's dtype.
- `conv3d_ndhwc`: `x [>= T H W, cin]`, `y` and `res` `[>= T H W, cout]`, `geom = (T, H, W)`; `w` is
PyTorch's Conv3d weight `[cout, cin, kt, k, k]` (a kernel may relayout it at load, as
`conv2d_nhwc`'s layout hook does) and `b [cout]`. Stride 1, zero padding `kt/2` frames and `k/2`
rows and columns on each side (`same`; `k` and `kt` odd):
- `conv3d_ndhwc`: `x [>= T H W, cin]`, `y` and `res` `[>= rows out, cout]`, `geom = (T, H, W)`;
`w` is PyTorch's Conv3d weight `[cout, cin, kt, k, k]` (a kernel may relayout it at load, as
`conv2d_nhwc`'s layout hook does) and `b [cout]`. The defaults are stride 1 with zero padding
`kt/2` frames and `k/2` rows and columns on each side (`pad` `same`; `k` and `kt` odd):
`y[(t,i,j), o] = rd(f32(sum over (dt, kh, kw, ci) of w[o, ci, dt, kh, kw]
x[(t+dt-kt/2, i+kh-k/2, j+kw-k/2), ci]) + b[o])`, terms outside the volume zero, f32 accumulation
in an order of the implementation's (libref: the taps in `(dt, kh, kw)` order, each tap's
@@ -1614,6 +1834,22 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t
memory as `y` (the residual added in place); `x` never aliases `y`. x, y, res and w bf16 (also
f32), b bf16 or f32. MiniMax-H3: `k` = `kt` = 3, `(cin, cout)` `(24, 512)`, `(512, 512)`,
`(512, 24)`.
The optional `stride` (rows and columns), `stride_t` (frames), `causal`, `pad` and `reflect`
give a causal video VAE's convolutions (MiniMax-H3's `CausalConv3d`), for `k = kt = 3` only. The
input is padded first, `ft` and `bk` frames in front and behind, `pt`, `pb`, `pl` and `pr` rows
and columns above, below, left and right, then strided: output `(t, i, j)` reads
`x[(t stride_t + dt - ft, i stride + kh - pt, j stride + kw - pl), ci]` (the same tap order),
and `y` holds `((T + ft + bk - kt) / stride_t + 1) ((H + pt + pb - k) / stride + 1)
((W + pl + pr - k) / stride + 1)` rows, PyTorch's output length (the divisions rounding
toward negative infinity). The defaults are `ft = bk = kt/2` and `pt = pb = pl = pr = k/2`.
`causal` 1 puts `ft = kt - 1` zero frames in front and none behind, so one frame in gives one
frame out at any temporal stride, as the reference's dropped taps do. `pad` `down` pads one row
below and one column right only (`pt = pl = 0`, `pb = pr = 1`), as `conv2d_nhwc`'s does.
`reflect` 1 mirrors the spatial padding instead of zeroing it, as PyTorch's `F.pad` mode
`reflect` does, without repeating the edge (`x[-n] = x[n]`, `x[D - 1 + n] = x[D - 1 - n]`), so
a padded axis must be longer than its pad (`H, W >= 2`); the frame padding is always zeros.
MiniMax-H3's encoder takes `reflect` 1 and `causal` 1 throughout, and `pad` `down` with
`stride` 2 in its downsamplers.
- `group_norm` is PyTorch's `nn.GroupNorm(groups, n)` on `[1, n, T, H, W]`: `x` and `y`
`[>= M, n]` (`M` is `y`'s rows), group `g` the channels `[g n/groups, (g+1) n/groups)` of all
`M` rows. `mean_g` and the biased `var_g` are over the group's `M n/groups` values, accumulated in
@@ -1653,6 +1889,25 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t
first, `stream` the parameter. `x` f32 `[M, n]` at its row pitch. MiniMax-H3: `n` 96 (the video's
patch rows) and 32 (the soundtrack's), `stream` 1.
### Condition-noise augmentation
MiniMax-H3 blends every visual condition's patchified latents with noise before they condition
the transformer (`_cond_video_rows`, `comfy/ldm/minimax/model.py`: weight `VISUAL_COND_TIMESTEP`
0.999, the generator restarted for every condition). The arch applies the blend once a media item,
over its encoded rows after the VAE encoder's fold. The weight is a declared constant, where
`flow_renoise` stages its `sigma`. Audio conditions take no blend.
| op | params | operands |
|---|---|---|
| `cond_aug` | `M`(range) `n` `stream` `aug`:f64 `dtype` | `seed`, `x`:inout |
- `cond_aug` blends condition rows with fresh noise, over `x`'s rows:
`x[k, c] = f32(f32(a x[k, c]) + f32(oma z(k n + c)))`, `a` = `aug` in `[0, 1)`, `oma` the f32 of
the f64 `1 - aug`, `z(e) = rad_philox_normal_s(seed, stream, e)` (`abi/rad_philox.h`), `seed`
u32 `[2]` low word first. `x` f32 `[M, n]` at its row pitch. The caller issues one media item's
rows at a time, so each item's draws start at `e = 0`. MiniMax-H3: `n` 96, `stream` 2, `aug`
0.999.
## LTX-2
The ops LTX-2's audio-video transformer adds (`libref/ref_ltx.cpp`): its rotary over fractional
@@ -2208,6 +2463,7 @@ device code.
| `ar_rmsnorm_post_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w |
| `ar_rmsnorm_had_quant_i8g` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
| `ar_rmsnorm_quant_i8` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt `sp`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
| `ar_rmsnorm_quant_i8g` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? |
| `ar_hc_write` | `M`(range) `n` `hc` `world_size` `dtype` `wire`/opt | `y`:inout, `inj`, `h`:inout |
| `ar_gather_hc_write` | `M`(range) `n` `hc` `top_k` `world_size` `dtype` `act`/opt `wire`/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`?, `y`:inout, `inj`, `h`:inout |
| `ar_ln_had_quant_i8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? |
@@ -2218,6 +2474,8 @@ parameter for the same reason as `min_bytes`. `x` is inout on `ar_rmsnorm_quant_
the message and the input, and the reduced sum lands in it.
`ar_rmsnorm_had_quant_i8g` is `ar_rmsnorm_quant_fp8` with `rmsnorm_had_quant_i8g`'s quantiser:
`x` and the residual are the same bytes, and the codes are int8 for a weight at `i8a8h`.
`ar_rmsnorm_quant_i8g` is `ar_rmsnorm_quant_i8` with `rmsnorm_quant_i8g`'s quantiser, at two
ranks, with no `sp`; `out_bf16` may be `x`'s buffer, which then ends holding the norm output.
`sp` on `ar_rmsnorm_quant_i8` (0 when absent) lets a row split the all-reduce around the
junction: reduce-scatter, the junction on the rows this rank owns (`M` split evenly over the
@@ -2536,6 +2794,47 @@ resolutions of one op. The one exception is `sample_chain` (below).
| `sample_argmax` | `M`(range) `n_vocab` | `logits`, `params` → `token` |
| `sample_merge_topk` | `M`(range) `n_cand` | `gathered`, `params` → `cand_idx`, `cand_val` |
| `sample_logprobs` | `M`(range) `n_vocab` `k` `vocab_off`/opt | `logits`, `params` → `stats` |
| `mtp_couple_propose` | `M`(range) `n_vocab` `round` `max_rounds` | `idx`:inout, `val`, `seq_ids`, `draw` → `state`:inout |
| `mtp_couple_verify` | `M`(range) `n_cand` `n_vocab` | `cand_idx`, `cand_val`, `params`, `state` → `token`:inout |
| `dflash_couple_propose` | `M`(range) `steps` `top_k` `rank` `n_vocab` `anchor_stride` `max_rounds` `q_temp`:f64/opt | `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w, `seq_ids`, `draw`, `tokens`:inout → `state`:inout |
`mtp_couple_propose`, `dflash_couple_propose` and `mtp_couple_verify` are the speculative coupling
(`--draft-coupling on`), and nothing else in the engine knows about coupling. Turning coupling on
requires a linear chain of drafts: a serial head's rounds, or a block drafter whose architecture
declares the coupled walk (DFlash2); no drafter, or a block drafter without the walk, is refused at
bringup, because neither has a per-round draw to couple. The `spechub` plugin ships every row and
their host oracle in one library and marks them per row, so the device rows count as production
kernels while the oracle stays reference; on a machine with no card only the oracle is left, and
the gate refuses the coupling there. A `RADIANCE_KERNELS` list is exclusive:
if it is set, it must name `spechub` or the coupled ops are not loaded at all.
`mtp_couple_propose` runs on a draft round's
final reranked top-8 and samples the proposal `x ~ Q`, where `Q` is the FP64 softmax of those
scores at temperature 1; it writes `x` into column 0 of `idx` and one state row per round. A row
whose `seq_ids` does not name the card its draw was staged for, or whose shortlist is malformed,
leaves column 0 alone with `status = -1`. `mtp_couple_verify` runs after `sample_pick`, over the same
final candidate plane, and applies the maximal coupling: the draft is accepted when it equals the
token the target itself drew at that position, and otherwise the token is a draw from the FP64
residual `(P - Q)+`. Both use 53-bit uniforms at `params.pos`; a row whose state is not bound to
that seed and position keeps the ordinary token. `P` is FP64-normalised where `sample_pick` is
FP32/24-bit, so a coupled row realizes the ideal filtered target law and is **not** seed-identical
to the ordinary pick.
`dflash_couple_propose` is DFlash2's block walk sampled (abi/rad_spechub.h,
`rad_dflash_couple_step`). It runs right after `dflash_select` over the same lattice, one workgroup a
sequence. At position `l` every candidate scores `dflash_select`'s
`unary + Σ_r pred[pid][r]·hp[l][r]·succ[cand][r]`, with `pid` the anchor at `l = 0` and the walk's
own previous token after it; `Q_l` is the FP64 softmax of `score / q_temp` over the best eight
in-vocabulary candidates, `x_l ~ Q_l` at the draw's `(seed, base, KEY_DRAFT + l + 1)`, and `x_l` is
both the proposal (into `tokens`) and position `l + 1`'s predecessor. Position `l` writes the state
row of round `l + 1`, so the engine binds and the sampler verifies it exactly as an MTP round. A
greedy request's row (draw mode 0) keeps `dflash_select`'s tokens (`status = 0`); a draw staged for
another card, or a position whose eight cannot form a `Q`, takes the walk's argmax (`status = -1`)
and the ordinary verify. `Q_l` depends on the committed text and on `x_0 .. x_{l-1}`, never on the
verify, and is stored exactly, which is all the coupling needs to be lossless; `q_temp` (the
architecture's, 0.6 on Qwen3.5/3.8) moves acceptance only. Each edge is eight
partial `fmaf` chains over contiguous slices of the rank, added in order, so the device kernel and
the host oracle agree bit for bit.
`sample_temp` divides a row's logits by its `temp` and leaves a row whose `temp` is 0 or less, or
exactly 1, as it is. The sampler relies on that: a step none of whose chain rows has another
@@ -2627,13 +2926,15 @@ order, not a slow one.
| `mla_project` | `M`(range) `heads` `head_dim` `latent_dim` `mode` `dtype` | `a`, `b`w → `y` |
| `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` |
| `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` `signed`/opt | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` |
| `kv_resolve` | `M`(range) `blocks` `slots` `sel_pitch` `block_bytes` | `sel`:inout, `nsel`, `res`:inout, `slot_block`:inout, `slot_state`:inout, `ctl`:inout, `host`, `kv_cache`:inout |
| `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` |
| `qsa_work` | `M`(range) `n` `ratio` `ring` `seqs` `work` `dtype` | `k`, `pos`, `cu`, `state`, `sidx`, `bt`, `rope`? → `stage`, `page`, `bpos`, `nc` |
Five ops decompose one indexer, which scores blocks of key history against the query and hands
`attn_paged` a shorter block table. `docs/QSA.md` describes the decomposition and
`arch/common/rad_qsa.h` issues all five. libref implements all five (the oracle for libr4d's
kernels), and libavx all five for the host path.
kernels), and libavx all five for the host path. `kv_resolve` sits between the last of them and the
attention when the group's KV streams; it is described below, after `qsa_select`.
### `qsa_block_key`
@@ -2762,6 +3063,65 @@ because a chunk's local top-k contains every global top-k member of that chunk,
output layout too: the attention sums the selected pages in table order and float addition is not
associative. Without scratch, or above 32 rows, one workgroup per query walks the whole list.
### `kv_resolve`
Turns `qsa_select`'s block ids into the ring slots that hold them, copying a block in from the host
mirror when it is not resident. `qsa_select` writes pool page ids and `attn_paged` reads each entry
as a raw pool index, so when a group streams (its pool is `slots` blocks deep over a `blocks`-wide id
space) this op, between them, is all the sparse path needs; the attention is unchanged. The design
is docs/KV-STREAMING.md §3.4.
The layouts, which the schema cannot state (the op is the same code at every cache layout):
- **`sel`** — `i32 [M, sel_pitch]`, inout: block ids in, ring slots out, below `nsel[q]`; the `-1`
padding past it is untouched.
- **`nsel`** — `i32 [M]`, in: the valid entries of each row. Above `sel_pitch` is refused.
- **`res`** — `i32 [blocks]`, inout: block -> slot, or `-1` absent (`-2` is a claim within a call).
- **`slot_block`** — `i32 [slots]`, inout: slot -> block, or `-1` free. Its extent is the ring the
call may address; the declared `slots` (the carved ring, `RadBuildCtx::kv_resident_blocks` in
blocks) is the ceiling it may not pass.
- **`slot_state`** — `i32 [slots, 2]`, inout: the epoch of the slot's last use, and a two-bit heat
counter in `[0, 3]`, bumped on a use (once a slot a call) and halved when the sweep passes.
- **`ctl`** — `i32 [16]`, inout: `[0]` epoch, `[1]` clock hand, `[2]` blocks placed by the last call,
`[3]` overflow (latched), u64 misses, lookups and calls from `[4]` (8-byte aligned), and the
largest union `[10]`, placement `[11]` and claim count `[12]` of one call: the measurements a ring
and a claim list are sized from.
- **`host`** — bytes `[blocks, block_bytes]`, in: the layer's mirror, block `b` at `b * block_bytes`.
- **`kv_cache`** — bytes `[slots, block_bytes]`, inout: the layer's ring, `RAD_KV(group, layer)`.
One call:
1. **Bump the epoch.** A hit stamps its slot with it and bumps its heat, so the sweep knows what
this call already uses.
2. **One lookup per distinct block.** A miss is claimed once (`-1` -> `-2`), so the map is its own
set.
3. **The miss list in ascending block id.** First-appearance order would let thread timing decide
placement. A device launch sorts the claims it made; nothing walks the id space `blocks`, so a
launch costs its selection. A claim list holds at most `M * sel_pitch` ids (at most
`sum_q nsel[q]`); the device kernel sizes it from those operands.
4. **One victim per miss.** The block's own slot if it is free (a context shorter than the ring
stays at identity, and adjacent ids read adjacent slots), else a free slot, else CLOCK from the
hand: a slot this call used is passed, a warm slot's counter is halved and passed, a cold one is
taken. The hand picks the victim per visit, so the policy needs no reduction, unlike an exact
LRU. A 3 survives two passes, so a sweep visits at most `3 * slots` slots.
5. **Re-point both maps**, a placement counting as a use.
6. **Copy** `block_bytes` per placed block, nothing converted. Hence `block_bytes` rather than
`block_size`: the op never reads an element, and a `block_size` key would make it the KV group's
consumer in place of the attention.
7. **Rewrite** every valid entry as its slot.
- **The ring must hold one call's selection union** (`hits + misses <= slots`): a decode step's is at
most `max_seqs * (1 + n_spec) * (topk + 1)` blocks, the floor `--kv-resident` is raised to, and
prefill takes the stage instead. An unplaced miss reverts to `-1`, its entries become slot 0 (a
defined address; a block id would be read past the ring) and `ctl[3]` latches; the caller must
discard the step.
- **The miss list is the row's scratch**: `next_pow2(slots) + slots` i32s on the device (a launch
too wide for the LDS claim list sorts there); the reference needs none.
- **Stateful, so not concurrent**: the row carries no `rad_kernel_concurrent` promise. It is
recordable, since its addresses and pitches never move.
- **The caller brings the state up**: `res` and `slot_block` filled with `-1`, `slot_state` and `ctl`
zeroed. There is no reset op.
### `qsa_tail_store`
Parks the raw index keys of the tokens that have not completed a block yet:
@@ -2889,7 +3249,7 @@ contributes nothing, and a row with no visible key outputs zero. The softmax is
rounded once. `scale` is positive and finite and comes from the original query/key head width,
not the latent width (GLM: `1/sqrt(256)` against a latent of 512).
libr4d has two `mla_attn` rows, both at `latent_dim` 512, `block_size` 4 and up to 64 heads. The
libr4d has three `mla_attn` rows, all at `latent_dim` 512, `block_size` 4 and up to 64 heads. The
matrix row, `mla_attn_matrix_bf16`, ranks above the wave row and takes heads in multiples of 8: the
heads are the WMMA tile's rows, so all of them share each latent load, and the probabilities enter
it as bf16 high and low parts with f32 accumulation. At a multiple of 16 a tile holds 16 heads of
@@ -2901,6 +3261,19 @@ by table position, with a second pass where the two differ. Other head counts ta
workgroups and merge the f32 partials before narrowing, into the fixed scratch their hooks
reserve; without scratch they compute unsplit.
At exactly 64 heads the rows row, `mla_attn_rows_bf16`, ranks above both. A workgroup takes one
query row and all its heads, four waves to each group of sixteen, and loads each 16-token key chunk
once for all of them, where the matrix row loads it once a tile of sixteen. The scores are
`K Q^T`, tokens as the tile's rows and heads as its columns, so a head's running maximum and
denominator stay in its lane; the four waves of a group each take a quarter of the latent's dot
products and add the four partials in one order, and the probabilities reach the value product
through a lane swap instead of LDS. The next chunk's keys are fetched while the current one is
multiplied. A row's output does not depend on the other rows of the batch, so a run of rows gives
the bytes the whole batch would. Under 32 rows (a decode step at one rank) too few workgroups fill the card, and its launcher
runs the matrix row's kernel instead. It also takes multiples of 32 heads (two groups a
workgroup), which no constraint routes to it. GLM-5.3 splits a prefill's MLA by rows under tensor
parallelism, so each rank holds all 64 heads of its rows (ARCHITECTURES.md, `glm5next`).
`mla_project` moves a query into the latent and a latent result out of it, through the bf16
weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows.
`mode=absorb` multiplies `a` `[M, heads, head_dim]` by the head's key block as stored,
@@ -2925,6 +3298,17 @@ candidates, and what enters the head from the trunk.
| op | params | operands |
|---|---|---|
| `dflash_select` | `M` `steps` `top_k` `rank` `n_vocab` `anchor_stride`/opt `dtype` | `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w → `tokens` |
| `dflash_tree` | `M` `steps` `top_k` `rank` `n_vocab` `anchor_stride`/opt `nodes` `temp`:f64/opt `dtype` | `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w → `tokens`, `parents` |
`dflash_tree` grows the same lattice into a tree of `nodes` nodes instead of walking one path
(`rad_drafter_tree`). Node 0 is the anchor at lattice position -1 with log probability 0. A node at
position l with token t has a child for every candidate c at l + 1 whose id is in the vocabulary,
scored as `dflash_select` scores c after t; with x = score / `temp` (default 1) over those
candidates, the child's log probability is its parent's plus x - logsumexp(x). Best-first: each
round takes the not-yet-taken child of a taken node with the largest log probability, ties to the
one pushed first (lower parent, then lower c), until `nodes` are taken. Taken node j (1-based, so
every parent comes before its child) is `tokens[s, j-1]`, and `parents[s, j-1]` its parent's node
index, 0 for the anchor. A frontier that runs dry pads with token 0 under the last node.
`dflash_conv` is the drafter's grouped convolution (coefficient add and every tap in one pass):
+58 -4
View File
@@ -23,9 +23,11 @@ quantisers, and §13 building, installing and the search path.
```c
#include "rad_abi.h" /* required */
#include "rad_abi_layout.h" /* required: the layout fingerprint */
#include "rad_plugin.h" /* optional helpers -- see §6 */
uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
RAD_PLUGIN_ABI_LAYOUT_EXPORT /* uint64_t rad_plugin_abi_layout(void) */
const RadPluginInfo* rad_plugin_info(void) {
static const RadPluginInfo i = {
@@ -42,7 +44,16 @@ const RadKernelInfo* rad_kernel_at(int i);
A plugin whose `rad_plugin_abi_version` differs from the engine's is refused at load, by name, with
both numbers printed. Return the macro, not the integer, and rebuild when it changes; it changes
with any shape change in a header a plugin compiles against (`rad_abi.h` lists them).
with any shape change in a header a plugin compiles against (`rad_abi.h` lists them), a field
appended to a struct included, and the release that ships the change assigns the number: a tree of
your own never bumps it for its own fields.
`rad_plugin_abi_layout` is a fingerprint of those headers' struct layouts as your plugin was
compiled (every struct's size and every field's offset and size, `rad_abi_layout_rows.h`). A plugin
whose fingerprint differs from the engine's under the same version -- built against another tree's
headers that gave a different layout the same number -- is refused with both fingerprints printed,
and so is one that does not export it. Every kind of plugin (kernel, architecture, quantiser)
exports both.
`build_target` is printed, not trusted: the targets the library was built for (`"gfx1100"`,
`"gfx11-generic"`, several separated by spaces or commas), `"host"` for CPU kernels, or `""` for a
@@ -57,6 +68,7 @@ Five more exports are optional, each looked up by exactly this name:
| `int rad_kernel_concurrent(int i)` | nonzero: kernel `i` touches nothing but its operands and scratch, so independent launches may overlap |
| `int rad_kernel_collective(int i)` | nonzero: kernel `i` exchanges data with the other ranks' cards, so the engine keeps its own bulk link traffic away while it runs. 2: each launch ends that hold itself once the other ranks' bytes have landed, through the `link_gate` parameter (`rad_abi.h`). Without this export only the `all_reduce` op is a collective |
| `int rad_plugin_reference(void)` | nonzero: a **reference implementation**, ranked below every unnamed library, refused for serving unless `--debug-accept-reference-kernels`, and what `rad-kbench` checks the others against. libref declares itself this way |
| `int rad_kernel_reference(int i)` | per row: nonzero marks kernel `i` as a reference implementation and 0 as a production one, overriding `rad_plugin_reference` for that library. For a plugin that ships a device row and its host oracle side by side (`plugin/spechub`) |
---
@@ -361,10 +373,45 @@ says so with `RAD_ARCH_SERVES_IMPORTS(0)` (`qwen35_w8a8` does), and imports keep
(`rad_op_resolved`) and is an error only if issued. The in-tree blocks do this for
`qk_norm_rope_gate`.
- **Read §8** if the model has a linear or recurrent block.
- **Declare the second lane's window.** Work issued on the second lane (`rad_lane`,
`abi/rad_runtime.h`) runs beside lane 0 in time, so every buffer it touches is named to
`rad_buf_concurrent`, which keeps it live for the whole program: the planner cannot tell when
lane 1 runs. An architecture whose lane-1 work lies in one stretch of its declared ops says so,
calling `rad_lane1_window_begin(b)` before the first op of the stretch and
`rad_lane1_window_end(b)` after the last, once each and in that order, at declare. A concurrent
buffer is then live across the window and over its own declared uses only, so buffers used only
outside the window (a drafter's, the heads') share its bytes again. What the plugin promises:
it issues nothing on lane 1 outside the window. What the runtime does (`Ctx::issue`): an op
issued on lane 1 outside the window fails the step, naming the window's op range and the op's
position; an op issued on lane 0 outside the window, before or past it, joins lane 1 first when
lane 1 has work pending, so the plugin need not join before the window ends; an op the core appends behind a
declared one (runtime LoRA) counts at that op's position. The builder refuses a second `begin`,
an `end` without a `begin`, twice or around no op, a `begin` never closed, and either call after
declare. `qwen35_fp8` (with the plugins built from it) and `gemma3` declare one from the
embedding's all-reduce to the final norm. On Qwen3.8-27B with its DFlash2 drafter at 64 sequences
and speculation 7, on two R9700s, the activation arena went from 633.99 to 526.32 MiB a card, as
without a second lane, and with the second lane's own scratch region
([IMPLEMENTATION.md](IMPLEMENTATION.md)) the KV pool from 86 208 to 93 856 tokens.
`tests/arch_test.cpp`'s builder applies the window to liveness as the core does, so the pinned
graphs and steps are the ones the core plans; the runtime (`Ctx::issue`) is what refuses a lane-1
op outside the window. Both calls are ABI 27 exports; a plugin that does not call them is
unaffected.
- **A block drafter may serve a shorter block.** `rad_drafter_short_block(b, block)`, called once
after `rad_declare_drafter`, says the plugin declared its query pass at `block` rows a sequence as
well as at `RadDrafterDecl::block`, with the same anchor convention, so the core may stage a step
at either; the short block proposes `block - (RadDrafterDecl::block - depth)` tokens. A tree
drafter (`rad_drafter_tree`, called first) grows a tree of its own over the shorter pass, at most
`block - 1` nodes, and its short block needs only 2 rows. The builder refuses it without a block
drafter, at or above the drafter's own block, and where it would propose nothing. The engine runs it under `--draft-short-from` (GUIDE §4.6) and reads row `s` of
the proposals at `s * proposal_pitch`; a block drafter's `proposal_pitch` defaults to its
depth (a row holds the whole block's proposals and a short block fills its front) and is refused
below it. The pass's block is `n_tok / n_seq`; a block the plugin has no ops for should fail the
step (`rad_block_dflash2.h` does). Appended in ABI 27.
- **Media preprocessing is the core's** (`core/mm`): resizing, patching, placeholder-token
expansion and positions, in five processor families (Qwen-VL, Gemma 4, LFM2-VL, Unlimited-OCR,
GLM-5.3) chosen by the container's `vision_config.model_type` (Unlimited-OCR's by its
`model_type`). A vision model with another pipeline needs a core change.
expansion and positions, in six processor families (Qwen-VL, Gemma 4, LFM2-VL, Unlimited-OCR,
GLM-5.3 and Pixtral for Nemotron 3.5) chosen by the container's `vision_config.model_type`
and owning-model checks (Unlimited-OCR's by its `model_type`). A vision model with another
pipeline needs a core change.
Audio goes through one of two feature extractors, Gemma 4's and Qwen3-ASR's (Whisper's), chosen
by `audio_config.model_type`.
- **A speech model says how it hears**, through the optional
@@ -400,6 +447,13 @@ blk.*.ffn_*_exps.*.weight myquant bits=3 group=64
quantiser does not declare is refused before anything is quantised. Two plugins naming the same
quantiser are refused, both named.
A quantiser that can use a card exports `int rad_quant_devices(const int* ids, int n)`
(`RadQuantDevicesFn`). `rad-convert --gpus 0,1` calls it once, before the first weight; without
the flag the plugin runs on the host. Which device a weight ran on is not recorded anywhere, so the
planes must be the host's byte for byte: libquant's trellis GPTQ keeps the host's operations and
their order on the card (`tests/quant_tcq_gpu_test.cpp` compares the two). Return
`RAD_E_UNSUPPORTED` from a build with no device path.
The core decodes the `plain` and `affine` schemes. Your own scheme is decoded by your `decode`
hook, which the oracle, `rad-kbench` and `rad-convert`'s error report use; return
`RAD_E_UNSUPPORTED` for a scheme you did not write. Serving a new encoding also needs a kernel
+203
View File
@@ -0,0 +1,203 @@
# Preparing your rig
From bare hardware to a serving Qwen3.8-Flash-Next on two Radeon AI PRO R9700s: firmware, Arch Linux,
Docker, peer-to-peer between the cards, power tuning, compose. Each step ends with a check.
The reference rig: MSI MPG X670E CARBON WIFI, Ryzen 9 7950X3D, 64 GB RAM, one 2 TB NVMe, two R9700s
in the two CPU-attached x16 slots. Another board needs the same settings under its own menu names.
## 1. Firmware setup
Enter the firmware setup (Del at power-on) and set:
| Setting | Value | Why |
|---|---|---|
| XMP / EXPO | profile 1 | the RAM runs at its rated speed instead of JEDEC defaults |
| Above 4G Decoding | enabled | needed for Resizable BAR |
| Re-Size BAR Support | enabled | the host writes each dispatch's arguments straight into VRAM, and peer access needs the large BAR |
| CSM | disabled | Resizable BAR needs pure UEFI boot |
| Secure Boot | disabled | the Arch install medium is not signed |
| PCIe lane split of the two x16 slots | x8/x8 | both cards on CPU lanes |
| PCIe link speed of both slots | Gen5 | stops the slots training at a lower generation |
| Onboard Wi-Fi, Bluetooth | disabled | the rig is wired, and an unused device is one less driver and IRQ |
Save and exit (F10).
## 2. Install Arch Linux
Boot the [Arch ISO](https://archlinux.org/download/) from USB with the network cable plugged in, then
run `archinstall` with these choices. Leave everything else at its default.
| archinstall item | Choice |
|---|---|
| Disk configuration | best-effort default layout, ext4 |
| Swap | off |
| Bootloader | systemd-boot |
| User account | your user, as superuser (sudo) |
| Profile | Minimal (no desktop environment) |
| Audio | none |
| Kernels | linux |
| Network configuration | NetworkManager |
| Additional packages | `openssh git base-devel` |
Install, reboot into the new system, log in on the console and start the SSH server:
```sh
sudo systemctl enable --now sshd
ip -4 addr show # note the rig's address
```
Go back to your PC. Everything from here on runs over SSH:
```sh
ssh-copy-id you@RIG_ADDRESS
ssh you@RIG_ADDRESS
```
## 3. Docker and the AUR helper
```sh
sudo pacman -Syu --needed docker docker-compose docker-buildx
sudo systemctl enable --now docker
sudo usermod -aG docker,render,video "$USER" # log out and back in
git clone https://aur.archlinux.org/yay.git && (cd yay && makepkg -si) && rm -rf yay
yay -S rocm-bandwidth-test
```
## 4. Kernel parameters
Edit the boot entry archinstall wrote (`/boot/loader/entries/*_linux.conf`) and append these to its
`options` line:
```
iommu=pt amdgpu.ppfeaturemask=0xfff7ffff amdgpu.ras_enable=0
```
- `iommu=pt` keeps the IOMMU in passthrough, so the cards can reach each other's memory and pinned
host memory maps without translation.
- `amdgpu.ppfeaturemask=0xfff7ffff` is the driver's default mask with the OverDrive bit set. OverDrive
is what makes the undervolt in step 6 writable.
- `amdgpu.ras_enable=0` turns VRAM ECC off. With ECC on, each card reserves about 2 GB of its VRAM.
Arch's stock kernel has enabled peer-to-peer (`CONFIG_HSA_AMD_P2P`) since 7.1.2, so a current install
needs no custom kernel. An older one would need a rebuild with that option. Make the entry the default
and reboot:
```sh
bootctl list # the linux entry, with the new options
sudo bootctl set-default "$(basename /boot/loader/entries/*_linux.conf)"
sudo reboot
```
## 5. Check the cards
```sh
cat /proc/cmdline # the three parameters
zcat /proc/config.gz | grep -E 'HSA_AMD_P2P|PCI_P2PDMA' # both =y
lspci -vv -d 1002:7551 | grep 'Region 0' # size=32G on both cards (ReBAR)
sudo journalctl -k -b | grep 'available PCIe bandwidth' # 32.0 GT/s PCIe x8 per card
cat /sys/class/drm/card*/device/mem_info_vram_total # 34208743424 (32624 MiB) on both: ECC off
rocm-bandwidth-test -a
```
In the bandwidth matrices, each card reaches about 28 GB/s to and from the CPU. Every GPU-to-GPU cell
must show a rate. A missing cell means no peer access: check `iommu=pt` and the BAR size.
An idle link reads 2.5 GT/s in `lspci`, and that is normal. If one card measures half the other's rate
under load, the PCIe power state of its root port is stuck one level down, and a reboot clears it.
## 6. Power limit and undervolt
210 W costs under 1% of decode speed against the 300 W default. Use -70 mV: at -75 mV the reference
rig's heaviest GEMMs gave run-to-run differences. Both settings are lost at every reboot, and the
undervolt also at every runtime resume of the card. A boot service applies them and keeps the cards
awake:
```sh
sudo tee /usr/local/sbin/gpu-tune.sh >/dev/null <<'EOF'
#!/bin/bash
# Undervolt and power-cap every R9700, then return the cards to automatic clocks.
# Needs amdgpu.ppfeaturemask=0xfff7ffff on the kernel command line (OverDrive).
set -u
OFFSET='vo -70'
CAP_UW=210000000
rc=0
for d in /sys/bus/pci/drivers/amdgpu/0000:*; do
[ "$(cat "$d/device")" = 0x7551 ] || continue
for _ in $(seq 1 30); do [ -e "$d/pp_od_clk_voltage" ] && break; sleep 1; done
[ -e "$d/pp_od_clk_voltage" ] || { echo "${d##*/}: no OverDrive interface" >&2; rc=1; continue; }
echo on > "$d/power/control" # a runtime resume drops the OverDrive table
echo manual > "$d/power_dpm_force_performance_level"
echo "$OFFSET" > "$d/pp_od_clk_voltage"
echo c > "$d/pp_od_clk_voltage"
echo auto > "$d/power_dpm_force_performance_level"
for h in "$d"/hwmon/hwmon*; do echo "$CAP_UW" > "$h/power1_cap"; done
echo "${d##*/}: $(grep -A1 OD_VDDGFX "$d/pp_od_clk_voltage" | tail -1)," \
"cap $(( $(cat "$d"/hwmon/hwmon*/power1_cap) / 1000000 )) W"
done
exit $rc
EOF
sudo chmod +x /usr/local/sbin/gpu-tune.sh
sudo tee /etc/systemd/system/gpu-tune.service >/dev/null <<'EOF'
[Unit]
Description=R9700 undervolt and power cap
After=multi-user.target
ConditionKernelCommandLine=amdgpu.ppfeaturemask=0xfff7ffff
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/gpu-tune.sh
RemainAfterExit=yes
TimeoutStartSec=90
[Install]
WantedBy=multi-user.target
EOF
sudo systemctl enable --now gpu-tune.service
journalctl -u gpu-tune -b --no-pager | tail -2 # -70mV, cap 210 W on both cards
```
## 7. Serve Qwen3.8-Flash-Next
```sh
git clone https://codeberg.org/StillDeadcode/radiance.git
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
mkdir -p ~/models/rad
curl -L -C - -o ~/models/rad/qwen3.8-next-flash-fp8-iq4r-moe.rad \
https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe/resolve/main/qwen3.8-next-flash-fp8-iq4r-moe.rad
# 114 GiB; -C - resumes after an interruption
cp .env.example .env && chmod 600 .env
```
Set these in `.env`:
| Variable | Value |
|---|---|
| `RADIANCE_MODELS` | `/home/you/models/rad` |
| `RADIANCE_API_KEY` | a long random string (`openssl rand -hex 32`) |
| `RADIANCE_UID`, `RADIANCE_GID` | `id -u`, `id -g` |
| `RENDER_GID`, `VIDEO_GID` | `getent group render \| cut -d: -f3`, the same for `video` |
```sh
docker compose -f flashnext.yaml up -d
docker compose -f flashnext.yaml logs -f # Ctrl-C once it serves; the container keeps running
```
The startup log must say `device: the 2 cards reach each other's memory directly (peer to peer)`. A
`no peer-to-peer access` warning means step 5's checks did not all pass. Then:
```sh
KEY=$(grep ^RADIANCE_API_KEY= .env | cut -d= -f2)
curl -s localhost:8000/health
curl -s localhost:8000/v1/chat/completions -H "Authorization: Bearer $KEY" \
-H 'Content-Type: application/json' \
-d '{"messages":[{"role":"user","content":"What is 65 * 3?"}]}'
```
The container restarts with the machine. `docker compose -f flashnext.yaml down` stops it.
[`DOCKER.md`](DOCKER.md) lists the other models' compose files, and [`GUIDE.md`](GUIDE.md) covers
serving flags and the API.
+5 -2
View File
@@ -191,8 +191,11 @@ drops blocks.
## Checking
There is deliberately no switch that forces dense attention above the bound, where it is not the
model the checkpoint was trained as. libref implements only `qsa_block_key` of the QSA ops, so
there is no whole-subsystem reference comparison. Changes are checked with:
model the checkpoint was trained as. libref implements all five QSA ops (`ref_qsa_block_key` in
`libref/ref_attn.cpp`; `ref_qsa_score`, `ref_qsa_select`, `ref_qsa_tail_store` and `ref_qsa_work`
in `libref/ref_qsa.cpp`), so each device kernel has a row to compare against. No oracle gives the
whole-subsystem comparison, a dense run against a sparse one above the bound. Changes are checked
with:
- **`r4d_selftest` oracles**: `qsa_block_key` and `qsa_score` against f64 evaluations,
`qsa_work` and `qsa_tail_store` against a host walk of the batch, `qsa_select` against a host
+104 -100
View File
@@ -2,15 +2,14 @@
Every flag of every tool, with examples. Start with [GUIDE.md](GUIDE.md).
Six binaries and the `rad-export` and `rad-pack-m2xfp4` scripts are installed beside `radiance`;
the shell harnesses live in `scripts/`:
Six binaries and the `rad-export` script are installed beside `radiance`; the shell harnesses
live 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-export`](#rad-export) | a finetune (merged checkpoint or LoRA adapter) to a `.rad`, with the base model's own recipe |
| [`rad-pack-m2xfp4`](#rad-pack-m2xfp4) | a ParoQuant M2XFP4 fine-tune to a `.rad`, its packed planes imported rather than re-quantised |
| [`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 |
@@ -19,7 +18,8 @@ the shell harnesses live in `scripts/`:
| [`scripts/`](#the-shell-harnesses) | bring a model up, measure it, assert on what comes back |
[`rad-avx-check`](#rad-avx-check), which checks a host kernel library against libref without a GPU,
is built beside libavx rather than installed.
is built beside libavx rather than installed, and [`r4d_selftest`](#r4d_selftest), libr4d's own
check and kernel timer, into the build's `bin/`.
`rad-convert`, `rad-kbench` and `rad-tune` run the engine's startup with a different last step:
the same plugins, in the same hierarchy, through the same declare phase, so they resolve kernels
@@ -129,6 +129,8 @@ rad-convert [options] <input> -o <model.rad>
--changed FILE with --reuse: checkpoint tensors (one name a line) that differ from
the --reuse container's source; every weight that reads one is converted
--in-place with --reuse: extend that container instead of writing a new one
--gpus LIST the cards (HIP device numbers, comma separated) quantisers may run on;
large weights then run two at a time. The bytes are the host's
--plan-only declare, plan every weight's encoding, print the plan, and stop
--report N the worst N quantisation errors to print (default 20)
-v, --verbose
@@ -168,13 +170,8 @@ output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf1
blk.*.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
```
A checkpoint whose `quantization_config` names a form rad-convert imports (a ParoQuant release at
`int5-bitplane`, AWQ int4, MXFP4 or M2XFP4, Quark's MXFP4, GPTQ/`auto-round`, compressed-tensors'
int4, NVFP4, ModelOpt) is written plane by plane instead: the codes, scales and metadata bytes as
they ship, the learned rotations as the encoding's `givens` tables, nothing dequantised or
re-quantised. Those weights need no rule -- a rule that matches one would ask a quantiser to read
codes as floats, and is refused -- so a recipe beside them covers only what the checkpoint does
not ship in a form the architecture declares.
A ParoQuant M2XFP4 checkpoint (`quant_method` `paroquant_m2xfp4`) is imported plane by plane: the
codes, exponents and metadata bytes as shipped, the rotations as the encoding's `givens` tables.
A pattern is a glob over the whole name: `*` crosses dots, `?` is one character. `$NAME` (or
`${NAME}`) in an option is taken from the environment; an unset variable is refused. `--quant`
@@ -193,12 +190,12 @@ also matches a norm leaves the norm as it is.
| `awq` | each input column scaled by its activation magnitude to a searched power, then a per-block clip search, both against the Hessian; the column scales are the encoding's last scale level |
| `autoround` | sign-gradient descent on a rounding offset per value and a range factor per block, against the Hessian; `iters` steps of N·K² multiply-adds each |
| `paroquant` | a channel scaling and `stages` rounds of Givens pair rotations, learned against the Hessian, then AutoRound on the rotated weight; the encoding's `givens` transform |
| `m2xfp4` | M2XFP's weight-side Sg-EM (arXiv 2601.19213): MXFP4 plus one metadata byte a group of 32, each subgroup of 8's extra mantissa k and the exponent's bias chosen by least squared error; its own scheme `m2xfp4` (spec.md), served by `gemm_nt_q` at dtype m2xfp4. `adaptive=0` pins the bias, `wide=1` widens it to {-2..2} |
| `ggml` | `type=` one of llama.cpp's formats (q4_0, q4_1, q5_0, q5_1, q8_0, q2_K..q6_K, iq4_nl, iq4_xs, iq2_xxs, iq2_xs, iq2_s, iq3_xxs, iq3_s, iq1_s, iq1_m), chosen by llama.cpp's own search, imatrix-weighted; the codes are byte for byte llama.cpp's, stored as each type's affine planes. iq2_xxs, iq2_xs and iq1_s need `--imatrix` |
| `m2xfp4` | M2XFP: MXFP4 whose group of 32 also carries one metadata byte of four 2-bit subgroup extra mantissas, each a subgroup of 8 columns refining the shared exponent to (1 + k/4) . 2^E; the subgroups' k and the exponent's bias in {-1, 0, 1} (`adaptive=1`, the default; `adaptive=0` pins the bias at 0) are the least squared error choices, the OCP exponent rule, rounding, zero groups and short final groups otherwise the MXFP4 grid's; 4.5 bits an element, weights only, decoded by the quantiser itself (arXiv 2601.19213) |
| `cast` | a float weight in another float dtype (`dtype=` f32, bf16, f16, fp8_e4m3, fp8_e5m2), no scale |
| `import` | rad-convert's own, not a plugin: the numbers a quantised release ships, in the spelling the kernels read, instead of quantising again. `codes=uN` makes a symmetric grid's signed codes unsigned under a zero point of 2^(N-1); `zero=` is the zero plane's dtype (u4, u8); `scale=` the scale's (f16, bf16, f32), each shipped scale rounded to nearest; `block=RxC` repeats an FP8 scale shipped per row or per tensor over that block grid. It reads an imported integer grid (GPTQ, CT-INT4) or an FP8 weight with a scale per row or per tensor, refuses any other quantised form by name, and keeps a plain float weight as it is. The run reports per rule how many weights it re-expressed and how many scales the new dtype rounded |
Every quantiser except `ggml`, `m2xfp4`, `cast` and `import` takes the grid options:
Every quantiser except `m2xfp4`, `ggml`, `cast` and `import` takes the grid options:
| option | |
|---|---|
@@ -214,8 +211,7 @@ Every quantiser except `ggml`, `m2xfp4`, `cast` and `import` takes the grid opti
| `clamp` | a signed code's range, `full` or `sym` |
Examples: MXFP4 is `codes=fp4_e2m1 group=32 scale=e8m0`; NVFP4 is `codes=fp4_e2m1 group=16
scale=fp8_e4m3 scale2=f32`; its metadata-augmented cousin is the `m2xfp4` quantiser itself; NF4 is
`table=nf4 group=64`; a K-quant-like grid is `codes=i4
scale=fp8_e4m3 scale2=f32`; NF4 is `table=nf4 group=64`; a K-quant-like grid is `codes=i4
group=32 scale=u6 scale2=f16 group2=256`; a ternary BitNet weight is `table=ternary`.
A container can hold only what some kernel reads. The converter checks every planned encoding
@@ -399,84 +395,6 @@ is `UNSLOTH_HOOK_OUTPUT=<path of the .rad>`, which a trainer UI can list with th
---
## rad-pack-m2xfp4
```
rad-pack-m2xfp4 SRC [-o OUT.rad] [--recipe FILE] [--draft DIR] [--rad-convert PATH]
[--home DIR] [--jobs N] [--convert-with 'CMD {model} {result_dir} {out}']
[--model BASE] [--hf-out DIR] [--convert-path FROM=TO ...]
[--verify-only] [--list] [--skip-tables]
SRC a converted ParoQuant M2XFP4 checkpoint, or a `paroquant.cli.optimize`
result directory (quant_grid.json + per-module .pt)
-o, --out FILE the container (default: SRC's folder name + .rad, beside SRC)
--convert-with C run `paroquant.cli.convert --mode real` through C first, with {model}
{result_dir} {out} substituted; a result directory needs it and --model
--model BASE the donor checkpoint convert loads (the fine-tune's weights are in the
result directory, not in BASE)
--hf-out DIR where --convert-with writes (default: SRC/hf), as this machine sees it
--convert-path FROM=TO a prefix the convert runtime spells differently (docker exec of a
container whose /models is this machine's ~/models), applied to {model},
{result_dir} and {out}. Repeatable
--recipe FILE rad-convert's recipe for the weights the checkpoint does not ship quantised
(data/recipes/q38-27b-paro-m2xfp4-df2.recipe)
--draft DIR a drafter merged as dflash.*
--verify-only skip rad-convert and check the container at -o against the checkpoint
--list print the container's m2xfp4 entries and stop
--skip-tables check the three code planes only, not the rotation tables
```
A ParoQuant M2XFP4 fine-tune is a set of `paroquant.cli.optimize` per-module files: trained
weights, the learned rotation and the grid's exponent bias, not packed planes. Two steps turn it
into a container, and this script owns the seam:
1. `paroquant.cli.convert --mode real` re-derives each module's codes under the M2XFP4 grid the
optimizer trained with and writes an ordinary Hugging Face checkpoint: `X.weight` (e2m1
nibbles `[N, K/2]`), `X.weight_scale` (e8m0 `[N, K/32]`), `X.weight_meta` (u8 `[N, K/32]`, four
2-bit subgroup multipliers a byte) and the rotation (`X.theta`, `X.pairs`, `X.channel_scales`),
with `quantization_config.quant_method = "paroquant_m2xfp4"`. It needs a GPU; the script runs it
when it is handed a result directory and `--convert-with`.
2. `rad-convert` imports those planes -- `Import::ParoM2` in core/format/checkpoint.cpp: the codes,
exponents and metadata bytes become the weight's three planes byte for byte, the rotation
becomes the encoding's `givens` tables, and the GEMM is the plain M2XFP4 one over an activation
`givens_dense_quant` rotates first. It is CPU-only, so it runs beside a serving GPU.
Then it reads the container back and proves the seam: every `m2xfp4` entry's three planes are
byte-identical to its checkpoint tensors, and the rotation tables are the checkpoint's
(`t.scale` = 1/channel_scales in f32, `t.pairs` offset to whole-row columns, `t.angle` widened,
`t.dense` the stages composed over groups of 128 in f64 and rounded once).
A mismatch exits non-zero; it is not a warning. Loading the container also deserves
`rad-kbench -m`: its cases run over the container's own bytes in the layout the kernel asked for.
```bash
# the full model, once the fine-tune lands (convert needs a GPU; the rest does not). The
# container's mounts are spelled differently from this machine's; -u keeps the checkpoint's files
# this user's, and every path the script hands it is translated by --convert-path.
rad-pack-m2xfp4 /media/zee/ai/paro-out-ft-m2xfp4/Qwen3.8-27B-fp16 \
--model /media/zee/ai/paro-stage/Qwen3.8-27B-fp16 \
--convert-with 'docker exec -u 1000:1000 paro_stage2 python3 -m paroquant.cli.convert \
--model {model} --result-dir {result_dir} --output-path {out} --mode real' \
--convert-path /media/zee/ai/paro-out-ft-m2xfp4=/out \
--convert-path /media/zee/ai/paro-stage=/staging \
--convert-path /home/zee/models=/models \
--hf-out /home/zee/models/paro-ft-m2xfp4-hf --draft /home/zee/models/hf/Qwen3.8-27B-DFlash2 \
--recipe data/recipes/q38-27b-paro-m2xfp4-df2.recipe \
-o /home/zee/models/rad/q38-27b-paro-m2xfp4.rad
# and the pack alone, from the checkpoint the convert left, plus its check
rad-pack-m2xfp4 /home/zee/models/paro-ft-m2xfp4-hf \
-o /home/zee/models/rad/q38-27b-paro-m2xfp4.rad \
--recipe data/recipes/q38-27b-paro-m2xfp4-df2.recipe --draft /home/zee/models/hf/Qwen3.8-27B-DFlash2
rad-pack-m2xfp4 --list -o /home/zee/models/rad/q38-27b-paro-m2xfp4.rad
```
The recipe (`data/recipes/q38-27b-paro-m2xfp4-df2.recipe`) covers what the checkpoint does not ship
in a form the architecture declares -- f32 norm casts, the bf16 embedding, the head, the drafter's
own linears -- and names no trunk linear, which are imported. The alternative shortcut, `convert
--mode pseudo` (dequantised fp16 weights) then a `m2xfp4` recipe rule, re-quantises every weight in
the unrotated basis: it needs no import, but it is a second lossy step and its planes are not the
fine-tune's.
## rad-kbench
Checks every kernel every loaded library supplies against the reference library's answers,
@@ -556,13 +474,10 @@ on an eighth of the rows.
`--rerecord FILE` writes the replayed fixtures' cases again with the reference's current answers
in the current format, each case keeping the laws it was recorded with. `--record-rows FILE`
moves the fixtures' cases into the constraints of every row of the libraries under test and
records the reference at every distinct geometry that lands there -- one case serves every row
sharing it, so a band's whole M ladder is covered -- described afresh: a fixture that reaches
rows no container selects, to replay with `--all-rows`. The gemm_nt_q mx/m2 pair re-encodes
between the two families (codes and exponents are the same planes; the meta plane is drawn
beside them), so an m2xfp4 recording can drive the OCP rows and vice versa. A row whose
geometry would change a weight's shape needs a container, and is listed.
moves the fixtures' cases into the constraints of every row of the libraries under test (another
band, tuned point or dtype) and records the reference there, described afresh: a fixture that
reaches rows no container selects, to replay with `--all-rows`. A row whose geometry would change
a weight's shape needs a container, and is listed.
### Verdicts
@@ -746,6 +661,13 @@ Declare at the shapes you serve:
At `--tp > 1` every rank declares at once, each on its own thread and device, as the engine does:
a collective's `init` is a rendezvous, so declaring rank 0 alone at world size 2 hangs.
A collective is measured as the exchange. Each rank gets its own operands (drawn with its own seed,
so a fold of two identical halves cannot pass), its own scratch and stream, and the instance its
own declare made, since `init` publishes the peer bundle a launch needs. Every rank fires the
candidate's launches at once and the clock stops when the last stream drains, so the time is the
round trip through the peer, as a served step pays it. Candidates are judged against the defaults
on rank 0's output. A row that is not collective runs on rank 0 alone.
Before trusting a cache, check that the tuned variants beat the defaults. `RADIANCE_TUNE` pins a
kernel's axes for such a comparison; it is a measurement aid, not a deployment setting.
@@ -819,6 +741,28 @@ serves fails in either case: the selector would resolve to it and the step would
---
## r4d_selftest
```
r4d_selftest <libr4d.so> [--case <row>]
r4d_selftest <libr4d.so> --perf N K M [iters] (and the other --perf* modes in its usage text)
```
With no mode it runs libr4d's catalogue and static checks, then each row's smoke and numeric cases
in a child process of its own, the fusion claims compared byte for byte (ctest runs it as
`r4d_selftest`, labels `slow`, `gpu`); `--case` runs one row in this process, as the reproducer.
The `--perf*` modes time rows at one shape on a card. Two that cover the dense GEMMs:
| | |
|---|---|
| `--perf N K M [iters]` | the fp8 decode GEMMs, and the fp8 head (`logits_gemm_fp8`) |
| `--perfmxd N K M [iters]` | the dense OCP-MXFP4 rows (`gemm_mxfp4a8_gemv`, `_decode`, `_nt_m64`, `_tiled`) at one shape, with the weight bandwidth each reaches; at a gate_up shape (N a multiple of 256, K of 128, M up to 64) also the ops after the GEMM, `gated_quant_fp8` (SwiGLU) and `gelu_mul` + `quant_act_fp8` (GeGLU), and the fold that replaces them at both activations, `gemm_mxfp4a8_gated_gemv` (M ≤ 8) or `_gated_gemv_wide` (9..64) |
`--perfmx` is the MXFP4 expert GEMM (`M`, experts, `top_k`, skew), not the dense rows. `--cold MIB`
times each launch alone behind a cache flush instead of back to back.
---
## rad-tokcheck
```
@@ -889,6 +833,17 @@ reference with the exact wire and a bf16 KV cache.
A loaded control vector is applied at the deployment's default: `--control-vector on` scores every
document with the projection, `--control-vector off` without it.
**The sparse reference.** A full row is the vocabulary in f16, so ten million positions of a
248K-token vocabulary would be 5 TB. `--kld-record DIR --kld-top N` keeps, per position, the `N`
most likely tokens exactly (f32 log p) and the mass of every other token, summed from the full row
(one minus the head would cancel to noise on a confident position): 8 bytes a token, 4 KiB a
position at `N` = 512. `--kld-ref` reads the form from the manifest and scores the KL between the
two distributions coarsened to the reference's `N` tokens and one bucket for the rest. By the
data-processing inequality that is at most the full KL; it loses only how each model spreads the
tail inside the bucket, which is small where the reference's tail mass is small and nothing on a
confident position. The report's `ref_form` says which form a number was scored against, and
numbers from the two forms do not compare.
`--kld-out FILE` writes the report as JSON, and every position's KL, both NLLs and the argmax
agreement to `FILE.rows` (`[positions, 4]` f32, reference row order), so two candidates can be
compared position by position.
@@ -900,6 +855,46 @@ with `PREFIX` through it and the rest as the base, in the same steps. The steps
all-adapter and all-base runs with the same flags, so each document's rows should be byte for byte
theirs: that is how a mixed batch is checked.
## The calibration mode
```
radiance --model BF16.rad ... --calib-corpus CORPUS.jsonl --calib-dir DIR [--calib-layers LO:HI]
```
Records GPTQ's Hessian, `H = sum over tokens of x x^T`, of the whole input of every linear in a
dense bf16 trunk (`qwen35_bf16`), over a corpus. Like the KL mode it replaces the server: every
document goes through prefill once, with the prefix cache and speculation off so that each corpus
token is counted exactly once. A document is submitted only while the whole lengths of those in
flight, its own included, fit the KV pool at once, so none is preempted (a re-prefill would count
its tokens twice), and a run that preempts all the same fails. The corpus is the KL mode's JSONL;
only `prompt` is read.
`--calib-dir` beside `--kld-record` (no `--calib-corpus`) records both in one run: the reference
over `--kld-corpus`, and the Hessians over the same tokens, fed the same way.
Under tensor parallelism a linear split by its input columns (`o_proj`, the delta net's
`out_proj`, `down_proj`) sees only its rank's columns, and a Gram of those is one diagonal block
of H. The tap gathers such an input to its whole width before taking the Gram, so the files hold
the whole matrix at any `--tp`. One rank records each layer (layer modulo the rank count): its card
sums a step's rows into an f32 scratch (`gram_accum`, upper triangle only), and the host adds the
step's sum into an accumulator of the packed upper triangle. The host holds every recorded input of
its rank, 786 MB a layer at Qwen3.8-27B (50 GB for 64 layers), so a large model is recorded in
several runs over the same corpus, each with its own `--calib-layers`; the run whose range ends at
the last layer also records the lm_head's input.
The files, written once the corpus is through: `DIR/<checkpoint prefix>.<layer>.<site>.safetensors`
per input, each holding `hessian_upper`, f32 `[k (k + 1) / 2]` (row `i`'s entries `k2 = i .. k-1`
after row `i-1`'s), with metadata `k`, `rows` and `linears`, the checkpoint linears that read the
input (q, k and v share one; so do gate and up). H is the raw sum: divide by `rows` for the mean
second moment.
```python
import numpy as np, safetensors.numpy as st
t = st.load_file("model.language_model.layers.3.mlp.down_proj.input.safetensors")["hessian_upper"]
k = int((np.sqrt(8 * t.size + 1) - 1) / 2)
H = np.zeros((k, k), np.float32); H[np.triu_indices(k)] = t; H = H + np.triu(H, 1).T
```
---
## The shell harnesses
@@ -1032,3 +1027,12 @@ scripts/mctools.sh && scripts/mcstream.sh
`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
checks `docs/OPS.md` against the schemas the plugins declare.
`rad-chatparse` (built into the build's `bin/`) answers where a tool call goes wrong without loading
weights. `rad-chatparse --request REQ.json --rad MODEL.rad --reply R.txt` renders one OpenAI chat
request as the server would (the container's template or `--override-chat-template`,
`--chat-template-kwargs`, the plugin's declared reply format, or the template's own with
`--no-plugin`), then reads each reply file as the model's output: parsed whole, parsed through the
SSE stream as a client reassembles it, and run through the request's tool-call grammar. It prints one
JSON object; the exit status is 1 when the two parses disagree or the grammar refuses a token.
`--render-raw T.jinja --context CTX.json` renders a template with any context.
+13
View File
@@ -9,6 +9,14 @@ All numbers: paired within-session windows, bar ≥0.5% + sign test, geometry
`--prefill-span 2 --tp-wire wht6 --placement all_vram` iq4r MoE unless stated.
Every "dead" row is a *measured* dead — the mechanism, not a guess.
Shorthand: `pp` prefill; `c1/c2/c8/c16` concurrency (live streams) 1/2/8/16; `M` rows in a
collective (batch tokens at a step, rows in a MoE launch); `I` `--checkpoint-interval`; `T` tokens
(`T<=25` at most 25 tokens); `ti8` the int8 peer wire (`--tp-wire wht6`'s coding); `FK` the MoE fast
band; `W4` the 4-bit weight format; `iq4r` the shipped MoE quantisation; `hc_write` the fused
all-reduce + residual-write row; `pp64K` a 64 K-token prefill; `QSA` the sparse indexer
(docs/QSA.md); `L0..L3` kill levels, defined under *Kill levels*; `W#`/`R#` the experiment rows of
this table.
## The table
| # | Element | What we tried | Result (measured) | Status / PR |
@@ -73,6 +81,11 @@ promotion truth; quick concurrency ladders within windows.
4. ti8 **one-shot band** for 128 KiB–512 KiB lossy messages (currently every
such message pays two-shot 1.5N + 2 syncs) — flagged upstream on #78.
5. Draft-pass graph capture — only if low-concurrency latency ever matters.
6. **The dense pipelined prefill at TP4** (`qwen35_fp8`, `qwen35_w8a8`, `gemma3`; GUIDE §4.5): a
prefill step of one sequence in two pieces, every block boundary's all-reduce on the second lane
at `overlap` 1, which at four ranks would take this table's `*_4rank_*_lane` rows (row 1). It
runs at two ranks only; enabling it here (`g.world == 2` in both plugins' declare) needs a
timing against the serial step at 18K-64K prompts and the chunk served.
## Interaction diagram
+50
View File
@@ -0,0 +1,50 @@
# DeepSeek-V4.1-Flash: a .rad from the release (no GGUF converter)
The official DeepSeek-V4.1-Flash release converts with `rad-convert` alone: no llama.cpp GGUF is
built as an intermediate, and no separate drafter directory is grafted. The pieces below prepare
and convert the release. Serving the container needs the `deepseek41` architecture plugin, which
this tree does not include yet.
- `data/engram_tables.py` builds the Engram hash tables from the release's own `tokenizer.json` and
`config.json`. It reimplements the tokenizer's ByteLevel decode, the normaliser sequence (NFKC,
NFD, strip marks, lowercase, collapse spaces, sentinel), the PCG64 multipliers and the prime
buckets. Against HF `tokenizers`: 0 mismatched token ids of 129280, compressed vocab 99092, the
release's two Engram layers [1, 14]. It writes `engram-tables.safetensors`.
- `data/imatrix_merge.py` fuses the imatrix entries llama.cpp's converter writes split
(`ffn_gate_exps`, `ffn_up_exps`) into the plugin's fused `ffn_gate_up_*`, summing the two halves
(and those of `shexp`): 1184 entries carried through, 160 fused for 40 layers. IQ1_S refuses a
fused weight without one.
- `data/recipes/deepseek41-ud-iq1s.recipe` is the UD-IQ1_S per-tensor mix as rules for libquant's
`ggml` quantiser, so the release converts to the same encodings the GGUF has.
- `rad-convert --chat-template FILE` bakes a template into the container's vocab section. The
release carries no `chat_template.jinja` and its `tokenizer_config.json` names none, so a
container converted without this flag answers `/v1/chat/completions` with 501. Trailing newlines
are stripped as for a sibling template, and an unreadable or empty file is refused.
## Conversion
```
# 1. the Engram tables, from the release's tokenizer (not a GGUF)
python3 data/engram_tables.py <HF release dir> engram-tables.safetensors
# 2. fuse the imatrix's split gate/up entries
python3 data/imatrix_merge.py imatrix_unsloth.gguf_file imatrix-merged.gguf
# 3. convert, with a chat template for the model baked into the container
rad-convert <HF release dir> --add engram-tables.safetensors \
--recipe data/recipes/deepseek41-ud-iq1s.recipe \
--imatrix imatrix-merged.gguf --tokenizer <HF release dir>/tokenizer.json \
--chat-template chat_template.jinja -o deepseek-v4.1-flash-ud-iq1s.rad
```
From DeepSeek-V4.1-Flash-1017 (fp8 with e8m0 scales per 32x32 block, MXFP4 experts) the plan is
32701 weights, 251.07 GiB, and the container 251.13 GiB. The `deepseek41` plugin serves it on 4x
R9700 at `--tp 4` with its DSpark metadata (block 5, 128 experts, targets 37/38/39) and the Engram
tables baked in. Quality, greedy, thinking off: HumanEval 154/164 = 0.939 (the native UD-IQ1_S
reference 0.963, McNemar p = 0.125), GSM 194/200 = 0.970 (reference 0.960).
## Serving
A container converted with `--chat-template` needs no template at serve time. One converted
without it needs `--override-chat-template FILE`; the file must be a template radiance renders
(the release's own is; llama.cpp-only Jinja, such as `dict()` in a GGUF's template, is not).