radiance 2.0.0

Radiance becomes a multi-model engine: one process serves several models behind one port, loads
each when a request names it, parks it in host memory or restores it from its container, and
shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the
command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP).

Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an
int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block
FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such
weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5,
Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B,
the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0
serves all of them.

Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new
Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill
reworked, and a reworked adaptive draft window.

Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its
configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool
in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server,
each accelerator's memory by model, model states over time.

Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by
AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests
keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410);
eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d
large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi
(#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon
(#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and
multi-model serving as asked for in #367 and #109.

Plugin ABI 39: out-of-tree plugins need to be rebuilt.

Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
Deadcode committed 2026-11-14 22:32:28 +01:00
1 parent b4c04b6042
commit ddcb9c69bb
696 files changed
+120770 -56596

No files matched your search

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