Archived
radiance 1.13.0
New models: - Tencent Hy-Memory (HYV3) from its BF16, FP8 and GGUF checkpoints, with its native tool calls - M2XFP4: metadata-augmented MXFP4 weights for Qwen3.8-27B and its DFlash2 drafter (top-1 89.1% -> 92.4% against plain MXFP4), its quantiser and recipe, and ParoQuant's M2XFP4 checkpoints - Gemma 4 E2B/E4B audio input; NVIDIA-Nemotron-3.5-Bolt-E4B in int8 and 4-bit, on two cards by default; Ornith-1.5-122B compose files Speed: - Weight reads beside the decode all-reduces (qwen35_fp8, gemma3; --weight-prefetch, on by default): the 27B MXFP4 with DFlash2 61.2 -> 67.9 tok/s at c1, TranslateGemma 27B +13% - Head-256 split-KV decode attention at 256 workgroups and without bank conflicts (27B: +3-5% a step at 25-41K context), and the prefill KV split for small launches (a short turn over a long context decodes the other sequences 27% faster in that step) - MXFP4 decode gate_up, activation and fp8 quantiser in one launch (27B, Gemma 3 up to 64 rows: TranslateGemma +2-5% at 2-8 streams) - ParoQuant int4/int5 tiled GEMMs 6-9% faster - Speculation: a step's tokens are sent before the drafter's passes end, no step waits behind one that ends its requests, and the MTP head's first draft no longer collapses after short chats in the prefix cache Features: - --kv-resident N: KV streaming for a context bigger than VRAM (qwen4exp_fp8, GLM-5.3) - MiniMax-H3: reference media and keyframe conditioning with the VAE encoders - Krea 2 rebalance presets balanced, detail and subtle - The dashboard's request history; a stall watch that reports a frozen step's thread and stack - rad-tune at the served configuration, collectives measured as the exchange; Gemma 4 E2B/E4B's per-layer embeddings read ahead off the step path - A GPTQ calibration tap and recipe for Gemma 4 31B's w4a8 container Fixes: - The two-rank all-reduce checks that a peer's push has landed before reducing it - z-lab's DFlash drafter on Gemma 4 31B keeps drafting after a prefix-cache hit - MiniMax-H3's modulation rows Changes: Plugin ABI 31: out-of-tree plugins must be rebuilt. RADIANCE_PREFETCH_BESIDE is --weight-prefetch now; RADIANCE_NO_HUGE_PAGES, RADIANCE_IDS_EARLY, RADIANCE_ATTN_BAND_SPLIT, R4D_PREFILL_SPLITS, RAD_PLE_TIMING and RAD_PLE_CACHE_ROWS are gone.
This commit is contained in:
commit
6645337f69
198 files changed
+20904
-3240
No files matched your search
+24
-9
@@ -33,7 +33,7 @@ plugin claims.
|
||||
| `arch/minimaxmusic3` | `minimaxmusic3` | *(empty)* | MiniMax-Music3, songs from a description and lyrics: a Qwen3-8B frame model, a depth decoder, a flow-matching DiT and a DAC vocoder, from the diffusers pipeline directory, bf16 |
|
||||
| `arch/breeze` | `breeze` | *(empty)* | Breeze-TTS-2, speech from text and a description of the voice: a T5Gemma 2 text encoder, a Qwen3 backbone with a 16-codebook depth decoder and the Qwen3-TTS 12 Hz codec, from the release directory, bf16, one card |
|
||||
| `arch/fishomni` | `fishomni` | `bsgemm-moe` | Fish Audio drama-3, speech from text with speaker tags and inline direction, its voices cloned from reference clips: the Qwen3.5-35B-A3B backbone with its routed experts block fp8 at f32 scales and everything else bf16, a 13-layer codebook tower over the backbone's full-attention cache, and Fish S2's modified DAC, encoder and decoder (`codec.pth`, read as data); from the release directory, two cards |
|
||||
| `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`) |
|
||||
| `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text, between keyframes or from reference media: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`), or the DiT's per-token linears int8, served w8a8 (`minimax-h3-w8a8.recipe`); a curve-form checkpoint, whose timestep embeddings ship as a table, by the `minimax-h3-curve-*` recipes |
|
||||
| `arch/ltx2` | `ltx2` | *(empty)* | LTX-2.5 (base and distilled), a video with its stereo soundtrack from text or from text and a first frame: Gemma 4's language model and two text connectors, the duration head, a dual-stream audio-video DiT with four-way guidance, the causal video VAE (tiled past the default canvas) or the diffusion decoder, the audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; bf16 or block fp8, one card |
|
||||
|
||||
The traps below are readings that are wrong without any error: the model produces fluent output.
|
||||
@@ -1868,13 +1868,14 @@ a frame with the codec), a paragraph at 0.29 (11.6 s in 3.34 s); a stream's firs
|
||||
# `minimaxh3`: MiniMax-H3, video with sound
|
||||
|
||||
`arch/minimaxh3` declares a video generator (`rad_declare_video_generator`), which makes the
|
||||
program a four-pass one the engine drives through `core/gen/video_driver.h`: VCOND runs the text
|
||||
encoder and the refiner over the prompt and computes every step's modulation, VSTEP is one
|
||||
denoising step of one request's packed sequence, ADECODE plays the soundtrack, VDECODE decodes
|
||||
one temporal chunk of frames. A request is a lane; two hold state at once (one denoising, one
|
||||
conditioned and waiting). It is served on `/v1/videos` ([GUIDE §5.16](GUIDE.md)), block fp8 on two
|
||||
cards with `--vision-tower-placement ram`. The checkpoint is the diffusers pipeline directory,
|
||||
read as one; only workflow t2va is served.
|
||||
program one the engine drives through `core/gen/video_driver.h`: VCOND runs the text encoder and
|
||||
the refiner over the prompt and computes every step's modulation, VSTEP is one denoising step of
|
||||
one request's packed sequence, ADECODE plays the soundtrack, VDECODE decodes one temporal chunk of
|
||||
frames; with keyframes or reference media, VENCODE and AENCODE first run each through the video or
|
||||
the audio VAE's encoder into the lane. A request is a lane; two hold state at once (one denoising,
|
||||
one conditioned and waiting). It is served on `/v1/videos` ([GUIDE §5.16](GUIDE.md)), block fp8 or
|
||||
int8 on two cards with `--vision-tower-placement ram`. The checkpoint is the diffusers pipeline
|
||||
directory, read as one; the workflows t2va, i2va, l2va, fl2va and ref2va are served.
|
||||
|
||||
```
|
||||
text Qwen3-VL-32B's language model: 64 layers of 5120 (64 q / 8 kv heads of 128, ff 25600,
|
||||
@@ -1907,6 +1908,16 @@ VAE 2 2 2), each followed by the mean of three AMP blocks (k 3/7/11, dilat
|
||||
channel, clamped. 800 samples a latent, 32 kHz, each stereo channel its own sequence
|
||||
length 24 fps; a video of n chunks is 17 n + 5 frames over 5 n + 2 latent frames, n 7..20
|
||||
(5.17 to 14.4 s); the soundtrack is round-half-even(frames x 40 / 24) latents a channel
|
||||
encoders the video VAE's: six levels of two causal 3x3x3 residual blocks (GroupNorm 32), four
|
||||
strided downsamplers, 17-frame clips to 5 latent frames, reflect padding; the audio
|
||||
VAE's: a DAC encoder (strides 2 4 4 5 5) and a causal attention block, 800 samples a
|
||||
latent, a channel at a time. Latents normalised as the decoders read them
|
||||
pack with references the sequence is [text | keyframes | references | soundtrack | video]
|
||||
(arch/minimaxh3/rad_ref2va_pack.h, ComfyUI's PackedLayout): a reference in its own
|
||||
latent grid on a clock before the video's, a keyframe at its frame of the video. Their
|
||||
rows take a timestep pinned at max(t, 0.999) (1.0 for sound), and the sampler steps only
|
||||
the last two segments. Each segment is its own attention sink; a run of segments with
|
||||
the same modulation is one group of the modulation table, eight at most
|
||||
```
|
||||
|
||||
Traps:
|
||||
@@ -1918,10 +1929,14 @@ Traps:
|
||||
embedding reads t in [0, 1] as it is, not scaled to 1000.
|
||||
- **The grid's second half is linspace's from the end**: torch computes `linspace(1, 0, N)` half
|
||||
from each end in f32, which `gen::video_schedule` reproduces.
|
||||
- **The packed rows' positions are f64 rounded to f32**: a latent frame spans 5/3 x (1, 4, 4, 4,
|
||||
- **The packed rows' positions are f64 rounded to f32** (ComfyUI's arithmetic, tested against its
|
||||
own numbers in tests/data/ref2va): a latent frame spans 5/3 x (1, 4, 4, 4,
|
||||
4)[i mod 5] time units from `n_text`, the spatial axes are each side's latents over the square
|
||||
root of the frame's area, centred on the unit interval, times 32, and the soundtrack's two
|
||||
channels sit at the two ends of the width axis.
|
||||
- **The video encoder's shortcut convolves the block's raw input**, before norm1 normalises it in
|
||||
place; and the audio encoder's attention block feeds its qkv from norm1 but its projection
|
||||
from norm3. Either swapped shrinks every latent after it.
|
||||
- **A tile is blended with its neighbours as they were decoded**: the vertical blend reads the
|
||||
original tile above, and the horizontal blend the original tile to the left, not the blended
|
||||
ones. Chunks keep frames [3, 20) of their 28 and blend their last 5 linearly into the next
|
||||
|
||||
@@ -189,3 +189,8 @@ Every model listens on the same port and most take both cards (`flashnext-tp1.ya
|
||||
`ornith-1.5-122b*.yaml` files four, `glm53-flash.yaml` eight), so run one at a time: `down` one before `up` on another. The server runs as the host user given in `.env`. `/health`, `/ping` and
|
||||
the dashboard page answer without the API key, and the health check fetches `/health` with
|
||||
busybox's `wget`.
|
||||
|
||||
A container serving MiniMax-H3 also serves ComfyUI's Radiance MiniMax node
|
||||
(`integrations/comfyui/ComfyUI-Radiance-MiniMax`), a client of `/v1/videos`. With
|
||||
`--lora-dir /models/loras/h3` in the command, the node's adapter lists show the files under
|
||||
`$RADIANCE_MODELS/loras/h3`.
|
||||
@@ -19,9 +19,8 @@ with the int4 codes chosen by GPTQ against the bf16 model's own activations.
|
||||
its block (`.part`), which libquant places on the diagonal.
|
||||
2. **The convert.** `CALIB=DIR rad-convert` with the recipe: libquant's `gptq` on the trunk's four
|
||||
linears, everything else as the -df2 recipe makes it. libquant factors each Hessian through
|
||||
OpenBLAS's LAPACK where the build finds OpenBLAS (the container image does once libopenblas-dev
|
||||
is in its build stage, a separate change); without it, libquant's own single-threaded loops take
|
||||
hours for each 21504-wide down projection.
|
||||
OpenBLAS's LAPACK where the build finds OpenBLAS (the Docker image has it); without it,
|
||||
libquant's own single-threaded loops take hours for each 21504-wide down projection.
|
||||
|
||||
The w4a8 container's own plugin cannot record them: its linears read int8 activations, which
|
||||
`gram_accum` does not take, and a quantised container's activations would come through its
|
||||
@@ -43,7 +42,7 @@ and the other 2.47M tokens (4,252 conversations) is the calibration corpus.
|
||||
| reasoning | 417K | 285 | rStar-Coder (CC-BY-4.0) prompts, the 31B's replies |
|
||||
|
||||
The held-out tenth (305K tokens) is never fitted to; 44.5K tokens of it are the KL mode's corpus
|
||||
below. BetterBench's corpora, on which the stall was found and is measured, are in neither.
|
||||
below. BetterBench's corpora, on which the stall is measured, are in neither.
|
||||
|
||||
## Running it
|
||||
|
||||
@@ -141,7 +140,7 @@ on BetterBench's 7 multi-turn conversations is the same: first turns 159.6 tok/s
|
||||
thinking off, the two containers served at once and the card pairs swapped for a second run (both
|
||||
runs given):
|
||||
|
||||
| | main's container | this one |
|
||||
| | RTN | GPTQ |
|
||||
|---|---|---|
|
||||
| multi-turn: the right tool | 15/18, 15/18 | **18/18, 18/18** |
|
||||
| multi-turn: a turn after the tool's result | 16/21, 17/21 | **18/18, 18/18** |
|
||||
|
||||
+153
-14
@@ -962,6 +962,80 @@ speculation f16 also changes which drafts the greedy text accepts, so one and fo
|
||||
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
|
||||
|
||||
```sh
|
||||
radiance --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.00 KiB a token a rank at fp8 on
|
||||
two ranks: 192 MiB at 32 768), the prefill stage, one layer of the retained context (512 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`) and GLM-5.3-Flash (`glm5next`), with a bf16 or fp8
|
||||
cache. Anywhere else the flag is ignored with one warning and every block stays on the card;
|
||||
so is a packed cache (`--kv-cache-dtype fp8_v4` or `k6_v4`).
|
||||
- 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, fp8 | 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
|
||||
flag. `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
|
||||
@@ -1413,6 +1487,9 @@ radiance --model m.rad --prefix-cache-mib 8192 --prefix-cache-ttl 3600
|
||||
gives the rest up; the startup log warns when the tier holds less than one `--max-model-len`
|
||||
conversation and says how many MiB would, and a `kv tiers: ... got no host copy` line appears when
|
||||
it happens (`/sessions` `moved.held_back`).
|
||||
While a KV group streams (`--kv-resident`), the tier is off and its MiB are not reserved: a
|
||||
cached conversation holds the streamed group, whose rows are its pinned mirror at the
|
||||
conversation's block ids and cannot move to a host slot (`docs/KV-STREAMING.md` §3.8).
|
||||
- `--prefix-cache-ttl S`: seconds an unused conversation is kept (default 3600); `0` keeps it until
|
||||
the memory is wanted.
|
||||
|
||||
@@ -1615,6 +1692,10 @@ below.
|
||||
unload while serving: `POST /v1/load_lora_adapter {"lora_name": "x", "lora_path": "/dir"}` and
|
||||
`POST /v1/unload_lora_adapter {"lora_name": "x"}` (vLLM's routes; loopback-only without
|
||||
`--api-key`).
|
||||
- On a video generator the slots come out of what its largest step leaves of the card, which
|
||||
`--max-num-batched-tokens` cannot lower. MiniMax-H3 on two 32 GB cards has room for one slot at
|
||||
rank 16 (265 MiB a card), two only when no other process holds VRAM on them; past that the
|
||||
start stops with `vram_kv resolved to 0 MiB`.
|
||||
- An unload of an idle adapter answers 200 and frees its slot. An unload of an adapter requests
|
||||
are still using **drains** it and answers 202
|
||||
`{"action": "draining", "lora_name": "x", "in_flight": N}`: from then on a request naming `x`
|
||||
@@ -1802,6 +1883,7 @@ by 0.002-0.003 nats.
|
||||
| `--state-cache-dtype T` | f32 | `f32` or `f16`: the recurrent (delta-net) state cache; f16 halves the state memory and is lossy, `qwen35` plugins only (§4.4) |
|
||||
| `--attn-prefill-fp8 MODE` | off | `off`, `qk`, `pv` or `both`: the prefill attention's Q·Kᵀ, P·V or both in E4M3 over an `fp8`, `fp8_v4` or `k6_v4` cache; lossy, Qwen3.8-27B (§4.4) |
|
||||
| `--host-pool-mib N` | 0 | pinned host tier (weights) |
|
||||
| `--kv-resident N` | 0 (off) | stream the sparse attention group's KV from pinned host memory, keeping a ring of N tokens on the card. Raised to 32 768 and to one decode step's selection; a ring that covers the context streams nothing. Ignored with a warning on an architecture that cannot stream (§4.4.1, [KV-STREAMING.md](KV-STREAMING.md)) |
|
||||
| `--host-headroom-mib N` | 4096 | host RAM left free for the system when startup pins host memory — kept for the unpooled allocations, staging and page cache (§4.3) |
|
||||
| `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card (§4.3) |
|
||||
| `--ngram-placement WHERE` | auto | `auto`, `vram`, `ram` or `disk`: an n-gram table on the card, as a copy in RAM made at load and read by the card, or read from the container (§4.3) |
|
||||
@@ -1844,6 +1926,7 @@ by 0.002-0.003 nats.
|
||||
| `--tp N` | 1 | tensor-parallel ranks |
|
||||
| `--tp-wire MODE` | exact | `exact` or `wht6`, the lossy wire (§4.7) |
|
||||
| `--tp-wire-min-kb N` | 128 | smallest all-reduce, in KiB, the lossy wire is used for |
|
||||
| `--weight-prefetch MODE` | on | `on` or `off`: whether a plugin reads a GEMM's weight into the cache beside the collective before it, at decode heights. `off` for an engine that shares its cards with another server (§8, two engines on one set of cards); alone it costs a few percent of decode |
|
||||
| `--tp-attn-split MODE` | heads | `heads` or `rows`: how a prefill-sized step's attention splits over the ranks, on a plugin that serves the row split (§4.7) |
|
||||
| `--p2p MODE` | auto | `auto` asks the driver, `on` requires peer access, `off` exchanges through host memory (§4.7) |
|
||||
|
||||
@@ -2955,7 +3038,8 @@ curl -s http://localhost:8000/v1/videos/video_.../content -o fox.mp4
|
||||
```
|
||||
|
||||
- **`prompt`** is read as written, with no template; MiniMax-H3 was trained on long structured
|
||||
descriptions (a shot, its soundscape, its music), which follow it best. At most 2048 tokens.
|
||||
descriptions (a shot, its soundscape, its music), which follow it best. At most 8192 tokens,
|
||||
the vision tokens of any reference pictures included.
|
||||
- **`seconds`** is rounded up to the model's length steps (17 frames, 0.71 s, at 24 frames a
|
||||
second): 5.17 to 14.4 seconds, 5.17 by default. The video object's `seconds` is what is made.
|
||||
- **`size`** is the frame's `WIDTHxHEIGHT`: both sides multiples of 32 from 256, at most
|
||||
@@ -2967,8 +3051,39 @@ curl -s http://localhost:8000/v1/videos/video_.../content -o fox.mp4
|
||||
evaluations, by default; at most 65). The model is guidance-distilled, so there is no guidance
|
||||
scale and no negative prompt. A step-distilled release (FastH3, below) runs only the schedule it
|
||||
was trained on: 9 grid points, and any other count is refused with a 400.
|
||||
- Only text is read: `input_reference` and non-empty `conditions` are refused, as is a `task`
|
||||
other than `t2va`. Fields are JSON or a multipart form (OpenAI's clients send the form).
|
||||
- **`sampler`** is `euler` (the default) or `res_multistep`, the second-order step on the clean
|
||||
estimate (k-diffusion's, as ComfyUI workflows for the model use it). **`shift`** and
|
||||
**`audio_shift`** replace the shift of the video's and the soundtrack's sigma grid, each in
|
||||
(0, 100]; the model's own are `video_shift` and `video_audio_shift` in its capabilities.
|
||||
- Fields are JSON or a multipart form (OpenAI's clients send the form); media come as form file
|
||||
parts. `input_reference` and non-empty `conditions` are refused.
|
||||
|
||||
**Keyframes and reference media.** A container converted with the VAEs' encoders (every pipeline
|
||||
directory since the ref2va release ships them; the recipe says how to add them to an older
|
||||
container) also makes a video between keyframes or from reference media; `task` may name the
|
||||
workflow, and is otherwise read off the parts:
|
||||
|
||||
- **Keyframes**: a `first_frame` (`i2va`), a `last_frame` (`l2va`) or both (`fl2va`), each an image
|
||||
pinned at that end of the video. The first frame is stretched to the video's size, or, with
|
||||
`"first_frame_mode": "center"`, scaled to cover it and cropped at the centre; the last frame is
|
||||
always cropped. A keyframe request takes no `latent_upscale`: the pins are on the video's own grid.
|
||||
- **Reference media** (`ref2va`): `ref_image_1` .. `ref_image_9`, `ref_video_1` .. `ref_video_3`, each
|
||||
video with an optional soundtrack `ref_video_audio_N` of its own number, and `ref_audio_1` ..
|
||||
`ref_audio_3`, numbered from 1 without gaps. Pictures and video frames are fitted into 256 x 256
|
||||
and a video keeps at most 289 frames, soundtracks at most 15.6 s. The pictures are shown to the
|
||||
text encoder as well, as `<Picture N>` in front of the prompt, so the container needs its vision
|
||||
tower for them.
|
||||
|
||||
A request carries keyframes or reference media, not both. `capabilities` reports the counts a
|
||||
model takes (`video_max_ref_images` and the rest). Every reference adds rows to each step, so
|
||||
many large ones may need a larger `--max-model-len`; a request that does not fit, or whose
|
||||
references alternate kinds too often for the model's modulation table (group them by kind), is
|
||||
refused naming why.
|
||||
|
||||
```sh
|
||||
curl -s http://localhost:8000/v1/videos -F task=fl2va -F first_frame=@start.png \
|
||||
-F last_frame=@end.png -F size=1344x768 -F 'prompt=...'
|
||||
```
|
||||
|
||||
**FastH3.** FastVideo's FastH3 8-Step V2 (`FastVideo/FastVideo-FastH3-8-Step-V2`) is the same model
|
||||
distilled to eight steps with video sparse attention; it is converted with the same recipe, its text
|
||||
@@ -2976,6 +3091,12 @@ encoder and decoders taken from a MiniMax-H3 container (`data/recipes/minimax-h3
|
||||
how), served the same way and named `fastvideo-fasth3-8-step-v2`. Its card notes that difficult
|
||||
motion, fine detail and some audio may fall below the base model's; it serves text to video only.
|
||||
|
||||
**Other encodings.** `data/recipes/minimax-h3-w8a8.recipe` stores the DiT's per-token linears as
|
||||
int8 with a scale per 128 columns, read at w8a8, in the same memory as the fp8 container. A
|
||||
curve-form checkpoint (its `config.json` sets `adaln_curve_grid`) ships its timestep embeddings
|
||||
as a table and its modulation projections bf16; `minimax-h3-curve-fp8.recipe` and
|
||||
`minimax-h3-curve-w8a8.recipe` convert one.
|
||||
|
||||
**Latent upscaling.** A container that carries LBH-123-AI's latent upscaler
|
||||
(`LBH-123-AI/Minimax_h3_latent_Upscaler`, Apache-2.0; the recipe says how to add it to a container,
|
||||
in place) takes **`latent_upscale`**, a factor from 1 to 4: the first steps run at `size` divided
|
||||
@@ -2984,7 +3105,7 @@ upscaler, re-noised, and the last **`upscale_refine_steps`** run at the full siz
|
||||
and 12 of the base model's 49 by default). The steps at the small size cost a fraction of a
|
||||
full-size step's, so most of the time goes to the refinement. The video object of an upscaled
|
||||
video carries `latent_upscale`, the `upscale_refine_steps` it ran and `upscale_from`, the small
|
||||
size.
|
||||
size. Reference media ride it unchanged; keyframes do not (above).
|
||||
|
||||
```sh
|
||||
curl -s http://localhost:8000/v1/videos -H 'Content-Type: application/json' -d '{
|
||||
@@ -3387,7 +3508,7 @@ is the part of a log to paste into an issue. Its sections:
|
||||
warning is also printed as a `W` line of its own.
|
||||
|
||||
```
|
||||
I STARTUP REPORT -- radiance 1.12.0
|
||||
I STARTUP REPORT -- radiance 1.13.0
|
||||
I CONFIGURATION -- every option, the value in force, and where it came from
|
||||
I --model /models/flashnext.rad [command line]
|
||||
I --tp 2 [command line]
|
||||
@@ -3463,7 +3584,6 @@ rad-kbench --home $RADIANCE_HOME --max-cases 1 # are the kernels correct?
|
||||
| `HF_TOKEN` | for `scripts/hfget.sh` and `--model <owner/name>` on a gated or private repo |
|
||||
| `XDG_CACHE_HOME` | where `--model <owner/name>` fetches to without `--download-dir` (`$XDG_CACHE_HOME/radiance/hf`, else `~/.cache/radiance/hf`) |
|
||||
| `R4D_AR_MAX_BLOCKS` | a ceiling on libr4d's collective block counts, for two tensor-parallel engines on one set of cards; set it in both (below). The MoE models' hyper-connection gathers keep the minimum their LDS table needs. Unset, nothing changes |
|
||||
| `RADIANCE_PREFETCH_BESIDE` | `0` issues no weight prefetch beside the decode collectives. For an engine that shares its cards with another server (below); alone it costs a few percent of decode. Unset, nothing changes |
|
||||
|
||||
**Two engines on one set of cards.** Every block of a libr4d collective spins until its twin on the
|
||||
peer card has pushed, and a prefill-sized fused all-reduce launches more blocks than a card holds at
|
||||
@@ -3476,9 +3596,33 @@ low enough that their spinners together leave part of a card free, the cycle can
|
||||
Qwen3.8-27B (its decode at 16 sequences x 4 rows stays uncapped) and 16 for the Gemma ran 15
|
||||
minutes of concurrent long prompts on both without a stall. The ceiling costs prefill time, the
|
||||
reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapped, 9.8 s at 64,
|
||||
10.3 s at 32. Give the engine started first its `--gpu-headroom-mib` for the second. A model whose decode reads weights ahead on a second queue (Gemma 4 without chained launches) slows sharply beside a second server: an R9700 has four compute queue slots and the two servers hold eight, so every decode step waits for a queue switch. Gemma 4 31B at TP4 beside an idle Qwen3.8-Flash-Next went from 13 ms to 41 ms a step; with `RADIANCE_PREFETCH_BESIDE=0` in the Gemma engine it took 13.8 ms.
|
||||
10.3 s at 32. Give the engine started first its `--gpu-headroom-mib` for the second. A model whose
|
||||
decode reads weights ahead on a second queue (Gemma 4 without chained launches) slows sharply
|
||||
beside a second server: an R9700 has four compute queue slots and the two servers hold eight, so
|
||||
every decode step waits for a queue switch. Gemma 4 31B at TP4 beside an idle
|
||||
Qwen3.8-Flash-Next went from 13 ms to 41 ms a step; with `--weight-prefetch off` in the Gemma
|
||||
engine it took 13.8 ms.
|
||||
|
||||
The four slots are what the amdgpu kernel driver leaves to user queues. It keeps compute queues of its own for submissions through the graphics stack (Vulkan and OpenGL in Mesa), four of the eight on the card's two compute pipes by default (`num_cp_queues 4` in `/sys/class/kfd/kfd/topology/nodes/*/properties`). A machine that drives its cards through ROCm alone can give them back with the module option `amdgpu.num_kcq=0` (a line `options amdgpu num_kcq=0` in `/etc/modprobe.d/`, then `update-initramfs -u` and a reboot): `num_cp_queues` reads 8 and `dmesg` shows `compute_hqd_mask 0x0000000f` (`num_kcq=1` leaves `0x0000000e`, three queues a pipe, though `num_cp_queues` reads 7). An engine holds up to four queues a card (the step's lane, the second lane, the mover's and the runtime's own), so two engines then fit and the weight reads can stay on. Start them one after the other and send the first a short request before starting the second: an engine creates its second-lane queue at the first step that uses it (a decode step where the weight reads or another second-lane op run), and a queue created after the other engine's queues lands where both run slower (TranslateGemma one stream 120 t/s instead of 181, Qwen beside a busy TranslateGemma 50 ms a step instead of 43). Qwen3.8-27B and TranslateGemma 27B on two R9700s, the reads on in both: TranslateGemma one stream 180.6-180.9 t/s and Qwen beside a busy TranslateGemma 42.9 ms a step, against 152-154 t/s and 41.0-42.8 ms with the default slots and `RADIANCE_PREFETCH_BESIDE=0` in both; Qwen beside an idle TranslateGemma 18.3 ms a step, against 19.8-20.5. Mesa then finds no compute ring of its own on those cards.
|
||||
The four slots are what the amdgpu kernel driver leaves to user queues: by default it keeps four of
|
||||
the eight compute queues on the card's two pipes for the graphics stack (Vulkan and OpenGL in Mesa),
|
||||
and `num_cp_queues` in `/sys/class/kfd/kfd/topology/nodes/*/properties` reads 4. A machine that
|
||||
drives its cards through ROCm alone can give them back:
|
||||
|
||||
- set the module option `amdgpu.num_kcq=0` (`options amdgpu num_kcq=0` in `/etc/modprobe.d/`, then
|
||||
`update-initramfs -u` and a reboot). `num_cp_queues` then reads 8 and `dmesg` shows
|
||||
`compute_hqd_mask 0x0000000f`; `num_kcq=1` leaves `0x0000000e`, three queues a pipe. Mesa then has
|
||||
no compute ring of its own on those cards.
|
||||
- An engine holds up to four queues a card (the step's lane, the second lane, the mover's and the
|
||||
runtime's own), so two engines fit and the weight reads beside the all-reduces can stay on.
|
||||
- Start them one after the other, and send the first a short request before starting the second:
|
||||
an engine creates its second-lane queue at the first step that uses it, and a queue created after
|
||||
the other engine's lands where both run slower (TranslateGemma at one stream 120 tok/s instead of
|
||||
181).
|
||||
|
||||
Qwen3.8-27B and TranslateGemma 27B on two R9700s, weight reads on in both: TranslateGemma at one
|
||||
stream 180.6-180.9 tok/s and Qwen beside a busy TranslateGemma 42.9 ms a step, against 152-154 tok/s
|
||||
and 41.0-42.8 ms with the default slots and `--weight-prefetch off`; Qwen beside an idle
|
||||
TranslateGemma 18.3 ms a step, against 19.8-20.5.
|
||||
|
||||
**Tooling**
|
||||
|
||||
@@ -3489,14 +3633,9 @@ The four slots are what the amdgpu kernel driver leaves to user queues. It keeps
|
||||
| `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) |
|
||||
| `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) |
|
||||
| `RADIANCE_G4_CALIB_LAYERS` | `lo:hi`: the same for `arch/gemma4`'s tap, which takes the Gemma 4 31B's Grams from its bf16 checkpoint (docs/GEMMA4-31B-GPTQ.md) |
|
||||
| `RADIANCE_G3_FOLD_ROWS` | `arch/gemma3`, an A/B knob: the gated fold (gate_up, GeGLU and down's E4M3 quantiser in one launch, libr4d `gemm_nt_q_gated_mx`) on decode and verify steps of up to this many rows, 9..64 through `gemm_mxfp4a8_gated_gemv_wide`; `0` or unset is 8. Bit for bit at any value. Read at startup; anything but an integer 0..64 refuses to start |
|
||||
| `RADIANCE_G3_PF_EARLY` | `arch/gemma3`, an A/B knob: `1` issues the weight read beside a bare (unfused, lossy-wire) all-reduce in front of it rather than after it, so it overlaps the reduction rather than the post-norm, the junction and the next GEMM; `0` or unset is the old order. The fused all-reduce junction's steps have it in front either way |
|
||||
| `RADIANCE_G3_PF_MIB` | `arch/gemma3`, an A/B knob: the size in MiB (1..256) of the weight reads beside the all-reduces on decode steps of more than 32 rows (default 24, the narrow steps' size); declared only when `RADIANCE_G3_PF_ROWS` reaches past 32 |
|
||||
| `RADIANCE_G3_PF_ROWS` | `arch/gemma3`, an A/B knob: the tallest decode or verify step that reads beside its all-reduces (default 32; 64 covers eight sequences at speculation 7). Never on a step with a prompt's rows |
|
||||
| `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) |
|
||||
| `RADIANCE_AQL_STAMP`, `RADIANCE_AQL_STAMP_OUT` | `N`: every dispatch of one recorded pass in N on card 0 gets a completion signal of its own, which carries its start and end; the barrier bits and chains stay as unstamped, unlike `--profile-ops`, which plays no recorded pass. One CSV line a dispatch (pass, record, queue, kernel, whether it waited for the one before, whether it was chained, start and end in ns) is appended to `RADIANCE_AQL_STAMP_OUT` (default `/tmp/radiance-stamps-<pid>.csv`) once the card is done with it; `scripts/stampgaps.py` reads it per kind of pass (idle share, gaps before ordered starts, kernels by time). AQL backend only |
|
||||
| `RADIANCE_AQL_STAMP`, `RADIANCE_AQL_STAMP_OUT` | `N`: time every dispatch of one recorded pass in N on card 0, each with a completion signal of its own, without changing its barriers or chains (`--profile-ops` plays no recorded pass). One CSV line a dispatch (pass, record, queue, kernel, ordered, chained, start and end in ns) goes to `RADIANCE_AQL_STAMP_OUT` (default `/tmp/radiance-stamps-<pid>.csv`); `scripts/stampgaps.py` summarises it per kind of pass. AQL backend only |
|
||||
| `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) |
|
||||
| `RADIANCE_IDS_EARLY=0` | read a step's sampled tokens only once the drafter's passes behind it have run. By default they are read, committed and streamed while the card runs those passes. For an A/B |
|
||||
|
||||
Engine development has its own instruments: `RADIANCE_DEBUG_*` (residual probes, routing and issue
|
||||
dumps), `RADIANCE_OP_ORACLE*` (named ops checked against `libref` on the operands the model issued;
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
# KV streaming: host-authoritative KV with a resident VRAM window
|
||||
|
||||
A streamed group keeps its whole context in pinned host RAM and only a ring of blocks in VRAM; the
|
||||
VRAM that frees up goes to experts. `--max-model-len` and `--max-num-seqs` size the host side,
|
||||
`--kv-resident` the ring. The operator's view is [GUIDE.md](GUIDE.md) §4.4.1; source comments cite
|
||||
the section numbers below.
|
||||
|
||||
Streaming pays only when a step reads far less than the context, which is true of radiance's
|
||||
indexer-selected attention (the QSA family and GLM-5.3's MLA block) and false of dense attention
|
||||
(§2). An architecture with no streamed path ignores the flag with one warning (§4.5).
|
||||
|
||||
Two views sit over one allocation: the **ring**, `n_slots` blocks deep and `n_layers` stripes,
|
||||
addressed through a residency map, and the **stage**, the group's context deep and one stripe,
|
||||
addressed by block id. The allocation is `max(ring, stage)`, never the sum (§3.1). A pass's view
|
||||
follows from its phase and row shape, both already in the pass key.
|
||||
|
||||
---
|
||||
|
||||
## 1. Why the idle tiers are not the stream
|
||||
|
||||
The VRAM paged pool (`core/mem/kv.{h,cpp}`) is where a live sequence's KV lives. The idle tiers
|
||||
(`core/mem/kvtier.*`, `core/runtime/tierexec.*`) copy a finished conversation's blocks to pinned
|
||||
host memory and back on a prefix-cache hit: a hot cache whose unit is a published prefix entry,
|
||||
moved between identical layouts on publish and admission, in memory no kernel dereferences.
|
||||
Streaming needs many small, per-launch, selection-driven copies with a residency map, so it is a
|
||||
module of its own (§4.1). It keeps the tiers' two rules: never block the host on the step path, and
|
||||
order copies with events, not syncs (`spec.md` §5.4).
|
||||
|
||||
---
|
||||
|
||||
## 2. What bounds a step's read
|
||||
|
||||
Qwen3.8-Flash-Next (`arch/qwen4exp_fp8`) at `--tp 2`, fp8 KV, per rank; 12 QSA layers plus the
|
||||
MTP head bind `kv_attn`:
|
||||
|
||||
| group | per 4-token block | per token | at 262 144 tokens |
|
||||
|---|---|---|---|
|
||||
| `kv_attn` (fp8, 2 kv heads, head_dim 256, 13 layers) | 26.00 KiB | 6.50 KiB | 1.66 GiB |
|
||||
| `kv_qsa_bkey` (bf16, 1 head, head_dim 16) | 3.25 KiB | 0.83 KiB | 208 MiB |
|
||||
|
||||
Decode is sparse at every context: the selection keeps `topk = budget / ratio = 512` blocks a row
|
||||
(`docs/QSA.md`), so a step reads about 13 MiB of `kv_attn` whatever the history. The indexer is
|
||||
different: `qsa_score` reads every complete block of `kv_qsa_bkey` each step (208 MiB at 262K), so
|
||||
that group is dense-read and stays resident (§3.1).
|
||||
|
||||
A dense family (Qwen3.8-27B, `arch/qwen35_*`) reads the whole context every step, 16 KiB a token per
|
||||
rank at fp8, so a ring only subtracts from a read that is already link-bound. It declares no
|
||||
streamed path.
|
||||
|
||||
---
|
||||
|
||||
## 3. The contracts
|
||||
|
||||
### 3.1 One id space, two depths
|
||||
|
||||
The paged pool is block-id indexed and layer-major: layer `i` at `base + i * layer_stride`, block
|
||||
`b` at `b * layer_bytes_per_block`, and a slot is `block_table[bi] * block_size + pos % block_size`.
|
||||
Nothing indirects, so a block id outside the pool corrupts the next layer with fluent text.
|
||||
|
||||
`KVGroupPlan` therefore carries two depths: `n_blocks`, the id space (the context), which the
|
||||
allocator, refcounts, block table, prefix cache and every `id < n_blocks` guard count; and
|
||||
`n_slots`, the blocks the device pool backs. `pool_blocks()` is `n_slots` (or `n_blocks`),
|
||||
`streamed()` is `n_slots < n_blocks`, and `layer_stride()` uses `n_slots`. Only addressing moves.
|
||||
|
||||
The pool is one reservation of `max(ring, stage)` (`kv_pool_bytes`, `kv_ceiling_bytes`), and
|
||||
`carve()` writes `n_blocks`, `n_slots` and `depth` together (`kvstream_apply`). A streamed group takes
|
||||
its id space from the context (`kv_context_blocks`) rather than the pool split, so it does not
|
||||
compete for VRAM; it never lends to the expert slab, and the idle tiers never gather it (§4.1).
|
||||
Refused or charged by name:
|
||||
|
||||
- **a window that does not fit** the budget is refused against `--kv-resident` before the split
|
||||
(`kvstream_window_fit`), rather than leaving a neighbour with zero blocks;
|
||||
- **a streamed `RAD_KV_WINDOW` group** is refused: a window bounds its own history;
|
||||
- **the dense-read floor**: a group read over its whole history every step
|
||||
(`rad_kv_group_dense_read`, an indexer's block keys) cannot stream, and while a sibling streams
|
||||
its carve is `max_seqs` full contexts, since the sibling's mirror holds that many (`kvstream_dense`).
|
||||
With nothing streaming the floor is off;
|
||||
- **the maps** are reserved from the KV pool before `carve()`, which the budget probe cannot do, so
|
||||
`kvstream_maps_charged()` charges them in both paths and the carve adds back what was reserved.
|
||||
|
||||
A ring that covers the group's context is not a streamed group: no mirror, maps, stage or resolve,
|
||||
and a null `RadKVStream`, decided at startup.
|
||||
|
||||
### 3.2 The host mirror
|
||||
|
||||
The mirror is `RAD_MEM_HOST_MAPPED`, so a kernel reads it over the link in place, and laid out like
|
||||
the pool: layer `l`'s row for block `b` is at `host + l * host_layer_stride + b * block_bytes`, with
|
||||
`block_bytes` both the resolve's row pitch and the length of every copy into the ring. It is
|
||||
`n_blocks * bytes_per_block`, zeroed at bring-up, and kept per rank, each rank with its own maps in
|
||||
its own pool (`kvstream_step_view`). It is the first in-place device writer of mapped host memory,
|
||||
so its coherence is pinned by a test (§6.2).
|
||||
|
||||
### 3.3 The writer maintains both copies
|
||||
|
||||
`kv_store_streamed`, and its fold into the prologue `qk_norm_rope_gate_kv_store_streamed`, writes
|
||||
the host mirror always and the ring slot only when `res[block] >= 0`. A slot never goes stale, so
|
||||
nothing needs invalidating, not on a rejected draft and not on a restore. The residency test must
|
||||
be in the writer: at decode the block a step writes is usually the one the previous step made
|
||||
resident, so a mirror-only writer would leave the ring's copy short of this step's tokens and the
|
||||
resolve, seeing it resident, would not copy it. `res` is written by `kv_resolve` alone.
|
||||
|
||||
A layer's order is **store, then resolve, then attention**, so a block copied in from the mirror
|
||||
carries this step's tokens; the indexer runs before the store and so cannot resolve. The streamed
|
||||
store has E4M3 and bf16 rows; a packed cache (`fp8_v4`, `k6_v4`) has none and is ignored (§4.5).
|
||||
|
||||
### 3.4 The resolve
|
||||
|
||||
`qsa_select` writes pool page ids into `sel`, and `attn_paged` uses each entry as a raw pool index.
|
||||
`sel` is the only place the sparse path names KV storage, so `kv_resolve`, between select and
|
||||
attention, is the one op streaming adds: it makes every selected block resident, copying misses in
|
||||
from the mirror, and rewrites `sel` as ring slots. Its operands, parameters and control block are in
|
||||
docs/OPS.md ("kv_resolve"); `libref/ref_kvstream.cpp` is the serial definition.
|
||||
|
||||
The order is a contract, so every implementation places the same blocks in the same slots:
|
||||
|
||||
1. bump the epoch;
|
||||
2. one lookup per valid entry: a hit stamps its slot and bumps its two-bit heat counter once a
|
||||
call; a miss claims its map entry once (`-1 -> -2`), so the map is its own set;
|
||||
3. the miss list in ascending block id, never first-appearance order;
|
||||
4. one victim per miss: the block's own slot when free (a context shorter than the ring stays at
|
||||
identity, and the attention's adjacent ids read adjacent slots), else a free slot, else a CLOCK
|
||||
sweep over the heat counter that never takes a slot this call stamped;
|
||||
5. re-point both maps;
|
||||
6. copy each placed block as bytes;
|
||||
7. rewrite every valid entry as its slot.
|
||||
|
||||
Step 3 makes the resolve deterministic; a device implementation sorts its claim list rather than
|
||||
scanning `blocks`, so a launch costs its selection, not the cache.
|
||||
|
||||
**Overflow.** The ring must hold the call's selection union. When it cannot, the unplaced claims
|
||||
revert to `-1`, `ctl[3]` latches and their entries become slot 0, a defined address (a block id
|
||||
there would be read past the ring). The engine copies each group's `ctl` behind the step's last
|
||||
resolve and reads it at the commit, so the step path never waits; a newly latched overflow fails
|
||||
every request prefilling in that step, naming the ring and the union, and clears the latch.
|
||||
|
||||
**State and recording.** The epoch, hand, heat and counters live between calls, so two launches
|
||||
must never overlap (the row is not in `rad_kernel_concurrent`). The op is recordable: its addresses
|
||||
and pitches are fixed from bring-up. `Ctx::pass_key` keys a streamed group by the memory its view
|
||||
names (`kvstream_view_key`), never by the view's address, which the builder's rotating Out slots
|
||||
change every step.
|
||||
|
||||
**Three implementations.** `libref/ref_kvstream.cpp` is the oracle; `libavx/avx_kvstream.cpp`
|
||||
follows it step for step and vectorises only the rewrite and the copy; `libr4d/r4d_kv_resolve.hip`
|
||||
is the card's row, checked against libref by `r4d_selftest --case kv_resolve` (hits, ascending
|
||||
misses, eviction, free before live, second chance, saturation, overflow, 2052 claims, the copy, the
|
||||
refusals).
|
||||
|
||||
### 3.5 Prefill: the union, and the stage
|
||||
|
||||
Above `qsa_exact_to = budget + ratio - 1 = 2051`, prefill is per-query sparse: every row of a chunk
|
||||
selects its own 512 blocks. One launch's union (`scripts/kv-union.sh`, Flash-Next `--tp 2`):
|
||||
|
||||
| prompt tokens | ring that held | largest union | largest misses of one call |
|
||||
|---|---|---|---|
|
||||
| 3 958 | 2 048 blocks | 990 | 976 |
|
||||
| 16 048 | 4 096 | 4 000 | 1 024 |
|
||||
| 66 131 | 16 384 | 14 608 | 1 024 |
|
||||
| 133 331 | 32 768 | 23 429 | 1 024 |
|
||||
|
||||
The union is 70-100 % of the history and grows with it, so no ring sized for decode (at most 513
|
||||
blocks a row) serves prefill. Prefill therefore takes the **stage**: one layer's whole history at
|
||||
block-id addressing, filled from the mirror per layer, with no selection awareness and no resolve.
|
||||
A prompt below `qsa_exact_to` runs dense attention, which reads block ids from the table; it stages
|
||||
the same way.
|
||||
|
||||
### 3.5.1 The aliased stage and the ordering rule
|
||||
|
||||
Every layer of the stage aliases offset 0 of one allocation. The operand resolution accepts that:
|
||||
a `RAD_KV` operand is bounded by `off + layer_stride <= bytes`, which a one-layer pool satisfies at
|
||||
`off = 0` for every layer (`a_streamed_groups_layers_may_all_alias_one_pool_slot`). The aliasing is
|
||||
the binding's `depth` (1 = every layer at offset 0), not a rewritten `layer_slot`: that table is also
|
||||
the host mirror's row (`rad_kv_layer_index`), so collapsing it would write every layer into one
|
||||
mirror row.
|
||||
|
||||
The KV operand is external memory, so the buffer plan never sees it, and the hazard pass sees the
|
||||
same range for every aliased layer. The order rests on the stage's barriers alone, stated beside
|
||||
the code in `core/kvstream/stage.h`: the copy of layer L lands before L's store, L's store and
|
||||
attention follow, and the copy of L+1 starts after every attention launch of L. What breaks it:
|
||||
taking the ride before all of L's chunked attention launches, waiting after the store instead of
|
||||
before it, moving the copy to lane 1 without a join, replaying a recorded pass without re-running
|
||||
the arm and submit (`Ctx::tape_kv_stage` does), or a binding that moves between passes sharing a
|
||||
key.
|
||||
|
||||
A staged pass reads the pool by block id, while `kv_store_streamed` writes the ring only where the
|
||||
map names a slot (none before the group's first decode), so a staged pass also stores at identity
|
||||
(`AttnGatedFP8::store_stage_identity`, GLM's plain store), after the mirror writer.
|
||||
|
||||
**Volume.** A layer's copy moves the mirror row up to the highest block id the pass can read, not the
|
||||
whole context allocation. The bound is `KVManager::held_top_blocks`, one past the highest held block,
|
||||
read every step after the step's blocks are ensured (`kvstream_bound_live`). It must never be low:
|
||||
the attention would read whatever the previous layer left, which is wrong text, not a fault. It is
|
||||
an upper bound because every id a table holds is held, the stage is identity-addressed from block 0,
|
||||
and allocation is not assumed ascending. It counts every held block, including the prefix cache's;
|
||||
0 (nothing held) stages the whole row.
|
||||
|
||||
### 3.6 The ABI surface
|
||||
|
||||
`RadKVStream` (`abi/rad_runtime.h`) is one group's fixed view: the mirror, the per-layer residency
|
||||
maps (`res`, `slot_block`, `slot_state`), the shared control block, `block_bytes`,
|
||||
`host_layer_stride`, the ring's `slots` and `host_bytes`. `RadKVGroupBatch` carries a trailing
|
||||
`const RadKVStream* stream`, null for a resident group: a pointer, because the view is fixed at
|
||||
bring-up while the batch is rebuilt every step. The build side is `RadBuildCtx::kv_resident_blocks`
|
||||
(the ring in tokens), `RadBuildCtx::kv_stream_ok` and `RadArchProbe::kv_stream_ok` (§4.5). The arch
|
||||
side is `rad_kv_layer_index`, `rad_kv_stage_layer` and `rad_kv_stage_next`, with the
|
||||
`kv_stream_layer`, `kv_resolve_declare`, `kv_resolve_issue` and `kv_stage_*` helpers in
|
||||
`arch/common/rad_arch.h`.
|
||||
|
||||
### 3.7 Flags, report, metrics
|
||||
|
||||
`--kv-resident N` is the only switch. The KV report gains the streamed group's two-tier line, and the
|
||||
startup lines name the ring (and why it was raised), the host mirror, the stage, or which context a
|
||||
covering flag spans. Metrics: `radiance:kv_resident_blocks`, `radiance:kv_stream_misses_total` and
|
||||
`radiance:kv_stream_bytes_total{dir="in"}`. A request's end logs each group's cumulative resolves,
|
||||
lookups and misses with the largest union, misses and claims of one launch (`ctl[10..12]`).
|
||||
|
||||
### 3.8 The host-RAM budget and the gate
|
||||
|
||||
The mirror is the largest host allocation after the experts' pool: 4.69 GiB a rank for four
|
||||
204 800-token sequences of Flash-Next. `kvstream_host_gate` checks the mirrors once, before any rank
|
||||
pins one, against the host tiers still to be pinned after them (the activation arenas and, when
|
||||
sized, the checkpoint store) plus `--host-headroom-mib`. A refusal names `--max-model-len` and
|
||||
`--max-num-seqs`, which size the mirror; `--host-pool-mib` sizes the experts' tier and cannot make
|
||||
room.
|
||||
|
||||
The prefix cache's host tier (`--prefix-cache-mib`) is turned off when a group streams, before
|
||||
anything is sized from it: an entry covers every cached group, and a streamed group's rows are
|
||||
addressed by the block ids its sequence used, so the entry cannot move to a host slot
|
||||
(`PrefixCache::demotable`). Prefix hits still work from VRAM; a conversation evicted from VRAM is
|
||||
prefilled again rather than restored. "Streams" is the engine's answer (`cfg.kv_streams`): the flag
|
||||
set, the architecture's streamed ops declared and linked for the group with an fp8 or bf16 cache,
|
||||
and a ring under the context. In every other case the host tier is as configured.
|
||||
|
||||
### 3.9 What it costs
|
||||
|
||||
`--kv-resident` has two floors, applied in `kvstream_ring_shape`/`kvstream_ring` and clamped to the
|
||||
context, and the carve takes the larger:
|
||||
|
||||
- **correctness**: one decode step's selection, `max_seqs x (1 + n_spec) x 513` blocks (16 416
|
||||
tokens at two sequences and speculation 3); a request under it could not be served from the
|
||||
selection table;
|
||||
- **cost**: **32 768 tokens** (`kStreamFloorTokens`). Below about 24 576 tokens the misses cost more
|
||||
than the VRAM the ring frees (at 64k of history: 24 576 runs 37.9 tok/s, 8 192 runs 37.1 with 75 %
|
||||
more misses), and a ring larger than the history buys nothing.
|
||||
|
||||
A flag under either is raised with one warning. The raised number is what
|
||||
`RadBuildCtx::kv_resident_blocks` carries into the declare, since `kv_resolve` sizes its table from
|
||||
it. A context under 32 768 tokens cannot stream.
|
||||
|
||||
Decode: a miss costs about 0.8 us, and a resolve launch about 4 us of device time, flat across ring
|
||||
sizes; the twelve a step cannot merge (each follows its layer's store), so streaming costs about 3 %
|
||||
of decode at `--tp 2` and nothing at `--tp 1`. The identity placement is worth +2 % at 16k. Warming
|
||||
the ring from the last prefill chunk made decode 3.8 % slower, through slot order.
|
||||
|
||||
Capacity is bought in host RAM. Flash-Next fp8, two ranks, `--kv-resident 24576`:
|
||||
|
||||
| configuration | VRAM KV per card | host RAM per rank |
|
||||
|---|---|---|
|
||||
| resident, 2 x 204 800 | 1.43 GiB, one conversation retained | - |
|
||||
| resident, 4 x 204 800 | 1.53 GiB, 25 % of the four conversations | - |
|
||||
| streamed, 2 x 204 800 | ring 144 MiB, stage 200 MiB (pool 200 MiB), indexer 300 MiB: 618 MiB | 2.34 GiB |
|
||||
| streamed, 4 x 204 800 | ring 144, stage 400, indexer 600: 1 232 MiB, all four funded | 4.69 GiB |
|
||||
|
||||
Per retained token: 6.00 KiB of mirror (host), 0.83 KiB of indexer and 0.50 KiB of stage (VRAM);
|
||||
only the ring does not scale. Prefill comes out 3-5 % above the resident arm, because the VRAM the
|
||||
cache no longer holds goes to experts that would otherwise be read over the link. The stage copy's
|
||||
cost is its volume (the held bound moves 0.6 GiB a pass at 16k and 45 GiB at 160k, within 0.3 % of
|
||||
the live KV), not its overlap, since it shares the link as an equal (§6.1). Capacity is bought with
|
||||
`--max-num-seqs`, inside the trained window, so no rope change is needed. Perplexity: 3.994 resident,
|
||||
4.015 with a covering window, 4.014 with a fraction of it.
|
||||
|
||||
---
|
||||
|
||||
## 4. Architecture
|
||||
|
||||
### 4.1 The module
|
||||
|
||||
`core/kvstream/` holds the feature; the existing files make one call at each seam.
|
||||
|
||||
| file | owns |
|
||||
|---|---|
|
||||
| `plan.h`, `.cpp` | the policy: which group streams, the ring's floors, the sizes, which ops a group needs. Arithmetic only. |
|
||||
| `bind.h`, `.cpp` | the layout: both views over a plan, `layer_slot` kept as the mirror's row, the per-pass view, `kvstream_step_view`, `kvstream_view_key`. |
|
||||
| `stage.h`, `.cpp` | the driver: per pass and layer, the copy of the layer's live blocks from the mirror into the stage on the DMA engine (§5.3). |
|
||||
| `mirror.h`, `.cpp` | the mirror and the maps: sizes, allocation, initialisation, release, the window cap and the counters. `KVManager` holds one `KVStreamStore` and delegates. |
|
||||
| `carve.h`, `.cpp` | the carve's part: windows and the dense-read floor leaving the budget first, the window-fit refusal, `n_blocks`/`n_slots`/`depth`, the maps' charge, the report line. |
|
||||
| `bringup.h`, `.cpp` | the engine side: the group, the refusals (§4.5), the floors, the host-RAM gate, the startup lines. |
|
||||
|
||||
Only `stage.cpp` and `mirror.cpp` touch a device. Deliberately left alone: the block ids, refcounts
|
||||
and free lists (the stage addresses every block identically, and a prefix hit adopts the same ids);
|
||||
`TierExec` (a gather of one layer from a one-layer pool would copy the last staged layer `n_layers`
|
||||
times; the mirror is the tier); the prefix cache's host tier (§3.8); the expert stager and mover; and
|
||||
`qsa_select`.
|
||||
|
||||
### 4.2 Core changes
|
||||
|
||||
1. **The carve split**: `n_slots` beside `n_blocks`, `layer_stride()` over `n_slots`, ids still in
|
||||
`[0, n_blocks)`.
|
||||
2. **The host mirror**: `n_blocks * bytes_per_block` of mapped pinned memory a streamed group and rank,
|
||||
gated by `lockable_room`.
|
||||
3. **The maps**: device `res`, `slot_block`, `slot_state` per layer and a control block, from the KV
|
||||
pool, carried in the batch.
|
||||
4. **Report, flag, metrics** (§3.7).
|
||||
|
||||
### 4.3 Device changes
|
||||
|
||||
1. `kv_resolve`: a libr4d kernel, a libavx form and the libref oracle (§3.4).
|
||||
2. `kv_store_streamed` and its prologue fold (§3.3), E4M3 and bf16.
|
||||
3. The stage copy, a DMA list per layer (§5.3); no kernel.
|
||||
|
||||
### 4.4 Arch changes
|
||||
|
||||
The gated fp8 attention block (`arch/common/rad_block_attn_gated_fp8.h`) declares the streamed store
|
||||
beside `kv_store`, issues it instead when the batch hands the group a stream, and issues the resolve
|
||||
after the store and before each sparse launch. GLM-5.3's MLA block (`rad_block_glm_mla.h`) declares
|
||||
the same pair and resolves at finish, after its indexer selects.
|
||||
|
||||
### 4.5 The capability gate
|
||||
|
||||
A plugin states once, in `RadArchProbe::kv_stream_ok`, that its architecture can stream; the engine
|
||||
carries it into every declare as `RadBuildCtx::kv_stream_ok`. `qwen4exp_fp8` and `glm5next` set it.
|
||||
The three streamed-only ops (`kv_store_streamed`, its fold, `kv_resolve`) are declared only when the
|
||||
architecture can stream and `--kv-resident` asks for a ring (`kvstream_op_gated`, consulted by
|
||||
`Builder::op_declared`), so a model file never knows whether the operator asked, and every
|
||||
`rad_op_declared` check falls through to the resident path. Fail-safe, with one warning each:
|
||||
|
||||
- a group with no `kv_resolve` or no streamed store for its geometry is ignored: without the resolve
|
||||
the attention would read block ids past the ring; without the store a miss would read zeros. A
|
||||
declaration with no kernel, or one stating another group's geometry, does not count;
|
||||
- a packed cache (`fp8_v4`, `k6_v4`) is ignored the same way, naming the layout;
|
||||
- an architecture whose probe says no turns the flag off at startup.
|
||||
|
||||
Without the flag no streamed op is declared and no budget changes. The graph is not byte-identical
|
||||
to a build without the feature, though: `qsa_select` writes its entry count (`qsa_nsel`,
|
||||
`selected_count`), an i32 a token, whether or not anything streams.
|
||||
|
||||
---
|
||||
|
||||
## 5. The stage copy's transport, and the ring's depth
|
||||
|
||||
### 5.1 The ring's depth
|
||||
|
||||
`--kv-resident` is off by default. When set it is never carved below 32 768 tokens, nor below one
|
||||
decode step's selection when that is larger (§3.9), and never above the context; one function,
|
||||
`kvstream_ring_shape`, gives the budget probe, the carve and the declared `kv_resolve` the same
|
||||
depth.
|
||||
|
||||
`kv_pass_view` picks a pass's view: a decode pass of at most `1 + n_spec` rows a sequence takes the
|
||||
ring; every other pass (prefill, a mixed step, and a decode-classified pass wider than that, such as
|
||||
the serial drafter's history pass over a prefill chunk) takes the stage.
|
||||
|
||||
### 5.2 There is no streaming switch
|
||||
|
||||
`--kv-resident N` is the feature: absent or 0 and nothing streams, set and the ring is N tokens. A
|
||||
ring that covers the context does not stream at all (§3.1), so a configuration whose context fits
|
||||
runs the same path as without the flag.
|
||||
|
||||
### 5.3 The transport
|
||||
|
||||
The copy of layer L+1 is one `rad_xp_list` on the card's prefetch DMA queue, riding (`rad_ride`) on
|
||||
the compute stream after every attention launch of layer L, so it starts once L is done with the
|
||||
aliased buffer and crosses the link under L's out projection and L+1's projections, holding no CU
|
||||
slot. The compute stream waits for it before L+1's store through an event the list completes
|
||||
(`rad_event_dma`): the list writes 0 to the event's completion word, armed with a 1 in stream order
|
||||
by the weight-table patch dispatch the ride completes on. A host-side arm could race a wait still
|
||||
queued for layer L, and an event record cannot be used, since a record completes by reaching 0.
|
||||
|
||||
The list passes `RAD_XP_NO_YIELD`: the compute stream waits on it, so yielding the link to a hold
|
||||
whose release is behind that wait would deadlock. A backend with no DMA queue copies on the compute
|
||||
stream in the same order. The arch seams are `kv_stage_wait` before the store and `kv_stage_next`
|
||||
after the attention (`arch/common/rad_arch.h`).
|
||||
|
||||
### 5.4 What is not reused
|
||||
|
||||
The transport is the expert prefetch's; the policy is not. The prefetch patches weight-table entries
|
||||
and is sized for experts, and a late prefetch is simply unused, while a stage copy cannot be skipped
|
||||
and must be waited on. They do not compete: the prefetch is decode-only and the stage prefill-shaped.
|
||||
Rejected alternatives: carving the stage from the arena's lent top (a KV base inside another owner's
|
||||
pool, lent per step while the carve is per bring-up); a full `n_layers`-deep buffer lent to the
|
||||
experts between requests (1.66 GiB at 262K during prefill, and reclaiming it is a host wait); the
|
||||
whole context resident during prefill (the group would still carve `n_layers x context`).
|
||||
|
||||
---
|
||||
|
||||
## 6. Failure modes and the tests that hold them
|
||||
|
||||
| failure mode | what prevents it | test |
|
||||
|---|---|---|
|
||||
| a block id read as an address past the ring | the resolve rewrites every entry; overflow writes slot 0, latches, fails the request | `tests/ref_test.cpp` `kv_resolve_*`; `r4d_selftest --case kv_resolve` |
|
||||
| a streamed plan without a mirror or maps | `kvstream_apply` refuses | `a_streamed_group_is_refused_at_carve_without_its_host_copy` |
|
||||
| a pool whose depth disagrees with its id space | `n_blocks`, `n_slots` and `depth` written together | `a_streamed_group_addresses_its_context_but_backs_only_the_resident_window` |
|
||||
| a streamed window group, or a window that does not fit | refused by name | `a_streamed_window_group_is_refused_by_name` |
|
||||
| a ring under one decode step's selection | raised at startup | `a_ring_below_one_decode_step_s_selection_is_raised_to_the_ceiling` |
|
||||
| a covering ring paying for streaming | `streams()` false, null `RadKVStream` | `a_ring_that_covers_the_context_streams_nothing_and_the_engine_pays_nothing`; `scripts/kv-parity.sh` |
|
||||
| a wide decode-classified pass resolving a ring it cannot fit | `kv_pass_view` takes the stage | `a_decode_pass_wider_than_a_verify_stages_instead_of_resolving_the_ring` |
|
||||
| a mirror nothing writes | the store must resolve to a kernel for the group's geometry | `a_declared_streamed_store_with_no_kernel_is_not_a_streamed_path`; `a_packed_cache_warns_that_the_layout_has_no_writer_and_serves_non_streamed`; `a_resolve_declared_for_another_group_does_not_enable_streaming` |
|
||||
| the flag honoured with no streamed path | the capability gate | `a_model_whose_architecture_declares_no_streamed_ops_ignores_the_flag`; `a_streamed_op_exists_only_for_a_capable_architecture_and_a_ring` |
|
||||
| a stage reading the previous layer's bytes | the ordering rule (§3.5.1) | `a_streamed_groups_layers_may_all_alias_one_pool_slot`; `scripts/kv-stage-parity-64k.sh` |
|
||||
| a stage copying less than the pass reads | the `held_top_blocks` bound | `scripts/kv-stage-parity-64k.sh` |
|
||||
| maps leaving the pool short of the probe | `kvstream_maps_charged` in both paths | `a_streamed_groups_maps_are_charged_before_the_pool_is_sized` |
|
||||
| a dense-read sibling funded for one sequence | the `kvstream_dense` floor | `a_dense_read_groups_floor_holds_every_sequence_while_a_sibling_streams` |
|
||||
| a recorded pass replayed against another view | `kvstream_view_key`; fixed addresses | `Ctx::pass_key`'s static assertion on `RadKVGroupBatch` |
|
||||
| the copy moved to another lane or re-issued from the host | §3.5.1 and §5.3 | reviewed, not tested |
|
||||
|
||||
### 6.1 The link, the lanes, and the hold
|
||||
|
||||
At `--tp 2` the all-reduce, the stage copies and the prefill expert stager share the link. DMA lists
|
||||
take their share at full rate without a CU slot; an ordinary stream copy would hold one and starve
|
||||
the kernels. Because the stage list must not yield, it competes as an equal, which is why overlap
|
||||
recovers only part of its cost (§3.9). A stage moved to lane 1 needs `rad_lane_join(1, 0)` before
|
||||
its reader.
|
||||
|
||||
### 6.2 The first in-place device write to mapped host memory
|
||||
|
||||
`r4d_selftest --case kv_store_streamed_fp8` and `--case kv_store_streamed_bf16` put the mirror in
|
||||
mapped pinned memory, run the kernel and compare the bytes the host reads after the sync with
|
||||
libref's; `scripts/kv-stage-parity-64k.sh` exercises the same write in the served path.
|
||||
|
||||
### 6.3 Rank coverage
|
||||
|
||||
Every rank resolves the same shared block ids through identically built maps of its own. Only
|
||||
`--tp 1` and `--tp 2` have run; `--tp 3` and `--tp 4`, the uneven split, the attention-zero ranks
|
||||
and the four-card selftest cases are untested, and the per-rank view (`kvstream_step_view`) is the
|
||||
path to check first.
|
||||
|
||||
### 6.4 The draft model
|
||||
|
||||
The MTP head binds the same `kv_attn` group. A verify step issues one selection a row and takes the
|
||||
ring, which is why the decode bound counts `1 + n_spec` rows (§3.9), and a decode-classified pass
|
||||
wider than that stages (§5.1). Whether the drafter should share the residency map with the trunk
|
||||
is open.
|
||||
+202
-213
@@ -212,6 +212,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
|
||||
| `act_mul` | `M`(range) `n` `act` `dtype` | `a`, `b` → `y` (act(a)·b, two operands) |
|
||||
| `seg_mean` | `M`(range) `n` `dtype` | `x`, `cu_seqlens` → `y` (one mean row a segment) |
|
||||
| `pool_rows` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean row a window of k rows) |
|
||||
| `pool_cols` | `M`(range) `n` `k` `mult`:f64/opt `dtype` | `x` → `y` (one mean column a window of k columns) |
|
||||
| `relu` | `M`(range) `n` `dtype` | `x` → `y` |
|
||||
| `clamp` | `M`(range) `n` `dtype` | `x`, `lo`w, `hi`w → `y` |
|
||||
| `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` `t_last`/opt `act`/opt | `x`, `w`w, `cu_seqlens`, `valid`? → `y`; `b`w? |
|
||||
@@ -292,6 +293,12 @@ op; the segment count is `cu_seqlens`' length less one. An empty segment is a ze
|
||||
of `x`'s rows `[r*k, r*k + k)`, summed in f32 and rounded to `y`'s dtype, then times `mult` and
|
||||
rounded again (the unfused pair stores the mean). `M` is the input row count, a multiple of `k`.
|
||||
|
||||
**`pool_cols`** pools along a row instead: column `c` of row `m` of `y` is the mean of `x[m]`'s
|
||||
columns `[c*k, c*k + k)`, with the same f32 sum, the same two roundings and the same optional
|
||||
`mult`. `n` is the input width, a multiple of `k`; `y` has `n / k` columns. MiniMax-H3's audio
|
||||
encoder pools its attention block's features this way (an `adaptive_avg_pool1d` over the feature
|
||||
axis).
|
||||
|
||||
**`fill`** writes `y = value` over the extent (`value` 0 when absent). A rank issues it where it
|
||||
computes nothing but a downstream reader still expects a defined buffer: an attention-zero rank's
|
||||
block (`docs/TP3.md`) is one `fill` of its output wire before the all-reduce. A wire shared across
|
||||
@@ -1049,77 +1056,33 @@ declares bound it lower.
|
||||
`RadKVGroupBatch` carries the slot mapping, the block table and the sequence lengths, but the pool
|
||||
base belongs to the block manager, not the batch.
|
||||
|
||||
**When the group streams, the pool is a ring and the operand is its layer.** The device pool then
|
||||
holds `slots` blocks and the sequence's block table still names up to `blocks` ids, so the sparse
|
||||
path needs one indirection: `kv_resolve` (in "Sparse attention (QSA)") rewrites the selected ids as
|
||||
ring slots and copies a block in from the pinned host mirror on a miss. Every other op reads the
|
||||
cache exactly as before, because it is handed a resolved table.
|
||||
|
||||
Such a group is written by `kv_store_streamed` instead of `kv_store`: the token's k and v go into
|
||||
the host mirror ALWAYS and into the ring slot only when the residency map says the block is
|
||||
resident. The mirror is the truth; the ring is a cache of it. The order a layer keeps is **store,
|
||||
then resolve, then attention**, because a block this step writes may not be in the ring yet and the
|
||||
resolve copies such a block whole out of the mirror. The residency test belongs in the writer, not
|
||||
only in the resolve: at decode the block a step writes is usually the block the previous step made
|
||||
resident, so a mirror-only writer would leave the ring's copy of it missing this step's tokens and
|
||||
the resolve, seeing the block resident, would not copy it.
|
||||
|
||||
**`kv_dtype` `fp8_v4` and `k6_v4`** (device-only) are the quantised layouts of
|
||||
`--kv-cache-dtype` (`RadBuildCtx::kv_quant`). A head's dims are grouped by 32, each group with an
|
||||
f16 scale (its absmax over the largest code, clamped so every code decodes finite in f16),
|
||||
codes two's complement. A token's row in a head, at
|
||||
head_dim HD:
|
||||
|
||||
| bytes | `fp8_v4` (25 HD / 16) | `k6_v4` (22 HD / 16) |
|
||||
|---|---|---|
|
||||
| K | [0, HD): E4M3, as `fp8_e4m3` | [0, HD/2): the codes' low four bits; [HD/2, 3HD/4): their high two bits, a word per 16 dims whose byte j holds dims 2j, 2j+1 in bits 0-3 and 8+2j, 9+2j in bits 4-7 |
|
||||
| V | [HD, 3HD/2): int4 codes, dim d in the nibble at bit 4 (d mod 2) of byte d/2 | [3HD/4, 5HD/4): the same |
|
||||
| scales | [3HD/2, 25HD/16): V's (absmax / 7) | [5HD/4, 21HD/16): K's (absmax / 31); [21HD/16, 22HD/16): V's |
|
||||
|
||||
The group is declared at `RAD_F8E4M3` with head_dim the row's bytes / 2, so the core sizes pages
|
||||
as it does for fp8, and the cache operand's last extent is the row. The ops take the model's
|
||||
head_dim. libr4d's rows are `kv_store_fp8v4` / `kv_store_k6v4`,
|
||||
`qk_norm_rope_gate_kv_store_fp8v4` / `_k6v4` (byte-identical to the prologue and the store, as at
|
||||
the other widths), `attn_prefill_h256_gqa6_{fp8v4,k6v4}` and `attn_decode_h256_gqa6_{fp8v4,k6v4}`,
|
||||
which widen the codes to f16 in a tile's staging, and the same kernels at Qwen3.8-Flash-Next's
|
||||
ratios over 4-token pages: `attn_{prefill,decode,decode_gq}_h256_gqa12_{fp8v4,k6v4}` and
|
||||
`attn_{prefill,decode,decode_gq}_h256_gqa6_bs4_{fp8v4,k6v4}`, the `decode_gq` rows with the output
|
||||
gate and quantiser in the split-KV merge. `r4d_selftest` holds the stores to an exactly
|
||||
representable set and the attention rows to its inline oracle.
|
||||
**A streamed group's cache operand is its ring.** Its pool holds `slots` blocks while the block
|
||||
table names up to `blocks` ids, so the sparse path resolves the selected ids to ring slots first
|
||||
(`kv_resolve`, under "Sparse attention (QSA)"), and every other op reads the cache as before.
|
||||
Such a group is written by `kv_store_streamed`. A layer's order is store, then resolve, then
|
||||
attention, so a block the resolve copies in from the mirror carries this step's tokens.
|
||||
|
||||
### `kv_store_streamed`
|
||||
|
||||
`kv_store` for a group whose KV streams: one scatter into the group's two copies instead of one.
|
||||
|
||||
- **`k`, `v`, `slot_mapping`** — as `kv_store`: bf16 activations, an i32 flat slot per token, a
|
||||
negative slot skipped. `slot / block_size` is the block and `slot % block_size` the position in
|
||||
it.
|
||||
- **`host`** — bytes, `[blocks, row]`, inout. The layer's authoritative mirror, one block a row,
|
||||
the identity layout the design note gives it (`[block, kv_heads, block_size, 2 * head_dim]`,
|
||||
K then V in a slot). **Written for every token with a slot, always.**
|
||||
- **`kv_cache`** — the ring, the same `RAD_KV(group, layer)` operand `attn_paged`, `kv_store` and
|
||||
`kv_resolve` take. **Written at `res[block]` only when that is >= 0.**
|
||||
- **`res`** — `i32 [blocks]`, in. The residency map `kv_resolve` maintains. Read, never written:
|
||||
residency is the resolve's decision, so the store cannot move the map under a selection that has
|
||||
already been resolved.
|
||||
|
||||
Both planes are dense rows of the same byte pitch, so one offset addresses the same element of the
|
||||
same block in either and the two copies cannot disagree. The conversion follows the cache's dtype:
|
||||
`kv_store_fp8`'s for E4M3 (divided by the reader's descales) and `kv_store_bf16`'s for bf16 (the
|
||||
value itself, no descales; every offset is two bytes wide). The rows are `kv_store_streamed_fp8`
|
||||
and `kv_store_streamed_bf16`, so the default `--kv-cache-dtype bf16` streams as well as fp8; a
|
||||
packed fp8_v4/k6_v4 group has no streamed row and the engine refuses to stream it rather than leave
|
||||
it without a writer.
|
||||
|
||||
The caller's order, per layer, is **store → resolve → attention**. A block the current step writes
|
||||
may not be in the ring at all (a block's first tokens, or a block a previous resolve evicted); the
|
||||
resolve then copies the whole block out of the mirror, so the store must have written it. A block
|
||||
that is resident takes the token in both copies, so the ring never holds a stale block and the
|
||||
resolve never needs to re-copy a resident one. A map entry outside `[-1, slots)` is a state fault
|
||||
that libref refuses; the device kernel treats it as not resident, which writes the mirror and lets
|
||||
the resolve refuse the step.
|
||||
`kv_store` for a streamed group, into both of its copies.
|
||||
|
||||
- **`k`, `v`, `slot_mapping`** — as `kv_store`; a negative slot is skipped. `slot / block_size` is
|
||||
the block and `slot % block_size` the position in it.
|
||||
- **`host`** — bytes `[blocks, row]`, inout: the layer's authoritative mirror, one block a row in the
|
||||
cache's layout (`[block, kv_heads, block_size, 2 * head_dim]`, K then V in a slot). Written for every
|
||||
token with a slot.
|
||||
- **`kv_cache`** — the ring, `RAD_KV(group, layer)`. Written at `res[block]` only when that is `>= 0`.
|
||||
- **`res`** — `i32 [blocks]`, in: the residency map. Read, never written; residency is
|
||||
`kv_resolve`'s decision.
|
||||
|
||||
The residency test is in the writer because at decode the block a step writes is usually the one
|
||||
the previous step made resident: a mirror-only writer would leave the ring's copy short of this
|
||||
step's tokens, and the resolve, seeing the block resident, would not copy it. Both planes share one
|
||||
byte pitch, so one offset addresses the same element in either. The rows are
|
||||
`kv_store_streamed_fp8` (`kv_store_fp8`'s conversion) and `kv_store_streamed_bf16` (the value
|
||||
itself); a packed `fp8_v4`/`k6_v4` cache has none. A map entry outside `[-1, slots)` is a state
|
||||
fault libref refuses; the device kernel treats it as absent, writes the mirror, and the resolve
|
||||
refuses the step.
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
@@ -1158,24 +1121,13 @@ accepts, but a rotated element is a difference of two products, so where those n
|
||||
ULP becomes a few percent and the transcript moves within a few dozen steps. The kernel reproduces
|
||||
the reference's fold exactly: widths above the head dim contribute zeros, and adding 0.0f is exact.
|
||||
|
||||
**`qk_norm_rope_gate_kv_store_streamed`** is that fold for a group whose KV streams: the store is
|
||||
`kv_store_streamed` instead of `kv_store`, so it takes the residency map and the group's host
|
||||
mirror as its last two operands. The token's rotated k and its v go into the mirror's block row for
|
||||
every token with a slot, and into `kv_cache[res[block]]` only where the map calls the block
|
||||
resident; a negative or out-of-range slot stores nothing, and a map entry outside `[-1, slots)` is
|
||||
treated as not resident (libref refuses it as a state fault, and the resolve then refuses the
|
||||
step). Both planes are the same dense row of the same paged layout, and the rotated k is the value
|
||||
`k_out` receives, so the bytes are exactly `qk_norm_rope_gate` then `kv_store_streamed`'s. It has
|
||||
an E4M3 row (`_fp8`) and a bf16 row (`_bf16`, the default cache dtype; the two planes hold the
|
||||
rotated k and v themselves, two bytes wide). It
|
||||
exists because the pair costs a launch a layer on the decode path: one launch where the unfused
|
||||
prologue and the store were two, and one fewer hop between store, resolve and attention.
|
||||
|
||||
The caller's order is unchanged -- **store, then resolve, then attention** -- and a staged pass
|
||||
keeps the stage-copy wait before the store, which is now the prologue's own write. The folded path
|
||||
takes the same guards as the hosted one: `T` at or below the fused rows and a pass at one rotary
|
||||
component per token (no mixed media positions). Where the row is absent, or a pass declines it, the
|
||||
layer runs `qk_norm_rope_gate` plus a separate store exactly as before.
|
||||
**`qk_norm_rope_gate_kv_store_streamed`** is that fold with `kv_store_streamed` as the store, taking
|
||||
the residency map and the host mirror as its last two operands: the rotated k and the v go to the
|
||||
mirror for every token with a slot and to `kv_cache[res[block]]` only where the block is resident.
|
||||
The bytes are exactly `qk_norm_rope_gate` then `kv_store_streamed`'s. Rows `_fp8` and `_bf16`. It
|
||||
saves a launch a layer on the decode path. A staged pass waits for its stage copy before this op,
|
||||
which is the store; a pass the row declines (more than the fused rows, or mixed media positions)
|
||||
runs the prologue and a separate store.
|
||||
|
||||
## Image generation
|
||||
|
||||
@@ -1191,7 +1143,7 @@ says which (`libref/ref_gen.cpp`).
|
||||
| `ln_mod` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `s`, `cu_seqlens` → `y` |
|
||||
| `gate_add` | `M`(range) `n` `dtype` `act`/opt | `y`, `g`, `cu_seqlens`, `x`:inout |
|
||||
| `ln_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` | `y`?, `g`?, `s`, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? |
|
||||
| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `dtype` | `t` → `y` |
|
||||
| `timestep_embed` | `M`(range) `n` `scale`:f64 `max_period`:f64 `round`/opt `clamp_min`:f64/opt `curve`/opt `dtype` | `t` → `y`, `table`w? |
|
||||
| `gather_rows2` | `M`(range) `n` `dtype` | `a`, `b`, `idx` → `y` |
|
||||
| `table_add` | `M`(range) `n` `L` `dtype` | `x`, `t`w → `y` |
|
||||
| `mix_rows` | `M`(range) `n` `k` `dtype` | `x`, `w`w → `y` |
|
||||
@@ -1232,7 +1184,13 @@ source into every listed lane (a repainted picture's latent into each of its ima
|
||||
`t' = scale * t`; with `round` 1, `t' = scale * bf16(bf16(t * scale) / scale)`, the value
|
||||
diffusers' pipeline hands its transformer; with `round` 2, `t' = scale * bf16(t)` (a pipeline
|
||||
that hands the transformer `t` in bf16 and scales it inside, Krea 2's); with `round` 3,
|
||||
`t' = bf16(scale * bf16(t))` (the scaling also in bf16, FLUX's). `t` is f32 `[M]`.
|
||||
`t' = bf16(scale * bf16(t))` (the scaling also in bf16, FLUX's). `t` is f32 `[M]`. With
|
||||
`clamp_min`, each `t` is first raised to it, `t = max(t, clamp_min)`: MiniMax-H3's pinned
|
||||
references take a near-clean timestep whatever the step's. With `curve` = G > 0 and the `table`
|
||||
weight (f32 `[G, n]`), `y[m]` is instead interpolated linearly between the table's two rows
|
||||
around `clamp01(max(t[m], clamp_min)) * (G - 1)` (the lower row at most `G - 2`): the timestep
|
||||
embedding a curve-form checkpoint ships precomputed, in place of the sinusoid and its MLP.
|
||||
`scale`, `max_period` and `round` do not apply there, and `n` need not be even.
|
||||
- `gather_rows2`: `y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]`, zeros past either source.
|
||||
- `table_add`: `y[r, l n + c] = x[r, c] + t[l, c]` for each of `L` rows of the weight `t` `[L, n]`,
|
||||
the sum f32 and rounded once: a modulation shared by every block plus each block's own learned
|
||||
@@ -1346,7 +1304,7 @@ libref function says which (`libref/ref_audio.cpp`).
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt `stride`/opt `cu_div`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
|
||||
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt `stride`/opt `pad`/opt `cu_div`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
|
||||
| `conv_t1d` | `M`(range) `cin` `cout` `stride` `dtype` `pad`/opt `k`/opt | `x`, `w`w, `b`w, `cu_seqlens` → `y` |
|
||||
| `snake` | `M`(range) `n` `dtype` `log`/opt | `x`, `alpha`w → `y`; `beta`w? |
|
||||
| `snake_aa` | `M`(range) `n` `ratio` `k` `log`/opt `dtype` | `x`, `alpha`w, `beta`w, `f_up`w, `f_down`w, `cu_seqlens` → `y` |
|
||||
@@ -1450,14 +1408,20 @@ input reads zero outside it.
|
||||
- `conv1d`: PyTorch's `[cout, cin, k]` weight, `k` odd, dilation `dil` and padding
|
||||
`dil (k - 1) / 2` a side, or with `causal` 1 (any `k`) `dil (k - 1)` on the left; `res` is added
|
||||
after the bias, then `act` `none`, `tanh` or `clamp`, `min(max(y, -1), 1)` (BigVGAN's output
|
||||
clamp; a NaN stays NaN). f32 accumulation, one rounding. `stride` s > 1 (causal only, the reach
|
||||
`dil (k - 1) + 1` at least s) pads `dil (k - 1) + 1 - s` on the left and keeps every s-th row:
|
||||
output row `o` of a sequence reads input rows `o s - pad + t dil`, and sequence `e`'s rows
|
||||
`[cu[e], cu[e+1])` become `[cu[e] / s, cu[e+1] / s)`, so every bound is a multiple of s; `res`
|
||||
and `y` have the output's rows (a causal codec encoder's downsampling, as Fish Audio's).
|
||||
`cu_div` reads the bounds in units that many input rows apart, as the other encoder ops do:
|
||||
sequence `e` is input rows `[cu[e] / cu_div, cu[e+1] / cu_div)`, each bound a multiple of
|
||||
`cu_div` times the stride, so one bounds array in samples serves every rate of an encoder.
|
||||
clamp; a NaN stays NaN). f32 accumulation, one rounding. A `stride` s > 1 comes in two forms.
|
||||
A causal one (the reach `dil (k - 1) + 1` at least s) pads `dil (k - 1) + 1 - s` on the left
|
||||
and keeps every s-th row: output row `o` of a sequence reads input rows `o s - pad + t dil`,
|
||||
and sequence `e`'s rows `[cu[e], cu[e+1])` become `[cu[e] / s, cu[e+1] / s)`, so every bound is
|
||||
a multiple of s; `res` and `y` have the output's rows (a causal codec encoder's downsampling,
|
||||
as Fish Audio's). `cu_div` reads the bounds in units that many input rows apart, as the other
|
||||
encoder ops do: sequence `e` is input rows `[cu[e] / cu_div, cu[e+1] / cu_div)`, each bound a
|
||||
multiple of `cu_div` times the stride, so one bounds array in samples serves every rate of an
|
||||
encoder. A non-causal one takes an explicit `pad` (bf16 rows only, the audio encoder's
|
||||
downsample): `k` is any size, the op is one sequence `cu_seqlens` = `[0, rows of x]`, output
|
||||
row `m` reads `x[m s + tap dil - pad]` with zeros outside, PyTorch's zero-padded strided conv
|
||||
exactly (`k = 2 s`, `pad = ceil(s / 2)` gives `M / s` rows), and `y` has
|
||||
`(rows + 2 pad - dil (k - 1) - 1) / s + 1` rows exactly. An explicit `pad` without a stride,
|
||||
and an even `k` with neither a causal nor a stride, are refused.
|
||||
- `conv_t1d`: PyTorch's `[cin, cout, k]` transposed weight, any `k` of at least a stride (two
|
||||
strides by default), padding `pad` (`(k - stride) / 2` by default, which needs `k - stride` even;
|
||||
0 is the causal form, whose full output's last `k - stride` rows are dropped; it may exceed a
|
||||
@@ -1504,12 +1468,17 @@ bf16 tensor and keeps f32 where it computes in f32; the libref function says whi
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `z` |
|
||||
| `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`? |
|
||||
| `rms_mod` | `M`(range) `n` `eps`:f64 `gated`/opt `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `z`, `colmap`? |
|
||||
| `rms_mod_quant_fp8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`?, `colmap`? |
|
||||
| `rms_mod_quant_i8` | `M`(range) `n` `eps`:f64 `group` `gated` `dtype` `wadd`:f64/opt `norm_once`/opt `norm`/opt | `y`?, `g`?, `s`, `w`w?, `cu_seqlens`, `x`:inout → `q`, `scale`, `z`?, `colmap`? |
|
||||
| `flow_x0_step` | `M`(range) `n` `dtype` | `v`, `t`, `sigma`, `sigma_next`, `x`:inout |
|
||||
| `flow_res_multistep` | `M`(range) `n` `dtype` | `v`, `x0`:inout, `sigma`, `r`, `hb1`, `hb2`, `order`, `x`:inout |
|
||||
| `patch_unfold` | `M`(range) `C` `pt` `ph` `pw` `mul` `add` `dtype` | `x`, `geom` → `y` |
|
||||
| `vtile_gather` | `M`(range) `n` `tile` `overlap` `frames` `period` `n_reg` `dtype` | `x`, `reg`w, `geom` → `y` |
|
||||
| `vtile_stitch` | `M`(range) `tile` `overlap` `scale` `pt` `skip` `keep` `blend` `period` `mean` `std` | `x`, `geom`, `prev`:inout → `y` |
|
||||
| `vtile_plan` | `M`(range) `tile` `overlap` `ratio` | `geom` → `y` |
|
||||
| `vtile_crop` | `M`(range) `tile` `overlap` `ratio` `dtype` | `x`, `geom` → `y` |
|
||||
| `vtile_join` | `M`(range) `tile` `overlap` `n` `dtype` | `x`, `geom` → `y` |
|
||||
| `grid_pos3` | `M`(range) `T` `H` `W` `period` `scale`:f64 | → `y` |
|
||||
|
||||
**The transformer.** `cu_seqlens` partitions the rows into entries as for `ln_mod`, and each row
|
||||
@@ -1529,14 +1498,26 @@ reads its entry's rows of `s` and `g`.
|
||||
`eps`. Without `w` the norm has no gain and rounds once, `n2 = bf16((x - mean) rsqrt(var +
|
||||
eps))` (FLUX.3's LayerNorm without an affine). `norm` `none` takes no norm and no gain,
|
||||
`n2 = x`, and refuses `w` (LTX-2's text keys and values, modulated as they are).
|
||||
`colmap` (optional, trailing, i32 one a sequence) maps a sequence to its table row: every `[e]`
|
||||
above becomes `[colmap[e]]`, so groups that share a modulation cell read one row. With it, `s`
|
||||
and `g` may hold fewer rows than there are sequences; the map's bound is the issuer's.
|
||||
- `rms_mod_quant_fp8` is `rms_mod` with the norm chain in bf16, then `quant_act_fp8` of that bf16
|
||||
row per `group` as `ln_mod_quant_fp8` takes it; `z` written when bound.
|
||||
- `rms_mod_quant_i8` is the same with `quant_act_i8g` in place of `quant_act_fp8`: symmetric int8
|
||||
codes with a scale per `group` columns of a row, for the int8 GEMMs. `z` written when bound.
|
||||
- `flow_x0_step` is MiniMax-H3's sampler step over a lane's rows, all f32, each product and sum
|
||||
one rounding: the velocity points at the data, so the clean estimate is `d = x + (1 - t) v` and
|
||||
the step blends toward it, `st = f32(1 - t)`, `d = f32(x + f32(st v))`,
|
||||
`r = f32(sigma_next / sigma)`, `x = f32(f32(r x) + f32(f32(1 - r) d))`. `t` (the timestep the
|
||||
transformer was conditioned on), `sigma` and `sigma_next` (the schedule's entries) are one f32
|
||||
value each; `v` is f32 or bf16, `x` f32.
|
||||
- `flow_res_multistep` is the same sampler's second-order form (k-diffusion's `res_multistep` at
|
||||
eta 0, DPM-Solver++ 2M): with the clean estimate `d = f32(x + f32(sigma v))`, the step also
|
||||
takes the previous step's estimate `x0`, `x = f32(f32(f32(r x) + f32(hb1 d)) + f32(hb2 x0))`,
|
||||
then writes `d` to `x0` for the next step (`x` and `x0` f32). With `order` below 1.5 it is the
|
||||
Euler step `x = f32(f32(r x) + f32(f32(1 - r) d))`, which a step with no previous estimate on its
|
||||
grid takes (core/gen/video_driver.cpp's `stage_sched` has the coefficients, `hb1 + hb2 = 1 - r`).
|
||||
`sigma`, `r`, `hb1`, `hb2` and `order` are one f32 value each; `v` f32 or bf16.
|
||||
|
||||
**The decoder** runs over a request's latent geometry, which `geom`, i32 on the device, carries
|
||||
(the parameters are fixed at declare). `mul`, `add`, `mean` and `std` are space-separated lists
|
||||
@@ -1596,6 +1577,38 @@ written.
|
||||
`axial` then reads as f32 positions. MiniMax-H3: `T` 7, `H` 16, `W` 16, `period` 1797,
|
||||
`scale` `2 pi`.
|
||||
|
||||
**The tiled encoder** encodes a one-frame media larger than a tile as vae.py's `tiled_encode` does
|
||||
(`comfy/ldm/minimax/vae.py`): the pixel plane is cut into tiles, each goes through the encoder
|
||||
alone (the per-level ops, issued per tile), and the tiles' moments are blended into one latent
|
||||
plane. These three ops are the plan, the cut and the blend. Their axis split is the decoder's rule
|
||||
above, except that an axis no longer than a tile is one tile `[0, L)`, short if need be.
|
||||
MiniMax-H3: `tile` 16 latents, `overlap` 4, `ratio` 16. An `M` in a shape below is that operand's
|
||||
row count, read from the operand; the ranged `M` argument is a ceiling only.
|
||||
|
||||
- `vtile_plan`: the plan for one frame of `geom` = `(clip, H, W)` pixels, split in latent units
|
||||
over the spatial axes and numbered row-major over (row band, column band). Row `t` of the i32
|
||||
`y [M, 22]`: the tile's first pixel `(y0, x0)` at [0] [1], its pixel extent `(th, tw)` at
|
||||
[2] [3] (`tile ratio`, except a lone short tile), and level `L`'s volume
|
||||
`(1, th / 2^min(L, 4), tw / 2^min(L, 4))` at `3 L + 4` for `L = 0..5` (levels 4 and 5 share a
|
||||
size).
|
||||
- `vtile_crop`: the frame's pixel plane `x [>= H W, 3]` (pixel `(Y, X)` at row `Y W + X`) cut into
|
||||
the plan's tiles: `y [M, 3]` holds the tiles' pixels tile-major, each tile's rows in plane
|
||||
order; `M` is the tiles' pixel count, more than the plane's since the tiles overlap.
|
||||
- `vtile_join`: the tiles' `n`-channel moments (`vtile_crop`'s row layout at latent extent)
|
||||
blended into the canvas `y [M, n]` of `geom` = `(clip, lat_h, lat_w)` in latent units, `M`
|
||||
`lat_h lat_w`. As in the stitch, position `(Y, X)` belongs to the tile `(i, j)` whose range
|
||||
`[start_i, start_{i+1})` holds it, at `(ly, lx)` within it, `T(i, j, ly, lx)` that tile's
|
||||
value; unlike the stitch, the neighbours are read unblended. `rd`, `wa` and `wb` are the
|
||||
stitch's, rounding to `x`'s dtype:
|
||||
|
||||
V = rd(rd(T(i-1, j, ly + tile - ev, lx) wa(ly, ev)) + rd(T(i, j, ly, lx) wb(ly, ev)))
|
||||
when i > 0 and ly < ev = ov_y[i-1], else T(i, j, ly, lx)
|
||||
y[(Y, X)] = rd(rd(T(i, j-1, ly, lx + tile - eh) wa(lx, eh)) + rd(V wb(lx, eh)))
|
||||
when j > 0 and lx < eh = ov_x[j-1], else V
|
||||
|
||||
Only a lone tile is short, and it has no neighbour, so a neighbour is always `tile` long on the
|
||||
blended axis.
|
||||
|
||||
### Video sparse attention
|
||||
|
||||
MiniMax-H3's step-distilled form (FastH3) was trained with FastVideo's video sparse attention: a
|
||||
@@ -1693,7 +1706,7 @@ pass starts from. Each op rounds once into its output (`libref/ref_video.cpp`).
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` `tpad`/opt `tpre`/opt | `x`, `w`w, `b`w, `geom`, `res`? → `y` |
|
||||
| `conv3d_ndhwc` | `M`(range) `cin` `cout` `k` `kt` `dtype` `stride`/opt `stride_t`/opt `causal`/opt `pad`/opt `reflect`/opt `tpad`/opt `tpre`/opt | `x`, `w`w, `b`w, `geom`, `res`? → `y` |
|
||||
| `group_norm` | `M`(range) `n` `groups` `eps`:f64 `act` `dtype` | `x`, `w`w, `b`w, `mod`?, `stats`:inout → `y` |
|
||||
| `tconv_dw` | `M`(range) `n` `k` `dtype` | `x`, `w`w, `b`w, `geom` → `y` |
|
||||
| `resize_bilinear` | `M`(range) `n` `dtype` | `x`, `geom` → `y` |
|
||||
@@ -1705,10 +1718,10 @@ innermost (NDHWC). `geom` is the request's volume, i32 on the device (the parame
|
||||
declare). An output holds at least the rows the volume writes; rows past them are not written.
|
||||
Every op honours its activation operands' row pitches. `rd` is a rounding into the output's dtype.
|
||||
|
||||
- `conv3d_ndhwc`: `x [>= T H W, cin]`, `y` and `res` `[>= T H W, cout]`, `geom = (T, H, W)`; `w` is
|
||||
PyTorch's Conv3d weight `[cout, cin, kt, k, k]` (a kernel may relayout it at load, as
|
||||
`conv2d_nhwc`'s layout hook does) and `b [cout]`. Stride 1, zero padding `kt/2` frames and `k/2`
|
||||
rows and columns on each side (`same`; `k` and `kt` odd):
|
||||
- `conv3d_ndhwc`: `x [>= T H W, cin]`, `y` and `res` `[>= rows out, cout]`, `geom = (T, H, W)`;
|
||||
`w` is PyTorch's Conv3d weight `[cout, cin, kt, k, k]` (a kernel may relayout it at load, as
|
||||
`conv2d_nhwc`'s layout hook does) and `b [cout]`. The defaults are stride 1 with zero padding
|
||||
`kt/2` frames and `k/2` rows and columns on each side (`pad` `same`; `k` and `kt` odd):
|
||||
`y[(t,i,j), o] = rd(f32(sum over (dt, kh, kw, ci) of w[o, ci, dt, kh, kw]
|
||||
x[(t+dt-kt/2, i+kh-k/2, j+kw-k/2), ci]) + b[o])`, terms outside the volume zero, f32 accumulation
|
||||
in an order of the implementation's (libref: the taps in `(dt, kh, kw)` order, each tap's
|
||||
@@ -1720,6 +1733,22 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t
|
||||
memory as `y` (the residual added in place); `x` never aliases `y`. x, y, res and w bf16 (also
|
||||
f32), b bf16 or f32. MiniMax-H3: `k` = `kt` = 3, `(cin, cout)` `(24, 512)`, `(512, 512)`,
|
||||
`(512, 24)`.
|
||||
The optional `stride` (rows and columns), `stride_t` (frames), `causal`, `pad` and `reflect`
|
||||
give a causal video VAE's convolutions (MiniMax-H3's `CausalConv3d`), for `k = kt = 3` only. The
|
||||
input is padded first, `ft` and `bk` frames in front and behind, `pt`, `pb`, `pl` and `pr` rows
|
||||
and columns above, below, left and right, then strided: output `(t, i, j)` reads
|
||||
`x[(t stride_t + dt - ft, i stride + kh - pt, j stride + kw - pl), ci]` (the same tap order),
|
||||
and `y` holds `((T + ft + bk - kt) / stride_t + 1) ((H + pt + pb - k) / stride + 1)
|
||||
((W + pl + pr - k) / stride + 1)` rows, PyTorch's output length (the divisions rounding
|
||||
toward negative infinity). The defaults are `ft = bk = kt/2` and `pt = pb = pl = pr = k/2`.
|
||||
`causal` 1 puts `ft = kt - 1` zero frames in front and none behind, so one frame in gives one
|
||||
frame out at any temporal stride, as the reference's dropped taps do. `pad` `down` pads one row
|
||||
below and one column right only (`pt = pl = 0`, `pb = pr = 1`), as `conv2d_nhwc`'s does.
|
||||
`reflect` 1 mirrors the spatial padding instead of zeroing it, as PyTorch's `F.pad` mode
|
||||
`reflect` does, without repeating the edge (`x[-n] = x[n]`, `x[D - 1 + n] = x[D - 1 - n]`), so
|
||||
a padded axis must be longer than its pad (`H, W >= 2`); the frame padding is always zeros.
|
||||
MiniMax-H3's encoder takes `reflect` 1 and `causal` 1 throughout, and `pad` `down` with
|
||||
`stride` 2 in its downsamplers.
|
||||
- `group_norm` is PyTorch's `nn.GroupNorm(groups, n)` on `[1, n, T, H, W]`: `x` and `y`
|
||||
`[>= M, n]` (`M` is `y`'s rows), group `g` the channels `[g n/groups, (g+1) n/groups)` of all
|
||||
`M` rows. `mean_g` and the biased `var_g` are over the group's `M n/groups` values, accumulated in
|
||||
@@ -1759,6 +1788,25 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t
|
||||
first, `stream` the parameter. `x` f32 `[M, n]` at its row pitch. MiniMax-H3: `n` 96 (the video's
|
||||
patch rows) and 32 (the soundtrack's), `stream` 1.
|
||||
|
||||
### Condition-noise augmentation
|
||||
|
||||
MiniMax-H3 blends every visual condition's patchified latents with noise before they condition
|
||||
the transformer (`_cond_video_rows`, `comfy/ldm/minimax/model.py`: weight `VISUAL_COND_TIMESTEP`
|
||||
0.999, the generator restarted for every condition). The arch applies the blend once a media item,
|
||||
over its encoded rows after the VAE encoder's fold. The weight is a declared constant, where
|
||||
`flow_renoise` stages its `sigma`. Audio conditions take no blend.
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `cond_aug` | `M`(range) `n` `stream` `aug`:f64 `dtype` | `seed`, `x`:inout |
|
||||
|
||||
- `cond_aug` blends condition rows with fresh noise, over `x`'s rows:
|
||||
`x[k, c] = f32(f32(a x[k, c]) + f32(oma z(k n + c)))`, `a` = `aug` in `[0, 1)`, `oma` the f32 of
|
||||
the f64 `1 - aug`, `z(e) = rad_philox_normal_s(seed, stream, e)` (`abi/rad_philox.h`), `seed`
|
||||
u32 `[2]` low word first. `x` f32 `[M, n]` at its row pitch. The caller issues one media item's
|
||||
rows at a time, so each item's draws start at `e = 0`. MiniMax-H3: `n` 96, `stream` 2, `aug`
|
||||
0.999.
|
||||
|
||||
## LTX-2
|
||||
|
||||
The ops LTX-2's audio-video transformer adds (`libref/ref_ltx.cpp`): its rotary over fractional
|
||||
@@ -2895,121 +2943,62 @@ associative. Without scratch, or above 32 rows, one workgroup per query walks th
|
||||
|
||||
### `kv_resolve`
|
||||
|
||||
Turns `qsa_select`'s block ids into the ring slots that hold them, and copies a block in when it is
|
||||
not resident. It is the one op a streamed KV group needs: `sel` is the only place the sparse path
|
||||
names KV storage, because `qsa_select` already writes `tb[b]`, the group's pool page id, and
|
||||
`attn_paged` uses each entry as a raw pool index. When the group streams, the device pool is
|
||||
`slots` blocks deep and the id space is `blocks`, so an id is no longer an address; after this op
|
||||
every entry is a slot of `kv_cache` and the attention is unchanged.
|
||||
Turns `qsa_select`'s block ids into the ring slots that hold them, copying a block in from the host
|
||||
mirror when it is not resident. `qsa_select` writes pool page ids and `attn_paged` reads each entry
|
||||
as a raw pool index, so when a group streams (its pool is `slots` blocks deep over a `blocks`-wide id
|
||||
space) this op, between them, is all the sparse path needs; the attention is unchanged. The design
|
||||
is docs/KV-STREAMING.md §3.4.
|
||||
|
||||
The layouts, which the schema cannot state (the maps are one format, and the two block planes are
|
||||
bytes, so the op is the same code at every cache layout). The shape given is the operand's extent:
|
||||
The layouts, which the schema cannot state (the op is the same code at every cache layout):
|
||||
|
||||
- **`sel`** — `i32 [M, sel_pitch]`, inout. In: block ids. Out: the ring slot holding each block, for
|
||||
the entries below `nsel[q]`; the -1 padding of `qsa_select` past them is untouched.
|
||||
- **`nsel`** — `i32 [M]`, in. The valid entries of each row, as `qsa_select` wrote them.
|
||||
- **`res`** — `i32 [blocks]`, inout. Block id -> slot, or -1 absent; -2 is a claim this call has made
|
||||
and never leaves it behind.
|
||||
- **`slot_block`** — `i32 [slots]`, inout. Slot -> block id, or -1 free.
|
||||
- **`slot_state`** — `i32 [slots, 2]`, inout. Column 0 is the epoch that last used the slot, column 1
|
||||
a two-bit **heat counter** in `[0, 3]`: bumped by one, clamped at 3, on every use (a hit or a
|
||||
placement, once a slot a call), and halved when the sweep passes the slot. 31 bits of the i32 are
|
||||
unused, so the policy needs no new field and no ABI change.
|
||||
- **`ctl`** — `i32 [16]`, inout. `[0]` epoch, `[1]` clock hand, `[2]` blocks placed by the last call,
|
||||
`[3]` overflow (latched), then `u64` misses, lookups and calls from `[4]`, 8-byte aligned, then
|
||||
`[10]` the largest selection union one call has seen (distinct blocks, hits plus misses), `[11]`
|
||||
the largest number of blocks one call has placed, and `[12]` the largest number of distinct
|
||||
blocks one call has claimed — the depth its miss list had to hold. The maxima are the measurement
|
||||
a ring and a claim list are sized from: `[10]` against the ring's depth says whether one launch
|
||||
can overflow it, `[12]` against `max_seqs * sel_pitch` says whether a claim list is wide enough.
|
||||
- **`host`** — bytes, `[blocks, block_bytes]`, in. The layer's authoritative mirror, identity block
|
||||
layout: block `b` at `b * block_bytes`, exactly as the design note lays it out.
|
||||
- **`kv_cache`** — bytes, `[slots, block_bytes]`, inout. The layer's ring, the same operand
|
||||
`attn_paged` and `kv_store` take as `RAD_KV(group, layer)`.
|
||||
- **`sel`** — `i32 [M, sel_pitch]`, inout: block ids in, ring slots out, below `nsel[q]`; the `-1`
|
||||
padding past it is untouched.
|
||||
- **`nsel`** — `i32 [M]`, in: the valid entries of each row. Above `sel_pitch` is refused.
|
||||
- **`res`** — `i32 [blocks]`, inout: block -> slot, or `-1` absent (`-2` is a claim within a call).
|
||||
- **`slot_block`** — `i32 [slots]`, inout: slot -> block, or `-1` free. Its extent is the ring the
|
||||
call may address; the declared `slots` (the carved ring, `RadBuildCtx::kv_resident_blocks` in
|
||||
blocks) is the ceiling it may not pass.
|
||||
- **`slot_state`** — `i32 [slots, 2]`, inout: the epoch of the slot's last use, and a two-bit heat
|
||||
counter in `[0, 3]`, bumped on a use (once a slot a call) and halved when the sweep passes.
|
||||
- **`ctl`** — `i32 [16]`, inout: `[0]` epoch, `[1]` clock hand, `[2]` blocks placed by the last call,
|
||||
`[3]` overflow (latched), u64 misses, lookups and calls from `[4]` (8-byte aligned), and the
|
||||
largest union `[10]`, placement `[11]` and claim count `[12]` of one call: the measurements a ring
|
||||
and a claim list are sized from.
|
||||
- **`host`** — bytes `[blocks, block_bytes]`, in: the layer's mirror, block `b` at `b * block_bytes`.
|
||||
- **`kv_cache`** — bytes `[slots, block_bytes]`, inout: the layer's ring, `RAD_KV(group, layer)`.
|
||||
|
||||
One call, in order: bump the epoch, one lookup per distinct block, one victim per miss, re-point
|
||||
both maps, copy each missed block, rewrite every valid selection entry. What each step owes:
|
||||
One call:
|
||||
|
||||
- **One call is one epoch.** The epoch is bumped first; a resident block takes the new epoch and
|
||||
bumps its heat counter, so the sweep can tell what this call has already touched from what it may
|
||||
take.
|
||||
- **One lookup per distinct block, and the map is its own set.** A miss is claimed once, `-1` to
|
||||
`-2`, so a block named by several rows is claimed by the first of them. `sel` entries past
|
||||
`nsel[q]` are `-1` padding and are not touched; `nsel[q]` above `sel_pitch` is refused rather than
|
||||
steered into the neighbouring row.
|
||||
- **The miss list is in ascending block id, and that is part of the contract.** First-appearance
|
||||
order would let the row that claimed a block first decide which slot it lands in, so two
|
||||
implementations of one contract would produce different tables. Ascending is a fact about the
|
||||
claim set, not about the map: a device launch sorts the claims it made, or — above the shared
|
||||
claim list — collects the smallest `slots` of them a window of the id space at a time, both over
|
||||
the selection's entries. `blocks` is the id space (`max_seqs * ceil(max_ctx / block_size)`, 102 400
|
||||
at the parity shape) and never the size of one launch, so nothing here walks it.
|
||||
- **The claim list's depth is derived, not a constant.** One claim is one distinct absent block a
|
||||
selection entry names, so a launch makes at most `M * sel_pitch` of them (and at most `lookups`,
|
||||
which is `sum_q nsel[q]`). The device kernel sizes its shared list at
|
||||
`next_pow2(min(M * sel_pitch, the workgroup's LDS room))`, so any `--max-num-seqs` follows from the
|
||||
operands: `max_seqs * 513` is 2052 at four sequences, 4104 at eight. There is no cap to raise and
|
||||
none to fall off, and `ctl[12]` reports the largest count a launch has made.
|
||||
- **The victim rule is the block's own slot if it is free, then a free slot, then CLOCK, from a hand
|
||||
that ends just past the last slot taken, with second chance.** A miss whose id is inside the ring
|
||||
and whose own slot is free goes to slot `b`, so while the context is shorter than the ring the map
|
||||
is `res[b] = b` and adjacent block ids land in adjacent slots of one layer's stripe, which is the
|
||||
order the attention's gather reads them in. That is placement only: it takes a slot only when
|
||||
that slot is free and it does not move the hand, so it never evicts, and a miss it cannot place
|
||||
falls through to the walk below from the hand it would always have seen -- at depth, where most ids
|
||||
are past `slots`, the same blocks land in the same slots as before. A free slot holds no block, so
|
||||
taking it costs nothing and it is claimed before any resident block is considered; the ring's empty
|
||||
region fills before an eviction.
|
||||
A slot this call already used (a hit's, or a miss's already claimed) is passed and keeps its
|
||||
heat counter, free or not; when a whole turn finds no free slot, the sweep halves the counter of a
|
||||
warm slot (`old >> 1`) and passes it, and takes a cold one (counter 0). The hand still **picks**
|
||||
the victim -- a per-visit decision, not a search -- so the policy costs no reduction, no barrier
|
||||
and no extra traffic: an add-and-clamp in place of a constant store and a shift in place of a
|
||||
zero. That is why it is affordable where an exact LRU is not: the epoch-ordered minimum needs a
|
||||
collective reduction per miss, which costs more than the choice is worth. The free scan halves no
|
||||
counter and leaves the hand alone when it finds nothing, so a ring with no free slot takes exactly
|
||||
the victim the sweep names. Every write clamps the counter to 3,
|
||||
so two passes halve any value to 0 and the third places the miss: a sweep visits at most
|
||||
`3 * slots` slots. The counter is the same decayed-use-count mechanism the streamed experts
|
||||
already replace by (`core/place/heat.*`), at ring granularity.
|
||||
- **The ring must hold the union of one call's selection.** A hit holds a slot and a miss needs
|
||||
another, so `hits + misses <= slots` is the sizing rule. What that union is depends on the launch:
|
||||
a decode step takes the ring and a prefill step takes the one-layer stage, and a decode step issues
|
||||
one row a sequence (`1 + n_spec` rows a sequence under speculation), so at most
|
||||
`max_seqs * (1 + n_spec) * (topk + 1)` blocks -- which is the ceiling `--kv-resident` is held to at
|
||||
startup, and `ctl[10]` is what says at run time that the bound held. Overflow is not silent: an unplaced miss reverts to `-1` (so a later call may claim it)
|
||||
and its selection entries are rewritten to slot 0 -- a defined address inside the ring, because a
|
||||
block id is an address past it that the attention dereferences unchecked -- with `ctl[3]` latched.
|
||||
A caller that finds `ctl[3]` set must discard the step: those entries do not name their blocks, so
|
||||
the launch's output is wrong by construction and is never served.
|
||||
- **The copied bytes are the mirror's bytes.** One `memcpy` per placed miss, `block_bytes` long,
|
||||
nothing converted, so a streamed block is bit-identical to what the writer put in the mirror.
|
||||
That is why `block_size` is not a parameter and `block_bytes` is: the op never reads an element,
|
||||
and a `block_size` key would make it a KV group's consumer, taking the block size the block
|
||||
manager reads away from the resolved attention kernel.
|
||||
- **`slots` is the operand's, not only the parameter's.** `slot_block`'s extent is the ring a call
|
||||
may address, exactly as `sel`'s extent states `M` and its row pitch states `sel_pitch`; the declared
|
||||
parameter is the ceiling a call may not pass. The pool is planned after the program is built, so a
|
||||
ring the engine sized smaller (`--kv-resident`, when it streams at all) reaches the op as a
|
||||
shorter operand. The declared ceiling is the ring the deployment carves -- `--kv-resident` in
|
||||
tokens rounded up to whole blocks, clamped to the group's context (`RadBuildCtx::
|
||||
kv_resident_blocks`) -- and not the block-id space `blocks`, so the geometry an engine reports for
|
||||
this op is the ring it is issued with; with nothing streaming the two are equal. The ceiling also
|
||||
sizes the row's scratch.
|
||||
- **The miss list is scratch, not an operand.** It is one launch's temporary; a device row declares
|
||||
`next_pow2(slots) + slots` i32s through its scratch hook (the miss list, then the slots it pairs
|
||||
with) and the reference needs none. The claim list before the sort is dynamic LDS, not scratch,
|
||||
while it fits: the sort reads every element from every thread, so it belongs in the workgroup, and
|
||||
the row sizes that launch's LDS from the bound above. A launch too wide for that room sorts the
|
||||
list in the scratch's first plane, which is why it is padded to a power of two.
|
||||
- **The op is stateful, and therefore not concurrent.** epoch, hand, heat counters and counters
|
||||
live between launches, so the row must not carry `rad_kernel_concurrent`
|
||||
(`abi/rad_abi.h:493`); without the promise the engine orders the launch behind everything before
|
||||
it, which is what the map needs. It is still recordable: the maps, the ring and the mirror are
|
||||
fixed-size from the group's declaration, so addresses and pitches never move and a replay is
|
||||
valid.
|
||||
- **The caller brings the state up.** `res` and `slot_block` filled with `-1`, `slot_state` and
|
||||
`ctl` zeroed. There is no reset op: a residency map lives as long as its pool.
|
||||
1. **Bump the epoch.** A hit stamps its slot with it and bumps its heat, so the sweep knows what
|
||||
this call already uses.
|
||||
2. **One lookup per distinct block.** A miss is claimed once (`-1` -> `-2`), so the map is its own
|
||||
set.
|
||||
3. **The miss list in ascending block id.** First-appearance order would let thread timing decide
|
||||
placement. A device launch sorts the claims it made; nothing walks the id space `blocks`, so a
|
||||
launch costs its selection. A claim list holds at most `M * sel_pitch` ids (at most
|
||||
`sum_q nsel[q]`); the device kernel sizes it from those operands.
|
||||
4. **One victim per miss.** The block's own slot if it is free (a context shorter than the ring
|
||||
stays at identity, and adjacent ids read adjacent slots), else a free slot, else CLOCK from the
|
||||
hand: a slot this call used is passed, a warm slot's counter is halved and passed, a cold one is
|
||||
taken. The hand picks the victim per visit, so the policy needs no reduction, unlike an exact
|
||||
LRU. A 3 survives two passes, so a sweep visits at most `3 * slots` slots.
|
||||
5. **Re-point both maps**, a placement counting as a use.
|
||||
6. **Copy** `block_bytes` per placed block, nothing converted. Hence `block_bytes` rather than
|
||||
`block_size`: the op never reads an element, and a `block_size` key would make it the KV group's
|
||||
consumer in place of the attention.
|
||||
7. **Rewrite** every valid entry as its slot.
|
||||
|
||||
- **The ring must hold one call's selection union** (`hits + misses <= slots`): a decode step's is at
|
||||
most `max_seqs * (1 + n_spec) * (topk + 1)` blocks, the floor `--kv-resident` is raised to, and
|
||||
prefill takes the stage instead. An unplaced miss reverts to `-1`, its entries become slot 0 (a
|
||||
defined address; a block id would be read past the ring) and `ctl[3]` latches; the caller must
|
||||
discard the step.
|
||||
- **The miss list is the row's scratch**: `next_pow2(slots) + slots` i32s on the device (a launch
|
||||
too wide for the LDS claim list sorts there); the reference needs none.
|
||||
- **Stateful, so not concurrent**: the row carries no `rad_kernel_concurrent` promise. It is
|
||||
recordable, since its addresses and pitches never move.
|
||||
- **The caller brings the state up**: `res` and `slot_block` filled with `-1`, `slot_state` and `ctl`
|
||||
zeroed. There is no reset op.
|
||||
|
||||
### `qsa_tail_store`
|
||||
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
# Preparing your rig
|
||||
|
||||
From bare hardware to a serving Qwen3.8-Flash-Next on two Radeon AI PRO R9700s: firmware, Arch Linux,
|
||||
Docker, peer-to-peer between the cards, power tuning, compose. Each step ends with a check.
|
||||
|
||||
The reference rig: MSI MPG X670E CARBON WIFI, Ryzen 9 7950X3D, 64 GB RAM, one 2 TB NVMe, two R9700s
|
||||
in the two CPU-attached x16 slots. Another board needs the same settings under its own menu names.
|
||||
|
||||
## 1. Firmware setup
|
||||
|
||||
Enter the firmware setup (Del at power-on) and set:
|
||||
|
||||
| Setting | Value | Why |
|
||||
|---|---|---|
|
||||
| XMP / EXPO | profile 1 | the RAM runs at its rated speed instead of JEDEC defaults |
|
||||
| Above 4G Decoding | enabled | needed for Resizable BAR |
|
||||
| Re-Size BAR Support | enabled | the host writes each dispatch's arguments straight into VRAM, and peer access needs the large BAR |
|
||||
| CSM | disabled | Resizable BAR needs pure UEFI boot |
|
||||
| Secure Boot | disabled | the Arch install medium is not signed |
|
||||
| PCIe lane split of the two x16 slots | x8/x8 | both cards on CPU lanes |
|
||||
| PCIe link speed of both slots | Gen5 | stops the slots training at a lower generation |
|
||||
| Onboard Wi-Fi, Bluetooth | disabled | the rig is wired, and an unused device is one less driver and IRQ |
|
||||
|
||||
Save and exit (F10).
|
||||
|
||||
## 2. Install Arch Linux
|
||||
|
||||
Boot the [Arch ISO](https://archlinux.org/download/) from USB with the network cable plugged in, then
|
||||
run `archinstall` with these choices. Leave everything else at its default.
|
||||
|
||||
| archinstall item | Choice |
|
||||
|---|---|
|
||||
| Disk configuration | best-effort default layout, ext4 |
|
||||
| Swap | off |
|
||||
| Bootloader | systemd-boot |
|
||||
| User account | your user, as superuser (sudo) |
|
||||
| Profile | Minimal (no desktop environment) |
|
||||
| Audio | none |
|
||||
| Kernels | linux |
|
||||
| Network configuration | NetworkManager |
|
||||
| Additional packages | `openssh git base-devel` |
|
||||
|
||||
Install, reboot into the new system, log in on the console and start the SSH server:
|
||||
|
||||
```sh
|
||||
sudo systemctl enable --now sshd
|
||||
ip -4 addr show # note the rig's address
|
||||
```
|
||||
|
||||
Go back to your PC. Everything from here on runs over SSH:
|
||||
|
||||
```sh
|
||||
ssh-copy-id you@RIG_ADDRESS
|
||||
ssh you@RIG_ADDRESS
|
||||
```
|
||||
|
||||
## 3. Docker and the AUR helper
|
||||
|
||||
```sh
|
||||
sudo pacman -Syu --needed docker docker-compose docker-buildx
|
||||
sudo systemctl enable --now docker
|
||||
sudo usermod -aG docker,render,video "$USER" # log out and back in
|
||||
|
||||
git clone https://aur.archlinux.org/yay.git && (cd yay && makepkg -si) && rm -rf yay
|
||||
yay -S rocm-bandwidth-test
|
||||
```
|
||||
|
||||
## 4. Kernel parameters
|
||||
|
||||
Edit the boot entry archinstall wrote (`/boot/loader/entries/*_linux.conf`) and append these to its
|
||||
`options` line:
|
||||
|
||||
```
|
||||
iommu=pt amdgpu.ppfeaturemask=0xfff7ffff amdgpu.ras_enable=0
|
||||
```
|
||||
|
||||
- `iommu=pt` keeps the IOMMU in passthrough, so the cards can reach each other's memory and pinned
|
||||
host memory maps without translation.
|
||||
- `amdgpu.ppfeaturemask=0xfff7ffff` is the driver's default mask with the OverDrive bit set. OverDrive
|
||||
is what makes the undervolt in step 6 writable.
|
||||
- `amdgpu.ras_enable=0` turns VRAM ECC off. With ECC on, each card reserves about 2 GB of its VRAM.
|
||||
|
||||
Arch's stock kernel has enabled peer-to-peer (`CONFIG_HSA_AMD_P2P`) since 7.1.2, so a current install
|
||||
needs no custom kernel. An older one would need a rebuild with that option. Make the entry the default
|
||||
and reboot:
|
||||
|
||||
```sh
|
||||
bootctl list # the linux entry, with the new options
|
||||
sudo bootctl set-default "$(basename /boot/loader/entries/*_linux.conf)"
|
||||
sudo reboot
|
||||
```
|
||||
|
||||
## 5. Check the cards
|
||||
|
||||
```sh
|
||||
cat /proc/cmdline # the three parameters
|
||||
zcat /proc/config.gz | grep -E 'HSA_AMD_P2P|PCI_P2PDMA' # both =y
|
||||
lspci -vv -d 1002:7551 | grep 'Region 0' # size=32G on both cards (ReBAR)
|
||||
sudo journalctl -k -b | grep 'available PCIe bandwidth' # 32.0 GT/s PCIe x8 per card
|
||||
cat /sys/class/drm/card*/device/mem_info_vram_total # 34208743424 (32624 MiB) on both: ECC off
|
||||
rocm-bandwidth-test -a
|
||||
```
|
||||
|
||||
In the bandwidth matrices, each card reaches about 28 GB/s to and from the CPU. Every GPU-to-GPU cell
|
||||
must show a rate. A missing cell means no peer access: check `iommu=pt` and the BAR size.
|
||||
|
||||
An idle link reads 2.5 GT/s in `lspci`, and that is normal. If one card measures half the other's rate
|
||||
under load, the PCIe power state of its root port is stuck one level down, and a reboot clears it.
|
||||
|
||||
## 6. Power limit and undervolt
|
||||
|
||||
210 W costs under 1% of decode speed against the 300 W default. Use -70 mV: at -75 mV the reference
|
||||
rig's heaviest GEMMs gave run-to-run differences. Both settings are lost at every reboot, and the
|
||||
undervolt also at every runtime resume of the card. A boot service applies them and keeps the cards
|
||||
awake:
|
||||
|
||||
```sh
|
||||
sudo tee /usr/local/sbin/gpu-tune.sh >/dev/null <<'EOF'
|
||||
#!/bin/bash
|
||||
# Undervolt and power-cap every R9700, then return the cards to automatic clocks.
|
||||
# Needs amdgpu.ppfeaturemask=0xfff7ffff on the kernel command line (OverDrive).
|
||||
set -u
|
||||
OFFSET='vo -70'
|
||||
CAP_UW=210000000
|
||||
rc=0
|
||||
for d in /sys/bus/pci/drivers/amdgpu/0000:*; do
|
||||
[ "$(cat "$d/device")" = 0x7551 ] || continue
|
||||
for _ in $(seq 1 30); do [ -e "$d/pp_od_clk_voltage" ] && break; sleep 1; done
|
||||
[ -e "$d/pp_od_clk_voltage" ] || { echo "${d##*/}: no OverDrive interface" >&2; rc=1; continue; }
|
||||
echo on > "$d/power/control" # a runtime resume drops the OverDrive table
|
||||
echo manual > "$d/power_dpm_force_performance_level"
|
||||
echo "$OFFSET" > "$d/pp_od_clk_voltage"
|
||||
echo c > "$d/pp_od_clk_voltage"
|
||||
echo auto > "$d/power_dpm_force_performance_level"
|
||||
for h in "$d"/hwmon/hwmon*; do echo "$CAP_UW" > "$h/power1_cap"; done
|
||||
echo "${d##*/}: $(grep -A1 OD_VDDGFX "$d/pp_od_clk_voltage" | tail -1)," \
|
||||
"cap $(( $(cat "$d"/hwmon/hwmon*/power1_cap) / 1000000 )) W"
|
||||
done
|
||||
exit $rc
|
||||
EOF
|
||||
sudo chmod +x /usr/local/sbin/gpu-tune.sh
|
||||
|
||||
sudo tee /etc/systemd/system/gpu-tune.service >/dev/null <<'EOF'
|
||||
[Unit]
|
||||
Description=R9700 undervolt and power cap
|
||||
After=multi-user.target
|
||||
ConditionKernelCommandLine=amdgpu.ppfeaturemask=0xfff7ffff
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/gpu-tune.sh
|
||||
RemainAfterExit=yes
|
||||
TimeoutStartSec=90
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
sudo systemctl enable --now gpu-tune.service
|
||||
journalctl -u gpu-tune -b --no-pager | tail -2 # -70mV, cap 210 W on both cards
|
||||
```
|
||||
|
||||
## 7. Serve Qwen3.8-Flash-Next
|
||||
|
||||
```sh
|
||||
git clone https://codeberg.org/StillDeadcode/radiance.git
|
||||
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
|
||||
|
||||
mkdir -p ~/models/rad
|
||||
curl -L -C - -o ~/models/rad/qwen3.8-next-flash-fp8-iq4r-moe.rad \
|
||||
https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe/resolve/main/qwen3.8-next-flash-fp8-iq4r-moe.rad
|
||||
# 114 GiB; -C - resumes after an interruption
|
||||
|
||||
cp .env.example .env && chmod 600 .env
|
||||
```
|
||||
|
||||
Set these in `.env`:
|
||||
|
||||
| Variable | Value |
|
||||
|---|---|
|
||||
| `RADIANCE_MODELS` | `/home/you/models/rad` |
|
||||
| `RADIANCE_API_KEY` | a long random string (`openssl rand -hex 32`) |
|
||||
| `RADIANCE_UID`, `RADIANCE_GID` | `id -u`, `id -g` |
|
||||
| `RENDER_GID`, `VIDEO_GID` | `getent group render \| cut -d: -f3`, the same for `video` |
|
||||
|
||||
```sh
|
||||
docker compose -f flashnext.yaml up -d
|
||||
docker compose -f flashnext.yaml logs -f # Ctrl-C once it serves; the container keeps running
|
||||
```
|
||||
|
||||
The startup log must say `device: the 2 cards reach each other's memory directly (peer to peer)`. A
|
||||
`no peer-to-peer access` warning means step 5's checks did not all pass. Then:
|
||||
|
||||
```sh
|
||||
KEY=$(grep ^RADIANCE_API_KEY= .env | cut -d= -f2)
|
||||
curl -s localhost:8000/health
|
||||
curl -s localhost:8000/v1/chat/completions -H "Authorization: Bearer $KEY" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"messages":[{"role":"user","content":"What is 65 * 3?"}]}'
|
||||
```
|
||||
|
||||
The container restarts with the machine. `docker compose -f flashnext.yaml down` stops it.
|
||||
[`DOCKER.md`](DOCKER.md) lists the other models' compose files, and [`GUIDE.md`](GUIDE.md) covers
|
||||
serving flags and the API.
|
||||
+8
-10
@@ -188,11 +188,12 @@ also matches a norm leaves the norm as it is.
|
||||
| `awq` | each input column scaled by its activation magnitude to a searched power, then a per-block clip search, both against the Hessian; the column scales are the encoding's last scale level |
|
||||
| `autoround` | sign-gradient descent on a rounding offset per value and a range factor per block, against the Hessian; `iters` steps of N·K² multiply-adds each |
|
||||
| `paroquant` | a channel scaling and `stages` rounds of Givens pair rotations, learned against the Hessian, then AutoRound on the rotated weight; the encoding's `givens` transform |
|
||||
| `m2xfp4` | M2XFP's weight-side Sg-EM (arXiv 2601.19213): MXFP4 plus one metadata byte a group of 32, each subgroup of 8's extra mantissa k and the exponent's bias chosen by least squared error; its own scheme `m2xfp4` (spec.md), served by `gemm_nt_q` at dtype m2xfp4. `adaptive=0` pins the bias, `wide=1` widens it to {-2..2} |
|
||||
| `ggml` | `type=` one of llama.cpp's formats (q4_0, q4_1, q5_0, q5_1, q8_0, q2_K..q6_K, iq4_nl, iq4_xs, iq2_xxs, iq2_xs, iq2_s, iq3_xxs, iq3_s, iq1_s, iq1_m), chosen by llama.cpp's own search, imatrix-weighted; the codes are byte for byte llama.cpp's, stored as each type's affine planes. iq2_xxs, iq2_xs and iq1_s need `--imatrix` |
|
||||
| `cast` | a float weight in another float dtype (`dtype=` f32, bf16, f16, fp8_e4m3, fp8_e5m2), no scale |
|
||||
| `import` | rad-convert's own, not a plugin: the numbers a quantised release ships, in the spelling the kernels read, instead of quantising again. `codes=uN` makes a symmetric grid's signed codes unsigned under a zero point of 2^(N-1); `zero=` is the zero plane's dtype (u4, u8); `scale=` the scale's (f16, bf16, f32), each shipped scale rounded to nearest; `block=RxC` repeats an FP8 scale shipped per row or per tensor over that block grid. It reads an imported integer grid (GPTQ, CT-INT4) or an FP8 weight with a scale per row or per tensor, refuses any other quantised form by name, and keeps a plain float weight as it is. The run reports per rule how many weights it re-expressed and how many scales the new dtype rounded |
|
||||
|
||||
Every quantiser except `ggml`, `cast` and `import` takes the grid options:
|
||||
Every quantiser except `m2xfp4`, `ggml`, `cast` and `import` takes the grid options:
|
||||
|
||||
| option | |
|
||||
|---|---|
|
||||
@@ -658,15 +659,12 @@ Declare at the shapes you serve:
|
||||
At `--tp > 1` every rank declares at once, each on its own thread and device, as the engine does:
|
||||
a collective's `init` is a rendezvous, so declaring rank 0 alone at world size 2 hangs.
|
||||
|
||||
A collective is then measured as the exchange, not as one rank's copy of it. Each rank gets its own
|
||||
operands -- drawn with its own seed, so a fold of two identical halves cannot pass a correctness
|
||||
check -- its own scratch, its own stream, and the instance its own declare made: `init` is what
|
||||
publishes the peer bundle (scratch, flags, sequence counters) and a launch with no instance is
|
||||
refused before it starts. The candidate's launches are fired on every rank at once and the clock
|
||||
stops when the last stream drains, so the reported time is the round trip through the peer, which
|
||||
is what the served step pays; timing rank 0 alone would time a local copy. Candidates are still
|
||||
judged against the defaults on rank 0's output. A row that is not collective runs on rank 0 alone,
|
||||
as it always did.
|
||||
A collective is measured as the exchange. Each rank gets its own operands (drawn with its own seed,
|
||||
so a fold of two identical halves cannot pass), its own scratch and stream, and the instance its
|
||||
own declare made, since `init` publishes the peer bundle a launch needs. Every rank fires the
|
||||
candidate's launches at once and the clock stops when the last stream drains, so the time is the
|
||||
round trip through the peer, as a served step pays it. Candidates are judged against the defaults
|
||||
on rank 0's output. A row that is not collective runs on rank 0 alone.
|
||||
|
||||
Before trusting a cache, check that the tuned variants beat the defaults. `RADIANCE_TUNE` pins a
|
||||
kernel's axes for such a comparison; it is a measurement aid, not a deployment setting.
|
||||
|
||||
Reference in new issue
Block a user