radiance 1.14.0

New models and formats:
- libr3d: a kernel library for RDNA3 (gfx11) cards
- nomic-embed-text-v2-moe (the nomicbert plugin)
- Gemma 4 E2B with its per-layer MLP width, and Google's unmodified E2B/E4B directories in bf16
- DeepSeek-V4.1-Flash converted straight from its release: the Engram tables, the fused imatrix and
  rad-convert --chat-template for a release that ships no template
- GGUF Q8_0, Q4_K and Q6_K tensors import as their planes; rad-convert writes them without a recipe
- Qwen3.8-Flash-Next-FP8 converts and serves through qwen4exp_fp8

Speed:
- hc_read's decode kernels as one grid (34.7 -> 25.2 us at 4 rows) and its tiled up-mix pipelined
- gemm_fp8a8: the narrow form's scales staged through LDS (Flash-Next int8 at 32 rows 83.6 -> 68.3
  us), the gated three-tile form at 8 waves (gate_up at 48 rows 272.9 -> 180.6 us)
- Qwen3.8-27B: the delta net's out-projection read beside its decode recurrent update (x1 19.40 ->
  19.10 ms a step), and the verify's split-KV attention sized by context depth (x3 at 180K 42.4 ->
  40.3 ms a step)
- Hy-Memory (HYV3) decode: fused QK norm, RoPE and KV store, residual adds folded into the norms,
  coalesced one-token expert GEMMs
- spechub: the coupled verify walks the live candidates only (151 -> 31 us a launch)

Speculation:
- DFlash2: lossless coupled acceptance at T > 0 (--draft-coupling on)
- A block drafter's proposals verified as a tree, on by default for the Gemma 4 31B's DFlash2, with
  a block-16 tree that runs its short block under load

Features:
- Decode-hot residency: --draft-expert-placement host, --expert-profile, --expert-pin-top, and
  --expert-stats FILE for the routed experts each layer selects
- --ngram-placement ram=DIR: one n-gram table shared by engines on separate cards
- Prefix cache: --prefix-resume exact (default) resumes a hit on the cold run's own chunk grid, so it
  answers bit-identically; snapshots at a head other prompts share, from 528-token prompts, and for
  tip-only one drafter window below the tip; hits on models whose KV groups have different block
  sizes; the snapshot store keeps a floor of 8 ahead of --host-headroom-mib
- Typed tool-call argument tags; rad-chatparse --request renders and reads back one request as the
  server does
- MiniMax-H3: keyframes ride a latent upscale
- Gemma 3's fused all-reduce junction on the lossy wire

Fixes:
- A speculative step shorter than its band (an MTP step of 4 rows at gqa 8) no longer stops the
  engine with a scratch refusal at issue (#293)
- --p2p off: prefill back to 1.12.0's rate; 1.13.0's push check read a host-memory slot over the link
  twice (#323)
- A chat template that cannot render a conversation is refused at load, not mid-request
- imatrix entries found under llama.cpp's spelling; the W4A8 prefill's tail scale read; the GDN conv
  kernels on an f32 weight; dense integer rows at the group they compute (a Q8_0 weight at group 32)
- --expert-profile refuses a profile recorded on another model
- hc_read's one-grid wait traps past its deadline instead of reading a stale value

Changes: Plugin ABI 31, unchanged. RADIANCE_DRAFT_TREE, DFLASH2_TREE_NODES, DFLASH2_TREE_TEMP and
DFLASH_Q_TEMP are gone (trees run where the probe says they pay; temperatures 1.25 / 0.6).
This commit is contained in:
Deadcode committed 2026-10-29 12:04:24 +01:00
1 parent 481fcd5df0
commit 4a61d7296b
160 files changed
+8790 -6819

No files matched your search

+3 -4
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.21)
# VERSION is the server release that /version reports. The plugin ABI version is separate and is
# read from abi/rad_abi.h below.
project(radiance VERSION 1.13.0 LANGUAGES C CXX)
project(radiance VERSION 1.14.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
@@ -299,9 +299,8 @@ if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt)
endif()
# libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP
# toolchain. It declares itself for `^gfx11` and returns without a target when the build's
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it (and a card
# with no kernel library of its own keeps refusing device-only ops, which is the rule, not a
# regression: docs/PLUGIN.md §10).
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it. A card
# with no kernel library of its own refuses device-only ops (docs/PLUGIN.md §10).
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt)
add_subdirectory(libr3d)
endif()
+39 -10
View File
@@ -22,14 +22,21 @@ Written by Deadcode, with contributions from:
through w4a16_asym, and the Ornith-1.5-122B compose files
- mechkbfan: the token embedding in the pinned host pool
- Code000: the n-gram gather on the card and the MTP head's history-pass skip, and the MTP draft
coupling with its cooperative verify (--draft-coupling)
coupling with its cooperative verify (--draft-coupling), the W4A8 prefill's tail scale read, and
the ISA instruments' VGPR granule, back-edge count and fail-closed parse
- baKon: three-rank tensor parallelism, serving any world size from the shipped container, the
request log, an uneven world's per-rank KV and weights split, --rope-scaling, the model entry's
context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8
wire, the diagnosis of the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, curl,
jq and a CA bundle in the image with hfget.sh under its busybox, rad-export, --prefill-interleave,
runtime LoRA adapters served beside the base model and picked per request, and the prefix cache's
reserved snapshots held until their save lands
reserved snapshots held until their save lands, --expert-stats, imatrix entries in llama.cpp's
spelling, typed tool-call argument tags, a chat template refused at load when it cannot render,
rad-chatparse --request, a draft head's routed experts in host memory (--draft-expert-placement
host) and decode-hot residency (--expert-profile, --expert-pin-top), prefix hits over KV groups
of different block sizes and a hybrid's window in the checkpoint slot, --prefix-resume exact, and
DeepSeek-V4.1-Flash's conversion from its release (the Engram tables, the fused imatrix, the
UD-IQ1_S recipe and rad-convert --chat-template)
- hazyumps: static YaRN for the Qwen rotary paths
- malic: ParoQuant, with its MXFP4, int5 and int4 checkpoints imported and served, the Givens
rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and 4-bit
@@ -42,8 +49,10 @@ Written by Deadcode, with contributions from:
drafters), the embedding scale rounded as Hugging Face rounds it, block drafters' drafts
accepted on the card, z-lab's DFlash drafter drafting on after a prefix-cache hit and the 31B's
GPTQ calibration tap, and for speculation the MTP head's first draft read up to where it sits, no
step queued behind one that ends its requests, and a step's tokens streamed before the drafter's
passes end
step queued behind one that ends its requests, a step's tokens streamed before the drafter's
passes end, a block drafter's proposals verified as a tree, the 31B's block-16 DFlash2 tree with
its short block under load, a block drafter's window carried in the window snapshot, and window
snapshots from short prompts
- redxherring: --model taking a Hugging Face repo id
- Smellyyyy: the idea behind --prefill-interleave
- gearwave00001: /v1/messages as Claude Code sends it
@@ -64,7 +73,11 @@ Written by Deadcode, with contributions from:
(--draft-short-from), the f16 delta-net state cache, the two-rank all-reduce checking a peer's push
has landed, the MXFP4 decode gate_up folded with its activation and fp8 quantiser, the head-256
split-KV decode attention, weight reads beside the decode all-reduces (--weight-prefetch), the
head-256 prefill attention's KV split for small launches, and the GUIDE's two engines on one pair
head-256 prefill attention's KV split for small launches, the GUIDE's two engines on one pair,
DFlash2's coupled acceptance at T > 0, the prefix cache's snapshot at a head prompts share,
tip-only's snapshot a drafter window below the tip, Gemma 3's fused all-reduce junction on the
lossy wire, the three-wave verify's split by depth, and the delta net's out-projection read
beside its decode recurrent update
- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the
out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8
linears' operands directly
@@ -75,8 +88,10 @@ Written by Deadcode, with contributions from:
name the opener opens, GLM-5.3-Flash's vision tower and processor, its decode at a few rows and
its DSA indexer split over the ranks, a host-tier restore that makes room as pressure does, KV
groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA
row form (--tp-attn-split rows), DELETE /sessions, and the dispatch stamps of a played pass with
stampgaps.py
row form (--tp-attn-split rows), DELETE /sessions, the dispatch stamps of a played pass with
stampgaps.py, one n-gram table for engines on separate cards (--ngram-placement ram=DIR), GGUF
Q8_0, Q4_K and Q6_K tensors imported as their planes, the dense integer rows at the group they
compute, and the GDN conv kernels on an f32 weight
- John McDonough: GLM-5.3-Flash -- its plugin, its blocks (mHC streams, KDA, the DSA indexer and
sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their
reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the
@@ -86,18 +101,32 @@ Written by Deadcode, with contributions from:
rotation
- C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual
projection, KV streaming for a context bigger than VRAM (--kv-resident), and the dashboard's
request history
request history, KV streaming traffic and one-unit KV meter
- J-Nova: Unlimited-OCR, and Sage-A1.5 with its vision tower and its DFlash2 drafter
- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8)
- lortht: Krea 2's rebalance of the text taps and its presets, and MiniMax-H3's modulation rows
- lortht: Krea 2's rebalance of the text taps and its presets, MiniMax-H3's modulation rows, and
keyframes carried through a latent upscale
- Quackster: cards with a small PCI BAR, their kernel arguments kept in host memory
- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix
- gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its
BF16, FP8 and GGUF adapters, its KV scales, and its native sectioned tool calls
BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode
(the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds)
- launch80_assets: tuning collectives as the exchange they serve at the served configuration, the
per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch
- hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2
drafter -- and the ParoQuant M2XFP4 import
- steki: Gemma 4 E2B's per-layer MLP width and the bf16 descriptor for Google's E2B/E4B
directories, nomic-embed-text-v2-moe (the nomicbert plugin), its config key aliases and
RAD_MAP_TRANSPOSE honouring src_index, an f32 source narrowed to a bf16 declaration at load, and
the snapshot store's floor ahead of --host-headroom-mib
- griffin-warrior: the kernel report's consistency checks and coverage header, collective selftest
cases skipped without a peer path, the build's media capability in the diagnostics, and the
GUIDE's ROCm SDK and ffmpeg notes
- nickreese: GBNF bounded-repetition chains shared across identical operands
- Dad_Vibes: hc_read's decode kernels as one grid, its tiled up-mix pipelined and its one-grid
wait trapping past its deadline, and gemm_fp8a8's narrow form with its scales staged through LDS
and its gated three-tile form at 8 waves
- RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library
This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each.
+1
View File
@@ -38,6 +38,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (22 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash) | `gemma4-31b-w4a8-df.yaml` |
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` |
| Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` |
| Gemma 4 31B on four or two cards: int4 trunk, int8 activations and lm_head, a block-16 DFlash2 drafter (15 drafts a step, verified as a tree), vision | `gemma4-31b-dense-w4a8-df2b16-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2-b16) | `gemma4-31b-w4a8-df2b16-tp4.yaml`, `gemma4-31b-w4a8-df2b16-tp2.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16 (Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-bf16.rad` (17 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-bf16) | `nemotron-3.5-bolt-e4b-bf16.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-i8g.rad` (13 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-i8g) | `nemotron-3.5-bolt-e4b-i8g.yaml` |
| NVIDIA-Nemotron-3.5-Bolt-E4B 4-bit (int4 feed-forward, GPTQ, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, audio | `nemotron-3.5-bolt-e4b-a4.rad` (12 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-a4) | `nemotron-3.5-bolt-e4b-a4.yaml` |
+44 -4
View File
@@ -261,6 +261,16 @@ typedef struct RadBuildCtx {
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int weight_prefetch_off;
/* ---- appended in ABI 31 (tree verification) */
/* Nonzero: grow the block drafter's proposals into a tree (rad_drafter_tree) where the plugin
* can. The engine sets it where the plugin's probe said trees pay (RadArchProbe::tree_pays)
* and the drafter decodes speculatively; 0 keeps the chain. A plugin that grows no trees
* ignores it. 64-bit so it starts past the older
* struct's tail padding, where a plugin built against it would read nothing.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int64_t draft_tree;
} RadBuildCtx;
/* ================================================================== control vectors */
@@ -759,6 +769,25 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
* checkpoint was trained with is the plugin's to know. */
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
/* A block drafter whose one pass proposes a tree rather than a chain. Called once, after
* rad_declare_drafter. `parents` is an i32 buffer at the proposal's pitch: row i's j-th entry is
* the parent of the proposal's j-th token as a node index, 0 for the token the verify starts from
* (the bonus token) and j' + 1 for the proposal's j'-th token, with every parent before its child.
* Additive export; RAD_ABI_VERSION does not move.
*
* Each verify then runs the proposal as a tree in the same rows: node j at row j, rotated at the
* committed end + its depth, its K and V stored at the committed end + j, and every trunk step
* carries RadBatch::spec_parent, which the plugin hands its attention so a row sees, inside its
* own block, only its ancestors. The acceptance follows the deepest root path the target agrees
* with; the core then moves that path's K and V into place in every paged group. A proposal from
* prompt lookup is verified as the chain-shaped tree.
*
* Requirements on the plugin: the trunk's attention honours spec_parent on every decode row; the
* drafter's context pass stores K and V through the slot mapping only (it is staged per node, the
* rejected ones at slot -1); and the step is issued ahead, behind which the block driver queues
* the drafter's passes (the KL mode drafts nothing, so trees do not apply there). */
int rad_drafter_tree(RadBuilder* b, rad_buf parents);
/* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on
* the AQL backend only, which keeps a completion counter per queue, where the model's plugin
* measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
@@ -770,11 +799,14 @@ int rad_chain_on(void);
/* A block drafter that also serves a shorter block: the plugin declared its query pass at `block`
* rows a sequence as well as at RadDrafterDecl::block, with the same anchor convention, so the
* core may stage a step's block at either. The short block proposes
* `block - (RadDrafterDecl::block - depth)` tokens. Called once, after rad_declare_drafter.
* `block - (RadDrafterDecl::block - depth)` tokens; a tree drafter's (rad_drafter_tree, declared
* first) a tree of its own over the shorter pass, at most `block - 1` nodes, which needs only that
* the short block be 2 rows or more. Called once, after rad_declare_drafter.
*
* The block is proposed whole, so its length is paid for by every drafting sequence whatever each
* verifies: at one sequence a long block's extra drafts pay, at many its rows and its weaker first
* positions cost more than they bring. The core picks per step (--draft-short-from). */
* positions cost more than they bring. The core picks per step (--draft-short-from; by default
* a tree's from two decoding sequences on, a chain's never). */
/* ---- appended in ABI 27 (a block drafter's short block) */
int rad_drafter_short_block(RadBuilder* b, int64_t block);
@@ -1254,8 +1286,8 @@ int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
*
* `enc_kind` (RAD_ENC_*, rad_runtime.h) and `enc_slot`, the media's 1-based number within its kind,
* say where the latents go. A latent-upscaled request's keyframes, pinned on the grid its steps
* run on, are encoded at W' x H' before the prompt pass and again at W x H, into the same slots,
* after the VUPSCALE pass and before the first evaluation at W x H; references, in their own grid,
* run on, are encoded at W' x H' before the prompt pass, then again at W x H into the same slots
* after the VUPSCALE pass and before the first evaluation at W x H. References, on their own grid,
* are encoded once. The media's shape is the plugin's to accept: rad_arch_encode_geom
* (below) refuses what the encoders cannot take, and the step's packed sequence with the encoded
* media in it is the plugin's rad_arch_video_pack.
@@ -1518,6 +1550,14 @@ typedef struct RadArchProbe {
* and its kernels read that width. --state-cache-dtype f16 is refused at startup with the
* plugin named when this is 0. */
int32_t state_f16_ok;
/* ---- appended in ABI 31 (tree verification) */
/* Nonzero when this plugin can grow its block drafter's proposals into a tree
* (rad_drafter_tree) and measured its speculative step faster with one. The core then asks for
* a tree (RadBuildCtx::draft_tree) wherever that drafter decodes speculatively. Zero keeps the
* chain: a plugin that never measured trees asks for none. 64-bit so it starts past the older
* struct's tail padding, which a plugin built against it may copy over. */
int64_t tree_pays;
} RadArchProbe;
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
+6 -1
View File
@@ -119,7 +119,12 @@ typedef struct RadBatch {
/* Speculative window (spec §10). n_spec == 0 for an ordinary decode step. */
int n_spec; /* draft tokens per sequence this step */
const int32_t* num_accepted; /* [n_seq] device, from the previous verify */
const int32_t* spec_parent; /* [n_tok] device, tree layout; null for a linear chain */
/* [n_tok] device; null for a linear chain. A tree verify (rad_drafter_tree): -2 marks an
* ordinary causal row; any other entry is a node of its sequence's verify block and names its
* parent by row within the sequence's rows (cu_seqlens), -1 for the block's first row, every
* parent before its child. Inside its block such a row attends to itself and its ancestors
* only (docs/OPS.md, attn_paged_tree). */
const int32_t* spec_parent;
/* The draft pass. 0 is an ordinary step that runs the trunk; non-zero runs only the draft
* head, and the sign gives the kind:
+89 -11
View File
@@ -123,6 +123,16 @@ struct Dflash2 {
int64_t group = 16;
int64_t sel_rank = 256; /* the codebooks' width */
int64_t sel_topk = 16; /* candidates kept per position */
/* Propose a tree of `steps()` nodes instead of the selector's one path (`dflash_tree`,
* rad_drafter_tree): best-first over the candidate lattice by path probability, each
* edge's probability the softmax of its scores over the K candidates divided by
* `tree_temp`. False: the greedy walk. */
bool tree = false;
double tree_temp = 1.0;
/* A tree's draft nodes a step, 0 for `steps()`. More than the block drafts is a wider tree
* over the same lattice (its depth is still at most `steps()`); the proposal buffers, the
* drafter's declared depth and the verify are this wide. */
int64_t tree_nodes = 0;
int64_t window = 0; /* sliding attention width, 0 for none */
int causal = 0;
/* The target's embedding scale, applied to the query block as the drafter was trained
@@ -132,15 +142,18 @@ struct Dflash2 {
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
int64_t prefetch = 0;
/* Also declare the short block's query pass (kShortBlock rows) for --draft-short-from; an
* architecture that does not call rad_drafter_short_block leaves it off and its graph as
* it was. */
/* Also declare the short block's query pass (kShortBlock rows, or `short_rows`) for
* --draft-short-from; an architecture that does not call rad_drafter_short_block leaves
* it off and its graph as it was. A tree's selector at that block grows a tree of its own
* over the shorter pass, `short_rows - 1` nodes or fewer. */
int short_block = 0;
/* --draft-coupling: the temperature of the draft law Q the coupled walk samples from
* (dflash_couple_propose's `q_temp`). Any value keeps the output exact; it only moves
* acceptance, sum min(P, Q). */
double q_temp = 1.0;
int64_t short_rows = 0;
int64_t steps() const { return block - 1; }
int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); }
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
* `dflash_conv` reads a slice of it at the full row pitch. */
@@ -198,6 +211,8 @@ struct Dflash2 {
/* --draft-coupling: [max_seqs, DRAW_WORDS] draws the engine stages, and [steps, max_seqs,
* STATE_WORDS] states it reads back (abi/rad_spechub.h). Both or neither. */
rad_buf couple_draws = 0, couple_state = 0;
/* [max_seqs, steps] i32 a tree's parents (Config::tree, rad_drafter_tree); 0 otherwise */
rad_buf parents = 0;
};
/* Whether the 2-bit draft head is vocab-sharded (rad_arch.h: vocab_head_sharded), so whoever
@@ -277,6 +292,7 @@ struct Dflash2 {
* and the selector strides by it, so each has an op of its own; every other op is per row. */
rad_op op_aconv_lo[MAX_LAYERS] = {}, op_fconv_lo[MAX_LAYERS] = {}, op_sel_lo = 0;
int64_t block_lo = 0;
int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
@@ -718,7 +734,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* layers. Planned from those alone, its range would end before the coefficients' begins and
* the plan could lay one over the other. Read by the last convolution as well, it is live
* wherever the coefficients are. */
block_lo = cfg.short_block && cfg.block > kShortBlock ? kShortBlock : 0;
{
const int64_t rows = cfg.short_rows > 0 ? cfg.short_rows : kShortBlock;
block_lo = cfg.short_block && rows >= 2 && cfg.block > rows ? rows : 0;
}
for (int64_t l = 0; block_lo && l < g.n_layer; ++l) {
const int i = (int)l;
op_aconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv",
@@ -943,15 +962,65 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_selp)),
{w.sel_h}, {w.hp});
/* `anchor_stride` is `block`: the operand is the step's token_ids, `block` per sequence with
* the anchor first. */
op_sel = rw(b, RAD_OP(b, "dflash_select",
* the anchor first.
*
* A tree (Config::tree): `dflash_tree` grows `steps` nodes best-first over the same lattice
* and the same edge scores, writing each node's parent beside its token. Where no library
* serves it the block falls back to the chain and says so; the caller reads `cfg.tree` after
* declare to decide whether to tell the core (rad_drafter_tree). --draft-coupling samples one
* path per sequence, so a coupled drafter proposes the chain. */
if (cfg.tree && (w.couple_draws || w.couple_state)) {
rad_note(b, "DFlash2: --draft-coupling samples a chain; the drafter proposes no tree");
cfg.tree = false;
}
if (cfg.tree) {
op_sel = RAD_OP(b, "dflash_tree",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", cfg.block),
RAD_INT("nodes", cfg.nodes()), RAD_F64("temp", cfg.tree_temp),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_pred, w_succ));
if (op_sel && rad_op_resolved(b, op_sel)) {
rw(b, op_sel, {w.cand, w.unary, w.hp}, {w.tokens, w.parents});
} else {
rad_note(b, "DFlash2: no library serves dflash_tree here; the drafter proposes its "
"selector's chain");
cfg.tree = false;
op_sel = 0;
}
}
if (!cfg.tree) op_sel = rw(b, RAD_OP(b, "dflash_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_pred, w_succ)),
{w.cand, w.unary, w.hp}, {w.tokens});
if (block_lo)
if (block_lo && cfg.tree) {
/* A tree over the short block's own lattice (the pass attends across its block, so it is
* not the full pass's prefix): as many nodes as the block drafts, or the tree's own count
* where that is fewer. */
sel_lo_nodes = std::min<int64_t>(cfg.nodes(), block_lo - 1);
op_sel_lo = RAD_OP(b, "dflash_tree",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
RAD_INT("n_vocab", g.n_vocab_all),
RAD_INT("anchor_stride", block_lo),
RAD_INT("nodes", sel_lo_nodes), RAD_F64("temp", cfg.tree_temp),
RAD_STR("dtype", g.dtype)),
RAD_WEIGHTS(w_pred, w_succ));
if (op_sel_lo && rad_op_resolved(b, op_sel_lo)) {
rw(b, op_sel_lo, {w.cand, w.unary, w.hp}, {w.tokens, w.parents});
} else {
rad_note(b, "DFlash2: no library serves dflash_tree at the short block; the tree keeps "
"its own block under load");
op_sel_lo = 0;
block_lo = 0;
sel_lo_nodes = 0;
}
} else if (block_lo)
op_sel_lo = rw(b, RAD_OP(b, "dflash_select",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
@@ -1197,10 +1266,19 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
}
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
brows(w.tokens, batch->n_seq));
/* A tree's outputs as views exactly its nodes wide, at the buffers' row pitch: at the short
* block it grows fewer nodes than a row holds, and the proposals are read at the full pitch. */
const int64_t nn = lo ? sel_lo_nodes : cfg.nodes();
if (cfg.tree)
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
bcol(w.tokens, 0, nn, batch->n_seq), bcol(w.parents, 0, nn, batch->n_seq));
else
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
brows(w.tokens, batch->n_seq));
if (op_couple)
RAD_ISSUE_N(c, lo ? op_couple_lo : op_couple, batch->n_seq,
bcol(w.cand, 0, cfg.sel_topk, S), bcol(w.unary, 0, cfg.sel_topk, S),
+3 -3
View File
@@ -1419,9 +1419,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
}
if (separate_fp32_combine) {
/* BF16 add widens both inputs to FP32, adds, then rounds once to BF16: exactly the
* former cast + cast + F32 add + cast chain. Keep the routed gather's BF16 rounding
* and the separate TP reductions; a local gather cannot fold those reductions. */
/* BF16 add widens both inputs to FP32, adds, then rounds once to BF16: the same bytes as
* cast + cast + F32 add + cast. The routed gather's BF16 rounding and the separate TP
* reductions stay; a local gather cannot fold those reductions. */
op_combine = rw(b, RAD_OP(b, "add",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
RAD_STR("dtype", "bf16")),
+2 -1
View File
@@ -178,7 +178,8 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
/* E4M3 with one scale for all 320 million rows (Qwen3.8-Flash-Next-FP8's choice; E4M3 has its
* own exponent, a row's dynamic range is 2.3x, and the scale sits on a three-octave plateau).
* One stored weight, `fp8_e4m3*bf16[*x*]`: codes plus a one-element scale plane, made by the
* recipe (data/recipes/qwen4exp-w4.recipe); the gather takes them as two operands. The name map
* recipe (data/recipes/qwen4exp-w4.recipe) or read as that release ships it (its shards under
* one `weight_scale`); the gather takes them as two operands. The name map
* joins the shards along rows and is declared first, since the encoding is looked up through
* it. RAD_ACCESS_VOCAB: it is a vocabulary table, just not the token one. */
const char* tn = nm.f("blk.%d.ple_ngram.weight", layer);
+4
View File
@@ -188,6 +188,10 @@ inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
out->draft_depth = (int)(bs - 1);
out->draft_depth_fixed = 1;
out->chain_pays = 1;
/* Its proposals verified as a tree of the same node count (dflash_tree, rad_drafter_tree): on
* 4x R9700 +7% single-stream decode and +6-9% aggregate at 1-16 users over the selector's
* chain (BetterBench, thinking off; on two cards +4% and +6-12%). */
out->tree_pays = 1;
return true;
}
+10 -12
View File
@@ -831,12 +831,10 @@ struct G3Junction {
/* The tallest step that takes the fp8 junction's lossy twin (G3JunctionFP8::op_ar6); a taller one
* keeps the standalone lossy all-reduce, unfused. The fused kernel gives each block one row, so past
* a few sequences the standalone all-reduce, spread over more blocks, wins despite its extra
* launches. TranslateGemma-27B MXFP4 + DFlash2 at tp 2 on 2x R9700, --tp-wire wht6, production's
* flags (--draft-short-from 8), greedy, aggregate tok/s, two rounds, limit never / 16 / 24 / any:
* 2 streams (16 rows) 350.7 346.2 / 371.8 367.7 / 370.4 367.0 / 357.7 356.0; 3 (24 rows) 455.8
* 451.2 / 455.1 454.2 / 462.8 460.6 / 437.3 436.8; 4 (32 rows) 553.7 553.6 / 557.9 554.2 / 553.9
* 560.2 / 521.0 523.0; 8 (32 rows, the short block) 717.4 718.0 / 717.2 720.5 / 716.7 720.8 /
* 662.4 661.9. One stream's 8 rows go out exact under the default --tp-wire-min-kb (op_ar). */
* launches. TranslateGemma-27B MXFP4 + DFlash2 at tp 2 on 2x R9700 (--tp-wire wht6,
* --draft-short-from 8, greedy): fusing raises aggregate throughput by 1-6% up to 24 rows and
* lowers it by 6-8% at 32. One stream's 8 rows go out exact under the default --tp-wire-min-kb
* (op_ar). */
constexpr int64_t kAr6MaxRows = 24;
/* ---- the MXFP4 trunk's junction (libr4d `rmsnorm_quant_fp8`): the add of the branch `x` into
@@ -848,10 +846,10 @@ struct G3JunctionFP8 {
rad_op op = 0;
/* At two ranks: the branch's all-reduce and post-norm folded in front
* (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. `op_ar` sends
* the exact wire, taken by the steps whose message goes out exact (ar_wire_is_exact: a decode
* step of a few rows, under --tp-wire-min-kb); `op_ar6` the rotated 6-bit one, declared under a
* lossy --tp-wire and taken by the steps above that up to kAr6MaxRows, byte-identical to the
* standalone lossy all-reduce, rmsnorm and rmsnorm_quant_fp8 it replaces. */
* the exact wire, for the steps whose message goes out exact (ar_wire_is_exact: a decode step
* of a few rows, under --tp-wire-min-kb). `op_ar6` sends the rotated 6-bit one: declared under
* a lossy --tp-wire, it takes the steps above that up to kAr6MaxRows and is byte-identical to
* the standalone lossy all-reduce, rmsnorm and rmsnorm_quant_fp8 it replaces. */
rad_op op_ar = 0, op_ar6 = 0;
Geom gm{};
rad_buf x = 0, res = 0, q = 0, s = 0;
@@ -883,8 +881,8 @@ struct G3JunctionFP8 {
const rad_buf wa[4] = { x, q, s, res };
rad_op_reads (b, op_ar, rd, 2);
rad_op_writes(b, op_ar, wa, 4);
/* The lossy twin where that wire is reachable and the row is whole 64-element
* groups (the kernel pads a partial last 512-element chunk). */
/* The lossy twin, under a lossy wire and for a row of whole 64-element groups
* (the kernel pads a partial last 512-element chunk). */
if (!g.wire_exact && n % 64 == 0) {
const RadParam p6[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
+127 -21
View File
@@ -423,6 +423,12 @@ struct Gemma4Attn {
* the copies of k and v too, ahead of the unfused prologue, which reads them dense. */
rad_op op_attn_row = 0, op_attn_dec = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0;
int64_t dec_hi = 0;
/* Tree verification (rad_drafter_tree): attention that honours RadBatch::spec_parent over a
* step's decode rows, reading q in the row (attn_paged_qrow_tree) or dense (attn_paged_tree,
* after op_tree_lift copies it out). Declared only when `tree` is set before declare; 0 where
* no library serves it, which the model reads as "no trees". */
bool tree = false;
rad_op op_attn_tree = 0, op_tree_lift = 0;
/* the feed-forward's gate_up read into the cache beside this block's all-reduce, or 0 (see
* "Prefetch beside the reductions") */
rad_op op_pf = 0;
@@ -697,6 +703,20 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
}
}
/* The tree form over the decode rows: a verify block of 1 + n_spec rows a sequence, so the
* split-KV band (q_len * gqa <= 64) covers it at every class here. In the row where the
* prologue leaves q there, else dense after a copy. */
if (tree) {
const int64_t thi = std::min<int64_t>(
g.max_tok, std::max<int64_t>({ (int64_t)1, 64 / cls.gqa(), (int64_t)g.max_spec + 1 }));
if (fused && op_qnr && rad_op_declared(b, "attn_paged_qrow_tree"))
op_attn_tree = attn("attn_paged_qrow_tree", {w.qkv}, thi);
if (!op_attn_tree && rad_op_declared(b, "attn_paged_tree")) {
op_attn_tree = attn("attn_paged_tree", {w.q}, thi);
if (op_attn_tree && fused && op_qnr) op_tree_lift = lift(qd, w.q);
}
}
/* With the cache store folded into the prologue where a library serves it
* (qkv_norm_rope_kv_store: the same prologue, then kv_store of the finished k and v from the
* same launch, byte for byte), one launch a layer fewer. Declared after the attention ops,
@@ -947,26 +967,51 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
if (op_kv) RAD_ISSUE(c, op_kv, K, V, praw(slot, RAD_I32, T), kv_cache(kv, layer));
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
rad_op a_op = op_attn;
RadOperand a_q = brows(w.q, T);
if (op_attn_row) {
a_op = op_attn_row;
a_q = Q;
} else if (op_attn_dec && batch->max_q_len <= dec_hi) {
a_op = op_attn_dec;
a_q = Q;
} else if (row) {
if (T == 1) a_q = Q;
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
/* A tree step (rad_drafter_tree): every decode row's verify block sees, inside the block,
* only that row's ancestors (RadBatch::spec_parent), so the decode rows go through the tree
* form. On a step of decode rows alone that is the step's attention; beside a prefill chunk the
* ordinary form runs over every row first and the tree form then rewrites the decode rows,
* which come first (spec §8). */
const bool tree_step = op_attn_tree && batch->spec_parent && batch->draft_pass == 0 &&
batch->n_seq_decode > 0;
if (!tree_step || batch->n_seq_decode < batch->n_seq) {
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
rad_op a_op = op_attn;
RadOperand a_q = brows(w.q, T);
if (op_attn_row) {
a_op = op_attn_row;
a_q = Q;
} else if (op_attn_dec && batch->max_q_len <= dec_hi) {
a_op = op_attn_dec;
a_q = Q;
} else if (row) {
if (T == 1) a_q = Q;
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
}
RAD_ISSUE_N(c, a_op, batch->max_q_len,
a_q, kv_cache(kv, layer),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn, T));
}
if (tree_step) {
const int64_t Td = batch->n_tok_decode, Sd = batch->n_seq_decode;
RadOperand tq = row ? bcol(w.qkv, 0, qd, Td) : brows(w.q, Td);
if (op_tree_lift) {
RAD_ISSUE_N(c, op_tree_lift, Td, bcol(w.qkv, 0, qd, Td), brows(w.q, Td));
tq = brows(w.q, Td);
}
RAD_ISSUE_N(c, op_attn_tree, batch->max_q_len_decode,
tq, kv_cache(kv, layer),
praw2(table, RAD_I32, Sd, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, Sd),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, Sd + 1),
brows(w.attn, Td),
praw(batch->spec_parent, RAD_I32, Td));
}
RAD_ISSUE_N(c, a_op, batch->max_q_len,
a_q, kv_cache(kv, layer),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
brows(w.attn, T));
}
/* A slice's rows see exactly the keys they see in the whole step: the cache holds the step's
@@ -1811,6 +1856,9 @@ struct Model {
Dflash2 df2{};
Dflash2::Wire df2w{};
bool have_df2 = false;
/* Tree verification (RadBuildCtx::draft_tree): every layer's attention has its tree form, and
* the drafter proposes trees once it has declared dflash_tree too. */
bool tree = false;
/* The prefill overlap runs attention per slice: a trim a KV group (sliding, global). */
SliceTrim trim[2]{};
int n_trim = 0;
@@ -1877,6 +1925,13 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
Dflash2::Config dc{};
dc.n_taps = m.n_taps;
dc.block = ctx->max_spec + 1;
/* A tree (m.tree, asked before the trunk) is `max_spec` nodes grown over the lattice of the
* block the drafter was trained at, whatever its width: the block is the trained one and
* --num-speculative-tokens counts nodes. */
if (m.tree && gemma4::dflash_block(meta) > 1) {
dc.block = gemma4::dflash_block(meta);
dc.tree_nodes = ctx->max_spec;
}
dc.taps = df2_geti(meta, "conv_kernel_size", 2);
dc.group = df2_geti(meta, "conv_group_size", 16);
dc.sel_rank = df2_geti(meta, "selector_rank", 0);
@@ -1985,13 +2040,39 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2});
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2});
}
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
const int64_t nodes = dc.tree_nodes > 0 ? dc.tree_nodes : dc.steps();
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, nodes});
/* Trees (RadBuildCtx::draft_tree; the trunk's attention already has its tree form): the
* selector's lattice grown best-first into `steps` nodes, each edge weighed by the softmax of
* its scores over a temperature. 1.25 measured best at 7 nodes on the speculator benchmarks
* (greedy, and sampled at 0.7 and 1.0); its path probabilities are calibrated there. */
if (m.tree) {
dc.tree = true;
dc.tree_temp = 1.25;
dw.parents = decl_b(b, nm.f("dflash_parents"), RAD_I32, {dg.max_seqs, nodes});
/* A block of 16 (the DBloom drafter): its 15-node tree's verify rows pay at one sequence
* and not at many, so the query pass is declared at half the block too, over which the
* drafter grows a 7-node tree of its own: the drafter's short block
* (rad_drafter_short_block), which the core runs from two decoding sequences on
* (--draft-short-from auto). A shorter block's tree verifies as few rows as that already. */
if (dc.block >= 16 && (dc.block & (dc.block - 1)) == 0) {
dc.short_block = 1;
dc.short_rows = dc.block / 2;
}
}
/* The head copy comes from the tied table, under the block's own name; the recipe makes it
* 8-bit. */
RAD_ARCH_TRY(m.df2.declare(b, nm, dg, dc, (int)m.n_main, m.kv_draft, m.w_tok, "draft",
nm.ckpt("model.language_model.embed_tokens.weight"), dw));
m.have_df2 = true;
m.tree = m.df2.cfg.tree; /* false where dflash_tree did not resolve */
if (!m.tree && nodes != dc.steps()) {
fprintf(stderr, "radiance: gemma4: a DFlash2 tree of %lld nodes needs dflash_tree, which no "
"library serves here; the block's chain is %lld\n", (long long)nodes,
(long long)dc.steps());
return RAD_E_UNSUPPORTED;
}
RadDrafterDecl drf{};
drf.name = "dflash2";
@@ -1999,7 +2080,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
drf.depth = ctx->max_spec;
drf.block = dc.block;
drf.proposal = dw.tokens;
drf.proposal_pitch = dc.steps();
drf.proposal_pitch = nodes;
drf.window = dc.window;
drf.mask_token = (int32_t)df2_geti(meta, "mask_token_id", -1);
if (drf.mask_token < 0) {
@@ -2008,6 +2089,17 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
return RAD_E_FORMAT;
}
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
if (m.tree) {
RAD_ARCH_TRY(rad_drafter_tree(b, dw.parents));
if (m.df2.block_lo > 0) {
RAD_ARCH_TRY(rad_drafter_short_block(b, m.df2.block_lo));
rad_note(b, "DFlash2 drafter: a short block of %lld rows, a tree of %lld nodes over it",
(long long)m.df2.block_lo, (long long)m.df2.sel_lo_nodes);
}
rad_note(b, "DFlash2 drafter: a tree of %lld nodes a step (softmax temperature %.3g) over "
"the lattice of its %lld-row block, verified in %lld rows", (long long)nodes,
dc.tree_temp, (long long)dc.block, (long long)nodes + 1);
}
rad_note(b, "DFlash2 drafter: %lld layers at absolute %lld.., %lld heads / %lld kv x %lld, ffn "
"%lld, %s attention with a %lld-token window, %d trunk taps; one forward proposes "
@@ -2351,6 +2443,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
Gemma4Attn::Wire gw{}; gw.x = m.b_x; gw.h = m.b_h; gw.q = m.b_qg; gw.k = m.b_kg; gw.v = m.b_vg; gw.attn = m.b_atting;
Gemma4Mlp::Wire mw{}; mw.x = m.b_x; mw.h = m.b_h; mw.gu = m.b_gu; mw.ffn = m.b_ffn;
/* Tree verification for a DFlash2 drafter (RadBuildCtx::draft_tree, which the engine sets
* from this plugin's probe; rad_drafter_tree): asked of every layer's attention here, before
* the drafter, and used only if every layer has it. Not where a layer reads another layer's
* cache (KV sharing, Gemma 4 E2B/E4B): untested there. */
const bool tree_want = ctx->max_spec > 0 && m.n_taps > 0 && gemma4::dflash_kind(meta) == 2 &&
kv_shared == 0 && ctx->draft_tree != 0;
bool tree_all = tree_want;
m.layers.resize((size_t)m.n_main);
for (int64_t l = 0; l < m.n_main; ++l) {
Layer& lay = m.layers[(size_t)l];
@@ -2360,8 +2460,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
const Gemma4Attn::Wire& aw = lay.global ? gw : sw;
/* A KV-shared layer is not bound: the group's pages hold only the layers that write. */
if (kv_src[(size_t)l] < 0) RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
lay.attn.tree = tree_want;
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre,
lay.global ? &m.b_qkvg : &m.b_qkvs, kv_src[(size_t)l]));
if (tree_want && !lay.attn.op_attn_tree) tree_all = false;
/* The double-wide layers write their own pair of buffers (see b_gu_w). */
Gemma4Mlp::Wire lw = mw;
const bool wide = wide_mlp && l >= first_shared;
@@ -2626,6 +2728,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* declaration order is the buffer planner's liveness. It reads the taps the trunk copied into
* `dflash_src` and the trunk's tied table, as its embedding and, where the container holds no
* 8-bit copy, as its head. */
if (tree_want && !tree_all)
rad_note(b, "DFlash2 tree: no library serves tree attention for every layer here "
"(attn_paged_qrow_tree / attn_paged_tree); the drafter proposes a chain");
m.tree = tree_all;
if (m.n_taps > 0 && gemma4::dflash_kind(meta) == 2) {
RAD_ARCH_TRY(declare_dflash2(b, meta, ctx, m));
} else if (m.n_taps > 0) {
+38 -79
View File
@@ -6,7 +6,7 @@
* returns each sequence's pooled row. Attention is bidirectional on every layer, so nothing is
* paged: a token attends to later tokens, and there is nothing to carry between steps.
*
* ============================== THE SHAPE ==============================
* Shape:
*
* 12 layers, hidden 768, 12 heads of 64, ffn 3072, vocab 250048, type vocab 1
* post-norm block, the config's `prenorm: false`:
@@ -20,14 +20,12 @@
* output: the mean of every real token, then cast to the f32 pooled buffer
*
* The expert tables are one concatenated tensor each: w1 [8 * 3072, 768] as [out, in], w2
* [8 * 3072, 768] as [in, out] per expert, so w2 is sliced then transposed at convert
* (RAD_MAP_TRANSPOSE with src_index and src_rows). Every expert's two tensors take distinct group
* slots.
* [8 * 3072, 768] as [in, out] per expert, so w2 is sliced, then transposed (RAD_MAP_TRANSPOSE
* with src_index and src_rows). Every expert's two tensors take distinct group slots.
*
* The block order and the unused shared experts.bias were settled against the production
* llama.cpp embedder by scripts/nomic_ref.py; the winning variant and the vectors it produced are
* in tests/data/nomic/golden.json (norm=post, bias=none). The checkpoint's `experts.bias` tensors
* are therefore not declared and stay unconverted.
* The block order and the omitted shared bias match llama.cpp's embedder for this model
* (post-norm, no expert bias). The checkpoint's `experts.bias` tensors are not declared and stay
* unconverted.
*/
#include <arch/rad_arch.h>
@@ -40,10 +38,8 @@ namespace nomicbert {
using namespace rad::arch;
/* Post-norm, the reading scripts/nomic_ref.py and tests/data/nomic/golden.json settle: the
* attention is on the raw stream, then LN1, then the feed-forward on LN1's output, then LN2 over
* that output plus the feed-forward's. The shared experts.bias is not applied (bias=none there). */
constexpr bool kPostNorm = true;
/* Post-norm: attention on the raw stream, then LN1, then the feed-forward on LN1's output, then
* LN2 over that output plus the feed-forward's. */
struct Layer {
bool moe = false;
@@ -77,10 +73,9 @@ struct Model {
static Model g_model[MAX_RANKS];
/* The layer schedule, read rather than derived: a wrong interval would turn a dense layer into a
* MoE layer whose tensors the checkpoint does not hold, which convert refuses but only after the
* graph was built. Layer l is routed when (l + 1) % moe_every_n_layers == 0, as nomic's
* modeling_hf_nomic_bert builds it. */
/* The layer schedule, read from moe_every_n_layers rather than derived: a wrong interval would
* declare a MoE layer whose tensors the checkpoint does not hold. Layer l is routed when
* (l + 1) % moe_every_n_layers == 0, as nomic's modeling_hf_nomic_bert builds it. */
static bool is_moe_layer(int64_t l, int64_t every) {
return every > 0 && (l + 1) % every == 0;
}
@@ -99,7 +94,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx) return RAD_E_INVAL;
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
/* One 475M-parameter encoder on one card; tensor parallelism would only add an all-reduce per
/* A 475M-parameter encoder fits one card; tensor parallelism would only add an all-reduce per
* layer. */
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: nomicbert runs on one card (--tp 1); the model is 475M "
@@ -325,8 +320,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
src("mlp.router.layer.weight")));
y.w_router = decl_w(b, nm.f("blk.%lld.ffn_router.weight", ll), RAD_BF16,
{m.n_expert, E}, A, N, gl);
/* mlp.experts.bias is deliberately not mapped: the verified variant applies no
* expert bias, so the tensor is left in the checkpoint. */
/* mlp.experts.bias is not mapped (no expert bias, see the header). */
/* Each projection is a consecutive run of expert handles: all w1 in expert order,
* then all w2. A grouped GEMM takes the run's first handle and its length. The name
* maps come first: declare reads a weight's planned encoding when the weight is
@@ -356,9 +350,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
}
}
const rad_buf att_in = kPostNorm ? m.b_x : m.b_h;
y.op_qkv = rw(b, gemm_bias_op(3 * E, E, y.w_qkv, y.b_qkv, nullptr),
{att_in}, {m.b_qkv});
{m.b_x}, {m.b_qkv});
y.op_rope = rw(b, RAD_OP(b, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head),
@@ -381,12 +374,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
if (!y.moe) {
y.op_fc1 = rw(b, gemm_bias_op(g.n_ff, E, y.w_fc1, y.b_fc1, "gelu"),
{m.b_h}, {m.b_ff});
if constexpr (kPostNorm)
y.op_fc2 = rw(b, gemm_bias_op(E, g.n_ff, y.w_fc2, y.b_fc2, nullptr),
{m.b_ff, m.b_h}, {m.b_o});
else
y.op_fc2 = rw(b, gemm_bias_op(E, g.n_ff, y.w_fc2, y.b_fc2, nullptr),
{m.b_ff, m.b_x}, {m.b_x});
y.op_fc2 = rw(b, gemm_bias_op(E, g.n_ff, y.w_fc2, y.b_fc2, nullptr),
{m.b_ff, m.b_h}, {m.b_o});
} else {
y.op_router = rw(b, gemm_op(m.n_expert, E, y.w_router), {m.b_h}, {m.b_logits});
y.op_topk = rw(b, RAD_OP(b, "router_topk",
@@ -416,16 +405,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_STR("act", "none")),
RAD_NOWEIGHTS),
{m.b_edn, m.b_ew, m.b_sorted}, {m.b_emoe});
if constexpr (kPostNorm)
y.op_add = add_op(m.b_h, m.b_emoe, m.b_o);
else
y.op_add = add_op(m.b_x, m.b_emoe, m.b_x);
y.op_add = add_op(m.b_h, m.b_emoe, m.b_o);
}
if constexpr (kPostNorm)
y.op_norm2 = rw(b, layernorm_op(y.w_norm2, y.b_norm2), {m.b_o}, {m.b_x});
else
y.op_norm2 = rw(b, layernorm_op(y.w_norm2, y.b_norm2), {m.b_x}, {m.b_h});
y.op_norm2 = rw(b, layernorm_op(y.w_norm2, y.b_norm2), {m.b_o}, {m.b_x});
if (!y.op_qkv || !y.op_rope || !y.op_attn || !y.op_out || !y.op_norm1 || !y.op_norm2)
return RAD_E_INVAL;
@@ -446,13 +429,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_NOWEIGHTS),
{m.b_mean}, {m.b_pooled});
rad_note(b, "embedding model: %lld layers (%lld routed every %lld), hidden %lld, ffn %lld, "
"%lld heads of %lld, %lld experts top %lld; post-norm %d, no expert bias; "
int64_t n_routed = 0;
for (const Layer& y : m.layers) n_routed += y.moe ? 1 : 0;
rad_note(b, "embedding model: %lld layers (%lld routed, every %lld), hidden %lld, ffn %lld, "
"%lld heads of %lld, %lld experts top %lld; post-norm, no expert bias; "
"mean-pooled to %lld",
(long long)g.n_layer, (long long)m.n_expert, (long long)every, (long long)E,
(long long)g.n_layer, (long long)n_routed, (long long)every, (long long)E,
(long long)g.n_ff, (long long)g.n_head, (long long)g.head_dim,
(long long)m.n_expert, (long long)m.n_expert_used, kPostNorm ? 1 : 0,
(long long)E);
(long long)m.n_expert, (long long)m.n_expert_used, (long long)E);
return RAD_OK;
}
@@ -474,43 +458,22 @@ static void step(RadCtx* c, const RadBatch* batch) {
for (int64_t l = 0; l < g.n_layer; ++l) {
const Layer& y = m.layers[(size_t)l];
auto attention = [&] {
const rad_buf att_in = kPostNorm ? m.b_x : m.b_h;
RAD_ISSUE_N(c, y.op_qkv, T, brows(att_in, T), RAD_W(y.w_qkv), RAD_W(y.b_qkv),
RAD_NONE, brows(m.b_qkv, T));
RAD_ISSUE(c, y.op_rope, brows(m.b_qkv, T), pos);
RAD_ISSUE(c, y.op_attn, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
RAD_ISSUE_N(c, y.op_out, T, brows(m.b_att, T), RAD_W(y.w_out), RAD_W(y.b_out),
brows(m.b_x, T), brows(m.b_x, T));
};
if constexpr (kPostNorm) {
attention();
RAD_ISSUE(c, y.op_norm1, brows(m.b_x, T), RAD_W(y.w_norm1), RAD_W(y.b_norm1),
brows(m.b_h, T));
} else {
RAD_ISSUE(c, y.op_norm1, brows(m.b_x, T), RAD_W(y.w_norm1), RAD_W(y.b_norm1),
brows(m.b_h, T));
attention();
}
RAD_ISSUE_N(c, y.op_qkv, T, brows(m.b_x, T), RAD_W(y.w_qkv), RAD_W(y.b_qkv),
RAD_NONE, brows(m.b_qkv, T));
RAD_ISSUE(c, y.op_rope, brows(m.b_qkv, T), pos);
RAD_ISSUE(c, y.op_attn, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
RAD_ISSUE_N(c, y.op_out, T, brows(m.b_att, T), RAD_W(y.w_out), RAD_W(y.b_out),
brows(m.b_x, T), brows(m.b_x, T));
RAD_ISSUE(c, y.op_norm1, brows(m.b_x, T), RAD_W(y.w_norm1), RAD_W(y.b_norm1),
brows(m.b_h, T));
if (!y.moe) {
RAD_ISSUE_N(c, y.op_fc1, T, brows(m.b_h, T), RAD_W(y.w_fc1), RAD_W(y.b_fc1),
RAD_NONE, brows(m.b_ff, T));
if constexpr (kPostNorm)
RAD_ISSUE_N(c, y.op_fc2, T, brows(m.b_ff, T), RAD_W(y.w_fc2),
RAD_W(y.b_fc2), brows(m.b_h, T), brows(m.b_o, T));
else
RAD_ISSUE_N(c, y.op_fc2, T, brows(m.b_ff, T), RAD_W(y.w_fc2),
RAD_W(y.b_fc2), brows(m.b_x, T), brows(m.b_x, T));
if constexpr (kPostNorm)
RAD_ISSUE(c, y.op_norm2, brows(m.b_o, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
brows(m.b_x, T));
RAD_ISSUE_N(c, y.op_fc2, T, brows(m.b_ff, T), RAD_W(y.w_fc2),
RAD_W(y.b_fc2), brows(m.b_h, T), brows(m.b_o, T));
} else {
if constexpr (!kPostNorm)
RAD_ISSUE(c, y.op_norm2, brows(m.b_x, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
brows(m.b_h, T));
RAD_ISSUE(c, y.op_router, brows(m.b_h, T), RAD_W(y.w_router), brows(m.b_logits, T));
RAD_ISSUE(c, y.op_topk, brows(m.b_logits, T), brows(m.b_ids, T), brows(m.b_ew, T));
RAD_ISSUE(c, y.op_scatter, brows(m.b_ids, T), brows(m.b_sorted, T * K),
@@ -524,14 +487,10 @@ static void step(RadCtx* c, const RadBatch* batch) {
brows(m.b_edn, T * K));
RAD_ISSUE_N(c, y.op_gather, T, brows(m.b_edn, T * K), brows(m.b_ew, T),
brows(m.b_sorted, T * K), RAD_NONE, RAD_NONE, brows(m.b_emoe, T));
if constexpr (kPostNorm)
RAD_ISSUE(c, y.op_add, brows(m.b_h, T), brows(m.b_emoe, T), brows(m.b_o, T));
else
RAD_ISSUE(c, y.op_add, brows(m.b_x, T), brows(m.b_emoe, T), brows(m.b_x, T));
if constexpr (kPostNorm)
RAD_ISSUE(c, y.op_norm2, brows(m.b_o, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
brows(m.b_x, T));
RAD_ISSUE(c, y.op_add, brows(m.b_h, T), brows(m.b_emoe, T), brows(m.b_o, T));
}
RAD_ISSUE(c, y.op_norm2, brows(m.b_o, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
brows(m.b_x, T));
}
RAD_ISSUE(c, m.op_mean, brows(m.b_x, T), cu, brows(m.b_mean, S));
+5 -14
View File
@@ -434,11 +434,11 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
/* --draft-coupling (RadBuildCtx::draft_coupling): the walk samples each draft from Q, its
* scores' softmax over the best eight candidates, and the sampler couples the target's own draw
* to it (abi/rad_spechub.h). The planes are named as the MTP head's, which is how the engine
* finds them. RADIANCE_DFLASH_Q_TEMP sets Q's temperature; any value keeps the output exact
* and moves only acceptance. The default, 0.6, is where held-out acceptance peaked on
* Qwen3.8-27B MXFP4 + its DFlash2 drafter at request temperature 1 (tokens a step at x4, 32
* rows: ordinary rule 3.52; Q at 1.0 3.71, 0.7 3.88, 0.5 3.85, 0.35 3.77): the walk's scores
* are flatter than the target's law, and a sharper Q puts its mass where the target's is. */
* finds them. Q's temperature keeps the output exact at any value and moves only acceptance;
* 0.6 is where held-out acceptance peaked on Qwen3.8-27B MXFP4 + its DFlash2 drafter at request
* temperature 1 (tokens a step at x4, 32 rows: ordinary rule 3.52; Q at 1.0 3.71, 0.7 3.88,
* 0.5 3.85, 0.35 3.77): the walk's scores are flatter than the target's law, and a sharper Q
* puts its mass where the target's is. */
if (ctx->draft_coupling) {
if (dc.steps() > RAD_MTP_COUPLE_MAX_ROUNDS || dc.sel_topk > RAD_DFLASH_COUPLE_MAX_K ||
dc.sel_rank % RAD_DFLASH_EDGE_PARTS || dc.sel_rank > RAD_DFLASH_COUPLE_MAX_R) {
@@ -449,15 +449,6 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
return RAD_E_UNSUPPORTED;
}
dc.q_temp = 0.6;
if (const char* e = std::getenv("RADIANCE_DFLASH_Q_TEMP")) {
const double t = std::strtod(e, nullptr);
if (!(t > 0.0) || t > 100.0) {
fprintf(stderr, "radiance: RADIANCE_DFLASH_Q_TEMP=%s is not a temperature in "
"(0, 100]\n", e);
return RAD_E_INVAL;
}
dc.q_temp = t;
}
dw.couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
{dg.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS}, RAD_BUF_PERSIST);
dw.couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
+1
View File
@@ -130,6 +130,7 @@ public:
int lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
int64_t from_hi, int64_t to_lo);
int drafter_short_block(int64_t block);
int drafter_tree(rad_buf parents);
int declare_encoder(const RadEncoderDecl* d);
int declare_generator(const RadGeneratorDecl* d);
int declare_audio_generator(const RadAudioGenDecl* d);
+54 -5
View File
@@ -1930,7 +1930,10 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
int64_t block = d->block;
if (d->kind == RAD_DRAFT_BLOCK) {
if (block == 0) block = (int64_t)d->depth + 1;
if (block < 2 || block < (int64_t)d->depth || block > (int64_t)d->depth + 1) {
/* A tree's (rad_drafter_tree) node count is not its block's draft count: more nodes
* than draft positions (a wider tree) or fewer (a block longer than the tree is deep on
* most steps). Checked at finish, once the tree is or is not declared. */
if (block < 2) {
err(RAD_E_INVAL, "declare_drafter '%s': block %lld rows at depth %d. The head runs "
"over the last %d rows of the block, so the block is either %d rows "
"(the anchor predicts nothing) or %d (it does).",
@@ -2064,17 +2067,48 @@ int Builder::drafter_short_block(int64_t block) {
}
const int64_t full = prog_.drafter.block > 0 ? prog_.drafter.block : prog_.drafter.depth + 1;
const int64_t lead = full - prog_.drafter.depth; /* rows ahead of the proposing ones */
if (block >= full || block - lead < 1) {
/* A tree (rad_drafter_tree, declared first) grows a tree of its own over the shorter pass, up
* to block - 1 nodes whatever its own node count, so it needs only two rows. */
if (prog_.drafter_tree ? (block < 2 || block >= full) : (block >= full || block - lead < 1)) {
err(RAD_E_INVAL, "drafter_short_block '%s': %lld rows. The short block must be shorter "
"than the drafter's own (%lld) and still propose a token (more than %lld "
"rows).", prog_.drafter_name.c_str(), (long long)block, (long long)full,
(long long)lead);
"than the drafter's own (%lld) and still propose a token (%s %lld rows).",
prog_.drafter_name.c_str(), (long long)block, (long long)full,
prog_.drafter_tree ? "at least" : "more than",
(long long)(prog_.drafter_tree ? 2 : lead));
return RAD_E_INVAL;
}
prog_.drafter_short_block = block;
return RAD_OK;
}
/* A block drafter whose proposal is a tree (rad_builder.h). */
int Builder::drafter_tree(rad_buf parents) {
if (finished_) {
err(RAD_E_STATE, "drafter_tree after declare finished");
return RAD_E_STATE;
}
if (prog_.drafter.kind != RAD_DRAFT_BLOCK) {
err(RAD_E_STATE, "drafter_tree: %s. Only a BLOCK drafter's one pass proposes every node at "
"once; declare it with rad_declare_drafter first.",
prog_.drafter.kind == RAD_DRAFT_NONE ? "no drafter is declared"
: "the declared drafter is a SERIAL head");
return RAD_E_STATE;
}
if (parents == RAD_NULL_HANDLE || (size_t)parents >= prog_.buffers.size()) {
err(RAD_E_INVAL, "drafter_tree '%s': parents buffer %u is not a declared buffer",
prog_.drafter_name.c_str(), (unsigned)parents);
return RAD_E_INVAL;
}
if (prog_.buffers[parents].decl.dtype != RAD_I32) {
err(RAD_E_DTYPE, "drafter_tree '%s': parents buffer '%s' is not i32",
prog_.drafter_name.c_str(), prog_.buffers[parents].name.c_str());
return RAD_E_DTYPE;
}
prog_.drafter_tree = true;
prog_.drafter_parents = parents;
return RAD_OK;
}
void Builder::note_v(const char* f, va_list ap) {
char msg[1024];
vsnprintf(msg, sizeof msg, f ? f : "", ap);
@@ -2429,6 +2463,16 @@ int Builder::finish() {
w.source.c_str(), rad_dtype_name(w.decl.dtype));
}
if (prog_.drafter.kind == RAD_DRAFT_BLOCK && !prog_.drafter_tree &&
(prog_.drafter.block < prog_.drafter.depth ||
prog_.drafter.block > (int64_t)prog_.drafter.depth + 1))
err(RAD_E_INVAL, "declare_drafter '%s': block %lld rows at depth %d. The head runs over the "
"last %d rows of the block, so the block is either %d rows (the anchor "
"predicts nothing) or %d (it does); only a tree (rad_drafter_tree) "
"proposes a node count other than its block's drafts.",
prog_.drafter_name.c_str(), (long long)prog_.drafter.block, prog_.drafter.depth,
prog_.drafter.depth, prog_.drafter.depth + 1, prog_.drafter.depth);
if (instances_) finish_instances();
fill_tune_instances();
finish_weight_uses();
@@ -2612,6 +2656,11 @@ int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const ch
return B(b)->lora_alias(native, from, to, from_lo, from_hi, to_lo);
}
int rad_drafter_tree(RadBuilder* b, rad_buf parents) {
if (!b) return RAD_E_INVAL;
return B(b)->drafter_tree(parents);
}
int rad_chain_on(void) { return rad_dev_chain_enabled(); }
int rad_drafter_short_block(RadBuilder* b, int64_t block) {
+7 -3
View File
@@ -175,8 +175,12 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
/* An imported quantisation is served by the family's quantised plugin (startup.h). A plugin
* that declines imports (rad_arch_serves_imports) is left out of the family here: neither
* counted as a second quantised plugin nor picked as the only one. */
if (imported && !arch_id.empty() && out->arch_plugin.empty()) {
* counted as a second quantised plugin nor picked as the only one. Block-scaled fp8 reads
* stock weight by weight, so a family with no plugin claiming it is served the same way: the
* plugin declares each weight at the encoding it finds (Qwen3.8-Flash-Next-FP8: fp8 routed
* experts beside bf16 linears, served by qwen4exp_fp8). */
const bool stock = quant == "fp8_e4m3";
if ((imported || stock) && !arch_id.empty() && out->arch_plugin.empty()) {
std::vector<const Plugin*> fam, quantised;
for (const Plugin& p : r.plugins())
if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id && p.arch_serves_imports) {
@@ -198,7 +202,7 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
out->arch_version = pick->version;
out->arch_id = pick->arch_id;
out->arch_quant = pick->arch_quant;
RAD_INFO("quantisation '%s' is imported weight by weight; '%s' serves it as %s",
RAD_INFO("quantisation '%s' is read weight by weight; '%s' serves it as %s",
quant.c_str(), pick->name.c_str(),
pick->arch_quant.empty() ? "(unquantised)" : pick->arch_quant.c_str());
}
+3 -2
View File
@@ -68,8 +68,9 @@ std::string rad_home_file(const std::string& home, const std::string& rel);
* its descriptor names the producing tool and no plugin claims it. The family's quantised plugin
* serves it: the one plugin claiming a descriptor, or the only plugin if none does. Two quantised
* plugins are refused by name. A plugin whose rad_arch_serves_imports returns 0 is left out of
* both counts. `out->arch_quant` is the chosen descriptor, which a container
* converted from it records. */
* both counts. Block-scaled fp8 (`fp8_e4m3`) that no plugin of the family claims is served the
* same way, since its weights read stock. `out->arch_quant` is the chosen descriptor, which a
* container converted from it records. */
int rad_tools_load_plugins(const std::string& radiance_home,
const std::vector<std::string>& hierarchy,
const std::string& arch_id,
+29 -8
View File
@@ -110,7 +110,10 @@ static const Flag g_flags[] = {
" host memory at load, pinned for the cards to read\n"
" (locked, where only a host kernel reads it); disk reads\n"
" its rows from the container on the host. auto takes the\n"
" first of the three that holds it" },
" first of the three that holds it. ram=DIR makes the\n"
" pinned copy a file in DIR (a tmpfs) mapped shared, so\n"
" two engines on separate cards hold one table: the\n"
" first fills it, the last to exit deletes it" },
{ "--weights-disk-tier", nullptr, "read weights that fit neither VRAM nor the host pool from the\n"
" container on disk (O_DIRECT); a routed expert is read a layer\n"
" at a time, so a step is paced by the drive" },
@@ -180,8 +183,9 @@ static const Flag g_flags[] = {
" with no draft head is unaffected -- auto resolves to 0." },
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
{ "--draft-short-from", "N", "a block drafter that also serves a shorter block runs it\n"
"from N decoding sequences on (0 never, the default): the\n"
"long block pays at one sequence, the short one at many" },
"from N decoding sequences on (0 never): the long block pays\n"
"at one sequence, the short one at many. auto (the default):\n"
"never for a chain, from 2 for a tree drafter" },
{ "--draft-coupling", "MODE", "off (default) | on -- a linear MTP drafter or DFlash2's walk\n"
" samples each proposal from its own shortlist and the sampler\n"
" couples the target's draw to it: more accepted drafts on sampled\n"
@@ -585,10 +589,20 @@ int config_parse(int argc, char** argv, Config* c) {
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
return RAD_E_INVAL;
}
if (!emb && !parse_table_placement(v, &p)) {
RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v);
std::string share_dir;
if (!emb && !std::strncmp(v, "ram=", 4)) {
share_dir = v + 4;
if (share_dir.empty()) {
RAD_ERR("--ngram-placement ram= needs a directory: ram=DIR, the tmpfs that "
"holds the shared table");
return RAD_E_INVAL;
}
p = TablePlacement::Ram;
} else if (!emb && !parse_table_placement(v, &p)) {
RAD_ERR("%s takes auto, vram, ram, ram=DIR or disk, not '%s'", a.c_str(), v);
return RAD_E_INVAL;
}
if (!emb) c->ngram_share_dir = share_dir;
(emb ? c->embedding_placement : c->ngram_placement) = p;
if (emb) c->embedding_placement_given = true;
}
@@ -727,7 +741,11 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
}
else if (S("--draft-short-from")) { if (!num(0, INT32_MAX, &c->draft_short_from)) return RAD_E_INVAL; }
else if (S("--draft-short-from")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "auto")) c->draft_short_from = -1;
else if (!parse_int(a.c_str(), v, 0, INT32_MAX, &c->draft_short_from)) return RAD_E_INVAL;
}
else if (S("--draft-coupling")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "off")) c->draft_coupling = false;
@@ -1166,7 +1184,9 @@ const ShowRow kShow[] = {
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } },
{ "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } },
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
{ "--ngram-placement", [](const Config& c) { return std::string(table_placement_name(c.ngram_placement)); } },
{ "--ngram-placement", [](const Config& c) {
std::string v = table_placement_name(c.ngram_placement);
return c.ngram_share_dir.empty() ? v : v + "=" + c.ngram_share_dir; } },
{ "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } },
{ "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } },
{ "--prefix-cache-mib", [](const Config& c) {
@@ -1202,7 +1222,8 @@ const ShowRow kShow[] = {
{ "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } },
{ "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } },
{ "--draft-short-from", [](const Config& c) {
return c.draft_short_from > 0 ? num(c.draft_short_from) : std::string("0 (never)"); } },
return c.draft_short_from < 0 ? std::string("auto")
: c.draft_short_from > 0 ? num(c.draft_short_from) : std::string("0 (never)"); } },
{ "--draft-coupling", [](const Config& c) { return onoff(c.draft_coupling); } },
{ "--draft-model", [](const Config&) { return std::string("not implemented (the container's own drafter)"); } },
{ "--host", [](const Config& c) { return c.host; } },
+103 -26
View File
@@ -3644,6 +3644,43 @@ void* pin_whole(int64_t bytes, const std::vector<hsa_agent_t>& cards) {
return p;
}
/* Locks [p, p + len) in pieces of at most kPinPiece for every card, each mapped on the cards at
* its host address. On failure sets the device error for `who` (asked for `bytes`), unlocks what
* was locked and returns false; the mapping stays the caller's to unmap. */
bool lock_pieces(char* p, int64_t len, int64_t bytes, std::vector<hsa_agent_t>& cards,
const char* who) {
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
int done = 0;
for (; done < pieces; ++done) {
const int64_t off = (int64_t)done * kPinPiece;
const int64_t n = std::min(kPinPiece, len - off);
void* on_card = nullptr;
const hsa_status_t st = hsa_amd_memory_lock_to_pool(p + off, (size_t)n, cards.data(),
(int)cards.size(), G().host_fine, 0,
&on_card);
if (st != HSA_STATUS_SUCCESS) {
device_set_error("%s(%s): locking piece %d of %d (%s at +%s): %s", who,
humanb(bytes).c_str(), done + 1, pieces, humanb(n).c_str(),
humanb(off).c_str(), hsa_why(st));
break;
}
if (on_card != p + off) {
++done;
device_set_error("%s(%s): piece %d of %d is mapped on the cards at %p, not "
"at its host address %p, so the pieces are not one range there, "
"although the kernel driver reports the SVM API that maps a lock in "
"place",
who, humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off));
break;
}
}
if (done < pieces) {
for (int i = 0; i < done; ++i) (void)hsa_amd_memory_unlock(p + (int64_t)i * kPinPiece);
return false;
}
return true;
}
void* pin_pieces(int64_t bytes) {
std::vector<hsa_agent_t> cards;
for (const Dev& d : G().dev) cards.push_back(d.agent);
@@ -3672,33 +3709,61 @@ void* pin_pieces(int64_t bytes) {
}
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
int done = 0;
for (; done < pieces; ++done) {
const int64_t off = (int64_t)done * kPinPiece;
const int64_t n = std::min(kPinPiece, len - off);
void* on_card = nullptr;
const hsa_status_t st = hsa_amd_memory_lock_to_pool(p + off, (size_t)n, cards.data(),
(int)cards.size(), G().host_fine, 0,
&on_card);
if (st != HSA_STATUS_SUCCESS) {
device_set_error("rad_dev_alloc(%s): locking piece %d of %d (%s at +%s): %s",
humanb(bytes).c_str(), done + 1, pieces, humanb(n).c_str(),
humanb(off).c_str(), hsa_why(st));
break;
}
if (on_card != p + off) {
++done;
device_set_error("rad_dev_alloc(%s): piece %d of %d is mapped on the cards at %p, not "
"at its host address %p, so the pieces are not one range there, "
"although the kernel driver reports the SVM API that maps a lock in "
"place",
humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off));
break;
}
if (!lock_pieces(p, len, bytes, cards, "rad_dev_alloc")) {
::munmap(p, (size_t)len);
return nullptr;
}
if (done < pieces) {
for (int i = 0; i < done; ++i) (void)hsa_amd_memory_unlock(p + (int64_t)i * kPinPiece);
std::lock_guard<std::mutex> lk(g_pinned_mu);
g_pinned.emplace((uintptr_t)p, Pinned{len, nullptr});
return p;
}
/* pin_pieces over a shared file mapping instead of private anonymous memory: the pages are the
* file's (a tmpfs file other processes map too) and the lock takes them in place. The file maps
* onto a 2 MiB boundary inside a reservation made with one alignment extra, then the ends are
* trimmed. MADV_HUGEPAGE is advised but shmem follows shmem_enabled, not it. A tmpfs page is
* swappable until the lock pins it, so MLOCK_ONFAULT keeps the pages in memory meanwhile; a
* refusal (the memlock limit) costs only that. */
void* pin_pieces_file(int64_t bytes, int fd, int64_t foff) {
std::vector<hsa_agent_t> cards;
for (const Dev& d : G().dev) cards.push_back(d.agent);
if (!svm_in_place()) {
device_set_error("rad_dev_map_file(%s): a file range is pinned in place only through the "
"kernel driver's SVM API, which this host lacks, so ram=DIR needs it",
humanb(bytes).c_str());
return nullptr;
}
const int64_t align = RAD_ALIGN_POOL;
const int64_t len = align_up(bytes, 4096);
void* m = ::mmap(nullptr, (size_t)(len + align), PROT_NONE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (m == MAP_FAILED) {
device_set_error("rad_dev_map_file(%s): mmap: %s", humanb(bytes).c_str(),
std::strerror(errno));
return nullptr;
}
const uintptr_t lo = (uintptr_t)m;
const uintptr_t at = (lo + (uintptr_t)align - 1) & ~((uintptr_t)align - 1);
if (::mmap((void*)at, (size_t)len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd,
(off_t)foff) == MAP_FAILED) {
device_set_error("rad_dev_map_file(%s): mmap of the file at +%s: %s", humanb(bytes).c_str(),
humanb(foff).c_str(), std::strerror(errno));
::munmap(m, (size_t)(len + align));
return nullptr;
}
if (at > lo) ::munmap(m, at - lo);
if (lo + (uintptr_t)align > at) ::munmap((void*)(at + (uintptr_t)len), lo + (uintptr_t)align - at);
char* const p = (char*)at;
if (len >= ((int64_t)2 << 20)) (void)::madvise(p, (size_t)len, MADV_HUGEPAGE);
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
if (::mlock2(p, (size_t)len, MLOCK_ONFAULT) != 0)
RAD_WARN("device: the shared file range %p (%s) could not be locked against swap (mlock2: "
"%s)", (void*)p, humanb(len).c_str(), std::strerror(errno));
prefer_numa_node(p, len, current_card_numa_node());
if (!lock_pieces(p, len, bytes, cards, "rad_dev_map_file")) {
::munmap(p, (size_t)len);
return nullptr;
}
@@ -3762,6 +3827,17 @@ void* a_alloc(int64_t bytes, int kind) {
return p;
}
void* a_map_file(int fd, int64_t foff, int64_t bytes) {
if (fd < 0 || foff < 0 || bytes <= 0) {
device_set_error("rad_dev_map_file(%d, %lld, %lld): a file, a non-negative offset and a "
"positive size are needed", fd, (long long)foff, (long long)bytes);
return nullptr;
}
void* p = pin_pieces_file(bytes, fd, foff);
note_alloc(p, bytes, RAD_MEM_HOST_MAPPED);
return p;
}
/* Every free invalidates locate()'s cache first. */
void (*g_hip_free)(void*, int) = nullptr;
void a_free(void* p, int kind) {
@@ -3842,6 +3918,7 @@ const DeviceBackend* aql_backend_if_present(void) {
g_hip_host_ptr = hip->host_ptr;
g_hip_device_ptr = hip->device_ptr;
g_aql.alloc = a_alloc;
g_aql.map_file = a_map_file;
g_aql.free = a_free;
g_aql.host_ptr = a_host_ptr;
g_aql.device_ptr = a_device_ptr;
+11
View File
@@ -135,6 +135,14 @@ extern "C" int64_t rad_xp_behind(int device);
extern "C" void* rad_dev_alloc_uncached(int64_t bytes);
extern "C" void rad_dev_free_uncached(void* p);
/* [foff, foff + bytes) of the open file `fd`, mapped MAP_SHARED and pinned for every card as a
* RAD_MEM_HOST_MAPPED allocation is: one range at the same address on host and cards. For a table
* that engines on separate cards share through a tmpfs file (format/table_share.h). `foff` is a
* multiple of 2 MiB and the file holds the whole range. Freed with rad_dev_free(p,
* RAD_MEM_HOST_MAPPED), which unpins and unmaps and leaves the file alone. Null with the reason in
* rad_dev_last_error() on a backend without it or a failure. */
extern "C" void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes);
/* A gate on a stream: the stream stops at the point rad_stream_gate enqueues and goes on once the
* host calls rad_gate_open. Everything enqueued behind the gate meanwhile is then ready at once, so
* the device runs it back to back however long the host took to submit it. For timing a batch of
@@ -339,6 +347,9 @@ struct DeviceBackend {
/* ---- rad_event_dma; null on a backend with no DMA queue. */
int (*event_dma)(RadEvent e, RadStream s, uint32_t** word);
/* ---- see rad_dev_map_file. Null on a backend with no pinned host memory to map a file into. */
void* (*map_file)(int fd, int64_t foff, int64_t bytes);
};
+14
View File
@@ -648,6 +648,20 @@ void* rad_dev_alloc_uncached(int64_t bytes) {
if (const auto f = dev()->alloc_uncached) return f(bytes);
return nullptr;
}
void* rad_dev_map_file(int fd, int64_t foff, int64_t bytes) {
const auto f = dev()->map_file;
if (!f) {
rad::device_set_error("rad_dev_map_file: the %s backend has no pinned host memory to map a "
"file into", dev()->name);
return nullptr;
}
void* p = f(fd, foff, bytes);
if (p) {
rad::g_ledger[RAD_MEM_HOST_MAPPED].bytes.fetch_add(bytes, std::memory_order_relaxed);
rad::g_ledger[RAD_MEM_HOST_MAPPED].count.fetch_add(1, std::memory_order_relaxed);
}
return p;
}
void rad_dev_free_uncached(void* p) {
if (const auto f = dev()->free_uncached) f(p);
}
+106 -47
View File
@@ -109,6 +109,8 @@ Engine::~Engine() {
table_copies_.clear();
for (void* p : card_copies_) rad_dev_free(p, RAD_MEM_HOST_MAPPED);
card_copies_.clear();
for (TableShare& t : table_shares_) table_share_close(&t);
table_shares_.clear();
rad_tools_registry().close();
}
@@ -553,6 +555,14 @@ int Engine::step_loop() {
pipelining_ = !cfg_.kld() && !embedding_ &&
(serial_drafting() || block_drafting() || cfg_.n_spec <= 0);
early_ids_ = !cfg_.kld() && !embedding_;
/* A tree's acceptance moves K and V on the card behind the step issued ahead. The KL mode
* drafts nothing and an embedding model declares no drafter, so no server reaches this today;
* it keeps a tree from running unverified should another path turn pipelining off. */
if (tree_ && !pipelining_) {
RAD_ERR("speculation: drafter '%s' proposes trees, which are verified only on steps issued "
"ahead, and this server issues none; ask the plugin for a chain", drafter_.name);
return fail_loop(RAD_E_UNSUPPORTED);
}
const bool t_on = (int)log_level() >= (int)Log::Debug;
/* The next step's forward pass when already issued behind the previous step, before its
* readback (Scheduler::step_next). */
@@ -788,46 +798,11 @@ int Engine::step_loop() {
return fail_loop(st);
}
/* Snapshot after the step that produced the state: the chunker ended this chunk at the
* checkpoint position, so copy 0 holds exactly that state. The copy to the host slot is
* issued before collect_step's readback and before any step issued ahead, which orders the
* next write of the state after it. Under the scheduler's lock, as the restore. */
bool any_save = false;
for (const StepEntry& e : plan.e)
if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0) { any_save = true; break; }
if (any_save) {
const int ss = sched_.locked([&]() -> int {
for (const StepEntry& e : plan.e) {
if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue;
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
/* The window behind the checkpoint position. The chunk ending there still
* holds it, so a miss is a broken invariant; skipping would commit a slot
* holding another sequence's pages. */
if (ranks_[0]->kv.has_window_snapshot() &&
!ranks_[0]->kv.window_rows(e.seq, e.ctx_len + e.ckpt_tok + 1,
&ckpt_win_)) {
RAD_ERR("sequence %llu: the window behind checkpoint %d is not held",
(unsigned long long)e.seq, (int)(e.ctx_len + e.ckpt_tok + 1));
return RAD_E_STATE;
}
for (auto& rk : ranks_) {
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
const int s = rk->kv.checkpoint_save(ckpt_slots_.data(),
(int)ckpt_slots_.size(),
e.ckpt_slot, rk->ctx.stream(),
&ckpt_win_);
if (s < 0) {
RAD_ERR("rank %d could not snapshot sequence %llu into checkpoint slot "
"%d: %s", rk->index, (unsigned long long)e.seq,
(int)e.ckpt_slot, rad_strerror(s));
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
return s;
}
}
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
}
return RAD_OK;
});
/* Snapshot after the step that produced the state (save_checkpoints). Where a block
* drafter's window rides in the snapshot, its context pass must store the step's rows
* first, so the card's driver saves right behind that pass instead. */
if (!(block_drafting() && drafter_snap_)) {
const int ss = save_checkpoints();
if (ss < 0) return fail_loop(ss);
}
@@ -902,6 +877,7 @@ int Engine::step_loop() {
res.lp = so.lp.data();
res.first_row = so.first_row.data();
}
res.path = so.path.empty() ? nullptr : so.path.data();
st = sched_.commit(res);
if (t_on) phase_mark(PH_COMMIT);
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
@@ -1164,6 +1140,57 @@ int Engine::collect_pooled(const RadBatch* b, StepOut& so) {
return RAD_OK;
}
/* Snapshot after the step that produced the state. Linear state is what the chunk's last token
* leaves, so the chunker ended the chunk at the checkpoint and copy 0 holds exactly that state; a
* window snapshot is the window's rows behind the checkpoint, which may lie inside the chunk
* (plan_chunk) and are still held when it ends. The copy to the host slot is issued before
* collect_step's readback and before any step issued ahead, which orders the next write of the
* state after it. Under the scheduler's lock, as the restore. A block drafter's window in the
* snapshot (drafter_snap_) is saved behind the drafter's context pass (issue_block_drafter),
* which writes only the drafter's groups. */
int Engine::save_checkpoints() {
const StepPlan& plan = sched_.plan();
bool any_save = false;
for (const StepEntry& e : plan.e)
if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0) { any_save = true; break; }
if (any_save) {
const int ss = sched_.locked([&]() -> int {
for (const StepEntry& e : plan.e) {
if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue;
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
/* The window behind the checkpoint position. This step's chunk reaches it, and
* a window slides only from a step's first query, so a miss is a broken
* invariant; skipping would commit a slot holding another sequence's pages. */
if (ranks_[0]->kv.has_window_snapshot() &&
!ranks_[0]->kv.window_rows(e.seq, e.ctx_len + e.ckpt_tok + 1,
&ckpt_win_)) {
RAD_ERR("sequence %llu: the window behind checkpoint %d is not held",
(unsigned long long)e.seq, (int)(e.ctx_len + e.ckpt_tok + 1));
return RAD_E_STATE;
}
for (auto& rk : ranks_) {
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
const int s = rk->kv.checkpoint_save(ckpt_slots_.data(),
(int)ckpt_slots_.size(),
e.ckpt_slot, rk->ctx.stream(),
&ckpt_win_);
if (s < 0) {
RAD_ERR("rank %d could not snapshot sequence %llu into checkpoint slot "
"%d: %s", rk->index, (unsigned long long)e.seq,
(int)e.ckpt_slot, rad_strerror(s));
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
return s;
}
}
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
}
return RAD_OK;
});
if (ss < 0) return ss;
}
return RAD_OK;
}
/* Scored rows (Request::token_scores): the logits row at a scored prompt's last position, copied
* to the host before the sampler can rewrite it in place. stage_scored_rows picks the rows while
* every rank is parked; issue_scored_rows copies one row per rank stream ahead of its sampler;
@@ -1235,10 +1262,11 @@ int Engine::collect_scored_rows() {
/* One sampled row's logprobs into the step's table, sized on first use. A non-finite row
* (RAD_E_INVAL) is left at token -1, and the scheduler fails only that request. A row outside the
* step, or never staged for logprobs, is an engine error. */
int Engine::row_logprobs(StepOut& so, int32_t row, int32_t token) {
int Engine::row_logprobs(StepOut& so, int32_t row, int32_t token, int32_t at) {
if (so.lp.empty()) so.lp.resize((size_t)so.n_rows);
if (row < 0 || row >= so.n_rows) return RAD_E_STATE;
TokenLogprobs& lp = so.lp[(size_t)row];
if (at < 0) at = row;
if (row < 0 || row >= so.n_rows || at >= so.n_rows) return RAD_E_STATE;
TokenLogprobs& lp = so.lp[(size_t)at];
const int s = ranks_[0]->sampler.logprobs_for(row, token, &lp);
if (s == RAD_E_INVAL) { lp = TokenLogprobs{}; return RAD_OK; }
return s;
@@ -1252,6 +1280,7 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
so.accepted.assign(plan.e.size(), 0);
so.eos.assign(plan.e.size(), 0);
so.lp.clear();
so.path.clear();
if (so.n_rows <= 0) return RAD_OK;
so.rows.resize((size_t)so.n_rows);
@@ -1302,7 +1331,16 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
if (!e.req) continue;
int32_t out[RAD_SCHED_MAX_SPEC + 1] = { 0 };
int32_t acc = 0;
RAD_TRY(accept_greedy(e.draft, e.n_spec, &so.rows[(size_t)so.first_row[i]], out, &acc));
/* A tree step verifies every proposal as a tree (a chain one as the chain-shaped
* tree), as the card's acceptance does; `path` names the accepted nodes. */
int32_t path[RAD_SCHED_MAX_SPEC] = { 0 };
const bool tree = plan.spec_is_tree;
if (tree)
RAD_TRY(accept_tree(e.draft, e.draft_parent, e.n_spec,
&so.rows[(size_t)so.first_row[i]], out, path, &acc));
else
RAD_TRY(accept_greedy(e.draft, e.n_spec, &so.rows[(size_t)so.first_row[i]], out,
&acc));
/* Truncated at the first end-of-generation token, so `accepted` and `token` (which
* drive the KV rollback, the conv cursor and the emitted text) say how far the step
@@ -1313,11 +1351,19 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
so.accepted[i] = acc;
so.token[i] = out[acc];
so.eos[i] = vocab_ && vocab_->is_eog(so.token[i]) ? 1 : 0;
if (tree) {
if (so.path.empty()) so.path.assign(plan.e.size() * RAD_SCHED_MAX_SPEC, 0);
for (int32_t t = 0; t < acc; ++t) so.path[i * RAD_SCHED_MAX_SPEC + t] = path[t];
}
/* Each emitted token's logprobs come from its own row, the distribution it was drawn
* from. */
* from: on a tree, the row of the node it follows. They are filed as the entry's j-th
* emitted token (StepResult::lp), whichever row they came from. */
if (e.req && e.req->sp.n_probs >= 0)
for (int32_t j = 0; j <= acc; ++j)
RAD_TRY(row_logprobs(so, so.first_row[i] + j, out[j]));
for (int32_t j = 0; j <= acc; ++j) {
const int32_t from = tree && j > 0 ? path[j - 1] : j;
RAD_TRY(row_logprobs(so, so.first_row[i] + from, out[j],
so.first_row[i] + j));
}
/* Advance the grammar over every emitted token, accepted drafts included, up to the
* truncated `acc`, so it sees exactly what the client sees. */
if (e.req)
@@ -2351,6 +2397,12 @@ int Engine::run_server() {
s.link.h2d_bytes = s.link.d2h_bytes = s.link.ssd_reads = 0;
s.link.ssd_bytes = s.link.prefetched = s.link.prefetch_bytes = 0;
s.link.stream_bytes = s.link.staged_bytes = 0;
s.link.kv_stream_bytes = 0;
s.link.kv_streaming = cfg_.kv_resident > 0; /* zeroed here if the arch refused it */
/* The ring's depth, not the flag: KVStreamStats::resident_blocks sums the device pool
* of every group that really runs a window under its context, so this is zero when
* --kv-resident was asked for and nothing streams anyway. */
s.link.kv_stream_active = ranks_[0]->kv.stream_stats().resident_blocks > 0;
for (const auto& rk : ranks_) {
const MoverStats rms = rk->mover.stats();
s.link.h2d_bytes += (int64_t)rms.h2d_bytes;
@@ -2362,6 +2414,13 @@ int Engine::run_server() {
s.link.staged_bytes += (int64_t)rms.staged_bytes;
if (rk->heat.enabled()) s.link.stream_bytes += (int64_t)rk->heat.stats().stream_bytes;
}
/* KV streaming: only rank 0's resolve counters are read -- every rank sees the same
* misses by design -- so the figure takes the world factor to reach all cards, the
* way the summed move rows sit there. The counters ride the step's ctl read; nothing
* here costs a step. */
if (s.link.kv_streaming)
s.link.kv_stream_bytes =
(int64_t)ranks_[0]->kv.stream_stats().bytes_in * (int64_t)ranks_.size();
}
};
+38 -5
View File
@@ -33,6 +33,7 @@
#include "text/tokenizer.h"
#include "format/radfile.h"
#include "format/table_copy.h"
#include "format/table_share.h"
#include "lora/adapter.h"
#include "lora/slots.h"
@@ -230,7 +231,7 @@ private:
int64_t host_late);
/* --ngram-placement ram: one copy of the container's [src, src + n) at file offset `foff`,
* shared by every rank. Locked for the host gather, or pinned for a device kernel to read
* over the link (`card`). */
* over the link (`card`); with ram=DIR the pinned copy is a file other engines map too. */
int copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
std::string* why);
/* An auto-chosen pinned copy failed: move every rank's n-gram gather to the host. */
@@ -240,6 +241,9 @@ private:
* the ranks that read them are gone. */
std::vector<TableCopy> table_copies_;
std::vector<void*> card_copies_;
/* The files behind the card copies made under --ngram-placement ram=DIR. Closed after the
* copies are freed, because the holder that leaves last deletes the file. */
std::vector<TableShare> table_shares_;
std::vector<std::pair<const void*, void*>> table_copy_of_;
/* --expert-profile: the decode ranking loaded once, before any rank plans, and handed to every
* rank's planner in place of the container's activation profile. */
@@ -268,6 +272,9 @@ private:
/* The ids' copy recorded tok_end_ ahead of the drafter's passes: collect_step waits for
* it alone, and the step loop for step_end_ after the commit. */
bool early = false;
/* [n_seq][RAD_SCHED_MAX_SPEC] on a tree step (StepPlan::spec_is_tree): each entry's
* accepted nodes in commit order (accept_tree's path). Empty on a chain step. */
std::vector<int32_t> path;
};
/* The text frontend, loaded from the container. The sampler's grammars walk `vocab_view_`,
@@ -341,7 +348,9 @@ private:
* records tok_end_, so the wait for the ids skips the passes (StepOut::early). */
int collect_issue(StepOut& so, bool fence = false);
int collect_step(const RadBatch* b, StepOut& so);
int row_logprobs(StepOut& so, int32_t row, int32_t token);
/* `row`'s logprobs for `token`, filed at `at` (default `row`): a tree verify emits a token from
* its parent node's row but files it as the entry's j-th emitted token. */
int row_logprobs(StepOut& so, int32_t row, int32_t token, int32_t at = -1);
/* The step's end on the card: after its last draft pass and the host readbacks, before the
* step issued ahead. The engine waits on this event, not the stream, so the card runs the
* next step while the host commits this one. */
@@ -375,10 +384,12 @@ private:
* string because RadDrafterDecl::name points into the Program. */
RadDrafterDecl drafter_{};
std::string drafter_name_;
/* The block drafter's shorter block (rad_drafter_short_block), 0 when it has none or
* --draft-short-from is 0. */
/* The block drafter's shorter block (rad_drafter_short_block), 0 when it has none or will not
* run it (--draft-short-from 0, or auto for a chain). */
int64_t drafter_short_ = 0;
bool short_on_ = false; /* the short block runs now (block_shape) */
/* --draft-short-from resolved at bring-up (auto: 0 for a chain, 2 for a tree). */
int64_t short_from_ = 0;
/* Serial driver (spec §10): `depth` dependent passes after the step commits, each embedding
* the previous proposal. MTP, EAGLE and Medusa-serial have this shape. */
@@ -475,11 +486,33 @@ private:
* both behind the step before its readback and finish_block_drafter publishes the proposals
* after the commit, so the step can be issued ahead. */
bool block_drafting() const;
/* RadBuildCtx::draft_tree for every declare: decided once in declare() from the plugin's probe
* (RadArchProbe::tree_pays). */
bool draft_tree_ = false;
int block_pass(const RadBatch* db, const char* what, int step);
/* A program's block drafter rides its window in the window snapshot: it stores its context
* in the context pass right behind the trunk step, and the snapshot is saved after that. Only
* where the trunk's window is snapshotted at all (window_snapshots): a full-attention trunk
* takes no snapshot for a drafter's window alone. */
bool drafter_window_snap(const Program& p) const {
return cfg_.n_spec > 0 && p.drafter.kind == RAD_DRAFT_BLOCK && p.drafter.depth > 0 &&
window_snapshots(p, cfg_);
}
/* The drafter's window rides in the window snapshot (KVManager::drafter_window_snapshot), so
* the checkpoint save waits for its context pass (save_checkpoints). */
bool drafter_snap_ = false;
int save_checkpoints();
/* A tree drafter (rad_drafter_tree), driven on the card only: ADV_BTAKE takes its parents,
* ADV_COMPACT moves the accepted path's K and V after the acceptance, and ADV_CTXTREE stages
* the context pass by that path. */
bool tree_ = false;
rad_buf tree_parents_ = 0;
int tree_compact(int rows);
int issue_block_drafter(int step, StepOut& so);
int finish_block_drafter(const StepOut& so);
/* The block and proposal count this step's query pass runs at: the drafter's own, or its short
* block once --draft-short-from sequences decode, back to its own only two below. */
* block once --draft-short-from sequences decode, back to its own two below or at one sequence
* (Scheduler::short_block_on). */
void block_shape(int* block, int* steps);
/* Handed from issue_block_drafter to finish_block_drafter and issue_ahead: the drafting rows,
* in the query pass's order, and how many there are (0 when no query pass ran). */
+148 -22
View File
@@ -19,6 +19,7 @@
#include "format/rope_override.h"
#include "format/share.h"
#include "format/table_copy.h"
#include "format/table_share.h"
#include "rad_plugin.h"
#include "mem/vram_budget.h"
#include "kvstream/bringup.h"
@@ -399,15 +400,59 @@ static int64_t lockable_bytes(int64_t still, int64_t margin, std::string* limit)
}
/* The copy is table_copy_make's (core/format/table_copy.h), or for a card, table_copy_fill into
* pinned memory every card maps (rad_dev_alloc RAD_MEM_HOST_MAPPED, locked in pieces). One copy
* per container address, shared by every rank; freed in ~Engine. */
* pinned memory every card maps (rad_dev_alloc RAD_MEM_HOST_MAPPED, locked in pieces). With
* --ngram-placement ram=DIR the pinned memory is a file in DIR mapped shared (core/format/
* table_share.h): this engine fills it or, if another engine did, checks samples of it against the
* container, and pins it either way. Only a table of kTableShareMin or more is shared: the gather's
* scale is an n-gram weight too, since it moves with the table between gather sites, and as a file
* its two bytes would cost the 2 MiB header and a 2 MiB page. One copy per container address,
* shared by every rank; freed in ~Engine. */
int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
std::string* why) {
for (const auto& c : table_copy_of_)
if (c.first == src) { *out = c.second; return RAD_OK; }
const auto t0 = std::chrono::steady_clock::now();
auto since = [&] {
return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
};
void* base = nullptr;
if (card) {
if (card && !cfg_.ngram_share_dir.empty() && n >= kTableShareMin) {
const std::string id = table_share_id(file_->path(), foff, n);
if (id.empty()) {
*why = fmt("the container %s cannot be stat'ed, which names the shared table",
file_->path());
return RAD_E_IO;
}
TableShare s;
int rc = table_share_open(cfg_.ngram_share_dir, id, n, &s, why);
if (rc != RAD_OK) return rc;
base = rad_dev_map_file(s.fd, kTableShareHeader, n);
if (!base) {
*why = fmt("pinning %s of %s: %s", humanb(n).c_str(), s.path.c_str(),
rad_dev_last_error());
table_share_close(&s);
return RAD_E_NOMEM;
}
if (s.filler) {
rc = table_copy_fill(*file_, src, n, foff, static_cast<uint8_t*>(base), why);
if (rc == RAD_OK) rc = table_share_mark_ready(&s, n, id, why);
} else {
rc = table_copy_check(src, n, static_cast<const uint8_t*>(base), why);
if (rc != RAD_OK)
*why = fmt("the shared file %s does not match the container (%s)", s.path.c_str(),
why->c_str());
}
if (rc != RAD_OK) {
rad_dev_free(base, RAD_MEM_HOST_MAPPED);
table_share_close(&s);
return rc;
}
card_copies_.push_back(base);
table_shares_.push_back(s);
RAD_INFO("placement: n-gram table in pinned memory the cards read, %s in shared file %s, "
"%s in %.1f s", humanb(n).c_str(), s.path.c_str(),
s.filler ? "filled" : "reused (probes match)", since());
} else if (card) {
base = rad_dev_alloc(n, RAD_MEM_HOST_MAPPED);
if (!base) {
*why = fmt("pinning %s: %s", humanb(n).c_str(), rad_dev_last_error());
@@ -419,16 +464,17 @@ int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, v
return rc;
}
card_copies_.push_back(base);
RAD_INFO("placement: n-gram table copied into pinned memory the cards read, %s in %.1f s",
humanb(n).c_str(), since());
} else {
TableCopy tc;
const int rc = table_copy_make(*file_, src, n, foff, &tc, why);
if (rc != RAD_OK) return rc;
table_copies_.push_back(tc);
base = tc.base;
RAD_INFO("placement: n-gram table copied into locked memory, %s in %.1f s",
humanb(n).c_str(), since());
}
RAD_INFO("placement: n-gram table copied into %s, %s in %.1f s",
card ? "pinned memory the cards read" : "locked memory", humanb(n).c_str(),
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
table_copy_of_.push_back({ src, base });
*out = base;
return RAD_OK;
@@ -564,8 +610,43 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
* then the container. */
const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_total_mib() * MiB +
cfg_.prefix_cache_mib * MiB + host_late;
const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy";
/* ram=DIR: the copy is a file other engines map too. One already complete costs this engine
* no host memory for the table; a weight under kTableShareMin beside it (the scale) is a
* private copy either way. */
std::string share_note;
if (!cfg_.ngram_share_dir.empty() && ngram_bytes > 0) {
if (!ngram_device) {
RAD_ERR("--ngram-placement ram=%s: only the pinned copy a card reads is shared, and no "
"loaded kernel plugin reads an n-gram table on a card (embed_lookup_q has host "
"kernels only), so the host gather would read a private locked copy. Use ram "
"or disk.", cfg_.ngram_share_dir.c_str());
return RAD_E_INVAL;
}
share_note = fmt("a file in %s that other engines share", cfg_.ngram_share_dir.c_str());
if (file_ && !ranks_.empty()) {
const Program& prog = ranks_.front()->program;
for (size_t i = 1; i < prog.weights.size(); ++i) {
const WeightInfo& w = prog.weights[i];
if (!is_ngram_table(prog, (rad_weight)i) || w.n_sel < 1) continue;
const RadFileEntry* e = file_->find(w.source);
if (!e) continue;
const RadFilePlane& p0 = file_->plane(*e, w.sel[0]);
if ((int64_t)p0.bytes < kTableShareMin) continue;
const std::string id =
table_share_id(file_->path(), (int64_t)p0.offset, (int64_t)p0.bytes);
if (table_share_is_ready(cfg_.ngram_share_dir, id, (int64_t)p0.bytes)) {
need = align_up(std::max<int64_t>(ngram_bytes - (int64_t)p0.bytes, 0),
(int64_t)2 << 20);
share_note = fmt("a complete shared file in %s already holds it, which "
"takes no memory of this engine's own for the table",
cfg_.ngram_share_dir.c_str());
}
break;
}
}
}
auto card_holds = [&](std::string* why) {
std::vector<VramFacts> with = facts;
int64_t fixed = 0;
@@ -640,7 +721,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
"%s: %s", humanb(ngram_bytes).c_str(), copy, ram_why.c_str());
return RAD_E_NOMEM;
}
ng_why = "as asked";
ng_why = share_note.empty() ? std::string("as asked") : "as asked, as " + share_note;
} else if (card) {
ng = TablePlacement::Vram;
ng_why = "the card holds it beside the other weights and a KV pool for one "
@@ -896,6 +977,7 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
bc.max_seqs = cfg_.max_seqs;
bc.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
bc.max_spec = cfg_.n_spec;
bc.draft_tree = draft_tree_ ? 1 : 0;
bc.tp_wire_lossy = cfg_.tp_wire_exact ? 0 : 1;
/* The engine always states the KV dtype. RAD_DT_INVALID (zero) remains valid in the ABI for
* other callers and means the plugin's default. */
@@ -1125,6 +1207,22 @@ int Engine::declare() {
RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why);
decide("chained launches", on ? "on" : "off", why);
}
/* Trees: a block drafter's proposals verified as a tree, where the model's plugin measured a
* gain with one (RadArchProbe::tree_pays; the Gemma 4 31B with DFlash2: +7% single-stream
* decode, +6-9% aggregate at 1-16 users on 4x R9700) and the drafter decodes speculatively.
* A tree changes no token, only how many drafts land a step. */
{
RadArchProbe pb{};
(void)rad_tools_probe(plugins_, meta_, &pb);
/* A tree is verified only behind a step issued ahead (step_loop). The KL mode, which issues
* none, drafts nothing either (n_spec is 0 there by now), so this never runs under it. */
draft_tree_ = cfg_.n_spec > 0 && pb.tree_pays != 0;
if (draft_tree_) {
const char* why = "the model's plugin measured a gain with them";
RAD_INFO("draft trees: asked -- %s", why);
decide("draft trees", "asked", why);
}
}
/* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio
* encoder (`radiance.encoder` names one) and the deployment is not text-only. */
if (cfg_.mm_audio_frames < 0) {
@@ -1364,7 +1462,14 @@ int Engine::declare() {
drafter_name_ = p0.drafter_name;
drafter_.name = drafter_name_.c_str();
if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{};
drafter_short_ = drafter_.kind == RAD_DRAFT_BLOCK && cfg_.draft_short_from > 0
/* A tree drafter (rad_drafter_tree): its parents plane rides with the proposal. */
tree_ = drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0 && p0.drafter_tree;
tree_parents_ = tree_ ? p0.drafter_parents : 0;
/* --draft-short-from auto: a chain keeps its own block, a tree runs its short block from two
* decoding sequences on. Its nodes are verify rows every drafting sequence pays for, which a
* wide tree's extra nodes repay at one sequence and not at many. */
short_from_ = cfg_.draft_short_from >= 0 ? cfg_.draft_short_from : (tree_ ? 2 : 0);
drafter_short_ = drafter_.kind == RAD_DRAFT_BLOCK && short_from_ > 0
? p0.drafter_short_block : 0;
if (cfg_.draft_short_from > 0 && drafter_.kind == RAD_DRAFT_NONE)
RAD_WARN("--draft-short-from %lld: this deployment runs no drafter, so there is no block "
@@ -1374,14 +1479,23 @@ int Engine::declare() {
drafter_name_.c_str(),
drafter_.kind == RAD_DRAFT_BLOCK ? "declares no shorter block, so it keeps its own"
: "is a serial head, which proposes no block");
if (drafter_short_)
if (drafter_short_ && tree_)
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
"row(s), %lld token(s)", (long long)cfg_.draft_short_from,
"row(s), a tree of %lld node(s) over it", (long long)short_from_,
drafter_name_.c_str(), (long long)drafter_short_,
(long long)std::min<int64_t>(drafter_.depth, drafter_short_ - 1));
else if (drafter_short_)
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
"row(s), %lld token(s)", (long long)short_from_,
drafter_name_.c_str(),
(long long)drafter_short_,
(long long)(drafter_short_ - ((drafter_.block > 0 ? drafter_.block
: drafter_.depth + 1) -
drafter_.depth)));
if (tree_)
RAD_INFO("speculation: '%s' proposes a tree of %d node(s); each verify follows the deepest "
"path the target agrees with, and that path's K and V move into place",
drafter_.name, drafter_.depth);
if (drafter_.kind != RAD_DRAFT_NONE) {
/* A zero proposal handle means the sampler's token buffer: the head's logits go through
* the ordinary sampler chain. */
@@ -1610,6 +1724,7 @@ int Engine::plan() {
* memory, and the real pool does not exist yet. */
KVManager probe;
host_arenas += arena_host_bytes(r->program);
probe.set_drafter_window_snapshot(drafter_window_snap(r->program));
if (declare_ring_windows(probe, r->program) == RAD_OK &&
probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
ck_slot += probe.checkpoint_bytes();
@@ -1702,9 +1817,9 @@ int Engine::plan() {
RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes,
ngram_device, ngram_host, ck_store + host_arenas));
/* --draft-expert-placement host: the drafter's experts are pinned in the host pool before
* the strategy runs, so they are not part of the elastic plane the card must hold and the
* pool must have room for them on top of the trunk's spill. Growing the pool here, before
* the split, is what lets a drafter fit beside a trunk that already fills the card. */
* the strategy runs, so they leave the elastic plane the card must hold and the pool must
* have room for them on top of the trunk's spill. The pool grows here, before the split,
* so a drafter fits beside a trunk that already fills the card. */
if (cfg_.draft_expert_placement == "host") {
const int64_t MiB = (int64_t)1 << 20;
int64_t draft_max = 0;
@@ -1715,10 +1830,9 @@ int Engine::plan() {
return RAD_E_INVAL;
}
if (draft_max > 0) {
/* The pool must hold the drafter on top of the trunk's own spill, so it grows by
* the drafter's bytes and the floor is recomputed against that larger room with
* the drafter taken out of the plane the card places. */
const int64_t add = (align_up(draft_max, MiB) + MiB - 1) / MiB;
/* The pool grows by the drafter's bytes, and each rank's floor is recomputed
* against that room with the drafter out of the plane the card places. */
const int64_t add = align_up(draft_max, MiB) / MiB;
cfg_.host_pool_mib += add;
for (size_t i = 0; i < facts.size(); ++i) {
int64_t room = cfg_.host_pool_mib * MiB;
@@ -1797,6 +1911,7 @@ int Engine::plan() {
* its carve). */
for (size_t i = 0; i < ranks_.size(); ++i) {
probes[i] = std::make_unique<KVManager>();
probes[i]->set_drafter_window_snapshot(drafter_window_snap(ranks_[i]->program));
if (declare_ring_windows(*probes[i], ranks_[i]->program) != RAD_OK ||
probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
@@ -1882,14 +1997,22 @@ int Engine::plan() {
in.profile = file_->profile();
in.n_profile = (int64_t)file_->header().prof_count;
}
/* --expert-profile replaces the container's activation profile, which is prefill-heavy:
* decode-hot experts differ, and the pin below keeps them resident. Loaded once, before
* any rank plans, so every rank ranks the same way. */
/* --expert-profile replaces the container's activation profile, which is prefill-heavy
* while decode-hot experts differ (--expert-pin-top keeps them resident). Loaded once, at
* the first rank's plan, so every rank ranks the same way. */
if (!cfg_.expert_profile.empty()) {
if (expert_profile_.empty() && ri == 0) {
int32_t trunk = -1;
const int pr = xs_profile_load(cfg_.expert_profile, &expert_profile_, &trunk);
if (pr < 0) return pr;
/* A profile from another model would rank its layers onto this one's. */
if (trunk >= 0 && trunk != (int32_t)meta_.n_layers) {
RAD_ERR("--expert-profile: %s counts %d trunk layers and this model has %d: "
"it was recorded on another model", cfg_.expert_profile.c_str(),
(int)trunk, (int)meta_.n_layers);
expert_profile_.clear();
return RAD_E_INVAL;
}
}
if (!expert_profile_.empty()) {
in.profile = expert_profile_.data();
@@ -3195,7 +3318,9 @@ int Engine::configure_kv() {
auto& r = ranks_[i];
LogRank lr(r->index);
RAD_TRY(declare_ring_windows(r->kv, r->program));
r->kv.set_drafter_window_snapshot(drafter_window_snap(r->program));
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
if (i == 0) drafter_snap_ = r->kv.drafter_window_snapshot();
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
/* A rank plan() re-sized for the common token count must page at least that count (same
* plan, same bytes); anything less is a broken invariant. */
@@ -3266,7 +3391,8 @@ int Engine::configure_kv() {
shard_off[i] = slot;
slot += ranks_[i]->kv.checkpoint_bytes();
}
/* A slot holds linear state, a trunk's window (KVGroupPlan::win_snap), or both. */
/* A slot holds linear state, a trunk's window (KVGroupPlan::win_snap), or both; a block
* drafter's window rides beside a trunk's window where the engine snapshots it. */
bool linear = false;
for (const KVGroupPlan& p : ranks_[0]->kv.plans()) linear = linear || p.stateful();
const char* what = !ranks_[0]->kv.has_window_snapshot() ? "linear-state"
+88 -7
View File
@@ -175,6 +175,14 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
: rk.ctx.buf_ptr(rk.tok_buf));
a.src_pitch = (drafter_.proposal && drafter_.proposal_pitch > 0)
? drafter_.proposal_pitch : 1;
/* A tree drafter's parents, at the proposal's pitch (rad_drafter_tree). */
if (tree_ && mode == ADV_BTAKE) {
a.par = static_cast<const int32_t*>(rk.ctx.buf_ptr(tree_parents_));
if (!a.par) {
RAD_ERR("drafter '%s': rank %zu has no parents buffer", drafter_.name, i);
return RAD_E_STATE;
}
}
} else {
a.src = static_cast<const int32_t*>(rk.ctx.buf_ptr(rk.tok_buf));
}
@@ -188,6 +196,49 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
return RAD_OK;
}
/* ADV_COMPACT on every rank, against the scheduler's latest build (the tree step just accepted):
* the accepted paths' K and V into place in every paged group. Each rank's pools are its own. */
int Engine::tree_compact(int rows) {
for (size_t i = 0; i < ranks_.size(); ++i) {
Rank& rk = *ranks_[i];
AdvanceArgs a = sched_.advance_args((int)i);
if (rows >= 0 && rows < a.n_seq) a.n_seq = rows;
a.mode = 0;
a.st = rk.step_slots;
const Program& p = rk.program;
for (size_t g = 1; g < p.kv_groups.size() && (int)g < a.n_groups; ++g) {
const int kind = p.kv_groups[g].decl.kind;
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) continue;
const KVPoolBinding* b = rk.ctx.kv_binding((uint32_t)g);
if (!b || !b->base || b->rank != 4) continue; /* a zero group on this rank */
const int bits = rad_dtype_bits(b->dtype);
const int64_t row = bits > 0 ? b->shape[3] * bits / 8 : 0;
int32_t layers = 0;
for (int32_t s : b->layer_slot) layers += s >= 0;
if (row <= 0 || row % 16 || (bits != 8 && bits != 16 && bits != 32) ||
(b->bytes && (int64_t)layers * b->layer_stride > b->bytes)) {
RAD_ERR("speculation: KV group %zu's cache (%s, %lld-byte rows) is not one a tree's "
"acceptance can move", g, rad_dtype_name(b->dtype), (long long)row);
return RAD_E_UNSUPPORTED;
}
if (a.n_pool >= kAdvMaxPools) {
RAD_ERR("speculation: more than %d paged KV groups for a tree's acceptance",
(int)kAdvMaxPools);
return RAD_E_UNSUPPORTED;
}
AdvPool& q = a.pool[a.n_pool++];
q.base = static_cast<char*>(b->base);
q.layer_stride = b->layer_stride;
q.n_layers = layers;
q.n_head = (int32_t)b->shape[1];
q.row_bytes = (int32_t)row;
q.grp = (int32_t)g;
}
RAD_TRY(step_compact(a, rk.ctx.stream()));
}
return RAD_OK;
}
/* Issue the step's draft passes behind it, without waiting. After the trunk's ranks join: the
* acceptance on every rank, the sampled-id readback (before a round can overwrite them), the
* history pass and every round, then the final proposal into the slots and their readback.
@@ -496,9 +547,13 @@ void Engine::block_shape(int* block, int* steps) {
* fewer proposals as rows. The load is the step just run's, which the next step, the one these
* proposals are for, mostly repeats (Scheduler::short_block_on). */
if (drafter_short_ <= 0) return;
short_on_ = Scheduler::short_block_on(short_on_, sched_.decoded_seqs(), cfg_.draft_short_from);
short_on_ = Scheduler::short_block_on(short_on_, sched_.decoded_seqs(), short_from_);
if (short_on_) {
*steps -= *block - (int)drafter_short_;
/* A tree (rad_drafter_tree) grows a tree of its own over the shorter pass, at most its
* draft positions of nodes (DFlash2 attends across its block, so the short pass is not the
* full pass's prefix); the verify takes that many. */
if (tree_) *steps = std::min(*steps, (int)drafter_short_ - 1);
else *steps -= *block - (int)drafter_short_;
*block = (int)drafter_short_;
}
}
@@ -508,6 +563,9 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
if (!block_drafting()) return RAD_OK;
RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
/* A tree's accepted path into place in the trunk's cache, against the same build (the step
* just accepted), before any later pass reads it. */
if (tree_) RAD_TRY(tree_compact(-1));
/* The sampled ids before either pass, as the serial driver reads them. */
RAD_TRY(collect_issue(so, /*fence=*/true));
@@ -518,15 +576,25 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
block_shape(&block, &steps);
block_steps_ = steps;
block_row_.resize((size_t)cfg_.max_seqs);
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
/* The head reads the block's draft rows. A tree (rad_drafter_tree; DFlash2's convention, the
* anchor predicts nothing) reads all block - 1 of them whatever its node count. */
const int head = tree_ ? block - 1 : steps;
const int n = sched_.block_begin(block, head, (int)drafter_.window, drafter_.mask_token,
block_row_.data(), (int)block_row_.size(), /*on_card=*/true);
/* --draft-coupling: the draws before the query pass reads them (stage_couple_draws). */
if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(block_row_.data(), n));
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
* drafter will need, and skipping would leave a permanent hole in its cache. */
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
* drafter will need, and skipping would leave a permanent hole in its cache. A tree verify's
* context rows store only the accepted path, at its committed positions (ADV_CTXTREE). */
if (const RadBatch* cb = sched_.block_context(step)) {
if (tree_) RAD_TRY(advance_all(ADV_CTXTREE, 0, false));
RAD_TRY(block_pass(cb, "context", step));
}
/* A snapshot carrying the drafter's window is saved now, with the step's context rows stored
* and before the query pass and the step issued ahead (save_checkpoints). */
if (drafter_snap_) RAD_TRY(save_checkpoints());
if (n <= 0) return RAD_OK;
const RadBatch* qb = sched_.block_query(step);
if (!qb) return RAD_OK;
@@ -581,12 +649,25 @@ int Engine::finish_block_drafter(const StepOut& so) {
for (int j = 0; j < steps; ++j)
draft_out_[(size_t)i * (size_t)steps + (size_t)j] = S.tok[1 + j];
}
/* -v: what each block pass proposed, a line a sequence, so two runs can be compared draft by
* draft where acceptance alone cannot tell them apart (a drafter whose context is wrong still
* drafts, and its rejected drafts change no token). */
const bool show = (int)log_level() >= (int)Log::Debug;
for (int i = 0; i < block_rows_; ++i) {
const int32_t* d = &draft_out_[(size_t)i * (size_t)steps];
if (show) {
std::string t;
for (int j = 0; j < steps; ++j) t += fmt(" %d", (int)d[j]);
RAD_DEBUG("drafter '%s': sequence %llu proposes%s", drafter_.name,
(unsigned long long)block_row_[(size_t)i].seq, t.c_str());
}
/* As in finish_serial_drafter: the step issued ahead only carries a request whose answer
* is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. */
* is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. A
* tree's parents come from the same slot, as ADV_BTAKE took them. */
if (!r0.sampler.allows_speculation(block_row_[(size_t)i].seq)) continue;
const uint64_t seq = block_row_[(size_t)i].seq;
const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)steps], steps);
const StepSlot& S = slots_host_[block_row_[(size_t)i].card];
const int rc = sched_.set_draft(seq, d, steps, tree_ ? S.par : nullptr);
if (mtp_couple_)
RAD_TRY(bind_couple(seq, i, steps, rc == RAD_OK, block_row_[(size_t)i].card));
}
+39 -12
View File
@@ -237,8 +237,8 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
RadModelMeta& m = out->m;
/* Nomic BERT states its geometry with n_layer, n_embd, n_head, n_inner, n_positions and
* moe_top_k. They are fallbacks in the same chain, so a config carrying both spellings keeps
* the HuggingFace one and every existing checkpoint reads byte for byte as before. */
* moe_top_k. They are the last fallbacks in each chain, so a config carrying both spellings
* reads the HuggingFace one. */
m.n_layers = gi("num_hidden_layers", gi("n_layer", 0));
m.n_embd = gi("hidden_size", gi("n_embd", 0));
m.n_head = gi("num_attention_heads", gi("n_head", 0));
@@ -274,18 +274,21 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4): the
* quant_method plus its fmt ("fp8_e4m3"), so the checkpoint, not a flag, distinguishes fp8 from
* bf16 releases.
* bf16 releases. transformers' fine-grained FP8 states no fmt (Qwen3.8-Flash-Next-FP8's config)
* and is always E4M3, so a bare "fp8" is "fp8_e4m3", as a release that states it is.
*
* A Gemma 4 E2B/E4B checkpoint states no quantization_config: it is the bf16 release that
* arch/gemma4_bf16 serves as compressed-tensors, which is what rad-convert's
* `--set quantization_config.quant_method=compressed-tensors` said by hand. Its per-layer
* embeddings or shared KV layers name the E form; arch/gemma4 serves only the 26B-A4B/31B shape
* and refuses those two keys, so the bare (gemma4, "") descriptor must not win. */
* A Gemma 4 E2B/E4B checkpoint states no quantization_config: it is a bf16 release that
* arch/gemma4_bf16 serves under "compressed-tensors", so it needs no
* `--set quantization_config.quant_method=compressed-tensors`. Its per-layer embeddings or shared
* KV layers name the E form; arch/gemma4 serves only the 26B-A4B/31B shape and refuses those two
* keys, so the bare (gemma4, "") descriptor must not win. */
std::string quant_descriptor(const MetaOwn& m) {
std::string q;
if (const char* qm = m.get("quantization_config.quant_method")) {
q = qm;
if (const char* fm = m.get("quantization_config.fmt")) { q += "_"; q += fm; }
const char* fm = m.get("quantization_config.fmt");
if (!fm && q == "fp8") fm = "e4m3";
if (fm) { q += "_"; q += fm; }
return q;
}
if (m.arch == "gemma4") {
@@ -2401,6 +2404,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
* RAD_MAP_COPY alternatives, first present wins (a tied lm_head is output.weight when
* shipped, else the embedding). */
const bool alternatives = maps.front()->mode == RAD_MAP_COPY && srcs.size() > 1;
/* Pieces whose scale is one `X.weight_scale` their shards share (below). */
bool shard_scaled = false;
for (const Src1& s1 : srcs) {
const SrcTensor* st = ck.find(s1.name);
/* An FP8 weight's scale plane: `X.weight_scale_inv` (block-scaled releases) or
@@ -2410,6 +2415,17 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
const SrcTensor* sc = st ? ck.find(std::string(s1.name) + "_scale_inv") : nullptr;
if (!sc && st && (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2))
sc = ck.find(std::string(s1.name) + "_scale");
/* A table split into shards, `X.shard_<i>.weight`, under one scale for all of them,
* `X.weight_scale` (Qwen3.8-Flash-Next-FP8's n-gram table). */
if (!sc && st && (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2)) {
const std::string n = s1.name;
const size_t at = n.rfind(".shard_");
const size_t end = n.size() >= 7 ? n.size() - 7 : 0;
if (at != std::string::npos && end > at + 7 && n.compare(end, 7, ".weight") == 0 &&
std::all_of(n.begin() + (long)at + 7, n.begin() + (long)end,
[](char c) { return c >= '0' && c <= '9'; }))
if ((sc = ck.find(n.substr(0, at) + ".weight_scale"))) shard_scaled = true;
}
/* A weight shipped in an imported form is read through that form's views. */
{
const SrcTensor *ic = nullptr, *is = nullptr;
@@ -2501,8 +2517,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
out->why = std::string("'") + p0.name + "' is a GGUF " +
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
/* Q8_0, Q4_K and Q6_K become their planes when every piece is of that type and they join
* along rows, so each row of the weight is one source row of blocks; the loader still
* refuses them, since the blocks interleave what the planes hold apart. */
* along rows, so each row of the weight is one source row of blocks. rad-convert imports
* them; the loader refuses them, since the blocks interleave what the planes hold apart. */
bool one_type = true;
for (const SrcTensor* pk : out->pieces) one_type = one_type && pk->ggml == p0.ggml;
RadEncoding enc;
@@ -2693,7 +2709,18 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
bad = true;
out->why = "its FP8 pieces are joined along a column, across their scale planes";
}
if (!bad) {
/* Shards under the one scale they share are one tensor with one scale, byte for byte:
* `fp8_e4m3*<s>[*x*]`. */
bool one_scale = !bad && shard_scaled && n_one == (int)out->pieces.size();
for (size_t k = 1; one_scale && k < out->scales.size(); ++k)
one_scale = out->scales[k] == out->scales[0];
if (one_scale) {
out->trivial = out->why.empty();
rad_enc_clear(&out->enc);
rad_enc_copy_str(out->enc.scheme, "affine");
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
rad_enc_add_plane(&out->enc, "scale", sdt, 0, 0);
} else if (!bad) {
out->trivial = out->why.empty() && n_one == 0;
/* A per-tensor scale is written once a row (ckpt_plane_rows). */
if (n_one) {
+2 -2
View File
@@ -63,13 +63,13 @@ inline void put_nibbles(uint8_t* row, const uint8_t* q, int n) {
row[k] = (uint8_t)((q[2 * k] & 15) | ((q[2 * k + 1] & 15) << 4));
}
/* Q4_K: value v is a nibble of qs[32*(v/64) + v%32], the low one for the first 32 of each 64. The
* 6-bit scale and min of sub-block j are get_scale_min_k4's. */
/* Q4_K: value v is a nibble of qs[32*(v/64) + v%32], the low one for the first 32 of each 64. */
inline uint32_t k_low4(const uint8_t* qs, int v) {
const uint8_t q = qs[32 * (v / 64) + v % 32];
return (uint32_t)((v % 64) < 32 ? q & 15 : q >> 4);
}
/* Q4_K: the 6-bit scale and min of sub-block j, as llama.cpp's get_scale_min_k4 unpacks them. */
inline void k4_scale_min(int j, const uint8_t* q, uint32_t* d, uint32_t* m) {
if (j < 4) {
*d = q[j] & 63u;
+15 -10
View File
@@ -14,6 +14,20 @@
namespace rad {
int table_copy_check(const uint8_t* src, int64_t n, const uint8_t* buf, std::string* why) {
if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
const int64_t probe = std::min<int64_t>(n, 4096);
bool same = std::memcmp(buf, src, (size_t)probe) == 0 &&
std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0;
for (int64_t o = 0; same && o + 4096 <= n; o += std::max<int64_t>(n / 64, 4096))
same = std::memcmp(buf + o, src + o, 4096) == 0;
if (!same) {
*why = "the copy does not match the container's mapping";
return RAD_E_IO;
}
return RAD_OK;
}
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
uint8_t* buf, std::string* why) {
if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
@@ -45,16 +59,7 @@ int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t
*why = fmt("reading the container failed (%s)", rad_strerror(err.load()));
return RAD_E_IO;
}
const int64_t probe = std::min<int64_t>(n, 4096);
bool same = std::memcmp(buf, src, (size_t)probe) == 0 &&
std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0;
for (int64_t o = 0; same && o + 4096 <= n; o += std::max<int64_t>(n / 64, 4096))
same = std::memcmp(buf + o, src + o, 4096) == 0;
if (!same) {
*why = "the copy does not match the container's mapping";
return RAD_E_IO;
}
return RAD_OK;
return table_copy_check(src, n, buf, why);
}
int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
+5
View File
@@ -32,6 +32,11 @@ int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
uint8_t* dst, std::string* why);
/* The check table_copy_fill ends with, on its own: samples of [buf, buf + n) against [src, src + n)
* (the first and last 4 KiB and 64 spread between). RAD_OK, or RAD_E_IO with `why`. For a copy
* another process filled. */
int table_copy_check(const uint8_t* src, int64_t n, const uint8_t* buf, std::string* why);
/* Unlock and unmap; a no-op for a copy never made. */
void table_copy_free(TableCopy* c);
+261
View File
@@ -0,0 +1,261 @@
/* table_share.cpp -- see table_share.h. */
#include "table_share.h"
#include "../rad_internal.h"
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/vfs.h>
#include <unistd.h>
#include <cerrno>
#include <climits>
#include <cstdlib>
#include <cstring>
namespace rad {
namespace {
constexpr char kMagic[8] = { 'R', 'A', 'D', 'N', 'G', 'R', 'M', '1' };
constexpr uint32_t kVersion = 1;
constexpr int64_t kHuge = (int64_t)2 << 20;
/* A leaving holder tries for LOCK_EX for about a second (table_share_close). */
constexpr int kLeaveTries = 10;
constexpr unsigned kLeaveWaitUs = 100 * 1000;
/* All integers host-endian: the file lives in a tmpfs, so it never leaves the machine. */
struct Header {
char magic[8];
uint32_t version;
uint32_t ready;
uint64_t bytes;
uint64_t filler_pid; /* for whoever reads the file by hand; nothing depends on it */
char id[24]; /* the 16 hex digits and a NUL */
};
static_assert(sizeof(Header) <= 4096, "the header must fit the first page");
enum class Seen { Fresh, Partial, Ready, Foreign };
std::string errno_text() { return std::strerror(errno); }
/* What the open data file holds. A fresh file and a half-filled one have a zero header; a header
* that is not this protocol's or not for this table is Foreign. */
Seen classify(int fd, const std::string& id, int64_t n, std::string* why) {
struct stat st{};
if (::fstat(fd, &st) != 0) {
*why = fmt("fstat: %s", errno_text().c_str());
return Seen::Foreign;
}
if (st.st_size == 0) return Seen::Fresh;
Header h{};
const ssize_t got = ::pread(fd, &h, sizeof h, 0);
if (got != (ssize_t)sizeof h) {
*why = fmt("its header is %lld bytes short", (long long)(sizeof h - (got < 0 ? 0 : got)));
return Seen::Foreign;
}
Header zero{};
if (std::memcmp(&h, &zero, sizeof h) == 0) return Seen::Partial;
if (std::memcmp(h.magic, kMagic, sizeof kMagic) != 0 || h.version != kVersion) {
*why = "it is not a table file of this version";
return Seen::Foreign;
}
if (h.bytes != (uint64_t)n || std::strncmp(h.id, id.c_str(), sizeof h.id) != 0) {
*why = fmt("it holds %s of table '%.16s', not %s of '%s'", humanb((int64_t)h.bytes).c_str(),
h.id, humanb(n).c_str(), id.c_str());
return Seen::Foreign;
}
if (!h.ready) return Seen::Partial;
if (st.st_size != table_share_file_bytes(n)) {
*why = fmt("it is marked ready but is %lld bytes long, not %lld", (long long)st.st_size,
(long long)table_share_file_bytes(n));
return Seen::Foreign;
}
return Seen::Ready;
}
std::string file_path(const std::string& dir, const std::string& id) {
const bool slash = !dir.empty() && dir.back() == '/';
return dir + (slash ? "" : "/") + "ngram-" + id + ".tab";
}
void fail(TableShare* s) {
if (s->lock_fd >= 0) ::close(s->lock_fd);
if (s->fd >= 0) ::close(s->fd);
*s = TableShare{};
}
} /* namespace */
int64_t table_share_file_bytes(int64_t n) {
return kTableShareHeader + ((n + kHuge - 1) & ~(kHuge - 1));
}
std::string table_share_id(const std::string& container_path, int64_t foff, int64_t n) {
char real[PATH_MAX];
const std::string path = ::realpath(container_path.c_str(), real) ? std::string(real)
: container_path;
struct stat st{};
if (::stat(path.c_str(), &st) != 0) return std::string();
uint64_t h = 1469598103934665603ull;
auto feed = [&](const void* p, size_t len) {
const unsigned char* b = static_cast<const unsigned char*>(p);
for (size_t i = 0; i < len; ++i) h = (h ^ b[i]) * 1099511628211ull;
};
const int64_t parts[] = { (int64_t)st.st_size, (int64_t)st.st_mtim.tv_sec,
(int64_t)st.st_mtim.tv_nsec, foff, n };
feed(path.data(), path.size());
feed(parts, sizeof parts);
return fmt("%016llx", (unsigned long long)h);
}
int table_share_open(const std::string& dir, const std::string& id, int64_t n, TableShare* out,
std::string* why) {
if (!out || !why || dir.empty() || id.empty() || n <= 0) return RAD_E_INVAL;
*out = TableShare{};
out->path = file_path(dir, id);
out->lock_path = out->path + ".lock";
/* A holder that left last deletes the file while we open it: its unlink comes with LOCK_EX, so
* once we hold LOCK_SH the link count says whether the file is still the one in the directory. */
for (;;) {
out->fd = ::open(out->path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
if (out->fd < 0) {
*why = fmt("opening %s: %s", out->path.c_str(), errno_text().c_str());
*out = TableShare{};
return RAD_E_IO;
}
if (::flock(out->fd, LOCK_SH) != 0) {
*why = fmt("locking %s: %s", out->path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
struct stat st{};
if (::fstat(out->fd, &st) != 0) {
*why = fmt("fstat %s: %s", out->path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
if (st.st_nlink > 0) {
struct statfs fs{};
if (::fstatfs(out->fd, &fs) == 0 && (long)fs.f_type != 0x01021994L &&
(long)fs.f_type != 0x858458f6L)
RAD_WARN("n-gram table share: %s is not on a tmpfs or ramfs, so the table is "
"written to its disk and held in the page cache", dir.c_str());
break;
}
::close(out->fd);
}
std::string seen_why;
Seen seen = classify(out->fd, id, n, &seen_why);
if (seen == Seen::Foreign) {
*why = fmt("%s exists, and %s", out->path.c_str(), seen_why.c_str());
fail(out);
return RAD_E_INVAL;
}
if (seen == Seen::Ready) {
out->ready = true;
return RAD_OK;
}
out->lock_fd = ::open(out->lock_path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
if (out->lock_fd < 0) {
*why = fmt("opening %s: %s", out->lock_path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
if (::flock(out->lock_fd, LOCK_EX) != 0) {
*why = fmt("locking %s: %s", out->lock_path.c_str(), errno_text().c_str());
fail(out);
return RAD_E_IO;
}
/* The holder we waited for may have finished. */
seen = classify(out->fd, id, n, &seen_why);
if (seen == Seen::Foreign) {
*why = fmt("%s exists, and %s", out->path.c_str(), seen_why.c_str());
fail(out);
return RAD_E_INVAL;
}
if (seen == Seen::Ready) {
::close(out->lock_fd);
out->lock_fd = -1;
out->ready = true;
return RAD_OK;
}
if (::ftruncate(out->fd, table_share_file_bytes(n)) != 0) {
*why = fmt("sizing %s to %s: %s", out->path.c_str(),
humanb(table_share_file_bytes(n)).c_str(), errno_text().c_str());
fail(out);
return RAD_E_NOMEM;
}
out->filler = true;
return RAD_OK;
}
int table_share_mark_ready(TableShare* s, int64_t n, const std::string& id, std::string* why) {
if (!s || !why || s->fd < 0 || !s->filler || id.size() >= sizeof(Header::id))
return RAD_E_INVAL;
Header h{};
std::memcpy(h.magic, kMagic, sizeof kMagic);
h.version = kVersion;
h.ready = 1;
h.bytes = (uint64_t)n;
h.filler_pid = (uint64_t)::getpid();
std::memcpy(h.id, id.c_str(), id.size());
if (::pwrite(s->fd, &h, sizeof h, 0) != (ssize_t)sizeof h) {
*why = fmt("writing the header of %s: %s", s->path.c_str(), errno_text().c_str());
return RAD_E_IO;
}
if (s->lock_fd >= 0) {
::close(s->lock_fd);
s->lock_fd = -1;
}
s->ready = true;
return RAD_OK;
}
void table_share_close(TableShare* s) {
if (!s) return;
if (s->lock_fd >= 0) ::close(s->lock_fd);
if (s->fd >= 0) {
/* Engines stopped together (a compose recreate) leave together: one that tries while the
* other still holds LOCK_SH, unpinning the table, is not the last, and the other may be
* killed at the stop timeout before its own try, which leaves the table in the tmpfs. So
* this holder lets go of LOCK_SH and tries for a while. It holds no lock from here on
* until LOCK_EX is granted; a conversion would not keep it either, since a refused one
* has already dropped LOCK_SH (flock(2): not atomic). LOCK_EX may then come on a file
* another holder already deleted, with a new engine's file at its name, so only the file
* the name still points to is deleted. The lock file goes first: nobody gets past
* LOCK_SH on this file to use it, while a file made anew at the name the moment this one
* is gone could already have a filler on it. */
(void)::flock(s->fd, LOCK_UN);
for (int i = 0; i < kLeaveTries; ++i) {
if (::flock(s->fd, LOCK_EX | LOCK_NB) == 0) {
struct stat mine{}, named{};
if (::fstat(s->fd, &mine) == 0 && ::stat(s->path.c_str(), &named) == 0 &&
mine.st_dev == named.st_dev && mine.st_ino == named.st_ino) {
::unlink(s->lock_path.c_str());
::unlink(s->path.c_str());
}
break;
}
if (errno != EWOULDBLOCK && errno != EINTR) break;
if (i + 1 < kLeaveTries) ::usleep(kLeaveWaitUs);
}
::close(s->fd);
}
*s = TableShare{};
}
bool table_share_is_ready(const std::string& dir, const std::string& id, int64_t n) {
if (dir.empty() || id.empty() || n <= 0) return false;
const int fd = ::open(file_path(dir, id).c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) return false;
std::string why;
const bool ready = classify(fd, id, n, &why) == Seen::Ready;
::close(fd);
return ready;
}
} /* namespace rad */
+69
View File
@@ -0,0 +1,69 @@
/* table_share.h -- an n-gram table as a file in a tmpfs that engines on separate cards share
* (--ngram-placement ram=DIR). Each engine maps the file MAP_SHARED and pins it for its own cards,
* so the host holds one copy however many engines read it. This is the file protocol only; the
* mapping and the pinning are the device layer's (rad_dev_map_file).
*
* The file is `DIR/ngram-<id>.tab`: a header in its first 2 MiB, the table from kTableShareHeader
* on, so the table keeps the 2 MiB alignment the pinned ranges want. The id names the container
* and the table's place in it, so a file never serves another model.
*
* Every holder keeps LOCK_SH on the data file for its life, which counts the readers. The first
* engine to find the file unready takes the fill lock (LOCK_EX on `<file>.lock`, a file of its
* own so that a later engine arriving while the table is read never waits behind the readers),
* fills the table and marks it ready; an engine arriving meanwhile waits on the fill lock and then
* finds it ready. The holder that gets LOCK_EX on the data file when it leaves is the last, and
* deletes the file and the lock file; one that leaves while another still holds LOCK_SH waits a
* moment for it, since engines stopped together leave together. A holder that died took its locks
* with it: a half-filled file is filled again, a ready one is reused after the same sample check
* as a fresh copy. */
#pragma once
#include <cstdint>
#include <string>
namespace rad {
/* The table's offset in the file. */
constexpr int64_t kTableShareHeader = (int64_t)2 << 20;
/* The file's length for an n-byte table: the header, then the table rounded up to 2 MiB. */
int64_t table_share_file_bytes(int64_t n);
/* The smallest table worth a shared file. A file costs the header and the table's rounding to
* 2 MiB, up to 4 MiB beside the table, and a tmpfs entry that outlives a crash; a weight of a few
* bytes the gather reads beside the table (its one-element scale) would cost more that way than as
* a private copy in every engine. From 16 headers on the file's overhead is under an eighth of the
* table; a smaller one takes the private pinned copy. */
constexpr int64_t kTableShareMin = 16 * kTableShareHeader;
struct TableShare {
int fd = -1; /* the data file, LOCK_SH held until table_share_close */
int lock_fd = -1; /* the fill lock, held while `filler` and not yet marked ready */
std::string path, lock_path;
bool ready = false; /* the table in the file is complete */
bool filler = false; /* this holder fills it, then calls table_share_mark_ready */
};
/* FNV-1a 64 over the container's real path, size and mtime (to the nanosecond), the table's file
* offset and its length, as 16 hex digits; empty if the container cannot be stat'ed. */
std::string table_share_id(const std::string& container_path, int64_t foff, int64_t n);
/* Open or create DIR/ngram-<id>.tab for an n-byte table and take part in the protocol: afterwards
* `out->ready` (map it and check samples) or `out->filler` (map it, fill [kTableShareHeader, +n),
* mark it ready). RAD_E_INVAL if a file of that name does not hold a table of this id and length
* (another program's, or another version's; never overwritten, since a live engine may map it),
* RAD_E_IO if the directory or file cannot be used. `why` carries the reason. */
int table_share_open(const std::string& dir, const std::string& id, int64_t n, TableShare* out,
std::string* why);
/* The filler's table is complete: write the header, release the fill lock. */
int table_share_mark_ready(TableShare* s, int64_t n, const std::string& id, std::string* why);
/* Leave. The last holder deletes the file and its lock file; while another still holds the file,
* this waits up to about a second for it to leave first. Safe on a TableShare never opened. */
void table_share_close(TableShare* s);
/* Whether DIR/ngram-<id>.tab is a complete table of n bytes now, read from its header without
* taking part: for the placement decision, which must know before anything is pinned. */
bool table_share_is_ready(const std::string& dir, const std::string& id, int64_t n);
} /* namespace rad */
+2 -2
View File
@@ -186,8 +186,8 @@ void KVStreamStore::release(MemAllocator& host_alloc) {
KVStreamStats KVStreamStore::stats(const std::vector<KVGroupPlan>& plans) const {
KVStreamStats st;
st.misses = misses_;
st.bytes_in = bytes_in_;
st.misses = (int64_t)misses_.load(std::memory_order_relaxed);
st.bytes_in = (int64_t)bytes_in_.load(std::memory_order_relaxed);
for (const auto& p : plans)
if (p.streamed()) st.resident_blocks += p.pool_blocks();
return st;
+8 -5
View File
@@ -9,6 +9,7 @@
#pragma once
#include "mem/pools.h"
#include <atomic>
#include <cstdint>
#include <vector>
@@ -85,17 +86,19 @@ public:
KVStreamStats stats(const std::vector<KVGroupPlan>& plans) const;
/* Charged by the engine, which reads the resolve's counters where a step has drained. */
/* Charged by the engine, which reads the resolve's counters where a step has drained. Atomic
* (relaxed): stats() is also read by the dashboard's snapshot on an HTTP thread while a step
* may be in flight; only the values carry meaning, not their order. */
void note_traffic(int64_t misses, int64_t bytes) {
if (misses > 0) misses_ += (uint64_t)misses;
if (bytes > 0) bytes_in_ += (uint64_t)bytes;
if (misses > 0) misses_.fetch_add((uint64_t)misses, std::memory_order_relaxed);
if (bytes > 0) bytes_in_.fetch_add((uint64_t)bytes, std::memory_order_relaxed);
}
private:
std::vector<int64_t> resident_tokens_; /* by group handle: its pool's depth in tokens */
std::vector<Map> maps_; /* set_map(), by group handle */
uint64_t misses_ = 0; /* note_traffic() */
uint64_t bytes_in_ = 0;
std::atomic<uint64_t> misses_{0}; /* note_traffic() */
std::atomic<uint64_t> bytes_in_{0};
};
} /* namespace rad */
+7 -3
View File
@@ -272,11 +272,15 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
for (const auto& p : plans_) if (p.stateful()) checkpoint_bytes_ += p.bytes_per_state;
/* Then the window behind a checkpoint, after the linear state (see has_window_snapshot). A
* trunk's window rides in the slot whether or not linear state is beside it: a hit resumes at
* a snapshot either way, and without the window there it could not resume at all. */
* a snapshot either way, and without the window there it could not resume at all. A drafter's
* window rides there only on a model without linear state (set_drafter_window_snapshot). */
bool has_state = false;
for (const auto& p : plans_) has_state = has_state || p.stateful();
for (size_t i = 1; i < plans_.size(); ++i) {
KVGroupPlan& p = plans_[i];
p.win_snap = p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
!p.runtime_win && !groups[i].drafter;
p.drafter = groups[i].drafter;
p.win_snap = p.kind == RAD_KV_WINDOW && p.window_blocks > 0 && !p.runtime_win &&
(!groups[i].drafter || (snap_drafter_ && !has_state));
if (p.win_snap && !p.zero && p.n_layers > 0)
window_ck_bytes_ += p.window_blocks * p.bytes_per_block;
}
+17 -2
View File
@@ -122,9 +122,12 @@ struct KVGroupPlan {
? (runtime_tokens + block_size - 1) / block_size : 0;
}
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot), after any
* linear state. Set for a trunk group; a drafter's window is recomputed by draft refill, so
* its snapshot would not be read. */
* linear state. Set for a trunk group, and for a drafter's group on a model without linear
* state where the engine saves the snapshot behind the drafter's context pass
* (set_drafter_window_snapshot). Elsewhere a drafter's window is recomputed by draft refill,
* so its snapshot would not be read. */
bool win_snap = false;
bool drafter = false; /* a drafter's group (KVGroupInfo::drafter) */
int64_t n_blocks = 0; /* paged groups: blocks the group addresses (its context) */
/* Paged groups: blocks the device pool backs, fewer than `n_blocks` when the group streams
@@ -230,6 +233,17 @@ public:
* is sized and capped from these two alone (core/mem/vram_budget.cpp); VRAM above the ceiling
* would never be addressed. carve() spends the pool it is given. */
int plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg);
/* Whether a drafter's WINDOW group rides in the window snapshot too (KVGroupPlan::win_snap).
* The engine sets it, before plan_groups, where the drafter stores its context right behind
* the trunk step and the snapshot is saved after that (a block drafter on the card's driver);
* a snapshot taken before would hold the window without the step's rows. Kept across
* forget(). */
void set_drafter_window_snapshot(bool on) { snap_drafter_ = on; }
/* Some drafter group rides in the window snapshot (after plan_groups). */
bool drafter_window_snapshot() const {
for (const auto& p : plans_) if (p.win_snap && p.drafter) return true;
return false;
}
int64_t ceiling(int64_t ctx) const;
/* The context-independent part of every ceiling: recurrent and conv state for max_seqs
* sequences, plus alignment padding. Set by plan_groups(). */
@@ -668,6 +682,7 @@ private:
int64_t max_seqs_ = 0;
int64_t max_ctx_ = 0;
int64_t max_tok_ = 0; /* --max-num-batched-tokens; the buffer floor is one of these */
bool snap_drafter_ = false; /* set_drafter_window_snapshot */
/* plan_groups() computes these; carve() spends against them and ceiling() reports on them. */
int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, padding */
int64_t ckpts_ = 0; /* --checkpoint-slots, kept for the warning on a model with none */
+17 -4
View File
@@ -77,7 +77,13 @@ void GeometricBackoff::select(const std::vector<int64_t>& pos, std::vector<int64
void KeepTipOnly::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep) const {
keep->clear();
if (!pos.empty()) keep->push_back(pos.back());
if (pos.empty()) return;
const int64_t tip = pos.back();
if (floor_ > 0) {
const auto it = std::upper_bound(pos.begin(), pos.end(), tip - floor_);
if (it != pos.begin()) keep->push_back(*(it - 1));
}
keep->push_back(tip);
}
void KeepAll::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep) const {
@@ -168,6 +174,7 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
ck_by_prefix_.clear(); ck_by_session_.clear();
/* set_policy() may override this afterwards. */
policy_ = make_checkpoint_policy(cfg.checkpoint_policy, checkpoint_interval);
policy_->set_floor(drafter_floor_);
report_.clear();
if (!kv) return RAD_E_INVAL;
@@ -177,9 +184,9 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
}
/* Every paged group but a windowed one is cached. An entry covers the lcm of their block
* sizes, and holds that over a group's block size of the group's blocks: a hit then ends on
* a block of every group, which adopt() needs. The chunk quantum is a multiple of every paged
* group's block (core/sched/geometry.cpp), so the lcm divides every checkpoint position. */
* sizes and holds lcm / B blocks of a group with B-token blocks, so a hit ends on a block of
* every group, which adopt() needs. The chunk quantum is a multiple of every paged group's
* block (core/sched/geometry.cpp), so the lcm divides every checkpoint position. */
for (const auto& p : kv->plans()) {
if (p.stateful()) has_linear_ = true;
if (p.paged() && p.kind != RAD_KV_WINDOW && p.block_size > 0)
@@ -267,6 +274,12 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
void PrefixCache::set_policy(std::unique_ptr<CheckpointPolicy> p) {
if (p) policy_ = std::move(p);
if (policy_) policy_->set_floor(drafter_floor_);
}
void PrefixCache::set_drafter_floor(int64_t tokens) {
drafter_floor_ = tokens > 0 ? tokens : 0;
if (policy_) policy_->set_floor(drafter_floor_);
}
std::string PrefixCache::report() const { return report_; }
+16 -3
View File
@@ -127,6 +127,10 @@ public:
* of the store. The base applies select() to its own output one checkpoint at a time, which
* is cheap only for a policy that keeps few. */
virtual int64_t held(int64_t ctx, int64_t interval) const;
/* Tokens before the tip a hit must be able to end at: a drafter whose KV the cache does not
* hold recomputes that much of the prompt's tail (Scheduler::init, HitCap). 0: none. A policy
* that would otherwise keep nothing that deep keeps one snapshot there. */
virtual void set_floor(int64_t) {}
};
/* Keep the tip and, at every scale S = interval x 2^k, the shallowest checkpoint in the tip's
@@ -146,12 +150,18 @@ private:
int64_t interval_;
};
/* The two ends of the trade, for comparison. */
/* The two ends of the trade, for comparison. tip-only under a drafter floor also keeps the deepest
* snapshot at or below tip - floor: without it a refill-capped hit finds nothing to end on, keeps
* the whole hit, and the request decodes with no drafts (8 sessions of 22k tokens: 5 ran
* unspeculated, decode 424-521 t/s against 738-754 under geometric backoff). */
class KeepTipOnly final : public CheckpointPolicy {
public:
const char* name() const override { return "tip-only"; }
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
int64_t held(int64_t, int64_t) const override { return 1; }
int64_t held(int64_t, int64_t) const override { return floor_ > 0 ? 2 : 1; }
void set_floor(int64_t tokens) override { floor_ = tokens > 0 ? tokens : 0; }
private:
int64_t floor_ = 0;
};
class KeepAll final : public CheckpointPolicy {
public:
@@ -255,6 +265,8 @@ public:
/* Overrides the policy configure() installed from Config::checkpoint_policy (custom policies,
* tests). Call after configure(), which would undo it. */
void set_policy(std::unique_ptr<CheckpointPolicy> p);
/* The drafter's refill window (CheckpointPolicy::set_floor), held across set_policy. */
void set_drafter_floor(int64_t tokens);
const CheckpointPolicy& policy() const { return *policy_; }
/* ---------------- full attention ---------------- */
@@ -445,7 +457,7 @@ private:
struct Entry {
/* blocks_per_entry(i) per cached group, in groups_ order: entry_groups_[k] owns blocks[k] */
std::vector<int32_t> blocks;
std::vector<int32_t> tokens; /* the block's token ids, compared on hit */
std::vector<int32_t> tokens; /* the entry's token ids, compared on hit */
/* On the LRU exactly while the cache holds the blocks; `lru` is valid only then. An
* off-device entry owns no block, so eviction must not reach it. */
bool in_lru = false;
@@ -551,6 +563,7 @@ private:
}
mutable uint64_t clock_ = 0;
std::unique_ptr<CheckpointPolicy> policy_;
int64_t drafter_floor_ = 0;
mutable Stats stats_;
std::string report_;
};
+3 -3
View File
@@ -36,9 +36,9 @@ struct FrameRGBA {
/* Whether this build has a decoder. */
bool decoder_available();
/* "libavformat <version>" when the decoder is built in, "absent (built without libav*)"
* when it is not: one string for the startup report and /diagnostics, so a media 500 can be
* read off the report instead of bisected. */
/* "libavformat <version>" when the decoder is built in, "absent (built without libav*)" when it
* is not: one string for the startup report and /diagnostics, so a build that refuses every media
* part shows it there. */
std::string decoder_version();
/* The first frame of an image (or of anything with a video stream). Refuses a source over
+2 -2
View File
@@ -210,8 +210,8 @@ private:
std::vector<Tier> tier_;
std::vector<uint8_t> busy_;
std::vector<uint8_t> movable_;
/* --expert-pin-top: a decode-hot resident the planner marked unmovable is never a demotion
* candidate, even where a later pass made its unit movable again. */
/* --expert-pin-top: a decode-hot resident the planner pinned is never a demotion candidate,
* even where a later pass made its unit movable again. */
std::vector<uint8_t> pinned_;
std::vector<int32_t> layer_of_;
/* Bit 0: promoted before. Bit 1: demoted before. Feeds the readmit counters. */
+9 -14
View File
@@ -1053,10 +1053,9 @@ int Planner::pin_towers(const Config& cfg, Plan* p) const {
/* --draft-expert-placement host: a draft head's routed experts (layers at meta.n_layers and above,
* and only when the program declares a drafter) go to the pinned host pool before any strategy
* runs. The card reads them in place at the DeviceZeroCopy site, the same way it reads a pooled
* expert, so a drafter's experts fit beside a trunk that already fills the card instead of the
* strategy having to make room for them on it. They are not movable: heat never promotes a draft
* expert onto the card and into the trunk's slab. */
* runs. The card reads them in place at the DeviceZeroCopy site, as it reads a pooled expert, so
* a drafter's experts fit beside a trunk that already fills the card. They are not movable: heat
* never promotes a draft expert onto the card and into the trunk's slab. */
int Planner::pin_draft_experts(const Program& prog, const Config& cfg, Plan* p) const {
if (cfg.draft_expert_placement != "host") return RAD_OK;
if (prog.drafter.kind == RAD_DRAFT_NONE || prog.meta.n_layers == 0) {
@@ -1107,12 +1106,12 @@ int Planner::pin_draft_experts(const Program& prog, const Config& cfg, Plan* p)
/* --expert-pin-top F: the hottest fraction of the routed experts, ranked by the profile the planner
* was given (the container's, or --expert-profile's decode counts), stay resident. They are marked
* unmovable, so the heat engine never demotes them and the decode-hot set stops paying the host
* unmovable, so the heat engine never demotes them and the decode-hot set never pays the host
* pool's PCIe read. The cut keeps the hottest ceil(F * n), and a tie at the cut stays movable: the
* threshold is the share just below the hot set, and only a share strictly above it pins. Runs
* after the strategy, which has already put the hot set in VRAM; a hot unit the strategy had to
* leave on the host is left there and counted, since pinning it would need VRAM the card does not
* have. */
* leave on the host stays there and is counted, since pinning it would need VRAM the card does
* not have. */
void Planner::pin_hot(const Config& cfg, Plan* p) const {
if (cfg.expert_pin_top <= 0.0f) return;
std::vector<float> shares;
@@ -1120,9 +1119,7 @@ void Planner::pin_hot(const Config& cfg, Plan* p) const {
if (mu.expert >= 0 && mu.tier != Tier::Mapped) shares.push_back(mu.profile_share);
if (shares.empty()) return;
std::sort(shares.begin(), shares.end());
/* The cut sits after the coldest (1 - F) of the plane, so the hottest F are pinned. A tie at
* the cut stays movable: the threshold is the share just below the hot set, and only a share
* strictly above it pins. */
/* The cut sits after the coldest (1 - F) of the plane, so the hottest F are pinned. */
const double keep = (double)cfg.expert_pin_top * (double)shares.size();
const size_t hot = keep <= 0.0 ? 0 : std::min(shares.size(), (size_t)std::ceil(keep));
const float threshold = hot == 0 ? shares.back() + 1.0f
@@ -1174,7 +1171,8 @@ int Planner::plan(Plan* out) {
build_classes(out);
/* After build_classes: a unit's slot_bytes is its class's stride, and the pins below charge
* the host pool that. Before it the charge would be zero and the pool would not hold them. */
* the host pool that. Before it the charge would be zero and the pool would not hold them.
* Not RAD_TRY: a refusal still leaves `out` filled in far enough to print. */
int hrc = pin_embedding(prog, cfg, out);
const int trc = pin_towers(cfg, out);
if (hrc >= 0) hrc = trc;
@@ -1212,9 +1210,6 @@ int Planner::plan(Plan* out) {
}
}
/* Not RAD_TRY: a refusal still leaves `out` filled in far enough to print. The pins ran above,
* once slot_bytes was known. */
int rc = assign(out);
enforce_op_site_agreement(prog, out);
schedule_prefetch(out);
+2 -3
View File
@@ -230,9 +230,8 @@ public:
int64_t tower_host_bytes = 0;
int64_t draft_host_bytes = 0;
int64_t forced_host_used = 0;
/* --expert-profile and --expert-pin-top: the profile's units the planner pinned resident and the
* share threshold it derived from the fraction. Reported so the window can see what the decode
* set costs the card. */
/* --expert-profile and --expert-pin-top: the units the planner pinned resident, the profiled
* units, and the share threshold it derived from the fraction (Plan::report). */
int64_t pinned_units = 0;
int64_t profile_units = 0;
float pin_threshold = 0.0f;
+27 -13
View File
@@ -400,6 +400,10 @@ public:
int32_t drafter_pos_offset = 0;
/* A block drafter's shorter block (rad_drafter_short_block), 0 when it serves only its own. */
int64_t drafter_short_block = 0;
/* A block drafter that proposes a tree (rad_drafter_tree): `drafter_parents` holds each
* proposal's parent node, at the proposal's pitch. False and 0 for a chain drafter. */
bool drafter_tree = false;
rad_buf drafter_parents = 0;
/* The declared media encoder (rad_declare_encoder). `modalities == 0` when none: every
* text-only program, and every deployment with RadBuildCtx::max_enc_patches 0.
@@ -708,6 +712,9 @@ struct Request {
* (SchedReq owns this Request, so it outlives it) and is written alongside n_draft. Null when
* n_draft is 0. */
const int32_t* draft = nullptr;
/* A tree drafter's parents for `draft` (StepEntry::draft_parent): draft[j]'s parent node,
* 0 the bonus token. Null for a chain. The sampler reads each row's ancestors from it. */
const int32_t* draft_parent = nullptr;
int32_t n_accepted = 0; /* from the previous verify */
/* Whether this request may be speculated on. Written by the engine after every step, read by
@@ -858,6 +865,9 @@ struct Config {
TablePlacement embedding_placement = TablePlacement::Ram;
bool embedding_placement_given = false;
TablePlacement ngram_placement = TablePlacement::Auto;
/* --ngram-placement ram=DIR: the pinned n-gram copy is the file DIR/ngram-<id>.tab (a tmpfs),
* mapped shared, so engines on separate cards hold one table. Empty: a private copy. */
std::string ngram_share_dir;
TablePlacement embedding_resolved = TablePlacement::Vram;
TablePlacement ngram_resolved = TablePlacement::Disk;
/* Set by the resolver: pinned host MiB per rank for the token embedding when it resolves to
@@ -898,13 +908,15 @@ struct Config {
* store is opened (checkpoint_slots_auto in core/mem/prefix.h). */
int64_t checkpoint_slots = -1;
bool prefix_cache = true;
/* --prefix-resume exact|nearest. Exact (the default) resumes a prefix hit only on the grid an
* idle server's cold prefill chunks the same prompt on (ChunkGeometry::grid), and takes a
* prompt's tail snapshot where its last chunk starts: the hit recomputes the cold run's own
* chunks, so its output is the cold run's bit for bit, where a kernel rounds a row differently
* at another chunk length. Nearest resumes at the deepest snapshot or block, a prompt's tail
* snapshot at its last quantum boundary: up to a chunk less re-prefilled a turn, and a hit that
* can differ from a cold run in the last bits (a near-tie in greedy text). */
/* --prefix-resume exact|nearest.
* - exact (the default): a prefix hit resumes only on the grid an idle server's cold prefill
* chunks the same prompt on (ChunkGeometry::grid), and a prompt's tail snapshot is taken
* where its last chunk starts. The hit recomputes the cold run's own chunks, so its output
* is the cold run's bit for bit even where a kernel rounds a row differently at another
* chunk length.
* - nearest: a hit resumes at the deepest snapshot or block, and a prompt's tail snapshot is
* at its last quantum boundary. Up to a chunk less is re-prefilled a turn, and a hit can
* differ from a cold run in the last bits (a near-tie in greedy text). */
bool prefix_exact = true;
/* geometric-backoff | tip-only | keep-all. §19.1 records the default as unmeasured;
* core/mem/prefix.h ships the two extremes so they can be compared. */
@@ -944,8 +956,10 @@ struct Config {
int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */
DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */
/* A block drafter's short block (rad_drafter_short_block) from this many decoding sequences in
* the step just run; 0 never. Ignored without a drafter that declares one. */
int64_t draft_short_from = 0; /* --draft-short-from */
* the step just run; 0 never. -1, auto: never for a chain, and from two for a tree
* (rad_drafter_tree), whose nodes are verify rows every drafting sequence pays for. Ignored
* without a drafter that declares a short block. */
int64_t draft_short_from = -1; /* --draft-short-from */
/* --draft-coupling off|on: a linear serial drafter (or DFlash2's block walk) samples its
* proposals and the sampler applies the maximal coupling at the verify
@@ -1087,10 +1101,10 @@ struct Config {
* share, keeping them resident: heat never demotes them. 0 is off. */
float expert_pin_top = 0.0f;
bool expert_pin_top_given = false;
/* --draft-expert-placement auto|host: a draft head's (MTP/DSpark) routed experts are pinned in
* the host pool before any strategy runs, streamed in place like a pooled expert. `auto` (the
* default) leaves them to the strategy. `host` is what lets a drafter's experts fit beside a
* trunk that already fills the card. */
/* --draft-expert-placement auto|host. `host` pins a draft head's (MTP/DSpark) routed experts
* in the host pool before any strategy runs, read in place like a pooled expert, so they fit
* beside a trunk that already fills the card. `auto` (the default) leaves them to the
* strategy. */
std::string draft_expert_placement = "auto";
bool draft_expert_placement_given = false;
/* --live: the live view (spec §16). Off by default like everything else in that section. */
+30
View File
@@ -38,6 +38,36 @@ namespace rad {
int accept_greedy(const int32_t* draft, int n_draft, const int32_t* target,
int32_t* out, int32_t* n_accepted);
/* The same rule over a tree (rad_drafter_tree). Node 0 is the verify's first row (the bonus token
* it starts from); node j, 1 <= j <= n_draft, is draft[j - 1], verified at row j, and its parent
* is node parent[j - 1] (< j), or node j - 1 when `parent` is null (a chain). `target[r]` is the
* target's token after node r's row.
*
* From node 0, take the lowest-numbered child whose token is the target's at the current node,
* while there is one. Writes the walk's nodes to path[0..n_accepted) and the emitted tokens to
* out[0..n_accepted]: out[t] is the target's token at path[t - 1] (node 0 for t = 0), which equals
* the accepted draft there, and out[n_accepted] is the bonus. The card's acceptance
* (sched/advance_impl.h, ADV_ACCEPT) walks the same way. */
inline int accept_tree(const int32_t* draft, const int32_t* parent, int n_draft,
const int32_t* target, int32_t* out, int32_t* path, int32_t* n_accepted) {
if (!draft || !target || !out || !path || !n_accepted || n_draft < 0) return RAD_E_INVAL;
int32_t cur = 0, acc = 0;
for (;;) {
int32_t nxt = -1;
for (int32_t j = cur + 1; j <= n_draft; ++j) {
int32_t p = parent ? parent[j - 1] : j - 1;
if (p < 0 || p >= j) p = j - 1; /* as the builder and ADV_TRUNK read it */
if (p == cur && draft[j - 1] == target[cur]) { nxt = j; break; }
}
if (nxt < 0) break;
path[acc++] = nxt;
cur = nxt;
}
for (int32_t t = 0; t <= acc; ++t) out[t] = target[t == 0 ? 0 : path[t - 1]];
*n_accepted = acc;
return RAD_OK;
}
/* Where a verify step's emission ends: at the first end-of-generation token among `out`'s
* n_accepted + 1 tokens (accept_greedy's output), which is emitted, or after all of them. Returns
* the number of accepted drafts to commit, at most `n_accepted`. A drafter that predicts the stop
+49 -11
View File
@@ -3,6 +3,7 @@
*/
#include "sampler.h"
#include "gbnf.h"
#include "../sched/draft.h" /* RAD_SCHED_MAX_SPEC */
#include <algorithm>
#include <chrono>
@@ -618,8 +619,8 @@ int Sampler::accept_token(uint64_t req_id, int32_t token) {
}
/* A constraining grammar does not rule out speculation: build_step masks draft position i
* against the state after drafts 0..i-1 and then rewinds. Only a backend that cannot rewind is
* refused. */
* against the state after drafts 0..i-1 (on a tree, after row i's ancestors) and then rewinds.
* Only a backend that cannot rewind is refused. */
bool Sampler::allows_speculation(uint64_t req_id) const {
auto it = seqs_.find(req_id);
if (it == seqs_.end() || !it->second.grammar) return true;
@@ -729,7 +730,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
* `dead` is not a failure: a draft the grammar forbids will be rejected at verification
* and every later position discarded, so masking stops for the rest of the window. */
GrammarBackend* gr = st && st->grammar ? st->grammar.get() : nullptr;
const bool walk = gr && n_pos > 1;
/* A tree (rad_drafter_tree) is walked per row instead: row k's prefix is its ancestors,
* not drafts 0..k-1, so each row pushes the committed state, advances over its own path,
* is masked, and rolls back. A refused ancestor kills that row only: verification never
* reaches it, while a sibling's path may still be admissible. */
const int32_t* tpar = r->draft_parent;
const bool walk = gr && n_pos > 1 && !tpar;
const bool walk_tree = gr && n_pos > 1 && tpar;
if (walk) gr->push_state();
bool dead = false;
@@ -746,10 +753,38 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
st->think.push(sp.reasoning, r->output[st->think_seen]);
think = st->think;
}
const ReasoningCount think0 = think;
for (int k = 0; k < n_pos; ++k) {
/* Row k's drafts before it: 0..k-1 on a chain, its ancestors (root first) on a tree. */
int32_t anc[RAD_SCHED_MAX_SPEC];
int32_t dk = 0;
if (tpar) {
int32_t chain[RAD_SCHED_MAX_SPEC];
for (int32_t j = k; j > 0 && dk < RAD_SCHED_MAX_SPEC;) {
chain[dk++] = j;
int32_t pj = tpar[j - 1];
j = (pj < 0 || pj >= j) ? j - 1 : pj;
}
for (int32_t t = 0; t < dk; ++t) anc[t] = r->draft[chain[dk - 1 - t] - 1];
} else {
for (; dk < k; ++dk) anc[dk] = r->draft[dk];
}
if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true;
if (budget && k > 0) think.push(sp.reasoning, r->draft[k - 1]);
bool row_dead = false; /* a tree row whose path the grammar refuses */
bool pushed = false;
if (walk_tree && dk > 0) {
RAD_TRY(gr->push_state());
pushed = true;
for (int32_t t = 0; t < dk && !row_dead; ++t)
row_dead = gr->accept_token(anc[t]) < 0;
}
if (budget && tpar) {
think = think0;
for (int32_t t = 0; t < dk; ++t) think.push(sp.reasoning, anc[t]);
} else if (budget && k > 0) {
think.push(sp.reasoning, r->draft[k - 1]);
}
const int64_t row = n_seq_++;
/* Row k verifies draft k against the state its round left. A row with no bound state
* (the bonus row, a greedy row, an uncoupled step) gets a zeroed one, and the verify
@@ -781,8 +816,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
p.seed = sp.seed;
/* Output position: draft position k is token n_out + k, so its draw is the same with
* or without speculation. */
p.pos = (uint64_t)(n_out + k);
* or without speculation. On a tree it is the row's depth: siblings share a prefix
* length, hence a coordinate, hence the target's draw there. */
p.pos = (uint64_t)(n_out + dk);
p.temp = sp.temp;
p.top_p = sp.top_p;
@@ -857,14 +893,14 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
* this span, so the reference's update order holds at a verify: position k sees the
* drafts before it, as the processor would after emitting them. */
if (pen || dry || ngram) {
const int64_t len = n_total + k;
const int64_t len = n_total + dk;
const int64_t take = std::min<int64_t>(len, cfg_.max_hist);
int32_t* h = hist_stage_ + row * cfg_.max_hist;
for (int64_t i = 0; i < take; ++i) {
const int64_t src = len - take + i;
h[i] = src < n_prompt ? r->prompt[(size_t)src]
: src < n_total ? r->output[(size_t)(src - n_prompt)]
: r->draft[src - n_total];
: anc[src - n_total];
}
p.hist_len = (int32_t)take;
if (pen) p.flags |= RAD_SP_PENALTY;
@@ -874,7 +910,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
if (ngram && take >= sp.ngram_ban_n) any_ngram_ = true;
}
if (gr && !dead && gr->constrains()) {
if (gr && !dead && !row_dead && gr->constrains()) {
uint32_t* dst = mask_stage_ + row * mask_words_;
int s;
/* Mask cost, reported at Debug per 256 masks (mean and worst). It runs on the
@@ -914,8 +950,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
}
if (s < 0 && k > 0) {
/* At a draft position this only means a draft is wrong; verification
* rejects at or before here, so stop masking the rest of the window. */
dead = true;
* rejects at or before here, so stop masking the rest of the window. On a
* tree only this row's path is wrong; its siblings are masked on. */
if (!tpar) dead = true;
} else if (s < 0) {
/* A dead grammar fails its request, not the step: an error status would stop
* the step loop for every client. The row stays unmasked and the engine
@@ -939,6 +976,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
}
}
}
if (pushed) RAD_TRY(gr->rollback()); /* back to the committed state for the next row */
if (budget && think.inside() && think.body >= sp.thinking_budget)
force_close(p, row, sp.reasoning.close);
+2 -1
View File
@@ -167,7 +167,8 @@ public:
/* False only for a constraining grammar whose backend cannot snapshot its state. Masking a
* draft window walks the grammar over the drafts and rewinds, which needs
* push_state/rollback; without it the request decodes one token at a time. */
* push_state/rollback (a tree's rows each walk their own ancestors); without it the request
* decodes one token at a time. */
bool allows_speculation(uint64_t req_id) const;
/* Whether allows_speculation's answer can no longer change. It changes only when a grammar
* whose backend cannot rewind starts to constrain (on a commit). */
+20
View File
@@ -23,4 +23,24 @@ int step_advance(const AdvanceArgs& a, RadStream s) {
#endif
}
int step_compact(const AdvanceArgs& a, RadStream s) {
if (a.n_seq <= 0 || a.n_pool <= 0) return RAD_OK;
if (device_is_host()) {
RAD_TRY(rad_stream_sync(s));
const int items = adv_compact_items(a);
for (int i = 0; i < a.n_seq; ++i)
for (int w = 0; w < items; ++w) {
int p = 0, l = 0, h = 0;
if (adv_compact_item(a, w, &p, &l, &h)) adv_compact(a, i, p, l, h, 0, 1);
}
return RAD_OK;
}
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
return rad_step_compact_launch(&a, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE;
#else
(void)s;
return RAD_E_UNSUPPORTED;
#endif
}
} /* namespace rad */
+53 -1
View File
@@ -35,7 +35,20 @@ struct StepSlot {
int32_t acc; /* drafts the last verify step accepted */
/* The next verify step's input tokens: the bonus token, then the draft head's proposals. */
int32_t tok[1 + RAD_SCHED_MAX_SPEC];
int32_t pad[3];
/* A tree drafter's proposal (rad_drafter_tree): par[j] is the parent of node j + 1, a node
* index in [0, j], where node 0 is the bonus token tok[0] and node j + 1 is tok[j + 1].
* `ntree` is the number of nodes it describes, written by ADV_BTAKE from the drafter's
* parents plane; 0 means tok[1..] is a chain. */
int32_t par[RAD_SCHED_MAX_SPEC];
int32_t ntree;
/* The last verify's accepted root path: path[t] is the node committed (t + 1)-th, so the
* committed tokens are tok[path[0]], tok[path[1]], ... and the step's anchor sits at
* ctx - 1 - npath. ADV_COMPACT moves those nodes' K and V from where the verify stored them
* (its row index) to where they belong (their depth), and ADV_CTXTREE positions the
* drafter's context rows by it. 0 after a chain verify, which needs neither. */
int32_t npath;
int32_t path[RAD_SCHED_MAX_SPEC];
int32_t pad[2];
};
enum AdvMode : int32_t {
@@ -47,6 +60,26 @@ enum AdvMode : int32_t {
/* A block drafter (RAD_DRAFT_BLOCK) on the card: */
ADV_BLOCK = 6, /* before the query pass: the anchor at the committed end, then the masks */
ADV_BTAKE = 7, /* after it: its `round` proposals into the state, behind the bonus token */
/* A tree drafter (rad_drafter_tree), whose verify rows are a tree rather than a chain: */
ADV_CTXTREE = 8, /* before the context pass: the accepted path's rows at their depth, the
* rejected rows stored nowhere */
};
/* The most paged KV groups one ADV_COMPACT moves (the trunk's sliding and global groups and a
* drafter's own, with room). */
enum { kAdvMaxPools = 6 };
/* One paged group's cache on one rank, as ADV_COMPACT addresses it: `n_layers` caches of
* [n_blocks, n_head, block_size, row_bytes] bytes, `layer_stride` apart from `base`
* (core/runtime/kvbind.cpp composes that shape). `grp` indexes the batch's AdvGroup array, whose
* block table maps a position to a block. */
struct AdvPool {
char* base;
int64_t layer_stride;
int32_t n_layers;
int32_t n_head;
int32_t row_bytes;
int32_t grp;
};
/* One KV group, as the builder stages it for this build. Offsets are bytes into the rank's slab,
@@ -112,12 +145,31 @@ struct AdvanceArgs {
* position of those rows, 0 or 1 past the committed position. Zero for every other head. */
int32_t shared_kv = 0;
int32_t rot_shift = 0;
/* A tree drafter (rad_drafter_tree). ADV_BTAKE: the proposal's parents plane, row i's from
* i * src_pitch as the tokens are; null for a chain drafter. */
const int32_t* par = nullptr;
/* ADV_TRUNK: RadBatch::spec_parent [n_tok] in the slab, or -1 when the build stages none.
* A tree row's entry is its parent's row within the sequence's block (-1 for the bonus
* token); every other row's is -2, an ordinary causal row. */
int64_t parent_off = -1;
/* ADV_COMPACT: every paged group's cache on this rank. */
AdvPool pool[kAdvMaxPools] = {};
int32_t n_pool = 0;
};
/* Issue one advance on `s`. The rows are independent, so the card runs them in parallel. */
int step_advance(const AdvanceArgs& a, RadStream s);
/* ADV_COMPACT, after ADV_ACCEPT on a tree verify and before anything reads the trunk's cache: for
* every row whose StepSlot holds an accepted path, move the K and V each path node's verify row
* stored (at the anchor's position + its row index) to its committed position (+ its depth), in
* every pool of `a`, every layer and every head. A separate kernel from the advance because it
* moves bytes across the whole cache rather than patching a row's few integers. */
int step_compact(const AdvanceArgs& a, RadStream s);
} /* namespace rad */
/* The launcher in advance.hip: one kernel onto `stream` through hipLaunchKernel. */
extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream);
/* And ADV_COMPACT's. */
extern "C" int rad_step_compact_launch(const rad::AdvanceArgs* args, void* stream);
+43
View File
@@ -59,8 +59,51 @@ __global__ __launch_bounds__(kThreads) void r4dchain_step_advance(rad::AdvanceAr
}
}
/* ADV_COMPACT: block (x, y) is work item x (a pool, layer and head) of batch row y; its threads
* split the K|V row into 16-byte chunks. Chained like the advance where launches chain, every
* block waiting for the kernels before it and counting itself in after its moves. */
constexpr int kCompactThreads = 64;
__device__ __forceinline__ void step_compact_body(const rad::AdvanceArgs& a) {
int p = 0, l = 0, h = 0;
if (!rad::adv_compact_item(a, (int)blockIdx.x, &p, &l, &h)) return;
rad::adv_compact(a, (int)blockIdx.y, p, l, h, (int)threadIdx.x, kCompactThreads);
}
__global__ __launch_bounds__(kCompactThreads) void rad_step_compact(rad::AdvanceArgs a) {
step_compact_body(a);
}
__global__ __launch_bounds__(kCompactThreads) void r4dchain_step_compact(rad::AdvanceArgs a) {
const ChainRec* r = chain_rec();
if (r) {
if (threadIdx.x == 0)
while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target)
__builtin_amdgcn_s_sleep(1);
__syncthreads();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
}
step_compact_body(a);
if (r) {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
__syncthreads();
if (threadIdx.x == 0)
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
}
}
} // namespace
extern "C" int rad_step_compact_launch(const rad::AdvanceArgs* args, void* stream) {
if (!args || args->n_seq <= 0) return 0;
const int items = rad::adv_compact_items(*args);
if (items <= 0) return 0;
if (!rad_dev_chain_enabled())
hipLaunchKernelGGL(rad_step_compact, dim3((unsigned)items, (unsigned)args->n_seq),
dim3(kCompactThreads), 0, (hipStream_t)stream, *args);
else
hipLaunchKernelGGL(r4dchain_step_compact, dim3((unsigned)items, (unsigned)args->n_seq),
dim3(kCompactThreads), 0, (hipStream_t)stream, *args);
return hipGetLastError() == hipSuccess ? 0 : -1;
}
extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream) {
if (!args || args->n_seq <= 0) return 0;
const unsigned blocks = (unsigned)((args->n_seq + kThreads - 1) / kThreads);
+171 -13
View File
@@ -28,6 +28,20 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
return lo < a.n_eog && a.eog[lo] == t;
}
/* Group `e`'s slot for position `p` of batch row `i`, or -1 past its block table. A runtime
* window's position at or past ring_pos is in its ring (see adv_groups). */
RAD_ADV_FN int32_t adv_slot(const AdvanceArgs& a, const AdvGroup& e, int i, int32_t p) {
const int32_t first = adv_i32(a, e.first_off)[i];
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
int32_t bi = (p - first) / e.block_size;
if (e.ring && e.ring_blocks > 0 && adv_i32(a, e.tlen_off)[i] > 0) {
const int32_t rpos = adv_i32(a, e.rpos_off)[i];
if (p >= rpos) bi = rpos / e.block_size + ((p - rpos) / e.block_size) % e.ring_blocks;
}
return (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
? bt[bi] * e.block_size + p % e.block_size : -1;
}
/* Every group's slots for the row's `n` positions (from the positions just written) and its
* length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes
* tables for the furthest reachable position, so only a row whose output is unused hits this.
@@ -43,16 +57,18 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
* off the table once the ring wraps.
*
* `len`, when given, is the length's count from `base` in place of `n` (ADV_HIST: rows that
* repeat a position must not lengthen the context). */
* repeat a position must not lengthen the context). `at`, when given, is where each row stores its
* K and V instead of its position: a tree verify's rows rotate at their depth but store at their
* row index, since siblings share a depth (ADV_TRUNK), and a context row the tree rejected stores
* nowhere (-1, ADV_CTXTREE). */
RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n,
int32_t len = -1) {
int32_t len = -1, const int32_t* at = nullptr) {
const AdvGroup* G = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off);
const int32_t* pos = adv_i32(a, a.pos_off);
for (int g = 0; g < a.n_groups; ++g) {
const AdvGroup& e = G[g];
const int32_t first = adv_i32(a, e.first_off)[i];
/* Per sequence: each prompt has its own floor and its own table (advance.h). */
const int32_t rpos = e.ring ? adv_i32(a, e.rpos_off)[i] : 0;
const int32_t tlen = e.ring ? adv_i32(a, e.tlen_off)[i] : 0;
const bool ring = e.ring && tlen > 0;
int64_t used = (int64_t)base + (len >= 0 ? len : n) - first;
@@ -62,20 +78,22 @@ RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base,
}
adv_i32(a, e.used_off)[i] = (int32_t)used;
if (!e.paged) continue;
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
int32_t* slot = adv_i32(a, e.slot_off);
for (int32_t j = 0; j < n; ++j) {
const int32_t p = pos[k + j];
int32_t bi = (p - first) / e.block_size;
if (ring && p >= rpos && e.ring_blocks > 0)
bi = rpos / e.block_size +
((p - rpos) / e.block_size) % e.ring_blocks;
slot[k + j] = (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
? bt[bi] * e.block_size + p % e.block_size : -1;
const int32_t p = at ? at[j] : pos[k + j];
slot[k + j] = p >= 0 ? adv_slot(a, e, i, p) : -1;
}
}
}
/* A tree's node depths from its parents: node 0 (the bonus token) at 0, node j + 1 one below
* par[j]. A parent outside [0, j] is a drafter bug; it is read as the previous node, so the row
* still stores and rotates somewhere sane, and the verify rejects whatever it proposed. */
RAD_ADV_FN int32_t adv_parent(const StepSlot& S, int32_t j) {
const int32_t p = S.par[j - 1];
return (p < 0 || p >= j) ? j - 1 : p;
}
/* Writes a row's position and moves its rotary components by the same amount. A row whose
* position does not change keeps the host's components. */
RAD_ADV_FN void adv_pos(const AdvanceArgs& a, int32_t* pos, int32_t row, int32_t p) {
@@ -108,10 +126,39 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
switch (a.mode) {
case ADV_ACCEPT: {
const int32_t* y = a.src + rout;
/* A tree verify, which the trunk's spec_parent row says (its first entry is -1, the root,
* whoever staged it: ADV_TRUNK for a card row, the builder for a host row): accept_tree's
* rule. From the bonus token, follow the first child (lowest node index) whose token is
* the target's pick at its parent's row, as long as one is; then the same
* end-of-generation cut over the tokens that walk emits. */
const int32_t* tp = a.parent_off >= 0 ? adv_i32(a, a.parent_off) + rtok : nullptr;
if (tp && aux > 0 && tp[0] == -1) {
const int32_t* d = tok + rtok; /* node j's token is d[j], 1 <= j <= aux */
const int32_t a0 = rtok - k; /* parents count rows from the sequence's first */
int32_t cur = 0, acc = 0;
for (;;) {
int32_t nxt = -1;
for (int32_t j = cur + 1; j <= aux; ++j)
if (tp[j] - a0 == cur && d[j] == y[cur]) { nxt = j; break; }
if (nxt < 0) break;
S.path[acc++] = nxt;
cur = nxt;
}
for (int32_t t = 0; t <= acc; ++t)
if (adv_is_eog(a, y[t == 0 ? 0 : S.path[t - 1]])) { acc = t; break; }
const int32_t head = ctx[i] + (rtok - k) + acc;
S.acc = acc;
S.head = head;
S.ctx = head + 1;
S.n_acc = acc + 1;
S.tok[0] = y[acc == 0 ? 0 : S.path[acc - 1]];
S.npath = acc;
return;
}
/* accept_greedy's rule, then collect_step's end-of-generation cut: a draft is accepted
* while it equals the target's pick at its position, and the run stops at an
* end-of-generation token, not after it. */
const int32_t* y = a.src + rout;
const int32_t* d = tok + rtok + 1;
int32_t acc = 0;
while (acc < aux && d[acc] == y[acc]) ++acc;
@@ -123,16 +170,64 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
S.ctx = head + 1;
S.n_acc = acc + 1;
S.tok[0] = y[acc];
S.npath = 0;
return;
}
case ADV_TRUNK: {
const int32_t base = S.ctx;
if (a.parent_off >= 0) {
int32_t* par = adv_i32(a, a.parent_off);
/* A row verifying fewer nodes than the drafter proposed (a window cut it) verifies
* their prefix, which is a tree too: every parent precedes its child. */
if (n > 1 && S.ntree >= n - 1) {
/* A tree: node j stores its K and V at base + j (siblings share a depth, so the
* position cannot address them) and rotates at base + its depth, the position the
* token would have if its path were committed. Attention reads spec_parent to see
* only a row's own ancestors inside the block. */
int32_t dep[1 + RAD_SCHED_MAX_SPEC], at[1 + RAD_SCHED_MAX_SPEC];
for (int32_t j = 0; j < n; ++j) {
const int32_t p = j == 0 ? -1 : adv_parent(S, j);
dep[j] = j == 0 ? 0 : dep[p] + 1;
tok[k + j] = S.tok[j];
par[k + j] = p;
adv_pos(a, pos, k + j, base + dep[j]);
at[j] = base + j;
}
ctx[i] = base;
adv_i32(a, a.acc_off)[i] = S.n_acc;
adv_groups(a, i, k, base, n, -1, at);
return;
}
for (int32_t j = 0; j < n; ++j) par[k + j] = -2;
}
for (int32_t j = 0; j < n; ++j) { tok[k + j] = S.tok[j]; adv_pos(a, pos, k + j, base + j); }
ctx[i] = base;
adv_i32(a, a.acc_off)[i] = S.n_acc;
adv_groups(a, i, k, base, n);
return;
}
case ADV_CTXTREE: {
/* The drafter's context pass over a tree verify's rows (one per node, in node order, as
* the trunk tapped them), a card row only where the host marked the step's entry as one.
* Only the accepted path is context: path node t's row writes at the anchor + t + 1,
* rotated there, which is where its token now sits, and every rejected node's row stores
* nowhere. Run after ADV_ACCEPT, which wrote the path, and before ADV_BTAKE. A chain
* verify's path is its first `acc` rows (npath 0). */
const int32_t base = S.head - S.acc;
int32_t at[1 + RAD_SCHED_MAX_SPEC];
at[0] = base;
adv_pos(a, pos, k, base);
for (int32_t j = 1; j < n; ++j) { at[j] = -1; adv_pos(a, pos, k + j, base); }
for (int32_t t = 0; t < S.acc; ++t) {
const int32_t r = t < S.npath ? S.path[t] : t + 1;
if (r < 1 || r >= n) continue;
at[r] = base + t + 1;
adv_pos(a, pos, k + r, base + t + 1);
}
ctx[i] = base;
adv_groups(a, i, k, base, n, -1, at);
return;
}
case ADV_HIST: {
if (a.shared_kv) {
/* A head that reads the trunk's cache and keeps none (rad_drafter_shared_kv). With no
@@ -205,13 +300,76 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
return;
}
case ADV_BTAKE:
/* Row i is the query pass's i-th block, which is the i-th drafting sequence. */
/* Row i is the query pass's i-th block, which is the i-th drafting sequence. A tree
* drafter's parents come with the tokens, at the same pitch. */
for (int32_t j = 0; j < a.round; ++j)
S.tok[1 + j] = a.src[(int64_t)i * a.src_pitch + j];
if (a.par) {
for (int32_t j = 0; j < a.round; ++j) S.par[j] = a.par[(int64_t)i * a.src_pitch + j];
S.ntree = a.round;
} else {
S.ntree = 0;
}
return;
default:
return;
}
}
/* ADV_COMPACT for one (batch row, pool, layer, head): the moves the row's accepted path asks
* for, `c0` and every `cstep`-th 16-byte chunk of each K|V row. Node path[t] stored at
* base + path[t] and belongs at base + t + 1. path[] increases (a parent's index is below its
* child's) and path[t] >= t + 1, so in t order no move overwrites a node a later move still reads:
* a destination base + t + 1 is either the node's own place or a place a node already moved out
* of. Each caller keeps one chunk set across every t, so its reads and writes stay in order. */
RAD_ADV_FN void adv_compact(const AdvanceArgs& a, int i, int p, int l, int h, int c0, int cstep) {
/* Only a row that sampled in this step: ADV_ACCEPT just wrote its slot. Any other row's slot
* may hold a path from an earlier request that used the same slot. */
const int32_t* rows = adv_i32(a, a.row_off);
if (rows[2 * a.row_pitch + i] < 0) return;
const StepSlot& S = a.st[adv_i32(a, a.sid_off)[i]];
const int32_t np = S.npath < S.acc ? S.npath : S.acc;
if (np <= 0) return;
const AdvPool& P = a.pool[p];
if (!P.base || l >= P.n_layers || h >= P.n_head) return;
const AdvGroup& e = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off)[P.grp];
if (!e.paged) return;
const int32_t base = S.head - S.acc;
const int32_t bs = e.block_size;
char* lay = P.base + (int64_t)l * P.layer_stride;
const int32_t chunks = P.row_bytes / 16;
for (int32_t t = 0; t < np; ++t) {
const int32_t src = base + S.path[t], dst = base + t + 1;
if (src == dst) continue;
const int32_t ss = adv_slot(a, e, i, src), ds = adv_slot(a, e, i, dst);
if (ss < 0 || ds < 0) continue;
const uint32_t* from = reinterpret_cast<const uint32_t*>(
lay + (((int64_t)(ss / bs) * P.n_head + h) * bs + ss % bs) * P.row_bytes);
uint32_t* to = reinterpret_cast<uint32_t*>(
lay + (((int64_t)(ds / bs) * P.n_head + h) * bs + ds % bs) * P.row_bytes);
for (int32_t c = c0; c < chunks; c += cstep) {
const uint32_t v0 = from[4 * c], v1 = from[4 * c + 1], v2 = from[4 * c + 2],
v3 = from[4 * c + 3];
to[4 * c] = v0; to[4 * c + 1] = v1; to[4 * c + 2] = v2; to[4 * c + 3] = v3;
}
}
}
/* The (pool, layer, head) of ADV_COMPACT's work item `w`, counting every pool's layers x heads in
* order; false past the last. */
RAD_ADV_FN bool adv_compact_item(const AdvanceArgs& a, int w, int* p, int* l, int* h) {
for (int q = 0; q < a.n_pool; ++q) {
const int n = a.pool[q].n_layers * a.pool[q].n_head;
if (w < n) { *p = q; *l = w / a.pool[q].n_head; *h = w % a.pool[q].n_head; return true; }
w -= n;
}
return false;
}
RAD_ADV_FN int adv_compact_items(const AdvanceArgs& a) {
int n = 0;
for (int q = 0; q < a.n_pool; ++q) n += a.pool[q].n_layers * a.pool[q].n_head;
return n;
}
} /* namespace rad */
+29 -10
View File
@@ -862,14 +862,6 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
(long long)max_seqs_, (long long)max_tok_);
return nullptr;
}
if (plan.spec_is_tree) {
/* spec_parent is in the ABI and allocated, but no drafter emits a tree, so tree parents
* and positions are not written. Filling in the linear-chain answer would verify a tree
* against the wrong causal mask. */
RAD_ERR("tree-layout speculation was requested but is not implemented in this build");
return nullptr;
}
Set& s = set_;
const int64_t n_seq = (int64_t)plan.e.size();
@@ -957,6 +949,29 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
s.h_tok[k + j] = token_at(e, (int64_t)e.ctx_len + j + shift);
s.h_pos[k + j] = e.ctx_len + j;
}
/* A tree verify (RadBatch::spec_parent): every verify block of a tree step is staged as
* a tree, a chain proposal (prompt lookup) as the tree whose node j hangs off j - 1, so
* the card's acceptance and the host's agree on every row. Node j stores its K and V at
* its row's position (the slots below are unchanged) and rotates at the anchor + its
* depth. A parent is named by its row within the sequence's rows (from cu_seqlens), the
* index an attention kernel has. A card row is restaged by ADV_TRUNK from its StepSlot. */
if (plan.spec_is_tree) {
for (int32_t j = 0; j < e.n_tokens; ++j) s.h_parent[k + j] = -2;
if (e.produces_token && !e.is_prefill && e.n_spec > 0 &&
e.n_spec < e.n_tokens && e.n_spec <= RAD_SCHED_MAX_SPEC) {
const int32_t a0 = e.n_tokens - 1 - e.n_spec; /* the anchor's row */
int32_t dep[1 + RAD_SCHED_MAX_SPEC];
dep[0] = 0;
s.h_parent[k + a0] = -1;
for (int32_t j = 1; j <= e.n_spec; ++j) {
int32_t p = e.draft_parent ? e.draft_parent[j - 1] : j - 1;
if (p < 0 || p >= j) p = j - 1;
dep[j] = dep[p] + 1;
s.h_parent[k + a0 + j] = a0 + p;
s.h_pos[k + a0 + j] = e.ctx_len + a0 + dep[j];
}
}
}
/* Every row of a sequence runs with its request's adapter (RadBatch::lora_slot), fixed at
* admission; a placeholder row with no request is a base row. */
if (lora_on_) {
@@ -973,7 +988,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
(e.req && e.req->media && !e.req->media->rope.empty()) ? &e.req->media->rope : nullptr;
for (int32_t j = 0; j < e.n_tokens; ++j) {
int32_t v[3];
const int64_t p = (int64_t)e.ctx_len + j;
/* h_pos, not ctx_len + j: a tree verify's rows rotate at their depth. */
const int64_t p = (int64_t)s.h_pos[k + j];
if (rl) rl->at(p, v);
else v[0] = v[1] = v[2] = (int32_t)p;
s.h_rope[k + j] = v[0];
@@ -1166,7 +1182,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
* without drafts may follow one that had drafts, and the linear kernels need its accepted
* count instead of their absent-operand default of 1. */
B.num_accepted = cfg_.n_spec > 0 ? on_rank(base, b0, s.d_acc) : nullptr;
B.spec_parent = nullptr; /* a linear chain; the tree case is refused above */
/* Staged above on a tree step: each row's parent row, -2 for an ordinary causal one. */
B.spec_parent = plan.spec_is_tree ? on_rank(base, b0, s.d_parent) : nullptr;
B.rope_pos = mm_on_ ? on_rank(base, b0, s.d_rope) : nullptr;
B.rope_mixed = rope_mixed;
B.n_mm_rows = n_mm;
@@ -1205,6 +1222,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
++ring_.live;
last_n_seq_ = n_seq;
last_n_tok_ = n_tok;
last_tree_ = plan.spec_is_tree;
ring_.head = off + used;
out_last_ = out_next_;
out_next_ = (out_next_ + 1) % kOut;
@@ -1236,6 +1254,7 @@ AdvanceArgs BatchBuilder::advance_args(int rank) const {
a.cu_off = off(s.d_cu);
a.q_off = off(s.d_q);
a.row_off = off(s.d_rows);
a.parent_off = last_tree_ ? off(s.d_parent) : -1;
a.row_pitch = (int32_t)max_seqs_;
a.grp_off = off(s.d_grp);
if (mm_on_) {
+5
View File
@@ -41,6 +41,10 @@ struct StepEntry {
int32_t ckpt_restore = -1;
const int32_t* draft = nullptr; /* the drafter's proposal, appended after the committed tail */
int32_t n_draft = 0;
/* A tree drafter's proposal (rad_drafter_tree): draft_parent[j] is the parent of draft[j] as a
* node index (0 the anchor, j + 1 draft[j]). Null for a chain. Read only on a tree step
* (StepPlan::spec_is_tree), where a null one is staged as the chain. */
const int32_t* draft_parent = nullptr;
/* First logits row, written into `out_ids`, that this entry reads, or -1 for the default
* rule. The MTP history pass uses it to gather the 1 + n_spec trunk rows of a verifying
* sequence; the DFlash2 query pass uses it to name the mask rows of its own block. Which
@@ -315,6 +319,7 @@ private:
int64_t pay_words_ = 0; /* payload build_groups wrote, in int32 words */
void forget_tables();
int64_t last_n_seq_ = 0;
bool last_tree_ = false; /* the last build staged spec_parent (advance_args' parent_off) */
int64_t derived_bytes_ = 0;
std::vector<Derived> derived_;
+34 -20
View File
@@ -38,6 +38,30 @@ int64_t prefill_shared_tok(const Config& cfg) {
return std::max(std::min(cfg.max_tok, I), cfg.max_tok - (cfg.prefill_span - 1) * I);
}
/* What a prefix hit restores beside the cached blocks: linear state, or a trunk's sliding window.
* Only the trunk's window makes a model take window snapshots; a block drafter's rides in them
* where they exist (KVManager::set_drafter_window_snapshot) and is recomputed by draft refill
* where they do not. A RAD_KV_RING group has no snapshot at all
* (KVManager::declare_runtime_window): its window is each sequence's own prompt length, which no
* slot could describe, so it is sized for the context plus a ring and is never checkpointed. */
static void restored_state(const Program& prog, bool* linear, bool* window) {
*linear = *window = false;
for (const KVGroupInfo& kg : prog.kv_groups) {
if (kg.decl.kind != RAD_KV_FULL && kg.decl.kind != RAD_KV_WINDOW &&
kg.decl.kind != RAD_KV_RING)
*linear = true;
else if (kg.decl.kind == RAD_KV_WINDOW && kg.block_size > 0 && !kg.layers.empty() &&
!kg.drafter)
*window = true;
}
}
bool window_snapshots(const Program& prog, const Config& cfg) {
bool linear = false, window = false;
restored_state(prog, &linear, &window);
return !linear && window && cfg.prefix_cache && cfg.checkpoint_interval > 0;
}
int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out) {
if (!out) return RAD_E_INVAL;
ChunkGeometry g;
@@ -46,22 +70,12 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
/* lcm across every paged group. libr4d uses 16 for all of them, but a sliding-window group
* served by a different kernel may differ (§7.2). */
bool has_linear = false, has_window = false;
restored_state(prog, &has_linear, &has_window);
for (const KVGroupInfo& kg : prog.kv_groups) {
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
kg.decl.kind == RAD_KV_RING) {
if (kg.block_size > 0) {
g.attn_block = lcm64(g.attn_block, kg.block_size);
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
/* A drafter's window is recomputed by draft refill; only the trunk's needs a
* snapshot for a prefix hit to resume. A RAD_KV_RING group has no snapshot at all
* (KVManager::declare_runtime_window): its window is each sequence's own prompt
* length, which no slot could describe, so it is sized for the context plus a ring
* and is never checkpointed. */
if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter)
has_window = true;
}
} else {
has_linear = true;
if ((kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
kg.decl.kind == RAD_KV_RING) && kg.block_size > 0) {
g.attn_block = lcm64(g.attn_block, kg.block_size);
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
}
}
@@ -152,11 +166,11 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
}
/* The resume grid (--prefix-resume exact): where an idle server's prefill chunks start. A
* prefill alone in its step takes the budget, rounded down to the quantum, and stops at every
* interval boundary it reaches where chunks split at the interval (linear state, or periodic
* window snapshots); a span carries h intervals from the second one on. An interval past the
* budget must then be a multiple of the budget's chunk, or the chunk after a checkpoint would
* start off the grid every cold run cuts: rounded up, as the quantum rounds it, since a longer
* prefill alone in its step takes the budget, rounded down to the quantum. Where chunks split
* at the interval (linear state, or periodic window snapshots) it stops at every interval
* boundary it reaches, and a span carries h intervals from the second one on. An interval past
* the budget must be a multiple of the budget's chunk, or the chunk after a checkpoint would
* start off the cold run's grid; it is rounded up, as the quantum rounds it, since a longer
* interval costs only retention. */
const int64_t I0 = g.checkpoint_interval;
const bool splits = I0 > 0 && (!g.window_ckpt || g.window_periodic);
+13 -8
View File
@@ -61,14 +61,14 @@ struct ChunkGeometry {
bool window_periodic = false;
/* --prefix-resume exact (Config::prefix_exact): a prefix hit resumes only where a cold prefill
* of the same prompt starts a chunk, so the tokens a hit recomputes are cut into the chunks a
* cold run cuts them into. A kernel may round a row differently at another chunk length (a
* split-K count chosen from M, a small-M path); computed in the same chunks, the hit's output
* is the cold run's, bit for bit, on an idle server. The grid is where an idle server's prefill
* chunks start: 0, then grid_origin + k * grid. `grid` is the checkpoint interval where chunks
* split at it and it fits the budget, times the span from the second interval on (origin = the
* interval), and otherwise --max-num-batched-tokens rounded down to the quantum (the interval
* is then rounded up to a multiple of it). Zero when not exact. */
* of the same prompt starts a chunk, so the tokens it recomputes are cut into the cold run's
* chunks. A kernel may round a row differently at another chunk length (a split-K count chosen
* from M, a small-M path); in the same chunks, on an idle server, the hit's output is the cold
* run's bit for bit. The grid is where an idle server's prefill chunks start: 0, then
* grid_origin + k * grid. Where chunks split at the interval and it fits the budget, `grid` is
* the interval times the span the budget holds, from grid_origin = the interval when that span
* is over 1. Otherwise `grid` is --max-num-batched-tokens rounded down to the quantum, and the
* interval is rounded up to a multiple of it. Zero when not exact. */
bool exact = false;
int64_t grid = 0;
int64_t grid_origin = 0;
@@ -91,6 +91,11 @@ struct ChunkGeometry {
* (RadBuildCtx::max_mixed_tok) and the scheduler plans by it, so the two agree. */
int64_t prefill_shared_tok(const Config& cfg);
/* ChunkGeometry::window_ckpt from the program and the configuration alone, without resolving or
* reporting the geometry: a trunk's sliding window, no linear state, a prefix cache and an
* interval. Bring-up asks it before the geometry is resolved (Engine::drafter_window_snap). */
bool window_snapshots(const Program& prog, const Config& cfg);
/* Resolve the geometry from the declared program and the operator's budgets.
*
* Returns RAD_E_INVAL when cfg.max_tok is too small (the required number is in
+6 -1
View File
@@ -172,10 +172,14 @@ struct IPrefixCache {
/* Longest cached prefix, plus the checkpoint covering the linear state for a prefix of it.
* `blocks_out` receives block ids per cached group, in cached_groups() order, for
* IKVManager::adopt: n_attn_tokens over the group's own block size of them. `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
* IKVManager::adopt: n_attn_tokens over the group's own block size of them. `cap`, when not
* null, ends the hit early (HitCap, core/mem/prefix.h). */
virtual CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* blocks_out,
const HitCap* cap) const = 0;
virtual const std::vector<int32_t>& cached_groups() const = 0;
/* The drafter's refill window (Scheduler::init): retention keeps a snapshot that deep below a
* session's tip, so a refill-capped hit has one to end on (PrefixCache::set_drafter_floor). */
virtual void set_drafter_floor(int64_t) {}
/* Publish what this sequence computed so a later request sharing the prefix can adopt it.
* `blocks[i]` is the block table of cached_groups()[i]; `n_tokens` is how many tokens are
@@ -472,6 +476,7 @@ struct PCBinding final : IPrefixCache {
}
void release(const Request& r) override { m->release(r.id); }
const std::vector<int32_t>& cached_groups() const override { return m->cached_groups(); }
void set_drafter_floor(int64_t tokens) override { m->set_drafter_floor(tokens); }
/* Indexes prompt ++ output: the next turn sends the reply back in its prompt, so indexing the
* prompt alone would stop hitting at the first assistant token. */
+101 -43
View File
@@ -146,7 +146,10 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
RAD_INFO("draft refill: a prefix hit ends %lld tokens before the prompt's end, so the "
"drafter's window is recomputed", (long long)draft_refill_);
}
if (pc) pc->set_drafter_floor(draft_refill_);
/* A tree drafter (rad_drafter_tree): every trunk step verifies its proposals as trees. */
tree_ = cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter_tree;
serial_shared_ = cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_SERIAL &&
prog.drafter_shared_kv;
serial_rot_shift_ = serial_shared_ ? prog.drafter_pos_offset : 0;
@@ -363,12 +366,18 @@ bool Scheduler::committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const {
return false;
}
int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n, const int32_t* parents) {
std::lock_guard<std::mutex> lk(mu_);
auto it = by_id_.find(id);
if (it == by_id_.end()) return RAD_E_NOTFOUND;
SchedReq& s = *reqs_[(size_t)it->second];
if (n < 0) return RAD_E_INVAL;
/* A tree's parents travel with its tokens; a prefix of a tree is a tree (every parent
* precedes its child), so the caps below keep them valid. */
s.draft_tree = parents != nullptr;
if (parents)
for (int i = 0; i < n && i < RAD_SCHED_MAX_SPEC; ++i) s.draft_par[i] = parents[i];
s.req->draft_parent = parents ? s.draft_par : nullptr;
/* The step issued ahead already verifies these: it was planned with the drafter's count and
* the card has the tokens. The host copy is what its commit emits accepted tokens from, so it
@@ -479,9 +488,9 @@ void Scheduler::trim_prefix_cache() {
if (!pc_ || !cfg_.prefix_cache) return;
const std::vector<int32_t>& cg = pc_->cached_groups();
if (cg.empty()) return;
/* An entry covers the lcm of the cached groups' blocks and holds that over a group's block of
* its blocks (PrefixCache::blocks_per_entry); the trim asks for entries, as many as the group
* furthest short needs. */
/* An entry covers the lcm of the cached groups' block sizes and holds lcm / B blocks of a
* group with B-token blocks (PrefixCache::blocks_per_entry). The trim asks for entries, as
* many as the group furthest short needs. */
int64_t entry = 0;
for (int32_t g : cg) {
const int64_t bs = kvgeom_.g[(size_t)g].block_size;
@@ -874,10 +883,10 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
if (geo_.checkpoints() && geo_.exact) {
/* --prefix-resume exact: checkpoints only where an idle cold prefill of this prompt starts
* a chunk (ChunkGeometry::grid), so a hit that resumes at one recomputes the cold run's
* own chunks. Splits as below at the interval and a span's end; the tail snapshot is at
* the start of the prompt's last chunk (tail_checkpoint), a boundary an idle chunk already
* ends on, so it costs a copy and no step. A step that shares the budget (another
* request, decode rows) may straddle it, and is split there. */
* own chunks. Splits at the interval and a span's end as nearest does (below). The tail
* snapshot is at the start of the prompt's last chunk (tail_checkpoint), a boundary an
* idle chunk already ends on, so it costs a copy and no step. A step that shares the
* budget (another request, decode rows) may straddle it, and is split there. */
const int64_t I = geo_.checkpoint_interval;
const bool periodic = !geo_.window_ckpt || geo_.window_periodic;
const int64_t next = periodic ? ((n_computed / I) + 1) * I : INT64_MAX;
@@ -895,28 +904,27 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
} else if (periodic && (n_computed + want) % I == 0 && geo_.on_grid(n_computed + want)) {
if (checkpoint_pos) *checkpoint_pos = n_computed + want;
}
/* A request's own checkpoint (Request::checkpoint_at) as below, wherever it falls: the
* head the request shares with others resumes there by design. */
/* A request's own checkpoint (Request::checkpoint_at), wherever it falls, as nearest
* takes it: the head the request shares with others resumes there by design. */
const int64_t keep = keep_at / geo_.quantum * geo_.quantum;
if (keep > n_computed && keep <= n_computed + want && keep <= n_target) {
want = keep - n_computed;
if (checkpoint_pos) *checkpoint_pos = keep;
}
} else if (geo_.checkpoints()) {
/* --prefix-resume nearest, or no prefix cache: interval checkpoints, and a tail snapshot
* as deep in the prompt as the rules below allow. */
const int64_t I = geo_.checkpoint_interval;
int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */
if (geo_.window_ckpt && !geo_.window_periodic) {
/* An explicit tail-only policy should not pay for intermediate
* window copies or chunk splits just to retire those snapshots. */
next = INT64_MAX;
} else if (geo_.window_ckpt) {
/* A tail-only window snapshot is unreachable after a prompt edit.
* Keep interval checkpoints too; the ordinary retention policy bounds
* their storage. Preserve the tail before the template's changed suffix,
* even when the prompt ends exactly on an interval boundary. */
const int64_t tail = tail_checkpoint(n_target);
if (tail > n_computed) next = std::min(next, tail);
}
/* Otherwise a window keeps interval snapshots too (a tail-only one is unreachable after a
* prompt edit; the ordinary retention policy bounds their storage), each splitting the
* prefill at its boundary. The tail's is taken inside the chunk that carries it
* (wtail below), so it splits nothing. */
/* A span (ChunkGeometry::span) starts only on an interval boundary past the first
* interval, and its chunk is the span's intervals in a row, each the piece a span of 1
* makes a chunk of its own. Not from a prompt's start: the first interval may be served on
@@ -930,16 +938,26 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
want = far - n_computed;
else if (n_computed + want > next && n_computed + want < n_target)
want = (n_computed + want) / I * I - n_computed;
if ((geo_.window_ckpt && n_computed + want == next) ||
(!geo_.window_ckpt && (n_computed + want) % I == 0)) {
/* A window snapshot at the prompt's tail, a block short of its end (the next turn's
* rendering may differ there), even where the prompt ends on an interval boundary. The
* window's rows behind it are still held when the chunk ends (a window slides from a
* step's first query, KVManager::recycle_window), so it is taken inside whichever chunk
* carries that position, and the prompt is not split there: no extra step. It wins over
* an interval snapshot at the same chunk's end, which lies past it. */
const int64_t wtail = geo_.window_ckpt ? tail_checkpoint(n_target) : -1;
if (wtail > n_computed && wtail <= n_computed + want) {
if (checkpoint_pos) *checkpoint_pos = wtail;
} else if ((geo_.window_ckpt && n_computed + want == next) ||
(!geo_.window_ckpt && (n_computed + want) % I == 0)) {
if (checkpoint_pos) *checkpoint_pos = n_computed + want;
} else if (n_computed + want == n_target) {
/* Also one at the prompt's tail. The next turn resumes from the deepest snapshot
* under its hit, which on the interval alone can be nearly an interval short of this
* prompt's end, re-prefilled every turn. The final chunk splits at the last quantum
* boundary, and the remainder (under a quantum) runs as the next step's chunk
* (tail_checkpoint decides when that is worth it). */
const int64_t tail = tail_checkpoint(n_target);
* prompt's end, re-prefilled every turn. Linear state is what the chunk's last token
* leaves, so the final chunk splits at the last quantum boundary and the remainder
* (under a quantum) runs as the next step's chunk (tail_checkpoint decides when that
* is worth it). A window's tail snapshot is taken above, inside its chunk. */
const int64_t tail = geo_.window_ckpt ? -1 : tail_checkpoint(n_target);
if (tail > n_computed) {
want = tail - n_computed;
if (checkpoint_pos) *checkpoint_pos = tail;
@@ -974,36 +992,46 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
}
if (aligned < end) {
want = aligned - n_computed;
if (checkpoint_pos) *checkpoint_pos = -1;
/* A checkpoint at the old end goes with it (the chunk that reaches it takes it); a
* window's tail snapshot the trimmed chunk still carries stays, or the next chunk
* would start past it and the prompt take none. */
if (checkpoint_pos && *checkpoint_pos > aligned) *checkpoint_pos = -1;
}
}
return want;
}
/* The tail checkpoint of a `target`-token prompt, or -1: its last quantum boundary, only past the
* first interval (a shorter prompt is cheap to redo) and only where it gains at least a quarter
* interval over the interval checkpoint below it, which pays for the extra step. */
/* The tail checkpoint of a `target`-token prompt, or -1. Under --prefix-resume exact, where its
* last chunk starts (below). Under nearest, its last quantum boundary, only past the first
* interval (a shorter prompt is cheap to redo) and only where it gains at least a quarter
* interval over the interval checkpoint below it, which pays for the extra step; a window
* snapshot follows its own rule (below). */
int64_t Scheduler::tail_checkpoint(int64_t target) const {
const int64_t I = geo_.checkpoint_interval, Q = geo_.quantum;
if (I <= 0 || Q <= 0) return -1;
if (geo_.exact) {
/* --prefix-resume exact: where the prompt's last chunk starts on the resume grid, so an
* exact repeat re-prefills that chunk as the cold run did, and an appended turn that chunk
* and what it added. A window snapshot keeps its margin below (next comment): the grid
* point under the end less a block. Past the first interval, as below. */
* and what it added. A window snapshot keeps nearest's margin (next comment): the grid
* point under the end less a block. From the first interval on, as nearest's linear-state
* rule (a window's lower floor, kWindowSnapshotMin, is nearest's only). */
const int64_t margin = geo_.window_ckpt ? std::max<int64_t>(Q, 16) : 1;
const int64_t t = geo_.grid_floor(target - margin);
if (geo_.window_ckpt) return t >= I ? t : -1;
return t > I ? t : -1;
}
const int64_t tail = target / Q * Q;
/* A window snapshot is taken at the tail of any prompt of an interval or more, a block short
* of the end: the next turn re-renders the last few tokens (the generation prompt is replaced
* by the reply), and a snapshot past where the two renderings diverge is unreachable. Prompts
* that left fewer than ~8 tokens in their last block always missed. */
/* A window snapshot is taken at the tail of a prompt, a block short of its end: the next turn
* re-renders the last few tokens (the generation prompt is replaced by the reply), and a
* snapshot past where the two renderings diverge is unreachable. Prompts that left fewer than
* ~8 tokens in their last block always missed. It is taken where that position is at least
* kWindowSnapshotMin, or an interval where that is lower: from a 528-token prompt at a quantum
* of 16. The snapshot is the only way a hit resumes on a model whose windowed layers the cache
* does not index, so the floor is low: copying the window out and back costs a few
* milliseconds, recomputing the prompt a prefill. */
if (geo_.window_ckpt) {
const int64_t t = (target - std::max<int64_t>(Q, 16)) / Q * Q;
return t >= I ? t : -1;
return t >= std::min<int64_t>(I, kWindowSnapshotMin) ? t : -1;
}
return tail > I && tail - tail / I * I >= std::max<int64_t>(Q, I / 4) ? tail : -1;
}
@@ -1248,8 +1276,10 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
* tenant wrote, so the model would attend to the previous request's KV. Zero the reuse
* and re-prefill unless a window snapshot covers it.
*
* A drafter's own group (bound at base_layer and above) is not this clamp's business:
* draft refill caps the hit so the recompute covers the drafter's window. */
* A drafter's own group (bound at base_layer and above) is not this clamp's business: it
* rides in the window snapshot where the engine puts it there
* (IKVManager::window_snapshot), and otherwise draft refill caps the hit so the recompute
* covers the drafter's window. */
if (reuse > 0 && (hit_holes_trunk_ || (hit_needs_window_ && !win_hit))) {
reuse = 0;
s.hit_cut = SchedReq::HitCut::Window;
@@ -1407,6 +1437,7 @@ const RadBatch* Scheduler::step() {
if (pc_) pc_->begin_step();
plan_.reset();
plan_.spec_is_tree = tree_;
step_prefill_tok_ = 0;
step_decode_tok_ = 0;
@@ -1623,14 +1654,17 @@ const RadBatch* Scheduler::step() {
e.n_draft = s.n_draft;
e.is_prefill = prefill;
e.ngram = !prefill && s.draft_ngram && s.n_draft > 0;
/* A tree drafter's parents, unless prompt lookup replaced its proposal with a chain. */
e.draft_parent = (!prefill && s.draft_tree && !e.ngram) ? s.draft_par : nullptr;
r.draft_parent = e.n_spec ? e.draft_parent : nullptr;
e.produces_token = (r.n_computed + want >= target);
/* The snapshot a hit resumes from, consumed once: the state is in the slot for the whole
* sequence after this, and restoring it again on a later chunk would rewind it. */
e.ckpt_restore = s.ckpt_src;
s.ckpt_src = -1;
/* The checkpoint is the state after the chunk's last token, which the split put at the
* interval boundary. */
if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(want - 1));
/* The checkpoint is the state after the chunk's token at `ckpt`: its last, where the split
* put the interval boundary there, or inside it for a window snapshot (plan_chunk). */
if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(ckpt - r.n_computed - 1));
s.entry = (int32_t)plan_.e.size();
s.sched_tokens = (int32_t)want;
plan_.e.push_back(e);
@@ -1698,6 +1732,7 @@ const RadBatch* Scheduler::step() {
* preemption may still carry a drafter's proposal. */
r.n_draft = 0;
r.draft = nullptr;
r.draft_parent = nullptr;
e.n_accepted = 1; /* one-based; a prefill rolls nothing back */
e.conv_cursor = s.conv_cursor;
e.draft = s.draft;
@@ -1708,7 +1743,8 @@ const RadBatch* Scheduler::step() {
* restoring again on a later chunk would rewind the recurrence to the hit. */
e.ckpt_restore = s.ckpt_src;
s.ckpt_src = -1;
if (s.pending_ckpt > 0) reserve_ckpt(e, r, s.pending_ckpt, s.sched_tokens - 1);
if (s.pending_ckpt > 0)
reserve_ckpt(e, r, s.pending_ckpt, (int32_t)(s.pending_ckpt - r.n_computed - 1));
s.entry = (int32_t)plan_.e.size();
plan_.e.push_back(e);
plan_.n_tok += s.sched_tokens;
@@ -1748,7 +1784,7 @@ const RadBatch* Scheduler::step() {
if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) {
e.n_tokens = (int32_t)grown;
e.produces_token = (r.n_computed + grown >= s.seq_len());
if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(grown - 1));
if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(ckpt - r.n_computed - 1));
s.sched_tokens = (int32_t)grown;
plan_.n_tok += grown - had;
budget -= grown - had;
@@ -2003,6 +2039,7 @@ const RadBatch* Scheduler::step_next_locked() {
if (ends_every_request()) return nullptr;
plan_next_.reset();
plan_next_.spec_is_tree = tree_;
for (const StepEntry& e : plan_.e) {
if (e.slot < 0 || (size_t)e.slot >= reqs_.size()) return nullptr;
SchedReq& s = *reqs_[(size_t)e.slot];
@@ -2034,6 +2071,8 @@ const RadBatch* Scheduler::step_next_locked() {
n.n_accepted = 1; /* the card's: StepSlot::n_acc */
n.conv_cursor = s.conv_cursor;
n.draft = s.draft; /* published before this step commits (set_draft) */
/* And the tree drafter's parents, which the card verifies by (ADV_BTAKE took them). */
n.draft_parent = tree_ ? s.draft_par : nullptr;
n.n_draft = d;
n.is_prefill = false;
n.produces_token = true;
@@ -2080,7 +2119,11 @@ void Scheduler::promote_next() {
s.entry_next = -1;
s.draft_next = 0;
s.sched_tokens = plan_.e[i].n_tokens;
if (s.req) { s.req->n_draft = plan_.e[i].n_spec; s.req->draft = s.draft; }
if (s.req) {
s.req->n_draft = plan_.e[i].n_spec;
s.req->draft = s.draft;
s.req->draft_parent = tree_ && plan_.e[i].n_spec ? s.draft_par : nullptr;
}
}
++m_.steps_decode;
/* A step issued ahead during a hold is one of its decode-only steps. */
@@ -2241,7 +2284,12 @@ int Scheduler::commit(StepResult& res) {
if (lp_failed || (lp && lp->token < 0)) { lp_failed = true; return; }
if (!server::sink_push(r.sink, t, lp)) overflowed = true;
};
for (int32_t j = 0; j < a; ++j) emit(s.draft[j], j);
/* On a tree step the accepted drafts are the path's nodes, in path order. */
const int32_t* path = res.path ? res.path + (size_t)i * RAD_SCHED_MAX_SPEC : nullptr;
for (int32_t j = 0; j < a; ++j) {
const int32_t d = path ? path[j] - 1 : j;
emit(d >= 0 && d < e.n_spec ? s.draft[d] : s.draft[j], j);
}
if (res.token) emit(res.token[i], a);
r.n_computed = valid;
step_decode_tok_ += 1 + a;
@@ -2692,6 +2740,7 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block
d.card = e.card;
d.ctx_len = e.ctx_len;
d.n_tokens = e.n_tokens;
d.n_spec = e.produces_token && !e.is_prefill ? e.n_spec : 0;
/* Every entry of the trunk step gets a row, in order, running or not: the context pass's
* row i must be the trunk's row i, so leaving out a sequence the commit just finished
@@ -2811,6 +2860,15 @@ const RadBatch* Scheduler::block_context(int step) {
/* The context pass reads tapped hidden states, not token ids: nothing to shift and no
* draft. */
e.produces_token = false;
/* A tree verify's rows are restaged on the card from its accepted path (ADV_CTXTREE):
* only that path is context, each node at its committed position. Not a placeholder,
* whose blocks may already be free. */
if (tree_ && d.dev && !d.mirror && d.n_spec > 0 && d.n_tokens == 1 + d.n_spec) {
e.dev = true;
e.dev_tok = (int32_t)block_plan_.n_tok;
e.dev_out = -1;
e.dev_aux = 0;
}
block_plan_.e.push_back(e);
block_plan_.n_tok += e.n_tokens;
}
+23 -5
View File
@@ -46,6 +46,10 @@ struct SchedReq {
int32_t draft[RAD_SCHED_MAX_SPEC] = {};
int32_t n_draft = 0;
int32_t conv_cursor = 0;
/* A tree drafter's parents for `draft` (StepEntry::draft_parent), valid while `draft_tree`;
* a chain proposal (prompt lookup, or a chain drafter) clears it. */
int32_t draft_par[RAD_SCHED_MAX_SPEC] = {};
bool draft_tree = false;
/* A serial drafter's valid history: positions [0, draft_filled) of the head's own layer hold
* K and V for the sequence's real tokens. Only the head writes that layer, so before drafting
@@ -140,6 +144,9 @@ public:
* accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */
const TokenLogprobs* lp = nullptr;
const int32_t* first_row = nullptr; /* [n_seq] */
/* A tree step's accepted nodes, [n_seq][RAD_SCHED_MAX_SPEC]: entry i's t-th accepted
* draft is draft[path[i][t] - 1]. Null on a chain step, where it is draft[t]. */
const int32_t* path = nullptr;
};
/* What commit left a sequence at: its committed length and whether it is still Running.
@@ -262,7 +269,8 @@ public:
/* The drafter's proposal for a request's next step. n is clamped to the sequence's window
* (draft_cap): the controller's depth, or what the adaptive policy gives the sequence. */
int set_draft(uint64_t id, const int32_t* tokens, int n);
/* `parents`: a tree drafter's (rad_drafter_tree), node j + 1's parent node, null for a chain. */
int set_draft(uint64_t id, const int32_t* tokens, int n, const int32_t* parents = nullptr);
/* ---------------------------------------------------------- media the encoder owes
* A request carrying media is admitted only once every item is encoded; until then it keeps
@@ -400,11 +408,14 @@ public:
* block drafter's block length is chosen by. Read before block_begin(). */
int decoded_seqs() const;
/* Whether a block drafter runs its short block (--draft-short-from `from`), given whether it
* ran it last step and this step's decoded_seqs(): on from `from`, off again only at two
* below, so a load wavering at the threshold does not switch the pass shape every step. */
* ran it last step and this step's decoded_seqs(): on from `from`, and off again two below or
* at one sequence below `from`, where the long block pays. Two below keeps a load wavering at
* a threshold of 3 or more from switching the pass shape every step. From 2 there is no such
* margin: a load between one and two sequences switches every step (block_shape reads it per
* step), and the one sequence left after an overlap runs the long block again. */
static bool short_block_on(bool was_on, int64_t decoded, int64_t from) {
if (decoded >= from) return true;
if (decoded + 2 <= from) return false;
if (decoded <= 1 || decoded + 2 <= from) return false;
return was_on;
}
const RadBatch* block_context(int step);
@@ -425,11 +436,15 @@ public:
SchedMetrics observed_metrics() const;
int observed_requests(ReqStat* out, int max) const;
/* plan_chunk's tail-checkpoint rule (see the definition). */
/* plan_chunk's tail-checkpoint rule for each --prefix-resume mode (see the definition). */
int64_t tail_checkpoint(int64_t target) const;
/* The least recompute a snapshot at a shared head (CacheHit::branch_at) must save each later
* request for the chunk split that takes it. */
static constexpr int64_t kSharedHeadMin = 256;
/* The lowest position tail_checkpoint takes a window snapshot at (ChunkGeometry::window_ckpt),
* or the interval where that is lower. A prompt reaches it at kWindowSnapshotMin +
* max(quantum, 16) tokens: 528 at a quantum of 16. */
static constexpr int64_t kWindowSnapshotMin = 512;
/* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a
* token budget, and the checkpoint position it will land on (-1 for none). `keep_at` is the
* request's own checkpoint (Request::checkpoint_at), 0 for none. */
@@ -520,6 +535,8 @@ private:
* at the committed position (advance.h). False and 0 for every other drafter. */
bool serial_shared_ = false;
int32_t serial_rot_shift_ = 0;
/* A tree drafter (rad_drafter_tree): every trunk plan is StepPlan::spec_is_tree. */
bool tree_ = false;
BatchBuilder builder_;
DraftController draft_;
@@ -662,6 +679,7 @@ private:
int32_t card = -1;
int32_t ctx_len = 0;
int32_t n_tokens = 0;
int32_t n_spec = 0; /* the trunk entry's drafts: a tree verify when > 0 */
int64_t base_pos = 0; /* the anchor's position: the sequence's next one */
bool can_draft = false;
/* On the card: the anchor's position is the card's, and `base_pos` the furthest it can
+78 -28
View File
@@ -462,6 +462,9 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
l["prefetch_bytes"] = s.link.prefetch_bytes;
l["staged_bytes"] = s.link.staged_bytes;
l["stream_bytes"] = s.link.stream_bytes;
l["kv_stream_bytes"] = s.link.kv_stream_bytes;
l["kv_streaming"] = s.link.kv_streaming;
l["kv_stream_active"] = s.link.kv_stream_active;
o["link"] = std::move(l);
}
if (s.passes.present) {
@@ -1182,7 +1185,7 @@ nav button.on { color:var(--fg); background:var(--track); }
otherwise have had, and a percentage of the paged pool's token capacity says nothing
about it: it is a preemption signal, so it is kept, underneath, where it reads as one. -->
<div class="cell"><div class="n" id="m-kv">–<u></u></div>
<span class="cap">kv cache in vram</span>
<span class="cap" id="m-kvcap">kv cache in vram</span>
<span class="det" id="m-kvdet"></span>
<svg viewBox="0 0 200 22" preserveAspectRatio="none"><path/></svg></div>
<div class="cell"><div class="n" id="m-accept">–<u>%</u></div>
@@ -1353,7 +1356,7 @@ nav button.on { color:var(--fg); background:var(--track); }
<span class="cap">conversations can resume</span>
<span class="det" id="s-livedet"></span></div>
<div class="cell"><div class="n" id="s-vram">–<u>tok</u></div>
<span class="cap">context in vram</span>
<span class="cap" id="s-vramcap">context in vram</span>
<span class="det" id="s-vramdet"></span></div>
<div class="cell" id="s-hostcell"><div class="n" id="s-host">–<u></u></div>
<span class="cap">moved to host ram</span>
@@ -1638,6 +1641,9 @@ const RECENT = 30; /* 15 s at the 500 ms poll for a figure sampled every poll;
const RECENT_PREFILL = 10; /* 5 s */
const extAt = {}, winAt = {};
let lastActiveC = 0;
/* Whether the server streams its KV (--kv-resident). Settled at bringup, so it cannot change under
* a running page: the cells that name a memory tier read it instead of guessing. */
let kvStreamOn = false;
/* `win` false records the extreme only: acceptance pools its window in accPool and reads only
* `highest` from extAt. */
function noteSample(key, c, value, cap, win) {
@@ -1867,7 +1873,7 @@ const linkSegs = segs("linkbar", "linkrows");
* own mapping, read in place -- so it is the one that is not a grey. */
const TIER_INK = ["#f5f5f5", "#9a9a9a", "#5e5e5e", "#2b2b2b", "#3f6fa8"];
const INK_AR = "#60a5fa", INK_UP = "#4ade80", INK_DOWN = "#fbbf24", INK_SSD = "#a78bfa";
const INK_STREAM = "#f472b6", INK_PREFETCH = "#2dd4bf";
const INK_STREAM = "#f472b6", INK_PREFETCH = "#2dd4bf", INK_KV = "#fb923c";
/* The plane is painted as raw pixels, so the same inks are wanted as RGB triples. Parsed from
* TIER_INK rather than written out a second time: two lists of five colours is one list that
* will drift, and the drift is a legend that names the wrong band of the picture. */
@@ -2243,7 +2249,13 @@ function update(s, dt) {
* wrong headline: the drafter's own window group is sized one block-run per slot and therefore
* sits at 100% for the whole life of the server, so a headline reading the max reads 100% on a
* server using 4% of its cache. */
const kvFrac = s.kv_tokens_total > 0 ? s.kv_tokens_used / s.kv_tokens_total : 0;
/* ONE UNIT FOR ONE METER. The figure is bytes -- every group's, which is the only unit groups
* can be summed in -- and the bar used to be TOKENS, the binding group's. Groups hold different
* bytes per token, so the two were answering at different rates: the figure reached its total
* while the bar was half full and then the figure stood still while the bar went on climbing.
* A streamed group's host mirror, whose pages arrive in their own order, made the gap wide
* enough to read as a bug, and it was one. Both are bytes now, and the percentage is the bar. */
const kvFrac = s.kv_bytes_total > 0 ? (s.kv_bytes_used || 0) / s.kv_bytes_total : 0;
/* HELD, NOT READ. A finished turn's blocks stay held by the prefix cache so the next turn can
* reuse them, and they occupy the card for exactly as long as they are held -- so they belong
* in this figure. What leaves it is a block that reached the free list, which is where an
@@ -2255,14 +2267,31 @@ function update(s, dt) {
* holds, in place, so what it keeps for itself is below what the carve gave it -- and the gap is
* the expert plane's "Borrowed VRAM". The line says both numbers rather than one, because
* "of 3.1 GiB" alone would read as a smaller budget. */
const kvGave = (s.kv_bytes_carved || 0) - s.kv_bytes_total;
/* TWO LINES, because the slot is two lines and a third is clipped rather than drawn. The share
of the pool is not among them: it is the bar in the memory panel, and repeating it here cost
the line that says how much context the bytes are actually holding. */
const kvGave = (s.kv_bytes_carved || 0) - (s.kv_bytes_total || 0);
/* KV STREAMING CHANGES WHAT THESE BYTES ARE -- but only where it is switched on in fact, not
* where it was asked for: --kv-resident is a preference (zeroed when the architecture refuses
* it, and a no-op at or above the group's context), while kv_stream_active says a group really
* keeps a resident window under its context. Without it every block the cache holds is on the
* card, so "of <total>" is VRAM and the carve is its ceiling. With it the card holds only the
* ring and every other block's K/V sits in a pinned host mirror: the figure above is the
* mirror, which is the whole context and therefore larger than the carve -- printing the carve
* beside it as a "max", or below as "can grow to", put a smaller number next to the larger one,
* and the pool read full the moment the mirror did. The line names the tier instead, and the
* ring keeps its own figure. */
const kvStream = !!(s.link && s.link.kv_stream_active);
/* THE TIER THE NUMBER IS IN, spelled. A streamed group's held context lives in the host mirror,
* so the same figure is "in ram" on this card; without streaming every block is on the card and
* it stays "in vram". The sessions view asks the same question of the same pool and renames its
* cell from the flag this poll settles. `kvStream` is the ring's actual state, not the switch. */
kvStreamOn = kvStream;
$("m-kvcap").textContent = kvStream ? "kv cache in ram" : "kv cache in vram";
$("m-kvdet").textContent = s.kv_bytes_total > 0
? "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
+ cnt3(s.kv_tokens_used) + " tok"
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : "")
? (kvStream
? "of " + hb(s.kv_bytes_total) + " in host mirror · " + cnt3(s.kv_tokens_used) + " tok"
+ " · " + hb(s.kv_bytes_carved || 0) + " VRAM ring"
: "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
+ cnt3(s.kv_tokens_used) + " tok"
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : ""))
: "";
const aw = accWindow(s);
const awR = aw ? aw.ratio : null;
@@ -2298,29 +2327,31 @@ function update(s, dt) {
/* ONE MERGED FIGURE. The pool is carved into groups by state kind -- paged attention, the
* linear state, the drafter's own window -- and which of them a token landed in is an
* implementation detail of the carve, not a question anybody watching a server is asking. */
/* THE BAR IS THE BYTES BECAUSE THE PANEL IS ABOUT THE CARD, and it is filled from every group
* -- the recurrent ones included -- while the token figure beside it is the binding paged
* group's alone. They are not a unit conversion of each other and the panel says both.
*
* THE FILL IS IN TWO PARTS, and the second is the one that answers "why is the pool full when
* one conversation is running". The bytes are apportioned by the token split rather than
* measured, because the cache counts in blocks of the shared token axis and the bytes are
* every group's -- the ratio is what is being drawn, and it is exact in the unit it is taken
* in. */
/* THE FILL IS IN TWO PARTS, and the second is the one that answers "why is the pool full when
* one conversation is running". The share comes from the tokens (which blocks a running request
* reads versus which only the cache keeps is a fact about blocks) and is then spent in BYTES,
* the unit the figure and the percentage beside it are in, so the three cannot disagree. */
const kvCached = Math.min(s.kv_tokens_cached || 0, s.kv_tokens_used || 0);
const kvLive = Math.max(0, (s.kv_tokens_used || 0) - kvCached);
const kvCachedShare = (s.kv_tokens_used || 0) > 0 ? kvCached / s.kv_tokens_used : 0;
mKv.v.textContent = hbOf(s.kv_bytes_used, s.kv_bytes_total, " / ") + " · " + pct(kvFrac);
setSplit(mKv, kvLive, kvCached, s.kv_tokens_total || 0);
/* The two shares are FRACTIONS OF THE FILL, not of the track: spent as widths against a total
* of 1 they would draw a full bar for a pool holding 29 KiB. */
setSplit(mKv, (1 - kvCachedShare) * kvFrac, kvCachedShare * kvFrac, 1);
/* The segments named by what reclaiming them would cost, since a dimmer bar is not
self-explanatory. The split is by who references the blocks: the first part is context a
request on the card is reading, the second context nothing reads and the next eviction frees. */
mKvSub.textContent = s.kv_tokens_used > 0
? cnt3(kvLive) + " tok read by running requests · " + cnt3(kvCached) + " kept for reuse"
: "";
mKvMax.textContent = s.kv_tokens_max > 0
? "can grow to " + hb(s.kv_bytes_carved || 0) + " · " + cnt3(s.kv_tokens_max)
+ " tok, with what the experts borrowed taken back"
: "";
mKvMax.textContent = kvStream
? (s.kv_tokens_max > 0
? "a miss streams the missing blocks from the mirror into the ring"
: "")
: (s.kv_tokens_max > 0
? "can grow to " + hb(s.kv_bytes_carved || 0) + " · " + cnt3(s.kv_tokens_max)
+ " tok, with what the experts borrowed taken back"
: "");
mPc.v.textContent = pct(s.prefix_hit_rate); setBar(mPc.i, s.prefix_hit_rate, false);
/* ---- draft. The bar is the CONDITIONAL acceptance at that position; the reach row under the
@@ -2498,6 +2529,8 @@ function update(s, dt) {
const pre = (f) => lk[f] || 0;
const dP = (f) => prev.link[f] == null ? 0 : Math.max(0, (pre(f) - prev.link[f]) / dt);
const ar = d("ar_bytes"), dn = d("d2h_bytes"), sd = d("ssd_bytes"), st = d("stream_bytes");
/* Null-safe until a server reports it: an older one, or the switch off, reads as zero. */
const kv = lk.kv_streaming ? dP("kv_stream_bytes") : 0;
const pf = dP("staged_bytes") + dP("prefetch_bytes");
const up = Math.max(0, d("h2d_bytes") - pf);
const pfAll = pre("staged_bytes") + pre("prefetch_bytes");
@@ -2508,7 +2541,7 @@ function update(s, dt) {
* proportion then falls back to the CUMULATIVE bytes, which is the same question asked over
* the whole run, and the panel says out loud which of the two it is showing. The rates stay
* in the rows either way: they are never wrong, only sometimes zero. */
const live = ar + up + pf + dn + sd + st > 0;
const live = ar + up + pf + dn + sd + st + kv > 0;
const w = (now, all) => live ? now : all;
linkSegs([
{ name: "All-reduce", ink: INK_AR, w: w(ar, lk.ar_bytes),
@@ -2531,6 +2564,16 @@ function update(s, dt) {
a: rate(sd), b: hb(lk.ssd_bytes) },
{ name: "Expert streaming", ink: INK_STREAM, w: w(st, lk.stream_bytes),
a: rate(st), b: hb(lk.stream_bytes) },
/* KV STREAMING, --kv-resident (core/kvstream): each step's resolve copies the blocks a
* streamed group missed from the pinned host mirror into the VRAM ring. The row rides the
* switch, not the traffic: a server that took --kv-resident but never streams -- a pipeline
* that never enters the streaming path -- is exactly what a zero row with the switch on
* says, and that is a question worth answering at a glance. The bytes are rank 0's resolve
* counters times the world: the ranks see the same misses through maps brought up
* identically, so each card's link carries one rank's figure. */
...(lk.kv_streaming ? [{ name: "KV streaming", ink: INK_KV,
w: w(kv, pre("kv_stream_bytes")),
a: rate(kv), b: hb(pre("kv_stream_bytes")) }] : []),
]);
/* THE HEADLINE IS THE PCIe TOTAL, which is the all-reduce plus the moves. The SSD tier is
* left out of it on purpose: those bytes come off a disk into host memory and only the ones
@@ -2540,8 +2583,12 @@ function update(s, dt) {
* EXPERT STREAMING IS IN IT. A routed expert that was not resident is read by the MoE GEMM
* where it lies, which for every tier above VRAM means crossing the link on the critical
* path of the step. It is not a move and not a collective, and it is the traffic a promotion
* is spent to remove -- so the two belong on one axis. */
const lr = rates(ar + up + pf + dn + st);
* is spent to remove -- so the two belong on one axis.
*
* KV STREAMING IS IN IT WHILE THE SWITCH IS ON. Its resolve copies cross the same PCIe the
* movers use, already summed over the cards; with the switch off the term is zero and the
* headline reads as it did without the counter. */
const lr = rates(ar + up + pf + dn + st + kv);
$("lnk_n").firstChild.nodeValue = lr.n;
$("lnk_n").querySelector("u").textContent = lr.u;
/* WHAT IS SUMMED AND WHAT IS NOT. The move and stream rows are every card's added up,
@@ -3462,6 +3509,9 @@ async function loadSessions() {
/* VRAM IN TOKENS, HOST MEMORY IN BYTES. The pool's token count is the context the card can
serve without a copy; the host tier is sized by --prefix-cache-mib and read against it. A
tier that is off has no cell. */
/* A streamed server holds that context in its host mirror, not on the card, so the cell says
* where the tokens are; the flag comes from the stats poll (kvStreamOn). */
$("s-vramcap").textContent = kvStreamOn ? "context in ram" : "context in vram";
$("s-vram").firstChild.nodeValue = cnt3(pool.tokens_used || 0);
$("s-vramdet").textContent = pool.tokens_total ? "of " + cnt3(pool.tokens_total) + " tok" : "";
for (const [id, used, cap] of [["s-host", occ.host_bytes, occ.host_cap_bytes]]) {
+6 -3
View File
@@ -260,15 +260,18 @@ std::string LiveView::render_line(const LiveSnapshot& s) const {
o += " readmit=" + std::to_string(s.experts.readmits);
}
}
/* Link traffic by consumer (collective, mover, MoE GEMM streaming), cumulative so a `| tee`
* of these lines can be differenced into rates. */
/* Link traffic by consumer (collective, mover, MoE GEMM streaming, KV streaming), cumulative
* so a `| tee` of these lines can be differenced into rates. */
if (s.link.present &&
(s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes)) {
(s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes ||
s.link.kv_streaming)) {
o += " link ar=" + std::to_string(s.link.ar_bytes);
o += " h2d=" + std::to_string(s.link.h2d_bytes);
o += " d2h=" + std::to_string(s.link.d2h_bytes);
if (s.link.stream_bytes) o += " stream=" + std::to_string(s.link.stream_bytes);
if (s.link.ssd_bytes) o += " ssd=" + std::to_string(s.link.ssd_bytes);
/* Printed at zero when the switch is on: the zero is the measurement. */
if (s.link.kv_streaming) o += " kv=" + std::to_string(s.link.kv_stream_bytes);
}
o += "\n";
return o;
+20 -5
View File
@@ -95,11 +95,12 @@ struct ExpertPlane {
/* Interconnect traffic by consumer.
*
* Three things share the link: the tensor-parallel all-reduce (set by model width and batch), the
* expert mover's promotions and demotions (set by placement policy), and the MoE GEMM streaming a
* routed expert that is not in VRAM (what the moves try to avoid). All are cumulative byte counts
* on one clock, so rates from two polls compare directly: is the link busy because the model is
* wide or because placement is thrashing?
* Four things share the link: the tensor-parallel all-reduce (set by model width and batch), the
* expert mover's promotions and demotions (set by placement policy), the MoE GEMM streaming a
* routed expert that is not in VRAM (what the moves try to avoid), and --kv-resident's per-step
* resolve, which copies the blocks a streamed KV group missed from its host mirror into the VRAM
* ring (core/kvstream). All are cumulative byte counts on one clock, so rates from two polls
* compare directly: is the link busy because the model is wide or because placement is thrashing?
*
* `ar_bytes` is the message payload summed over issues (see Ctx::ar_bytes). `h2d`/`d2h` are the
* mover's measured copy sizes.
@@ -117,6 +118,20 @@ struct LinkStat {
/* The prefill stager's copies of the next layer's pooled experts (core/place/stager.h).
* Included in `h2d_bytes`, like `prefetch_bytes`; subtract both for promotions alone. */
int64_t staged_bytes = 0;
/* KV streaming (--kv-resident): the bytes the resolves copied from the host mirror into the
* ring. Rank 0's counters -- the ranks resolve the same block ids through maps brought up
* identically, so one rank's answer is every rank's (see Engine::stream_probe_take) -- times
* the world, to sit on every card's link like the move rows. `kv_streaming` says the switch
* was asked for; a renderer then shows the row at zero included, because a zero with the
* switch on is the answer to "does this model's pipeline ever stream?".
*
* `kv_stream_active` is the DIFFERENT question: whether a group's device pool really is a
* resident window under its context. The switch is a preference -- it is zeroed when the
* architecture refuses it, and --kv-resident at or above the group's context leaves a plain
* resident pool -- so text that names a memory tier must read this, never the flag. */
int64_t kv_stream_bytes = 0;
bool kv_streaming = false;
bool kv_stream_active = false;
};
/* How the ranks ran their passes, summed over ranks (see Ctx::PassCounts). A played pass costs
+2 -3
View File
@@ -24,6 +24,8 @@ struct ChatTemplate::Impl {
bool add_bos = false, add_eos = false;
};
/* The template's own words: the lifted autoparser wraps whatever the render threw in a sentence
* about parser generation, which the render's failure is not. */
static std::string template_words(const char* what) {
static const char kWrap[] = "Unable to generate parser for this template. Automatic parser "
"generation failed: ";
@@ -190,9 +192,6 @@ static bool lead_system(const ojson& messages, ojson* out) {
return true;
}
/* The template's own words: the lifted autoparser wraps whatever the render threw in a sentence
* about parser generation, which the render's failure is not. */
int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt,
ChatPrompt* out) const {
if (!ready()) {
+2 -2
View File
@@ -15,8 +15,8 @@ rest U64 in the GGUF, which the core reads as I64):
engram.head_vocab_sizes I64 [n_engram_layers * (max_ngram - 1) * n_heads]
engram.head_offsets I64 [same] (absolute row offsets into the joined table)
The deepseek41 plugin reads them under these names when the checkpoint is the release
(arch/deepseek41 ckpt_name). Reads config.json and tokenizer.json only (small).
The deepseek41 architecture plugin, which this tree does not include, reads them under these names
when the checkpoint is the release. Reads config.json and tokenizer.json only (small).
usage: python3 data/engram_tables.py RELEASE_DIR OUT.safetensors
"""
+1 -1
View File
@@ -8,7 +8,7 @@
# rad-convert <DeepSeek-V4.1-Flash-1017 dir> --add engram-tables.safetensors \
# --recipe data/recipes/deepseek41-ud-iq1s.recipe --imatrix <imatrix.gguf> -o deepseek41-ud-iq1s.rad
#
# The imatrix is Unsloth's with entries for the fused weights added (docs/deepseek41-wip.md). One rule per weight,
# The imatrix is Unsloth's with entries for the fused weights added (data/imatrix_merge.py, docs/deepseek41-hf-direct.md). One rule per weight,
# experts collapsed per layer; first match wins.
# PATTERN QUANTISER OPTIONS
dspark.enc.output_norm.weight cast dtype=f32
+7 -5
View File
@@ -3,8 +3,9 @@
# speculator merged in (gemma-4-31B-it-speculator.dflash2: block 8, 7 drafts a pass, int8 head), and
# the vision tower. Converted with data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe, or downloaded
# from https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2. The drafter
# serves the depth it was trained at (`auto`). Sampling defaults are the checkpoint's
# generation_config; thinking is switched per request (chat_template_kwargs).
# serves the depth it was trained at (`auto`), its proposals verified as a 7-node tree a step (on
# by default for this drafter). Sampling defaults are the
# checkpoint's generation_config; thinking is switched per request (chat_template_kwargs).
#
# --tp 4 over four cards; chained launches, the weight reads beside the collectives and the prefill
# overlap turn themselves on there.
@@ -12,9 +13,10 @@
# tokens of a step, with one decode-only step after it, so a long prompt holds the others up by a
# fraction of a chunk rather than all of it. 16 sequences, as measured below.
#
# On 4x R9700 (PCIe 4.0 x16): one user 390 code / 288 prose / 208 story tok/s, and
# 590 after a 6442-token prompt (prefill 5962 tok/s); 302 / 512 / 658 / 835 / 981 tok/s aggregate
# at 1 / 2 / 4 / 8 / 16 users (BetterBench, thinking off).
# On 4x R9700 (PCIe 4.0 x16), BetterBench with thinking off: 378 tok/s single-stream (weighted
# over its categories; JSON 593, math 496, code 417, prose 230) and 341 / 552 / 727 / 877 / 960
# tok/s aggregate at 1 / 2 / 4 / 8 / 16 users. The chain on the same cards: 352, and 315 / 505 /
# 680 / 816 / 907. Prefill of a 6442-token prompt: about 5960 tok/s.
#
# Measured with the host CPU's performance governor and its idle states past C1 off. The cards'
# peer-to-peer traffic crosses the root complex, so the host's power state shows in every step, and
@@ -0,0 +1,41 @@
# Gemma 4 31B-it on two cards with a block-16 DFlash2 drafter: the int4 trunk of
# gemma4-31b-w4a8-df2-tp4.yaml (round-to-nearest with a scale search, from the bf16 checkpoint; q, k
# and v as one linear) with int8 activations and lm_head, and the vision tower, with RedHatAI's DFlash2
# speculator fine-tuned from block 8 to block 16
# (https://huggingface.co/Ashlyn4202025/gemma-4-31B-it-speculator.dflash2-b16: 15 drafts a pass, int8
# head). Converted with data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe and that drafter, or
# downloaded from https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2-b16. Sampling defaults
# are the checkpoint's generation_config; thinking is switched per request (chat_template_kwargs).
#
# The drafter's proposals are verified as a 15-node tree a step (`auto`). From two users on, each
# tree is a 7-node one over the drafter's short block of 8 rows, so a busy server verifies and
# drafts the block-8 tree's shape, from the block-16 drafter. It turns itself on for this container
# (--draft-short-from auto; --draft-short-from 0 keeps the whole tree under load, for an A/B).
#
# --tp 2 over two cards. The token embedding stays in pinned host memory (the default), which leaves
# its VRAM to the KV cache. 16 sequences, as measured below. --gpu-headroom-mib 160 keeps room for
# the page tables the cards hold for pinned host memory, which the VRAM budget does not yet charge:
# without it a two-card start settles ~55 MiB short, and the prefill overlap's second lane can fail
# mid-serve.
#
# On 2x R9700 (PCIe 4.0 x16), BetterBench with thinking off, the box's other two cards serving a
# second server at the same time, the mean of two runs with the card pairs swapped: 253 tok/s
# single-stream (weighted over its categories; JSON 450, math 360, code 280, prose 131) and
# 217 / 328 / 518 / 559 / 776 tok/s aggregate at 1 / 2 / 4 / 8 / 16 users. The block-8 container,
# measured the same way: 199, and 180 / 323 / 494 / 530 / 682.
#
# Measured with the host CPU's performance governor and its idle states past C1 off. The cards'
# peer-to-peer traffic crosses the root complex, so the host's power state shows in every step, and
# a compose file can't set it.
name: radiance-gemma4-31b-w4a8-df2b16-tp2
services:
radiance:
extends: { file: common.yaml, service: radiance }
container_name: radiance-gemma4-31b-w4a8-df2b16-tp2
command: >
--model /models/gemma4-31b-dense-w4a8-df2b16-qkv.rad
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
--tp 2 --max-num-seqs 16 --max-model-len 65536 --kv-cache-dtype fp8
--num-speculative-tokens auto --max-num-batched-tokens 8192
--busy-prefill-chunk 512 --prefill-interleave 1 --gpu-headroom-mib 160
--temp 1.0 --top-p 0.95 --top-k 64
@@ -0,0 +1,38 @@
# Gemma 4 31B-it on four cards with a block-16 DFlash2 drafter: the int4 trunk of
# gemma4-31b-w4a8-df2-tp4.yaml (round-to-nearest with a scale search, from the bf16 checkpoint; q, k
# and v as one linear) with int8 activations and lm_head, and the vision tower, with RedHatAI's DFlash2
# speculator fine-tuned from block 8 to block 16
# (https://huggingface.co/Ashlyn4202025/gemma-4-31B-it-speculator.dflash2-b16: 15 drafts a pass, int8
# head). Converted with data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe and that drafter, or
# downloaded from https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2-b16. Sampling defaults
# are the checkpoint's generation_config; thinking is switched per request (chat_template_kwargs).
#
# The drafter's proposals are verified as a 15-node tree a step (`auto`). From two users on, each
# tree is a 7-node one over the drafter's short block of 8 rows, so a busy server verifies and
# drafts the block-8 tree's shape, from the block-16 drafter. It turns itself on for this container
# (--draft-short-from auto; --draft-short-from 0 keeps the whole tree under load, for an A/B).
#
# --tp 4 over four cards, with everything else as in gemma4-31b-w4a8-df2-tp4.yaml: chained launches,
# the weight reads beside the collectives and the prefill overlap turn themselves on there. 16
# sequences, as measured below.
#
# On 4x R9700 (PCIe 4.0 x16), BetterBench with thinking off: 446 tok/s single-stream (weighted
# over its categories; JSON 801, math 624, code 520, prose 228) and 376 / 553 / 727 / 870 / 965
# tok/s aggregate at 1 / 2 / 4 / 8 / 16 users. The block-8 file, measured alongside: 389, and
# 338 / 560 / 716 / 873 / 970.
#
# Measured with the host CPU's performance governor and its idle states past C1 off. The cards'
# peer-to-peer traffic crosses the root complex, so the host's power state shows in every step, and
# a compose file can't set it.
name: radiance-gemma4-31b-w4a8-df2b16-tp4
services:
radiance:
extends: { file: common.yaml, service: radiance }
container_name: radiance-gemma4-31b-w4a8-df2b16-tp4
command: >
--model /models/gemma4-31b-dense-w4a8-df2b16-qkv.rad
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
--tp 4 --max-num-seqs 16 --max-model-len 65536 --kv-cache-dtype fp8
--num-speculative-tokens auto --max-num-batched-tokens 8192
--busy-prefill-chunk 512 --prefill-interleave 1
--temp 1.0 --top-p 0.95 --top-k 64
+27 -18
View File
@@ -16,7 +16,7 @@ plugin claims.
| `arch/hyv3_gguf` | `hyv3` | `gguf_ftype_15` | llama.cpp Hy-Memory Q4_K_M GGUF, dequantized and recipe-converted to native Radiance weights; TP1/2 |
| `arch/qwen35_w8a8` | `qwen35` | `w8a8_fwht128` | `qwen35_fp8` with an int8 trunk: i8 weights with a bf16 scale per 128 of K, rotated by a 128-wide Hadamard, against int8 activations under the same rotation (`data/recipes/q38-27b-w8a8-df2.recipe`) |
| `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed |
| `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert |
| `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert, or Qwen's FP8 release as it ships |
| `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Pictures through its vision tower (`arch/common/rad_block_glm_vision.h`); bf16 KV |
| `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank |
| `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector |
@@ -345,8 +345,11 @@ Architecture tests cover geometry, GGUF tensor maps, dense-to-MoE scheduling, TP
and FP32 combine order; checkpoint tests cover Q4_K/Q6_K block decoding. Numerical parity against Tencent/llama.cpp
remains untested.
See [HYV3 W4 decode optimizations](benchmarks/hyv3-w4-decode.md) for affected paths,
historical measurements, validation limits and the remaining benchmark/quality gates.
Decode on the full-GPTQ W4 model, TP1 on one R9700 (10,030-token prompt, 2,000 generated tokens,
greedy, no drafter): 76.6 tok/s before the per-128 I4 expert packing, the one-row W4/W5 epilogue,
the in-GEMM BF16 narrowing, the fused Q/K norm + RoPE + KV store and the residual and shared-expert
folds; 109.6 tok/s with them, prefill unchanged (7,876 to 7,927 tok/s). The answer is byte-identical,
and on an eight-document teacher-forced corpus the two builds agree at every top-1 (mean KL 7.6e-8).
## `qwen35_w8a8`
@@ -415,6 +418,13 @@ plugin reads each weight's encoding from the container and declares the op that
- bf16: every norm gain, `A_log`, `dt_bias`, `conv1d`, `in_proj_a` and `in_proj_b` (48 rows is not
a whole scale block), the router, `shared_expert_gate` and `embed_tokens`.
Qwen's own `Qwen3.8-Flash-Next-FP8` converts without a recipe too. Its `quantization_config`
(`quant_method: fp8`, no `fmt`) is block-scaled E4M3, descriptor `fp8_e4m3`; no `qwen4exp` plugin
claims it, so each weight is read as it ships and this plugin serves it: the routed experts (MTP
head's included) at block FP8 with their bf16 `weight_scale_inv`, the n-gram table's 128 FP8
shards under its one `ngram_embedding.weight_scale`, and every other weight bf16. A recipe applies
to it as to the bf16 checkpoint, with each FP8 weight read through its scales.
**The attention cache takes `--kv-cache-dtype fp8_v4` or `k6_v4`.** The QSA layers' cache (and the
MTP head's layer, which shares it) is then declared at head_dim 200 or 176, a token's quantised row
over two, and read by the gqa12 rows (gqa6 with 4-token pages at four ranks) of those layouts
@@ -872,9 +882,9 @@ text 12 layers, hidden 768, ffn 3072, vocab 250048, 12 heads of 64, type vo
mean over every real token, cast to the f32 pooled buffer; the server L2-normalises
```
The block order is the one the verified variant uses: attention on the raw stream, then LN1, the
feed-forward on LN1's output, then LN2 over that output plus the feed-forward's. The checkpoint's
shared `experts.bias` is not applied, and the plugin does not map it. A container that sets
Block order: attention on the raw stream, then LN1, the feed-forward on LN1's output, then LN2
over that output plus the feed-forward's. The checkpoint's shared `experts.bias` is not applied,
and the plugin does not map it. A container that sets
`prenorm`, `causal`, interleaved, partial or scaled rotary, a gelu variant, renormalised routing
or a shared expert is refused at declare.
@@ -895,10 +905,10 @@ reads a bf16 table. The token embedding, linears, router and expert tables are b
| `blk.N.ffn_exp_w2.E.weight` (odd N) | `encoder.layers.N.mlp.experts.mlp.w2` | [768, 3072] | slice E, transpose |
| not declared (odd N) | `encoder.layers.N.mlp.experts.bias` | [768] | not mapped |
The checkpoint stores `w1` and `w2` as one stacked tensor each, `[24576, 768]`; `E` takes the
expert's dim-0 slice, and `w2` is transposed to `[768, 3072]` for the grouped GEMM. Every expert
has two group slots, one for each projection. Nothing else is mapped: there is no final norm, no
pooler, no position table and no output head.
The checkpoint stores `w1` and `w2` as one stacked tensor each, `[24576, 768]`; expert `E` is rows
`[E * 3072, (E + 1) * 3072)`, and `w2`'s block is transposed to `[768, 3072]` for the grouped GEMM.
Every expert has two group slots, one for each projection. Nothing else is mapped: there is no
final norm, no pooler, no position table and no output head.
**The recipe.** The checkpoint is f32 (1.9 GB).
@@ -907,15 +917,14 @@ rad-convert <checkpoint dir> --recipe data/recipes/nomic-embed-v2-moe-bf16.recip
-o nomic-embed-v2-moe-bf16.rad
```
It takes 3.5 s and writes a 959 MB container (907 MiB of weights). The checkpoint directory must
contain `tokenizer.json`. The recipe casts the token embedding, the token-type table, the
attention, dense MLP and expert weights to bf16 and leaves the norms and biases f32.
It writes a 959 MB container (907 MiB of weights). The checkpoint directory must contain
`tokenizer.json`. The recipe casts the token embedding, the token-type table, the attention,
dense MLP and expert weights to bf16 and leaves the norms and biases f32.
**Verified.** 20 texts against a pure-float32 reference: mean cosine 0.99995, min 0.99983 on a
gfx1201 card, with libavx and libref the same to 4 decimals. Against a Q6_K quantisation of the
same model the mean is 0.9944 (min 0.990); the Q8_0 one agrees with the reference at 0.9994, so
the Q6_K quantisation is the outlier, about 0.006 off the true model, and stored vectors from a
Q6_K server drift by about that much.
**Verified.** On 20 texts against a pure-float32 reference, on a gfx1201 card: mean cosine
0.99995, min 0.99983; libavx and libref agree with it to 4 decimals. Against the same reference a
Q8_0 quantisation of the model scores a mean of 0.9994 and a Q6_K one 0.9944 (min 0.990), so
vectors stored from a Q6_K server differ by about 0.006.
**Measured.** On one gfx1201 card, short texts take 2 ms a request at one client, 3854 requests/s
at 64 concurrent clients and 4400 texts/s for a batch of 32 in one request; a 1354-character text
+96 -46
View File
@@ -52,7 +52,7 @@ driver. [`DOCKER.md`](DOCKER.md) covers it, with compose files per model.
| Optional | ROCm with `hipcc`, for AMD device kernels; without it you get the host backend. Set `ROCM_PATH` if ROCm is not at `/opt/rocm` |
| With a card | Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The host writes every dispatch's arguments into VRAM there. On a card whose BAR is smaller than its VRAM they stay in pinned host memory and every dispatch reads them over the link: on R9700s, Qwen3.8-27B fp8 decode steps take 0.4-1.8% longer at `--tp 1` and 2 than with the arguments in VRAM. Peer access needs the large BAR too, so at `--tp 2` and above such a card takes the collectives through host memory (§4.7) |
| Optional | OpenMP, used by the host kernel libraries if present |
| Optional | `libavformat-dev libavcodec-dev libavutil-dev libswscale-dev libswresample-dev` (ffmpeg 6+), for image, video and audio input. The probe is `RAD_WITH_FFMPEG` (`ON` fatal, `OFF` off, default `AUTO`): built without them the engine boots normal, serves text, and refuses every image/video/audio part with HTTP 500 — the configure log is the only warning (`radiance: no libavformat ...`). `GET /diagnostics` shows `media decoders` |
| Optional | `libavformat-dev libavcodec-dev libavutil-dev libswscale-dev libswresample-dev` (ffmpeg 6+), for image, video and audio input. CMake option `RAD_WITH_FFMPEG`: `AUTO` (default) uses them when found, `ON` fails the configure without them, `OFF` builds without. A build without them starts and serves text, and refuses every image, video and audio part with HTTP 500; the only warning is the configure log line `radiance: no libavformat ...`. The diagnostics report says which (`media decoders`; `host.media` in `GET /diagnostics`) |
| Optional | `clang++` (or ROCm's), for `tests/r4d_emu` when the C++ compiler is g++; CMake 3.25+ for `CMakePresets.json` |
| Shell harnesses | `curl` and `jq` |
@@ -93,10 +93,10 @@ cmake --build build -j
ctest --test-dir build -L fast -j8 --output-on-failure
```
A ROCm SDK installed outside `/opt/rocm` — a userspace SDK tree under a virtualenv, a core-only
system install — needs more than `ROCM_PATH`: hipcc is found, then device compilation dies inside
`cuda_wrappers/cmath` with `Could not find standard C++ header 'cmath'`, because ROCm's clang
does not pick up the distro gcc's libstdc++ headers on its own. The flags that make it work:
A ROCm SDK installed outside `/opt/rocm` (a userspace SDK tree under a virtualenv, or a core-only
system install) needs more than `ROCM_PATH`. hipcc is found, but device compilation fails inside
`cuda_wrappers/cmath` with `Could not find standard C++ header 'cmath'`, because ROCm's clang does
not pick up the distro gcc's libstdc++ headers on its own. Configure with:
```sh
ROCM=/path/to/_rocm_sdk_devel # the SDK root (the venv's site-packages/_rocm_sdk_devel)
@@ -108,11 +108,11 @@ cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
export LD_LIBRARY_PATH=$ROCM/lib:$LD_LIBRARY_PATH
```
`--gcc-install-dir` takes the distro gcc's directory (the installed gcc-15's; after a distro gcc
upgrade it must be repointed, and the configure cached in `build/CMakeCache.txt` reset with
`-c`). The device-lib path is where the SDK tree keeps `amdgcn/bitcode` (under `lib/llvm/` in a
userspace SDK, `$ROCM/amdgcn/bitcode` in a core system install). The flags are not needed for a
full `/opt/rocm` install, and `DOCKER.md`'s container sidesteps them.
`--gcc-install-dir` is the distro gcc's directory (gcc 15 in the example). After a gcc upgrade,
repoint it and reset the configure cached in `build/CMakeCache.txt` (`-c`). The device-lib path is
where the SDK keeps `amdgcn/bitcode`: under `lib/llvm/` in a userspace SDK, `$ROCM/amdgcn/bitcode`
in a core system install. A full `/opt/rocm` install needs none of these flags, and the container
in `DOCKER.md` avoids them.
### 1.3 Check that it works
@@ -368,7 +368,7 @@ planes, with the tokeniser and chat template.
**A recipe decides what is quantised**, in rules from weight names to quantisers. Without one,
every weight keeps the checkpoint's encoding, which suits a bf16 or block-fp8 checkpoint served at
its own precision. Flash-Next's four-bit experts need one:
its own precision (Qwen3.8-Flash-Next-FP8 included). Flash-Next's four-bit experts need one:
```sh
rad-convert /srv/models/Qwen/Qwen3.8-Flash-Next -o /srv/models/rad/flashnext-w4.rad \
@@ -835,6 +835,22 @@ for the gather (no libr4d) the table is read on the host: `vram` is refused, and
locked huge pages, which also needs a memlock limit that large (`--ulimit memlock=-1` in Docker,
`LimitMEMLOCK=infinity` under systemd).
`--ngram-placement ram=DIR` makes the pinned copy a file, `DIR/ngram-<id>.tab`, in a tmpfs, mapped
`MAP_SHARED` and pinned for the cards as `ram` pins it, so two engines on separate card sets
(`ROCR_VISIBLE_DEVICES`) hold one table in host memory. The first engine to start fills the file
from the container; a second finds it complete, checks samples of it against its own container and
only pins it. The `<id>` is a hash of the container's path, size and mtime and the table's place in
it, so a file never serves another model. A weight under 32 MiB the gather reads beside the table
(its scale) keeps a private pinned copy, since its file would be mostly header. The engine that
leaves last deletes the file, and one that leaves while another still holds it waits up to a second
for it, so two engines stopped together still remove it; after a crash a complete file stays and is
reused, or removed by hand. `DIR` must be a tmpfs (`/dev/shm`, or a tmpfs mounted for it, sized for
the table); `ram=DIR` needs the card gather kernel and the driver's SVM API, and is refused
otherwise. The driver counts a shared page against every process that pins it, so with two engines
the pinned total is twice the table: set `amdgpu.no_system_mem_limit=1` (the cap is RAM less 1/64
and 1.5 GiB) or the second pin can be refused. The kernel charges the tmpfs pages to the memory
cgroup of the engine that filled them.
**`--weights-disk-tier`** serves a model larger than the card and the host pool together, with every
step paced by the drive. A routed expert that fits neither lives only in the container. Before each
routed layer's first expert op, on every pass, the engine reads all that layer's on-disk experts into
@@ -1193,30 +1209,32 @@ snapshot lets it skip at least 256 tokens of that head, the request takes one wh
ends, at the cost of one chunk split, and the requests after it resume there. A conversation's
next turn has only its own earlier turn past that point, so it splits nothing extra.
A prefix hit answers exactly as the same prompt prefilled cold, by default
(`--prefix-resume exact`). A kernel can round a row differently at another chunk
length (the fp8 GEMM's split-K count is chosen from `M`, spec §17), so a hit that
recomputes its tail in other chunks than a cold prefill can flip a near-tie in
greedy text. The hit therefore resumes only where an idle server's cold prefill of
that prompt starts a chunk: every `--max-num-batched-tokens` tokens (rounded down
to the chunk quantum), or every `--checkpoint-interval` when that is smaller. A
prompt's tail snapshot is taken where its last chunk starts, a boundary the chunk
already ends on, so it costs a copy and no step. An exact repeat re-prefills the
cold run's last chunk; an appended turn, that chunk and what the turn added: up to
one chunk more than `--prefix-resume nearest`, which resumes at the deepest
snapshot or block and splits a prompt's last chunk at its last quantum boundary.
The interval must be a multiple of the chunk when it is larger; otherwise it is
rounded up, and startup says so:
**Where a hit resumes** (`--prefix-resume`). A kernel can round a row differently at another
chunk length (the fp8 GEMM's split-K count is chosen from `M`, spec §17), so a hit that recomputes
its tail in other chunks than a cold prefill can flip a near-tie in greedy text. Two modes:
- `exact` (the default): a hit answers exactly as the same prompt prefilled cold. It resumes only
where an idle server's cold prefill of that prompt starts a chunk: every
`--max-num-batched-tokens` tokens (rounded down to the chunk quantum), or every
`--checkpoint-interval` when that is smaller. A prompt's tail snapshot is taken where its last
chunk starts, a boundary the chunk already ends on, so it costs a copy and no step. An exact
repeat re-prefills the cold run's last chunk; an appended turn re-prefills that chunk and what
the turn added.
- `nearest`: a hit resumes at the deepest snapshot or block, and a prompt's tail snapshot is at
its last quantum boundary. A turn re-prefills up to one chunk less than under `exact`.
Under `exact` an interval larger than the chunk must be a multiple of it; otherwise it is rounded
up, and startup says so:
```
--checkpoint-interval 6144 resolves to 8192: --prefix-resume exact needs it a multiple of the
4096-token prefill chunk (--max-num-batched-tokens 4096) ...
```
It is an idle-server property, as greedy batching is: a prefill that shares its
steps with other requests or decode rows (`--busy-prefill-chunk`,
`--prefill-interleave`) is cut differently, and a request's own checkpoint
(`/v1/systemone`'s shared head) resumes where it was asked.
Exactness holds on an idle server, as greedy batching does: a prefill that shares its steps with
other requests or decode rows (`--busy-prefill-chunk`, `--prefill-interleave`) is cut
differently, and a request's own checkpoint (`/v1/systemone`'s shared head) resumes where it was
asked.
**One prefill sequence in two pieces.** At two ranks, on `qwen35_fp8` (and `qwen35_w8a8`, built
from it, where its norms do not write rotated int8 codes) and on `gemma3`'s MXFP4 trunk with the
@@ -1296,10 +1314,15 @@ head inside the target checkpoint, which needs no flag. `radiance --draft-model`
says so. Measure speculation by step time, not tokens per second.
A drafter with a sliding window over its own cache (DFlash2) keeps that cache outside the prefix
cache, so after a prefix hit it cannot draft until its window has slid past the hit, which on a
chat's follow-up turn is most of the reply. Such a hit is therefore ended one drafter window before
the end of the prompt, at a checkpoint, and the window is recomputed; the reply is the same. A hit
whose nearest checkpoint below that point would give back more than two windows is kept whole.
cache. Where a hit resumes from a window snapshot (a model whose sliding layers the cache does not
index and that keeps no linear state, as the Gemma 4 31B under gemma4_bf16; the 26B-A4B declares
its sliding layers full and takes no snapshot), the snapshot carries the drafter's window with the
trunk's, so the hit leaves it whole and it drafts from the first decoded token. Elsewhere (a
model with linear state, as Qwen3.8), after a prefix hit it could not draft until its window had
slid past the hit, which on a chat's follow-up turn is most of the reply. Such a hit is therefore
ended one drafter window before the end of the prompt, at a checkpoint, and the window is
recomputed; the reply is the same. A hit whose nearest checkpoint below that point would give back
more than two windows is kept whole. The startup line `draft floor` says which applies;
`radiance:draft_refills_total` counts the hits ended early and `radiance:draft_refill_tokens_total`
the tokens recomputed.
@@ -1332,14 +1355,31 @@ behind the packet processor's barrier bit, which saves most of the launch gap be
kernels. The bytes are the same. Plain decode measured slower with them, so they stay off there
and on every other model; the startup report's `chained launches` row says which and why.
**Draft trees.** Where the model's plugin measured a gain (the Gemma 4 31B with DFlash2: +7%
single-stream decode and +6-9% aggregate at 1-16 users on 4x R9700, +4% and +6-12% on two,
BetterBench with thinking off), a block drafter's proposals are verified as a tree: grown best-first
over the drafter's candidates, the deepest path the target agrees with is accepted, and its K and V
move into place. A tree changes no token, only how many drafts land a step; the startup report's
`draft trees` row says when it is on. Under a tree `--num-speculative-tokens` counts the tree's
nodes, grown over the block the drafter was trained at. A request with a grammar (`response_format`,
tools) speculates on a tree too: each row is masked against the grammar after its own ancestors.
`--draft-coupling on` samples one path, so a coupled drafter proposes the chain.
**A shorter block under load: `--draft-short-from N`.** A block drafter's block is paid for by
every drafting sequence, whatever each one verifies. At one sequence a long block pays; at many, its
drafter rows and its weaker first positions cost more than the extra drafts bring. A drafter that also
serves a shorter block declares it (PLUGIN.md §11); DFlash2 declares a block of 4 (3 drafts) wherever its
own is longer, on `qwen35_fp8` and `gemma3`. With `--draft-short-from N` the engine runs that short block
once N sequences decoded in the step just run, and the drafter's own block again only once the count
falls two below N, so a load wavering at N does not change the pass shape every step. `0`, the default,
never switches. Startup names what it will run:
own is longer, on `qwen35_fp8` and `gemma3`, and the Gemma 4 31B's block-16 DFlash2 drafter, as a tree of
15 nodes, a block of 8 (a 7-node tree over it). With `--draft-short-from N` the engine runs that short block
once N sequences decoded in the step just run, and the drafter's own block again once the count
falls two below N or to one sequence, where the long block pays. From N of 3 on, a load wavering at
N does not change the pass shape every step; at 2, a load between one and two sequences does, which
costs only the other shape's pass. `0` never
switches. `auto`, the default, never switches a chain and switches a tree drafter
from 2: a tree's nodes are verify rows every drafting sequence pays for, which a wide tree's extra nodes
repay at one sequence and not at many; it switches back at one decoding sequence. At the short block the
drafter grows a tree of its own over the shorter pass, at most `block - 1` nodes. Startup names what it
will run:
```
speculation: from 16 decoding sequences on, 'dflash2' runs its short block of 4 row(s), 3 token(s)
@@ -1572,6 +1612,17 @@ hit. Snapshots never take VRAM: each is copied to host memory after the step tha
back before the step that resumes from it. `/sessions` shows what is stored, where, and whether the
linear half is served.
On a model with sliding-window layers and no linear state (Gemma 3, and the Gemma 4 31B as gemma4_bf16
declares it), the cache does not
index the sliding layers, so a hit resumes only from a window snapshot, taken a block short of a
prompt's end, where the next turn's rendering still agrees. Under `--prefix-resume nearest` one is
taken at the end of every prompt of 528 tokens or more (with `--checkpoint-interval` under 512,
from that interval plus a block). Under `exact` it is taken at the start of the prompt's last
chunk, once that lies at least one checkpoint interval in, so a conversation whose prompts stay
under one prefill chunk reuses nothing there; serve such a model with `--prefix-resume nearest`
where short chats matter more than bit-identical hits. A shorter prompt is recomputed: its
prefill is cheap, and its snapshot would take a slot from a longer conversation.
**How many snapshots.** The snapshot store (`--checkpoint-slots`) is shared by every conversation,
running or not, and a conversation without a snapshot under its next prompt reuses nothing. With
`auto`, the default, each of `--max-num-seqs` gets what `--checkpoint-policy` keeps for one
@@ -1987,7 +2038,7 @@ by 0.002-0.003 nats.
| `--deterministic` | off | pin placement to the loader's plan, so the resident set cannot change under the heat engine |
| `--checkpoint-interval N` | 2048 | linear-attention state checkpoint interval, in tokens |
| `--prefill-span N` | 1 | checkpoint intervals one step may carry of a prefill alone in its step, from the prompt's second interval on; needs `--max-num-batched-tokens` of N intervals. Every other step is planned at the budget less the extra intervals, and the checkpoints inside a span are not written (§4.5) |
| `--checkpoint-slots N` | auto | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`, 144 MiB on Qwen3.8-27B; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`). `auto` gives each of `--max-num-seqs` what `--checkpoint-policy` keeps for a `--max-model-len` session plus one (10 at 200K tokens under geometric backoff), within an eighth of host memory and what the host can pin; a floor of 8 (or what the policy wants, if fewer) outranks `--host-headroom-mib`, which gives back exactly the shortfall down to 1 GiB rather than take the store to none, and the startup line says so. The startup line and the report say what it chose and why (§4.8). A full store retires its least recently used snapshot. A count is taken as given: a store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start |
| `--checkpoint-slots N` | auto | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`, 144 MiB on Qwen3.8-27B; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB, and with its DFlash2 drafter that drafter's 2048-token window too, 487 MiB). `auto` gives each of `--max-num-seqs` what `--checkpoint-policy` keeps for a `--max-model-len` session plus one (10 at 200K tokens under geometric backoff), within an eighth of host memory and what the host can pin; a floor of 8 (or what the policy wants, if fewer) outranks `--host-headroom-mib`, which gives back exactly the shortfall down to 1 GiB rather than take the store to none, and the startup line says so. The startup line and the report say what it chose and why (§4.8). A full store retires its least recently used snapshot. A count is taken as given: a store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start |
| `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` |
| `--prefix-resume MODE` | exact | `exact`: a prefix hit resumes only where an idle server's cold prefill of the prompt starts a chunk, and a prompt's tail snapshot is taken where its last chunk starts, so a hit answers bit-identically to a cold run; an interval past the chunk is rounded up to a multiple of it. `nearest`: the deepest snapshot or block, up to a chunk less re-prefilled a turn |
| `--no-prefix-cache` | prefix cache on | disable prefix caching |
@@ -2009,8 +2060,8 @@ by 0.002-0.003 nats.
|---|---|---|
| `--num-speculative-tokens N` | auto | speculative window; 0 disables. The ceiling under `--draft-window adaptive` |
| `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, serial draft heads only (§4.6) |
| `--draft-short-from N` | 0 | a block drafter that declares a shorter block runs it from N decoding sequences on, its own block again two below; 0 never (§4.6) |
| `--draft-coupling MODE` | off | `on`: a linear MTP drafter with a 2-bit candidate head (Qwen3.8-Flash-Next) samples each proposal from its reranked top-8 and the sampler maximally couples the target's draw to it. The output distribution is unchanged and a fixed seed yields other tokens than `off`. The head's law is taken at temperature 1, so it pays at high request temperatures and costs at low ones: on Flash-Next TP2 at 2x R9700, tokens per decode step +18% at temperature 1.0 and c1, +11% at 0.7 and c4, -4% at 0.3. Greedy rows are unchanged. A DFlash2 drafter (Qwen3.5/3.8) couples its candidate walk instead: each position is sampled from the softmax of the walk's own scores over its best eight candidates, at temperature `RADIANCE_DFLASH_Q_TEMP` (default 0.6, where acceptance peaked); on Qwen3.8-27B MXFP4 TP2 at 2x R9700 and request temperature 1, tokens per verify step +8% on held-out prompts at c4 (3.53 to 3.82) and decode +2..8% per stream at c1/c4. Any other drafter is refused at startup |
| `--draft-short-from N` | auto | a block drafter that declares a shorter block runs it from N decoding sequences on, its own block again two below or at one sequence; 0 never; auto never for a chain and 2 for a tree drafter, which then verifies the short block's nodes (§4.6) |
| `--draft-coupling MODE` | off | `on`: a linear MTP drafter with a 2-bit candidate head (Qwen3.8-Flash-Next) samples each proposal from its reranked top-8 and the sampler maximally couples the target's draw to it. The output distribution is unchanged and a fixed seed yields other tokens than `off`. The head's law is taken at temperature 1, so it pays at high request temperatures and costs at low ones: on Flash-Next TP2 at 2x R9700, tokens per decode step +18% at temperature 1.0 and c1, +11% at 0.7 and c4, -4% at 0.3. Greedy rows are unchanged. A DFlash2 drafter (Qwen3.5/3.8) couples its candidate walk instead: each position is sampled from the softmax of the walk's own scores over its best eight candidates, at temperature 0.6 (where acceptance peaked); on Qwen3.8-27B MXFP4 TP2 at 2x R9700 and request temperature 1, tokens per verify step +8% on held-out prompts at c4 (3.53 to 3.82) and decode +2..8% per stream at c1/c4. Any other drafter is refused at startup |
| `--draft-model PATH` | | not implemented: merge the drafter at convert time |
**Server**
@@ -2304,12 +2355,11 @@ returns the text as both `prompt` (vLLM) and `content` (llama-server).
completions and chat answer 501. One input is one vector and must fit one step
(`--max-num-batched-tokens`); a longer one is refused with `context_length_exceeded`.
nomic-embed-text-v2-moe is converted from its f32 checkpoint with `rad-convert <checkpoint dir>
nomic-embed-text-v2-moe converts from its f32 checkpoint with `rad-convert <checkpoint dir>
--recipe data/recipes/nomic-embed-v2-moe-bf16.recipe -o nomic-embed-v2-moe-bf16.rad` (959 MB);
the directory must contain `tokenizer.json`. The `search_query: ` and `search_document: ` prefixes
are the client's text and the engine adds neither; the checkpoint's prompt names work through
`prompt_name`. The checkpoint's shared `experts.bias` tensors are not applied and stay in the
checkpoint.
the directory must contain `tokenizer.json`. The engine adds neither the `search_query: ` nor the
`search_document: ` prefix: the client sends it, or names the checkpoint's prompt with
`prompt_name`. The checkpoint's shared `experts.bias` tensors are not applied.
```sh
# text, a batch of texts, or token ids
@@ -3592,7 +3642,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.13.0
I STARTUP REPORT -- radiance 1.14.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]
+31 -2
View File
@@ -464,7 +464,25 @@ at h128/gqa8 up to q_len 16 by reading each kv head for two query groups of 4 (a
then holds each kv head once). Since no host library declares the op, a plugin that asks for it
learns whether a card serves the geometry.
libref has no row for any of them, deliberately. An architecture asks for a fusion and declares
Tree verification (`rad_drafter_tree`, abi/rad_builder.h) adds one operand to both: the step's
`RadBatch::spec_parent`, `[rows]` i32.
| op | params | operands |
|---|---|---|
| `attn_paged_tree` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `prefill_fp8`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `spec_parent` |
| `attn_paged_qrow_tree` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `prefill_fp8`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `spec_parent` |
A row whose `spec_parent` is -2 is an ordinary causal row. Any other row is a node of its sequence's
verify block, and its entry names its parent by row within the sequence's rows (`cu_seqlens`), -1
for the block's first row, every parent before its child. Inside the block (keys from
`seqused - q_len` on) such a row sees itself and its ancestors only; before it, every key as an
ordinary row does, except that a window is measured from the block's first position plus the row's
depth, the position its token takes once its path is committed. Causal layers only. libref serves
`attn_paged_tree`; libr4d `attn_paged_qrow_tree` at h256/gqa2 on the split-KV decode kernel and at
every geometry of the windowed kernels, to 64 rows a block.
Of the ops above, libref serves only `attn_paged_tree`, which is not a fusion but `attn_paged`'s
tree form. It has no row for any of the fusions, deliberately. An architecture asks for a fusion and declares
the chain where it does not resolve (`rad_op_resolved`); a reference row would make it resolve
everywhere, so a model loaded without the serving library would resolve to the reference and be
refused at serve, instead of running the chain on libr4d or libavx. libr4d declares them with
@@ -2728,7 +2746,7 @@ greedy request's row (draw mode 0) keeps `dflash_select`'s tokens (`status = 0`)
another card, or a position whose eight cannot form a `Q`, takes the walk's argmax (`status = -1`)
and the ordinary verify. `Q_l` depends on the committed text and on `x_0 .. x_{l-1}`, never on the
verify, and is stored exactly, which is all the coupling needs to be lossless; `q_temp` (the
architecture's, `RADIANCE_DFLASH_Q_TEMP` on Qwen3.5/3.8) moves acceptance only. Each edge is eight
architecture's, 0.6 on Qwen3.5/3.8) moves acceptance only. Each edge is eight
partial `fmaf` chains over contiguous slices of the rank, added in order, so the device kernel and
the host oracle agree bit for bit.
@@ -3194,6 +3212,17 @@ candidates, and what enters the head from the trunk.
| op | params | operands |
|---|---|---|
| `dflash_select` | `M` `steps` `top_k` `rank` `n_vocab` `anchor_stride`/opt `dtype` | `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w → `tokens` |
| `dflash_tree` | `M` `steps` `top_k` `rank` `n_vocab` `anchor_stride`/opt `nodes` `temp`:f64/opt `dtype` | `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w → `tokens`, `parents` |
`dflash_tree` grows the same lattice into a tree of `nodes` nodes instead of walking one path
(`rad_drafter_tree`). Node 0 is the anchor at lattice position -1 with log probability 0. A node at
position l with token t has a child for every candidate c at l + 1 whose id is in the vocabulary,
scored as `dflash_select` scores c after t; with x = score / `temp` (default 1) over those
candidates, the child's log probability is its parent's plus x - logsumexp(x). Best-first: each
round takes the not-yet-taken child of a taken node with the largest log probability, ties to the
one pushed first (lower parent, then lower c), until `nodes` are taken. Taken node j (1-based, so
every parent comes before its child) is `tokens[s, j-1]`, and `parents[s, j-1]` its parent's node
index, 0 for the anchor. A frontier that runs dry pads with token 0 under the last node.
`dflash_conv` is the drafter's grouped convolution (coefficient add and every tap in one pass):
+4 -3
View File
@@ -388,9 +388,10 @@ says so with `RAD_ARCH_SERVES_IMPORTS(0)` (`qwen35_w8a8` does), and imports keep
- **A block drafter may serve a shorter block.** `rad_drafter_short_block(b, block)`, called once
after `rad_declare_drafter`, says the plugin declared its query pass at `block` rows a sequence as
well as at `RadDrafterDecl::block`, with the same anchor convention, so the core may stage a step
at either; the short block proposes `block - (RadDrafterDecl::block - depth)` tokens. The builder
refuses it without a block drafter, at or above the drafter's own block, and where it would
propose nothing. The engine runs it under `--draft-short-from` (GUIDE §4.6) and reads row `s` of
at either; the short block proposes `block - (RadDrafterDecl::block - depth)` tokens. A tree
drafter (`rad_drafter_tree`, called first) grows a tree of its own over the shorter pass, at most
`block - 1` nodes, and its short block needs only 2 rows. The builder refuses it without a block
drafter, at or above the drafter's own block, and where it would propose nothing. The engine runs it under `--draft-short-from` (GUIDE §4.6) and reads row `s` of
the proposals at `s * proposal_pitch`; a block drafter's `proposal_pitch` defaults to its
depth (a row holds the whole block's proposals and a short block fills its front) and is refused
below it. The pass's block is `n_tok / n_seq`; a block the plugin has no ops for should fail the
+5 -4
View File
@@ -191,10 +191,11 @@ drops blocks.
## Checking
There is deliberately no switch that forces dense attention above the bound, where it is not the
model the checkpoint was trained as. libref implements all five QSA ops — `ref_qsa_block_key`,
`ref_qsa_score`, `ref_qsa_select`, `ref_qsa_tail_store`, `ref_qsa_work` (`libref/ref_qsa.cpp`) — so
each device kernel has a row to compare against; what no oracle gives is the whole-subsystem
comparison, a dense run against a sparse one above the bound. Changes are checked with:
model the checkpoint was trained as. libref implements all five QSA ops (`ref_qsa_block_key` in
`libref/ref_attn.cpp`; `ref_qsa_score`, `ref_qsa_select`, `ref_qsa_tail_store` and `ref_qsa_work`
in `libref/ref_qsa.cpp`), so each device kernel has a row to compare against. No oracle gives the
whole-subsystem comparison, a dense run against a sparse one above the bound. Changes are checked
with:
- **`r4d_selftest` oracles**: `qsa_block_key` and `qsa_score` against f64 evaluations,
`qsa_work` and `qsa_tail_store` against a host walk of the batch, `qsa_select` against a host
+9
View File
@@ -974,3 +974,12 @@ scripts/mctools.sh && scripts/mcstream.sh
`tools/kbench-analysis.sh` produces the static- and dynamic-analysis fragment that
`rad-kbench --analysis` splices into its report. `tools/ops_doc_check.sh` is the `ops_doc` test: it
checks `docs/OPS.md` against the schemas the plugins declare.
`rad-chatparse` (built into the build's `bin/`) answers where a tool call goes wrong without loading
weights. `rad-chatparse --request REQ.json --rad MODEL.rad --reply R.txt` renders one OpenAI chat
request as the server would (the container's template or `--override-chat-template`,
`--chat-template-kwargs`, the plugin's declared reply format, or the template's own with
`--no-plugin`), then reads each reply file as the model's output: parsed whole, parsed through the
SSE stream as a client reassembles it, and run through the request's tool-call grammar. It prints one
JSON object; the exit status is 1 when the two parses disagree or the grammar refuses a token.
`--render-raw T.jinja --context CTX.json` renders a template with any context.
+7 -8
View File
@@ -9,14 +9,13 @@ All numbers: paired within-session windows, bar ≥0.5% + sign test, geometry
`--prefill-span 2 --tp-wire wht6 --placement all_vram` iq4r MoE unless stated.
Every "dead" row is a *measured* dead — the mechanism, not a guess.
Shorthand used in the table and the prose (glossed once, used everywhere):
`pp` prefill; `c1/c2/c8/c16` concurrency (live streams) 1/2/8/16; `M` rows in a collective
(batch tokens at a step, rows in a MoE launch); `I` `--checkpoint-interval`; `T` tokens
(`T<=25` at most 25 tokens); `ti8` the int8 peer wire (`--tp-wire wht6`'s coding); `FK` the
MoE fast band; `W4` the 4-bit weight format; `iq4r` the shipped MoE quantisation; `hc_write`
the fused all-reduce + residual-write row; `pp64K` a 64 K-token prefill; `QSA` the sparse
indexer (docs/QSA.md); `L0..L3` kill levels, defined under *Kill levels*; `W#`/`R#` the
experiment rows of this table.
Shorthand: `pp` prefill; `c1/c2/c8/c16` concurrency (live streams) 1/2/8/16; `M` rows in a
collective (batch tokens at a step, rows in a MoE launch); `I` `--checkpoint-interval`; `T` tokens
(`T<=25` at most 25 tokens); `ti8` the int8 peer wire (`--tp-wire wht6`'s coding); `FK` the MoE fast
band; `W4` the 4-bit weight format; `iq4r` the shipped MoE quantisation; `hc_write` the fused
all-reduce + residual-write row; `pp64K` a 64 K-token prefill; `QSA` the sparse indexer
(docs/QSA.md); `L0..L3` kill levels, defined under *Kill levels*; `W#`/`R#` the experiment rows of
this table.
## The table
-270
View File
@@ -1,270 +0,0 @@
# HYV3 W4 decode optimizations
These changes optimize the existing HYV3 path and shared asymmetric W4/W5 and signed-I4 expert
kernels. They do not change the canonical `.rad` weight encodings, precision, default split-K
selection, or speculative decoding settings.
## Scope and affected paths
| Change | Affected paths | What remains to measure |
| --- | --- | --- |
| Compact one-row W4/W5 epilogue | Callers of the asymmetric W4/W5 GEMM at one live row and a compatible tile; includes Gemma callers | Fresh whole-model W4/W5 comparisons outside HYV3 |
| BF16-to-F16 narrowing inside W4 GEMM | Non-rotated group-128 asymmetric W4 `LinearFP8` decode through 64 rows | Other models using this path; Gemma's separate a4 graph still keeps its cast |
| Fragment-tiled expert I4 and one-row register loads | Per-128-scale signed-I4 experts, including plain and Hadamard-rotated formats | Other models/recipes that actually use this encoding, plus prefill and TP regressions |
| Fused Q/K prologue and residual/shared-combine folding | HYV3's graph; TP2 keeps separate routed/shared reductions | Fresh TP2 whole-model A/B; other models affected by shared-kernel changes |
Subgroup-scaled codebooks retain their row-major packing. In particular, the served Flash-Next
W5DN64 recipe is not evidence for the per-128 I4 kernel: its routed experts use a different
subgroup-scaled path. No speedup is claimed for it or for any unmeasured model.
## Historical HYV3 measurements
These are earlier measurements of the original optimization branch, **not a benchmark of this
rebased PR**. They establish motivation only.
- One Radeon AI PRO R9700 (`gfx1201`), TP1, full-GPTQ W4 HYV3.
- BF16 KV, 65,536 maximum context, one sequence, 4,096 batched tokens, no drafter or launch cache.
- Matched 10,030-token prompt and 2,000 generated tokens, temperature zero; reported decode
medians are from three repetitions.
- The frozen request SHA-256 is
`e04af05fd7952b5c1e8a38927bb53ab8621ca3e90a2713285eb98122c849ed47`.
The first repetition was uncached; later repetitions reused a 16-token prefix.
- The frozen prompt repeatedly requests the word `alpha`, and the generated answer repeats it.
This is a narrow synthetic workload, not representative prose, code or tool-use throughput.
| Historical stage | Median decode tokens/s |
| --- | ---: |
| Initial model path | 90.290 |
| Fresh pre-packing control after earlier graph work | 95.392 |
| Coalesced per-128 I4 expert packing | 103.364 |
| Rebuilt cast-free graph | 111.922 |
| Final untuned optimization stack | 115.678 |
The frozen answer SHA-256 was
`caca914b1bced70b2f9d8bf32d476179f18cef456201b02f55f16b9863bedbf0` in every repetition.
That establishes parity for this answer, not numerical or semantic equivalence on arbitrary input. An intermediate 104.744 tokens/s
cast-fusion result used a stale architecture plugin and must not be used to quantify removal of
graph casts. A separate launch-cache experiment near 120.5 tokens/s changed reduction order and
is not part of this patch.
The earlier native-tool comparison was unmatched: the untuned stack scored 102/113 exact and
112/113 executable cases versus 105/113 and 113/113 in an older baseline. The matched release-tag
A/B below supersedes it for this PR validation: both arms scored 102/113 and 112/113, with identical
per-case results. This remains a small curated subset, not a broad quality test.
## Validation on the rebased optimization branch
The full-suite GPU, layout and reference results below were recorded with the candidate based on
merged main `2d2f638`. The PR was later rebased onto `d650eca` and then onto current `origin/main`
`96bc046`. The full unit, GPU and inference suites have not been rerun on that latest base. Its
`radiance` target remains blocked by the missing KV-stream headers noted below; focused validation
of the latest source is recorded separately here.
### Code-review follow-up on current main
The review found that removing the explicit BF16-to-F16 graph cast changed CPU/reference results for
BF16 values in F16's subnormal range. The host backends now explicitly narrow BF16 activations to
F16 before W4/W5 asymmetric GEMM, preserving the old cast semantics. This does not change the HIP
kernel path.
On the latest rebased source (`origin/main` `96bc046` plus this PR):
- Built the updated `libref`, `libavx`, and `rad-avx-check` host plugins, plus the complete `gfx1201`
`libr4d` HIP plugin and `r4d_selftest`. The full Radiance engine build is still blocked by the
missing upstream KV-stream headers.
- The new direct `libref` regression test passed 7 checks: BF16-subnormal W4 output matched the
explicit-F16 input byte-for-byte and produced BF16 `0x3900`.
- `rad-avx-check --op gemm_nt_q` passed 26 generated geometries and 46 hand-built cases at scalar,
AVX and AVX2 levels, with four-thread reruns byte-identical. This CPU exposes AVX2 but not AVX-512.
- Stored-layout parity passed 1,145 checks over 20 cases.
- On the authorized GPU, focused W4 checks passed 341/341, including finite and raw-bit BF16-to-F16
cast parity. The signed-I4/MoE `moe_gemm_w4a8` test had 647 passes, zero failures and 12 expected
skips for unsupported aligned prefill tiles above the 512-expert run-map limit (the harness exits
2 when skips occur).
- A short post-fix HYV3 full-GPTQ W4 compatibility smoke on the existing release-plus-PR deployment
build returned `42`; it was stopped afterward, the temporary port was free, and no serving route
was changed. That build does not include the updated CPU plugins, so this smoke is not evidence
for the CPU fix or a current-main A/B.
### Non-target model dispatch checks (Flash-Next and Qwen3.8-27B)
These graph-only checks used the local artifacts and the ABI-compatible release-plus-PR engine; the
engine exits after `declare`, before placing or loading model weights. The latest-source engine still
cannot be built because of the unrelated KV-stream integration gap.
- **Qwen3.8-Flash-Next IQ4R (QFN):** the graph declared 2,054 ops and contained 98
`moe_gemm_q` bands at `w4nl64a8h`; all resolved to the existing `libr4d` row
`moe_gemm_w4a8`. This shared row is selected for QFN, so its decode geometry was benchmarked below.
The new `moe_w4_rows_kernel` is not selected: QFN's W4NL64 format maps to `moe_gemm_launch<2>`,
while its dispatch is guarded by `if constexpr (W4 == 1)`. For W4NL64, the modified loader wrapper
takes its `W4 != 1` branch and calls the previous `w4_load_w` implementation.
- **Qwen3.8-27B MXFP4:** the graph declared 1,821 ops, with 329 MXFP4 `gemm_nt_q` bands (plus one
W2A8 band); it selected existing `gemm_mxfp4a8_*` rows. It had no `moe_gemm_q`, asymmetric W4 or
W5 bands. The PR's new expert-I4/W4/W5 paths are therefore not selected for this model; its
MXFP4 rows are unchanged.
No benchmark was needed for an untouched path.
For QFN's shared W4NL64 row, `r4d_selftest --perfmoe 1 12 512 10 23 --cold 256` was run three
times per arm on the same `gfx1201` device. It uses QFN's TP2 rank-0 gate/up and down widths, one
decode token, 512 experts, top-10 routing, and 23% pooled experts. Baseline is `origin/main`
`96bc046`; candidate is that base plus this PR. The decode-selected forms had matching output
hashes and no measurable regression:
| QFN W4NL64 decode projection | Baseline median | PR median | Change |
| --- | ---: | ---: | ---: |
| Gate/up, two-K-block decode form | 23.60 us | 23.50 us | -0.4% |
| Sorted down decode form | 17.10 us | 17.00 us | -0.6% |
This is an op-level microbenchmark with synthetic weights at the exact QFN geometry, not a
whole-model QFN performance or quality A/B. Logs: `/tmp/pr237-qfn-debug-graph.log`,
`/tmp/pr237-qfn-moebench-{candidate,baseline}-cold{1,2,3}.log`, and
`/tmp/pr237-qwen27-debug-graph.log`.
- Release and ASan/UBSan/leak architecture suites, including HYV3 TP1/TP2 graph checks: passed
before the base advance.
- `gfx1201` `libr4d`, `r4d_selftest`, and all three HYV3 plugins: compiled.
- Stored-layout parity: 1,145 checks over 20 cases passed, including independent canonical nibble
addresses, GPTQ and rotated experts, subgroup codebooks and unaffected dense formats.
- Reference arithmetic: 136,622 checks over 254 cases passed with the incomplete upstream
inventory/sweep cases excluded. The new exhaustive BF16-add/cast-chain case passed separately.
The unfiltered reference suite's three failed assertions were reproduced with unchanged upstream
test source: an operation-count mismatch and missing sweep geometry for `kv_store_streamed` and
`kv_resolve`.
- Full rebased GPU selftest on the designated last R9700 (`gfx1201`, UUID
`GPU-7f082536d27449f3`): 9,057 `ok` results, 194 skips, and two failing assertions in one
`hc_read_e4m3` test case at M=2048; overall exit 1. The same untouched HC-read test family
failed with the pre-follow-up baseline plugin at M=2048 and M=700 (the particular stream/form
varied). The PR does not change that kernel or test. This is not a clean full-suite pass.
- Focused GPU checks passed for `gemm_w4a16_asym_nt_m64`, `moe_gather_bf16`,
`qkv_norm_rope_kv_store_h128_bf16` (including byte parity to the split norm/RoPE/store chain),
and `rmsnorm_bf16`. The signed-I4 `moe_gemm_w4a8` case had no failures; its exit status was the
harness's intentional-skip status for unsupported large-expert aligned tiles. The full run also
exercised its HYV3 top-8 gate/up and down cases without failures.
The latest-source `radiance` target build stops at `ctx.cpp:6`, `kvbind.cpp:4`, `issue.cpp:22`,
and `tierexec.cpp:4`: the runtime includes `kvstream/bind.h`, `kvstream/stage.h` and
`kvstream/plan.h`, but current `main` has no engine-side `core/kvstream/` module. This blocks
building the matching ABI-30 HIP engine needed for whole-model tests. The older available GPU
engine is ABI 27 and refuses the ABI-30 plugin; the current-main host build has no HIP backend.
Accordingly, no fresh HYV3 or Qwen inference A/B ran.
The user's local Qwen `.rad` was inspected without downloading anything:
`/mnt/gostar_data/models/StillDeadcode/qwen3.8-27b-mxfp4/qwen3.8-27b-mxfp4.rad` is a 19.4 GB
`Qwen3_5ForConditionalGeneration` container with `n_expert=0` and group-32 MXFP4 weights (SHA-256
`a4908940c568f5f9dd24e88f46aefe9ac2ae07dfec023a2eaa1d14dcaa3df4f8`). Its graph-only dispatch check
found only unchanged MXFP4 rows, not this PR's asymmetric W4/W5 or per-128 I4 paths. A prior
release-tag compatibility smoke answered `42`; neither check is an affected-model A/B. The current-main
engine still cannot be built because the KV-stream sources are missing. No model was downloaded and
no llama-swap route was edited.
### Release-tag plus PR build experiment
To isolate the later mainline KV-stream integration, a temporary worktree was based on release tag
`v1.12.0`, then given the HYV3 model-support patch (from `32881da` to `79487d2`) and the PR #237
delta (`d650eca` to this PR head). One context conflict in `libr4d/r4d_layout.cpp` came from a
post-release MXFP4-gated wrapper absent from the tag; the resolution kept the release's unrelated
MXFP4 code and applied the PR's I4 layout changes. No changes were made to the published branch for
this experiment.
- Full Release host build: passed (694 targets).
- Full `gfx1201` HIP build: passed (809 targets).
- Focused `arch_test`, `chat_test`, `chatparse_test`, and `checkpoint_test`: 4/4 passed.
Follow-up validation used only the third R9700 (GPU index 2, UUID
`GPU-7f082536d27449f3`):
- `gemm_w4a16_asym_nt_m64`: 341 checks passed, zero failures or skips.
- `moe_gemm_w4a8`: 647 checks passed, zero failures, 12 expected skips for unsupported aligned
prefill tiles at 640 experts (the run-map limit is 512); HYV3 top-8 gate/up and down geometries
were exercised. The selftest exits 2 when skips are present.
- The release+PR server loaded the local full-GPTQ W4 HYV3 container at 4096 context on loopback
port 18100. `/health` was OK and a chat request asking for 6×7 returned `42`. The process was
stopped afterward and the port was confirmed free; no route was changed.
### Full-suite, performance and quality A/B (completed on the release-tag stack)
The full CTest suite on the release+HYV3-support+PR candidate passed **121/121** tests, including
83 unit tests and all 10 GPU-labelled tests. The full `r4d_selftest` passed on a standalone rerun
and again in the final complete suite. An earlier full-suite attempt had an intermittent
`hc_read_e4m3` assertion; the same untouched family also failed on the baseline run, while four
isolated baseline/candidate reruns passed 38/38 each. The final full-suite run was clean.
A matched TP1 full-GPTQ W4 A/B used the exact frozen 10,030-token prompt and 2,000-token decode
request (`e04af05f...`), on the third R9700, BF16 KV, one sequence, 65,536 context, 4,096 batched
tokens, and no launch tune or speculative decoding. The reference was release `v1.12.0` plus HYV3
model support; the candidate added only PR #237's delta. Each arm had three repetitions, with the
same 16-token prefix-cache behavior after the first run.
| Arm | Median decode tokens/s | Median prefill tokens/s | Answer SHA-256 |
| --- | ---: | ---: | --- |
| v1.12.0 + HYV3 support (baseline) | 76.567 | 7,876.292 | `caca914b...` |
| v1.12.0 + HYV3 support + PR #237 | 109.618 | 7,926.569 | `caca914b...` |
That is **+43.17% median decode throughput** and **+0.64% prefill throughput** on this narrow
synthetic workload; all six generated-answer hashes were identical. The speed result is specific
to this matched release-tag comparison, not a claim about other models or current-main performance.
Quality comparisons on the same two builds:
- Greedy output hashes matched **12/12** fixed probes.
- Teacher-forced evaluation on the frozen eight-document, 578-position corpus measured mean KL
`7.61e-8`, maximum KL `1.57e-6`, **100% top-1 agreement**, and identical PPL `2.875200`.
- The 113-case native-tool BFCL subset was identical row-for-row: **102/113** exact calls,
**112/113** execution successes, and zero API errors on both arms. This is a curated subset, not
broad capability evidence.
#### Same-build cross-card diagnostic
At the user's request, I reran the same candidate executable, `.rad` artifact, launch flags, and
three 2,000-token repetitions on two individual R9700s. The frozen 10,030-token benchmark used the
same per-repetition prefix scheme on both cards; no launch tune or drafter was enabled. The model
was loaded separately on each card, with no other Radiance process using either device.
| Device | Median decode tok/s | Median prefill tok/s | Answer SHA-256 |
| --- | ---: | ---: | --- |
| PCI `0000:06:00.0`, UUID `GPU-048200e09844fd51` | 118.380 | 8,077.674 | `caca914b...` |
| PCI `0000:0f:00.0`, UUID `GPU-7f082536d27449f3` | 109.834 | 8,011.282 | `caca914b...` |
The same candidate was **7.2% slower on the designated PCI `0f:00.0` card**. A fresh confirmation
on that card measured **110.311 tok/s**, within 0.44% of the initial 109.834 tok/s result. The older
115.678 tok/s untuned run was on PCI `06:00.0`, so the earlier 115-versus-109 comparison was
confounded by card/operating-point differences, not evidence that splitting the branch caused a
regression. All three R9700 UUIDs are configured for PPT0=210 W in
`/usr/local/sbin/gpu-power-caps`; its AMD cap loop runs before the separate NVIDIA stage where the
service fails. So a different *configured* cap is not established as the cause. Per-run live
cap/clock telemetry was not captured; card-specific boost, thermal/board behavior, or silicon
variation could still matter. PCIe bandwidth is not established as the cause. Raw-request repeats
that reused 10,000 cached prompt tokens are retained separately and excluded from this comparison.
Additional compatibility smokes using the same candidate build passed for the local Qwen4Exp W5
container (returned `42`; prompt-lookup drafted 6 tokens and accepted 1), Qwen Flash-Next IQ4R
(TP1 and TP2 launchers, answered `42`), Qwen3.8 27B MXFP4 (answered `42`), Breeze-TTS-2 (valid
24 kHz mono PCM), and HYV3 (answered `42`). The verified deployment build was moved intact to
`/mnt/gostar_data/radiance-builds/radiance-v1.12-hyv3-pr237/build-gfx1201`; all six local model
launchers were syntax-checked and updated to use it. The W5 launcher dropped a stale
`--draft-coupling on` option rejected by this container (it declares no linear drafter); its
six-token prompt-lookup setting remains. These are smoke tests, not matched performance/quality
results for those models. No model was downloaded and no llama-swap route was changed.
Logs, summaries and raw rows are under
`/mnt/gostar_data/radiance-calib/hyv3-pr-validation-20261025/pr237/` and
`/mnt/gostar_data/radiance-calib/hyv3-w4-round2-20261024/` (labels `release-v112-baseline` and
`release-v112-pr`).
## Integration caveat and scope of claims
The successful full builds, full test suite and A/B above use the release-tag stack because the
current-main source still lacks the engine-side `core/kvstream/` headers introduced by upstream
`486c933`; it therefore cannot produce the matching ABI-30 HIP engine. That unrelated upstream
build break remains outside this PR, so the A/B must not be described as a current-main-vs-PR run.
The PR is validated and ready for review against the buildable release-tag stack, but after the
upstream KV-stream integration is restored, current-main builds/tests should be rerun.
Performance and quality claims are limited to the HYV3 TP1 full-GPTQ W4 A/B above. The Qwen W5,
IQ4R and MXFP4 runs were compatibility smokes only; no broad speedup or quality claims are made for
other model families or formats. The native BFCL corpus is also a small safe subset, not a broad
quality benchmark.
The cold-weight diagnostics are `r4d_selftest --perfw4`, `--perfw4bf16`, `--perfbf16` and
`--perfhyv3moe`; see [libr4d/README.md](../../libr4d/README.md). Their byte/canonical checks and
shape-specific timings do not replace whole-model performance or quality comparisons.
+27 -23
View File
@@ -1,25 +1,27 @@
# DeepSeek-V4.1-Flash: a .rad straight from the release (no GGUF converter)
# DeepSeek-V4.1-Flash: a .rad from the release (no GGUF converter)
The official DeepSeek-V4.1-Flash release converts with `rad-convert` alone: no llama.cpp GGUF is
built as an intermediate, and no separate drafter directory is grafted. The pieces are in the tree:
built as an intermediate, and no separate drafter directory is grafted. The pieces below prepare
and convert the release. Serving the container needs the `deepseek41` architecture plugin, which
this tree does not include yet.
- `data/engram_tables.py` builds the Engram hash tables from the release's own `tokenizer.json` and
`config.json`, reimplementing the tokenizer's ByteLevel decode and the normaliser sequence
(NFKC, NFD, strip marks, lowercase, collapse spaces, sentinel) and the PCG64 multipliers and
prime buckets. Validated against HF `tokenizers`: 0 mismatched token ids of 129280, compressed
vocab 99092, the release's two Engram layers [1, 14]. It writes `engram-tables.safetensors`.
`config.json`. It reimplements the tokenizer's ByteLevel decode, the normaliser sequence (NFKC,
NFD, strip marks, lowercase, collapse spaces, sentinel), the PCG64 multipliers and the prime
buckets. Against HF `tokenizers`: 0 mismatched token ids of 129280, compressed vocab 99092, the
release's two Engram layers [1, 14]. It writes `engram-tables.safetensors`.
- `data/imatrix_merge.py` fuses the imatrix entries llama.cpp's converter writes split
(`ffn_gate_exps`, `ffn_up_exps`) into the plugin's fused `ffn_gate_up_*`, summing the two halves
(and `shexp`): 1184 entries carried through, 160 fused for 40 layers. IQ1_S refuses a fused
weight without one.
- `data/recipes/deepseek41-ud-iq1s.recipe` is the UD-IQ1_S per-tensor mix, as rules for libquant's
`ggml` quantiser, so the release converts to the same encodings the GGUF gives.
(and those of `shexp`): 1184 entries carried through, 160 fused for 40 layers. IQ1_S refuses a
fused weight without one.
- `data/recipes/deepseek41-ud-iq1s.recipe` is the UD-IQ1_S per-tensor mix as rules for libquant's
`ggml` quantiser, so the release converts to the same encodings the GGUF has.
- `rad-convert --chat-template FILE` bakes a template into the container's vocab section. The
release carries no `chat_template.jinja` and its `tokenizer_config.json` names none, so without
this flag an HF-direct container answers `/v1/chat/completions` with 501. Trailing newlines are
stripped as for a sibling template, and an unreadable or empty file is refused, not skipped.
release carries no `chat_template.jinja` and its `tokenizer_config.json` names none, so a
container converted without this flag answers `/v1/chat/completions` with 501. Trailing newlines
are stripped as for a sibling template, and an unreadable or empty file is refused.
## The three steps
## Conversion
```
# 1. the Engram tables, from the release's tokenizer (not a GGUF)
@@ -28,19 +30,21 @@ python3 data/engram_tables.py <HF release dir> engram-tables.safetensors
# 2. fuse the imatrix's split gate/up entries
python3 data/imatrix_merge.py imatrix_unsloth.gguf_file imatrix-merged.gguf
# 3. convert; the template is the model's own, baked into the container
# 3. convert, with a chat template for the model baked into the container
rad-convert <HF release dir> --add engram-tables.safetensors \
--recipe data/recipes/deepseek41-ud-iq1s.recipe \
--imatrix imatrix-merged.gguf --tokenizer <HF release dir>/tokenizer.json \
--chat-template chat_template.jinja -o deepseek-v4.1-flash-ud-iq1s.rad
```
Measured on the release (DeepSeek-V4.1-Flash-1017, fp8 with e8m0 per 32×32 blocks, MXFP4 experts):
plan 32701 weights / **251.07 GiB**, conversion **251.13 GiB in 2h11m** on this host, and the
container serves on 4× R9700 at TP4 with its DSpark metadata (block 5, 128 experts, targets
37/38/39) and Engram baked. Quality of the converted container, greedy, thinking off: HE 154/164 =
.939 (the native UD-IQ1_S reference .963, McNemar p = .125), GSM 194/200 = .970 (reference .960).
From DeepSeek-V4.1-Flash-1017 (fp8 with e8m0 scales per 32x32 block, MXFP4 experts) the plan is
32701 weights, 251.07 GiB, and the container 251.13 GiB. The `deepseek41` plugin serves it on 4x
R9700 at `--tp 4` with its DSpark metadata (block 5, 128 experts, targets 37/38/39) and the Engram
tables baked in. Quality, greedy, thinking off: HumanEval 154/164 = 0.939 (the native UD-IQ1_S
reference 0.963, McNemar p = 0.125), GSM 194/200 = 0.970 (reference 0.960).
Serving: nothing else is needed now that the template is baked. A container built before this flag
needed `--override-chat-template FILE` at serve time; the file has to be a Radiance-renderable
template (the release's own is; llama.cpp-only jinja such as `dict()` in a GGUF's template is not).
## Serving
A container converted with `--chat-template` needs no template at serve time. One converted
without it needs `--override-chat-template FILE`; the file must be a template radiance renders
(the release's own is; llama.cpp-only Jinja, such as `dict()` in a GGUF's template, is not).
+35 -2
View File
@@ -246,12 +246,17 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
return RAD_OK;
}
/* attn_paged_tree's ninth operand, `spec_parent` (rad_drafter_tree), is read here too, as libref
* reads it: -2 an ordinary causal row; else the row's parent's index within its sequence's rows
* (-1 for the block's first). Inside the block such a row sees itself and its ancestors only, and
* its window is measured from the block's first position plus its depth. */
AVX_KERNEL(attn_paged) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
const RadTensor* kdes = rad_arg_in(a, 4);
const RadTensor* vdes = rad_arg_in(a, 5);
const RadTensor* cus = rad_arg_in(a, 6);
const RadTensor* tpar = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr;
if (!q->data || !kv->data || !bt->data || !su->data || !o->data) return RAD_E_INVAL;
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
@@ -294,7 +299,7 @@ AVX_KERNEL(attn_paged) {
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
/* Uniform long queries take the panel form; ragged (cus) inputs stay here. */
if (!cus && q_len >= 32) return attn_paged_prefill(a, stream);
if (!cus && q_len >= 32 && !tpar) return attn_paged_prefill(a, stream);
/* Work units are (token, kv-head) groups: the gqa query rows of a group share every key and
* value row, so each is widened once for gqa dots/axpys. Per-row arithmetic is unchanged. */
const int64_t total = rows * kv_heads;
@@ -317,6 +322,25 @@ AVX_KERNEL(attn_paged) {
if (qlen <= 0) continue;
const int64_t ctx = ldi(su, offlin(su, s));
const int64_t pos = ctx - qlen + i;
/* A tree row: its ancestors inside the block (a bit per row) and its depth. */
const int64_t base = ctx - qlen;
bool tree = false;
uint64_t tmask = 0;
int64_t tdep = 0;
if (tpar) {
int64_t pj = ldi(tpar, offlin(tpar, tok));
if (pj != -2 && i < 64) {
tree = true;
tmask = 1ull << i;
for (int64_t at = i; pj >= 0 && pj < at; ) {
tmask |= 1ull << pj;
++tdep;
at = pj;
pj = ldi(tpar, offlin(tpar, tok - i + pj));
}
}
}
const int64_t wpos = tree ? base + tdep : pos;
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
@@ -393,8 +417,9 @@ AVX_KERNEL(attn_paged) {
for (int64_t j = 0; j < ctx; ++j) {
if (causal ? (j > pos) : (j >= ctx)) continue;
if (tree && j >= base && !((tmask >> (j - base)) & 1)) continue;
if (window > 0) {
const int64_t d = pos - j;
const int64_t d = wpos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) continue;
}
if (j / block_size >= max_blocks) break; /* past the block table's width */
@@ -721,6 +746,14 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
}
#endif
/* attn_paged with its tree operand present, which attn_paged reads (see there). Refused without
* one, and for a non-causal layer. */
AVX_KERNEL(attn_paged_tree) {
if (a->n_t < 9 || !rad_arg_in(a, 8)) return RAD_E_INVAL;
if (p_int(a, "causal", 1) != 1) return RAD_E_UNSUPPORTED;
return AVX_FN(avx_attn_paged)(a, stream);
}
/* ------------------------------------------------------------------ attn_dense */
/* Unpaged, unquantised attention (vision towers): `cu_seqlens` bounds one image or attention
* window per entry, so a whole batch is one launch. `causal` is a parameter so a dense
+14
View File
@@ -347,6 +347,13 @@ std::vector<Case> build_cases() {
HI("block_size", 16), HI("causal", 1), HI("window", window),
HS("q_dtype", dt), HS("kv_dtype", dt), HF("scale", 0.125),
HI("max_ctx", 128), HI("n_head", 8), HI("max_seqs", 2) });
/* The tree form over the same shapes (its described parents are ordinary rows, -2). */
for (const char* dt : { "f32", "bf16" })
for (int qlen : { 1, 17 })
add("attn_paged_tree", { HI("q_len", qlen), HI("head_dim", 64), HI("gqa", 4),
HI("block_size", 16), HI("causal", 1), HI("window", 8),
HS("q_dtype", dt), HS("kv_dtype", dt), HF("scale", 0.125),
HI("max_ctx", 128), HI("n_head", 8), HI("max_seqs", 2) });
for (const char* dt : { "f32", "bf16" })
for (int causal : { 0, 1 })
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
@@ -751,6 +758,13 @@ std::vector<Case> build_cases() {
HI("n_vocab", 300), HI("anchor_stride", 1), HS("dtype", "bf16") });
add("dflash_select", { HI("M", 5), HI("steps", 3), HI("top_k", 12), HI("rank", 37),
HI("n_vocab", 97), HI("anchor_stride", 2), HS("dtype", "bf16") });
/* The same lattices grown into trees: more nodes than steps, and fewer. */
add("dflash_tree", { HI("M", 3), HI("steps", 4), HI("top_k", 8), HI("rank", 64),
HI("n_vocab", 300), HI("anchor_stride", 1), HI("nodes", 6),
HS("dtype", "bf16") });
add("dflash_tree", { HI("M", 5), HI("steps", 3), HI("top_k", 12), HI("rank", 37),
HI("n_vocab", 97), HI("anchor_stride", 2), HI("nodes", 2),
HS("dtype", "bf16") });
/* DFlash2's convolution: the 27B drafter's form (2 taps, groups of 16) over a narrower row,
* then groups that are no multiple of a vector, three taps and a one-row block. f16 rows take
* the path through f32 copies, bf16 and f32 the fused one. */
+1 -1
View File
@@ -4063,7 +4063,7 @@ void planes_cases(const Check& ck, std::vector<Hand>& hs, Broken& broken) {
static const Grid kGrids[] = {
{ "w2a8", RAD_U2, 0, 1 }, { "w4a8_asym", RAD_U4, 0, 1 },
{ "w4a16_asym", RAD_U4, 2, 1 }, { "w4a16_asym", RAD_U4, 2, 2 },
{ "w4a16_asym", RAD_U4, 3, 1 }, /* BF16 input, oracle is the former F16 cast */
{ "w4a16_asym", RAD_U4, 3, 1 }, /* BF16 input, narrowed to F16 as the cast kernel does */
{ "w5a16", RAD_U5, 2, 1 }, { "w5a16", RAD_U5, 2, 3 },
{ "w4a8i8_asym", RAD_U4, 1, 1 }, { "w4a8i8_asym", RAD_U4, 1, 2 },
{ "w5a8i8", RAD_U5, 1, 1 }, { "w5a8i8", RAD_U5, 1, 3 },
+2 -2
View File
@@ -840,8 +840,8 @@ static int gemm_zp(const avxp::ZpGrid& zg, const RadTensor* A, const RadTensor*
if (A->rank >= 2 && A->shape[A->rank - 1] != acols) return RAD_E_SHAPE;
int64_t ars = row_stride(A, acols), acs = laststride(A);
/* The W4 decode graph supplies BF16 directly so HIP can narrow on load. Keep the previous
* explicit BF16->F16 cast semantics for CPU execution before entering the F16 activation grid. */
/* A BF16 activation (the W4 decode graph's, which the card narrows on load) is narrowed to F16
* first, with the cast kernel's rounding, so the F16 grid sees what the card's GEMM sees. */
std::vector<uint16_t> narrowed;
RadTensor a_f16{};
if (zg.act == ZP_F16 && A->dtype == RAD_BF16) {
+2 -1
View File
@@ -143,7 +143,8 @@ int avx_par_force(int threads);
X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \
X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \
X(sample_merge_topk) X(sample_mask) X(sample_pick) X(sample_argmax) \
X(sample_ngram_ban) X(sample_logprobs) X(dflash_select) X(dflash_conv)
X(sample_ngram_ban) X(sample_logprobs) X(dflash_select) X(dflash_conv) \
X(dflash_tree) X(attn_paged_tree)
/* One ISA level's table: one member per op, in AVX_OP_LIST order. A missing definition is a link
* error from that level's avx_table.cpp object. */
+29
View File
@@ -294,6 +294,11 @@ static const RadOperandSpec oAttnPaged[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), OUT("out")
};
/* attn_paged with a tree verify's parents (RadBatch::spec_parent, rad_drafter_tree). */
static const RadOperandSpec oAttnPagedTree[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
OPD_O("k_descale"), OPD_O("v_descale"), OPD_O("cu_seqlens"), OUT("out"), OPD("spec_parent")
};
static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) };
static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
@@ -877,6 +882,13 @@ static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_I
static const RadOperandSpec oDflashSelect[] = { OPD("cand"), OPD("unary"), OPD_O("hp"),
OPD("anchor"), WGT("pred"), WGT("succ"),
OUT("tokens") };
static const RadParamSpec pDflashTree[] = { P_INT("M"), P_INT("steps"), P_INT("top_k"),
P_INT("rank"), P_INT("n_vocab"),
P_INTO("anchor_stride"), P_INT("nodes"),
P_F64O("temp"), P_STR("dtype") };
static const RadOperandSpec oDflashTree[] = { OPD("cand"), OPD("unary"), OPD_O("hp"),
OPD("anchor"), WGT("pred"), WGT("succ"),
OUT("tokens"), OUT("parents") };
/* DFlash2's grouped convolution, as libref declares it. */
static const RadParamSpec pDflashConv[] = { P_INT("T"), P_INT("hidden_size"), P_INT("taps"),
P_INT("group_size"), P_INT("NG"), P_INT("block_size"),
@@ -1052,6 +1064,11 @@ static const RadOpSchema kSchemas[] = {
{ "attn_paged", ARR(pAttnPaged), ARR(oAttnPaged),
"paged causal / sliding-window attention, any query length, online-softmax so one pass over the "
"cache suffices." },
{ "attn_paged_tree", ARR(pAttnPaged), ARR(oAttnPagedTree),
"attn_paged over a tree verify (rad_drafter_tree): spec_parent is -2 for an ordinary causal row, "
"else the row's parent's index within its sequence's rows (-1 for the block's first). Inside the "
"block such a row sees itself and its ancestors only; its window is measured from the block's "
"first position plus its depth." },
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense),
"dense varlen attention over cu_seqlens; a non-causal window may reach further right "
"(`window_right`)." },
@@ -1385,6 +1402,11 @@ static const RadOpSchema kSchemas[] = {
"a greedy walk over a candidate lattice: score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * "
"hp[l][r] * succ[cand[l, c]][r], pid(0) the anchor and pid(l) the walk's own previous pick. "
"`hp` absent is a plane of ones." },
{ "dflash_tree", ARR(pDflashTree), ARR(oDflashTree),
"dflash_select's lattice grown best-first into a tree of `nodes` nodes: each taken node's "
"children are the valid candidates at the next position with log probability parent + "
"log_softmax(score / temp); each round takes the largest untaken child, ties to the first "
"pushed. tokens and parents list the taken nodes in order, a parent as its node index." },
};
/* ================================================================== the kernel table
@@ -1668,6 +1690,10 @@ ROW("avx_attn_paged", "attn_paged", "attn",
"paged causal / sliding-window attention, any query length",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(attn_paged)),
ROW("avx_attn_paged_tree", "attn_paged_tree", "attn",
"paged causal / sliding-window attention with a tree verify block (spec_parent)",
"any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales; i32 parents",
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(attn_paged_tree)),
SIMPLE("avx_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT,
L(attn_dense)),
SIMPLE("avx_attn_cross", "attn_cross", "attn",
@@ -1969,6 +1995,9 @@ SIMPLE("avx_dflash_conv", "dflash_conv", "draft",
SIMPLE("avx_dflash_select", "dflash_select", "draft",
"DFlash2's greedy walk over the candidate lattice",
"i32 candidates and tokens, float unary and codebooks", L(dflash_select)),
SIMPLE("avx_dflash_tree", "dflash_tree", "draft",
"DFlash2's candidate lattice grown best-first into a tree",
"i32 candidates, tokens and parents, float unary and codebooks", L(dflash_tree)),
};
/* ================================================================== plugin exports */
+102
View File
@@ -29,6 +29,7 @@
#include "rad_sample.h"
#include <cfloat>
#include <cmath>
#include <vector>
using namespace avx;
@@ -923,3 +924,104 @@ AVX_KERNEL(dflash_select) {
}
return RAD_OK;
}
/* ================================================================== dflash_tree
*
* The same lattice grown best-first into a tree of `nodes` nodes (rad_drafter_tree), libref's rule
* (ref_quant.cpp, ref_dflash_tree): a taken node's children are the valid candidates at the next
* position, scored as dflash_select scores them after the node's token, each with log probability
* parent + log_softmax(score / temp) over them; each round takes the largest untaken child, ties to
* the one pushed first. Parallel over sequences. */
AVX_KERNEL(dflash_tree) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *cand = &a->t[0], *un = &a->t[1], *anc = &a->t[3];
const RadTensor *pred = &a->t[4], *succ = &a->t[5], *out = &a->t[6], *par = &a->t[7];
const RadTensor* hp = rad_arg_in(a, 2);
if (!cand->data || !un->data || !anc->data || !pred->data || !succ->data || !out->data ||
!par->data)
return RAD_E_INVAL;
const int64_t steps = p_int(a, "steps", 0);
const int64_t K = p_int(a, "top_k", 0);
const int64_t M = steps > 0 && K > 0
? band_rows(numel(cand) / (steps * K), p_int(a, "M", 0)) : 0;
const int64_t R = p_int(a, "rank", pred->rank >= 2 ? pred->shape[pred->rank - 1] : 0);
const int64_t nv = p_int(a, "n_vocab", pred->rank >= 2 ? pred->shape[pred->rank - 2] : 0);
const int64_t astr = p_int(a, "anchor_stride", 1);
const int64_t N = p_int(a, "nodes", steps);
const float temp = p_f32(a, "temp", 1.0f);
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0 || N <= 0 ||
!(temp > 0.0f))
return RAD_E_SHAPE;
if (numel(un) < M * steps * K) return RAD_E_SHAPE;
if (numel(anc) < (M - 1) * astr + 1 || numel(out) < M * N || numel(par) < M * N)
return RAD_E_SHAPE;
if (numel(pred) < nv * R || numel(succ) < nv * R) return RAD_E_SHAPE;
if (hp && numel(hp) < M * steps * R) return RAD_E_SHAPE;
const int64_t cs = laststride(cand), us = laststride(un), os = laststride(out);
const int64_t pps = laststride(par);
AVX_PARALLEL_FOR_IF(M * N * K * R >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
struct Node { int64_t l, tok, parent; float lp; };
struct Kid { float lp; int64_t parent, l, tok; bool taken; };
std::vector<Node> sel;
std::vector<Kid> front;
std::vector<float> ax((size_t)R), rv((size_t)R), hv((size_t)R), x((size_t)K);
sel.push_back({ -1, ldi(anc, offlin(anc, m * astr)), -1, 0.0f });
auto expand = [&](int64_t n) {
const Node nd = sel[(size_t)n];
const int64_t l = nd.l + 1;
if (l >= steps) return;
const int64_t r = m * steps + l;
const int64_t cb = rowoff(cand, r, K), ub = rowoff(un, r, K);
const bool ok = nd.tok >= 0 && nd.tok < nv;
const float* pv = ok ? in_row(pred, rowoff(pred, nd.tok, R), R, rv.data()) : nullptr;
const float* hw = hp ? in_row(hp, rowoff(hp, r, R), R, hv.data()) : nullptr;
for (int64_t i = 0; i < R; ++i)
ax[(size_t)i] = (ok ? pv[i] : 0.0f) * (hp ? hw[i] : 1.0f);
float mx = -INFINITY;
for (int64_t c = 0; c < K; ++c) {
const int64_t tok = ld_int_dt(cand->dtype, cand->data, cb + c * cs);
float sc = ldt(un, ub + c * us);
const bool valid = tok >= 0 && tok < nv;
if (valid)
sc += dot_r(ax.data(), in_row(succ, rowoff(succ, tok, R), R, rv.data()), R);
x[(size_t)c] = valid ? sc / temp : -INFINITY;
if (x[(size_t)c] > mx) mx = x[(size_t)c];
}
if (mx == -INFINITY) return;
float sum = 0.0f;
for (int64_t c = 0; c < K; ++c)
if (x[(size_t)c] > -INFINITY) sum += std::exp(x[(size_t)c] - mx);
const float lse = mx + std::log(sum);
for (int64_t c = 0; c < K; ++c) {
if (!(x[(size_t)c] > -INFINITY)) continue;
front.push_back({ nd.lp + (x[(size_t)c] - lse), n, l,
ld_int_dt(cand->dtype, cand->data, cb + c * cs), false });
}
};
expand(0);
for (int64_t j = 1; j <= N; ++j) {
int64_t best = -1;
for (size_t f = 0; f < front.size(); ++f)
if (!front[f].taken && (best < 0 || front[f].lp > front[(size_t)best].lp))
best = (int64_t)f;
if (best < 0) {
sel.push_back({ steps, 0, (int64_t)sel.size() - 1, -INFINITY });
} else {
Kid& k = front[(size_t)best];
k.taken = true;
sel.push_back({ k.l, k.tok, k.parent, k.lp });
if (j < N) expand((int64_t)sel.size() - 1);
}
const Node& nd = sel.back();
st_int_dt(out->dtype, out->data, rowoff(out, m, N) + (j - 1) * os, nd.tok);
st_int_dt(par->dtype, par->data, rowoff(par, m, N) + (j - 1) * pps, nd.parent);
}
}
return RAD_OK;
}
+35 -45
View File
@@ -1,14 +1,12 @@
# libr3d serves RDNA3 only, declared here and nowhere else. Its kernels rely on wave32 and on
# instructions RDNA3 has: v_dot2acc_f32_f16 for the matrix work, v_cvt_pkrtz_f16_f32, DPP16 and
# v_permlanex16. They do not use the WMMA fragment layouts (RDNA3's 16x16x16 wave-matrix family is
# a re-tile of the dot2 lane map, not a drop-in) or gfx12-only instructions such as
# global_load_tr_b128, and they decode every quantised weight in software: the lane map, not a
# missing instruction, is the reason.
# libr3d serves RDNA3 only; this file is the one place that says so. Its kernels rely on wave32 and
# on RDNA3 instructions: v_dot2acc_f32_f16 for the matrix work, v_cvt_pkrtz_f16_f32, DPP16 and
# v_permlanex16. They do not use the WMMA fragment layouts (RDNA3's 16x16x16 wave-matrix family
# needs a different lane map than dot2) or gfx12-only instructions such as global_load_tr_b128,
# and they decode every quantised weight in software because of that lane map.
#
# A build targeting other cards skips libr3d. The engine then has no device kernel library for that
# card and refuses ops only a reference library implements, unless
# --debug-accept-reference-kernels is passed (spec §17). The supported fix is a kernel library for
# that card; libr4d is that library for gfx12 and libr3d is it for gfx11.
# A build targeting other cards skips libr3d. Without a device kernel library the engine refuses ops
# only a reference library implements, unless --debug-accept-reference-kernels is passed (spec §17).
# libr4d is the kernel library for gfx12, libr3d for gfx11.
#
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S libr3d -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`, naming the HIP compiler as for
@@ -20,11 +18,11 @@ if(NOT COMMAND rad_add_plugin)
rad_plugin_defaults()
endif()
# `^gfx11` is the family, not a chip: gfx1100, gfx1101, gfx1102, gfx1103, gfx1150, gfx1151 and the
# family target `gfx11-generic` all take these kernels, exactly as `^gfx12` covers RDNA4 for libr4d.
# The RDNA3 cards differ in CU count and clock, never in the instructions these kernels issue, so
# one code object per family serves the lot; a build that lists both a chip and the family gets
# both, and the engine picks the chip's object first (docs/PLUGIN.md §10).
# `^gfx11` matches the family: gfx1100, gfx1101, gfx1102, gfx1103, gfx1150, gfx1151 and
# `gfx11-generic`, as `^gfx12` does for libr4d. The RDNA3 chips differ in CU count and clock, not in
# the instructions these kernels issue, so one code object per family serves them all. A build
# listing both a chip and the family gets both, and the engine prefers the chip's object
# (docs/PLUGIN.md §10).
rad_plugin_gpu_targets(R3D_GPU_TARGETS "^gfx11")
if(NOT R3D_GPU_TARGETS)
message(STATUS
@@ -32,16 +30,15 @@ if(NOT R3D_GPU_TARGETS)
return()
endif()
# R3D_UNITS is the definitive list of libr3d's device translation units, as "unit|extra flags".
# R3D_UNITS lists libr3d's device translation units, as "unit|extra flags".
#
# Every unit is compiled -ffp-contract=off, which rad_hipify puts on all HIP sources. It is not a
# style preference: libref accumulates in f32 with no FMA and no reassociation (ref_common.h), and
# a contracted device kernel disagrees with the oracle it is checked against. It also keeps the
# instruction counts quoted in kernel comments true.
# Every unit is compiled -ffp-contract=off (rad_hipify sets it on all HIP sources). libref
# accumulates in f32 with no FMA and no reassociation (ref_common.h), and a contracted kernel would
# disagree with that oracle. It also keeps the instruction counts quoted in kernel comments true.
# Kernels and libr3d's declaration (row table, operand descriptions) share one directory. There is
# no launch adapter: every entry point takes `(const RadArgs*, RadStream)` and sits beside its
# kernel. The plugin links rad_abi only, like one written out of tree.
# Kernels and the declaration (row table, operand descriptions) share one directory. Every entry
# point takes `(const RadArgs*, RadStream)` and sits beside its kernel. The plugin links rad_abi
# only, like an out-of-tree plugin.
set(R3D_UNITS
# The model's small ops, one workgroup per row: rmsnorm, layernorm, the binary and unary element
@@ -49,19 +46,19 @@ set(R3D_UNITS
# kv_store. This is the set the engine refuses on a card with no device kernel library.
"r3d_model_bf16|"
# The sampler's pre-filters: penalties, DRY, the n-gram ban, the bitmask, and the logprobs
# summary, which reads the logits plane once where the reference reads it three.
# summary, which reads the logits plane once (the reference reads it three times).
"r3d_sample_pre_f32|"
# The speculative decoder's accept step: a walk over the draft block's candidate lattice, which is
# a gather out of two codebooks rather than arithmetic.
"r3d_dflash_f32|"
# The gated MLP band: GEMM, gate and output quantiser in one launch, so the [M,N] intermediate the
# unfused chain writes and re-reads never exists.
# The gated MLP band: GEMM, gate and output quantiser in one launch, so the [M,N] intermediate
# is never written to memory.
"r3d_gemm_fp8a8_gated|"
# The vocab projection at decode: U2 codes, int8 activations, a joined scale+zero operand.
"r3d_gemm_nt_q_w2a8|"
# The vocabulary projection at both heights: the head streamed for M <= 16, tiled above it.
"r3d_vocab_bf16|"
# The quantised GEMM at prefill heights: the 176 bands a forward pass ran on the CPU.
# The quantised GEMM at prefill heights.
"r3d_gemm_fp8a8_tiled|"
# The OCP-MXFP4 weight against the fp8 activation, both heights: e2m1 codes with one e8m0 scale
# per 32 of K, the block's partials scaled at the block boundary.
@@ -77,18 +74,14 @@ set(R3D_UNITS
# Activation quantisation: per-(row, group) symmetric E4M3 and int8, the gated form that
# quantises a silu-gated pair, and the dequantise that reads a container's own quantised weights.
"r3d_quant_fp8|"
# The skinny bf16 GEMM, M <= 16: one output element a lane, k ascending, so the accumulation order
# is libref's. The decode GEMM -- the op a token is made of.
# The skinny bf16 GEMM for decode, M <= 16: one output element a lane, k ascending, so the
# accumulation order is libref's.
"r3d_gemm_bf16_nt_m16|"
# The same shape over a block-scaled fp8 weight, decoded to f16 exactly (E4M3's four exponent bits
# and three mantissa bits are a subset of f16's), and over int8 codes.
"r3d_gemm_fp8a16_nt_m1|"
# Landing next, in the same shape as libr4d's: the prefill GEMM (an 8x8 tile a wave over LDS, the
# same dot2 inner product), paged causal attention (the decode leg split-KV, the prefill leg a
# query tile a workgroup, bf16 or fp8 KV), the vocab (logits as a GEMM over the embedding, the row
# top-k, the cross-rank top-1) and the sampler's stages. Their rows are not in r3d_rows.cpp yet,
# because a row naming an entry point that is not in the library is an undefined symbol and the
# plugin would fail to load, taking every other row with it.
# A row in r3d_rows.cpp must name an entry point defined by one of these units: an undefined
# symbol makes the whole plugin fail to load.
)
set(R3D_SRC "")
@@ -110,12 +103,11 @@ foreach(u ${R3D_UNITS})
list(APPEND R3D_SRC "${src}")
endforeach()
# The host sources are declaration only: the row table, the operand descriptions and the fusion
# claims. They are pure host C++ that includes neither r3d.h nor hip_runtime.h, so these tables
# compile and can be inspected without ROCm. libr3d has no layout source: nothing it serves is
# repacked, because a dot2 GEMM reads a weight in the order it is stored (see r3d_rows.cpp).
# r3d_fuse.cpp joins the list with the first fused row: a `replaces` chain with no row naming it
# would be dead code, and the fused rmsnorm-then-quant kernel is the first one worth its bytes.
# The host sources are declaration only: the row table and the operand descriptions. They are pure
# host C++ that includes neither r3d.h nor hip_runtime.h, so the tables compile and can be inspected
# without ROCm. libr3d has no layout source: nothing it serves is repacked, because a dot2 GEMM
# reads a weight in the order it is stored (see r3d_rows.cpp). There is no fusion source because
# no fused row exists.
set(R3D_DECLARATION r3d_rows.cpp r3d_shapes.cpp)
rad_add_plugin(libr3d kernels
@@ -137,14 +129,12 @@ add_executable(r3d_selftest ${CMAKE_CURRENT_SOURCE_DIR}/r3d_selftest.cpp)
# Links the HIP runtime to allocate the device buffers it feeds the kernels.
target_link_libraries(r3d_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME})
target_include_directories(r3d_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
# The device phase of the selftest -- the per-row launch -- is built only when the HIP runtime is
# there, which in this plugin's build it always is.
# The selftest's device phase (the per-row launch) needs the HIP runtime, which this build has.
target_compile_definitions(r3d_selftest PRIVATE RAD_HAVE_HIP)
set_target_properties(r3d_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# Installed beside the tools, so the image can run the rows' own card checks without a build tree:
# r3d_selftest <home>/kernels/libr3d.so [--case <row>]
install(TARGETS r3d_selftest RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
# C++17, the standard every radiance plugin builds device code at: it is what the tree's kernels are
# written against and what the cost figures assume.
# C++17, the standard all radiance plugins build device code with.
set_target_properties(libr3d PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON)
+693 -1028
View File
File diff suppressed because it is too large. Load diff
+109 -145
View File
@@ -1,23 +1,22 @@
/* r3d.h -- the entry points libr3d exports, and the launchers behind them.
*
* Two layers, in every unit, as in libr4d:
* Every unit has two layers, as in libr4d:
*
* The launcher (`r3d_<op>(...)`, this header) takes pointers as longs, a geometry as ints and a
* stream as a long, checks what a `__global__` cannot (nulls, non-positive extents, a pitch that
* does not describe the operand), computes the grid, and issues one kernel with
* hipLaunchKernelGGL on the stream it was handed. It returns 0, or a negative launcher code:
* -1 a null pointer, -2 a bad extent, -3 a bad pitch, -4 the HIP launch failed. It allocates
* nothing and synchronises on nothing.
* stream as a long. It checks what a `__global__` cannot (nulls, non-positive extents, a pitch
* that does not describe the operand), computes the grid and issues one kernel with
* hipLaunchKernelGGL on the given stream. It returns 0 or a negative code: -1 a null pointer,
* -2 a bad extent, -3 a bad pitch, -4 the HIP launch failed. It allocates nothing and
* synchronises on nothing.
*
* The shim (`r3d_rad_<op>(const RadArgs*, RadStream)`, declared in the unit) is the RadLaunchFn
* the row table names. It reads the operands with r3d_args.h, takes the dtype from the tensor and
* not from the `dtype` parameter, takes the row count from the operand and not from `M` (which is
* the band's upper bound), checks strides, translates the ABI dtypes to the codes below, and
* returns a RAD status.
* the row table names. It reads the operands with r3d_args.h, takes the dtype from the tensor
* (not the `dtype` parameter) and the row count from the operand (not `M`, which is the band's
* upper bound), checks strides, translates ABI dtypes to the codes below and returns a RAD
* status.
*
* A launcher is declared here and defined beside its kernel, in the same translation unit as the
* shim that calls it: there is no adapter, and an out-of-tree author reading one unit sees the whole
* path from RadArgs to the grid.
* A launcher is defined beside its kernel, in the same translation unit as the shim that calls
* it, so one unit shows the whole path from RadArgs to the grid.
*
* Streams: a RadStream is the engine's queue, usable with hipLaunchKernel (and so <<<>>>),
* hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync and with nothing else in HIP
@@ -37,22 +36,22 @@ extern "C" {
*/
/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. `wdt` is R3D_DT_BF16 or R3D_DT_F32 for a
* gain, R3D_DT_N for none (the gain is then 1, and wadd is refused by the shim, as libref does). */
* gain, R3D_DT_N for none (gain 1; the shim then refuses wadd, as libref does). */
int r3d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, float mult,
int x_ld, int y_ld, int wdt, long stream);
/* The same at f32 activations, for an f32 checkpoint's residual stream: the row is the op's, the
* store narrows nothing. `wdt` is the gain's dtype code, R3D_DT_N for none. */
/* The same at f32 activations, for an f32 checkpoint's residual stream; the store narrows
* nothing. `wdt` is the gain's dtype code, R3D_DT_N for none. */
int r3d_rmsnorm_f32(long x, long w, long y, int M, int n, float eps, float wadd, float mult,
int x_ld, int y_ld, int wdt, long stream);
/* y = (x - mean) / sqrt(var + eps) * w + b, the mean and variance both taken in the reference's
* two passes. `b` may be 0 (no bias). */
/* y = (x - mean) / sqrt(var + eps) * w + b, mean and variance in the reference's two passes.
* `b` may be 0 (no bias). */
int r3d_layernorm_bf16(long x, long w, long b, long y, int M, int n, float eps,
int x_ld, int y_ld, long stream);
/* y = a + b, and y = a * b. `bcast` says b carries n elements and rides every row. `div` is the
* `add` op's optional divisor, 0 meaning none: with it, y = rd(rd(a + b) / div). */
/* y = a + b and y = a * b. `bcast`: b holds n elements, applied to every row. `div` is the `add`
* op's optional divisor, 0 for none; with it, y = rd(rd(a + b) / div). */
int r3d_add_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, float div,
int bcast, long stream);
int r3d_add_f32(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, float div,
@@ -62,13 +61,13 @@ int r3d_mul_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y
int r3d_mul_f32(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, int bcast,
long stream);
/* y = x, one dtype to another, over M rows of n at the given pitches. The dtypes are R3D_DT_*;
* an integer pair goes straight through (ids above 2^24 survive an i64 -> i32 copy), everything
* else widens to f32 and narrows once on the way out. */
/* y = x, one dtype to another, over M rows of n at the given pitches. The dtypes are R3D_DT_*.
* An integer pair is copied directly (ids above 2^24 survive an i64 -> i32 copy); everything else
* widens to f32 and narrows once on the store. */
int r3d_cast(long x, long y, int M, int n, int x_ld, int y_ld, int from_dt, int to_dt, long stream);
/* The unary activations, f32 in, narrowed once by the store: y = x*sigmoid(x), 0.5x(1+erf(x/sqrt2))
* and 1/(1+exp(-x)) respectively. */
/* Unary activations computed in f32 and narrowed once by the store: silu x*sigmoid(x), gelu
* 0.5x(1+erf(x/sqrt2)), sigmoid 1/(1+exp(-x)). */
int r3d_silu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
int r3d_gelu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
int r3d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
@@ -80,62 +79,54 @@ int r3d_act_mul_bf16(long gate, long up, long y, int M, int n, int g_ld, int u_l
int act, long stream);
/* y[i] = silu(gate_up[i]) * gate_up[n + i]: the llama MLP's gated product over one fused plane,
* the gate the FIRST half, which is the order rad-convert fuses gate and up in. The activation is
* not narrowed before the product: that is `act_mul`'s order, over two operands, and it stands for
* the unfused pair that stored the activation. `gu_ld` is the FUSED row's pitch (>= 2n), `y_ld` the
* output's; 0 takes each one's dense width. 0, -1, -2, -3, -4. */
* gate in the first half (rad-convert's fusion order). The activation is not narrowed before the
* product; `act_mul`, over two operands, stands for the unfused pair that stores it. `gu_ld` is the
* fused row's pitch (>= 2n), `y_ld` the output's; 0 takes each one's dense width. */
int r3d_silu_mul_bf16(long gate_up, long y, int M, int n, int gu_ld, int y_ld, long stream);
/* Row-wise softmax over f32, maximum subtracted, the denominator summed in ascending order. */
int r3d_softmax_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
/* y = x * s, where `s` is the op's [1] weight plane, in device memory, of dtype `s_dt`
* (R3D_DT_BF16 or R3D_DT_F32). The scalar is read by the kernel, not by the launcher: a launch may
* not copy device memory to the host, and the reference reads the same one value on the host because
* its operands are host planes. Every lane loads the same address, which is one uniform load per
* block; `s` is 0 only for a call the shim has already refused.
/* y = x * s, where `s` is the op's [1] weight plane in device memory, dtype `s_dt` (R3D_DT_BF16 or
* R3D_DT_F32). The kernel reads the scalar, not the launcher, because a launch may not copy device
* memory to the host. Every lane loads the same address, one uniform load per block. `s` is 0 only
* for a call the shim has already refused.
*
* y = v (fill) is the other scalar-carried op, and its value is a parameter, so it is by value. */
* fill (y = v) takes its value as a parameter, so it is passed by value. */
int r3d_scale_bf16(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, long stream);
int r3d_scale_f32(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, long stream);
int r3d_fill(long y, int M, int n, int y_ld, int dt, float v, long stream);
/* In-place rotary on a fused qkv row: q, then k, then v untouched. `mode` is R3D_ROPE_NEOX or
* R3D_ROPE_GPTJ; `rot` the rotary width (<= head_dim, even). `scale` is the position divisor: the
* angle of pair i is (pos / scale) * theta^-i, which is libref's proportional ladder at a factor
* other than 1 (ref_rope's `scale` divides the position, and YaRN's magnitude is carried by
* `yarn_factor`, which this kernel does not implement). `pos` is M i32 positions, one a row. */
/* In-place rotary on a fused qkv row: q, then k; v is untouched. `mode` is R3D_ROPE_NEOX or
* R3D_ROPE_GPTJ; `rot` the rotary width (<= head_dim, even). `scale` divides the position: the
* angle of pair i is (pos / scale) * theta^-i, as in ref_rope. YaRN's magnitude (`yarn_factor`) is not
* implemented. `pos` is M i32 positions, one per row. */
int r3d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_head, int n_head_kv, float theta,
float scale, int mode, int rot, int qkv_ld, long stream);
/* K and V into a paged cache, at slot_mapping's slots. The cache is [blocks, kv_heads, block_size,
* 2*head_dim] with the strides the shim read off the operand and passes as sb/sh/so/sd; a negative
* slot is skipped, and so is one at or past `slot_max` = n_blocks * block_size, which the launcher
* computes from M and block_size exactly as `r3d_shape_kv_store` sizes the cache. The reference
* *refuses* such a slot on the host, where it can see the block count; a launch cannot refuse a
* slot it has not read, and writing past the cache is the one failure mode worse than a value
* dropped, so the bound is the kernel's and the divergence is a slot lost rather than a step lost. `kv_dt` R3D_DT_BF16 stores the values, R3D_DT_U8 encodes them as E4M3 with the
* reciprocal of k_scale / v_scale, R3D_DT_F16 as f16. */
/* K and V into a paged cache at slot_mapping's slots. The cache is [blocks, kv_heads, block_size,
* 2*head_dim] with the strides the shim reads off the operand (sb/sh/so/sd). A negative slot is
* skipped, and so is one at or past `slot_max` = n_blocks * block_size, computed as
* `r3d_shape_kv_store` sizes the cache. The reference refuses such a slot on the host; a launch
* cannot refuse a slot it has not read, so the kernel drops it rather than write past the cache.
* `kv_dt`: R3D_DT_BF16 stores the values, R3D_DT_U8 encodes E4M3 with the reciprocal of
* k_scale / v_scale, R3D_DT_F16 stores f16. */
int r3d_kv_store(long k, long v, long sm, long kv, int M, int head_dim, int n_head_kv,
int block_size, int kv_dt, float k_scale, float v_scale, int k_ld, int v_ld,
long long slot_max, long sb, long sh, long so, long sd, long stream);
/* x[r] = wte[ids[r] - vocab_offset] * wscale, narrowed once. A row whose id is out of the table's
* range is zeroed, as libref does. */
/* x[r] = wte[ids[r] - vocab_offset] * wscale, narrowed once. A row whose id is outside the table
* is zeroed, as in libref. */
int r3d_embed_lookup(long ids, long wte, long x, int M, int n_embd, int n_vocab, int vocab_offset,
float wscale, float mult, int x_ld, int w_ld, int dt, long stream);
/* y[r] = x[idx[r]] and x[idx[r]] = v[r], rows of n elements.
*
* `src_rows` and `dst_rows` are the plane's own row count. Only the shim can supply it -- it has the
* operand's numel, the launcher has a pointer -- and the kernel needs it, because the reference
* reads the index plane on the host and refuses an index outside the row count, while a launch
* cannot refuse an index it has not read. So the bound travels to the kernel and the kernel acts on
* it: a gather at idx >= src_rows takes the padding path (the zero row libref's padding form
* writes), a scatter at idx >= dst_rows drops the row, which is the same refusal seen from inside a
* launch. The worst failure here is a read or a write past the plane, and a dropped row is what
* stands between this card and it. 0 means unchecked: the shim's bug to avoid, not a caller's to
* supply. */
* `src_rows` / `dst_rows` are the plane's own row count, which only the shim knows (from the
* operand's numel). The reference refuses an out-of-range index on the host; a launch cannot refuse
* an index it has not read, so the kernel enforces the bound: a gather at idx >= src_rows writes
* the zero row of libref's padding form, a scatter at idx >= dst_rows drops the row. This keeps
* every access inside the plane. 0 means unchecked and is a shim bug, not a caller option. */
int r3d_gather_rows(long x, long idx, long y, int M, int n, int x_ld, int y_ld, int dt,
long long src_rows, long stream);
int r3d_scatter_rows(long v, long idx, long x, int M, int n, int v_ld, int x_ld, int dt,
@@ -143,7 +134,7 @@ int r3d_scatter_rows(long v, long idx, long x, int M, int n, int v_ld, int x_ld,
/* ================================================================== r3d_quant_fp8.hip
*
* All three quantisers write a plain row-major code plane and one f32 scale per (row, group); no
* The quantisers write a plain row-major code plane and one f32 scale per (row, group), with no
* fragment permutation, because a dot2 GEMM reads codes in order.
*/
@@ -155,10 +146,9 @@ int r3d_quant_act_fp8(long x, long q, long s, int M, int n, int group, int x_ld,
int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n, int group, int x_ld, int s_ld,
long stream);
/* quant_act_i8g: the same code at `group` granularity -- amax / 127 per (row, group), 1 for an
* all-zero group -- stored row-major. This is the plane libr3d's i8a8 GEMM reads; `quant_act_i8`
* above is the per-row plane the WMMA-ordered ops read, and the two are not interchangeable.
* 0, -1, -2, -3, -4. */
/* The same int8 code at `group` granularity (amax / 127 per (row, group), 1 for an all-zero
* group), stored row-major. This is the plane libr3d's i8a8 GEMM reads; `quant_act_i8` above is the
* per-row plane the WMMA-ordered ops read. The two are not interchangeable. */
int r3d_quant_act_i8g(const void* x, void* q, void* s, int M, int n, int group,
long long x_ld, long long s_ld, long stream);
@@ -168,14 +158,13 @@ int r3d_quant_act_i8g(const void* x, void* q, void* s, int M, int n, int group,
int r3d_gated_quant_fp8(long gate_up, long q, long s, long out_bf16, int M, int n, int group,
int act, long stream);
/* The residual add, the RMS norm and the E4M3 quantiser in one pass, so the normalised row never
* goes back to VRAM. `res` is the residual plane, INOUT, and 0 when the op has no residual: with it
* the sum is STORED, narrowed to bf16, BEFORE the variance reads it, so the norm is over the bf16
* sum -- the `add` + `rmsnorm` pair, not `rmsnorm_add`, which normalises the unrounded sum. `ob`,
* when present, receives exactly the bf16 values the codes were taken over. Pitches are in elements
* of their own operand, `s_ld` in scales, so a dense scale plane is n/group. `group` must divide n:
* a partial group is the standalone quantiser's zero-padded store, which this pass does not have.
* 0, -1, -2, -3, -4. */
/* Residual add, RMS norm and E4M3 quantiser in one pass, so the normalised row never goes back to
* VRAM. `res` is the residual plane (in/out), 0 when the op has none. With it, the sum is stored
* narrowed to bf16 before the variance reads it, so the norm is over the bf16 sum: the `add` +
* `rmsnorm` pair, not `rmsnorm_add`, which normalises the unrounded sum. `ob`, when present,
* receives the bf16 values the codes were taken over. Pitches are in elements of their own operand,
* `s_ld` in scales (dense: n/group). `group` must divide n; this pass has no zero-padded partial
* group. */
int r3d_rmsnorm_quant_fp8(long x, long res, long w, long q, long s, long ob, int M, int n,
int group, float eps, float wadd, int x_ld, int res_ld, int ob_ld,
int q_ld, int s_ld, int wdt, long stream);
@@ -187,7 +176,7 @@ int r3d_dequant(long q, long s, long y, int M, int n, int group, int q_dt, int s
/* ================================================================== r3d_gemm_*.hip
*
* y[M,N] = a[M,K] @ b[N,K]^T. One output element a lane, k ascending, f32 accumulate, the sum
* y[M,N] = a[M,K] @ b[N,K]^T. One output element per lane, k ascending, f32 accumulate, the sum
* narrowed once by the store. Split-K (sk > 0) writes partials to `scratch` and reduces them in a
* second kernel on the same stream; the row's scratch hook sizes the arena for the largest sk the
* band allows.
@@ -200,29 +189,15 @@ int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int K, int a_ld
int kb, int nt, long scratch, long stream);
/* A block-scaled fp8 weight: b is E4M3 codes, b_scale one scale per (pb1 rows of N, pb2 of K)
* block, pb1/pb2 the block sizes the container states (absent, both default to `group`). The
* scale plane is **bf16** in the container's quantised family -- `gemm_q_shape` writes
* `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})` -- and f32 only under the separate dtype `fp8a8f32`.
* a is bf16 (fp8a16, no a_scale) or E4M3 codes with per-(row, group) f32 a_scale (fp8a8). */
int r3d_gemm_nt_q_fp8(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K,
int group, int pb1, int pb2, int a_ld, int y_ld, int sk, int nt,
long scratch, long stream);
/* The same kernel with the scale plane's dtype named, which the 17-argument entry above cannot
* state: it forwards RAD_F32, and the container's quantised weights carry bf16 block scales. Land
* new callers on this one; the older entry is kept for callers written against its RAD_F32
* behaviour. bs_dt is the plane's RadDataType: RAD_BF16 reads bf16, anything else -- 0 included --
* reads f32. */
* block, pb1/pb2 the container's block sizes (both default to `group`). The scale plane is bf16 in
* the container's quantised family (`gemm_q_shape` writes `o.t(f32s ? RAD_F32 : RAD_BF16, {nb,
* kb})`) and f32 only under the separate dtype `fp8a8f32`. a is bf16 (fp8a16, no a_scale) or E4M3
* codes with per-(row, group) f32 a_scale (fp8a8). bs_dt is the scale plane's RadDataType:
* RAD_BF16 reads bf16, anything else (0 included) reads f32. */
int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K,
int group, int pb1, int pb2, int a_ld, int y_ld, int sk, int nt,
long scratch, int bs_dt, long stream);
/* The int8 weight twin, with the optional a_sum / b_ref row sums an int8 GEMM with a zero point
* needs (libquant's symmetric form leaves them null). */
int r3d_gemm_nt_q_i8(long a, long a_scale, long b, long b_scale, long a_sum, long b_ref, long y,
int M, int N, int K, int group, int a_ld, int y_ld, int sk, int nt,
long scratch, long stream);
/* ================================================================== r3d_attn_paged_h128.hip
*
* Paged causal attention. `kv` is the cache the shim read its strides from; `bt` a
@@ -245,9 +220,9 @@ int r3d_attn_prefill_h128(long q, long kv, long bt, long seqused, long k_desc, l
/* ================================================================== r3d_gemm_fp8a8_tiled.hip
*
* The quantised GEMM at prefill heights. b_row/bs_row are the container's row strides, 0 meaning
* dense; `group` is the scale block, 128 on every band this checkpoint declares. The scales arrive
* as the container's two planes behind one operand, which is what the row's layout hook presents;
* the plain two-tensor form is the same entry with bs_row dense.
* dense; `group` is the scale block, 128 on every declared band. The scales arrive as the
* container's two planes behind one operand, as the row's layout hook presents them; the plain
* two-tensor form is the same entry with bs_row dense.
*/
int r3d_gemm_nt_q_fp8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, int M, int N,
int K, int group, int a_ld, long long b_row, int as_ld, long long bs_row,
@@ -257,9 +232,9 @@ int r3d_gemm_nt_q_fp8_tiled(long a, long a_scale, long b_codes, long b_scale, lo
*
* The quantised GEMM at dtype=mxfp4a8: an OCP-MXFP4 weight against the fp8 activation. `b` is the
* e2m1 codes, two per byte, [N, K/2] u8; `b_scale` the e8m0 scale, one per 32 of K, [N, K/32] u8;
* `a` E4M3 with `a_scale` f32 per (row, 128 of K); `y` bf16. b_row/e8_row are the row strides in
* bytes, 0 meaning dense. There is no zero point: the scale is symmetric, and a reserved e8 (0,
* 255) is refused. M <= 16 takes the m16 launcher, M >= 17 the tiled one.
* `a` E4M3 with `a_scale` f32 per (row, 128 of K); `y` bf16. b_row/e8_row are row strides in bytes,
* 0 meaning dense. No zero point (symmetric scale); a reserved e8 (0, 255) is refused. M <= 16
* takes the m16 launcher, M >= 17 the tiled one.
*/
int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N,
int K, int group, int a_ld, int y_ld, long long e8_row, long stream);
@@ -269,13 +244,12 @@ int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale
/* ================================================================== r3d_gemm_inta8.hip
*
* The quantised GEMM at dtype=w4a8 and w8a8: the symmetric int4 and int8 weight grids at decode
* heights. `b` is the signed codes (I4, two a byte, or I8, one a byte), [N, K]; `b_scale` the f16
* scale, one per (row, 128 of K), [N, K/128]; `a` int8 in the step order with `a_scale` f32 per
* row; `y` bf16. b_rb and sb_rb are the row strides (bytes / elements), 0 meaning dense.
* There is no zero point:
* the dequant is code times scale. M <= 16 only; the prefill band is the tiled rows' and the
* 8-bit grid at prefill heights is declared out of this unit.
* The quantised GEMM at dtype=w4a8 and w8a8: symmetric int4 and int8 weight grids at decode
* heights. `b` is the signed codes (I4 two per byte, or I8), [N, K]; `b_scale` the f16 scale, one
* per (row, 128 of K), [N, K/128]; `a` int8 in step order with `a_scale` f32 per row; `y` bf16.
* b_rb and sb_rb are the row strides (bytes / elements), 0 meaning dense. No zero point: the
* dequant is code times scale. M <= 16 only; prefill heights are served by the tiled rows, and the
* 8-bit grid at prefill heights is declared outside this unit.
*/
int r3d_gemm_nt_q_w4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N,
int K, int a_ld, int y_ld, long long b_rb, long long sb_rb, long stream);
@@ -287,37 +261,27 @@ int r3d_gemm_nt_q_w8a8_m16(long a, long a_scale, long b, long b_scale, long y, i
* The vocab-sharded logits and the top-k that follows them.
*/
/* logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T: the decode heights (M <= 16) on
* the decode arm, a prefill arm above them, over a vocabulary-wide N. */
/* logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T: a decode arm for M <= 16 and a
* prefill arm above, over a vocabulary-wide N. */
int r3d_logits_gemm_bf16(long x, long lm, long y, int M, int n_vocab, int n_embd, int x_ld,
int y_ld, int sk, int nt, long scratch, long stream);
/* Per-row top-R of a [M, N] logits row: idx (i32) and val (f32), descending, ties to the lower
* index. `pairs`, when present, also receives the (index, value) dwords a cross-rank merge reads. */
int r3d_row_topk_bf16(long x, long idx, long val, long pairs, int M, int N, int R, int vocab_off,
int x_ld, int rc, int nch, long scratch, long stream);
/* The cross-rank top-1: one id and one value a row, out of [M, n] candidate pairs. */
int r3d_pair_argmax(long pairs, long idx, long val, int M, int n, long stream);
/* ================================================================== r3d_sample_f32.hip
* The sampler, and the vocabulary row it starts from.
*
* The shapes are libref's, operand for operand, and so is the `params` plane:
* one `RadSampleParams` a row, 96 bytes of f32 words, which every stage reads by field. `logits` is
* f32 and the candidate planes are word-typed -- `cand_idx` i32, `cand_val` f32, the pair planes
* i32 holding an id's bits beside a logit -- because that is what the reference writes.
* The shapes and the `params` plane are libref's: one `RadSampleParams` per row, 96 bytes of f32
* words, read by field. `logits` is f32 and the candidate planes are word-typed (`cand_idx` i32,
* `cand_val` f32, the pair planes i32 holding an id's bits beside a logit), as the reference
* writes them.
*
* The stages over the full vocabulary (argmax, temp, topk, logprobs, penalties, dry, ngram_ban) are
* one block a row and are bound by the plane: at the band MiniCPM5-2B asks for, 2048 rows of 130560
* f32, the logits are 1.02 GiB and one pass is the floor. The stages over the candidate set (the
* four narrowings and pick) are one block a row of `n_cand` and are bound by the arithmetic, which
* is why `pick` keeps the reference's double `exp`: the law is `(float)std::exp((double)x)`, and a
* hardware `v_exp_f32` two ulp away moves a draw whenever a true probability lands within an ulp of
* the `u < cum` boundary.
* The full-vocabulary stages (argmax, temp, topk, logprobs, penalties, dry, ngram_ban) run one
* block per row and are bandwidth-bound: at MiniCPM5-2B's band, 2048 rows of 130560 f32, the logits
* are 1.02 GiB. The candidate-set stages (the four narrowings and pick) run one block per row of
* `n_cand` and are arithmetic-bound. `pick` keeps the reference's `(float)std::exp((double)x)`,
* because a hardware `v_exp_f32` two ulp away moves a draw whenever a probability lands within an
* ulp of the `u < cum` boundary.
*
* M comes off the operand, never off the band: the band's `M` is a range's bound and a step's row
* count is what the planes hold. 0, -1 null pointer, -2 bad extent, -3 pitch, -4 launch failed.
* M comes from the operand, never from the band, whose `M` is only an upper bound.
*/
int r3d_row_topk(long x, long idx, long val, long pairs, int M, int N, int R, int x_dt,
long long x_ld, long long idx_ld, long long val_ld, long long pairs_ld,
@@ -330,9 +294,9 @@ int r3d_sample_topk(long lg, long params, long ci, long cv, long pairs, int M, i
int r3d_sample_pick(long ci, long cv, long params, long tok, int M, int n_cand,
long long ci_ld, long long cv_ld, long stream);
/* The four narrowing stages: one shape, `cand_idx` and `cand_val` in place, one predicate each --
* top-p a prefix rule in candidate order, min-p a floor under the best candidate's probability,
* typical the band around the set's entropy, XTC the exclusion-the-model-would-not-choose cut. */
/* The four narrowing stages share one shape and edit `cand_idx` / `cand_val` in place: top-p is a
* prefix rule in candidate order, min-p a floor under the best candidate's probability, typical a
* band around the set's entropy, XTC the exclude-top-choices cut. */
int r3d_sample_topp(long ci, long cv, long params, int M, int n_cand, long long ci_ld,
long long cv_ld, long stream);
int r3d_sample_minp(long ci, long cv, long params, int M, int n_cand, long long ci_ld,
@@ -343,9 +307,9 @@ int r3d_sample_xtc(long ci, long cv, long params, int M, int n_cand, long long c
long long cv_ld, long stream);
/* The pre-filters over the logits row. `hist` is the row's history of global token ids, i32
* [M, max_hist]; its window, and the rule that a token is penalised at its first occurrence in the
* window, are libref's (`hist_window`), and the window is placed inside the params plane by the
* descriptor's `fill_chunk`. `vocab_off` shifts the ids a stage reports, for a split vocabulary. */
* [M, max_hist]. Its window, and the rule that a token is penalised at its first occurrence in the
* window, are libref's (`hist_window`); the descriptor's `fill_chunk` writes the window into the
* params plane. `vocab_off` shifts the ids a stage reports, for a split vocabulary. */
int r3d_sample_penalties(long lg, long params, long hist, int M, int n_vocab, long long lg_ld,
long long hist_ld, int vocab_off, long stream);
int r3d_sample_dry(long lg, long params, long hist, long breakers, int M, int n_vocab,
@@ -355,26 +319,26 @@ int r3d_sample_ngram_ban(long lg, long params, long hist, long ngram, long white
long stream);
int r3d_sample_mask(long lg, long params, long bitmask, int M, int n_vocab, long long lg_ld,
int mask_rows, long stream);
/* The gated MLP band: b is E4M3 codes of N = 2n rows (gate rows [0,n), up rows [n,N)), b_scale one
* scale per (group, group) block, bf16 as the container writes it. The row is narrowed to bf16 as
* the unfused pair leaves it, gated (act: R3D_ACT_SILU | R3D_ACT_SIGMOID), narrowed again, and coded
* per group of `group` columns: q is the codes [M,n], scale the per-(row, group) amax scales, and
* out_bf16 the narrowed gated tensor when the caller wants it (y_ld is its row pitch, n when the
* plane is absent). M <= 64, sk == 1; no scratch, because the row never leaves the registers. */
/* The gated MLP GEMM: b is E4M3 codes of N = 2n rows (gate rows [0,n), up rows [n,N)), b_scale one
* bf16 scale per (group, group) block, as the container writes it. The row is narrowed to bf16 as
* the unfused pair leaves it, gated (act: R3D_ACT_SILU | R3D_ACT_SIGMOID), narrowed again and coded
* per `group` columns: q is the codes [M,n], scale the per-(row, group) amax scales, out_bf16 the
* narrowed gated tensor if wanted (y_ld its row pitch, n when absent). M <= 64, sk == 1; no
* scratch, because the row never leaves the registers. */
int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, long q, long scale,
long out_bf16, int M, int N, int K, int group, int act,
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch, long stream);
/* The same kernel naming the scale plane's dtype. The entry above forwards RAD_BF16, which is the
* container's form for this op; f32 is accepted and equal bit for bit. */
/* The same kernel naming the scale plane's dtype. The entry above passes RAD_BF16, the container's
* form for this op; f32 is accepted and gives bit-identical results. */
int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale, long q, long scale,
long out_bf16, int M, int N, int K, int group, int act,
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
int bs_dt, long stream);
/* DFlash2's greedy walk over the candidate lattice. `hp` may be 0: the plane of ones the reference
* computes when the operand is absent. The rows of cand, unary and tokens are (sequence, step),
* M * steps of them; `anchor` is a row of M * anchor_stride ids. */
/* DFlash2's greedy walk over the candidate lattice. `hp` may be 0, meaning the plane of ones the
* reference uses when the operand is absent. cand, unary and tokens have M * steps rows ordered
* (sequence, step); `anchor` is a row of M * anchor_stride ids. */
int r3d_dflash_select(long cand, long unary, long hp, long anchor, long pred, long succ,
long tokens, int M, int steps, int top_k, int rank, int n_vocab,
int anchor_stride, long long cand_ld, long long un_ld, long long hp_ld,
+54 -66
View File
@@ -1,14 +1,12 @@
/* r3d_args.h -- how a libr3d entry point reads its arguments.
*
* There is no adapter layer. An entry point takes `(const RadArgs*, RadStream)` and returns a
* status, the same RadLaunchFn contract every other plugin implements; an out-of-tree author can
* write the same kernel without an adapter they could not reach.
* An entry point takes `(const RadArgs*, RadStream)` and returns a status, the RadLaunchFn
* contract every plugin implements; there is no adapter layer. This header holds the shared
* helpers for reading parameters, finding operands and testing contiguity, mostly one line over
* rad_abi.h.
*
* This header holds the shared helpers: reading a parameter, finding an operand, testing
* contiguity. Most are one line over rad_abi.h.
*
* Nothing here includes r3d.h or HIP: host translation units (the row table, the shape hooks)
* include it too, so those tables compile and can be checked without ROCm.
* Nothing here includes r3d.h or HIP, so host translation units (the row table, the shape hooks)
* can include it and compile without ROCm.
*/
#ifndef R3D_ARGS_H
#define R3D_ARGS_H
@@ -23,8 +21,7 @@
/* ================================================================== parameter access
*
* Forwards to rad_abi.h's static inline helpers, the ones a third-party plugin gets, keeping
* libr3d's spelling at its call sites. */
* Forwards to rad_abi.h's static inline helpers under libr3d's names. */
static inline int r3d_geti(const RadArgs* a, const char* k, long long* out) {
return rad_args_geti(a, k, out);
}
@@ -37,10 +34,10 @@ static inline const char* r3d_gets(const RadArgs* a, const char* k) {
return rad_args_gets(a, k);
}
/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so `dval` arrives
* and the step path runs no strtod. Deliberately laxer than rad_args_getf_or: string and integer
* spellings are still read, because a tool or selftest may call a launch directly with no declare
* to enforce the type. */
/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so the step path
* reads `dval` without strtod. Deliberately laxer than rad_args_getf_or: string and integer forms
* are accepted because a tool or selftest may call a launch directly, with no declare to enforce
* the type. */
static inline double r3d_getf(const RadArgs* a, const char* k, double dflt) {
if (!a || !k) return dflt;
for (int i = 0; i < a->n_p; ++i) {
@@ -57,10 +54,9 @@ static inline double r3d_getf(const RadArgs* a, const char* k, double dflt) {
return dflt;
}
/* An enumerated parameter: `act` is "silu" or "sigmoid", not 0 or 1, so a --debug-graph dump says
* what runs; the mapping to libr3d's integer lives in the shim. Returns -1 for an unknown name,
* which every caller turns into RAD_E_INVAL. `alt` is libr3d's own integer spelling of the same
* key, consulted only when the name is absent. */
/* An enumerated parameter: `act` is "silu" or "sigmoid" rather than 0 or 1, so a --debug-graph dump
* names what runs. Returns -1 for an unknown name, which callers turn into RAD_E_INVAL. `alt` is an
* integer-valued key for the same choice, read only when the named key is absent. */
static inline int r3d_act_code(const RadArgs* a, const char* key, const char* alt, int dflt) {
if (const char* s = r3d_gets(a, key)) {
if (!std::strcmp(s, "silu") || !std::strcmp(s, "swish")) return 0;
@@ -84,25 +80,20 @@ static inline const char* r3d_pgets(const RadParam* p, int n_p, const char* k) {
/* ================================================================== operand access
*
* An absent optional operand is a null RadTensor.data (rad_abi.h). r3d_opt() returns null both
* past the end and for a present-but-null operand, so an optional test is one pointer test. For a
* required operand the caller turns null into RAD_E_INVAL: it is a bug in the issue, not a shape
* the kernel declines.
* An absent optional operand has a null RadTensor.data (rad_abi.h). For a required operand the
* caller turns null into RAD_E_INVAL: it is an issue bug, not a shape the kernel declines.
*/
static inline const RadTensor* r3d_opt(const RadArgs* a, int i) { return rad_arg_in(a, i); }
/* An optional operand the plan carries a slot for, with no bytes behind it, is ABSENT -- it is not a
* dtype problem. The engine hands the slots of an op's optional operands as descriptors with a null
* `data` when the graph did not bind one, and a shim that dtype-checks such a descriptor would refuse
* a band the op never reads -- `rmsnorm_quant_fp8` answering E_DTYPE to a band whose dtype is fine,
* for an empty `out_bf16` slot. Every test of an optional operand goes through here; a bare `if (t)`
* is the bug. */
/* Whether an optional operand is present. The engine passes an unbound optional operand as a
* descriptor with null `data`, so a bare `if (t)` is wrong: a shim that dtype-checks such a
* descriptor refuses a call that never reads it (e.g. an empty `out_bf16` slot of
* `rmsnorm_quant_fp8`). Every test of an optional operand goes through here. */
static inline bool r3d_has(const RadTensor* t) { return t && t->data; }
static inline const void* r3d_p(const RadTensor* t) { return t ? t->data : nullptr; }
/* The same for an operand a kernel writes, so an output cast reads as one rather than as a pointer
* laundered through `long`. */
/* The same for an operand a kernel writes. */
static inline void* r3d_wp(const RadTensor* t) { return t ? t->data : nullptr; }
static inline long r3d_addr(const RadTensor* t) { return t ? (long)(uintptr_t)t->data : 0L; }
@@ -118,8 +109,8 @@ static inline long long r3d_stride(const RadTensor* t, int i) {
static inline long long r3d_numel(const RadTensor* t) { return rad_tensor_numel(t); }
/* [rows..., K] flattened to (M, K). Every per-row kernel in libr3d owns whole rows (one workgroup
* per row), so the leading axes are only a row count. The GEMM makes the same fold explicitly. */
/* [rows..., K] flattened to (M, K). Every per-row kernel owns whole rows (one workgroup per row),
* so the leading axes are only a row count. */
static inline int r3d_rows_of(const RadTensor* t, long long* M, long long* K) {
if (!t || t->rank < 1) return RAD_E_SHAPE;
*K = t->shape[t->rank - 1];
@@ -128,10 +119,9 @@ static inline int r3d_rows_of(const RadTensor* t, long long* M, long long* K) {
return (*M >= 1 && *K >= 1) ? RAD_OK : RAD_E_SHAPE;
}
/* Dense row-major over the whole tensor. libr3d's entry points take at most one pitch, so
* everything else must be tight, and the shim checks it. This is the "necessary condition only"
* boundary of spec §2.1: the constraint table settles geometry, contiguity is a property of the
* call. */
/* Dense row-major over the whole tensor. Entry points take at most one pitch, so everything else
* must be tight, and the shim checks it: per spec §2.1 the constraint table settles geometry while
* contiguity is a property of the call. */
static inline int r3d_contig(const RadTensor* t) { return rad_tensor_is_contiguous(t); }
/* Contiguous in every axis but the leading one, whose stride is the row pitch libr3d takes as an
@@ -150,10 +140,10 @@ static inline long long r3d_row_pitch(const RadTensor* t) {
/* [rows..., n] read as (rows, n): the leading axes are a row count and only the last is
* structural. Returns the pitch in elements, or -1.
*
* A column slice must refuse. k out of a fused [tok, 2*kv_dim] projection, read as
* A column slice is refused. k out of a fused [tok, 2*kv_dim] projection, read as
* [tok*n_head_kv, head_dim] for a per-head norm, has rows `n` apart within a token and a buffer row
* apart between tokens; no single pitch describes that, and the leading stride would make the
* consumer read most heads from garbage. So the trailing axes must cover the whole row. */
* apart between tokens; no single pitch describes that, and using the leading stride would read
* most heads from the wrong place. So the trailing axes must cover the whole row. */
static inline long long r3d_rows_pitch(const RadTensor* t, long long n, long long* rows) {
if (!t || t->rank < 1 || n <= 0) return -1;
const long long nel = rad_tensor_numel(t);
@@ -191,10 +181,10 @@ static inline int r3d_aligned(const void* p, unsigned bytes) {
/* ================================================================== which check refused
*
* A shim refuses in many places with the same few codes, so the engine's report names the kernel
* and geometry but not the failing condition. R3D_NO() wraps a refusal and prints its own line when
* RAD_R3D_TRACE is set; otherwise it is the bare return plus one cached-flag load on a path that is
* failing anyway. */
* A shim refuses in many places with the same few codes, and the engine's report names the kernel
* and geometry but not the failing condition. R3D_NO() wraps a refusal and, when RAD_R3D_TRACE is
* set to a value other than "0", prints "[r3d] file:line refused -> code" to stderr. The variable
* is read once and cached; unset, the cost is one flag load on a refusal path. */
static inline int r3d_trace_on(void) {
static int on = -1;
if (on < 0) { const char* e = std::getenv("RAD_R3D_TRACE"); on = (e && *e && *e != '0'); }
@@ -206,9 +196,10 @@ static inline int r3d_refused(int code, const char* file, int line) {
}
#define R3D_NO(code) r3d_refused((code), __FILE__, __LINE__)
/* The descriptor we were handed, printed when we decline one. A stride refusal that names no stride
* is a refusal the reader has to reproduce, and reproducing it costs a probe cycle: the engine binds
* rank, shape and strides in ELEMENTS, and the shape it binds is the step's, not the band's. */
/* Under RAD_R3D_TRACE, prints a refused descriptor's dtype, rank, shape, strides and data pointer.
* The engine binds shape and strides in elements, and the shape is the step's, not the band's.
* R3D_STR refuses with RAD_E_STRIDE and, under the same flag, prints the reason and two named
* values. */
static inline void r3d_trace_desc(const char* what, const RadTensor* t) {
if (!r3d_trace_on()) return;
if (!t) { std::fprintf(stderr, "[r3d] %s: (absent)\n", what); return; }
@@ -229,8 +220,8 @@ static inline void r3d_trace_desc(const char* what, const RadTensor* t) {
/* ================================================================== dtype helpers
*
* A row's `dtype` constraint is a necessary condition on the geometry, not a promise about the
* tensors: the shim reads the dtype off the operand, and these are the tests it reads it with. */
* A row's `dtype` constraint is a necessary condition, not a promise about the tensors, so the
* shim tests each operand's dtype with these. */
static inline int r3d_is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; }
static inline int r3d_is_f16(const RadTensor* t) { return t && t->dtype == RAD_F16; }
static inline int r3d_is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; }
@@ -258,12 +249,12 @@ static inline int r3d_dt_named(uint32_t dt, const char* name) {
/* ================================================================== libr3d's constants
*
* Restated here because r3d_rows.cpp and r3d_shapes.cpp are host code built without ROCm and cannot
* Defined here because r3d_rows.cpp and r3d_shapes.cpp are host code built without ROCm and cannot
* include r3d.h, and because a .rad container records them in its layout tag. */
enum {
R3D_WAVE = 32,
/* The activation quantiser's group: the width a scale covers along n. 128 is the WEIGHT
* scale's block width and therefore a property of the checkpoint, not a knob. */
/* The activation quantiser's group: the width a scale covers along n. It equals the weight
* scale's block width, a property of the checkpoint, not a knob. */
R3D_ACT_GROUP = 128,
/* Block-scaled fp8, on both axes: the checkpoint's `quantization_config.weight_block_size`,
* which the bytes on disk follow. The entry points reject a mismatch. */
@@ -272,23 +263,20 @@ enum {
R3D_W8_GROUP = 128,
/* The largest N a dot2 GEMM's per-lane accumulator grid spans in one wave. */
R3D_NTILE = 16,
/* The operand count of `gemm_nt_q` (a, a_scale, b, b_scale, y, a_sum, b_ref). The shape hook
* builds the whole list at once and needs a name for its length; the schema in r3d_rows.cpp is
* the authority, and rad-kbench checks the two against each other. */
/* The operand count of `gemm_nt_q` (a, a_scale, b, b_scale, y, a_sum, b_ref), used by the shape
* hook. The schema in r3d_rows.cpp is authoritative; rad-kbench checks the two agree. */
R3D_GEMM_Q_NOPERAND = 7
};
/* ================================================================== libr3d's tunables
*
* The knobs the row table declares, exposed so `rad-tune` can walk them and `--debug-graph` can
* name the pick (spec §15). The chosen point comes back appended to RadArgs::p, so a launch reads
* it with r3d_geti_or like any other parameter; these structs are how a launch reads several at
* once, with the row's defaults where a caller supplied none.
* The knobs the row table declares, so `rad-tune` can search them and `--debug-graph` can name the
* choice (spec §15). The chosen point is appended to RadArgs::p; these structs read several knobs
* at once, with the row's defaults where a caller supplied none.
*
* sk == 0 means "choose the largest legal split count at issue". Split-K requires
* K % (sk * group) == 0, so no fixed default is legal at every shape, and an illegal default would
* make an untuned install fail rather than run slowly. The sentinel is resolved in one place, in
* the GEMM unit.
* sk == 0 means "the largest legal split count at issue". Split-K requires K % (sk * group) == 0,
* so no fixed default is legal at every shape, and an illegal default would make an untuned install
* fail. The GEMM unit resolves the sentinel.
*/
struct R3dGemmCfg { int wv, sk, kb, nt; }; /* waves a block, split-K, K slab, non-temporal loads */
struct R3dSplitCfg { int splits; }; /* split-KV segments; 0 is the kernel's own law */
@@ -297,10 +285,10 @@ struct R3dTopkCfg { int rc, nch; }; /* candidates a chunk keeps, chunk
extern "C" {
/* -- the tuned configuration (r3d_rows.cpp) --
*
* The core picked a point in the space the row declared and appended it to RadArgs::p. These read
* it back, falling to the axis's default (defined once, in the RadTunable table) when a caller
* supplied none, so a checker with no tuned key runs what an untuned install runs. They cannot
* fail: the loader refuses a plugin whose default is not one of the axis's values. */
* Read the point the core appended to RadArgs::p, falling back to each axis's default (defined in
* the RadTunable table) when none was supplied, so a caller without a tuned key runs what an
* untuned install runs. They cannot fail: the loader refuses a plugin whose default is not one of
* the axis's values. */
void r3d_cfg_gemm (const RadArgs*, struct R3dGemmCfg*);
void r3d_cfg_split(const RadArgs*, struct R3dSplitCfg*);
void r3d_cfg_topk (const RadArgs*, struct R3dTopkCfg*);
File diff suppressed because it is too large. Load diff
+77 -93
View File
@@ -1,20 +1,18 @@
/* r3d_codecs.h -- the numeric codecs, in the one spelling every libr3d unit and the host use.
/* r3d_codecs.h -- the numeric codecs, shared by every libr3d unit and the host.
*
* These define what a result is, so they are stated once: rad_plugin.h's bf16 / f16 / fp8 / int8
* rounders, restated so a device kernel can call them. rad_plugin.h's are `static inline` host
* functions, which a `__global__` cannot reach, and libref -- the oracle every libr3d row is
* checked against at kbench -- is built out of them. The mirror is therefore not a style choice,
* and r3d_selftest.cpp compares the two over the whole fp8 code space, the whole bf16 code space
* and 2^20 random f32s, so a drift of one ulp is a test failure here and not a tolerance argument
* at kbench.
* rad_plugin.h's bf16 / f16 / fp8 / int8 rounders, restated so a device kernel can call them
* (rad_plugin.h's are `static inline` host functions a `__global__` cannot reach). libref, the
* oracle every libr3d row is checked against at kbench, is built from those, so these must match
* bit for bit. r3d_selftest.cpp compares the two over the whole fp8 and bf16 code spaces and 2^20
* random f32s, so a one-ulp drift fails there.
*
* The contract, from ref_common.h and rad_plugin.h: f32 accumulation, IEEE round-to-nearest-ties-
* to-even narrowing, no fused multiply-add and no reassociation, subnormals kept. Widening is
* exact. `-ffp-contract=off` is a correctness flag, and rad_hipify puts it on every HIP source.
* to-even narrowing, no fused multiply-add, no reassociation, subnormals kept. Widening is exact.
* `-ffp-contract=off` is a correctness flag; rad_hipify puts it on every HIP source.
*
* R3D_HD is `__host__ __device__` in a HIP translation unit and nothing in a host one, which is how
* the same header serves a kernel and r3d_selftest.cpp. The pieces that want a GPU instruction are
* behind __HIP_DEVICE_COMPILE__ and have a plain-C++ twin a device build never takes.
* R3D_HD is `__host__ __device__` in a HIP translation unit and nothing in a host one, so the same
* header serves kernels and r3d_selftest.cpp. Code that uses a GPU instruction sits behind
* __HIP_DEVICE_COMPILE__ with a plain-C++ host equivalent.
*/
#ifndef R3D_CODECS_H
#define R3D_CODECS_H
@@ -22,12 +20,10 @@
#include <cstdint>
#include <cstring>
/* HIP first, and before R3D_HD: `__forceinline__` is a macro of hip_runtime.h's, so a unit that
* includes this header without including the runtime first -- r3d_common.h includes the codecs
* before it -- would read `__forceinline__` as a type name. The runtime declares no
* `__host__ __device__` memcpy, which is why the bitcasts below go through bits_of and float_of.
* A host translation unit -- the row table, the operand descriptions, r3d_selftest.cpp -- takes the
* #else and pulls in no ROCm header at all. */
/* The HIP runtime comes first, before R3D_HD: `__forceinline__` is a hip_runtime.h macro, and
* r3d_common.h includes the codecs before the runtime, so without this it would parse as a type
* name. Host translation units (the row table, the operand descriptions, r3d_selftest.cpp) pull in
* no ROCm header. */
#if defined(__HIPCC__)
#include <hip/hip_runtime.h>
#endif
@@ -38,11 +34,10 @@
#define R3D_HD inline
#endif
/* The bit cast, in one place. Device code cannot call `memcpy` and the HIP headers do not declare a
* `__host__ __device__` one on every release, so the device path is the compiler's bit cast; the
* host path keeps memcpy, which the optimiser folds to a move, because GCC only grew
* `__builtin_bit_cast` in C++20 mode and r3d_selftest.cpp is built at C++17 by the tree's host
* compiler. */
/* The bit cast. Device code cannot call `memcpy` (the HIP headers do not declare a
* `__host__ __device__` one on every release), so the device path uses the compiler's bit cast.
* The host path keeps memcpy, which folds to a move, because GCC has `__builtin_bit_cast` only in
* C++20 mode and r3d_selftest.cpp builds at C++17. */
R3D_HD uint32_t bits_of(float f) {
#if defined(__HIPCC__)
return __builtin_bit_cast(uint32_t, f);
@@ -68,9 +63,9 @@ R3D_HD float float_of(uint32_t u) {
*
* bf16 is f32's top half: widening is a shift, narrowing one add and a shift.
*
* `(u >> 16) & 1` is the tie-break -- it adds one more than the halfway point when the surviving
* bit is odd, so ties go to even. Overflow carries into the bf16 infinity; a NaN is forced quiet so
* it cannot round into an infinity, which is what rad_f32_to_bf16 does and what libref does. */
* `(u >> 16) & 1` is the tie-break: it adds one more than the halfway point when the surviving bit
* is odd, so ties go to even. Overflow carries into the bf16 infinity. A NaN is forced quiet so it
* cannot round into an infinity, as in rad_f32_to_bf16 and libref. */
R3D_HD float bf16_to_f32(uint16_t h) {
const uint32_t u = (uint32_t)h << 16;
return float_of(u);
@@ -82,15 +77,15 @@ R3D_HD uint16_t f32_to_bf16(float f) {
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
/* The same rounding, stopped one shift short: the rounded value sitting in a word's high half, the
* form a packed store wants. gfx11 in this ROCm has no v_cvt_pk_bf16_f32 (llvm-mc rejects it on
* gfx1100, gfx1102 and gfx1151), so a bf16 pair is two of these and one byte permute. */
/* The same rounding without the final shift: the rounded value in a word's high half, the form a
* packed store wants. gfx11 in this ROCm has no v_cvt_pk_bf16_f32 (llvm-mc rejects it on gfx1100,
* gfx1102 and gfx1151), so a bf16 pair is two of these and one byte permute. */
R3D_HD uint32_t bf16_hi_rne(float f) {
const uint32_t u = bits_of(f);
return u + 0x7fffu + ((u >> 16) & 1u);
}
/* Two such words as one bf16 pair, `lo`'s half in the low half of the result: one v_perm_b32. */
/* Two such words as one bf16 pair, `lo`'s value in the low half: one v_perm_b32. */
R3D_HD uint32_t bf16_pack_hi(uint32_t lo, uint32_t hi) {
#if defined(__HIP_DEVICE_COMPILE__)
return __builtin_amdgcn_perm(hi, lo, 0x07060302u);
@@ -103,7 +98,7 @@ R3D_HD uint32_t bf16x2_rne(float lo, float hi) {
return bf16_pack_hi(bf16_hi_rne(lo), bf16_hi_rne(hi));
}
/* A bf16 pair word's two values as floats: a shift and a mask, no conversion. */
/* A bf16 pair word's two values as floats: a shift or a mask, no conversion. */
R3D_HD float bf16w_lo(uint32_t w) {
const uint32_t u = w << 16;
return float_of(u);
@@ -115,8 +110,8 @@ R3D_HD float bf16w_hi(uint32_t w) {
/* ================================================================== f16
*
* RTNE both ways with subnormals kept, as rad_f16_to_f32 and rad_f32_to_f16 do -- not the hardware
* convert, whose rounding mode a caller could have changed and which flushes subnormal halves. */
* RTNE both ways with subnormals kept, as rad_f16_to_f32 and rad_f32_to_f16 do. The hardware
* convert is not used: its rounding mode is caller-settable and it flushes subnormal halves. */
R3D_HD float f16_to_f32(uint16_t h) {
const uint32_t s = (uint32_t)(h >> 15) << 31;
const uint32_t e = (uint32_t)(h >> 10) & 0x1fu;
@@ -171,12 +166,12 @@ R3D_HD uint16_t f32_to_f16(float f) {
/* Two f32 as one dword of two f16, `lo` in the low half.
*
* v_cvt_pkrtz_f16_f32 rounds toward zero, which is not RTNE, so this is only ever called with
* values f16 represents exactly: a bf16 widened (seven mantissa bits into ten) or an E4M3 code
* (three into three). For those the two spellings give the same bits and the instruction is free. */
* v_cvt_pkrtz_f16_f32 rounds toward zero, not RTNE, so this is only called with values f16
* represents exactly: a widened bf16 (seven mantissa bits into ten) or an E4M3 code (three into
* ten). For those both paths give the same bits. */
R3D_HD uint32_t f16x2_pack(float lo, float hi) {
#if defined(__HIP_DEVICE_COMPILE__)
/* The builtin answers as a pair of __fp16; the bits are the dword the dot2 reads. */
/* The builtin returns a pair of __fp16; its bits are the dword the dot2 reads. */
return __builtin_bit_cast(uint32_t, __builtin_amdgcn_cvt_pkrtz(lo, hi));
#else
return (uint32_t)f32_to_f16(lo) | ((uint32_t)f32_to_f16(hi) << 16);
@@ -185,22 +180,17 @@ R3D_HD uint32_t f16x2_pack(float lo, float hi) {
/* A dword of two bf16 as a dword of two f16.
*
* Exact over f16's normal range, and that is what makes the dot2 path sound: a bf16 has seven
* mantissa bits and an f16 ten, so within [2^-14, 65504] a widening costs no rounding and a dot
* product over widened bf16 accumulates the sums libref forms over its bf16 operands.
* Exact over f16's normal range, which makes the dot2 path sound: bf16 has seven mantissa bits and
* f16 ten, so within [2^-14, 65504] widening costs no rounding and a dot over widened bf16 forms
* the sums libref forms over its bf16 operands.
*
* Outside it the widening is not exact, and the two edges behave differently. Above 65504 a
* magnitude becomes an infinity (the packing instruction saturates, which is the kinder of the two
* answers). Below 2^-14 the operand is an f16 subnormal, whose grid is a power of two coarser than
* bf16's at the same magnitude, so a widening truncates toward zero -- and below 2^-24 it flushes.
* The truncation is what the packing instruction does, `v_cvt_pkrtz_f16_f32` rounding toward zero.
*
* The low edge costs a served model nothing: an activation below 2^-14 times a weight of a
* hundredth is 1e-18, against an accumulator of order one, so it is not a term the sum can see;
* and a scale-reduced operand is scaled back up before it is used, which is why the quantised rows
* put the scale on the block, not the element. What would be visible is a weight stream whose
* magnitudes live below 2^-14, and no checkpoint's do. The rows whose band can reach 65504 say so
* in their `shape` text. */
* Outside that range: above 65504 a magnitude becomes an infinity. Below 2^-14 the operand is an
* f16 subnormal on a coarser grid than bf16's, and v_cvt_pkrtz_f16_f32 truncates toward zero;
* below 2^-24 it flushes. The low edge does not affect a served model: an activation below 2^-14
* times a weight of 0.01 is 1e-18 against an accumulator of order one, and the quantised rows keep
* the scale on the block, not the element, so scale-reduced operands are scaled back before use. No
* checkpoint's weights live below 2^-14. Rows whose band can reach 65504 say so in their `shape`
* text. */
R3D_HD uint32_t bf16x2_to_f16x2(uint32_t w) {
return f16x2_pack(bf16w_lo(w), bf16w_hi(w));
}
@@ -210,11 +200,10 @@ R3D_HD uint32_t bf16x2_to_f16x2(uint32_t w) {
* 1-4-3, bias 7, no infinity, S1111111 the only NaN, 448 the largest finite. The KV-cache and
* block-scaled weight format, so the attention oracle and every fp8 row depend on its rounding.
*
* RDNA3 has no instruction for it: v_cvt_pk_fp8_f32 and v_cvt_pk_f32_fp8 need the fp8 feature,
* which RDNA3 does not have. The builtins are *declared* for gfx11 -- so `__has_builtin` is true
* here, which is the trap a `__has_builtin` guard falls into, and libr4d's guards are exactly that
* -- and rejected at instruction selection. Both directions are bit maths, about eleven VALU an
* encode and six a decode. */
* RDNA3 has no fp8 instructions: v_cvt_pk_fp8_f32 and v_cvt_pk_f32_fp8 need the fp8 feature. The
* builtins are declared for gfx11, so a `__has_builtin` guard (as in libr4d) passes, but they are
* rejected at instruction selection. Both directions are bit maths, about eleven VALU per encode
* and six per decode. */
R3D_HD float e4m3_to_f32(uint8_t b) {
const uint32_t s = (uint32_t)(b >> 7) << 31;
const uint32_t e = (uint32_t)(b >> 3) & 0xfu;
@@ -237,9 +226,9 @@ R3D_HD float e4m3_to_f32(uint8_t b) {
return float_of(u);
}
/* Saturates at 448 rather than overflowing: a NaN from one large activation spreads through the
* whole row, and every fp8 cast in this project clamps for that reason. The clamp is inside the
* codec here because there is no instruction to clamp in front of. */
/* Saturates at 448 rather than overflowing, because a NaN from one large activation spreads
* through the whole row; every fp8 cast in this project clamps. The clamp is inside the codec
* because there is no hardware convert to clamp in front of. */
R3D_HD uint8_t f32_to_e4m3(float f) {
const uint32_t u = bits_of(f);
const uint8_t s = (uint8_t)((u >> 24) & 0x80u);
@@ -270,31 +259,29 @@ R3D_HD uint8_t f32_to_e4m3(float f) {
return (uint8_t)(s | ((uint32_t)ee << 3) | q);
}
/* Two codes in one dword, the low element in the low byte: the store a wave's lane does. */
/* Two codes in one dword, the low element in the low byte: one lane's store. */
R3D_HD uint32_t e4m3x2_pack(float lo, float hi) {
return (uint32_t)f32_to_e4m3(lo) | ((uint32_t)f32_to_e4m3(hi) << 8);
}
/* A dword of two E4M3 codes as a dword of two f16.
*
* Exact -- e4m3 has four exponent and three mantissa bits, f16 five and ten -- and this is the fp8
* matrix path: a code becomes the f16 the checkpoint means, dot2 multiplies it, and the block
* scale is applied once per block. RDNA3 has no fp8 hardware, so the decode is VALU, and it is
* paid where the weight bytes are being read anyway. */
* Exact (e4m3 has four exponent and three mantissa bits, f16 five and ten). This is the fp8 matrix
* path: a code becomes its f16 value, dot2 multiplies it, and the block scale is applied once per
* block. Without fp8 hardware the decode is VALU work, done where the weight bytes are read. */
R3D_HD uint32_t e4m3x2_to_f16x2(uint32_t w) {
return f16x2_pack(e4m3_to_f32((uint8_t)(w & 0xffu)), e4m3_to_f32((uint8_t)(w >> 8)));
}
/* ================================================================== int8
*
* The symmetric int8 twin: amax/127, RTNE, saturating. f16 holds every int8 exactly, so widening
* into a dot product is exact and the scale is the only float in the path. */
* Symmetric int8: amax/127, RTNE, saturating. f16 holds every int8 exactly, so widening into a
* dot product is exact and the scale is the only float in the path. */
R3D_HD int8_t f32_to_i8_rtne(float f) {
if (!(f == f)) return 0;
/* Round to nearest, ties to even, in integer arithmetic. A tie at the top of the range would
* round to a code that does not exist (+128), so the clamp is applied after the rounding, not
* as an early return: 127.5 goes to the even 128 and then clamps to 127, which is what
* rad_round_even_sat gives. */
/* Round to nearest, ties to even, in integer arithmetic, then clamp. The clamp follows the
* rounding, not an early return: 127.5 rounds to the even 128 and clamps to 127, as
* rad_round_even_sat does. */
const float fl = __builtin_floorf(f);
const float frac = f - fl;
int32_t q = (int32_t)fl;
@@ -315,28 +302,25 @@ R3D_HD uint32_t i8x2_to_f16x2(uint32_t w) {
/* ================================================================== the dot product
*
* Two f16 products into an f32 accumulator, one instruction: v_dot2acc_f32_f16, which
* __builtin_amdgcn_fdot2 lowers to on every gfx11 target (checked by reading the emitted asm on
* gfx1100, gfx1102 and gfx1151). RDNA3 pairs it as v_dual_dot2acc_f32_f16 where the scheduler can,
* which is how libr3d's inner loops reach the matrix unit's absence without noticing.
* Two f16 products into an f32 accumulator in one instruction: v_dot2acc_f32_f16, which
* __builtin_amdgcn_fdot2 lowers to on every gfx11 target (verified in the emitted asm on gfx1100,
* gfx1102 and gfx1151). RDNA3 pairs it as v_dual_dot2acc_f32_f16 where the scheduler can.
*
* The selector is FALSE, always. RDNA3 has no bf16 dot2, and this compiler accepts the bf16
* selector and emits the f16 instruction anyway: a bf16 pair passed with sel=true is read as two
* f16s and the products are nonsense, silently, on every gfx11 target. bf16 operands are widened
* with bf16x2_to_f16x2, which is exact.
* Invariant: the last argument is always false. RDNA3 has no bf16 dot2, yet this compiler accepts
* the bf16 selector and emits the f16 instruction, so a bf16 pair passed with sel=true is silently
* read as two f16s. bf16 operands are widened exactly with bf16x2_to_f16x2.
*
* The two products go into `acc` in the order written, and a kernel that walks k ascending
* reproduces libref's summand-for-summand: the reference loop is `s += a[k]*b[k]` with
* -ffp-contract=off. The match is not bit-exact and cannot be: `v_dot2acc_f32_f16` folds the two
* products and the accumulator with guard bits and rounds once, where the reference rounds each
* product and each sum. The difference is under an f32 ulp a pair, a random walk of about
* sqrt(K/2) ulps over a K-long dot, which is a thousandth of the bf16 the store narrows to -- so it
* sits inside what `rad-kbench` measures, exactly as libr4d's WMMA accumulation does. What is
* required, and what every loop here keeps, is that the *order* of the summands be the reference's:
* k ascending, one accumulator per output element, no reassociation across lanes.
* The two products go into `acc` in the order written, so a kernel walking k ascending follows
* libref's summand order (`s += a[k]*b[k]` with -ffp-contract=off). The result is not bit-exact:
* v_dot2acc_f32_f16 folds both products and the accumulator with guard bits and rounds once, where
* the reference rounds each product and sum. The difference is under an f32 ulp per pair, a random
* walk of about sqrt(K/2) ulps over a K-long dot: about a thousandth of the bf16 the store narrows
* to, and inside what `rad-kbench` measures (as with libr4d's WMMA accumulation). What every loop
* here must keep is the reference's summand order: k ascending, one accumulator per output element,
* no reassociation across lanes.
*
* The host path below is the same arithmetic with each product rounded first, which is what a test
* needs it to be. It is not the hardware's rounding. */
* The host path is the same arithmetic with each product rounded first, for tests; it is not the
* hardware's rounding. */
R3D_HD float dot2_f16x2(uint32_t a, uint32_t b, float acc) {
#if defined(__HIP_DEVICE_COMPILE__)
typedef __fp16 v2h __attribute__((ext_vector_type(2)));
@@ -350,8 +334,8 @@ R3D_HD float dot2_f16x2(uint32_t a, uint32_t b, float acc) {
#endif
}
/* Four f16 products into one accumulator: the step every libr3d matmul runs. The two dot2s are a
* dependency chain of two; a kernel keeps four of these chains in flight. */
/* Four f16 products into one accumulator, the step every libr3d matmul runs. The two dot2s form a
* dependency chain of two; a kernel keeps four such chains in flight. */
R3D_HD float dot4_f16x4(uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1, float acc) {
return dot2_f16x2(a1, b1, dot2_f16x2(a0, b0, acc));
}
+60 -74
View File
@@ -1,45 +1,39 @@
/* r3d_common.h -- the RDNA3 seams a kernel needs: the wave's lane maths, the loads, the block
* reduce, the occupancy and LDS conventions.
/* r3d_common.h -- RDNA3 kernel primitives: lane maths, global loads, the block reduce, occupancy
* and LDS conventions. The codecs are in r3d_codecs.h.
*
* What RDNA3 gives, measured on the ROCm this tree builds against (AMD clang 24; `__has_builtin`
* off --offload-device-only, and llvm-mc -show-encoding per target). The codecs are in r3d_codecs.h;
* this header is what is left.
* Instruction availability on gfx11 with the AMD clang this tree builds with (checked with
* `__has_builtin` under --offload-device-only and llvm-mc -show-encoding per target):
*
* v_dot2acc_f32_f16 yes, every gfx11 target, from __builtin_amdgcn_fdot2, and RDNA3 pairs
* it as v_dual_dot2acc_f32_f16 where the scheduler can. The matrix work.
* v_dot2 with bf16 no, and the builtin's bf16 selector is accepted and ignored -- the f16
* instruction is emitted -- so bf16 is widened, never asserted.
* WMMA the mnemonic is unreachable -- every v_wmma_* is rejected by the
* assembler on gfx1100, gfx1102, gfx1151 and gfx1201 alike, and inline
* asm dies in amdgcn-link -- but the builtin is not:
* __builtin_amdgcn_wmma_f32_16x16x16_f16_w32 compiles for the three gfx11
* targets and emits a real tile instruction. Measured here against dot2 at
* four occupancies, 1.99 against 1.97 TFLOP/s: RDNA3's AI accelerator is a
* 2x f16-rate feature and a paired dot2 is already at that rate, so the
* tile buys a fragment layout and a block-alignment requirement and no
* throughput. No fragment layouts here, so no repacked weights, so no
* layout hook: a dot2 GEMM reads a weight in the order it is stored.
* fp8 convert no (needs the fp8 feature); the builtins are declared and die at
* instruction selection, which is why the codecs are software.
* v_dot2acc_f32_f16 yes, all gfx11, via __builtin_amdgcn_fdot2; dual-issued as
* v_dual_dot2acc_f32_f16 where possible. Carries the matrix work.
* v_dot2 with bf16 no. The builtin's bf16 selector is accepted and ignored (the f16
* instruction is emitted), so bf16 is widened.
* WMMA the assembler rejects every v_wmma_* mnemonic and inline asm fails in
* amdgcn-link, but __builtin_amdgcn_wmma_f32_16x16x16_f16_w32 compiles on
* gfx11. It runs at the same rate as paired dot2 (about 2 TFLOP/s each
* on the tested part; RDNA3's matrix unit is a 2x f16-rate feature that
* dual dot2 already reaches), so it would add a fragment layout and an
* alignment requirement for no throughput. Without fragment layouts no
* weight is repacked: a dot2 GEMM reads a weight in stored order.
* fp8 convert no (needs the fp8 feature); the builtins are declared but fail at
* instruction selection, so the codecs are software.
* v_cvt_pkrtz_f16_f32 yes. Used only where it is exact.
* v_cvt_pk_bf16_f32 no on gfx1100/1102/1151 in this build, so bf16 packs are software.
* DPP16, v_permlanex16 yes, RDNA1 onward. The lane maths below is libr4d's, unchanged: the
* encodings are the same silicon, and they were verified on hardware.
* v_cvt_pk_bf16_f32 no on gfx1100/1102/1151, so bf16 packs are software.
* DPP16, v_permlanex16 yes (RDNA1 onward). The lane maths below uses libr4d's encodings,
* which are hardware-verified.
* ballot_w32, readlane,
* readfirstlane, ds_bpermute,
* v_perm_b32, exp2f, rcpf,
* s_barrier, fence,
* sched_group_barrier yes.
* transposed loads no: neither global_load_tr_b128 (RDNA4) nor ds_read_b64_tr_b16 (dropped
* by RDNA4, kept here as a fact about gfx11 -- this ROCm's assembler
* rejects it too). A transpose is done in registers.
* transposed loads no: neither global_load_tr_b128 (RDNA4) nor ds_read_b64_tr_b16 (the
* assembler rejects it for gfx11). Transposes are done in registers.
*
* Wave32 is gfx11's default and every kernel here is written for it; the guard below fires if a
* build asks for wave64, because that computes garbage rather than running slower.
* Every kernel is written for wave32, gfx11's default; the guard below rejects a wave64 build,
* which would compute wrong results.
*
* The register file is the one number that is NOT the same as RDNA4's: a gfx11 SIMD has 1024 VGPRs
* for a wave32, allocated in groups of 8, against gfx1201's 1536. R3D_WAVES is stated per kernel,
* and a kernel's budget is computed against 1024.
* Register file: a gfx11 SIMD has 1024 VGPRs for wave32, allocated in groups of 8 (gfx1201 has
* 1536). R3D_WAVES is set per kernel and each kernel's budget is computed against 1024.
*/
#ifndef R3D_COMMON_H
#define R3D_COMMON_H
@@ -57,26 +51,25 @@
enum : int { kWave = 32 };
/* A 16-byte staging register as a native vector. HIP's uint4 is a class template wrapping a union,
* and an array of them carried across a loop is kept in scratch by LLVM 22 and 24; an
* ext_vector_type array is promoted to registers. Loaded and stored whole only. */
/* A 16-byte staging register as a native vector. HIP's uint4 is a class wrapping a union, and LLVM
* 22 and 24 keep an array of them carried across a loop in scratch; an ext_vector_type array is
* promoted to registers. Loaded and stored whole only. */
typedef unsigned int r3d_u32x4 __attribute__((ext_vector_type(4)));
typedef unsigned int r3d_u32x2 __attribute__((ext_vector_type(2)));
/* ================================================================== the occupancy a kernel is
* built for
*
* Fixes the waves per SIMD the compiler schedules for. Left unstated, the scheduler picks the
* target itself and the choice moves between compiler releases. gfx11's budget is 1024 VGPRs a
* SIMD at wave32, in granules of 8: a kernel asking for 5 waves has 204 registers to spend. */
* Fixes the waves per SIMD the compiler schedules for; left unstated, the choice changes between
* compiler releases. gfx11's budget is 1024 VGPRs a SIMD at wave32, in granules of 8: a kernel
* asking for 5 waves has 204 registers to spend. */
#define R3D_WAVES(n) __attribute__((amdgpu_waves_per_eu((n), (n))))
/* ================================================================== exp2
*
* The hardware transcendental. libr4d's rule applies: exp2f, powf and sincosf are the accurate
* forms, not the __ approximations -- rope positions reach 262144, past __sincosf's argument
* reduction, and libref uses libm. exp2f itself is the one place the hardware op is exactly what
* the reference computes, because both sides round the same result once. */
* The hardware transcendental. Elsewhere use the accurate exp2f, powf and sincosf, not the __
* approximations: rope positions reach 262144, past __sincosf's argument reduction, and libref uses
* libm. exp2 is the exception because the hardware op and the reference round the same result once. */
__device__ __forceinline__ float ex2(float x) {
return __builtin_amdgcn_exp2f(x);
}
@@ -87,12 +80,11 @@ __device__ __forceinline__ float rcp(float x) { return __builtin_amdgcn_rcpf(x);
*
* A 16-bit element of global memory, zero-extended into a whole register (global_load_u16). Read as
* `uint16_t` it lands in a register half (global_load_d16_b16) whose other half the waitcnt pass
* then waits for; through a generic pointer it is also a flat load. The pointer must address global
* memory, which every caller's operand is.
* then waits for, and through a generic pointer it is a flat load. The pointer must address global
* memory.
*
* libr4d notes that LLVM 24 gives gfx12 real 16-bit registers and the packability that follows;
* gfx11 does not have them, so keeping bf16 in whole registers from load to store is the plain
* reading as well as the portable one. */
* gfx11 has no true 16-bit registers (LLVM 24 gives them to gfx12 only), so bf16 stays in whole
* registers from load to store. */
typedef const uint16_t __attribute__((address_space(1))) *r3d_gu16;
__device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(r3d_gu16)p; }
__device__ __forceinline__ uint32_t ldg_u32(const uint32_t* p) { return *(const __attribute__((address_space(1))) uint32_t*)p; }
@@ -102,16 +94,15 @@ __device__ __forceinline__ float ldg_f32(const float* p) {
/* ================================================================== lane maths
*
* A wave is 32 lanes, two rows of sixteen. Reductions are XOR butterflies, in the order a
* __shfl_xor loop runs in, so the result is bit-identical to that loop -- which is what libref
* sums, since the reference sums a row in ascending index order and a wave of lanes maps to
* consecutive elements.
* A wave is 32 lanes, two rows of sixteen. Reductions are XOR butterflies in the order a
* __shfl_xor loop runs them, so results are bit-identical to that loop and to libref, which sums a
* row in ascending index order over consecutive elements.
*
* `__shfl_xor` lowers to ds_bpermute_b32 plus s_wait_dscnt, an LDS round trip that dominates a
* dependency chain. DPP16's ROW_XMASK (control 0x160 | N) makes the partner read a modifier on the
* consuming VALU op, and N = 16 crosses the two rows of a wave32 with v_permlanex16, still one VALU
* op. Row and bank masks are all-ones because every lane participates; bound_ctrl is moot because
* every lane has a partner. These are libr4d's encodings, verified on hardware. */
* consuming VALU op, and N = 16 crosses the two rows with v_permlanex16, also one VALU op. Row and
* bank masks are all-ones because every lane participates; bound_ctrl is moot because every lane
* has a partner. */
template <int N>
__device__ __forceinline__ uint32_t r3d_xor_lane_u32(uint32_t v) {
static_assert(N >= 1 && N <= 16 && (N & (N - 1)) == 0, "a lane xor within the wave");
@@ -139,7 +130,7 @@ __device__ __forceinline__ unsigned long long r3d_xor_lane_u64(unsigned long lon
* other half; sel0 covers lanes 0-7, sel1 lanes 8-15); zero selectors silently broadcast lane 0. */
__device__ __forceinline__ float swap16(float x) { return r3d_xor_lane<16>(x); }
/* v + the partner's v, the partner read by DPP so the add carries it. */
/* v + the partner's v, read by DPP as a modifier on the add. */
template <int CTRL>
__device__ __forceinline__ float r3d_dpp_xor_add(float v) {
return v + __uint_as_float(__builtin_amdgcn_update_dpp(0, __float_as_uint(v), CTRL, 0xF, 0xF,
@@ -166,7 +157,7 @@ __device__ __forceinline__ float wave_max(float v) {
/* The same butterflies over a group of W lanes (a power of two up to the wave), in the order
* `for (o = W/2; o; o >>= 1) v = op(v, __shfl_xor(v, o))` runs them, so bit-identical to it. A row
* of sixteen lanes -- the sixteen columns a lane owns in a bf16 pair layout -- uses W = 16. */
* of sixteen lanes (the sixteen columns of a bf16 pair layout) uses W = 16. */
template <int W>
__device__ __forceinline__ float r3d_xor_sum(float v) {
static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave");
@@ -190,8 +181,8 @@ __device__ __forceinline__ float r3d_xor_max(float v) {
}
/* A wave's inclusive prefix sum in registers: row_shr 1, 2, 4 and 8 within each row of sixteen,
* then the other row's total from one readlane. Lane L ends with the sum over lanes 0..L. Replaces
* an LDS step-doubling scan, which costs two barriers a round. Integer, so combine order is free.
* then the first row's total from one readlane. Lane L ends with the sum over lanes 0..L. Avoids an
* LDS step-doubling scan, which costs two barriers a round. Integer, so combine order is free.
* Every lane must be active. */
__device__ __forceinline__ uint32_t wave_prefix_u32(uint32_t x, int lane) {
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x111, 0xF, 0xF, true); /* row_shr:1 */
@@ -205,9 +196,8 @@ __device__ __forceinline__ uint32_t wave_prefix_u32(uint32_t x, int lane) {
/* ================================================================== a block's sum
*
* Wave sum, one LDS round trip, then every thread adds the wave partials in wave order. The order
* is the contract: libref sums a row in ascending index order, the waves cover consecutive
* elements, and adding the partials in wave order is the same bracketing at any thread count.
* `lds` holds NWAVES floats. */
* is part of the contract: waves cover consecutive elements, so wave order gives the same
* bracketing at any thread count. `lds` holds NWAVES floats. */
template <int NTHREADS>
__device__ __forceinline__ float block_sum(float v, float* lds) {
constexpr int NWAVES = NTHREADS / kWave;
@@ -225,22 +215,19 @@ __device__ __forceinline__ float block_sum(float v, float* lds) {
/* ================================================================== scheduling
*
* LLVM single-buffers LDS and drains before every dependent read unless told otherwise; on gfx11
* the matrix unit is absent so there is nothing to overlap a load with, and the barrier the
* kernels need is the plain one. */
* LLVM single-buffers LDS and drains before every dependent read unless told otherwise. On gfx11
* there is no matrix unit to overlap a load with, so the plain barrier is enough. */
__device__ __forceinline__ void sched_barrier() { __builtin_amdgcn_sched_barrier(0); }
__device__ __forceinline__ void group_barrier() { __syncthreads(); }
/* ================================================================== the geometry constants
*
* A gfx11 GPU's wave slots: a CU has 4 SIMDs, a SIMD holds 16 wave32s, so 64 slots a CU. HIP's
* multiProcessorCount reports CUs on gfx11 (it reports WGPs on gfx12, which is where libr4d's 2048
* comes from), and a launch whose grid passes 64 * multiProcessorCount waves has more work than
* slots: the tail waves start after another wave retires. A row-per-block kernel with one wave a
* block is exactly that cliff, and its row count is where the cliff is.
* A gfx11 GPU's wave slots: a CU has 4 SIMDs and a SIMD holds 16 wave32s, so 64 slots a CU. HIP's
* multiProcessorCount reports CUs on gfx11 (WGPs on gfx12, hence libr4d's different constant). A
* grid with more than 64 * multiProcessorCount waves runs its tail waves only after others retire,
* so for a one-wave row-per-block kernel that row count is a performance cliff.
*
* A launcher's question, so a host function: this HIP declares no device-side hipGetDevice or
* hipDeviceGetAttribute, and a __device__ body does not compile at all. */
* Host only: HIP declares no device-side hipGetDevice or hipDeviceGetAttribute. */
static inline int wave_slot_count() {
int dev = 0, cu = 0;
(void)hipGetDevice(&dev);
@@ -248,9 +235,8 @@ static inline int wave_slot_count() {
return 64 * cu;
}
/* The LDS a workgroup gets is 64 KiB, the same figure RDNA4 gives, and no kernel in libr3d needs
* more. There is no hipFuncSetAttribute opt-in: 64 KiB of dynamic shared memory is available as
* soon as it is asked for. */
/* A workgroup gets 64 KiB of LDS, as on RDNA4, and no libr3d kernel needs more. No
* hipFuncSetAttribute opt-in is needed for the full 64 KiB of dynamic shared memory. */
enum : int { kLdsCap = 64 * 1024 };
#endif /* R3D_COMMON_H */
+56 -74
View File
@@ -1,62 +1,48 @@
/* r3d_dflash_f32.hip -- DFlash2's candidate walk, `dflash_select`, on the card.
/* r3d_dflash_f32.hip -- DFlash2's candidate walk, `dflash_select`.
*
* A block-diffusion drafter proposes every position of a block in one backbone pass, so position
* l+1 is not conditioned on what the drafter chose at l. This op restores that dependence: it walks
* the `steps` positions in order and, at each, picks the candidate that maximises
* l+1 is not conditioned on the drafter's choice at l. This op restores that dependence: it walks
* the `steps` positions in order and at each picks the candidate that maximises
*
* score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * hp[l][r] * succ[cand[l, c]][r]
*
* where pid(0) is the anchor -- the token the target just committed, read at
* `anchor[m * anchor_stride]` -- and pid(l) is the walk's own previous pick, `cand[l-1, chosen]`.
* `hp` absent is a plane of ones, which drops the trilinear form to a low-rank bigram (DSpark's
* Markov head). libref's `ref_dflash_select` is the law, and this file transcribes its arithmetic
* and its order.
* where pid(0) is the anchor (the token the target just committed, at `anchor[m * anchor_stride]`)
* and pid(l) is the walk's previous pick, `cand[l-1, chosen]`. With `hp` absent it is a plane of
* ones and the form reduces to a low-rank bigram (DSpark's Markov head). This file transcribes the
* arithmetic and order of libref's `ref_dflash_select`.
*
* ============================== why it is a kernel and not a GEMM ==============================
* Parallelism. The walk is serial in l, because step l's predecessor is the pick of step l-1;
* scoring the whole [steps, K, K] edge tensor up front would compute K times the edges read. The
* sequences and, within a step, the K candidates are parallel: a block takes `256 / top_k`
* sequences, each lane scores one (sequence, candidate) edge, and one lane per sequence takes the
* argmax. Each step costs two LDS round trips (scores out, pick back).
*
* The walk is serial in l: the predecessor of step l is not known until step l-1 has been decided,
* so the [steps, K, K] edge tensor cannot be scored in advance -- scoring it computes K times the
* edges that are ever read. What is parallel is the sequences (M of them) and, inside a step, the K
* candidates. So a block takes `256 / top_k` sequences and gives each lane one (sequence,
* candidate) pair: the lane runs the rank sum for its own edge, in the reference's order, and one
* lane per sequence scans the K scores and takes the pick. The loop over `steps` stays serial, with
* the two LDS round trips per step (the scores out, the pick back) that the dependence requires.
* Cost. At the band (steps=7, top_k=16, rank=256, M=256) a walk is 7 * 16 * 256 = 28672 terms, and
* the op is a gather over `succ` [n_vocab, rank]: 66.8 MiB of codebook, of which the walk reads
* M * steps * K = 28672 rows (about 14.7 MiB) plus one predecessor row per step. There is no
* arithmetic to hide the gather behind, so a tree reduction gains nothing and would break the
* agreement below.
*
* The rank sum is the whole cost: at the band (steps=7, top_k=16, rank=256, M=256) a walk is
* 7 * 16 * 256 = 28672 fused terms, and the bytes it touches are the K successor rows a step reads,
* 16 * 512 B of bf16, so the op is a gather over `succ` [n_vocab, rank] -- 66.8 MiB of codebook at
* the band, of which the walk reads M * steps * K = 28672 rows, about 14.7 MiB, plus one
* predecessor row a step. There is no arithmetic to hide that behind, which is why the sum is a
* plain ascending chain and not a tree: a tree buys nothing here and costs the agreement.
* Agreement with the reference is bit-exact:
*
* ============================== agreement, and where this file declines ==============================
*
* Bit-exact by construction, not by tolerance:
*
* - the rank sum is `sc = unary; for (i = 0; i < rank; ++i) sc += ax[i] * succ[i];` -- ascending
* in r, one accumulator, no reduction, no tree, with `-ffp-contract=off` so no FMA fusion
* changes the rounding of a term;
* - `ax[i] = pred[pid][i] * hp[l][i]` is rounded to f32 before it meets `succ`, because the
* reference writes it into a float array first (and with `hp` absent it is `pred * 1.0f`, which
* is the same value);
* - the rank sum is `sc = unary; for (i = 0; i < rank; ++i) sc += ax[i] * succ[i];`, ascending in
* r, one accumulator, with `-ffp-contract=off` so no FMA changes a term's rounding;
* - `ax[i] = pred[pid][i] * hp[l][i]` is rounded to f32 before it meets `succ`, as the reference
* stores it in a float array first (with `hp` absent, `pred * 1.0f` is the same value);
* - the argmax is a strict `>` over c ascending, so the earliest candidate wins a tie and a NaN
* never displaces the incumbent -- the reference's loop, statement for statement;
* - a predecessor outside the vocabulary contributes zero, and a candidate outside it is scored
* by `unary` alone: both are the reference's tests (`pid >= 0 && pid < nv`, `tok >= 0 &&
* tok < nv`), and both are why padding rows -- a shard's unused rows, a block shorter than
* `steps` -- are legal inputs;
* - the pick of step l is written to `tokens[m, l]` and becomes pid(l+1) unchanged, including
* when it is out of range for the codebooks.
* never displaces the incumbent;
* - a predecessor outside the vocabulary contributes zero and a candidate outside it is scored by
* `unary` alone (the reference's `pid >= 0 && pid < nv`, `tok >= 0 && tok < nv`), so padding
* rows (a shard's unused rows, a block shorter than `steps`) are legal inputs;
* - the pick of step l is written to `tokens[m, l]` and becomes pid(l+1) unchanged, even when it
* is out of range for the codebooks.
*
* Declines, all of them the shim's, none reachable from a row that carries the constraints its row
* states: a codebook (`pred`, `succ`, `hp`) that is not bf16, because this is the bf16
* instantiation -- the band's `dtype` is the codebooks' width and a row asks for bf16 (RAD_E_DTYPE);
* `unary` that is not f32, `cand`/`anchor`/`tokens` that are not i32, exactly as the schema's
* operand list types them (RAD_E_DTYPE); a codebook whose rows are not contiguous -- the gather is
* `token * rank + r` and a row stride inside the row is not that (RAD_E_STRIDE); `top_k` above 256,
* which is one lane a candidate and no more candidates than lanes (RAD_E_UNSUPPORTED); and a `cand`
* plane that describes more sequences than the band's `M`, which is `band_rows` refusing and is
* RAD_E_SHAPE, not a truncation.
* The shim refuses, none of it reachable from a row whose constraints hold: a codebook (`pred`,
* `succ`, `hp`) or band `dtype` other than bf16, the one instantiation (RAD_E_DTYPE); `unary` not
* f32 or `cand`/`anchor`/`tokens` not i32, as the schema types them (RAD_E_DTYPE); a codebook whose
* rows are not contiguous, since the gather is `token * rank + r` (RAD_E_STRIDE); `top_k` above
* 256, one lane per candidate (RAD_E_UNSUPPORTED); a `cand` plane describing more sequences than
* the band's `M` (RAD_E_SHAPE, not a truncation).
*/
#include "r3d.h"
@@ -72,8 +58,8 @@ namespace {
constexpr uint32_t kThr = 256; /* 8 waves: the block's (sequence, candidate) lanes */
constexpr uint32_t kKMax = kThr; /* one lane a candidate, so top_k <= 256 */
/* Whole-register loads of the planes the walk gathers through. bf16 is a 16-bit load and the
* library's codec, which is the same decode libref's `ldt` performs. */
/* Whole-register loads of the planes the walk gathers through. bf16 is a 16-bit load decoded with
* the library's codec, the same decode as libref's `ldt`. */
__device__ __forceinline__ int32_t ldg_i32(const int32_t* p) {
return (int32_t)ldg_u32((const uint32_t*)p);
}
@@ -81,10 +67,10 @@ __device__ __forceinline__ float ldg_f32(const float* p) { return *(const float*
__device__ __forceinline__ uint16_t ldg_u16(const uint16_t* p) { return *(const uint16_t*)p; }
/* ------------------------------------------------------------------ the walk
* `per` sequences per block, `K` candidates per sequence, so lane (s, c) owns the edge
* (sequence s, candidate c) of the step in hand. `hp` may be null: then the `hp` factor is 1.0f,
* exactly as the reference's `(hp ? ldt(hp, ...) : 1.0f)` writes it. */
*
* `per` sequences per block, `K` candidates per sequence; lane (s, c) owns the edge
* (sequence s, candidate c) of the current step. `hp` may be null, and the factor is then 1.0f, as
* in the reference's `(hp ? ldt(hp, ...) : 1.0f)`. */
__global__ __launch_bounds__(kThr) void dflash_select_kernel(
const int32_t* __restrict__ cand, const float* __restrict__ un,
const uint16_t* __restrict__ hp, const int32_t* __restrict__ anc,
@@ -100,13 +86,13 @@ __global__ __launch_bounds__(kThr) void dflash_select_kernel(
const uint32_t c = threadIdx.x - s * K; /* the candidate this lane scores */
const uint32_t seq0 = blockIdx.x * per + s;
/* A block of 256 lanes holds ceil(256 / K) sequences and the last group can be partial. A lane
* with no sequence replays the last real one: it reaches every __syncthreads() and its stores
* are suppressed, and the loads it performs are in range because the sequence it replays is. */
* with no sequence replays the last real one, so it reaches every __syncthreads() and its loads
* stay in range; its stores are suppressed. */
const uint32_t seq = seq0 < M ? seq0 : M - 1;
const bool mine = seq0 < M;
/* pid(0): the anchor, at `m * anchor_stride` in a flat plane. The reference reads it through
* `ld_int`, so a negative id is a legal "no predecessor" and not an error. */
/* pid(0): the anchor, at `m * anchor_stride` in a flat plane. As in the reference (`ld_int`),
* a negative id means "no predecessor", not an error. */
int32_t pid = ldg_i32(anc + (size_t)seq * (size_t)astr);
const bool has_hp = (hp != nullptr);
@@ -116,9 +102,8 @@ __global__ __launch_bounds__(kThr) void dflash_select_kernel(
const int32_t tok = ldg_i32(cand + cb + c);
float sc = ldg_f32(un + (size_t)r * (size_t)un_ld + c);
/* A predecessor outside the vocabulary contributes nothing; a candidate outside it is
* scored by `unary` alone. Both tests are the reference's, and both are why a shard's
* padding rows and a block shorter than `steps` are legal inputs. */
/* Out-of-vocabulary predecessor: no contribution. Out-of-vocabulary candidate: `unary`
* alone. See the header. */
const bool have_p = pid >= 0 && (uint32_t)pid < nv;
const bool have_s = tok >= 0 && (uint32_t)tok < nv;
if (have_s) {
@@ -126,8 +111,7 @@ __global__ __launch_bounds__(kThr) void dflash_select_kernel(
const uint16_t* sp = succ + (size_t)tok * (size_t)succ_ld;
const uint16_t* hpb = hp + (size_t)r * (size_t)hp_ld;
for (uint32_t i = 0; i < R; ++i) {
/* ax[i], rounded to f32 where the reference writes it into its float array, and
* then the ascending chain. 1.0f for a missing hp is the reference's own factor. */
/* ax[i] is rounded to f32 before the multiply, as in the reference. */
const float ax = have_p
? bf16_to_f32(ldg_u16(pp + i)) * (has_hp ? bf16_to_f32(ldg_u16(hpb + i)) : 1.0f)
: 0.0f;
@@ -138,8 +122,7 @@ __global__ __launch_bounds__(kThr) void dflash_select_kernel(
__syncthreads();
if (c == 0) {
/* The reference's argmax: strict `>`, c ascending, so the earliest candidate wins a
* tie and a NaN never takes the lead from a number. */
/* Strict `>`, c ascending: the earliest candidate wins a tie, a NaN never leads. */
uint32_t best_c = 0;
float best_s = -INFINITY;
for (uint32_t j = 0; j < K; ++j) {
@@ -157,9 +140,8 @@ __global__ __launch_bounds__(kThr) void dflash_select_kernel(
/* ------------------------------------------------------------------ shim helpers */
/* The plane's row pitch, from the plane: `rows` is its row count and `ld` the pitch a row's
* elements start at, K apart. A rank-1 plane is a run of rows K apart, which is what the
* reference's rowoff does for one. */
/* The plane's row count (`rows`) and row pitch (`ld`) for rows of K elements. A rank-1 plane is a
* run of rows K apart, as the reference's rowoff treats it. */
static inline int rows_pitch(const RadTensor* t, long long K, long long* rows, long long* ld) {
const long long p = r3d_rows_pitch(t, K, rows);
if (p < 0) return RAD_E_STRIDE;
@@ -201,7 +183,7 @@ static inline int r3d_launch_status(int rc) {
* anchor [M*anchor_stride] i32, the token each walk starts from, at m*anchor_stride
* pred [n_vocab][rank] bf16, the predecessor codebook
* succ [n_vocab][rank] bf16, the successor codebook the walk gathers with its picks
* tokens [M][steps] i32, out: the accepted prefix, one pick a step
* tokens [M][steps] i32, out: the accepted prefix, one pick per step
*
* 0, -1 null, -2 bad extent, -3 pitch, -4 the HIP launch failed. No allocation, no synchronisation.
*/
@@ -237,10 +219,10 @@ extern "C" int r3d_dflash_select(long cand, long unary, long hp, long anchor, lo
/* ================================================================== shim
*
* libref's operand list is {cand, unary, hp?, anchor, pred, succ, tokens} and its parameter list is
* {M, steps, top_k, rank, n_vocab, anchor_stride?, dtype}. Sequences come from `cand` -- the plane
* holds M * steps * top_k ids -- through `band_rows`, so a plane describing more sequences than the
* band's M is refused, not truncated. `rank` and `n_vocab` fall back to the predecessor codebook's
* own shape, as the reference's do, and `anchor_stride` defaults to 1.
* {M, steps, top_k, rank, n_vocab, anchor_stride?, dtype}. The sequence count comes from `cand`
* (M * steps * top_k ids), with the band's M as a ceiling: a plane describing more sequences is
* refused, not truncated. `rank` and `n_vocab` default to the predecessor codebook's shape, as in
* the reference, and `anchor_stride` to 1.
*/
extern "C" int r3d_rad_dflash_select(const RadArgs* a, RadStream stream) {
const RadTensor* cand = r3d_opt(a, 0);
@@ -269,7 +251,7 @@ extern "C" int r3d_rad_dflash_select(const RadArgs* a, RadStream stream) {
if (K > (long long)kKMax) return R3D_NO(RAD_E_UNSUPPORTED);
if (steps > 0x7fffffffLL / (K * 256) ) return R3D_NO(RAD_E_SHAPE);
/* Sequences from the plane, the band as a ceiling -- band_rows refuses, it does not truncate. */
/* Sequences from the plane, the band as a ceiling. */
const long long all = steps * K;
if (all <= 0 || r3d_numel(cand) % all) return R3D_NO(RAD_E_SHAPE);
const long long M = r3d_numel(cand) / all;
+24 -35
View File
@@ -1,36 +1,26 @@
/* r3d_fp8_dequant.h -- the E4M3 -> f16 decoder as a table, for the rows that read fp8 codes.
/* r3d_fp8_dequant.h -- E4M3 -> f16 decode through a 256-entry LDS table.
*
* WHY THIS EXISTS, WITH THE MEASUREMENT THAT ASKED FOR IT
* gfx11 has no E4M3-to-f16 instruction: `__builtin_amdgcn_cvt_pk_f16_fp8` compiles on gfx1102 but
* emits no `v_cvt_pk_f16_fp8`, only the same software exponent work as `e4m3_to_f32`. The codec in
* r3d_codecs.h costs about 25 instructions a pair, 100 an eight-code group. On the M=1 vocabulary
* head (r3d_vocab_bf16.hip, gfx1102, 32 CU) that makes the row ALU-bound at about 8x its DRAM floor.
*
* gfx11 has no instruction that converts E4M3 to f16. clang lists `__builtin_amdgcn_cvt_pk_f16_fp8`
* for the target, and a build that calls it on gfx1102 contains ZERO `v_cvt_pk_f16_fp8` in its ISA:
* the builtin is software here, lowered to the same exponent work `e4m3_to_f32` does. r3d_codecs.h's
* codec is two `e4m3_to_f32` (a dozen instructions of shifts, exponent bias and subnormal handling
* each) plus a pack, about 25 instructions a pair, 100 an eight-code group. Measured on the
* vocabulary head at M=1 (r3d_vocab_bf16.hip, RX 7600 / gfx1102 / 32 CU): 13.603 ms a token at
* 19.6 GB/s of codes, 8x above the 1.64 ms the codes' 255 MiB floor at this row's own 163 GB/s, and
* the ALU was the binding resource, not DRAM.
* Every one of E4M3's 256 bit patterns has an exact f16 value (f16's exponent range covers E4M3's,
* subnormals included, and NaN maps to NaN), so the decoder is a 512-byte table and eight LDS reads
* replace about a hundred ALU instructions. The table lives in LDS, not __constant__: each lane
* decodes a different code, and divergent constant indexes serialise.
*
* E4M3 has 256 bit patterns and every one of them has an f16 value (f16's exponent range covers
* E4M3's, its subnormals included, and E4M3's NaN maps to an f16 NaN). So the decoder is a
* 256-entry table of 512 bytes, and eight LDS reads replace the hundred ALU instructions. That is
* the whole idea, and the table goes in LDS -- not __constant__, whose broadcast is a liability here
* because every lane decodes a DIFFERENT code, and divergent constant indexes serialise.
* Cost: 512 bytes of LDS a block and a 256-store fill plus a barrier at block start. Reads are
* 16-bit loads at data-dependent addresses; random codes put about two lanes on each bank word, for
* about two cycles a read.
*
* Cost: 512 bytes of LDS a block, one fill of 256 stores at block start plus a barrier. Conflict
* behaviour on the reads: 16-bit loads at data-dependent addresses, so a wavefront's 32 lanes land
* on 16 bank words; random codes give roughly two lanes per word, and measured cost is about two
* cycles a read -- eight reads an eight-code group against the codec's hundred instructions.
* The table is filled by calling the codec once per entry, so results are bit-identical to the
* codec. Invariant: the table must be filled before any lane reads it; r3d_e4m3_f16_init contains
* the barrier.
*
* The table is EXACT: it is built by calling the codec once per entry, so it is the codec, moved
* from the loop to the block's start. Nothing about the arithmetic changes, and a row's rel_l2
* against its reference is unchanged by this header. The one thing to keep: the table must be filled
* before any lane reads it, so every use is `..._init` then the barrier it contains, then reads.
* int8 codes need no table: `v_cvt_f32_i8` is a hardware instruction (r3d_codecs.h: i8x2_to_f16x2).
*
* int8 codes do NOT want a table: `v_cvt_f32_i8` is a hardware instruction, so
* r3d_codecs.h's i8x2_to_f16x2 is two converts and a pack. This header serves the fp8 codes.
*
* Header-only, like the rest of libr3d. Include it in a .hip after r3d_codecs.h.
* Include in a .hip after r3d_codecs.h.
*/
#ifndef R3D_FP8_DEQUANT_H
#define R3D_FP8_DEQUANT_H
@@ -40,8 +30,8 @@
#define R3D_E4M3_TBL 256 /* every E4M3 bit pattern, in order, as the f16 it means */
#define R3D_E4M3_TBL_BYTES (R3D_E4M3_TBL * 2)
/* Fill the block's table: `tbl` is __shared__ uint16_t[R3D_E4M3_TBL]. The barrier is inside it,
* because the only correct order is fill-then-read and the row should not have to remember it. */
/* Fill the block's table: `tbl` is __shared__ uint16_t[R3D_E4M3_TBL]. Ends with the barrier that
* orders the fill before any read. */
__device__ __forceinline__ void r3d_e4m3_f16_init(uint16_t* tbl, int tid, int nthr)
{
for (int i = tid; i < R3D_E4M3_TBL; i += nthr)
@@ -49,8 +39,8 @@ __device__ __forceinline__ void r3d_e4m3_f16_init(uint16_t* tbl, int tid, int nt
__syncthreads();
}
/* Two codes (the low 16 bits of a dword) as one f16 pair, the pair layout dot2_f16x2 reads: the
* first code in the low half. Same answer as e4m3x2_to_f16x2, eight table reads per eight codes. */
/* Two codes (the low 16 bits of a dword) as one f16 pair in dot2_f16x2 layout, the first code in
* the low half. Same result as e4m3x2_to_f16x2. */
__device__ __forceinline__ uint32_t r3d_e4m3x2_ld(const uint16_t* tbl, uint32_t pair)
{
const uint16_t lo = tbl[pair & 0xffu];
@@ -58,9 +48,8 @@ __device__ __forceinline__ uint32_t r3d_e4m3x2_ld(const uint16_t* tbl, uint32_t
return (uint32_t)lo | ((uint32_t)hi << 16);
}
/* Eight codes (two dwords, straddling pairs as always) as four f16 pairs. The sibling of
* codes8_to_f16x4 in r3d_vocab_bf16.hip; the int8 side of that helper stays with the codec, because
* int8 has a hardware convert and fp8 does not. */
/* Eight codes (two dwords) as four f16 pairs; the fp8 counterpart of codes8_to_f16x4 in
* r3d_vocab_bf16.hip. */
__device__ __forceinline__ void r3d_e4m3x8_ld(const uint16_t* tbl, uint2 c, uint32_t* w)
{
const uint32_t d0 = c.x, d1 = c.y;
@@ -70,7 +59,7 @@ __device__ __forceinline__ void r3d_e4m3x8_ld(const uint16_t* tbl, uint2 c, uint
w[3] = r3d_e4m3x2_ld(tbl, d1 >> 16);
}
/* One code, for the rows that decode a scalar a step (an activation tile staged a byte a lane). */
/* One code, for rows that decode a scalar per step (an activation tile staged a byte a lane). */
__device__ __forceinline__ uint16_t r3d_e4m3_ld(const uint16_t* tbl, uint8_t code)
{
return tbl[code];
+84 -106
View File
@@ -1,89 +1,78 @@
/* r3d_gemm_bf16_nt_m16.hip -- the skinny bf16 GEMM, M <= 16: the linear a token is made of.
/* r3d_gemm_bf16_nt_m16.hip -- the skinny bf16 GEMM, M <= 16.
*
* y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store.
*
* The band is decode and speculative verify, where the weight is the cost and the activation is
* free: the kernel is built so the whole weight plane streams once, and so every output's sum is
* the sum libref forms.
* The band is decode and speculative verify, where the weight stream is the cost. The kernel
* streams the whole weight plane once, and every output's sum is the sum libref forms.
*
* ---- the lane map --------------------------------------------------------------------------
*
* One output element a lane, walking k ascending. A wave covers MT rows of the activation by
* 32/MT rows of the weight: lane l owns (m = l % MT, n = n0 + l / MT), MT being the template
* argument -- the request's M rounded up to 1, 2, 4, 8 or 16. Lanes sharing an n read the same
* weight words, so the wave issues 32/MT loads per step and broadcasts them to MT lanes each;
* lanes sharing an m read the same activation words out of LDS. A lane therefore owns its own
* accumulator from 0 to K and never exchanges a value with another lane: its chain is
* One output element per lane, walking k ascending. A wave covers MT activation rows by 32/MT
* weight rows: lane l owns (m = l % MT, n = n0 + l / MT), where MT (the template argument) is M
* rounded up to 1, 2, 4, 8 or 16. Lanes sharing an n read the same weight words; lanes sharing an m
* read the same activation words from LDS. Each lane owns one accumulator from 0 to K and never
* exchanges a value with another lane:
*
* acc = 0; for k ascending: acc = dot2(pair k+1, dot2(pair k, acc))
*
* with pairs taken two k at a time, which is `s += a[k]*b[k]` in ascending k, summand for summand,
* the loop r4d_gemm_bf16_nt_tiled's contract quotes and ref_gemm.h's quant_tile runs. There is no
* wave reduction anywhere in this kernel, so nothing reassociates: at sk = 1 the output is
* bit-identical to libref's, not merely within a tolerance.
* which is `s += a[k]*b[k]` in ascending k, the loop r4d_gemm_bf16_nt_tiled's contract quotes and
* ref_gemm.h's quant_tile runs. No wave reduction, so nothing reassociates: at sk = 1 the output
* is bit-identical to libref's.
*
* Rows past M and columns past N are clamped, not skipped -- a tail lane re-reads the last real row
* and its result is dropped at the store -- so the k loop stays uniform and the loads stay
* straight-line.
* Rows past M and columns past N are clamped, not skipped: a tail lane re-reads the last real row
* and its result is dropped at the store, so the k loop stays uniform and the loads straight-line.
*
* ---- where the bytes come from --------------------------------------------------------------
*
* The activation is staged in LDS and widened on the way in: one row is M <= 16 elements wide per
* k, so a tile is MT * 128 bf16 (4.25 KiB at MT = 16) and one 16-byte load a thread. Staging
* converts bf16 -> f16 once per element with bf16x2_to_f16x2, which is exact, so the dot2 reads
* f16 pairs straight out of LDS and the widening is paid N/MT times less often than it would be
* read. The pitch is 68 dwords: 68 mod 32 = 4, so the eight lanes of a ds_read_b128 phase land on
* banks 4 apart -- conflict-free -- and 68 * 4 = 272 keeps a 16-byte LDS read aligned.
* The activation is staged in LDS: a tile is MT * 128 bf16 (4.25 KiB at MT = 16), one 16-byte load
* per thread. Staging widens bf16 -> f16 once per element with the exact bf16x2_to_f16x2, so the
* dot2 reads f16 pairs straight from LDS and the conversion is not repeated for every weight row.
* The pitch is 68 dwords: 68 mod 32 = 4 puts the eight lanes of a ds_read_b128 phase on banks 4
* apart (conflict-free), and 68 * 4 = 272 bytes keeps a 16-byte LDS read aligned.
*
* The weight is NOT staged. M is tiny, so a staged tile would be read by 32/MT lanes and then
* thrown away; LDS staging buys reuse a skinny shape does not have. Weight bytes go straight from
* global memory into registers, widened there by four v_cvt_pkrtz per eight values (one per dword,
* so one convert per two dot2 products -- the price of the dot2 path being the widening the staged
* row pays once per element), and live for the four products they feed.
* Each wave keeps NT = 32/MT rows resident in L1 (NT lines of 128 B, 4 KiB at MT = 1, the worst
* case), which is what makes 16-byte-per-lane strided reads across NT rows cost what they fetch.
* The weight is not staged: with M this small a staged tile would be read by 32/MT lanes and
* discarded, so LDS buys no reuse. Weight bytes go from global memory into registers, are widened
* there by four v_cvt_pkrtz per eight values (one convert per two dot2 products), and live for the
* four products they feed. Each wave keeps NT = 32/MT rows resident in L1 (NT lines of 128 B,
* 4 KiB at MT = 1, the worst case), so 16-byte-per-lane strided reads across NT rows cost only what
* they fetch.
*
* ---- the register budget --------------------------------------------------------------------
*
* A gfx11 SIMD has 1024 VGPRs for a wave32. The loop is one accumulator, four activation pairs,
* four weight dwords, one 16-byte staging quad and a handful of pointers and counters: about 24
* live VGPRs, so the kernel is nowhere near the 128 that R3D_WAVES(8) -- eight waves a SIMD,
* 1024/8 -- asks for. The target is stated for the reason r3d_common.h gives: unstated, the
* scheduler picks the occupancy itself, and this kernel's throughput is waves in flight, since
* every wave is waiting on a memory load that takes hundreds of cycles. Eight waves a block of
* 256 threads is the default, and `wv` is the axis a tuner walks.
* A gfx11 SIMD has 1024 VGPRs for a wave32. The loop holds one accumulator, four activation pairs,
* four weight dwords, one 16-byte staging quad and some pointers and counters: about 24 live
* VGPRs, far under the 128 that R3D_WAVES(8) (eight waves per SIMD, 1024/8) allows. The target is
* stated for the reason r3d_common.h gives: otherwise the scheduler picks the occupancy, and this
* kernel's throughput is waves in flight, each waiting hundreds of cycles on a memory load. Eight
* waves per 256-thread block is the default; `wv` is the tuner's axis.
*
* ---- split-K --------------------------------------------------------------------------------
*
* At M = 1 a wide N is the only parallelism there is, and N = 48 (a GDN a|b projection) gives three
* waves on a 32-CU card. `sk` splits K into that many contiguous slabs, each owned by one
* blockIdx.y, each writing an f32 partial to the caller's `scratch` arena; a second kernel on the
* same stream adds the partials per output in ascending split order and narrows once.
* At M = 1 the only parallelism is N, and N = 48 (a GDN a|b projection) gives three waves on a
* 32-CU card. `sk` splits K into that many contiguous slabs, one per blockIdx.y, each writing an
* f32 partial to the caller's `scratch` arena; a second kernel on the same stream adds the partials
* per output in ascending split order and narrows once.
*
* The order matters and is stated: summing sk per-slab partials is NOT the ascending sum libref
* forms. Each partial is an ascending sum over its own slab, and the slab sums are then added in
* ascending slab order, which brackets the products differently than a single running chain does.
* sk = 1 is the bit-identical case; sk > 1 agrees to the last bits, which is the same contract
* libr4d's tiled row states about its slices. The row is verified at every sk kbench measures.
* Summing sk per-slab partials is not libref's single ascending chain: the slab sums bracket the
* products differently. sk = 1 is bit-identical; sk > 1 agrees to the last bits, the same contract
* libr4d's tiled row states for its slices. The row is verified at every sk kbench measures.
*
* `sk == 0` means "the largest legal split for this K" off the axis's ladder {16, 8, 4, 2, 1},
* legality being K % (sk * 8) == 0: a slice must end where the inner loop stops, on a group of the
* eight k (four f16 pairs) a lane consumes per step, so a slice boundary never falls inside a
* step. The staged tile is 128 k wide and its last tile is ragged, which is what lets a slice be
* 8 k long, and the cap of 16 is the split the row's scratch hook sizes the arena for.
* `sk == 0` picks the largest legal split from the axis's ladder {16, 8, 4, 2, 1}. A split is legal
* when K % (sk * 8) == 0, so a slice boundary never falls inside a lane's step of eight k (four f16
* pairs). The staged tile is 128 k wide with a ragged last tile, which allows slices as short as
* 8 k. The cap of 16 is the split the row's scratch hook sizes the arena for.
*
* ---- `nt` -----------------------------------------------------------------------------------
*
* RDNA3 has no global_load_tr_b128 (that is RDNA4) and no cache-swizzle field on a global load. So
* `nt` is an axis that measures a knob the ISA does not special-case: nt = 1 issues the weight
* reads through an address-space-1 pointer, which lowers to global_load_b128 with no cache modifier
* and no swizzle -- a plain stream -- and nt = 0 issues the same 16-byte reads through the generic
* pointer, which lowers to flat_load_dwordx4. Nothing is invented here; the axis exists so kbench
* can price the two lowerings and record that on this card they are the same stream.
* RDNA3 has no global_load_tr_b128 (an RDNA4 instruction) and no cache-swizzle field on a global
* load. nt = 1 issues the weight reads through an address-space-1 pointer, which lowers to
* global_load_b128 with no cache modifier and no swizzle; nt = 0 issues the same 16-byte reads
* through the generic pointer, which lowers to flat_load_dwordx4. The axis lets kbench price the
* two lowerings, which on this card stream the same.
*/
/* hip_runtime.h first: it defines __forceinline__, which r3d_codecs.h's R3D_HD spells, and
* r3d_common.h reaches the codecs before it reaches the runtime. */
/* hip_runtime.h first: it defines __forceinline__, which r3d_codecs.h's R3D_HD uses, and
* r3d_common.h includes the codecs before the runtime. */
#include <hip/hip_runtime.h>
#include "r3d.h"
@@ -96,15 +85,14 @@ namespace {
constexpr int kBlockThreads = 256; // eight waves, the default
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kKTile = 128; // k a staged tile of a covers
constexpr int kAPitch = kKTile / 2 + 4; // dwords a staged a row
constexpr int kKTile = 128; // k covered by one staged tile of a
constexpr int kAPitch = kKTile / 2 + 4; // dwords per staged row of a
constexpr int kMTMax = 16; // the band's upper bound
/* The split rule, in one place so the launch, the shim and the row's gemm_tune_valid agree.
* `kUnit` is the k a lane's step consumes -- eight elements, four f16 pairs -- and a slice must be
* whole steps, so a split is legal when K divides by sk * kUnit. The ladder is the row's `sk` axis
* descending, and its top is the split the scratch hook sizes for: a wider split the arena cannot
* hold is not a legal default. */
/* The split rule, shared by the launcher, the shim and the row's gemm_tune_valid. `kUnit` is the
* k one lane step consumes (eight elements, four f16 pairs); a slice must be whole steps, so a
* split is legal when K divides by sk * kUnit. The ladder is the row's `sk` axis descending; its
* top is the split the scratch hook sizes the arena for. */
constexpr int kUnit = 8;
inline int pick_sk(long long K, int maxsk)
{
@@ -114,9 +102,8 @@ inline int pick_sk(long long K, int maxsk)
return 1;
}
/* A 16-byte weight read. NT true is the address-space-1 form: global_load_b128, no cache modifier,
* no swizzle, the plain stream the row's `nt` axis names. NT false goes through the generic
* pointer, which the compiler lowers to flat_load_dwordx4. */
/* A 16-byte weight read. NT true is the address-space-1 form (global_load_b128, no cache modifier,
* no swizzle); NT false goes through the generic pointer (flat_load_dwordx4). See the header. */
template <bool NT>
__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p)
{
@@ -129,19 +116,19 @@ __device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p)
return *(const r3d_u32x4*)p;
}
/* y[M,N] = a[M,K] @ b[N,K]^T, one output element a lane.
/* y[M,N] = a[M,K] @ b[N,K]^T, one output element per lane.
*
* `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the
* narrowed bf16 the caller asked for. With sk > 1 every split writes its own f32 partial, dense
* [sk][M][N], and gemm_split_reduce adds them. */
* `kslab` is the k range one blockIdx.y owns. With sk = 1 it is all of K and the store is bf16.
* With sk > 1 each split writes an f32 partial into a dense [sk][M][N] plane, and
* gemm_split_reduce adds them. */
template <int MT, bool NT, bool SPLIT>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ B,
uint16_t* __restrict__ Y, float* __restrict__ Part,
int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab)
{
/* Staged activation, widened to f16 pairs on the way in. One allocation for the widest MT:
* this kernel is instantiated for MT = 1, 2, 4, 8 and 16 and 4.25 KiB is not worth a template. */
/* Staged activation, widened to f16 pairs. Sized for the widest MT (4.25 KiB) in every
* instantiation. */
__shared__ uint32_t s_a[kMTMax * kAPitch];
const uint32_t tid = threadIdx.x;
@@ -164,13 +151,12 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel(
for (int kt = kbeg; kt < kend; kt += kKTile) {
const int kl = std::min(kKTile, kend - kt);
/* Stage: eight elements a unit, MT * (kl/8) units, 256 threads. A row past M re-reads the
* last real row, whose products the store drops. */
/* Stage: eight elements per unit, MT * (kl/8) units. A row past M re-reads the last real
* row, whose products the store drops. */
const int nu = (kl + 7) / 8;
/* blockDim.x, not the 256-thread default: the wv axis launches one, two, four or eight
* waves, and a stage loop that strides the block constant leaves units staged only for
* the waves that exist -- wv = 1 stages 32 of MT*16 units and the k loop reads the rest of
* the tile out of LDS that was never written. */
/* Stride by blockDim.x, not 256: the wv axis launches one, two, four or eight waves, and a
* fixed stride would leave part of the tile unstaged (wv = 1 would stage 32 of MT*16
* units). */
for (int i = (int)tid; i < MT * nu; i += (int)blockDim.x) {
const int r = i / nu, c = (i % nu) * 8;
const int rr = r < M ? r : M - 1;
@@ -198,33 +184,28 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel(
for (int k = 0; k < kf; k += 8) {
const r3d_u32x4 aw = lds_a(ap + k / 2);
const r3d_u32x4 b16 = ldw<NT>(w + kt + k);
/* The weight is widened here and it is not optional: dot2's operands are f16, and a
* bf16 bit pattern read as f16 is a different number -- bf16's 1.0 (0x3F80) is 1.875 --
* and any magnitude at or above 2^16 is an infinity. Feeding the bytes straight in is
* the trap this ISA sets for a bf16 GEMM that reaches for v_dot2acc_f32_f16, and it
* arrives as an output uncorrelated with the reference at rel ~ 1, with infinities in
* it, which reads as a numerics problem and is a reading problem. Four
* v_cvt_pk_rtz_f16_f32_e32 per eight values, each with the pair's two VALU of unpack,
* so the widening costs one ALU slot per product the dot2 makes; RDNA3 pairs some of
* the dots as v_dual_dot2acc_f32_f16 with the converts riding alongside. */
/* The weight must be widened: dot2's operands are f16, and a bf16 bit pattern read as
* f16 is a different number (bf16 1.0, 0x3F80, reads as 1.875; magnitudes >= 2^16
* become infinities). Four v_cvt_pk_rtz_f16_f32_e32 per eight values, each with two
* VALU of unpack, so the widening costs one ALU slot per dot2 product; RDNA3 pairs
* some of the dots as v_dual_dot2acc_f32_f16 alongside the converts. */
const r3d_u32x4 bw = r3d_u32x4{ bf16x2_to_f16x2(b16.x), bf16x2_to_f16x2(b16.y),
bf16x2_to_f16x2(b16.z), bf16x2_to_f16x2(b16.w) };
acc = dot4_f16x4(aw.x, aw.y, bw.x, bw.y, acc);
acc = dot4_f16x4(aw.z, aw.w, bw.z, bw.w, acc);
}
/* The ragged end of the last slab, ascending. A split is legal only when its slab is whole
* tiles, so this runs at sk = 1 with a K that is not a multiple of 128. */
/* The elements past the last whole step of eight, ascending. The launcher's
* K % (sk * 8) == 0 rule leaves none, so this loop does not run. */
for (int k = kf; k < kl; ++k)
acc = acc + bf16_to_f32((uint16_t)ldg_u16(A + (size_t)m_real * a_ld + kt + k))
* bf16_to_f32((uint16_t)ldg_u16(w + kt + k));
group_barrier(); // the next tile's stage must not race this one's reads
group_barrier(); // the next tile's stage must not race these reads
}
const bool keep = (n0 < (uint32_t)N) && (m < (uint32_t)M);
if (!keep) return;
if constexpr (SPLIT) {
/* Partial plane [sk][M][N]: split-major, so the reducer reads sk values M*N apart and this
* store keeps the same [M][N] shape at every split. */
/* Partial plane [sk][M][N], split-major: the reducer reads sk values M*N apart. */
Part[((size_t)blockIdx.y * M + m) * N + n0] = acc;
} else {
Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc); // narrowed once, here
@@ -232,10 +213,7 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel(
}
/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one narrowing.
*
* This is the order libref's ascending sum produces at sk = 1 and not at sk > 1: each partial is
* ascending over its own slab, and the slab sums bracket the products differently than one chain
* does. The difference is in the last bits and is the split's, not a bug in it. */
* At sk > 1 this differs from libref's single chain in the last bits (see the header). */
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_split_reduce(
const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk)
{
@@ -254,14 +232,14 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_split_reduce(
/* y[M,N] = a[M,K] @ b[N,K]^T, bf16 in and out, f32 accumulate, M <= 16.
*
* a [M][K] bf16, `a_ld` elements a row (0 = K)
* a [M][K] bf16, `a_ld` elements per row (0 = K)
* b [N][K] bf16, row-major, k contiguous
* y [M][N] bf16, `y_ld` elements a row (0 = N)
* y [M][N] bf16, `y_ld` elements per row (0 = N)
*
* `sk` splits K (0 = the largest legal split), `wv` is waves per block (0 = 8), `nt` picks the
* weight load's lowering (see the file header), and `scratch` is the f32 partial arena,
* sk * M * N * 4 bytes, required when the split is on. Returns 0, -1 a null pointer, -2 a shape it
* does not serve, -3 a pitch it cannot read, -4 the HIP launch failed. */
* sk * M * N * 4 bytes, required when sk > 1. Returns 0, -1 a null pointer, -2 an unsupported
* shape, -3 an unreadable pitch, -4 the HIP launch failed. */
extern "C" int r3d_gemm_nt_bf16_m16(long a, long b, long y, int M, int N, int K, int a_ld,
int y_ld, int sk, int wv, int nt, long scratch, long stream)
{
@@ -344,10 +322,10 @@ extern "C" int r3d_rad_gemm_nt_bf16_m16(const RadArgs* a, RadStream s)
const long long y_ld = r3d_rows_pitch(Y, N, &yrows);
if (a_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (arows < M || yrows < M) return R3D_NO(RAD_E_SHAPE);
/* The weight must be dense: every wave reads b[n][k] at n * K + k, and a pitch the launcher
* does not carry cannot be described to it. */
/* The weight must be dense: every wave reads b[n][k] at n * K + k, and the launcher takes no
* weight pitch. */
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
/* 16-byte weight loads, at a row base and at a tile base, both multiples of 8 elements. */
/* 16-byte loads at a row base and at a tile base, both multiples of 8 elements. */
if (a_ld % 8) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN);
+85 -120
View File
@@ -1,76 +1,67 @@
/* r3d_gemm_fp8a16_nt_m1.hip -- the same skinny shape against a block-scaled weight.
/* r3d_gemm_fp8a16_nt_m1.hip -- the skinny GEMM shape (M <= 16) against a block-scaled weight.
*
* y[M,N] = a[M,K] @ b[N,K]^T, b stored as E4M3 codes with one f32 scale per (pb1 x pb2) block,
* f32 accumulate, narrowed once by the store. `a_scale`, when present, means the activation is
* coded too -- quant_act_fp8's E4M3 codes with one f32 per (row, group) -- which is the fp8a8
* form the row table names `fp8a8`.
* y[M,N] = a[M,K] @ b[N,K]^T, b stored as E4M3 codes with one scale (bf16 or f32) per
* (pb1 x pb2) block, f32 accumulate, narrowed once by the store. When `a_scale` is present the
* activation is coded too (quant_act_fp8's E4M3 codes, one f32 per (row, group)): the row
* table's `fp8a8` form.
*
* RDNA3 has no fp8 instruction: the builtins are declared for gfx11 and die at instruction
* selection. So the codes are decoded in software, and the decode is free of cost in the sense
* that matters here: E4M3 is four exponent and three mantissa bits, f16 is five and ten, so
* e4m3x2_to_f16x2 is EXACT and the dot2 multiplies the numbers the checkpoint means. Nothing is
* rounded between the code and the product, which is why this row's output is libref's to the bit
* at sk = 1 and not merely inside fp8 quantisation noise.
* RDNA3 has no fp8 instructions (the builtins are declared for gfx11 but fail at instruction
* selection), so the codes are decoded in software. E4M3 has four exponent and three mantissa
* bits and f16 five and ten, so e4m3x2_to_f16x2 is exact and the dot2 multiplies the checkpoint's
* values. Nothing is rounded between code and product, so at sk = 1 the output matches libref bit
* for bit.
*
* ---- the lane map --------------------------------------------------------------------------
*
* The same as r3d_gemm_bf16_nt_m16's: lane l owns the output (m = l % MT, n = n0 + l / MT) for the
* template's MT = ceil(M) in {1,2,4,8,16}, walks k ascending and holds its own accumulator. One
* difference is forced by the format, and it is the one that makes this kernel what it is: a lane
* consumes sixteen codes per step, because that is what sixteen bytes are, and sixteen bytes is
* one global_load_b128. Eight dot2 per step, so the weight stream is one 16-byte load per eight
* matrix instructions -- the decode (eight v_perms and shifts, exact) sits between them and is the
* reason this kernel's rate is not the bf16 row's.
* As in r3d_gemm_bf16_nt_m16: lane l owns the output (m = l % MT, n = n0 + l / MT), MT being M
* rounded up to {1,2,4,8,16}, walks k ascending and holds its own accumulator. The difference is
* that a lane consumes sixteen codes per step, one global_load_b128, feeding eight dot2. The decode
* (eight v_perms and shifts) sits between load and dot2, so this kernel runs slower than the bf16
* row.
*
* A lane owns one (m, n) pair, so a lane owns one scale per block: `n / pb1` picks b_scale's row
* and the block index picks its column, and both are hoisted out of the block's sixteen-element
* steps. The activation's scale, when the activation is coded, is `m`'s row at the same block
* index. Lanes sharing an n agree on it, which is why no lane-to-lane exchange is needed.
* Each lane owns one (m, n) pair and so one scale per block: `n / pb1` picks b_scale's row and the
* block index its column, both hoisted out of the block's steps. A coded activation's scale is
* `m`'s row at the same block index. No lane-to-lane exchange is needed.
*
* ---- where the scale multiplies -------------------------------------------------------------
*
* ref_gemm.h's quant_tile, and quant_dot beside it, is the spec, and the order it writes is the
* order this kernel runs:
* The order is ref_gemm.h's quant_tile (and quant_dot beside it):
*
* for gi ascending: sub = 0
* for k in the group, ascending: sub += a[k] * b[k] (from the CODES)
* for k in the group, ascending: sub += a[k] * b[k] (from the codes)
* acc = acc + (sub * sa) * sb
*
* with sa = a_scale[m][gi] or 1, and sb = b_scale[n / pb1][gi]. The scale multiplies the finished
* block, once, at the block's end -- not every product: scaling each product is equal in exact
* arithmetic and differs in the last bits, which moves an fp8 code and so moves a token. And
* `(sub * sa) * sb` is an order, not a formula: the parentheses are libref's, and the products are
* summed from the raw codes with no scale folded into them. This kernel accumulates a block's
* sub-sum into a register of its own, so the bracketing is the reference's, and the widening is
* exact, so at sk = 1 the output is bit-identical to it.
* block sub-sum once, not every product: scaling each product is equal in exact arithmetic but
* differs in the last bits, which can move an fp8 code and so a token. The parentheses in
* `(sub * sa) * sb` are libref's and must be kept. Each block's sub-sum has its own register, so
* the bracketing matches the reference.
*
* ---- the activation ---------------------------------------------------------------------------
*
* Staged in LDS per block of the weight's K, widened on the way in: bf16 -> f16 for fp8a16, E4M3 ->
* f16 for fp8a8, both exact. One row of a is M <= 16 elements wide per k, so a staged block is
* MT * 128 values, 4.25 KiB at MT = 16, and the pitch is 68 dwords: 68 mod 32 = 4, so a
* ds_read_b128's eight lanes land on banks four apart, and 272 bytes a row keeps the 16-byte reads
* aligned. The weight is not staged: with M <= 16 a staged tile has 32/MT readers, so staging
* trades a wave's worth of L1 residency for a round trip through LDS and buys nothing.
* Staged in LDS per scale block of K and widened exactly on the way in: bf16 -> f16 for fp8a16,
* E4M3 -> f16 for fp8a8. A staged block is MT * 128 values (4.25 KiB at MT = 16). The pitch is 68
* dwords: 68 mod 32 = 4 puts a ds_read_b128's eight lanes on banks four apart, and 272 bytes per
* row keeps the 16-byte reads aligned. The weight is not staged: with M <= 16 a staged tile has
* only 32/MT readers, so a round trip through LDS gains nothing over L1.
*
* ---- split-K --------------------------------------------------------------------------------
*
* `sk` contiguous slices, one per blockIdx.y, each writing its f32 partial to `scratch` and a
* second kernel adding them per output in ascending slice order. Each partial is a chain of
* `(sub * sa) * sb` terms over its own slices of blocks, so at sk = 1 the chain is libref's
* exactly; sk > 1 brackets the block terms by slice, which is the split's doing and agrees to the
* last bits. Legality is K % (sk * group) == 0 -- a slice that ends mid-block cannot apply that
* block's scale -- which is the row's gemm_tune_valid rule, unit = group.
* `sk` contiguous slices, one per blockIdx.y, each writing its f32 partial to `scratch`; a second
* kernel adds them per output in ascending slice order. sk = 1 is libref's chain exactly; sk > 1
* brackets the block terms by slice and agrees to the last bits. A split is legal when
* K % (sk * group) == 0, because a slice that ends mid-block cannot apply that block's scale (the
* row's gemm_tune_valid rule, unit = group).
*
* ---- `nt` -----------------------------------------------------------------------------------
*
* No transposed load on this ISA and no cache field on a global load. nt = 1 issues the weight
* reads through an address-space-1 pointer, which lowers to global_load_b128 with no cache
* modifier and no swizzle; nt = 0 issues the same 16-byte reads through the generic pointer. The
* axis measures the two lowerings, and on this card it measures the same stream twice.
* This ISA has no transposed load and no cache field on a global load. nt = 1 issues the weight
* reads through an address-space-1 pointer (global_load_b128, no cache modifier, no swizzle);
* nt = 0 issues the same 16-byte reads through the generic pointer. On this card both lowerings
* stream the same.
*/
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD spells
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD uses
#include "r3d.h"
#include "r3d_common.h"
@@ -83,12 +74,12 @@ namespace {
constexpr int kBlockThreads = 256;
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kMTMax = 16;
constexpr int kStep = 16; // codes a lane takes per step: one 16-byte load
constexpr int kAPitch = 68; // dwords a staged activation row (128 values + 4)
constexpr int kStep = 16; // codes per lane step: one 16-byte load
constexpr int kAPitch = 68; // dwords per staged activation row (128 values + 4)
constexpr int kGroupMax = 128; // the stage is sized for one 128-wide block per row
/* A slice is legal when it is a whole number of scale blocks, so the split ladder is capped by
* the scratch hook's widest split and stepped by the block the weight carries. */
/* A slice must be a whole number of scale blocks. The ladder is capped by the scratch hook's
* widest split. */
int pick_sk(long long K, int group, int maxsk)
{
static const int kLadder[] = { 16, 8, 4, 2, 1 };
@@ -116,11 +107,9 @@ __device__ __forceinline__ uint32_t ldg_u8(const uint8_t* p)
/* The weight's 16 codes as eight f16 pairs, exact.
*
* e4m3x2_to_f16x2 decodes the TWO codes in a dword's low half, so a 16-byte load -- four dwords,
* sixteen codes -- is eight decodes, each fed the 16-bit pair it wants: the pairs straddle the
* dwords, four dwords in, eight pairs out. Feeding the codec whole dwords decodes eight codes and
* leaves the rest of the step multiplying registers that were never written, which is the quiet
* version of this bug: the answer comes back a fraction of its size, not a NaN. */
* e4m3x2_to_f16x2 decodes only the two codes in a dword's low half, so a 16-byte load (four
* dwords) is eight decodes, each fed one 16-bit pair. Feeding it whole dwords would decode only
* eight of the sixteen codes and silently shrink the result. */
__device__ __forceinline__ void codes_to_f16x8(const r3d_u32x4 c, uint32_t* w)
{
const uint32_t d[4] = { c.x, c.y, c.z, c.w };
@@ -129,8 +118,8 @@ __device__ __forceinline__ void codes_to_f16x8(const r3d_u32x4 c, uint32_t* w)
w[j] = e4m3x2_to_f16x2((d[j >> 1] >> (16 * (j & 1))) & 0xffffu);
}
/* y[M,N] = a[M,K] @ dequant(b)[N,K]^T. `A8` is the fp8a8 form: a carries E4M3 codes and a_scale
* carries one f32 per (row, block); without it a is bf16 and read directly. */
/* y[M,N] = a[M,K] @ dequant(b)[N,K]^T. `A8` is the fp8a8 form: a is E4M3 codes and a_scale one
* f32 per (row, block); otherwise a is bf16. */
template <int MT, bool A8, bool NT, bool SPLIT>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
const uint8_t* __restrict__ A, const float* __restrict__ AScale,
@@ -155,10 +144,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
const int kend = kbeg + kslab < K ? kbeg + kslab : K;
const uint8_t* w = B + (size_t)n_real * K;
/* b_scale is the container's `weight_scale_inv`, and the op's shape hook writes it bf16 for the
* whole quantised family -- `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})`; f32 belongs to the
* separate `fp8a8f32` spelling. Both are read here; bf16 widens to f32 exactly, since every
* bf16 value is representable in f32, so the widening is free and the products are unchanged. */
/* b_scale is the container's `weight_scale_inv`: bf16 for the whole quantised family (the shape
* hook's `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})`), f32 under the separate `fp8a8f32`
* dtype. Both are read; bf16 widens to f32 exactly. */
const size_t bsrow = (size_t)(n_real / pb1) * nkb;
const float* bsF = bs16 ? nullptr : (const float*)BScale + bsrow;
const uint16_t* bsH = bs16 ? (const uint16_t*)BScale + bsrow : nullptr;
@@ -166,15 +154,15 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
float acc = 0.0f;
/* One scale block per round: stage the block's activation, walk the block's k, fold the block's
* scale in at the end. `kb` is the block's first k, which is where the scales are indexed. */
/* One scale block per iteration: stage the block's activation, walk its k, apply its scale at
* the end. `kb` is the block's first k. */
for (int kb = kbeg; kb < kend; kb += group) {
const int gl = std::min(group, kend - kb);
const int gi = kb / group;
/* Stage gl elements of MT activation rows, widened to f16 pairs. Eight values a unit: a
* 16-byte load for a bf16 row, an 8-byte one for a coded row, which is why the coded row's
* pitch check is eight, not sixteen. A row past M re-reads the last real row. */
/* Stage gl elements of MT activation rows, widened to f16 pairs. Eight values per unit: a
* 16-byte load for a bf16 row, an 8-byte one for a coded row. A row past M re-reads the
* last real row. */
constexpr int kUnit = 8;
const int nu = (gl + kUnit - 1) / kUnit;
for (int i = (int)tid; i < MT * nu; i += (int)blockDim.x) { // see the m16 unit's note on wv
@@ -183,7 +171,7 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
const int cnt = std::min(kUnit, gl - c);
uint32_t* dst = s_a + (size_t)r * kAPitch + c / 2;
if constexpr (A8) {
const uint8_t* src = A + (size_t)rr * a_ld + kb + c; // codes: bytes and elements agree
const uint8_t* src = A + (size_t)rr * a_ld + kb + c; // codes: one byte per element
for (int e = 0; e < cnt; e += 8) {
const uint8_t* sp = src + e;
uint32_t q[2];
@@ -206,8 +194,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
if (e + 2 * t < gl) dst[e / 2 + t] = p[t];
}
} else {
/* A is a byte pointer here because the coded form codes it: cast first, then the
* row and k offsets are ELEMENT offsets, which for bf16 is twice the byte count. */
/* A is a byte pointer (for the coded form): cast first, so the row and k offsets
* are bf16 element offsets. */
const uint16_t* src = (const uint16_t*)A + (size_t)rr * a_ld + kb + c;
for (int e = 0; e < cnt; e += 8) {
uint32_t p[4];
@@ -248,10 +236,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
sub = dot4_f16x4(a1.x, a1.y, b[4], b[5], sub);
sub = dot4_f16x4(a1.z, a1.w, b[6], b[7], sub);
}
/* The last partial block, when K is not a whole block: ascending, two k at a time, each
* code decoded on its own. The launcher refuses a K that is not a multiple of the block
* (a ragged block would read past the scale plane), so this is a shape the kernel carries
* for completeness and the row never issues. */
/* A partial block's tail, ascending, two k at a time. The launcher refuses a K that is not
* a multiple of the block (a ragged block would read past the scale plane), so this loop
* does not run. */
for (int k = gf; k < gl; k += 2) {
const uint32_t aw = ap[k / 2];
const uint32_t c0 = ldg_u8(w + kb + k);
@@ -259,9 +246,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
const uint32_t pw = e4m3x2_to_f16x2(c0 | (c1 << 8));
sub = dot2_f16x2(aw, pw, sub);
}
group_barrier(); // the next block's stage must not race this one's reads
group_barrier(); // the next block's stage must not race these reads
/* The block's finished sub-sum, scaled once, in libref's parentheses. */
/* The block's sub-sum, scaled once, in libref's parentheses. */
const float sa = A8 ? as[gi] : 1.0f;
acc = acc + (sub * sa) * (bs16 ? bf16_to_f32(bsH[gi]) : bsF[gi]);
}
@@ -275,9 +262,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
}
}
/* The split reduction, the m16 unit's, in the same order: v = ((p0 + p1) + p2) + ... ascending by
* slice, then one narrowing. Ascending slice order is libref's ascending sum only at sk = 1; past
* that the block terms are bracketed by slice, which is the split's cost and is stated as such. */
/* The split reduction, as in the m16 unit: v = ((p0 + p1) + p2) + ... ascending by slice, then one
* narrowing. */
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_reduce(
const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk)
{
@@ -300,12 +286,12 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_reduce(
* a_scale [M][ceil(K/group)] f32, or 0
* b [N][K] E4M3 codes, row-major, k contiguous
* b_scale [ceil(N/pb1)][ceil(K/pb2)] bf16 (the container's weight_scale_inv) or f32, block-major
* y [M][N] bf16, `y_ld` elements a row (0 = N)
* y [M][N] bf16, `y_ld` elements per row (0 = N)
*
* `group` is the code group along K (pb2, the checkpoint's block width); `pb1` the rows sharing a
* scale row (0 = group). `sk` splits K (0 = the widest legal), `nt` the weight load's lowering,
* `scratch` the f32 partial arena, sk * M * N * 4 bytes, required when the split is on. Returns 0,
* -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 HIP failed. */
* scale row (0 = group). `sk` splits K (0 = the widest legal), `nt` picks the weight load's
* lowering, `scratch` is the f32 partial arena, sk * M * N * 4 bytes, required when sk > 1. Returns
* 0, -1 a null pointer, -2 an unsupported shape, -3 an unreadable pitch, -4 HIP failed. */
extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, int M,
int N, int K, int group, int pb1, int pb2, int a_ld, int y_ld,
int sk, int nt, long scratch, int bs_dt, long stream)
@@ -316,7 +302,7 @@ extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale,
if (group <= 0) group = R3D_FP8_BLOCK;
if (pb1 <= 0) pb1 = group;
if (pb2 == 0) pb2 = group;
if (pb2 != group) return -2; // one block: the K block IS the code group
if (pb2 != group) return -2; // the K block is the code group
if (group > kGroupMax) return -2;
if (group % kStep) return -2; // a block must be whole lane steps
if (K % group) return -2; // a ragged block reads past the scale plane
@@ -372,20 +358,6 @@ extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale,
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* The declaration in r3d.h carries no scale dtype, and the weight's block scales are bf16 for the
* whole quantised family (see the entry above), so the family needs a second spelling. `_ex` adds
* `bs_dt`, the b_scale plane's RadDataType: RAD_BF16 reads it as bf16, anything else -- 0 included
* -- reads it as f32, which is exactly what the entry below, and every caller written before the
* bf16 discovery, asks for. The shim takes the dtype off the operand and calls `_ex`; the old entry
* forwards, so a raw caller of the old name sees the behaviour it was written against. */
extern "C" int r3d_gemm_nt_q_fp8(long a, long a_scale, long b, long b_scale, long y, int M, int N,
int K, int group, int pb1, int pb2, int a_ld, int y_ld, int sk,
int nt, long scratch, long stream)
{
return r3d_gemm_nt_q_fp8_ex(a, a_scale, b, b_scale, y, M, N, K, group, pb1, pb2, a_ld, y_ld, sk,
nt, scratch, RAD_F32, stream);
}
/* ============================================================== the plugin ABI entry point
*
* gemm_nt_q's operands are [a, a_scale, b, b_scale, y, a_sum?, b_ref?] and its parameters M, N, K,
@@ -396,9 +368,8 @@ enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF };
static int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; }
static int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
/* The trace latch for this file: distinct GEMM shapes, printed once each. A static array and a
* counter, no lock -- the flag is a diagnostic and a doubled line is a cosmetic cost, a lock in
* the served path is not. */
/* The trace latch: distinct GEMM shapes, printed once each. A static array and a counter, no lock:
* the trace is a diagnostic, and a duplicated line is cheaper than a lock on the served path. */
struct GemmPlanKey { long long M, N, K; unsigned a_rank, as_rank; long long a_ld, y_ld; };
static bool gemm_plan_once(long long M, long long N, long long K, unsigned a_rank,
@@ -422,13 +393,11 @@ extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s)
const RadTensor* BS = r3d_opt(a, Q_BSCALE);
const RadTensor* Y = r3d_opt(a, Q_Y);
if (!A || !B || !BS || !Y) return R3D_NO(RAD_E_INVAL);
/* The schemes this kernel decodes: E4M3 codes on the weight, bf16 activations (fp8a16) or
* E4M3 codes with their own scale (fp8a8). E5M2 has no decoder here. */
/* E4M3 weight codes with bf16 activations (fp8a16) or E4M3 activation codes with their own
* scale (fp8a8). E5M2 has no decoder here. */
if (!r3d_is_e4m3(B)) return R3D_NO(RAD_E_DTYPE);
/* The weight's block scales are bf16 for the whole quantised family -- the shape hook's
* `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})` is the container's `weight_scale_inv`, and f32 is
* the separate `fp8a8f32` spelling, which no row here claims (those bands stay with the
* reference). Accept both; the kernel widens bf16 -> f32 at the load, exactly and for free. */
/* Block scales are bf16 in the quantised family; f32 is the separate `fp8a8f32` dtype, which no
* row here claims. Both are accepted; the kernel widens bf16 exactly at the load. */
const bool bs16 = r3d_is_bf16(BS);
if (!bs16 && !r3d_is_f32(BS)) return R3D_NO(RAD_E_DTYPE);
R3D_NEED(dt_bf16(Y));
@@ -448,8 +417,8 @@ extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s)
const long long M = nel / N; // never from the `M` parameter
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
/* The block geometry, and the disagreement libref refuses: `group` is what the selector
* matched on, and pb2 is the checkpoint's, and they describe the same bytes. */
/* The block geometry. `group` is what the selector matched and pb2 the checkpoint's block
* width; they describe the same bytes, and libref refuses a disagreement. */
const long long group = r3d_geti_or(a, "group", R3D_FP8_BLOCK);
const long long pb1 = r3d_geti_or(a, "pb1", group), pb2 = r3d_geti_or(a, "pb2", group);
if (group != R3D_FP8_BLOCK) return R3D_NO(RAD_E_SHAPE);
@@ -460,8 +429,8 @@ extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s)
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(BS) < nrowb * nkb) return R3D_NO(RAD_E_SHAPE);
if (AS && r3d_numel(AS) < M * nkb) return R3D_NO(RAD_E_SHAPE);
/* `a_sum` removes an activation zero point this grid does not have, and `b_ref` is an mxfp4
* scale reference: libref refuses both beside these schemes (gemm_ntq_impl), so we do. */
/* `a_sum` removes an activation zero point this grid lacks, and `b_ref` is an mxfp4 scale
* reference; libref refuses both with these schemes (gemm_ntq_impl). */
if (r3d_opt(a, Q_ASUM)) return R3D_NO(RAD_E_UNSUPPORTED);
if (r3d_opt(a, Q_BREF)) return R3D_NO(RAD_E_UNSUPPORTED);
@@ -479,14 +448,10 @@ extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s)
if ((a8 && (a_ld % 8)) || (!a8 && (a_ld % 8))) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN);
/* The plan's own numbers for the M<=16 band, under RAD_R3D_TRACE=1 and once per distinct
* shape -- the same instrument the tiled row carries, in the row that serves the short steps.
* It lives here because the served collapse begins at 15 prompt tokens, a step the tiled shim
* never sees: the ladder's numbers below 17 are M=5..16 and the tiled row's line cannot speak
* for them. M is derived off the activation's output the way the row derives it (line 430:
* numel(y)/N, never the `M` parameter), and nothing is read that the checks above did not
* already require. With the flag unset this is one cached getenv and a return: no copy, no
* latch slot, no new operand read, no syscall. */
/* Under RAD_R3D_TRACE, print the plan's numbers once per distinct shape for the M <= 16 band,
* which the tiled row's trace does not cover. M is numel(y)/N as above, and nothing is read
* beyond what the checks already required. With the flag unset this is one cached getenv and
* a return. */
if (r3d_trace_on() && gemm_plan_once(M, N, K, A->rank, AS ? AS->rank : 0u, a_ld, y_ld)) {
std::fprintf(stderr, "[r3d] plan: gemm M=%lld (band M<=%d) N=%lld K=%lld group=%lld "
"a rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld rows=%lld "
+182 -262
View File
@@ -1,128 +1,101 @@
/* r3d_gemm_fp8a8_gated.hip -- gemm_nt_q_gated: the gated MLP's GEMM, its gate and its quantiser in
* one launch. 48 bands on one 2B model (N=12288 K=2048 group=128 dtype=fp8a8 act=silu, M=64 x47
* and M=16), and the reason the [M, N] bf16 intermediate never exists.
/* r3d_gemm_fp8a8_gated.hip -- gemm_nt_q_gated: the gated MLP's GEMM, gate and quantiser in one
* launch, so the [M, N] bf16 intermediate is never materialised. On the 2B model it serves
* (N=12288 K=2048 group=128 dtype=fp8a8 act=silu) 47 bands are M=64 and one is M=16.
*
* y[M,n] = gate(a[M,K] @ b[N,K]^T), quantised: n = N/2, gate half = b's rows [0, n),
* up half = [n, N). `q` is E4M3 codes over y, `scale` one f32 per (row, `group` of n), and
* `out_bf16`, when bound, is exactly the bf16 the codes were taken over.
* `out_bf16`, when bound, is the bf16 the codes were taken over.
*
* The law is ref_gemm_nt_q_gated and it is transcribed in its order:
* Transcribed from ref_gemm_nt_q_gated, in its order:
*
* row[j] = quant_dot(ma, mb, SA, SB, m, j, K) over the FULL N, j ascending
* gt = round_bf16(row[i]), up = round_bf16(row[n + i]) BOTH halves, before the gate
* sg = 1 / (1 + exp(-gt)) the gate is the FIRST half
* row[j] = quant_dot(ma, mb, SA, SB, m, j, K) over the full N, j ascending
* gt = round_bf16(row[i]), up = round_bf16(row[n + i]) both halves, before the gate
* sg = 1 / (1 + exp(-gt)) the gate is the first half
* h = f32_to_bf16((act == silu ? gt * sg : sg) * up) the activation is not narrowed
* fp8_row(h, n, group) amax -> scale[m, group], codes
*
* Both halves are narrowed before the gate because the unfused pair writes a bf16 [M, N] tensor and
* re-reads it: the fused form must be byte-identical to the pair it replaces, so the narrowing that
* the store performed is kept, and `out_bf16` is what the pair's tensor held. The activation itself
* is NOT narrowed -- `gt * sg` is formed in f32 from the narrowed gate, and the product with `up`
* Both halves are narrowed before the gate because the unfused pair writes and re-reads a bf16
* [M, N] tensor, and the fused form must be byte-identical to it; `out_bf16` is what that tensor
* held. The activation is not narrowed: `gt * sg` is formed in f32 and the product with `up`
* rounds once, at the store.
*
* ---- the lane map: one lane owns a PAIR of dots -----------------------------------------------
* ---- the lane map: one lane owns a pair of dots -----------------------------------------------
*
* The gate couples column i with column n + i, and a wave covers 32 consecutive columns, so the
* partner column is 192 waves away for the band's n = 6144: no lane-to-lane exchange reaches it, and
* staging a whole row through LDS to reach it costs a round trip of the [M, N] tensor this op exists
* to avoid. So the lane owns BOTH products of its column: it walks k ascending with two accumulators
* and reads two weight rows, `i` and `n + i`. The weight traffic is unchanged -- the pair of rows is
* exactly the traffic the unfused GEMM spent on the two columns -- and the coupling is free.
* The gate couples column i with column n + i, which for n = 6144 is 192 waves away: no lane
* exchange reaches it, and staging the row through LDS would cost the round trip this op avoids.
* So each lane computes both products of its column, walking k ascending with two accumulators over
* weight rows `i` and `n + i`. The weight traffic equals the unfused GEMM's for the two columns.
*
* A block covers ONE group of `group` output columns and RP = 256 / group rows, so a lane is
* A block covers one group of `group` output columns and RP = 256 / group rows:
*
* i = blockIdx.x * group + (tid % group) m = blockIdx.y * RP + tid / group
*
* and a wave's 32 lanes are 32 consecutive columns of one group of one row, for group >= 32. That
* alignment is what closes the epilogue inside the block: the group's amax is a wave max folded over
* the group's group/32 waves in LDS, the scale is one store, the codes are one byte a lane. The
* whole op -- product, gate, quantiser -- is one launch and no scratch, which is why the row is
* concurrent (`rad_kernel_concurrent(i)` is `scratch == nullptr`) and why the bf16 row of the
* intermediate is not written, read, or allocated.
* so for group >= 32 a wave's 32 lanes are 32 consecutive columns of one group of one row. The
* epilogue therefore closes inside the block: the group's amax is a wave max folded over group/32
* waves in LDS, the scale is one store, the codes one byte per lane. The op is one launch with no
* scratch, so the row is concurrent (`rad_kernel_concurrent(i)` is `scratch == nullptr`).
*
* ---- the two streams: fp8a8 at M <= 8 reads the codes, the rest stages them -------------------
* ---- the two arms: fp8a8 at M <= 8 reads the codes directly, the rest stage them --------------
*
* The band's served case is a decode: one row, the whole 12288 x 2048 operand, 42 calls a token.
* The shape above is built for the band's declared ceiling (M = 64, 47 of the 48 bands) and serves
* that height well; at M = 1 it spends 987 us on 24 MiB of codes, 25 GB/s, and the reason is not
* the loads. It is the path a code takes: global -> LDS stage -> decode -> dot, with two
* `group_barrier`s per k-block holding the block in step, and a decoder of ten VALU a code (RDNA3
* has no fp8 instruction: r3d_codecs.h, and the builtins that look like one are rejected at
* instruction selection on gfx1102).
* The staged shape below suits the bands' ceiling (M = 64) but not decode (M = 1, the whole
* 12288 x 2048 operand, 42 calls per token). Its cost there is the path a code takes: global ->
* LDS stage -> decode -> dot, with two `group_barrier`s per k-block, and an arithmetic decoder of
* ten VALU per code (RDNA3 has no fp8 instructions; see r3d_codecs.h). The launcher picks the arm
* by row count:
*
* So the arm is chosen by the row count, in the launcher, from the same band key:
* M <= 8 and fp8a8 read the activation and both weight rows directly, 16 bytes at a time,
* decode them from a 256-entry table the block builds once, and multiply. No
* shared memory between load and dot, no barrier in the k-loop, six loads in
* flight.
* M >= 9, and every fp8a16 case the staged shape, with the same table decoder. At these
* heights the grid is 48 x M/2 blocks and occupancy feeds the stream.
*
* M <= 8 and fp8a8 read the activation and both weight rows straight from memory, 16 bytes at
* a time, decode them out of a 256-entry table the block builds once, and
* multiply. No shared memory between a load and a dot, no barrier in the
* k-loop, six loads in flight.
* M >= 9, and every fp8a16 case the shape above, with the same table decoder in place of the
* arithmetic one. At these heights the grid is 48 x M/2 blocks and occupancy,
* not the window, is what feeds the stream; the stage pays for itself.
* On the band's stream (24 MiB of codes, kernel loop without the epilogue) the staged arithmetic
* path takes 497 us, the direct table path 187 us, and the bare loads 139 us. The table decoder
* also cuts M = 64 by about two thirds at no register cost (109 per lane, four waves per SIMD, no
* spills).
*
* Measured on the band, vram, GPU 2, nine launches timed on their own, best/median:
*
* M = 1 987.4 / 1154.9 -> 171.3 / 181.6 us (147 GB/s of codes; the card's 163 GB/s
* M = 2 1120.6 / 1196.5 -> 166.2 / 177.1 us floor for 24 MiB is 154 us, and the same
* M = 4 1417.3 / 1581.2 -> 221.0 / 229.6 us sixteen loads with no decode and no dot
* M = 8 1874.0 / 2318.0 -> 403.4 / 412.3 us run in 139 us)
* M = 16 2949.3 / 3226.1 -> 1055.0 / 1160.6 us
* M = 32 5123.4 / 5405.1 -> 1660.6 / 1705.0 us
* M = 64 8395.3 / 9051.0 -> 2786.5 / 2877.3 us
*
* The two numbers behind the shape, both from the band's own stream (24 MiB of codes, vram, 11
* launches, this kernel's loop with the epilogue off): staged through LDS and decoded arithmetically
* 497 us; read straight and decoded from the table 187 us; the read alone 139 us. The table alone
* moves M = 64 from 8395 us to 2786 us -- two thirds of the tall arm's gain is the decoder, and it
* costs nothing in registers (109 a lane, four waves a SIMD, zero spills).
*
* Two things in this file are load-bearing. The table's argument is a PAIR, not an index (see
* build_e4m3_table). And the decoded pairs go from the table into the dot inline, never through an
* array (see the tall arm's step_body).
* Two invariants: the table builder's codec argument is a pair, not an index (build_e4m3_table),
* and decoded pairs go from the table into the dot inline, never through an array (step_body).
*
* ---- where the scale multiplies -------------------------------------------------------------
*
* quant_dot, unchanged from r3d_gemm_fp8a16_nt_m1.hip: per group of k a sub-sum from zero over
* ascending k of the CODES' products, then `acc = acc + (sub * sa) * sb` -- the parentheses are the
* reference's, the scale multiplies the finished block once, and `sa` is `a_scale[m][gi]` (1 when
* the activation carries no scale plane). Each lane's two chains are the two calls the unfused pair
* makes, so the bracketing is the pair's, element for element.
* quant_dot, as in r3d_gemm_fp8a16_nt_m1.hip: per group of k a sub-sum from zero over ascending k
* of the codes' products, then `acc = acc + (sub * sa) * sb` with the reference's parentheses, `sa`
* being `a_scale[m][gi]` (1 without a scale plane). Each lane's two chains are the unfused pair's
* two calls, so the bracketing matches element for element.
*
* b_scale is bf16: this op's shape hook writes `o.t(RAD_BF16, {nb, kb})` with no f32 spelling, so
* the plain entry reads the plane as bf16 and the `_ex` twin takes the dtype, as the fp8 GEMM's
* does. bf16 -> f32 widening is exact, so an f32 plane carrying the same values must produce
* bit-identical output; the driver tests exactly that.
* b_scale is bf16: this op's shape hook writes `o.t(RAD_BF16, {nb, kb})` with no f32 form, so the
* plain entry reads bf16 and the `_ex` entry takes the dtype, as for the fp8 GEMM. bf16 -> f32
* widening is exact, so an f32 plane with the same values gives bit-identical output (the test
* driver checks this).
*
* ---- the epilogue's one transcendental -------------------------------------------------------
*
* libref's sigmoid is `1.0f / (1.0f + (float)std::exp((double)(-x)))`. There is no f64 ALU on this
* card (1:64, emulated), and the band asks for M*n = 393216 exponentials a layer, which is
* attention's regime and not the sampler's. `expf` is the accurate device form, as in
* r3d_gated_quant_fp8's kernel (r3d_quant_fp8.hip), not `__expf`; what it feeds is a bf16
* narrowing, whose ulp is 2^-8 against the transcendental's ~1e-7, so the narrowing lands the same
* bf16 everywhere but on a tie. The count of those ties is in the row's prose, measured.
* libref's sigmoid is `1.0f / (1.0f + (float)std::exp((double)(-x)))`. f64 runs at 1:64 on this
* card, and the band needs M*n = 393216 exponentials per layer, so the kernel uses the accurate
* device `expf` (not `__expf`), as r3d_gated_quant_fp8 (r3d_quant_fp8.hip) does. Its ~1e-7 error is
* far under the bf16 ulp of 2^-8 the result is narrowed to, so the bf16 differs only on a tie; the
* row's text records the tie count.
*
* ---- what the launcher refuses ----------------------------------------------------------------
*
* M > 64 (the bands' ceiling, and past it the weight stream -- M reads of an [N, K] plane from L2 --
* is the wall, which is a tiled kernel's problem, not this one's); N odd (the reference's own
* `N & 1` test); a group that is not a power of two in [32, 256] (a wave must sit inside one group,
* and the block is one group wide); group > n, where the reference defaults the QUANTISER's group to
* n and leaves the weight's K block at the stated width: two widths this kernel reads as one, so it
* refuses rather than serve a geometry whose two grids disagree; K % group != 0, because a ragged K
* block reads past the scale plane; sk > 1, because no K slab closes an epilogue that needs the
* whole row. Refusals are codes: -1 null, -2 shape, -3 pitch, -4 HIP.
* M > 64 (the bands' ceiling; beyond it the M reads of an [N, K] plane from L2 are a tiled
* kernel's problem); N odd (the reference's `N & 1` test); a group that is not a power of two in
* [32, 256] (a wave must sit inside one group, and the block is one group wide); group > n, where
* the reference would use n for the quantiser's group but keep the stated K block, two widths this
* kernel reads as one; K % group != 0, because a ragged K block reads past the scale plane; sk > 1,
* because the epilogue needs the whole row. Codes: -1 null, -2 shape, -3 pitch, -4 HIP.
*
* ---- relayout: none, and it is a claim ---------------------------------------------------------
* ---- no relayout ------------------------------------------------------------------------------
*
* libref reads the gated weight [N, K] row-major; libr4d stores fp8a8 weights in WMMA fragment order
* (`r4d.fp8.w.frag64`). The two readings are ~1.35 apart, a relative error, not noise, so this row
* carries no relayout and says so: a row that inherits the fp8 GEMM's unrelayout scores 1.35 against
* the per-op oracle and reads as a broken kernel. The stored order is the reading order here, which
* is the library's rule for every row.
* This row reads the gated weight [N, K] row-major, as libref does. libr4d stores fp8a8 weights in
* WMMA fragment order (`r4d.fp8.w.frag64`); the two readings differ by a relative error of ~1.35,
* so a row that inherited the fp8 GEMM's relayout would fail the per-op oracle. The stored order
* is the reading order, as for every row in the library.
*/
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD spells
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD uses
#include "r3d.h"
#include "r3d_common.h"
@@ -134,27 +107,23 @@ namespace {
constexpr int kBlockThreads = 256;
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kStep = 16; // codes a lane takes per step: one 16-byte load
constexpr int kWin = 64; // codes a lane takes per WINDOW: four loads per stream
constexpr int kStep = 16; // codes per lane step: one 16-byte load
constexpr int kGroupMin = 32; // a wave's 32 columns must sit inside one group
constexpr int kGroupMax = 256; // a block is one group wide, at 256 threads
constexpr int kMMax = 64; // the bands' ceiling: 47 of the 48 are M = 64
constexpr int kMMax = 64; // the bands' ceiling
constexpr float kTopE4M3 = 448.0f; // q8_group's top for E4M3: the largest finite code
/* The E4M3 decoder as a table: 256 f16, one entry per code. The codec's arithmetic decode is ten
* VALU a code (r3d_codecs.h -- RDNA3 has no fp8 instruction, and the builtins that look like one
* are rejected at instruction selection), and this kernel decodes every weight code it multiplies,
* twice over at RP = 2, which at M = 1 is every code in the operand. The table costs two
* `ds_read_u16` and a pack a PAIR, and it is exact by construction: the entry for code c is the
* dword the arithmetic path returns for c, computed by that path at the block's first instruction.
* The unit test reads all 256 entries back and compares them with the codec. */
* VALU per code (r3d_codecs.h), and this kernel decodes every weight code it multiplies (twice at
* RP = 2). The table costs two `ds_read_u16` and a pack per pair, and is exact: entry c is what the
* arithmetic path returns for c, computed by that path at block start. The unit test reads all 256
* entries back and compares them with the codec. */
__device__ __forceinline__ void build_e4m3_table(uint16_t* tab, uint32_t tid)
{
for (uint32_t u = tid; u < 128; u += kBlockThreads)
/* The codec's argument is a PAIR, low code in the low byte; the entry is indexed by code.
* Feeding it the index alone fills the even entries and decodes code 0 into every odd one,
* so the kernel multiplies half the plane by zero -- the board's `codes256` case, whose
* weight is the code enumeration, shows it: rel_l2 9.6e-01, not a NaN. */
/* The codec's argument is a pair, low code in the low byte; the entry is indexed by code.
* Passing the index alone would decode code 0 into every odd entry and silently zero half
* the products (the `codes256` test case catches this). */
*(uint32_t*)&tab[2 * u] = e4m3x2_to_f16x2((u * 2) | ((u * 2 + 1) << 8));
}
@@ -165,10 +134,9 @@ __device__ __forceinline__ uint32_t tab_pair(const uint16_t* tab, uint32_t pair)
return lo | (hi << 16);
}
/* One step of the skinny arm: sixteen codes of activation and sixteen of weight, both coded, both
* out of the same table. This is the whole of the reference's inner step -- `sub += a[k] * b[k]`,
* k ascending -- with the pairs decoded as each dot consumes them. Four dot4, the pairs in order,
* one accumulator; nothing about it depends on where the bytes came from. */
/* One step of the skinny arm: sixteen activation codes and sixteen weight codes, both decoded from
* the same table as each dot consumes them. The reference's `sub += a[k] * b[k]`, k ascending: four
* dot4, pairs in order, one accumulator. */
__device__ __forceinline__ float dot_coded_step(const uint16_t* tab, const r3d_u32x4 a,
const r3d_u32x4 c, float sub)
{
@@ -183,14 +151,11 @@ __device__ __forceinline__ float dot_coded_step(const uint16_t* tab, const r3d_u
return sub;
}
/* One step's sixteen codes into the accumulator: four dot4, the pairs decoded out of the table as
* each dot consumes them. Materialising the eight pairs first and feeding the dots from the array
* is what the register file cannot afford here: the scheduler hoists the sixteen table reads, so
* all eight decoded pairs are live at once on top of the window's loads. Consuming a pair in the
* dot that wants it keeps two registers live where the array keeps eight -- which is the
* difference between this arm compiling at zero spills and spilling 374 bytes against the
* 128-register budget a 256-thread block gets at four waves a SIMD. The order is unchanged: the
* pairs ascend, four dot4 a step, into one accumulator. */
/* One step's sixteen weight codes into the accumulator: four dot4, pairs decoded from the table as
* each dot consumes them. Materialising the eight pairs in an array first lets the scheduler hoist
* all sixteen table reads, keeping eight decoded pairs live instead of two, which spills against
* the 128-register budget of a 256-thread block at four waves per SIMD. Pairs ascend into one
* accumulator. */
__device__ __forceinline__ float dot_step(const uint16_t* tab, const r3d_u32x4 c,
const r3d_u32x4 a0, const r3d_u32x4 a1, float sub)
{
@@ -211,8 +176,8 @@ __device__ __forceinline__ r3d_u32x4 ldc(const uint8_t* p) // 16 codes
__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p) { return *(const r3d_u32x4*)p; }
/* q8_group's clamp, with q8_group's comparisons: fminf/fmaxf replace a NaN with the bound, and a NaN
* activation is a value the reference encodes as the format's NaN, not as +-top. */
/* q8_group's clamp, with q8_group's comparisons rather than fminf/fmaxf, which would replace a NaN
* with the bound; the reference encodes a NaN activation as the format's NaN, not +-top. */
__device__ __forceinline__ float clamp_top(float c)
{
if (c > kTopE4M3) c = kTopE4M3;
@@ -220,16 +185,15 @@ __device__ __forceinline__ float clamp_top(float c)
return c;
}
/* y[M,n] = gate(a @ b^T), with the quantiser. GROUP is the block's width in output columns AND the
* weight's K block AND the quantiser's group: one `group` parameter, three grids, which is what the
* op states: kb, nb and ng are derived from the one key. ACT is the gate, A8 the coded activation,
* NT the weight load's lowering.
/* y[M,n] = gate(a @ b^T), with the quantiser. GROUP is at once the block's width in output columns,
* the weight's K block and the quantiser's group: the op states one `group` key, and kb, nb and ng
* derive from it. ACT is the gate, A8 the coded activation, NT the weight load's lowering, WIN the
* skinny (direct-read) arm.
*
* The activation is staged in LDS per K block, widened to f16 pairs on the way in -- E4M3 -> f16 and
* bf16 -> f16 are both exact over f16's normal range. A block stages RP * GROUP values, 512 bytes at
* every supported GROUP, and a wave reads its row's 16 values per step as one broadcast ds_read: all
* 32 lanes of a wave own the same m, so all 32 read the same address. The weight is not staged: a
* lane streams two rows of it and no other lane reads them with it. */
* The tall arm stages the activation in LDS per K block, widened exactly to f16 pairs. A block
* stages RP * GROUP values (512 bytes at every supported GROUP). All 32 lanes of a wave share one
* m, so a wave reads its row's 16 values per step as one broadcast ds_read. The weight is not
* staged: each lane streams two rows no other lane reads. */
template <int GROUP, int ACT, bool A8, bool NT, bool WIN>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_kernel(
const uint8_t* __restrict__ A, const float* __restrict__ AScale,
@@ -237,8 +201,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
uint8_t* __restrict__ Q, float* __restrict__ S, uint16_t* __restrict__ Y,
int M, int N, int K, int a_ld, int q_ld, int y_ld, int nkb, int ng)
{
constexpr int RP = kBlockThreads / GROUP; // rows a block carries
constexpr int AP = GROUP / 2; // dwords a staged activation row (f16 pairs)
constexpr int RP = kBlockThreads / GROUP; // rows per block
constexpr int AP = GROUP / 2; // dwords per staged activation row (f16 pairs)
constexpr int WPG = GROUP / kWave; // waves covering one group of columns
static_assert(RP >= 1 && WPG >= 1 && RP * WPG == kWaves, "a block is one group wide");
@@ -250,10 +214,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
/* The block's decoder, filled before any lane reads it: 128 dwords, one per pair of codes, by
* the codec's own arithmetic. The cost is 128 decodes a block -- at the band's M = 64 that is
* 0.02% of the block's decodes, and at M = 1 it is paid once per block for 128 codes x 16 k
* blocks of table reads. */
/* The block's decoder table, filled before any lane reads it: 128 dwords, one per pair of
* codes, 128 arithmetic decodes per block. */
build_e4m3_table(s_tab, tid);
group_barrier();
@@ -263,15 +225,15 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
const uint32_t m = (uint32_t)blockIdx.y * RP + mloc;
const int n = N / 2;
/* A ragged last group runs past n: the pair's rows are clamped, so no lane reads past the weight
/* A ragged last group runs past n: the pair's rows are clamped so no lane reads past the weight
* plane, and its stores are guarded below. A row past M re-reads the last real row. */
const int i_real = (int)(i < (uint32_t)n ? i : (uint32_t)(n - 1));
const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1));
const uint8_t* wg = B + (size_t)i_real * K; // the gate's row
const uint8_t* wu = B + (size_t)(n + i_real) * K; // the up's row, n rows further on
/* b_scale is [ceil(N/group)][ceil(K/group)]: make_scales gives rblk = group (fewer scale rows
* than operand rows is a block grid), so a row's scale row is its row index over the block. */
/* b_scale is [ceil(N/group)][ceil(K/group)] (make_scales uses rblk = group), so a row's scale
* row is its row index divided by the block. */
const size_t bsg = (size_t)((uint32_t)i_real / GROUP) * (size_t)nkb;
const size_t bsu = (size_t)((uint32_t)(n + i_real) / GROUP) * (size_t)nkb;
const float* bsF = bs16 ? nullptr : (const float*)BScale;
@@ -280,23 +242,19 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
float acc_g = 0.0f, acc_u = 0.0f;
/* One scale block per round, `nkb` of them: stage the block's activation, walk the block's k
* with two chains, fold the block's two scales in at the block's end. K is a multiple of GROUP,
* which the launcher requires, so every block is whole and the staging loop has no tail. */
/* The skinny arm's activation pointer: the row, in bytes. */
/* One scale block per iteration, `nkb` of them: stage the block's activation, walk its k with
* two chains, apply its two scales at the end. The launcher requires K % GROUP == 0, so every
* block is whole and staging has no tail. */
/* The skinny arm's activation row, in bytes. */
const uint8_t* ar = (A8 && WIN) ? (const uint8_t*)A + (size_t)m_real * a_ld : nullptr;
for (int kb = 0; kb < K; kb += GROUP) {
const int gi = kb / GROUP;
/* The staged round, and the barrier around it, belong to the tall arms. At the skinny height
* -- M <= 8, the threshold `R3D_GT_G` selects on, 16 KiB of activation at the band's K --
* the whole activation is M*K bytes and the 48 column groups of a row all
* read the same slice of it, so it lives in L1 from the first k-block on and staging it
* through shared memory buys nothing but a barrier a block a k-block. The numbers: the
* same stream read straight from memory 187 us, the same stream staged through LDS 497 us,
* at 48 blocks, 24 MiB of codes, on a part of this family. */
/* Staging and its barrier belong to the tall arm. At the skinny height (M <= 8, at most
* 16 KiB of activation at the band's K) all 48 column groups read the same activation
* slice, so it stays in L1 and staging would only add a barrier per k-block. */
if constexpr (!WIN) {
constexpr int kUnit = 8; // codes (fp8a8) or elements (bf16) a unit
constexpr int kUnit = 8; // codes (fp8a8) or elements (bf16) per unit
constexpr int nu = GROUP / kUnit;
#pragma unroll
for (int u = (int)tid; u < RP * nu; u += kBlockThreads) {
@@ -312,8 +270,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
dst[2] = e4m3x2_to_f16x2(b8.y & 0xffffu);
dst[3] = e4m3x2_to_f16x2(b8.y >> 16);
} else {
/* Cast to the element pointer FIRST: the row and k offsets are ELEMENT offsets,
* which for bf16 is twice the byte count (r3d_gemm_fp8a16_nt_m1.hip). */
/* Cast to the element pointer first: the row and k offsets are bf16 element
* offsets. */
const r3d_u32x4 b16 = *(const __attribute__((address_space(1))) r3d_u32x4*)(
(const uint16_t*)A + (size_t)rr * a_ld + kb + c);
dst[0] = bf16x2_to_f16x2(b16.x);
@@ -327,49 +285,29 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
}
const uint32_t* ap = s_a + (size_t)mloc * AP;
/* One chain at a time. The gate's product, k ascending into `sub_g`, then the up's into
* `sub_u` -- the two chains are the two calls the unfused pair makes, they share nothing,
* and each one's bracketing is that call's, element for element.
/* The two chains, gate into `sub_g` and up into `sub_u`, each k ascending: the unfused
* pair's two calls, each with that call's bracketing.
*
* Sequencing them, rather than interleaving them step by step, is what the register file
* asks for. The window is eight 16-byte loads a stream; holding both streams' windows
* live at once is 64 registers of loads on top of the decode's temporaries, the staged
* activation's reads, the two accumulators and the block's pointers, and at 256 threads
* (four waves a SIMD, 128 registers a lane) it spills 365 bytes. One chain's window is
* 32 registers, and the arm compiles clean.
*
* On the band's stream -- 24 MiB of codes, vram, 11 launches, GPU 2, this kernel's loop
* with the epilogue off: 16-byte step with the arithmetic decoder 584 us; table decoder,
* same step 453 us; table, window 64 283 us; table, window 128 187 us; the same sixteen
* loads with no decode and no dot 139 us. The op without the table decoder and the window
* spends 1474 us a call. */
* The skinny arm runs the chains one after the other rather than interleaved: holding
* both streams' windows live (64 registers of loads, on top of everything else) spills at
* 256 threads (four waves per SIMD, 128 registers per lane), while one chain's window is
* 32 registers and does not. */
float sub_g, sub_u;
if constexpr (WIN) {
/* The skinny arm, M <= 8 (the threshold `R3D_GT_G` selects on): read the codes, decode
* them out of the block's table, multiply
* them. No shared memory between the load and the dot, and no barrier in the k-loop --
* the two chains, gate then up, k ascending inside each, the scales folded at the block's
* end, the epilogue below untouched.
*
* Three loads a step, sixteen bytes each: the activation's sixteen codes, the gate's,
* the up's. Six of them are in flight at the depth below, against the 163 GB/s the card
* does; the tall arms feed the same stream with occupancy, at 32 waves a CU.
*
* On this band's stream (24 MiB of codes, vram, 11 launches, GPU 2, epilogue off):
* the staged shape 497 us; the same codes read straight 187 us; the same sixteen loads
* with no decode and no dot 139 us. The op without the table decoder and the window
* spends 1474 us a call. */
constexpr int kNS = GROUP / kStep; // steps a block
constexpr int kD = 2; // loads a chain in flight
/* The skinny arm, M <= 8 (selected by `R3D_GT_G`): load the codes, decode them from
* the block's table and multiply, with no shared memory between load and dot and no
* barrier in the k-loop. Each step loads 16 bytes of activation and 16 of weight;
* prefetching two steps ahead keeps loads in flight, where the tall arm relies on
* occupancy (32 waves per CU). */
constexpr int kNS = GROUP / kStep; // steps per block
constexpr int kD = 2; // loads in flight per chain
auto chain = [&](const uint8_t* w, float sub) {
auto ld = [&](int st) {
return ldc<NT>(w + kb + (st < kNS ? st : kNS - 1) * kStep);
};
/* Named registers, not an array: an array indexed across a round -- even with the
* round count constant and the loop marked for unrolling -- puts the codes in the
* private segment, 572 bytes a lane, and every code crosses scratch on its way from
* the load to the dot. Two named dwords-in-four, prefetched two steps ahead, keep
* the same six loads in flight and the frame at zero. */
/* Named registers, not an array: an array indexed across iterations, even with a
* constant trip count and unrolling, is placed in private (scratch) memory. Two
* named 16-byte registers, prefetched two steps ahead, keep the frame at zero. */
r3d_u32x4 c0 = ld(0), c1 = ld(1);
#pragma unroll
for (int st = 0; st < kNS; st += kD) {
@@ -387,25 +325,19 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
sub_g = chain(wg, 0.0f);
sub_u = chain(wu, 0.0f);
} else {
/* The tall arms: one 16-code step a round, both streams in the same round.
* At M >= 8 the block grid is 48 x M/2 blocks, the wave slots are full, and the stream
* is fed by occupancy -- 109 registers a lane, four waves a SIMD, 32 waves a CU. The
* window is a skinny-arm fix: it buys its loads per lane at 32 registers, which on
* this arm is a fifth wave a SIMD given up, and on the 47 bands at M = 64 that is the
* whole op. Measured: windowed at M = 64 costs more than it saves. */
/* The tall arm: one 16-code step per iteration, both streams in the same iteration.
* At M >= 9 the grid is 48 x M/2 blocks and occupancy feeds the stream (109 registers
* per lane, four waves per SIMD, 32 waves per CU). A load window would cost 32
* registers per lane here, and at M = 64 it costs more than it saves. */
sub_g = 0.0f;
sub_u = 0.0f;
/* The round's unroll depth is a register decision, and at group = 32 it is the whole
* decision: the block is two steps wide, so `unroll 2` is a full unroll, the scheduler
* takes all thirty-two table reads of the two chains and hoists them above the dots,
* and the arm lands at 128 registers with 12 spilled (the same arm at group >= 64, in
* the same file, is 106 to 112 with none). Left as a loop the body is one step. */
/* Inline, from the table into the dot, on purpose. Materialising the eight decoded
* pairs into an array on the way -- the shape the arithmetic decoder above feeds --
* puts the plane about a third away from the reference at every tall height (M = 7:
* rel_l2 6.6e-01; M = 64: -nan), with the table itself exact on the device, entry by
* entry and pair by pair. The array form is the one that miscomputes here; do not
* restore it as a tidy-up. */
/* Unroll depth is a register decision. At group = 32 the block is two steps wide, so
* `unroll 2` is a full unroll: the scheduler hoists all 32 table reads of both chains
* above the dots and the arm spills at 128 registers. group = 32 therefore stays a
* one-step loop; group >= 64 unrolls by 2 without spilling. */
/* Do not materialise the eight decoded pairs into an array on the way to the dot:
* that form miscomputes on this arm (rel_l2 6.6e-01 at M = 7, NaN at M = 64) although
* the table itself is exact. Keep the decode inline. */
auto step_body = [&](int k) {
const r3d_u32x4 a0 = lds_a(ap + k / 2);
const r3d_u32x4 a1 = lds_a(ap + k / 2 + 4);
@@ -421,9 +353,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
}
}
if constexpr (!WIN)
group_barrier(); // the next block's stage must not race this one's reads
group_barrier(); // the next block's stage must not race these reads
/* The two finished sub-sums, each scaled once, in libref's parentheses. */
/* The two sub-sums, each scaled once, in libref's parentheses. */
const float sa = A8 ? as[gi] : 1.0f;
acc_g = acc_g + (sub_g * sa) * (bs16 ? bf16_to_f32(bsH[bsg + gi]) : bsF[bsg + gi]);
acc_u = acc_u + (sub_u * sa) * (bs16 ? bf16_to_f32(bsH[bsu + gi]) : bsF[bsu + gi]);
@@ -437,8 +369,8 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
const bool keep = (i < (uint32_t)n) && (m < (uint32_t)M);
if (keep && Y) Y[(size_t)m * y_ld + i] = h;
/* A column past n, and a row past M, contribute 0.0f: padding takes no part in the amax and
* takes no store, which is quant_act_fp8's rule for a ragged row. */
/* A column past n or a row past M contributes 0.0f to the amax and is not stored, as in
* quant_act_fp8 for a ragged row. */
const float am = keep ? fabsf(bf16_to_f32(h)) : 0.0f;
float mx = wave_max(am); // fmaxf skips a NaN, as `if (m > amax)` does
@@ -449,9 +381,9 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
for (int w = 1; w < WPG; ++w) mx = fmaxf(mx, s_mx[mloc * WPG + w]);
const float sc = mx > 0.0f ? mx * (1.0f / kTopE4M3) : 1.0f;
/* One store per (row, group): the group's WPG waves all hold the same max, so the first writes
* and the rest stand down. `scale` is dense -- the launcher takes no pitch for it -- so a row is
* `ng` scales and the group index is the block's. */
/* One store per (row, group): the group's WPG waves hold the same max and the first writes it.
* `scale` is dense (the launcher takes no pitch for it): `ng` scales per row, indexed by the
* block's group. */
if (keep && lane == 0 && (wave % WPG) == 0) S[(size_t)m * ng + gidx] = sc;
if (keep) {
@@ -469,19 +401,18 @@ __global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_ke
* b [N][K] E4M3 codes, row-major, k contiguous: gate rows [0,n), up rows
* [n,N)
* b_scale [ceil(N/group)][ceil(K/group)] bf16 (the op's stated dtype) or f32, block-major
* q [M][n] E4M3 codes, `q_ld` elements a row (0 = n)
* scale [M][ceil(n/group)] f32, DENSE (no pitch is taken)
* out_bf16 [M][n] bf16, `y_ld` elements a row (0 = n), optional: the pre-gate...
* the gated bf16 tensor the codes were taken over
* q [M][n] E4M3 codes, `q_ld` elements per row (0 = n)
* scale [M][ceil(n/group)] f32, dense (no pitch is taken)
* out_bf16 [M][n] bf16, `y_ld` elements per row (0 = n), optional: the gated
* bf16 tensor the codes were taken over
*
* `group` is the weight's K block, the weight's row block and the output quantiser's group at once,
* which is what the op's single key states; 0 takes the checkpoint's 128. `act` is R3D_ACT_SILU
* (down_proj's input) or R3D_ACT_SIGMOID (a gated attention o_proj's). `sk` is accepted as 0/1 and
* refused above it: the epilogue needs a whole row. `nt` selects the weight load's lowering.
* `scratch` is unused -- the op needs no arena, which is what keeps the row concurrent.
* `group` is at once the weight's K block, the weight's row block and the output quantiser's group,
* as the op's single key states; 0 takes the checkpoint's 128. `act` is R3D_ACT_SILU (down_proj's
* input) or R3D_ACT_SIGMOID (a gated attention o_proj's). `sk` is accepted as 0/1 and refused above
* it: the epilogue needs a whole row. `nt` selects the weight load's lowering. `scratch` is unused;
* needing no arena keeps the row concurrent.
*
* Returns 0, -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 HIP
* failed. */
* Returns 0, -1 a null pointer, -2 an unsupported shape, -3 an unreadable pitch, -4 HIP failed. */
extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale, long q, long scale,
long out_bf16, int M, int N, int K, int group, int act,
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
@@ -510,14 +441,12 @@ extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale
const int rp = kBlockThreads / group;
const dim3 grid((unsigned)ng, (unsigned)((M + rp - 1) / rp)), blk(kBlockThreads);
/* The skinny arms -- the decode's height -- take the windowed stream; the tall arms keep
* the step. One number, two kernels, and the band key that names them is the same one.
/* fp8a8 at M <= 8 takes the skinny (direct-read) arm, everything else the staged arm.
*
* M <= 8 is the shipped threshold and it is a tunable, not a fact. With the table decoder in both
* arms, N=12288 K=2048 group=128 vram: at M=8 skinny 402 against staged 754, at M=16 skinny 955
* against staged 1030 -- so the crossover is above 16; M=9..15 is unmeasured. Decode lives at M=1
* and a draft's verify at M<=8, which is what the threshold is chosen for; a prefill at 9..16 rows
* would take the skinny arm on the M=16 numbers, for about 7%. */
* The threshold is a tunable chosen for decode (M = 1) and draft verify (M <= 8). With the table
* decoder in both arms, at N=12288 K=2048 group=128 the skinny arm takes 402 us against 754 at
* M = 8 and 955 against 1030 at M = 16, so the crossover lies above 16 (M = 9..15 unmeasured);
* raising the threshold to 16 would gain about 7% for a prefill of 9..16 rows. */
#define R3D_GT_G(G, A, A8, NTV) \
do { \
if (A8 && M <= 8) R3D_GT_W(G, A, A8, NTV, true); \
@@ -546,10 +475,9 @@ extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* The declaration in r3d.h carries no scale dtype, and this op's shape hook states bf16 -- the hook
* has no f32 spelling at all -- so the plain entry reads bf16 and the `_ex` twin above carries the
* key. A caller with an f32 scale plane (the `fp8a8f32` reading of the unfused GEMM) lands on `_ex`
* with RAD_F32; the kernel widens bf16 -> f32 exactly, so the two agree to the bit. */
/* The entry without a scale dtype reads bf16, the only form this op's shape hook states. A caller
* with an f32 scale plane (the `fp8a8f32` reading of the unfused GEMM) uses `_ex` with RAD_F32;
* bf16 widens exactly, so the two agree bit for bit. */
extern "C" int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, long q, long scale,
long out_bf16, int M, int N, int K, int group, int act,
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
@@ -562,9 +490,9 @@ extern "C" int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, l
/* ============================================================== the plugin ABI entry point
*
* gemm_nt_q_gated's operands are [a, a_scale, b, b_scale, q, scale, out_bf16?] and its parameters
* M, N, K, group, dtype, act (libref's pGemmQGated/oGemmQGated: `act` REQUIRED, `a_scale` REQUIRED,
* M, N, K, group, dtype, act (libref's pGemmQGated/oGemmQGated: `act` and `a_scale` required,
* `out_bf16` optional). The shape hook declines every scheme but fp8a8, so the row binds fp8a8 and
* the shim reads the coded activation off the operands. */
* the shim reads the coded activation from the operands. */
enum { G_A = 0, G_ASCALE, G_B, G_BSCALE, G_Q, G_SCALE, G_OB };
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
@@ -586,10 +514,9 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
R3D_NEED(dt_e4m3(Q));
R3D_NEED(dt_f32(SC));
if (OB) R3D_NEED(dt_bf16(OB));
/* The activation: E4M3 codes with a per-(row, group) f32 scale (fp8a8, the scheme this op's
* shape hook and every band states), or bf16 with no scale (fp8a16, which the hook declines, so
* no band arrives: the kernel carries the path because the launcher does, and the shim accepts
* it on the operands). E5M2 has no decoder here. */
/* The activation: E4M3 codes with a per-(row, group) f32 scale (fp8a8, the scheme every band
* states), or bf16 with no scale (fp8a16, which the shape hook declines, so no band reaches it;
* the launcher supports it and the shim accepts it). E5M2 has no decoder here. */
const bool a8 = AS != nullptr;
if (a8) {
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
@@ -597,16 +524,14 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
} else {
R3D_NEED(dt_bf16(A));
}
/* b_scale is bf16 -- `o.t(RAD_BF16, {nb, kb})` is this op's own line in the hook, and the
* container's `weight_scale_inv` for the whole quantised family. f32 is accepted because the
* widening is exact and the kernel reads both: the driver's bf16/f32 pair must agree element
* for element. */
/* b_scale is bf16 (the hook's `o.t(RAD_BF16, {nb, kb})`, the container's `weight_scale_inv`).
* f32 is also accepted; the widening is exact, so both give the same output. */
const bool bs16 = r3d_is_bf16(BS);
if (!bs16 && !r3d_is_f32(BS)) return R3D_NO(RAD_E_DTYPE);
/* `act` is required by the schema (P_STR, not P_STRO): an implementation may compile one gate,
* and an optional parameter would let the row resolve for the other. libref's default is -1 and
* it refuses it; so does this shim, with no `mode` integer spelling to fall back on. */
/* `act` is required by the schema (P_STR, not P_STRO), because an implementation may compile
* only one gate. libref defaults it to -1 and refuses that; so does this shim, with no integer
* `mode` fallback. */
const int act = r3d_act_code(a, "act", nullptr, -1);
if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return R3D_NO(RAD_E_INVAL);
@@ -615,20 +540,18 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
if (K < 1 || N < 2 || (N & 1)) return R3D_NO(RAD_E_SHAPE);
const long long n = N / 2;
/* Rows come from `q`, never from the `M` parameter, which is the band's upper bound. libref
* reads numel(q) / n; on a plane whose pitch exceeds n that counts the padding, so the shape's
* own row count clamps it. A dense plane -- every case the fixture draws -- reads the same
* number either way. */
/* Rows come from `q`, never from the `M` parameter (the band's upper bound). libref reads
* numel(q) / n, which on a plane with pitch > n counts the padding, so the shape's row count
* clamps it. Dense planes give the same number either way. */
const long long qnel = r3d_numel(Q);
if (qnel < n || qnel % n) return R3D_NO(RAD_E_SHAPE);
long long M = qnel / n;
if (Q->rank >= 2 && r3d_dim(Q, (int)Q->rank - 2) < M) M = r3d_dim(Q, (int)Q->rank - 2);
if (M < 1 || M > kMMax) return R3D_NO(RAD_E_SHAPE);
/* The group: the weight's K block, the weight's row block and the quantiser's group, from the
* one key the op states. The reference defaults 0 to `group`-as-stated for the grids and
* `g > n` to n for the quantiser alone; this kernel reads one width, so a group wider than the
* fused width is refused rather than served on a grid the two sides do not share. */
/* The group: the weight's K block, row block and the quantiser's group, from the op's one key.
* The reference would use n for the quantiser alone when group > n; this kernel reads one
* width, so such a group is refused. */
const long long group = r3d_geti_or(a, "group", R3D_FP8_BLOCK);
if (group < kGroupMin || group > kGroupMax || (group & (group - 1))) return R3D_NO(RAD_E_SHAPE);
if (group > n) return R3D_NO(RAD_E_SHAPE);
@@ -645,14 +568,12 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
const long long q_ld = r3d_rows_pitch(Q, n, &qrows);
const long long y_ld = OB ? r3d_rows_pitch(OB, n, &yrows) : n;
if (a_ld < 0 || q_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
/* `yrows` is only a promise when the plane is there. `r3d_rows_pitch` leaves the count at zero
* for a null operand, and an absent optional output is a null operand by contract (r3d_args.h),
* so testing `yrows` unconditionally reads "the row is missing" from "the caller asked for no
* bf16 mirror". */
/* `yrows` is only meaningful when the plane exists: `r3d_rows_pitch` leaves it zero for a null
* operand, and an absent optional output is a null operand (r3d_args.h). */
if (arows < M || qrows < M || (OB && yrows < M)) return R3D_NO(RAD_E_SHAPE);
if (a_ld % 8) return R3D_NO(RAD_E_STRIDE); // 8-code / 8-element staging
/* The scale planes travel without a pitch argument, so they must be dense, and `scale`'s grid
* must be the one the kernel walks: `ng` scales a row. */
/* The scale planes take no pitch argument, so they must be dense, and `scale` must hold `ng`
* scales per row. */
if (!r3d_contig(B) || !r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE);
if (AS && !r3d_contig(AS)) return R3D_NO(RAD_E_STRIDE);
if (r3d_rows_pitch(SC, ng, &srows) != ng) return R3D_NO(RAD_E_STRIDE);
@@ -663,9 +584,8 @@ extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
/* Split-K is the axis this kernel cannot honour: a K slab produces a partial product, and the
* epilogue needs the finished row -- its bf16 narrowing, the gate's partner column, the group's
* amax. A caller that states sk > 1 is refused here, at the row, not answered slowly. */
/* No split-K: the epilogue needs the finished row (its bf16 narrowing, the gate's partner
* column, the group's amax), so sk > 1 is refused. */
if (c.sk > 1) return R3D_NO(RAD_E_SHAPE);
const int e = r3d_gemm_nt_q_gated_ex(
File diff suppressed because it is too large. Load diff
+49 -53
View File
@@ -1,45 +1,44 @@
/* r3d_gemm_inta8.hip -- gemm_nt_q at dtype=w4a8 and w8a8: the symmetric int4 and int8 weight
* grids at decode heights, one kernel per grid.
*
* The grids, libref's descriptions: int8 activations in quant_act_i8's step order against
* signed weight codes (I4, two a byte, or I8, one a byte) with one f16 scale per (row, 128 of
* K), an f32 activation scale per row, and no zero point -- the dequant is code times scale,
* so there is no a_sum to carry and no bias to take off. The group sub-sum is formed on the
* integer grid and scaled once per group, the reference's order:
* The grids (libref's descriptions): int8 activations in quant_act_i8's step order with an f32
* scale per row, against signed weight codes (I4 two per byte, or I8) with one f16 scale per
* (row, 128 of K). No zero point: the dequant is code times scale, so there is no a_sum and no
* bias. The group sub-sum is formed on the integer grid and scaled once per group, in the
* reference's order:
*
* sub = sum over the group of a * code, an exact integer
* acc += (sub * a_scale[m]) * scale[n, g]
*
* ---- exactness, and why the dots may run in f16 --------------------------------------------------
*
* A lane's 64 products are |a * code| <= 127 * 7 (w4a8) or 127 * 127 (w8a8), and the group's
* 128 of them sum to 113,792 (w4a8) or 2,064,512 (w8a8): both under 2^24, the f32 mantissa, so
* the lane partial and the pair fold are exact, and the group terms land in the accumulator
* in the reference's ascending order. The codes widen to f16 through a sign extension, which
* is exact for both grids; the activations widen through the i8 codec the w2a8 arm uses.
* Each product is |a * code| <= 127 * 7 (w4a8) or 127 * 127 (w8a8), and a group's 128 of them sum
* to at most 113,792 (w4a8) or 2,064,512 (w8a8), both under 2^24, so the lane partial and the pair
* fold are exact and the group terms enter the accumulator in the reference's ascending order. The
* codes widen to f16 by sign extension, exact for both grids; the activations widen through the i8
* codec the w2a8 arm uses.
*
* The activation is the step order: within each sixteen-byte step the middle two dwords are
* exchanged, so the staging reads through the same position map the w2a8 arm does, and a
* weight row's codes are plain row-major, two a byte at I4 and one a byte at I8.
* In the activation's step order the middle two dwords of each 16-byte step are exchanged, so the
* staging reads through the same position map as the w2a8 arm. Weight codes are plain row-major.
*
* ---- the tile --------------------------------------------------------------------------------------
*
* One workgroup serves kWaves weight rows; a wavefront takes one row, lane l owns rows
* l & (MT-1) and k-lane l / MT, and the chunk is 2048 / MT codes: a multiple of the 128
* group at every MT, so a chunk carries CG = 16 / MT whole groups and the group's scale is
* one read. The lane's 64 codes are 32 bytes at I4, two 16-byte loads, and 64 at I8, four.
* The lane's 64 sit in the group's two halves the w2a8 arm folds with one shfl_xor(MT), and
* the group's term -- scaled by the activation's row scale and the weight's group scale --
* goes to shared, where the row's owner lane sums the chunk's groups in ascending order.
* One workgroup serves kWaves weight rows, one per wave. Lane l owns activation row l & (MT-1) and
* k-lane l / MT. A chunk is 2048 / MT codes, a multiple of the 128 group at every MT, so it holds
* CG = 16 / MT whole groups and a group's scale is one read. A lane's 64 codes are 32 bytes at I4
* (two 16-byte loads) and 64 at I8 (four). Lanes l and l^MT hold the two halves of one group and
* fold with one shfl_xor(MT); the group's term, scaled by the activation's row scale and the
* weight's group scale, goes to shared memory, where the row's owner lane sums the chunk's groups
* in ascending order.
*
* M > 16 is the tiled row's; the w2a8 arm serves the 2- and 4-bit container grids there, and
* the 8-bit grid at prefill heights is declared out of this unit.
* M > 16 belongs to the tiled row, where the w2a8 arm serves the 2- and 4-bit container grids; the
* 8-bit grid at prefill heights is declared outside this unit.
*
* ---- refusals --------------------------------------------------------------------------------------
*
* Every structural violation is a refusal, in the shim: the dtypes of all five operands,
* K % 128, the band's M, the b row pitch's 16-byte alignment, the a and y pitches. There is
* no data that is a refusal: both grids have no reserved value.
* The shim refuses every structural violation: the dtypes of all five operands, K % 128, the
* band's M, the b row pitch's 16-byte alignment, the a and y pitches. No data value is refused;
* neither grid has a reserved value.
*/
#include "r3d_common.h"
@@ -56,18 +55,17 @@ constexpr int kMTMax = 16;
constexpr int kGroup = 128;
constexpr int kTileQuads = 512; /* MT rows x CHUNK/4 f16, constant over MT */
/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse.
* Applied to the four columns of one dword it leaves them four contiguous bytes and turns
* the map on the DWORD index into a swap of bits 0 and 1 -- the middle two dwords of a
* 16-byte step exchanged. */
/* Column c sits at byte step_pos(c): bits 2 and 3 of c swapped, a self-inverse map. On the
* dword index it is a swap of bits 0 and 1, i.e. the middle two dwords of a 16-byte step
* exchanged, with each dword's four columns left contiguous. */
__device__ __forceinline__ int64_t dword_pos(int64_t d)
{
return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1));
}
/* The LDS swizzle, at the granularity the tile is touched: a quad of four f16, two dwords,
* moved as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low
* four bits with bits 4..7 -- a bijection on 16-quad groups. */
/* The LDS swizzle, at the tile's access granularity: a quad of four f16 (two dwords) moved as one
* 8-byte word. Quads are numbered q = r*(CHUNK/4) + c; p_ix XORs q's low four bits with bits 4..7,
* a bijection on 16-quad groups. */
__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); }
/* Four int8 codes -> two f16x2 dwords. Exact: an integer of |a| <= 127 needs no rounding. */
@@ -78,11 +76,10 @@ __device__ __forceinline__ void i8x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t
(float)(int32_t)(int8_t)((w >> 24) & 0xffu));
}
/* Four signed int4 codes (two bytes, the low code in the low nibble) -> two f16x2 dwords.
* Exact: the sign extension lands on an integer, and f16 steps by 1/8 at exponent 2^-3.
* A nibble n is the value (n & 7) - (n & 8): 0..7 pass through and 8..15 land on -8..-1.
* The gfx1102 backend folds the bias-8 spelling ((n ^ 8) - 8) to n ^ 16 once it has proven
* the nibble range, so the sign is kept as a bit term. */
/* Four signed int4 codes (two bytes, the low code in the low nibble) -> two f16x2 dwords. Exact:
* the sign extension yields an integer in -8..7. A nibble n is the value (n & 7) - (n & 8), so
* 0..7 pass through and 8..15 map to -8..-1. The gfx1102 backend folds the bias-8 form
* ((n ^ 8) - 8) to n ^ 16 once it has proven the nibble range, so the sign stays a bit term. */
__device__ __forceinline__ void i4x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi)
{
const uint32_t n0 = w & 0xFu;
@@ -144,8 +141,8 @@ gemm_inta8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa,
float acc = 0.0f;
for (int ch = 0; ch < nchunk; ++ch) {
/* Stage the chunk's activation rows, widened and step-unpermuted on the way in. Cells
* are four codes: MT * CHUNK/4 = 512 of them at every MT, two per thread. */
/* Stage the chunk's activation rows, widened and step-unpermuted. Cells are four codes:
* MT * CHUNK/4 = 512 at every MT, two per thread. */
for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) {
const int r = i / (chunk >> 2), c = i % (chunk >> 2);
uint32_t w = 0;
@@ -160,17 +157,17 @@ gemm_inta8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa,
__syncthreads();
if (live) {
/* 64 codes: 32 bytes at I4, 64 at I8. The lane's codes are kl * 64 within the
* chunk, and the row pitch keeps every 16-byte load aligned. */
/* 64 codes: 32 bytes at I4, 64 at I8, starting at code kl * 64 of the chunk. The
* row pitch keeps every 16-byte load aligned. */
const uint8_t* bp = b + (long long)n * row_bytes + (int64_t)ch * cq +
kl * (CL / 2) * (CDT / 4);
uint4 qw[NLOAD];
#pragma unroll
for (int L = 0; L < NLOAD; ++L)
__builtin_memcpy(&qw[L], bp + 16 * L, 16);
/* One value per quad: I4 the two-byte window as a 16-bit element, I8 the dword.
* The I4 window is taken as a half at its own address; shifting a dword array by
* a byte amount miscompiles on the gfx1102 backend. */
/* One value per quad: at I4 the two-byte window as a 16-bit element, at I8 the dword.
* The I4 window is read as a 16-bit element at its own address, because shifting a
* dword array by a byte amount miscompiles on the gfx1102 backend. */
uint32_t wd[(CL >> 2)];
if (CDT == 4) {
uint16_t wq[CL / 2];
@@ -208,14 +205,13 @@ gemm_inta8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa,
const int g = ch * CG + (kl >> 1);
const float sc = f16_to_f32(sb[(long long)n * sb_rb + g]);
const float term = (isg * sSa[m]) * sc; /* the reference's parentheses */
/* One slot per (row, group-in-chunk): MT*CG is 16 at every MT. The group's two
* half-lanes write the same value, which is what the pair fold above is for. */
/* One slot per (row, group-in-chunk); MT*CG is 16 at every MT. Both half-lanes of
* a group write the same folded value. */
sT[warp * 16 + m * CG + (kl >> 1)] = term;
}
__syncthreads();
/* The chunk's groups, in ascending order, into the lane that owns the row's answer:
* the reference walks g in ascending order and f32 adds are not associative, so the
* order is part of the answer, not a detail. */
/* The chunk's groups in ascending g, into the row's owner lane: f32 adds are not
* associative and the reference walks g ascending. */
if (live && kl == 0) {
#pragma unroll
for (int j = 0; j < CG; ++j)
@@ -309,9 +305,9 @@ extern "C" int r3d_gemm_nt_q_w8a8_m16(long a, long a_scale, long b, long b_scale
/* ================================================================== the shims
*
* gemm_nt_q's slots, as the two shims take them: 0 a (I8, step order), 1 a_scale (f32, one
* per row), 2 b (I4 or I8 codes), 3 b_scale (f16, one per (row, 128 of K)), 4 y (bf16),
* 5 a_sum (absent: symmetric), 6 b_ref (absent).
* gemm_nt_q's slots: 0 a (I8, step order), 1 a_scale (f32, one per row), 2 b (I4 or I8 codes),
* 3 b_scale (f16, one per (row, 128 of K)), 4 y (bf16), 5 a_sum (absent: symmetric),
* 6 b_ref (absent).
*/
extern "C" int r3d_rad_gemm_nt_q_w4a8_m16(const RadArgs* a, RadStream s)
@@ -359,7 +355,7 @@ extern "C" int r3d_rad_gemm_nt_q_w4a8_m16(const RadArgs* a, RadStream s)
if (yp < N) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
const long long bbr = r3d_row_pitch(B) / 2; /* I4 counts elements, two a byte */
const long long bbr = r3d_row_pitch(B) / 2; /* I4 pitch is in elements, two per byte */
const int rc = r3d_gemm_nt_q_w4a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp,
bbr, (long long)r3d_row_pitch(BS), (long)s);
+95 -113
View File
@@ -7,69 +7,61 @@
*
* ---- the format, and the fold it gives ----------------------------------------------------------------
*
* OCP MXFP4 stores a weight row as e2m1 codes, two per byte, element 2j in the LOW nibble of
* byte j, with one e8m0 exponent per 32 K elements: a u8 plane [N, K/32] behind the u8 codes
* plane [N, K/2]. e8m0 value e means the factor 2^(e-127); e = 0 and e = 255 are reserved
* (zero, NaN) and a plane carrying either is refused, the reference's answer for the same
* bytes.
* OCP MXFP4 stores a weight row as e2m1 codes, two per byte, element 2j in the low nibble of
* byte j, with one e8m0 exponent per 32 K elements: a u8 plane [N, K/32] beside the u8 codes
* plane [N, K/2]. e8m0 value e means the factor 2^(e-127); e = 0 and e = 255 are reserved (zero,
* NaN), and a plane carrying either is refused, as the reference does.
*
* The fold this kernel runs, per 32-block:
* Per 32-block:
*
* 1. the code for element k is e4m3(mag) at d = 0 -- the e2m1 magnitude is EXACT in e4m3,
* because all eight magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} are e4m3 grid points. The
* unpack is a 4-bit lookup on the nibble through the eight e4m3 magnitude bytes
* {0x00, 0x30, 0x38, 0x3C, 0x40, 0x44, 0x48, 0x4C}, the sign bit of the code on the
* sign bit of the byte.
* 2. the code products run on dot2_f16x2. A product is at most 6 x 448 = 2688, in f16's
* range (65504), and an eight-term partial is under 21504, in f16's grid: the dot's
* only rounding is the instruction's own.
* 3. the per-block factor 2^(e-127) is applied in the epilogue: the 32-block partial, an
* f32, is multiplied by the factor -- a power of two, exact in f32 short of the
* under/overflow edge -- and added to the running f32 sum. One multiply and one add per
* block per output element, no per-element scale traffic.
* 1. the code for element k becomes e4m3(mag): all eight e2m1 magnitudes
* {0, .5, 1, 1.5, 2, 3, 4, 6} are e4m3 grid points, so this is exact. The unpack is a
* 4-bit lookup on the nibble through the e4m3 bytes {0x00, 0x30, 0x38, 0x3C, 0x40, 0x44,
* 0x48, 0x4C}, with the code's sign bit moved to the byte's sign bit.
* 2. the products run on dot2_f16x2. A code product is at most 6 x 448 = 2688, inside f16's
* range (65504), and an eight-term partial is under 21504.
* 3. the block factor 2^(e-127) is applied in the epilogue: the f32 32-block partial is
* multiplied by it (a power of two, exact short of under/overflow) and added to the running
* f32 sum. One multiply and one add per block per output, no per-element scale traffic.
* 4. the store narrows once, to bf16.
*
* The e2m1 magnitude is exact, the products are exact, and the two roundings a block sees are
* the dot's fused rounding and the store: the row's distance from the reference is the store's
* ulp, nothing else.
* The roundings are the activation-scale fold at staging (fold_pair, f16), the dot's fused
* rounding, and the store.
*
* The RDNA4 sibling folds the e8 into the table through a d-indexed row, because its WMMA
* path needs one scale per row; this library's dot2 path folds per block in the epilogue, and
* the table is the eight fixed magnitude bytes, no index.
* The RDNA4 sibling folds the e8 into a d-indexed table row because its WMMA path needs one scale
* per row; the dot2 path here applies it per block in the epilogue, so the table is the eight
* fixed magnitude bytes.
*
* ---- the tiled row (M >= 17) -------------------------------------------------------------------------
*
* The 128x128 tile, 8x8 f32 accumulators a lane, k ascending in 32-code chunks. The chunk IS
* the OCP 32-block: the lane's e8 bytes for its eight tile columns enter as one byte per row
* at staging, through LDS, and the chunk's partials flush at the chunk's end:
* A 128x128 tile, 8x8 f32 accumulators per lane, k ascending in 32-code chunks. A chunk is one OCP
* 32-block: the e8 byte of each tile column is staged through LDS, and the chunk's partials flush
* at its end:
*
* total[i][j] += acc[i][j] * 2^(e8[n_c + j][blk] - 127); acc[i][j] = 0;
*
* `acc` is the 32-block partial, `total` the running f32 sum over blocks in ascending k. The
* activation stages exactly as the fp8a8 tiled row's: E4M3 through the LDS table, the f32
* scale per (row, 128 of K) folded at staging; 32 divides 128, so a chunk sits inside one
* group and never straddles one.
* activation stages as in the fp8a8 tiled row: E4M3 through the LDS table, with the f32 scale per
* (row, 128 of K) folded in at staging. 32 divides 128, so a chunk never straddles a group.
*
* ---- the m16 row (M <= 16) ----------------------------------------------------------------------------
*
* One wave per weight row, the w2a8 row's shape: lane l owns row m = l % MT and k-lane
* kl = l / MT, a chunk is CHUNK = 2048/MT codes, and every lane takes 64 of them -- two OCP
* 32-blocks, the lane's blocks 2*kl and 2*kl+1 of the chunk. Each lane sums its two blocks in
* k, scales each by the block's e8, and the group's four block terms are formed in ascending
* block order by one shfl_xor pair and written to LDS, where the kl == 0 lane adds them to the
* accumulator in ascending block order: the reference's ascending-k accumulation, at the
* 32-block granularity the format fixes.
* One wave per weight row, as in the w2a8 row: lane l owns row m = l % MT and k-lane kl = l / MT,
* a chunk is CHUNK = 2048/MT codes, and each lane takes 64 of them, the chunk's 32-blocks 2*kl and
* 2*kl+1. Each lane sums its two blocks in k and scales each by its e8; one shfl_xor pair puts the
* group's four block terms in ascending order in LDS, and the kl == 0 lane adds them to the
* accumulator in that order. This is the reference's ascending-k accumulation at the 32-block
* granularity the format fixes.
*
* ---- refusals -----------------------------------------------------------------------------------------
*
* Every structural violation is a refusal, in the shim: the dtypes of all seven operands (the
* codes as fp4_e2m1 or raw bytes, the e8 plane as e8m0 or u8, `b_ref` the e8 plane again and
* ignored), K % 32 and K % 128, the codes plane's extent and 16-byte row alignment, the e8
* plane's [N, K/32] extent, the pitches, the band's M. A reserved e8 (0, 255) is a data
* violation, and it is refused where the data is readable: the shim scans the e8 plane once
* per (pointer, size) pair, on a plane the host can see, and answers E_INVAL. A plane the
* host cannot see is not scanned, and the kernel's e8 guard -- reserved values take the scale
* zero -- keeps its output finite.
* The shim refuses every structural violation: the dtypes of all seven operands (codes as
* fp4_e2m1 or raw bytes, the e8 plane as e8m0 or u8, `b_ref` the e8 plane again, ignored), K % 32
* and K % 128, the codes plane's extent and 16-byte row alignment, the e8 plane's [N, K/32]
* extent, the pitches and the band's M. A reserved e8 (0, 255) is refused with E_INVAL where the
* host can read the plane: the shim scans it once per (pointer, size) pair. A plane the host
* cannot see is not scanned; the kernel gives reserved values the scale zero, so the output stays
* finite.
*/
#include <hip/hip_runtime.h>
@@ -90,26 +82,24 @@ namespace {
constexpr int kBlockThreads = 256;
constexpr int kWaves = 8;
constexpr int kTM = 128; /* rows a tile */
constexpr int kTN = 128; /* columns a tile */
constexpr int kKC = 32; /* k a chunk: one OCP 32-block */
constexpr int kTM = 128; /* rows per tile */
constexpr int kTN = 128; /* columns per tile */
constexpr int kKC = 32; /* k per chunk: one OCP 32-block */
constexpr int kMX = 32; /* K per e8m0 exponent: the OCP MX block */
constexpr int kGroup = 128; /* the activation's scale group */
constexpr int kMMin = 17; /* the tiled row's floor: the m16 row's ceiling plus one */
constexpr int kMTMax = 16;
constexpr int kTileQuads = 512; /* MT * CHUNK/4, constant over MT: 2048 codes, 4 KiB of f16 */
/* The eight e2m1 magnitudes, as e4m3 bytes: 0, .5, 1, 1.5 in the low word, 2, 3, 4, 6 in the
* high. Every one is exact, which is the whole point of the fold. */
/* The eight e2m1 magnitudes as e4m3 bytes, each exact: 0, .5, 1, 1.5 in the low word, 2, 3, 4, 6
* in the high. */
#define R3D_MXFP4_MAG_LO 0x3c383000u
#define R3D_MXFP4_MAG_HI 0x4c484440u
/* Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) as eight e4m3
* bytes in k order (word 0 = elements 0..3, word 1 = 4..7). Even and odd nibbles each run
* through the magnitude bytes by a v_perm_b32 on the 3-bit magnitude, bit 3 of the code shifts
* onto the e4m3 sign, and two more v_perm_b32 interleave the halves. The table is the fixed
* d = 0 row: no index, because the per-block factor is applied in the epilogue, not folded
* here. */
* bytes in k order (word 0 = elements 0..3, word 1 = 4..7). Even and odd nibbles each go through
* the magnitude bytes with a v_perm_b32 on the 3-bit magnitude, bit 3 of the code shifts onto the
* e4m3 sign, and two more v_perm_b32 interleave the halves. */
__device__ __forceinline__ void mxfp4_unpack8(uint32_t wv, uint32_t* lo, uint32_t* hi)
{
const uint32_t ev = wv & 0x0F0F0F0Fu; /* low nibble of each byte -> even elements */
@@ -122,9 +112,9 @@ __device__ __forceinline__ void mxfp4_unpack8(uint32_t wv, uint32_t* lo, uint32_
*hi = __builtin_amdgcn_perm(bo, be, 0x07030602u);
}
/* The e8m0 factor: 2^(e-127). The reserved values take the scale zero -- e = 0 is the
* format's zero, e = 255 its NaN -- so a plane that carries one computes a zero block and
* stays finite; the refusal for such a plane is the shim's, where the bytes are readable. */
/* The e8m0 factor: 2^(e-127). The reserved values (e = 0 the format's zero, e = 255 its NaN) take
* the scale zero, so such a block computes zero and stays finite; the shim refuses such a plane
* where it can read it. */
__device__ __forceinline__ float e8_scale(uint8_t e)
{
return (e == 0 || e == 255) ? 0.0f : ldexpf(1.0f, (int)e - 127);
@@ -138,7 +128,7 @@ __device__ __forceinline__ void e4m3x4_to_f16x2(const uint16_t* tbl, uint32_t w,
o[1] = (uint32_t)tbl[(w >> 16) & 0xffu] | ((uint32_t)tbl[(w >> 24) & 0xffu] << 16);
}
/* code * scale, in f16 arithmetic: one v_mul_f16, round to nearest, subnormals kept. NOT
/* code * scale, in f16 arithmetic: one v_mul_f16, round to nearest, subnormals kept. Not
* f16x2_pack, which truncates. */
__device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc)
{
@@ -186,13 +176,11 @@ struct MxWQ {
};
/*
* The tile: 128 rows x 128 columns of y, 256 threads, eight waves, eight outputs a side a
* lane -- 64 f32 accumulators a lane for the 32-block partials, 64 more for the running
* sum, grid (N/kTN) x ceil(M/kTM). k is walked in chunks of 32; the activation arrives as
* E4M3 codes, decodes through the block's table and leaves staging as f16 with its scale
* folded in, and the weight arrives as e2m1 nibbles, unpacks to e4m3 and leaves staging as
* f16 UNSIGNED by the block: its scale is the e8, and the e8 is applied at the chunk's end,
* where the chunk's partials meet it.
* The tile: 128 rows x 128 columns of y, 256 threads, eight waves, 8x8 outputs per lane (64 f32
* accumulators for the 32-block partials and 64 for the running sum), grid (N/kTN) x ceil(M/kTM).
* k is walked in chunks of 32. The activation's E4M3 codes decode through the block's table and
* are staged as f16 with their scale folded in. The weight's e2m1 nibbles unpack to e4m3 and are
* staged as f16 without the block scale, which is applied to the partials at the chunk's end.
*/
template <int NT>
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
@@ -242,12 +230,12 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
const int n = n0 + nn;
uint4 st[4] = { make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0),
make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0) };
/* The e8 for the column, written even past N: a row the tile does not serve keeps
* the scale zero, so the flush multiplies a staged zero by a defined value. */
/* The column's e8, written even past N (as zero), so the flush multiplies a staged
* zero by a defined value. */
sE8[nn] = (n < N) ? h.e8[(long long)n * h.e8_row + blk] : 0;
if (n < N) {
/* 32 codes, 16 bytes, one load: k0 is a multiple of 32, the row a multiple of
* 64 bytes, so the load is aligned. */
/* 32 codes, 16 bytes, one load, aligned because k0 is a multiple of 32 and the
* row pitch a multiple of 16 bytes. */
uint4 cv;
__builtin_memcpy(&cv, h.codes + (long long)n * h.code_row + (k0 >> 1), 16);
const uint32_t d[4] = { cv.x, cv.y, cv.z, cv.w };
@@ -269,9 +257,8 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
}
__syncthreads();
/* The chunk's e8 for the lane's eight columns, held in registers: the flush reads it
* and nothing else does. The index is tile-local -- sE8 is this tile's 128 rows, and a
* global column index reads past it on every tile past the first. */
/* The chunk's e8 for the lane's eight columns, in registers for the flush. sE8 holds
* this tile's 128 columns, so the index is tile-local. */
float e8s[8];
#pragma unroll
for (int j = 0; j < 8; ++j) e8s[j] = e8_scale(sE8[cg * 8 + j]);
@@ -290,8 +277,8 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
#pragma unroll
for (int j = 0; j < 8; ++j) acc[i][j] = dot2_f16x2(af[i], bf[j], acc[i][j]);
}
/* The 32-block boundary: the partial scales by the block's factor, the sum keeps the
* blocks in ascending k, and the partial resets for the next block. */
/* The 32-block boundary: scale the partial by the block's factor, add it to the running
* sum in ascending k, reset the partial. */
#pragma unroll
for (int i = 0; i < 8; ++i)
#pragma unroll
@@ -325,9 +312,9 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res
/* ================================================================== the m16 row */
/* The LDS swizzle, at the granularity the tile is touched: a quad of four codes, two dwords,
* moved as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low four
* bits with bits 4..7 -- a bijection on 16-quad groups. */
/* The LDS swizzle, at the tile's access granularity: a quad of four codes (two dwords) moved as one
* 8-byte word. Quads are numbered q = r*(CHUNK/4) + c; p_ix XORs q's low four bits with bits 4..7,
* a bijection on 16-quad groups. */
__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); }
template <int MT>
@@ -339,7 +326,7 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
{
constexpr int KL = kWave / MT; /* k-lanes per activation row */
constexpr int CL = 64; /* codes per lane per chunk: two 32-blocks */
constexpr int BPR = (2048 / MT) / kMX; /* 32-blocks a row of the chunk: 64/MT */
constexpr int BPR = (2048 / MT) / kMX; /* 32-blocks per chunk row: 64/MT */
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL];
__shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/2 f16, swizzled */
@@ -361,8 +348,8 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
for (int ch = 0; ch < nchunk; ++ch) {
__syncthreads();
/* The chunk's activation rows, decoded and scaled on the way in. Cells are four codes:
* MT * CHUNK/4 = 512 of them at every MT, two per thread. The scale is per (row, 128
* of K); a cell's four codes sit in one group, so one scalar a cell. */
* MT * CHUNK/4 = 512 at every MT, two per thread. A cell's four codes sit in one 128-wide
* scale group, so one scale per cell. */
for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) {
const int r = i / (chunk >> 2), c = i % (chunk >> 2);
uint32_t lo = 0, hi = 0;
@@ -406,8 +393,8 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
}
/* The lane's two blocks, scaled by their e8. The pair (kl, kl^1) owns the group's
* four blocks -- kl even the lower two, kl odd the upper two -- so one exchange
* forms the group in ascending block order. */
* four blocks (kl even the lower two, kl odd the upper two), so one exchange puts
* them in ascending block order. */
const int blk0 = ch * (chunk / kMX) + 2 * kl;
const float q0f = p0 * e8_scale(e8[(long long)n * e8_row + blk0]);
const float q1f = p1 * e8_scale(e8[(long long)n * e8_row + blk0 + 1]);
@@ -419,8 +406,8 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
const float t2 = lo ? o0f : q0f;
const float t3 = lo ? o1f : q1f;
/* One slot per (row, 32-block-in-chunk): MT*BPR is 64 at every MT. The group's two
* half-lanes write the same four values. */
/* One slot per (row, 32-block-in-chunk); MT*BPR is 64 at every MT. Both half-lanes
* of a group write the same four values. */
const int j = kl >> 1;
const int bb = warp * 64 + m * BPR + 4 * j;
sB[bb + 0] = t0;
@@ -429,9 +416,8 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__
sB[bb + 3] = t3;
}
__syncthreads();
/* The chunk's block terms, in ascending block order, into the lane that owns the row's
* answer: the reference walks k in ascending order and f32 adds are not associative, so
* the order is part of the answer, not a detail. */
/* The chunk's block terms in ascending block order, into the row's owner lane: f32 adds
* are not associative and the reference walks k ascending. */
if (live && kl == 0) {
#pragma unroll
for (int bl = 0; bl < BPR; ++bl)
@@ -467,7 +453,7 @@ extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_sc
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (a_ld < K) return -3;
if (a_ld % 4) return -3; /* four codes a dword, staged whole */
if (a_ld % 4) return -3; /* four codes per dword, staged whole */
if (y_ld < N) return -3;
if (!e8_row) e8_row = K / kMX;
if (e8_row < K / kMX) return -3;
@@ -548,17 +534,16 @@ extern "C" int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, l
/* ================================================================== the shims
*
* gemm_nt_q's slots, as the two shims take them: 0 a (E4M3), 1 a_scale (f32, one per (row,
* 128 of K)), 2 b (the e2m1 codes -- fp4_e2m1, or the raw u8 bytes, two a byte), 3 b_scale (the
* e8 plane, e8m0 or u8, one per 32 of K), 4 y (bf16), 5 a_sum (absent: symmetric), 6 b_ref (the
* e8 plane again, accepted and ignored).
* gemm_nt_q's slots: 0 a (E4M3), 1 a_scale (f32, one per (row, 128 of K)), 2 b (the e2m1 codes,
* as fp4_e2m1 or raw u8 bytes, two per byte), 3 b_scale (the e8 plane, e8m0 or u8, one per 32 of
* K), 4 y (bf16), 5 a_sum (absent: symmetric), 6 b_ref (the e8 plane again, accepted and
* ignored).
*/
/* The reserved-e8 scan: one pass per (pointer, size) pair for the process's life. The plane is
* the weight's, its address stable across the launches a pass makes, and a second scan of the
* same bytes buys nothing. The scan needs the host to see the plane -- the mapped tier's form,
* the placement the row's operands take; a plane the host cannot see is not scanned, and the
* kernel's e8 guard carries the reserved values there. */
/* The reserved-e8 scan, once per (pointer, size) pair for the process's life: the plane is a
* weight at a stable address. The host must be able to read the plane (the mapped tier's
* placement); a plane it cannot see is not scanned, and the kernel's e8 guard handles reserved
* values there. */
struct E8ScanKey { const void* p; long long n; };
static bool e8_scan_once(const void* p, long long n)
{
@@ -591,20 +576,20 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s)
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y))
return R3D_NO(RAD_E_INVAL);
if (r3d_has(ASUM)) return R3D_NO(RAD_E_DTYPE); /* symmetric: no zero point */
/* `b_ref` is the reference's per-row exponent, derived from `b_scale`: it changes no
* product, so beside an e2m1 weight its dtype is checked and its value ignored. */
/* `b_ref` is the reference's per-row exponent, derived from `b_scale`. It changes no product,
* so with an e2m1 weight only its dtype is checked. */
if (r3d_has(BREF) && BREF->dtype != RAD_E8M0 && BREF->dtype != RAD_U8)
return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE);
if (B->dtype != RAD_FP4E2M1 && B->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); /* e2m1, two a byte */
if (B->dtype != RAD_FP4E2M1 && B->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); /* e2m1, 2 per byte */
if (BS->dtype != RAD_E8M0 && BS->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); /* e8m0, one per 32 */
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
/* The `group` key names the band; the blocks the kernel reads -- 128 for the activation's
* scale, 32 for the weight's e8 -- are the format's, so the key is not checked. */
/* The `group` key names the band; the kernel's blocks (128 for the activation scale, 32 for
* the weight's e8) are fixed by the format, so the key is not checked. */
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
if (K % kGroup || K % kMX) return R3D_NO(RAD_E_SHAPE);
@@ -669,14 +654,13 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
if (BS->dtype != RAD_E8M0 && BS->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
/* The band's keys, from the schema: N, K, group. The codes plane is [N, K/2], so a band that
* names no N or K is answered by the operand, with the /2 restored. */
/* The band's keys from the schema: N, K, group. A band without N or K takes them from the
* codes plane. */
const long long M_band = r3d_geti_or(a, "M", 0);
const long long N0 = r3d_geti_or(a, "N", 0), K0 = r3d_geti_or(a, "K", 0);
const long long N = N0 > 0 ? N0 : r3d_dim(B, 0);
/* A band that names no K is answered by the codes plane: [N, K] of fp4_e2m1, [N, K/2] of
* raw bytes. The `group` key names the band; the blocks the kernel reads are the
* format's, so the key is not checked. */
/* Without a K key, K comes from the codes plane: [N, K] of fp4_e2m1, [N, K/2] of raw bytes.
* The `group` key is not checked (see the m16 shim). */
const long long K = K0 > 0 ? K0
: (B->dtype == RAD_FP4E2M1 ? r3d_dim(B, 1) : 2 * r3d_dim(B, 1));
if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE);
@@ -686,10 +670,8 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
long long a_rows = 0;
const long long ap = r3d_rows_pitch(A, K, &a_rows);
if (ap < K || a_rows < 1) return R3D_NO(RAD_E_STRIDE);
if (ap % 8) return R3D_NO(RAD_E_STRIDE); /* 8-byte code loads, 8 codes a lane */
/* THE STEP'S M IS THE ACTIVATION'S ROW COUNT. The band key M is an upper bound: a step
* shorter than the band is the step the engine runs, and the key keeps its job as the
* ceiling the plan promised not to exceed. */
if (ap % 8) return R3D_NO(RAD_E_STRIDE); /* 8-byte code loads, 8 codes per lane */
/* The step's M is the activation's row count; the band key M is only the upper bound. */
const long long M = a_rows;
if (M_band > 0 && M > M_band) return R3D_NO(RAD_E_SHAPE);
if (M < kMMin) return R3D_NO(RAD_E_UNSUPPORTED); /* the m16 row serves M <= 16 */
@@ -706,7 +688,7 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
const long long as_p = r3d_row_pitch(AS);
if (as_p < K / kGroup) return R3D_NO(RAD_E_STRIDE);
/* The codes plane's pitch, in bytes: fp4_e2m1 counts elements, two to a byte. */
/* The codes plane's pitch in bytes: fp4_e2m1 counts elements, two per byte. */
const long long cp0 = r3d_row_pitch(B);
const long long cp = B->dtype == RAD_FP4E2M1 ? cp0 / 2 : cp0;
if (cp < K / 2) return R3D_NO(RAD_E_STRIDE);
+124 -180
View File
@@ -1,112 +1,84 @@
/* r3d_gemm_nt_q_w2a8.hip -- gemm_nt_q at dtype=w2a8: the vocabulary projection, decode-sized.
*
* y[M,N] = a[M,K] @ b[N,K]^T over a 2-bit unsigned weight code with an f16 scale and an unsigned
* integer zero per (row, group of K), an int8 activation with one f32 scale per ROW, and the int8
* code sums `a_sum` the zero is removed with. f32 accumulate, bf16 store.
* integer zero per (row, group of K), an int8 activation with one f32 scale per row, and the int8
* code sums `a_sum` that remove the zero. f32 accumulate, bf16 store.
*
* This is the band that gates the server. MiniCPM5-2B's `output.weight` is N=130560, K=2048,
* group=128, dtype=w2a8, and its stored form is the container's joined `rad.planes` operand: a
* scale plane and a zero plane behind ONE operand (b_scale). libref declines w2a8 in
* `gemm_q_shape`, so kbench has no case for the op the engine needs most -- the fixture cannot
* draw the dtype, which is why this row's evidence is a driver that builds the joined operand with
* `rad_planes_relayout` and compares every element against `ref_gemm_nt_q`'s own body. libref reads
* the form in `gemm_zp`, so a host row serves it, at 135 GFLOP of CPU work per token; and a
* placement without a reader is refused, because nothing in the loaded set can READ the joined form.
* `r3d_layout_gemm_q_w2a8` below is that reader: it DESCRIBES the container's bytes (that is what
* RadLayoutFn in rad_abi.h is), and the row carries no relayout and no repacking.
* MiniCPM5-2B's `output.weight` is N=130560, K=2048, group=128, dtype=w2a8, stored as the
* container's joined `rad.planes` operand: a scale plane and a zero plane behind one operand
* (b_scale). libref's `gemm_q_shape` declines w2a8, so kbench has no case for it; the row is
* verified by a driver that builds the joined operand with `rad_planes_relayout` and compares every
* element against `ref_gemm_nt_q`. libref's host row (`gemm_zp`) costs 135 GFLOP of CPU work per
* token, and the engine refuses a placement no loaded library can read, so this row needs
* `r3d_layout_gemm_nt_q_w2a8` below: it describes the container's bytes (RadLayoutFn in
* rad_abi.h) and does no repacking.
*
* ---- the law, and the order inside it ---------------------------------------------------------
*
* gemm_zp, the ZP_I8_ROW arm, is the spec, and this kernel runs its order:
* gemm_zp's ZP_I8_ROW arm is the spec, and this kernel runs its order:
*
* q[k] = rad_load_bits(row n of b, 2, k) bits [2k,2k+2) of byte k/4
* is(g) = SUM_{k in group g} (int)a[m][i8_step_pos(k)] * (int)q[k] integers: exact
* sub(g) = (float)is(g) - (float)z[n][g] * a_sum[g*mpad + m] mpad = ceil(M/16)*16 = 16
* acc = acc + (sub(g) * sa[m]) * sb[n][g] g ASCENDING
* acc = acc + (sub(g) * sa[m]) * sb[n][g] g ascending
* y[m,n] = bf16(acc)
*
* `a_sum` is per row and per group and group-major, `sa` is one f32 per ROW (ZP_I8_ROW: quant_act_i8
* scales a whole row, not a group), and `(sub * sa) * sb` is a parenthesised order, not a formula.
* `a_sum` is per row and per group, group-major. `sa` is one f32 per row (ZP_I8_ROW: quant_act_i8
* scales a whole row, not a group). The parentheses in `(sub * sa) * sb` are the reference's order.
*
* The activation is in quant_act_i8's step order: column c sits at byte
* i8_step_pos(c) = (c & ~12) | ((c & 4) << 1) | ((c & 8) >> 1), bits 2 and 3 of c swapped, the map
* its own inverse. Swapping bits 2 and 3 of a column is swapping bits 0 and 1 of its DWORD index,
* so a dword's four columns stay four contiguous bytes: staging reads a's dwords in a permuted
* dword order, one 4-byte load per four codes, and nothing straddles a dword.
* i8_step_pos(c) = (c & ~12) | ((c & 4) << 1) | ((c & 8) >> 1), bits 2 and 3 of c swapped, a
* self-inverse map. On the dword index that is a swap of bits 0 and 1, so a dword's four columns
* stay contiguous: staging reads a's dwords in permuted order, one 4-byte load per four codes.
*
* `is` is a sum of integers, every partial sum under 2^24, so it is exact in f32 and its bracketing
* is free. `sub`, the products and the g-ascending accumulation are float, and their order is the
* reference's, so the store is bit-identical to the host row: bit-equality element by element is
* the test, not a tolerance, because nothing else on this machine can draw the operands.
* Exactness. In exact f32 arithmetic `is` (integer partials under 2^24) would be exact and the
* float steps follow the reference's order. The dot instruction is not that exact (below), so
* 0.1-0.2% of outputs land one bf16 ulp off the reference: rel_l2 5.0e-3 at the band, no
* non-finite values. The row is not bit-exact, and its row-table text says so.
*
* ---- U2 to f16 through a bias, and the bias removed with a_sum ---------------------------------
*
* There is no int8 dot on this ISA. `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a`
* and the RDNA3 matrix ops `__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are all undeclared in AMD
* clang 24.0.0git for gfx1102. So the codes widen to f16 and the dot runs on dot2_f16x2, whose
* hardware form folds a pair into an f32 accumulator. Every product is
* an integer and every partial sum is an integer, and "products and partials are integers below
* 2^24" is a true statement about f32 and a false statement about this instruction: v_fdot2_f32_f16
* carries a little under 24 bits of mantissa on integer operands -- about 22, from the ratio of the
* worst error to its magnitude -- so any kernel that pushes integers through a pair-dot inherits a
* tail once its partials reach 2^20. The instrument at the end of this file (one 64-code dot per
* lane, the f32 it produces beside the exact integer it should have produced) shows: bias 1024,
* 71027 of 262144 dots off, by up to 1/8. Bias 128, 70115 of 262144 off, by up to 1/64. The bias is 128 because the tail grows with the magnitude, and 128 is
* the largest power of two that keeps a lane's partial sum under 2^21; shrinking it is a smaller
* tail, not no tail. What the tail costs is one bit of the bf16 answer: 0.1-0.2% of outputs land one
* bf16 ulp off and nothing else, rel_l2 5.0e-3 at the band, no non-finite anywhere. That is this
* row's exactness, written out here because the law below is exact integers and the row reads like a
* bit-exact one. It is not, and the row's prose says so.
* The row without the dot unit -- four f32 words a quad in the tile, four __fmaf_rn per quad -- is
* not in this file. Its arithmetic is exact: a probe of 262144 samples of the four fmas with no
* tile, zero inexact dots, worst error exactly zero. Its staging is the defect: the f32 tile,
* written through a vector pointer at -O2, comes up with content that was never written, and
* typing the array `uint4` rules aliasing out, so the defect is in the tile staging and not in the
* arithmetic.
* At the band this row is not memory-bound. r3d_vocab_bf16.hip streams the same n_vocab x n_embd
* head in 535 MB of bf16 in 3.29 ms at M=1, 163 GB/s, two thirds of the card's DRAM. The 66.8 MB
* of codes this row reads has a streaming floor near 0.41 ms, not the 3.0 ms of one 22 GB/s pass
* this row measures, so this row runs 6-10x above its own floor and the headroom is in its loop --
* the group-term plane and the two barriers a chunk -- not in the memory system. An f32 row costs
* nothing to run, and the tail goes with it.
* The trick that pays for the widening is that f16 bits of (128 + x) are 0x5800 + 8x for 0 <= x < 8,
* so a 2-bit code becomes an f16 with a mask, two shifts and an add -- no table, no compare per
* code -- and the dot returns is' = SUM a[k]*(128 + q[k]) = is + 128*SUM a. SUM a over the group is
* the plane the op already carries: a_sum[g*mpad + m], the very number the zero is removed with.
* 128 * a_sum scales an integer-valued f32 by a power of two, so it is exact, is = is' - 128*a_sum
* is exact, and the reference's own sub = (float)is - (float)z*a_sum follows unchanged. The de-bias
* costs one exact f32 subtraction per (m, group) and is why a row with no int8 instruction on it is
* memory-bound at the band instead of unpack-bound.
* This ISA has no int8 dot: `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a` and the
* matrix ops `__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are undeclared in AMD clang 24.0.0git
* for gfx1102. The codes therefore widen to f16 and the dot runs on dot2_f16x2. v_fdot2_f32_f16
* carries about 22 bits of mantissa on integer operands, not 24, so integer partials pushed
* through it are inexact once they reach about 2^20. The bias choice is explained at u2x4_biased.
*
* The widening uses the fact that the f16 bits of (128 + x) are 0x5800 + 8x for 0 <= x < 8, so a
* 2-bit code becomes an f16 with a mask, two shifts and an add. The dot then returns
* is' = SUM a[k]*(128 + q[k]) = is + 128*SUM a, and SUM a over the group is a_sum[g*mpad + m],
* which the op already carries for the zero. 128 * a_sum is exact (a power-of-two scale of an
* integer-valued f32), so is = is' - 128*a_sum is exact and the reference's
* sub = (float)is - (float)z*a_sum follows unchanged, at one f32 subtraction per (m, group).
*
* The row is not memory-bound: its 66.8 MB of codes have a streaming floor near 0.41 ms, and the
* cost is in the loop (the group-term plane and the two barriers per chunk).
*
* ---- the lane map ------------------------------------------------------------------------------
*
* One warp per weight row n; a block of 8 waves covers 8 rows. MT, the template's row count, is the
* power of two that covers M, and KL = 32/MT is the number of k-lanes per activation row. A chunk
* is CHUNK = 2048/MT codes, so the staged tile is always MT*CHUNK/2 = 1024 dwords = 4 KiB: the
* tile shrinks with the row count exactly as the row count grows, which is what keeps the block
* resident at M=16. A chunk holds CHUNK/128 = 16/MT groups and every lane takes 64 codes -- one
* 16-byte load of codes (four bytes, sixteen codes each, U2 being four codes a byte), thirty-two
* dwords of activation from LDS and thirty-two dot2 in sixteen dot4_f16x4 -- so lane l owns row
* m = l % MT, k-lane kl = l / MT, and group ch*(16/MT) + kl/2, whose two halves are the pair
* (l, l^MT): the group folds with ONE shfl_xor, in integers.
* One warp per weight row n; a block of 8 waves covers 8 rows. MT is the power of two covering M,
* and KL = 32/MT is the number of k-lanes per activation row. A chunk is CHUNK = 2048/MT codes, so
* the staged tile is always MT*CHUNK/2 = 1024 dwords = 4 KiB, which keeps the block resident at
* M=16. A chunk holds CHUNK/128 = 16/MT groups. Each lane takes 64 codes per chunk: one 16-byte
* load of codes (U2 is four codes per byte), 32 dwords of activation from LDS and 32 dot2 in 16
* dot4_f16x4. Lane l owns row m = l % MT, k-lane kl = l / MT and group ch*(16/MT) + kl/2, whose two
* halves are the pair (l, l^MT), folded with one shfl_xor.
*
* Each lane's group index ascends with the chunk index, so `acc += term` in the lane IS the
* reference's ascending g loop over the groups that lane owns; the groups the other k-lanes own are
* added by kl-1 ordered broadcasts per chunk, in ascending kl, which is ascending g. At M=16, where
* a chunk is one group, there is no cross-lane float work at all. Reassociating the g sum is what
* would break bit-equality, and the map is built so that no lane ever has to.
* Group indices ascend with the chunk index, and within a chunk the row's owner lane adds the
* chunk's group terms in ascending g, so the accumulation is the reference's ascending g loop.
* Reassociating the g sum would change the result; no lane does.
*
* LDS is touched a quad at a time (two dwords, 8 bytes), swizzled as `p_ix` below; unswizzled the
* wavefront's 32 quads for one u all sit in the same bank pair.
* LDS is accessed one quad (two dwords, 8 bytes) at a time, swizzled by `p_ix` below; unswizzled,
* the wavefront's 32 quads for one u would all sit in the same bank pair.
*
* ---- refusals (codes; RAD_R3D_TRACE=1 prints the line) -----------------------------------------
*
* The shim mirrors gemm_ntq_impl's and gemm_zp's checks and declines two things the reference
* accepts, each named at its site: M > 16 (the band is 16, the tile is 16 rows, mpad is the
* reference's 16-row pad; the prefill vocab projection is `logits_gemm` and is a tiled bf16 row,
* not a wider loop bound here), and a zero plane stored sub-byte (U2/U4/U5), where the kernel reads
* a zero a byte at a time -- a sub-byte zero plane needs the bit-extract path,
* `rad_load_bits(zb, bits, g)` is ten lines. w2a8's practical form, and this container's, is U8.
* accepts, each named at its site: M > 16 (the tile is 16 rows and mpad is the reference's 16-row
* pad; the prefill vocab projection is `logits_gemm`, a tiled bf16 row), and a zero plane stored
* sub-byte (U2/U4/U5), because the kernel reads a zero one byte at a time; that would need the
* bit-extract path (`rad_load_bits(zb, bits, g)`). w2a8's practical form, and this container's,
* is U8.
*/
#include <hip/hip_runtime.h>
@@ -127,12 +99,10 @@ constexpr int kTileQuads = 512; /* MT * CHUNK/4, constant over MT: 512
constexpr int kGroup = 128; /* the block size w2a8 is stored at */
constexpr int kMpad = 16; /* the reference's (M+15)/16*16, M <= 16 */
/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse. Applying
* it to the four columns of one dword leaves them four contiguous bytes and turns the map on the
* DWORD index into a swap of bits 0 and 1 -- the middle two dwords of a 16-byte step exchanged.
* The byte a dword starts at is therefore 4 * dword_pos(d): NOT 4 * step_pos(d), which swaps the
* wrong pair of bits and reads the step's dwords unexchanged. */
[[maybe_unused]] [[maybe_unused]] __device__ __forceinline__ int64_t step_pos(int64_t c)
/* Column c sits at byte step_pos(c): bits 2 and 3 of c swapped, a self-inverse map. On the dword
* index it is a swap of bits 0 and 1 (the middle two dwords of a 16-byte step exchanged), so
* dword d starts at byte dword_pos(d). Not 4 * step_pos(d), which swaps the wrong pair of bits. */
[[maybe_unused]] __device__ __forceinline__ int64_t step_pos(int64_t c)
{
return (c & ~(int64_t)12) | ((c & 4) << 1) | ((c & 8) >> 1);
}
@@ -141,14 +111,13 @@ __device__ __forceinline__ int64_t dword_pos(int64_t d)
return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1));
}
/* The LDS swizzle, at the granularity the tile is touched: a quad of four codes, two dwords, moved
* as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low four bits with
* bits 4..7 -- a bijection on 16-quad groups, so on any tile whose quad count is a multiple of 16.
* A wavefront reads q = m*(CHUNK/4) + kl*16 + u for fixed u; CHUNK/4 is a multiple of 16 at every
* MT, so q ^ (q >> 4) mod 16 is u ^ (4m + kl) mod 16 over the 32 lanes -- 16 distinct values, each
* one 8-byte access spanning two banks: 32 banks, no conflict. The swizzle must leave bit 0 of the
* quad index alone: the two dwords of a quad are adjacent only then, and the scalar form that
* XORs bits 5..9 of the dword index does not. */
/* The LDS swizzle, at the tile's access granularity: a quad of four codes (two dwords) moved as one
* 8-byte word. Quads are numbered q = r*(CHUNK/4) + c; p_ix XORs q's low four bits with bits 4..7,
* a bijection on 16-quad groups and so on any tile whose quad count is a multiple of 16. A
* wavefront reads q = m*(CHUNK/4) + kl*16 + u for fixed u; CHUNK/4 is a multiple of 16 at every MT,
* so q ^ (q >> 4) mod 16 is u ^ (4m + kl) mod 16 over the 32 lanes: 16 distinct values, each an
* 8-byte access spanning two banks, 32 banks with no conflict. The swizzle works on quad indices
* so the two dwords of a quad stay adjacent; XORing bits 5..9 of the dword index would not. */
__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); }
/* Four int8 codes -> two f16x2 dwords. Exact: an integer of |a| <= 127 needs no rounding. */
@@ -159,17 +128,15 @@ __device__ __forceinline__ void i8x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t
(float)(int32_t)(int8_t)((w >> 24) & 0xffu));
}
/* Four U2 codes (one byte) -> two f16x2 dwords, BIASED by 128: each half is the f16 bits of
* (128 + code). An f16 at exponent 2^7 steps its mantissa by 1/8, so 128 + code is 0x5800 + 8*code
* and stays an integer. The dot therefore returns is + 128 * the group's code sum, which the
* epilogue takes off with the group's a_sum.
/* Four U2 codes (one byte) -> two f16x2 dwords, biased by 128: each half is the f16 bits of
* (128 + code). An f16 at exponent 2^7 steps its mantissa by 1/8, so 128 + code is 0x5800 + 8*code.
* The dot returns is + 128 * (the activation's group sum), which the epilogue removes with a_sum.
*
* The bias is 128 and not 1024 because of where the dot unit's precision runs out. a * (B + q) is an
* integer the size of 128 * B, and a lane's 64 of them sum to 64 * 128 * (B + 3): at B = 1024 that is
* 2^23, at B = 128 it is 2^20. The unit keeps a little under 24 bits of mantissa on integers, so the
* tail scales with the magnitude -- 71027 of 262144 dots off by up to 1/8 at B = 1024, 70115 off by
* up to 1/64 at B = 128, in the probe below. 128 is the largest power of two that keeps a lane's
* partial sum under 2^21, which is as close as a pair-dot gets; the header carries the rest. */
* The bias sets the magnitude of the dot's partial sums: a * (B + q) is up to 128 * B, and a lane's
* 64 of them reach 64 * 128 * (B + 3), about 2^23 at B = 1024 and 2^20 at B = 128. The dot unit
* keeps about 22 bits of mantissa on integers, so its error grows with the magnitude: over 262144
* sampled dots (probe below), the worst error is 1/8 at B = 1024 and 1/64 at B = 128. 128 is the
* largest power of two that keeps a lane's partial sum under 2^21. */
__device__ __forceinline__ void u2x4_biased(uint32_t w, uint32_t& lo, uint32_t& hi)
{
lo = 0x58005800u + ((w & 3u) << 3) + (((w >> 2) & 3u) << 19);
@@ -188,10 +155,10 @@ gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int
constexpr int CG = (2048 / MT) / kGroup; /* groups per chunk */
constexpr int CL = (2048 / MT) / KL; /* codes per lane per chunk: 64 */
/* The tile: one quad of four codes per slot, two f16x2 dwords, typed as the quad the staging
* writes and the dot reads. The tile is a `uint2[]` and not a `uint32_t[]` reached through a
* vector pointer: the f32 variant of this row, written through `*(uint4*)&sA[]` at -O2, comes
* up with content that was never written. */
/* The tile: one quad of four codes (two f16x2 dwords) per slot, typed as the quad the staging
* writes and the dot reads. It is a `uint2[]`, not a `uint32_t[]` written through a vector
* pointer: an f32 tile written through `*(uint4*)&sA[]` at -O2 read back content that was never
* written. */
__shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/2 f16, swizzled */
__shared__ float sT[kWaves * 16]; /* each warp's chunk terms: warp*16 + m*CG + j */
__shared__ float sSa[MT];
@@ -199,12 +166,10 @@ gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int
const int lane = threadIdx.x & (kWave - 1);
const int warp = (int)(threadIdx.x / kWave);
const int n = blockIdx.x * kWaves + warp;
/* A wavefront past the last row sits the chunk out, but it stages: the tile is block-wide, so
* the warps that have no row to serve still write the rows their lanes own. Only a block whose
* EIGHT rows are all past the last row leaves, which is a block-uniform test and cannot strand
* a barrier; a guard on the row would, because the tail block's dead warps own tile rows and
* staging them from never-written memory corrupts the tile. The store is guarded by `live`
* below, so a dead wavefront writes nothing. */
/* A wavefront past the last row skips the dot but still stages its share of the block-wide
* tile. Only a block whose eight rows are all past N returns early: that test is block-uniform
* and cannot strand a barrier, whereas a per-row return would leave tile rows unstaged. The
* store is guarded by `live`. */
const bool live = n < N;
if ((int)blockIdx.x * kWaves >= N) return;
@@ -219,8 +184,8 @@ gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int
float acc = 0.0f;
for (int ch = 0; ch < nchunk; ++ch) {
/* Stage the chunk's activation rows, widened and step-unpermuted on the way in. Cells are
* four codes: MT * CHUNK/4 = 512 of them at every MT, two per thread. */
/* Stage the chunk's activation rows, widened and step-unpermuted. Cells are four codes:
* MT * CHUNK/4 = 512 at every MT, two per thread. */
for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) {
const int r = i / (chunk >> 2), c = i % (chunk >> 2);
uint32_t w = 0;
@@ -261,26 +226,17 @@ gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int
const float iz = (float)zq[(long long)n * z_rb + g];
const float sc = f16_to_f32(sb[(long long)n * (sb_rb >> 1) + g]);
const float term = ((is - iz * as) * sSa[m]) * sc; /* gemm_zp's parentheses */
/* One slot per (row, group-in-chunk): MT*CG is 16 at every MT, so this is 64 bytes.
* The group's two half-lanes write the same value, which is why the pair fold above is
* a fold and not a broadcast. */
/* One slot per (row, group-in-chunk); MT*CG is 16 at every MT (64 bytes). Both
* half-lanes of a group write the same folded value. */
sT[warp * 16 + m * CG + (kl >> 1)] = term;
}
__syncthreads();
/* Group ch*CG + j, for j ascending, into the lane that owns the row's answer. The reference
* walks g in ascending order and f32 adds are not associative, so the order is part of the
* answer, not a detail. The group gather is the one place in the kernel that crosses
* k-lanes; it is a barrier and four LDS reads at 64 bytes, which is cheaper than a shuffle
* round-trip. */
/* Groups ch*CG + j, j ascending, into the row's owner lane: f32 adds are not associative
* and the reference walks g ascending. This gather is the only cross-k-lane step; a
* barrier and a few 64-byte LDS reads are cheaper than a shuffle round-trip. */
if (live && kl == 0) {
/* A chunk carries CG groups, and group ch*CG + j lives in the two k-lanes 2j and 2j+1:
* they hold the same group's two halves, which is what the fold above combined. Every
* lane adds all CG of them in ascending j, so each lane of a row ends on the same
* partial sum, built in the same order the reference walks its groups in -- f32 adds are
* not associative, and a lane that finished its own group last rounds the tail
* differently. Reading a lane's `acc` would not do: by j = 2 it has already added a
* group of its own. */
/* Group ch*CG + j comes from k-lanes 2j and 2j+1, already folded. */
#pragma unroll
for (int j = 0; j < CG; ++j)
if (m < M) acc += sT[warp * 16 + m * CG + j];
@@ -297,25 +253,21 @@ int mt_for(int M) { return M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : k
/* ================================================================== the launcher
*
* Codes: 0, -1 a required pointer is null, -2 a shape it does not read, -3 a pitch it cannot read,
* -4 HIP. `nt` is the threads argument every libr3d launcher takes and this kernel ignores: the
* work is one warp per weight row, and the wavefront count is the grid.
* Codes: 0, -1 a required pointer is null, -2 an unsupported shape, -3 an unreadable pitch, -4 HIP.
* `nt` is accepted for signature uniformity and ignored: the work is one warp per weight row.
*
* `b_scale` is the joined operand's base. The launcher reads the two planes out of its own header
* (rad_planes.h's rad_planes_find) and passes each plane's base, row pitch in bytes and the row
* count down, so the kernel reads the container's bytes where they lie. */
* `b_scale` is the joined operand's base. The launcher finds the two planes through its header
* (rad_planes.h's rad_planes_find) and passes each plane's base and row pitch in bytes, so the
* kernel reads the container's bytes in place. */
/* The instrument behind the measurement in the header: the dot on its own, one 64-code sample per
* lane, the f32 it produces beside the exact integer it should have produced. The driver runs it as
* `dot [n]`; the bias is sized from it, and it shows the f32 path to be exact. Two extern "C"
* symbols, no row, no cost at serve time. */
/* A probe of the dot's exactness: one 64-code sample per lane, the f32 the dot produces beside the
* exact integer. The test driver runs it as `dot [n]`; it is what sizes the bias. Two extern "C"
* symbols, no row, nothing at serve time. */
extern "C" __global__ void __launch_bounds__(256) probe_dot_kernel(const int8_t* a,
const uint8_t* codes,
float* out, long long* exact)
{
const int g = blockIdx.x * 32 + (int)(threadIdx.x / kWave) * 4 + (int)(threadIdx.x & 3);
const int lane4 = (int)(threadIdx.x & 31) & 3;
(void)lane4;
const uint32_t* w4 = (const uint32_t*)(codes + (long long)g * 16);
float p = 0.0f;
long long ex = 0;
@@ -353,8 +305,8 @@ extern "C" int r3d_gemm_nt_q_w2a8(long a, long a_scale, long b, long b_scale, lo
(void)nt;
if (!a || !a_scale || !b || !b_scale || !a_sum || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > kMTMax) return -2; /* the row says the same: C_LE("M", 16) */
if (group != kGroup) return -2; /* the tile is 128-wide: chunk = 128*16/MT */
if (M > kMTMax) return -2; /* as the row's C_LE("M", 16) */
if (group != kGroup) return -2; /* chunk = 128*16/MT */
if (K % kGroup) return -2;
if (K % 16) return -2; /* the step order is a 16-byte step */
const int mt = mt_for(M);
@@ -364,7 +316,7 @@ extern "C" int r3d_gemm_nt_q_w2a8(long a, long a_scale, long b, long b_scale, lo
if (G < 1) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (a_ld % 4) return -3; /* four codes a dword, staged whole */
if (a_ld % 4) return -3; /* four codes per dword, staged whole */
if (((uintptr_t)b & 15u) || ((uintptr_t)a & 3u)) return -3;
const RadPlanesHeader* h = rad_planes_header((const void*)(uintptr_t)b_scale);
@@ -402,8 +354,8 @@ extern "C" int r3d_gemm_nt_q_w2a8(long a, long a_scale, long b, long b_scale, lo
/* ================================================================== the shim
*
* gemm_nt_q's slots, as gemm_ntq_impl takes them: 0 a (i8, step order), 1 a_scale (f32, one per
* row), 2 b (the u2 codes), 3 b_scale (the joined scale+zero), 4 y (bf16), 5 a_sum (f32, group
* major, mpad = 16 columns). */
* row), 2 b (the u2 codes), 3 b_scale (the joined scale+zero), 4 y (bf16), 5 a_sum (f32,
* group-major, mpad = 16 columns). */
extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
@@ -434,16 +386,13 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
const long long ynel = r3d_numel(Y);
if (N < 1 || ynel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = ynel / N;
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); /* DECLINE, in the header: the band is
* 16 and the tile is 16 rows; the
* prefill vocab projection is
* logits_gemm, a tiled bf16 row. */
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); /* declined; see the header */
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(AS) < M) return R3D_NO(RAD_E_INVAL); /* gemm_zp's code for this one */
if (r3d_numel(ASUM) < G * kMpad) return R3D_NO(RAD_E_INVAL);
const long long ap = r3d_row_pitch(A);
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE); /* step order read four codes a dword */
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE); /* step order: four codes a dword */
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); /* gemm_zp: contiguous codes only */
long long yrows = 0;
const long long yp = r3d_rows_pitch(Y, N, &yrows);
@@ -459,8 +408,8 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
if (!sp || !zp || !es || !ez) return R3D_NO(RAD_E_DTYPE);
if (es->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE);
if (ez->dtype != RAD_U8)
return R3D_NO(RAD_E_DTYPE); /* DECLINE: a sub-byte zero plane needs the bit-extract path;
* rad_load_bits(zb, bits, g) is 10 lines. U8 is w2a8's form. */
return R3D_NO(RAD_E_DTYPE); /* declined: a sub-byte zero plane needs the bit-extract
* path (rad_load_bits). U8 is w2a8's form. */
if (es->rows != N || es->cols != G || ez->rows != N || ez->cols != G) return R3D_NO(RAD_E_SHAPE);
if ((es->row_bytes & 1) || es->row_bytes < 2 * G || ez->row_bytes < G) return R3D_NO(RAD_E_STRIDE);
@@ -469,8 +418,7 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
const int rc = r3d_gemm_nt_q_w2a8(
r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), r3d_addr(ASUM), r3d_addr(Y), (int)M,
(int)N, (int)K, (int)group, (int)ap, (int)yp, 0, (long)s);
/* The launcher's codes are its own (r3d_launch.h's set: null, shape, pitch, HIP); the row speaks
* RAD codes, and the shim is where the two are named. Same mapping as the gated row's. */
/* Launcher codes (null, shape, pitch, HIP) to RAD codes, as in the gated row. */
if (rc == 0) return RAD_OK;
return R3D_NO(rc == -1 ? RAD_E_INVAL : rc == -2 ? RAD_E_SHAPE
: rc == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
@@ -478,8 +426,8 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
/* ================================================================== the layout hook
*
* The scoped exception to libr3d's "no layout hooks, no repacking" rule, transcribed from libref's
* `ref_layout_gemm_q` with the checks and their order unchanged:
* One of libr3d's few layout hooks, transcribed from libref's `ref_layout_gemm_q` with the checks
* and their order unchanged:
*
* if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
* const ZpGrid* zg = zp_grid(dtype); group = param "group";
@@ -493,17 +441,14 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
*
* zp_grid, zero_dt and sel_roles are libref-internal statics, inlined below for w2a8: the grid is
* { "w2a8", RAD_U2, ZP_I8_ROW }, zero_dt is U8|U2|U4|U5, and the practical form is U8 (the kernel
* declines a sub-byte zero, at its site, with the fix named). The answer is rad_planes.h's own:
* the tag is "rad.planes", the dtype the first plane's, the shape the byte count. NOTHING HERE
* MOVES A BYTE: this hook is the reader the mapped tier needs and the row's relayout is null.
* declines a sub-byte zero at its site). The answer is rad_planes.h's: the tag "rad.planes", the
* dtype the first plane's, the shape the byte count. The hook moves no bytes.
*/
/* The writer for the joined operand this hook names: codes, scale and zero as the plan's one
* `rad.planes` weight, assembled by rad_planes_relayout -- header, entries, each plane's rows,
* copied. The ABI's contract is that a query answering RAD_OK is a promise the loader keeps on the
* row's word: "out describes the stored form, and relayout will produce it" (rad_abi.h), and a
* weight with no hook is the only kind that can be read where it lies, which is why a joined weight
* is placed in VRAM and a plain one can stay on the mapped tier. Nothing here transforms a code:
* the bytes written are the bytes stored. */
/* The writer for the joined operand this hook names: codes, scale and zero as one `rad.planes`
* weight, assembled by rad_planes_relayout (header, entries, each plane's rows, copied). A layout
* query answering RAD_OK promises "out describes the stored form, and relayout will produce it"
* (rad_abi.h). Only a weight with no hook can be read in place, so a joined weight is placed in
* VRAM while a plain one can stay on the mapped tier. No code is transformed. */
extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n_planes, void* dst,
@@ -514,9 +459,9 @@ extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int opera
return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes);
}
/* A layout query answers in the engine's own vocabulary and leaves no trace, and a model that will
* not load says only that two rows want one weight in two forms. This prints the question and the
* answer -- operand, band dtype, planes offered, code returned -- under RAD_R3D_TRACE=1. */
/* Under RAD_R3D_TRACE, prints each layout query (operand, band dtype, planes offered) and its
* return code. Otherwise a model that fails to load reports only that two rows want one weight in
* two forms. */
static int r3d_layout_trace(const char* who, int operand, const char* dt, int n_planes, int rc) {
if (r3d_trace_on())
std::fprintf(stderr, "[r3d] %s: operand %d dtype %s planes %d -> %d\n", who, operand,
@@ -530,11 +475,10 @@ extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand
{
if (n < 2 || operand != 3) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_UNSUPPORTED);
const char* dt = r3d_pgets(p, n_p, "dtype");
/* The plan this hook describes -- the (scale, zero) pair joined on operand 3 -- is a statement
* about the CONTAINER, not about the code width, and the engine forces every row that reads one
* weight to answer with one form. So both packed grids come through, and the width a row can
* unpack is the SHIM's business: gemm_nt_q_w2a8_m16 reads U2 and nothing else,
* gemm_nt_q_w2a8_tiled reads U2 and U4, and each says so at its own line. */
/* The (scale, zero) pair joined on operand 3 describes the container, not the code width, and
* every row that reads one weight must answer with one form. So both packed grids pass here;
* the code width is checked by each shim (gemm_nt_q_w2a8_m16 reads U2 only,
* gemm_nt_q_w2a8_tiled reads U2 and U4). */
if (!dt || (std::strcmp(dt, "w2a8") != 0 && std::strcmp(dt, "w4a8_asym") != 0))
return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* the packed grids */
const long long group = r3d_pgeti_or(p, n_p, "group", 0);
@@ -551,8 +495,8 @@ extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand
if (sel[i] < 0 || sel[i] >= enc->n_planes) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
if (std::strncmp(enc->plane[sel[i]].role, want, RAD_ENC_STR) != 0) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
}
/* The codes plane is the one this operand does NOT take: the weight's role "codes", the grid's
* dtype, block {1,1}. libref finds it by role over enc->plane, not by sel. */
/* The codes plane is not part of this operand: role "codes", the grid's dtype, block {1,1}.
* libref finds it by role over enc->plane, not by sel. */
int codes = -1;
for (int i = 0; i < enc->n_planes; ++i)
if (std::strncmp(enc->plane[i].role, "codes", RAD_ENC_STR) == 0) { codes = i; break; }
+7 -9
View File
@@ -1,15 +1,13 @@
/* r3d_launch.h -- the two lines a libr3d unit needs to launch a kernel.
/* r3d_launch.h -- kernel launch macros for libr3d units.
*
* R3D_KLAUNCH is the triple-chevron form, which the engine services on its own queues because the
* stream it hands a launch is the one hipLaunchKernel accepts (docs/PLUGIN.md §5). It is written as
* a macro so a test can define it and drive the same sources through a host SIMT emulator; a build
* does not, and gets the chevron.
* R3D_KLAUNCH is the triple-chevron launch on the stream the engine hands the entry point, which is
* a stream hipLaunchKernel accepts (docs/PLUGIN.md §5). It is a macro so a test can redefine it and
* run the same sources through a host SIMT emulator.
*
* R3D_DYN_LDS declares a kernel's dynamic LDS, sized by the launch: `extern __shared__` in a build.
* RDNA3 gives a workgroup the same 64 KiB RDNA4 does, so a tile sized for libr4d fits here too.
* R3D_DYN_LDS declares a kernel's dynamic LDS, sized by the launch. RDNA3 gives a workgroup 64 KiB,
* as RDNA4 does, so a tile sized for libr4d fits.
*
* R3D_KNAME names a kernel in a context where commas would split a macro argument, the way
* HIP_KERNEL_NAME does for hipLaunchKernelGGL.
* R3D_KNAME wraps a kernel name that contains commas, like HIP_KERNEL_NAME.
*/
#ifndef R3D_LAUNCH_H
#define R3D_LAUNCH_H
+229 -258
View File
@@ -1,48 +1,46 @@
/* r3d_model_bf16.hip -- the small ops the engine issues between the GEMMs: the norms, the
* elementwise arithmetic, the activations, cast, softmax, the embedding gather, gather_rows and
* scatter_rows, rope and the KV store. Every one of them needs a device launch, because the
* engine's buffers live in VRAM and `rad_issue` refuses an op with no launch for its operands'
* domain: on an RDNA3 card this unit is the difference between a model that runs and one that does
* not (R3D_CONTRACT, "What libr3d is").
* elementwise arithmetic, the activations, cast, softmax, embed_lookup, gather_rows and
* scatter_rows, rope and kv_store, plus the fused silu_mul and rmsnorm_quant_fp8. Each needs a
* device launch because the engine's buffers live in VRAM and `rad_issue` refuses an op with no
* launch for its operands' domain; without this unit no model runs on an RDNA3 card (R3D_CONTRACT,
* "What libr3d is").
*
* The arithmetic is libref's -- the oracle every row is checked against at kbench -- and each
* kernel names the ref function it must equal, its operation order and its rounding points:
* The arithmetic is libref's, the oracle every row is checked against by kbench, and each kernel
* names the ref function it must equal, its operation order and its rounding points:
*
* * every reduction accumulates in f32 and only the store narrows, RTNE (r3d_codecs.h is
* rad_plugin.h's rounders restated for device code, bit for bit);
* * a row's sum is taken over lanes covering consecutive elements, butterflies in the order a
* `__shfl_xor` loop runs and wave partials added in wave order: `block_sum` in r3d_common.h,
* so the bracketing is the one the contract fixes and not a per-thread accident;
* * bf16 is kept in whole registers from load to store (`ldg_u16`) and a lane that owns two
* consecutive columns stores them as one dword through `bf16x2_rne` -- gfx11 has no
* v_cvt_pk_bf16_f32, so the pack is two software roundings and a v_perm_b32;
* * no FMA and no reassociation: -ffp-contract=off is on every HIP source (libr3d/CMakeLists.txt)
* and the expressions below are written in the reference's order, with the temporaries the
* reference has;
* * a negative index -- token id, gather row, KV slot -- is padding: a zero row, or no store.
* It is not clamped to zero, which would duplicate row 0 across every padding row.
* * every reduction accumulates in f32 and only the store narrows, RTNE (r3d_codecs.h restates
* rad_plugin.h's rounders for device code, bit for bit);
* * a row's sum is taken over lanes covering consecutive elements with `block_sum`
* (r3d_common.h), so the bracketing is the one the contract fixes;
* * bf16 stays in whole registers from load to store (`ldg_u16`), and a lane that owns two
* consecutive columns stores them as one dword through `bf16x2_rne` (gfx11 has no
* v_cvt_pk_bf16_f32, so the pack is two software roundings and a v_perm_b32);
* * no FMA and no reassociation: -ffp-contract=off is on every HIP source (CMakeLists.txt), and
* expressions follow the reference's order and temporaries;
* * a negative index (token id, gather row, KV slot) is padding: a zero row, or no store. It is
* not clamped to zero, which would copy row 0 into every padding row.
*
* One deliberate divergence from ref, the same one libr4d states: ref validates its index arrays
* on the host and refuses an id at or past the row count. A kernel cannot do that without a copy
* and a sync on the step path, so a row count is an argument and an out-of-range id takes the
* padding path (zero row, no store) instead of faulting. kv_store's slot bound is the one place
* the reference has an argument the launcher does not (see below).
* One deliberate divergence from ref, shared with libr4d: ref validates its index arrays on the
* host and refuses an id at or past the row count. A kernel cannot do that without a copy and a
* sync on the step path, so the row count is an argument and an out-of-range id takes the padding
* path instead of faulting. kv_store's slot bound is the one place the reference has an argument
* the launcher does not (see below).
*
* `expf`, `powf` and `sincosf` are the accurate forms, not the `__` approximations: rope positions
* reach 262144, past __sincosf's argument reduction, and libref evaluates every transcendental in
* double and rounds once (libref's ref_exp/ref_pow/ref_sin/ref_cos/ref_erf). None of these
* paths is the step's bottleneck, so the difference between libm and a device routine -- a few
* ULP of f32, against the 1/256 of a bf16 store -- is the whole of the tolerance.
* double and rounds once (ref_exp/ref_pow/ref_sin/ref_cos/ref_erf). The few f32 ULP between libm
* and a device routine are the whole tolerance, far below a bf16 store's 1/256, and none of these
* paths is a step bottleneck.
*
* No fusion: `rmsnorm_add` and the gated quantisers are separate entry points the architecture
* plugin selects (spec §2.3), and live in other units.
* `rmsnorm_add` and the gated quantisers are separate entry points the architecture plugin selects
* (spec §2.3), in other units.
*
* Two layers per op, as r3d.h states: a launcher that takes pointers as longs and geometry as
* ints, checks what a `__global__` cannot, computes the grid and issues one kernel on the stream it
* was handed; and the shim the row table names, which reads the operands with r3d_args.h, takes
* the dtype from the tensor and the row count from the operand, and returns a RAD status. Neither
* allocates, neither synchronises. A launcher returns 0 or -1 (null), -2 (extent), -3 (pitch),
* -4 (the HIP launch failed); a shim maps any non-zero code to RAD_E_DEVICE.
* Two layers per op, as r3d.h states: a launcher that takes pointers as longs and geometry as ints,
* checks what a `__global__` cannot, computes the grid and issues one kernel on the given stream;
* and the shim the row table names, which reads the operands with r3d_args.h, takes the dtype and
* row count from the tensors and returns a RAD status. Neither allocates or synchronises. A
* launcher returns 0, or -1 (null), -2 (extent), -3 (pitch), -4 (HIP launch failed); a shim maps
* any non-zero code to RAD_E_DEVICE.
*/
#include "r3d.h"
@@ -60,18 +58,17 @@ constexpr uint32_t kThreads = 256; // eight wave32s: the wide row, the hidden
constexpr uint32_t kNarrow = 32; // one wave32: the narrow row, a head of a QK norm
constexpr uint32_t kNarrowN = 256; // a row this narrow is a wave's, eight columns a lane
/* The workgroup a row gets: one wave for the rows a wave already covers -- an attention head, a
* KV head, a QK norm, where a 256-thread group would spend three quarters of its lanes on a
* barrier -- and 256 for everything wider. */
/* The workgroup a row gets: one wave for rows a wave covers (an attention head, a KV head, a QK
* norm), where 256 threads would leave three quarters of the lanes waiting at a barrier, and 256
* for anything wider. */
static inline int row_threads(int n) { return n <= (int)kNarrowN ? (int)kNarrow : (int)kThreads; }
/* ================================================================== the seams every kernel here
* shares
*
* A whole-register store beside r3d_common.h's whole-register load. The dword form is the pair
* store; the caller has already proved the address even, in elements, from a base alignment of 4.
* The address-space cast is r3d_common.h's own, a C-style cast to the qualified type:
* reinterpret_cast refuses to change address spaces.
* Whole-register stores to match r3d_common.h's whole-register loads. The dword form is the pair
* store; the caller has proved the address even, in elements, from a base alignment of 4. The
* address-space casts are C-style because reinterpret_cast cannot change address spaces.
*/
typedef uint32_t __attribute__((address_space(1))) *r3d_gu32;
typedef float __attribute__((address_space(1))) *r3d_gf32;
@@ -88,10 +85,9 @@ __device__ __forceinline__ void stg_i32(int32_t* p, int32_t v) { *(r3d_gi32)p =
__device__ __forceinline__ void stg_i64(int64_t* p, int64_t v) { *(r3d_gi64)p = v; }
__device__ __forceinline__ uint16_t ldg_u16_at(const uint16_t* p, uint32_t i) { return (uint16_t)ldg_u16(p + i); }
/* The max across a workgroup, in the shape block_sum has: a wave butterfly and one LDS round trip.
* The order is free -- a max is associative, commutative and idempotent, so softmax's maximum is
* the one reduction whose bracketing cannot change the answer -- and every wave has to reach the
* LDS before any thread reads it, which is what the barrier inside is for. */
/* The max across a workgroup, shaped like block_sum: a wave butterfly and one LDS round trip. Max is
* associative, commutative and idempotent, so the bracketing cannot change the result. The barrier
* inside makes every wave's partial visible before any thread reads it. */
template <int NTHREADS>
__device__ __forceinline__ float block_max(float v, float* lds) {
constexpr int NWAVES = NTHREADS / kWave;
@@ -109,14 +105,12 @@ __device__ __forceinline__ float block_max(float v, float* lds) {
/* ================================================================== one element, any dtype
*
* cast, fill, gather_rows, scatter_rows, embed_lookup and kv_store are one kernel over several
* dtypes, because their dtype is a runtime value in the launcher's argument list. These are
* the reference's ld_dt and st_dt over libr3d's dtype codes, and they are deliberately as
* expensive -- one switch per element, "the price of being generic" in ref's own words. None of
* them is a matmul; none of them reads one element per FLOP.
* dtypes because the dtype is a runtime launcher argument. These are the reference's ld_dt and
* st_dt over libr3d's dtype codes, with one switch per element; none of these ops is compute-bound.
*
* The integer stores round to nearest even, saturate, and store NaN as 0 (sat_round, the
* reference's): wrapping an overflowing activation into a plausible small number is the failure
* this library has to catch, not hide.
* The integer stores round to nearest even, saturate, and store NaN as 0 (the reference's
* sat_round): wrapping an overflowing activation into a plausible small number would hide the
* error.
*/
__device__ __forceinline__ float sat_round(float v, float lo, float hi) {
if (v != v) return 0.0f;
@@ -196,10 +190,10 @@ __device__ __forceinline__ int dt_bytes(int dt) {
}
}
/* The activation, off libref's act_* set. The reference evaluates the transcendental in double
* and rounds once to f32 (libref's ref_exp/ref_erf); the device's accurate expf/erff are a
* few ULP of f32 away, and the store to bf16 keeps 8 mantissa bits. gelu is the exact erf form --
* "gelu" means this in libref, and the tanh approximation has to be asked for by name. */
/* The activation, from libref's act_* set. The reference evaluates the transcendental in double and
* rounds once to f32 (ref_exp/ref_erf); the device's accurate expf/erff are a few f32 ULP away, and
* the bf16 store keeps 8 mantissa bits. gelu is the exact erf form, as "gelu" means in libref; the
* tanh approximation is a separate op name. */
template <int ACT>
__device__ __forceinline__ float act_of(float x) {
if constexpr (ACT == R3D_ACT_SIGMOID) return 1.0f / (1.0f + expf(-x));
@@ -215,14 +209,14 @@ __device__ __forceinline__ float act_of(float x) {
* s = 1 / sqrt(ss/n + eps)
* y[i] = x[i] * s * (w ? w[i] + wadd : 1) * mult
*
* The mean is over the last n of the row and the gain rides every row. An absent gain is the
* constant 1 -- the shim refuses `wadd` without one, as ref does -- and the gain's dtype is read
* off the operand (WDT: R3D_DT_BF16, R3D_DT_F32, R3D_DT_N for none), because a checkpoint that
* stores its gains in f32 (a QK-norm's, an audio tower's) is read as it is. Forming 1+w in bf16
* first loses 0.3% per channel, which is why `wadd` is added in f32 here.
* The mean is over the last n of the row and the gain applies to every row. An absent gain is the
* constant 1 (the shim refuses `wadd` without one, as ref does). The gain's dtype is read off the
* operand (WDT: R3D_DT_BF16, R3D_DT_F32, or R3D_DT_N for none), so a checkpoint that stores f32
* gains (a QK norm's, an audio tower's) is read as stored. `wadd` is added in f32 because forming
* 1+w in bf16 first loses 0.3% per channel.
*
* `mult` scales the normed row before its one rounding, for a residual branch weighted by a
* constant (Gemma 4's audio feed-forward uses 0.5); 1 leaves the product chain alone.
* constant (e.g. 0.5 in Gemma 4's audio feed-forward); 1 leaves the product unchanged.
*/
template <int THR, int WDT, int F32>
__global__ __launch_bounds__(THR) void rmsnorm_kernel(
@@ -266,14 +260,14 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(
}
/* ================================================================== layernorm
* Two passes -- the mean, then the squared deviations about that
* mean -- and not one pass of E[x^2] - E[x]^2, which cancels badly when the mean is large against
* the spread. Biased variance (divide by n), as transformers use. The store is the third pass:
* Two passes, the mean and then the squared deviations about it, rather than E[x^2] - E[x]^2,
* which cancels badly when the mean is large against the spread. Biased variance (divide by n), as
* transformers use. The store is the third pass:
*
* y[i] = ((x[i] - mean) * s * w[i]) + b[i]
*
* with `b` optional and the gain bf16 (the launcher has no gain dtype; libref reads w's through
* its own dtype, so an f32 gain is refused by the shim, not read as bf16).
* `b` is optional. The gain is bf16 only (the launcher has no gain dtype), so the shim refuses an
* f32 gain rather than reading it as bf16.
*/
template <int THR>
__global__ __launch_bounds__(THR) void layernorm_kernel(
@@ -316,14 +310,14 @@ __global__ __launch_bounds__(THR) void layernorm_kernel(
* if (div != 1) s = round_to_y(s) / div; two roundings, y's dtype
* y[i] = round_to_y(s)
*
* `div` is the last sum of a mean taken pairwise -- (b0+b1+b2)/3, as a vocoder averages its
* residual blocks -- and the sum is narrowed before it is divided because the unfused pair stores
* it. 1 is the plain sum.
* `div` is the last step of a mean taken pairwise, (b0+b1+b2)/3 as a vocoder averages its residual
* blocks; the sum is narrowed before the divide because the unfused pair stores it. 1 is the plain
* sum.
*
* The broadcast: b carrying exactly n elements rides every row (`bcast`, which the shim sets off
* the operand's element count, as ref does); nothing else broadcasts, so a shape bug cannot pass
* as a plausible number. The f32 pair narrows nothing on the way (round_dt(f32) is the identity),
* and `y` may be `a`: every element is read by the thread that writes it.
* Broadcast: a b of exactly n elements applies to every row (`bcast`, set by the shim from the
* operand's element count, as ref does). Nothing else broadcasts, so a shape bug cannot pass as a
* plausible number. The f32 leg narrows nothing (round_dt(f32) is the identity), and `y` may alias
* `a`: every element is read by the thread that writes it.
*/
template <int THR, int MUL, int PAIR, int F32>
__global__ __launch_bounds__(THR) void binary_kernel(
@@ -364,10 +358,9 @@ __global__ __launch_bounds__(THR) void binary_kernel(
}
/* ================================================================== cast
* `from`/`to` are the selector's; the bytes are what the tensors say,
* which is what ref reads and what this kernel does. An integer pair goes straight through, so a
* token id above 2^24 survives an i64 -> i32 copy; everything else widens to f32 and narrows once
* on the way out. One switch per element: cast is a bandwidth op between stages, not a hot loop.
* `from`/`to` select the row; the kernel moves the dtypes the tensors carry, as ref does. An integer
* pair goes straight through, so a token id above 2^24 survives an i64 -> i32 copy; everything else
* widens to f32 and narrows once. One switch per element: cast is a bandwidth op, not a hot loop.
*/
template <int THR>
__global__ __launch_bounds__(THR) void cast_kernel(
@@ -384,9 +377,8 @@ __global__ __launch_bounds__(THR) void cast_kernel(
}
/* ================================================================== silu / gelu / sigmoid
* unary: one element, one activation, one narrowing by the store.
* The three are one kernel with the activation as a template argument, because libr3d's rows serve
* all three and the body differs by one expression. */
* unary: one element, one activation, one narrowing by the store. The activation is a template
* argument because the three bodies differ by one expression. */
template <int THR, int ACT, int PAIR, int F32>
__global__ __launch_bounds__(THR) void unary_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld,
@@ -418,14 +410,14 @@ __global__ __launch_bounds__(THR) void unary_kernel(
}
/* ================================================================== act_mul
* y = act(a) * b, with the activation narrowed to y's dtype first,
* because the unfused pair stores it -- the rounding is the contract, not a detail:
* y = act(a) * b, with the activation narrowed to y's dtype first because the unfused pair stores
* it; that rounding is part of the contract:
*
* v = act(a[i]); y[i] = round_to_y( round_to_y(v) * b[i] )
*
* `a` and `b` are the two halves of a fused projection, so each has its own pitch. The shims serve
* silu, gelu (the exact erf form) and sigmoid; gelu_tanh and quick_gelu are libref's other two
* kActs entries and are refused, so the row's constraints state which gated MLPs reach this card.
* silu, gelu (the exact erf form) and sigmoid; gelu_tanh and quick_gelu, libref's other two kActs
* entries, are refused.
*/
template <int THR, int ACT, int PAIR>
__global__ __launch_bounds__(THR) void act_mul_kernel(
@@ -450,12 +442,12 @@ __global__ __launch_bounds__(THR) void act_mul_kernel(
}
/* ================================================================== silu_mul
* y[i] = silu(gate_up[i]) * gate_up[n + i], over ONE fused operand:
* the gate is the first half, which is the order rad-convert fuses gate and up into one weight in.
* y[i] = silu(gate_up[i]) * gate_up[n + i] over one fused operand whose first half is the gate,
* the order rad-convert fuses gate and up in.
*
* Nothing is narrowed between the activation and the product. act_mul rounds the activation to y's
* dtype first because it replaces an unfused pair that stored it; silu_mul is the fused pair, so
* its product is the f32 activation times the f32 up, rounded once by the store.
* Nothing is narrowed between the activation and the product: act_mul rounds the activation
* because its unfused pair stores it, while silu_mul is the fused op, so the f32 activation times
* the f32 up is rounded once by the store.
*/
template <int THR, int PAIR>
__global__ __launch_bounds__(THR) void silu_mul_kernel(
@@ -477,24 +469,23 @@ __global__ __launch_bounds__(THR) void silu_mul_kernel(
}
/* ================================================================== rmsnorm_quant_fp8
* The residual add, the norm, and the E4M3 quantiser of the result in one
* pass, so the normalised activation never goes back to VRAM. The arithmetic of the quantiser is
* r3d_quant_fp8.hip's, and `q8_group` before it, bit for bit: `sc = amax * (1.0f /
* 448.0f)` (the reciprocal MULTIPLIED), `inv = 1.0f / sc`, the codes `v * inv` clamped to +-448 by
* comparisons and not by fminf/fmaxf (those replace a NaN with the bound; a NaN activation encodes
* as the format's NaN), and a group whose amax is zero takes scale 1.
* The residual add, the norm and the E4M3 quantiser in one pass, so the normalised activation is
* never written back to VRAM. The quantiser arithmetic is r3d_quant_fp8.hip's and `q8_group`'s,
* bit for bit: `sc = amax * (1.0f / 448.0f)` (the reciprocal multiplied), `inv = 1.0f / sc`, codes
* `v * inv` clamped to +-448 by comparisons rather than fminf/fmaxf (which would replace a NaN with
* the bound; a NaN activation encodes as the format's NaN), and scale 1 for an all-zero group.
*
* Two properties of ref's order are load-bearing and are kept:
* the residual sum is STORED (narrowed to bf16) before the variance reads it, so the norm is over
* the bf16 sum. That is what makes this the `add` + `rmsnorm` pair and not `rmsnorm_add`, which
* normalises the unrounded sum;
* the quantiser codes the bf16 normalised value, not the f32 one -- `out_bf16`, when asked for,
* holds exactly the bytes the codes were taken over.
* Two properties of ref's order are kept:
* the residual sum is stored (narrowed to bf16) before the variance reads it, so the norm is over
* the bf16 sum. That makes this the `add` + `rmsnorm` pair, not `rmsnorm_add`, which normalises
* the unrounded sum;
* the quantiser codes the bf16 normalised value, not the f32 one, so `out_bf16` holds exactly the
* values the codes were taken over.
*
* A group is a wave at a time, four consecutive columns a lane per 128 columns, so the amax is a
* register max plus one wave butterfly (a maximum is exact in any order) and the codes leave as
* dwords. The normalised row is RECOMPUTED in the second pass from the same operands -- hot in L2,
* and it keeps the row's length out of LDS, which is what lets one workgroup take a 5120-column row.
* A wave takes one group at a time, four consecutive columns a lane per 128 columns, so the amax
* is a register max plus one wave butterfly (a maximum is exact in any order) and the codes are
* stored as dwords. The second pass recomputes the normalised row from the same operands (hot in
* L2), which keeps the row out of LDS and lets one workgroup take a 5120-column row.
*/
template <int THR, int GROUP, int WDT>
__global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
@@ -538,9 +529,8 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
for (uint32_t j = 0; j < kNChunk; ++j) {
for (uint32_t c = 0; c < 4u; ++c) {
const uint32_t i = base + j * kChunk + c;
/* The gain's dtype is the checkpoint's, read off the operand -- WDT, the plain
* rmsnorm's leg: the gains are read as stored, and the op's `dtype` names the
* ACTIVATION, never the weight. */
/* The gain is read in the checkpoint's dtype (WDT, as in plain rmsnorm); the op's
* `dtype` names the activation, never the weight. */
const float gain = (!w ? 1.0f
: WDT == R3D_DT_F32 ? ldg_f32((const float*)w + i)
: bf16_to_f32(ldg_u16_at((const uint16_t*)w, i)))
@@ -580,11 +570,10 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
* e = exp(x[i] - mx); y[i] = e; sum += e ascending
* inv = 1 / sum; y[i] = y[i] * inv read back from y
*
* The maximum is subtracted first (a 60-nat row overflows f32's exp otherwise); the denominator is
* the ascending sum, which is what `block_sum` brackets. The kernel keeps `e` in a register
* between the two passes, which is exact: ref reads it back from an f32 plane, and an f32 store
* and load round nothing. The shim therefore requires y to be f32 -- a bf16 y would round `e`
* before the multiply and ref would not, and libref itself casts f32 to f32 for this op.
* The maximum is subtracted first (a row spanning 60 nats would overflow f32's exp otherwise); the
* denominator is the ascending sum `block_sum` brackets. `e` is stored to y and read back for the
* multiply, as ref does, which is exact for an f32 plane. The shim therefore requires an f32 y: a
* bf16 y would round `e` before the multiply where ref does not.
*/
template <int THR>
__global__ __launch_bounds__(THR) void softmax_kernel(
@@ -609,14 +598,12 @@ __global__ __launch_bounds__(THR) void softmax_kernel(
}
/* ================================================================== scale / fill
* scale is y = x * s, s one scalar; fill is y = v over the whole
* plane, and both narrow once, at the store.
* scale is y = x * s with s one scalar; fill is y = v over the whole plane. Both narrow once, at
* the store.
*
* scale's scalar is the op's [1] weight plane, in device memory, and the kernel reads it: a launch
* may not copy device memory to the host, and ref reads the same single value because its operands
* are host planes. Every lane loads the same address, so it is one uniform load per block; the
* product is taken in f32 and the store narrows, which is ref's `x * s` with round_dt(f32) as the
* store.
* scale's scalar is the op's [1] weight plane in device memory, and the kernel reads it because a
* launch may not copy device memory to the host. Every lane loads the same address, one uniform
* load per block; the product is taken in f32 and narrowed by the store, as ref's `x * s`.
*/
template <int THR, int PAIR, int F32>
__global__ __launch_bounds__(THR) void scale_kernel(
@@ -661,14 +648,13 @@ __global__ __launch_bounds__(THR) void fill_kernel(void* __restrict__ y, uint32_
* i0, i1 = (i, i + rot/2) neox, (2i, 2i + 1) gptj
* h[i0] = x0*c - x1*s ; h[i1] = x0*s + x1*c each narrowed once
*
* The pair lives in one thread, so the in-place store needs no exchange. `scale` is the position
* scale and divides the position, as ref's rope_pos does (the value that multiplies the rotated
* pair is YaRN's magnitude, and the shims refuse YaRN, so the magnitude is 1).
* The pair lives in one thread, so the in-place store needs no exchange. `scale` divides the
* position, as in ref's rope_pos (the factor on the rotated pair is YaRN's magnitude, which is 1
* because the shims refuse YaRN).
*
* The frequency is recomputed per pair, not built in a plane: powf runs once per pair per head,
* off the step's critical path, and no scratch is allocated. nfreq == rot/2 always, so no pair
* sits past the ladder (ref zeroes inv[] past nfreq for the proportional ladder it supports and
* libr3d refuses).
* The frequency is recomputed per pair rather than built in a plane: one pow per pair per head,
* off the critical path, with no scratch. nfreq == rot/2 always, so no pair lies past the ladder
* (ref zeroes inv[] past nfreq only for the proportional ladder, which libr3d refuses).
*/
template <int THR, int GPTJ>
__global__ __launch_bounds__(THR) void rope_kernel(
@@ -683,10 +669,10 @@ __global__ __launch_bounds__(THR) void rope_kernel(
for (uint32_t j = threadIdx.x; j < total; j += THR) {
const uint32_t h = j / half, i = j - h * half;
/* ref's ladder: `1.0f / ref_pow(theta, (float)(2i) / den)`, and ref_pow is the double pow
* narrowed once. powf here would put the reciprocal a ULP off, and at position 262144 a
* ULP of a frequency is a hundredth of a radian of rotation -- the ladder is the one place
* in this kernel where f32 is not enough. The angle itself stays f32, as ref's is. */
/* ref's ladder: `1.0f / ref_pow(theta, (float)(2i) / den)`, with ref_pow the double pow
* narrowed once. powf would put the reciprocal a ULP off, and at position 262144 a ULP of a
* frequency is about 0.01 rad of rotation, so the ladder is computed in double. The angle
* stays f32, as in ref. */
const float inv = 1.0f / (float)std::pow((double)theta, (double)((float)(2 * i) / (float)rot));
float s, c;
sincosf(p * inv, &s, &c);
@@ -709,14 +695,13 @@ __global__ __launch_bounds__(THR) void rope_kernel(
* cache[base + (hd + d)*sd] = v[t*v_ld + j] * v_inv
*
* k and v rows are not dense: a de-interleaved projection gives [tokens, kv_heads, head_dim], and
* otherwise they are a column slice of the fused QKV plane -- 2560 wide against a 256-wide row for
* 16 heads and 2 kv heads. Deriving the stride from the shape would read every token after the
* otherwise they are a column slice of the fused QKV plane (a 256-wide slice of a 2560-wide row for
* 16 heads and 2 kv heads). Deriving the stride from the shape would read every token after the
* first from the wrong rows, so the pitch is an argument.
*
* k_inv and v_inv are the reciprocal of the reader's descales and are 1 for every cache that is
* not fp8, so the multiply below is exact -- and for the fp8 cache it is the divide ref does, in
* the one place where a reciprocal costs nothing: a value times 1/scale against ref's
* `ldt(k,..) * ks` differs by at most the rounding of the reciprocal, far under the fp8 code step.
* k_inv and v_inv are the reciprocals of the reader's descales, and 1 for every non-fp8 cache, so
* the multiply is exact there. For the fp8 cache a value times 1/scale differs from ref's result by
* at most the reciprocal's rounding, far below the fp8 code step.
*/
template <int THR>
__global__ __launch_bounds__(THR) void kv_store_kernel(
@@ -726,9 +711,8 @@ __global__ __launch_bounds__(THR) void kv_store_kernel(
int64_t sd, int64_t slot_max) {
const uint32_t t = blockIdx.x;
const int32_t s = ldg_i32(sm + t);
/* A negative slot is padding and a slot at or past the cache's own span names a block the
* cache does not have: ref refuses such a launch on the host, where it can see the block
* count, and a kernel that has read the slot can only drop it. A slot lost, not a step lost. */
/* A negative slot is padding. A slot at or past the cache's span names a block the cache does
* not have; ref refuses such a launch on the host, and the kernel drops the slot. */
if (s < 0 || (int64_t)s >= slot_max) return;
const int64_t blk = (int64_t)s / (int64_t)block_size, off = (int64_t)s % (int64_t)block_size;
@@ -753,15 +737,15 @@ __global__ __launch_bounds__(THR) void kv_store_kernel(
* id = tok[m] - vocab_offset
* x[m][i] = (0 <= id < n_vocab) ? wte[id*w_ld + i] * wscale * mult : 0
*
* A negative id, or one at or past the table, is a zero row: padding's row, and in the
* vocab-parallel split another rank's token -- summing the ranks reconstructs x. ref validates the
* ids on the host when the table is whole and the world is one rank; a kernel cannot, so the table
* bound is an argument and an out-of-range id writes zeros.
* A negative id, or one at or past the table, gives a zero row: padding, or in the vocab-parallel
* split another rank's token, so summing the ranks reconstructs x. ref validates the ids on the
* host when the table is whole and there is one rank; a kernel cannot, so the table bound is an
* argument.
*
* The table's dtype is the launcher's `dt`: bf16, f16, f32, or E4M3 codes with the table's one
* scale in `wscale` (embed_lookup_q's byte plane, whose scale is a parameter because quantising
* the table sees the whole table and the gather sees one row). `mult` is Gemma's sqrt(hidden),
* applied after the scale, so with wscale 1 the product is ref's single rounding.
* The table's dtype is the launcher's `dt`: bf16, f16, f32, or E4M3 codes with the table's single
* scale in `wscale` (embed_lookup_q's byte plane; the scale is a parameter because it is computed
* over the whole table while the gather sees one row). `mult` is Gemma's sqrt(hidden), applied
* after the scale, so with wscale 1 the product is ref's single rounding.
*/
template <int THR>
__global__ __launch_bounds__(THR) void embed_lookup_kernel(
@@ -789,18 +773,18 @@ __global__ __launch_bounds__(THR) void embed_lookup_kernel(
}
/* ================================================================== gather_rows / scatter_rows
* y[r] = x[idx[r]] and x[idx[r]] = v[r], rows of n, and a row move
* with no arithmetic: ld_elem/st_elem is the identity for bf16, f16, f32, i32 and i64, and the
* fp8 code round trip is exact (every code decodes and re-encodes to itself).
* y[r] = x[idx[r]] and x[idx[r]] = v[r] over rows of n: a row move with no arithmetic. ld_elem /
* st_elem is the identity for bf16, f16, f32, i32 and i64, and the fp8 code round trip is exact
* (every code decodes and re-encodes to itself).
*
* A negative index is padding: gather writes a zero row, scatter writes nothing -- an unsampled row
* of a step, a slot with no counterpart. An index at or past the operand's row count takes the
* same path, where ref refuses the launch (see the file header).
* A negative index is padding (an unsampled row, a slot with no counterpart): gather writes a zero
* row, scatter writes nothing. An index at or past the operand's row count takes the same path,
* where ref refuses the launch (see the file header).
*
* scatter_rows' destination is INOUT and the write is partial: unnamed rows keep their contents,
* because the destination is often a pool other sequences are in. Its indices must be distinct --
* RAD_OPD_F_IDX_UNIQUE says so in the schema -- since two rows landing on one destination have no
* defined winner in parallel, and an op whose oracle and kernel may disagree is not checkable.
* because the destination is often a pool shared with other sequences. Indices must be distinct
* (RAD_OPD_F_IDX_UNIQUE in the schema): two rows landing on one destination have no defined
* winner, so the oracle and the kernel could disagree.
*/
template <int THR>
__global__ __launch_bounds__(THR) void gather_rows_kernel(
@@ -809,10 +793,9 @@ __global__ __launch_bounds__(THR) void gather_rows_kernel(
const uint32_t m = blockIdx.x;
const int32_t r = ldg_i32(idx + m);
char* __restrict__ yr = (char*)y + (size_t)m * y_ld * (size_t)es;
/* A negative index is padding and an index at or past the source plane is one libref refuses on
* the host, where it can read the plane. Both take the zero row: reading x past its end is the
* failure this bound exists to stop. `src_rows` 0 says the caller had no plane count, which is a
* shim bug, not a bound. */
/* A negative index is padding, and an index at or past the source plane is one libref refuses
* on the host; both take the zero row, so x is never read past its end. `src_rows` 0 means the
* caller supplied no row count (a shim bug) and disables the bound. */
if (r < 0 || (src_rows > 0 && (int64_t)r >= src_rows)) {
for (uint32_t i = threadIdx.x; i < n; i += THR) st_elem(dt, yr, i, 0.0f);
return;
@@ -827,8 +810,8 @@ __global__ __launch_bounds__(THR) void scatter_rows_kernel(
uint32_t v_ld, uint32_t x_ld, int dt, int32_t es, int64_t dst_rows) {
const uint32_t m = blockIdx.x;
const int32_t r = ldg_i32(idx + m);
/* A negative index is padding, one at or past the destination plane is libref's refused step:
* dropped, so no row of x is written outside the plane. `dst_rows` 0 is unchecked. */
/* A negative index is padding, and one at or past the destination plane is a step libref
* refuses; both are dropped, so nothing is written outside the plane. `dst_rows` 0 is unchecked. */
if (r < 0 || (dst_rows > 0 && (int64_t)r >= dst_rows)) return;
const char* __restrict__ vr = (const char*)v + (size_t)m * v_ld * (size_t)es;
char* __restrict__ xr = (char*)x + (size_t)r * x_ld * (size_t)es;
@@ -945,10 +928,9 @@ extern "C" int r3d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps,
/* The fused add + norm + E4M3 quantiser. `res` is the residual plane, INOUT, and 0 when the op has
* no residual; `ob` is the optional bf16 copy of exactly what was quantised. `group` is the
* quantiser's block and must divide n: a partial group needs the zero-padded store the standalone
* quantiser writes, and this row's band is a checkpoint whose block divides its hidden width.
* Pitches are in elements of their own operand; `s_ld` in scales, so a dense scale plane is n/group.
* 0, -1, -2, -3, -4. */
* quantiser's block and must divide n: a partial group would need the standalone quantiser's
* zero-padded store. Pitches are in elements of their own operand, `s_ld` in scales (dense is
* n/group). Returns 0, -1, -2, -3 or -4. */
extern "C" int r3d_rmsnorm_quant_fp8(long x, long res, long w, long q, long s, long ob, int M,
int n, int group, float eps, float wadd, int x_ld, int res_ld,
int ob_ld, int q_ld, int s_ld, int wdt, long stream) {
@@ -1179,7 +1161,7 @@ extern "C" int r3d_act_mul_bf16(long gate, long up, long y, int M, int n, int g_
}
/* y = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate and the up share one plane, so one pitch
* carries both halves: `gu_ld` is the FUSED row's pitch (>= 2n), `y_ld` the output's. */
* carries both halves: `gu_ld` is the fused row's pitch (>= 2n), `y_ld` the output's. */
extern "C" int r3d_silu_mul_bf16(long gate_up, long y, int M, int n, int gu_ld, int y_ld,
long stream) {
if (!gate_up || !y) return -1;
@@ -1188,7 +1170,7 @@ extern "C" int r3d_silu_mul_bf16(long gate_up, long y, int M, int n, int gu_ld,
if (!y_ld) y_ld = n;
if (gu_ld < 2 * n || y_ld < n) return -3;
const int thr = row_threads(n);
const int pair = row_pair(y, n, gu_ld, y_ld); /* n even puts the up half on a 2-byte boundary */
const int pair = row_pair(y, n, gu_ld, y_ld); /* n even keeps the up half pair-aligned */
#define R3D_SM(THR, PAIR) \
R3D_KLAUNCH(R3D_KNAME(silu_mul_kernel<THR, PAIR>), dim3((uint32_t)M), dim3(THR), \
(hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)gate_up, \
@@ -1276,8 +1258,8 @@ extern "C" int r3d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_head
if (!(theta > 0.0f) || !std::isfinite(theta)) return -2;
if (!qkv_ld) qkv_ld = (n_head + 2 * n_head_kv) * head_dim;
if (qkv_ld < (n_head + 2 * n_head_kv) * head_dim) return -3;
/* rope is a per-head-of-64-pairs op: one wave covers a token's rope heads when the head is
* narrow, and 256 threads take the wide ones. */
/* One wave covers a token's rope pairs when there are at most 256 of them; 256 threads take
* more. */
const int gptj = mode == R3D_ROPE_GPTJ;
const int thr = (n_head + n_head_kv) * (rot / 2) <= 256u ? (int)kNarrow : (int)kThreads;
R3D_ROPE2(thr, M, stream, (uint16_t*)(uintptr_t)qkv, (const int32_t*)(uintptr_t)pos,
@@ -1301,9 +1283,9 @@ extern "C" int r3d_kv_store(long k, long v, long sm, long kv, int M, int head_di
if (!v_ld) v_ld = n_head_kv * head_dim;
if (k_ld < n_head_kv * head_dim || v_ld < n_head_kv * head_dim) return -3;
if (sb < 0 || sh < 0 || so < 0 || sd <= 0) return -3;
/* The cache's span, as r3d_shape_kv_store sizes it: M tokens need ceil(M/block_size) blocks,
* and the shape adds two so a step that resolves its slots before the next block is written
* has somewhere to put them. Keep the two formulas in step. */
/* Default cache span, matching r3d_shape_kv_store: M tokens need ceil(M/block_size) blocks, plus
* two so a step that resolves its slots before the next block is written has room. Keep the two
* formulas in step. */
if (slot_max <= 0)
slot_max = (long long)((M + block_size - 1) / block_size + 2) * block_size;
const int thr = row_threads(n_head_kv * head_dim);
@@ -1366,21 +1348,20 @@ extern "C" int r3d_scatter_rows(long v, long idx, long x, int M, int n, int v_ld
/* ================================================================== the plugin ABI entry points
*
* Unpacking RadArgs and deriving the pitches belongs to the kernel library (r3d_args.h). The
* kernels take raw pointers and one pitch per operand, so anything unpitched must be tight
* (spec §2.1). Before each launch a shim checks:
* The shims unpack RadArgs and derive the pitches (r3d_args.h). The kernels take raw pointers and
* one pitch per operand, so anything unpitched must be tight (spec §2.1). Before each launch a
* shim checks:
*
* * the dtype, off the operand: a row's `dtype` constraint is a necessary condition on the
* geometry, not a promise about the tensors, and an f32 operand read as bf16 is a value the
* geometry checks will not catch;
* * the dtype, off the operand: a row's `dtype` constraint is a necessary condition, not a
* promise about the tensors, and an f32 operand read as bf16 passes every geometry check;
* * the row pitch, r3d_rows_pitch(): elements, or -1 (RAD_E_STRIDE) for a strided inner axis;
* * the row count, off the operand, never the `M` parameter: `M` is ranged, so the args carry
* the band's upper bound;
* * the parameters, with libref's defaults, and the forms the kernels cannot match -- refused
* with RAD_E_UNSUPPORTED so the row's constraints can state the band and a model that needs
* the refused form is not routed here at all.
* * the parameters, with libref's defaults. Forms the kernels cannot match are refused with
* RAD_E_UNSUPPORTED, and the row's constraints keep models that need them from being routed
* here.
*
* Every refusal goes through R3D_NO(), so a run with RAD_R3D_TRACE set says which line said no.
* Every refusal goes through R3D_NO(), so with RAD_R3D_TRACE set each refusal prints its line.
*/
static inline int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
@@ -1394,8 +1375,8 @@ static inline int dt_same(const RadTensor* a, const RadTensor* b) {
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
/* A launcher's return: 0 is RAD_OK, anything else is a device failure -- the arguments were the
* shim's to check, and it checked them. */
/* A launcher's return: 0 is RAD_OK and anything else is a device failure, because the shim has
* already checked the arguments. */
static inline int r3d_launch_ok(int rc) { return rc == 0 ? RAD_OK : R3D_NO(RAD_E_DEVICE); }
/* ------------------------------------------------------------------ rmsnorm */
@@ -1407,8 +1388,7 @@ extern "C" int r3d_rad_rmsnorm(const RadArgs* a, RadStream s) {
const RadTensor* w = r3d_opt(a, RMS_W);
const RadTensor* y = r3d_opt(a, RMS_Y);
if (!x || !y) return R3D_NO(RAD_E_INVAL);
/* The row's dtype band is bf16 or f32, and the two legs are the same two passes: an f32
* checkpoint's residual stream normalizes without a store that narrows. */
/* bf16 or f32, the same two passes; the f32 leg's store narrows nothing. */
const bool f32 = r3d_is_f32(x) && r3d_is_f32(y);
if (!f32) {
R3D_NEED(dt_bf16(x));
@@ -1418,8 +1398,7 @@ extern "C" int r3d_rad_rmsnorm(const RadArgs* a, RadStream s) {
const float wadd = (float)r3d_getf(a, "wadd", 0.0);
const float mult = (float)r3d_getf(a, "mult", 1.0);
const float eps = (float)r3d_getf(a, "eps", 1e-6);
/* `wadd` without a gain is refused, as ref does: 1 + wadd of a gain that does not exist is a
* constant scale wearing a norm's name. */
/* `wadd` without a gain is refused, as ref does: it would be a constant scale, not a norm. */
if (!w && wadd != 0.0f) return R3D_NO(RAD_E_INVAL);
/* The gain's dtype comes off the gain: bf16, f32, or none. */
int wdt = R3D_DT_N;
@@ -1449,10 +1428,9 @@ extern "C" int r3d_rad_rmsnorm(const RadArgs* a, RadStream s) {
}
/* ------------------------------------------------------------------ rmsnorm_quant_fp8
* The residual add, the norm and the E4M3 quantiser in one launch: {x, residual?, w, q, scale,
* out_bf16?} with {M, n, eps, group, dtype, wadd?}, libref's. The row's reason to exist is the
* traffic: the normalised row is written once as codes and one bf16 copy, not written as bf16 and
* read back by a separate quantiser.
* The residual add, the norm and the E4M3 quantiser in one launch: libref's {x, residual?, w, q,
* scale, out_bf16?} with {M, n, eps, group, dtype, wadd?}. The normalised row is written once, as
* codes and an optional bf16 copy, instead of as bf16 read back by a separate quantiser.
*/
extern "C" int r3d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
const RadTensor* x = r3d_opt(a, 0);
@@ -1463,17 +1441,15 @@ extern "C" int r3d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
const RadTensor* ob = r3d_opt(a, 5);
if (!x || !w || !q || !sc) return R3D_NO(RAD_E_INVAL);
R3D_NEED(dt_bf16(x));
/* The gain comes in the dtype the checkpoint stores it in -- bf16 or f32, read off the operand.
* The band's `dtype` is the activation's: a checkpoint that stores its gains as f32 is read as
* it is, and a shim that dtype-checks the weight against the activation band serves one
* checkpoint and refuses the next. The kernel's WDT leg is the plain rmsnorm's. */
/* The gain is read in the dtype the checkpoint stores it in, bf16 or f32. The band's `dtype` is
* the activation's, so checking the weight against it would refuse checkpoints with f32 gains. */
int wdt = R3D_DT_N;
if (r3d_is_bf16(w)) wdt = R3D_DT_BF16;
else if (r3d_is_f32(w)) wdt = R3D_DT_F32;
else return R3D_NO(RAD_E_DTYPE);
/* `residual` is validated below, where the flag that makes it read is read. `out_bf16` is
* checked because this kernel WRITES it, so it is required of the row that asks for it (the
* reference writes it when the operand is there) and absent when the slot carries no bytes. */
/* `residual` is validated below, under the flag that makes it read. `out_bf16` is checked only
* when its slot carries bytes, since the kernel then writes it (as the reference does whenever
* the operand is present). */
if (r3d_has(ob)) R3D_NEED(dt_bf16(ob)); /* no bytes = the plan asked for no bf16 copy */
if (r3d_dt_code(q->dtype) != R3D_DT_U8) return R3D_NO(RAD_E_DTYPE); // E4M3 codes
R3D_NEED(dt_f32(sc));
@@ -1481,17 +1457,15 @@ extern "C" int r3d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) {
const long long n = r3d_geti_or(a, "n", w->rank ? r3d_dim(w, (int)w->rank - 1) : 0);
const long long group = r3d_geti_or(a, "group", 0);
if (n <= 0 || group <= 0) return R3D_NO(RAD_E_SHAPE);
/* A wave covers a group, four columns a lane per 128 columns, and a partial group is the
* standalone quantiser's zero-padded store. A checkpoint whose block divides its hidden width
* is the band this row is for. */
/* A wave covers a group, four columns a lane per 128 columns; a partial group would need the
* standalone quantiser's zero-padded store. */
if (group != 128 && group != 256 && group != 512) return R3D_NO(RAD_E_UNSUPPORTED);
if (n % group) return R3D_NO(RAD_E_UNSUPPORTED);
const float eps = (float)r3d_getf(a, "eps", 1e-6);
const float wadd = (float)r3d_getf(a, "wadd", 0.0);
/* The reference reads `residual` under `wadd` and nowhere else, and so do we -- checked here,
* after the flag, and REQUIRED by it. The engine hands the slot a tensor even when the band
* says wadd=0, in any dtype; a row that validates an operand the op will not read is a row
* that refuses a checkpoint. */
/* The reference reads `residual` only under `wadd`, and so does this check. The engine binds
* the slot even when wadd=0, in any dtype, so validating it unconditionally would refuse valid
* checkpoints. */
if (wadd != 0.0f) {
if (!r3d_has(res)) return R3D_NO(RAD_E_INVAL);
R3D_NEED(dt_bf16(res));
@@ -1531,8 +1505,8 @@ extern "C" int r3d_rad_layernorm(const RadArgs* a, RadStream s) {
R3D_NEED(dt_bf16(w));
R3D_NEED(dt_bf16(y));
if (b) {
/* libref reads a bias in any float dtype; the kernel reads bf16 (the launcher has one
* dtype for gain and bias), so an f32 bias is refused, not read wrong. */
/* libref reads a bias in any float dtype; the kernel reads bf16 only (one dtype for gain
* and bias), so an f32 bias is refused rather than misread. */
if (!r3d_is_bf16(b)) return R3D_NO(RAD_E_DTYPE);
R3D_NEED(dt_bf16(b));
}
@@ -1555,8 +1529,8 @@ extern "C" int r3d_rad_layernorm(const RadArgs* a, RadStream s) {
/* ------------------------------------------------------------------ add / mul
* The broadcast rule is libref's, read off the operand: a `b` of exactly n elements against more
* than one row rides every row, and nothing else broadcasts. `div` is `add`'s only (mul's schema
* has no div key), and a zero, NaN or infinity is refused -- the reference refuses it too. */
* than one row applies to every row, and nothing else broadcasts. Only `add` has `div` (mul's
* schema has no div key); zero, NaN and infinity are refused, as by the reference. */
static int binary_shim(const RadArgs* a, RadStream s, int mul) {
const RadTensor* A = r3d_opt(a, 0);
const RadTensor* B = r3d_opt(a, 1);
@@ -1653,8 +1627,8 @@ static int unary_shim(const RadArgs* a, RadStream s, int act) {
R3D_NEED(dt_bf16(x));
R3D_NEED(dt_bf16(y));
}
/* Only silu has an f32 leg in r3d.h (the vocoder's f32 branch is the one that asked for it);
* an f32 gelu or sigmoid is refused, not served by the bf16 kernel. */
/* Only silu has an f32 leg in r3d.h; an f32 gelu or sigmoid is refused rather than run through
* the bf16 kernel. */
if (f32 && act != R3D_ACT_SILU) return R3D_NO(RAD_E_UNSUPPORTED);
const long long n = r3d_geti_or(a, "n", r3d_numel(y));
@@ -1686,9 +1660,8 @@ extern "C" int r3d_rad_sigmoid(const RadArgs* a, RadStream s) {
}
/* ------------------------------------------------------------------ act_mul
* libref's kActs order is silu, gelu, gelu_tanh, sigmoid, quick_gelu; libr3d's rows serve silu,
* gelu and sigmoid, and the other two are refused with RAD_E_UNSUPPORTED so the row's constraints
* state which gated MLPs reach an RDNA3 card. */
* libref's kActs are silu, gelu, gelu_tanh, sigmoid and quick_gelu. libr3d serves silu, gelu and
* sigmoid and refuses the other two with RAD_E_UNSUPPORTED. */
extern "C" int r3d_rad_act_mul(const RadArgs* a, RadStream s) {
const RadTensor* A = r3d_opt(a, 0);
const RadTensor* B = r3d_opt(a, 1);
@@ -1725,9 +1698,9 @@ extern "C" int r3d_rad_act_mul(const RadArgs* a, RadStream s) {
}
/* ------------------------------------------------------------------ silu_mul
* y[i] = silu(gate_up[i]) * gate_up[n + i]: libref's {gate_up, y} operands and its {M, n, dtype}
* schema. A distinct op from act_mul -- the llama MLP emits it, and act_mul takes two operands --
* so a model asking for silu_mul is not served by the act_mul_silu row.
* y[i] = silu(gate_up[i]) * gate_up[n + i]: libref's {gate_up, y} operands and {M, n, dtype}
* schema. The llama MLP emits it; it is a distinct op from act_mul (which takes two operands), so
* the act_mul_silu row does not serve it.
*/
extern "C" int r3d_rad_silu_mul(const RadArgs* a, RadStream s) {
const RadTensor* gu = r3d_opt(a, 0);
@@ -1740,7 +1713,7 @@ extern "C" int r3d_rad_silu_mul(const RadArgs* a, RadStream s) {
if (n <= 0) return R3D_NO(RAD_E_SHAPE);
long long M = 0, Mgu = 0;
const long long y_ld = r3d_rows_pitch(y, n, &M);
const long long gu_ld = r3d_rows_pitch(gu, 2 * n, &Mgu); /* the FUSED row is 2n wide */
const long long gu_ld = r3d_rows_pitch(gu, 2 * n, &Mgu); /* the fused row is 2n wide */
if (y_ld < 0 || gu_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (!row_count_ok(M) || Mgu < M) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(gu) < M * 2 * n) return R3D_NO(RAD_E_SHAPE); // ref's own bound on the plane
@@ -1750,9 +1723,9 @@ extern "C" int r3d_rad_silu_mul(const RadArgs* a, RadStream s) {
}
/* ------------------------------------------------------------------ softmax
* f32, as ref spells it: the reference casts to f32, computes, and casts back, and the intermediate
* `e` is read back from an f32 plane. A bf16 y would round that intermediate and the kernel cannot
* match ref with ref's own arithmetic, so it is refused rather than served at a tolerance. */
* f32 only: the reference casts to f32, computes and casts back, reading the intermediate `e` back
* from an f32 plane. A bf16 y would round that intermediate, so it is refused rather than served at
* a tolerance. */
extern "C" int r3d_rad_softmax(const RadArgs* a, RadStream s) {
const RadTensor* x = r3d_opt(a, 0);
const RadTensor* y = r3d_opt(a, 1);
@@ -1774,8 +1747,8 @@ extern "C" int r3d_rad_softmax(const RadArgs* a, RadStream s) {
/* ------------------------------------------------------------------ scale
* y = x * s. `s` is the op's [1] weight plane: the shim checks its dtype and that it has an
* element, and the kernel reads the value. The launcher cannot take the number by value, because
* reading a device plane on the host is a copy and a sync, and a row is neither. */
* element, and the kernel reads the value, because reading a device plane on the host needs a copy
* and a sync. */
extern "C" int r3d_rad_scale(const RadArgs* a, RadStream s) {
const RadTensor* x = r3d_opt(a, 0);
const RadTensor* sc = r3d_opt(a, 1);
@@ -1828,14 +1801,12 @@ extern "C" int r3d_rad_fill(const RadArgs* a, RadStream s) {
}
/* ------------------------------------------------------------------ rope
* In place, so operand 0 is the row's INOUT: the shim checks it is writable (the role says it is;
* a null data is the row's bug, and is RAD_E_INVAL) and that head_dim and rot are even.
* In place, so operand 0 is INOUT (a null data is RAD_E_INVAL); head_dim and rot must be even.
*
* What the shim refuses, and why: the multi-component modes (mrope, imrope, axial) need a
* [C, M] position plane and per-section ladders; the proportional ladder (`ladder=head`) pairs
* across the whole head; YaRN and Llama 3 rescale the ladder. Each changes the angles, not the
* arithmetic, and the kernel has the plain rotary -- so each is RAD_E_UNSUPPORTED, the row's
* constraints say so, and a model that needs one is not routed to this card's row.
* Refused with RAD_E_UNSUPPORTED: the multi-component modes (mrope, imrope, axial), which need a
* [C, M] position plane and per-section ladders; the proportional ladder (`ladder=head`), which
* pairs across the whole head; and YaRN and Llama 3, which rescale the ladder. Each changes the
* angles, not the arithmetic, and the kernel implements only the plain rotary.
*/
extern "C" int r3d_rad_rope(const RadArgs* a, RadStream s) {
const RadTensor* qkv = r3d_opt(a, 0);
@@ -1888,14 +1859,13 @@ extern "C" int r3d_rad_rope(const RadArgs* a, RadStream s) {
}
/* ------------------------------------------------------------------ kv_store
* The cache is INOUT: only the mapped slots are touched and every other slot must survive. Its
* strides are read off the operand (the reference's kv_view): a rank-4 cache carries them; the
* flat [blocks, kv_heads, block_size, 2*head_dim] form derives them.
* The cache is INOUT: only the mapped slots are written. Its strides are read off the operand (the
* reference's kv_view): a rank-4 cache carries them, and the flat
* [blocks, kv_heads, block_size, 2*head_dim] form derives them.
*
* ref also refuses a slot naming a block past the cache (RAD_E_SHAPE), which the shim cannot do
* before the launch: the slots are in device memory. The bound travels as `slot_max`, the slot span
* of the cache the shapes hook sizes, and the kernel drops a slot at or past it -- a slot lost,
* not a step lost.
* ref also refuses a slot naming a block past the cache (RAD_E_SHAPE), which the shim cannot check
* before the launch because the slots are in device memory. The bound travels as `slot_max` and
* the kernel drops a slot at or past it.
*/
extern "C" int r3d_rad_kv_store(const RadArgs* a, RadStream s) {
const RadTensor* k = r3d_opt(a, 0);
@@ -1942,12 +1912,11 @@ extern "C" int r3d_rad_kv_store(const RadArgs* a, RadStream s) {
if (T <= 0 || Mk < T || Mv < T) return R3D_NO(RAD_E_SHAPE);
if (!row_count_ok(T)) return R3D_NO(RAD_E_SHAPE);
/* The cache's span, in slots: the pool's own plane, NOT this step's. A step that adopts a
* prefix writes its tail into the blocks the table names, and those sit at the allocator's
* GLOBAL indices -- a 4-token tail placed at block 3 is slots 48..51, past any bound built
* from T. A bound built from the step's own span is no bound for the tail's slots, so the
* pool's plane is the true bound: a slot at or past it names memory the cache does not have,
* and the kernel drops it there. */
/* The cache's span in slots comes from the pool's own plane, not from this step. A step that
* adopts a prefix writes its tail into the blocks the table names, at the allocator's global
* indices (a 4-token tail in block 3 starts at slot 48), which a bound derived from T would
* reject. A slot at or past the plane's span names memory the cache does not have and is
* dropped by the kernel. */
long long slot_max;
if (kv->rank == 4) {
slot_max = (long long)r3d_dim(kv, 0) * block_size;
@@ -1957,17 +1926,19 @@ extern "C" int r3d_rad_kv_store(const RadArgs* a, RadStream s) {
slot_max = el / (2 * head_dim);
}
if (std::getenv("RAD_R3D_TRACE")) /* the write side, spoken: where this step's KV lands. A
* tail that names slots of an adopted block writes over the
* shared prefix, and this line is the one that says so. */
/* Diagnostic, when RAD_R3D_TRACE is set: synchronises the device and prints
* "[r3d] kvstore: T=<tokens> kvbase=<cache ptr> slots=<first 8 slot ids>", showing where this
* step's KV lands (a tail naming slots of an adopted block overwrites the shared prefix). */
if (r3d_trace_on())
{
(void)hipDeviceSynchronize();
int slots[8];
if (hipMemcpy(slots, (const void*)(uintptr_t)r3d_addr(sm), 8 * sizeof(int),
const int n_print = T < 8 ? (int)T : 8;
if (hipMemcpy(slots, (const void*)(uintptr_t)r3d_addr(sm), (size_t)n_print * sizeof(int),
hipMemcpyDeviceToHost) == hipSuccess) {
std::fprintf(stderr, "[r3d] kvstore: T=%lld kvbase=%p slots=", (long long)T,
(const void*)(uintptr_t)r3d_addr(kv));
for (int c = 0; c < 8 && (long long)c < T; ++c)
for (int c = 0; c < n_print; ++c)
std::fprintf(stderr, "%s%d", c ? " " : "", slots[c]);
std::fprintf(stderr, "\n");
}
@@ -1980,10 +1951,10 @@ extern "C" int r3d_rad_kv_store(const RadArgs* a, RadStream s) {
}
/* ------------------------------------------------------------------ embed_lookup
* tokens are i32 (the engine's token ids), the table's dtype is the launcher's `dt`, and x is
* bf16 -- a table in any other float dtype, or an E4M3 table whose scale arrives as a tensor
* (embed_lookup_q's operand), is refused: one scale per gathered row is a device read the step
* path cannot do, which is why the op's schema carries `wscale` as a parameter. */
* tokens are i32 (the engine's token ids), the table's dtype is the launcher's `dt`, and x is bf16.
* A table in any other float dtype is refused, as is an E4M3 table whose scale arrives as a tensor
* (embed_lookup_q's operand): a per-row scale read is a device read the step path cannot do, which
* is why the op's schema carries `wscale` as a parameter. */
extern "C" int r3d_rad_embed_lookup(const RadArgs* a, RadStream s) {
const RadTensor* tok = r3d_opt(a, 0);
const RadTensor* wte = r3d_opt(a, 1);
+67 -71
View File
@@ -2,8 +2,8 @@
*
* The row table (r3d_rows.cpp) and the operand descriptions (r3d_shapes.cpp) are pure host C++ and
* include only this file and the ABI; the launch shims include r3d.h and so <hip/hip_runtime.h>.
* The split lets the constraint table compile and be checked without ROCm, and is why every shim is
* declared here rather than beside its definition.
* The split lets the constraint table compile and be checked without ROCm, which is why every shim
* is declared here rather than beside its definition.
*
* Nothing in this header may include r3d.h.
*/
@@ -15,56 +15,53 @@
/* ================================================================== the priority ladder
*
* The selector ranks candidate rows by an integer priority (spec §2.1); where two rows of one op
* can match a geometry, it decides which serves. Each group states the reason for its order.
* Values are spaced by ten so a row can be slipped between two without renumbering.
* match a geometry, it decides which serves. Each group states the reason for its order. Values are
* spaced by ten so a row can be inserted between two without renumbering.
*
* libr3d ships one row per (op, dtype) pair far more often than libr4d does: the matrix work runs
* on the dot2 path, whose lane map takes a dtype as a template argument, so the kernel that serves
* bf16 serves f16 as is, and there is nothing to specialise a second row for. Where two rows of
* one op do exist, the reason is the geometry, and it is written next to the pair.
* Most ops have a single row: the matrix work runs on the dot2 path, whose lane map takes the dtype
* as a template argument, so the kernel that serves bf16 also serves f16. Where one op has two
* rows, the reason is geometry and is stated next to the pair.
*/
enum {
/* The common case: this op, these dtypes, one row. Nothing competes with it. */
/* One row for the op; nothing competes with it. */
R3D_PRIO_ONLY = 50,
/* `attn_paged` is banded on q_len, and the decode row's bound (q_len <= 16) is a bucket
* boundary, not a partition: a speculative verify at 8 query tokens matches the prefill row
* too, and the decode kernel -- split-KV, one head group a workgroup, no query tile -- is the
* faster one there. Decode therefore outranks prefill, as it does in libr4d. */
/* `attn_paged` is banded on q_len, and the decode row's bound (q_len <= 16) overlaps the
* prefill row: a speculative verify at 8 query tokens matches both, and the decode kernel
* (split-KV, one head group per workgroup, no query tile) is faster there. Decode outranks
* prefill, as in libr4d. */
R3D_PRIO_ATTN_DECODE = 70,
R3D_PRIO_ATTN_PREFILL = 60,
/* The skinny bf16 GEMM's band is M <= 16 and the tiled one's starts at M >= 16, so the two
* meet at exactly 16 rows and the skinny kernel wins there (it keeps the whole weight stream
* in flight with one wave a row and has no LDS staging to pay for). The overlap is deliberate:
* a caller that wants the tiled kernel at 16 rows asks with M=17, the same convention libr4d
* uses at its own m64/tiled boundary. */
/* The skinny bf16 GEMM's band is M <= 16 and the tiled one's starts at M >= 16. At 16 rows the
* skinny kernel wins: it keeps the whole weight stream in flight with one wave per row and has
* no LDS staging. The overlap is deliberate; a caller that wants the tiled kernel at 16 rows
* asks with M=17, as at libr4d's m64/tiled boundary. */
R3D_PRIO_GEMM_M16 = 60,
R3D_PRIO_GEMM_TILED = 40,
/* The vocab is a GEMM whose N is the vocabulary: one row, M <= 16, split-K across the whole
* card. The tiled GEMM has no row for these N, so this priority only decides against a future
* tiled vocab row. */
/* The vocab GEMM (N = the vocabulary): one row, M <= 16, split-K across the whole card. The
* tiled GEMM has no row for these N, so this priority only matters against a future tiled
* vocab row. */
R3D_PRIO_VOCAB_M1 = 60,
/* An fp8 weight row and an int8 weight row never compete: no dtype string reaches both, and a
* container's encoding picks which is legal. */
/* An fp8 weight row and an int8 weight row never compete: no dtype string reaches both, and
* the container's encoding picks which is legal. */
R3D_PRIO_GEMM_FP8 = 60,
/* The sampler stages are one row each, on one dtype (f32 logits), so there is nothing to rank.
* The name is here so a second row for a stage -- an i8 logits form, say -- has a ladder to
* join. */
/* One row per sampler stage, on f32 logits, so there is nothing to rank yet. A second row for
* a stage (an i8 logits form, say) would rank against this value. */
R3D_PRIO_SAMPLE = 50
};
/* ================================================================== the dtype codes a C
* launcher takes
*
* The launchers in r3d.h take a dtype as an int, because a `__global__`'s dtype has to be a runtime
* value for the ops that are one kernel over several (cast, fill, dequant) and a compile-time one
* everywhere else. These are the codes; they are libr3d's own, not rad_types.h's RAD_DT_* (a
* launcher's argument list is a private contract between a shim and its kernel, and the kernel
* switch reads better over a dense 0..n than over the ABI's sparse enum). Every shim translates. */
* The launchers in r3d.h take a dtype as an int: it is a runtime value for the ops that are one
* kernel over several dtypes (cast, fill, dequant) and a template argument everywhere else. The
* codes are libr3d's own, not rad_types.h's RAD_DT_*, because the launcher signature is private to
* a shim and its kernel and a dense 0..n switches more cleanly than the ABI's sparse enum. Every
* shim translates. */
enum {
R3D_DT_BF16 = 0,
R3D_DT_F16 = 1,
@@ -103,16 +100,16 @@ static inline int r3d_dt_size(int code) {
/* The activation an `act` parameter names, as the kernels' template argument. */
enum { R3D_ACT_SILU = 0, R3D_ACT_SIGMOID = 1, R3D_ACT_GELU = 2 };
/* rope's `mode`, same numbering as libref's kModes. libr3d's kernel implements neox and gptj; the
* rows' constraints say so, so a model that needs mrope is not routed here. */
/* rope's `mode`, numbered as libref's kModes. Only neox and gptj are implemented, and the rows'
* constraints say so, so a model that needs mrope is not routed here. */
enum { R3D_ROPE_NEOX = 0, R3D_ROPE_GPTJ = 1 };
/* ================================================================== the row table's entry points
*
* Declared here so r3d_rows.cpp, which is host code built without ROCm, can name them; each is
* defined beside its kernel, in the unit named below, and is documented there. A shim is a
* `RadLaunchFn`: operands read with r3d_args.h, dtype from the tensor, row count from the operand.
* A shape hook is a `RadShapeFn`: the extent and content domain of one operand (r3d_shapes.cpp).
* Declared here so r3d_rows.cpp, host code built without ROCm, can name them. Each is defined and
* documented beside its kernel, in the unit named below. A shim is a `RadLaunchFn`: operands read
* with r3d_args.h, dtype from the tensor, row count from the operand. A shape hook is a
* `RadShapeFn`: the extent and content domain of one operand (r3d_shapes.cpp).
*/
extern "C" {
@@ -145,7 +142,6 @@ int r3d_rad_dequant (const RadArgs* a, RadStream s);
/* --- r3d_gemm_bf16_nt_m16.hip, r3d_gemm_fp8a16_nt_m1.hip --- */
int r3d_rad_gemm_nt_bf16_m16 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_fp8 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_i8 (const RadArgs* a, RadStream s);
/* --- r3d_shapes.cpp --- */
int r3d_shape_rmsnorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
@@ -174,15 +170,15 @@ int r3d_shape_gemm_nt (const RadParam* p, int n_p, int operand, RadOpdDe
int r3d_shape_gemm_nt_q (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
/* --- r3d_attn_paged_h128.hip, r3d_vocab_bf16.hip, r3d_sample_f32.hip --- */
/* --- r3d_shapes.cpp: the fused-op, attention and sampler shape hooks --- */
extern "C" int r3d_shape_silu_mul (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_attn_paged (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_gemm_nt_q_gated (const RadParam*, int, int, RadOpdDesc*);
/* The vocab projection at w2a8, decode. The layout hook is this library's scoped exception to
* "no layout hooks" (the other two are the fp8 weight's and the logits head's, below): it repacks
* nothing, it presents the container's `scale` and `zero` planes as the single joined `b_scale`
* operand the way rad_planes stores them, transcribed from
* ref_layout_gemm_q. Without it the plan has a placement with no reader. */
/* r3d_gemm_nt_q_w2a8.hip: the w2a8 vocab projection's layout hook, one of the library's three
* (with the fp8 weight's and the logits head's, below). It repacks nothing: it presents the
* container's `scale` and `zero` planes as the single joined `b_scale` operand the way rad_planes
* stores them, transcribed from ref_layout_gemm_q. Without it the plan would have a placement with
* no reader. */
extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadEncoding*,
const int* sel, const RadTensor* planes, int n_planes,
RadLayout*);
@@ -202,8 +198,9 @@ extern "C" int r3d_shape_sample_ngram_ban (const RadParam*, int, int, RadOpdDes
extern "C" int r3d_shape_sample_mask (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_logprobs (const RadParam*, int, int, RadOpdDesc*);
/* --- r3d_sample_f32.hip: the draw spine (row_topk, argmax, temp, topk, pick, the four narrowings)
and r3d_model_bf16.hip's pre-filters (penalties, dry, ngram_ban, mask, logprobs) --- */
/* --- r3d_gemm_nt_q_w2a8.hip, r3d_gemm_fp8a8_gated.hip, r3d_dflash_f32.hip; r3d_sample_f32.hip's
draw spine (row_topk, argmax, temp, topk, pick, the four narrowings) and
r3d_sample_pre_f32.hip's pre-filters (penalties, dry, ngram_ban, mask, logprobs) --- */
int r3d_rad_gemm_nt_q_w2a8 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_gated (const RadArgs* a, RadStream s);
int r3d_rad_dflash_select (const RadArgs* a, RadStream s);
@@ -222,44 +219,39 @@ int r3d_rad_sample_ngram_ban (const RadArgs* a, RadStream s);
int r3d_rad_sample_mask (const RadArgs* a, RadStream s);
int r3d_rad_sample_logprobs (const RadArgs* a, RadStream s);
/* --- r3d_model_bf16.hip: the fused MLP activation and the fused norm-quantiser --- */
/* The paged attention's two entry points, banded on q_len: the decode kernel is split-KV over the
* cache with one head group a workgroup, the prefill kernel stages a 16-token query tile. */
/* --- r3d_attn_paged_h128.hip: the paged attention, banded on q_len. The decode kernel is
* split-KV over the cache with one head group per workgroup; the prefill kernel stages a 16-token
* query tile. */
int r3d_rad_attn_decode_h128 (const RadArgs* a, RadStream s);
int r3d_rad_attn_prefill_h128 (const RadArgs* a, RadStream s);
/* --- r3d_vocab_bf16.hip: the vocabulary projection, both heights. The shape hook is a
* transcription of ref_logits_gemm_shape -- three plain tensors, nothing joined -- so the band the
* engine declares is the band kbench fills, which is the opposite of the w2a8 row's null hook: there
* the describable byte count is the trap, here it is the point. */
/* --- r3d_gemm_fp8a8_tiled.hip: the quantised GEMM above the decode heights, and the reader for
* the container's fp8 weight: codes and per-128x128 scale as two planes behind `b_scale`. The
* reference's own gemm_nt_q hook answers nothing for this dtype -- ref_layout_gemm_q reads zp_grid,
* and zp_grid has no fp8a8 entry -- which is why the row carries its own. */
* the container's fp8 weight: codes and per-128x128 scale as two planes behind `b_scale`. The row
* carries its own layout hook because the reference's gemm_nt_q hook answers nothing for this
* dtype (ref_layout_gemm_q reads zp_grid, which has no fp8a8 entry). */
int r3d_rad_gemm_nt_q_fp8_tiled (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_w2a8_tiled (const RadArgs* a, RadStream s);
extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam*, int, int, const RadEncoding*,
const int*, const RadTensor*, int, RadLayout*);
/* --- r3d_gemm_mxfp4a8.hip: the OCP-MXFP4 weight against the fp8 activation, both heights. The
* weight is two plain u8 planes -- e2m1 codes [N, K/2] and the e8m0 scale [N, K/32] -- so the row
* reads them in place and carries no layout hook; the shape hook is its own because the weight's
* two planes are not the fp8 grid's E4M3 codes and block scale. */
* weight is two plain u8 planes (e2m1 codes [N, K/2], e8m0 scale [N, K/32]) read in place, so the
* row has no layout hook. Its shape hook is separate because these planes are not the fp8 grid's
* E4M3 codes and block scale. */
int r3d_rad_gemm_nt_q_mxfp4a8_m16 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s);
/* --- r3d_gemm_inta8.hip: the symmetric int4 and int8 weight grids at decode heights. The weight
* is signed codes (I4, two a byte, or I8, one a byte) against a plain f16 scale per (row, 128 of
* K) -- no zero point and no a_sum, so both planes are read in place and the rows carry no layout
* hook. */
* is signed codes (I4 two per byte, or I8) with a plain f16 scale per (row, 128 of K). No zero
* point and no a_sum, so both planes are read in place and the rows have no layout hook. */
int r3d_rad_gemm_nt_q_w4a8_m16(const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_w8a8_m16(const RadArgs* a, RadStream s);
int r3d_shape_gemm_nt_q_w4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gemm_nt_q_w8a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
/* The three writers that go with the three plane hooks, one per row, each delegating to
* rad_planes_relayout: the loader converts a quantised weight into the joined operand the plan names
* at load, and only the row that reads it can say how. See abi/rad_abi.h. */
/* The relayout writers for the three layout hooks, each delegating to rad_planes_relayout. The
* loader converts a quantised weight into the joined operand the plan names, and only the row that
* reads it can say how. See abi/rad_abi.h. */
extern "C" int r3d_relayout_logits_head(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
extern "C" int r3d_relayout_gemm_q_fp8_weight(const RadParam*, int, int, const RadEncoding*,
@@ -267,18 +259,22 @@ extern "C" int r3d_relayout_gemm_q_fp8_weight(const RadParam*, int, int, const R
extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadEncoding*,
const int*, const RadTensor*, int, void*, int64_t);
/* --- r3d_vocab_bf16.hip: the vocabulary projection, both heights. Its shape hook
* (r3d_shapes.cpp) transcribes ref_logits_gemm_shape, three plain tensors with nothing joined, so
* the band the engine declares is the band kbench fills. */
int r3d_rad_logits_gemm_bf16 (const RadArgs* a, RadStream s);
/* The head's reader: `output.weight` at a llama_dense_fp8 checkpoint is E4M3 codes and a bf16 scale
* per 128x128 block, stored as two container planes behind the one `lm_head` operand, and the mapped
* tier will not place a weight a loaded library cannot read in place. Transcribed from
* ref_layout_head (libref's own logits row carries that hook), with the statics it uses inlined
* beside it. It moves no byte: a round-trip through its relayout writer (above) reproduces the
* planes byte for byte, and that writer exists for the round-trip, not for a move. */
/* The head's layout hook: `output.weight` at a llama_dense_fp8 checkpoint is E4M3 codes and a bf16
* scale per 128x128 block, stored as two container planes behind the one `lm_head` operand, and the
* mapped tier does not place a weight a loaded library cannot read in place. Transcribed from
* ref_layout_head, with the statics it uses inlined. It moves no bytes: a round-trip through its
* relayout writer (above) reproduces the planes exactly, and the writer exists for that
* round-trip. */
extern "C" int r3d_layout_logits_head(const RadParam*, int, int, const RadEncoding*,
const int*, const RadTensor*, int, RadLayout*);
int r3d_rad_gemm_nt_bf16_tiled (const RadArgs* a, RadStream s);
int r3d_shape_logits_gemm_bf16 (const RadParam*, int, int, RadOpdDesc*);
/* --- r3d_model_bf16.hip: the fused MLP activation and the fused norm-quantiser --- */
int r3d_rad_silu_mul (const RadArgs* a, RadStream s);
int r3d_rad_rmsnorm_quant_fp8 (const RadArgs* a, RadStream s);
int r3d_shape_rmsnorm_quant_fp8 (const RadParam*, int, int, RadOpdDesc*);
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more