# radiance user guide radiance is an inference server: it loads a model and answers OpenAI-compatible HTTP requests. This guide covers building it, getting a model in, serving it and operating the server. The engine, the tools and the build are C++, CMake and shell; nothing needs Python. | To | Read | |---|---| | get something running | this file, in order | | see every flag of one tool | [TOOLS.md](TOOLS.md) | | write a kernel library for your card | [PLUGIN.md](PLUGIN.md) | | know why it is built this way | `../spec.md`, the binding design | --- ## 0. Quick start ```sh ./build.sh # build and test export RADIANCE_HOME=$PWD/build/radiance_home scripts/hfget.sh Qwen/Qwen3.8-27B /srv/models/ckpt # get a checkpoint build/bin/rad-convert /srv/models/ckpt -o /srv/models/m.rad \ --recipe data/recipes/q38-27b-iq8r-rtn.recipe \ --set quantization_config.quant_method=w8a8 \ --set quantization_config.fmt=fwht128 # quantise it into a container cat > radiance.yaml <<'EOF' server: port: 8000 models: m: model: /srv/models/m.rad EOF build/bin/radiance --config radiance.yaml # serve it ``` The server reads its settings from that YAML file and nothing else; §4.0 describes it. The entry's name, `m`, is the model id requests name. A checkpoint served at its own precision needs no container: `model: /srv/models/ckpt` reads it as it stands (§3.4). ```sh curl -s localhost:8000/v1/chat/completions -H 'Content-Type: application/json' \ -d '{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":50}' \ | jq -r '.choices[0].message.content' ``` The dashboard is at `http://localhost:8000/`. --- ## 1. Install To avoid building on the host, use the container image: `docker/build.sh` builds and tests the engine in the ROCm toolchain image and produces an image that needs only Docker and the `amdgpu` driver. [`DOCKER.md`](DOCKER.md) covers it, with two compose files that each serve a fleet of models, one for one card and one for two. ### 1.1 Requirements | | | |---|---| | Required | Linux, a C++20 compiler, CMake 3.21+, Ninja, pthreads | | Optional | ROCm with `hipcc`, for AMD device kernels; without it you get the host backend. Set `ROCM_PATH` if ROCm is not at `/opt/rocm` | | With a card | Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The host writes every dispatch's arguments into VRAM there. On a card whose BAR is smaller than its VRAM they stay in pinned host memory and every dispatch reads them over the link: on R9700s, Qwen3.8-27B fp8 decode steps take 0.4-1.8% longer at `tp: 1` and 2 than with the arguments in VRAM. Peer access needs the large BAR too, so at `tp: 2` and above such a card takes the collectives through host memory (§4.7) | | With a card | `amdgpu.cwsr_enable=1` (the default). With compute wave save/restore off the driver cannot preempt a queue it must evict, and the card hangs and resets. Startup refuses to serve on cards with it off and says what to change; `server.proceed-with-incompatible-configuration` starts anyway, **unsupported**, with a banner at the top of the log and of the startup report and `unsupported_configuration: true` in `/diagnostics` | | Optional | OpenMP, used by the host kernel libraries if present | | Optional | `libavformat-dev libavcodec-dev libavutil-dev libswscale-dev libswresample-dev` (ffmpeg 6+), for image, video and audio input. CMake option `RAD_WITH_FFMPEG`: `AUTO` (default) uses them when found, `ON` fails the configure without them, `OFF` builds without. A build without them starts and serves text, and refuses every image, video and audio part with HTTP 500; the only warning is the configure log line `radiance: no libavformat ...`. The diagnostics report says which (`media decoders`; `host.media` in `GET /diagnostics`) | | Optional | `clang++` (or ROCm's), for `tests/r4d_emu` when the C++ compiler is g++; CMake 3.25+ for `CMakePresets.json` | | Shell harnesses | `curl` and `jq` | The HTTP server, the JSON library and the llama.cpp parts are vendored in `vendor/`. A machine with no GPU is supported. The host backend is complete: the core, scheduler, planner, tokeniser and server run on it, `libavx` (AVX-512 and AVX2 kernels, chosen at run time) serves every shipped model, and the full test suite passes. Small models run at interactive speed on a desktop CPU; the 27B and larger models run far more slowly than on a card. A ROCm build, or the container image, uses it on a machine where no card is visible: the GPU library's kernels are left out and every op takes its host kernel. ### 1.2 Build ```sh git clone radiance && cd radiance ./build.sh ``` `build.sh` configures, builds and runs the fast tests (§1.3). If `hipcc` is present and a card can be enumerated, device kernels are compiled for that card's architecture; otherwise you get the host backend. ```sh ./build.sh -c # wipe the build directory first ./build.sh --no-hip # force the host backend even where hipcc exists ./build.sh --debug # -DCMAKE_BUILD_TYPE=Debug ./build.sh --asan # AddressSanitizer + UBSan, host backend, in build-asan/ ./build.sh --tsan # ThreadSanitizer, host backend, in build-tsan/ ./build.sh -b mybuild # build into mybuild/ instead of build/ ``` Or with CMake directly (`CMakePresets.json` names the same three configurations: `cmake --preset default`, `asan` or `tsan`): ```sh cmake -S . -B build -G Ninja cmake --build build -j ctest --test-dir build -L fast -j8 --output-on-failure ``` A ROCm SDK installed outside `/opt/rocm` (a userspace SDK tree under a virtualenv, or a core-only system install) needs more than `ROCM_PATH`. hipcc is found, but device compilation fails inside `cuda_wrappers/cmath` with `Could not find standard C++ header 'cmath'`, because ROCm's clang does not pick up the distro gcc's libstdc++ headers on its own. Configure with: ```sh ROCM=/path/to/_rocm_sdk_devel # the SDK root (the venv's site-packages/_rocm_sdk_devel) cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \ -DRAD_HIPCC=$ROCM/bin/hipcc \ -DCMAKE_HIP_COMPILER=$ROCM/llvm/bin/clang++ \ -DCMAKE_HIP_COMPILER_ROCM_ROOT=$ROCM \ -DCMAKE_HIP_FLAGS="--rocm-path=$ROCM --rocm-device-lib-path=$ROCM/lib/llvm/amdgcn/bitcode --gcc-install-dir=/usr/lib/gcc/x86_64-linux-gnu/15" export LD_LIBRARY_PATH=$ROCM/lib:$LD_LIBRARY_PATH ``` `--gcc-install-dir` is the distro gcc's directory (gcc 15 in the example). After a gcc upgrade, repoint it and reset the configure cached in `build/CMakeCache.txt` (`-c`). The device-lib path is where the SDK keeps `amdgcn/bitcode`: under `lib/llvm/` in a userspace SDK, `$ROCM/amdgcn/bitcode` in a core system install. A full `/opt/rocm` install needs none of these flags, and the container in `DOCKER.md` avoids them. ### 1.3 Check that it works The tests are grouped into tiers by label, and `CMakePresets.json` names the usual runs. A preset reads `build/`; add `--test-dir mybuild` for another tree (CMake 3.30+), or pass the labels shown. Times are wall clock on a 16-core (32-thread) host build with other work running: | Run | Selects | Time | |---|---|---| | `ctest --preset fast` (`-L fast -j8`) | the inner loop; what `build.sh` runs | about 10 s | | `ctest --preset host` (`-LE 'gpu\|oot' -j8`) | everything that runs without a card | about 1.5 minutes, most of it `r4d_emu_attn_sweep` and, after libref changes, `kbench_ref` | | `ctest --preset gpu` (`-L gpu`) | the tests that need a card, one at a time | minutes | | `ctest --preset perf` (`-L perf`) | the wall-clock checks, each alone | seconds | | `ctest --preset full` | every test | the above plus `oot` | | `ctest --preset asan` | the fast tier in `build-asan/` (`./build.sh --asan` first) | about 4 minutes | | Label | Tests | |---|---| | `unit` | one binary per `tests/*_test.cpp` except `engine_e2e_test`, always on the host backend (`ROCR_VISIBLE_DEVICES=99`) | | `fast` | every test with none of `slow`, `gpu`, `oot`, `perf`, `e2e` and `kbench` | | `perf` | `_perf`: a binary's cases named `perf_...`, which assert wall-clock costs; each runs alone | | `e2e` | `engine_e2e_test`: the `radiance` binary serving tiny synthetic checkpoints on the host backend | | `kbench` | `kbench`, `kbench_moe` and `kbench_ref`, the kernel replays (below) | | `slow` | `kbench_ref`, `r4d_selftest` and `r4d_emu_attn_sweep` | | `gpu` | `device_test_card`, `mem_test_card`, `place_test_card`, `runtime_test_card`, `device_test_nosvm`, `device_test_hostkargs`, `runtime_test_hostkargs`, `r4d_selftest`, and `kbench`/`kbench_moe` when libr4d is built; one at a time, and a server must not hold the card | | `oot` | `oot_plugins`: every bundled plugin rebuilt out of tree against an install | | `r4d_emu` | libr4d kernel sources run on the host by a SIMT emulator; registered where a clang++ is found | Each binary built on `tests/rad_test.h` takes the same arguments: ```sh build/tests/gbnf_test --list # its cases build/tests/gbnf_test oracle -tool # the cases containing "oracle" but not "tool" build/tests/gbnf_test --shard 1/4 # every fourth case, from the second RAD_TEST_FILTER=oracle build/tests/gbnf_test # patterns from the environment RAD_TEST_LEVEL=2 build/tests/gbnf_test # the exhaustive sizes, where a test has them ``` `device_test` and `runtime_test` also take `--host-kargs`: the AQL backend keeps kernel arguments in pinned host memory on every card, as it does on a card without a large BAR (§1.1). A case taking 0.1 s or more prints its time, and a binary ends with its wall and CPU time and its three slowest cases. A binary that checked nothing exits 77, which ctest reports as skipped, not passed. ctest sets, for each unit test: - `OMP_WAIT_POLICY=passive` and `OMP_NUM_THREADS=4`: the host kernel libraries' OpenMP teams spin at every barrier by default, which makes a 0.2 s test take a minute on a busy machine. - `RAD_TEST_STRICT=1`: a plugin or fixture this build makes that a test cannot find fails it; run by hand, the test skips. - `RAD_TEST_TMPDIR=build/tmp`: where `radtest::tmpdir()` is made. It is removed when the binary passes and kept, with its path printed, when it fails. - `RAD_TEST_CPU_BUDGET=10`: a binary that spends more CPU seconds than this fails, so a slow case or a spinning thread pool is caught when it lands. `tests/CMakeLists.txt` lists the few binaries allowed more. Sanitised and Debug builds have no budget. The sanitised tiers are host-only. `./build.sh --asan` builds `build-asan/` with AddressSanitizer and UBSan and runs the fast tier there; `--tsan` does the same with ThreadSanitizer in `build-tsan/`, where OpenMP runs one thread because libgomp is not instrumented. The `r4d_emu` tests are compiled without a sanitiser in both. The tests that check kernels: - `kbench` / `kbench_moe` (label `kbench`) replay a recorded fixture: every kernel every loaded library other than `libref` supplies, checked against `libref`'s recorded answers on seeded inputs. They need no model file. `--strict` fails a stale case (one whose operands or schema moved, or that the reference no longer serves or now describes differently), and `--coverage` fails when a kernel row the fixture reached (`data/kbench_rows/`) is no longer reached. - `kbench_ref` (labels `kbench`, `slow`) replays `libref` against its own recordings at tolerance zero, so any change to the reference shows before it becomes the next recording's target. Its answers are cached under `$RADIANCE_HOME/cache/kbench` by `libref`'s build, so an unchanged `libref` replays in seconds. - `r4d_selftest` (labels `slow`, `gpu`) checks libr4d's fusions by `memcmp` against the unfused kernels they replace. - `avx_check` (fast) compares libavx with libref op by op at every ISA level the CPU supports. - `r4d_emu_*` (fast, `r4d_emu_attn_sweep` slow) run libr4d's kernels on the host: those with no libref oracle (the windowed attention, the sandwich-norm joins, expert_scale, pair_argmax), and the QSA block selection's four kernels against libref's rule. - `ops_doc` (fast) checks that `docs/OPS.md` agrees with what the plugins declare. The kernel check by hand: ```sh build/bin/rad-kbench --home build/radiance_home --max-cases 1 ``` ### 1.4 Install to a prefix ```sh cmake -S . -B build -G Ninja -DCMAKE_INSTALL_PREFIX=/usr/local cmake --build build -j sudo cmake --install build ``` ``` /bin/ radiance, rad-convert, rad-info, rad-kbench, rad-tune, rad-schemas, rad-tokcheck /libexec/radiance/ hfget.sh, the downloader behind model: (§3.1) /include/radiance/ the ABI headers, all a plugin compiles against /lib/cmake/radiance/ the package config, for find_package(radiance) /share/radiance/ $RADIANCE_HOME: kernels/, architectures/, quantizers/, kernels*.rkb ``` ### 1.5 `$RADIANCE_HOME` The directory the engine and every tool scan at startup: ``` $RADIANCE_HOME/ kernels/ kernel libraries libr4d.so, libref.so, libavx.so, yours.so architectures/ architecture plugins qwen4exp_fp8.so, llama_fp8.so, ... quantizers/ quantiser plugins libquant.so kernels.rkb the recorded kernel fixtures rad-kbench replays (and kernels_moe.rkb) tune/ per-machine tuning caches rad-tune writes ``` It defaults to the install prefix's `share/radiance`. `server.radiance-home: DIRS` or `RADIANCE_HOME` override it with a search path: homes separated by `:`, the first winning, each holding any of the directories above, so a directory of your own plugins can go ahead of an installation's. `rad-info --plugins` prints what the path offers: ```sh RADIANCE_HOME=$HOME/radiance-plugins:/opt/radiance/share/radiance rad-info --plugins ``` In a build tree the home is `build/radiance_home`: ```sh export RADIANCE_HOME=$PWD/build/radiance_home build/bin/radiance --config radiance.yaml # the file of §0 ``` Supporting a new card takes an `.so` in `kernels/`, not a fork of the engine. The engine's own device code is built for every AMD GPU family, so one binary starts on any card; a kernel library with no code object for the card leaves itself out of selection at load and says so. `docs/PLUGIN.md` §10 walks through a library for a card the engine has never seen. ### 1.6 Building for a card you do not have Device kernels are compiled for the architectures the machine reports. To target others: ```sh cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201;gfx1200' ``` Each kernel library declares the architectures it serves and stays out of a build targeting anything else. The engine's own device code is built for every family's generic target regardless. --- ## 2. Concepts **1. A model is a checkpoint served as it stands, or a `.rad` container.** A checkpoint whose weights are bf16, f16, f32, block-scaled fp8 or Quark's MXFP4 is served at that precision from its directory. Anything that needs quantising is quantised once, by `rad-convert` and a recipe, into a container. A container holds each weight as the planes of its encoding (codes, scales, zero points, a rotation) in one canonical arrangement, plus the tokeniser, the chat template, the metadata, the recipe and optionally a draft head. Neither names a kernel library: kernels rearrange the planes into their own layouts at load, so a kernel library can change without a reconvert. **2. Kernels are plugins, and their order matters.** Every op is resolved against an ordered list of kernel libraries; the first that matches wins. `server.kernels: mylib,libref` names the libraries to load, in order; a library it leaves out is not loaded. Without a list every library found loads, with one that declares itself a reference implementation last. | library | | |---|---| | `libr4d` | the device library for AMD RDNA4 (`gfx12xx`): paged and dense attention, gated delta net, all-reduce over P2P or a host-memory mailbox, skinny and tiled quantised GEMM, rotate-and-quantise fusions. Built when ROCm is present and the build targets a `gfx12` card | | `libref` | every op, naively and generically: the last-resort fallback and the correctness oracle `rad-kbench` measures against | | `libavx` | the host library: the same vocabulary in x86 SIMD, dispatched by CPU feature at load. Serves every op placed on the host, including the n-gram embedding's gather. Built on x86-64 | A library that does not cover the configured card stays out of the build, so the tree still builds and runs. **3. Architectures are plugins too.** `arch//` declares a model family's graph: | plugin | serves | |---|---| | `llama_fp8`, `llama_dense_fp8` | LLaMA-shaped decoders: MiniCPM5, Llama 3, anything reporting `model_type: llama` | | `qwen35_bf16` | Qwen3.5 / 3.6 / 3.8 dense (0.8B–27B), bf16 | | `qwen35_fp8` | the same, block-scaled fp8 | | `qwen35_w8a8` | the same, an int8 trunk rotated by a 128-wide Hadamard | | `qwen35moe_fp8` | Qwen3.5 / 3.6 MoE (35B-A3B), 256 experts, 8 a token | | `qwen35moe_w8a8` | the same, an int8 trunk and rotated int8 experts | | `hyv3_bf16` | Tencent Hy-Memory-30B-A3B BF16 checkpoint; BF16, W4, W8A8, block-FP8 and MXFP4 recipes, TP1/2 | | `hyv3_fp8` | Tencent Hy-Memory-30B-A3B FP8 checkpoint: imported FP8 weights, dense-first MoE, TP1/2, BF16 or static-scaled E4M3 KV | | `hyv3_gguf` | llama.cpp Hy-Memory Q4_K_M input converted via `hy-memory-30b-a3b-gguf-q4k-to-w4.recipe`; requires `--tokenizer /tokenizer.json` | | `qwen4exp_fp8` | Qwen4-Exp / Qwen3.8-Flash-Next: hybrid Gated DeltaNet + gated attention, 512 experts | | `gemma4` | Gemma 4 text decoders (26B-A4B MoE and the dense members): bf16 trunk, routed experts bf16 or block fp8, and the DFlash drafter | | `gemma4_bf16` | Gemma 4 dense in bf16, with its vision tower | | `museglimmer` | Meta Muse Glimmer 30B: gated attention alternating sliding-window (rotary) and NoPE full layers, Gemma-2 double norms, a 50-block windowed ViT; bf16 | | `museglimmer_ct` | the same trunk as an int4 container (`--set quantization_config.quant_method=compressed-tensors`) | | `lfm2_bf16` | LiquidAI LFM2 and LFM2-VL in bf16, including d1 (§5.13) | | `lfm3_bf16` | LiquidAI LFM3 in bf16 (LFM3-1.7B) | | `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) | | `nomicbert` | nomic-embed-text-v2-moe, an embedding model (§5.6) | | `nemotron35_embed` | Nemotron 3.5 Embed 1B/8B and Rerank 8B, BF16 text/image retrieval at TP1 (§5.6) | | `qwenimage21` | Qwen-Image 2.1 and 2.1-Turbo, an image model (§5.6) | | `krea2` | Krea 2 Raw and Turbo, an image model from text (§5.6) | | `anima` | Anima Base, Aesthetic and Turbo, an anime and illustration image model from text (§5.6) | | `flux3`, `flux3distilled` | FLUX.3 [klein] and its base, an image model that also edits (§5.6); one plugin under the two names the releases give themselves | | `qwen3asr_bf16` | Qwen3-ASR, speech to text from the checkpoint as it ships (§5.14) | | `minimaxmusic3` | MiniMax-Music3, songs from a description and lyrics (§5.15) | | `breeze` | Breeze-TTS-2, speech from text and an optional description of the voice (§5.15) | | `fishomni` | Fish Audio drama-3, speech from text with speaker tags and inline direction (§5.15) | | `minimaxh3` | MiniMax-H3 and FastH3, video with its stereo soundtrack from text (§5.16) | | `ltx2` | LTX-2.5, video with its stereo soundtrack from text or a first frame (§5.16) | | `hunyuan3d2` | Hunyuan3D-2's shape model, an untextured 3-D mesh from one picture (§5.17) | **4. Falling back to the reference library is fatal.** If any op resolves to `libref`, the engine refuses to start and names the ops, because serving from it is orders of magnitude slower with nothing in the output to say so. That list is the work a new kernel library has to do. `server.debug-accept-reference-kernels: true` overrides it for bring-up. **5. Every pool is budgeted explicitly.** There is no profiling pass and no utilisation fraction. The trade between KV blocks and resident weights depends on the workload and is the operator's to make; a split the engine re-optimised on its own would make benchmarks irreproducible. --- ## 3. Get a model in ### 3.1 Download a checkpoint ```sh scripts/hfget.sh Qwen/Qwen3.8-Flash-Next /srv/models/Qwen/Qwen3.8-Flash-Next ``` It needs only `curl` and `jq`. Re-running resumes: a file whose local size matches is skipped and a short one is continued. When a repo carries `.safetensors`, other weight formats (`.bin`, ONNX, GGUF, ...) are not fetched. `HF_TOKEN` authenticates a gated or private repo; `HFGET_JOBS` sets concurrency (default 4). A complete fetch records each file's content key (its LFS sha256, or a small file's size) in `.hfget-manifest`, so the next run also fetches a file that changed at the same size. An LFS file's recorded key is verified, not just claimed: the download is hashed and compared against the sha256 the listing names before the file is kept. A listing that names a file outside the destination (an absolute path, a `..` segment) is refused whole rather than half-obeyed. Fetch what you will serve from a revision you chose: without `model-revision` a repo id tracks the repo's `main` branch, so a restart can bring weights nobody reviewed; name a tag or a commit sha. The free-space check counts only what is still to fetch. `model` also takes a repo id: ```yaml server: port: 8000 models: minicpm5-2b-iq8r: model: StillDeadcode/minicpm5-2b-iq8r ``` The server runs the same script (installed in `libexec/radiance/`) into `//` before bring-up, then serves the one `.rad` at the repo's top level, or the directory as a checkpoint (§3.4) when it holds none. A repo with several containers is refused, naming them; pass the file. Every start checks the hub and fetches what changed. A start that cannot read the listing, or whose update does not fit on disk, serves the copy a complete earlier fetch left and says so; a transfer that fails part-way stops startup. A path that exists is always a path, and a name ending in `.rad`, `.safetensors`, `.gguf` or `.json` is never looked up. ### 3.2 Convert it ```sh rad-convert /srv/models/Qwen/Qwen3.8-27B -o /srv/models/rad/q38-27b-iq8r.rad --home $RADIANCE_HOME \ --recipe data/recipes/q38-27b-iq8r-rtn.recipe \ --set quantization_config.quant_method=w8a8 --set quantization_config.fmt=fwht128 ``` Input is a `.gguf`, a `.safetensors`, an index or a checkpoint directory. The architecture plugin declares the graph and maps checkpoint tensors to weights, every op is resolved and each kernel is asked whether it reads its weight's encoding, then each weight is written once as its encoding's planes, with the tokeniser and chat template. **A recipe decides what is quantised**, in rules from weight names to quantisers. Without one, every weight keeps the checkpoint's encoding, which suits a bf16 checkpoint served at its own precision. A release stored as block fp8, MXFP4, NVFP4 or ParoQuant needs rules that re-quantise those weights: kept as stored, they make a container the engine refuses at startup, naming the first such weight. `q38-27b-iq8r-rtn.recipe` above writes every trunk linear as IQ8R (rotated int8) by round to nearest and needs only the checkpoint; the `--set` keys make the container's descriptor `w8a8_fwht128`, which selects `qwen35_w8a8`. Flash-Next's four-bit experts: ```sh CALIB=DIR rad-convert /srv/models/Qwen/Qwen3.8-Flash-Next -o /srv/models/rad/w4nl64-i8lm.rad \ --recipe data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe --home $RADIANCE_HOME ``` ``` # data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe (excerpt): PATTERN QUANTISER OPTIONS; the first match decides blk.*.ffn_*_exps.*.weight gptq table=w4nl group=64 scale=fp8_e4m3 scale2=f32 block2=*x* scale2_value=0.0001220703125 transform=fwht128 rule=search cd=3 calib=$CALIB blk.*.attn_qg.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search ``` The production Flash-Next container of `scripts/convfn.sh`, `w4nl64-i8lm.rad`, is built by this recipe, whose expert rule is GPTQ against recorded Grams. It expands `$CALIB` from the environment, so it runs as `CALIB=DIR rad-convert ...` with `DIR` holding a calibration run's files; the recipe's header and [MOE-W4.md](MOE-W4.md) say what that directory holds and how it is recorded. Every quantised weight is measured against the source and the worst are printed. The recipe syntax, the quantisers and their options are in [TOOLS.md](TOOLS.md#recipes). `rad-convert` runs the engine's declare phase, so anything that would be refused (including a recipe no loaded kernel can serve) is refused before the I/O, which takes an hour on a large checkpoint. To check the plan only: ```sh rad-convert -o out.rad --recipe r.recipe --plan-only -v ``` Other conversions: ```sh # Merge a separate drafter checkpoint (DSpark, DFlash2) into the container rad-convert $SRC -o out.rad --draft-model /srv/models/openbmb/MiniCPM5-2B-DSpark # Re-quantise some weights and copy the rest from an earlier container rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad # A bf16 Qwen3.8-27B finetune with the DFlash2 drafter in IQ8R: the recipe writes the linears, and # --set states the format, which selects qwen35_w8a8 rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-27b -o swift-27b-iq8r.rad \ --draft-model /srv/models/z-lab/Qwen3.8-27B-DFlash2 --recipe data/recipes/q38-27b-iq8r-rtn.recipe \ --set quantization_config.quant_method=w8a8 --set quantization_config.fmt=fwht128 # gemma-4-26B-A4B-it with z-lab's DFlash drafter, the routed experts' gate_up as rotated int8 (served # by arch/gemma4; docs/ARCHITECTURES.md says why down stays bf16) rad-convert /srv/models/google/gemma-4-26B-A4B-it -o gemma4-26b-a4b-dflash-i8.rad \ --draft-model /srv/models/z-lab/gemma-4-26B-A4B-it-DFlash --recipe data/recipes/gemma4-26b-a4b-df-i8.recipe # Qwen-Image 2.1 or 2.1-Turbo, an image model (§5.6): the diffusers pipeline directory is the # checkpoint (text encoder, DiT, VAE and tokenizer). IQ8R for the text encoder and the DiT (rotated # int8), or the checkpoint's bf16 (31 GB, two cards) rad-convert /srv/models/Qwen/Qwen-Image-2.1 -o qwen-image-2.1-iq8r.rad \ --recipe data/recipes/qwen-image-2.1-iq8r.recipe rad-convert /srv/models/Qwen/Qwen-Image-2.1-Turbo -o qwen-image-2.1-turbo-iq8r.rad \ --recipe data/recipes/qwen-image-2.1-iq8r.recipe # Krea 2 Raw or Turbo, and FLUX.3 [klein] or its base, image models (§5.6): the diffusers pipeline # directory; IQ8R for the text encoder and the DiT, or bf16. Krea 2 takes a recipe either way # (krea-2-iq8r.recipe or krea-2-bf16.recipe), since the release stores its embedders and # modulations f32 rad-convert /srv/models/krea/Krea-2-Turbo -o krea-2-turbo-iq8r.rad \ --recipe data/recipes/krea-2-iq8r.recipe rad-convert /srv/models/black-forest-labs/flux-3-image-klein -o flux-3-klein-iq8r.rad \ --recipe data/recipes/flux-3-klein-iq8r.recipe rad-convert /srv/models/black-forest-labs/flux-3-image-klein -o flux-3-klein-bf16.rad \ --recipe data/recipes/flux-3-klein-bf16.recipe # A Krea 2 finetune shipped as one DiT file in Krea's key names (civitai, ComfyUI): rewritten as the # transformer/ of a directory holding the release's other parts (Turbo's model_index.json for a Turbo # finetune, Raw's for a Raw one), then converted as the release is P=/srv/models/lustify-krea2; mkdir -p $P/transformer cp -r /srv/models/krea/Krea-2-Turbo/{model_index.json,scheduler,text_encoder,tokenizer,vae} $P/ cp /srv/models/krea/Krea-2-Turbo/transformer/config.json $P/transformer/ scripts/krea2_native.py lustifyNSFWCheckpoint_v10Krea2_fp8.safetensors \ $P/transformer/diffusion_pytorch_model.safetensors rad-convert $P -o lustify-krea2-turbo-iq8r.rad --recipe data/recipes/krea-2-iq8r.recipe # Anima, an image model (§5.6): the release's three single files merged (--add), Qwen3-0.6B-Base's # config.json and tokenizer.json (--config: the repository or a directory with just those two), and # ComfyUI's T5 tokenizer (comfy/text_encoders/t5_tokenizer/tokenizer.json, with its # tokenizer_config.json beside it) as the second vocabulary. The variant (base, aesthetic, turbo) # sets the defaults; anima-bf16.recipe keeps every linear bf16 A=/srv/models/circlestone-labs/Anima/split_files rad-convert $A/diffusion_models/anima-aesthetic-v1.1.safetensors \ --add $A/text_encoders/qwen_3_06b_base.safetensors --add $A/vae/qwen_image_vae.safetensors \ --config /srv/models/Qwen/Qwen3-0.6B-Base --tokenizer2 /srv/ComfyUI/comfy/text_encoders/t5_tokenizer/tokenizer.json \ --arch anima --set anima.variant=aesthetic -o anima-aesthetic-bf16.rad \ --recipe data/recipes/anima-bf16.recipe # Stable Diffusion XL or any of its finetunes (Illustrious, NoobAI, Pony, ...), an image model # (§5.6): the single .safetensors as civitai and Hugging Face publish it (Stability's layout, read as # it ships), bf16 throughout (6.4 GiB, one card). The file carries no tokenizer: CLIP's tokenizer.json # (openai/clip-vit-large-patch14) is passed beside it rad-convert /srv/models/OnomaAIResearch/Illustrious-XL-v2.0/Illustrious-XL-v2.0.safetensors \ -o illustrious-xl-v2.0-bf16.rad --recipe data/recipes/sdxl-bf16.recipe \ --tokenizer /srv/models/openai/clip-vit-large-patch14/tokenizer.json # LTX-2.5, video with sound (§5.16): the diffusers pipeline directory, latent_upsampler/ included # for the distilled release's two-stage recipe; rotated int8 (IQ8R) for the text encoder, the # connectors and the DiT, or bf16 (every recipe keeps the vocoders f32, which they run in). A component folder is read through its index, so one whose shards are missing is refused. rad-convert /srv/models/Lightricks/LTX-2.5-Diffusers -o ltx-2.5-iq8r.rad \ --recipe data/recipes/ltx-2.5-iq8r.recipe # Its full (SFT) DiT, transformer_full/, is guided and takes the base schedule back: a folder whose # transformer/ links to it, and the scheduler's shifting turned on as the release's README does mkdir ltx-2.5-full && ln -s /srv/models/Lightricks/LTX-2.5-Diffusers/* ltx-2.5-full/ rm ltx-2.5-full/transformer ltx-2.5-full/transformer_full ln -s /srv/models/Lightricks/LTX-2.5-Diffusers/transformer_full ltx-2.5-full/transformer rad-convert ltx-2.5-full -o ltx-2.5-full-iq8r.rad --recipe data/recipes/ltx-2.5-iq8r.recipe \ --set scheduler.use_dynamic_shifting=1 --set scheduler.shift_terminal=0.1 # MiniMax-Music3, songs (§5.15): the diffusers pipeline directory is the checkpoint (language model, # depth decoder, condition encoder, DiT, vocoder, tokenizer); bf16 throughout (21 GB, one card or two) rad-convert /srv/models/MiniMaxAI/MiniMax-Music3 -o minimax-music3-bf16.rad \ --recipe data/recipes/minimax-music3-bf16.recipe # Breeze-TTS-2, speech (§5.15): the release directory, its codec in audio_tokenizer/ read with it; # bf16 (6 GB, one card) rad-convert /srv/models/BreezeBlue/Breeze-TTS-2 -o breeze-tts2-bf16.rad \ --recipe data/recipes/breeze-tts2-bf16.recipe ``` A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read from, so a finetune that changed only some tensors can be assembled from shards of its changed tensors, links to the base model's shards, and an index pointing each name at its copy. A name held by two shards and not settled by the index is refused. The conversions of record are `scripts/convfn.sh` and `scripts/convdspark.sh`, with their recipes in `data/recipes/`. **A release someone else quantised is read as it ships.** These forms are imported weight by weight (`Checkpoint::Import`, core/format/checkpoint.h). rad-convert writes each quantised linear in the encoding below unless a recipe rule names it; a rule re-quantises from the exact dequantisation where the architecture's kernels read another form, and NVFP4 always needs one: | `quantization_config` | read as | | |---|---|---| | `quark`, MXFP4 weights (fp4, per_group 32, e8m0) | `fp4_e2m1*e8m0[1x32]` | byte for byte: the same codes and exponents. This build serves no MXFP4 trunk weight, so a recipe rule re-quantises them | | `paroquant_mxfp4` (z-lab's ParoQuant on the MXFP4 grid: `format mxfp4`, `mxfp4_block 32`, `group_size 128`) | `fp4_e2m1*e8m0[1x32]/givens` | the codes and exponents byte for byte, plus the learned rotation as the encoding's `givens` tables: per checkpoint tensor the Givens pairs (made whole-row columns), angles and `1 / channel_scales`, a fused gate\|up or qkv\|z carrying one set a part. Convert-time only (the tables are built, not mapped). This build serves no ParoQuant weight, so a recipe rule re-quantises each from its exact dequantisation. Its fp8 heads and embedding (one f32 scale a row) are read exactly, for a recipe's `cast`/`rtn` rule | | `paroquant`, `format int5-bitplane` (bits 5, group 128) and z-lab's plain `paroquant` (bits 4, group 128) | `u5*f16[1x128]-u8[1x128]/givens` and `u4*f16[1x128]-u8[1x128]/givens` | the AWQ-packed low nibbles (plus the fifth-bit plane) re-laid as a code bit stream along K, the f16 scales and integer zero points transposed to `[N, K/128]`, and the rotation as the `givens` tables above. Convert-time only. This build serves no ParoQuant weight, so a recipe rule re-quantises each from its exact dequantisation | | `compressed-tensors`, `format: pack-quantized` with every config group 4-bit `int` weights, `strategy: group`, not `dynamic`, no `input_activations`, `actorder` none, `static` or `weight` (e.g. Google's Gemma 4 QAT w4a16-ct, ukisai's Swift 1.5 27B INT4) | `i4*[1xG]`, G the groups' one group size | `X.weight_packed` (int32 `[N, K/8]`, eight codes a word from the low bits, offset 8) made signed, beside `X.weight_scale` (`[N, K/G]`, f16, bf16 or f32) as shipped. Act-order `static`/`weight` keeps each group's columns together and reads as none; `group`/`dynamic` reorders the groups and is refused by name, as is an `X.weight_g_idx` that moves a column. An `X.weight_shape` must state the codes' `[N, K]`. Convert-time only; `data/recipes/gemma4-31b-dense-w4a8.recipe` re-quantises the group-32 release to the group-128 grid the w4a8 kernels read, `data/recipes/q38-27b-w4a16.recipe` serves a group-128 one at its own numbers | | the same with `symmetric: false` (W4A16_ASYM, as llm-compressor's AWQ writes it; e.g. ukisai's Swift 1.5 27B W4A16-AWQ) | `u4*[1xG]-u4[1xG]` | the stored nibbles as the codes and `X.weight_zero_point` (int32 `[N/8, G]`, eight zero points a word along N, offset 8) as the zero plane, so `(u - z) * s` is compressed-tensors' `(q - zero_point) * scale` bit for bit | | `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16 (the routed-expert GEMMs' scale). Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped; an `import` rule keeps them in their shipped f16 (`data/recipes/q38-27b-w4a16.recipe`) | | `compressed-tensors` with an `nvfp4-pack-quantized` config group (`weights`: 4-bit float, group 16) | `fp4_e2m1*f32[1x16]` | the packed e2m1 codes beside an f32 scale per 16 of K, `weight_scale / weight_global_scale`: the global scale is a divisor, as compressed-tensors' dequantise and vLLM read it. Each piece keeps its own global, so a fused gate\|up reads both exactly. No kernel serves NVFP4, so every NVFP4 weight takes a recipe rule | | `compressed-tensors` whose config groups are all `float-quantized` with 8-bit `float` weights | `fp8_e4m3*[1x*]` or `[RxC]` | nothing is imported: each `X.weight` reads stock as FP8 with `X.weight_scale` beside it, one scale a row (`[N, 1]` or `[N]`, the channel strategy) or a block plane; a per-tensor scale (`[1]`) is written once a row, so it is imported rather than byte for byte. This build serves neither FP8 form, so each takes a recipe rule | | `modelopt` (NVIDIA ModelOpt) with `quant_algo` `NVFP4`, `FP8`, or `MIXED_PRECISION` whose `quantized_layers` are each NVFP4 (group 16) or FP8 (e.g. ukisai's Swift 1.5 27B NVFP4) | NVFP4: `fp4_e2m1*f32[1x16]`; FP8: `fp8_e4m3*f32[1x*]` | NVFP4: `X.weight` (U8 `[N, K/2]`, the even k in the low nibble) beside an f32 scale per 16 of K, `float(X.weight_scale) * X.weight_scale_2`: ModelOpt's second level multiplies, where compressed-tensors' global scale divides. FP8: `X.weight` E4M3 with its one f32 `X.weight_scale`, written once a row. `X.input_scale` (a static activation scale) is not read: activations are quantised from their own values. Any other algorithm is refused by name. No kernel serves NVFP4, and none an FP8 scale per tensor, so both take recipe rules | | GGUF `Q8_0`, `Q4_K` and `Q6_K` tensors (a GGUF file, not a `quantization_config`) | `i8*f16[1x32]`, `affine:codes=u4[1x1],scale=u6[1x32],scale.1=f16[1x256],min=u6[1x32],min.1=f16[1x256]` and `i6*i8[1x16]*f16[1x256]` | the blocks split into their planes, bit for bit; a rule re-quantises from the exact dequantisation. Not served as they stand: the loader refuses them with the hint to serve the container `rad-convert` writes | The width is read per tensor, so a release mixing int4 experts with int8 projections imports both. A mixed-precision release (NVFP4 MLPs beside FP8 or bf16 linears, the usual NVFP4 layout) reads every weight by its own form: a weight without `X.weight_packed` is not NVFP4 and reads stock, its `float-quantized` FP8 with the per-row (`[N, 1]`) or block scale beside it. A compressed-tensors release whose groups are all `float-quantized` FP8 reads the same way, with nothing to import. What an import cannot read (a GPTQ zero point other than the symmetric one, an act-order index that reorders groups, a GPTQ group under 128, a missing or zero global scale, a format or algorithm not listed here) is refused by name. The release's `quantization_config` names the tool, not a served form, so it is kept as `imported_quantization_config.*`, and the model is served by its family's quantised plugin (`qwen35_fp8` for Qwen3.8-27B, `qwen4exp_fp8` for Flash-Next). A weight the architecture declares in another form than the release holds still takes a rule: the recipe dequantises the import exactly and quantises from that. A rule names the target form, not the source, so one recipe covers a mixed release in one pass. Where the kernels read the release's own numbers in another spelling, a recipe's `import` rule (rad-convert's own, docs/TOOLS.md) writes them so instead of quantising again. An int4 W4A16 release reaches the 4-bit GEMMs that way, `blk.*.weight import codes=u4 zero=u4 scale=f16`: u4 codes, an f16 scale and a u4 zero point per 128 of K, a symmetric grid's codes made unsigned under a zero of 8. Every code and zero point is the release's and every scale is exact in f16 except a bf16 scale below f16's normal range (2^-14), which rounds; rad-convert reports how many did. Qwen3.8-27B serves them on `gemm_nt_q` at `w4a16_asym` over the input cast to f16 up to 64 rows a step and at `w4a8i8_asym` over an int8 activation with a scale per (row, 128) above (docs/OPS.md). The recipes of record: ```sh # TranslateGemma 27B from Google's bf16 checkpoint: every linear int8 with a bf16 scale a 128 # columns, served at i8a8 (also the container to record calibration Grams in: serve it with # RADIANCE_CALIB_DIR set and push translation prompts through prefill, see docs/ARCHITECTURES.md) rad-convert /srv/models/google/translategemma-27b-it \ --recipe data/recipes/translategemma-27b-i8a8.recipe -o translategemma-27b-i8a8.rad # An int4 W4A16 Qwen3.8-27B (compressed-tensors AWQ or GPTQ, AutoRound's auto_gptq; here ukisai's # Swift 1.5 W4A16-AWQ, and its INT4 and W4A16-AutoRound the same way): the shipped grids on the # 4-bit GEMMs, the head int8 rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ \ --recipe data/recipes/q38-27b-w4a16.recipe -o swift15-27b-w4a16-awq.rad # An AutoRound int4 Qwen3.8-Flash-Next: its experts imported, its int4 projections made int8 rad-convert /srv/models/ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound \ --recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe -o swift-autoround.rad # DeepSeek-V4.1-Flash from the official release (no GGUF in between) at Unsloth's UD-IQ1_S mix: # Engram tables rebuilt from the release's tokenizer, the imatrix's split gate/up entries fused, a # chat template baked in (the release names none). The recipe's header has the details; serving it # needs the deepseek41 architecture plugin, not in this tree python3 data/engram_tables.py /srv/models/deepseek-ai/DeepSeek-V4.1-Flash engram-tables.safetensors python3 data/imatrix_merge.py imatrix_unsloth.gguf_file imatrix-merged.gguf rad-convert /srv/models/deepseek-ai/DeepSeek-V4.1-Flash --add engram-tables.safetensors \ --recipe data/recipes/deepseek41-ud-iq1s.recipe --imatrix imatrix-merged.gguf \ --chat-template chat_template.jinja -o deepseek-v4.1-flash-ud-iq1s.rad ``` ### 3.3 Inspect a container ```sh rad-info /srv/models/rad/flashnext-w4.rad ``` ``` /srv/models/rad/flashnext-w4.rad format RAD2, 166.4 GiB, little-endian architecture qwen4exp model Qwen3.8-Flash-Next source quant (none) recipe 14 line(s) -- --recipe prints it created by rad-convert ... section offset bytes count strings 256 1.2 MiB - metadata 1258752 8.4 KiB 214 ... ``` `rad-info` opens the file read-only and loads no plugins. It lists every weight with its encoding and what made it: the checkpoint as it stood, or the recipe rule's quantiser and options. ```sh rad-info --meta m.rad # the metadata table rad-info --vocab m.rad # vocab summary and normaliser chain rad-info --recipe m.rad # the recipe it was converted with rad-info -v m.rad # every tensor ``` ### 3.4 Serving a checkpoint without a container ```yaml models: qwen3.8-27b: model: /srv/models/Qwen/Qwen3.8-27B ``` `model` takes a checkpoint directory, a `.safetensors`, an index or a `.gguf`, and serves it at its own precision. `config.json` (or the GGUF header) is the metadata, the `tokenizer.json` and chat template beside it are the tokeniser, and `generation_config.json` gives the sampling defaults. The weights are read once at load, by all relayout workers in parallel. Nothing is quantised at load. A weight the architecture plugin reads in another encoding than the checkpoint holds is named at startup, and needs a container with a recipe. So does a release stored as block fp8, MXFP4, NVFP4 or ParoQuant: this build serves none of them as they stand. What a container has that a checkpoint does not: | | | |---|---| | the file and mapped tiers | a checkpoint is neither grouped nor aligned for them, so every weight must fit VRAM or the host pool, and a weight only a host kernel reads (the n-gram table) cannot be served | | a merged drafter | `--draft-model` is `rad-convert`'s; a checkpoint serves the draft head it ships, if any | | a placement profile | worth about a point of expert hit rate | A GGUF is read when its architecture plugin maps llama.cpp's tensor names; the shipped plugins map Hugging Face's, so a model of a shipped architecture is converted from its safetensors release. --- ## 4. Serve it ### 4.0 The configuration file The server reads every setting from one YAML file: ```sh radiance --config radiance.yaml # serve radiance --config radiance.yaml --check # read and validate the file, serve nothing radiance --help # every key with its argument and meaning, by level ``` A key sits at one of these levels: | level | holds | |---|---| | `server:` | the listener and the process: `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`, `radiance-home`, `kernels`, `download-dir`, `log` (`info`, `debug` or `trace`), `proceed-with-incompatible-configuration`, `debug-accept-reference-kernels` | | `memory:` | the per-card budgets: `gpu-headroom-mib`, `gpu-memory-mib`, `host-headroom-mib`; and `host-mib`, the pinned host memory the process may hold, and `disk-tier`, a directory for parked models' copies | | `scheduler:` | `load-timeout`, `drain-timeout`, `keepalive` | | `cards:` | `all` or a list of card indices the models may use | | `groups:` | `together` and `exclusive` lists of model names | | `models:` | one entry per model, keyed by its name, holding every other key | | `defaults:` | model keys merged under every entry; an entry's own keys win | ```yaml server: host: "::" port: 8000 api-key-env: RADIANCE_API_KEY memory: gpu-headroom-mib: 96 models: flashnext: model: /models/qwen3.8-next-flash-iqr-v4.rad tp: 2 placement: expert_tiered host-pool-mib: 24576 ``` The entry's name (`flashnext` above) is the model id: what a request names in `model` and what `/v1/models` lists. A switch is `key: true`. A key that can be given more than once (`lora`, `allow-host`, `trusted-proxy`) takes a YAML list, and `lora` also takes a mapping of adapter name to path. A key whose value is JSON (`chat-template-kwargs`, `dry-sequence-breakers`) takes it as a flow mapping or list, written as JSON is: `chat-template-kwargs: {"enable_thinking": false}`. A key whose value is a list takes a YAML list or the comma-separated string. A key at the wrong level is refused with the level it belongs to, and an unknown key with the closest known one. This guide names a model key by its name alone (`max-num-seqs`) and the others with their level (`server.port`, `memory.gpu-headroom-mib`); the examples show only the keys they are about, under an entry named after the container. Every entry under `models:` is served by the one process, behind one listener; a request picks its model by `model` (MULTIMODEL.md §5). `aliases` names a model more ways; a request without `model` goes to the model named or aliased `default`, or to the only one; `base:adapter` names a LoRA adapter of the model `base`. A file with one model loads it at startup, as before. With several, a model loads when a request first names it, and the request waits for it (`scheduler.load-timeout`, 503 after; a streaming request gets its event stream at once with an SSE comment every `scheduler.keepalive`). The fleet puts each model on the cards (`cards:` limits them) where it displaces least, spreading models over the cards before they share one. When a load needs room, models leave in this order: lower `priority` first, idle before busy, then the one that comes back cheapest for how long it has been idle; a `pin: true` model loads at startup and never leaves, and a model never makes a higher-priority one leave, even an idle one. A lower-priority model whose room only such models hold waits out `scheduler.load-timeout` (MiniMax-Music3 and Hunyuan3D-2 did, in a fleet with priorities on the small models), so in a fleet where every model should be reachable the entries carry no `priority` and the least recently used gives way. A busy model that leaves finishes its requests for `scheduler.drain-timeout`, then ends them. A model that leaves VRAM is **parked** where it can be: its memory goes to pinned host RAM at the same addresses and the engine stays, so it comes back in about a second (the 27B IQR-V4 in 0.77 s, against 13.5 s to load it). `park: {ram: never}` unloads it instead. `memory.host-mib` caps all the pinned host memory the process holds, parked copies and the models' own pinned pools together (default 75% of the host, or of a container's memory limit when that is less), and a park never leaves less than 8 GiB available, on the host or in its container; past either, kept copies go first, then the longest-parked model. With `memory.disk-tier: DIR` a parked model's copy is also written there in the background, and when host memory runs short it waits on disk instead of unloading, coming back at the drive's speed. `ttl: 10m` parks a model idle that long. A parked model comes back whole before it serves; an embedding model whose cards have no room for all of it right now serves at once instead, its weights read in place from host memory until free memory takes them (`park: {restore: full}` turns that off), and `park: {restore: live}` makes any model serve at once while the rest moves onto the card (MULTIMODEL.md §7.4-7.5). A load that must wait for host memory to pin logs `model NAME: waiting for N of host memory to pin (...)`; when every other model is unloaded and the memory is still not there, it logs `... is not there with every other model unloaded ...` and gives up the wait then rather than at `scheduler.load-timeout`. Each model claims the part of a card it cannot start without: its weights, its activations and one full-length context of cache, or `gpu-memory-mib` when it states one. Its cache then grows into memory no model holds (flex), up to `flex: {kv: {max-tokens: N}}` or its ceiling, and gives it back when another model needs it: a higher-priority model even takes it from a busy one, whose running requests go back to the queue and recompute. `flex: {kv: {min-tokens: N}}` makes N tokens part of the claim. A tiered MoE's expert cache grows the same way while the model is busy, into free memory and into the room of a neighbour idle for a long while, up to `flex: {experts: {max-mib: N}}` of experts a card (0 keeps it at its claim), and is the first thing any model needing room takes back. `groups:` binds models: `together: [a, b]` load and leave as one, `exclusive: [a, b]` are never loaded at once. The dashboard's Overview draws this (§6.1). A dashboard read of a model that is not open answers 409 rather than bringing it back. The fleet's state is at `GET /admin/fleet`, with each model's `state` (MULTIMODEL.md §8.1): a model that is not serving and waits for room is `waiting`, and its `waiting_for` names what for, `accelerator` (memory on its cards) or `host memory` (memory to pin). The dashboard shows it as "Waiting for room". `POST /admin/models/NAME/{load,park,unload,pin,unpin}` moves one model, and `POST /admin/reload` or SIGHUP re-reads the file: changed models reload, removed ones leave, added ones register, and a `server:` or `cards:` change needs a restart. Without an api key these answer loopback callers only. Every model on one card runs its own queues beside the others (MULTIMODEL.md §9 has the measurement against taking turns). Before 2.0 the server took these settings as command-line flags of the same names (`--max-num-seqs 8` is `max-num-seqs: 8`; `-v` and `-vv` are `server.log: debug` and `trace`; `--served-model-name` is the entry's name). Started with such a command line, it refuses and prints the equivalent file. `rad-yaml` prints it without starting anything: ```sh rad-yaml --model m.rad --tp 2 --max-num-seqs 8 > radiance.yaml ``` ### 4.1 Minimal run ```yaml models: flashnext-w4: model: /srv/models/rad/flashnext-w4.rad ``` ```sh radiance --config radiance.yaml ``` It claims the card less `memory.gpu-headroom-mib` (default 96 MiB), splits it between weights and KV cache, loads, and serves on `http://0.0.0.0:8000`. The startup log states every budget before anything is allocated. ```yaml server: host: 127.0.0.1 port: 8100 models: m: model: m.rad ``` ### 4.2 Checking the plan ```yaml models: m: model: m.rad debug-graph: true ``` Prints the declared graph (every op, the kernel it resolved to, and why) and exits without serving. Run it first against a new container or a new kernel library. ```yaml debug-selection: true # the selection table only debug-placement: true # the placement plan only ``` ### 4.3 Memory: how the card is split The card is split into resident weights and the paged KV pool. The engine derives the split from the card and the model; no key states either pool. Its inputs: `memory.gpu-headroom-mib` leaves card space alone, `memory.gpu-memory-mib` claims a size (headroom is the card less that; give one of the two), `max-model-len` and `max-num-seqs` bound the cache, and `host-pool-mib` decides which experts must stay on the card. The startup receipt prints every term. With no visible card (the host backend) half of RAM stands in for the card and is split the same way; the weights pool is then host memory, holding the weights a host kernel cannot read where the container stores them. The non-expert weights come off the top. The rest (the receipt's `elastic` line) is shared by the expert slab and the KV cache: - **With a lending cache** (`placement: auto` or `expert_tiered`, no `deterministic`, a device with virtual memory management), the experts keep on the card what the pinned host pool cannot hold, plus one expert unit of packing slack. The cache takes the rest, up to what it could ever address (`max-num-seqs` x `max-model-len`), and lends every block no live request holds back to the expert slab in place. The prefill staging region comes out of the cache's side. - **Without a lender** (`deterministic`, an explicit `placement: all_vram` or `layer_offload`, or no virtual memory management), the experts come first and the cache keeps one `max-model-len` sequence. The cache never gets less than one `max-model-len` sequence, and when both sides fit, both are whole. With a lending cache, a larger `host-pool-mib` takes experts off the card and gives the cache more. **Next-layer expert prefetch.** Experts held only in the pinned host pool are read across the link by the routed GEMMs that need them. At each routed layer of a decode pass of up to 16 rows, the engine applies the next routed layer's router to this layer's router input, which predicts that layer's choice well, and the card's second DMA engine copies the two likeliest pool-only experts onto the card while the layer runs. The next layer's GEMMs read the copies that have landed from VRAM; a copy holds the pool slot's bytes, so outputs do not change, and a late copy is not used. It is on where one card's pool holds experts (`placement: expert_tiered` or `auto` at `tp: 1`), and off under `deterministic`, without a second DMA engine, and at `tp: 2` and above; the log says which (`expert prefetch on` / `off`). It costs one hardware queue and a ring of six expert units on the card (receipt lines `hardware queues` and `expert prefetch`). Every 2048 predictions it checks the share of its copies the steps routed; under 30% it rests (no prediction, no copy) for 8192 passes and logs `expert prefetch resting` once. On Qwen3.8-Flash-Next at `tp: 1` with the README's one-card settings about half the copies are used, and the decode step goes from 29.0 to 28.0 ms at one sequence and from 101.3 to 95.3 ms at four. At `tp: 2` each card keeps most of its experts and under a quarter of the copies are used, while a pass that runs beside the prefetch's stream starts each of its ordered dispatches later: one sequence took 20.5 ms a step with it and 10.1 ms without, so over several ranks there is none. **Uneven ranks.** The split is computed for the rank whose cache costs most, and one block table serves every rank. A rank whose cache costs less per token (an attention-zero rank at `tp: 3` keeps no attention cache) gets, under `expert_tiered`, a KV pool that pages exactly the common token count, and the difference goes to its weights, up to all of them resident, with or without a lending cache. The log names the rank and both sizes (`kv: rank N's cache costs ...`), or says on the same line why a cheaper rank kept the common split. At `tp: 2` and `tp: 4` every rank costs the same and nothing is re-split. Every rank still allocates its whole share of `host-pool-mib`; a re-split rank whose weights all fit on the card logs that its pinned host pool holds no weights ([`TP3.md`](TP3.md) §1). **Cache size and multi-turn.** Prefix caching holds a finished sequence's blocks for the next turn. When the pool cannot hold the live sessions, it drops prefixes the next turn wanted and that turn re-prefills its whole context. On Qwen3.8-Flash-Next at a 200K context with two ~184K-token sessions, the second turn took 173.0 s at a 0.0% prefix hit with a pool too small for both sessions, and 3.0 s at 99.0% with one large enough. The fall-off is sharp; `kv_util` shows a pool approaching it. To size it: multiply what a token of context costs across all paged groups (the startup log prints it) by the context you serve and by the sessions you want live at once, and compare with the cache the receipt reports. The cache already has everything the experts can spare; a larger `host-pool-mib` (RAM permitting) or `kv-cache-dtype: i8` gives it more. For example, on Qwen3.8-Flash-Next two paged groups share one token axis, `kv_attn` at 26.00 KiB and `kv_qsa_bkey` at 3.25 KiB per 4-token block, so a token costs 7.32 KiB and a 200K-token sequence 1.43 GiB. A prefix-cached session occupies about 1.8x its context in pool tokens, so two live 184K sessions need ~662K pool tokens. **The activation arena**, scratch for the largest step the engine may run, comes off the budget before the split, so both sides pay for it. It grows with `max-num-batched-tokens`, which is why a larger prefill chunk costs resident experts (§4.5). While steps are small most of it is lent back: the architecture plugin declares its activations again at smaller step sizes (the decode rows rounded up to a power of two, at least 256, then each level 4x the one below, up to the step budget), each packed into the bottom of the arena. While recent steps fit a smaller size, the top of the arena holds expert weights; the first larger step takes it back before it runs (an address change, not a copy). Startup prints what each size lends (`activation arena: lends ...`). A plugin opts in with `RadArchProbe::shape_probe_ok`; one that does not keeps its whole arena. Related keys: ```yaml memory: gpu-headroom-mib: 96 # VRAM left unclaimed on every card # gpu-memory-mib: 28000 # the same knob as a claim; not with gpu-headroom-mib models: m: model: m.rad kv-cache-dtype: i8 # halve what a token of context costs (a real quantisation) host-pool-mib: 8192 # pinned host tier for weights embedding-placement: vram # keep the token embedding on the card (below) ngram-placement: ram # an n-gram table in RAM instead of read from disk (below) vision-tower-placement: ram # the encoder towers in host memory, their VRAM to the KV cache (below) weights-disk-tier: true # stream what fits neither from the container; needs O_DIRECT ``` **Lookup tables.** A step reads only M rows of a lookup table, so a tier below the card serves it cheaply. Two have their own placement: | | `vram` | `ram` | `disk` | |---|---|---|---| | `embedding-placement` | on the card, with the other weights | pinned host memory of its own, read over the link in place (the default) | refused | | `ngram-placement` | on the card, every card holding all of it | a copy in RAM made at load, read by the card over the link | read from the container through a row cache | The n-gram table defaults to `auto`, the fastest tier with room once every other weight is placed. Startup prints what each table resolved to and why; a named tier that cannot be honoured stops the server with the reason. *The token embedding* is a dense model's largest model-level weight: 248320 x 5120 in bf16 is 1.18 GiB a card at `tp: 2`. Under `ram` each rank pins its own shard in host memory on top of `host-pool-mib`, and the lookup reads a step's rows over the link, so the table costs no VRAM. The table is the model-level weight only `embed_lookup` reads. A model whose head is tied to it keeps it on the card (the head's GEMM would stream it whole every step), and so does a host that cannot pin it (available memory and memory cgroups, after the pools, with `memory.host-headroom-mib` to spare, default 4 GiB); startup says which. An explicit `ram` turns either case into a refusal. `disk` is refused: the lookup writes activations the card reads, which a host kernel reading the container cannot do. ```yaml models: m: model: m.rad tp: 2 embedding-placement: vram # the table on the cards ``` *The encoder towers* (vision, and audio where a model has one) are read once per image, clip or recording, never on a text step. Under `vram`, the default, they are ordinary weights: Qwen3.8-27B's vision tower is 0.86 GiB a card, about 24,000 tokens of fp8 context. `vision-tower-placement: ram` pins a whole tower per rank in host memory, on top of `host-pool-mib`, and its kernels read the weights over the link. That VRAM goes to the KV cache, and each image costs one read of the tower over the link (about 55 ms for 0.86 GiB on PCIe 4.0 x16). A tower is every weight the architecture declares read once per request. `ram` is refused, with the reason, where the model has no tower, where `mm-max-patches: 0` declared none, or where the host cannot pin it. ```yaml models: qwen3.8-27b-iq8r: model: qwen3.8-27b-iq8r-dflash.rad tp: 1 vision-tower-placement: ram ``` *An n-gram table* (Qwen3.8-Flash-Next's is 47.7 GiB) is read a few rows a token. `disk` reads rows from the container through a row cache with direct reads on the host; about half of a step's rows are first-seen, so steps wait on the drive. `ram` copies the table into host memory at load (12 to 40 s more startup, depending on the page cache) and the card's gather kernel reads the pinned copy, so a step has no host work. `vram` puts all of it on every card. `ram` needs the table's size free after the pinned host pools and the prefix cache's host tier, with `memory.host-headroom-mib` to spare (default 4 GiB), under every memory cgroup the process sits in, and refuses the start otherwise. `auto` takes the first of `vram`, `ram` and `disk` that holds the table. Without a device kernel for the gather (no libr4d) the table is read on the host: `vram` is refused, and `ram` is a copy in locked huge pages, which also needs a memlock limit that large (`--ulimit memlock=-1` in Docker, `LimitMEMLOCK=infinity` under systemd). `ngram-placement: ram=DIR` makes the pinned copy a file, `DIR/ngram-.tab`, in a tmpfs, mapped `MAP_SHARED` and pinned for the cards as `ram` pins it, so two engines on separate card sets (`ROCR_VISIBLE_DEVICES`) hold one table in host memory. The first engine to start fills the file from the container; a second finds it complete, checks samples of it against its own container and only pins it. The `` is a hash of the container's path, size and mtime and the table's place in it, so a file never serves another model. A weight under 32 MiB the gather reads beside the table (its scale) keeps a private pinned copy, since its file would be mostly header. The engine that leaves last deletes the file, and one that leaves while another still holds it waits up to a second for it, so two engines stopped together still remove it; after a crash a complete file stays and is reused, or removed by hand. `DIR` must be a tmpfs (`/dev/shm`, or a tmpfs mounted for it, sized for the table); `ram=DIR` needs the card gather kernel and the driver's SVM API, and is refused otherwise. The driver counts a shared page against every process that pins it, so with two engines the pinned total is twice the table: set `amdgpu.no_system_mem_limit=1` (the cap is RAM less 1/64 and 1.5 GiB) or the second pin can be refused. The kernel charges the tmpfs pages to the memory cgroup of the engine that filled them. `ngram-placement: disk=DIR` reads the table from its own file, `DIR/ngram-.bin`, instead of from the container: a table on a faster or separate drive (an Optane beside a model on a large NVMe, or a model on a hard disk with its table on an SSD) at no host memory. The first start fills the file from the container (the table's size free in `DIR`, written under `.part` and renamed, so the real name is always complete); later starts check samples of it against the container and reuse it. The `` is `ram=DIR`'s, so a file never serves another model; remove the file to have it filled again. Reads go to it as `disk` reads the container, through the row cache with direct I/O, so `DIR`'s filesystem must support `O_DIRECT` (tmpfs since Linux 6.6 does, but a tmpfs is what `ram` is for). **`weights-disk-tier`** serves a model larger than the card and the host pool together, with every step paced by the drive. A routed expert that fits neither lives only in the container. Before each routed layer's first expert op, on every pass, the engine reads the layer's on-disk experts that its rows route to into one of two VRAM buffers: the layer's router has run by then, and its counts are copied back first (one wait on the card per routed layer), so an expert no row routes stays on the drive. A step whose rows route nearly every expert, 64 rows an expert on average (3277 tokens for Qwen3.8-Flash-Next's 512 experts at top-10), reads its layers whole instead, each one while the card computes the one before, with no wait on the card. The buffers come out of the weight budget (the plan's `file buffers` line), and the reads go through four 32 MiB pinned windows out of `host-pool-mib`, as long runs that skip resident experts. Without `deterministic` the host pool is also a cache of the drive: an expert read from it is kept in a free pool slot, and a full pool gives its coldest expert back to the drive for a warmer one. It is meant for running a checkpoint as shipped, to calibrate or compare against. The bf16 Qwen3.8-Flash-Next (335 GiB) runs on two cards at about 28 s a 32K-token step, so use large prefill steps: GLM-5.3-Flash lays its routed experts out by what the deployment needs. At four and eight cards each MXFP4 expert is split by width across every card, the shape its kernels are tuned for, and every expert must then fit in VRAM and the host pool. A container with any expert in another format stays whole. `weights-disk-tier: true` keeps them whole on one card each, so they can stay on the drive, at about a third of the prefill speed and two thirds of the decode speed on 4 x R9700. Two cards always keep them whole. ```sh rad-convert /srv/models/Qwen/Qwen3.8-Flash-Next -o flashnext-bf16.rad --max-ctx 4096 # no recipe: bf16 ``` ```yaml memory: gpu-headroom-mib: 768 models: flashnext-bf16: model: flashnext-bf16.rad tp: 2 placement: expert_tiered weights-disk-tier: true host-pool-mib: 24576 deterministic: true max-num-seqs: 32 max-num-batched-tokens: 32768 num-speculative-tokens: 0 ``` Without the key, a budget that does not fit is refused at startup. **The KV pool is always elastic.** It holds the blocks in use plus a buffer (one prefill chunk, or the largest shortfall admission met in the last few seconds, whichever is larger), and the expert plane grows into what it releases, so a model whose experts do not fit never streams weights to pay for unused cache. **Headroom.** `memory.gpu-headroom-mib` is kept for allocations the engine does not make, chiefly a kernel's code object, which HIP loads at the kernel's first launch. `memory.gpu-memory-mib: N` is the same knob written as a claim: headroom is the card less N. The two keys cannot be combined. With too little left, the first kernel that has never run (a draft head's, a sampler chain's) fails its load and faults inside the HIP runtime: a segfault in a correct kernel on a server that had been serving. Once everything is allocated, startup logs `card N settled at ... free`. Memory taken after the budget read the card (another process such as a desktop, or a driver allocation) comes out of the headroom, and the line says how much. It warns when the room left for first launches is under the 96 MiB the engine allows for its own, naming the `memory.gpu-headroom-mib` value that clears it (what is left rises one for one with the key); a larger headroom that lost part of itself is reported at INFO. What the engine allocates after reading the card is charged before the split, not to the headroom: the step staging, the KV tiers' copy staging and the hardware queues. The driver backs each queue with VRAM beyond its ring (33 MiB on an R9700), so startup measures one and the receipt's `hardware queues` line shows the count and price. It also includes the queue scratch the runtime keeps once a kernel with a private segment has run (5 MiB a compute unit, 160 MiB on an R9700). ### 4.4 Long context ```yaml models: m: model: m.rad max-model-len: 200000 kv-cache-dtype: i8 max-num-seqs: 8 ``` `max-model-len` reserves nothing per request; it is the worst case the pool is sized against. `0` takes the model's training context. `kv-cache-dtype: i8` is the int8 cache: K and V as int8 codes with one f16 scale each per token and head (the head's largest magnitude over 127), `2 * head_dim + 4` bytes a token and head against bf16's `4 * head_dim`. It halves what a token of context costs, which at a production context is most of the pool. It is a real quantisation that changes the output slightly, so it is only ever set explicitly. Every paged attention serves both caches, a drafter's (DSpark, DFlash2, Gemma 4's) included, and a streamed group (`kv-resident`) streams either. The delta-net state and the QSA indexer's key tail are recurrent state and keep their own widths. On two R9700s over four agent traces of about 245 000 tokens each, Qwen3.8-27B against the same weights with a bf16 cache, scored on the 453 857 positions the model writes itself: | `kv-cache-dtype` | mean KL | top-1 | KL past 200 000 tokens | |---|---|---|---| | `i8` | 0.000436 | 99.37% | 0.000396 | The scale follows each token and head, so the error does not grow with depth. Prefill and decode run at the speed of the one-byte E4M3 cache this one replaced (a speculative step of 8 sequences 71.05 ms on both; that cache's mean KL on the same traces was 0.001009). A decode step without the drafter at 1 / 4 / 8 sequences on two R9700s: Qwen3.6-35B-A3B 10.22 / 11.56 / 12.16 ms, Qwen3.8-Flash-Next 10.40 / 12.85 / 15.58. The row's layout and the kernels that read it are in [OPS.md](OPS.md#the-kv-cache-operand). `kv-cache-dtype: fp8` is GLM-5.3-Flash's alone (`glm5next`): it narrows the latent-attention cache to E4M3 at a descale of 1 (half its bf16 size); the DSA index, its key tail and the KDA caches keep their own widths. Every other model refuses it, naming `i8`. **Many sequences.** Every model here serves `max-num-seqs` up to 32. A sequence holds only the blocks its tokens occupy, but two costs exist per sequence regardless: - **Recurrent state.** On a hybrid model every sequence owns its delta-net state, two copies with speculation. Qwen3.8-Flash-Next keeps 54 MiB a copy on each card, so 32 sequences take 3.4 GiB of the cache share. The 27B in bf16, with no experts to give way, then holds about 117K tokens of attention cache, less than one 200K request, and startup warns that a longer one would be refused. The 27B in FP8 holds 2.8 full-length sessions at 32, the 35B-A3B ten. - **Block tables.** The step batch's tables are carved for every sequence at the full context and charged to the VRAM budget (`step staging` in the receipt), so they come out of the cache share. The line `kv: the pool backs N% of the worst case ... M full-length sessions` counts only the part of the pool that holds context; compare M with the sessions you expect to keep live. With `tp-wire: wht6`, a decode step above the row count startup names is all-reduced lossily like a prefill chunk; at 8 sequences and depth 3, Flash-Next's decode steps are above it. **The delta-net state at f16** (`state-cache-dtype: f16`). The `qwen35` plugins (`qwen35_fp8`, and `qwen35moe_fp8` and `qwen35_w8a8`, built from it) declare the recurrent state cache f32. With `state-cache-dtype: f16` they declare it f16; startup and the declare log say so (`GDN state cache f16`), and a plugin that does not serve it is refused at startup by name. **It is lossy**: the state is rounded wherever it is stored, so the generated text changes. It halves the state pool and its host checkpoints, and the state's traffic, which grows with the number of decoding sequences. Measured on `qwen35_fp8` only, Qwen3.8-27B MXFP4 at `tp: 2` on two R9700s (PCIe Gen5 x8, 265 W), against the bf16 model: | state | mean KL, 2048 chunk | mean KL, 64 chunk | top-1, 64 chunk | |---|---|---|---| | f32, `k6_v4` KV | 0.040238 | 0.039607 | 94.07% | | f16, `k6_v4` KV | 0.040005 | 0.040468 (+2.2%) | 94.00% | | f32, `fp8` KV | 0.039171 | 0.039327 | | | f16, `fp8` KV | 0.039600 (+1.1%) | 0.039690 (+0.9%) | | `k6_v4` and `fp8` in this table are E4M3 cache forms outside this build's `kv-cache-dtype` values. A 64-token chunk stores the state, and rounds it, every 64 tokens. Decode, greedy, three rounds (medians, tok/s): | streams | f32, no speculation | f16 | f32, speculation 7 | f16 | |---|---|---|---|---| | 1 | 67.1 | 67.5 (+0.6%) | 222.2 | 215.1 (-3.2%) | | 4 | 246.8 | 253.3 (+2.6%) | 636.9 | 621.0 (-2.5%) | | 16 | 708.0 | 779.5 (+10.1%) | 1223.8 | 1276.7 (+4.3%) | Without speculation the rounds agree to a tenth and the gain grows with the streams. With speculation f16 also changes which drafts the greedy text accepts, so one and four streams moved down; whether that is the text or the step was not separated. Use it for many concurrent sequences where the KL above is acceptable, and measure your own load. ### 4.4.1 Streaming KV: context bigger than the card ```yaml models: flashnext: model: flashnext.rad tp: 2 max-model-len: 262144 max-num-seqs: 2 kv-resident: 32768 ``` `kv-resident: N` keeps the whole KV cache of the model's sparse attention group in pinned host RAM and only a ring of N tokens on the cards. Each decode step makes the blocks it selected resident, copying in the missing ones and evicting the coldest; an evicted block is already in the host copy. Prefill reads the cache one layer at a time from the host copy. The ring is a fixed size at any context length, so the context is no longer bounded by VRAM: holding two 262k-token conversations on two 16 GB cards, the cache went from 3.84 GB of VRAM a card to 0.74 GB of VRAM and 3.22 GB of host RAM, and the VRAM it gave up went to the expert slab. - N is in tokens, rounded up to whole blocks (4 tokens on this family). Absent or `0`, nothing streams. **Use 32 768**: a smaller value is raised to it, and to one decode step's selection (`max-num-seqs` x (1 + speculative tokens) x 513 blocks) when that is larger, with one warning. At or above `max-num-seqs` x `max-model-len` the ring covers the context and nothing streams. - Cost: the ring at the cache's per-token bytes for every layer (6.05 KiB a token a rank at i8 on two ranks: 194 MiB at 32 768), the prefill stage, one layer of the retained context (516 B a token a rank), and the host copy of `max-num-seqs` x `max-model-len` tokens per rank. The VRAM pool is the larger of ring and stage, not their sum. - Models: Qwen3.8-Flash-Next (`qwen4exp_fp8`) with a bf16 or i8 cache and GLM-5.3-Flash (`glm5next`) with a bf16 or fp8 one. Anywhere else the key is ignored with one warning and every block stays on the card. - The prefix cache's host tier (`prefix-cache-mib`) is turned off while a group streams; prefix hits still work from VRAM (§4.8). - The startup receipt's `kv streaming:` lines name the ring, the stage and the host copy; `/metrics` carries `kv_resident_blocks`, `kv_stream_misses_total` and `kv_stream_bytes_total`. | model (arch id) | streams | KV dtypes | notes | |---|---|---|---| | Qwen3.8-Flash-Next (`qwen4exp_fp8`) | **yes** | bf16, i8 | sparse QSA; the measured path | | GLM-5.3-Flash (`glm5next`) | **yes** | bf16, fp8 | sparse MLA + DSA; declare and issue are tested, not served here | | Qwen3.5/3.6/3.8 dense (`qwen35_*`, `qwen35moe_fp8`) | no | | dense attention reads the whole history every step | | all other architectures | no | | no streamed store and no `kv_resolve` | **Measured.** Flash-Next, fp8 cache, 2x16 GB gfx1201 at TP2, one request, two cold starts a configuration, 2 048 tokens decoded: | configuration | prompt | prefill tok/s | tok/step | decode tok/s | |---|---|---|---|---| | streaming off | 61 971 | 2 722 | 1.00 | 39.89 | | **streaming on** | 61 971 | **2 783** | 1.00 | 39.78 | | streaming off + MTP | 61 971 | 2 600 | 2.87–3.23 | 62.3 (56.8–67.7) | | **streaming on + MTP** | 61 971 | **2 671** | 3.02–3.45 | 64.8 (53.2–76.5) | | streaming off | 249 939 | 2 635 | 1.00 | 38.60 | | **streaming on** | 249 939 | **2 669** | 1.00 | 39.07 | | streaming off + MTP | 249 939 | 2 577 | 3.10 | 50.56 | | **streaming on + MTP** | 249 939 | **2 623** | 3.10 | 50.86 | Decode is unchanged, with and without MTP (the MTP rows' spread is the text's acceptance, not the configuration); prefill is 1-2 % faster, because the VRAM the cache gives up holds routed experts. Per card the host copy is smaller than the VRAM it displaces (3.22 against 3.58 GiB), because each rank keeps only its own slice. **When not to use it.** - Per token streaming costs the same bytes, in host RAM instead of VRAM; at one conversation that fits it costs more than it saves. It is the way to keep a cache VRAM cannot hold. - The host copy is reserved for `max-num-seqs` x `max-model-len`, however short the requests. - At `tp: 1` the host copy for 2 x 262k (6.00 GiB) does not fit beside the weights, and the start is refused. - The copies cost about 3 % of decode at `tp: 2` with a small context, and nothing at `tp: 1`. - Quality: perplexity 3.994 streaming off, 4.015 with a ring covering the context, 4.014 with a ring a fraction of it. **Check it on your own machine.** `scripts/kv-parity.sh` checks the covering case: a ring at the group's context streams nothing and gives byte-identical completions to the same server without the key. `scripts/kv-stage-parity-64k.sh` checks the streaming case: with the ring at 32 768 tokens and a ~64k document, every prefill chunk is staged layer by layer and the completions are byte-identical to streaming off. Both need the cards and the toolchain container. The design is in [KV-STREAMING.md](KV-STREAMING.md). ### 4.5 Prefill chunk size A long prompt is prefilled in chunks of at most `max-num-batched-tokens`. On a mixture-of-experts model this is the largest lever on time to first token: a chunk sweeps the whole expert plane once however many tokens it carries. ```yaml models: m: model: m.rad max-num-batched-tokens: 2048 ``` On a 48-layer MoE at 200K context on two cards, prompts of 8K and 24K tokens: | chunk asked for | 512 | 1024 | **2048** | 4096 | |---|---|---|---|---| | chunk run | 512 | 1024 | **2048** | 2048 | | prefill | 1750 tok/s | 2200 | **2706** | 2620 | A 185,253-token prompt prefills in 91 s at a 2048 chunk and 138 s at 512. **The checkpoint interval caps the chunk.** On a hybrid model a prompt's chunk is clamped to `checkpoint-interval` (default 2048) before the token budget, so asking for 4096 runs 2048-token chunks with an activation arena sized for 4096, and the expert plane loses residency for a chunk it never gets (§4.3). Startup prints which bound applies: ``` chunk geometry: quantum 64 (attn block ..., state chunk ...), checkpoint interval 2048, max_tok 4096 -> prefill chunks of at most 2048 (the checkpoint interval, not the budget) ``` `RADIANCE_LOG_STEPS=1` prints the token count of every step. Raising both (`max-num-batched-tokens: 4096`, `checkpoint-interval: 4096`) runs 4096 chunks but gave 2610 tok/s against 2748, because the arena took another 239 resident experts (9219 to 8980). Where prefill is bound by the link carrying non-resident experts, a larger chunk stops paying once it costs residency. A longer chunk holds the device longer per step, but the prefill a decode step waits behind finishes sooner: four decoders with a long prompt beside them finished in 29.5 s at a 2048 chunk and 31.9 s at 512. **Decoders beside a chunk: `prefill-interleave: N`.** A step that carries a chunk takes the chunk's time, and every sequence decoding beside it waits that long for its next token. With `prefill-interleave: 2`, after a step that carried a chunk while other sequences were decoding, the next two steps carry decode rows only and admit nothing, then the next chunk is scheduled. The prompt's time to first token grows by those steps and the decoders keep their cadence. A lone prefill is not held, nor is the step after a prompt's last chunk. `0` schedules as before. `/stats` counts the decode-only steps the hold inserted as `steps_held`, `/metrics` as `radiance:engine_steps_held_total`. Served default: `prefill-interleave: auto:1` (below), so decoding sessions keep about half their rate while prompts prefill; `deterministic: true`, KL mode and generators keep 0, and an explicit `N` or `auto[:SHARE]` is kept as given. Measured on Qwen3.8-Flash-Next (fp8, TP2, MTP 3, 8 sessions decoding beside 64K prompts): 12.3 -> 40.9 decode tokens/s a session, aggregate prefill 3.7K -> 1.8K tokens/s, time to first token 17 -> 36 s. `prefill-interleave: 0` restores the old schedule. `prefill-interleave: auto` sizes the hold from measured step times instead: after each such chunk, as many decode-only steps as fit in a quarter of a chunk step's time at a decode step's (running means of both, at most 64 steps; one until a decode step has been timed). `auto:SHARE` uses SHARE of the chunk step's time instead of a quarter (0 < SHARE <= 4; `auto:1` gives decode as much time as prefill). With the quarter the prefill gives up at most a fifth of its rate however many sequences decode, and the decoders get several steps where a decode step is cheap beside a chunk, none where one costs more than that quarter (they still ride every chunk). In the scheduler's host simulation of 32 prompts of 128K tokens sent at once, each then decoding 512 tokens (2048-token chunks, MTP 3, step costs fitted to a lone prefill and to decode alone), auto raised the decode rate of the sequences decoding while prompts still waited from 6.5 to 31 tokens/s each and delayed the last first token by 6 %. Because the hold follows the device's timing, which steps carry a chunk differs from run to run; a number schedules the same steps every time. **A prefill alone in its step can carry several intervals** (`prefill-span: N`, default 1). A chunk ends on every checkpoint interval, so a prompt is otherwise prefilled one interval a step. With ```yaml models: m: model: m.rad max-num-batched-tokens: 4096 prefill-span: 2 ``` a prefill that is alone in its step carries up to N intervals a step, from the prompt's second interval on (the first is never spanned). Every other step -- one with decode rows, another prefill, or a request waiting to be admitted -- is planned at the shared budget, `max-num-batched-tokens` less the extra intervals (here 2048), as without the span, `busy-prefill-chunk` included. The checkpoints at a span's end and at a prompt's tail are written where a span of 1 writes them, so a follow-up turn resumes where it did. Startup states both budgets: ``` chunk geometry: a prefill alone in its step spans up to 2 intervals from its second interval on; every other step is planned at 2048 tokens ``` Flash-Next (`qwen4exp_fp8`) runs a spanned step in pieces of one MoE pass (2048 rows): every connection read takes a pass, and the indexer's score plane stays a pass tall and is scored in windows. Above two ranks the step is also pipelined: everything row-local runs a pass at a time and every all-reduce goes out on the second lane, beside the other piece's work (at TP4 a chunk's 97 tiered-int8 all-reduces are about a quarter of its time). Each piece then computes what a 2048-token chunk computes, so at the default `checkpoint-interval: 2048` greedy output is that of `max-num-batched-tokens: 2048`. At two ranks the gated residual's fused write takes every all-reduce, so a spanned step runs as one wider step; there, at one rank, and on every other architecture, a spanned step is a wider chunk and may differ from 2048 chunks at tie level. On Flash-Next (`fp8-iq4r-moe`, R9700 at 215 W, fp8 KV, MTP 3, `tp-wire: wht6`), the change in time to the first token of one prompt, `max-num-batched-tokens: 4096`, `prefill-span: 2` against `max-num-batched-tokens: 2048`: | prompt | TP4, all_vram | TP2, expert_tiered, 12 GiB host pool a rank | |---|---|---| | 2K | +0.4 % | -6.1 % | | 8K | +4.1 % | -1.0 % | | 18K | +8.0 % | +2.3 % | | 64K | +9.3 % | +9.0 % | | 250K | +8.8 % | +49.1 % | A positive figure is a shorter time. The gain depends on the box and the container: on another 2x R9700 at 210 W serving the w4nl64 Flash-Next container at TP2 (`expert_tiered`, 12 GiB host pool), the same span took 2.61 s against 2.56 s to the first token of an 18K-token prompt and 10.72 s against 10.55 s at 75K, and `max-num-batched-tokens: 8192`, `prefill-span: 4` took 3.30 s and 10.82 s. Measure the prompts you serve before turning it on at two ranks. What it costs: - **The checkpoints inside a span are not written.** A later request that shares only part of a prompt -- a long system prompt with a different question -- resumes up to one interval earlier. - **Activation memory.** The arena is sized for N-interval steps. On Flash-Next the largest buffer, the score plane, and the connection reads' scratch stay a pass tall; at TP4 and 256K context the KV pool goes from 12.42 GiB a card at a 2048 budget to 12.14 (11.53 for a 4096 budget without the span). - **Decode steps.** The step's token, position, output and slot-map arrays are carved for the budget and uploaded whole every step, so at 4096 a decode step uploads twice the bytes it does at 2048. - **Expert residency, where routed experts are in host memory** (`placement: expert_tiered`). The span's extra rows are VRAM the expert slab does not get (320 MiB a card on Flash-Next at TP2). Every step but a spanned one runs at an arena level of the shared size, which lends those rows to the slab and keeps the prefill stager's ring right above its own buffers. A prefill there spans only from eight intervals (16K tokens on), where the span starts to win. Startup says so: ``` scheduler: --prefill-span: a prefill spans when it is 16384 tokens or longer -- routed experts are read from host memory, and the arena a spanned step takes is room they lose for it ``` A model without checkpoints, or one whose checkpoints hold sliding windows (as on Gemma 4), does not support spans; there the key only plans every step but a lone prefill at the shared budget, and startup warns. Window snapshots are written at `checkpoint-interval` boundaries as well as just before the prompt's end. The intermediate snapshots let an edited prompt resume below its first changed token; `checkpoint-policy` bounds the snapshots kept. For a window-only checkpoint model, `checkpoint-policy: tip-only` also skips creating the intermediate snapshots and splitting chunks at their intervals, not just retaining the tip afterward. This restores tail-only snapshot scheduling and avoids the extra copies, at the cost of full re-prefill if an edit precedes the tip. Recurrent-state models still checkpoint at intervals under `tip-only`; their existing scheduling is unchanged. Both kinds also take a snapshot at a head other prompts share: when a prompt leaves a cached head that at least two earlier prompts already left differently (the same system prompt or instructions in front of a different text, as a translation service sends its pieces) and no snapshot lets it skip at least 256 tokens of that head, the request takes one where the head ends, at the cost of one chunk split, and the requests after it resume there. A conversation's next turn has only its own earlier turn past that point, so it splits nothing extra. **Where a hit resumes** (`prefix-resume`). A kernel can round a row differently at another chunk length (a quantised GEMM's split-K count is chosen from `M`, spec §17), so a hit that recomputes its tail in other chunks than a cold prefill can flip a near-tie in greedy text. Two modes: - `exact` (the default): a hit answers exactly as the same prompt prefilled cold. It resumes only where an idle server's cold prefill of that prompt starts a chunk: every `max-num-batched-tokens` tokens (rounded down to the chunk quantum), or every `checkpoint-interval` when that is smaller. A prompt's tail snapshot is taken where its last chunk starts, a boundary the chunk already ends on, so it costs a copy and no step. An exact repeat re-prefills the cold run's last chunk; an appended turn re-prefills that chunk and what the turn added. - `nearest`: a hit resumes at the deepest snapshot or block, and a prompt's tail snapshot is at its last quantum boundary. A turn re-prefills up to one chunk less than under `exact`. Under `exact` an interval larger than the chunk must be a multiple of it; otherwise it is rounded up, and startup says so: ``` --checkpoint-interval 6144 resolves to 8192: --prefix-resume exact needs it a multiple of the 4096-token prefill chunk (--max-num-batched-tokens 4096) ... ``` Exactness holds on an idle server, as greedy batching does: a prefill that shares its steps with other requests or decode rows (`busy-prefill-chunk`, `prefill-interleave`) is cut differently, and a request's own checkpoint (`/v1/systemone`'s shared head) resumes where it was asked. **One prefill sequence in two pieces.** At two ranks, on `qwen35_fp8` (and `qwen35_w8a8`, built from it, where its norms do not write rotated int8 codes), a step of at least 1024 tokens that carries one prefill sequence and nothing else runs in two pieces of about half, the first rounded up to 64 rows so both sit in the whole step's kernel band. Every block runs a piece at a time; the work between two blocks (the block's all-reduce, the next norm, and after a feed-forward the add) runs a piece at a time on the second lane, beside the other piece's compute. The all-reduce there is the narrow `overlap` launch ([OPS.md](OPS.md#collectives)): the fused all-reduce and norm holds its blocks while it waits on the link and slows the GEMM beside it by a third, and a wide launch slows it 1.45-2.1x. A piece computes what a narrower chunk computes, so a pipelined step is the serial step bit for bit, with one exception: a lossy `tp-wire` whose `tp-wire-min-kb` a piece's message falls under while the whole step's does not (that piece goes out exact). Decode steps are unchanged. There is no switch: the startup log says once that prefill steps are pipelined, and the first wide step that runs serially says why (`radiance: qwen35: a 2048-row prefill step runs serially: more than one sequence`). Measured on two R9700s (PCIe Gen5 x8, 265 W) over MXFP4 containers: | model, chunk | prompt | serial | pipelined | |---|---|---|---| | Qwen3.8-27B MXFP4, 2048 | 41k tokens | 9.00 s | 8.41 s | | TranslateGemma 27B MXFP4, 2048 | 6k | 1.27 s | 1.21 s | | | 12k | 2.48 s | 2.42 s | - **Two ranks only.** Other rank counts prefill serially: the pipeline has been timed against the serial step at two ranks only. - **Which steps.** A prefill step with more than one sequence, decode rows beside it, or media rows (an image's tokens) runs serially. `qwen35_w8a8` prefills serially where libr4d serves its rotated int8 norms (the boundary norms issue E4M3 codes only; startup says so). The pieces need 1024 rows, so the gain needs a chunk of 2048 (the default `max-num-batched-tokens`). - **Memory.** The buffers the second lane touches leave the arena's sharing pool across the architecture's second-lane window ([PLUGIN.md](PLUGIN.md) §11), so the drafter's and the heads' buffers still share their bytes; the second lane's scratch region holds only what its ops ask for ([IMPLEMENTATION.md](IMPLEMENTATION.md)). The second lane's hardware queue (33 MiB, §4.3) remains. **Sharing a step** (`busy-prefill-chunk`, default `auto`). When other work is pending, a prefill chunk leaves room for one row plus the draft window per decode row behind it, and a share of the budget (an eighth, at least one quantum) for each prefill behind it and for the next request waiting to start, so a long prompt (a minute or more at 256K) does not starve decode rows or admission. The chunk never drops under the smallest step the prefill stager overlaps (one more than the largest arena level, named on the startup line `prefill staging: ...`); below that every routed layer reads its pooled experts synchronously and the prefill slows far more than sharing saves. Where holding a chunk back would leave a short remainder before the checkpoint boundary, the interval is split into two staged halves instead. Decode rows alone take only their few tokens: the chunk ends a quantum short of the boundary and the next step finishes it. A prompt with nothing beside it is unaffected. `off` lets a chunk take the whole step; `N` holds a shared chunk to N tokens (startup warns when N is under the stager's step). `radiance:engine_prefill_chunks_capped_total` counts the chunks held back. **Adaptive mixed-step latency** (`mixed-step-target-ms: N`, default off). A mixed step contains both prefill rows and at least one decoding sequence. When this flag is set, completed mixed steps teach a model-agnostic controller an aggregate prefill-row cap. The cap is shared fairly among the prefills in that step, decode rows are reserved first, and a lone prefill remains unchanged. This is a soft service-time target, not a request deadline: timing starts when the engine issues the step and ends after its forward and speculative-drafter work. Queueing, HTTP transport and the client are outside it, and the legal chunk quantum, fixed decode cost, media passes or host jitter can make the target unattainable. The controller starts at one quarter of the model's shared-step capacity, corrects an over-target representative chunk immediately, and grows cautiously after three clearly under-target samples. A true prompt tail does not change the learned cap; a checkpoint or fixed busy-chunk boundary does, because the prompt continues and a lower cap can shorten its next step. If the target is lower than one legal mixed step, the cap bottoms out at one prefill quantum and misses remain visible. Startup refuses configurations whose token budget or explicit busy cap cannot carry one legal prefill quantum beside a decode row. When the batch budget cannot carry one quantum for every simultaneous prefill, equal sharing applies to the requests that fit and the scheduler's priority/arrival order continues the rest on later steps; startup prints that capacity. Raise the batch budget if every admitted prefill must progress in every mixed step. Use the target for an interactive multi-user deployment where long fresh prompts otherwise make active streams pause. It redistributes when useful work completes; it does not make the prefill free, and may lower fresh-prefill throughput under contention. Pin and measure the target per deployment rather than branching the scheduler by model name. The relevant metrics are `radiance:mixed_step_target_steps_total`, `_misses_total`, and `_prefill_cap`. **Check the prefix cache after changing the chunk.** The larger arena shrinks the KV pool (here 516,864 to 499,920 pool tokens, 3.3%), and §4.3's cliff is sharp. With two ~180K sessions (first turns back to back, then the first session's second turn), a 512 chunk took 137.7 s, 130.0 s and 1.42 s, and 2048 took 90.6 s, 93.2 s and 0.97 s; both cached 178,176 of 179,585 tokens with no evictions, and `kv_util` went from 0.70 to 0.73. Check your own shape with `prefix_hit_rate` and `prefix_evictions` on `/stats`; the failure looks like turn two taking as long as turn one. **The cost is decode.** The 239 experts the arena displaces slow steady-state decode. Measured with `scripts/cstep2.sh` (decode step time from the decode step counter, no sequence retiring inside the window), a 2048 chunk against 512 cost 0.6% of a single-stream decode step (22.3 to 22.4 ms) and nothing measurable at eight streams (about 40 ms). **Changing it changes the text.** A different chunk is a different batch shape, so the sums inside a prefill run in a different order, and at a tie that is a different token. Each setting is byte-identical across runs and restarts; reproducibility holds per configuration, and this key is part of the configuration like `tp` and `num-speculative-tokens`. Pin it before recording anything you will compare against later. ### 4.6 Speculative decoding If the container carries a draft head, it is used by default at the depth the plugin states: ```yaml models: m: model: m.rad # num-speculative-tokens: auto # unset: the drafter's own operating point # num-speculative-tokens: 0 # off num-speculative-tokens: 3 # a stated depth ``` The drafter comes from the container: merge one with `rad-convert --draft-model DIR`, or use an MTP head inside the target checkpoint, which needs no key. `draft-model` in the server's file is an error that says so. Measure speculation by step time, not tokens per second. A drafter with a sliding window over its own cache (DFlash2) keeps that cache outside the prefix cache. Where a hit resumes from a window snapshot (a model whose sliding layers the cache does not index and that keeps no linear state, as the Gemma 4 31B under gemma4_bf16; the 26B-A4B declares its sliding layers full and takes no snapshot), the snapshot carries the drafter's window with the trunk's, so the hit leaves it whole and it drafts from the first decoded token. Elsewhere (a model with linear state, as Qwen3.8), after a prefix hit it could not draft until its window had slid past the hit, which on a chat's follow-up turn is most of the reply. Such a hit is therefore ended one drafter window before the end of the prompt, at a checkpoint, and the window is recomputed; the reply is the same. A hit whose nearest checkpoint below that point would give back more than two windows is kept whole. The startup line `draft floor` says which applies; `radiance:draft_refills_total` counts the hits ended early and `radiance:draft_refill_tokens_total` the tokens recomputed. **Prompt lookup.** The engine also drafts with no model at all: for each sequence it finds the latest earlier occurrence of the sequence's last n tokens (prompt and output alike, n from `spec-ngram-max` down to `spec-ngram-min`, 4 and 2 by default, the longest first) and proposes the tokens that followed it, continuing past the end with its own proposal when the pattern repeats within the window. There is no draft pass, and no proposal when nothing recurs, so such a step is an ordinary decode. It pays where the reply copies its context -- code edits, rewrites, diffs, JSON, quoting -- and costs a verify row per wrong draft elsewhere. Each sequence keeps an index of where its n-grams last occurred (about 8 bytes a token per pattern length, 16 MiB at 400k tokens and the default range), extended by each commit, so a lookup does not scan the context. A verify row is not free: on a MoE each row reads its own routed experts, and five drafts can cost a couple of plain steps. So when prompt lookup is the only drafter, a proposal is verified only when it is expected to pay: K drafts are verified when E[accepted] * T(R) > tokens * (T(R + K) - T(R)), with T(R) the measured time of a decode step of R query rows (timed online over every pure decode step) and `tokens` what the step already expects to emit -- for one sequence, 1 + E[accepted] > T(1 + K) / T(1). E[accepted] is the sequence's own record, kept apart for a match that runs at least 8 tokens back (the reply is copying a stretch; drafted at once) and a shorter one (a recurring bigram; drafted once its record says so). A proposal held back is still scored against the tokens the sequence goes on to emit, which is exactly what a verify would have accepted, so a sequence that stops drafting on prose keeps learning and drafts again as soon as it starts copying. There is nothing to configure; the constants are in `core/sched/lookup.h`. Only which proposals are verified changes, never the text. `radiance:lookup_held_total` counts the held proposals. ```yaml spec-ngram: 5 # prompt lookup alone, up to 5 drafts ``` ```yaml spec-ngram: 5 draft-window: adaptive # each sequence's window follows its acceptance ``` ```yaml num-speculative-tokens: 4 # a head drafts; lookup fills in where it declines ``` `spec-ngram: K` sets the window to K (a different `num-speculative-tokens` is refused) for a container that declares no draft head; one that declares a head is refused at startup, because the head would draft in lookup's place (serve it with `num-speculative-tokens: N`). Without the key, prompt lookup still drafts for every sequence a declared head declines, and is the only drafter when speculation is on (`num-speculative-tokens: N`) and the container has no head. Startup says which (`speculation: prompt lookup only -- this container declares no draft head`), and the drafts count in `draft_n` / `draft_n_accepted` and the `radiance:draft_*` metrics like a head's. Prompt lookup reads the committed sequence, so a step is not issued ahead of the previous one's readback. A lookup draft is a single token, a point mass, and the verify accepts it when the target's own draw at that position equals it: with probability p(x), and otherwise the emitted token is the target's draw conditioned on not being x. That is the speculative-sampling rule for a deterministic proposal, so output is distribution-exact at any temperature and greedy text matches decoding without it. **Adaptive window.** Code and JSON keep accepting deep into the window; prose falls off after a position or two. With `draft-window: adaptive`, `num-speculative-tokens` is the ceiling and the engine keeps a smoothed acceptance per draft position for every sequence: ```yaml models: m: model: m.rad num-speculative-tokens: 6 draft-window: adaptive ``` A serial draft head runs as many rounds as the deepest window in the step, so the depth is chosen per step: the one that maximises the tokens its sequences are expected to emit over the measured cost of such a step (drafting steps' times by the query rows they carried, each sequence's verified token and its drafts; a row count not yet timed is priced from the timed ones around it). Under that depth each sequence stops at the first draft whose chance of being emitted is under one in ten. The depth moves only after eight steps and for a 2% gain, since each new window is a new pass shape and a new recording. A new sequence starts from what earlier sequences finished on. A block drafter proposes its whole block in one pass and each sequence verifies the first min(D, its stop) of it; prompt lookup as the only drafter is measured the same way, its drafts feeding each sequence's estimate. With speculation off the window has nothing to adapt and startup says so. Prompt-lookup proposals made when a head declines count in the acceptance metrics but do not move the head's window. At temperature 0 the text is that of a fixed depth wherever fixed depths agree; above 0 it is distribution-exact. `radiance:draft_depth_adaptive` and `radiance:draft_verify_depth_total` (§6.3) show the windows. **Adaptive chain depth: `draft-depth: adaptive`.** `draft-window: adaptive` picks the window of the next step from the acceptance and the cost of the steps before it. A coupled serial head can also stop the chain of a step within that step, from the head's own laws: a fixed chain drafts N tokens every step and its verify pays for N + 1 rows whatever the head thought of them. With `draft-depth: adaptive` (`draft-coupling: on` and a serial head; `draft-window` stays `fixed`, since both decide the depth and the engine refuses them together) `num-speculative-tokens` (or `draft-depth-max`) is the deepest chain, and round j runs only while the product of the earlier rounds' probabilities is at least `draft-depth-stop` -- each round's largest probability (`draft-depth-stat: top`, the default) or the probability of the token it drew (`path`). The next verify then carries exactly the drafts made (1 to N, each row count its own recorded pass), so a step whose head is unsure costs one or two rows and a confident one drafts deep. ```yaml num-speculative-tokens: 5 # the deepest chain draft-coupling: on draft-verify: traversal draft-depth: adaptive draft-depth-stop: 0.85 ``` The next verify is issued before the drafts exist (it runs behind them on the card), so its row count has to be known when it is issued. The host therefore reads one state row back after a round and decides the round after the next one (`draft-depth-lag: 1`, the default): the card is running the round in between, so the readback, the decision and the issue of the next round or of the verify (about 0.1 ms to the first packet) hide behind it and nothing waits. `draft-depth-lag: 0` decides every round from all the rounds before it; the card then waits for the host between two rounds. The step's tokens are streamed after the chain's last decision rather than right after the sampler (up to a millisecond or so later; the rate is the same). The rule reads the draft's side only -- the laws the rounds drew from and, for `path`, the tokens drawn before the one a decision admits -- never the target and never the admitted token itself, so the row-wise and the traversal verify stay exact (`core/sched/draft_depth.h` has the argument, `tests/mtp_rrs_test.cpp` the chi-square and the two rules that fail it). A greedy request has no law to read and drafts min(3, N). Shutdown logs the depths taken, and per depth the card's cycle and the drafts its verify accepted (`draft depth adaptive (final)`). On Qwen3.8-Flash-Next (2x R9700, traversal verify) a cap of 5 at stop 0.85 took 2.79 tokens a step where the fixed chain of 3 took 2.70, at the same mean of 3.0 drafts and a step 0.7% longer: +3.0% tokens a second (95% interval +1.0 to +5.0%) over temperatures 0.7 and 1.0; a cap of 7 gained no more, a deep verify row costing more than a shallow one. The stop is not sensitive between 0.80 and 0.90. The engine keeps 48 recorded passes instead of 24 (an adaptive chain makes more pass shapes than 24 hold: 3352 recordings per benchmark became 1472, +1.7% tokens a second for this mode); the other modes touch no more than they did. **SuffixDecoding as a step selector: `draft-suffix`.** `draft-suffix: on` (default off, which is the engine as it was, bit for bit) lets a serial head's chain give a step to the sequence's own history. After each commit the engine looks, in the sequence's prompt and output, for an earlier occurrence of its last `draft-suffix-min-match` tokens (default 6; the longest of that length and three more wins, the latest occurrence of it). If there is one, the next step is a pure verify of what followed it (a chain of at most `draft-suffix-max` rows, default 7) in place of the head's draft, cut where the path score falls under `draft-suffix-min-score` (default 0.3): SuffixDecoding's frequency rule (Oliaro et al., arXiv 2411.04975), the product along the chain of how often that token followed that context in the history. Otherwise the step is the head's, as before. It pays where the reply copies its context (code edits, quoting, agent and tool loops, pasted text, structured output) and does nothing on free chat. A cross-request suffix tree adds nothing on such loads and is not built. It works with the normal fixed MTP chain, with `draft-depth: adaptive` (the adaptive chain stays within the head's `num-speculative-tokens` rounds; the suffix window only widens the verify) and with `draft-verify: traversal` (a suffix row carries no coupled state, so it is a leaf of the walk). It is refused with `draft-verify: block` (the block verify decides a head chain as a whole), with `draft-window: adaptive`, and on a block drafter. How it is built: the verify window (`num-speculative-tokens` for every buffer, ring and kernel band) becomes `max(num-speculative-tokens, draft-suffix-max)` while the head keeps drafting its own `num-speculative-tokens` rounds, so the head's passes (and `draft-coupling`'s draws) do not change. A suffix step is built after the commit, where the lookup can read the committed end, so a sequence whose history ended in a recurring pattern at the last commit is **not issued ahead** (the step ahead is made on the card from the head's drafts, before the commit; deciding on the last readback costs one step of lag when a copy starts and one built-after-commit step when it ends, where the card-side alternative would need a per-sequence token history and a hash table in the advance kernels). The head still drafts behind every step, a suffix step included: its history pass covers all 1 + rows positions the step verified, so the head's cache has no hole behind it and its next draft is as good as after a head step; the draft pass behind a suffix step is the price of that. Exactness: the choice reads the committed text and nothing else, never a draw. A suffix step carries no coupled row (`Request::draft_suffix`): the sampler binds none of the head's staged states to its rows (a proposal that equals the head's unused draw `x` would otherwise select the coupling by the value of that draw). Each row is the target's plain draw from `(seed, position)` and the walk follows the proposal iff the draw equals it: greedy text is the head-only run's (up to the last-bit differences a different row count makes to the logits, as between any two window sizes) and the sampled law is the target's. `tests/mtp_rrs_test.cpp` checks the law (chi-square over the first three tokens, alone and mixed with adaptive-depth steps, under the row-wise and the traversal verify, with a negative control that exposes the variant in which the coupled rows see the suffix chain), `tests/sched_test.cpp` the selection, the issue-ahead rule and the head's catch-up, `tests/arch_test.cpp` the issue pattern of a nine-row verify. The window is bounded by the model's kernels: Flash-Next's fused conv + recurrent update serves at most 8 query rows (a register window), so `draft-suffix-max` is at most 7 there; a larger window makes the first step fail with `unsupported`. `/metrics` has `radiance:suffix_steps_total`, `suffix_rows_total`, `suffix_accepted_total` and `suffix_held_ahead_total`. ```yaml num-speculative-tokens: 3 draft-coupling: on draft-suffix: on draft-suffix-min-match: 6 draft-suffix-max: 7 draft-suffix-min-score: 0.3 ``` **Chained launches.** Where the model's plugin measured its step faster with them, the AQL backend lets a kernel that depends on the one before it on its queue wait in its own prologue instead of behind the packet processor's barrier bit, which saves most of the launch gap between dependent kernels. The bytes are the same. Qwen3.8-27B, the dense Gemma 4 models (31B, 12B and the E-series) and Qwen3.8-Flash-Next take them with and without a drafter; the Gemma 4 26B-A4B takes them while its DFlash drafter decodes. The wait behind the barrier bit is about 3 us after a short kernel and about 15 us after a long one, so the dense models gain most: on two R9700 a Qwen3.8-27B IQ8R step under DFlash2 went from 36.5 to 26.5 ms and a Gemma 4 31B int8 step under its assistant head from 42.1 to 31.2 ms (w4a8: 32.3 to 20.4), each to a pass with almost no time in which nothing runs. A Flash-Next pass is about 930 short launches, nearly all dependent: chained, a full pass under the draft head went from 13.9 to 12.5 ms. The plain-bf16 plugins of the small models take them as well: on one R9700 a Qwen3.5-0.8B step went from 3.89 to 3.60 ms, the 3B LFM2's from 12.14 to 11.31 and Unlimited-OCR's from 2.79 to 2.49. They stay off on every other model; the startup report's `chained launches` row says which and why. Where two models of more than one card share their cards, a launch behind a collective keeps its barrier bit (about 1% of a step; MULTIMODEL §9.1). A chained kernel acquires in its own prologue, behind its wait, so its packet goes out without the packet processor's acquire where every kernel library the engine loaded says its chained forms cover all they read there (`rad_kernel_chain` answering 2: libr4d's do, by emptying the scalar data cache behind the fence). That acquire holds the packet processor about 0.9 us a launch on an R9700 and comes before the kernel in front has written, so it guards nothing the launch reads. It did give the arguments the host had just written into VRAM the time to get there; the backend now sees to that itself and flushes the card's host data path in front of every doorbell, for every launch (a card that offers no flush register keeps the acquire). The log line `chained launches: on` says whether the packets take the acquire. `RADIANCE_AQL_CHAIN_FENCE=1` puts it back, to rule the change out. **Draft trees.** Where the model's plugin measured a gain (the Gemma 4 31B with DFlash2: +7% single-stream decode and +6-9% aggregate at 1-16 users on 4x R9700, +4% and +6-12% on two, BetterBench with thinking off), a block drafter's proposals are verified as a tree: grown best-first over the drafter's candidates, the deepest path the target agrees with is accepted, and its K and V move into place. A tree changes no token, only how many drafts land a step; the startup report's `draft trees` row says when it is on. Under a tree `num-speculative-tokens` counts the tree's nodes, grown over the block the drafter was trained at. A request with a grammar (`response_format`, tools) speculates on a tree too: each row is masked against the grammar after its own ancestors. `draft-coupling: on` samples one path, so a coupled drafter proposes the chain. **A shorter block under load: `draft-short-from: N`.** A block drafter's block is paid for by every drafting sequence, whatever each one verifies. At one sequence a long block pays; at many, its drafter rows and its weaker first positions cost more than the extra drafts bring. A drafter that also serves a shorter block declares it (PLUGIN.md §11); DFlash2 declares a block of 4 (3 drafts) wherever its own is longer, on `qwen35_fp8` and `gemma3`, and the Gemma 4 31B's block-16 DFlash2 drafter, as a tree of 15 nodes, a block of 8 (a 7-node tree over it). With `draft-short-from: N` the engine runs that short block once N sequences decoded in the step just run, and the drafter's own block again once the count falls two below N or to one sequence, where the long block pays. From N of 3 on, a load wavering at N does not change the pass shape every step; at 2, a load between one and two sequences does, which costs only the other shape's pass. `0` never switches. `auto`, the default, never switches a chain and switches a tree drafter from 2: a tree's nodes are verify rows every drafting sequence pays for, which a wide tree's extra nodes repay at one sequence and not at many; it switches back at one decoding sequence. At the short block the drafter grows a tree of its own over the shorter pass, at most `block - 1` nodes. Startup names what it will run: ``` speculation: from 16 decoding sequences on, 'dflash2' runs its short block of 4 row(s), 3 token(s) ``` or warns that the drafter declares no shorter block, is a serial head, or that none runs. The block driver runs the short block on the card as it runs the drafter's own: the query pass is the shorter batch, each row's proposals are the front of the drafter's proposal row, and the step issued ahead verifies that many. Qwen3.8-27B MXFP4 + DFlash2 on two R9700s, `num-speculative-tokens: 7` at the fixed window, a one-byte KV cache, sampled (temperature 1.0), medians of six rounds at 8 streams and three at 16-64, tok/s: | streams | unset | `draft-short-from: 8` | |---|---|---| | 8 | 652.8 | 696.8 | | 16 | 751.9 | 945.6 | | 32 | 985.7 | 1070.8 | | 64 | 1055.0 | 1334.6 | Below N the engine runs the drafter's own block, the same shapes as with the key unset (greedy, six rounds: 1 stream 183.4 and 183.1, 4 streams 529.1 and 537.2). Set it to 8 for a server that decodes eight or more sequences at once. The drafts are verified as any others; as with `num-speculative-tokens`, a different block is a different verify shape, so greedy text can differ at a near-tie. ### 4.7 Multiple cards ```yaml models: m: model: m.rad tp: 2 # tp-wire: wht6 # the lossy wire, for messages of 128 KiB and more # tp-wire-min-kb: 128 ``` `tp-wire` chooses the all-reduce payload. `exact` (default) is bf16. `wht6` is lossy: a Walsh-Hadamard-rotated 6-bit payload, 2.4x smaller over PCIe. The sum a rank receives is then not the exact sum and nothing downstream can detect it, so it is an explicit setting. `tp-wire-min-kb` is the size below which messages stay exact; 128 KiB keeps single-sequence decode exact and compresses prefill. `tp-attn-split: rows` runs a prefill-sized step's attention by rows: each rank takes its run of the step's rows with every head, and an `all_gather` of the runs replaces the all-reduce. Where the attention dominates a prefill that is faster, but every card then holds the attention's projections at full width, and the result is not bit-identical to the default `heads` split. Only a plugin that declares the row split takes it (GLM-5.3: +18 to 21 % prefill at eight ranks for 1.29 GiB a card, a mean KL of 0.038 against `heads`, docs/ARCHITECTURES.md); elsewhere, and at `tp: 1`, the key stops the start by name. At three and four ranks `wht6` selects tiered int8 over a two-shot all-reduce, both hops quantised (at three ranks the shards are whole 32-element groups, one uneven where the message does not divide), with the same floor. Eight ranks have no lossy wire; `tp: 8`, `tp-wire: wht6` stops at startup naming the all-reduce it found no kernel for, and `tp-wire: exact`. The exact wire is one-shot for small messages and two-shot above, which sends 2·(ranks−1)/ranks of the message per rank instead of (ranks−1) times it, with the same bits. At three ranks the one-shot runs up to 1 MiB a message; at four it hands a message of 32768 elements (64 KiB of bf16) or more to the two-shot, so a verify step's reductions take it too; at eight the one-shot's seven copies lose early, and it ends at 8192 elements (16 KiB of bf16). On a model with a gated residual (Qwen3.8-Flash-Next) the all-reduce runs inside the residual's write, with the MoE gather in front of it. At two ranks the rotated forms of `ar_hc_write` and `ar_gather_hc_write` produce the same bytes as the unfused chain on either wire; there `wht6` gains 5.6–6.3% of prefill at a 2048-token chunk (20K prompt 5556 to 5908 tok/s; a 23K extension at 81K depth 4998 to 5278) and 1.3% of the eight-stream decode step, and one-stream decode stays exact. At four ranks only the exact wire has a fused form, used for decode and verify steps of up to `max-num-seqs` x (1 + `num-speculative-tokens`) rows; prefill chunks and tiered-int8 messages run the unfused chain. **Cards without peer access.** The all-reduce kernels normally write into the other card's memory directly (P2P). At launch radiance asks the driver whether each pair of cards can, and logs the answer; the IOMMU setting, the PCIe topology and any switch between the cards decide. Where a pair cannot, the same kernels run with their exchange buffers in pinned host memory: each card writes its share to host RAM over its own link and reads the others' back. The startup line names the failed pairs, and the selection report names the `_host` rows that took the collectives. The results are the same bytes; a message crosses two links instead of one. On two R9700s on PCIe 4.0 that is within run-to-run noise for decode at one and four streams, and 2–10% on a 23.6K-token prefill, since there the peer link is no faster than the host link. Cards whose host link is narrower than their peer link pay more. `p2p` overrides the driver. `off` takes the host-memory path even where the driver reports peer access, for a board where peer traffic is broken or slow. `on` requires peer access and stops at startup, naming the pairs, if the driver refuses any. `auto`, the default, trusts the driver. **Eight cards on unequal links.** In the two-shot rank r reduces shard r of the message, and every rank's link carries at least the whole message each way whatever its shard, so the slowest link sets the time of every prefill all-reduce. On a board whose slots differ (here eight R9700s: four at Gen5 x16, two at Gen5 x8, two links that trained at Gen4 x8) the eight-rank two-shot does two things from 262144 elements (512 KiB of bf16) up: - it weights the shards by link: a rank on a slow link reduces a short shard, or none; - it runs the message in pieces, so one piece's second hop shares the link with the next piece's first, both directions at once: 2 pieces under 1048576 elements, 4 under 4194304, 8 above. Every word is still folded in fp32 in ascending rank order whoever reduces it, so the bits are those of the even split. Below that size a decode step's message runs even and in one piece: there the extra handshakes cost more than the link time they save. The weights come from the links. At startup each rank reads its card's PCIe path in sysfs from the root port down and takes the slowest hop (the R9700's on-card switch reports full speed in any slot, so a degraded slot shows only at the root port); its weight is round(4·(rate/fastest)²), so x16 is 4, half the rate 1 and a quarter 0. Equal links give equal weights and the unweighted kernel. One line names what was read: ``` [r4d] eight-rank two-shot shard weights from the slowest PCIe hop of each card: r0 32.0 GT/s x16 63.0 GB/s w4, r1 32.0 GT/s x8 31.5 GB/s w1, r2 16.0 GT/s x8 15.8 GB/s w0, ... ``` `r4d_selftest --perfar8 0` prints the same weights and times both rows at every piece count, each checked against the fold (warm, the slowest rank): | message (bf16) | even, one piece | weights 4,1,0,4,0,1,4,4 | |---|---|---| | 196608 elements (384 KiB) | 73 µs | below 262144: even, one piece | | 524288 (1 MiB) | 214 µs | 166 µs in 2 pieces | | 2097152 (4 MiB) | 699 µs | 531 µs in 4 pieces | | 8388608 (16 MiB, a 2048-token chunk at 4096 wide) | 2841 µs | 1636 µs in 8 pieces | With the two Gen4 links retrained to Gen5 x8 the weights read 4,1,1,4,1,1,4,4 and the 16 MiB message takes 1360 µs. That is 56% of the time the x8 cards' links need for its bytes (763 µs). `--perfar8 N iters bf16 lockstep,ring,split` times three forms of the two-shot side by side, all with the same bits: `lockstep`, the engine's, as above; `ring` sends the first hop to the other cards in ring order from the next rank, so no card receives from all seven at once; `split` does that and replaces each step's handshake, which waits for every card to finish the whole step, by a flag after each half of it, awaited only where its data is read. On this board ring takes 2-6% less time for 8 and 16 MiB messages, but serving GLM-5.3-Flash at TP8 split (ring order included) moves neither prefill nor decode beyond run-to-run noise, so the engine stays in lockstep. `--timeline` adds every rank's first push, each step's work and wait and the final assemble, which in one piece are the reduce-scatter and the all-gather apart. `R4D_SELFTEST_ONE_CARD=1` runs the eight ranks on one card, for their bits only, in `--perfar8` and in the eight-rank exact all-reduces' cases of a plain `r4d_selftest` run. The links are read once, at startup: a link that drops to a lower speed while the server runs keeps its weight until the next start. Messages under 262144 elements run even and in one piece. `--perfar8` also prints the duplex model's table (`r4d_ar_weights_duplex`), which weights the links so that every link's busier direction carries the same time's bytes when both directions run at once: on four Gen5 x16 and four Gen5 x8 links 64 and 8, a link time 10% under the `auto` weights' (a Gen4 x8 link gets 0). The engine does not use it: on this board those weights lost their lead within a timing run and served no faster. `r4d_selftest --perfar8 --ar8-weights W0,..,W7` times other weights on another board (`off` for even shards). ### 4.8 Host tier for finished conversations By default a finished conversation's KV blocks stay in VRAM, held by the prefix cache, until evicted under pressure; an evicted prefix is re-prefilled next turn. With a host tier, a conversation is copied to host memory when its request finishes and keeps its VRAM copy. Its VRAM can then be given up at no cost, and is, as soon as something wants it (the expert slab's loan, or a request the pool cannot otherwise serve). A conversation that returns before that resumes from VRAM; one that returns after is restored from host memory and keeps its host copy, so its next turn copies only what that turn added. A full host tier drops its least recently used conversations. Nothing is written to a drive. A restore is one of the requests VRAM is given up for. The cache keeps a quarter of the pool free after each turn, and a returning conversation larger than that takes the VRAM copies of other stored conversations too, the way an admission under pressure does: those with a host copy first, then those whose copy was still on its way, once it lands. Nothing is lost by it, since each keeps its host copy, and it never takes the returning conversation's own blocks, a conversation a running request reads, or one a waiting request has just brought back. A turn that has just finished holds its blocks until the next step, so a conversation returning right behind it waits that one step before it settles for less. Only when the pool cannot hold the whole conversation even then does it come back in part, and on a hybrid model it then ends at the deepest snapshot it reaches, where its next turn resumes; `radiance:prefix_restore_cuts_total` counts these (`/sessions` `moved.restore_cuts`). Every stored conversation expires: one unused for `prefix-cache-ttl` seconds is removed from whichever tier holds it (VRAM blocks to the pool, host slot to the arena, snapshots to the store). A hit or a new turn counts as a use, and a system prompt shared by several conversations stays while any of them is used. A client that knows a conversation is dead need not wait for the TTL: `DELETE /sessions/