diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c422bb3..c0a782b5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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() diff --git a/NOTICE b/NOTICE index b30cb6fa..d931c1d4 100644 --- a/NOTICE +++ b/NOTICE @@ -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. diff --git a/README.md b/README.md index f3935d7d..6ced154a 100644 --- a/README.md +++ b/README.md @@ -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` | diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 9ac5d26c..eee2f213 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -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); diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 59dd2ed3..fb4bc5bf 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -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: diff --git a/arch/common/rad_block_dflash2.h b/arch/common/rad_block_dflash2.h index c745c216..b9b9cf9c 100644 --- a/arch/common/rad_block_dflash2.h +++ b/arch/common/rad_block_dflash2.h @@ -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(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), diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h index 8c5df1c5..614db0ef 100644 --- a/arch/common/rad_block_moe_fp8.h +++ b/arch/common/rad_block_moe_fp8.h @@ -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")), diff --git a/arch/common/rad_block_ple.h b/arch/common/rad_block_ple.h index 3986fb24..b8d19a87 100644 --- a/arch/common/rad_block_ple.h +++ b/arch/common/rad_block_ple.h @@ -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); diff --git a/arch/common/rad_gemma4_dflash.h b/arch/common/rad_gemma4_dflash.h index 3a1fee71..94f8a382 100644 --- a/arch/common/rad_gemma4_dflash.h +++ b/arch/common/rad_gemma4_dflash.h @@ -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; } diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index 37d6975a..2f27687a 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -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), diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 43fd0f71..d1245fd1 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -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( + g.max_tok, std::max({ (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) { diff --git a/arch/nomicbert/nomicbert.cpp b/arch/nomicbert/nomicbert.cpp index 66c3b612..fc329cfd 100644 --- a/arch/nomicbert/nomicbert.cpp +++ b/arch/nomicbert/nomicbert.cpp @@ -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 @@ -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)); diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index 39a9bff5..d1957bac 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -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, diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 53de59f2..7bc985a3 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -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); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 63dfb561..67724102 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -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) { diff --git a/core/build/startup.cpp b/core/build/startup.cpp index a2e3468c..ea752fdd 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -175,8 +175,12 @@ int rad_tools_load_plugins(const std::string& home, const std::vectorarch_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 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::vectorarch_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()); } diff --git a/core/build/startup.h b/core/build/startup.h index a8333ead..2370d170 100644 --- a/core/build/startup.h +++ b/core/build/startup.h @@ -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& hierarchy, const std::string& arch_id, diff --git a/core/config.cpp b/core/config.cpp index 89d1cd81..0db587fc 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -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; } }, diff --git a/core/device/aql.cpp b/core/device/aql.cpp index 68759da8..9531d98b 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -3644,6 +3644,43 @@ void* pin_whole(int64_t bytes, const std::vector& 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& 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 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 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 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; diff --git a/core/device/device.h b/core/device/device.h index 4898f2ac..d6ab2631 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -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); }; diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index 8855e3f9..e54e4f7a 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -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); } diff --git a/core/engine.cpp b/core/engine.cpp index 35428364..75443104 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -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(); } }; diff --git a/core/engine.h b/core/engine.h index 29cee8da..b10743c4 100644 --- a/core/engine.h +++ b/core/engine.h @@ -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 table_copies_; std::vector 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 table_shares_; std::vector> 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 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). */ diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 913c1890..3ecdba82 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -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(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(base), why); + if (rc == RAD_OK) rc = table_share_mark_ready(&s, n, id, why); + } else { + rc = table_copy_check(src, n, static_cast(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(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& 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(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 with = facts; int64_t fixed = 0; @@ -640,7 +721,7 @@ int Engine::resolve_table_placement(const std::vector& 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(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(); + 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" diff --git a/core/engine_draft.cpp b/core/engine_draft.cpp index 1888fa58..9a2e1aa5 100644 --- a/core/engine_draft.cpp +++ b/core/engine_draft.cpp @@ -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(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(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(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)); } diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 9c0ae3ad..66739bfc 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -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_.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*[*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) { diff --git a/core/format/ggml_planes.h b/core/format/ggml_planes.h index 78414619..3261e926 100644 --- a/core/format/ggml_planes.h +++ b/core/format/ggml_planes.h @@ -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; diff --git a/core/format/table_copy.cpp b/core/format/table_copy.cpp index a549f642..727fbde1 100644 --- a/core/format/table_copy.cpp +++ b/core/format/table_copy.cpp @@ -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(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(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(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(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, diff --git a/core/format/table_copy.h b/core/format/table_copy.h index 4b6e968c..ba490a04 100644 --- a/core/format/table_copy.h +++ b/core/format/table_copy.h @@ -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); diff --git a/core/format/table_share.cpp b/core/format/table_share.cpp new file mode 100644 index 00000000..fcba11a9 --- /dev/null +++ b/core/format/table_share.cpp @@ -0,0 +1,261 @@ +/* table_share.cpp -- see table_share.h. */ +#include "table_share.h" + +#include "../rad_internal.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +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(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 */ diff --git a/core/format/table_share.h b/core/format/table_share.h new file mode 100644 index 00000000..5ebfff7a --- /dev/null +++ b/core/format/table_share.h @@ -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-.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 `.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 +#include + +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-.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-.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 */ diff --git a/core/kvstream/mirror.cpp b/core/kvstream/mirror.cpp index c3b5e21e..e012fe5f 100644 --- a/core/kvstream/mirror.cpp +++ b/core/kvstream/mirror.cpp @@ -186,8 +186,8 @@ void KVStreamStore::release(MemAllocator& host_alloc) { KVStreamStats KVStreamStore::stats(const std::vector& 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; diff --git a/core/kvstream/mirror.h b/core/kvstream/mirror.h index 23773fca..02f33c6c 100644 --- a/core/kvstream/mirror.h +++ b/core/kvstream/mirror.h @@ -9,6 +9,7 @@ #pragma once #include "mem/pools.h" +#include #include #include @@ -85,17 +86,19 @@ public: KVStreamStats stats(const std::vector& 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 resident_tokens_; /* by group handle: its pool's depth in tokens */ std::vector maps_; /* set_map(), by group handle */ - uint64_t misses_ = 0; /* note_traffic() */ - uint64_t bytes_in_ = 0; + std::atomic misses_{0}; /* note_traffic() */ + std::atomic bytes_in_{0}; }; } /* namespace rad */ diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index 506e44bd..19346e7e 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -272,11 +272,15 @@ int KVManager::plan_groups(const std::vector& 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; } diff --git a/core/mem/kv.h b/core/mem/kv.h index 2f9128d3..40db3715 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -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& 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 */ diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index b103ceb6..f2810f10 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -77,7 +77,13 @@ void GeometricBackoff::select(const std::vector& pos, std::vector& pos, std::vector* 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& pos, std::vector* 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 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_; } diff --git a/core/mem/prefix.h b/core/mem/prefix.h index a8ab500e..a2c35310 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -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& positions, std::vector* 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 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 blocks; - std::vector tokens; /* the block's token ids, compared on hit */ + std::vector 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 policy_; + int64_t drafter_floor_ = 0; mutable Stats stats_; std::string report_; }; diff --git a/core/mm/media.h b/core/mm/media.h index f887b79e..2a3adf06 100644 --- a/core/mm/media.h +++ b/core/mm/media.h @@ -36,9 +36,9 @@ struct FrameRGBA { /* Whether this build has a decoder. */ bool decoder_available(); -/* "libavformat " 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 " 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 diff --git a/core/place/heat.h b/core/place/heat.h index 16c95adf..df044000 100644 --- a/core/place/heat.h +++ b/core/place/heat.h @@ -210,8 +210,8 @@ private: std::vector tier_; std::vector busy_; std::vector 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 pinned_; std::vector layer_of_; /* Bit 0: promoted before. Bit 1: demoted before. Feeds the readmit counters. */ diff --git a/core/place/planner.cpp b/core/place/planner.cpp index 60ec2f09..2ea42205 100644 --- a/core/place/planner.cpp +++ b/core/place/planner.cpp @@ -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 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); diff --git a/core/place/planner.h b/core/place/planner.h index ffc371ca..b6faf117 100644 --- a/core/place/planner.h +++ b/core/place/planner.h @@ -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; diff --git a/core/rad_core.h b/core/rad_core.h index 0b74f5bc..ed994742 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -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-.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. */ diff --git a/core/sample/accept.h b/core/sample/accept.h index 9272a6e2..58a1bfdf 100644 --- a/core/sample/accept.h +++ b/core/sample/accept.h @@ -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 diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp index 6ed16c0d..013a586e 100644 --- a/core/sample/sampler.cpp +++ b/core/sample/sampler.cpp @@ -3,6 +3,7 @@ */ #include "sampler.h" #include "gbnf.h" +#include "../sched/draft.h" /* RAD_SCHED_MAX_SPEC */ #include #include @@ -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& 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& 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& 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& 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(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& 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& 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& 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); diff --git a/core/sample/sampler.h b/core/sample/sampler.h index 5eb8e254..73615bcf 100644 --- a/core/sample/sampler.h +++ b/core/sample/sampler.h @@ -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). */ diff --git a/core/sched/advance.cpp b/core/sched/advance.cpp index ad87fa33..0f2bfe29 100644 --- a/core/sched/advance.cpp +++ b/core/sched/advance.cpp @@ -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 */ diff --git a/core/sched/advance.h b/core/sched/advance.h index f0cfcc67..dd221b9d 100644 --- a/core/sched/advance.h +++ b/core/sched/advance.h @@ -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); diff --git a/core/sched/advance.hip b/core/sched/advance.hip index 0d35d4ad..828c149c 100644 --- a/core/sched/advance.hip +++ b/core/sched/advance.hip @@ -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); diff --git a/core/sched/advance_impl.h b/core/sched/advance_impl.h index a173f7d0..55f84eb8 100644 --- a/core/sched/advance_impl.h +++ b/core/sched/advance_impl.h @@ -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(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(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( + lay + (((int64_t)(ss / bs) * P.n_head + h) * bs + ss % bs) * P.row_bytes); + uint32_t* to = reinterpret_cast( + 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 */ diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index bd2907bc..05220592 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -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_) { diff --git a/core/sched/batch.h b/core/sched/batch.h index 524778cd..30ee5402 100644 --- a/core/sched/batch.h +++ b/core/sched/batch.h @@ -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_; diff --git a/core/sched/geometry.cpp b/core/sched/geometry.cpp index d6af36ed..f185cd74 100644 --- a/core/sched/geometry.cpp +++ b/core/sched/geometry.cpp @@ -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); diff --git a/core/sched/geometry.h b/core/sched/geometry.h index 72583964..7e0b39d5 100644 --- a/core/sched/geometry.h +++ b/core/sched/geometry.h @@ -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 diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index fd53ac05..377decde 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -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>* blocks_out, const HitCap* cap) const = 0; virtual const std::vector& 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& 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. */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 4a304cc4..822b7d0a 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -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 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& 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(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(Q, 16)) / Q * Q; - return t >= I ? t : -1; + return t >= std::min(I, kWindowSnapshotMin) ? t : -1; } return tail > I && tail - tail / I * I >= std::max(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; } diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index f33d248e..5f310196 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -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 diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 9993c082..e93fa793 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -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. -->
–
- kv cache in vram + kv cache in vram
–%
@@ -1353,7 +1356,7 @@ nav button.on { color:var(--fg); background:var(--track); } conversations can resume
–tok
- context in vram + context in vram
–
moved to host ram @@ -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 " 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]]) { diff --git a/core/server/liveview.cpp b/core/server/liveview.cpp index 4cfb13fd..f8a24354 100644 --- a/core/server/liveview.cpp +++ b/core/server/liveview.cpp @@ -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; diff --git a/core/server/liveview.h b/core/server/liveview.h index 9469df7c..4a4102f0 100644 --- a/core/server/liveview.h +++ b/core/server/liveview.h @@ -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 diff --git a/core/text/chat.cpp b/core/text/chat.cpp index 59e2cfcd..6e4a5112 100644 --- a/core/text/chat.cpp +++ b/core/text/chat.cpp @@ -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()) { diff --git a/data/engram_tables.py b/data/engram_tables.py index 605d182b..cc4090ec 100644 --- a/data/engram_tables.py +++ b/data/engram_tables.py @@ -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 """ diff --git a/data/recipes/deepseek41-ud-iq1s.recipe b/data/recipes/deepseek41-ud-iq1s.recipe index bc8ece4a..0e11ce8f 100644 --- a/data/recipes/deepseek41-ud-iq1s.recipe +++ b/data/recipes/deepseek41-ud-iq1s.recipe @@ -8,7 +8,7 @@ # rad-convert --add engram-tables.safetensors \ # --recipe data/recipes/deepseek41-ud-iq1s.recipe --imatrix -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 diff --git a/deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml b/deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml index 7f7505ae..120baad2 100644 --- a/deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml +++ b/deploy/compose/gemma4-31b-w4a8-df2-tp4.yaml @@ -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 diff --git a/deploy/compose/gemma4-31b-w4a8-df2b16-tp2.yaml b/deploy/compose/gemma4-31b-w4a8-df2b16-tp2.yaml new file mode 100644 index 00000000..9138028b --- /dev/null +++ b/deploy/compose/gemma4-31b-w4a8-df2b16-tp2.yaml @@ -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 diff --git a/deploy/compose/gemma4-31b-w4a8-df2b16-tp4.yaml b/deploy/compose/gemma4-31b-w4a8-df2b16-tp4.yaml new file mode 100644 index 00000000..6209516d --- /dev/null +++ b/deploy/compose/gemma4-31b-w4a8-df2b16-tp4.yaml @@ -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 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index ba88a86b..be30759a 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -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 --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 diff --git a/docs/GUIDE.md b/docs/GUIDE.md index a08087f8..2c5589e8 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -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-.tab`, in a tmpfs, mapped +`MAP_SHARED` and pinned for the cards as `ram` pins it, so two engines on separate card sets +(`ROCR_VISIBLE_DEVICES`) hold one table in host memory. The first engine to start fills the file +from the container; a second finds it complete, checks samples of it against its own container and +only pins it. The `` is a hash of the container's path, size and mtime and the table's place in +it, so a file never serves another model. A weight under 32 MiB the gather reads beside the table +(its scale) keeps a private pinned copy, since its file would be mostly header. The engine that +leaves last deletes the file, and one that leaves while another still holds it waits up to a second +for it, so two engines stopped together still remove it; after a crash a complete file stays and is +reused, or removed by hand. `DIR` must be a tmpfs (`/dev/shm`, or a tmpfs mounted for it, sized for +the table); `ram=DIR` needs the card gather kernel and the driver's SVM API, and is refused +otherwise. The driver counts a shared page against every process that pins it, so with two engines +the pinned total is twice the table: set `amdgpu.no_system_mem_limit=1` (the cap is RAM less 1/64 +and 1.5 GiB) or the second pin can be refused. The kernel charges the tmpfs pages to the memory +cgroup of the engine that filled them. + **`--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 +nomic-embed-text-v2-moe converts from its f32 checkpoint with `rad-convert --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] diff --git a/docs/OPS.md b/docs/OPS.md index 490abfec..a588af79 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -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): diff --git a/docs/PLUGIN.md b/docs/PLUGIN.md index b289e8f9..6b88ba42 100644 --- a/docs/PLUGIN.md +++ b/docs/PLUGIN.md @@ -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 diff --git a/docs/QSA.md b/docs/QSA.md index 1e8374e0..fd796c70 100644 --- a/docs/QSA.md +++ b/docs/QSA.md @@ -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 diff --git a/docs/TOOLS.md b/docs/TOOLS.md index eada4b30..74aa251c 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -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. diff --git a/docs/TP4.md b/docs/TP4.md index a51caa30..6403542b 100644 --- a/docs/TP4.md +++ b/docs/TP4.md @@ -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 diff --git a/docs/benchmarks/hyv3-w4-decode.md b/docs/benchmarks/hyv3-w4-decode.md deleted file mode 100644 index 6ad6eeea..00000000 --- a/docs/benchmarks/hyv3-w4-decode.md +++ /dev/null @@ -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. diff --git a/docs/deepseek41-hf-direct.md b/docs/deepseek41-hf-direct.md index fdeecf06..39da63c1 100644 --- a/docs/deepseek41-hf-direct.md +++ b/docs/deepseek41-hf-direct.md @@ -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 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 --add engram-tables.safetensors \ --recipe data/recipes/deepseek41-ud-iq1s.recipe \ --imatrix imatrix-merged.gguf --tokenizer /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). diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp index 3c349e43..f5421048 100644 --- a/libavx/avx_attn.cpp +++ b/libavx/avx_attn.cpp @@ -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 diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index a3d714f0..c8c5b5f9 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -347,6 +347,13 @@ std::vector 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 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. */ diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index 9d975961..fb8015a2 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -4063,7 +4063,7 @@ void planes_cases(const Check& ck, std::vector& 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 }, diff --git a/libavx/avx_gemm.cpp b/libavx/avx_gemm.cpp index f9f6a27b..972cb2cb 100644 --- a/libavx/avx_gemm.cpp +++ b/libavx/avx_gemm.cpp @@ -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 narrowed; RadTensor a_f16{}; if (zg.act == ZP_F16 && A->dtype == RAD_BF16) { diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index ae1a6cef..47541304 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -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. */ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 5f7321e4..1c6bb02a 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -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 */ diff --git a/libavx/avx_sample.cpp b/libavx/avx_sample.cpp index 2559978a..2048fb61 100644 --- a/libavx/avx_sample.cpp +++ b/libavx/avx_sample.cpp @@ -29,6 +29,7 @@ #include "rad_sample.h" #include +#include #include 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 sel; + std::vector front; + std::vector 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; +} diff --git a/libr3d/CMakeLists.txt b/libr3d/CMakeLists.txt index e72c7ca0..b62876c8 100644 --- a/libr3d/CMakeLists.txt +++ b/libr3d/CMakeLists.txt @@ -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=`, 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 /kernels/libr3d.so [--case ] 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) diff --git a/libr3d/README.md b/libr3d/README.md index 3d656499..aca5288f 100644 --- a/libr3d/README.md +++ b/libr3d/README.md @@ -1,118 +1,107 @@ # libr3d -libr3d is radiance's kernel library for RDNA3 and RDNA3.5 — the gfx11xx family: -`gfx1100`, `gfx1101`, `gfx1102`, `gfx1103`, `gfx1150`, `gfx1151`, and `gfx11-generic`, -the code object for a gfx11 card a build did not name. HIP kernels behind a plain C -ABI ([`r3d.h`](r3d.h)) plus the kernel-plugin rows the engine selects from -(`r3d_rows.cpp`); `libr3d/CMakeLists.txt` names every unit and its flags. +libr3d is radiance's kernel library for RDNA3 and RDNA3.5, the gfx11xx family: `gfx1100`, +`gfx1101`, `gfx1102`, `gfx1103`, `gfx1150`, `gfx1151`, and `gfx11-generic`, the code object for a +gfx11 card the build did not name. It is HIP kernels behind a plain C ABI ([`r3d.h`](r3d.h)) plus +the kernel-plugin rows the engine selects from (`r3d_rows.cpp`); `libr3d/CMakeLists.txt` names +every unit and its flags. -It claims `^gfx11` where [`libr4d`](../libr4d/README.md) claims `^gfx12`: a card gets -one device library, picked by the rows and never by the name. The kernels are not -libr4d's ported: the matrix work runs on the dot2 path — RDNA3's 16×16 wave-matrix -family is a fragment layout these kernels' lane map does not use, and gfx11 has no -bf16 pack and no VOPD — so every arithmetic path is its own: `v_dot2acc_f32_f16` for -products, software codecs for every format, a weight read in the order the container -stores it. The contract is shared: the same op schemas (copied -slot for slot from libref, as the loader requires), the same numerics rules, the same -geometry in constraints. Family parts differ in CU count and clock, never in these -instructions, so one code object per family suffices — and every number here is quoted -with its geometry, and with the class of part where the part's size is part of the -fact. +It claims `^gfx11` where [`libr4d`](../libr4d/README.md) claims `^gfx12`; a card gets one device +library, chosen by the rows, not by the name. The kernels are not ports of libr4d's. The matrix +work runs on the dot2 path (RDNA3's 16x16 wave-matrix family uses a fragment layout these lane +maps do not, and gfx11 has no bf16 pack and no VOPD), so every arithmetic path is its own: +`v_dot2acc_f32_f16` for products, software codecs for every format, and weights read in the order +the container stores them. The contract is shared with libr4d: the same op schemas (copied slot +for slot from libref, as the loader requires), the same numerics rules and the same geometry in +constraints. Parts of the family differ in CU count and clock, never in these instructions, so one +code object per family suffices. Numbers in this document are quoted with their geometry, and with +the class of part where the part's size matters. ## Naming -An entry point is `r3d__[_]`: -`gemm_nt_bf16_m16` serves `gemm_nt` at bf16 for M ≤ 16 and refuses a larger M; -`r3d_rope_bf16` serves bf16 QKV in place and refuses anything else. A dimension named -in a name is a compile-time constant, and the entry point rejects a mismatch instead -of running. Shared dimensions stay out of the names: wave32, the attention rows' head -size (128), and the target architecture, reported by `rad_plugin_info`'s -`build_target` — spelled as a device reports its arch, because the loader warns when a -plugin claims a card the running device is not. +An entry point is `r3d__[_]`: `gemm_nt_bf16_m16` +serves `gemm_nt` at bf16 for M <= 16 and refuses a larger M; `r3d_rope_bf16` serves bf16 QKV in +place and refuses anything else. A dimension in a name is a compile-time constant, and the entry +point rejects a mismatch instead of running. Dimensions shared by the whole library stay out of +the names: wave32, the attention rows' head size (128), and the target architecture, which +`rad_plugin_info`'s `build_target` reports, spelled as a device reports its arch, because the +loader warns when a plugin claims a card the running device is not. -Rows are `RadKernelInfo` entries in a table the engine reads from a dlopened `.so`; -the plugin links the ABI headers and nothing of the engine's. +Rows are `RadKernelInfo` entries in a table the engine reads from the dlopened `.so`; the plugin +links the ABI headers and nothing of the engine's. -**Schema equality at load:** the first library to declare an op fixes its schema, and -a second declaring it with a different schema is refused by name with every row it -carries — arguments are positional, so a mistyped operand role is not a bad row, it is -no library. +**Schema equality at load.** The first library to declare an op fixes its schema, and a second +library declaring it with a different schema is refused by name, with every row it carries. +Arguments are positional, so a mistyped operand role costs the whole library, not one row. -**The tail order is the ABI's:** `init, fini, launch, scratch, layout, relayout, -opd_shape, unrelayout, replaces` — `replaces` last on purpose, because kernel tables -are positional aggregate initialisers: a field inserted mid-struct shifts every later -one, and `nullptr` converts to any function pointer, so part of the shift would -compile. +**The tail order is the ABI's:** `init, fini, launch, scratch, layout, relayout, opd_shape, +unrelayout, replaces`. `replaces` is last on purpose: kernel tables are positional aggregate +initialisers, a field inserted mid-struct shifts every later one, and `nullptr` converts to any +function pointer, so part of such a shift would still compile. -There is no launch adapter: every entry point *is* the row's `launch`, `(const -RadArgs*, RadStream)`, spelled `r3d_rad_` in [`r3d_plugin.h`](r3d_plugin.h). +There is no launch adapter: every entry point is the row's `launch`, `(const RadArgs*, +RadStream)`, named `r3d_rad_` in [`r3d_plugin.h`](r3d_plugin.h). Behind it each unit has two +layers. The **launcher** (`r3d_(...)` in `r3d.h`) takes pointers as longs, checks what a +`__global__` cannot, computes the grid and issues one kernel on the given stream. The **shim**, +named by the row, reads operands with [`r3d_args.h`](r3d_args.h), takes the dtype from the tensor +and the row count from the operand, checks strides and returns a RAD status. Neither allocates and +neither synchronises. -Behind it, two layers per unit: the **launcher** (`r3d_(...)` in `r3d.h`) takes -pointers as longs, checks what a `__global__` cannot, computes the grid, issues one -kernel on the stream it was handed; the **shim**, named by the row, reads operands -with [`r3d_args.h`](r3d_args.h), takes dtype from the tensor and the row count from -the operand, checks strides, returns a RAD status. Neither allocates, neither -synchronises. The table lists a selection; `r3d_rows.cpp` and `r3d.h` hold the full -set. +The table groups the rows by family; `r3d_rows.cpp` and `r3d.h` hold the full set. | family | rows | | --- | --- | | `norm` | `rmsnorm_bf16` (optional residual add and multiplier), `rmsnorm_f32`, `layernorm_bf16` | -| `elem` | `add` (with `div`, and the broadcast band) · `mul` · `silu` · `gelu` · `sigmoid` · `act_mul_{silu,gelu,sigmoid}` · `softmax` · `scale` · `fill` (bf16/f32/i32/i64) · `gather_rows` · `scatter_rows`, bf16 and f32 where the op has both, plus seven `cast` pairs and `silu_mul_bf16` | -| `attn` | `rope_bf16` (neox and gptj, in place over packed QKV), `kv_store_{bf16,f16,fp8}`, `attn_paged_{bf16,fp8}_{decode,prefill}` — head_dim 128, split-KV combined in the same launch | -| `gemm` | `embed_lookup_bf16`, `gemm_nt_bf16_{m16,tiled}`, `gemm_nt_q_fp8a16_m16`, `gemm_nt_q_fp8a8_{m16,tiled}`, `gemm_nt_q_mxfp4a8_{m16,tiled}` (OCP-MXFP4 weight: e2m1 codes, an e8m0 scale per 32 of K), `gemm_nt_q_w2a8_{m16,tiled}` (2-bit and 4-bit grids on the 128×128 tile), `gemm_nt_q_w4a8_m16` (signed int4 weight, decode band), `gemm_nt_q_w8a8_m16` (signed int8 weight, decode band), `gemm_nt_q_gated_fp8a8` | -| `vocab` | `logits_gemm_bf16` — the head read once a token, bf16 codes, or E4M3 codes with a bf16 scale per 128×128 block | -| `quant` | `quant_act_fp8_bf16`, `quant_act_i8_bf16`, `quant_act_i8g_bf16`, `gated_quant_fp8_bf16`, `rmsnorm_quant_fp8_bf16` (norm and quantiser in one pass), `dequant_fp8` `dequant_e5m2` `dequant_i8` | +| `elem` | `add` (with `div`, and the broadcast band), `mul`, `silu`, `gelu`, `sigmoid`, `act_mul_{silu,gelu,sigmoid}`, `softmax`, `scale`, `fill` (bf16/f32/i32/i64), `gather_rows`, `scatter_rows`, bf16 and f32 where the op has both, plus seven `cast` pairs and `silu_mul_bf16` | +| `attn` | `rope_bf16` (neox and gptj, in place over packed QKV), `kv_store_{bf16,f16,fp8}`, `attn_paged_{bf16,fp8}_{decode,prefill}`: head_dim 128, split-KV combined in the same launch | +| `gemm` | `embed_lookup_bf16`, `gemm_nt_bf16_{m16,tiled}`, `gemm_nt_q_fp8a16_m16`, `gemm_nt_q_fp8a8_{m16,tiled}`, `gemm_nt_q_mxfp4a8_{m16,tiled}` (OCP-MXFP4 weight: e2m1 codes, an e8m0 scale per 32 of K), `gemm_nt_q_w2a8_{m16,tiled}` (2-bit and 4-bit grids on the 128x128 tile), `gemm_nt_q_w4a8_m16` (signed int4 weight, decode band), `gemm_nt_q_w8a8_m16` (signed int8 weight, decode band), `gemm_nt_q_gated_fp8a8` | +| `vocab` | `logits_gemm_bf16`: the head, read once per token, as bf16 or as E4M3 codes with a bf16 scale per 128x128 block | +| `quant` | `quant_act_fp8_bf16`, `quant_act_i8_bf16`, `quant_act_i8g_bf16`, `gated_quant_fp8_bf16`, `rmsnorm_quant_fp8_bf16` (norm and quantiser in one pass), `dequant_fp8`, `dequant_e5m2`, `dequant_i8` | | `sample` | pre-filters `sample_{penalties,dry,ngram_ban,mask,logprobs}_f32`; spine `sample_{argmax,temp,topk,pick,topp,minp,typical,xtc}_f32` | -| `moe` | `row_topk_{bf16,f32}` — the op's stage in the reference is `moe`, so the row's is too | -| `draft` | `dflash_select_bf16` — the drafter's accept step, a walk over the draft block's candidate lattice | +| `moe` | `row_topk_{bf16,f32}` (the reference files the op under `moe`, so the row does too) | +| `draft` | `dflash_select_bf16`: the drafter's accept step, a walk over the draft block's candidate lattice | -Seventy-eight rows, 44 schemas, every schema checked against the `libref.so` beside the -plugin, slot for slot, by `r3d_selftest`. GEMM rows carry tunables (`sk`, `wv`, `nt`); -the rest have none. +The table holds 78 rows over 44 schemas; `r3d_selftest` checks every schema slot for slot against +the `libref.so` beside the plugin. GEMM rows carry tunables (`sk`, `wv`, `nt`); the rest have none. -Two int8 activation rows, because the reference has two ops and they are not -interchangeable: `quant_act_i8` is one scale per row, codes in the order an int8 -matrix operand is read (`i8_step_pos`, bits 2 and 3 of the column swapped) — what -`w8a8`/`w4a8`/`w2a8` producers mean; `quant_act_i8g` is one scale per (row, group), -row-major codes — what this library's `i8a8` GEMM reads and `dequant` inverts. The -step order is the op's, not a kernel's convenience: the plane is what the oracle -compares element by element, the one place in libr3d where a store address carries a -permutation. +There are two int8 activation rows because the reference has two ops and they are not +interchangeable. `quant_act_i8` writes one scale per row, with codes in the order an int8 matrix +operand is read (`i8_step_pos`, bits 2 and 3 of the column swapped); that is what +`w8a8`/`w4a8`/`w2a8` consumers expect. `quant_act_i8g` writes one scale per (row, group) with +row-major codes; that is what this library's `i8a8` GEMM reads and `dequant` inverts. The step +order belongs to the op: the oracle compares the plane element by element, and it is the one place +in libr3d where a store address carries a permutation. ## Constraints as data -Constraints are data in the rows the engine reads — a third copy of a geometry in each -caller drifts — and `r3d_selftest` checks every constraint key against the op's -declared parameters: a key renamed in one place only is a row that matches nothing. -Three rules decide what goes in a table, all three the engine's. +Constraints are data in the rows the engine reads, because a further copy of a geometry in each +caller would drift. `r3d_selftest` checks every constraint key against the op's declared +parameters, so a key renamed in one place only is caught instead of producing a row that matches +nothing. Three engine rules decide what goes in a table: -* **A constraint on a key the band does not carry does not hold.** A band carries the - parameters its graph set and nothing else, so a row constraining an optional - parameter serves only graphs that spell it out: `rotary_dim` is optional on `rope`, - and binding it resolved a row to nothing for every graph that rotates a whole head; - `pb1`/`pb2` on the quantised GEMMs did the same to a whole model's bands, which fell - to the host. The selftest's reachability phase names every row that narrows itself - this way. -* **A band's `dtype` is the activation's.** A row whose dtype lives in the weight does - not constrain it: `logits_gemm` carries no `dtype` constraint, because the head's - dtype is a property of the operand and the row answers dtype with a check on the - tensor. `gemm_nt_q` is the opposite case — there `dtype` *is* the operand scheme, so - `C_IN` filters — stated at each table. -* **A row's floor is its sibling's declared ceiling + 1.** The tiled rows begin at `M - >= 17` because `gemm_nt_bf16_m16` declares `C_LE("M", 16)`, read from the constraint - and not from the name. A floor reasoned from prose ("the decode heights") left - 17..64 unserved and 209 batched-decode bands on the host: the shape a serving card - spends most of its life in. +* **A constraint on a key the band does not carry does not hold.** A band carries the parameters + its graph set and nothing else, so a row that constrains an optional parameter serves only + graphs that state it: binding `rotary_dim` (optional on `rope`) would resolve the row to nothing + for every graph that rotates a whole head, and binding `pb1`/`pb2` on the quantised GEMMs would + send a whole model's bands to the host. The selftest's reachability phase names every row that + narrows itself this way. +* **A band's `dtype` is the activation's.** A row whose dtype lives in the weight does not + constrain it: `logits_gemm` carries no `dtype` constraint, because the head's dtype is a + property of the operand, checked on the tensor. `gemm_nt_q` is the opposite case: there `dtype` + is the operand scheme, so `C_IN` filters on it. Each table states which case it is. +* **A row's floor is its sibling's declared ceiling + 1.** The tiled rows begin at `M >= 17` + because `gemm_nt_bf16_m16` declares `C_LE("M", 16)`, read from the constraint and not from the + name. A floor reasoned from prose ("the decode heights") leaves 17..64, the batched-decode + heights, unserved. -What the kernel cannot read goes in the constraints, not only in the launch: `n_vocab ->= 4` is the store's granularity (rows are written in 16-byte runs); `n_cand <= 1024` -is the candidate kernels' LDS budget (five f32 arrays of `n_cand` = 20 KiB of the 64 -KiB); `K % 32` / `K % 128` are the tile's k-chunk and the container's scale block. +What the kernel cannot read goes in the constraints as well as the launch check: `n_vocab >= 4` is +the store's granularity (rows are written in 16-byte runs); `n_cand <= 1024` is the candidate +kernels' LDS budget (five f32 arrays of `n_cand` = 20 KiB of the 64 KiB); `K % 32` and `K % 128` +are the tile's k-chunk and the container's scale block. ## Building -Out of tree, against an installed radiance, as a third-party plugin is built: +Out of tree, against an installed radiance, the way a third-party plugin is built: ``` cmake -S libr3d -B build -G Ninja \ @@ -122,415 +111,330 @@ cmake -S libr3d -B build -G Ninja \ cmake --build build ``` -`rad_plugin_gpu_targets(R3D_GPU_TARGETS "^gfx11")` filters requested targets to the -family, and the project returns without a target when the filter is empty: a build for -gfx12 machines does not produce this library, on any path. `gfx11-generic` is the -object for a gfx11 card the build did not name — why one `.so` serves the family. In -tree, `add_subdirectory(libr3d)` sits beside libr4d's under the same `RAD_HIP_FOUND` -guard. +`rad_plugin_gpu_targets(R3D_GPU_TARGETS "^gfx11")` filters the requested targets to the family, +and the project returns without a target when the filter is empty, so a build for gfx12 machines +never produces this library. `gfx11-generic` is the object for a gfx11 card the build did not +name, which is how one `.so` serves the family. In tree, `add_subdirectory(libr3d)` sits beside +libr4d's under the same `RAD_HIP_FOUND` guard. -`R3D_UNITS` lists units as `"file|extra flags"`, each named after the entry point it -provides; the shared headers (`r3d_common.h`, `r3d_codecs.h`, `r3d_args.h`, -`r3d_launch.h`, `r3d_tiling.h`, `r3d_fp8_dequant.h`) provide no kernel. Every unit is -`-ffp-contract=off`, which `rad_hipify` puts on all HIP sources — not a style -preference (Numerics). `r3d_rows.cpp` and `r3d_shapes.cpp` include neither `r3d.h` nor -the runtime, so the tables compile without ROCm. Occupancy is per kernel: -`__launch_bounds__` and `amdgpu_waves_per_eu` (`R3D_WAVES`) are written against this -family's register file, not RDNA4's. +`R3D_UNITS` lists the units as `"file|extra flags"`, each named after the entry point it provides; +the shared headers (`r3d_common.h`, `r3d_codecs.h`, `r3d_args.h`, `r3d_launch.h`, `r3d_tiling.h`, +`r3d_fp8_dequant.h`) provide no kernel. Every unit is compiled `-ffp-contract=off`, which +`rad_hipify` puts on all HIP sources; it is a correctness flag (see [Numerics](#numerics)). +`r3d_rows.cpp` and `r3d_shapes.cpp` include neither `r3d.h` nor the HIP runtime, so the tables +compile without ROCm. Occupancy is set per kernel: `__launch_bounds__` and `amdgpu_waves_per_eu` +(`R3D_WAVES`) are written against this family's register file, not RDNA4's. ## Adding a kernel 1. Write the `.hip`, named after the entry point it provides, geometry included. -2. Declare the launcher in [`r3d.h`](r3d.h) and the shim in - [`r3d_plugin.h`](r3d_plugin.h). +2. Declare the launcher in [`r3d.h`](r3d.h) and the shim in [`r3d_plugin.h`](r3d_plugin.h). 3. Add the unit to `R3D_UNITS` in `libr3d/CMakeLists.txt`, with any per-unit flags. -4. Add a `RadKernelInfo` row in `r3d_rows.cpp` with its constraint table. If its - `op` is one libref declares, copy libref's schema slot for slot — names and doc - strings are free, roles are not; if the op is new, declare the schema in the - same file. -5. Add the operand description to `r3d_shapes.cpp` if the row's operands are not - the schema's plain reading, and a geometry to the selftest's list. -6. Give the row a case: the selftest walks the table, so a row is run by adding no - test code — geometry comes from its constraints. +4. Add a `RadKernelInfo` row in `r3d_rows.cpp` with its constraint table. If its `op` is one + libref declares, copy libref's schema slot for slot (names and doc strings are free, roles are + not); if the op is new, declare the schema in the same file. +5. Add the operand description to `r3d_shapes.cpp` if the row's operands are not the schema's + plain reading, and a geometry to the selftest's list. +6. The selftest walks the table, so a new row runs with no new test code; its geometry comes from + its constraints. 7. Measure it: `r3d_selftest /kernels/libr3d.so --case `, then `rad-kbench --home "$RADIANCE_HOME" --kernels libref:libr3d --op `. -A row naming an entry point that does not exist is an undefined symbol at `dlopen`, -which refuses the library and takes every row with it: a row lands in the same change -as its kernel, and a constraint array whose kernel has not landed stays out of the -table. +A row naming an entry point that does not exist is an undefined symbol at `dlopen`, which refuses +the library and every row in it. A row therefore lands in the same change as its kernel, and a +constraint array whose kernel has not landed stays out of the table. -## What the family gives, and what it takes +## What the family provides, and what it lacks -Measured by reading emitted assembly for the gfx11 targets (`__has_builtin` off -`--offload-device-only`, `llvm-mc -show-encoding` per target) against the ROCm this -tree builds against; where a claim was taken on one chip it says which. Nothing here -changes between gfx110x and gfx115x — which is what makes the family one code object. +These facts come from emitted assembly for the gfx11 targets (`__has_builtin` under +`--offload-device-only`, `llvm-mc -show-encoding` per target) with the ROCm this tree builds +against; a claim checked on one chip names it. None of them differs between gfx110x and gfx115x, +which is what makes the family one code object. -**The dot2 path, and the wave-matrix instructions it does not use.** RDNA3 carries -exactly six wave-matrix instructions, all 16×16×16 wave32: f16, bf16, int8 and int4 -in, f32, f16, bf16 and i32 accumulating, and the toolchain emits them on every gfx11 -target. They are not a separate matrix unit: the ISA states the WMMA ops run over -multiple cycles and drive the DOT pipeline internally, and the MAC-core measurement -on this part confirms it (512 waves, K depth 4096, operands preloaded: f32-acc f16 -19.11, f32-acc bf16 19.24, f16-acc f16 19.44, i32-acc i8 19.29, dot2 paired as -`v_dual_dot2acc_f32_f16` 18.86 TFLOP/s — the f16/bf16/i8 tiles and the dot path sit -on the same pipe within three percent, matching the full-kernel 1.99-vs-1.97 of -r3d_common.h). The i32-acc i4 tile is the exception at 25.68 TFLOP/s, 35% above the -dot path, but that instruction takes i4 in *both* operands and the grids this -library serves pair i8 activations against i4 and i2 weights — there is no -mixed-precision integer WMMA on RDNA3, so that pipe is unreachable from the w4a8 -and w2a8 rows. The i8 tile's only edge over the current w8a8 path is a decode, and -the kernel-level measurement closes the question: the w8a8 m16 row runs 0.850 -TFLOP/s and w4a8 m16 0.789 (M=16, N=11008, K=4096, weights in device memory) -- -twenty-two times below the i8 tile's own MAC core, weight-byte-bound at the decode -band's geometry, where no re-tile of the arithmetic moves the number. These -kernels run -the dot2 path: one wave a weight row, a k-split per lane, the group's exact sub-sum -folded with one shfl. The WMMA fragment layout (lanes 0..15 replicated into 16..31, -A one row a lane, B one column a lane, the accumulator's row i at lane (i%2)·16+j -VGPR i/2) is a re-tile, not a drop-in, and no measured variant earns it. Products -go through `__builtin_amdgcn_fdot2` → `v_dot2acc_f32_f16` on every gfx11 target, -paired as `v_dual_dot2acc_f32_f16` where the scheduler can — about a quarter of -RDNA4's matrix rate. No fragment layouts, so no repacked weights, so no layout hook -except the container's own planes force. +**The dot2 path, and the wave-matrix instructions it does not use.** RDNA3 has six wave-matrix +instructions, all 16x16x16 wave32: f16, bf16, int8 and int4 inputs, accumulating in f32, f16, bf16 +or i32, and the toolchain emits them on every gfx11 target. They are not a separate matrix unit: +the ISA states that the WMMA ops run over multiple cycles on the DOT pipeline. A MAC-core +measurement (512 waves, K depth 4096, operands preloaded) agrees: f32-acc f16 19.11, f32-acc bf16 +19.24, f16-acc f16 19.44, i32-acc i8 19.29 and paired `v_dual_dot2acc_f32_f16` 18.86 TFLOP/s, all +within three percent. The i32-acc i4 tile reaches 25.68 TFLOP/s, but it takes i4 in both operands, +and the grids this library serves pair i8 activations with i4 or i2 weights; RDNA3 has no +mixed-precision integer WMMA, so that pipe is unreachable from the w4a8 and w2a8 rows. At the +decode band the integer rows are bound by weight bytes, not arithmetic: w8a8 m16 runs 0.850 TFLOP/s +and w4a8 m16 0.789 (M=16, N=11008, K=4096, weights in device memory), about 22x below the i8 +tile's MAC rate, so a re-tile onto WMMA would not move them. -**No int8 dot.** `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a`, -`__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are all undeclared for gfx1102, and all -four were tested. Codes widen to f16 and the dot runs on `dot2_f16x4`, paid for with a -trick: 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, and the dot's answer comes back -carrying `128 · Σa` — the plane the op already has for the zero point, so de-bias is -one exact f32 subtraction per (row, group). +The kernels therefore run the dot2 path: one wave per weight row, a k-split per lane, the group's +exact sub-sum folded with one shfl. Moving to the WMMA fragment layout (lanes 0..15 replicated into +16..31, A one row per lane, B one column per lane, accumulator row i at lane (i%2)*16+j VGPR i/2) +would be a re-tile, not a drop-in. Products go through `__builtin_amdgcn_fdot2` -> +`v_dot2acc_f32_f16` on every gfx11 target, paired as `v_dual_dot2acc_f32_f16` where the scheduler +can, about a quarter of RDNA4's matrix rate. With no fragment layouts there are no repacked +weights, and no layout hook except where the container's own planes require one. -**`v_fdot2_f32_f16` carries a little under 24 bits on integers — call it 22.** -"Products and partials are integers below 2^24, so the dot is exact" is true of f32 -and false of this instruction. Instrument: `probe_dot_kernel`, in the unit that uses -it — 32 lanes a block, one 64-code dot per lane, its f32 beside the exact integer. -Bias 1024: **71027 of 262144 dots inexact, worst |err| 0.125**, every one a dot whose -magnitude had reached 2^20; bias 128: 70115 of 262144, worst 0.015625. Worst error -over magnitude is ~2^-22, so shrinking the bias shrinks the tail and does not remove -it. The same work as four `__fmaf_rn` per quad in f32: 262144 samples, **0 inexact, -worst error exactly 0**. `gemm_nt_q` at `w2a8` ships a documented tail, not a claim. +**No int8 dot.** `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a` and +`__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are all undeclared for gfx1102. Codes widen to f16 +and the dot runs on `dot4_f16x4`. For 2-bit codes the widening uses the fact that the f16 bits of +`128 + x` are `0x5800 + 8x` for `0 <= x < 8`: a code becomes an f16 with a mask, two shifts and +an add, and the dot's result carries `128 * sum(a)`, which is the plane the op already has for the +zero point, so the de-bias is one exact f32 subtraction per (row, group). -**`v_cvt_pk_f16_fp8` is listed by the compiler and absent from the silicon:** on -gfx1102 the ISA of a build calling it contains zero `v_cvt_pk_f16_fp8`, counted by -grep — it expands to software, ~100 instructions per 8 codes against the four that -widen bf16. `v_cvt_pk_fp8_f32` / `v_cvt_pk_f32_fp8` need `fp8-conversion-insts`, which -no gfx11 target has; their builtins are *declared* for gfx11 — the trap a -`__has_builtin` guard falls into — and die at instruction selection. Both directions -of e4m3 are bit maths in [`r3d_codecs.h`](r3d_codecs.h), mirroring `rad_plugin.h` line -for line, checked over every code. +**`v_fdot2_f32_f16` carries about 22 bits of mantissa on integer operands, not 24.** "Products +and partials are integers below 2^24, so the dot is exact" holds for f32 and not for this +instruction. `probe_dot_kernel` in `r3d_gemm_nt_q_w2a8.hip` measures it: one 64-code dot per lane, +its f32 result beside the exact integer. Over 262144 dots, a bias of 1024 leaves 71027 inexact +with worst error 0.125 (every one a dot whose magnitude reached 2^20); a bias of 128 leaves 70115 +with worst error 0.015625. The worst error relative to magnitude is about 2^-22, so a smaller bias +shrinks the error without removing it. The same work as four `__fmaf_rn` per quad in f32 is exact +on all 262144 samples. `gemm_nt_q` at `w2a8` therefore ships with a documented one-ulp tail. -**No fp8 instruction means the decode is arithmetic, so the arithmetic gets a table.** -Ten VALU a code, and a weight-stationary row decodes every code it multiplies — twice -over where a lane owns two chains — which at M=1 is every code in the operand. A -256-entry f16 table in LDS, 512 bytes, built once a block by the arithmetic path -itself and therefore exact by construction, costs two `ds_read_u16` and a pack a pair -at zero register cost: the gated row's tall arm is 109 registers a lane, four waves a -SIMD, zero spills, and the table alone moves M=64 from 8395.3 us to 2786.5 us (its -band: N=12288 K=2048 group=128, codes resident, best of nine) — two thirds of that -arm's gain is the decoder. Two landmines in it, both load-bearing. The table's -argument is a **PAIR**, low code in the low byte, not an index: feeding it the index -fills the even entries and decodes code 0 into every odd one, and the code-enumeration -case names that as `rel_l2` 9.6e-01, not a NaN. And the decoded pairs -go from the table into the dot **inline**: materialising the round's eight pairs into -an array on the way — the shape this loop had, and the shape the arithmetic decoder -feeds — put 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 proven exact on the device, entry -by entry and pair by pair. The array form is the one that miscomputes; do not restore -it as a tidy-up. +**No fp8 conversion instructions.** On gfx1102 a build calling `v_cvt_pk_f16_fp8` contains no such +instruction; it expands to software, about 100 instructions per 8 codes against the four that widen +bf16. `v_cvt_pk_fp8_f32` / `v_cvt_pk_f32_fp8` need `fp8-conversion-insts`, which no gfx11 target +has; their builtins are declared for gfx11, so a `__has_builtin` guard passes, and they fail at +instruction selection. Both directions of e4m3 are bit maths in [`r3d_codecs.h`](r3d_codecs.h), +mirroring `rad_plugin.h` line for line and checked over every code. -**`f16x2_pack` is `v_cvt_pkrtz_f16_f32`: rounds toward zero, flushes subnormal f16.** -Only values f16 represents exactly may go through it — bf16 widened (7 mantissa bits -into 10), E4M3 widened (3 into 3) — never a code times a scale. Folding `code * scale` -through the pack biased every product toward zero: `rel_l2` 2.8e-4 against the fold's -law, 0.53 of outputs within 2 ulps. Folding with `v_mul_f16` (round to nearest, -subnormals kept) is one rounding in the right direction and one instruction: 4.5e-06, -1.000 within 2 ulps, nothing beyond six. Every scale fold here goes through -`v_mul_f16`. +**The E4M3 decode is a table.** The arithmetic decode costs about ten VALU per code, and a +weight-stationary row decodes every code it multiplies (twice where a lane owns two chains). A +256-entry f16 table in LDS (512 bytes), built once per block by the arithmetic path and therefore +exact, costs two `ds_read_u16` and a pack per pair, at no register cost: the gated row's tall arm +is 109 registers per lane, four waves per SIMD, no spills. On the gated band (N=12288 K=2048 +group=128, codes resident) the table takes M=64 from 8395.3 us to 2786.5 us. Two invariants: -**`v_cvt_pk_bf16_f32` does not exist** on gfx1100, gfx1102, gfx1151: a bf16 pair is -rounded by hand and packed with `v_perm_b32`. **The dot's bf16 selector is a lie** — -`__builtin_amdgcn_fdot2` takes a `sel` operand for the bf16 form, the compiler accepts -`sel = true`, emits the f16 instruction, and bf16 operands are read as f16s: nonsense -products, silently. `dot2_f16x2` passes `false`, always. f16 is the compute type: bf16 -and E4M3 widen to it exactly, with the edges in the codecs — above 65504 a widening -saturates, below 2^-14 the f16 subnormal grid is coarser than the source's and -truncates. +* The table builder's codec argument is a pair (low code in the low byte), not an index. Passing + the index decodes code 0 into every odd entry, which zeroes half the products without producing + a NaN (`rel_l2` 9.6e-01 on the code-enumeration case). +* Decoded pairs go from the table into the dot inline. Materialising a step's eight pairs into an + array on the way miscomputes on the tall arm (`rel_l2` 6.6e-01 at M=7, NaN at M=64) even though + the table itself is exact on the device. Do not restore the array form. -**Wave32, smaller register file than RDNA4:** 1024 VGPR entries a SIMD for a wave32, -granules of 8, against RDNA4's 1536; 64 KiB of LDS a workgroup on both. Occupancy -constants do not cross the generation, so `R3D_WAVES` is per kernel. A CU is 4 SIMDs × -16 wave32s = 64 wave slots, and `multiProcessorCount` reports CUs on gfx11 (WGPs on -gfx12), so a row-per-block kernel with one wave a block passes 64 waves a CU at -exactly the row count where tail waves start waiting. A wave64 build is refused at -compile time: it computes garbage rather than running slower. +**`f16x2_pack` is `v_cvt_pkrtz_f16_f32`: it rounds toward zero and flushes subnormal f16.** Only +values f16 represents exactly may go through it (widened bf16, widened E4M3), never a code times a +scale. Folding `code * scale` through the pack biases every product toward zero (`rel_l2` 2.8e-4 +against the fold's law, 53% of outputs within 2 ulps). Folding with `v_mul_f16` (round to nearest, +subnormals kept) is one instruction and one correct rounding (4.5e-06, all outputs within 2 ulps, +none beyond six). Every scale fold here uses `v_mul_f16`. -**No vector f64:** consumer RDNA3 is 1:64 on doubles, in practice soft-float, which -sets the transcendental policy per unit — the sampler keeps the reference's -`(float)exp((double)x)` (drawing a different token than the recording is wrong at any -speed), attention cannot pay it and ships a polynomial, the gated MLP uses `expf` into -a bf16 narrowing. +**`v_cvt_pk_bf16_f32` does not exist** on gfx1100, gfx1102 or gfx1151: a bf16 pair is rounded by +hand and packed with `v_perm_b32`. -**The lane ops are libr4d's** — `update_dpp` (xor and shr controls), `permlanex16`, -`readlane`, `readfirstlane`, `ballot`, `ds_bpermute`, `v_perm_b32`, `exp2f`, `rcpf`, -`s_barrier`, `sched_group_barrier`; DPP16 and `v_permlanex16` are RDNA1 onward, and -the encodings in [`r3d_common.h`](r3d_common.h) are the ones libr4d proved on -hardware. **No transposed loads, no VOPD:** neither `global_load_tr_b128` (RDNA4) nor -`ds_read_b64_tr_b16` (rejected by this assembler), so a transpose is done in -registers; VOPD is RDNA4, and the tree's `-mllvm=-amdgpu-enable-vopd=false` comes from -the LLVM version, not from here. LLVM single-buffers LDS and drains before a dependent -read unless told, and with no matrix unit there is nothing to overlap a load with, so -the barrier needed is the plain one. +**The dot's bf16 selector does not select bf16.** `__builtin_amdgcn_fdot2` takes a `sel` operand +for the bf16 form; the compiler accepts `sel = true`, emits the f16 instruction, and reads bf16 +operands as f16, silently producing wrong products. `dot2_f16x2` always passes `false`. f16 is the +compute type: bf16 and E4M3 widen to it exactly, with the edges handled in the codecs (above 65504 +a widening saturates; below 2^-14 the f16 subnormal grid is coarser than the source's and +truncates). -## Weights are stored once: the hook, and the writer that goes with it +**Wave32, a smaller register file than RDNA4.** A SIMD has 1024 VGPRs for wave32, in granules of +8, against RDNA4's 1536; LDS is 64 KiB per workgroup on both. Occupancy constants do not carry +across the generation, so `R3D_WAVES` is set per kernel. A CU is 4 SIMDs x 16 wave32s = 64 wave +slots, and `multiProcessorCount` reports CUs on gfx11 (WGPs on gfx12), so a row-per-block kernel +with one wave per block reaches 64 waves per CU exactly at the row count where tail waves start +waiting. A wave64 build is refused +at compile time (`r3d_common.h`): it would compute garbage rather than run slower. -Four rows declare a `layout` — `gemm_nt_q_w2a8_m16`, `gemm_nt_q_w2a8_tiled`, -`gemm_nt_q_fp8a8_tiled`, `logits_gemm_bf16` — and each declares the `relayout` that -produces the form it names; `r3d_selftest.cpp` enforces the pair by name (a `layout` -without a `relayout` fails the table, a `relayout` without a `layout` fails it, any -`unrelayout` fails it). +**No vector f64.** Consumer RDNA3 runs doubles at 1:64, in practice soft-float, which sets the +transcendental policy per unit: the sampler keeps the reference's `(float)exp((double)x)`, +because a draw must reproduce; attention cannot afford it and uses a polynomial; the gated MLP uses +`expf` into a bf16 narrowing. -The starting rule — *no layout hooks in this library* — came from the dot path: a dot2 -GEMM reads a weight in the order it is stored, so there is nothing to repack. It -stands in every part that carries weight: **no plugin-private dtype, no repack into a -format of this plugin's invention, no container format changed from inside a kernel -library.** +**The lane ops are libr4d's:** `update_dpp` (xor and shr controls), `permlanex16`, `readlane`, +`readfirstlane`, `ballot`, `ds_bpermute`, `v_perm_b32`, `exp2f`, `rcpf`, `s_barrier`, +`sched_group_barrier`. DPP16 and `v_permlanex16` exist from RDNA1 on, and the encodings in +[`r3d_common.h`](r3d_common.h) are the ones libr4d verified on hardware. -What it got wrong is that the container's quantiser already stores weights where a -kernel cannot read them in place — codes and per-block scales as separate planes, -`fp8_e4m3 * bf16[128x128]` for a head — and the engine's answer is its own canonical -form: planes joined behind one operand, `rad.planes`, sized by `rad_planes_plan`, -written by `rad_planes_relayout`. A row that reads such a weight *describes* that form -and *produces* it; the engine does the work at load, in the loader's pool behind the -container read. Three laws came out of it. +**No transposed loads, no VOPD.** There is no `global_load_tr_b128` (RDNA4) and +`ds_read_b64_tr_b16` is rejected by this assembler, so transposes are done in registers. VOPD is +RDNA4; the tree's `-mllvm=-amdgpu-enable-vopd=false` comes from the LLVM version. LLVM +single-buffers LDS and drains before a dependent read unless told otherwise, and without a matrix +unit there is nothing to overlap a load with, so the plain barrier is the one needed. -* **A hook that answers is a promise** — the ABI says so: *RAD_OK: out describes the - stored form, and `relayout` will produce it*. With `relayout = nullptr` the model - does not load: `could not produce '…' (rad.planes) from fp8_e4m3*bf16[128x128]: - unsupported`. -* **A weight is stored once, so the row that got there first owns its plan.** The - engine arbitrates across every row of every band reading the weight, at declare: *is - wanted in two stored forms: 'rad.planes' by row A and '(as it is)' by row B. A - weight is stored once.* A second row gets the same answer by *calling the first - row's hook*, and its kernel reads the container the builder settled — by role, not - by the arrangement it declared. -* **`RAD_E_UNSUPPORTED` means stored as is**, the only kind of weight the mapped tier - can read where it lies — the lever the placement ladder runs on. A joined weight is - a resident weight, and a band that resolves to the host drags its whole layer group - onto the tier that reads the container in place, where a norm weight needing - conversion at load refuses to live. Hence the quantised GEMM at prefill heights as a - startup failure and not a slow band: no device row for `gemm_nt_q` above the decode - band → bands resolve to host kernels → the layer's weights stay in the container's - mapping → its norms group with them → the mapped tier is asked for a widening it - cannot perform. -* **A container arrives as a tensor of `rank = 1`, `shape[0] = bytes`.** That is the - joined form's stored shape — a byte count, from `rad_planes_layout` — and not a - plane. A consumer that reads it as a plane measures a scale plane's rows against - `ceil(N/group)` and refuses with a message about a geometry the operand never had: - the fp8a8 tiled row refused the sibling decode row's settled spelling (codes plain - on `b`, scale joined behind `b_scale`) with `E_SHAPE` from a tensor geometry test on - every case of one probe and at `n_b = 0`, and with `E_STRIDE` at one band — two - codes, one expression, both naming rows and columns of a thing that was never a - plane. Decode by role, on the host, where the header lives: the tag, the entry table - and the stored dtype (the first plane's) are host-readable, so the shim reads them - once per call and hands the kernel three device pointers. In that form the row - computed the reference's answer on **192 cases, 192 agreements, worst `rel_l2` - 1.362e-03** — and the same fix carried the m16/tiled crossing to 1018 cases with no - numeric divergence, where before it the crossing never reached the joined spelling. -* **A `zero` plane is refused as `E_DTYPE`, not folded.** `w2a8` is the only scheme - here with an activation zero point, and its producer is a row of this library. - `fp8a8`'s quantiser is symmetric, so the reference's fp8a8 arm refuses `a_sum` - outright (`ref_gemm.cpp:395`, `RAD_E_UNSUPPORTED` — that arm has no grid to sum a - zero over), the shape hook skips the operand, and every served band omits it. A row - that folded a zero point would be inventing a number the oracle has no law for, so - the refusal names its own fix instead: the row that computes zeros is - `r3d_gemm_nt_q_w2a8`. +## Stored weights: layout hooks and their writers -Same law, gains: read them in the dtype the checkpoint stores (a 2048-element norm -gain in f32 is 8.00 KiB), because the row's `dtype` band names the activation, never -the weight — the fused norm's kernel grew the plain norm's `WDT` leg, a dtype -parameter on the gain, rather than ask the checkpoint to be rewritten. +Four rows declare a `layout`: `gemm_nt_q_w2a8_m16`, `gemm_nt_q_w2a8_tiled`, +`gemm_nt_q_fp8a8_tiled` and `logits_gemm_bf16`. Each also declares the `relayout` that produces +the form it names, and `r3d_selftest.cpp` enforces the pair by name: a `layout` without a +`relayout`, a `relayout` without a `layout`, or any `unrelayout` fails the table. -## The request: a plan's vocabulary is not its contents +A dot2 GEMM reads a weight in the order it is stored, so libr3d never repacks: **no +plugin-private dtype, no repack into a format of this plugin's invention, no container format +changed from inside a kernel library.** The hooks exist because the container's quantiser itself +stores some weights as separate planes a kernel cannot read in place, codes and per-block scales +(for a head, `fp8_e4m3 * bf16[128x128]`). The engine's canonical form for those is the planes +joined behind one operand, `rad.planes`, sized by `rad_planes_plan` and written by +`rad_planes_relayout`. A row that reads such a weight describes that form and produces it; the +engine does the work at load, in the loader's pool behind the container read. The rules: -A clean graph dump means every band has a row; it does not mean a request runs. At -request time the engine hands the shim the *contents* — descriptors, strides, an -arena, a step's shape — and the refusals between a clean dump and a first generated -token were one mistake: code that read the band's vocabulary as if it were the plan's -contents. Laws of the ABI, not of any one model. +* **A hook that answers is a promise.** The ABI states: *RAD_OK: out describes the stored form, + and `relayout` will produce it*. With `relayout = nullptr` the model does not load + (`could not produce '...' (rad.planes) from fp8_e4m3*bf16[128x128]: unsupported`). +* **A weight is stored once, so the first row to claim it owns its plan.** The engine arbitrates + across every row of every band that reads the weight, at declare (*is wanted in two stored + forms: 'rad.planes' by row A and '(as it is)' by row B. A weight is stored once.*). A second row + gets the same answer by calling the first row's hook, and its kernel reads the stored container + by role, not by the arrangement it declared. +* **`RAD_E_UNSUPPORTED` means stored as is**, the only kind of weight the mapped tier can read in + place, and the lever the placement ladder works with. A joined weight is a resident weight. A + band that resolves to the host pulls its whole layer group onto the tier that reads the + container in place, where a norm weight that needs conversion at load cannot live. A missing + device row for `gemm_nt_q` above the decode band therefore shows up as a startup failure, not a + slow band: the bands resolve to host kernels, the layer's weights stay in the container's + mapping, its norms group with them, and the mapped tier is asked for a widening it cannot do. +* **A container arrives as a tensor of `rank = 1`, `shape[0] = bytes`.** That is the joined form's + stored shape (a byte count, from `rad_planes_layout`), not a plane. A consumer that reads it as a + plane measures a scale plane's rows against `ceil(N/group)` and refuses with a geometry the + operand never had. Decode it by role on the host, where the header lives: the tag, the entry + table and the stored dtype (the first plane's) are host-readable, so the shim reads them once per + call and hands the kernel device pointers. +* **A `zero` plane is refused as `E_DTYPE`, not folded.** `w2a8` is the only scheme here with an + activation zero point, and its consumer is a row of this library (`r3d_gemm_nt_q_w2a8`). + `fp8a8`'s quantiser is symmetric: the reference's fp8a8 arm refuses `a_sum` + (`RAD_E_UNSUPPORTED`), the shape hook skips the operand, and every served band omits it. A row + that folded a zero point would compute a number the oracle has no law for. -**A band's `dtype` is the activation's; a weight's dtype comes off the operand.** The -key names the step's activations, and the head of a `dtype=bf16` band can be E4M3 -codes with a bf16 scale per 128×128 block. A shim that trusts the key refuses the -request the plan is making. +Gains follow the same rule: they are read in the dtype the checkpoint stores (a 2048-element norm +gain in f32 is 8 KiB), because a row's `dtype` band names the activation, never the weight. The +fused norm's kernel takes the gain's dtype as a parameter (`WDT`), as the plain norm does. -**An optional operand with no bytes is absent.** Optional operands arrive as -descriptors with a null `data` when the graph bound none, so the test is `r3d_has(t)` -— `t && t->data`; a bare `if (t)` is the bug: dtype-checking a descriptor with no -bytes answers `E_DTYPE` to a band whose dtype was fine, which is what -`rmsnorm_quant_fp8` did at M=5 with an unbound `out_bf16`. +## Request-time rules: a plan's vocabulary is not its contents -**A sizing hook runs at declare, where a descriptor has a shape and no bytes** (`data` -is null for every tensor in the plan). A scratch hook opening `if (!a->t[0].data) -return 0` answers 0 for the whole run, the engine allocates an arena of 0 bytes, the -split pass finds nowhere to write — a request-time `scratch buffer absent or too -small` from a hook that looked healthy. Size off the shape (`rad_tensor_numel`) or the -parameters, as the GEMM hook does. Absence at launch means the plan asked for nothing; -absence at declare means the bytes come later. +A clean graph dump means every band has a row; it does not mean a request runs. At request time +the engine hands the shim the contents (descriptors, strides, an arena, a step's shape), and a shim +must not read the band's vocabulary as if it were those contents. These are rules of the ABI, not +of any one model. -**A band key is a bound, not the step's value.** A plan's geometry line reads `at M=30 -[band M<=2048] geometry {N=2560 K=2048 group=128 M=2048}`: the geometry's `M` is the -**ceiling the band was built for**; the height of *this* step is what the operands -say. A GEMM asking a 30-row activation for 2048 rows, and a sampler computing `rows = -(M_hint > 0) ? *M_hint : cirows` before asking the plane to be that tall, refuse every -request that asks for logprobs. Geometry comes off the operand — `nel / N`, `qnel / -n`, `r3d_rows_pitch(y, N, &M)` — and the key stays the ceiling promised not to be -exceeded. **Exceeding it is a refusal, and it prints both numbers.** +**A band's `dtype` is the activation's; a weight's dtype comes from the operand.** The head of a +`dtype=bf16` band can be E4M3 codes with a bf16 scale per 128x128 block. A shim that trusts the +key refuses the request the plan is making. -**The engine sizes vector operands to the step, so their geometry comes from the -tensor.** The attention shim required `numel(BT) >= n_seq * max_blocks` with -`max_blocks` from the band's `max_ctx` — a table as wide as the cache — while a -five-token prompt with nothing behind it carries `[n_seq, 1]`: one block, because one -block is what the sequence has. The reference takes geometry from the tensor -(`max_blocks` from `bt->shape[last]`, row pitch from `stride[rank-2]`, column stride -from `stride[rank-1]`, `jend = min(ctx, max_blocks * block_size)`), so a context -longer than the table has columns is truncated — by the oracle as much as by us, which -makes it truncation, not corruption. The shim derives all three from the operand and -checks the one thing required: that the last reachable index `(n_seq-1)*bt_rs + -(bt_cols-1)*bt_cs + 1` is inside the plane. Two conflated counts are named apart: +**An optional operand with no bytes is absent.** Optional operands arrive as descriptors with a +null `data` when the graph bound none, so the test is `r3d_has(t)` (`t && t->data`). A bare +`if (t)` dtype-checks a descriptor with no bytes and answers `E_DTYPE` to a band whose dtype is +fine. + +**A sizing hook runs at declare, where a descriptor has a shape and no bytes** (`data` is null for +every tensor in the plan). A scratch hook that returns 0 when `a->t[0].data` is null answers 0 for +the whole run, the engine allocates a zero-byte arena, and the split pass fails at request time +with `scratch buffer absent or too small`. Size from the shape (`rad_tensor_numel`) or the +parameters, as the GEMM hook does. Absence at launch means the plan asked for nothing; absence at +declare means the bytes come later. + +**A band key is a bound, not the step's value.** A plan's geometry line reads `at M=30 [band +M<=2048] geometry {N=2560 K=2048 group=128 M=2048}`: the geometry's `M` is the ceiling the band was +built for, and the height of this step is what the operands say. Geometry comes from the operand +(`nel / N`, `qnel / n`, `r3d_rows_pitch(y, N, &M)`); the key stays the ceiling, and exceeding it is +a refusal that prints both numbers. + +**The engine sizes vector operands to the step, so their geometry comes from the tensor.** A +five-token prompt with nothing behind it carries a block table of `[n_seq, 1]`, not one as wide as +the cache. The reference takes the geometry from the tensor (`max_blocks` from `bt->shape[last]`, +row pitch from `stride[rank-2]`, column stride from `stride[rank-1]`, +`jend = min(ctx, max_blocks * block_size)`), so a context longer than the table's columns is +truncated by the oracle and the kernel alike. The attention shim derives all three from the +operand and checks the one thing required: that the last reachable index +`(n_seq-1)*bt_rs + (bt_cols-1)*bt_cs + 1` lies inside the plane. Two counts are kept apart: `cache_blocks` bounds a slot's byte offset, `bt_cols` bounds the walk. -**Serve the unoptimised form when the optimisation has no room.** Split-KV's halving -loop said "down to 1, which needs none" in its comment and returned `RAD_E_SCRATCH` at -1. One slice is the whole walk in one block, the same keys in the same order: not a -degraded answer, the answer without the split. Refusing a band because an optimisation -has no arena tells the user to go away. +**Serve the unoptimised form when the optimisation has no room.** One split-KV slice is the whole +walk in one block, the same keys in the same order, so the launcher lowers `splits` to what the +arena holds, down to 1, instead of refusing. -**A refusal carries a code, names its own fix, and prints the descriptor it saw.** -`R3D_NO(code)` prints the site under `RAD_R3D_TRACE=1`; `R3D_STR` prints the two -numbers a stride test compared; `r3d_trace_desc` prints dtype, rank, shape and strides -— in **elements**, what the engine binds and what a reader reproducing a refusal -needs. +**A refusal carries a code, names its fix, and prints what it saw.** `R3D_NO(code)` prints the +site under `RAD_R3D_TRACE=1`; `R3D_STR` prints the two numbers a stride test compared; +`r3d_trace_desc` prints dtype, rank, shape and strides in elements, as the engine binds them. -**The ragged query batch is a descriptor, not a second kernel.** `cu_seqlens`, when -present, is `[n_seq + 1]` of i32, and `cu[0] == 0`, monotonicity, and `cu[n_seq] ==` -the plane's row count are the *description's* promises — the served engine keeps them, -and no row may rely on them. `seq_of` walks `while (s + 1 < n && cu[s+1] <= row) ++s`, -so rows below `cu[0]` are not excluded: they land in sequence 0 with a negative index -into its query, and the reference computes them at `pos = ctx - qlen + i`, pushed -`cu[0]` keys into the past. Nothing in the oracle says the plane starts where the -descriptor starts. So `q_len` is *per-sequence* (`q_len = cus ? 0 : rows / n_seq`), the -total row count is the plane's, and a ragged batch has no `q_len` at all. One grid -covers it because the clamp a tile needs is per sequence; the rectangular case is the -descriptor's absence (`len_s = q_len`, `start_s = s * q_len`). One mapping, one mask, -one walk, one store, both forms. +**The ragged query batch is a descriptor, not a second kernel.** `cu_seqlens`, when present, is +`[n_seq + 1]` i32. `cu[0] == 0`, monotonicity and `cu[n_seq] ==` the plane's row count are +promises of the description that the engine keeps, but no row may rely on them. The reference's +`seq_of` walks `while (s + 1 < n && cu[s+1] <= row) ++s`, so rows below `cu[0]` are not excluded: +they land in sequence 0 with a negative index into its query, and the reference computes them at +`pos = ctx - qlen + i`, `cu[0]` keys into the past. So `q_len` is per sequence +(`q_len = cus ? 0 : rows / n_seq`), the total row count is the plane's, and a ragged batch has no +`q_len`. One grid covers both forms because the clamp a tile needs is per sequence; the +rectangular case is the descriptor's absence (`len_s = q_len`, `start_s = s * q_len`). **A descriptor carries two row counts, and the store is bounded by the second.** -`len = cu[s+1] - cu[s]` is what the positions count from; `span = cu[s+1] - start`, -with `start = (s == 0 && cu[0] > 0) ? 0 : cu[s]`, is how many rows the sequence's tiles -carry, because the grid covers the plane from 0. The tile count comes from the length; -the store bound comes from the span. Bounding the store by the length drops the last -`cu[0]` rows of an in-bounds plane, silently, with status 0 from both rows: 20 rows, -`cu = [3, 17]`, one sequence, ctx 24 left 6144 items — 3 rows × 2048 — at the `0x7fc0` -pre-fill while the 17 rows it wrote agreed to bf16 rounding (max abs 1.22e-04), and the -engine read its own `out` buffer back as attention output. The plane's `rel_l2` is -`nan` in that case only because the untouched slots are bf16 NaN, which is exactly why -a finite-output check passes it and a whole-plane read-back does not. Every other -served shape agreed — 233 cases — which is what makes `cu[0] > 0` the descriptor's own -law and not a geometry note: the reference reads the descriptor, the fixture never -draws one, and the ragged oracle builds its prefix sum from 0, so the shape -that broke the agreement is a shape no oracle upstream could generate. +`len = cu[s+1] - cu[s]` is what positions count from; `span = cu[s+1] - start`, with +`start = (s == 0 && cu[0] > 0) ? 0 : cu[s]`, is how many rows the sequence's tiles carry, because +the grid covers the plane from row 0. The tile count comes from the length and the store bound +from the span. Bounding the store by the length silently drops the last `cu[0]` rows of an +in-bounds plane with status 0, which only a whole-plane read-back after a NaN pre-fill detects +(see [Numerics](#numerics)); the fixture never draws `cu[0] > 0`. ## Numerics -f32 accumulation, IEEE round-to-nearest-even narrowing, subnormals kept, no -reassociation; the oracle is `libref`. +f32 accumulation, IEEE round-to-nearest-even narrowing, subnormals kept, no reassociation; the +oracle is `libref`. -**`-ffp-contract=off` on every HIP source** (`rad_hipify`, library-wide): a fused -product-sum rounds once where the reference rounds twice, and a kernel diverging by a -rounding the reference does not make will not match it; the flag also keeps the -instruction counts quoted in kernel comments true. +**`-ffp-contract=off` on every HIP source** (`rad_hipify`, library-wide): a fused product-sum +rounds once where the reference rounds twice, so a contracted kernel cannot match it. The flag +also keeps the instruction counts quoted in kernel comments true. -**Accumulation order is part of the contract:** `v_dot2acc_f32_f16` folds two products -into the accumulator and rounds once, so the match is not bit-exact and cannot be — -under an ulp a pair, a random walk of ~`sqrt(K/2)` ulps over a K-long dot, a -thousandth of the bf16 a store narrows to and inside what `rad-kbench` measures. The -*order* must be the reference's: k ascending, one accumulator per output, no -reassociation across lanes, with lane maps built so no lane ever has to break it (a -group spanning two lanes folds in one `shfl_xor`, in integers, before any float work). +**Accumulation order is part of the contract.** `v_dot2acc_f32_f16` folds two products into the +accumulator and rounds once, so the match cannot be bit-exact: under an ulp per pair, a random walk +of about `sqrt(K/2)` ulps over a K-long dot, about a thousandth of the bf16 a store narrows to and +inside what `rad-kbench` measures. The order must be the reference's: k ascending, one accumulator +per output, no reassociation across lanes. Lane maps are built so no lane has to break it (a group +spanning two lanes folds with one `shfl_xor`, in integers, before any float work). -**Reductions are the reference's tree:** a wave butterfly (`dpp_xor` at 16, 8, 4, 2, -1; the halves of a 64-lane row read through `permlanex16` first where the reference -sums a whole row), then wave partials in wave order — the same bracketing at any -thread count. Activations, rope and quantisation are the reference's formulas in its -order (`1/(1+exp(-x))`, `0.5*x*(1+erf(x*0.70710678118654752))`, amax/127 with ties to -even), from `libref/ref_common.h`. +**Reductions use the reference's tree:** a wave butterfly (`dpp_xor` at 16, 8, 4, 2, 1; the halves +of a 64-lane row read through `permlanex16` first where the reference sums a whole row), then wave +partials in wave order, which gives the same bracketing at any thread count. Activations, rope and +quantisation are the reference's formulas in its order (`1/(1+exp(-x))`, +`0.5*x*(1+erf(x*0.70710678118654752))`, amax/127 with ties to even), from `libref/ref_common.h`. -**The accepted divergences, and the family reason for each** — where a row is checked -against a law it implements rather than against libref's bytes, each named in the unit -that ships it. +**Accepted divergences.** Where a row is checked against the law it implements rather than +libref's bytes, the unit that ships it names the divergence: -| divergence | why, and what it costs | +| divergence | reason and cost | | --- | --- | -| an index at or past an operand's row count takes the padding path (zero row, no store); `kv_store` drops a slot past the cache's span | the reference validates index arrays on the host and refuses, and `kv_store` refuses such a slot with `E_SHAPE` before it starts; a kernel cannot, so the bound travels as an argument (`slot_max`). A slot lost, not a step lost. A negative index is padding too and is not clamped to zero, which would duplicate row 0 across every padding row | -| rope divides the position by `scale` and evaluates the frequency ladder in double | `scale` is the position scale (the multiplier on a rotated pair is YaRN's magnitude, and the shims refuse YaRN, so it is 1). `powf` puts the reciprocal a ulp off, and at position 262144 a ulp of a frequency is a hundredth of a radian — the one place in that kernel where f32 is not enough | -| `block_sum`'s tree | wave butterfly, then partials in wave order: the reference's bracketing at any thread count, and why kernel and reference agree at 256 threads and at 64 | -| `sample_logprobs` keeps a NaN out of the max and into the sum; `sample_mask` skips a row whose `mask_row` is negative | maxima are a strict `>`, `std::max`'s law, so a NaN is never adopted; the sum propagates it, because the reference's `exp(NaN - mx)` is NaN and is added. The k-list is per lane in the reference's order (descending by value, ties to the lower column), merged in the same butterfly; the pool is 64 deep and a bigger k is refused, not truncated. The mask bound is the reference's own test (`mask_row` is `-1` for no mask), read off the operand, not off M | -| the sampler's `exp` and `log` are `double` calls narrowed once | the draws must reproduce: the device's `(float)exp((double)x)` is bit-identical to the host's over 2^20 points in [-100, 100] (0 differ) where `expf` differs by 1 ulp in 5.7% of them. Consumer RDNA3 is 1:64 on doubles, so this is the slow path by law: at the band, one read of the logits plane is 3.6 ms, a read that also sums double exponentials 30.4 ms, this kernel 38.9 ms. The candidate set is where it is affordable (1024 exponentials a row); attention is not | -| attention's `exp` is a degree-8 polynomial; the gated MLP's sigmoid is `expf` | no vector f64, and prefill is tens of millions of exponentials a layer. Against `(float)exp((double)x)` over 1.31M points of [-100, 0]: every point within one f32 ulp, 76.1% bit-identical (the device `expf` is 94.0% identical and no better in ulps), `exp(0)` exactly 1 — the only place an explicit `__fmaf_rn` is allowed, because what must be reproduced is a *function*. The MLP feeds 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 | -| `w2a8` lands with a one-ulp tail | the pair-dot carries ~22 bits on integers: 0.1–0.2% of outputs one bf16 ulp off, `rel_l2` 5.0e-3 at the band, nothing further. The row's prose says so, because the law it transcribes is exact integers and the row reads like a bit-exact one | -| the fp8 folds land in f16, not f32 | the tile is f16, so a scale enters as a f16 multiply at staging — one rounding per staged value, through `v_mul_f16`. Against the reference's exact dequantise law: `rel_l2` 2.77e-04, half an f16 ulp, 250× finer than an E4M3 code's quantum (2^-4); against a model of the fold itself: 4.5e-06, the dot's fused rounding. At a bf16 output the store's ulp (3.9e-3) binds, not the fold's: 83% of outputs bit-exact, 99.93% within fold plus one store ulp | -| the bf16 GEMM's long-K tail | the pair is folded into the accumulator by one rounding, so ~0.3% of a long-K output lands one bf16 store ulp from the reference's and none is further: 99.93% bit-exact at the 512-column twin, 100% within two ulps | +| an index at or past an operand's row count takes the padding path (zero row, no store); `kv_store` drops a slot past the cache's span | the reference validates index arrays on the host and refuses, and `kv_store` refuses such a slot with `E_SHAPE`; a kernel cannot, so the bound travels as an argument (`slot_max`) and a slot is lost rather than a step. A negative index is padding too and is not clamped to zero, which would duplicate row 0 across every padding row | +| rope divides the position by `scale` and evaluates the frequency ladder in double | `scale` is the position scale (the multiplier on a rotated pair is YaRN's magnitude; the shims refuse YaRN, so it is 1). `powf` leaves the reciprocal an ulp off, and at position 262144 an ulp of a frequency is a hundredth of a radian, the one place in that kernel where f32 is not enough | +| `block_sum`'s tree | wave butterfly, then partials in wave order: the reference's bracketing at any thread count, so kernel and reference agree at 256 threads and at 64 | +| `sample_logprobs` keeps a NaN out of the max and in the sum; `sample_mask` skips a row whose `mask_row` is negative | maxima are a strict `>` (`std::max`'s law), so a NaN is never adopted; the sum propagates it, because the reference's `exp(NaN - mx)` is NaN and is added. The k-list is per lane in the reference's order (descending by value, ties to the lower column), merged in the same butterfly; the pool is 64 deep and a larger k is refused, not truncated. The mask bound is the reference's test (`mask_row` is `-1` for no mask), read from the operand, not from M | +| the sampler's `exp` and `log` are `double` calls narrowed once | draws must reproduce: the device's `(float)exp((double)x)` is bit-identical to the host's over 2^20 points in [-100, 100], where `expf` differs by 1 ulp on 5.7% of them. At 1:64 doubles this is the slow path (one read of the band's logits plane takes 3.6 ms, a read that also sums double exponentials 30.4 ms), affordable on the candidate set (1024 exponentials per row) but not in attention | +| attention's `exp` is a degree-8 polynomial; the gated MLP's sigmoid uses `expf` | prefill needs tens of millions of exponentials per layer. Against `(float)exp((double)x)` over 1.31M points of [-100, 0], every point is within one f32 ulp and 76.1% are bit-identical (device `expf`: 94.0%, no better in ulps), and `exp(0)` is exactly 1. The polynomial is the only place an explicit `__fmaf_rn` is allowed, because what must be reproduced is a function. The MLP's sigmoid feeds a bf16 narrowing (ulp 2^-8 against `expf`'s ~1e-7), so the bf16 differs only on a tie | +| `w2a8` has a one-ulp tail | the pair-dot carries about 22 bits on integers: 0.1-0.2% of outputs land one bf16 ulp off, `rel_l2` 5.0e-3 at the band, nothing further. The row's text says so, because the law it transcribes is exact integers | +| the fp8 scale folds land in f16, not f32 | the tile is f16, so a scale enters as an f16 multiply at staging, one `v_mul_f16` rounding per staged value. Against the reference's exact dequantise law: `rel_l2` 2.77e-04, half an f16 ulp, 250x finer than an E4M3 code's quantum (2^-4). At a bf16 output the store's ulp (3.9e-3) dominates: 83% of outputs bit-exact, 99.93% within the fold plus one store ulp | +| the bf16 GEMM's long-K tail | each pair is folded into the accumulator with one rounding, so about 0.3% of a long-K output lands one bf16 ulp from the reference's and none further: 99.93% bit-exact at the 512-column case, 100% within two ulps | -**How a plane is proved to have been written.** Every output plane in the comparison -runs is pre-filled with the dtype's NaN (`0x7fc0` for bf16 and f16) and read back whole: a -kernel returning `RAD_OK` without launching leaves the caller's bytes behind, and the -caller's zeros are finite, so only a NaN fill says the row ran. A clean case prints -`untouched 0`, `nonfinite 0`, no output beyond six ulps of the law the kernel -implements, and a whole-plane `rel_l2` inside what the fusion costs — `2 · sqrt(K/2)` -output ulps, with room for the fixture's spread. +**Proving a plane was written.** Every output plane in a comparison run is pre-filled with the +dtype's NaN (`0x7fc0` for bf16 and f16) and read back whole. A kernel that returns `RAD_OK` +without launching leaves the caller's bytes, and zeros are finite, so only a NaN fill shows the row +ran. A clean case reports `untouched 0` and `nonfinite 0`, no output beyond six ulps of the law the +kernel implements, and a whole-plane `rel_l2` within what the fusion costs (`2 * sqrt(K/2)` output +ulps, with room for the fixture's spread). Two planes (an int8 row-sum padded to a 16-row grid, a +quantiser's per-group statistics) legitimately keep the fill in their padding, because the row +writes only the rows it was given; the report names that padding, and a NaN anywhere else is a +silent no-op. -Two named planes (an int8 row-sum padded to a 16-row grid, a quantiser's per-group -statistics) keep the fill in their padding legitimately, because the row writes only -the rows it was given: the report says *pad NaN of N, the reference's grid, not the -row's work*, and a NaN anywhere else is the silent no-op the fill exists to find. - -Infinities are contract, not corruption, in the sampler and row top-k: a dropped -candidate, a narrowing stage's drop, and an unfilled `row_topk` slot are all `-inf`. +Infinities are part of the contract in the sampler and row top-k: a dropped candidate, a +narrowing stage's drop and an unfilled `row_topk` slot are all `-inf`. ## Testing -[`r3d_selftest.cpp`](r3d_selftest.cpp) dlopens the `.so` — so an undefined symbol is -its failure, not a link failure — and runs five gates. +[`r3d_selftest.cpp`](r3d_selftest.cpp) dlopens the `.so`, so an undefined symbol is its failure +rather than a link failure, and runs five gates: -**Codecs** against the ABI's host versions in `rad_plugin.h`: bf16 and f16 over all -65536 patterns both directions; e4m3 over all 256 codes plus the encoder's saturating, -subnormal, signed-zero and NaN cases; int8 against `rad_round_even_sat` over every -tie; the widenings over the range they are exact in; the bf16 pair packer against -`rad_f32_to_bf16`. The codecs are this library's own arithmetic, so they belong to the -tests: kbench compares whole ops, where a codec's disagreement is a diffuse -percentage. - -**The table:** unique names, a launch on every row, an `init` with a `fini`, the -device domain, prose on every row, a schema for every `op`, every constraint key a -declared parameter, a tunable's default among its ascending values, the layout pair -rule. - -**Band reachability:** every constraint a row puts on an optional parameter, named — -not an error, it is how a row says *I serve the form that states the parameter*, but a -decision, and a row whose author did not make it silently will not serve. - -**The schemas against `libref.so` beside the plugin**, with the loader's own -comparison (parameter count, keys, types, requiredness; operand count, roles, -optionality): one role mistyped and the loader refuses the whole library, every row -with it, one line in a log. - -**Every row, run** on a card — buffers from the row's own `opd_shape`, filled per its -fill code, outputs checked whole, one child process per row so a GPU page fault names -its row and the run continues. No card is not a failure: the static phase is a third -of what it checks, and a build machine runs it without one. +* **Codecs** against the ABI's host versions in `rad_plugin.h`: bf16 and f16 over all 65536 + patterns in both directions; e4m3 over all 256 codes plus the encoder's saturating, subnormal, + signed-zero and NaN cases; int8 against `rad_round_even_sat` over every tie; the widenings over + the range in which they are exact; the bf16 pair packer against `rad_f32_to_bf16`. kbench compares + whole ops, where a codec disagreement shows up only as a diffuse percentage, so the codecs are + tested here. +* **The table:** unique names, a launch on every row, an `init` with a `fini`, the device domain, + prose on every row, a schema for every `op`, every constraint key a declared parameter, each + tunable's default among its ascending values, and the layout pair rule. +* **Band reachability:** every constraint a row puts on an optional parameter is listed. It is not + an error (it is how a row says it serves only the form that states the parameter), but it must be + a deliberate choice. +* **The schemas against `libref.so`** beside the plugin, with the loader's own comparison + (parameter count, keys, types, requiredness; operand count, roles, optionality). One mistyped + role makes the loader refuse the whole library. +* **Every row, run** on a card: buffers from the row's own `opd_shape`, filled per its fill code, + outputs checked whole, one child process per row so a GPU page fault names its row and the run + continues. Without a card the static phases still run, so a build machine runs them. The numerical authority is `rad-kbench`, replaying a recorded fixture against libref: @@ -538,25 +442,17 @@ The numerical authority is `rad-kbench`, replaying a recorded fixture against li rad-kbench --home "$RADIANCE_HOME" --kernels libref:libr3d ``` -`--all-rows` runs every row whose constraints hold, not only the one selection picks — -how a tunable arm the tuned defaults never reach gets measured. `--coverage DIR ---coverage-write` records the rows a fixture reaches, so a row that stops being -reachable fails the run; the census is -[`kbench_rows_kernels_libr3d.txt`](../data/kbench_rows/kbench_rows_kernels_libr3d.txt), -written by the same run, so census and numbers cannot disagree. +`--all-rows` runs every row whose constraints hold, not only the one selection picks, which is how +tunable arms the tuned defaults never reach get measured. `--coverage DIR --coverage-write` +records the rows a fixture reaches, so a row that stops being reachable fails the run; the census +is [`kbench_rows_kernels_libr3d.txt`](../data/kbench_rows/kbench_rows_kernels_libr3d.txt), written +by the same run. -**A fixture covers a checkpoint, not the library.** A fixture is generated from the -bands a recorded checkpoint issues, so a row can be shipped, correct, and absent from -its census: the packed 2-bit grid serves the head bands of the checkpoint it is served -on, and the base fixture has no `w2a8` band above M=16. Its gate: clean cases on both -stored arrangements, every refusal refused as stated, the writer's codes, scale and -zero regions byte-identical to the fixture's including a 73,113,920-byte head operand — -plus the fp8a8 row against the same file, 36 of 36 clean. - -A row should say which of the two vouches for it. - -The rule has a tool: `rad-kbench` records a fixture **from a model**, reading only the -tables, then widens every case into the constraints of every row under test. +**A fixture covers a checkpoint, not the library.** A fixture is generated from the bands a +recorded checkpoint issues, so a row can be correct and absent from the census: the base fixture +has no `w2a8` band above M=16. Record one fixture per served checkpoint; `rad-kbench` records one +from a model (reading only the tables) and widens every case into the constraints of every row +under test: ``` rad-kbench -m /path/to/served.rad --record "$RADIANCE_HOME/kb-served.rkb" @@ -566,161 +462,98 @@ rad-kbench --fixture "$RADIANCE_HOME/kbrows.rkb" --kernels libref:libr3d --all-r --no-cache --max-cases 2 --max-bytes 1024 --seed 42 ``` -Line 1 answers the served checkpoint's own bands against the reference on the -container's real weight bytes: **975 checked, 975 passed, 0 diverged, worst `rel_l2` -1.605e-03** — the sentence worth keeping in a log is *every resolved kernel agrees -with libref on this container's bytes*. +The first command checks the served checkpoint's own bands against the reference on the +container's real weight bytes. The second and third take each case to the M and `q_len` values no +container selects, the edges of each row's constraints where floors and ceilings are exercised. +Rows the checkpoint's graph never uses report `no recorded case of its op`. -Lines 2–3 take each case into the M and `q_len` no container selects, the edges of a -row's constraints where its floors and ceilings get exercised: 45 cases reach 45 rows, -90 checked, 90 passed, 0 diverged, worst 9.684e-04. Rows a checkpoint's -graph never uses report `no recorded case of its op`. **Record one fixture per -checkpoint you serve:** a row green on a 27B fp8 fixture and untested at the shape -your served model walks is covered by a checkpoint, not by you. +**Checks a tolerance cannot make.** A refactor is proved by the recorded decision lines being +bit-identical between the old and new builds (diffed with the timing column blanked). A change to +an index, a scale plane or a row mapping is proved bit for bit against the same fixture: a fixture +whose scales are statistically alike cannot tell a row-indexing error from rounding (with uniform +random data the amax of 128 samples is concentrated, every block's scale rounds to the same bf16, +and reading group 0's scale for group 7 changes nothing), so paired runs spread their activations +by orders of magnitude one group at a time. The comparison harness carries a `selfcheck` control +that hands the scorer a plane rebuilt under a known misreading and requires a divergent verdict +naming it. -Against that base fixture, on a 16-CU RDNA3 part with 8 GiB, built out of tree as -above: **1153 checked, 1153 passed, 0 failed, 24 skipped for the case's own memory -budget, 0 diverged, 0 capped, worst `rel_l2` 1.362e-03** against a tolerance of 8e-03 -— the GEMMs' long-K accumulations and the fused norm-quantiser's E4M3 step. 436 cases -ran inside guarded allocations and 0 wrote outside one: the whole-plane write law, -tested on the fixture and in the hand-rolled comparisons. +The gates test a built binary, not the commit: build a clean export of the commit on the target +before trusting the gates for that commit. -**Two proofs a tolerance cannot give.** A refactor is proved by the recorded decision -lines **bit-identical**: the same run against the build of HEAD and the build of the new -file, diffed with the timing column blanked (`6143/6144`, `2047/2048`, -`3667126/3670016`, -`4193353/4194304`). A change to an index, a scale plane or a row mapping is proved -**bit-for-bit against the same fixture**, in a mode whose whole job is that pair test: -feeding a per-row scale plane as the first M floats of the `[M][groups]` array -*passed*, because those floats are row 0's slots, so row *m* read row *m/groups*' -scale, and on data drawn from one distribution the answer is a few percent off — -inside a `rel_l2` tolerance, outside the truth. A fixture whose scales are -statistically alike cannot tell a row-indexing error from rounding; the pair test can. +## The fp8a8 GEMM by row count -A test that cannot fail is not a test, so the comparison harness carries the control -that says so: a `selfcheck` run hands the scorer a plane rebuilt under a -known misreading and requires a DIVERGENT verdict naming it. - -The first full fixture run found three bugs a finite-output check cannot find: a cast -and a gather advancing the row base by the pitch in *bytes* where it is in *elements*; -raw bf16 patterns fed to `v_dot2acc_f32_f16` (0x3F80 is bf16 1.0 and f16 1.875); a -staging loop striding by the compile-time block size, correct at eight waves a block -and silently reading unwritten LDS at one. All three are in rows a fixture selects at -M > 1, none in a row the tuned defaults select. - -The gates prove a binary, not a tree. The box builds a *synced* tree, so a file that -never went to the box can reach the repo unmeasured, and one commit did exactly that: -it carried 567 lines of a unit's redesign where the built and measured file is 483, -and the added staged-arm and window paths use a constant — `kWin` — that is declared -nowhere, so the tree at tip did not compile while every gate above kept passing, -because not one of them builds from the commit. The check that catches it costs one -clean export: archive HEAD, build the archive on the target, and `build=0` is the only -answer. Two rules follow. A file enters the tree in the bytes that were measured — the -file an agent measured in its own snapshot is the file that lands, and its md5 is -quoted with its numbers. And unfinished work stays in a scratch directory, never in a -path a commit will sweep: the 567-line file is outside the repo now, with the constant -declared, for whoever finishes and measures it. - -## The fp8x8 GEMM by row count - -The band this family exists for is 42 layers plus a drafter at `group=128 -dtype=fp8a8` with a band ceiling of M=2048: N=12288 K=2048 ×44 (the gated MLP, two -halves of 6144), N=2560 K=2048 ×44 (qkv), N=2048 K=6144 ×44 (o-proj), N=2048 K=2048 -×44, and N=2048 K=10240 ×3 (the drafter). Three rows cover it by row count and the -boundary is read off the constraint tables, not off names: `gemm_nt_q_fp8a8_m16` +The bands this family targets are 42 layers plus a drafter at `group=128 dtype=fp8a8`, band +ceiling M=2048: N=12288 K=2048 x44 (the gated MLP, two halves of 6144), N=2560 K=2048 x44 (qkv), +N=2048 K=6144 x44 (o-proj), N=2048 K=2048 x44, and N=2048 K=10240 x3 (the drafter). Three rows +cover them by row count, with boundaries read from the constraint tables: `gemm_nt_q_fp8a8_m16` declares `C_LE("M", 16)`, so `gemm_nt_q_fp8a8_tiled` opens at `C_GE("M", 17)`, and -`gemm_nt_q_gated_fp8a8` runs M=1..64 with N even and K % 128. A floor reasoned from -prose, not from the sibling's *declared* ceiling, left 17..64 unserved and 209 -batched-decode bands on the host. The census in [Naming](#naming) is the index; the -measured floors and the placement law that prices them are in -[Measuring](#measuring). +`gemm_nt_q_gated_fp8a8` serves M=1..64 with N even and K % 128 == 0. -**The m16 row is a wave a run of columns.** One output element a lane, the weight -streamed past an activation kept in registers, no wave reduction — so a lane's chain is -the reference's chain and the row is bit-comparable at the store. Above 16 rows the same -operands want a 128×128 tile through LDS with 8×8 f32 accumulators a lane. The two -ranges are complements by construction, so neither row competes for the other's band, -and the m16 row is run against the tiled row on the same bytes, which is where a -boundary that moved would be seen. +**The m16 row** gives each lane one output element and streams the weight past an activation kept +in registers, with no wave reduction, so a lane's chain is the reference's and the row is +bit-comparable at the store. Above 16 rows the same operands use a 128x128 tile through LDS with +8x8 f32 accumulators per lane. The two ranges are complements, and the m16 row is compared against +the tiled row on the same bytes, where a moved boundary would show. -**The tiled row folds the scales at staging, and the fold is the arithmetic.** The tile -is f16, so both scale streams enter as f16 multiplies where the codes are staged: the -activation's `a_scale[m][g]` per staged row, the weight's `b_scale[nb][g]` once a chunk -— TN 128 is the scale plane's row extent, so a tile is one scale-row, and kKC 32 divides -128, so a chunk sits inside one k-block. The products are separable, -`(a*sa)*(b*sb) = (a*b)*sa*sb`, so folding each side is the same sum formed a different -way and the accumulator stays one f32 register. The reference's law is the group sub-sum -accumulated from the raw codes and scaled once per group (`ref_gemm.h`'s `quant_dot`, the -same body the m16 and gated rows carry); the fold answers to it at 2.77e-04 `rel_l2` -against a store that costs 3.9e-3, so it is invisible under the bf16 output: 1.71e-03 -overall, 83% of outputs bit-exact, 99.93% within the fold floor plus one store rounding, -nothing beyond eight fold floors and two store ulps. `|y|` is not the denominator — a sum -of 2048 random products is as often near zero as not — the scale is -`S = sqrt(sum (a_k b_k)^2)`, and the fold's measured floor is 9.8e-4 of it. +**The tiled row folds the scales at staging.** The tile is f16, so both scale streams enter as f16 +multiplies where the codes are staged: the activation's `a_scale[m][g]` per staged row, the +weight's `b_scale[nb][g]` once per chunk (TN 128 is the scale plane's row extent, so a tile is one +scale row, and kKC 32 divides 128, so a chunk sits inside one k-block). The products are +separable, `(a*sa)*(b*sb) = (a*b)*sa*sb`, so the accumulator stays one f32 register. The +reference's law is the group sub-sum accumulated from the raw codes and scaled once per group +(`ref_gemm.h`'s `quant_dot`, the body the m16 and gated rows carry); the fold differs from it by +`rel_l2` 2.77e-04 against a bf16 store that costs 3.9e-3, so it is invisible in the output (see the +divergence table). `|y|` is not a usable denominator, since a sum of 2048 random products is often +near zero; the scale is `S = sqrt(sum (a_k b_k)^2)`, and the fold's floor is 9.8e-4 of it. -**At the band's ceiling.** M=2048, container resident, every number on a -placement line: N=12288 K=2048 28.171 ms and 3659 GFLOP/s; N=2560 K=2048 5.911 ms and -3633; N=2048 K=6144 14.699 ms and 3506; N=2048 K=2048 4.381 ms and 3922; N=2048 K=10240 -29.798 ms and 2883, the drafter. 2883 to 3922 GFLOP/s is 27 to 36% of a part's dense f16 -rate; the bytes floor at the 163 GB/s this class streams is 0.051 to 0.257 ms a band, and -2MNK/(K+N) is ~1900 flops a byte at M=2048. Prefill is compute-bound here, as it should -be, so these numbers describe the loop and not the wire. +**At the band ceiling** (M=2048, container resident): N=12288 K=2048 28.171 ms (3659 GFLOP/s); +N=2560 K=2048 5.911 ms (3633); N=2048 K=6144 14.699 ms (3506); N=2048 K=2048 4.381 ms (3922); +N=2048 K=10240 29.798 ms (2883). That is 27 to 36% of the part's dense f16 rate. The bytes floor at +163 GB/s is 0.051 to 0.257 ms per band, and 2MNK/(K+N) is about 1900 flops per byte at M=2048, so +prefill is compute-bound and these numbers describe the loop, not memory. -**The cliff is recorded with its numbers, because it is not arithmetic.** The tiled -kernels run one block a CU at 18.4 to 18.5 us a block on every column-tile count the -graphs issue (16 and 20 measured, 4.72 and 5.911 ms over the grid); 19 tiles costs 211 us -a block, 11.4×, and 21 tiles 385 us, 20.9× — deterministic to 0.1% in two isolated -processes, clean at both. Every column-tile count the served graphs issue is even, -so no band walks into it; first try the block-index swizzle these cliffs usually answer -to, then the `nt` streaming loads. +**A grid-shape cliff.** The tiled kernels run one block per CU at 18.4 to 18.5 us per block at the +column-tile counts the graphs issue (16 and 20); 19 tiles cost 211 us per block (11.4x) and 21 +tiles 385 us (20.9x), deterministic to 0.1%. Every column-tile count the served graphs issue is +even, so no band hits it. The first things to try are a block-index swizzle, then the `nt` +streaming loads. -**What proved the crossing, and what would not have.** One `RadArgs`, the device row and -libref's host row on the same bytes, the whole `y` plane compared — pre-filled `0x7fc0` -so an unwritten element is visible, every other plane poisoned, 256-byte guards checked -after the launch. In every form the served plan hands the row (rank-1 `a_scale` of `[M]`, -the codes as a rank-3 `[M][ceil(K/128)][128]` plane, the weight as the container the -layout hook writes) at the four served bands and at M = 17, 21, 30, 45, 64, 65, 128, 258: -**832 of 1600 cases computed by both sides, 0 numeric divergences, worst `rel_l2` -1.440e-03** against a 5e-3 tolerance, 86.8% of elements bit-identical. The container form -above is what let the crossing reach the joined spelling at all: in it, 192 cases, 192 -agreements, worst 1.362e-03, and the full crossing comes to 1018 cases with 0 numeric -divergences; the same band with `b_scale=[scale,zero]` is 192 cases refused `E_DTYPE`. +**Verifying the crossing.** One `RadArgs`, the device row and libref's host row on the same bytes, +the whole `y` plane compared, pre-filled with `0x7fc0` so an unwritten element is visible, every +other plane poisoned, and 256-byte guards checked after the launch. The run covers every form the +served plan hands the row (rank-1 `a_scale` of `[M]`, the codes as a rank-3 +`[M][ceil(K/128)][128]` plane, the weight as the container the layout hook writes) at the four +served bands and at M = 17, 21, 30, 45, 64, 65, 128 and 258, against a 5e-3 tolerance; the same +band with `b_scale=[scale,zero]` is refused with `E_DTYPE`. The harness has two plugins dlopened, +both row tables resolved the way the engine's loader resolves them, and scores a plane against nine +index laws with a hash beside it. It also covers the collapsed mapped and managed tier +arrangements (the mirror layout, the default, is the served one). The rank-1 `a_scale` binding +matters: a shim passing the wrong row pitch for it reads rows 0 and 1 correctly and everything past +the plane after that, which the row's own geometry test cannot see. -**A fixture whose scales are alike cannot tell an indexing error from rounding.** The -paired run spreads its activation by orders of magnitude a group at a time, because with -uniform random data the amax of 128 samples is statistically concentrated, every block's -scale comes out equal to bf16, and a scale-*index* bug — reading group 0's scale for -group 7 — changes nothing. The unit's own selfcheck said so: two of its eight sabotages -scored 0.00. So the crossing is proved by the paired run and not by the selftest, and -the -planted bug is the proof of the instrument: one line in the shim's launch call — the row -pitch handed to the kernel for a rank-1 activation scale becomes `kb`, a row plane read -at a group plane's pitch, checks and geometry untouched. Against the paired run, 300 -cases: -**240 divergent, worst `rel_l2` 1.389e+00**, and all 180 cases whose `a_scale` is the -served rank-1 binding diverge (9.669e-01, 43 507 of 43 520 elements differing, max abs -6.75e+01: rows 0 and 1 read real scales, every row from 2 reads the bytes past the plane -and produces zeros) while the 60 rank-2 cases are untouched and agree. In `served`, the -fixed scorer names 8 of 8 as `a_scale[m*kb+g]` — the read law, which is what the sabotage -*is*. The same bug is invisible to the row's own geometry test, which sees a rank-1 scale -of `M` rows at a stride of `groups`: a gate that cannot see a wrong scale is not a gate. +### The gated MLP row -**The gated row couples column *i* to column *n + i*,** so a lane owns both products of -its column: the partner is 192 waves away at the band's n = 6144, no lane-to-lane -exchange reaches it, and staging a whole row through LDS to get it is a round trip of the -[M, N] tensor the row exists to avoid. A lane walks k ascending with two accumulators -over two weight rows, `i` and `n + i` — exactly the traffic the unfused GEMM spent on the -two columns, so the coupling is free — and a block is one group of columns by -`256/group` rows, which closes the group's amax inside the block: a wave max folded over -the group's waves in LDS, one scale store, one code a lane. Product, gate and quantiser -in one launch with 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. Both halves are narrowed to bf16 before -the gate because the pair it replaces stored them and re-read them; the activation itself -is not — `gt * sg` is f32 from the narrowed gate and the product with `up` rounds once, at -the store. The law is `ref_quant.cpp:700` and its order is the point. +`gemm_nt_q_gated_fp8a8` fuses the GEMM, the gate and the output quantiser, so the bf16 `[M, N]` +intermediate is never written, read or allocated. The gate couples column `i` with column `n + i`, +192 waves apart at n = 6144, out of reach of any lane exchange; so each lane computes both products +of its column, walking k ascending with two accumulators over weight rows `i` and `n + i`, the same +traffic the unfused GEMM spends on the two columns. A block is one group of columns by `256/group` +rows, which closes the group's amax inside the block: a wave max folded over the group's waves in +LDS, one scale store, one code per lane. The op is one launch with no scratch, so the row is +concurrent (`rad_kernel_concurrent(i)` is `scratch == nullptr`). Both halves are narrowed to bf16 +before the gate, because the pair it replaces stores and re-reads them; the activation is not +(`gt * sg` is f32 from the narrowed gate, and the product with `up` rounds once, at the store). The +law is libref's `ref_gemm_nt_q_gated`, and its order must be kept. -**The gated band, both arms, best/median of nine launches, codes resident:** +The launcher picks the arm by row count. fp8a8 at M <= 8 reads the activation and both weight rows +directly, 16 bytes at a time, decodes them from the block's table and multiplies: no shared memory +between load and dot, no barrier in the k-loop, six loads in flight. M >= 9, and every fp8a16 case, +stage through LDS; at those heights the grid is 48 x M/2 blocks and occupancy feeds the stream. +On the band's stream (24 MiB of codes, resident, loop without the epilogue), staging with the +arithmetic decoder takes 497 us, direct reads with the table 187 us, and the bare loads 139 us. + +Measured on the band (N=12288 K=2048 group=128, codes resident), best / median of nine launches, +staged arithmetic-decode arm against the shipped arms: ``` M = 1 987.4 / 1154.9 -> 171.3 / 181.6 us (147 GB/s of codes; the floor for @@ -732,480 +565,312 @@ M = 32 5123.4 / 5405.1 -> 1660.6 / 1705.0 us M = 64 8395.3 / 9051.0 -> 2786.5 / 2877.3 us ``` -**The arm is chosen by row count, in the launcher, from the same band key.** M ≤ 8 with -fp8a8 reads the activation and both weight rows straight from memory, 16 bytes at a -time, decodes them out of the block's table and multiplies: 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, stages — at those heights the grid is 48 × M/2 blocks and occupancy, not the -window, feeds the stream, and the stage pays for itself. The two numbers that chose the -shape came from the band's own stream (24 MiB of codes, resident, this 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 crossover and its gap live in -the launcher's comment, beside the `M <= 8` it selects on: with the table decoder in -**both** arms, N=12288 K=2048 group=128, codes resident, skinny 402 against staged 754 at -M=8 and skinny 955 against staged 1030 at M=16 — so the crossover is above 16 and -M=9..15 has never been measured. Decode lives at M=1 and a draft's verify at M ≤ 8, which -is what the shipped threshold is chosen for; a prefill at 9..16 rows would take the skinny -arm on the M=16 numbers, for about 7%. The window is a skinny-arm fix only: at M=64 it -buys its loads per lane at 32 registers, which is a fifth of a wave a SIMD given up on the -47 bands at the ceiling, and there it costs more than it saves. +The M <= 8 threshold is a tunable, chosen for decode (M=1) and draft verify (M <= 8). With the table +decoder in both arms the direct arm takes 402 us against 754 at M=8 and 955 against 1030 at M=16, +so the crossover is above 16; M=9..15 is unmeasured, and a prefill of 9..16 rows pays about 7% for +the staged arm. The load window is for the direct arm only: on the staged arm it costs 32 +registers per lane, a fifth wave per SIMD, and at M=64 it costs more than it saves. -**No relayout on the gated row, and that is a claim.** libref reads the gated -`[N, K]` weight row-major; libr4d stores fp8a8 weights in WMMA fragment order. The two -readings are ~1.35 apart — a relative error, not noise — so this row carries no -relayout and says so in its prose: a row that inherits the fp8 GEMM's `unrelayout` -scores 1.35. The launcher refuses M > 64 (past the bands' ceiling the weight stream is -the wall, and that is a tiled kernel's problem), N odd, a group that is not a power of -two in [32, 256], `group > n` (the reference then defaults the *quantiser's* group to -n and leaves the weight's K block at the stated width: two grids this kernel reads as -one), `K % group != 0` (a ragged K block reads past the scale plane), `sk > 1` (no K -slab closes an epilogue that needs the whole row), and an absent `act`. - -**The instrument** is a paired run with two plugins dlopened, both row tables resolved -the way the engine's loader resolves them, one `RadArgs`, and a plane scored against -nine index laws with a hash beside it. It runs every stored form × the bands × the -crossing heights, the served geometry with the rank-1 activation scales the plan binds, -and the collapsed mapped and managed tier arrangements (the mirror layout, the default, -is the served one). Its numbers are the ones quoted above. +The row carries no relayout. libref reads the gated `[N, K]` weight row-major; libr4d stores fp8a8 +weights in WMMA fragment order, and the two readings differ by a relative error of about 1.35, so +a row that inherited the fp8 GEMM's `unrelayout` would fail the per-op oracle. The launcher refuses +M > 64 (beyond the bands' ceiling the weight stream is a tiled kernel's problem), N odd, a group +that is not a power of two in [32, 256], `group > n` (the reference would then use n for the +quantiser's group while keeping the weight's K block at the stated width, two grids this kernel +reads as one), `K % group != 0` (a ragged K block reads past the scale plane), `sk > 1` (the +epilogue needs the whole row), and an absent `act`. ## The paged attention, decode and prefill -Two rows, chosen by `q_len`: the decode entry, which takes `splits`, and the prefill -entry. The served plan is n_head 16 over n_head_kv 2 at head_dim 128 — gqa 8 — with -`block_size 16` and a 4096 context, the cache `fp8_e4m3` with its descales attached. The -layout is the reference's: `kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim]`, -K then V inside a slot, so a key's row is a 512-byte pair and both halves are 16-byte -aligned at every slot; `block_table[seq, j / block_size]` names the block holding key -j; a negative entry is an unmapped block and hides its key, which the allocator uses to -free a sequence by writing −1, so the kernel keeps that test even though the fixture -never sets it; `seqused[s]` is the sequence's **total** key count, this step's query -rows included, so query row *i* of a `len_s`-row step sits at the absolute position -`seqused[s] - len_s + i`. One kernel serves decode (q_len 1), a speculative verify -(q_len 7) and a prefill chunk (q_len 2048). +Two rows, chosen by `q_len`: the decode entry, which takes `splits`, and the prefill entry. The +served geometry is n_head 16 over n_head_kv 2 at head_dim 128 (gqa 8), `block_size 16`, a 4096 +context, and an `fp8_e4m3` cache with its descales. The layout is the reference's: +`kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim]`, K then V inside a slot, so a key's row +is a 512-byte pair and both halves are 16-byte aligned at every slot. `block_table[seq, j / +block_size]` names the block holding key j; a negative entry is an unmapped block and hides its +key (the allocator frees a sequence by writing -1, so the kernel keeps the test although the +fixture never sets it). `seqused[s]` is the sequence's total key count including this step's query +rows, so query row *i* of a `len_s`-row step sits at absolute position `seqused[s] - len_s + i`. +One kernel serves decode (q_len 1), speculative verify (q_len 7) and a prefill chunk (q_len 2048). -**A lane owns one output row and a wave is the GQA heads of one KV head:** -`h = kh * GQA + (lane & (GQA-1))`, `tok = base + (lane >> lg GQA)` — 8 heads over 4 rows -at gqa 8 — so every lane of a wave reads the same cache row at the same moment. Every -cache read is then an LDS broadcast, one `ds_read_b128` serving the wave, and the paged -walk is a per-wave event rather than a per-lane one. 32 rows per cache read is also the -register file's ceiling, not a preference: a second output row a lane needs 2 × 64 -VGPRs of widened query plus 2 × 128 of f32 accumulator, 384, over the 256 that four -waves a SIMD allows. +**A lane owns one output row, and a wave is the GQA heads of one KV head:** +`h = kh * GQA + (lane & (GQA-1))`, `tok = base + (lane >> lg GQA)` (8 heads over 4 rows at gqa 8), +so every lane of a wave reads the same cache row at the same time. Every cache read is then an LDS +broadcast, one `ds_read_b128` serving the wave, and the paged walk is a per-wave event. 32 rows per +cache read is also the register file's ceiling: a second output row per lane would need 2 x 64 +VGPRs of widened query plus 2 x 128 of f32 accumulator, 384, over the 256 that four waves per SIMD +allow. -**The walk happens twice, on purpose.** The reference keeps its scores; 32 keys × 128 -dims of f32 is 512 KiB a wave against 64 KiB of LDS, so pass two recomputes them. The -recomputation is the same order over the same operands, so it is bit-identical the -second time, and the op costs half again what keeping them would. A masked key is -skipped, never scored to −inf, so the denominator gets exactly the terms the reference -has, and a row with no visible key stores zeros — the reference's `mx == -INFINITY` -case, as in every other kernel here. P·V stays f32: folding the softmax weight into V -reads every weight to 11 bits, a ~1e-4 change that survives the bf16 store on a few -percent of outputs, for a third of the instructions. `exp` is a degree-8 polynomial -because there is no vector f64: over 1.31M points of [-100, 0] every point lands within -one f32 ulp of `(float)exp((double)x)` and 76.1% land bit-identical, where the device's -`expf` is 94.0% bit-identical — neither is the reference, and `exp(0)` is exactly 1, -which is the term the row is normalised by. +**The walk runs twice.** The reference keeps its scores, but 32 keys x 128 dims of f32 is 512 KiB +per wave against 64 KiB of LDS, so pass two recomputes them, in the same order over the same +operands, bit-identically; the op costs half again what keeping them would. A masked key is +skipped, never scored to -inf, so the denominator has exactly the reference's terms, and a row with +no visible key stores zeros (the reference's `mx == -INFINITY` case). P*V stays f32: folding the +softmax weight into V would read every weight to 11 bits, a ~1e-4 change that survives the bf16 +store on a few percent of outputs. `exp` is the degree-8 polynomial from the divergence table, and +`exp(0)` is exactly 1, the term the row is normalised by. -**The width of a workgroup is the only lever this op has ever given.** A row slot past -a sequence's length computes a clamped duplicate: the walk, the tile and the store all -run for it. `pick_waves` picks the narrowest workgroup that carries the step's `q_len` -(one wave to 32/GQA rows, two to 64/GQA, four above); prefill keeps four. Medians of 15 -per-launch event times, two binaries in one session so the clocks drift together — the -same session's prefill reads 44.9 for both, which is how an earlier session's 40.0 was -explained: 294.7 → 158.4 ms at 256 sequences × 7 rows over 4096 keys, 268.0 → 128.4 ms -with 4 splits, 4.33 → 2.06 ms at 8 sequences over 2048, 4.27 → 3.97 ms at one sequence -over 4096, prefill 44.95 → 44.78. The kernel issues ~15% of the SIMD's slots at the -band and 3.7% at eight sequences, so halving arithmetic on a stalling kernel "should -not" buy 46%, and it did: two waves arriving at a barrier is not twice as cheap as -four, it is four times cheaper. A measurement, not an explanation, which is why the -width is a run-time choice. +**Workgroup width is the effective lever.** A row slot past a sequence's length computes a clamped +duplicate (walk, tile and store all run for it). `pick_waves` picks the narrowest workgroup that +carries the step's `q_len` (one wave up to 32/GQA rows, two up to 64/GQA, four above); prefill +keeps four. Against a fixed four-wave workgroup (medians of 15 per-launch event times): 294.7 vs +158.4 ms at 256 sequences x 7 rows over 4096 keys, 268.0 vs 128.4 ms with 4 splits, 4.33 vs 2.06 ms +at 8 sequences over 2048, 4.27 vs 3.97 ms at one sequence over 4096, prefill unchanged. The kernel +issues about 15% of the SIMD's slots at the band and 3.7% at eight sequences, so the gain is not +explained by arithmetic; the width is therefore chosen at run time. -**Measured, and not the answer.** `s_setprio` around the consume leg of the walk: |Δ| ≤ -0.7% everywhere, and the one −6.4% in a session's first pair is clock ramp — the same -band run second gives +0.26%. `R3D_WAVES(2)` to lift the scalar-register ceiling: -`sgpr_count` 107 and `sgpr_spill_count` ~98 at *both* 4 and 2 waves a SIMD, timings -unmoved — the compute-shader scalar budget is not set by waves/SIMD the way the VGPR one -is. `__noinline__` on the staging leg: spills 98 → 72, a 160-byte private frame, timings -unchanged. A two-stage pipeline: +7% prefill, +7% decode, −5% split-KV. +**Levers that did not help:** `s_setprio` around the consume leg of the walk (|delta| <= 0.7%); +`R3D_WAVES(2)` to lift the scalar-register ceiling (`sgpr_count` 107 and about 98 SGPRs spilled at +both 4 and 2 waves per SIMD, timings unchanged: the compute-shader scalar budget is not set by +waves per SIMD the way the VGPR budget is); `__noinline__` on the staging leg (spills 98 -> 72, a +160-byte private frame, timings unchanged); a two-stage pipeline (+7% prefill, +7% decode, -5% +split-KV). -**Split-KV is a rescale, and the row says which splits are bit-identical.** A slice -accumulates its own `(acc[128], sum, max)` into scratch and the reducer combines before -the single narrowing, rescaling each partial by `exp(m_s - M)`; every term then arrives -as `exp(s - m_s) * exp(m_s - M)` where the reference has `exp(s - M)` — last-bit at f32 -(~2 ulp a term, ~1 ulp on the sum), and it vanishes under the bf16 store except on -outputs sitting on a rounding boundary. The row's prose states the contract: `splits = 1` -is bit-identical to the reference, `splits > 1` is not. `splits` is a **maximum**, -resolved per sequence from its own `seqused`: `nslice = ceil(nblk / ceil(nblk / splits))` -with `nblk` the sequence's block count, so a short sequence uses fewer slices and there -is no per-sequence legality check to fail, and the reducer recomputes `nslice` from the -same two numbers, so a partial needs no header. The arena is a bound, not an error: the -launcher lowers `splits` to what the arena holds, down to 1, which needs none. +**Split-KV is a rescale.** A slice accumulates its own `(acc[128], sum, max)` into scratch and the +reducer combines them before the single narrowing, rescaling each partial by `exp(m_s - M)`. Every +term then arrives as `exp(s - m_s) * exp(m_s - M)` where the reference has `exp(s - M)`, a last-bit +difference at f32 (about 2 ulp per term, 1 ulp on the sum) that vanishes under the bf16 store +except on rounding boundaries. The row's text states the contract: `splits = 1` is bit-identical to +the reference, `splits > 1` is not. `splits` is a maximum, resolved per sequence from its own +`seqused`: `nslice = ceil(nblk / ceil(nblk / splits))` with `nblk` the sequence's block count, so a +short sequence uses fewer slices and needs no per-sequence legality check, and the reducer +recomputes `nslice` from the same two numbers, so a partial needs no header. -**The split curve on the served shape** — 64 sequences, 8 KV heads, fp8 cache, 15 -launches, ms a launch, at splits 1/2/4/8/16/32/64: at ctx 1024, 8.17 / 5.51 / 9.29 / -1.50 / 2.54 / 0.39 / 0.23; at ctx 4096, 35.71 / 20.92 / 11.41 / 5.79 / 2.67 / 1.44 / -2.60. Each workgroup walks `ceil(nblk / splits)` blocks with `nblk = ceil(jcap/16)`, so -the total keys read are `jcap` at **every** split count: the cost is slices × per-slice -work plus the reduce, it falls to 32 and then rises. The clamp `splits ≤ -ceil(jcap/block_size)` is a no-op at the served shape — `ceil(1024/16)` is 64 — and -bites only where splits exceed `nblk`, where a grid built from the requested number -leaves slices with no blocks: 12 of 12 such cases agree, so the extra waves cost, they -do not corrupt. The curve declines the lever with its numbers; the launcher does not -refuse it. +The split curve on the served shape (64 sequences, 8 KV heads, fp8 cache, ms per launch at splits +1/2/4/8/16/32/64): ctx 1024, 8.17 / 5.51 / 9.29 / 1.50 / 2.54 / 0.39 / 0.23; ctx 4096, 35.71 / +20.92 / 11.41 / 5.79 / 2.67 / 1.44 / 2.60. Each workgroup walks `ceil(nblk / splits)` blocks with +`nblk = ceil(jcap/16)`, so the total keys read are `jcap` at every split count, and the cost is +slices times per-slice work plus the reduce. The clamp `splits <= ceil(jcap/block_size)` is a no-op +at the served shape (`ceil(1024/16)` is 64) and applies only where splits exceed `nblk`; a grid +built from the requested count then has slices with no blocks, which costs waves but stays +correct. -**Two counts bound the walk, and the descriptor's two counts bound the store.** -`jcap = min(max_ctx, cols * block_size)`: the block table is the window the kernel is -allowed to read, so a context longer than the table has columns is truncated — by the -oracle as much as by us, which makes it truncation, not corruption. `cache_blocks` -bounds a slot's byte offset, `bt_cols` bounds the walk, and the shim checks the one -thing required: that the last reachable index `(n_seq-1)*bt_rs + (bt_cols-1)*bt_cs + 1` -is inside the plane. In the tile walk, the descriptor's length gives the tile count and -its span gives the store bound, so a sequence whose `cu[0]` is above 0 stores every row -the grid covers: see the descriptor's two counts in -[The request](#the-request-a-plans-vocabulary-is-not-its-contents). +**Bounds.** `jcap = min(max_ctx, cols * block_size)`: the block table is the window the kernel may +read (see [the request-time rules](#request-time-rules-a-plans-vocabulary-is-not-its-contents) for +`cache_blocks`, `bt_cols` and the last-index check). In the tile walk the descriptor's length gives +the tile count and its span the store bound, so a sequence with `cu[0] > 0` stores every row the +grid covers. -**A padding row must not write a partial.** A padding row's `row` clamps to a REAL row, -so the split path needs the row-validity test *before* the partial store. Unguarded, -two lanes write the same `(row, h, slice)` — inside the declared arena, so no bounds -check sees it — and their 132-float records interleave, leaving a slot with one lane's -accumulator and the other lane's `(sum, max)`. The reducer then rescales a full slice by -the wrong maximum, the combined sum comes out thousands of times too small, and `1/sum` -hands back a power of two where a logit belongs. Measured at the sliding-window band -(one sequence, 32 heads over 8 KV heads, window 2048, fp8 cache, splits 4): q_len 4 at -ctx 8192 gives `rel_l2` 1.65e-01 with a worst item of +32.0 against a reference -+1.2e-05, and q_len 6 at the same context gives 1.23e-03 where splits 1 gives 1.09e-03. -The mechanism needs `q_len < 32/gqa`, which is why the decode band (q_len 7 at gqa 8 -fills a wave, so there are no padding rows) and a run of that geometry never -saw it, and why the failing fixture cases fail identically at three seeds: a schedule, -not a sample. The slots a padding row leaves unwritten are exactly the slots the reduce -does not read; its index runs over real rows only. +**A padding row must not write a partial.** A padding row's `row` clamps to a real row, so the +split path tests row validity before the partial store. Without it, two lanes write the same +`(row, h, slice)` record inside the declared arena, their 132-float records interleave, and the +reducer rescales a full slice by the wrong maximum, producing sums thousands of times too small. It +needs `q_len < 32/gqa` (at gqa 8, q_len 7 fills a wave and there are no padding rows), and it is a +schedule, not a sample: it fails identically at every seed. The slots a padding row leaves unwritten +are exactly those the reduce does not read; its index runs over real rows only. -**The instrument** is a paired run with libref and libr3d dlopened in one process, both -called with the *same* `RadArgs`, absent optional operands passed as a descriptor with -null `data` and never as a shorter `n_t`, with the fp8 cache form in the same run: 233 -served-shape cases with no divergence, the rectangular matrix, the deep contexts -512..4096, the narrow block tables (`bt cols` 1/2/3/4/8, so `jcap` 16/32/48/64/128 -under a ctx of 512), empty sequences (`cu = [0,0,5,5,17]`), split counts 1 and 4, -windows 1/3/17/64/512, causal and non-causal. It is where the descriptor law above -was found. On the fixture the row scores 87 of 87 with worst `rel_l2` 7.558e-05, the -same numbers in the base build and the work build — the pair a change has to keep. +**Verification** is a paired run with libref and libr3d dlopened in one process, both called with +the same `RadArgs`, absent optional operands passed as a descriptor with null `data` (never as a +shorter `n_t`), with the fp8 cache form in the same run. It covers the served shapes, the +rectangular matrix, deep contexts 512..4096, narrow block tables (`bt cols` 1/2/3/4/8, so `jcap` +16/32/48/64/128 under a ctx of 512), empty sequences (`cu = [0,0,5,5,17]`), split counts 1 and 4, +windows 1/3/17/64/512, causal and non-causal. -**The unit's own launch counts itself.** A served decode step is *played* — the recorded -pass re-issues queue packets and never calls the plugin's shim — so a print that lives in -the shim has never seen the played steps. The kernel does. Under -`RAD_R3D_TRACE` only, `attn_kernel` writes one record per launch — its launch ordinal, -the row's `ctx` off `seqused`, the whole block-id row of the table, the six operand -addresses, and FNV-1a folds of the query row and of the first and last block it walks — -into a plugin-owned `__device__` ring of 256 fixed 216-byte slots, and the shim drains -the ring to stderr on a traced call. Budget is a device global the shim writes; the -decrement is `atomicSub`, the counter `atomicAdd`, and with the flag unset the kernel -pays one scalar load and a not-taken branch on one thread. The record's emission is one -step late for played steps, and the record's own `L` and `ctx` restore the order. +**Launch tracing.** A served decode step is played: the recorded pass re-issues queue packets and +never calls the plugin's shim, so a print in the shim never sees played steps. Under +`RAD_R3D_TRACE` only, `attn_kernel` writes one record per launch: its launch ordinal, the row's +`ctx` from `seqused`, the whole block-id row of the table, the six operand addresses, and FNV-1a +folds of the query row and of the first and last block it walks. Records go to a plugin-owned +`__device__` ring of 256 fixed 216-byte slots that the shim drains to stderr on a traced call; the +budget is a device global the shim writes, decremented with `atomicSub`, the counter advanced with +`atomicAdd`. A played step's record is emitted one step late, and the record's own `L` and `ctx` +restore the order. In a served process the plugin is dlopened, and the runtime's symbol stub for a +plugin-owned `__device__` global is not the address the kernel's module writes, so the ring cannot +be armed there; the served channel is a `hipMalloc`'d record slot passed as a kernel argument, +drained at the launch and armed by the same flag. With the flag unset the kernel pays one scalar +load and a not-taken branch on one thread, and the launch one cached flag read. With it set, a +traced call pays one device synchronize (the descriptor probe reads the table on the host) and one +stream synchronize (the record drain), and the first traced call allocates the record slot; that is +why the flag is a tracing switch and not a mode. -**The served channel is a buffer, not a global.** In a served process the plugin is -dlopened, and the runtime's symbol stub for a plugin-owned `__device__` global is not the -address the kernel's module writes: the shim's arm and the kernel's read are two -different memories, so the ring's budget cannot be armed and the ring drains zero. The -served channel is therefore a plain `hipMalloc`'d record slot passed as a kernel -argument — no symbol table between writer and reader, one record per launch, drained at -the launch, armed by the same flag. The ring stays the board's channel, where the two -memories are one. - -**The flag's price, stated.** A launch function serves the step and is not a place to -allocate or to synchronize. With the flag *unset* both hold: the attention launch pays -one cached flag read and nothing else. With it *set*, the traced call pays one device -synchronize (the descriptor probe reads the table on the host) and the launch one stream -synchronize (the record drain), and the first traced call allocates the record slot. -Those are the instruments working, and they are the reason the flag is a tracing -switch, not a mode. - -**The law that made it a ring:** a kernel that calls device `printf` takes an extra -implicit argument — `hidden_hostcall_buffer` — and the AQL backend does not provide it, -so such a kernel is *undispatchable by the engine* (the fixture refuses the row with -`refused a geometry its constraints accept: device error`) while the same kernel, -hipLaunched by a hand-rolled board, prints every line. A board is therefore blind to -dispatch-side problems of its own kernels: only a gate that dispatches through the -engine can see them, and for this unit that gate is the recorded fixture. +Device `printf` cannot be used instead: a kernel that calls it takes an extra implicit argument, +`hidden_hostcall_buffer`, which the AQL backend does not provide, so the engine cannot dispatch it +(the fixture refuses the row with `refused a geometry its constraints accept: device error`), while +the same kernel launched with hipLaunch from a standalone harness prints normally. Only a gate that +dispatches through the engine, here the recorded fixture, sees such dispatch-side problems. ## The sampler spine -Thirteen rows: five pre-filters, `sample_topk` feeding `sample_pick`, and the narrowing -stages that run between them. `abi/rad_sample.h` is the wire format and it is the point -of the design: every scalar — `temp`, `top_k`, `top_p`, `min_p`, `typical_p`, the -`xtc_*` pair, `seed`, `pos`, the flags, the history window — is **data**, one 96-byte -row per sampled position, because a parameter is geometry and geometry is frozen at -declare, and two rows of one batch with different `top_p` must resolve to one kernel. -`param_rows` is that check, and it is the dtype check libref states: the plane is -32-bit words, and a 16-bit view passes a byte-count test and then misreads every row. +Thirteen rows: five pre-filters, `sample_topk` feeding `sample_pick`, and the narrowing stages +between them. `abi/rad_sample.h` is the wire format, and the central design choice: every scalar +(`temp`, `top_k`, `top_p`, `min_p`, `typical_p`, the `xtc_*` pair, `seed`, `pos`, the flags, the +history window) is data, one 96-byte row per sampled position, because parameters are geometry, +geometry is frozen at declare, and two rows of one batch with different `top_p` must resolve to one +kernel. `param_rows` is that check, and it is the dtype check libref states: the plane is 32-bit +words, and a 16-bit view passes a byte-count test and then misreads every row. -**The draws must reproduce, so the summation order is transcription and not -performance.** Every max here is a strict `>`, and that is also how NaN is kept out: -libref's `if (v > mx) mx = v` over −infinity never adopts a NaN, and the butterfly -merges with the same strict comparison, so a NaN in a row of logits cannot become the -max anywhere. A sum of f32 is not order-free: the reference's sums run over the -candidates in **index order** and its CDF scan accumulates in index order, so the exps -are computed in parallel — each a separate value, order-free — and the accumulation is -serial on one lane, in index order, exactly as written. Parallel values, serial sums: -the whole design of the candidate kernels in one line. +**Draws must reproduce, so summation order is transcribed.** Every max is a strict `>`, which also +keeps NaN out: libref's `if (v > mx) mx = v` from -infinity never adopts a NaN, and the butterfly +merges with the same comparison. The reference's sums run over the candidates in index order, and +its CDF scan accumulates in index order, so the exponentials are computed in parallel (each an +independent value) and the accumulation is serial on one lane, in index order. -**The draw is a function of the ABI, not of a library, and the transcendentals are the -reference's.** splitmix64 over `seed * 0x9E3779B97F4A7C15 + pos`, the top 24 bits over -2^24, integer arithmetic so it is the same number on the device as on the host, -independent streams per purpose (the pick XORs `RAD_SAMPLE_KEY_PICK`, XTC's coin +**The draw is a function of the ABI, not of a library.** splitmix64 over +`seed * 0x9E3779B97F4A7C15 + pos`, the top 24 bits over 2^24, in integer arithmetic so device and +host agree, with independent streams per purpose (the pick XORs `RAD_SAMPLE_KEY_PICK`, XTC's coin `RAD_SAMPLE_KEY_XTC`). `ref_exp`/`ref_log` are `(float)std::exp((double)x)` and -`(float)std::log((double)x)`, transcribed as double calls rounded once to f32: the -device's are bit-identical to the host's over 2^20 points in [-100, 100] — 0 differ — -where `expf` differs from the host's by 1 ulp in 5.7% of them, and a `u < cum` -comparison sitting on an ulp boundary changes the drawn token, which is a fixture -failure even when the distribution is right. This is where the 1:64 fp64 rate is -affordable: the widest softmax here is the candidate set, 1024 exponentials a row at -half a millisecond a step, so the switch stays off and attention, at 17M exponentials a -layer, ships the polynomial instead. +`(float)std::log((double)x)`, transcribed as double calls rounded once (see the divergence table); +a `u < cum` comparison on an ulp boundary changes the drawn token, which fails the fixture even +when the distribution is right. The widest softmax here is the candidate set, 1024 exponentials per +row at about half a millisecond per step, where the 1:64 f64 rate is affordable; attention, at 17M +exponentials per layer, uses the polynomial. -**The top-R is one scan because the reference's R scans are a sort.** `topk_next` takes, -on each of R scans, the largest value strictly below the last pick, ties to the LOWER -column; read as a whole that is a sort by (−value, +column), and the rule -`v == *pv && i <= *pi` is exactly "the next one within a run of equal values". So one -pass keeping the best R by that order produces the same R pairs, in the same order, with -the same tie-breaks. At the band's row — M=1792, N=130560, R=16, bf16 — the reference -scans the row sixteen times, 7.0 GB; this scans it once, 468 MB. Measured 22.0 ms bf16 -and 22.4 ms f32, 21 GB/s and 42 GB/s: the same time for half the bytes, which is the -finding. The pass is bound by the accepted inserts — ~55 sifts a lane at 510 elements a -lane — not by the plane, and a lane filtering against a block-wide threshold instead of -its own tail would take ~5 sifts a lane and land near the 2 ms the bandwidth floor -allows; 22 ms is not the memory system's answer, and it is written here so nobody reads -it as one. One pass needs a per-lane list, so the list is 64 deep and a merge keeps the -best 64 of two: a lane's test against its 64th best is one comparison for almost every -element (~12% of a row clears it at 510 elements a lane), and the deep comparisons -happen only for elements that enter. Sixty-four covers R=16, the selftest's 64-wide set, -and every `top_k` a request asks for in practice; past it `r3d_sample_topk` and -`r3d_row_topk` take `ceil(k/64)` passes — the reference's own chain, so the answer is -the same at any k and only the time is the reference's. +**The top-R is one scan.** `topk_next` takes, on each of R scans, the largest value strictly below +the last pick, ties to the lower column; as a whole that is a sort by (-value, +column), and the +rule `v == *pv && i <= *pi` is "the next one within a run of equal values". One pass keeping the +best R in that order produces the same R pairs in the same order with the same tie-breaks. At the +band's row (M=1792, N=130560, R=16, bf16) the reference scans the row sixteen times (7.0 GB); this +scans it once (468 MB), in 22.0 ms bf16 and 22.4 ms f32. The pass is bound by accepted inserts +(about 55 sifts per lane at 510 elements per lane), not by memory; filtering against a block-wide +threshold instead of each lane's own tail would cut that to about 5 sifts and approach the 2 ms +bandwidth floor. Each lane keeps a 64-deep list and a merge keeps the best 64 of two; testing an +element against the lane's 64th best is one comparison for almost every element (about 12% of a +row clears it at 510 elements per lane). 64 covers R=16, the selftest's 64-wide set and every +practical `top_k`; above it `r3d_sample_topk` and `r3d_row_topk` take `ceil(k/64)` passes, the +reference's own chain, so the result is the same at any k. -**The candidate plane is the contract, its width is the BUFFER's, and it carries -LOGITS.** A row's set is its `top_k` largest logits, descending, ties to the lower -token id, with `cand_idx` −1 and `cand_val` −infinity for a hole. The width is the -declare-time bound — 1024 candidates is the engine's declared buffer width, and two f32 -arrays of it is 8 KiB of the 64 KiB a workgroup gets — and the row's `top_k` only -narrows *within* it: `top_k` 40 in a 1024-wide buffer is 40 candidates and 984 holes, -and the whole buffer is written every step because a hole is a value the later stages -test for. A greedy row takes none: its token is `sample_argmax`'s and the pick must not -overwrite it. `cand_val` carries LOGITS, not probabilities — every narrowing stage takes -its own softmax over the set, which is what lets the stages compose in any order and is -why a pre-filter can be moved rather than re-derived. +**The candidate plane is the contract.** A row's set is its `top_k` largest logits, descending, +ties to the lower token id, with `cand_idx` -1 and `cand_val` -infinity for a hole. The width is +the buffer's declare-time bound: 1024 candidates is the engine's declared width (two f32 arrays of +it are 8 KiB of the 64 KiB a workgroup has), and the row's `top_k` narrows within it, so `top_k` 40 +in a 1024-wide buffer is 40 candidates and 984 holes. The whole buffer is written every step, +because later stages test for holes. A greedy row takes no candidates: its token is +`sample_argmax`'s and the pick must not overwrite it. `cand_val` carries logits, not probabilities: +every narrowing stage takes its own softmax over the set, so the stages compose in any order and a +pre-filter can be moved without re-deriving anything. -**The band key is a ceiling and the plane is the step, and reading one as the other -killed every logprobs request.** The step's rows are the operand's row count. Preferring -the key's `M` over the plane asked one row of candidates to be 256 of them — `refused op -sample_topp at M=1 [band M<=256] geometry {n_cand=1024 M=256}` — so every request that -asked for logprobs died with `shape this kernel does not serve`. It was the third unit -in one night to read a band's bound as the step's value, after the tiled GEMM at M=30 -and the block table sized to the cache, which is the reason the rule is stated as a law -and not a fix. The key keeps its job as the ceiling the plan promised not to exceed, and -the refusal that fires on a plane over it prints the descriptor it saw. +**The step's row count comes from the operand** (see +[the request-time rules](#request-time-rules-a-plans-vocabulary-is-not-its-contents)). A candidate +stage that used the band key's `M` would ask one row of candidates to be 256 rows tall and refuse +every logprobs request (`refused op sample_topp at M=1 [band M<=256] geometry {n_cand=1024 +M=256}`). -**The spine's instrument is the fixture, not a paired run.** No comparison harness pairs -these rows with libref: the selftest builds each row's buffers from its own `opd_shape`, -fills per the fill code, runs the row, and checks the plane whole in a child process, -and kbench -drives the `sample_*` bands against libref on the served checkpoint's fixture (975 of -975 across every op the run resolves, worst 1.605e-03, in the -[Testing](#testing) tally). What a paired run would add is the part the fixture cannot -check: the seeded draw compared against a *recording*, over the parameter rows a request -actually sends. That gap is in -[What is not here yet](#what-is-not-here-yet). +**Verification** is the fixture rather than a paired run: the selftest builds each row's buffers +from its own `opd_shape`, runs it and checks the plane whole in a child process, and kbench drives +the `sample_*` bands against libref on the served checkpoint's fixture. What the fixture cannot +check is the seeded draw against a recording, over the parameter rows a real request sends (see +[What is not here yet](#what-is-not-here-yet)). ## Measuring -**Measure the floor first and name it in the verdict.** 66.8 MB of codes at a part's -22 GB/s is a 3.0 ms floor; 255 MiB at 163 GB/s is 1.64 ms; a 73.1 MB operand is a -0.449 ms read. Against those, "13.6 ms a token" and "24.151 ms at M=64" are statements -about the loop, not the wire. A number with no floor beside it is a feeling. +**State the floor beside the number.** 66.8 MB of codes at a part's 22 GB/s is a 3.0 ms floor; +255 MiB at 163 GB/s is 1.64 ms; a 73.1 MB operand is a 0.449 ms read. Against those, 13.6 ms per +token or 24.151 ms at M=64 describe the loop, not memory. -**Name the placement of every operand on every timing line.** On a part whose memory -cannot hold the head this is worth an order of magnitude, and it is a property of the -class: at M=1, one kernel, the same head in VRAM is 13.6 ms a token; on the mapped -tier (pinned host bytes read over the host link by 8-byte strided loads) 643 ms; -managed and left alone 2071 ms at 122 MB/s, because managed pages do not migrate for a -read-mostly device access and the kernel faults page by page. A layout hook makes the -mapped placement *legal*, not fast. Boards state which placement produced which -number, time after a prefetch, and note that a container operand must be host-readable -at all (the shim reads its header on the host) — hence pinned or managed, never plain -`malloc`, which faults. +**State the placement of every operand on every timing line.** On a part whose memory cannot hold +the head it is worth an order of magnitude: at M=1, one kernel, the same head in VRAM is 13.6 ms +per token; on the mapped tier (pinned host bytes read over the host link by 8-byte strided loads) +643 ms; managed and left alone 2071 ms at 122 MB/s, because managed pages do not migrate for a +read-mostly device access and the kernel faults page by page. A layout hook makes the mapped +placement legal, not fast. Benchmarks state which placement produced which number and time after a +prefetch. A container operand must be host-readable (the shim reads its header on the host), so it +is pinned or managed, never plain `malloc`, which faults. Allocation history matters too: the same +shape in the same binary measures 5.911 ms as a process's first case and 85.7 ms after a 24 MiB +managed container was allocated and freed, because the slow run reads its weight over the host +link. The row's number is the VRAM one, because the engine moves weights to VRAM at load. -A number belongs to whoever placed the bytes: the same shape in the same binary -measured 5.911 ms as the first case of a process and 85.7 ms as the second case of a -sequence that had allocated and freed a 24 MiB managed container first — 14.5×, -deterministic, clean run both ways, and at 0.2 GB/s the slow run is reading its -weight over the host link. The row's number is 5.911 ms, because the engine ships -weights to VRAM at load and reads them 44 times. +**`vgpr_spill_count` is a gate:** every kernel must report zero VGPR spills. Per-group partials +scaled into the accumulator cost 64 more accumulators on an arm already at 237 VGPRs, and a runtime +index into a register array spills the array to private memory; both need a rewrite, not a tunable. +A scalar spill in a compute-shader wavefront is a slow path, not a stall (see the attention +measurements), so SGPR spills are reported, not gated. -**`vgpr_spill_count` is a gate, not a note:** 44 kernels, all zero, both builds of an -A/B. Per-group partials scaled into the accumulator cost 64 more accumulators on an -arm already at 237 VGPRs, and a runtime index into a register array of candidates -spills the array to private memory; both are rewrites, not tunables. A scalar spill in -a compute-shader wavefront is a slow path, not a stall — the ablations below say so -with numbers — so VGPR spills gate and SGPR spills get reported. - -**Number before verdict.** Four things that look like they should work on the -attention unit were measured to not work, and the one width that did move it is -recorded with them -[in the attention section](#the-paged-attention-decode-and-prefill); the tiled rows' -grid-shape cliff is recorded -[in the GEMM section](#the-fp8x8-gemm-by-row-count). A negative result carrying its -numbers is the cheapest documentation in a library: it is the only thing that stops -the next session re-measuring it. - -**Profiled per-op times sum to more than the token, and that is the tool working.** -On the served 2B plan, 61 + 24 + 12.7 + 4.2 = 102 ms of per-op device time against a -measured 87.6 ms token: the engine overlaps its ops, and `--profile-ops` restores the -synchronisations that serialise them — the caveat the served engine prints in its own -startup diagnostics ([`core/diag/checks.cpp`](../core/diag/checks.cpp): *times every op, -which restores synchronisations … drop `--profile-ops` for anything measured*). A per-op -table taken under that flag ranks the work and does not price it, and the token rate is -the price. The pair that proves the reading: the gated row's profiled saving on that plan -was ~44 ms of the 87.6 ms token, and the token got 11.4 ms faster. Quote a served run's -shape with its served numbers — the context length it was taken at, the prompt lengths it -walked — because a ranking is a property of the shape, not of the model. +**Per-op profile times sum to more than the token.** `--profile-ops` restores the synchronisations +that the engine's overlap removes, as the engine's startup diagnostics state +([`core/diag/checks.cpp`](../core/diag/checks.cpp)). A per-op table taken under that flag ranks the +work and does not price it; the token rate is the price. Quote a served run's shape with its +numbers (context length, prompt lengths), because a ranking is a property of the shape, not the +model. ## Notes on the kernels -Three properties are assumed throughout and not restated per kernel: **wave32 with a -1024-entry VGPR file a SIMD**, so every lane map has a lane owning whole dwords and -every budget is computed against 1024; **64 KiB of LDS a workgroup**, which sets the -candidate kernels' `n_cand <= 1024` and the tile sizes; **the dot2 path** (the -wave-matrix fragment layout is a re-tile, not a drop-in for these lane maps), which is -why the tile is a dot loop over LDS with an 8-element XOR swizzle, shared by every -tiled row in [`r3d_tiling.h`](r3d_tiling.h) and proven byte-identical between them. +Three properties are assumed throughout and not restated per kernel: **wave32 with a 1024-entry +VGPR file per SIMD**, so every lane map has a lane owning whole dwords and every budget is computed +against 1024; **64 KiB of LDS per workgroup**, which sets the candidate kernels' `n_cand <= 1024` +and the tile sizes; and **the dot2 path**, which is why the tile is a dot loop over LDS with an +8-element XOR swizzle, shared by every tiled row in [`r3d_tiling.h`](r3d_tiling.h). -**A staged chunk of 8 bytes against a row pitch of 512 is the 2-bit grid moving 8× the -bytes it uses** at `kKC` 32: 24.151 ms at M=64, N=130560, K=2048 against a 0.449 ms -read floor, 3.7 GB/s useful. The lever is a wider k-chunk (64 codes = 16 bytes, paid -for in LDS), not more loads in flight: leading the codes measured 0.6%, bit-identical, -and was reverted. +**The 2-bit grid's tiled staging moves 8x the bytes it uses.** A staged chunk of 8 bytes against a +row pitch of 512 at `kKC` 32 gives 24.151 ms at M=64, N=130560, K=2048 against a 0.449 ms read +floor, 3.7 GB/s useful. The lever is a wider k-chunk (64 codes = 16 bytes, paid for in LDS); more +loads in flight moved it by 0.6%. -**The head is the largest read in a decode step**, and the sampler reads f32 — why the -store is typed, not narrowed, and why a prefill band writes 1.07 GB. bf16 codes: 3.29 -ms a token at M=1 (163 GB/s), 0.507 ms at M=16 (the head read once for sixteen rows), -269 ms at 2048 rows (4067 GFLOP/s). E4M3 codes with a bf16 scale per 128×128 block, -read as the two container planes they are: 13.6 ms a token at M=1, 8× above the 1.64 -ms floor, cause named — the E4M3 decoder, ~100 instructions an eight-code group. The -decoder-as-a-table pass (256-entry f16 table in LDS, 512 bytes, eight reads a group, -exact by construction) is 2.70× where the decoder binds (M=8: 2.500 → 0.924 ms a -token), flat at prefill, and a **named non-result at M=1**: removing ~100 ALU -instructions did not move it. The suspect at M=1 is load width — eight codes a lane -through an 8-byte load, where the bf16 arm takes sixteen bytes a lane at 163 GB/s — so -the next experiment is a 16-byte code load, not more ALU. `rel_l2` between the two -binaries is bit-identical: the check that the swap moved work, not arithmetic. +**The head is the largest read in a decode step,** and the sampler reads f32, so the store is +typed, not narrowed, and a 2048-row prefill band writes 1.07 GB. bf16 head: 3.29 ms per token at +M=1 (163 GB/s), 0.507 ms at M=16 (the head read once for sixteen rows), 269 ms at 2048 rows (4067 +GFLOP/s). E4M3 head with a bf16 scale per 128x128 block, read as its two container planes: 13.6 ms +per token at M=1, 8x above the 1.64 ms floor. The table decoder gives 2.70x where the decoder binds +(M=8: 2.500 -> 0.924 ms per token), nothing at prefill, and nothing at M=1. The likely limit at +M=1 is load width (eight codes per lane through an 8-byte load, where the bf16 arm loads sixteen +bytes per lane), so the next step there is a 16-byte code load. -**A launch check that does not clear the flag first refuses a healthy step.** -`hipGetLastError()` reports the first error raised *since it was last cleared*, so a -check that does not clear attributes to this launch whatever the process raised before -it: in a served process, the op that ran last; in a comparison run, its own setup. Both -were -seen. The symptom to recognise is a whole timing mode returning the device code on -every geometry of every row, all of it vanishing under `HIP_LAUNCH_BLOCKING=1` — which -is what a synchronous launch does to a pending asynchronous error, it clears it before -the check — and a shim's own text rendering it as something about strides, because the -launcher printed a raw code and the caller appended its own sentence. Two lines fix -it: clear the flag after the arguments are staged and before the chevron, then read it -straight back; and on a refusal, name the error and print the grid, the block, the -waves, the splits and the width the launcher chose. A refusal that does not say what -it saw cost two hours, and the failure mode is a healthy step refused for a symptom a -neighbour caused — the launch is not the suspect. +**Clear the HIP error flag before a launch check.** `hipGetLastError()` reports the first error +raised since it was last cleared, so a check that does not clear first attributes to this launch +whatever the process raised before it (in a served process, the previous op; in a comparison run, +its own setup). The symptom is a whole timing mode returning the device code on every geometry of +every row, disappearing under `HIP_LAUNCH_BLOCKING=1` (a synchronous launch clears a pending +asynchronous error before the check). Clear the flag after the arguments are staged and before the +launch, read it straight back, and on a refusal name the error and print the grid, block, waves, +splits and width the launcher chose. -**No collective rows, and no chained forms.** The parts this family ships in are -single-GPU, and an all-reduce over the host link most of them sit on is slower than -sending the bytes through the host. Nothing here is built as a chained form, so both -optional symbols are left out — the ABI's own answer, with one less thing to keep in -step. +**No collective rows and no chained forms.** The parts in this family are single-GPU, and an +all-reduce over the host link most of them sit on is slower than sending the bytes through the +host. Nothing here is built as a chained form, so both optional symbols are omitted, which is the +ABI's own answer. ## What is not here yet -Stated as library work, so nobody looks for it in a row table. +**The 2-bit grid's staging width.** The packed-code tile at prefill heights moves 8x the bytes it +uses at `kKC` 32; the fix is a 64-code chunk (16 bytes per lane) paid for in LDS, which is the +whole gap between 24.151 ms and a 0.449 ms floor at M=64, N=130560, K=2048. -**The 2-bit grid's staging width.** The packed-code tile at prefill heights moves 8× -the bytes it uses at `kKC` 32; the fix is a 64-code chunk (16 bytes a lane) paid for -in LDS — the whole distance between 24.151 ms and a 0.449 ms floor at M=64, N=130560, -K=2048. +**A 16-byte code load for a one-row E4M3 head.** The decode arm loads eight codes per lane through +an 8-byte load and runs 8x above its floor at M=1; the table decoder is not the lever there. -**The skinny-load path for a one-row head.** The E4M3 decode arm loads eight codes a -lane through an 8-byte load and runs 8× above its floor at M=1; the 16-byte load (16 -codes, eight pairs, half the wavefronts) is the experiment, and the decoder table has -been shown not to be the lever. +**A gated MLP pass over rows and column groups.** Past M=64 the fused row refuses and the work is +four ops over a bf16 `[M, N]` tensor (two GEMMs, the gate, the quantiser). At M=64, the ceiling 47 +of the 48 bands declare, the weight read is the limit; a pass that amortises the weight read across +rows and column groups is what is missing. -**The gated MLP's rows-by-column-groups pass.** The table decoder moved M=64 from -8395.3 to 2786.5 us (best of nine), which is most of the row's story at the ceiling -and none of its floor: the weight read is the wall there, and 47 of the 48 bands -declare the ceiling. Past 64 the fused row refuses and the work is four ops over a -bf16 `[M, N]` tensor — two GEMMs, the gate, the quantiser — so the pass that -amortises the weight read across rows *and* column groups is what stands between the -fused form and the pair it replaces, priced at M=64. +**The gated row's arm threshold.** The crossover between the direct and staged arms lies above 16 +rows and M=9..15 is unmeasured; measuring it would move the threshold, not the kernel. -**The gated row's arm threshold is a tunable.** The crossover between the skinny and -staged arms is above 16 rows and M=9..15 has never been measured; the shipped M ≤ 8 is -chosen for the decode's M=1 and a draft's verify, and the launcher's comment says so -beside the number it selects on. Nine launches a band would move the threshold, not the -kernel, and a band that lives in 9..15 is paying the staged arm for about 7%. +**`gemm_nt_q_bias` has no row.** `gemm_nt_q` has no bias operand; bias is its own op in the +registry ("gemm_nt_q with a per-column bias"), and this library declares no row for it. Every band +carrying a bias therefore resolves to the reference's host row: correct and slow, with no `E` line +in the coverage and no profile entry, because nothing refused and the op never reaches a device. A +checkpoint whose bias tensors have count 0 (no planes, no bytes) carries no bias band, by the rule +that an optional operand with no bytes is absent; `rad-info -v | grep -i bias` shows +whether a model's bias tensors have planes. The row would be a bias load in the tiled rows' +epilogue plus a declared schema. -**`gemm_nt_q_bias` has no row, and the gap is silent.** `gemm_nt_q` has no bias -operand: bias is its own op in the registry (`ref_registry.cpp:1361`, "gemm_nt_q with -a per-column bias"), and this library declares no row for it. So every band carrying a -bias resolves to the reference's host row — correct, slow, and invisible: no `E` line -in the coverage, because nothing refused, and no entry in the profile, because the op -never reaches a device. A model with bias'd projections runs them on the host while -the census reports a clean tree. The row is a bias load in the epilogue of the tiled -rows plus a declared schema; the gap is that nobody has to notice it. +**Sliding window over a partial last tile diverges.** With `window` from 2 to 15 over a query plane +whose last tile is not full, the attention row diverges from the reference (for example 17 rows at +ctx 33 with w = 3: `rel_l2` 1.196e+00, status 0 from both rows, no non-finite values). Full +attention (`window = 0`) agrees, and served plans use a 2048 window over 16-wide blocks, so no +served band reaches it. The fix belongs in the last tile's mask, not the window's clamp. -It is a *model-shaped* gap, not a served one, and the container says so: the checkpoint -measured here declares `draft.attention_bias` and `draft.mlp_bias` with **count 0** — -no planes, no bytes — so by the law that an optional operand with no bytes is absent, -this model carries no bias band and nothing falls. `rad-info -v | grep -i bias` -is the one-line census: a model whose bias tensors have planes is the model this row is -for, and on that model the fall is real and silent. +**`sample_merge_topk`**, the cross-rank candidate merge: under a split vocabulary it holds +`world_size * n_cand` gathered pairs, and there is no row for it. -**The sliding window over a partially-filled last tile diverges.** The shape is -`window` between 2 and 16, exclusive of 1 and 16, over a query plane whose last tile is -not full: 10 of 60 cases in the row's window matrix, base and work producing -byte-identical planes for all 60 — 10 divergent each, same hashes — so it is in the -shipped row, not in a session's change. The scan: rows 17 at ctx 33 agree at w = 1 and 16 and diverge at w = 2, 3 and -15; ctx 32 at w = 3 agrees where ctx 34 diverges; rows 32 at ctx 48 — two full tiles — -agree where rows 33 at ctx 49 diverge, tile 3 holding one row; rows 18..24 at ctx + 16 -diverge by two rows each. Five runs of rows 17 at ctx 33, w = 3, give the identical plane -hash (`223c70af1e9e5276`): one row of 17, 2044 of 2048 items differing, `rel_l2` -1.196e+00, status 0 from both rows, no non-finite. Served bands are full attention — all -471 `window = 0` cases agree — and the plan's windowed layers use a 2048 window over -16-wide blocks, so no served band walks into it. It is a bounded, named, reproducible -divergence in a row the plan declares, and the fix belongs in the last tile's mask, not in -the window's clamp. A dedicated comparison run reproduces it. +**A seeded-draw comparison for the spine.** kbench grades the `sample_*` bands against the +reference on the fixture, which covers the arithmetic; nothing yet compares the drawn token against +a captured sequence, over the parameter rows a request actually sends. -**`sample_merge_topk`**, the cross-rank candidate merge: under a split vocabulary it -holds `world_size * n_cand` gathered pairs, and there is no row for it here. +**int8 x int8.** The constraint table is written (`i8a8`, group 128, M <= 16, K % 128) and +`quant_act_i8g` produces the row-major activation it reads; the kernel has not landed, so the row +is not in the table. -**A seeded-draw comparison for the spine.** kbench grades the `sample_*` bands against -the reference on the fixture, which covers the arithmetic and not the recording: no run -compares the *drawn token* against a captured sequence, over the parameter rows a -request actually sends. The draws are the part of this library a `rel_l2` cannot grade. +**Chunked logits.** The head's f32 plane is written whole (1.07 GB at a 2048-row prefill band); +nothing emits it in chunks for the sampler to consume in passes. -**int8 × int8.** The constraint table is written (`i8a8`, group 128, M ≤ 16, K % 128) -and `quant_act_i8g` already produces the row-major activation it wants; the kernel is -not landed, so the row is not in the table, because a row naming an entry point that -is not in the library is an undefined symbol at `dlopen` and takes every other row -with it. +**A sub-byte zero plane.** `w2a8` reads a zero point one byte at a time and refuses a zero stored +as U2/U4/U5 by name; the bit-extract path would be the same `rad_load_bits` the codes use. -**Chunked logits.** The head's f32 plane is written whole (1.07 GB at a 2048-row -prefill band); nothing yet emits it in chunks the sampler consumes in passes. - -**A sub-byte zero plane.** `w2a8` reads a zero point a byte at a time and refuses a -zero stored U2/U4/U5 by name; the bit-extract path is the ten lines `rad_load_bits` -already is for the codes. Written for the codes and not for the zero, and the refusal -is not an approximation. - -**Speculation that pays.** The draft head is served end to end — its bands by the -2-bit grid, its accept step by `dflash_select` — and the accepted text is identical. -The target's head read amortises over the draft block (5× cheaper per token at 8 rows -than at 1 on the same kernel), so what has to pay is the drafter's own steps, and on -the 16-CU part that measured it they did not: 87.6 → 94.4 ms/token on a 5-token -prompt, 91.6 → 187.1 on a 16-token chat band with 7 drafts. The engine's own rule -switches the drafter off for a plugin whose rows measured a gain without them, so the -work left is a draft path that costs less than the head read it saves, not a flag. +**Speculation that pays.** The draft head is served end to end (its bands by the 2-bit grid, its +accept step by `dflash_select`) and the accepted text is identical. The target's head read +amortises over the draft block (5x cheaper per token at 8 rows than at 1 on the same kernel), so +the drafter's own steps have to pay for themselves, and on a 16-CU part they do not (87.6 -> 94.4 +ms per token on a 5-token prompt, 91.6 -> 187.1 on a 16-token chat band with 7 drafts). The +engine switches the drafter off for a plugin whose rows measured a gain without it; what is missing +is a draft path that costs less than the head read it saves. diff --git a/libr3d/r3d.h b/libr3d/r3d.h index e4dae930..1228d9d9 100644 --- a/libr3d/r3d.h +++ b/libr3d/r3d.h @@ -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_(...)`, 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_(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, diff --git a/libr3d/r3d_args.h b/libr3d/r3d_args.h index 4738edf6..0a26eb4b 100644 --- a/libr3d/r3d_args.h +++ b/libr3d/r3d_args.h @@ -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*); diff --git a/libr3d/r3d_attn_paged_h128.hip b/libr3d/r3d_attn_paged_h128.hip index 3838d965..1663bab5 100644 --- a/libr3d/r3d_attn_paged_h128.hip +++ b/libr3d/r3d_attn_paged_h128.hip @@ -1,10 +1,10 @@ -/* r3d_attn_paged_h128.hip -- paged attention at head_dim 128, the two bands MiniCPM5-2B declares. +/* r3d_attn_paged_h128.hip -- paged attention at head_dim 128, decode and prefill bands. * * out[tok, h, :] = softmax_j( scale * q[tok, h, :] . K[j, h/gqa, :] ) . V[j, h/gqa, :] * - * over a paged cache, in libref's order. The order is the point of the file: a - * tolerance on an attention output is not where a summation-order difference hides, so this kernel - * keeps the chain the reference writes, and says out loud where it cannot. + * over a paged cache, in libref's order. A tolerance on an attention output can hide a + * summation-order difference, so the kernel keeps the reference's chain and states where it + * departs from it. * * ============================== the layout ============================== * @@ -12,32 +12,28 @@ * * A slot's K is 128 elements and V the 128 after it, so a key's row is a 512-byte pair and both * halves are 16-byte aligned at every slot. `block_table[seq, j / block_size]` names the block - * holding key j; the fixture *draws* its entries over [0, max_blocks), so ids repeat and one block - * serves several keys. A negative entry is an unmapped block and hides its key -- the engine's - * allocator frees a sequence by writing -1 into rows it is done with, so the kernel keeps the test - * even though the fixture never sets it. `seqused[seq]` is the sequence's TOTAL key count, this - * step's query rows included, so query row i of a len_s-row step sits at absolute position - * `seqused[s] - len_s + i`. One kernel serves decode (q_len 1), a speculative verify (q_len 7) and a - * prefill chunk (q_len 2048). + * holding key j; ids may repeat, so one block can serve several keys. A negative entry is an + * unmapped block and hides its keys (the engine's allocator frees a sequence by writing -1 into + * its rows). `seqused[seq]` is the sequence's total key count, this step's query rows included, so + * query row i of a len_s-row step sits at absolute position `seqused[s] - len_s + i`. One kernel + * serves decode (q_len 1), a speculative verify (q_len 7) and a prefill chunk (q_len 2048). * * ============================== the ragged batch ============================== * - * A step's sequences do not have to contribute the same number of query rows. `cu_seqlens`, when - * the caller has it, is [n_seq + 1] of i32 with cu[0] == 0 and cu[n_seq] == the query plane's row - * count, and sequence s owns the rows [cu[s], cu[s+1]) -- `len_s = cu[s+1] - cu[s]` rows, whose - * positions run from `seqused[s] - len_s`. That is libref's reading and not a local invention: - * its shape hook (`cu[n_seq] == rows`, `q_len = cus ? 0 : rows / n_seq`) and its walk, where - * the row's sequence, its length and its index within the sequence come from the descriptor and the - * position from the sequence's own length. So `q_len` is a PER-SEQUENCE number in the reference and - * in this file; the total row count is the plane's, and a ragged batch has no q_len at all. + * Sequences may contribute different numbers of query rows. `cu_seqlens`, when present, is + * [n_seq + 1] i32 with cu[0] == 0 and cu[n_seq] == the query plane's row count; sequence s owns + * rows [cu[s], cu[s+1]), `len_s = cu[s+1] - cu[s]` of them, at positions from `seqused[s] - len_s`. + * This is libref's reading (its shape hook: `cu[n_seq] == rows`, `q_len = cus ? 0 : rows / n_seq`; + * its walk takes each row's sequence, length and index from the descriptor). So `q_len` is a + * per-sequence number; the total row count is the plane's, and a ragged batch has no q_len. * - * One grid covers a ragged batch because the clamp the width section documents is per sequence: a - * tile is `ceil(len_s / rows_per_tile)` tiles for sequence s, and the slots of its last tile past - * `len_s` compute a duplicate that stores nothing. The rows are laid out by `map_seq`, which walks - * the descriptor once a workgroup -- a rectangular batch is the same walk with len_s = q_len and - * cu[s] = s * q_len, so there is one mapping, one mask, one walk and one store for both forms. - * The causal mask, the window, the block-table walk and the descales all key off the sequence the - * row belongs to, exactly as the reference's `s = seq_of(cus, n_seq, tok)` keys them. + * One grid covers a ragged batch because the clamp described under "the width of a workgroup" is + * per sequence: sequence s gets `ceil(len_s / rows_per_tile)` tiles, and its last tile's slots past + * `len_s` compute a duplicate that stores nothing. `map_seq` lays out the rows by walking the + * descriptor once per workgroup; a rectangular batch is the same walk with len_s = q_len and + * cu[s] = s * q_len, so both forms share one mapping, mask, walk and store. The causal mask, the + * window, the block-table walk and the descales all key off the row's sequence, as the reference's + * `s = seq_of(cus, n_seq, tok)` does. * * ============================== the mask ============================== * @@ -46,192 +42,154 @@ * window > 0 causal: additionally pos - j < window; non-causal: |pos - j| < window, the * two-sided reading libref's prose and libr4d's window kernel both state. * - * A masked key is skipped, never scored to -inf: the denominator gets exactly the terms the - * reference has, and a row with no visible key stores zeros, which is libref's `mx == -INFINITY` - * case and every other kernel in the project. + * A masked key is skipped, never scored to -inf, so the denominator has exactly the reference's + * terms; a row with no visible key stores zeros (libref's `mx == -INFINITY` case). * * ============================== the tile ============================== * * An output row is (query row, query head): 128 dims, one f32 chain per dim. A lane owns one output - * row, exactly as the skinny GEMM rows do, and for the same reason -- a lane's chain over keys is - * the reference's chain, and no cross-lane reduction touches the denominator. A wave32 is 32 output - * rows, and they must be 32 rows that read the same KV, which fixes the mapping: + * row, as in the skinny GEMM rows: the lane's chain over keys is the reference's, and no cross-lane + * reduction touches the denominator. A wave's 32 output rows must read the same KV, which fixes the + * mapping: * * kh = blockIdx.y h = kh * GQA + (lane & (GQA-1)) tok = base + (lane >> lg GQA) * - * so a wave is the GQA query heads of one KV head over 32/GQA query rows -- 8 heads x 4 rows at - * gqa = 8. Every lane of a wave then reads the same cache row at the same moment, which makes every - * cache read in this file an LDS broadcast (one `ds_read_b128` serves the wave) and makes the paged - * walk a per-wave event rather than a per-lane one. A workgroup is WAVES waves = WAVES x 32 threads - * = WAVES x (32/GQA) query rows of one sequence, one KV head: 16 rows at gqa 8 with four waves. - * WAVES is a template parameter and the launcher picks it -- see "the width of a workgroup" below. + * A wave is the GQA query heads of one KV head over 32/GQA query rows (8 heads x 4 rows at gqa 8). + * Every lane of a wave reads the same cache row at the same moment, so every cache read is an LDS + * broadcast (one `ds_read_b128` serves the wave) and the paged walk is per wave, not per lane. A + * workgroup is WAVES waves = WAVES x (32/GQA) query rows of one sequence and one KV head: 16 rows + * at gqa 8 with four waves. WAVES is a template parameter chosen by the launcher (see below). * - * Rows per cache read is 32. It is also the ceiling the register file sets: a lane carrying a second - * output row needs 2 x 64 VGPRs of widened query and 2 x 128 of f32 accumulator, 384, over the 256 - * that four waves a SIMD allows. So the traffic is what gqa and the register file say it is. + * 32 rows per cache read is also the register-file ceiling: a second output row per lane needs + * 2 x 64 VGPRs of widened query and 2 x 128 of f32 accumulator, 384, over the 256 that four waves a + * SIMD allow. * * ============================== the width of a workgroup ============================== * - * A row slot whose row is past its sequence's length computes a clamped duplicate: the walk, the - * tile and the store all run for it and the result is dropped. At the decode band's q_len = 7 with - * gqa = 8 a four-wave workgroup carries 16 row slots for 7 rows -- twice the walk for half the - * outputs. So the launcher picks the narrowest workgroup that carries the caller's q_len (pick_waves: - * one wave to 32/GQA rows, two to 64/GQA, four above), and prefill keeps four because its q_len is the - * whole chunk. At the decode band that is two waves: 512 workgroups of 64 threads, 7 of 8 slots used. - * A ragged batch has no one q_len to pick on: the launcher picks on the average sequence - * (`ceil(rows / n_seq)`), which is a performance choice and nothing else -- the tile width moves - * duplicate rows between tiles, never a result, and no host code reads the descriptor. + * A row slot past its sequence's length computes a clamped duplicate: the walk, the tile and the + * store run and the result is dropped. At q_len = 7 with gqa = 8 a four-wave workgroup carries 16 + * slots for 7 rows, twice the walk for half the outputs. So the launcher picks the narrowest + * workgroup that carries the caller's q_len (pick_waves: one wave up to 32/GQA rows, two up to + * 64/GQA, four above); prefill keeps four because its q_len is the whole chunk. A ragged batch is + * picked on the average sequence (`ceil(rows / n_seq)`); the width only moves duplicate rows + * between tiles, never a result. * - * Measured on the card: medians of 15 per-launch event times, both widths in one session, so the - * clock drifts together (both read the prefill band at 44.9): + * The tile is the same 8 KiB at every width, so the cache traffic is unchanged and the gain comes + * from the duplicated rows. The kernel is issue-starved at the decode bands (about 15% of the + * SIMD's VALU slots at 256 sequences, under 4% at eight), and its cost follows how many waves a + * workgroup brings to each barrier: at q_len 7, gqa 8, two waves take about half the time of four. + * The width is a run-time choice because it is the main lever on this op. * - * decode 256 x 7 @4096 294.7 ms -> 158.4 ms -46% - * decode 256 x 7 @4096 sp4 268.0 ms -> 128.4 ms -52% - * decode 8 x 7 @2048 sp8 4.33 -> 2.06 ms -53% - * decode 1 x 7 @4096 sp8 4.27 -> 3.97 ms -7% - * prefill 2048 x 2048 44.95 -> 44.78 ms the path is unchanged + * ============================== levers that do not help ============================== * - * The tile is the same 8 KiB at every width, so nothing about the cache traffic changes; the win is - * the duplicated rows, and the reason it is this large is the one the counters show: the kernel - * issues 15% of the SIMD's slots at the band (SQ_INSTS_VALU 4.5G against 30G of capacity, - * SQ_INSTS_LDS 769M) and 3.7% at eight sequences. Halving the arithmetic on a kernel that is - * stalling is not supposed to buy 46%; it does, and that says the stall is a function of how many - * waves a workgroup has to bring to a barrier -- two arriving is not twice as cheap as four, it is - * four times cheaper. The width is a run-time choice because it is the only lever on this op that - * moves the band. + * Each of these changed nothing measurable on the decode and prefill bands: * - * ============================== measured, and not the answer ============================== + * s_setprio 1 around the consume leg of the walk (`s_setprio` takes an immediate, not an SGPR). * - * Four things that look like they should work, each measured to not (medians of 15 per-launch - * hipEventElapsedTime, A/B in one process), so the next reader does not spend an hour on them: + * R3D_WAVES(2) to lift the scalar-register ceiling: the bf16 variants report sgpr_count 107 and + * about 98 spilled SGPRs at both 4 and 2 waves a SIMD. The compute-shader scalar budget does not + * follow waves/SIMD the way the VGPR budget does. * - * s_setprio 1 around the consume leg of the walk, 0 after: |delta| <= 0.7% on the bands. The - * knob is fine -- `s_setprio` takes an immediate, not an SGPR, so `s_setprio %0` will not link -- - * but priority does not move this op. + * __noinline__ on the stage leg: spills drop to 72 and a 160-byte private frame appears. Note: + * while the bf16 variants spill SGPRs, a kernel in this TU that also needs a private segment + * fails to launch ("the operation cannot be performed in the present state"). * - * R3D_WAVES(2) to lift the scalar-register ceiling: the bf16 arms report sgpr_count 107 and - * sgpr_spill_count ~98 at BOTH 4 and 2 waves a SIMD, and the timings do not move. The - * compute-shader scalar budget is not set by waves/SIMD the way the VGPR one is, so this is not - * a lever for the spills. - * - * __noinline__ on the stage leg: the spills drop (98 -> 72) and a 160-byte private frame - * appears, timings unchanged. The spills are a load-safety matter, not a time matter: while the - * bf16 arms spill SGPRs, a kernel in this TU that also needs a private segment fails to launch - * with "the operation cannot be performed in the present state". - * - * A two-stage pipeline -- two tiles, the next block's global loads issued before the current - * block is consumed, one barrier a block instead of two: a wash on the bands. The walk's - * per-block structure is the cost, and the two legs do not overlap at all -- the workgroup's - * width is the lever. + * A two-stage pipeline (two tiles, the next block's loads issued before the current one is + * consumed, one barrier a block instead of two): the per-block structure is the cost and the + * legs do not overlap; the workgroup width is the lever. * * ============================== the walk ============================== * - * block_size = 16, so keys advance 16 at a time and one step stages a block of the KV head: 16 slots - * x 128 elements, K and V, widened to f16 pairs on the way in, 4 KiB each. The four waves of a - * workgroup share the stage, so a block of cache is one global read per workgroup per pass, and the - * walk costs 8 KiB of the 64 KiB of LDS. The second pass re-reads the same blocks; a sequence's - * cache for one KV head is ctx x 256 B, which at 4096 keys is 1 MiB, so the second pass is an L2 - * hit and the card's DRAM sees each byte once. + * block_size = 16, so one step stages a block of the KV head: 16 slots x 128 elements, K and V, + * widened to f16 pairs on the way in, 4 KiB each. The waves of a workgroup share the stage, so a + * block is one global read per workgroup per pass, and the walk uses 8 KiB of the 64 KiB of LDS. + * The second pass re-reads the same blocks; one KV head's cache is ctx x 256 B (1 MiB at 4096 + * keys), so the second pass hits L2 and DRAM sees each byte once. * - * The mask sits where the geometry puts it: a wave's query rows are consecutive, so at gqa 8 its - * four positions span 3 and its diagonals lie in one 16-key block, two at a block boundary. Blocks - * entirely below the wave's minimum position are walked with no mask code at all; the one or two - * diagonal blocks test `j <= pos` per lane; blocks past the wave's maximum position are not walked. - * In a 2048-token causal prefill that is one masked block in sixty-four. + * A wave's query rows are consecutive, so at gqa 8 its four positions span 3 and its diagonals lie + * in one 16-key block, or two at a block boundary. Blocks entirely below the wave's minimum + * position need no mask; the one or two diagonal blocks test `j <= pos` per lane; blocks past the + * wave's maximum position are not walked. In a 2048-token causal prefill that is one masked block + * in sixty-four. * * ============================== the two passes ============================== * - * The reference is two-pass: pass one every visible key's score and the maximum; pass two, ascending - * keys, `w = exp(score - max)`, `sum += w`, `acc[d] += w * v[d]`, then `acc * (1/sum)` and one - * narrowing at the store. Online softmax -- the flash form, rescaling a running accumulator by - * `exp(m_old - m_new)` -- brackets the denominator and every acc[d] differently, so it is not in - * this file. Keeping the scores as the reference does costs a workspace of jcap floats a row: 32 - * rows x 4096 keys = 512 KiB a wave against 64 KiB of LDS. So the two passes are two walks, and - * pass two recomputes the scores it needs -- same order, same operands, bit-identical the second - * time. QK is paid twice and the op costs half again what keeping the scores would; that is the - * price of the reference's parentheses. + * The reference is two-pass: pass one finds every visible key's score and the maximum; pass two, + * ascending keys, computes `w = exp(score - max)`, `sum += w`, `acc[d] += w * v[d]`, then + * `acc * (1/sum)` and one narrowing at the store. Online (flash) softmax, rescaling a running + * accumulator by `exp(m_old - m_new)`, brackets the denominator and every acc[d] differently, so it + * is not used. Keeping the scores would need jcap floats a row (32 rows x 4096 keys = 512 KiB a + * wave against 64 KiB of LDS), so pass two recomputes them with the same order and operands, + * bit-identical. QK is paid twice, about 1.5x the cost of keeping the scores. * * QK is 64 `v_dot2acc_f32_f16` a key a lane over widened f16 pairs, ascending d. A dot2 folds a - * pair's two products into the accumulator in one rounding where the reference rounds per product, - * so a lane's score chain brackets the reference's: the same one-ulp departure the bf16 GEMM row - * documents, on a fraction of a percent of outputs, one bf16 store ulp each. + * pair's two products into the accumulator with one rounding where the reference rounds per + * product: the same one-ulp departure the bf16 GEMM row documents, on a fraction of a percent of + * outputs, one bf16 ulp each. * * P . V is 128 f32 multiply-accumulates a key a lane, `acc[d] += w * v[d]` with -ffp-contract=off, - * which is the reference's expression with vds already folded into the staged V. dot2 cannot do this - * leg in this layout: w is a per-lane scalar and the accumulation is per dim, so the only route to - * the matrix path is to fold w into V -- and w is f32, so every weight of the sum would be read to - * 11 bits, a ~1e-4 relative change on the output that survives the bf16 store as a few percent of - * outputs moved one ulp. It is a third of the instruction count, and it is not the default; the - * numbers this unit is measured with are the f32 leg's. + * the reference's expression with vds folded into the staged V. dot2 cannot do this leg here: w is + * a per-lane f32 scalar and the accumulation is per dim, so dot2 would need w folded into V at f16, + * reading every weight to 11 bits (about 1e-4 relative, a few percent of outputs one ulp off after + * the bf16 store). That variant is a third of the instructions and is not used. * * ============================== exp ============================== * - * `ref_exp` is `(float)std::exp((double)x)`: the reference's exponent is correctly rounded to f32 - * through a double. RDNA3 has no vector f64 -- double is soft-float, hundreds of cycles a call, and - * a call per key per lane is the whole kernel. The device libm's `expf` is a ~1-ulp polynomial and - * `__expf` is two orders of magnitude worse. `exp_ref` is a software expf: two-term range reduction - * against a split ln2, a degree-8 polynomial, and 2^k assembled in the integer domain (no libm call - * in the hot path). It is the only place in this library where an explicit `__fmaf_rn` is allowed, - * and the rule it is an exception to is the no-FMA rule: that rule exists because libref's - * expressions contain no FMA and a contracted multiply-add changes the order of rounding in - * arithmetic we are required to reproduce. Here the thing we must reproduce is a *function* libref - * computes in double precision on hardware that has f64 and this card does not. The polynomial's - * FMA is arithmetic we chose, scoped to this helper, to get the closest legal transcription of that - * function; it contracts no expression the reference wrote. + * `ref_exp` is `(float)std::exp((double)x)`, correctly rounded to f32 through a double. RDNA3 has + * no vector f64 (soft-float double costs hundreds of cycles a call), the device libm's `expf` is a + * ~1-ulp polynomial and `__expf` is two orders of magnitude worse. `exp_ref` is a software expf: + * two-term range reduction against a split ln2, a degree-8 polynomial, and 2^k assembled in the + * integer domain. It is the only place in this library where an explicit `__fmaf_rn` is allowed. + * The no-FMA rule exists because libref's expressions contain no FMA; here the target is a + * function libref computes in double, and the polynomial's FMAs are local to this helper and + * contract no expression the reference wrote. * - * `exp(0)` is exactly 1.0: k is 0, the reduction leaves r exactly 0, and the polynomial's constant - * term passes through untouched. The argument here is always <= 0 (the max is taken over the same - * set the exponentials are taken of), so the domain that matters is x <= 0. Below -103.98 the - * result is under f32's smallest subnormal and the helper returns 0; the reference's - * `(float)exp(-100)` is a denormal of order 3.7e-44, and a term that small added to a denominator - * of order 1 is not a change of any kind, let alone one that survives a bf16 store -- which is the - * reason the flush is legal and not an approximation to defend. Between -103.98 and -87.3 the - * result is subnormal, and the helper reaches it by one hardware multiply by 2^-126, so it is - * rounded the way the hardware rounds and not by hand. + * `exp(0)` is exactly 1.0: k is 0, r is exactly 0, and the polynomial's constant term passes + * through. The argument is always <= 0 (the max is over the same set), so only x <= 0 matters. + * Below -103.98 the result is under f32's smallest subnormal and the helper returns 0; the + * reference's value there is of order 1e-44, which cannot change a denominator of order 1 or + * survive a bf16 store. Between -103.98 and -87.3 the result is formed by one hardware multiply by + * 2^-126, which the hardware flushes to zero (see exp_ref). * * ============================== split-KV ============================== * - * The decode entry takes `splits`: a sequence's blocks are cut into slices of a whole number of - * blocks, each slice accumulating its own (acc[128], sum, max) into scratch, and a second kernel - * combines the slices before the single narrowing. Combining needs the slices' maximum, so each - * slice's partial is rescaled by `exp(m_slice - M)`: the denominator becomes - * `sum = Σ_slices sum_s * exp(m_s - M)`, ascending in slice, and every term arrives as - * `exp(s - m_s) * exp(m_s - M)` where the reference has `exp(s - M)`. Both are last-bit at the f32 - * level -- ~2 ulp per term, ~1 ulp on the sum -- and both vanish under the bf16 store except on - * outputs sitting on a rounding boundary. The row's prose says `splits > 1` is not bit-identical to - * the reference and `splits = 1` is. + * The decode entry takes `splits`: a sequence's blocks are cut into slices of whole blocks, each + * accumulating its own (acc[128], sum, max) into scratch, and a second kernel combines the slices + * before the single narrowing. Each slice is rescaled by `exp(m_slice - M)` with M the slices' + * maximum: the denominator becomes the sum over slices of `sum_s * exp(m_s - M)`, ascending in + * slice, and every term arrives as `exp(s - m_s) * exp(m_s - M)` where the reference has + * `exp(s - M)`. That is about 2 f32 ulp per term and 1 on the sum, visible after the bf16 store + * only on outputs at a rounding boundary. `splits > 1` is not bit-identical to the reference; + * `splits = 1` is. * * `splits` is a maximum, resolved per sequence from its own `seqused`: `nslice = ceil(nblk / * ceil(nblk / splits))` with nblk the sequence's block count, so a short sequence uses fewer slices - * and there is no per-sequence legality check to fail. `nslice` is recomputed by the reducer from - * the same two numbers, so the partials need no header beyond (acc, sum, max). + * and there is no per-sequence legality check. The reducer recomputes `nslice` from the same two + * numbers, so a partial needs no header beyond (acc, sum, max). * * ============================== what the shims refuse ============================== * - * head_dim other than 128 (`RAD_E_SHAPE`; this file is named for it); a cache dtype other than bf16 - * and fp8_e4m3 -- an f32 cache has no dot2 path, and u8/u4/int8 codes are not this cache form - * (`RAD_E_DTYPE`); a query dtype other than bf16 or f16, and an out dtype that is not the query's - * (`RAD_E_DTYPE`); gqa outside {1,2,4,8} or not dividing n_head (the wave's head split is a shift); - * block_size other than 16 (the stage is sized for one); q_len < 1 in a rectangular batch, and a - * row count < 1 in a ragged one; a row count that does not fit the plane's 32-bit row indexing - * (num_seqs * q_len, or cu[n_seq], past 2^31); a q, kv or out stride that puts a slot's halves off - * a 16-byte boundary, or a row pitch that is not a multiple of 8; a `cu_seqlens` that is not i32 - * (`RAD_E_DTYPE` -- the kernel reads int, and the fix is an i32 plane, which is what the op - * describes), is not contiguous (`RAD_E_STRIDE`), is not [n_seq + 1] (`RAD_E_SHAPE`), or is not - * 4-byte aligned (`RAD_E_ALIGN`); descales attached to a bf16 cache, which the reference ignores - * and this kernel refuses rather than drops, and an fp8 cache missing them (`RAD_E_SHAPE`); an - * output shorter than rows * n_head * head_dim; and a scratch arena too small for the partials the - * requested `splits` needs, which the launcher answers by lowering `splits` to what the arena - * holds, down to 1, which needs none. + * head_dim other than 128 (`RAD_E_SHAPE`); a cache dtype other than bf16 and fp8_e4m3 (an f32 cache + * has no dot2 path, and u8/u4/int8 codes are not this cache form; `RAD_E_DTYPE`); a query dtype + * other than bf16, and an out dtype that is not the query's (`RAD_E_DTYPE`); gqa outside {1,2,4,8} + * or not dividing n_head (the wave's head split is a shift); block_size other than 16 (the stage is + * sized for it); q_len < 1 in a rectangular batch, and a row count < 1 in a ragged one; a row count + * past 2^31 (num_seqs * q_len, or cu[n_seq]), since row indexing is 32-bit; a q, kv or out stride + * that puts a slot's halves off a 16-byte boundary, or a row pitch that is not a multiple of 8; a + * `cu_seqlens` that is not i32 (`RAD_E_DTYPE`; the kernel reads int), not contiguous + * (`RAD_E_STRIDE`), not [n_seq + 1] (`RAD_E_SHAPE`) or not 4-byte aligned (`RAD_E_ALIGN`); descales + * attached to a bf16 cache, which the reference ignores and this kernel refuses rather than drops, + * and one descale plane without the other (`RAD_E_SHAPE`); an output shorter than + * rows * n_head * head_dim. A scratch arena too small for the requested `splits` is not refused: + * the shim lowers `splits` until the partials fit, down to 1, which needs none. * * What the descriptor carries that the host cannot see is clamped, not refused, because a launcher - * reads no device memory: cu[0] == 0, monotonicity and cu[n_seq] == the plane's row count are the - * description's promises (the reference's shape hook states all three), and the kernel's answer to each - * is the reference's own. Rows past the plane are dropped (`row_ok` tests the plane's row count, so - * a descriptor that runs long cannot write outside `out`); a segment with cu[s+1] <= cu[s] has no - * tiles and contributes no rows, which is the reference's `if (qlen <= 0) return;` - * (the reference's walk); and rows under cu[0] belong to sequence 0 with a negative index into its - * query, which is what `seq_of` gives them. + * reads no device memory. cu[0] == 0, monotonicity and cu[n_seq] == the plane's row count are the + * description's promises (the reference's shape hook states all three), and the kernel handles each + * violation as the reference does: rows past the plane are dropped (`row_ok` tests the plane's row + * count, so a long descriptor cannot write outside `out`); a segment with cu[s+1] <= cu[s] has no + * tiles and contributes no rows (the reference's `if (qlen <= 0) return;`); and rows under cu[0] + * belong to sequence 0 with a negative index into its query, as `seq_of` assigns them. */ #include "r3d.h" #include "r3d_common.h" @@ -243,56 +201,49 @@ #include #include /* size_t, in the arena indexing and the shim's scratch sizing */ -#include /* the device print, behind the budget; the shims already use std::fprintf */ -#include /* std::getenv / std::atoi, in the arming */ +#include /* std::fprintf, the RAD_R3D_TRACE lines */ +#include /* std::getenv / std::atoi, RAD_R3D_TRACE and RAD_R3D_DEV */ /* ================================================================== the device record ring * - * THE LAW. A kernel that calls device `printf` is given an extra implicit argument -- - * `hidden_hostcall_buffer` -- and the engine's AQL dispatcher does not provide it, so a kernel that - * prints is UNDISPATCHABLE BY THE ENGINE: the instrument is not merely silent, the row is refused, - * and a gate that hipLaunches by hand cannot see it. The kernel therefore writes; it does not speak. - * The shim drains the ring to stderr, which is a host facility and costs the kernel nothing. + * Diagnostic instrument, enabled by RAD_R3D_TRACE with its record budget from RAD_R3D_DEV (default + * 64): thread 0 of workgroup (0,0,0) of each attn_kernel launch writes one DevRec describing what + * the launch was handed, and the shim prints the records to stderr as "[r3d dev] L=... ctx=... + * ids=..." lines. * - * Four plugin-owned device globals, and nothing else is added to the kernel: the launch parameters - * are fixed, `RadArgs` is the row's ABI and the plan builds it, so a field cannot join it (and `abi/` - * is untouched). The kernel owns these; the shim resolves them with `hipGetSymbolAddress` (once, - * cached) and, ONLY under `RAD_R3D_TRACE`, writes the budget with `hipMemcpyToSymbol`. + * The kernel writes to memory rather than calling device `printf`: a printing kernel takes an + * implicit `hidden_hostcall_buffer` argument that the engine's AQL dispatcher does not provide, so + * the engine could not dispatch it at all. * - * r3d_dev_budget records left to write; 0 -- its initial value -- means record nothing - * r3d_dev_launches launches seen, incremented once per launch by the same thread that records + * Four plugin-owned device globals hold the state, because neither the launch parameters nor + * `RadArgs` (the row's ABI) can take a new field. The shim writes the budget with + * `hipMemcpyToSymbol` only under RAD_R3D_TRACE: + * + * r3d_dev_budget records left to write; 0, the initial value, means record nothing + * r3d_dev_launches launches seen, incremented once per launch by the recording thread * r3d_dev_widx the ring's write index, bumped once per record written - * r3d_dev_ring kDevRing records, a fixed struct, 216 bytes each: 55 KiB, allocated once + * r3d_dev_ring kDevRing records of 216 bytes each, 55 KiB * - * Why they exist: the engine's recorded pass plays a decode step by writing queue packets, and a - * play never reaches a plugin shim. The shim is not in the path of a played step. The kernel is. So - * the kernel writes down what it was handed: the step's `ctx` as the row reads it off `seqused`, the - * block ids as the walk reads them off the table, the operand addresses baked into the packet, and - * three content folds -- the query row, the K row of the FIRST block the row walks, the K row of the - * LAST one -- so a block whose BYTES move underneath a step is visible: the adopted prefix whose - * recycled block still holds the previous tenant's KV, and the address slip that serves fluent, - * plausible, wrong text. + * The record is written by the kernel because a step replayed from the engine's recorded pass only + * writes queue packets and never calls the shim. A record holds the step's `ctx` as read from + * `seqused`, the block ids the walk reads from the table, the operand addresses in the packet, and + * three content folds (the query row, and the K rows of the first and last blocks the row walks), + * so a block whose contents or address change underneath a step is visible. * - * A played step's record is written on the device and printed at the NEXT shim call, so a served - * log's lines land one step behind the step they describe. The - * record's own `L` and `ctx` restore the order, and the shim's plan line quotes the same counter, so - * the gap between the two prints is the played pass, measured. + * A replayed step's record is printed at the next shim call, one step late; the record's `L` and + * `ctx`, and the counter the shim's plan line quotes, restore the order. * - * Inert when the flag is unset: the budget is 0, so a launch pays one uniform scalar load of a - * global and one not-taken branch, on one thread of one workgroup, plus the atomic increment of the - * counter. The bound is decremented with `atomicSub` -- 16 CUs cannot record 16 copies of one launch - * -- and the counter is `atomicAdd` before it, so a launch counted is a launch that ran, played ones - * included. The ring is bounded (kDevRing slots): a harness that arms more than the ring holds loses - * records, never the count, and the shim says so on one line. + * Cost with the flag unset: a launch pays one atomic increment of the counter, one atomic decrement + * of the budget and a not-taken branch, on one thread of one workgroup. The budget is decremented + * atomically so several workgroups cannot record copies of one launch. A full ring drops records + * but keeps counting, and the shim reports the loss on one line. * - * The counter counts every `attn_kernel` launch, budget or not. It does NOT count the split-KV - * reduce: that kernel is a second launch of a step's work, not a step. */ + * The counter counts every `attn_kernel` launch, budget or not, but not the split-KV reduce. */ enum { kDevRing = 256, kDevIds = 8 }; -/* One launch, as the launch saw it. A fixed plain-old struct: no pointers, no float, no padding the - * reader has to guess. The ids are the row's first kDevIds columns -- `block_size` 16 and a served - * ladder's 21 to 33 token contexts make that two columns, so the whole row fits -- and `idsum` folds - * every column, so a 4096-token context still has one comparable number for its row. */ +/* One launch's record: a fixed plain struct with no pointers, floats or padding. `b` holds the + * row's first kDevIds table columns (two columns cover a short context at block_size 16), and + * `idsum` folds every column so a long context still yields one comparable number. */ struct DevRec { unsigned long long L; /* the launch's own ordinal */ @@ -307,10 +258,8 @@ struct DevRec extern "C" __device__ int r3d_dev_budget = 0; extern "C" __device__ unsigned long long r3d_dev_launches = 0ULL; extern "C" __device__ unsigned r3d_dev_widx = 0u; -/* `= {}` is load-bearing: an uninitialised `__device__` variable emits no host-side symbol, and - * the engine's loader dlopens the plugin with the symbol live, so it stops with - * `undefined symbol: r3d_dev_ring` before a single row is declared. The zero fill is the device - * side's init, and it is what the flag-unset state is. */ +/* `= {}` is required: an uninitialised `__device__` variable emits no host-side symbol, and the + * loader's dlopen then fails with `undefined symbol: r3d_dev_ring` before any row is declared. */ extern "C" __device__ DevRec r3d_dev_ring[kDevRing] = {}; @@ -329,27 +278,23 @@ constexpr int kPartStride = kHeadDim + 4; // acc[128], sum, max, pad -- 528 /* ------------------------------------------------------------------ exp */ -/* exp(x) narrowed to f32, as close to `(float)std::exp((double)x)` as an ALU with no f64 gets. +/* exp(x) narrowed to f32, as close to `(float)std::exp((double)x)` as an ALU without f64 gets. * - * Measured against `(float)std::exp((double)x)` over 1.31M points of [-100, 0] and the boundary - * cases: every point is within one f32 ulp, 76.1% bit-identical (the device libm's expf is 94.0% - * identical and no better in ulps), exp(0) is exactly 1. The tail below 2^-126 -- x under about - * -87.3 -- comes out zero, not subnormal: the scaling multiply that assembles the subnormal is - * flushed by the hardware. That is invisible at the store, which is where the reference is - * compared: a weight of 1e-38 next to a maximum weight of exactly 1 cannot move an accumulator, and - * the bf16 store has no resolution at that ratio. + * Against `(float)std::exp((double)x)` over 1.31M points of [-100, 0] and the boundary cases, + * every point is within one f32 ulp and 76.1% are bit-identical (the device libm's expf: 94.0%, no + * better in ulps); exp(0) is exactly 1. Below 2^-126 (x under about -87.3) the result is zero, not + * subnormal, because the hardware flushes the scaling multiply. That is invisible at the store: a + * weight of 1e-38 beside a maximum weight of 1 cannot move an accumulator. * - * Reduce by ln2 against a two-term constant: k = rn(x / ln2), r = x - k*LN_HI - k*LO with LN_HI the - * high 24 bits of ln2 and LO what is left. A single-term reduction is what makes the naive version - * 1.5 ulp -- k*ln2 is not representable, and the subtraction's cancellation is the whole error - * budget. |r| <= 0.35, where a degree-8 polynomial reaches ~0.55 ulp, then 2^k by exponent - * assembly. */ + * Reduction by ln2 against a two-term constant: k = rn(x / ln2), r = x - k*LN_HI - k*LN_LO with + * LN_HI the high 24 bits of ln2. A single-term reduction costs 1.5 ulp, since k*ln2 is not + * representable and the subtraction's cancellation dominates the error. |r| <= 0.35, where a + * degree-8 polynomial reaches ~0.55 ulp, then 2^k by exponent assembly. */ __device__ __forceinline__ float exp_ref(float x) { - /* Above the overflow point the reference's own double path yields +inf, so this one must too; - * a NaN in, a NaN out. Both cases are outside the softmax's reach (the argument is a score - * minus the row's maximum, never positive), and are here so the function is an exp, not a - * softmax helper with an undefined edge. */ + /* Above the overflow point the reference's double path yields +inf, and so does this; NaN in, + * NaN out. Neither occurs in the softmax (the argument is never positive); they keep the + * function a true exp. */ if (!(x < 88.7228390525719f)) return x == x ? __int_as_float(0x7f800000) : __int_as_float(0x7fc00000); if (x < -103.9720770839916f) return 0.0f; /* under the subnormals: see header */ @@ -390,44 +335,40 @@ struct Args { uint16_t* out; float* part; /* split-KV partials */ - /* Strides are elements, and 32-bit: a cache is blocks x kv_heads x 16 x 256 elements, a row + /* Strides are 32-bit, in elements: a cache is blocks x kv_heads x 16 x 256 elements, a row * pitch is n_head x head_dim, a block table pitch is max_blocks, and the launcher checks that - * each fits. Every address in this kernel is a 64-bit base plus a 32-bit product, and the - * register allocator is out of scalar registers long before it is out of vector ones -- the - * wavefront runs in compute-shader mode, where a scalar spill is not a slow path, it is a - * kernel the runtime refuses to load. */ + * each fits. Every address is a 64-bit base plus a 32-bit product because scalar registers run + * out first: in compute-shader mode a scalar spill is not a slow path but a kernel the runtime + * refuses to load. */ int sb, sh, so, sd; /* cache strides */ int q_rs, o_rs; /* row pitches; the head stride is head_dim */ - int bt_rs; /* the block table row pitch, in entries: the tensor own stride */ - int bt_cs; /* its column stride: 1 for every dense table the engine builds */ /* block table pitch */ + int bt_rs; /* the block table row pitch, in entries: the tensor's own stride */ + int bt_cs; /* its column stride: 1 for every dense table the engine builds */ int n_seq, q_len, rows, n_head, kv_heads, causal, window, jcap, splits, q16, waves; float scale; - DevRec* trace_buf; /* one record slot, a plain hipMalloc buffer: the device - * globals are stubs in a dlopened plugin, the buffer is not */ + DevRec* trace_buf; /* RAD_R3D_TRACE: one record slot in a hipMalloc buffer, which + * the engine process reads back reliably, unlike a dlopened + * plugin's device globals */ }; __device__ __forceinline__ long long ld_ix(const int* p, size_t i) { return p[i]; } /* ------------------------------------------------------------------ the row map * - * One map for both batch forms. With a descriptor, sequence s owns the query rows [cu[s], cu[s+1]) - * -- `len_s` rows, the row's index within the sequence `i = row - cu[s]`, its absolute position + * One map for both batch forms. With a descriptor, sequence s owns query rows [cu[s], cu[s+1]): + * `len_s` rows, the row's index within the sequence `i = row - cu[s]`, its absolute position * `seqused[s] - len_s + i`. Without one, the same walk with len_s = q_len and cu[s] = s * q_len, - * which is the reference's own rectangular reading, not a parallel implementation - * of it. + * the reference's rectangular reading. * * A grid row is resolved by subtracting each sequence's tile count from blockIdx.x until the - * remainder fits: n_seq int loads and n_seq subtractions, once per workgroup, against a walk of - * nblk blocks with two barriers each. The descriptor is device memory and a launcher reads none of - * it, so the grid is sized on the bound in `launch` and a grid row past the batch's last tile comes - * back with tile < 0 and leaves, having staged nothing. + * remainder fits: n_seq loads and subtractions once per workgroup, against a walk of nblk blocks + * with two barriers each. The launcher reads no device memory, so the grid is sized on a bound and + * a grid row past the batch's last tile gets tile < 0 and returns without staging. * * `start` is the sequence's first dense row and `i0` the row its positions count from. They differ - * only when cu[0] > 0: the reference's `seq_of` hands rows under cu[0] to sequence - * 0 with a negative index into its query, and that is transcribed rather than refused because a - * descriptor that does not start at 0 is a caller's arithmetic slip, not a geometry this kernel has - * to be wider than. Both are 32-bit: they index rows of a plane whose element offsets the launcher - * has already checked fit in 31 bits. */ + * only when cu[0] > 0: the reference's `seq_of` assigns rows under cu[0] to sequence 0 with a + * negative index into its query, and that is reproduced rather than refused. Both are 32-bit: the + * launcher has checked that the plane's element offsets fit in 31 bits. */ struct RowMap { int s, tile, start, i0, len, span; }; __device__ __forceinline__ RowMap map_seq(const Args& A, const int tpb, int g) @@ -439,15 +380,12 @@ __device__ __forceinline__ RowMap map_seq(const Args& A, const int tpb, int g) const int start = (s == 0 && c0 > 0) ? 0 : c0; const int nr = c1 - start; const int nt = nr > 0 ? (nr + tpb - 1) / tpb : 0; /* tpb is a template constant */ - /* TWO counts that are easy to conflate. `len` is the sequence's query length, - * cu[s+1] - cu[s], and it is what the positions count from (the reference: qlen, and - * pos = ctx - qlen + i). `span` is the number of rows this sequence's TILES carry, - * cu[s+1] - start, and the two differ by exactly cu[0] on sequence 0 of a descriptor that - * does not start at row 0: `start` reaches below cu[0] because seq_of hands those rows to - * sequence 0 with a negative index, so the tiles must cover `span` rows, and only `len` of - * them are inside the sequence. The store below is checked against the span and the - * positions against the length: bounding the tile slots by `len` drops the last cu[0] - * rows of the QUERY PLANE -- a silent, partial, in-bounds shortfall. */ + /* `len` is the sequence's query length, cu[s+1] - cu[s], which the positions count from + * (the reference's qlen; pos = ctx - qlen + i). `span` is the rows this sequence's tiles + * carry, cu[s+1] - start; the two differ by cu[0] on sequence 0 when the descriptor does + * not start at row 0, because `start` then reaches below cu[0]. Stores are bounded by the + * span and positions by the length; bounding the tiles by `len` would silently drop the + * last cu[0] rows of the query plane. */ if (g < nt) return RowMap{ s, g, start, c0, c1 - c0, nr }; if (s + 1 >= n) return RowMap{ s, -1, start, c0, c1 - c0, nr }; /* past the batch's tiles */ g -= nt; @@ -455,8 +393,8 @@ __device__ __forceinline__ RowMap map_seq(const Args& A, const int tpb, int g) return RowMap{ n - 1, -1, 0, 0, 0, 0 }; } -/* The same walk for a row, not a tile: which sequence owns dense query row `r`. The reducer needs - * it because a partial is indexed by (row, head) and its slice count is the SEQUENCE's block count. */ +/* The same walk for a row rather than a tile: which sequence owns dense query row `r`. The reducer + * needs it because a partial's slice count is the sequence's block count. */ __device__ __forceinline__ int seq_of_row(const Args& A, int r) { const int n = A.n_seq; @@ -469,11 +407,10 @@ __device__ __forceinline__ int seq_of_row(const Args& A, int r) /* ------------------------------------------------------------------ staging */ -/* Sixteen E4M3 codes -- one 16-byte load, the aligned unit a slot's 128-byte half divides into -- as - * eight f16 pairs, descaled on the way. A code is exact in f16, so a power-of-two descale (every real - * cache scale) costs a multiply and no rounding at all; a general descale is rounded once, toward - * zero by the packing instruction, where the reference keeps it in f32. The bf16 path has no descale, - * so it has no rounding to report. */ +/* Sixteen E4M3 codes (one 16-byte load, the aligned unit a slot's 128-byte half divides into) as + * eight f16 pairs, descaled on the way. A code is exact in f16, so a power-of-two descale (every + * real cache scale) costs a multiply and no rounding; a general descale is rounded once, toward + * zero by the packing instruction, where the reference keeps f32. The bf16 path has no descale. */ __device__ __forceinline__ void codes16_to_f16x8(const uint8_t* p, float s, uint32_t* w) { const r3d_u32x4 c = *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)p; @@ -491,17 +428,13 @@ __device__ __forceinline__ void codes16_to_f16x8(const uint8_t* p, float s, uint /* Stage one block of one KV head: 16 slots x 128 elements, K and V, widened to f16 pairs. * - * A slot's halves are 512 bytes apart and each 256 of them, so a bf16 chunk of 8 elements is 16 - * bytes and lands on a 16-byte boundary; an E4M3 chunk of 16 codes is 16 bytes and lands there too. - * A chunk of 8 codes is 8 bytes and does not -- a misaligned 16-byte load on this hardware returns - * garbage, which is the whole difference between the two chunk sizes below. 128 threads, one chunk of - * K and one of V each for the cache, two each for the bf16: 256 chunks of 16 bytes a half, 8 KiB of - * tile, two loads and two stores a thread. + * A slot's halves are 256 bytes each, so an 8-element bf16 chunk is 16 bytes on a 16-byte boundary, + * and so is a 16-code E4M3 chunk. An 8-code chunk would be 8 bytes, and a misaligned 16-byte load + * returns wrong data on this hardware; hence the two chunk sizes. The tile is 8 KiB; at 128 threads + * each thread moves one K and one V chunk for fp8, two of each for bf16. * * Every offset is 32-bit and the launcher has checked that the whole cache fits in 2^31 elements: - * the wavefront runs in compute-shader mode, where a scalar spill is not a slow path but a kernel the - * runtime refuses to load, and 64-bit index arithmetic across a loop like this one is what fills the - * scalar bank. */ + * 64-bit index arithmetic in this loop would exhaust the scalar registers (see Args). */ template __device__ __forceinline__ void stage(Args const& A, uint32_t* sK, uint32_t* sV, int blk, int kh, float kds, float vds, int tid) @@ -509,7 +442,7 @@ __device__ __forceinline__ void stage(Args const& A, uint32_t* sK, uint32_t* sV, constexpr int kC = FP8 ? 16 : 8; /* elements a 16-byte chunk */ constexpr int kCPH = kHeadDim / kC; /* chunks a half, a slot */ constexpr int kChunks = kBlock * kCPH; /* 128 code chunks, 256 bf16 */ - constexpr int kIter = kChunks / NTH; /* bf16: 8, 4, 2 at a wave, two, four */ + constexpr int kIter = kChunks / NTH; /* bf16: 8, 4, 2 at one, two, four waves */ static_assert(kIter * NTH == kChunks, "the stage must divide into whole per-thread trips: " "a bounds check inside the unrolled loop keeps the " "loop from unrolling, and the loop-invariant operands " @@ -565,25 +498,17 @@ __device__ __forceinline__ float score_of(const uint32_t* qf, const uint32_t* kp return dot * scale; } -/* ------------------------------------------------------------------ the launch's own voice +/* ------------------------------------------------------------------ the launch record * - * Two content folds and one line, printed from ONE thread of ONE workgroup of a launch. + * `fold64` is FNV-1a over 64-bit words (multiply and xor per word, no float arithmetic, nothing a + * compiler could contract), so a host-side checker can recompute it exactly. It is order-sensitive, + * so the same elements read at a wrong (e.g. layer-major) offset fold to a different value. * - * `fold64` is FNV-1a over 64-bit words -- multiply, xor, per word; no float arithmetic, no - * reduction that a compiler could contract. The spelling is exact and the board's host-side fold - * copies it byte for byte, because a hash the driver cannot recompute is a number nobody can check. - * It is order-sensitive by construction (a permuted row is a different hash), which is the property - * that makes the layer-major addressing slip visible: the same 128 elements read at a layer-major - * offset fold to something else. - * - * The words are the row's OWN bytes, read as the walk reads them: the query row at - * `q + row * q_rs` for head 0 -- head 0 is the first head of kv-head 0, and 128 bf16 elements are - * the 32 words -- and the K row of the block the walk names FIRST, at `blk * sb + kh * sh + - * slot * so`, the same arithmetic `stage()` uses (this file has no `slot_of` helper; `slot_k_off` - * spells it out here so the print prints it). 128 elements are 16 words of E4M3 codes and 32 of - * bf16. Both rows are 16-byte aligned: the shim checks a 16-aligned cache, query and output base - * and a row pitch that is a multiple of 8 elements, and the header's layout note puts a slot's K on - * a 16-byte boundary at every slot. + * The words are the row's own bytes, read as the walk reads them: the query row at + * `q + row * q_rs` for head 0 (32 words of bf16), and the K row of a block the walk names, at + * `blk * sb + kh * sh + slot * so`, the same arithmetic as `stage()` (`slot_k_off`): 16 words of + * E4M3 or 32 of bf16. Both are 16-byte aligned: the shim checks 16-aligned cache, query and output + * bases and a row pitch that is a multiple of 8 elements. */ __device__ __forceinline__ unsigned long long fold64(const void* p, int words) { @@ -598,44 +523,35 @@ __device__ __forceinline__ long long slot_k_off(const Args& A, int blk, int kh, return (long long)blk * A.sb + (long long)kh * A.sh + (long long)slot * A.so; } -/* One record per launch, from block (0,0,0), thread 0, into the ring. `noinline` on purpose: the - * walk's register budget is the scarcest thing in this file (see the stride note on Args -- a scalar - * spill is a kernel the runtime refuses to load), and a writer that a traced run runs once a launch - * must not be inlined into the middle of the mapping code that every launch runs. +/* One record per launch, from block (0,0,0), thread 0, into the ring. `noinline` keeps the writer + * out of the mapping code every launch runs, because the kernel's register budget is the scarcest + * resource here (see Args). * - * This function reads memory, so its bounds are the subject. THREE reads, three bounds: + * Its three reads are bounded: * - * the query row bound: the PLANE's row count `A.rows`, the same bound the kernel checks - * before it stores (`M.start + tok < A.rows`, in the caller). `row` is the - * caller's clamped row index: the grid is sized on a bound, so a tile can name - * rows the plane does not have, and `row_ok` says whether this one is real. A - * band key (`q_len`) and the sequence's length are bounds on the SHAPE the shim - * accepted, not on the plane, and the clamp exists because the grid exceeds - * them; reading through a band key is the out-of-bounds this guard kills. A tile - * the batch has no rows for records `qh=0, rowok=0` -- the record says it did - * not read, and `L` still counts the launch. - * the table's row bound: the columns the WALK can name, ceil(jcap / block_size), where - * jcap = min(ctx, bt_cols * block_size), so a column under it is a column the - * shim proved when it sized the table from the tensor (row pitch plus bt_cols - * columns fit, at the table's own pitches), and the row is `M.s * bt_rs` with - * `M.s` a sequence index the mapping clamped. - * the cache bound: a block id is one the table names, and the shim insists every index - * the walk can reach is inside the cache's plane (`0 <= id < num_blocks`, plus - * the dense-stride requirement). The fold reads the slot-0 K row of kv-head 0 at - * the offset `stage()` computes, kHeadDim elements: 256 bytes of bf16, 128 of - * fp8, both inside a slot's 2*kHeadDim. A negative id -- an unmapped slot prints - * -1 -- folds to 0 and is not dereferenced. */ + * the query row by the plane's row count `A.rows`, the bound the store uses. `row` is the + * caller's clamped row index and `row_ok` says whether it is real; a band key + * (`q_len`) or the sequence's length bounds the shape, not the plane, so + * reading through one could leave the plane. A tile with no rows records + * `qh=0, rowok=0`, and `L` still counts the launch. + * the table row by the columns the walk can name, ceil(jcap / block_size) with + * jcap = min(ctx, bt_cols * block_size), which the shim proved the table + * covers; the row is `M.s * bt_rs` with `M.s` a clamped sequence index. + * the cache by block ids the table names; the shim requires every index the walk can + * reach to be inside the cache plane (`0 <= id < num_blocks`, dense strides). + * The fold reads kv-head 0's slot-0 K row at the `stage()` offset, kHeadDim + * elements (256 bytes bf16, 128 fp8), inside a slot's 2*kHeadDim. A negative + * id (an unmapped block, printed -1) folds to 0 and is not dereferenced. */ template __device__ __noinline__ void dev_record(const Args& A, const RowMap& M, long long row, bool row_ok, long long ctx, int jend_all, long long pos) { - /* A launch that runs is a launch that is counted, budget or not: this is the number that stops - * the decode steps of a request being inferred from shim lines. */ + /* Every launch that runs is counted, budget or not. */ const unsigned long long n = atomicAdd(&r3d_dev_launches, 1ULL) + 1ULL; - /* The bound, decremented atomically, so 16 CUs cannot record 16 copies of one launch. A caller - * that armed 3 gets 3 records, wherever in the run they fall. The buffer channel bypasses the - * bound: it is one slot per launch, drained at the launch, and the budget is a device global - * that the engine process cannot arm. */ + /* The budget is decremented atomically, so several workgroups cannot record copies of one + * launch; a caller that armed 3 gets 3 records. The buffer channel bypasses the budget: it is one + * slot per launch, read back at the launch, and the engine process cannot arm the device + * global. */ if (!A.trace_buf && atomicSub(&r3d_dev_budget, 1) <= 0) return; DevRec r; @@ -654,15 +570,15 @@ __device__ __noinline__ void dev_record(const Args& A, const RowMap& M, long lon const int cols = (A.jcap + kBlock - 1) / kBlock; /* <= bt_cols, by jcap's bound */ const long long r0 = (long long)M.s * A.bt_rs; r.ncols = cols; - unsigned long long is = 14695981039346656037ULL; /* the fold64 basis, so a sum of ids is a - * fold of them, spelled the same way */ + unsigned long long is = 14695981039346656037ULL; /* fold64's basis: idsum is an FNV-1a + * fold of the ids */ for (int c = 0; c < cols; ++c) { const int b = (int)ld_ix(A.bt, (size_t)r0 + (size_t)c * (size_t)A.bt_cs); is = (is * 1099511628211ULL) ^ (unsigned long long)(unsigned int)b; if (c < kDevIds) r.b[c] = b; } - for (int c = cols; c < kDevIds; ++c) r.b[c] = -2; /* a column the row does not have. -2 is - * not -1, which is an unmapped block */ + for (int c = cols; c < kDevIds; ++c) r.b[c] = -2; /* a column the row does not have; -1 + * means an unmapped block */ r.idsum = (long long)is; /* The query row, under the plane's bound, named above. */ @@ -670,13 +586,12 @@ __device__ __noinline__ void dev_record(const Args& A, const RowMap& M, long lon r.rowok = q_ok ? 1 : 0; r.qh = q_ok ? fold64(A.q + row * (long long)A.q_rs, kHeadDim / 4) : 0ULL; - /* The head K row of the first block the row WALKS, and of the last block it walks. The walk's - * extent is `jend_all = min(ctx, A.jcap)` keys, so the blocks it visits are `ceil(jend_all / - * kBlock)` — NOT the table's `cols`: the table row is the plane's full capacity (64 columns at - * a 4096 cap) and its far columns are `-1` for a short context, a fold of which is a fold of - * nothing. `ncols` and `idsum` keep the whole table row — that is the census — while `kh`, - * `khL`, `slot0`, `slotL` and `bL` are the walk's two ends: the head of an adopted prefix and - * the tail the step is writing, where a recycled block shows up. */ + /* The K rows of the first and last blocks the row walks. The walk covers + * `jend_all = min(ctx, A.jcap)` keys, so it visits ceil(jend_all / kBlock) blocks, not the + * table's `cols`: the table row spans the plane's full capacity and its far columns are -1 for + * a short context. `ncols` and `idsum` cover the whole table row; `kh`, `khL`, `slot0`, `slotL` + * and `bL` describe the walk's two ends, the head of an adopted prefix and the tail being + * written, where a recycled block shows up. */ const int walk_cols = (jend_all + kBlock - 1) / kBlock; const int b0 = walk_cols > 0 ? r.b[0] : -2; const int blast = walk_cols > 0 @@ -688,17 +603,15 @@ __device__ __noinline__ void dev_record(const Args& A, const RowMap& M, long lon r.kh = b0 < 0 ? 0ULL : (FP8 ? fold64(A.kv8 + k0, kHeadDim / 8) : fold64(A.kv + k0, kHeadDim / 4)); r.khL = (kL == 0) ? 0ULL : (FP8 ? fold64(A.kv8 + kL, kHeadDim / 8) : fold64(A.kv + kL, kHeadDim / 4)); - r.spare = blast; /* the id the last fold is of, printed */ + r.spare = blast; /* printed as bL */ r.spare2 = cols; r.spare3 = 0; - /* One slot, claimed by one atomic. Past the ring's end a record is counted and dropped: the - * counter keeps the truth, and the shim prints one line saying how many were lost. The struct is - * filled in a local and copied in one statement so the writer is one block of stores; a drain - * runs at a shim call, after the engine has synced the step, so it reads slots that are written - * whole. */ + /* One slot, claimed by one atomic. Past the ring's end a record is counted and dropped, and the + * shim reports the loss. The record is built in a local and copied in one statement; the drain + * runs at a shim call after the engine has synced the step, so it reads whole records. */ const unsigned w = atomicAdd(&r3d_dev_widx, 1u); if (w < (unsigned)kDevRing) r3d_dev_ring[w] = r; - if (A.trace_buf) A.trace_buf[0] = r; /* the engine-process channel: no symbol between us */ + if (A.trace_buf) A.trace_buf[0] = r; /* read back by launch() */ } /* One wave's work: GQA heads x 32/GQA rows, over its slice of one sequence's blocks, for one KV @@ -718,10 +631,9 @@ void attn_kernel(const Args A) const int tid = (int)threadIdx.x; const int wave = tid >> 5, lane = tid & 31; const RowMap M = map_seq(A, ROWSB, (int)blockIdx.x); - /* A grid row the batch has no tiles for (the grid is sized on a bound), and a sequence with no - * rows (cu[s+1] <= cu[s], the reference's `qlen <= 0`), stage nothing and store nothing. A - * sequence that starts past the query plane -- a descriptor running beyond the operand -- is - * nobody's rows: the plane's row count is the bound the store is checked against below. */ + /* Nothing to do for a grid row past the batch's tiles (the grid is sized on a bound), a + * sequence with no rows (cu[s+1] <= cu[s], the reference's `qlen <= 0`), or a sequence that + * starts past the query plane (a descriptor running beyond the operand). */ if (M.tile < 0 || M.len <= 0 || M.start >= A.rows) return; const int s = M.s; const int tile = M.tile; @@ -732,13 +644,12 @@ void attn_kernel(const Args A) const int tb = tile * ROWSB + wave * TOKS; /* the wave's first row of the sequence */ const int tok = tb + (lane >> LG); /* this lane's, counted inside the sequence */ /* A row the operands do not have: past the rows this sequence's tiles carry (the last tile of - * any sequence, and every tile of a short one in a ragged step), or past the query plane (a - * descriptor that runs long). Both are the clamp the width section documents. The bound is the - * SPAN, not the length: with cu[0] > 0 the span reaches below cu[0], and the rows there are - * the reference's rows too (seq_of gives them to sequence 0), so they are stored. */ + * any sequence, every tile of a short one), or past the query plane (a long descriptor). The + * bound is the span, not the length: with cu[0] > 0 the span reaches below cu[0], and those + * rows belong to sequence 0 in the reference too, so they are stored. */ const bool row_ok = tok < M.span && M.start + tok < A.rows; - /* The clamp target is a row that EXISTS: the wave's first row if the sequence has one, else its - * last, and never past the plane. An idle lane loads a real query row so the walk stays + /* The clamp target is a row that exists: the wave's first row if the sequence has one, else its + * last, never past the plane. An idle lane loads a real query row so the walk stays * branch-free; it never stores. */ int tclamp = tb < M.span ? tb : M.span - 1; if (M.start + tclamp >= A.rows) tclamp = A.rows - 1 - M.start; @@ -751,31 +662,18 @@ void attn_kernel(const Args A) const long long ib = (long long)M.start - M.i0; const long long pos = ctx - M.len + tok + ib; - /* THE LAUNCH WRITES. The shim is not in the path of a played step -- a play writes queue - * packets and never calls `rad_arch_step` (the recorded pass's packet path) -- and this kernel - * is, so the row writes down what the row was - * handed: `ctx` off `seqused`, the block ids off the table at the table's own pitches, the six - * operand addresses baked into the packet, and three content folds. ONE thread of ONE workgroup - * (`blockIdx.z` is the split-KV slice: one launch, not `splits` of them), gated on a global the - * shim writes only under `RAD_R3D_TRACE`. With the flag unset the gate is one load of a zero - * global and a not-taken branch, and the launch records nothing. It does not printf: a kernel - * that does takes the implicit `hidden_hostcall_buffer`, which the AQL backend does not supply, - * and the row stops being dispatchable at all (see the ring's header). - * - * Placed HERE, before the query is widened and long before the walk, so the record covers the - * launch even when the walk's rows are all clamped -- which is why the writer's own read of the - * query row is bounded by the PLANE's rows and not by the band key, and why a clamped tile - * records `qh=0 rowok=0` -- and so the writer's registers are live over the fewest live values - * in the kernel. */ + /* RAD_R3D_TRACE device record (see "the device record ring"): one thread of one workgroup + * (`blockIdx.z` is the split-KV slice, so this is once per launch), gated on the budget global. + * It sits before the query is widened and the walk starts, so the record covers launches whose + * rows are all clamped and the writer overlaps the fewest live values. */ if (blockIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0 && threadIdx.x == 0) dev_record(A, M, row, row_ok, ctx, jend_all, pos); - /* The WORKGROUP's bounds, not the wave's. The stage is one tile shared by the four waves, so - * every wave of a workgroup must walk exactly the same blocks: a range narrowed to a wave's own - * four positions makes the waves stage different blocks over the same LDS, and the last writer - * per 16-byte chunk wins -- a corrupted tile that looks like a numerical error. The positions of - * a workgroup's 4 x TOKS consecutive rows span 4 x TOKS - 1, and keys past the last are nobody's; - * a window cuts the front off as well. The mask that this widens past is per lane and free. */ + /* The workgroup's bounds, not the wave's. All waves share one staged tile, so they must walk + * exactly the same blocks; a range narrowed to one wave's positions would make waves stage + * different blocks into the same LDS and corrupt the tile. A workgroup's ROWSB consecutive rows + * span ROWSB - 1 positions and keys past the last are unused; a window also trims the front. + * The per-lane mask handles the rest. */ const int gb = tile * ROWSB; const long long wmin = ctx - M.len + gb + ib; const long long wmax = wmin + ROWSB - 1; @@ -804,9 +702,8 @@ void attn_kernel(const Args A) const float kds = A.kds ? A.kds[(size_t)s * A.kv_heads + kh] : 1.0f; const float vds = A.vds ? A.vds[(size_t)s * A.kv_heads + kh] : 1.0f; - /* The query row, widened once and kept for both walks: 64 dwords, the lane's own 256 bytes, the - * eight heads of a token contiguous in memory. An idle lane loads its wave's first row so the - * registers hold something and the walk stays branch-free; it never stores. */ + /* The query row, widened once and kept for both walks: 64 dwords, the lane's 256 bytes. An idle + * lane loads its clamped row (see above) and never stores. */ uint32_t qf[kPairs]; { const uint16_t* qp = A.q + row * (long long)A.q_rs + h * kHeadDim; @@ -877,17 +774,12 @@ void attn_kernel(const Args A) } } - /* A row slot past its sequence's length, or past the query plane, is a clamped duplicate: it - * computed a walk, and it stores nothing -- the partial store included, which needs the same - * test BEFORE it. A padding row's `row` clamps to a REAL row, so an unguarded partial store - * puts a second writer into (row, h, slice) -- inside the declared arena, so no bounds check - * sees it -- and the two writers' 132-float records interleave: a slot can end with one lane's - * acc and another lane's (sum, max). The reduce then rescales a full slice's accumulator by - * the other lane's maximum, the combined sum comes out thousands of times too small, and - * `1/sum` hands back a power of two where a logit belongs. The mechanism needs a padding row - * -- q_len < 32/gqa -- so a band that fills its waves (q_len 7 at gqa 8) has none. The slots a - * padding row leaves unwritten are exactly the slots the reduce does not read: its index runs - * to `nrows * n_head`, over real rows only. */ + /* A row slot past its sequence's length or the query plane is a clamped duplicate and stores + * nothing, partial store included. Its `row` clamps to a real row, so an unguarded partial store + * would add a second writer to (row, h, slice), inside the arena where no bounds check sees it; + * the two 132-float records would interleave, the reduce would rescale one lane's accumulator by + * another lane's maximum, and the output would be badly wrong. The reduce reads only real rows + * (`nrows * n_head`), so slots a padding row leaves unwritten are never read. */ if (!row_ok) return; if (SPLIT) { @@ -969,17 +861,15 @@ void attn_reduce(const Args A, long long nrows) /* ================================================================== launchers * - * Both entries take raw addresses and extents, in the library's style, and both assume the dense - * layouts the shim has just checked: the cache at [blocks, kv_heads, 16, 256], a block table whose - * row pitch is exactly ceil(max_ctx / block_size), seqused one i32 a sequence. That is what the - * signatures carry, so the shims refuse anything they cannot describe with it -- a strided cache, a - * wider block table, an i64 index plane. + * Both entries take raw addresses and extents and assume the dense layouts the shim has checked: + * the cache at [blocks, kv_heads, 16, 256] and seqused one i32 a sequence. The shims refuse + * anything else (a strided cache, an i64 index plane). The block table's columns and strides are + * arguments. * - * `cu` is the ragged query descriptor, and with it `q_len` changes meaning: it is the query PLANE's - * row count, the total, which the descriptor's cu[num_seqs] states and libref reads off the tensor - * (`rows = numel(q) / (q_heads * head_dim)`, `cu[n_seq] == rows`). Absent, it - * keeps its per-sequence meaning and the total is num_seqs * q_len. No entry reads the plane: the - * grid is sized on a bound, and the kernel does the walking. + * With `cu` (the ragged descriptor), `q_len` is the query plane's total row count, which + * cu[num_seqs] states and libref reads off the tensor (`rows = numel(q) / (q_heads * head_dim)`); + * without it, `q_len` is per sequence and the total is num_seqs * q_len. No entry reads the + * descriptor: the grid is sized on a bound and the kernel does the walking. */ #define R3D_NEED(cond) do { if (!(cond)) return R3D_NO(RAD_E_SHAPE); } while (0) @@ -1005,16 +895,14 @@ int fill(Args& A, long q, long kv, long bt, long seqused, long k_desc, long v_de if (!q || !kv || !bt || !seqused) return -1; const int kv_heads = n_head / gqa; - /* Two counts that must not be conflated. The CACHE holds - * ceil(max_ctx / block_size) blocks, which bounds the byte offset of a slot address. The TABLE - * has `bt_cols` columns, and the engine sizes it to the step: a five-token prompt with nothing - * behind it is one block, a table of [n_seq, 1]. The walk is bounded by the TABLE -- - * the reference takes max_blocks from `bt->shape[last]`, the row pitch from - * `stride[rank-2]` and the column stride from `stride[rank-1]`, and jend = min(ctx, max_blocks * - * block_size) -- so a context longer than the table has columns is truncated by the reference, - * which is the oracle, and by us, to the same keys. */ + /* Two different counts. The cache holds ceil(max_ctx / block_size) blocks, which bounds a slot + * address. The table has `bt_cols` columns, sized by the engine to the step (a five-token prompt + * with nothing behind it is a [n_seq, 1] table). The walk is bounded by the table, as in the + * reference (max_blocks from `bt->shape[last]`, row pitch `stride[rank-2]`, column stride + * `stride[rank-1]`, jend = min(ctx, max_blocks * block_size)), so a context longer than the + * table is truncated to the same keys. */ const int cache_blocks = (max_ctx + block_size - 1) / block_size; - if (bt_cols < 1 || bt_rs < 1 || bt_cs < 1) return -2; /* RAD_E_STRIDE, said where the shim sees it */ + if (bt_cols < 1 || bt_rs < 1 || bt_cs < 1) return -2; /* the shim refuses this first, RAD_E_STRIDE */ A.q = (const uint16_t*)(uintptr_t)q; A.kv = kv_dt == RAD_BF16 ? (const uint16_t*)(uintptr_t)kv : nullptr; @@ -1042,25 +930,25 @@ int fill(Args& A, long q, long kv, long bt, long seqused, long k_desc, long v_de A.causal = causal ? 1 : 0; A.window = window; A.jcap = max_ctx; if ((long long)bt_cols * block_size < max_ctx) A.jcap = bt_cols * block_size; - if (r3d_trace_on()) /* the walk's reach is a number the shim can print: a context that - * comes back short is a table narrower than the sequence, and - * that is a plan fact, not a kernel fact */ + /* RAD_R3D_TRACE: the table geometry and the walk's reach (jcap). A short jcap means the table + * is narrower than the sequence, a plan fact rather than a kernel one. */ + if (r3d_trace_on()) std::fprintf(stderr, "[r3d] attn: q_len %d rows %ld n_seq %d bs %d bt cols %d pitch %d " "cstride %d max_ctx %d -> jcap %d\n", q_len, rows, num_seqs, block_size, bt_cols, bt_rs, bt_cs, max_ctx, A.jcap); - { /* the record's slot, for the engine process: a plain buffer the kernel can write and the - * shim can read back, no symbol table between them. Inert when the flag is unset. */ + { /* RAD_R3D_TRACE: a one-record hipMalloc buffer the kernel writes and launch() reads back, + * allocated on first traced use. Null when the flag is unset. */ static void* g_trace_buf = nullptr; A.trace_buf = nullptr; if (r3d_trace_on() && !g_trace_buf) (void)hipMalloc(&g_trace_buf, sizeof(DevRec)); if (g_trace_buf) A.trace_buf = (DevRec*)g_trace_buf; } - if (r3d_trace_on()) /* the device's own view, at the launch: the table row, the - * seqused, the KV base, and the first block's bytes -- the - * four things a wrong answer can come from, spoken together. - * The sync is the price: the staging may ride the engine's - * stream, and a read on the default stream is unordered to it. */ + /* RAD_R3D_TRACE: synchronise the device and print, for up to 4 sequences, the first 16 block + * table entries ("[r3d] devstate s=.. bt=..") and seqused with the KV base, then the first + * block id. The device sync is needed because staging may run on the engine's stream, and a + * copy on the default stream is unordered with it. */ + if (r3d_trace_on()) { (void)hipDeviceSynchronize(); const char* kvb = A.kv8 ? (const char*)A.kv8 : (const char*)A.kv; @@ -1083,16 +971,12 @@ int fill(Args& A, long q, long kv, long bt, long seqused, long k_desc, long v_de if (kvb && hipMemcpy(&first, (const char*)A.bt, sizeof(int), hipMemcpyDeviceToHost) == hipSuccess && first >= 0) { - /* The block's bytes are spoken by address only: a D2H of the cache base page faults - * the engine process where the kernel's own read is fine, so the content check stays - * with the board, and the table + base are what the served run speaks. */ - std::fprintf(stderr, "[r3d] devstate first_block=%d (content not read: see the board)\n", + /* Only the block id is printed: a D2H copy from the cache base faults in the engine + * process even where the kernel's own read is fine. */ + std::fprintf(stderr, "[r3d] devstate first_block=%d (block content not read)\n", first); } } - /* The table bounds the walk, as in the reference: a context with more blocks than the - * table has columns stops at the table, which is what the reference does and therefore - * what the fixture and the served numbers say. */ A.scale = scale > 0.0f ? scale : 1.0f / std::sqrt((float)kHeadDim); A.splits = splits > 0 ? splits : 1; A.waves = waves; @@ -1101,16 +985,12 @@ int fill(Args& A, long q, long kv, long bt, long seqused, long k_desc, long v_de return 0; } -/* The narrowest workgroup that carries the caller's q_len. A wave carries 32 / gqa query rows, and - * a row slot whose row is past q_len computes a clamped duplicate: at the decode band's q_len = 7 - * with gqa = 8 a four-wave workgroup spends 9 of its 16 row slots on duplicates, twice the walk for - * half the outputs. The tile is the same 8 KiB at every width -- 16 tokens a block, staged once per - * workgroup -- so a narrower workgroup is the same cache read spread over more workgroups, and - * 512 -> 1024 of them is the fill the counters say the op is short of (15% issue at the band, - * 3.7% at eight sequences, where splits=8 buys 3.6x). Prefill keeps four waves: its q_len is the - * whole chunk, every slot is used, and a smaller workgroup would only re-read the cache. - * The accumulation order does not depend on the width: the softmax sum is over keys, ascending, - * inside one lane, and the rows a wave holds are the same rows shifted by wave * TOKS. */ +/* The narrowest workgroup that carries the caller's q_len (see "the width of a workgroup"). A wave + * carries 32 / gqa query rows, and a slot past q_len computes a clamped duplicate. The tile is the + * same 8 KiB at every width, so a narrower workgroup spreads the same cache reads over more + * workgroups, the occupancy the op lacks at decode. Prefill keeps four waves: its q_len is the + * whole chunk and every slot is used. The accumulation order does not depend on the width: the + * softmax sum is over keys, ascending, inside one lane. */ int pick_waves(int q_len, int gqa) { const int rows = 32 / (gqa > 0 ? gqa : 1); @@ -1118,30 +998,25 @@ int pick_waves(int q_len, int gqa) return w <= 1 ? 1 : (w <= 2 ? 2 : 4); /* the ladder the grid is cut on: 1, 2, 4 */ } -/* The rows one sequence of a batch contributes, as well as a host can know them: the plane's row - * count over the sequence count, rounded up. With a descriptor the true lengths are device memory - * and a launcher reads none of it, so this is what the width and the split count are picked on for a - * ragged step. Both choices move duplicated row slots and grid blocks; neither can move a result, - * which is why the average is legal as a proxy and a per-sequence length is not needed. */ +/* The rows per sequence as a host can know them: the plane's row count over the sequence count, + * rounded up. With a descriptor the true lengths are device memory, so the width and split count of + * a ragged step are picked on this average. Both choices only move duplicated row slots and grid + * blocks, never a result. */ int avg_rows(int rows, int num_seqs) { return num_seqs > 0 ? (rows + num_seqs - 1) / num_seqs : rows; } -/* Every width the ladder can return, at every gqa, must be instantiated and dispatched: pick_waves - * is `ceil(q_len / (32/gqa))` clamped to the ladder, so gqa = 4 asks for W = 4 at q_len > 16, - * gqa = 2 at q_len > 32, gqa = 1 at q_len > 64 -- and the prefill entry passes kWaves = 4 - * unconditionally. The launcher dispatches through `if constexpr (waves_ok<...>::value)`, so a - * missing instantiation compiles the kernel call out: the entry returns RAD_OK, hipGetLastError() - * is clean, and the output plane keeps what the caller put there. A silent no-op is the worst - * failure a kernel row can have: the engine reads its own input back as the attention output. The - * gate therefore asserts the whole ladder, at every gqa -- every width it admits is a width some - * q_len can ask for. */ +/* Every width pick_waves can return must be instantiated at every gqa: gqa = 4 asks for W = 4 at + * q_len > 16, gqa = 2 at q_len > 32, gqa = 1 at q_len > 64, and the prefill entry always passes + * kWaves = 4. The launcher dispatches through `if constexpr (waves_ok<...>::value)`, so a missing + * instantiation silently compiles the launch out: the entry returns RAD_OK and the output keeps + * whatever the caller put there. waves_ok therefore admits the whole ladder. */ template struct waves_ok { static const bool value = (W == 1) || (W == 2) || (W == 4); }; int tok_per_block(int gqa, int waves) { return waves * (32 / (gqa > 0 ? gqa : 1)); } -/* The decode entry's `splits`, when the caller asked for the widest legal: enough workgroups to - * fill the card (16 CUs x two workgroups at four waves a SIMD) and no more, on a doubling ladder. */ +/* The decode entry's `splits` when the caller asked for the widest legal: enough workgroups to fill + * a 16-CU card (two workgroups a CU at four waves a SIMD) and no more, on a doubling ladder. */ int pick_splits(int tiles, int num_seqs, int kv_heads) { const long long blocks = (long long)tiles * num_seqs * kv_heads; @@ -1150,7 +1025,7 @@ int pick_splits(int tiles, int num_seqs, int kv_heads) return sp; } -static void dev_speak(const DevRec& r); /* the record, spoken; defined with the ring below */ +static void dev_speak(const DevRec& r); /* prints a DevRec; defined with the ring below */ int launch(const Args& A, long out, long stream) { @@ -1160,12 +1035,12 @@ int launch(const Args& A, long out, long stream) const int waves = A.waves > 0 ? A.waves : kWaves; const int tpb = tok_per_block(gqa, waves); /* The grid's row count. Rectangular: every sequence has the same tile count, so the product is - * exact and is the grid. Ragged: the tile count is - * sum_s ceil(len_s / tpb), which lives in device memory, so the launch uses the bound + * exact. Ragged: the tile count sum_s ceil(len_s / tpb) is in device memory, so the launch uses + * the bound * sum_s ceil(len_s / tpb) <= ceil(rows / tpb) + n_seq - 1 - * (ceil(x) + ceil(y) <= ceil(x + y) + 1, inducted over the sequences), and `map_seq` sends a grid - * row past the last tile straight home. The slack is at most n_seq - 1 empty workgroups, and an - * empty one stages nothing: it reads n_seq descriptor entries and returns. */ + * (ceil(x) + ceil(y) <= ceil(x + y) + 1, by induction over the sequences), and `map_seq` + * returns early for a grid row past the last tile. The slack is at most n_seq - 1 empty + * workgroups, each reading n_seq descriptor entries and returning. */ const int tiles = A.cu ? (A.rows + tpb - 1) / tpb + A.n_seq - 1 : (A.q_len + tpb - 1) / tpb * A.n_seq; dim3 grid((unsigned)tiles, (unsigned)A.kv_heads, @@ -1181,13 +1056,10 @@ int launch(const Args& A, long out, long stream) #define R3D_ATTN_SEL(GQAV, WAVESV) \ do { \ if constexpr (waves_ok::value) { \ - /* `sel` is three bits, and all eight combinations are reachable: a single-sequence \ - * causal decode picks splits 4 on its own (pick_splits(1, 1, 8) = 4), so sel 6 and 7 \ - * are the engine's most common split shape. Each combination needs its own arm: a \ - * causal-with-splits launch routed into the non-causal instantiation takes its maximum \ - * over keys the row must not see, the softmax loses its top weight to a future key, \ - * and the reduce amplifies the loss into a 1/sum of the wrong size. All eight arms \ - * exist. */ \ + /* `sel` is three bits and all eight combinations are reachable (a single-sequence \ + * causal decode picks splits 4 itself: pick_splits(1, 1, 8) = 4). Each needs its own \ + * arm: a causal split launch routed to the non-causal instantiation would take its \ + * maximum over keys the row must not see. */ \ if (sel == 0) R3D_ATTN(false, false, false, GQAV, WAVESV); \ else if (sel == 1) R3D_ATTN(true, false, false, GQAV, WAVESV); \ else if (sel == 2) R3D_ATTN(false, true, false, GQAV, WAVESV); \ @@ -1207,13 +1079,11 @@ int launch(const Args& A, long out, long stream) } while (0) const int sel = (fp8 ? 1 : 0) | (causal ? 2 : 0) | (A.splits > 1 ? 4 : 0); - /* The flag is cleared HERE, after the arguments are staged and before the chevron, and read - * straight back after it. `hipGetLastError()` reports the first error raised since it was last - * cleared, so a check that does not clear first attributes to this launch whatever the process - * raised before it: in a served process, the op that ran last. A synchronous launch clears a - * pending asynchronous error before the check, so `HIP_LAUNCH_BLOCKING=1` hides a - * misattribution of exactly this kind. A healthy step refused by a symptom it did not cause is - * the failure mode; the launch is not. */ + /* Clear the error flag here, after the arguments are staged and before the chevron, and read + * it right after. `hipGetLastError()` reports the first error since it was last cleared, so + * without the clear this launch would be blamed for an earlier op's error. + * HIP_LAUNCH_BLOCKING=1 hides this kind of misattribution, because a synchronous launch clears a + * pending asynchronous error before the check. */ (void)hipGetLastError(); switch (gqa) { case 1: R3D_ATTN_GQA(1); break; @@ -1227,8 +1097,8 @@ int launch(const Args& A, long out, long stream) { const hipError_t ke = hipGetLastError(); if (ke != hipSuccess) { - /* A launch failure names what it saw: the error, the grid, the workgroup and the width - * the launcher chose. */ + /* Under RAD_R3D_TRACE, a launch failure prints the error, the grid, the workgroup + * size and the chosen width. */ if (r3d_trace_on()) std::fprintf(stderr, "[r3d] attn: %s on the attn launch: grid (%u, %u, %u) block " "%d waves %d gqa %d splits %d rows %d n_seq %d jcap %d\n", @@ -1238,7 +1108,7 @@ int launch(const Args& A, long out, long stream) } } - if (B.trace_buf) { /* the record, spoken at the launch that wrote it: one sync, under the flag */ + if (B.trace_buf) { /* RAD_R3D_TRACE: sync the stream and print this launch's record */ (void)hipStreamSynchronize(st); DevRec rec; if (hipMemcpy(&rec, (const void*)B.trace_buf, sizeof rec, hipMemcpyDeviceToHost) == hipSuccess) @@ -1249,7 +1119,7 @@ int launch(const Args& A, long out, long stream) const long long rows = A.rows; /* the plane's rows: cu[n_seq], or n_seq * q_len */ const long long total = rows * A.n_head; dim3 rg((unsigned)((total + 3) / 4)); - (void)hipGetLastError(); /* the same rule, the same reason */ + (void)hipGetLastError(); /* clear first, as above */ R3D_KLAUNCH(attn_reduce, rg, dim3(128), st, B, rows); const hipError_t re = hipGetLastError(); if (re != hipSuccess) { @@ -1271,11 +1141,10 @@ extern "C" int r3d_attn_decode_h128(long q, long kv, long bt, long seqused, long int window, int causal, float scale, int kv_dt, long q_ld, long out_ld, int splits, long scratch, long stream) { - /* `cu` is the ragged query descriptor and it is served: with it, `q_len` is the query plane's - * row count (see the launchers' header) and the rows per sequence are cu[s+1] - cu[s]. The - * width and the split count are picked on the average sequence, because the descriptor is on the - * device and this function reads no device memory -- both numbers choose how many row slots are - * duplicated, and neither touches a result. */ + /* With `cu` (the ragged descriptor) `q_len` is the query plane's row count (see the launchers' + * header) and a sequence's rows are cu[s+1] - cu[s]. The width and split count are picked on + * the average sequence because the descriptor is device memory; both only change how many row + * slots are duplicated, never a result. */ if (splits < 0) return -2; if (gqa <= 0 || n_head <= 0 || n_head % gqa) return -2; if (cu && num_seqs <= 0) return -2; @@ -1300,15 +1169,12 @@ extern "C" int r3d_attn_prefill_h128(long q, long kv, long bt, long seqused, lon long q_ld, long out_ld, long scratch, long stream) { (void)scratch; /* the prefill kernel has no split pass, so no partials */ - /* The width is kWaves with a descriptor or without one. A rectangular prefill's q_len is the - * whole chunk, so every slot of a four-wave workgroup is used; a ragged step's rows are laid - * out by the same workgroup, and the width that matters on a step with only a few rows in it is - * how many waves the GPU gets, not how many slots go unused. A 5-row step at gqa 8 is one - * workgroup per KV head: two waves is 2 x 2 wavefronts over 16 CUs, four waves is 2 x 4, and - * the measured 5-row launch at 2048 keys is 16.7 ms at four waves against 19.3 at two, with the - * duplicate slots costing nothing because a wave walks its tile once whatever rows it carries. - * A step whose rows are one per sequence is a decode step and goes to the decode entry, which - * picks its width on the average sequence -- that is where a narrow workgroup is the win. */ + /* Four waves with or without a descriptor. A rectangular prefill's q_len is the whole chunk, so + * every slot is used. For a ragged step with few rows the number of waves on the GPU matters + * more than unused slots: a 5-row step at gqa 8 is one workgroup per KV head, and four waves run + * faster than two (16.7 vs 19.3 ms at 2048 keys), since a wave walks its tile once whatever rows + * it carries. A step with one row per sequence is a decode step and goes to the decode entry, + * where a narrow workgroup pays. */ Args A; const int waves = kWaves; const int e = fill(A, q, kv, bt, seqused, k_desc, v_desc, cu, cu ? q_len : 0, num_seqs, @@ -1332,32 +1198,22 @@ enum { P_Q = 0, P_KV = 1, P_BT = 2, P_SU = 3, P_KDS = 4, P_VDS = 5, P_CU = 6, P_ /* ---- arming the device record ring ---------------------------------------------------------- * - * The kernel's four globals (`r3d_dev_budget`, `r3d_dev_launches`, `r3d_dev_widx`, `r3d_dev_ring`) - * are plugin-owned, at file scope, `extern "C"` so the names are the ones the code object carries. - * `RadArgs` is the row's ABI and the plan builds it, so nothing joins it; the kernel's launch - * parameters are fixed, so nothing joins them. The shim's whole instrument surface is therefore four - * symbols: + * The ring's four globals are plugin-owned, at file scope, and `extern "C"` so the code object + * carries these names. The shim's interface to them, all under RAD_R3D_TRACE: * - * hipGetSymbolAddress, once, cached -- the counter, for the plan line to quote - * hipMemcpyToSymbol of the budget, under RAD_R3D_TRACE ONLY -- 0 means the kernel records nothing - * hipMemcpy of the ring, under RAD_R3D_TRACE -- the drain: the records to stderr, host-side - * hipMemcpyToSymbol of the write index -- the drain's reset, so a record is spoken once + * hipGetSymbolAddress of the budget, once -- checks the symbol resolves before arming + * hipMemcpyToSymbol of the budget -- RAD_R3D_DEV records (default 64; 0 records nothing) + * hipMemcpyFromSymbol of the counter -- quoted on the plan line as `dev_launches=` + * hipMemcpyFromSymbol of the ring -- the drain: records printed as "[r3d dev]" lines + * hipMemcpyToSymbol of the write index -- the drain's reset, so each record prints once * - * The budget is re-written on every traced call, not once per process, and `RAD_R3D_DEV` is its - * size (default 64). Re-arming is one 4-byte copy under a flag that already does four device reads - * a line, and it buys the property the board needs: a harness can arm exactly -- arm 3, launch 10, - * count 3 -- between launches, with the kernel untouched. The last write wins, so a served ladder - * re-arms at every prefill and the budget never runs dry mid-request. + * The drain and the arming run on every traced shim call, drain first. The budget is rewritten on + * each call, so a caller can arm an exact count between launches (arm 3, launch 10, get 3) and + * the last write wins. A replayed step makes no shim call, so its records print at the next call, + * one step late; `L` and `ctx` restore the order. * - * The drain runs on every traced call too, BEFORE the arming: it speaks the records the kernel has - * written since the last call. For a played step there is no shim call in between, so its lines land - * at the next step's shim call, one step behind the step they describe. The record's `L` and `ctx` - * restore the order, and the plan line's `dev_launches=` quote is the counter the kernel itself ran, - * so the two prints of one step line up and the gap between them is the played pass, measured. - * - * Inert when the flag is unset: `dev_ring_drain` and `dev_trace_arm` return before the runtime call, - * the budget keeps its initial 0, and every kernel gates on it. Nothing here is on the served path - * at all: the shim calls them from inside its existing `r3d_trace_on()` arm. + * With the flag unset, `dev_ring_drain` and `dev_trace_arm` return before any runtime call and the + * budget stays 0. */ enum { kDevPrintDefault = 64 }; @@ -1379,11 +1235,10 @@ void* g_dev_launches = nullptr; unsigned long long dev_launch_count() { - /* `hipMemcpyFromSymbol`, not `hipGetSymbolAddress` + `hipMemcpy`: the arming's - * `hipMemcpyToSymbol` resolves the stub the runtime owns, and in the engine process a - * `hipGetSymbolAddress` on a dlopened plugin's symbol can hand back an address the kernel's - * module does not write to -- the read is a copy of the initial value, forever. The same stub - * resolution the arming uses is the one the read must use. */ + /* `hipMemcpyFromSymbol`, not `hipGetSymbolAddress` + `hipMemcpy`: in the engine process + * `hipGetSymbolAddress` on a dlopened plugin's symbol can return an address the kernel's module + * does not write, so the read would only ever see the initial value. The read must resolve the + * symbol the same way the arming's `hipMemcpyToSymbol` does. */ unsigned long long n = 0; (void)hipMemcpyFromSymbol(&n, HIP_SYMBOL(r3d_dev_launches), sizeof n); return n; @@ -1392,9 +1247,9 @@ unsigned long long dev_launch_count() void* g_dev_widx = nullptr; void* g_dev_ring = nullptr; -/* One record, spoken. The format is the line the board parses: the same field names in the same - * order, `ids=` the row's columns, `kh` the fold of the FIRST block it walks and `khL` the fold of - * the LAST, `idsum` a fold of every column so a long row is one comparable number. */ +/* Prints one record as a "[r3d dev] L=... ids=... idsum=..." line; the field names and order are + * a format log tooling parses. `kh` folds the first block walked, `khL` the last, and `idsum` every + * table column. */ static void dev_speak(const DevRec& r) { std::fprintf(stderr, "[r3d dev] L=%llu dec=%d n_seq=%d rows=%d q_len=%d s=%d len=%d span=%d " @@ -1412,16 +1267,13 @@ static void dev_speak(const DevRec& r) r.rowok); } -/* The ring, spoken. The drain is a D2H of at most kDevRing records (55 KiB) on a traced call: one - * sync per shim call, under the flag only. The index is the kernel's own, so the drain can never - * read past what the kernel wrote, and the reset is to 0, not to a moving base: a record is spoken - * exactly once, and the counter -- which the drain does not touch -- is the launch census. */ +/* Copies at most kDevRing records (55 KiB) from the ring and prints them, then resets the write + * index to 0 so each record prints once. The index is the kernel's own, so the drain never reads + * past what the kernel wrote. The launch counter is not touched. */ void dev_ring_drain() { if (!r3d_trace_on()) return; - /* The reads go through `hipMemcpyFromSymbol`, the same stub resolution the arming's - * `hipMemcpyToSymbol` uses (see `dev_launch_count`): in the engine process a - * `hipGetSymbolAddress` on a dlopened plugin's symbol is not the address the kernel writes. */ + /* Read through `hipMemcpyFromSymbol` for the reason given at `dev_launch_count`. */ unsigned w = 0; if (hipMemcpyFromSymbol(&w, HIP_SYMBOL(r3d_dev_widx), sizeof w) != hipSuccess) return; if (w == 0) return; @@ -1431,19 +1283,18 @@ void dev_ring_drain() return; for (unsigned i = 0; i < keep; ++i) dev_speak(buf[i]); if (w > keep) - std::fprintf(stderr, "[r3d dev] ring: %u records written, %u kept, %u counted and dropped " - "-- the counter is the truth\n", w, keep, w - keep); + std::fprintf(stderr, "[r3d dev] ring: %u records written, %u kept, %u counted and dropped\n", w, keep, w - keep); const unsigned zero = 0u; (void)hipMemcpyToSymbol(HIP_SYMBOL(r3d_dev_widx), &zero, sizeof zero); } void dev_trace_arm() { - if (!r3d_trace_on()) return; /* the gate: with the flag unset, nothing here */ + if (!r3d_trace_on()) return; /* RAD_R3D_TRACE unset: no-op */ int want = kDevPrintDefault; if (const char* e = std::getenv("RAD_R3D_DEV")) { const int v = std::atoi(e); - if (v > 0) want = v; /* a harness arms exactly; 0 disables */ + if (v > 0) want = v; /* an exact count; 0 disables */ else if (v == 0) want = 0; } static bool said = false; @@ -1458,33 +1309,26 @@ void dev_trace_arm() } -/* ---- the plan line: the one number a launcher has never been able to read ---------------------- +/* ---- the plan line ---------------------------------------------------------------------------- * - * `cu_seqlens` is device memory -- the header's rule is that a launcher reads none of it -- and the - * walk's bound is a single value inside it: `cu[0]`. The served descriptors start at row 0. Under - * RAD_R3D_TRACE=1 this stops being an inference: the shim copies the descriptor's `n_seq + 1` i32 - * and prints them, once per shape. + * Under RAD_R3D_TRACE, prints one "[r3d] plan:" line per distinct shape: the batch geometry, the + * walk's reach (jcap), the chosen width and splits, `seqused[0]`, the operand addresses, the + * kernel's launch counter, the descriptor (`cu[0]`, `cu[n_seq]`, all of it when n_seq + 1 <= 8) and + * the first row of the block table. The launcher never reads `cu_seqlens`, so this is the only + * place its contents are visible. * - * Inert when the flag is unset. Everything below sits behind `r3d_trace_on()`, the cached flag load - * `R3D_NO` already pays on a path that is failing anyway: no copy, no latch, no syscall, and no - * operand the served path did not already touch. + * Every read is bounded. The descriptor holds exactly `n_seq + 1` ints (checked by the shim) and + * the copy is capped at `kCuPrint`, with the last entry read separately when the plane is wider. + * `seqused` is read for its first int only. The descriptor is read only after `r3d_has(CU)`, and + * `SU->data` is required at the top of the shim. `hipMemcpyDefault` works for VRAM and host-mapped + * planes alike. * - * The reads, all of them bounded. The descriptor's plane holds exactly `n_seq + 1` ints -- the shim - * has proved `r3d_numel(CU) == n_seq + 1` above -- and the copy is capped at `kCuPrint` of them, - * with the LAST entry taken by its own one-int read when the plane is wider, so the printed total is - * the total and nothing past the plane is touched. `seqused` is read for ONE int, its first, because - * `ctx` is `seqused[0]` and a plan line that cannot say where the walk bounds is - * half a line. A null pointer is never dereferenced: the descriptor is read only after `r3d_has(CU)` - * said it carries bytes, and `SU->data` was required at the top of the shim. `hipMemcpyDefault` is - * placement-agnostic, so the same line prints for a vram plane and for a host-mapped one. - * - * The latch is keyed on the shape -- n_seq, the plane's rows, the kernel's q_len, the table's - * columns -- because the engine calls this shim once a layer a step and 42 identical lines are - * noise. It is a plain static array with no lock: the worst a race can do here is print a shape - * twice, and nothing at all when the flag is off. */ + * The latch is keyed on the shape (n_seq, the plane's rows, the kernel's q_len, the table's + * columns) because the shim runs once a layer a step. It is a plain static array with no lock: a + * race can at worst print a shape twice. */ enum { kCuPrint = 64, kPlanShapes = 512 }; -/* RAD_R3D_TRACE=2 is the same instrument with ctx in the shape key (see plan_once). Read once. */ +/* RAD_R3D_TRACE=2: the same plan line with ctx added to the shape key (see plan_once). Read once. */ bool r3d_trace_wide() { static int wide = -1; @@ -1495,12 +1339,10 @@ bool r3d_trace_wide() return wide != 0; } -/* The shape key: n_seq, the plane's rows, the kernel's q_len, the table's - * columns. `ctx` rides along ONLY under RAD_R3D_TRACE=2, which is the wide form of the same - * instrument: a serving engine's requests all share the shape (rows 1, one sequence, 128 columns) - * and differ only in how deep the context has grown, so with the narrow key the block table prints - * once for the FIRST request and the requests that matter -- the ones after six blocks are in play - * -- never print. The default (=1) is the narrow key. */ +/* The plan line's shape key: n_seq, the plane's rows, the kernel's q_len, the table's columns and, + * under RAD_R3D_TRACE=2 only, `ctx`. Serving requests usually share one shape and differ only in + * context depth, so the narrow key prints the block table once, for the first request; the wide + * key prints again as the context grows. */ struct PlanKey { long long n_seq, rows, q_len, cols, ctx; }; bool plan_once(long long n_seq, long long rows, long long q_len, long long cols, long long ctx, @@ -1531,8 +1373,7 @@ void plan_line(bool decode, const RadTensor* Q, const RadTensor* KV, const RadTe if (r3d_p(SU) && hipMemcpy(&ctx0, r3d_p(SU), sizeof(int), hipMemcpyDefault) == hipSuccess) ctx = ctx0; - /* The latch lives here, after the one-int ctx read, because the wide key is keyed on it. This - * whole function is called only under the flag, so the served path pays none of it. */ + /* The latch comes after the ctx read because the wide key includes ctx. */ if (!plan_once(n_seq, rows, q_len, bt_cols, ctx, by_ctx)) return; std::fprintf(stderr, @@ -1542,24 +1383,17 @@ void plan_line(bool decode, const RadTensor* Q, const RadTensor* KV, const RadTe r3d_has(CU) ? (unsigned)CU->rank : 0u, r3d_has(CU) ? r3d_numel(CU) : 0LL, ctx, bt_cols, bt_rs, max_ctx, jcap, waves, splits); - /* The ADDRESSES the launch bakes. The engine captures this step into a graph after two eager - * decode steps -- one request generating twelve tokens calls this shim for the prefill and for - * two decode steps, and for nothing after that -- and a replay re-runs the kernels with the - * ARGUMENTS frozen at capture. The planes a step reads are named by address in those arguments, - * so if a later request's plan lives at different addresses, a replay is reading the earlier - * request's planes and no per-row fixture, ladder or descriptor print can see it. `%p` of the - * five operands this step reads and the one it writes, nothing dereferenced. */ + /* The addresses the launch bakes into its arguments. A replayed graph re-runs the kernels with + * the arguments frozen at capture, so if a later request's planes live at other addresses the + * replay reads the earlier request's planes. Printed with `%p`, nothing dereferenced. */ std::fprintf(stderr, " q=%p kv=%p bt=%p cu=%p su=%p out=%p part=%p", r3d_p(Q), r3d_p(KV), r3d_p(BT), r3d_p(CU), r3d_p(SU), r3d_p(O), scratch); - /* The kernel's own launch counter, quoted on the shim's line so the two prints of one step line - * up: the shim sees a served request's prefill and its first two decode steps, the kernel sees - * every one, and the gap between the two numbers IS the played pass. One 8-byte device read, - * under the flag, on a line that is already reading three planes. */ + /* The kernel's own launch counter, so the shim's line and the kernel's records line up; the + * shim sees only eagerly issued steps, the kernel every launch. One 8-byte device read. */ std::fprintf(stderr, " dev_launches=%llu", (unsigned long long)dev_launch_count()); - if (!r3d_has(CU)) { /* an absent optional operand is ABSENT, not a refusal: the - rectangular step is the common case and it says so */ + if (!r3d_has(CU)) { /* no descriptor: a rectangular step */ std::fprintf(stderr, " cu=absent (rectangular)"); } else { int cuh[kCuPrint]; @@ -1583,13 +1417,10 @@ void plan_line(bool decode, const RadTensor* Q, const RadTensor* KV, const RadTe } } - /* The block table's own entries for the row this step walks. The walk's arithmetic -- which - * block holds key j -- is the one part of the plan this file cannot check from the descriptor, - * and a reused block id inside one row, or an id the cache does not have, is invisible to every - * per-row fixture (the drivers deal their ids from a shuffled pool, so they cannot produce the - * first). Bounded three ways: at most `kCuPrint` columns of ONE row, only columns the shim has - * already proved the plane covers (the reach check above), and row 1's first entry only when - * there is a row 1. A -1 is an unmapped block and prints as -1, which is what the kernel sees. */ + /* The block table entries of the first row the step walks: a reused block id inside one row, + * or an id the cache does not have, is otherwise invisible. Bounded to `kCuPrint` columns of row + * 0, only columns the shim proved the plane covers, plus row 1's first entry when there is a + * row 1. An unmapped block prints as -1, as the kernel sees it. */ if (r3d_has(BT)) { const int take = (int)(bt_cols < kCuPrint ? bt_cols : kCuPrint); int bth[kCuPrint]; @@ -1628,11 +1459,9 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode) const RadTensor* CU = r3d_opt(a, P_CU); if (!Q || !KV || !BT || !SU || !O) return R3D_NO(RAD_E_INVAL); if (!Q->data || !KV->data || !BT->data || !SU->data || !O->data) return R3D_NO(RAD_E_INVAL); - /* `cu_seqlens` present is a ragged batch, and this file serves it: the row map, the positions, - * the mask and the walk all key off the sequence a row belongs to, which is what the descriptor - * says it is (see "the ragged batch" in the header). The descriptor is device memory, so what - * the shim can check here is its shape and dtype; what it cannot see -- cu[0] == 0, monotonicity, - * cu[n_seq] == the plane's row count -- the kernel clamps, exactly as libref's row loop does. */ + /* `cu_seqlens` present means a ragged batch (see "the ragged batch" in the header). The shim + * can check the descriptor's shape and dtype; what it cannot see (cu[0] == 0, monotonicity, + * cu[n_seq] == the plane's row count) the kernel clamps, as libref's row loop does. */ const bool ragged = r3d_has(CU); const int head_dim = (int)r3d_geti_or(a, "head_dim", r3d_dim(Q, (int)Q->rank - 1)); @@ -1643,29 +1472,24 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode) const int window = (int)r3d_geti_or(a, "window", 0); const float scale = (float)r3d_getf(a, "scale", 0.0); - /* The kernel's f16 query path is written -- `A.q16` makes the widening a copy -- but the - * launcher's signature carries one dtype slot, `kv_dt`, and it is the cache's, so the shim has - * no way to tell the kernel that q is f16: the flag would sit at zero and the kernel would - * widen f16 codes as bf16, a 2^9 scale error, not a rounding difference. Refused until `q_dt` - * joins the signature. A row set that widens `q_dtype` to "bf16 f16" must land with that - * parameter. */ + /* The kernel has an f16 query path (`A.q16`), but the launcher's only dtype argument, `kv_dt`, + * is the cache's, so the shim cannot tell the kernel that q is f16 and it would widen f16 as + * bf16. f16 queries are refused until a `q_dt` argument exists; widening the row's `q_dtype` to + * "bf16 f16" requires it. */ if (Q->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); if (O->dtype != Q->dtype) return R3D_NO(RAD_E_DTYPE); if (KV->dtype != RAD_BF16 && KV->dtype != RAD_F8E4M3) return R3D_NO(RAD_E_DTYPE); if (BT->dtype != RAD_I32 || SU->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); const bool quant = KV->dtype == RAD_F8E4M3; - /* A quantised cache with no descale plane is a cache with scale 1.0, not a refused geometry. - * The reference reads the planes only when they are there: + /* A quantised cache without descale planes has scale 1.0. The reference reads the planes only + * when present: * const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f; * const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f; - * and says it in prose ("the scales are the reader's descales, default 1.0"). - * The op's operand description describes both planes as ABSENT, so a fixture that draws this - * op hands every implementation null descales; refusing them is refusing the case class. The - * kernel already carries the null through and widens at 1.0 (`A.kds ? ... : 1.0f`). */ + * and the op's operand description marks both optional, so the kernel carries the null through + * (`A.kds ? ... : 1.0f`). */ const bool kgiven = KDS && KDS->data, vgiven = VDS && VDS->data; if (!quant && (kgiven || vgiven)) - return R3D_NO(RAD_E_SHAPE); /* a bf16 cache has no scales: the caller believes something - the op does not have, and dropping that quietly is worse */ + return R3D_NO(RAD_E_SHAPE); /* a bf16 cache has no scales; refused, not ignored */ if (quant && kgiven && !r3d_is_f32(KDS)) return R3D_NO(RAD_E_DTYPE); if (quant && vgiven && !r3d_is_f32(VDS)) return R3D_NO(RAD_E_DTYPE); @@ -1683,8 +1507,7 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode) const long long n_seq = r3d_numel(SU); if (n_seq < 1 || n_seq > 65536) return R3D_NO(RAD_E_SHAPE); /* The descriptor is [n_seq + 1] i32, contiguous: the kernel reads it with int indices, so an - * i64 plane is not a wider form of the same operand, it is the wrong operand, and the fix is the - * plane the op's description names. `seqused` is read the same way and is checked below. */ + * i64 plane is refused rather than misread. `seqused` is checked the same way below. */ if (ragged) { if (CU->dtype != RAD_I32) { r3d_trace_desc("cu_seqlens", CU); return R3D_NO(RAD_E_DTYPE); } if (!r3d_contig(CU)) { r3d_trace_desc("cu_seqlens", CU); return R3D_NO(RAD_E_STRIDE); } @@ -1698,12 +1521,10 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode) if (!r3d_head_rows(O, kHeadDim, &ot, &oh, &old) || oh != n_head) { r3d_trace_desc("out", O); return R3D_NO(RAD_E_STRIDE); } if (qld % 8 || old % 8) return R3D_NO(RAD_E_STRIDE); - /* Rows per sequence: the plane's row count divided by the sequence count when the batch is - * rectangular, and nothing at all when it is ragged -- the reference's `q_len = cus ? 0 : - * rows / n_seq` (the reference's reading), with the plane's row count (its `rows`, and the number a - * descriptor's cu[n_seq] equals) carried to the launcher as the row count. A ragged batch is not - * required to divide: 5 rows over 3 sequences is the case the engine sends, and `qt % n_seq` is - * exactly the shape it arrives in. */ + /* Rows per sequence: the plane's row count over the sequence count for a rectangular batch. + * For a ragged one the reference's `q_len = cus ? 0 : rows / n_seq` applies, and the plane's + * row count (which cu[n_seq] equals) is passed as the row count. A ragged batch need not divide + * evenly (5 rows over 3 sequences is a normal shape). */ if (qt < 1) return R3D_NO(RAD_E_SHAPE); if (qt > 2147483000LL) return R3D_NO(RAD_E_SHAPE); /* the kernel's row index is 32-bit */ if (!ragged && qt % n_seq) return R3D_NO(RAD_E_SHAPE); @@ -1720,13 +1541,12 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode) /* The cache is dense and the launcher assumes it: a slot's halves must land on a 16-byte * boundary at every slot, so the cache's strides have to be the dense ones. */ if (!r3d_contig(KV)) { r3d_trace_desc("kv", KV); return R3D_NO(RAD_E_STRIDE); } - /* The table is the engine's, sized to the step, so its geometry comes from the tensor and not - * from the band: `max_blocks` is the TABLE's columns, the row pitch is `stride[rank-2]` and the - * column stride `stride[rank-1]` (the reference's table read). A five-token prompt carries - * [n_seq, 1]: one block per sequence, because nothing is behind it. What the shim insists on is - * that every index the walk can reach is inside the plane -- the last row's pitch plus the last - * column it can name: a contiguity check asks for a table as wide as the cache and refuses a - * step the engine sends. */ + /* The table is the engine's, sized to the step, so its geometry comes from the tensor: the + * columns are `shape[last]`, the row pitch `stride[rank-2]` and the column stride + * `stride[rank-1]` (the reference's table read). A five-token prompt carries [n_seq, 1]. The + * shim requires that every index the walk can reach (the last row's pitch plus the last column) + * is inside the plane; a contiguity check would demand a table as wide as the cache and refuse + * steps the engine sends. */ const long long bt_cols = BT->rank >= 2 ? r3d_dim(BT, (int)BT->rank - 1) : (n_seq ? r3d_numel(BT) / n_seq : 0); const long long bt_rs = BT->rank >= 2 ? BT->stride[BT->rank - 2] : bt_cols; const long long bt_cs = BT->rank >= 2 ? BT->stride[BT->rank - 1] : 1; @@ -1743,20 +1563,17 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode) int splits = decode ? (int)r3d_geti_or(a, "splits", 0) : 1; if (splits < 0) return R3D_NO(RAD_E_SHAPE); - /* The width the launcher will cut the grid on. A ragged batch has no per-sequence length to pick - * on -- the descriptor is on the device -- so the average sequence decides, as it does in the - * entry itself. It moves duplicated row slots between tiles and no result. */ + /* The width the launcher will use; a ragged batch is picked on the average sequence, as in the + * entry itself. */ const long long per = ragged ? (rows + n_seq - 1) / n_seq : q_len; const int waves = pick_waves((int)per, gqa); const int tiles = (int)((per + tok_per_block(gqa, waves) - 1) / tok_per_block(gqa, waves)); if (splits == 0) splits = decode ? pick_splits(tiles, (int)n_seq, kv_heads) : 1; if (splits > 64) splits = 64; if (splits > 1) { - /* The arena the engine offers is the bound: halve the split count until the partials fit, - * down to 1, which needs none -- and one slice is the whole walk in one block, the same - * keys in the same order, so it is not a degraded answer, it is the answer without the - * optimisation. A row that refuses a band because an optimisation has no room is a row that - * tells the user to go away; the number is the same either way. */ + /* Halve the split count until the partials fit the arena the engine offers, down to 1, + * which needs none. One slice is the same keys in the same order, so a smaller count + * changes speed, not the result, and the band is never refused for lack of scratch. */ for (;;) { if (splits <= 1) { splits = 1; break; } const long long need = qt * n_head * (long long)splits * kPartStride * 4; @@ -1769,15 +1586,10 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode) (long long)splits * kPartStride * 4)); } - /* The plan line: what the descriptor actually says, once per shape, under the flag only. The - * `q_len` printed is the one the kernel is given -- 0 with a descriptor, the per-sequence length - * without one (the reference's reading) -- and `rows` is the plane's row count, which is what - * cu[n_seq] is required to equal. Printed AFTER every check: a refused step's shape is the - * refusal lines' business, not this one's. */ - /* The kernel is the one instrument that a played step runs through: its records sit in the ring - * until a shim call drains them, so drain FIRST -- the records written since the last call, the - * played steps included -- and THEN arm the budget this launch will spend, under the flag only - * (both functions gate themselves on the same cached load). */ + /* Trace output, all under RAD_R3D_TRACE and after every check (a refused step is reported by + * the refusal lines). The ring is drained first, printing records written since the last call + * (replayed steps included), then re-armed for this launch. The plan line's `q_len` is the + * kernel's (0 with a descriptor) and `rows` is the plane's row count. */ dev_ring_drain(); dev_trace_arm(); @@ -1786,9 +1598,8 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode) n_seq, rows, ragged ? 0LL : q_len, bt_cols, bt_rs, bt_cs, block_size, max_ctx, waves, splits, r3d_trace_wide()); - /* The entries take the descriptor's row count where a rectangular batch has its per-sequence - * length: `rows` is the plane's, which is what cu[n_seq] equals and what libref counts off the - * tensor, and `q_len` is the per-sequence length only when there is no descriptor. */ + /* With a descriptor the entries take the plane's row count where a rectangular batch passes + * its per-sequence length. */ const int e = decode ? r3d_attn_decode_h128(r3d_addr(Q), r3d_addr(KV), r3d_addr(BT), r3d_addr(SU), r3d_addr(KDS), r3d_addr(VDS), r3d_addr(CU), r3d_addr(O), (int)n_seq, diff --git a/libr3d/r3d_codecs.h b/libr3d/r3d_codecs.h index 485ebde2..5a545e3c 100644 --- a/libr3d/r3d_codecs.h +++ b/libr3d/r3d_codecs.h @@ -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 #include -/* 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 #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)); } diff --git a/libr3d/r3d_common.h b/libr3d/r3d_common.h index ce40c8e8..5616381e 100644 --- a/libr3d/r3d_common.h +++ b/libr3d/r3d_common.h @@ -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 __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 __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 __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 __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 */ diff --git a/libr3d/r3d_dflash_f32.hip b/libr3d/r3d_dflash_f32.hip index 39904757..d56dbfca 100644 --- a/libr3d/r3d_dflash_f32.hip +++ b/libr3d/r3d_dflash_f32.hip @@ -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; diff --git a/libr3d/r3d_fp8_dequant.h b/libr3d/r3d_fp8_dequant.h index 4ee6dbd7..45f32928 100644 --- a/libr3d/r3d_fp8_dequant.h +++ b/libr3d/r3d_fp8_dequant.h @@ -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]; diff --git a/libr3d/r3d_gemm_bf16_nt_m16.hip b/libr3d/r3d_gemm_bf16_nt_m16.hip index 439e11f4..45d527e2 100644 --- a/libr3d/r3d_gemm_bf16_nt_m16.hip +++ b/libr3d/r3d_gemm_bf16_nt_m16.hip @@ -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 #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 __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 __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(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); diff --git a/libr3d/r3d_gemm_fp8a16_nt_m1.hip b/libr3d/r3d_gemm_fp8a16_nt_m1.hip index a110186d..aa94a412 100644 --- a/libr3d/r3d_gemm_fp8a16_nt_m1.hip +++ b/libr3d/r3d_gemm_fp8a16_nt_m1.hip @@ -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 // __forceinline__, which r3d_codecs.h's R3D_HD spells +#include // __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 __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 " diff --git a/libr3d/r3d_gemm_fp8a8_gated.hip b/libr3d/r3d_gemm_fp8a8_gated.hip index 9f365467..918c3548 100644 --- a/libr3d/r3d_gemm_fp8a8_gated.hip +++ b/libr3d/r3d_gemm_fp8a8_gated.hip @@ -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 // __forceinline__, which r3d_codecs.h's R3D_HD spells +#include // __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 __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(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( diff --git a/libr3d/r3d_gemm_fp8a8_tiled.hip b/libr3d/r3d_gemm_fp8a8_tiled.hip index 7ec9ce39..c77b7efe 100644 --- a/libr3d/r3d_gemm_fp8a8_tiled.hip +++ b/libr3d/r3d_gemm_fp8a8_tiled.hip @@ -1,184 +1,94 @@ /* r3d_gemm_fp8a8_tiled.hip -- gemm_nt_q at prefill M, fp8a8, on a tiled f16 dot. * - * ---- why this row exists ------------------------------------------------------------------------ + * gemm_nt_q needs a device row at prefill M. Without one its bands resolve to a host kernel, which + * keeps the layer's weights (norms included) in the container's mapping, where the mapped tier + * cannot widen the norms' stored form. * - * The graph, at the vocabulary head: + * Bands: dtype in {fp8a8}, group == 128, M >= 17, K % 128 == 0. The target model's prefill bands + * are M=2048 with (N, K) in {(12288, 2048), (2560, 2048), (2048, 6144), (2048, 2048), (2048, + * 10240)}. M <= 16 is gemm_nt_q_fp8a8_m16's; the floor `kMMin` is that row's ceiling plus one. * - * W placement: 'blk.0.attn_norm.weight' is grouped with a weight only a host kernel can read, so - * the whole group stays in the container's mapping - * E rank 0: 'blk.0.attn_norm.weight' was placed on the mapped tier, which reads the container - * where it lies, and its stored form is not the container's (widened at load) + * ---- the law ------------------------------------------------------------------------------------ * - * The chain is arithmetic, not policy: `gemm_nt_q` has no device row at prefill M, so its bands - * resolve to a host kernel, so the layer's weights stay in the container's mapping, so the layer's - * NORM weights are grouped with them, so the mapped tier is asked to perform the widening the norms' - * stored form needs, so startup stops. `--placement all_vram` is already the default and there is no - * grouping flag. The row that breaks the chain is the one the README names: the tiled - * quantised GEMM at prefill M. This file is that row. - * - * ---- the bands (42 layers + the drafter, per --debug-graph) ------------------------------------- - * - * gemm_nt_q N=12288 K= 2048 group=128 dtype=fp8a8 M=2048 x44 the gated MLP, 2 x 6144 - * gemm_nt_q N= 2560 K= 2048 group=128 dtype=fp8a8 M=2048 x44 qkv: 2048 + 2 x 256 - * gemm_nt_q N= 2048 K= 6144 group=128 dtype=fp8a8 M=2048 x44 o-proj - * gemm_nt_q N= 2048 K= 2048 group=128 dtype=fp8a8 M=2048 x44 - * gemm_nt_q N= 2048 K=10240 group=128 dtype=fp8a8 M=2048 x3 the drafter - * - * M=16 and M=1 are served, by gemm_nt_q_fp8a8_m16. The vocab prefill (N=130560 dtype=w2a8 M=1792) is - * the 2-bit grid and not this row's. Constraints bind the BAND's keys: dtype in {fp8a8}, group == - * 128, M >= 17, K % 128. Below M=17 the m16 rows are the served path and this row says so. The floor - * is `kMMin`, and it is the sibling row's declared ceiling plus one; the w2a8 arm below carries the - * same floor, with the reason for it. - * - * ---- the law, transcribed ----------------------------------------------------------------------- - * - * gemm_nt_q's law, in the registry: "The group sub-sum is accumulated from the raw codes and scaled - * once per group, which is what an int8 or fp8 WMMA kernel does." In code, the reference's - * quant_dot -- the same body r3d_gemm_fp8a8_gated.hip and r3d_gemm_fp8a16_nt_m1.hip carry: + * gemm_nt_q's registry law: the group sub-sum is accumulated from the raw codes and scaled once + * per group. The reference's quant_dot (also in r3d_gemm_fp8a8_gated.hip and + * r3d_gemm_fp8a16_nt_m1.hip): * * for g in groups: sub = 0 * for k in g, ascending: sub = sub + code_a[m][k] * code_b[n][k] * acc = acc + (sub * a_scale[m][g]) * b_scale[n/128][g] * - * The codes are the raw E4M3 values, widened exactly into f32; the scale multiplies the finished - * block ONCE, and the parentheses are the reference's. Operands, from gemm_q_shape, in schema - * order: a E4M3 {M,K}; a_scale F32 {M, ceil(K/group)}; b E4M3 {N,K} (the checkpoint's own bytes); - * b_scale BF16 {ceil(N/group), ceil(K/group)} -- f32 at fp8a8f32; y BF16 {M,N}; a_sum ABSENT for - * fp8a8 because fp8a8 is symmetric; b_ref absent. y is bf16 with one narrowing at the store, f32 - * accumulate throughout. + * Codes are raw E4M3 values widened exactly to f32. Operands (gemm_q_shape, schema order): a E4M3 + * {M,K}; a_scale F32 {M, ceil(K/group)}; b E4M3 {N,K}, the checkpoint's bytes; b_scale BF16 + * {ceil(N/group), ceil(K/group)} (f32 at fp8a8f32); y BF16 {M,N}; a_sum absent (fp8a8 is + * symmetric); b_ref absent. f32 accumulate, one bf16 narrowing at the store. * - * ---- the fold, and where it goes ---------------------------------------------------------------- + * ---- the fold ----------------------------------------------------------------------------------- * - * The tile is f16, so the two scale streams enter as f16 multiplies at staging: the activation's - * `a_scale[m][g]` per staged row, the weight's `b_scale[nb][g]` once a chunk -- TN is 128, the scale - * plane's row extent, so a tile is one scale-row, and kKC 32 divides 128, so a chunk sits inside one - * k-block. The products are separable: (a*sa)*(b*sb) = (a*b)*sa*sb, so folding each side is the same - * sum, formed a different way, and the accumulator stays one f32 register per output -- 64 a lane. - * The alternative, a per-group partial scaled into the accumulator, needs 64 more registers on an arm - * that is at 237 VGPRs, and spills. + * The tile is f16, so both scales enter as f16 multiplies at staging: `a_scale[m][g]` per staged + * row, `b_scale[nb][g]` once a chunk (TN = 128 is one scale row, and KC = 32 divides 128, so a + * chunk sits inside one k-block). (a*sa)*(b*sb) = (a*b)*sa*sb, so the accumulator stays one f32 + * per output, 64 a lane. A per-group partial scaled into the accumulator would need 64 more + * registers on an arm at 237 VGPRs, and spills. * - * The fold goes through v_mul_f16, never through f16x2_pack. That builtin is v_cvt_pkrtz_f16_f32, - * rounds toward zero, and r3d_codecs.h restricts it to values f16 represents exactly; a folded - * product is not one, and on the vocabulary head the truncation measured rel_l2 2.8e-04 against the - * fold law with 0.53 of outputs inside 2 ulps, where the f16 multiply gives 4.5e-06 and 1.000. + * The fold uses v_mul_f16, never f16x2_pack (v_cvt_pkrtz_f16_f32, round toward zero, only for + * values f16 represents exactly; r3d_codecs.h). Truncating folded products biases them toward + * zero. * - * Against the reference's law the fold costs the two f16 roundings of the staged values: measured - * rel_l2 2.77e-04 at the head's band, which is half an f16 ulp (2^-12 = 2.44e-04) and 250x finer than - * the E4M3 code's own quantum (2^-4). Against a model of the fold itself it is 4.5e-06 -- the dot's - * fused rounding, the pair-dot folding two products into the accumulator per step. This row's board - * reports both numbers, per band. + * The fold's cost against the reference is the two f16 roundings of the staged values, about + * rel_l2 2.8e-4, 250x finer than the E4M3 quantum (2^-4). * - * ---- the decoder is a table, and that is measured ---------------------------------------------- + * gfx11 has no fp8 -> f16 instruction (the clang builtin expands to software on gfx1102), so the + * E4M3 decode uses r3d_fp8_dequant.h's 256-entry f16 LDS table. * - * gfx11 has no fp8->f16 instruction: clang lists __builtin_amdgcn_cvt_pk_f16_fp8 and a gfx1102 build - * that calls it contains zero of them in its ISA, so the builtin is software. r3d_fp8_dequant.h - * replaces the codec with a 256-entry f16 table in LDS, 512 bytes, eight reads an eight-code group. - * Measured on the vocabulary head's bands (the A/B is one source, -DR3D_NO_E4M3_TBL for the codec): - * M=8 speculation 2.500 -> 0.924 ms a token, 2.70x; M=2048 prefill 323.978 -> 322.661 ms, flat; and - * M=1 12.999 -> 13.293 ms, NOT moved: at M=1 the decoder is not the binding resource, and the - * limiting access there is the 8-byte code load, not the ALU. + * ---- tolerance ---------------------------------------------------------------------------------- * - * ---- what the board measures -------------------------------------------------------------------- + * The fold's floor is 2^-11 per staged rounding, twice, on S = sqrt(sum_k (a_k b_k)^2), the + * quadrature scale of the dequantised terms: 9.8e-4 S. At a bf16 output the store's own ulp + * (3.9e-3 of the output's binade) is the larger bound. |y| is not a usable denominator, since a + * sum of random products is often near zero, so the per-output gate is fold floor + store ulp + * against S. * - * Five bands, M=2048, GPU 2 (RX 7600, gfx1102, 32 CU), the container managed with its pages - * prefetched to the card, every number on a placement line: + * ---- known performance cliff -------------------------------------------------------------------- * - * N=12288 K= 2048 28.171 ms 3659 GFLOP/s 0.0138 ms/token the gated MLP, x44 - * N= 2560 K= 2048 5.911 ms 3633 GFLOP/s 0.0029 ms/token qkv 2048 + 2 x 256 - * N= 2048 K= 6144 14.699 ms 3506 GFLOP/s 0.0072 ms/token o-proj, x44 - * N= 2048 K= 2048 4.381 ms 3922 GFLOP/s 0.0021 ms/token x44 - * N= 2048 K=10240 29.798 ms 2883 GFLOP/s 0.0145 ms/token the drafter, x3 + * The grid is (ceil(N/128), ceil(M/128)) at one block a CU. Odd column-tile counts 19 and 21 + * (N=2432, N=2688) run 11x and 21x slower per block, deterministically and with correct results; + * every band the target model issues has an even count. Untried remedies: a block-index swizzle, + * then `nt` streaming loads. * - * 2883-3922 GFLOP/s is 27-36% of this card's dense f16 peak (10.8 TFLOP/s), above the vocabulary - * head's fp8 3369 and within 4% of its bf16 4067. The bytes floor is 0.051-0.257 ms a band at the - * 163 GB/s the head's row streams, and 2MNK/(K+N) is ~1900 flops a byte at M=2048: prefill is - * compute-bound here, as it should be, and these bands are the box's fp8a8 prefill numbers. + * ---- placement ---------------------------------------------------------------------------------- * - * The floors, as the gate uses them. The fold's is 2^-11 a staged rounding, twice, on S = - * sqrt(sum_k (a_k b_k)^2) -- the quadrature scale of the DEQUANTISED terms -- so 9.8e-4 S. The - * store's is bf16's own ulp, 3.9e-3 of the output's binade, and at a bf16 output the store is the - * binding one: rel_l2 lands at 1.71e-03 against BOTH the reference's per-group law and the fold - * model, 83% of outputs are bit-exact bf16, 99.93% are within the fold's floor plus one store ulp, - * and 0 outputs are beyond eight fold floors plus two store ulps, on every band. |y| alone is not a - * denominator: a sum of 2048 random products is as often near zero as not, and a relative test - * against it is a coin flip. S is the denominator, and it is why the per-output gate is - * fold-bound + store-ulp and not a multiple of |y|'s ulp. + * The shim reads the container header on the host and the kernel reads the same bytes on the + * device, so operands must be managed (prefetched) or hipHostMalloc memory; plain malloc faults. * - * ---- the open item, with numbers, and what is NOT the kernel ------------------------------------- + * ---- refusals ----------------------------------------------------------------------------------- * - * The grid is (ceil(N/128), ceil(M/128)) at one block a CU (64 f32 accumulators a lane). Measured - * per block, the fast shapes cost a constant 18.4-18.5 us a block (16 tiles: 4.72 ms/256; 20 tiles: - * 5.911/320). Column-tile counts 19 and 21 do not: at the same M and K, N=2432 (19 tiles) is - * 64.283 ms and 64.301 ms in two isolated processes (211 us a block, 11.4x) and N=2688 (21 tiles) is - * 129.383 ms (385 us a block, 20.9x). Deterministic to 0.1%, and it is a grid-shape cliff, not - * arithmetic -- the board is CLEAN at both. Every column-tile count the graph issues is even (96, 20, - * 16, 16, 16), so no band the graph runs lands on it; the first thing to try is the block-index - * swizzle that tile-count cliffs usually answer to, and `nt` streaming loads second. + * The shim: n_t < 5 (E_INVAL); a_sum present (E_DTYPE: fp8a8 is symmetric, the asymmetric grid is + * r3d_gemm_nt_q_w2a8.hip's); a container with a zero plane, planes that are not codes + scale, + * codes not tiled one a cell, sub-byte codes, e5m2 and other code dtypes, a table scale, an + * integer scale (E_DTYPE); a scale block other than {group, group} (E_SHAPE); planes that do not + * cover the band (E_SHAPE); a row_bytes shorter than the row (E_STRIDE); a not E4M3, a_scale not + * f32, b not E4M3, b_scale not bf16/f16/f32, y not bf16 (E_DTYPE); M < 17 (E_UNSUPPORTED); + * group != 128 (E_SHAPE: the fold indexes 128); K % 128 (E_SHAPE); pitches a vector load cannot + * walk (E_STRIDE); addresses not 16-byte aligned (E_ALIGN); absurd shapes (E_INVAL). * - * Separately, and named so nobody reads it as the kernel: the qkv shape measures 5.911, 5.919 and - * 6.002 ms as the FIRST case of a process and 85.669 / 85.847 ms as the SECOND case of the band - * sequence, same binary, same seed, same grid, CLEAN board both ways, 250 GFLOP/s when slow. A - * 14.5x deterministic placement artefact of a fixture that allocates and frees a 24 MiB managed - * container in the case before it; at 0.2 GB/s the slow run is reading b over PCIe, in the mapped - * tier's class, which is the placement law this file's header states. The row's number for the qkv - * band is 5.911 ms; the sequence's 85.8 ms is the fixture's, and the engine ships the weights to - * VRAM at load and reads them 44 times, which is the case the 5.911 measures. + * N and M need no divisibility: the last tile stages rows and columns past the edge as zeros and + * guards its stores, so ragged shapes (M=65, 129, 258, 512) are served. K % 128 is the kernel's + * rule: a 32-code chunk must sit inside one scale group, and a ragged K would read the scale + * plane past its columns. The scale plane must be exactly ceil(N/128) x ceil(K/128) and the codes + * N x K, as the reference's `scaled_rows` requires. * - * ---- where the bytes live, named on every line -------------------------------------------------- + * The band's shape keys are M, N, K (gemm_q_shape, pGemmQ), not logits_gemm's n_vocab/n_embd. + * When the band names no N or K, they come from the weight's dims, since b is [N, K]. * - * The head's bands, one kernel, three placements, measured: VRAM 13.6 ms a token; the mapped tier - * (hipHostMalloc) 643 ms; managed and left alone 2071 ms, 122 MB/s, because managed pages do not - * migrate for a read-mostly device access on this box. This row's operands are host-readable for the - * same reason the head's are -- the shim reads the container's header on the host, the kernel reads - * the same bytes on the card -- so the board allocates with hipMallocManaged and prefetches, and says - * which placement produced which number. Plain malloc faults 700. + * The launcher's private codes are -1 a null plane, -2 a shape, -3 a pitch, -4 HIP, -5 an address; + * they collide numerically with the RAD codes, so the shim maps them. * - * ---- what is refused, and where ----------------------------------------------------------------- + * ---- code order --------------------------------------------------------------------------------- * - * The shim, at its own lines, each naming its fix: n_t < 5 (E_INVAL); a_sum present on an fp8a8 band - * (E_DTYPE -- fp8a8 is symmetric, a zero belongs to an asymmetric grid, and that is - * r3d_gemm_nt_q_w2a8.hip); a container carrying a zero plane (E_DTYPE, the same reason); planes that - * are not codes + scale, a codes plane tiled by anything but one code a cell, sub-byte codes - * (w4a16's ground), e5m2 and the rest, a scale that is a table, an integer scale (E_DTYPE, each its - * own line); a scale block that is not {group, group} (E_SHAPE); a plane that does not cover the - * band, ceil() arithmetic included (E_SHAPE); a plane whose row_bytes is shorter than its row - * (E_STRIDE); dtype of a not E4M3, a_scale not f32, b codes not E4M3, b_scale not bf16/f16/f32, y - * not bf16 (E_DTYPE); M < 17 (E_UNSUPPORTED: gemm_nt_q_fp8a8_m16 serves that); group != 128 - * (E_SHAPE: the fold indexes 128 and kKC 32 divides it); K % 128 (E_SHAPE); pitches that a vector - * load cannot walk (E_STRIDE); addresses not 16-byte aligned (E_ALIGN); absurd shapes (E_INVAL). - * The kernel's shape rule is stated here, because "shape this kernel does not serve" is a coverage - * claim, and coverage is caught by the fixture, not the board. - * The tile is 128 wide, so a ragged N is covered by ceil(): the last column tile stages the columns - * past N as zeros, writes the columns it owns and guards its stores column by column -- N needs NO - * divisibility, and `N % 128` is not a band key gemm_nt_q carries (r3d_rows.cpp's pGemmQ is M, N, - * K, group, dtype, pb1, pb2, split_n), so a check that wanted one could only ever refuse a shape - * the row advertised. M is the same in rows: ceil(M/128) row-tiles, rows past M stage zeros, write - * nothing, and M=65, 129, 258 and 512 -- the 27B fixture's geometries -- are served. - * K % 128 IS a rule, and it is the kernel's and not a coverage one: a 32-code chunk must sit inside - * one scale group (kKC 32 divides the group 128) and the scale plane is indexed by group, so a - * ragged K reads the scale plane past its columns. The scale plane is read at ceil(N/128) x - * ceil(K/128), exactly as the reference's `scaled_rows` covers it; the codes plane at rows == N, - * cols == K. Those two are equalities because that IS the reference's coverage rule, and every - * other shape test on this path is a covering one. - * - * And the keys, the same class of rule: the band's shape arrives as M, N, K -- gemm_q_shape reads - * exactly those and pGemmQ names them -- and n_vocab and n_embd are logits_gemm's keys, not this - * op's: read them and N and K are 0, the axis test fires, and a row whose constraints match the - * bands refuses them all at launch, invisible at planning, because the graph reports constraint - * matches and never asks the shim. N and K therefore fall back to r3d_dim(B, 0) and r3d_dim(B, 1) - * -- the weight IS [N, K], so when the band names no key the operand answers, and the operand is - * the authority the engine filled. - * - * The launcher's private codes are -1 a null plane, -2 a shape, -3 a pitch, -4 HIP, -5 an address, - * and the driver names them apart from the RAD codes, which collide numerically. - * - * ---- relayout: none, and it is a claim ---------------------------------------------------------- - * - * The codes plane is read row-major [N, K], the order the container stores it in and the order - * libref reads. libr4d keeps fp8a8 weights in WMMA fragment order (r4d.fp8.w.frag64, - * r3d_gemm_fp8a8_gated.hip's header): the two readings are ~1.35 apart, a relative error, not noise. - * So this row carries no relayout and no unrelayout, and the hook is a reader, not a mover -- the - * same claim the gated row makes, for the same reason. + * The codes plane is read row-major [N, K], as the container stores it and libref reads it. libr4d + * keeps fp8a8 weights in WMMA fragment order (r4d.fp8.w.frag64), a different reading of the same + * bytes, so no code is ever reordered here; the relayout writer below only assembles planes. */ #include @@ -188,7 +98,7 @@ #include "r3d_common.h" #include "r3d_codecs.h" #include "r3d_fp8_dequant.h" -#include "r3d_tiling.h" /* the LDS row law: srow, srow_pair */ +#include "r3d_tiling.h" /* LDS tile addressing: srow, srow_pair */ #include "r3d_launch.h" #include "rad_planes.h" @@ -203,43 +113,25 @@ constexpr int kTM = 128; /* rows a tile */ constexpr int kTN = 128; /* columns a tile: one scale-row */ constexpr int kKC = 32; /* k a chunk: divides the group */ constexpr int kGroup = 128; /* R3D_FP8_BLOCK: the band's group */ -/* The complement of gemm_nt_q_fp8a8_m16's declared ceiling, read from the row table: its name - * says M <= 16, so this floor is 17 and M=17..64 is covered. M=17..64 is a batched decode step, - * the most common shape a serving card sees; a floor above it leaves those bands to the host -- - * 209 bands a pass, six of them -- and one host band is what drags the whole model into one host - * run. The tile is 128 rows, so a band of 17 computes 128: 2x wasted at M=64, 7.5x at M=17, and - * 1.8 TFLOP/s on the card is still two orders above the host loop. */ +/* One above gemm_nt_q_fp8a8_m16's declared ceiling (M <= 16). M=17..64 is a batched decode step, + * and one host band pulls the whole model into one host run, so the floor stays low although the + * 128-row tile wastes 2x at M=64 and 7.5x at M=17; that is still about two orders of magnitude + * faster than the host loop. */ constexpr int kMMin = 17; -/* LDS row: 8-element granularity keeps the swizzle uint4-aligned, the rule every tiled row here - * follows (r3d_vocab_bf16.hip's srow, the same function for the same reason). */ -/* srow / srow_pair: r3d_tiling.h, the family's law in one place. */ +/* Tile addressing (srow, srow_pair) is r3d_tiling.h's; 8-element granularity keeps the swizzle + * uint4-aligned. */ -/* The staged side of the same family, typed next to the row law so a kernel's staging and its - * swizzle are read together. u16v is a 16-byte streamed load -- 32 U4 codes, 16 E4M3 codes, and - * the uint4 the tile is written in -- memcpy'd in, never cast: an unaligned cast is UB and the - * compilers say so in bytes of spill. u8v, its 8-byte sibling (8 E4M3 codes, 32 U2 codes, the f32 - * pair a scale row is read in), is declared with the streamed-load helper below. - * - * The scale row, which is why the two arms read a different number of scalars a staged tile: - * fp8a8 b_scale's block is {group, group} = {128, 128}, the block the shape function names, and - * the tile is 128 columns wide, so a staged chunk of 128 rows shares ONE scale: a single - * scalar read a tile, indexed by (n0/128, k0/128). - * w2a8 the grid's block is {1, group}, the same rule that fixes the scale's dtype at f16, so - * the tile's 128 rows are 128 scale rows: 128 scalar reads a chunk, and - * the zero rides with them, 128 more. That is the decode row's pattern -- its scale_at per - * staged 8-group IS the {1, group} case -- and it is kept: the scale is read where the grid - * puts it, not where the tile would like it. A staged row's pair is (scale, zero) and the - * value it stages is (code - zero) * scale, in f16 arithmetic, one v_mul_f16 and one - * v_sub_f16 a code. */ +/* A 16-byte load (32 U4 codes, or 16 E4M3 codes), memcpy'd in rather than cast, since an + * unaligned cast is UB. Its 8-byte sibling u8v is declared in loadc8s. */ typedef uint32_t __attribute__((ext_vector_type(4))) u16v; /* a 16-byte streamed load */ /* The two operands' scale planes, read the way the container hands them. */ struct ActQ { const float* scale; /* a_scale, f32: [M][ceil(K/group)], or [M] with gmode 0 */ long long row; /* elements a row: ceil(K/group) in group mode, 1 in row mode */ - int gmode; /* 1: one scale per (row, group) -- `a_scale[m][g]`; - * 0: one per ROW -- `a_scale[m]`, the ZP_I8_ROW form */ + int gmode; /* 1: one scale per (row, group), `a_scale[m][g]`; + * 0: one per row, `a_scale[m]` (the ZP_I8_ROW form) */ }; struct WQ { @@ -254,25 +146,24 @@ struct WQ { int srows; /* 0: scale rows are 128-blocks (fp8a8); 1: scale rows are rows (w2a8, w4a8_asym) */ }; +/* quant_act_i8's step order swaps bits 2 and 3 of a column, which are bits 0 and 1 of its dword + * index: dword L of a row is stored at dword i8_dw(L), so a 16-code run's dwords are read in the + * order 0, 2, 1, 3 and no dword is split. The map is its own inverse. */ __device__ __forceinline__ int i8_dw(int L) { return (L & ~3) | ((L & 1) << 1) | ((L & 2) >> 1); } -/* (code - zero) * scale, in f16 arithmetic, for a sub-byte code read through the block's table: - * the table holds f16(i) for the grid's code values, so the code's decode is one LDS read, the - * scale one v_mul_f16 and the zero one v_sub_f16. This IS the reference's `sub(g) = is(g) - - * z[n][g] * a_sum[g][m]`, formed per element: sum over a group of (a * (q - z) * sb) is the - * reference's bracketed (sum a*q - z * sum a) * sb, term for term. */ +/* (code - zero) * scale in f16 for a sub-byte code read through the block's table, which holds + * f16(i) for each code value: one LDS read, one v_sub_f16, one v_mul_f16. Summed over a group this + * equals the reference's `sub(g) = is(g) - z[n][g] * a_sum[g][m]` term for term. */ __device__ __forceinline__ uint32_t fold_pair_q(uint32_t codepair, const uint16_t* tbl, _Float16 s, _Float16 zf, int bits) { const uint32_t m = (1u << bits) - 1u; - /* The table entry is an f16 BIT PATTERN, so it is bit_cast, not converted: a converting cast - * stages 16384 for the code 0x4000, where the value is zero (the board's number was 217). The - * zero comes off BEFORE the scale -- the grid's zero is an integer code and code minus zero is - * exact in f16 for a 4-bit code and a U8 zero, so the staged value costs ONE rounding (the - * multiply) where (code*s) - (z*s) costs two and cancels. */ + /* The table entry is an f16 bit pattern, so it is bit_cast, not converted. The zero comes off + * before the scale: code minus zero is exact in f16 for a 4-bit code and a U8 zero, so the + * staged value costs one rounding, where (code*s) - (z*s) costs two and cancels. */ const _Float16 a = (__builtin_bit_cast(_Float16, tbl[codepair & m]) - zf) * s; const _Float16 b = (__builtin_bit_cast(_Float16, tbl[(codepair >> bits) & m]) - zf) * s; return (uint32_t)__builtin_bit_cast(uint16_t, a) | @@ -287,14 +178,12 @@ __device__ __forceinline__ float scale_w(const WQ h, int nb, int g) return h.sdt == 1 ? f16_to_f32(u) : bf16_to_f32(u); } -/* The scale of (row n, group g), in the grid the plane is laid out in. This one line is the whole - * difference between the two grids' scale rows, so it is written once and named for the ROWS: - * fp8a8 b_scale's rows are 128-row blocks ({group, group}) -> the tile's row n lives in block - * n>>7, one scalar serves the tile's 128 rows. - * w2a8 b_scale's rows are the weight's rows ({1, group}) -> row n, 128 scalars a staged chunk. - * The srows flag must match the grid: a scale read from the wrong row is not noise, it is a - * systematic few percent -- the head's bands at rel_l2 1.6e-02 against a fold floor of 1.8e-03 -- - * and it passes any gate set loosely enough. */ +/* The scale of (row n, group g) in the plane's grid: + * fp8a8 b_scale rows are 128-row blocks ({group, group}): row n is in block n>>7, so one scalar + * serves a tile's 128 rows. + * w2a8 b_scale rows are the weight's rows ({1, group}): 128 scalars a staged chunk. + * `srows` must match the grid. A scale read from the wrong row is a systematic error of a few + * percent, not noise, and passes a loose gate. */ __device__ __forceinline__ float scale_at_w(const WQ h, int n, int g) { return scale_w(h, h.srows ? n : (n >> 7), g); @@ -303,17 +192,13 @@ __device__ __forceinline__ float scale_at_w(const WQ h, int n, int g) __device__ __forceinline__ float zero_at_w(const WQ h, int n, int g) { if (!h.zero) return 0.0f; - return (float)h.zero[(long long)n * h.zero_row + g]; /* U8: the plane's practical form */ + return (float)h.zero[(long long)n * h.zero_row + g]; /* U8 zero plane */ } -/* quant_act_i8's step order: column c sits at (c & ~12) | ((c & 4) << 1) | ((c & 8) >> 1), the - * swap of bits 2 and 3, which is its own inverse. Bits 2 and 3 of a column are - * bits 0 and 1 of its DWORD index, so a dword's four codes stay four contiguous bytes and the - * staging reads a 16-code run's dwords in the order 0, 2, 1, 3. Nothing straddles a dword. */ -/* code * scale, in f16 arithmetic: one v_mul_f16, round to nearest, subnormals kept. NOT - * f16x2_pack, which truncates -- see the header and r3d_codecs.h. */ +/* code * scale in f16: one v_mul_f16, round to nearest, subnormals kept. Not f16x2_pack, which + * truncates (see the header). */ __device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc) { const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16); @@ -325,8 +210,8 @@ __device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc) ((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16); } -/* Eight codes -> eight f16 pairs, through the table. int8 codes take the codec's hardware convert, - * which is two v_cvt_f32_i8 and a pack; there is no such instruction for E4M3. */ +/* Eight codes -> four f16 pairs: E4M3 through the table, int8 through the codec's hardware + * convert (two v_cvt_f32_i8 and a pack). */ __device__ __forceinline__ void codes8(const uint2 c, int cdt, const uint16_t* tbl, uint32_t* w) { if (!cdt) { r3d_e4m3x8_ld(tbl, c, w); return; } @@ -349,10 +234,13 @@ __device__ __forceinline__ uint2 loadc8s(const uint8_t* p) } /* - * The tile: 128 rows x 128 columns of y, 256 threads, eight waves, eight outputs a side a lane -- - * 64 f32 accumulators a lane, grid (N/kTN) x ceil(M/kTM). k is walked in chunks of 32; both sides - * arrive as E4M3 codes, decode through the block's table and leave staging as f16 with their scale - * folded in, so the dot loop is the vocabulary head's dot loop and nothing in it scales anything. + * The tile: 128 x 128 outputs, 256 threads (eight waves), an 8x8 square a lane (64 f32 + * accumulators), grid ceil(N/kTN) x ceil(M/kTM). k is walked in chunks of 32; both sides are + * decoded and leave staging as f16 with their scale folded in, so the dot loop is + * r3d_vocab_bf16.hip's and does no scaling. + * + * ARM 0 is fp8a8 (E4M3 or int8 weight codes); ARM 1 is the zero-point grid (U2 or U4 codes against + * an int8 activation in step order). */ template /* CDT: 0 E4M3, 1 int8, 2 U2, 3 U4 */ __global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) @@ -365,10 +253,9 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest const int tid = (int)threadIdx.x; if (ARM == 0) { - r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* E4M3 -> f16, the decoder table */ + r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* E4M3 -> f16 decoder table */ } else { - /* The asym grid's codes are unsigned integers: U2 has 4 values, U4 has 16. The same - * 512 bytes, filled with f16(i) -- exact for every code the grid can hold. */ + /* U2 and U4 codes are unsigned integers (at most 16 values): the table holds f16(i). */ for (int i = tid; i < 16; i += kBlockThreads) sTbl[i] = f32_to_f16((float)i); __syncthreads(); } @@ -383,20 +270,12 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest for (int j = 0; j < 8; ++j) acc[i][j] = 0.0f; const int m_r = m0 + rg * 8, n_c = n0 + cg * 8; - const int nb = n0 / kGroup; /* TN == the scale plane's row */ + const int nb = n0 / kGroup; /* TN is one scale-plane row */ - /* The asym arm's staged row, one per thread for the whole tile: the B staging's row loop is - * `nn = tid; nn < kTN; nn += kBlockThreads`, so thread tid stages row n0+tid in every chunk. - * That is what makes the {1, group} grid's scalars cheap to read: the pair a row needs changes - * only when the k-group changes (kKC 32 divides kGroup 128, so every fourth chunk), and the - * load can be issued a chunk ahead, where its round trip overlaps the dot. - * - * At the 2-bit head's band M=64 N=12288 K=2048, the pair read inside the fold is 210.835 ms, - * 15.3 GFLOP/s; read once a group with a chunk's lead, 2.4 ms, 1344 GFLOP/s. - * The scalar is 128 a chunk -- the grid puts the scale at the row, so that is where it is read, - * and the decode row's pattern is kept -- with one row per thread there is no second load to - * overlap it with, and a round trip on the staging critical path is 64 of them a tile, paid in - * full. The values are identical either way; this is placement of a load, not arithmetic. */ + /* ARM 1: thread tid stages weight row n0+tid in every chunk, so the (scale, zero) pair it needs + * changes only with the k-group (every fourth chunk) and is loaded one chunk ahead, overlapping + * the dot. Loading it inside the fold puts a round trip on the staging critical path, which at + * M=64 N=12288 K=2048 is about 90x slower. */ const int b_row = n0 + tid; const bool b_has = (ARM == 1) && (tid < kTN) && (b_row < N); _Float16 s_cur = (_Float16)0.0f, zf_cur = (_Float16)0.0f; @@ -404,19 +283,13 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest s_cur = (_Float16)scale_at_w(h, b_row, 0); zf_cur = (_Float16)zero_at_w(h, b_row, 0); } - /* NAMED NON-RESULT: the codes stream is NOT limited by loads in flight. A one-chunk lead on - * the row's codes load -- 8 bytes (U2) or 16 (U4) a row a chunk, issued before the fold -- - * measures 24.430 ms against 24.585 ms at M=64 N=130560 K=2048, 0.6%, bit-identical output. - * The scalar load is the cost because it sits on the critical path with nothing to overlap; the - * stream is not waiting for latency, it is paying sector count: kKC 32 codes a row a chunk is - * 8 bytes drawn from a 512-byte-strided plane, so every row costs a full 64-byte sector and the - * band moves 8x the bytes it uses. 3.7 GB/s useful, 30 GB/s of sectors, and the card is not - * near the sector limit: the shape is the limit. The lever is a wider k-chunk (kKC 64 = 16 bytes - * a row = 4x amplification, kKC 128 = one group a chunk = 2x), paid for in LDS and occupancy -- - * a tiling pass on this arm, not a load lead. */ + /* The code stream is limited by sector amplification, not loads in flight (a one-chunk lead + * on the codes load gains under 1%). kKC = 32 U2 codes are 8 bytes from a 512-byte-strided + * plane, so each row costs a whole 64-byte sector, 8x the bytes used. A wider k-chunk (64: 4x, + * 128: 2x) would cut that, at a cost in LDS and occupancy. */ for (int k0 = 0; k0 < K; k0 += kKC) { - const int g = k0 / kGroup; /* one group a chunk: 32 | 128 */ + const int g = k0 / kGroup; /* one group a chunk: 32 divides 128 */ const float sb = scale_w(h, nb, g); /* one scale for the whole tile */ #pragma unroll @@ -426,19 +299,16 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest uint4 staged = make_uint4(0, 0, 0, 0); if (m < M) { if (ARM == 0) { - /* A row's scale, once a staged run: a_scale is (row, group) and the run is - * inside one group. */ - /* The row form contributes no g: `aq.gmode` is 0 and the term is a select, so - * one scale a row costs one IADD and no branch in the staging loop. */ + /* One scale a staged run, which lies inside one group. In row form + * (`aq.gmode` 0) the group term is selected away without a branch. */ const float sa = aq.scale[(long long)m * aq.row + (aq.gmode ? g : 0)]; uint32_t w[4]; codes8(loadc8s(a + (long long)m * a_ld + k), 0, sTbl, w); staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa), fold_pair(w[2], sa), fold_pair(w[3], sa)); } else { - /* The w2a8 activation: int8 codes in quant_act_i8's step order, read four codes - * a dword at the permuted dword address, and ONE scale per ROW (ZP_I8_ROW: - * quant_act_i8 scales a whole row, not a group). */ + /* int8 codes in quant_act_i8's step order, read a dword at the permuted + * address (i8_dw), with one scale per row (ZP_I8_ROW). */ const float sa = aq.scale[(long long)m * aq.row]; const int L0 = k >> 2; const uint8_t* ap = a + (long long)m * a_ld; @@ -470,12 +340,10 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest *(uint4*)&sB[srow(nn, c8, kKC)] = staged; } } else { - /* The sub-byte weight, w2a8 (U2, four codes a byte, a row is K>>2 bytes) and - * w4a8_asym (U4, two a byte, K>>1). A lane takes the whole 32-code chunk in one load: - * 8 bytes of U2, 16 of U4, k0 is a multiple of 128 so both are aligned. The scale AND - * the zero are per (row, group) -- the grid's block is {1, group} -- so every staged - * row reads its own pair of scalars: the decode row's pattern, 128 scalar reads a chunk - * where the fp8a8 arm reads one. */ + /* The sub-byte weight: w2a8 (U2, four codes a byte, K>>2 bytes a row) or w4a8_asym + * (U4, two a byte, K>>1). A thread loads a row's whole 32-code chunk at once, 8 bytes + * of U2 or 16 of U4, aligned because k0 is a multiple of 32. Scale and zero are per + * (row, group), prefetched above. */ constexpr int BITS = (CDT == 2) ? 2 : 4; constexpr int FIELD = 2 * BITS; /* bits a pair of codes occupies */ #pragma unroll @@ -499,9 +367,8 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest uint32_t w[16]; #pragma unroll for (int q = 0; q < 16; ++q) { - /* Pair q of the chunk sits at bit FIELD*q of the row: a 4-bit field for U2 - * (eight to a dword), an 8-bit field for U4 (four to a dword). Neither - * straddles a dword, which is why the field is read from one word. */ + /* Pair q sits at bit FIELD*q: a 4-bit field for U2 (eight a dword), an 8-bit + * field for U4 (four a dword). No field straddles a dword. */ const int bit = q * FIELD; w[q] = fold_pair_q((d[bit >> 5] >> (bit & 31)) & ((1u << FIELD) - 1u), sTbl, s, zf, BITS); @@ -548,8 +415,8 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest ((uint32_t)f32_to_bf16(acc[i][2 * j + 1]) << 16); *(uint4*)(row + n_c) = make_uint4(p[0], p[1], p[2], p[3]); } else { - /* The ragged N tail, unrolled: a dynamic index into acc[i] would put the 64 - * accumulators in local memory, which is the trap this family of kernels documents. */ + /* Unrolled: a dynamic index into acc[i] would put the 64 accumulators in local + * memory. */ #pragma unroll for (int j = 0; j < 8; ++j) if (n_c + j < N) row[n_c + j] = f32_to_bf16(acc[i][j]); @@ -558,13 +425,12 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest } /* ------------------------------------------------------------------ the launcher ------------------ */ -/* The launcher speaks the internal codes the shim maps (-3 stride, -4 device, -5 align), so a - * refusal here prints what it saw and returns -3, not the ABI code: the shim would translate -4 into - * E_DEVICE and the message the user reads would name the wrong thing. */ +/* A pitch refusal: traces what it saw and returns the internal -3, which the shim maps to + * E_STRIDE. */ #define L_STR(why, a1, v1, a2, v2) \ do { \ if (r3d_trace_on()) \ - std::fprintf(stderr, "[r3d] %s:%d %s: %s = %lld, %s = %lld\\n", \ + std::fprintf(stderr, "[r3d] %s:%d %s: %s = %lld, %s = %lld\n", \ __FILE__, __LINE__, (why), (a1), (long long)(v1), (a2), \ (long long)(v2)); \ return R3D_NO(-3); \ @@ -581,14 +447,9 @@ int launch(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K, if (nt < 0 || nt > 1) return -2; if (a_ld % 8) L_STR("a pitch: 8-byte code loads, 8 codes a lane", "a_ld", a_ld, "K", K); if (b_row & 7) L_STR("b row pitch is not 8-aligned", "b_row", b_row, "N", N); - /* The activation's scale row, which is a DIFFERENT thing in the two arms: fp8a8 carries one - * scale per (row, group) so the row is ceil(K/group) columns; w2a8 and w4a8_asym scale the - * whole row (ZP_I8_ROW: quant_act_i8's law), so it is one column a row and as_ld 1 is the - * legal pitch, not a broken one. The check is per arm for the same reason the staging is. */ - /* The activation's scales arrive in two forms, both the reference's: one per (row, group) at - * width ceil(K/group), and one per ROW at width 1 (the ZP_I8_ROW form -- which is what a per-row - * quantiser produces, and what this checkpoint's plan binds for the served model). Row mode is - * `as_ld == 1` and the kernel drops the group term. */ + /* The activation scale's pitch: ARM 0 takes one scale per (row, group) at width ceil(K/group) + * or one per row at width 1 (ZP_I8_ROW, a per-row quantiser's output); `as_ld == 1` selects row + * mode. ARM 1 is always one scale per row. */ if (arm == 0 && as_ld != 1 && as_ld < (K + kGroup - 1) / kGroup) L_STR( "a_scale: neither one per row nor one per (row, group)", "as_ld", as_ld, "ceil(K/group)", (K + kGroup - 1) / kGroup); @@ -597,11 +458,11 @@ int launch(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K, if (a_ld < K) L_STR("a pitch shorter than K", "a_ld", a_ld, "K", K); if (y_ld < N) L_STR("y pitch shorter than N", "y_ld", y_ld, "N", N); if ((av & 7) || (bvc & 7) || (yv & 7) || (asv & 3) || (bsv & 3)) return -5; - if (bs_row & (sdt == 2 ? 3 : 1)) return -3; /* a scale row is 4 bytes a column for f32, 2 for - bf16/f16: ceil(K/128) = 3 columns is 6 bytes. */ + if (bs_row & (sdt == 2 ? 3 : 1)) return -3; /* scale loads are 4 bytes (f32) or 2 (bf16/f16); + a 3-column 16-bit row (6 bytes) is legal */ if (arm == 1) { if (!(arm == 1 && (cdt == 2 || cdt == 3))) return -2; - if (!zv) return -1; /* the asym grid has no spelling without a zero */ + if (!zv) return -1; /* the zero-point grid needs its zero plane */ if (z_row < 1) return -3; if (zv & 1) return -5; if (cdt == 3 && (bvc & 15)) return -5; /* a 16-byte U4 load; U2 loads 8 */ @@ -635,9 +496,8 @@ int launch(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K, return 0; } -/* libref's float_scale_dt and enc_scaled_rows, inlined: libref keeps them static inline in its own - * header, so a row that transcribes a layout hook transcribes its helpers with it. Checks and - * order unchanged. */ +/* libref's float_scale_dt and enc_scaled_rows, transcribed (libref keeps them static inline), + * checks and order unchanged. */ bool float_scale_dt(uint32_t dt) { return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; } bool enc_scaled_rows(const RadEncoding* enc, const int* sel, int n) @@ -661,18 +521,15 @@ bool enc_scaled_rows(const RadEncoding* enc, const int* sel, int n) /* ================================================================================================== * The layout hook: b (operand 2) as codes + one scale. * - * `ref_layout_gemm_q` is the w2a8/w4a8 grid's hook: it is `layout_scaled(operand, 3, -1, ...)` over - * `sel_roles("scale","zero")` with block {1, group}, and it reads `zp_grid(dtype)` first -- and - * zp_grid has no "fp8a8" entry (it lists w2a8, w4a8_asym, w4a16_asym, w5a16, w4a8i8_asym, w5a8i8), - * so the reference's own gemm_nt_q hook ANSWERS NOTHING for dtype=fp8a8: it returns E_DTYPE, the - * placement finds no reader, and the group stays mapped. That is the chain's first link, and it is - * why this hook is the head's class and not that one: two planes, "codes" and "scale", NO zero - * plane (fp8a8 is symmetric), codes tiled one a cell, the scale on the block the shape function - * names -- {group, group}. Body: layout_scaled(operand, 2, -1, ...) as ref_layout_head's is. + * The reference's gemm_nt_q hook, `ref_layout_gemm_q`, serves only the zero-point grids + * (`zp_grid` lists w2a8, w4a8_asym, w4a16_asym, w5a16, w4a8i8_asym, w5a8i8) and returns E_DTYPE + * for fp8a8, leaving no reader. For fp8a8 this hook follows `ref_layout_head` instead, + * `layout_scaled(operand, 2, -1, ...)`: two planes, "codes" and "scale", no zero plane (fp8a8 is + * symmetric), codes tiled one a cell, the scale on the {group, group} block the shape function + * names. * ================================================================================================== */ -/* The writer for the layout this hook names -- the same rad_planes_relayout, the same operand guard, - * the same reason: the plan asks for the container's codes and per-block scales as one operand, and - * the loader converts at load with the row's help and nobody else's. */ +/* The writer for the layout the hook names: rad_planes_relayout assembles the container's codes + * and per-block scales as one operand, with the hook's operand guard. */ extern "C" int r3d_relayout_gemm_q_fp8_weight(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* planes, int n_planes, void* dst, @@ -687,16 +544,8 @@ extern "C" int r3d_relayout_gemm_q_fp8_weight(const RadParam* p, int n_p, int op return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes); } -/* The grids this row reads behind operand 2, in two branches that never borrow each other's - * checks. fp8a8 is the symmetric pair (codes, scale) on {1,1} + {group,group}. w2a8 and - * w4a8_asym are the ZERO-POINT triple (codes, scale, zero) on {1,1} + {1,group} + {1,group}: - * ref_layout_gemm_q's plane rules with the codes plane riding along, because this row's plan puts - * all three behind b. The dtype names which grid, and the codes dtype follows it (zp_grid: - * w2a8 -> U2, w4a8_asym -> U4) -- a grid and a code width that disagree is a container this row - * cannot read, at its own line. */ -/* 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. */ +/* Traces a layout query (operand, band dtype, planes offered, code returned) when tracing is on + * (RAD_R3D_TRACE=1), since a refused query otherwise leaves no record. */ 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, @@ -704,6 +553,14 @@ static int r3d_layout_trace(const char* who, int operand, const char* dt, int n_ return rc; } +/* The grids this row reads behind operand 2, in two branches that share no checks. fp8a8 is the + * symmetric pair (codes, scale) on {1,1} + {group,group}. w2a8 and w4a8_asym are the zero-point + * triple (codes, scale, zero); the codes dtype follows the grid (w2a8 -> U2, w4a8_asym -> U4). + * + * The zero-point grids delegate to the decode row's hook, r3d_layout_gemm_nt_q_w2a8 (codes plain + * on operand 2, the (scale, zero) pair joined on operand 3, {1, group} block, f16 scale, unsigned + * zero). The engine stores one form per weight across every row that reads it, so both rows must + * describe the weight identically or the model does not load. */ extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* planes, int n, RadLayout* out) @@ -714,17 +571,6 @@ extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam* p, int n_p, int oper if (n < 2 || operand != 2) return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_UNSUPPORTED); /* b is operand 2 of gemm_nt_q */ - /* The packed grids ask the DECODE ROW what the container looks like, and get the answer by - * calling its hook -- `r3d_layout_gemm_nt_q_w2a8`: codes plain on operand 2, the (scale, zero) - * pair joined on operand 3, the {1, group} block, the f16 scale, the unsigned zero. The engine - * settles one stored form per weight across every row of the op that reads it and says so at - * declare time -- `weight 'dspark.draft_head.scale' is wanted in two stored forms: - * 'rad.planes' by gemm_nt_q_w2a8_m16 and '(as it is)' by gemm_nt_q_w2a8_tiled. A weight is - * stored once` -- so a tile that wants the trio joined behind `b` is not a different plan, it is - * a model that will not load. Two rows describing one weight in one function cannot drift; the - * arm's board measures this arrangement as `decodeform`, 1.660e-03 against the joined fixture's - * 1.677e-03, the same law's noise. */ - if (!enc_scaled_rows(enc, sel, n)) return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); const long long group = r3d_pgeti_or(p, n_p, "group", 0); if (group <= 0) return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* the band names the block */ @@ -734,10 +580,10 @@ extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam* p, int n_p, int oper } /* ================================================================================================== - * The planes' entry: the caller has resolved the two planes and hands their addresses. The band is - * fp8a8, group 128, y bf16. Codes row-major, scales [ceil(N/128)][ceil(K/128)], read as bf16 -- - * fp8a8's stated dtype; the f32 spelling (fp8a8f32) arrives through the shim, which reads the dtype - * off the plane. b_row and bs_row of 0 mean the dense pitch. + * The planes' entry: the caller has resolved the two planes and passes their addresses. fp8a8, + * group 128, y bf16; codes row-major, scales [ceil(N/128)][ceil(K/128)] read as bf16 (fp8a8f32's + * f32 scales go through the shim, which reads the dtype off the plane). b_row and bs_row of 0 mean + * the dense pitch. * ================================================================================================== */ extern "C" 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, @@ -755,23 +601,17 @@ extern "C" int r3d_gemm_nt_q_fp8_tiled(long a, long a_scale, long b_codes, long } /* ================================================================================================== - * The RadArgs shim. Schema positions: a 0, a_scale 1, b 2, b_scale 3, y 4, a_sum 5, b_ref 6. The - * placement joins b and b_scale into one container, so 3 is absent and the container's header is - * read here, on the host; a caller that resolved the planes itself passes 3 and takes the plain - * path. Same kernel, same law, one branch. + * The RadArgs shim. Schema positions: a 0, a_scale 1, b 2, b_scale 3, y 4, a_sum 5, b_ref 6. When + * the placement joins b and b_scale into one container, 3 is absent and the header is read here + * on the host; a caller that resolved the planes passes 3 and takes the plain path. * ================================================================================================== */ -/* RadStream, the ABI's type: RadLaunchFn is int (*)(const RadArgs*, RadStream) and RadStream is - * void* (rad_abi.h, rad_types.h). A shim that takes a long runs -- same width, same convention -- - * and is a function-pointer type the row table has to be lied to about. The entry below keeps long - * because it takes addresses as longs; the cast is here, at the boundary. */ +/* Shims take RadStream so they match RadLaunchFn (rad_abi.h); the long-taking entries cast at the + * boundary. */ -/* The plan line's latch: one print per distinct shape this shim sees, keyed on what the line prints - * -- M, N, K, the activation's rank, the scale's rank and the two pitches -- because the served plan - * runs this shim 176 times a forward pass and 42 copies of one line are noise. A plain static array - * with no lock: the worst a race does is print a shape twice, and the flag-off path never reaches - * it. The sibling decode row (gemm_nt_q_fp8a8_m16) has no such line: the shapes below M=17 are its - * served path, and the ones above it are what this line is for. */ +/* Latch for the trace plan line: true once per distinct (M, N, K, ranks, pitches), since the shim + * runs many times a forward pass. Unlocked: a race can only print a shape twice, and only with + * tracing on. */ 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, unsigned as_rank, @@ -798,24 +638,21 @@ extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s) const RadTensor* ASUM = r3d_opt(args, 5); if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(Y)) return R3D_NO(RAD_E_INVAL); - /* The band's keys, from the schema this row is declared against: gemm_nt_q carries M, N, K, - * group, dtype (r3d_rows.cpp pGemmQ) -- NOT n_vocab/n_embd, which belong to logits_gemm. Read - * the wrong keys and N and K are 0, every launch is refused below at the shape check, the op - * resolves to a host kernel for every band, the planner puts the whole model in one host run, - * and a norm weight two tiers away refuses to load. Falling back to the weight's own dims keeps - * a caller that names no N/K working, and says which operand is the authority. */ + /* gemm_nt_q's keys are M, N, K, group, dtype (r3d_rows.cpp pGemmQ), not logits_gemm's + * n_vocab/n_embd. Reading the wrong keys gives N = K = 0 and silently refuses every band. A + * band that names no N or K falls back to the weight's dims. */ const long long M_band = r3d_geti_or(args, "M", 0), N0 = r3d_geti_or(args, "N", 0); const long long K0 = r3d_geti_or(args, "K", 0); const long long N = N0 > 0 ? N0 : r3d_dim(B, 0); const long long K = K0 > 0 ? K0 : r3d_dim(B, 1); const long long group = r3d_geti_or(args, "group", 0); if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE); - if (K > (1 << 24)) return R3D_NO(RAD_E_INVAL); /* absurd: a 16M-wide K is a 2 GiB code plane per row */ + if (K > (1 << 24)) return R3D_NO(RAD_E_INVAL); /* absurd K */ if (group != kGroup) return R3D_NO(RAD_E_SHAPE); /* the fold indexes 128 */ if (K % kGroup) return R3D_NO(RAD_E_SHAPE); if (ASUM && r3d_p(ASUM)) - return R3D_NO(RAD_E_DTYPE); /* fp8a8 is symmetric: a_sum is an asymmetric grid's, and - r3d_gemm_nt_q_w2a8.hip reads that one */ + return R3D_NO(RAD_E_DTYPE); /* fp8a8 is symmetric; a_sum belongs to the zero-point + grid (r3d_gemm_nt_q_w2a8.hip) */ /* ---- b: a container of codes + scale, or the two planes as tensors -------------------------- */ const void* bvc = r3d_p(B); @@ -824,11 +661,11 @@ extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s) int sdt = 0, cdt = 0; const RadPlanesHeader* ph = (const RadPlanesHeader*)rad_planes_header(bvc); if (ph) { - /* find answers with the bytes and points into the container; no copy. */ + /* rad_planes_find points into the container; nothing is copied. */ const RadPlanesEntry* ce = nullptr; const RadPlanesEntry* se = nullptr; if (rad_planes_find(bvc, "zero", nullptr)) - return R3D_NO(RAD_E_DTYPE); /* codes+scale+zero is gemm_nt_q's asymmetric grid: w2a8 */ + return R3D_NO(RAD_E_DTYPE); /* codes+scale+zero: the zero-point grid */ if (ph->n_planes != 2) return R3D_NO(RAD_E_DTYPE); const void* cb = rad_planes_find(bvc, "codes", &ce); const void* sb = rad_planes_find(bvc, "scale", &se); @@ -837,58 +674,48 @@ extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s) return R3D_NO(RAD_E_DTYPE); /* codes: one a cell, tiled plain */ if (ce->dtype != RAD_F8E4M3 && ce->dtype != RAD_I8) { if (rad_dtype_bytes(ce->dtype, 8) < 8) - return R3D_NO(RAD_E_DTYPE); /* sub-byte codes: w4a16's ground */ + return R3D_NO(RAD_E_DTYPE); /* sub-byte codes */ return R3D_NO(RAD_E_DTYPE); /* e5m2 and the rest: no decoder here */ } if (se->kind != RAD_PLANE_TILED) return R3D_NO(RAD_E_DTYPE); if (se->dtype == RAD_BF16) sdt = 0; else if (se->dtype == RAD_F16) sdt = 1; else if (se->dtype == RAD_F32) sdt = 2; - else return R3D_NO(RAD_E_DTYPE); /* an integer scale is not float_scale_dt */ + else return R3D_NO(RAD_E_DTYPE); /* not in float_scale_dt's set */ if (se->block[0] != group || se->block[1] != group) - return R3D_NO(RAD_E_SHAPE); /* per-(row, group) is gemm_nt_q's w2a8 grid; per-row is - not cover's indexing of the plane */ + return R3D_NO(RAD_E_SHAPE); /* only {group, group} blocks */ bvc = cb; bsv = sb; b_row = ce->row_bytes; bs_row = se->row_bytes; cdt = ce->dtype == RAD_I8; const long long sb_r = (N + group - 1) / group, sb_c = (K + group - 1) / group; if (ce->rows != N || ce->cols != K) return R3D_NO(RAD_E_SHAPE); if (se->rows != sb_r || se->cols != sb_c) return R3D_NO(RAD_E_SHAPE); - if (ce->row_bytes < K) return R3D_NO(RAD_E_STRIDE); /* a packed row is not this form */ + if (ce->row_bytes < K) return R3D_NO(RAD_E_STRIDE); /* one byte a code */ if (se->row_bytes < sb_c * (sdt == 2 ? 4 : 2)) return R3D_NO(RAD_E_STRIDE); } else { if (!BS || !r3d_p(BS)) - return R3D_NO(RAD_E_DTYPE); /* a weight that is neither a container nor a scale - tensor: gemm_nt_q's shape hook names the two */ + return R3D_NO(RAD_E_DTYPE); /* neither a container nor a scale tensor */ b_row = K; const long long sb_r = (N + group - 1) / group, sb_c = (K + group - 1) / group; - /* b_scale as a CONTAINER -- the codes plain on b, the scale joined behind b_scale. The - * sibling decode row uses that spelling for the shared weight, and - * r3d_relayout_gemm_q_fp8_weight writes it for a band whose encoding names its container at - * operand 3, so the plan can hand it here. The header is read on the host, where it lives - * (the same call b's arm makes above); the kernel gets the scale plane's BYTES and the row - * pitch off the ENTRY, which is the identical answer the two-tensor spelling gives. - * A `zero` plane stays refused: fp8a8's activation quantiser is symmetric and this arm has - * no zero to fold -- the reference refuses the grid for it outright -- so a row that - * computed through a zero plane would be inventing a number the oracle has no law for. The - * asymmetric grid is gemm_nt_q's w2a8 form and r3d_gemm_nt_q_w2a8 owns that spelling. */ + /* b_scale may itself be a container: codes plain on b, the scale joined behind b_scale (the + * decode row's spelling for a shared weight, which r3d_relayout_gemm_q_fp8_weight can + * write). The header is read on the host; the kernel gets the scale plane's bytes and the + * entry's row pitch, the same as the two-tensor spelling. A `zero` plane is refused: fp8a8 + * is symmetric and the reference defines no law for it here. */ const RadPlanesHeader* sph = (const RadPlanesHeader*)rad_planes_header(r3d_p(BS)); if (sph) { if (rad_planes_find(r3d_p(BS), "zero", nullptr)) - return R3D_NO(RAD_E_DTYPE); /* codes + scale + zero: r3d_gemm_nt_q_w2a8's grid, - not this arm's -- nor libref's */ + return R3D_NO(RAD_E_DTYPE); /* codes + scale + zero: the zero-point grid */ const RadPlanesEntry* se = nullptr; const void* sb = rad_planes_find(r3d_p(BS), "scale", &se); if (!sb || !se) - return R3D_NO(RAD_E_DTYPE); /* a joined stream with no `scale` plane: - r3d_relayout_gemm_q_fp8_weight is its writer */ + return R3D_NO(RAD_E_DTYPE); /* a joined stream with no `scale` plane */ if (se->kind != RAD_PLANE_TILED) return R3D_NO(RAD_E_DTYPE); if (se->dtype == RAD_BF16) sdt = 0; else if (se->dtype == RAD_F16) sdt = 1; else if (se->dtype == RAD_F32) sdt = 2; - else return R3D_NO(RAD_E_DTYPE); /* an integer scale is not float_scale_dt */ + else return R3D_NO(RAD_E_DTYPE); /* not in float_scale_dt's set */ if (se->block[0] != group || se->block[1] != group) - return R3D_NO(RAD_E_SHAPE); /* per-row scales are the w2a8 grid; the 128x128 - quantiser writes one scale a (128 rows x 128 codes) */ + return R3D_NO(RAD_E_SHAPE); /* one scale per 128 rows x 128 codes only */ if (se->rows != sb_r || se->cols != sb_c) return R3D_NO(RAD_E_SHAPE); if (se->row_bytes < sb_c * (sdt == 2 ? 4 : 2)) return R3D_NO(RAD_E_STRIDE); bsv = sb; @@ -915,22 +742,17 @@ extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s) if (A->dtype != RAD_F8E4M3) return R3D_NO(RAD_E_DTYPE); if (AS->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE); - if (Y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); /* gemm_q_shape: y is bf16, one narrowing */ + if (Y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); /* gemm_q_shape: y is bf16 */ if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); long long a_rows = 0; long long a_ld = r3d_rows_pitch(A, K, &a_rows); - /* THE STEP'S M IS THE ACTIVATION'S ROW COUNT. The band key `M` is an upper bound, and the - * engine's own line says so -- its refusal names the step's M against the band's declared bound - * -- so reading the key as the value would refuse a step shorter than the band. libref derives - * M from the operands (the plane, not the plan), and the m16 row does it the same way. The key - * keeps its job as the ceiling the plan promised not to exceed. */ + /* The step's M is the activation's row count, as libref and the m16 row derive it. The band + * key `M` is only an upper bound, checked below. */ if (a_ld < K || a_rows < 1) { - /* A group-quantised activation is the same row-major K codes the kernel wants, described in - * the rank the quantiser writes them in: [M][ceil(K/group)][group], contiguous, the row - * exactly K wide. `r3d_rows_pitch` asks for the width by name and a rank-3 plane whose last - * axis is the group does not answer it, so the plane is asked directly: contiguous and - * dividing by K is a plane of rows K wide. */ + /* A group-quantised activation may arrive as rank 3, [M][ceil(K/group)][group], which + * r3d_rows_pitch cannot read as rows of K. A contiguous plane whose numel divides by K is + * rows K wide. */ if (rad_tensor_is_contiguous(A) && K > 0 && r3d_numel(A) % K == 0) { const long long r = r3d_numel(A) / K; if (r >= 1) { a_ld = K; a_rows = r; } @@ -944,17 +766,13 @@ extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s) if (M_band > 0 && M > M_band) { r3d_trace_desc("a", A); std::fprintf(stderr, "[r3d] a: %lld rows in a band that declared M <= %lld\n", M, M_band); return R3D_NO(RAD_E_SHAPE); } - if (M * N > (1ll << 34)) return R3D_NO(RAD_E_INVAL); /* 32-bit tile indices, at the step's - * height, not the band's bound */ - if (M < kMMin) return R3D_NO(RAD_E_UNSUPPORTED); /* gemm_nt_q_fp8a8_m16 serves M <= 16, and - * this arm's floor is that declared - * ceiling + 1, read from its array */ + if (M * N > (1ll << 34)) return R3D_NO(RAD_E_INVAL); /* 32-bit tile indices, at the + * step's M */ + if (M < kMMin) return R3D_NO(RAD_E_UNSUPPORTED); /* gemm_nt_q_fp8a8_m16 serves M <= 16 */ const long long kb = (K + group - 1) / group; - /* Two forms of the activation's scales, and the plan binds the one its quantiser produces: - * [M][ceil(K/group)] for a group quantiser, [M] for a per-row one (`a_scale[m]`, the ZP_I8_ROW - * form). `r3d_rows_pitch(AS, kb, ...)` returns -1 for the rank-1 plane -- the scales do not - * divide into rows of kb -- so the width asked for depends on the form, which the rank states; - * both forms must pass, the row form included. */ + /* The activation's scales: [M][ceil(K/group)] from a group quantiser, or rank-1 [M] from a + * per-row one (ZP_I8_ROW). The rank picks the width asked of r3d_rows_pitch, which would + * refuse the rank-1 plane at width kb. */ const int as_row = (AS->rank <= 1); const long long as_w = as_row ? 1 : kb; long long as_rows = 0; @@ -973,20 +791,11 @@ extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s) return R3D_NO(RAD_E_ALIGN); if (!r3d_aligned(r3d_p(AS), 4) || !r3d_aligned(bsv, 4)) return R3D_NO(RAD_E_ALIGN); - /* ---- the plan line, the GEMM's side of the same instrument --------------------------------- + /* ---- the plan line --------------------------------------------------------------------------- * - * The step's M, off the activation (the header's law: the band key `M` is a BOUND, the plane is - * the value), with the forms the served plan hands this row -- the codes' rank, pitch and numel, - * the scale's rank and pitch, the output's pitch. The fixture draws its descriptors from the - * shape hooks and does not cover the plan's own rank-1 `[M]` scale and rank-3 codes at a - * M >= 17 launch; this line is the instrument for that form: the step's rows against the - * arena's padding, ceil(M/16)*16, and the strides the producer and the consumer each read the - * same plane through. - * - * Inert when the flag is unset -- the cached `r3d_trace_on()` every refusal already pays, and - * the descriptors print through the existing `r3d_trace_desc`. Latched per shape, because this - * shim runs 176 times a forward pass and 42 copies of one line are noise. Printed AFTER every - * check, so a refused step stays the refusal lines' business. */ + * With tracing on, prints once per shape the step's M, the operands' ranks, pitches and + * strides, and the arena padding ceil(M/16)*16, after every check has passed. It covers the + * plan's rank-1 `[M]` scale and rank-3 codes, which the shape-hook fixtures do not draw. */ if (r3d_trace_on() && gemm_plan_once(M, N, K, A->rank, AS->rank, a_ld, y_ld)) { std::fprintf(stderr, "[r3d] plan: gemm M=%lld (band M<=%lld) N=%lld K=%lld group=%lld " @@ -1015,36 +824,26 @@ extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s) } /* ================================================================================================== - * The w2a8 arm's shim: gemm_nt_q at dtype=w2a8 (codes U2) and dtype=w4a8_asym (codes U4), the same - * tile above the decode heights. The band that gates start-up is N=130560 K=2048 group=128 - * dtype=w2a8 at M=1792 -- the drafter's draft head, read three times a step -- and the graph prints - * it as the last band with no device row. Below kMMin the m16 row (gemm_nt_q_w2a8_m16, - * C_LE("M", 16) in its constraint array) is the served path; above it the tile. The floor is the - * sibling's CEILING, read from its constraints, and it is 17: M=17..64 is a batched decode step, - * the shape a serving card lives in, and 1.8 TFLOP/s of 128-row waste is two orders above the host. + * The w2a8 arm's shim: gemm_nt_q at dtype=w2a8 (U2 codes) or w4a8_asym (U4 codes), the same tile + * at M >= kMMin; below it gemm_nt_q_w2a8_m16 serves (C_LE("M", 16)). A typical band is a draft + * head, N=130560 K=2048 group=128 at M=1792. * - * The law is the reference's gemm_zp, ZP_I8_ROW arm, and the kernel runs it in a folded form: + * The law is the reference's gemm_zp, ZP_I8_ROW arm, run in a folded form: * * q[k] = the grid's code of weight row n, column k U2: bits [2k,2k+2) of k/4 * sub(g) = SUM_{k in g} (int)a[m][i8_step_pos(k)] * ((int)q[k] - (int)z[n][g]) integers * acc = acc + (sub(g) * sa[m]) * sb[n][g] g ASCENDING * y[m,n] = bf16(acc) * - * which is the reference's `sub = is - z * a_sum` term for term: sum a*(q - z) = sum a*q - z*sum a, - * exactly, over the same group. So the staged tile carries (q - z) * sb and the a-side carries - * a * sa[m], and a_sum -- which exists to take the 128 bias off an integer dot, because this ISA - * has no int8 dot (r3d_gemm_nt_q_w2a8.hip) -- has no term to take off here: the zero is - * removed per element, before the dot. a_sum is still REQUIRED of a w2a8 band (gemm_zp reads it and - * the schema carries it at slot 5; a band without it is not this band) and the refusal is this - * shim's own line, not the fp8a8 arm's, which REFUSES the same tensor: the two arms' lines are - * deliberately not shared, and the driver's board fires each at its own arm. The bracketing - * differs from the reference (a per-group bracket there, one chain here) by the fold's floor, which - * is what the board measures: rel_l2 against the transcribed body, at a bf16 output, where the - * store's own ulp is the wider of the two. + * This equals the reference's `sub = is - z * a_sum`, since sum a*(q - z) = sum a*q - z*sum a over + * the same group. The staged tile carries (q - z) * sb and the a side a * sa[m], so the zero is + * removed per element and a_sum is never read. a_sum is still required (gemm_zp reads it and the + * schema carries it at slot 5), while the fp8a8 shim refuses it; the two arms keep separate checks. + * The bracketing differs from the reference's per-group bracket by the fold's floor, which at a + * bf16 output is below the store's ulp. * - * The activation arrives in quant_act_i8's step order, and its scale is ONE f32 PER ROW (ZP_I8_ROW: - * quant_act_i8 scales a whole row), not per group like fp8a8's. The scale and the zero are per - * (row, group): 128 scalar reads a staged chunk where the fp8a8 arm reads one. + * The activation is in quant_act_i8's step order with one f32 scale per row (ZP_I8_ROW). The + * weight's scale and zero are per (row, group). * ================================================================================================== */ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) { @@ -1055,10 +854,8 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) if (dt && std::strcmp(dt, "w2a8") == 0) cdt = 2; else if (dt && std::strcmp(dt, "w4a8_asym") == 0) cdt = 3; if (cdt < 0) - return R3D_NO(RAD_E_DTYPE); /* the zero-point grids on an int8 activation; w4a8i8_asym and - * w5a8i8 quantise the activation to int8 with a DIFFERENT - * trunk (ZP_I8_GROUP, no per-row scale) and this arm does not - * read them. */ + return R3D_NO(RAD_E_DTYPE); /* w4a8i8_asym and w5a8i8 use ZP_I8_GROUP (no per-row + * scale), which this arm does not read */ const RadTensor* A = r3d_opt(args, 0); const RadTensor* AS = r3d_opt(args, 1); @@ -1068,20 +865,16 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) const RadTensor* ASUM = r3d_opt(args, 5); if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(Y)) return R3D_NO(RAD_E_INVAL); if (!r3d_p(ASUM)) - return R3D_NO(RAD_E_DTYPE); /* a w2a8 band without a_sum is not a w2a8 band: gemm_zp's - * ZP_I8_ROW arm reads it. This kernel folds the zero into the - * staged tile and never indexes it -- see the header. */ + return R3D_NO(RAD_E_DTYPE); /* required by the schema, though never read (see above) */ const long long M_band = r3d_geti_or(args, "M", 0), N0 = r3d_geti_or(args, "N", 0); const long long K0 = r3d_geti_or(args, "K", 0); - const long long N = N0 > 0 ? N0 : r3d_dim(B, 0); /* the weight IS [N, K]: name the operand - * when the band names no key */ + const long long N = N0 > 0 ? N0 : r3d_dim(B, 0); /* b is [N, K] */ const long long K = K0 > 0 ? K0 : r3d_dim(B, 1); const long long group = r3d_geti_or(args, "group", 0); if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE); - /* The step's M, off the codes plane, exactly as in the fp8a8 shim above: the band key `M` is the - * ceiling the plan promised not to exceed, not the height of this step, and a draft pass whose - * chunk is shorter than the band it matched is refused by the bound below. */ + /* The step's M comes from the activation, as in the fp8a8 shim; the band key `M` is the upper + * bound. */ long long M = 0; if (K > 0 && r3d_numel(A) % K == 0) M = r3d_numel(A) / K; if (M < 1) M = M_band; @@ -1089,13 +882,12 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) std::fprintf(stderr, "[r3d] w2a8 a: %lld rows in a band that declared M <= %lld\n", M, M_band); return R3D_NO(RAD_E_SHAPE); } if (group != kGroup) - return R3D_NO(RAD_E_SHAPE); /* the fold indexes the group as kGroup; kKC 32 divides it */ + return R3D_NO(RAD_E_SHAPE); /* the fold indexes the group as kGroup */ if (K % kGroup) return R3D_NO(RAD_E_SHAPE); /* a ragged k-chunk reads past the plane */ if (M < kMMin) - return R3D_NO(RAD_E_UNSUPPORTED); /* gemm_nt_q_w2a8_m16's array says M <= 16; the floor of - * this arm is that ceiling + 1, read from the array */ + return R3D_NO(RAD_E_UNSUPPORTED); /* gemm_nt_q_w2a8_m16 serves M <= 16 */ const long long G = (K + kGroup - 1) / kGroup; - const long long mpad = ((M + 15) / 16) * 16; /* a_sum is group-major, 16 columns min */ + const long long mpad = ((M + 15) / 16) * 16; /* a_sum is group-major [G][Mpad] */ if (A->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE); /* quant_act_i8's codes */ if (Y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); @@ -1105,12 +897,9 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE); if (M * N > (1ll << 34)) return R3D_NO(RAD_E_INVAL); /* 32-bit tile indices */ - /* The weight's planes. This row's plan puts codes, scale and zero behind b (operand 2), which is - * what r3d_layout_gemm_q_fp8_weight's asym branch describes. The decode row's plan puts the - * scale+zero pair behind b_scale and leaves the codes plain on b, and the builder settles ONE - * stored form per weight, so read whichever the container is and find the planes by role: a row - * that insists on the arrangement it declared will refuse the settled bytes of a weight it - * shares with the sibling. */ + /* The weight's planes, found by role in either arrangement: codes, scale and zero all behind b, + * or the decode row's (codes plain on b, scale+zero joined behind b_scale). One stored form is + * settled per weight, so a weight shared with the decode row may arrive in either. */ const void* bbase = r3d_p(B); const RadPlanesHeader* bh = rad_planes_header(bbase); bool codes_joined = false; /* the codes plane inside b's container? */ @@ -1129,37 +918,29 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) c_row = ce->row_bytes; codes_joined = true; } else { - if (!r3d_p(BS)) return R3D_NO(RAD_E_DTYPE); /* no zero, no plain spelling: the zero - * point has nowhere to live outside the - * container. */ + if (!r3d_p(BS)) return R3D_NO(RAD_E_DTYPE); /* the zero plane lives only in a + * container */ const RadPlanesHeader* h3 = rad_planes_header(r3d_p(BS)); - if (!h3) return R3D_NO(RAD_E_DTYPE); /* the decode row's arrangement: the - * scale+zero pair joined behind b_scale */ + if (!h3) return R3D_NO(RAD_E_DTYPE); /* scale+zero joined behind b_scale */ sp = rad_planes_find(r3d_p(BS), "scale", &se); zp = rad_planes_find(r3d_p(BS), "zero", &ze); if (!sp || !zp) return R3D_NO(RAD_E_DTYPE); if (B->dtype != (uint32_t)(cdt == 2 ? RAD_U2 : RAD_U4)) return R3D_NO(RAD_E_DTYPE); if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); - c_row = rad_dtype_bytes(B->dtype, r3d_dim(B, 1)); /* the row in BYTES, the same measure - * the container's entry carries on the - * joined side: K/4 for U2, K/2 for U4. - * A hand-rolled `K * (1) / 2` - * integer-divides the U2 case to zero - * and the kernel then reads every row - * from the start of the plane: the - * decode form comes out rel_l2 1.9. */ + c_row = rad_dtype_bytes(B->dtype, r3d_dim(B, 1)); /* the row in bytes (K/4 for U2, K/2 + * for U4), as the joined entry carries + * it; integer byte-per-element math + * truncates U2 to zero */ (void)ce; } if (!se || !ze) return R3D_NO(RAD_E_DTYPE); if (se->dtype != RAD_F16) - return R3D_NO(RAD_E_DTYPE); /* the grid's scale is f16; a bf16 or f32 - * scale plane is the fp8a8 grid's, not this one. */ + return R3D_NO(RAD_E_DTYPE); /* the zero-point grid's scale is f16 */ if (ze->dtype != RAD_U8) - return R3D_NO(RAD_E_DTYPE); /* DECLINED, at the site: a sub-byte zero plane needs the bit - * extract (rad_load_bits(zb, bits, g), ten lines) that the m16 - * row also declines. U8 is w2a8's practical form. */ + return R3D_NO(RAD_E_DTYPE); /* a sub-byte zero plane would need a bit extract + * (rad_load_bits), which the m16 row also declines */ if (se->rows != N || se->cols != G || ze->rows != N || ze->cols != G) - return R3D_NO(RAD_E_SHAPE); /* {1, group}: the scale's rows are the weight's rows */ + return R3D_NO(RAD_E_SHAPE); /* {1, group}: scale rows are weight rows */ if ((se->row_bytes & 1) || se->row_bytes < 2 * G || ze->row_bytes < G) return R3D_NO(RAD_E_STRIDE); if (bh) { @@ -1169,7 +950,7 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) long long a_rows = 0; const long long a_ld = r3d_rows_pitch(A, K, &a_rows); - if (a_ld < K || (a_ld & 3)) return R3D_NO(RAD_E_STRIDE); /* four codes a dword, step order */ + if (a_ld < K || (a_ld & 3)) return R3D_NO(RAD_E_STRIDE); /* dword reads in step order */ long long yrows = 0; const long long y_ld = r3d_rows_pitch(Y, N, &yrows); if (y_ld < N) return R3D_NO(RAD_E_STRIDE); @@ -1179,8 +960,7 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) zv = ze ? (const char*)zp : nullptr; s_row = se->row_bytes; z_row = ze->row_bytes; const long long bvc = codes_joined - ? (long long)(uintptr_t)((const char*)bbase + ce->offset) /* the container's - * codes plane */ + ? (long long)(uintptr_t)((const char*)bbase + ce->offset) /* codes plane */ : (long long)(uintptr_t)r3d_p(B); if (!r3d_aligned(r3d_p(A), 8) || !r3d_aligned(r3d_p(Y), 8) || diff --git a/libr3d/r3d_gemm_inta8.hip b/libr3d/r3d_gemm_inta8.hip index 27454ebc..2a847a50 100644 --- a/libr3d/r3d_gemm_inta8.hip +++ b/libr3d/r3d_gemm_inta8.hip @@ -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); diff --git a/libr3d/r3d_gemm_mxfp4a8.hip b/libr3d/r3d_gemm_mxfp4a8.hip index cb3dc181..fcdd7f4b 100644 --- a/libr3d/r3d_gemm_mxfp4a8.hip +++ b/libr3d/r3d_gemm_mxfp4a8.hip @@ -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 @@ -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 __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 @@ -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); diff --git a/libr3d/r3d_gemm_nt_q_w2a8.hip b/libr3d/r3d_gemm_nt_q_w2a8.hip index 524c8028..17c1ce74 100644 --- a/libr3d/r3d_gemm_nt_q_w2a8.hip +++ b/libr3d/r3d_gemm_nt_q_w2a8.hip @@ -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 @@ -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; } diff --git a/libr3d/r3d_launch.h b/libr3d/r3d_launch.h index bdda29e5..48df1996 100644 --- a/libr3d/r3d_launch.h +++ b/libr3d/r3d_launch.h @@ -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 diff --git a/libr3d/r3d_model_bf16.hip b/libr3d/r3d_model_bf16.hip index 6f6e557c..d38b06d1 100644 --- a/libr3d/r3d_model_bf16.hip +++ b/libr3d/r3d_model_bf16.hip @@ -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 __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 __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 __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 __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 __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 __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 __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 __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 __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 __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 __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 __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 __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 __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 __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 __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), 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= kvbase= slots=", 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); diff --git a/libr3d/r3d_plugin.h b/libr3d/r3d_plugin.h index 4a7c6675..8ad08eb6 100644 --- a/libr3d/r3d_plugin.h +++ b/libr3d/r3d_plugin.h @@ -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 . - * 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*); diff --git a/libr3d/r3d_quant_fp8.hip b/libr3d/r3d_quant_fp8.hip index d953ee3c..e259abc9 100644 --- a/libr3d/r3d_quant_fp8.hip +++ b/libr3d/r3d_quant_fp8.hip @@ -1,39 +1,31 @@ /* r3d_quant_fp8.hip -- the activation quantisers and the dequantise that reads a container's own * codes. * - * The arithmetic is libref's, transcribed. The group core is `q8_group`: an amax over - * the group's consecutive columns, `sc = amax * (1.0f / top)` -- a MULTIPLY by the reciprocal, not a - * divide -- codes `v * (1/sc)` clamped to +-top and encoded by the codec, and scale 1 for an - * all-zero group, whose reciprocal would be an infinity. The five bodies are libref's - * quant_act_fp8, quant_act_i8, quant_act_i8g, gated_quant_fp8 and dequant, loop order and rounding - * points as written. The clamp is required and not defensive: `amax * (1/scale)` is - * 448 exactly and can round an ulp above once the reciprocal is rounded, and a code out of range - * encodes as NaN, which then spreads through every row that reads it. + * The arithmetic is libref's, transcribed: quant_act_fp8, quant_act_i8, quant_act_i8g, + * gated_quant_fp8 and dequant, loop order and rounding points as written. The group core is + * `q8_group`: an amax over the group's columns, `sc = amax * (1.0f / top)` (a multiply by the + * reciprocal, not a divide), codes `v * (1/sc)` clamped to +-top, and scale 1 for an all-zero + * group. The clamp is required: `amax * (1/scale)` can round an ulp above 448, and an + * out-of-range code encodes as NaN. * - * RDNA3 has no fp8 instruction (r3d_common.h), so both directions are the software codecs in - * r3d_codecs.h, which are bit-exact mirrors of rad_plugin.h's; the absmax is a butterfly - * (r3d_xor_max), which reproduces a `__shfl_xor` loop bit for bit, and a max is exact and - * order-free, so the bracketing is q8_group's ascending one whatever the lane mapping. + * RDNA3 has no fp8 instruction (r3d_common.h), so both directions use the software codecs in + * r3d_codecs.h, bit-exact mirrors of rad_plugin.h's. The absmax is a butterfly (r3d_xor_max); a + * max is exact and order-free, so it matches q8_group whatever the lane mapping. * - * No kernel here carries a layout hook, and the codes are the bytes their consumer reads, which is - * the reason a container converted on this card is readable anywhere. Four of the five planes are - * plain row-major with one f32 scale per (row, group), because a dot2 GEMM reads codes in the order - * they are stored. The fifth is the op whose NAME carries the order: libref stores quant_act_i8's - * codes in the int8 WMMA's step order (`i8_step_pos`, the middle two dwords of every 16-byte step - * exchanged) because that is what the w4a8, w8a8 and w2a8 GEMMs read, so this kernel stores them - * that way too and its n is a multiple of 16; quant_act_i8g is the row-major int8 plane, and it is - * the one this library's i8a8 GEMM consumes. The two are not interchangeable. + * The codes are the bytes their consumer reads, with no layout hook. Four of the five planes are + * row-major with one f32 scale per (row, group), the order a dot2 GEMM reads. quant_act_i8 stores + * its codes in the int8 WMMA's step order (`i8_step_pos`) because the w4a8, w8a8 and w2a8 GEMMs + * read that, so its n is a multiple of 16. quant_act_i8g is the row-major int8 plane this + * library's i8a8 GEMM consumes. The two are not interchangeable. * - * The store address costs nothing either way: a lane owns FOUR CONSECUTIVE COLUMNS, so its codes are - * one dword, a wave's are 128 contiguous bytes, and a wave covers exactly one 128-column group; - * `i8_step_pos` preserves c % 4, so it permutes a wave's 128 bytes without splitting a lane. The - * launchers therefore refuse `n % 4` -- and quant_act_i8 `n % 16` -- and a ragged last group - * (n % group != 0) is written zero-padded: padding is a zero code and takes no part in the amax. + * A lane owns four consecutive columns, so its codes are one dword and a wave's are 128 + * contiguous bytes; `i8_step_pos` preserves c % 4, so it never splits a lane. The launchers + * refuse `n % 4` (quant_act_i8: `n % 16`), and a ragged last group is zero-padded: padding is a + * zero code and takes no part in the amax. * - * Group widths: the rows ask for 128, the checkpoint's weight-scale block width, and the kernels - * also serve any other power of two from 4 to 512, so a selftest can drive a narrow group and a - * future row on a 64-wide grid needs no new kernel. A group is a power of two because the amax - * butterfly is over the lanes covering it, GROUP/4 of them. + * Group widths: the rows ask for 128, the checkpoint's weight-scale block width; the kernels serve + * any power of two from 4 to 512. A group is a power of two because the amax butterfly is over + * the GROUP/4 lanes covering it. */ #include "r3d.h" @@ -51,15 +43,13 @@ enum : uint32_t { kWaveCols = kWave * kColsPerLane /* 128: the columns a wave covers */ }; -/* The largest code each quantiser saturates at. E4M3 has no infinity, so 448 is the largest finite - * value, and the scale is a dequant multiplier like the checkpoint's weight_scale_inv: the GEMM - * multiplies the activation's scale by the weight's block scale and never divides. */ +/* The largest code each quantiser saturates at; 448 is E4M3's largest finite value. The scale is a + * dequant multiplier like the checkpoint's weight_scale_inv: the GEMM multiplies, never divides. */ constexpr float kTopE4M3 = 448.0f; constexpr float kTopI8 = 127.0f; -/* The floor quant_act_i8's amax is raised to before its DIVIDE by 127, where quant_act_fp8 - * multiplies by a reciprocal, so the two quantisers round one ulp apart here; that is libref's - * spelling and the GEMMs read the scale as it is. */ +/* The floor quant_act_i8's amax is raised to before it divides by 127. quant_act_fp8 multiplies by + * a reciprocal instead, so the two can round one ulp apart; both follow libref. */ constexpr float kI8Floor = 1e-8f; /* The LDS code-sum accumulator's width, in groups, as in libr4d's r4d_quant_act_i8. */ @@ -70,10 +60,9 @@ __device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) { return bf16_to_f32((uint16_t)ldg_u16(p + i)); } -/* q8_group's clamp, in q8_group's order and with q8_group's comparisons, at the codec's top -- 448 - * for E4M3, 127 for int8. fminf/fmaxf are NOT the same function here: they replace a NaN with the - * bound, and a NaN in an activation is a value the reference encodes as the format's NaN, not as - * +-top. */ +/* q8_group's clamp, in its order and with its comparisons, at the codec's top (448 for E4M3, 127 + * for int8). Not fminf/fmaxf: they replace a NaN with the bound, and the reference encodes a NaN + * activation as the format's NaN. */ __device__ __forceinline__ float clamp_top(float c, float top) { if (c > top) c = top; if (c < -top) c = -top; @@ -87,9 +76,7 @@ __device__ __forceinline__ uint32_t e4m3_codes4(const float* v, float inv) { return lo | (hi << 16); } -/* The same four codes as int8, at the same rounding points: clamp to +-127, then the codec's - * round-to-nearest-even. quant_act_i8g's store; quant_act_i8's is the same bytes at a permuted - * address. */ +/* The same four codes as int8: clamp to +-127, then the codec's round-to-nearest-even. */ __device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) { const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8)); const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8)); @@ -98,24 +85,22 @@ __device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) { return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); } -/* q8_group's scale from the group's amax: the reciprocal of `top` MULTIPLIED, not a divide -- the - * one place the two int8 quantisers and the fp8 one agree, and the reason the per-row - * quant_act_i8 spells its scale as a divide and is a separate body. */ +/* q8_group's scale from the group's amax: multiplied by the reciprocal of `top`, not divided. The + * per-row quant_act_i8 divides, which is why it is a separate body. */ __device__ __forceinline__ float group_scale(float am, float top) { return am > 0.0f ? am * (1.0f / top) : 1.0f; } -/* The map libref uses, verbatim: where a row's column c is stored in the step-ordered int8 plane. - * Bits 2 and 3 of c exchanged = the middle two dwords of every 16-byte step swapped, which is the - * order the int8 WMMA reads an A fragment. The map is its own inverse, and it preserves c % 4, so a - * lane's four columns stay contiguous and its store stays one dword. */ +/* libref's map from column c to its position in the step-ordered int8 plane: bits 2 and 3 of c + * exchanged, i.e. the middle two dwords of every 16-byte step swapped, the order the int8 WMMA + * reads an A fragment. It is its own inverse and preserves c % 4, so a lane's store stays one + * dword. */ __device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) { return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1); } -/* block_sum's twin for a maximum -- r3d_common.h has the sum. A max needs no order argument at all: - * it is exact, so the wave partials combine in any order -- but it is spelled the same way, so a - * reader sees one reduction shape in this library and not two. `lds` holds kWaves floats. */ +/* block_sum's (r3d_common.h) twin for a maximum. A max is exact, so the wave partials combine in + * any order. `lds` holds kWaves floats. */ __device__ __forceinline__ float block_max(float v, float* lds) { const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; v = wave_max(v); @@ -129,18 +114,16 @@ __device__ __forceinline__ float block_max(float v, float* lds) { /* ================================================================== quant_act_fp8 * - * Per-(row, group) symmetric E4M3 of an activation, over q8_group. One workgroup - * a row, a wave a group, a lane four columns -- libr4d's layout, because the reason for - * it (one dword a lane, 128 contiguous bytes a wave) is the store and not the instruction set. + * Per-(row, group) symmetric E4M3 of an activation, over q8_group. One workgroup a row, a wave a + * group, a lane four columns: libr4d's layout, chosen for the store (one dword a lane, 128 + * contiguous bytes a wave), not the instruction set. * - * GROUP is the group's width. At 128 a wave covers one group and the amax is r3d_xor_max<32>. A - * narrower group is covered by GROUP/4 lanes of the wave and the butterfly is over those lanes, so - * one wave quantises 128/GROUP groups in a pass; a wider one is covered by one wave in sub-blocks - * of 128 whose maxima are fmaxf'd. All three are q8_group's bracketing. + * At GROUP = 128 a wave covers one group and the amax is r3d_xor_max<32>. A narrower group is + * covered by GROUP/4 lanes, so one wave quantises 128/GROUP groups a pass; a wider one is walked + * by one wave in 128-column sub-blocks whose maxima are fmaxf'd. * * Rows are dim 0, so a rank-3 activation ([tokens, heads, width], a GDN block's out-projection - * input) is one row per token, as libref reads it: its consuming GEMM's K is heads*width, and one - * row per head would put scales on a grid that GEMM does not read. + * input) is one row per token, as libref reads it: the consuming GEMM's K is heads*width. */ template __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel( @@ -168,8 +151,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel( for (int j = 0; j < kColsPerLane; ++j) { const uint32_t c = c0 + (uint32_t)j; /* Past the row's end a lane contributes 0.0f, so padding is a zero code and takes - * no part in the amax. n is a multiple of 4, so a lane's four columns are all in - * the row or all outside it: the ragged edge never splits a lane. */ + * no part in the amax. n is a multiple of 4, so the edge never splits a lane. */ v[sb][j] = c < n ? ld_bf(xr, c) : 0.0f; } float m = 0.0f; @@ -178,10 +160,9 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel( am = fmaxf(am, r3d_xor_max(m)); } const float sc = group_scale(am, kTopE4M3); - /* The scale store is guarded by the group count, not just by the lane: a wave covers - * kPer = 128/GROUP groups and a row's group count is ceil(n/group), which is not a multiple - * of kPer when the last group is ragged. Unguarded, those lanes wrote one row past the - * scale row -- and on a ragged n, past the plane's end. */ + /* Guarded by the group count as well as the lane: a wave covers kPer = 128/GROUP groups + * and ceil(n/group) need not be a multiple of kPer, so the surplus lanes would write past + * the scale row (and on the last row, past the plane). */ if ((lane & (kLanes - 1)) == 0) { const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes; if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc; @@ -197,17 +178,14 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel( /* ================================================================== quant_act_i8g * - * The same group core at int8, q8_group called with top 127. One scale - * per (row, group), `sc = amax * (1.0f / 127)` -- the reciprocal MULTIPLIED, as in the fp8 path, so - * this is quant_act_fp8 with a different codec and not quant_act_i8 at a finer granularity -- codes - * clamp(v * (1/sc), +-127) to nearest even, stored ROW-MAJOR, and scale 1 for an all-zero group. + * q8_group at top 127: one scale per (row, group), `sc = amax * (1.0f / 127)` as in the fp8 path + * (so this is quant_act_fp8 with an int8 codec, not quant_act_i8 at a finer granularity), codes + * clamp(v * (1/sc), +-127) rounded to nearest even, scale 1 for an all-zero group. * - * The row-major store is the point of the op: libr3d's only int8 GEMM is the i8a8 one, and a dot2 - * GEMM reads a row in the order it is stored. The step-ordered plane belongs to quant_act_i8, whose - * consumers are libr4d's WMMA GEMMs, and the two are not interchangeable. + * The store is row-major because libr3d's int8 GEMM (i8a8) is a dot2 GEMM that reads a row in + * stored order. The step-ordered plane is quant_act_i8's, read by libr4d's WMMA GEMMs. * - * Same lane mapping and same ragged rules as quant_act_fp8_kernel, so the two bodies read as one - * shape with the codec swapped. + * Lane mapping and ragged rules are quant_act_fp8_kernel's. */ template __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8g_kernel( @@ -258,13 +236,12 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8g_kernel( } /* namespace */ /* x [M][n] bf16, `x_ld` elements a row (0 = n) - * q [M][n] E4M3, DENSE: the launcher takes no code pitch, so the plane is - * row-major with no hole in it, rounded up to 4 bytes for the padding + * q [M][n] E4M3, dense (the launcher takes no code pitch) * s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group)) * - * A launcher checks what a `__global__` cannot and issues one kernel: 0, -1 a null pointer, -2 a bad - * extent (including a group with no instantiation), -3 a pitch that does not describe the operand, - * -4 the HIP launch failed. It allocates nothing and synchronises on nothing. */ + * Each launcher validates and issues one kernel: 0, -1 a null pointer, -2 a bad extent (including + * a group with no instantiation), -3 a pitch that does not describe the operand, -4 the HIP launch + * failed. It allocates nothing and does not synchronise. */ extern "C" int r3d_quant_act_fp8(long x, long q, long s, int M, int n, int group, int x_ld, int s_ld, long stream) { if (!x || !q || !s) return -1; @@ -301,27 +278,20 @@ namespace { /* ================================================================== quant_act_i8 * - * The activation of the w4a8, w8a8 and w2a8 GEMMs, ONE SCALE PER ROW, - * max(amax, 1e-8) / 127, codes x * (1/scale) rounded to nearest even by the int8 codec. + * The activation of the w4a8, w8a8 and w2a8 GEMMs: one scale per row, max(amax, 1e-8) / 127, + * codes x * (1/scale) rounded to nearest even by the int8 codec. * - * The codes go out in libref's STEP ORDER, `i8_step_pos`: the middle two - * dwords of every 16-byte step exchanged, which is why this op's n is a multiple of 16 and not of - * 4. That order is what the op MEANS -- the w4a8, w8a8 and w2a8 GEMMs read the plane that way, and - * kbench compares the plane element by element -- so it is kept on a card that has no WMMA, and the - * row-major int8 plane is a separate op, quant_act_i8g below, which is the one this library's i8a8 - * GEMM consumes. The permutation is per-lane and preserves c % 4, so a lane's four codes stay - * contiguous and the store stays one dword; a wave's 128 bytes are a permutation of the same 128. + * The codes are stored in libref's step order (`i8_step_pos`), hence n % 16 == 0. That order is + * the op's contract (those GEMMs read it and kbench compares the plane element-wise), so it is + * kept on a card without WMMA; the row-major plane is quant_act_i8g. * - * One divergence from the reference's arithmetic, and it is inert: libref reduces a row with - * std::max and this with fmaxf. They agree on every input the op can see -- std::max(a, NaN) is a, so - * the reference's amax is never a NaN, and fmaxf drops the NaN the same way; an all-NaN row has amax - * 0 in both and scale 1e-8/127. + * libref reduces with std::max and this with fmaxf. Both drop a NaN operand, so they agree on + * every input; an all-NaN row has amax 0 and scale 1e-8/127 in both. * - * ASUM, when present, also takes each row's code sums per `group` columns, group-major - * [n/group][Mpad] with Mpad = ceil(M/16)*16: an asymmetric weight grid needs sum_k a_k to subtract - * z_g * sum_k a_k from a group's dot product once instead of N times, and it reads whole 16-row - * tiles. The sums are integers, so the LDS accumulator's atomic adds are exact and their order is - * free. Rows M..Mpad-1 are not written; the caller zeroes them, as libref does. + * ASUM also writes each row's code sums per `group` columns, group-major [n/group][Mpad] with + * Mpad = ceil(M/16)*16: an asymmetric weight grid subtracts z_g * sum_k a_k once per group instead + * of N times, and reads whole 16-row tiles. The sums are integers, so the LDS atomics are exact in + * any order. Rows M..Mpad-1 are not written; the caller zeroes them, as libref does. */ template __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel( @@ -359,10 +329,9 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel( const uint32_t cc = c + (uint32_t)j; const int8_t code = (cc < n) ? f32_to_i8_rtne(ld_bf(xr, cc) * inv) : (int8_t)0; w |= (uint32_t)(uint8_t)code << (8 * j); - /* n % group == 0 and group % 4 == 0, so a lane's four columns are in one group. The - * sum is over column order, and the map is its own inverse, so summing the codes of - * columns [gi*group, (gi+1)*group) here is libref reading qr[i8_step_pos(i)] -- - * same bytes, same groups. */ + /* n % group == 0 and group % 4 == 0, so a lane's four columns are in one group. Sums + * are over logical columns, which equals libref reading qr[i8_step_pos(i)] since the + * map is its own inverse. */ if (ASUM && cc < n) atomicAdd(&gs[cc / group], (int)code); } *(uint32_t*)(qr + i8_step_pos(c)) = w; /* the step order, one dword a lane */ @@ -377,17 +346,14 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel( } /* namespace */ /* x [M][n] bf16, `x_ld` elements a row (0 = n) - * q [M][n] i8, DENSE, in libref's STEP ORDER (i8_step_pos: bits 2 and 3 of the - * column exchanged), so n is a multiple of 16, not of 4 - * s [M] f32, ONE scale a row, written at element pitch `s_ld` (0 = 1). A - * plane with more room than rows is legal and filled in libref's flat - * order -- the row's scale at s[r], the tail the caller's -- because - * that is what libref does with whatever capacity it is handed, and a - * byte comparison of the tail then agrees. + * q [M][n] i8, dense, in libref's step order (i8_step_pos), n % 16 == 0 + * s [M] f32, one scale a row at element pitch `s_ld` (0 = 1). A larger + * plane is legal and filled as libref fills it: the row's scale at + * s[r], the tail left to the caller. * asum [n/group][Mpad] f32, optional, group-major, Mpad = ceil(M/16)*16 * - * `group` sizes asum and is ignored without it, as libref ignores it: it is the width of the code - * sums, not the granularity of the scale, which is the whole row. */ + * `group` is the width of the code sums, not of the scale, and is ignored without asum (as in + * libref). */ extern "C" 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) { if (!x || !q || !s) return -1; @@ -419,13 +385,11 @@ extern "C" int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n, } /* x [M][n] bf16, `x_ld` elements a row (0 = n) - * q [M][n] i8, DENSE and ROW-MAJOR: the plane this library's i8a8 GEMM reads + * q [M][n] i8, dense and row-major: the plane this library's i8a8 GEMM reads * s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group)) * - * `group` is the scale's width and is clamped to n when absent, as libref clamps it: `group >= n` - * and `group` absent are both one scale a row. Codes clamp to +-127 before - * the codec, in q8_group's order. 0, -1, -2 a bad extent or an uninstantiated group, -3 a pitch - * that does not describe the operand, -4 the HIP launch failed. */ + * `group` is the scale's width; `group >= n` is one scale a row (the shim clamps an absent group + * to n, as libref does). Return codes as r3d_quant_act_fp8. */ extern "C" 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) { if (!x || !q || !s) return -1; @@ -462,20 +426,17 @@ namespace { /* ================================================================== gated_quant_fp8 * - * act(gate) * up, then quant_act_fp8's quantiser, in one pass. `gate_up` is - * [M, 2n], gate in the first n and up in the second, which is what a fused gate_up projection - * writes; the product is what gets quantised, and `out_bf16`, when bound, receives it. + * act(gate) * up, then quant_act_fp8's quantiser, in one pass. `gate_up` is [M, 2n], gate first, + * as a fused gate_up projection writes it; `out_bf16`, when bound, receives the product. * - * The product is narrowed to bf16 and read back before the absmax. That is the op and not an - * optimisation: the unfused pair writes a bf16 [M, n] tensor and quantises those bytes, so the - * codes are taken over the narrowed value and out_bf16 holds exactly the value they came from. - * Within the product the rounding points are libref's: sg = 1/(1+exp(-gate)) in f32, then - * (gate*sg) for silu -- MULTIPLIED, not divided, which is a different f32 -- then * up, then one - * bf16 narrowing. `expf` is the accurate form and not __expf (r3d_common.h); it is the one value in - * this unit the reference evaluates in double, so a code can move by one where the bf16 narrowing - * lands on a tie. Every other number here is bit-for-bit. + * The product is narrowed to bf16 and read back before the absmax, matching the unfused pair + * (which quantises a bf16 tensor), so out_bf16 holds exactly the value the codes came from. + * Rounding points are libref's: sg = 1/(1+exp(-gate)) in f32, then gate*sg for silu (multiplied, + * not divided), then * up, then one bf16 narrowing. `expf` is the accurate form, not __expf + * (r3d_common.h). The reference evaluates exp in double, so a code can differ by one where the + * bf16 narrowing lands on a tie; everything else is bit-exact. * - * No row reduction, so no first pass and no barrier: a wave a group, a lane four columns. + * No row reduction, so no barrier: a wave a group, a lane four columns. */ template __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void gated_quant_fp8_kernel( @@ -567,8 +528,7 @@ extern "C" int r3d_gated_quant_fp8(long gate_up, long q, long s, long out_bf16, case 512: R3D_GQ(512, A); break; \ default: return -2; \ } - /* The gate is a template argument, so the multiply below is one instruction and not a branch in - * the inner loop; the switch is over the group widths, each with its own lane mapping. */ + /* The activation is a template argument, so the inner loop has no branch on it. */ if (act == R3D_ACT_SILU) { R3D_GQ_ACT(R3D_ACT_SILU); } else { R3D_GQ_ACT(R3D_ACT_SIGMOID); } #undef R3D_GQ_ACT @@ -580,16 +540,13 @@ namespace { /* ================================================================== dequant * - * y = code * scale, the read of a container's own quantised weight. Elementwise, - * so there is no reduction and no order to match; the code decodes exactly (E4M3's four exponent - * bits and three mantissa bits are a subset of f16's, and of f32's; E5M2 is f16's top byte, - * rad_plugin.h; int8 is exact in f32), the product is one f32 multiply per element, and the - * store narrows it to bf16 -- the width every consumer of a dequantised weight on this card reads, - * which is why the launcher names the codes' dtype and not the output's. + * y = code * scale, the read of a container's own quantised weight. Elementwise; each code + * decodes exactly to f32 (E4M3 is a subset of f16 and f32, E5M2 is f16's top byte per + * rad_plugin.h, int8 is exact), one f32 multiply follows, and the store narrows to bf16, the width + * every consumer of a dequantised weight here reads. * - * The scale stream is [M, ceil(n/group)] and the shim requires it to carry every group, so the - * clamp below never fires on a well-formed call; libref clamps a short stream's index to its last - * scale instead of reading off the end, and a kernel row refuses that geometry instead. + * The shim requires the scale stream [M, ceil(n/group)] to carry every group, so the index clamp + * below (libref's behaviour for a short stream) never fires on a well-formed call. */ template __device__ __forceinline__ float code_value(uint8_t b) { @@ -612,8 +569,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void dequant_kernel( const float sc = ldg_f32(sr + gi); /* n is a multiple of 4 and the plane is dense, so a lane's four codes are one dword. */ const uint32_t w = ldg_u32((const uint32_t*)(qr + c)); - /* One 8-byte store a lane: bf16x2_rne is software RTNE, because gfx11 has no - * v_cvt_pk_bf16_f32 (r3d_common.h), and the narrowing is the store's single round. */ + /* One 8-byte store a lane. bf16x2_rne is software RTNE since gfx11 has no + * v_cvt_pk_bf16_f32 (r3d_common.h). */ uint32_t* yp = (uint32_t*)(yr + c); yp[0] = bf16x2_rne(code_value((uint8_t)(w & 0xffu)) * sc, code_value((uint8_t)(w >> 8)) * sc); @@ -624,13 +581,12 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void dequant_kernel( } /* namespace */ -/* q [M][n] codes, DENSE: E4M3, E5M2 or i8, one byte apiece +/* q [M][n] codes, dense: E4M3, E5M2 or i8, one byte apiece * s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group)) * y [M][n] bf16, `y_ld` elements a row (0 = n) * - * `y` is bf16: the launcher describes the codes' dtype and not the output's, because a dequantised - * weight here is read by a bf16 dot2 GEMM, which is the same reason r3d.h gives this launcher one - * dtype argument. An f32 plane is r3d_cast's, which carries two. */ + * `q_dt` names the codes; the output is always bf16, since a dequantised weight here feeds a bf16 + * dot2 GEMM. An f32 output is r3d_cast's job. */ extern "C" int r3d_dequant(long q, long s, long y, int M, int n, int group, int q_dt, int s_ld, int y_ld, long stream) { if (!q || !s || !y) return -1; @@ -660,22 +616,17 @@ extern "C" int r3d_dequant(long q, long s, long y, int M, int n, int group, int /* ================================================================== the plugin ABI entry points * - * Three things every shim here reads off the operands and not off the parameters: + * Every shim reads three things off the operands, not the parameters: * - * * the dtype. A row's `dtype` constraint is a necessary condition on the geometry, not a promise - * about the tensors, and an f32 activation read as bf16 is a value that passes every other - * check. - * * the row count. `M` is the band's upper bound, so the args carry a bound and the operand - * carries the call. - * * the pitch. r3d_rows_pitch() answers in elements, or -1 for an inner axis that is strided. + * * the dtype. A row's `dtype` constraint is a condition on the geometry, not a promise about the + * tensors, and an f32 activation read as bf16 would pass every other check. + * * the row count. `M` is the band's upper bound; the operand carries the call's rows. + * * the pitch. r3d_rows_pitch() answers in elements, or -1 for a strided inner axis. * - * The code planes are dense: none of the four launchers takes a code pitch, because a dot2 GEMM - * reads codes row-major and the engine hands them over in the order it stores them. A plane with a - * hole in it is a stride refusal and not a slow path. */ + * Code planes are dense: no launcher takes a code pitch, and a plane with a hole is a stride + * refusal, not a slow path. */ -/* bf16 is the only activation width these kernels read. An f32 activation is r3d_cast's problem, - * which takes the dtypes as arguments; a quantiser with a dtype switch in its inner loop is the - * wrong shape for an op whose whole point is the store. */ +/* bf16 is the only activation dtype these kernels read; an f32 activation goes through r3d_cast. */ static inline int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; } static inline int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; } /* The codes' dtype picks the codec, so it is checked exactly and never as "some byte". */ @@ -695,11 +646,10 @@ static inline int r3d_launch_status(int e) { } } -/* The group must be a power of two from 4 to 512: the amax butterfly is over the lanes covering a - * group, GROUP/4 of them, and the kernels are instantiated for those widths. libref clamps - * `group <= 0 || group > n` to n, so "one scale a row" arrives as 0 and leaves as n; - * a width with no instantiation is refused and not rounded, because a rounded group would quantise - * on a grid the weight's scales are not on. */ +/* The group must be a power of two from 4 to 512, the instantiated widths. As in libref, + * `group <= 0 || group > n` means one scale a row (n). Any other width is refused, not rounded, + * since a rounded group would quantise on a grid the weight's scales are not on. Returns 0 on + * refusal. */ static inline int r3d_group_of(long long g, long long n) { if (g <= 0 || g > n) g = n; return (g >= 4 && g <= 512 && (g & (g - 1)) == 0) ? (int)g : 0; @@ -752,20 +702,15 @@ extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) { R3D_NEED(dt_bf16(x)); R3D_NEED(dt_i8(q)); R3D_NEED(dt_f32(sc)); - if (r3d_has(as)) R3D_NEED(dt_f32(as)); /* a slot with no bytes is the operand being absent */ + if (r3d_has(as)) R3D_NEED(dt_f32(as)); /* a slot with no bytes is an absent operand */ const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1)); if (n <= 0 || n % 16) return R3D_NO(RAD_E_SHAPE); /* a whole 16-byte step: see i8_step_pos */ - /* One scale a row: this op's scale granularity IS the row (the amax runs over the whole row, - * and the store is `stt(s, rowoff(s, r, 1), scale)`, a FLAT stream at element pitch 1), and - * libref lists `group` as the width of the row SUMS, not of the scale. A plane with more - * elements than rows is therefore accepted and filled in libref's order: the row's scale - * lands at s[r], the plane's first M elements, and the rest of it stays the caller's. That - * is exactly the plane the row's operand description gives -- - * [M, ceil(n/group)], quant_act_i8g's width, of which this op writes the first column -- and - * refusing it would be the shim tightening its own row past the reference: libref requires - * numel(s) >= rows and nothing more, and the bytes it never touches compare equal. */ + /* One scale a row, a flat stream at element pitch 1 as libref writes it (`group` is the + * width of the row sums, not the scale). A larger plane, such as the [M, ceil(n/group)] one + * the row's operand description may give, is accepted: libref requires only + * numel(s) >= rows, writes s[r] and leaves the rest untouched. */ long long rows = 0, qrows = 0, srows = 0; const long long x_ld = r3d_rows_pitch(x, n, &rows); @@ -777,8 +722,7 @@ extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) { if (srows < rows || r3d_numel(sc) < rows) return R3D_NO(RAD_E_SHAPE); if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN); - /* `group` sizes asum only, and is not read without it. n % group == 0, because a sum is over - * whole columns of a row, and the LDS accumulator is 256 groups wide. */ + /* `group` sizes asum only. n % group == 0, and the LDS accumulator is kI8MaxGroups wide. */ int group = 0; if (as) { group = (int)r3d_geti_or(a, "group", R3D_W8_GROUP); @@ -797,8 +741,8 @@ extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) { /* ------------------------------------------------------------------ quant_act_i8g */ -/* The int8 plane at group granularity, and the one this library's i8a8 GEMM reads. Operands are - * libref's oQuantFp8 shape -- {x, q, scale} -- with the int8 codes' dtype. */ +/* The int8 plane at group granularity, read by this library's i8a8 GEMM. Operands are libref's + * oQuantFp8 shape {x, q, scale} with int8 codes. */ enum { QAG_X = 0, QAG_Q, QAG_S }; extern "C" int r3d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) { @@ -812,9 +756,7 @@ extern "C" int r3d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) { const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1)); if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE); - /* libref's clamp of `group`: absent, zero or wider than the row is one - * scale a row, so the default here is 0 and the clamp turns it into n. A width the kernels have - * no instantiation for is refused, not rounded to one. */ + /* Absent `group` defaults to 0, which r3d_group_of turns into one scale a row. */ const int group = r3d_group_of(r3d_geti_or(a, "group", 0), n); if (!group) return R3D_NO(RAD_E_SHAPE); const long long ngrp = (n + group - 1) / group; @@ -846,12 +788,11 @@ extern "C" int r3d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) { R3D_NEED(dt_bf16(gu)); R3D_NEED(dt_e4m3(q)); R3D_NEED(dt_f32(sc)); - if (r3d_has(y)) R3D_NEED(dt_bf16(y)); /* the same: an empty slot is no operand at all */ + if (r3d_has(y)) R3D_NEED(dt_bf16(y)); /* an empty slot is an absent operand */ - /* "silu" (down_proj's input) or "sigmoid" (a gated attention o_proj's), `mode` the integer - * spelling of the same choice, `act` winning where both are given. libref's `act` enumerates - * those two, so a gelu-gated feed-forward is not this row's: it asks for a gate the oracle has - * no definition for here. */ + /* "silu" (down_proj's input) or "sigmoid" (a gated attention o_proj's); `mode` is the integer + * spelling and `act` wins when both are given. libref defines only these two, so a gelu gate + * is unsupported. */ const int act = r3d_act_code(a, "act", "mode", R3D_ACT_SILU); if (act < 0) return R3D_NO(RAD_E_UNSUPPORTED); @@ -861,8 +802,8 @@ extern "C" int r3d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) { if (!group) return R3D_NO(RAD_E_SHAPE); const long long ngrp = (n + group - 1) / group; - /* The fused gate_up projection writes the plane dense, gate half first, [M, 2n] with no hole: a - * sliced gate is r3d_act_mul_bf16's, which takes the two pitches. */ + /* gate_up must be dense [M, 2n], as the fused projection writes it; a sliced gate goes through + * r3d_act_mul_bf16, which takes two pitches. */ long long rows = 0, qrows = 0, srows = 0, yrows = 0; const long long gu_ld = r3d_rows_pitch(gu, 2 * n, &rows); const long long q_ld = r3d_rows_pitch(q, n, &qrows); @@ -890,15 +831,14 @@ extern "C" int r3d_rad_dequant(const RadArgs* a, RadStream stream) { const RadTensor* sc = r3d_opt(a, DQT_S); const RadTensor* y = r3d_opt(a, DQT_Y); if (!q || !sc || !y) return R3D_NO(RAD_E_INVAL); - /* The codes' dtype IS the encoding, so it is read off the tensor: E4M3 and E5M2 are one byte - * apiece and nothing in the bytes tells them apart. A plain u8 plane carries no encoding, so it - * is not accepted under the E4M3 code. */ + /* The codes' dtype is the encoding, read off the tensor since E4M3 and E5M2 bytes look alike. + * A plain u8 plane carries no encoding and is refused (R3D_DT_U8 is the E4M3 code here). */ if (q->dtype == RAD_U8) return R3D_NO(RAD_E_DTYPE); const int q_dt = r3d_dt_code(q->dtype); if (q_dt != R3D_DT_U8 && q_dt != R3D_DT_E5M2 && q_dt != R3D_DT_I8) return R3D_NO(RAD_E_DTYPE); R3D_NEED(dt_f32(sc)); - R3D_NEED(dt_bf16(y)); /* the launcher has no output dtype; see above */ + R3D_NEED(dt_bf16(y)); /* the launcher writes bf16 only */ const long long n = r3d_geti_or(a, "n", r3d_dim(y, (int)y->rank - 1)); if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE); @@ -911,8 +851,8 @@ extern "C" int r3d_rad_dequant(const RadArgs* a, RadStream stream) { if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE); - /* The scale stream's extent gives the group count and `group` each group's width, as libref - * reads them; with no `group`, the stream is taken as one scale per group of ceil(n/ngrp). */ + /* As in libref, `group` gives each group's width; without it the width is ceil(n/ngrp), with + * ngrp taken from the scale stream's extent. */ const long long ngrp_param = r3d_numel(sc) / rows > 0 ? r3d_numel(sc) / rows : 1; long long group = r3d_geti_or(a, "group", 0); if (group <= 0) group = (n + ngrp_param - 1) / ngrp_param; diff --git a/libr3d/r3d_rows.cpp b/libr3d/r3d_rows.cpp index 58cb10e6..12a27b69 100644 --- a/libr3d/r3d_rows.cpp +++ b/libr3d/r3d_rows.cpp @@ -1,52 +1,44 @@ -/* r3d_rows.cpp -- what libr3d can compute, and for which geometry. +/* r3d_rows.cpp -- the libr3d row table: what each kernel computes and for which geometry. * * One row per (kernel, band). A row is a `RadKernelInfo`: names, prose, the geometry it serves as - * constraints, the tuning axes, and the entry points that launch it. The engine reads this table at - * load, matches a requested op and geometry against it, and ranks the candidates by `priority`; it - * never calls a function in this file to do that, and it never looks at a kernel's name. Nothing in - * the engine, the graph, the containers or a test names libr3d's kernels: a card runs this library - * because the rows say they cover its ops, and it stops running them when they do not. + * constraints, the tuning axes and the entry points that launch it. The engine reads this table at + * load, matches a requested op and geometry against it and ranks the candidates by `priority`. It + * never calls into this file to select, and nothing outside libr3d names libr3d's kernels. * * ============================================================ the schema table * * The first plugin in hierarchy order to declare an op fixes its schema, and a plugin whose schema - * disagrees is refused at load, both plugins named (rad_abi.h, spec §2.3): arguments are positional, - * so two schemas for one op would make one call mean two things depending on which row won. libref - * declares the vocabulary in `docs/OPS.md`, so every schema below is libref's -- the same keys, the - * same types, the same requiredness, the same operand roles and optionality, in the same order. The - * prose is ours, because it states what *this* row computes; the loader's comparison - * covers the positional slots and not the documents. + * disagrees is refused at load (rad_abi.h, spec §2.3): arguments are positional, so two schemas + * would give one call two meanings. libref declares the vocabulary (`docs/OPS.md`), so every schema + * below is libref's: the same keys, types, requiredness, operand roles and optionality, in the same + * order. The prose describes this library's rows; the loader compares only the positional slots. * - * An op libr3d invents needs a schema here too, and libref's side of it: an op whose schema is - * declared only by a kernel plugin cannot be checked against a reference, and an op that exists in - * two kernels with two schemas breaks the rule above. That is why libr3d declares no new op: every - * row below implements an op libref declares. + * libr3d declares no new op: an op declared only by a kernel plugin has no reference to be checked + * against. * * ============================================================ the constraint table * - * A constraint is a necessary condition on the geometry (spec §2.1). "bf16 only" is not one: the - * dtype of an operand is a property of the call, and the shim reads the tensor. What goes here is - * what the *kernel* cannot do -- the divisibility its lane map assumes, the band its grid is sized - * for, the scheme its decoders implement -- and what the selector needs to choose between rows. - * A constraint the shim also checks costs nothing; a constraint the kernel does not actually - * enforce is a promise the tests will break. + * A constraint is a necessary condition on the geometry (spec §2.1). An operand's dtype is a + * property of the call, and the shim checks it on the tensor. Constraints state what the kernel + * cannot do (the divisibility its lane map assumes, the band its grid is sized for, the scheme its + * decoders implement) and what the selector needs to choose between rows. A constraint the kernel + * does not actually honour is a promise the tests will break. * * ============================================================ rows are positional * * `RadKernelInfo` is initialised positionally, as `rad_abi.h` requires: a field added anywhere but - * the end shifts every later initialiser, and `nullptr` converts to any function pointer, so part - * of the shift compiles. The order below is the struct's; the trailing slots a row does not use are - * left off, which aggregate initialisation zeroes. A row's entry points are, in order: init, fini, - * launch, scratch, layout, relayout, opd_shape, unrelayout, replaces. + * the end shifts every later initialiser, and because `nullptr` converts to any function pointer, + * part of the shift still compiles. Unused trailing slots are left off and zero-initialised. A row's + * entry points are, in order: init, fini, launch, scratch, layout, relayout, opd_shape, unrelayout, + * replaces. * - * The only `layout` and `relayout` hooks in this table present the container's own planes as the - * joined operands they store -- the w2a8 row's `b_scale`, the fp8 weight's codes and scale, the - * logits head -- and repack nothing, so a container converted on this card keeps row-major codes - * against row-major scales. A dot2 GEMM reads a weight in the order it is stored; libr4d's fragment - * permutations are a WMMA fact, and RDNA3's wave-matrix instructions use a 16x16 fragment layout - * this table's dot2 kernels do not (r3d_common.h has the measurements). + * The `layout` and `relayout` hooks here only present the container's own planes as the joined + * operands they store (the w2a8 row's `b_scale`, the fp8 weight's codes and scale, the logits head) + * and repack nothing, so a container converted on this card keeps row-major codes and scales. A + * dot2 GEMM reads a weight in stored order; libr4d's fragment permutations exist for WMMA, which + * these kernels do not use (see r3d_common.h). * - * Pure host C++: no r3d.h, no HIP, so this table compiles and can be read and tested without ROCm. + * Pure host C++ (no r3d.h, no HIP), so the table compiles and can be tested without ROCm. */ #include "r3d_plugin.h" @@ -83,9 +75,8 @@ /* ================================================================== schemas * - * Operand names are diagnostics only; roles and optionality are positional and must match. Where - * libref's array carries a name libr3d's reads differently (`b` for a gate, say) the names differ - * and the schema does not. + * Operand names are diagnostics only; roles and optionality are positional and must match. + * Operand names may differ from libref's (`b` for a gate, say) without changing the schema. */ /* --- norms and elementwise --- */ @@ -112,11 +103,10 @@ static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_ static const RadParamSpec pCast[] = { P_INT("M"), P_INT("n"), P_STR("from"), P_STR("to") }; static const RadParamSpec pScale[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; -/* `s` is a WEIGHT, which is what the reference declares and what the core acts on: a weight operand - * has its issue resolve a handle and wait on the mover, and a scale plane comes from the container - * or from a quantiser, not from a buffer the planner allocated for this step. Declaring it IN is - * not a cosmetic difference -- the loader compares roles positionally and refuses the library that - * disagrees, every row with it. */ +/* `s` is a weight operand, as the reference declares it: the issue resolves a handle and waits on + * the mover, because a scale plane comes from the container or a quantiser, not from a buffer the + * planner allocated for the step. The loader compares roles positionally, so declaring it IN would + * get the whole library refused. */ static const RadOperandSpec oScale[] = { { "x", RAD_OPD_IN, 0 }, { "s", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 } }; @@ -189,38 +179,28 @@ static const RadOperandSpec oGemmQ[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RA /* ================================================================== the vocab and the sampler * - * The vocab and sampler bands, transcribed from libref. A schema is inert on its own -- the loader - * matches a row to a schema, and a row naming an entry point no unit defines is an undefined symbol - * that kills `dlopen` and takes every row in the library with it -- so `r3d_selftest`'s schema phase - * compares every declared schema against libref's, slot for slot, the moment the library loads, and - * a misspelled key is refused at load, not when a row first meets it. + * The vocab and sampler schemas, transcribed from libref. `r3d_selftest`'s schema phase compares + * every declared schema against libref's, slot for slot, when the library loads, so a misspelled + * key is caught at load rather than when a row first uses it. * - * The sampler is a law, not a shape: the candidate set, the tie-break in the top-k, the order of the - * renormalisations and the seeded draw are all observable, and libref is the oracle for all of them. + * The sampler's behaviour is fully specified: the candidate set, the top-k tie-break, the order of + * the renormalisations and the seeded draw are all observable, and libref is the oracle for each. */ -/* The gated MLP's activation, as the llama-family graphs emit it: one fused [M, 2n] projection, the - * gate's half activated and multiplied by the other. `act_mul` is the same arithmetic over two - * operands; these are different ops, and an architecture emits one or the other. */ +/* The gated MLP's activation as llama-family graphs emit it: one fused [M, 2n] projection, the + * gate half activated and multiplied by the other half. `act_mul` is the same arithmetic over two + * operands; an architecture emits one op or the other. */ static const RadOperandSpec oGateUp[] = { { "gate_up", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; -/* Paged attention. `block_size` is RAD_DERIVED here (the container's cache geometry, admitted by a - * constraint that only refuses its absence), and `n_head`, `max_seqs`, `max_ctx` and `prefill_fp8` - * are on the list because a plugin's scratch hook sizes a split-KV buffer from them and both - * libraries must agree on the parameter list -- libref ignores them. */ -/* DFlash2's candidate walk: a draft block of `steps` proposals, `top_k` candidates at each step, - * rescored against the target's rank-d codebooks. `anchor_stride` is optional and defaults to 1; - * `hp` is the optional per-edge scaling of the predecessor's codebook row, and absent it is a plane - * of ones, which is what the reference computes. */ -/* The gated MLP band: one weight of N = 2n rows (gate first, then up), the GEMM, the gate and the - * output quantiser in one launch, so the [M, N] intermediate the unfused chain writes and re-reads - * never exists. `act` is a required string: an implementation compiles one gate, and an optional - * would let a row resolve for the gate it does not have. */ +/* The gated MLP band: one weight of N = 2n rows (gate first, then up), with the GEMM, the gate and + * the output quantiser in one launch so the [M, N] intermediate is never stored. `act` is a required + * string because an implementation compiles one gate; an optional key would let a row resolve for a + * gate it does not have. */ static const RadParamSpec pGemmQGated[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), P_STR("dtype"), P_STR("act") }; -/* The vocabulary projection's schema, slot for slot with the reference's: the geometry is the head's - * (`n_vocab` x `n_embd`), the dtype is the activation's, and `logits` is f32 -- the op exists - * separately from gemm_nt for that reason, and the row that serves it narrows nothing. */ +/* The vocabulary projection's schema, slot for slot with the reference's: the geometry is the + * head's (`n_vocab` x `n_embd`), the dtype is the activation's, and `logits` is f32, which is why + * the op is separate from gemm_nt. */ static const RadParamSpec pLogits[] = { P_INT("M"), P_INT("n_vocab"), P_INT("n_embd"), P_STR("dtype") }; static const RadOperandSpec oLogits[] = { @@ -233,6 +213,10 @@ static const RadOperandSpec oGemmQGated[] = { { "out_bf16", RAD_OPD_OUT, 1 }, }; +/* DFlash2's candidate walk: a draft block of `steps` proposals with `top_k` candidates each, + * rescored against the target's rank-d codebooks. `anchor_stride` is optional and defaults to 1. + * `hp` is an optional per-edge scaling of the predecessor's codebook row; absent, it is a plane of + * ones, as the reference computes. */ static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_INT("top_k"), P_INT("rank"), P_INT("n_vocab"), P_INTO("anchor_stride"), P_STR("dtype") }; @@ -243,6 +227,10 @@ static const RadOperandSpec oDflashSelect[] = { { "tokens", RAD_OPD_OUT, 0 }, }; +/* Paged attention. `block_size` is RAD_DERIVED (the container's cache geometry, admitted by a + * constraint that only refuses its absence). `n_head`, `max_seqs`, `max_ctx` and `prefill_fp8` are + * listed because a plugin's scratch hook sizes the split-KV buffer from them and both libraries must + * agree on the parameter list; libref ignores them. */ static const RadParamSpec pAttnPaged[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"), P_INT("window"), P_STR("q_dtype"), P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"), @@ -305,13 +293,12 @@ static const RadOperandSpec oPick[] = { { "cand_idx", RAD_OPD_IN, 0 }, { "token", RAD_OPD_OUT, 0 } }; -/* The fused MLP activation and the fused norm-quantiser, both from the model unit. The first takes - * one [M, 2n] operand and produces [M, n]; the second is libref's, slot for slot, with `residual` - * INOUT because the sum it stores is the one the variance reads. */ +/* The fused norm-quantiser from the model unit, libref's slot for slot. `residual` is INOUT because + * the sum it stores is the one the variance reads. */ static const RadParamSpec pRmsQuantFp8[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), P_STR("dtype"), P_F64O("wadd") }; -/* `residual` is optional because the op has a no-residual form, which is what the launcher's `res` - * pointer being 0 means; libref spells it INOUT_O and the loader compares the flag. */ +/* `residual` is optional because the op has a no-residual form (the launcher's `res` pointer is 0); + * libref declares it INOUT optional and the loader compares the flag. */ static const RadOperandSpec oRmsQuantFp8[] = { { "x", RAD_OPD_IN, 0 }, { "residual", RAD_OPD_INOUT, 1 }, { "w", RAD_OPD_WEIGHT, 0 }, { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "out_bf16", RAD_OPD_OUT, 1 } @@ -361,8 +348,8 @@ static const RadOpSchema kSchemas[] = { "Symmetric per-(row, group) E4M3: scale = amax * (1/448) with the reciprocal " "multiplied, not divided; an all-zero group gets scale 1 and the codes 0."), SCHEMA("quant_act_i8", pQuant, oQuant, - "Symmetric int8 with ONE SCALE PER ROW, max(amax, 1e-8) / 127, codes round-to-nearest-" - "ties-to-even and saturating, stored in the STEP ORDER the int8 WMMA reads. `asum` takes " + "Symmetric int8 with one scale per row, max(amax, 1e-8) / 127, codes round-to-nearest-" + "ties-to-even and saturating, stored in the step order the int8 WMMA reads. `asum` takes " "the group-major row sums the zero-pointed GEMMs reduce."), SCHEMA("quant_act_i8g", pQuant, oQuantFp8, "The same int8 code at `group` granularity: one f32 scale per (row, group), amax / 127, " @@ -383,17 +370,17 @@ static const RadOpSchema kSchemas[] = { SCHEMA("rmsnorm_quant_fp8", pRmsQuantFp8, oRmsQuantFp8, "RMS norm with an optional residual add, then the E4M3 quantiser, in one pass. The " - "residual add is STORED BEFORE THE VARIANCE READS IT, so the sum the norm is taken over " - "is the bf16 one and not the f32 one -- that is what makes this the `add` + `rmsnorm` " - "pair and not `rmsnorm_add`, which normalises the unrounded sum. `wadd` is added to every " + "residual sum is stored as bf16 before the variance reads it, so the norm is taken over " + "the rounded sum, as the `add` + `rmsnorm` pair computes it (`rmsnorm_add` normalises " + "the unrounded sum). `wadd` is added to every " "gain in f32. `out_bf16` holds exactly the value the codes were taken over."), /* ---- the vocabulary and the sampler: schemas first, rows with their kernels ---- */ SCHEMA("silu_mul", pMnDtype, oGateUp, "y[i] = silu(gate_up[i]) * gate_up[n + i] over one fused [M, 2n] plane, the gate the " "first half -- rad-convert's fusion order -- and the product of an activation that was " - "never narrowed. act_mul is the same arithmetic over two operands, narrowing first, " - "because the pair it replaces stored the activation."), + "never narrowed. act_mul is the same arithmetic over two operands, narrowing the " + "activation first, as a stored activation is."), SCHEMA("attn_paged", pAttnPaged, oAttnPaged, "Scaled dot-product attention over a paged KV cache: q [tokens, n_head, head_dim], the " "cache [blocks, kv_heads, block_size, 2*head_dim], `block_table` a row's block list, " @@ -473,37 +460,32 @@ extern "C" const RadOpSchema* rad_kernel_schema_at(int i) { /* ================================================================== tuning * - * The axes a kernel is instantiated along, measured on this card (`rad-tune`, spec §15). Every row - * without a matrix instruction to size a tile against has few axes: what is left to measure is how - * the work is split across the card, and how the weight stream is read. + * The axes a kernel is instantiated along, measured per card by `rad-tune` (spec §15). Without a + * matrix instruction to size a tile against, the rows have few axes: how the work is split across + * the card and how the weight stream is read. */ -/* Split-K. 0 is not a point in the space, it is the kernel's own law: "the largest split legal at - * this K", because no fixed default is legal at every shape and an illegal default would make an - * untuned install fail rather than run slowly. */ +/* Split-K. 0 is not a point in the space but the kernel's rule, "the largest split legal at this + * K" (r3d_args.h: libr3d's tunables). */ static const int64_t kSk[] = { 0, 1, 2, 4, 8, 16 }; /* Waves per block. 8 is 256 threads, which is the largest block that keeps the register budget of * a wave-per-N-tile kernel inside gfx11's 1024 VGPRs a SIMD at four waves. */ static const int64_t kWv[] = { 1, 2, 4, 8 }; -/* Non-temporal weight streaming: a decode GEMM reads a weight once per token, so the L2 is a - * latency cache and not a reuse cache. RDNA3 has no transposed-load instruction, so this axis - * selects the plain 128-bit stream with the cache hints off -- a knob worth measuring, not an - * instruction. */ +/* Non-temporal weight streaming: a decode GEMM reads a weight once per token, so the L2 serves + * latency, not reuse. RDNA3 has no transposed-load instruction, so this axis only switches the cache + * hints on the plain 128-bit stream. */ static const int64_t kNt[] = { 0, 1 }; -/* No `kb` axis. Only a GEMM that stages a K slab through LDS has a slab width to measure, and - * the skinny rows stream the weight through registers; the axis joins the table with the tiled - * row. */ +/* No `kb` axis: only a GEMM that stages a K slab through LDS has a slab width to tune, and the + * skinny rows stream the weight through registers. */ static const RadTunable tGemmM16[] = { { "sk", kSk, NELEM(kSk), 0, "split-K slices; 0 is the widest legal for this K" }, { "wv", kWv, NELEM(kWv), 8, "waves per block" }, { "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" }, }; -/* No `wv` here. The quantised kernel's launcher takes a fixed block of eight waves -- its weight - * decode, sixteen codes a lane into eight dot2, is the whole of a wave's issue budget at any block - * size -- so an axis the tuner would sweep is an axis the kernel ignores, and a tunable that changes - * nothing is worse than none: it spends the tuner on a knob and teaches the reader that the table - * lies. The axis joins the row with a launcher that takes it. */ +/* No `wv` axis: the quantised kernel's launcher uses a fixed block of eight waves, because its + * weight decode (sixteen codes a lane into eight dot2) fills a wave's issue budget at any block + * size. An axis the kernel ignores would only spend tuner time. */ static const RadTunable tGemmQ[] = { { "sk", kSk, NELEM(kSk), 0, "split-K slices; 0 is the widest legal for this K" }, { "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" }, @@ -524,8 +506,8 @@ static int gemm_tune_valid(const RadParam* p, int n_p, const RadParam* c, int n_ return sk >= 0 && (sk == 0 || K % (sk * unit) == 0); } -/* The chosen point, read back. `TUNE` falls to the axis's default when the core appended nothing, - * so a checker with no tuned key runs what an untuned install runs. */ +/* The chosen point, read back. `TUNE` falls back to the axis's default when the core appended + * nothing, so a caller with no tuned key runs what an untuned install runs. */ static long long tune_i(const RadArgs* a, const RadTunable* t, int n, const char* key) { if (a && a->p) for (int i = 0; i < a->n_p; ++i) @@ -551,21 +533,15 @@ extern "C" void r3d_cfg_topk(const RadArgs* a, R3dTopkCfg* out) { out->nch = 0; } -/* A split's partials are f32 over the output, plus one arrival counter per split. Sized at the - * band's bounds and the axis's widest split, because a scratch hook runs at declare, where the - * range may still be open: the buffer must hold any point the tuner can pick. */ -/* Split-KV's partials: one record of 128 accumulator floats plus the running max and sum -- 132 - * floats -- per (query row, head, slice). The shim takes the slice count from the bytes the engine - * offers and halves it until they fit, so this is the want, stated at the slice count the walk - * benefits from and capped at what these bands can carry: 15 MB at the decode band (1792 rows over - * 16 heads) and 17 MB at the prefill band. Attaching scratch makes the row non-concurrent, which is - * the ABI's rule (rad_kernel_concurrent is `scratch == nullptr`) and the price of the split. */ +/* Split-KV partials: one record of 128 accumulator floats plus the running max and sum (132 + * floats) per (query row, head, slice). The shim takes the slice count from the bytes the engine + * offers, halving it until they fit, so this is the request at the slice count the walk benefits + * from, capped at 16 MiB. Attaching scratch makes the row non-concurrent (rad_kernel_concurrent is + * `scratch == nullptr`), which is the cost of the split. */ static int64_t attn_scratch(const RadArgs* a) { - /* The size comes from the SHAPE, and a scratch hook runs at declare, where the engine has bound - * the operands' shapes and has no bytes to hand out yet -- `data` is null at declare for every - * tensor in the plan. A hook that requires bytes answers 0 for the whole run, the engine - * allocates an arena of 0 bytes, and the shim's split pass finds no partials to write. The - * sibling `gemm_scratch` sizes off `RadParam` dims for exactly this reason. */ + /* Sized from the shape: a scratch hook runs at declare, when the operands' shapes are bound + * but every tensor's `data` is still null. A hook that required data would answer 0 and the + * split pass would find no buffer. gemm_scratch sizes from RadParam dims for the same reason. */ if (!a || a->n_t < 1 || a->t[0].rank == 0) return 0; long long n_head = 0, head_dim = 0; const int64_t nh = rad_args_geti(a, "n_head", &n_head) ? n_head : 0; @@ -577,6 +553,9 @@ static int64_t attn_scratch(const RadArgs* a) { return want < cap ? want : cap; } +/* A split's partials are f32 over the output, plus one arrival counter per split. Sized at the + * band's bounds and the axis's widest split, because a scratch hook runs at declare, where the + * range may still be open: the buffer must hold any point the tuner can pick. */ static int64_t gemm_scratch(const RadParam* p, int n_p) { const long long M = rad_param_getdim(p, n_p, "M", 0), N = rad_param_getdim(p, n_p, "N", 0); const long long sk = kSk[NELEM(kSk) - 1]; @@ -586,9 +565,9 @@ static int64_t gemm_scratch(const RadParam* p, int n_p) { /* ================================================================== constraints * - * What the kernel cannot do, and what the selector needs. The divisibility in each is the lane map - * in the unit: a wave covering a bf16 row reads four elements a lane (two pairs), so a row of 4m - * elements needs no tail; where the kernel has a tail path the constraint says 2, not 4. + * What the kernel cannot do, and what the selector needs. Divisibility follows the unit's lane map: + * a wave covering a bf16 row reads four elements a lane (two pairs), so a row of 4m elements needs + * no tail; where the kernel has a tail path the constraint says 2, not 4. */ /* bf16 elementwise, norms and the GEMMs: rows of an even width, so a lane owns a pair. */ @@ -630,14 +609,12 @@ static const RadConstraint cFillF32[] = { C_IN("dtype", "f32") }; static const RadConstraint cFillI32[] = { C_IN("dtype", "i32") }; static const RadConstraint cFillI64[] = { C_IN("dtype", "i64") }; -/* rope: the two modes this kernel implements, and a rotary width that is a whole even head. The - * yarn, llama3 and ladder parameters are absent from these rows' bands, so a geometry carrying them - * is not routed here. */ -/* `rotary_dim` is optional on the op, and a constraint on a parameter a band does not carry does - * not hold -- the engine's rule, quoted in r3d_selftest.cpp's band-reachability phase -- so it - * cannot appear here: an architecture that rotates the whole head, which is every llama-family - * graph, emits a band without the parameter and would find no row. Its evenness is the shim's to - * refuse (RAD_E_SHAPE), and `rotary_dim` absent is head_dim, which is even by the constraint above. */ +/* rope: the two modes this kernel implements and an even head_dim. The yarn, llama3 and ladder + * parameters are absent from these rows' bands, so a geometry carrying them is not routed here. + * `rotary_dim` cannot be constrained: it is optional, a constraint on a key the band does not carry + * does not hold (see r3d_selftest.cpp's band-reachability phase), and llama-family graphs, which + * rotate the whole head, omit it. The shim refuses an odd rotary_dim (RAD_E_SHAPE); absent, it is + * head_dim, which the constraint keeps even. */ static const RadConstraint cRope[] = { C_IN("mode", "neox gptj"), C_DIV("head_dim", 2) }; /* The cache's dtype is the row: a bf16 cache stores the value, an E4M3 cache encodes it with the @@ -661,17 +638,17 @@ static const RadConstraint cScatterBf16[] = { C_IN("dtype", "bf16"), C_DIV("n", * wave's four-elements-a-lane store is whole. */ static const RadConstraint cQuantFp8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_FP8_BLOCK), C_DIV("n", 4) }; -/* `quant_act_i8` is the per-row int8 whose codes the int8 WMMA reads, so its width is a whole - * 16-byte step, not a lane's four. `quant_act_i8g` is the per-group one whose codes are row-major, - * which is what a dot2 GEMM reads; it is the activation of this library's i8a8 row. */ +/* `quant_act_i8` is the per-row int8 whose codes are in the int8 WMMA's step order, so its width + * is a whole 16-byte step. `quant_act_i8g` is per group with row-major codes, as a dot2 GEMM reads + * them; it is the activation of this library's i8a8 row. */ static const RadConstraint cQuantI8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_W8_GROUP), C_DIV("n", 16) }; static const RadConstraint cQuantI8g[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_W8_GROUP), C_DIV("n", 4) }; -/* Not `C_IN("act", "silu sigmoid")`: `act` is optional on the op (a graph may carry libref's integer - * `mode` instead, and libref's own default is silu), and a band that states neither would resolve to - * nothing. The shim reads `act`, falls back to `mode`, then to silu, and refuses a gelu -- the - * activation whose kernel this unit does not carry -- with RAD_E_UNSUPPORTED. */ +/* Not `C_IN("act", "silu sigmoid")`: `act` is optional on the op (a graph may carry libref's + * integer `mode` instead, and libref defaults to silu), so a band with neither would match no row. + * The shim reads `act`, then `mode`, then defaults to silu, and refuses gelu, which this unit has no + * kernel for, with RAD_E_UNSUPPORTED. */ static const RadConstraint cGateQuant[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_FP8_BLOCK), C_DIV("n", 4) }; static const RadConstraint cDequantFp8[] = { C_IN("dtype", "fp8_e4m3"), @@ -681,50 +658,35 @@ static const RadConstraint cDequantE5[] = { C_IN("dtype", "fp8_e5m2"), static const RadConstraint cDequantI8[] = { C_IN("dtype", "i8"), C_EQ("group", R3D_W8_GROUP), C_DIV("n", 4) }; -/* The GEMMs. The skinny row's band is the decode and verify height: 16 rows, which is a speculative - * verify's ceiling with room to spare, and below the height where staging the activations through - * LDS starts to pay. K even, because the inner loop consumes pairs; N unconstrained, because a wave - * covering N tiles the tail. - * - * No upper bound on N: the vocabulary and the feed-forward widths are 11008, 14336, 128256 and - * whatever a given checkpoint's `intermediate_size` is, and a bound would refuse them. */ +/* The GEMMs. The skinny row's band is the decode and verify height, M <= 16: it covers a + * speculative verify with room to spare and stays below the height where staging the activations + * through LDS pays. K even because the inner loop consumes pairs. N has no bound: a wave covering N + * handles the tail, and feed-forward and vocabulary widths (11008, 14336, 128256, a checkpoint's + * `intermediate_size`) vary. */ static const RadConstraint cGemmM16[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 2), C_GE("N", 1) }; -/* The vocabulary projection. **No `dtype` constraint, and the reason is the engine's, not the - * kernel's**: the band this op is declared with carries the geometry (M, n_vocab, n_embd) and not a - * dtype key -- the head's dtype is a property of the weight, which is why libref's own logits row - * answers it with a `check_dtypes` hook and not with a constraint. A constraint on a key the - * geometry does not carry serves nobody: with `dtype in {bf16}` declared, the engine resolves a - * host kernel and no device one and refuses to start, so the dtype is refused where it is read, at - * the shim, naming the widening the kernel does. - * `n_embd` in 32-code chunks is the entry's own rule (K % 32), stated so a band outside it is - * refused at declare rather than at launch. `n_vocab`'s floor is the store's granularity: a row - * writes 16-byte runs, so a plane four ids wide is the narrowest it can read, and a band narrower - * than that -- a shard's padding, a 1-id test vocabulary -- is refused by the constraint and not by - * the launch. Above the floor the grid is vocab-wide at every M, so a 320-wide vocabulary and a - * 130560-wide one are the same kernel. */ +/* The vocabulary projection has no `dtype` constraint because its band carries no `dtype` key: the + * head's dtype is a property of the weight (libref checks it with a `check_dtypes` hook). A + * constraint on a key the band lacks does not hold, which would leave only the host kernel and the + * engine would refuse to start, so the shim refuses an unsupported dtype instead. + * `n_embd % 32` is the entry's chunk rule, stated so a band outside it is refused at declare rather + * than at launch. `n_vocab >= 4` is the store's granularity (16-byte runs); a narrower band (a + * shard's padding, a 1-id test vocabulary) is refused here. Above that floor the grid spans the + * vocabulary at every M, so every vocabulary width runs the same kernel. */ static const RadConstraint cLogitsGemm[] = { C_GE("M", 1), C_GE("n_vocab", 4), C_DIV("n_embd", 32) }; -/* The tiled GEMM at prefill heights. M >= 17 is the complement of cGemmM16's M <= 16 by - * construction, so the two rows never compete for a band: the skinny shape (a wave a run of - * columns, the weight streamed past registers) is right up to 16 rows and wrong above it, and the - * 128x128 tile is the reverse. K % 32 is the tile's k-chunk and N >= 8 the bf16 store run, for the - * same reason cLogitsGemm states its floor: what the kernel cannot read is in the constraints. */ -/* The quantised GEMM above the decode heights. Here `dtype` IS the operand scheme -- gemm_q_shape - * switches on it -- so C_IN filters, which is the distinction from logits_gemm, where the band's - * dtype names the activation and C_IN filters nothing. M >= 17 is the complement of - * gemm_nt_q_fp8a8_m16's M <= 16 -- read from its constraint, not from its name: a higher floor - * would leave 17..64 unserved, and a 209-row batched decode is the shape a serving card spends - * most of its life in. The tile's k-chunk (32) divides the container's scale - * block (128), which is why `group` is an equality and `K` a divisibility. */ +/* The quantised GEMM above decode heights. Here `dtype` is the operand scheme (gemm_q_shape + * switches on it), so C_IN filters rows, unlike logits_gemm, where the band's dtype names the + * activation. M >= 17 complements gemm_nt_q_fp8a8_m16's M <= 16; a higher floor would leave batched + * decode at 17..64 rows unserved. The tile's k-chunk (32) divides the container's scale block + * (128), so `group` is an equality and `K` a divisibility. */ static const RadConstraint cGemmQFP8Tiled[] = { C_IN("dtype", "fp8a8 fp8a8f32"), C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 17), C_DIV("K", 128) }; -/* The OCP-MXFP4 rows: the weight is e2m1 with one e8m0 scale per 32 of K, the activation's - * scale per 128 -- both fixed by the format, so the `group` key carries no kernel-side meaning - * and the rows do not constrain it (the reference derives the planes from it). K dividing 128 - * carries the 32-block; the band split is the fp8a8 one, 16 at the ceiling and 17 at the floor, - * and the dtype carries the whole scheme. */ +/* The OCP-MXFP4 rows: e2m1 weight codes with one e8m0 scale per 32 of K, the activation scaled per + * 128. Both are fixed by the format, so the `group` key has no kernel-side meaning and is not + * constrained (the reference derives the planes from it). K % 128 covers the 32-block, the bands + * split at M = 16 / 17 as for fp8a8, and the dtype names the whole scheme. */ static const RadConstraint cGemmQMxfp4a8M16[] = { C_IN("dtype", "mxfp4a8"), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; @@ -732,9 +694,8 @@ static const RadConstraint cGemmQMxfp4a8Tiled[] = { C_IN("dtype", "mxfp4a8"), C_GE("M", 17), C_DIV("K", 128) }; -/* The symmetric int4 / int8 weight grids at decode heights: the block is the weight's scale - * group (128), and the band is the m16 one -- M > 16 is the tiled rows', and the 8-bit grid at - * prefill heights is declared out. */ +/* The symmetric int4 / int8 weight grids at decode heights: the block is the weight's scale group + * (128) and the band is M <= 16. No row serves the 8-bit grid at prefill heights. */ static const RadConstraint cGemmQW4A8M16[] = { C_IN("dtype", "w4a8"), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; @@ -742,26 +703,26 @@ static const RadConstraint cGemmQW8A8M16[] = { C_IN("dtype", "w8a8"), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; +/* The tiled bf16 GEMM at prefill heights. M >= 17 complements cGemmM16's M <= 16, so the two rows + * never compete for a band: the skinny shape (a wave a run of columns, the weight streamed through + * registers) suits up to 16 rows and the 128x128 tile suits more. K % 32 is the tile's k-chunk and + * N >= 8 the bf16 store run. */ static const RadConstraint cGemmNTTiled[] = { C_IN("dtype", "bf16"), C_GE("M", 17), C_DIV("K", 32), C_GE("N", 8) }; /* The quantised GEMM: the scheme names the row, the weight's block is the container's, and a split - * must land on a block boundary (gemm_tune_valid). */ -/* The block: `group` is required and every band names it, so the row states it. `pb1` and `pb2` are - * OPTIONAL, and a constraint on a key the band omits does not hold -- a model whose container - * declares the default block says nothing about pb1, and constraining it would make every one of - * that model's GEMM bands fall through to the reference and its host kernel -- 259 ops on one - * 2B model. The launcher defaults them to `group` (r3d_gemm_fp8a16_nt_m1.hip) and refuses a - * pb2 that is not the code group, which is the container's own invariant: the K block IS the code - * group, so a band naming pb2 unequal to group resolves to this row and is refused at launch. */ + * must end on a block boundary (gemm_tune_valid). `group` is required and every band names it, so + * the row constrains it. `pb1` and `pb2` are optional, and a constraint on a key the band omits does + * not hold, so constraining them would send every GEMM band of a container using the default block + * to the reference's host kernel. The launcher defaults them to `group` (r3d_gemm_fp8a16_nt_m1.hip) + * and refuses a pb2 that differs from the code group, the container's own invariant. */ static const RadConstraint cGemmQFp8a16[] = { C_IN("dtype", "fp8a16"), C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; static const RadConstraint cGemmQFp8a8[] = { C_IN("dtype", "fp8a8"), C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; -/* The int8 GEMM's constraints are written ahead of its row: 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. */ +/* The int8 GEMM's constraints. No row uses them: a row must name an entry point the library + * defines, or the plugin fails to load. */ static const RadConstraint cGemmQI8[] = { C_IN("dtype", "i8a8"), C_EQ("group", R3D_W8_GROUP), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; @@ -771,30 +732,25 @@ static const RadConstraint cGemmQI8[] = { C_IN("dtype", "i8a8"), * Declaration order is the tie-break within one priority, so rows that share an op are declared * narrowest first. */ -/* The constraints above are written ahead of the rows that use them, for the same reason the - * schemas are: the table reads as one document. A constraint array with no row is not an error, so - * the file builds; the comment above each says which row it serves. */ +/* Constraint arrays are declared ahead of the rows that use them, each with a comment naming the + * row it serves. */ /* ================================================================== the fused-MLP rows * - * The two rows the llama graphs ask for that the model unit serves. `silu_mul` constrains - * nothing but the dtype and an even `n`: `act` is not in this op's parameter list (it is the fused - * form of one fixed activation), and a constraint on a key the geometry lacks does not hold, so a - * row built on the act_mul constraints would resolve to no band at all. `rmsnorm_quant_fp8` states - * the group the kernel covers with a wave and requires it to divide `n`; the standalone quantiser's - * `n % 4` would admit a band this kernel refuses, and a row that resolves at declare and fails at - * launch is the shape of bug this file exists to prevent. + * Two rows llama graphs ask for that the model unit serves. `silu_mul` constrains only the dtype + * and an even `n`: `act` is not in this op's parameter list (the op fuses one fixed activation), and + * a constraint on a key the band lacks does not hold, so the act_mul constraints would match no band. + * `rmsnorm_quant_fp8` requires the group the kernel covers with a wave to divide `n`; the standalone + * quantiser's `n % 4` would admit bands this kernel refuses at launch. */ static const RadConstraint cSiluMul[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; static const RadConstraint cRmsQuantFp8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_FP8_BLOCK), C_DIV("n", R3D_FP8_BLOCK) }; -/* The sampler's pre-filters constrain `n_vocab` and nothing else. The bands an architecture emits - * for these ops carry `n_vocab` and `M` (plus `vocab_off`, and `k` for logprobs) and no `dtype` - * key, so a row that constrained a dtype would constrain a key the geometry lacks and resolve to no - * band at all. The dtype is f32; the shims check it on the tensor, which is where a dtype belongs - * when the geometry does not name it. `k <= 64` is the depth of the logprobs kernel's pool, so the - * row serves exactly the bands its launcher accepts. +/* The sampler's pre-filters constrain only `n_vocab`. Their bands carry `n_vocab` and `M` (plus + * `vocab_off`, and `k` for logprobs) and no `dtype` key, so a dtype constraint would match no band; + * the shims check that the tensors are f32. `k <= 64` is the depth of the logprobs kernel's pool, so + * the row serves exactly the bands its launcher accepts. */ static const RadConstraint cSampleF32[] = { C_GE("n_vocab", 1) }; static const RadConstraint cSampleLogprobs[] = { C_GE("n_vocab", 1), C_GE("k", 1), C_LE("k", 64) }; @@ -814,25 +770,18 @@ static const RadConstraint cAttnFp8Prefill[] = { C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), C_EQ("head_dim", 128), C_GE("q_len", 17) }; -/* `row_topk` is banded on dtype, so it gets two rows; the candidate stages are banded on `n_cand`, - * whose ceiling is the kernel's: five f32 arrays of n_cand in LDS is 20 KiB of the 64 KiB, and a - * wider band is refused by the shim (RAD_E_SHAPE), so the row states the ceiling and resolves for - * exactly what it serves. The vocab stages carry `n_vocab` and no dtype key, and the logits are f32 - * by the shim's check on the tensor. +/* `row_topk` is banded on dtype, so it has two rows. The candidate stages are banded on `n_cand`, + * capped at the kernel's ceiling: five f32 arrays of n_cand in LDS is 20 KiB of the 64 KiB, and the + * shim refuses a wider band (RAD_E_SHAPE). The vocab stages carry `n_vocab` and no dtype key; the + * shim checks that the logits are f32. */ static const RadConstraint cRowTopkBf16[] = { C_IN("dtype", "bf16"), C_GE("N", 1), C_GE("R", 1) }; static const RadConstraint cRowTopkF32[] = { C_IN("dtype", "f32"), C_GE("N", 1), C_GE("R", 1) }; static const RadConstraint cSampleCand[] = { C_GE("n_cand", 1), C_LE("n_cand", 1024) }; -/* Every key the walk reads is required and in the band, so all of them are bound -- `top_k <= 256` - * is one lane a candidate. `anchor_stride` is deliberately NOT bound: it is optional, defaults to - * 1, and the kernel serves any value at or above 1, so a band that omits it must still resolve. */ -/* The block is one key for three things at once: the weight's K block, its row block and the - * quantiser's group. `act` is C_IN because it is a required string here, not the optional `mode` - * form. M <= 64 is the ceiling the launcher serves; 47 of MiniCPM5-2B's 48 bands are M=64. */ -/* The container's 2-bit vocab weights. `group` is one key for the weight's K block and the scale's - * block, as everywhere in this family; K must also be a multiple of the launcher's chunk - * (2048 / M-tile), which the launcher refuses and the row does not pretend to cover. */ +/* The container's 2-bit vocab weights. `group` is both the weight's K block and the scale's block. + * K must also be a multiple of the launcher's chunk (2048 / M-tile), which the launcher refuses and + * the row does not express. */ static const RadConstraint cGemmQW2A8[] = { C_IN("dtype", "w2a8"), C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; @@ -844,12 +793,18 @@ static const RadConstraint cGemmQW2A8Tiled[] = { C_IN("dtype", "w2a8 w4a8_asym") C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 17), C_DIV("K", 128) }; +/* `group` is one key for three things: the weight's K block, its row block and the quantiser's + * group. `act` is C_IN because it is a required string here, not the optional `mode` form. M <= 64 + * is the launcher's ceiling. */ static const RadConstraint cGemmGated[] = { C_IN("dtype", "fp8a8"), C_IN("act", "silu sigmoid"), C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1), C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 2), C_GE("N", 2) }; +/* Every key the walk reads is required and in the band, so all are bound; `top_k <= 256` gives each + * candidate one lane. `anchor_stride` is deliberately unbound: it is optional, defaults to 1, and + * the kernel serves any value >= 1, so a band that omits it must still resolve. */ static const RadConstraint cDflashSelect[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_GE("steps", 1), C_GE("top_k", 1), C_LE("top_k", 256), C_GE("rank", 1), @@ -1121,11 +1076,10 @@ static const RadKernelInfo kKernels[] = { /* ------------------------------------------------------------------ r3d_quant_fp8.hip * - * Plain row-major code planes against one f32 scale per (row, group). No fragment permutation for - * the codes a dot2 GEMM reads: it reads them in the order they are stored, which is the whole - * reason a container converted on this card is readable by libref and by `rad-convert` on any other - * card. The one plane that keeps libref's permutation is `quant_act_i8`'s, whose order is part of - * what the op means -- see the row. + * Plain row-major code planes with one f32 scale per (row, group). A dot2 GEMM reads codes in + * stored order, so they carry no fragment permutation, and a container converted on this card is + * readable by libref and by `rad-convert` on any card. Only `quant_act_i8` keeps libref's + * permutation, because its order is part of the op (see the row). */ { "quant_act_fp8_bf16", "quant_act_fp8", "quant", "symmetric per-(row, group) E4M3: scale = amax * (1/448), the codes the value times 1/scale", @@ -1136,12 +1090,11 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r3d_rad_quant_act_fp8, nullptr, nullptr, nullptr, r3d_shape_quant_act_fp8 }, -/* The per-row int8, in libref's step order. The order is the op's, not the kernel's convenience: - * the codes are the WMMA A-fragment's, and the plane is what the oracle compares, so this row keeps - * the permutation and the kernel's store address carries it. libr3d's own int8 GEMM reads the - * row-major `quant_act_i8g` plane two rows below, which is the pairing libref's comment states; a - * gfx11 card has no consumer for the step-ordered plane and serves the op so an architecture that - * emits it resolves to a kernel here rather than to the reference. */ +/* The per-row int8, in libref's step order. The order belongs to the op: the codes are the WMMA + * A-fragment's and the oracle compares the plane, so the kernel's store address applies the + * permutation. libr3d's own int8 GEMM reads the row-major `quant_act_i8g` plane (two rows below); + * this row exists so an architecture that emits the op resolves to a kernel here rather than to the + * reference. */ { "quant_act_i8_bf16", "quant_act_i8", "quant", "symmetric int8 with one scale per row: scale = max(amax, 1e-8) / 127, ties to even, saturating", "n a multiple of 16, a whole WMMA step; a wave a row of the row sums; the codes stored in the " @@ -1199,8 +1152,8 @@ static const RadKernelInfo kKernels[] = { /* ------------------------------------------------------------------ r3d_gemm_bf16_nt_m16.hip * * The decode GEMM: M is 1 to 16, so a wave owns a run of N columns and streams the weight's rows - * past an activation kept in registers. There is no fragment layout to fill, which is why this - * kernel reads the checkpoint's rows in order. + * past an activation kept in registers. There is no fragment layout, so the kernel reads the + * checkpoint's rows in order. */ { "gemm_nt_bf16_m16", "gemm_nt", "gemm", "a[M,K] @ b[N,K]^T for the decode and verify heights, f32 accumulate, one narrowing at the store", @@ -1218,9 +1171,9 @@ static const RadKernelInfo kKernels[] = { /* ------------------------------------------------------------------ r3d_gemm_fp8a16_nt_m1.hip * - * The same shape against a block-scaled weight. The codes are E4M3, widened to f16 exactly and + * The same shape against a block-scaled weight. The E4M3 codes are widened to f16 exactly and * accumulated by dot2; the block scale is applied once per 128-element slab, after the slab's - * products, which is where the reference applies it. + * products, where the reference applies it. */ { "gemm_nt_q_fp8a16_m16", "gemm_nt_q", "gemm", "a[M,K] @ b[N,K]^T against E4M3 codes with a scale per 128x128 block", @@ -1286,8 +1239,8 @@ static const RadKernelInfo kKernels[] = { { "silu_mul_bf16", "silu_mul", "elem", "silu(gate) * up over one fused gate_up plane, the gate the first half", - "any n; a workgroup a row; the activation is NOT narrowed before the product, as ref's is not " - "-- act_mul narrows it, over two operands, because the pair it replaces stored it", + "any n; a workgroup a row; the activation is not narrowed before the product, as ref's is not " + "(act_mul, over two operands, narrows it, as a stored activation is)", "bf16 in and out, fp32 arithmetic", RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cSiluMul), NOTUNE, @@ -1309,8 +1262,8 @@ static const RadKernelInfo kKernels[] = { /* ------------------------------------------------------------------ r3d_sample_pre_f32.hip * * The sampler's pre-filters: one workgroup a row over the logits plane. The history stages are - * sparse -- a row's history is a few hundred tokens against a vocabulary of 130560, so the - * reference's own shape, walk the window and not the row, is the fast shape too. + * sparse (a row's history is a few hundred tokens against a vocabulary of about 130K), so walking + * the window rather than the row, the reference's shape, is also the fast one. */ { "sample_penalties_f32", "sample_penalties", "sample", "presence, frequency and repetition penalties from the row's history, in place", @@ -1379,11 +1332,10 @@ static const RadKernelInfo kKernels[] = { /* ------------------------------------------------------------------ r3d_attn_paged_h128.hip * * Paged attention, head_dim 128, banded on q_len. The two kernels share the block walk and differ - * in what a workgroup is: decode is one head group over 16 query rows with split-KV, prefill stages - * a 16-token query tile. The walk's block bounds are the WORKGROUP's -- a tile is staged once into - * LDS and every wave of the workgroup consumes it, and waves that narrowed the walk to their own - * query positions would stage different blocks over the same LDS, the last writer per 16-byte chunk - * winning. + * in what a workgroup is: decode is one head group over 16 query rows with split-KV, prefill a + * 16-token query tile. The walk's block bounds are per workgroup: a tile is staged once into LDS + * and every wave consumes it, so a wave must not narrow the walk to its own query positions, or the + * waves would stage different blocks into the same LDS. */ { "attn_paged_bf16_decode", "attn_paged", "attn", "paged attention over a bf16 cache: one head group a workgroup, 16-token tiles, split-KV", @@ -1432,14 +1384,14 @@ static const RadKernelInfo kKernels[] = { /* ------------------------------------------------------------------ r3d_sample_f32.hip * - * The sampler's spine: the row's top-R, and the stages that turn the top-R's candidate plane into - * one token. The candidate set is the contract between them -- `cand_val` carries LOGITS, so each - * narrowing stage takes its own softmax and the stages compose in any order; a dropped candidate is - * `cand_idx` -1 and `cand_val` -inf; the set is descending by value then ascending by id; and every + * The sampler's spine: the row's top-R and the stages that turn its candidate plane into one token. + * The candidate set is the contract between them: `cand_val` carries logits, so each narrowing + * stage takes its own softmax and the stages compose in any order; a dropped candidate is + * `cand_idx` -1 and `cand_val` -inf; the set is descending by value, then ascending by id; and every * stage leaves a greedy row byte-identical, because a greedy row's token is `sample_argmax`'s. - * `topk_next` is a sort by (-value, +column) wearing a loop -- the rule `v == *pv && i <= *pi` is - * "the next one in a run of equal values" -- so one pass keeping the best R returns the reference's - * R pairs, in its order, with its tie-breaks to the lower column. + * `topk_next` is a sort by (-value, +column) written as a loop (`v == *pv && i <= *pi` steps through + * a run of equal values), so one pass keeping the best R returns the reference's R pairs, in its + * order and with its tie-breaks to the lower column. */ { "row_topk_bf16", "row_topk", "moe", "the row's top R, with the reference's tie-breaks, in one scan of the row", @@ -1561,30 +1513,25 @@ static const RadKernelInfo kKernels[] = { /* ------------------------------------------------------------------ r3d_dflash_f32.hip * - * The speculative decoder's accept step. It is a gather, not arithmetic: two 63.8 MiB codebooks, a - * walk gathering `M * steps * rank` elements, so the score's rank sum is one lane's serial chain -- - * there is nothing to hide the gather behind, and a tree would be a different sum for no gain. + * The speculative decoder's accept step. It is a gather, not arithmetic: two 63.8 MiB codebooks and + * `M * steps * rank` gathered elements, so each score's rank sum is one lane's serial chain. There + * is no work to hide the gather behind, and a tree reduction would change the sum for no gain. */ /* ------------------------------------------------------------------ r3d_gemm_nt_q_w2a8.hip * - * `output.weight`: U2 codes, int8 activations, one f32 scale per activation ROW (ZP_I8_ROW), and a - * joined `b_scale` the container writes as two planes -- scale f16 and zero u8 -- behind one operand - * that only a layout hook can present. libref's shape hook declines the dtype for exactly that - * reason, so kbench has no case for the band: the row's opd_shape is null, which is the tool's - * named skip, and the joined plane is built with rad_planes_relayout, the same builder the driver - * uses. + * `output.weight`: U2 codes, int8 activations, one f32 scale per activation row (ZP_I8_ROW), and a + * joined `b_scale` stored as two planes (scale f16, zero u8) behind one operand, which only a layout + * hook can present. libref's shape hook declines the dtype for that reason, so kbench has no case + * for the band: the row's opd_shape is null (the tool's named skip), and the joined plane is built + * with rad_planes_relayout, the same builder the driver uses. * - * Exactness, measured and not assumed: `v_fdot2_f32_f16` carries ~22 bits of mantissa on integer - * operands, not 24, so an integer dot through it is inexact above 2^20 (71027 of 262144 sampled dots - * at bias 1024, worst |err| 0.125; 70115 and 0.015625 at bias 128). The bias is 128 because the - * error's ratio to the magnitude is ~2^-22 and shrinking the bias shrinks the tail. The result is - * that 0.1-0.2% of outputs land one bf16 ulp off the reference: rel_l2 5.0e-3 at the band, - * max_abs 9.8e-4, no non-finite anywhere. This row is NOT bit-exact by construction, and the dot - * probe in the unit is the check that states it. + * Exactness: `v_fdot2_f32_f16` carries about 22 bits of mantissa on integer operands, not 24, so an + * integer dot through it is inexact above 2^20. The error is about 2^-22 of the magnitude, so a + * smaller bias shrinks the tail; the bias is 128 (sampled worst |err| 0.015625, against 0.125 at + * bias 1024). 0.1-0.2% of outputs land one bf16 ulp off the reference (rel_l2 5.0e-3, max_abs + * 9.8e-4, no non-finite values). This row is not bit-exact; the unit's dot probe states the bound. * - * M <= 16 is decode. 46 of these per token, 135 GFLOP a token of CPU work that the host row puts on - * the card at 3.0-4.2 ms (66.8 MB of codes at the card's 22 GB/s is the floor; the warm-L2 run is - * 2.43 ms at 30 GB/s). + * M <= 16 is decode. */ { "gemm_nt_q_w2a8_m16", "gemm_nt_q", "gemm", "the vocab projection at decode: 2-bit codes, int8 activations, the zero removed with a_sum", @@ -1612,17 +1559,15 @@ static const RadKernelInfo kKernels[] = { "row needs it to lift the integer bias off its f16-as-int dot. The row's scale and zero are one " "per ROW on a {1, group} plane, so the staging reads 128 scalars a chunk where the fp8a8 arm reads " "one, at the row the grid puts it; issued one chunk ahead of the fold that consumes them, because " - "a scalar load with nothing to overlap it is the whole band (210.8 ms against 2.396 ms with the " - "answer hoisted, the same output bits). r3d_tiling.h's swizzle is shared, proven byte-identical", + "a scalar load with nothing to overlap it dominates the band otherwise (the output bits are " + "the same either way). r3d_tiling.h's swizzle is shared, proven byte-identical", "M <= 16 is gemm_nt_q_w2a8_m16's by its declared C_LE(\"M\", 16); fp8a8 and fp8a16 take their own " "rows, and the fp8a8 arm refuses a band carrying a_sum at its own line -- a row that silently " "ignores a band operand passes a checkpoint whose a_sum is garbage. A zero plane stored sub-byte " - "(U2/U4) is refused and named, not approximated: rad_load_bits is the ten-line fix and it is " - "written for the codes, not the zero. Measured, VRAM: M=64 N=130560 K=2048 w2a8 24.151 ms, 1417 " - "GFLOP/s, 3.7 GB/s useful against a 0.449 ms read floor of the 73.1 MB operand -- at kKC=32 a " - "staged chunk draws 8 bytes from a row of pitch 512, so the band moves 8x the bytes it uses and " - "the lever is a wider k-chunk, not more loads in flight (the codes lead measured 0.6%, " - "bit-identical)", + "(U2/U4) is refused and named, not approximated (rad_load_bits reads codes, not zeros). At " + "kKC=32 a staged chunk draws 8 bytes from a row of pitch 512, so the band moves 8x the bytes it " + "uses and is far from its read floor; a wider k-chunk, not more loads in flight, is what would " + "close it", RAD_DOMAIN_DEVICE, R3D_PRIO_VOCAB_M1, ROW(cGemmQW2A8Tiled), NOTUNE, nullptr, nullptr, r3d_rad_gemm_nt_q_w2a8_tiled, nullptr, @@ -1631,12 +1576,10 @@ static const RadKernelInfo kKernels[] = { /* ------------------------------------------------------------------ r3d_gemm_fp8a8_gated.hip * * The gate couples column i to column n+i, so a lane owns both dots and the coupling costs no extra - * weight traffic; the block is one group by 256/group rows so the group's amax closes in-block, - * which is also why there is nothing to tune (the block shape is the quantiser's rule, not a knob) - * and why the row keeps its M ceiling in the prose. At the band's own numbers this is ~341 GFLOP/s - * at M=64 -- 0.7% of the card's fp8 peak, 46 of these per forward pass -- and it is still the row - * the model wants, because the alternative it replaces is the reference's host GEMM: the same 3.2 - * GFLOP per layer on the CPU, which is 135 GFLOP a token for this checkpoint. + * weight traffic. The block is one group by 256/group rows so the group's amax closes in-block. That + * block shape is the quantiser's rule, so there is nothing to tune, and the row states its M ceiling + * in the prose. Throughput is low (about 0.7% of the card's fp8 peak at M=64), but the alternative + * is the reference's host GEMM. */ { "gemm_nt_q_gated_fp8a8", "gemm_nt_q_gated", "gemm", "the gated MLP band's GEMM, its gate and its output quantiser in one launch", @@ -1678,14 +1621,11 @@ static const RadKernelInfo kKernels[] = { /* ------------------------------------------------------------------ r3d_vocab_bf16.hip * - * The head is the largest read in a decode step -- 510 MiB at this checkpoint's 130560 x 2048 -- and - * the sampler reads f32, which is why the store is typed rather than narrowed and why a prefill band - * writes 1.07 GB. Measured on the card: 3.29 ms a token at M=1 (163 GB/s of the head), 0.507 ms a - * token at M=16 (the head read once for sixteen rows), 269 ms for a 2048-token prefill at 4067 - * GFLOP/s. Against the reference's law the f32 plane is 1.77e-6 in rel_l2, which is ~30 f32 ulps at - * K=2048 and is the pair-dot folding two products into one rounding -- measured identical against - * the same law with the operands widened to f16 first, so the widening contributes nothing and the - * head's own bf16 quantisation (4.9e-4 an element) is 300x coarser than the row. + * The head is the largest read in a decode step (510 MiB at 130560 x 2048), and the sampler reads + * f32, so the store is f32 rather than narrowed and a prefill band writes about 1 GB. Against the + * reference the f32 plane is at rel_l2 1.77e-6 (about 30 f32 ulps at K=2048), from dot2 folding two + * products into one rounding; widening the operands to f16 first changes nothing. The head's own + * bf16 quantisation (4.9e-4 an element) is 300x coarser. */ { "logits_gemm_bf16", "logits_gemm", "vocab", "logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T, the head read once a token", @@ -1710,14 +1650,9 @@ static const RadKernelInfo kKernels[] = { /* ------------------------------------------------------------------ r3d_gemm_fp8a8_tiled.hip * - * The prefill projection: this checkpoint declares 176 of these a forward pass (44 of qkv, 44 of - * the gated MLP's 12288 columns, 44 of o, 44 of the 2048-wide one, three of the drafter at - * K=10240), and the reference does their 135 GFLOP a token in a host loop. - * Measured at the graph's own bands, weights in VRAM: 28.171 ms at N=12288 K=2048 (3659 GFLOP/s), - * 14.699 at N=2048 K=6144, 5.911 at N=2560, 4.381 at N=2048 K=2048, 29.798 at N=2048 K=10240 -- - * 27 to 36% of the card's dense f16 peak against a byte floor of 0.051 to 0.257 ms. These are the - * first bands in this library where the dot, not the wire, is the limit, and it is the reason the - * E4M3 decoder is a table: at the tile's densities the decode ALU is on the critical path. + * The prefill projection. At these densities the dot product, not memory bandwidth, is the limit + * (about 27-36% of the card's dense f16 peak at the graph's bands), which is why the E4M3 decoder is + * a table: the decode ALU is on the critical path. */ { "gemm_nt_q_fp8a8_tiled", "gemm_nt_q", "gemm", "y[M,N] = a[M,K] @ dequant(b)^T at prefill heights, the group sub-sum from the raw codes and one " @@ -1757,10 +1692,8 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r3d_rad_gemm_nt_q_mxfp4a8_tiled, nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_mxfp4a8 }, -/* The same tiling on gemm_nt's operands, the prefill projection the reference runs on the host: at - * M=2048 this checkpoint's q/k/v/o and the MLP's up/down are 135 GFLOP a token of f32-accumulating - * bf16, and the reference does them on the CPU. The exactness is the m16 row's, because it is the - * same dot. */ +/* The same tiling on gemm_nt's bf16 operands, the prefill projection the reference runs on the + * host. The exactness is the m16 row's, because it is the same dot. */ { "gemm_nt_bf16_tiled", "gemm_nt", "gemm", "a[M,K] @ b[N,K]^T at prefill heights, f32 accumulate, one narrowing at the store", "128x128 tiles through LDS, 8x8 f32 accumulators a lane, k ascending in 32-code chunks, the " @@ -1769,7 +1702,7 @@ static const RadKernelInfo kKernels[] = { "the other's band", "bf16 a, b and y, fp32 accumulation; the pair is folded into the accumulator by one rounding, so " "about 0.3% of a long-K output lands one bf16 store ulp from the reference's, and no output is " - "further. 99.93% bit-exact measured at the 512-column twin, 100% within two ulps", + "further", RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_TILED, ROW(cGemmNTTiled), NOTUNE, nullptr, nullptr, r3d_rad_gemm_nt_bf16_tiled, nullptr, @@ -1779,17 +1712,16 @@ static const RadKernelInfo kKernels[] = { /* ================================================================== the exports * - * The two every plugin must export, the four that make a kernel library, and `rad_kernel_concurrent`. + * The two exports every plugin needs, the four that make a kernel library, and + * `rad_kernel_concurrent`. * - * libr3d exports no `rad_kernel_chain`: chaining replaces the queue's ordering bit between two - * dependent launches with a spin in the kernel, and it pays where a wave is idle during that spin. - * Nothing here is built as a chained form, so the answer would be 0 for every row; the symbol is - * left out, which is the same answer with one less thing to keep in step (ABI, - * `rad_kernel_chain`: "without the symbol, or with 0, the engine never asks"). + * No `rad_kernel_chain`: chaining replaces the queue's ordering between two dependent launches with + * a spin in the kernel, and no row here has a chained form, so every answer would be 0. Omitting the + * symbol means the same (ABI, `rad_kernel_chain`: "without the symbol, or with 0, the engine never + * asks"). * - * It exports no `rad_kernel_collective` either: there is no second rank in this plugin's world. The - * cards that run these rows are single-GPU cards, and an all-reduce over the PCIe x1 slot most of - * them sit in is slower than sending the bytes through the host. + * No `rad_kernel_collective`: these rows run on single-GPU cards, and an all-reduce over the PCIe x1 + * slot most of them sit in is slower than going through the host. */ extern "C" int rad_kernel_count(void) { return (int)(sizeof(kKernels) / sizeof(kKernels[0])); @@ -1799,18 +1731,16 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { return &kKernels[i]; } -/* Which rows touch nothing but their operands and the scratch they were handed. +/* Which rows touch nothing but their operands and their scratch. * - * The elementwise, norm, quant, cast, rope, cache and gather rows do: one launch, one pass, no - * state between launches, so two of them may run at once and the engine can start a row before an - * independent earlier one finishes. + * The elementwise, norm, quant, cast, rope, cache and gather rows: one launch, one pass, no state + * between launches, so two may run at once and the engine can start one before an independent + * earlier one finishes. * - * The GEMM rows do not, and the reason is the scratch, not the kernel. The scratch arena belongs to - * the op instance, so two layers' decode GEMMs launched at the same time share it: a split-K row's - * partials and arrival counters from the two launches would land on each other. With sk = 1 a GEMM - * launch has no partials and is safe, but the promise is per row and the axis is chosen per - * geometry, so the row states the worst case. When split-K is off on a given card (a tuned point of - * sk = 1 for every shape), the loss is one overlap the engine would have taken. + * Not the GEMM rows, because of the scratch: the arena belongs to the op instance, so two layers' + * decode GEMMs launched together share it and their split-K partials and arrival counters would + * collide. With sk = 1 a GEMM has no partials, but the promise is per row and sk is chosen per + * geometry, so the row states the worst case. */ extern "C" int rad_kernel_concurrent(int i) { const RadKernelInfo* k = rad_kernel_at(i); @@ -1824,14 +1754,12 @@ static const RadPluginInfo kInfo = { "0.1.0", "the RDNA3 (gfx11) kernel library: the elementwise, norm, rope, cache and embedding rows, fp8 " "and int8 activation quantisation with its dequant and gated forms, and the skinny bf16 and " - "fp8a16 GEMMs, every one of them through v_dot2acc_f32_f16 because RDNA3 has no matrix " - "instruction a compiler will emit", + "fp8a16 GEMMs, the matrix work through v_dot2acc_f32_f16 rather than RDNA3's WMMA " + "fragment layout", /* The architectures this build's code objects run on, spelled as `RadDeviceProps::arch`. The - * loader compares a device's arch against these words and warns once when the code object it - * picked names a card this list does not (`target_covers`), so the string has to be the build's - * real targets rather than an author's guess at them. - * RAD_GPU_TARGETS reaches this source as a compile definition from CMakeLists.txt; the fallback - * is the whole family, which is what a build that did not say is claiming. */ + * loader warns once when the code object it picked names a card this list does not + * (`target_covers`), so the string must be the build's real targets. R3D_BUILD_TARGET comes + * from CMakeLists.txt as a compile definition; the fallback is the whole family. */ R3D_BUILD_TARGET, }; diff --git a/libr3d/r3d_sample_f32.hip b/libr3d/r3d_sample_f32.hip index a9e2cda1..dd4ec1b1 100644 --- a/libr3d/r3d_sample_f32.hip +++ b/libr3d/r3d_sample_f32.hip @@ -1,95 +1,62 @@ /* r3d_sample_f32.hip -- the sampler: the two full-vocabulary reductions, the candidate set, the * seeded draw and the four narrowing stages. * - * The arithmetic is libref's, transcribed -- the reference's sampler is the law and the ORDER of - * its passes is the point. `abi/rad_sample.h` is the wire format: every scalar (`temp`, `top_k`, - * `top_p`, `min_p`, `typical_p`, `xtc_*`, `seed`, `pos`, the flags, the history window) is DATA, one - * 96-byte row per sampled position, because a parameter is geometry and frozen at declare, and two - * rows of one batch with different top_p must resolve to one kernel. `param_rows` below is that - * check, and it is the dtype check libref states: the plane is 32-bit words, and a 16-bit view - * passes a byte-count test and then misreads every row. + * The arithmetic is libref's, transcribed, including the order of its passes. `abi/rad_sample.h` + * is the wire format: every scalar (`temp`, `top_k`, `top_p`, `min_p`, `typical_p`, `xtc_*`, `seed`, + * `pos`, the flags, the history window) is data, one 96-byte row per sampled position, because a + * parameter is geometry frozen at declare and two rows of one batch with different top_p must + * resolve to one kernel. The params plane must be 32-bit words (see params_ok). * - * ============================== what has to agree, and with what ============================== + * ============================== reproducibility ============================== * - * The draws must REPRODUCE, so the summation order is transcription and not performance: + * Draws must reproduce, so summation order is transcribed, not chosen for speed: * - * - A MAX is order-free and every max here is a strict `>`, which is also how NaN is kept out: - * libref's `if (v > mx) mx = v` over -infinity never adopts a NaN, and the butterfly merges with - * the same strict comparison, so a NaN in a row of logits cannot become the max anywhere. - * - A SUM of f32 is not order-free. libref's `sum` (the pick, the narrowing stages) runs - * over the candidates in INDEX order, and the CDF scan below it accumulates in index order too. - * So the exps are computed in parallel -- each is a separate value, order-free -- and the - * accumulation is serial on one lane, in index order, exactly as written. That is the whole - * design of the candidate kernels: parallel values, serial sums. - * - The draw is specified in the ABI, not left to a library: splitmix64 over - * `seed * 0x9E3779B97F4A7C15 + pos`, top 24 bits over 2^24. Integer arithmetic, so it is the - * same number here as on the host. Independent draws at one position are independent streams: - * the pick XORs the seed with RAD_SAMPLE_KEY_PICK (0), XTC's firing coin with RAD_SAMPLE_KEY_XTC. - * - `ref_exp`/`ref_log` are `(float)std::exp((double)x)` and `(float)std::log((double)x)`, and - * they are transcribed as double calls rounded once to f32. There is no fp8-style hardware - * shortcut to take: an f32 exp2 (`v_exp_f32`) is a couple of ulps away, and a `u < cum` - * comparison sitting on an ulp boundary changes the drawn token, which is a fixture failure even - * when the distribution is right. Consumer RDNA3 fp64 is 1:64, so this is the slow path and the - * candidate set is where it shows: it costs time, not agreement. The device's - * `(float)exp((double)x)` and `(float)log((double)x)` are bit-identical to glibc's over - * a million points in [-100, 100] (0 of 2^20 differ), while `expf` differs from the host's - * `expf` in 5.7% of them by 1 ulp -- the double call is not only the law, it is the only one - * of the two that reproduces the recording. + * - Every max is a strict `>`, order-free, and keeps NaN out: libref's `if (v > mx) mx = v` from + * -infinity never adopts a NaN, and the butterfly merges the same way. + * - An f32 sum is not order-free. libref's sums (the pick, the narrowing stages) and the CDF scan + * run over the candidates in index order, so exps are computed in parallel and accumulated + * serially on one lane in index order: parallel values, serial sums. + * - The draw is specified by the ABI: splitmix64 over `seed * 0x9E3779B97F4A7C15 + pos`, top 24 + * bits over 2^24, integer arithmetic, so device and host agree. Independent draws at one + * position XOR the seed with a key: RAD_SAMPLE_KEY_PICK (0) for the pick, RAD_SAMPLE_KEY_XTC for + * XTC's coin. + * - `ref_exp`/`ref_log` are `(float)std::exp((double)x)` and `(float)std::log((double)x)`, as in + * the reference. On gfx1102 the device's double exp/log match glibc's bit for bit over 2^20 + * points in [-100, 100], while `expf` differs from the host's by 1 ulp on 5.7% of them, and a + * `u < cum` comparison on an ulp boundary changes the drawn token. Consumer RDNA3 runs fp64 at + * 1:64, which the candidate set (1024 exponentials a row) can afford. The attention unit, at + * millions of exponentials a layer, uses a 0.5-ulp polynomial instead. * - * This is where the law is affordable, and it is why this file and the attention unit differ. Here - * the widest softmax is the candidate set: 1024 exponentials a row, 2 per lane, and the whole op is - * half a millisecond a step at the band. Attention at the prefill band is 17 M exponentials a layer - * on the same 1:64 fp64, and there the law cannot be paid, so that unit ships a 0.5-ulp polynomial - * and says so. A sampler that draws a different token than the recording is wrong at any speed, so - * this unit keeps the double call and the switch stays off. + * ============================== one-pass top-k ============================== * - * ============================== the top-k, and why it is one pass ============================== + * libref selects with `topk_next`: R scans of the row, each taking the largest value strictly below + * the last pick, ties to the lower column. That is a sort by (-value, +column), so one pass keeping + * the best R in that order yields the same R pairs in the same order. At N=130560, R=16, M=1792 + * this reads the row once instead of sixteen times. The pass is bound by accepted inserts into + * each lane's list, not by memory; filtering against a block-wide threshold instead of each lane's + * own tail would cut the inserts about tenfold. * - * libref selects with `topk_next`: R scans of the row, each taking the largest - * value strictly below the last pick, ties to the LOWER column. Read as a whole that is a sort by - * (-value, +column), and the rule `v == *pv && i <= *pi` is exactly "the next one within a run of - * equal values" -- so one pass that keeps the best R by that order produces the same R pairs, in the - * same order, with the same tie-breaks. At the band's row (N=130560, R=16, bf16, M=1792) the - * reference scans the row sixteen times: 7.0 GB of traffic. This file scans it once: 468 MB. + * The per-lane list is at most 64 deep, and the merge keeps the best 64 of two lists. Almost every + * element costs one comparison against the lane's last entry (about 12% clear it at 510 elements a + * lane). 64 covers R=16, a 64-wide candidate set and practical top_k values; a larger k takes + * ceil(k/64) passes, carrying the chain's state, so the answer is the same at any k. * - * At the band (M=1792, N=130560, R=16) the one pass is 22.0 ms bf16, 22.4 ms f32, i.e. 21 GB/s and - * 42 GB/s: the same time for half the bytes, so the pass is not bound by the plane, it is bound by - * the accepted inserts (~55 sifts a lane at 510 elements a lane, POOL steps each). The traffic is 15x - * lower than the reference's and the headroom is in the insert, not in the load; a lane that filtered - * against a block-wide threshold instead of its own tail would take ~5 sifts a lane and land near the - * 2 ms the bandwidth floor allows. The number is stated so it is not read as the memory system's - * answer. - * - * One pass needs a per-lane list, and a list costs comparisons, so it is 64 deep and the merge keeps - * the best 64 of two lists: a lane's test against its 64th best is ONE comparison for almost every - * element (only ~12% of a row's elements clear it at 510 elements a lane), and the deep comparisons - * happen only for the elements that enter. Sixty-four covers R=16, the selftest's 64-wide candidate - * set, and every top_k a request asks for in practice. Deeper is not free and is not silent: - * `r3d_sample_topk` and `r3d_row_topk` take ceil(k/64) passes when the row asks for more, and each - * pass is one more read of the row. That is the reference's own chain, so the answer is the same one - * at any k; only the time is the reference's. - * - * The chain's QUIRK is transcribed too, because kbench compares the plane. `topk_next` seeds its - * scan with `best_i < 0 ||`, so the first element it examines becomes the best even when it is a - * NaN, and after that `v > best_v` is false for everything: a row whose FIRST logit is NaN yields R - * identical (NaN, 0) slots, not a hole. To reproduce that the 64-deep pool is re-scanned by ONE lane - * in ascending column order with the literal chain -- the pool provably contains every element the - * chain can ever pick (a pick is in the global top-64, so it is in its own lane's top-64), and the - * chain's comparisons are only exact when the scan order is the row's. + * The chain's quirk is transcribed too, because kbench compares the plane: `topk_next` seeds its + * scan with `best_i < 0 ||`, so the first element becomes the best even when it is a NaN, and + * nothing displaces it. A row whose first logit is NaN yields R identical (NaN, 0) slots. The + * kernels test the first element for that case explicitly. * * ============================== shape ============================== * - * One block a row everywhere: at the band a row of 130560 f32 is 510 KiB and M is 2048, so the whole - * plane is 1 GiB and these are the memory-bound kernels of the library -- argmax and top-k each read - * 1 GiB, temp reads and writes 2 GiB. A row of the candidate set is 1024 f32 and the work is the - * transcendentals, so the same shape costs nothing and buys the serial order for free. The candidate - * stages keep their probabilities in LDS (2 * 1024 floats), which is what makes typical's O(n^2) + * One block a row everywhere. At the band a row is 130560 f32 (510 KiB) and M is 2048, so argmax + * and top-k each read 1 GiB and temp reads and writes 2 GiB: these are memory-bound. A candidate + * row is at most 1024 f32 and the work is transcendentals, so the same shape costs nothing and + * gives the serial order for free; the stages keep the row in LDS, which makes typical's O(n^2) * distance scan affordable. * - * Single rank. `vocab_off` is read where libref reads it (`row_topk`'s reported ids, `sample_topk`'s - * `pairs` plane) and the pair planes are written as the shape hooks describe them, because kbench - * fills and compares them. There is no all-gather here and no merge kernel: `sample_merge_topk` is - * declined by libref's own shape hook and rank 0 has nothing to merge. + * Single rank. `vocab_off` is applied where libref applies it (`row_topk`'s reported ids, + * `sample_topk`'s `pairs` plane), and the pair planes are written as the shape hooks describe them. + * There is no merge kernel: libref's own shape hook declines `sample_merge_topk`. */ #include "r3d.h" @@ -106,31 +73,18 @@ constexpr uint32_t kThreads = 256; /* 8 waves */ constexpr uint32_t kWave = 32; constexpr uint32_t kWaves = kThreads / kWave; -/* The candidate pool's depth, and the widest candidate set the narrowing stages carry in LDS. - * 1024 candidates is the engine's declared buffer width; two f32 arrays of it is 8 KiB of 64 KiB. */ +/* The candidate pool's depth, and the widest candidate set the narrowing stages carry in LDS (the + * engine's declared buffer width). */ constexpr int kPool = 64; constexpr int kCandMax = 1024; -/* The double call and the single rounding to f32 ARE the law: libref's oracle - * is glibc's double exp and log, and the f32 result of a double-accurate implementation agrees with - * it for every input but a double-rounding tie. */ -/* The two transcendentals, and the A/B switch. The law is libref's `(float)std::exp((double)x)`, - * and on this card the device's double `exp`/`log` are BIT-IDENTICAL to glibc's (0 of 2^20 points - * in [-100, 100] differ, both functions), so the law is reproducible here and the draw is the - * recording's. `expf` is not: it moves 5.7% of inputs by 1 ulp relative to the host's, which is - * under a bit-exact fixture. -DR3D_EXP_F32 swaps both for the f32 hardware path, so the cost of the - * law can be measured in kbench; nothing in the shipped build uses it, and the flips it causes are - * reported with it. */ -#ifdef R3D_EXP_F32 -__device__ __forceinline__ float ref_exp(float x) { return expf(x); } -__device__ __forceinline__ float ref_log(float x) { return logf(x); } -#else +/* The reference's transcendentals: a double call rounded once to f32 (see the file header), so the + * draws are the reference's. */ __device__ __forceinline__ float ref_exp(float x) { return (float)exp((double)x); } __device__ __forceinline__ float ref_log(float x) { return (float)log((double)x); } -#endif /* abi/rad_sample.h's draw, verbatim: splitmix64 over (seed * golden + pos), top 24 bits as a float - * in [0, 1) -- exactly f32's mantissa, so no double anywhere. */ + * in [0, 1). 24 bits fit f32's mantissa exactly. */ __device__ __forceinline__ uint64_t splitmix64(uint64_t z) { z += 0x9E3779B97F4A7C15ull; z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; @@ -142,17 +96,8 @@ __device__ __forceinline__ float uniform01(uint64_t seed, uint64_t pos) { return (float)(uint32_t)(z >> 40) * (1.0f / 16777216.0f); } -/* The params row, as the kernels see it. 96 bytes, a multiple of 8, so row m is 8-byte aligned in a - * plane of words and the u64 seed and pos load as one instruction. */ -struct Params { - const RadSampleParams* p; - __device__ __forceinline__ const RadSampleParams& operator[](uint32_t m) const { - return p[m]; - } -}; - -/* A block-wide maximum with a strict `>`, which is the comparison libref writes and the reason a NaN - * is never the max: a wave butterfly, then the wave partials. `lds` holds kWaves floats. */ +/* A block-wide maximum: a wave butterfly of fmaxf, then the wave partials. fmaxf drops a NaN, so a + * NaN is never the result. `lds` holds kWaves floats. */ __device__ __forceinline__ float block_max(float v, float* lds) { const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; v = wave_max(v); /* a butterfly of fmaxf: drops a NaN */ @@ -166,30 +111,20 @@ __device__ __forceinline__ float block_max(float v, float* lds) { /* ------------------------------------------------------------------ sample_argmax * - * The law: the largest logit, ties to the LOWER column, because greedy and top-1 have to - * agree. The scan's rule is `bi < 0 || v > best`: strict, so the first of a run wins, and a NaN is - * never adopted -- except as the row's very first element, which the seed of the scan adopts. The - * parallel form is the same total order: take the right candidate only when it is strictly better - * (larger, or equal with a lower column), which is associative, so the butterfly and the serial scan - * agree, and a NaN in `best` is never displaced by anything. + * The largest logit, ties to the lower column, so greedy and top-1 agree. The reference's scan is + * `bi < 0 || v > best`: strict, so the first of a run wins, and a NaN is adopted only as the row's + * first element. The parallel form uses the same total order, which is associative, so the + * butterfly and the serial scan agree. */ struct Best { float v; uint32_t i; }; -/* The scan's law, made associative. `best_take(a, b)` keeps `a` unless `b` is strictly better -- - * larger, or equal with a lower column -- and `b.i == kNone` is "nothing examined yet". The - * reference's serial scan seeds with `bi < 0 ||` and then moves only on a strict `>`, which is the - * same total order, so a butterfly of this and a scan of that agree on every input. */ +/* `best_take(a, b)` keeps `a` unless `b` is strictly better (larger, or equal with a lower column); + * `b.i == 0xffffffff` means nothing examined yet. */ __device__ __forceinline__ Best best_take(Best a, Best b) { const bool better = (b.v > a.v) || (b.v == a.v && b.i < a.i); return (b.i != 0xffffffffu && better) ? b : a; } -/* A max with a strict `>` over the block, NaN dropped: `fmaxf` is the drop, and libref's - * `if (v > mx) mx = v` from -infinity never adopts a NaN either. */ -__device__ __forceinline__ float block_max_strict(float v, float* lds) { - return block_max(v != v ? -INFINITY : v, lds); -} - __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_argmax_kernel( const float* __restrict__ lg, int32_t* __restrict__ tok, uint32_t n, uint32_t lg_ld) { __shared__ float red[kWaves]; @@ -223,9 +158,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_argmax_kernel( Best t{ red[0], redi[0] }; #pragma unroll for (uint32_t w = 1; w < kWaves; ++w) t = best_take(t, Best{ red[w], redi[w] }); - /* topk_next's seed, and nothing else: the first element the reference examines becomes its - * best even when it is a NaN, and no finite value can displace a NaN afterwards, so a row - * that opens with a NaN reports column 0. Every other NaN the scan walks past. */ + /* topk_next's seed: a row whose first element is NaN reports column 0 (see the file + * header); every other NaN is skipped. */ const float x0 = ldg_f32(lr); tok[row] = (int32_t)(x0 != x0 ? 0u : t.i); } @@ -233,10 +167,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_argmax_kernel( /* ------------------------------------------------------------------ sample_temp * - * The law: `inv = 1/t` computed once per row, then every logit multiplied -- by the - * reciprocal, not divided, and only when the row is sampled at all: `!(t > 0) || t == 1` leaves the - * row exactly as it was, bit for bit, which is what makes temp 1.0 and temp 0.0 (greedy) no-ops the - * kernel has to keep. The write is in place: logits are an INOUT operand. + * `inv = 1/t` once per row, then every logit multiplied by it (not divided), in place. A row with + * `!(t > 0) || t == 1` is left bit-exact, so temp 1.0 and temp 0.0 (greedy) are no-ops. */ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_temp_kernel( float* __restrict__ lg, const RadSampleParams* __restrict__ pr, uint32_t n, uint32_t lg_ld) { @@ -255,8 +187,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_temp_kernel( /* lg [M][n_vocab] f32, INOUT for temp, read-only for argmax; `lg_ld` elements a row (0 = n) * tok [M] i32 - * params [M] 24 words a row; argmax does not read it, and libref's shape hook describes - * it anyway, so the operand is there and unchecked, as libref leaves it. + * params [M] 24 words a row; argmax does not read it (libref describes it anyway) * * 0, -1 null, -2 bad extent, -3 pitch that does not describe the operand, -4 the HIP launch failed. * No allocation, no synchronisation. */ @@ -290,20 +221,16 @@ extern "C" int r3d_sample_temp(long lg, long params, int M, int n_vocab, long lo /* ================================================================== the top-k pool * - * One lane's share of a row, kept as the 64 best by (value descending, column ascending) -- the - * order `topk_next` walks. Two rules make it one pass and make it exact: + * One lane's share of a row, kept as the POOL best by (value descending, column ascending), the + * order `topk_next` walks. * - * - the order is a STRICT total order, so a merge of two such lists is a merge of two sorted - * lists and keeps the first 64 of the union, which is what the reference's R scans converge on; - * - the list lives in registers, so insertion is a 64-step sift with STATIC indices (compare, and - * swap when the newcomer is better) and never a dynamic index, which would spill the array to - * private memory. The sift costs 64 compares per INSERTED element, and elements are inserted - * only after a single compare against the lane's 64th best -- about one element in eight at the - * band's 510 columns a lane -- so the amortised cost is a few comparisons a column. + * - The order is strict and total, so merging two lists keeps the first POOL of the union. + * - The list lives in registers, so insertion is a POOL-step sift with static indices; a dynamic + * index would spill the array to private memory. Only elements that beat the lane's last entry + * (one compare) are sifted. * - * Slots the row never filled hold (-INFINITY, 0xffffffff): lower than any real value, and higher - * than any real column, so a real -infinity logit (a masked one) beats a pad and the extraction - * stops at the first pad. + * Unfilled slots hold (-INFINITY, 0xffffffff): below any real value and above any real column, so a + * real -infinity logit (a masked one) beats a pad and extraction stops at the first pad. */ namespace { @@ -314,27 +241,23 @@ __device__ __forceinline__ bool pool_better(float av, uint32_t ai, float bv, uin return av > bv || (av == bv && ai < bi); } -/* Insert (v, i) into a lane's register list. POOL is the list depth, which is the width of a pass: - * the sift is POOL steps and the merges are POOL-wide. The band asks for 16 (a router's top_k) and - * a candidate set for 64; carrying 64 through a router row costs four times the sift and returns - * the same 16 pairs. +/* Insert (v, i) into a lane's register list. POOL is the list depth and the width of a pass, so a + * router's top_k of 16 uses a 16-deep pool rather than paying for 64. * - * `pv`/`pi` carry the pick chain: an element at or above the last pick has been picked already, and - * within a run of equal values only columns after the last pick are still candidates -- - * `topk_next`'s two skips, in its order. */ + * `pv`/`pi` carry the pick chain across passes: an element above the last pick, or equal to it at + * or before its column, was already picked (`topk_next`'s two skips, in its order). */ template __device__ __forceinline__ void pool_insert(float v, uint32_t i, float pv, uint32_t pi, float* lv, uint32_t* li) { - if (v != v) return; /* the scan walks past a NaN (its first element is - handled by the caller, as the reference's is) */ + if (v != v) return; /* skip NaN; the caller handles a NaN first element */ if (v > pv) return; /* picked on an earlier pass */ if (v == pv && i <= pi) return; /* the last pick, or one before it */ - if (!pool_better(v, i, lv[POOL - 1], li[POOL - 1])) return; /* the fast path: one compare */ + if (!pool_better(v, i, lv[POOL - 1], li[POOL - 1])) return; /* fast path: one compare */ float cv = v; uint32_t ci = i; #pragma unroll - for (int j = 0; j < POOL; ++j) { /* the sift: every index a compile-time constant */ + for (int j = 0; j < POOL; ++j) { /* the sift, static indices */ if (pool_better(cv, ci, lv[j], li[j])) { const float tv = lv[j]; const uint32_t ti = li[j]; lv[j] = cv; li[j] = ci; cv = tv; ci = ti; @@ -342,26 +265,22 @@ __device__ __forceinline__ void pool_insert(float v, uint32_t i, float pv, uint3 } } -/* The best 64 of the union of two lists, in the pool's order. +/* The best POOL of the union of two lists, in the pool's order. * - * A[j] and B[j] are descending, so C[j] = the better of A[j] and B[kPool-1-j] is a bitonic sequence - * that already contains the top 64 of the union, and a bitonic sort of 64 in registers is six - * passes of 32 compare-exchanges with static strides -- no dynamic index, no spill, 448 compares. - * Both lanes of a shuffle pair compute the same result, which is what makes a butterfly of this - * operation a wave reduction. */ + * A and B are descending, so C[j] = the better of A[j] and B[POOL-1-j] is a bitonic sequence + * holding the union's top POOL; a bitonic sort in registers with static strides finishes it without + * spilling. Both lanes of a shuffle pair compute the same result, so a butterfly of merges is a + * wave reduction. */ template __device__ __forceinline__ void pool_merge(const float* av, const uint32_t* ai, const float* bv, const uint32_t* bi, float* ov, uint32_t* oi) { -#define R3D_POOL_GET(X, J) \ - const float x##v = r3d_xor_lane(X[0]); (void)x##v #pragma unroll for (int j = 0; j < POOL; ++j) { const int r = POOL - 1 - j; if (pool_better(av[j], ai[j], bv[r], bi[r])) { ov[j] = av[j]; oi[j] = ai[j]; } else { ov[j] = bv[r]; oi[j] = bi[r]; } } -#undef R3D_POOL_GET #pragma unroll for (int k = POOL; k > 1; k >>= 1) { #pragma unroll @@ -370,8 +289,8 @@ __device__ __forceinline__ void pool_merge(const float* av, const uint32_t* ai, for (int j = 0; j < POOL; ++j) { const int o = j ^ h; if (o <= j) continue; - /* Descending everywhere: the whole array is one descending run, so the direction of - * every compare-exchange is "the larger value to the lower index". */ + /* One descending run: every compare-exchange moves the better entry to the lower + * index. */ if (pool_better(ov[o], oi[o], ov[j], oi[j])) { const float tv = ov[j]; const uint32_t ti = oi[j]; ov[j] = ov[o]; oi[j] = oi[o]; ov[o] = tv; oi[o] = ti; @@ -381,8 +300,7 @@ __device__ __forceinline__ void pool_merge(const float* av, const uint32_t* ai, } } -/* One lane's pass over its columns of a row. STEP is 1 (scalar) or 4 (a vector load a step); LD - * reads one column. */ +/* One lane's pass over its columns of a row. STEP is 1 (scalar) or 4 (one vector load a step). */ template __device__ __forceinline__ void pool_scan(const void* __restrict__ x, uint32_t n, uint32_t x_ld, float pv, uint32_t pi, float* lv, uint32_t* li) { @@ -399,7 +317,7 @@ __device__ __forceinline__ void pool_scan(const void* __restrict__ x, uint32_t n pool_insert(bf16_to_f32((uint16_t)(hi & 0xffffu)), 4 * w + 2, pv, pi, lv, li); pool_insert(bf16_to_f32((uint16_t)(hi >> 16)), 4 * w + 3, pv, pi, lv, li); } - for (uint32_t c = nw * 4 + tid; c < n; c += kThreads) /* the row's odd tail, once */ + for (uint32_t c = nw * 4 + tid; c < n; c += kThreads) /* the row's tail */ pool_insert(bf16_to_f32((uint16_t)ldg_u16(p + c)), c, pv, pi, lv, li); } else { for (uint32_t c = tid; c < n; c += kThreads) @@ -426,10 +344,8 @@ __device__ __forceinline__ void pool_scan(const void* __restrict__ x, uint32_t n } /* One pass over the row: every lane's list, a wave butterfly of merges, the eight wave lists in - * LDS, and the block's 64 best in LDS at [kWaves*kPool, ...). Returns how many are real (pads - * stop it). */ -/* The block's 64 best are left in LDS at [kWaves*kPool, ...): the extraction that follows walks - * them with a runtime index, and a runtime index into a register array is a spill. */ + * LDS, and the block's POOL best left in LDS at [kWaves*POOL, ...) (in LDS because the extraction + * walks them with a runtime index). Returns how many are real. */ template __device__ __forceinline__ uint32_t pool_pass(const void* __restrict__ x, uint32_t n, uint32_t x_ld, int xdt, int vec, @@ -471,7 +387,7 @@ __device__ __forceinline__ uint32_t pool_pass(const void* __restrict__ x, uint32 __syncthreads(); uint32_t nout = 0; - if (threadIdx.x == 0) { /* the eight lists, merged with cursors */ + if (threadIdx.x == 0) { /* merge the eight wave lists with cursors */ uint32_t cur[kWaves]; #pragma unroll for (int w = 0; w < kWaves; ++w) cur[w] = 0; @@ -492,19 +408,14 @@ __device__ __forceinline__ uint32_t pool_pass(const void* __restrict__ x, uint32 return nout; } -/* The pool, in LDS: the eight wave lists, then the block's. */ } /* namespace */ /* ================================================================== row_topk * - * The law: exact per-row top-R, descending, ties to the lower column, with `vocab_off` - * added to every reported id and the optional [M, R, 2] pair plane an all-gather moves (an int32 id - * in the first f32 slot, the value in the second, id -1 for a slot the row could not fill). - * - * The reference calls `topk_next` R times, a full scan each time; the pool above produces the same - * R pairs from one scan, because the pool's order IS the chain's order. A row that wants more than - * 64 costs ceil(R/64) scans and carries the chain's state across them, so the answer is the same at - * any R and only the time is the reference's. + * Exact per-row top-R, descending, ties to the lower column, with `vocab_off` added to every + * reported id, and the optional [M, R, 2] pair plane an all-gather moves (an int32 id's bits in the + * first f32 slot, the value in the second, id -1 for an unfilled slot). One scan per POOL entries + * (see the file header). */ namespace { @@ -523,22 +434,24 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void row_topk_kernel( int32_t* __restrict__ ir = idx + (size_t)row * idx_ld; float* __restrict__ pr = pairs ? pairs + (size_t)row * pairs_ld : nullptr; - /* topk_next's seed of the scan: the first element it looks at becomes the best even as a NaN, - * and nothing displaces a NaN, so a row that opens with one reports (0, NaN) in every slot. - * Stated once, here, rather than buried in the pool's comparisons. */ + /* topk_next's seed: a row whose first element is NaN reports (0, NaN) in every slot. */ if (threadIdx.x == 0) st[0] = XDT == 0 ? bf16_to_f32((uint16_t)ldg_u16((const uint16_t*)x + (size_t)row * x_ld)) : ldg_f32((const float*)x + (size_t)row * x_ld); __syncthreads(); - if (st[0] != st[0] && threadIdx.x == 0) { - for (uint32_t r = 0; r < k; ++r) { - ir[r] = (int32_t)vocab_off; - vr[r] = st[0]; - if (pr) { - int32_t bits = (int32_t)vocab_off; - float v = st[0]; - __builtin_memcpy(&pr[2 * r], &bits, 4); - pr[2 * r + 1] = v; + /* The test reads shared memory after the barrier, so the whole block takes the same branch + * and none of it reaches the pool passes' barriers. */ + if (st[0] != st[0]) { + if (threadIdx.x == 0) { + for (uint32_t r = 0; r < k; ++r) { + ir[r] = (int32_t)vocab_off; + vr[r] = st[0]; + if (pr) { + int32_t bits = (int32_t)vocab_off; + float v = st[0]; + __builtin_memcpy(&pr[2 * r], &bits, 4); + pr[2 * r + 1] = v; + } } } return; @@ -552,8 +465,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void row_topk_kernel( __syncthreads(); const uint32_t nout = pool_pass(x, n, x_ld, XDT, vec, pv, pi, lds_v, lds_i); if (threadIdx.x == 0) { - /* Only the first `nout` entries of the block list were written this pass; what sits past - * them is last pass's list, so the count, not the pad sentinel, bounds the copy. */ + /* Only the first `nout` block entries were written this pass (the rest are stale), so + * the count, not the pad sentinel, bounds the copy. */ const uint32_t room = (k - done < POOL) ? k - done : (uint32_t)POOL; const uint32_t take = nout < room ? nout : room; uint32_t j = 0; @@ -582,18 +495,12 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void row_topk_kernel( s2[1] = nout == 0 ? k : done + take; } __syncthreads(); -#ifdef R3D_POOL_TRACE - if (threadIdx.x == 0) - printf(" [pool] n=%u done=%u nout=%u take=%u pv=%g pi=%u -> pv=%g pi=%u done=%u\n", - n, done, nout, (uint32_t)0, pv, pi, st[1], s2[0], s2[1]); -#endif pv = st[1]; pi = s2[0]; done = s2[1]; } } -/* One row's top_k: the request's, clamped to the buffer, whole width when absent, none when the row - * is greedy (its token is sample_argmax's, and a stage that wrote it candidates would be a bug the - * pick cannot see). */ +/* One row's top_k: the request's, clamped to the buffer; the whole width when absent; none for a + * greedy row, whose token is sample_argmax's. */ __device__ __forceinline__ uint32_t row_k(const RadSampleParams& sp, uint32_t n_cand) { if (sp.flags & RAD_SP_GREEDY) return 0; const int32_t k = sp.top_k; @@ -654,14 +561,13 @@ extern "C" int r3d_row_topk(long x, long idx, long val, long pairs, int M, int N /* ================================================================== sample_topk * - * The law: the row's top_k largest logits into the fixed-width candidate set, descending, - * ties to the lower token id, with `cand_idx` -1 and `cand_val` -infinity for a hole. Two things - * here are not in row_topk: the width is the BUFFER's (a declare-time bound), the row's top_k only - * narrows within it -- top_k 40 in a 1024-wide buffer is 40 candidates and 984 holes -- and a greedy - * row takes none, because its token is sample_argmax's and the pick must not overwrite it. + * The row's top_k largest logits into the fixed-width candidate set, descending, ties to the lower + * token id, with `cand_idx` -1 and `cand_val` -infinity for a hole. Unlike row_topk, the width is + * the buffer's (a declare-time bound) and the row's top_k narrows within it (top_k 40 in a 1024-wide + * buffer is 40 candidates and 984 holes), and a greedy row takes none. * - * `cand_val` carries LOGITS, not probabilities: every narrowing stage takes its own softmax over the - * set, which is what lets the stages compose in any order. + * `cand_val` carries logits, not probabilities: each narrowing stage takes its own softmax over the + * set, so the stages compose in any order. */ template __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel( @@ -679,8 +585,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel( float* __restrict__ vr = cv + (size_t)row * cv_ld; int32_t* __restrict__ pp = pairs ? pairs + (size_t)row * pairs_ld : nullptr; - /* The whole buffer is written every step: a hole is a value the later stages test for, and a - * stale candidate from the previous step would be drawn. */ + /* The whole buffer is written every step, since a stale candidate from the previous step would + * be drawn. */ auto hole = [&](uint32_t r) { ir[r] = -1; vr[r] = -INFINITY; @@ -706,8 +612,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel( __syncthreads(); const uint32_t nout = pool_pass(lg, n_vocab, lg_ld, 1, vec, pv, pi, lds_v, lds_i); if (threadIdx.x == 0) { - /* Only the first `nout` entries of the block list were written this pass; what sits past - * them is last pass's list, so the count, not the pad sentinel, bounds the copy. */ + /* As in row_topk: `nout` bounds the copy. */ const uint32_t room = (k - done < POOL) ? k - done : (uint32_t)POOL; const uint32_t take = nout < room ? nout : room; uint32_t j = 0; @@ -716,7 +621,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel( if (col == kPadCol) break; const float v = lds_v[kBlk + j]; const int32_t id = (int32_t)(col + (uint32_t)vocab_off); - ir[done + j] = (int32_t)col; /* cand_idx is LOCAL: it indexes this row of logits */ + ir[done + j] = (int32_t)col; /* cand_idx is local to this row of logits */ vr[done + j] = v; if (pp) { pp[2 * (done + j)] = id; pp[2 * (done + j) + 1] = *(const int32_t*)&v; } pv = v; pi = col; @@ -734,8 +639,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel( /* lg [M][n_vocab] f32; `lg_ld` a row (0 = n_vocab) * params [M] 24 words a row - * ci [M][n_cand] i32, LOCAL columns, -1 for a hole - * cv [M][n_cand] f32, the LOGIT, -infinity with the hole + * ci [M][n_cand] i32, local columns, -1 for a hole + * cv [M][n_cand] f32, the logit, -infinity with the hole * pairs [M][2*n_cand] i32, optional: (global id, logit bits), 0xffffffff for a hole * * The candidate width is ci's last dimension, as libref takes it; the row's top_k only narrows @@ -771,66 +676,21 @@ extern "C" int r3d_sample_topk(long lg, long params, long ci, long cv, long pair /* ================================================================== the narrowing stages and the draw * - * One block a row of the candidate set, the row in LDS (five arrays of n_cand f32 at the band's - * 1024 is 20 KiB of the 64 KiB), and the division of labour the arithmetic asks for: + * One block a row of the candidate set, the row in LDS (five arrays of up to 1024 f32, 20 KiB): * - * - the max is a butterfly of strict `>`: libref's `if (v > mx) mx = v` from -infinity, so a - * candidate at -infinity (a hole, or a grammar-masked token at the set's tail) is never the max - * and a NaN never is; - * - exp(v - mx) is one value per candidate, so the wave computes them all, in parallel, into LDS; - * - every SUM that follows is libref's loop, in index order, on lane 0. The normaliser, the top-p - * prefix, the entropy and the inverse-CDF scan are all order-sensitive f32 accumulations, and - * the draw is decided by the last of them. A parallel prefix sum would round differently, and a - * draw that rounds differently is a different token: this is the law, so the loop stays serial. - * It is 1024 adds, half a microsecond; the transcendentals it waits on are the cost, and they - * are already out of the loop. + * - the max is libref's strict `if (v > mx) mx = v` from -infinity, so a hole, a masked + * candidate at -infinity and a NaN are never the max; + * - exp(v - mx) is computed for all candidates in parallel into LDS; + * - every sum (the normaliser, the top-p prefix, the entropy, the inverse-CDF scan) is libref's + * loop in index order on lane 0. A parallel prefix sum would round differently and could draw a + * different token; the serial loop is 1024 adds, small next to the transcendentals. * - * A greedy row is left alone by every stage, as the reference leaves it, which is the same rule - * that keeps its token the argmax's. + * Every stage leaves a greedy row alone, as the reference does. */ namespace { enum { ST_TOPP = 0, ST_MINP = 1, ST_TYPICAL = 2, ST_XTC = 3, ST_PICK = 4 }; -__device__ __forceinline__ void cand_load(uint32_t n_cand, const int32_t* __restrict__ ir, - const float* __restrict__ vr, int32_t* __restrict__ ci, - float* __restrict__ cv) { - for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { - ci[i] = ir[i]; - cv[i] = vr[i]; - } -} - -__device__ __forceinline__ void cand_write(uint32_t n_cand, int32_t* __restrict__ ir, - float* __restrict__ vr, const int32_t* __restrict__ ci, - const float* __restrict__ cv) { - for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { - ir[i] = ci[i]; - vr[i] = cv[i]; - } -} - -/* exp(v[i] - mx) for every live candidate, in parallel. A dropped candidate gets 0, which is what - * the reference's loops contribute for it (they skip it, and a 0 is inert in every sum below). */ -__device__ __forceinline__ void cand_exp(uint32_t n_cand, const int32_t* __restrict__ ci, - const float* __restrict__ cv, float mx, - float* __restrict__ ev) { - for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) - ev[i] = (ci[i] >= 0) ? ref_exp(cv[i] - mx) : 0.0f; -} - -__device__ __forceinline__ float lane0_sum(uint32_t n_cand, const float* __restrict__ ev, - uint32_t* out) { - if (threadIdx.x == 0) { - float sum = 0.0f; - for (uint32_t i = 0; i < n_cand; ++i) sum += ev[i]; - out[0] = (uint32_t)(uintptr_t)0; - ((float*)out)[0] = sum; - } - __syncthreads(); - return ((float*)out)[0]; -} - /* A minimum to match, for typical's cut: the smallest qualifying distance. */ __device__ __forceinline__ float block_min(float v, float* lds) { const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; @@ -867,8 +727,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel( for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { s_ci[i] = ir[i]; s_cv[i] = vr[i]; } __syncthreads(); - /* mx over live candidates with a strict `>` from -infinity: a hole, a masked tail at -infinity - * and a NaN are all excluded, exactly as the reference's loop excludes them. */ + /* mx over live candidates with a strict `>` from -infinity, excluding holes, masked candidates + * and NaN, as the reference's loop does. */ float mine = -INFINITY; for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) if (s_ci[i] >= 0 && s_cv[i] > mine) mine = s_cv[i]; @@ -927,9 +787,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel( if (s_ci[i] < 0) continue; if (s_ev[i] * inv >= th) { cnt += 1.0f; last = (float)i; } } - /* Count and last are a sum and a maximum: both order-free, which is why this stage needs - * no serial loop. Candidates above the threshold are re-tested below, from the same - * values in `s_ev`. */ + /* Count and last index are order-free (a sum of small integers and a max), so no serial + * loop is needed; candidates are re-tested below from the same `s_ev`. */ const float n_above = block_sum(cnt, red); const float hi = block_max(last, red); if (n_above < 2.0f) return; /* needs two to exclude all but the least likely */ @@ -939,8 +798,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel( if (s_ev[i] * inv >= th) { s_ci[i] = -1; s_cv[i] = -INFINITY; } } __syncthreads(); - } else if (STAGE == ST_TYPICAL) { /* typical: the pick must not fall through here, - * it needs s_ev to still hold the exponentials */ + } else if (STAGE == ST_TYPICAL) { /* overwrites s_ev with log(q); only the pick + * reads s_ev afterwards, and it never runs this */ const float p = sp.typical_p; if (!(p < 1.0f) || !(p > 0.0f)) return; for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) @@ -962,7 +821,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel( __syncthreads(); /* The smallest distance whose mass reaches p. A lane owns one candidate's distance and * sums the mass at or below it in index order; ties are kept, so the set may overshoot - * p and does not depend on the candidate order. */ + * p but does not depend on candidate order. */ float cut = INFINITY; for (uint32_t c = threadIdx.x; c < n_cand; c += kThreads) { if (!(s_q[c] > 0.0f)) continue; @@ -1004,8 +863,8 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel( } /* namespace */ /* ci [M][n_cand] i32, INOUT: -1 marks a dropped candidate - * cv [M][n_cand] f32, INOUT: the LOGIT, -infinity with a drop - * params [M] 24 words a row -- the stage's own scalar, the seed and the pos + * cv [M][n_cand] f32, INOUT: the logit, -infinity with a drop + * params [M] 24 words a row: the stage's own scalar, the seed and the pos * * The set is not re-sorted: it arrives descending from sample_topk and the stages skip holes. A * greedy row is left exactly as it was. 0, -1, -2, -3, -4. */ @@ -1056,10 +915,9 @@ extern "C" int r3d_sample_pick(long ci, long cv, long params, long tok, int M, i /* ================================================================== the plugin ABI * - * Nine shims, one per op. What a row's dtype is, the tensor says; what a row's geometry is, the - * operand says; `M` is the band's ceiling and never the row count, which is numel(x)/n_vocab. The - * params plane is checked the way libref checks it -- a 32-bit dtype and enough bytes for M rows -- - * and contiguous, because the kernels index it flat, as libref does. + * Nine shims, one per op. Dtypes come from the tensors and geometry from the operands; `M` is the + * band's ceiling, never the row count. The params plane is checked as libref checks it (a 32-bit + * dtype and enough bytes for M rows) and must be contiguous, since the kernels index it flat. */ #define R3D_NEED(expr) do { const int r3d_s = (expr); if (r3d_s) return R3D_NO(r3d_s); } while (0) @@ -1079,9 +937,8 @@ static inline int sp_is_word(const RadTensor* t) { return t && (t->dtype == RAD_U32 || t->dtype == RAD_I32 || t->dtype == RAD_F32); } -/* param_rows: the params operand is a byte blob of [M, 24] words. The dtype test - * is not decoration -- a 16-bit view of the plane passes a byte-count check and then misreads every - * row, so a stage would sample with the top half of one row's temp and the bottom of the next. */ +/* The params plane: [M, 24] words. The dtype test matters: a 16-bit view passes a byte-count check + * and then misreads every row. */ static inline int params_ok(const RadTensor* t, long long M) { if (!t || !t->data) return RAD_E_INVAL; if (!sp_is_word(t)) return RAD_E_DTYPE; @@ -1159,8 +1016,7 @@ extern "C" int r3d_rad_sample_argmax(const RadArgs* a, RadStream stream) { if (rows <= 0 || rows > 0x7fffffffLL || n_vocab > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); if (r3d_numel(tk) < rows) return R3D_NO(RAD_E_SHAPE); if (!r3d_contig(tk) || !r3d_aligned(r3d_p(tk), 4)) return R3D_NO(RAD_E_SHAPE); - /* The kernel reads no scalar from the params plane, so a missing one is not a refusal: argmax is - * the row every greedy request needs, and libref describes the operand without reading it. */ + /* argmax reads nothing from params, so a missing plane is not a refusal. */ if (pr && pr->data) R3D_NEED(params_ok(pr, rows)); return r3d_launch_status(r3d_sample_argmax(r3d_addr(lg), r3d_addr(tk), (int)rows, (int)n_vocab, lg_ld, (long)(uintptr_t)stream)); @@ -1199,7 +1055,7 @@ extern "C" int r3d_rad_sample_topk(const RadArgs* a, RadStream stream) { if (!r3d_aligned(r3d_p(ci), 4) || !r3d_aligned(r3d_p(cv), 4)) return R3D_NO(RAD_E_ALIGN); const long long n_vocab = r3d_geti_or(a, "n_vocab", r3d_dim(lg, (int)lg->rank - 1)); - /* The width is the buffer's, the declare-time bound: the row's top_k narrows inside it. */ + /* The width is the buffer's declare-time bound; the row's top_k narrows inside it. */ const long long n_cand = r3d_dim(ci, (int)ci->rank - 1); if (n_vocab <= 0 || n_cand <= 0 || n_cand > kCandMax) return R3D_NO(RAD_E_SHAPE); long long rows = 0, cirows = 0, cvrows = 0, prows = 0; @@ -1244,10 +1100,7 @@ static inline int cand_row_ok(const RadArgs* a, const RadTensor* ci, const RadTe const long long ci_ld = r3d_rows_pitch(ci, n_cand, &cirows); const long long cv_ld = r3d_rows_pitch(cv, n_cand, &cvrows); if (ci_ld < 0 || cv_ld < 0) return RAD_E_STRIDE; - /* The step's rows are the operand's row count. The band key `M` is the plan's ceiling, never a - * source of row count: the plane decides the rows, and `M` is checked only as the upper bound - * the plan promised not to exceed. Preferring the key over the plane would refuse a step that - * fits the band. */ + /* The step's rows come from the operand; the band key `M` is only checked as an upper bound. */ const long long rows = cirows; if (rows <= 0 || rows > 0x7fffffffLL) { r3d_trace_desc("ci", ci); if (r3d_trace_on()) diff --git a/libr3d/r3d_sample_pre_f32.hip b/libr3d/r3d_sample_pre_f32.hip index 41e46231..e48c5568 100644 --- a/libr3d/r3d_sample_pre_f32.hip +++ b/libr3d/r3d_sample_pre_f32.hip @@ -3,78 +3,54 @@ * `sample_ngram_ban` and `sample_mask`; the draw spine -- argmax, temp, top-k, the narrowings and * the pick -- is `r3d_sample_f32.hip`, and the only things shared are statics. * - * The arithmetic is libref's, transcribed: the reference's sampler is the law, and - * `abi/rad_sample.h` is the wire format for every scalar, one 96-byte row per sampled position. The order of the - * arithmetic is transcription where the order can be seen, and there is a lot of it here: the - * penalties law (sign-dependent repetition, the count times the frequency, presence once per - * distinct token, all of it at the token's FIRST occurrence in the window), DRY's longest-suffix - * repeat per continuation token with its repeated-multiplication penalty, the n-gram ban's - * windowed prefix search and its whitelist exemption, and the mask's bit-per-token rule. + * The arithmetic is libref's, transcribed, and `abi/rad_sample.h` is the wire format for every + * scalar (one 96-byte row per sampled position). Order is transcribed wherever it is visible: the + * penalties law (sign-dependent repetition, count times frequency, presence once per distinct + * token, all at the token's first occurrence in the window), DRY's longest-suffix repeat per + * continuation token with its repeated-multiplication penalty, the n-gram ban's windowed prefix + * search and whitelist exemption, and the mask's bit-per-token rule. * - * ============================== what each stage reads, and why the shapes differ ============== + * ============================== stage shapes ============================== * - * The row is 130560 f32 at the band and there are 2048 of them: the logits plane is 1.02 GiB and - * one pass over it is ~3.6 ms on this card (RX 7600, 16 CUs). That number sorts the five into two - * shapes, and the shape is decided by how many of the row's columns the stage touches -- which is - * what the reference touches, not what it could: + * At the band a row is 130560 f32 and there are 2048 rows: the logits plane is 1.02 GiB, about + * 3.6 ms a pass on gfx1102. The stages fall into two shapes by how many columns they touch, as + * the reference does: * - * HISTORY STAGES -- penalties, dry, ngram_ban. A row's window is 64 tokens, so a row has at most - * 64 columns to touch. libref touches exactly those, and so does this file: one block a row of 64 - * threads, each position a thread, the window read straight from L2 (4096 integer reads a row, - * which is why the quadratic scans are free and why there is no LDS copy of the history). These - * kernels move kilobytes a row. Micro-optimising the scans would be optimising the part that is - * not the cost. + * History stages (penalties, dry, ngram_ban). A window is 64 tokens, so a row touches at most 64 + * columns: one block of 64 threads a row, a position a thread, the window read straight from L2 + * (4096 integer reads a row). The quadratic scans cost little, so there is no LDS copy. * - * ROW STAGES -- mask, logprobs. A mask writes every disallowed column of the row and logprobs - * summarises every column of it, so these read and write the plane and are the bandwidth rows of - * the unit: 256 threads a row, a thread a run of columns, so each lane's traffic is one - * contiguous segment. + * Row stages (mask, logprobs). These read or write the whole plane and are bandwidth-bound: 256 + * threads a row, each lane a contiguous run of columns. * - * `sample_logprobs` is where the pass count is the whole argument. libref reads the row three - * times -- a max, then a sum of `exp(v - max)`, then a third scan to insert every element into a - * k-list -- so at the band it reads 3.06 GiB where one pass reads 1.02. One pass cannot know the - * row's max before it has seen the row, so each lane keeps a running max and a running DOUBLE sum - * of `exp(v - its own max)`, rescaling its sum when its max rises (one double multiply per rise, - * a handful per lane), and the butterfly merges pairs of (max, sum) by + * `sample_logprobs` reads the row once where libref reads it three times (max, sum of + * `exp(v - max)`, k-list). Each lane keeps a running max and a running double sum of + * `exp(v - its own max)`, rescaling the sum when its max rises, and pairs merge by * * m = max(a, b); sum = a.sum * exp(a.mx - m) + b.sum * exp(b.mx - m) * - * which is the reference's sum shifted by a constant per lane. Each term is the reference's term - * to a fraction of an f64 ulp, the merged sum lands on the reference's to ~1e-15 relative, and the - * stored value is f32 -- 6e-8 is the granularity of what the plane holds, so the rescaling is - * below the store's own rounding. The lane shuffles carry the max (32-bit) and the k-list (one - * 8-byte pattern an entry at a time); the sum is merged in LDS, by wave and then across waves, and - * the reason is in sample_logprobs_kernel's comment: a double can cross lanes soundly only by - * moving bits, never by value. `r3d_lanes_check` at the end of the file is the control that keeps - * that true, and `r3d_selftest.cpp` runs it. The `exp` - * is `exp(double)`, the reference's own width: libref's sum adds double exps and the row is the - * logit distribution, so this is the file's one fp64-heavy kernel and it is the slow path by law, - * not by oversight -- consumer RDNA3 is 1:64 on doubles. At the band (M=2048, - * n_vocab=130560, k=21) the plane's one read is 3.6 ms at 266 GiB/s, a read that also sums - * `exp(double)` is 30.4 ms, this kernel is 38.9 ms, and libref's three reads of that plane are - * 2.988 GiB against this kernel's 0.996. + * which is the reference's sum shifted by a constant per lane; it agrees to about 1e-15 relative, + * far below the f32 store's 6e-8. The max and the k-list cross lanes by shuffle; the sum merges in + * LDS (see sample_logprobs_kernel), checked by `r3d_lanes_check` at the end of the file, which + * `r3d_selftest.cpp` runs. The exp is `exp(double)`, the reference's width, which makes this the + * file's one fp64-heavy kernel (consumer RDNA3 runs doubles at 1:64); at the band most of its time + * is the double exp, not the read. * - * The k-list is per lane too, k deep, kept in the reference's order -- descending by value, ties - * to the LOWER column, which is `topk_next`'s total order and the narrowing stages' -- and merged - * pairwise in the same butterfly, so the block's list is the reference's list. `k` at the band is - * 21; the pool is 64 deep, and a request above that is refused rather than silently truncated. + * The k-list is per lane, k deep, in the reference's order (descending by value, ties to the lower + * column, `topk_next`'s total order) and merged pairwise in the same butterfly. The pool is 64 + * deep; a larger k is refused, not truncated. * - * ============================== agreement, and where this file declines ============================== + * ============================== agreement and declines ============================== * - * Maxima are strict `>` with the max as the first argument, which is `std::max`'s law and is how a - * NaN is kept out of the row's max: a NaN never compares greater, so it is never adopted, at the - * first element or anywhere later. A NaN in the sum propagates, because the reference's - * `exp(NaN - mx)` is NaN and it is added. + * Maxima use a strict `>` with the max as the first argument (`std::max`'s law), so a NaN is never + * adopted as the row's max. A NaN in the sum propagates, as the reference's `exp(NaN - mx)` does. * - * A row whose parameters turn the stage off is left bit for bit as it was -- the flag test is the - * reference's, and for penalties the identity test (rep 1, freq 0, pres 0) is too. + * A row whose parameters turn the stage off is left bit-exact; the flag test is the reference's, + * and for penalties so is the identity test (rep 1, freq 0, pres 0). * - * Declines, all of them RAD_E_UNSUPPORTED from the shim and none of them reachable from a row that - * carries the constraints its rows do: a history plane wider than 2^31/8 columns is not a plane; - * `k` above 64 for logprobs (the pool's depth, and far above any k the engine requests); and for - * ngram_ban a `whitelist` plane, which the kernel implements -- the whitelist is exempted before - * the -inf writes, as the reference removes it from the banned set -- so the only decline is the - * `ngram` plane's dtype and the mask and whitelist's, which must be 32-bit words. + * Declines (RAD_E_UNSUPPORTED or a dtype refusal from the shim, none reachable from a row that + * carries its constraints): a history plane wider than 2^31/8 columns; `k` above 64 for logprobs; + * an `ngram` plane of the wrong dtype; mask or whitelist planes that are not 32-bit words. */ #include "r3d.h" @@ -88,8 +64,8 @@ /* ================================================================== shared helpers (statics) * - * The headers are frozen, so a unit that needs a helper carries its own copy and keeps it static: a - * non-static one collides at link with the same helper in another unit and takes the library down. + * Helpers are per-unit and internal-linkage: a non-static copy would collide at link with the same + * helper in another unit. */ namespace { @@ -99,17 +75,9 @@ constexpr uint32_t kWave = 32; constexpr uint32_t kWaves = kThreads / kWave; constexpr int kKMax = 64; /* the k-list pool's depth, per lane */ -/* The row's summary accumulates `exp` in DOUBLE, because that is where the reference's sum lives. - * The width is a switch, because the width is the cost: at the band the double exp is 30 ms of the - * kernel's 38 ms against a 3.7 ms plane read, and an f32 exp widened to double -- - * `expf`, terms accurate to an f32 ulp, summed in double -- lands the row's sum on the reference's - * to ~1e-10 relative against a stored f32 granularity of 6e-8. Define R3D_LP_EXP_F32 to build the - * fast exp; the default is the reference's arithmetic. */ -#ifdef R3D_LP_EXP_F32 -__device__ __forceinline__ double dexp(double x) { return (double)expf((float)x); } -#else +/* The row's summary accumulates `exp` in double, as the reference's sum does. At the band the + * double exp is most of the kernel's time; it stays, so the summary is the reference's arithmetic. */ __device__ __forceinline__ double dexp(double x) { return exp(x); } -#endif /* A whole-register load of an index plane: the history, the n-gram pair, the bitmask words. */ __device__ __forceinline__ int32_t ldg_i32(const int32_t* p) { @@ -122,12 +90,10 @@ template __device__ __forceinline__ int32_t xor_i32(int32_t v) { return (int32_t)r3d_xor_lane_u32((uint32_t)v); } -/* There is no 64-bit lane shuffle here on purpose: see sample_logprobs_kernel. */ +/* No 64-bit numeric lane shuffle: see sample_logprobs_kernel. */ -/* The law, verbatim. The window both history stages read, clamped to the row's own row - * of the plane; `last_n` 0 disables the stage, a negative keeps the whole span, a positive keeps - * its TAIL. The window law IS the history law: the window, and the rule that a token is penalised - * at its first occurrence in it. */ +/* The reference's window, verbatim, clamped to the row's own row of the plane: `last_n` 0 + * disables the stage, a negative keeps the whole span, a positive keeps its tail. */ __device__ __forceinline__ bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax, int64_t* ho_out, int64_t* hl_out) { if (last_n == 0) return false; @@ -144,8 +110,8 @@ __device__ __forceinline__ bool hist_window(const RadSampleParams& sp, int32_t l return hl > 0; } -/* The law, verbatim, including the stop short of overflow: repeated multiplication, so - * every implementation lands on the same float. */ +/* The reference's penalty, verbatim, including the stop short of overflow. Repeated multiplication + * rather than powf, so every implementation lands on the same float. */ __device__ __forceinline__ float dry_penalty(float multiplier, float base, int64_t e) { float pen = multiplier; if (base == 1.0f) return pen; @@ -157,8 +123,8 @@ __device__ __forceinline__ float dry_penalty(float multiplier, float base, int64 return pen; } -/* The k-list's order: descending by value, ties to the lower column. `above(x, y)` is "x comes - * first", the reference's comparator and `topk_next`'s chain. */ +/* The k-list's order: descending by value, ties to the lower column. `above(x, y)` means x comes + * first (the reference's comparator, `topk_next`'s chain). */ struct Cand { float v; int32_t i; }; __device__ __forceinline__ bool above(Cand x, Cand y) { return x.v > y.v || (x.v == y.v && x.i < y.i); @@ -166,13 +132,12 @@ __device__ __forceinline__ bool above(Cand x, Cand y) { /* ================================================================== sample_logprobs * - * The law. The row's summary: its max, the sum of exp(v - max) in double, and the k - * largest as (id, logit) pairs descending, ids as floats with `vocab_off` added, an unfilled slot - * id -1 and logit -infinity. Rows without RAD_SP_LOGPROBS are not written at all. + * The row's summary: its max, the sum of exp(v - max) in double, and the k largest as (id, logit) + * pairs descending, ids as floats with `vocab_off` added; an unfilled slot is id -1, logit + * -infinity. Rows without RAD_SP_LOGPROBS are not written. * - * One pass over the row, per the file's header: the max, the sum and the k-list are three - * independent accumulations of the same read, and the sum is rescaled into the row's final max at - * the merge, which is a per-lane shift of the reference's terms. + * One pass (see the file header): max, sum and k-list accumulate from the same read, and the sum is + * rescaled into the final max at each merge. */ struct Acc { float mx; @@ -181,17 +146,17 @@ struct Acc { int n; }; -/* A lane's running state over its own elements. A new maximum rescales the sum it has so far; the - * reference never rescales (it knows the max up front) and the rescale is the price of the read. */ +/* A lane's running state over its own elements. A new maximum rescales the sum so far, the cost + * of not knowing the max up front as the reference does. */ __device__ __forceinline__ void acc_push(Acc& a, int k, uint32_t col, float v) { if (v > a.mx) { if (a.mx != -INFINITY) a.sum *= dexp((double)a.mx - (double)v); a.mx = v; } a.sum += dexp((double)v - (double)a.mx); - /* The reference's insertion: an element that is not above the k-th is dropped, and the insert - * point is the first slot the element beats (with a NaN, no slot, so the tail: insert, then the - * pop leaves the list exactly as it was). */ + /* The reference's insertion: an element not above the k-th is dropped; otherwise it goes in + * the first slot it beats. A NaN beats no slot, so it lands at the tail and the list is + * unchanged. */ if (a.n == k && !above(Cand{ v, (int32_t)col }, a.c[a.n - 1])) return; int pos = 0; while (pos < a.n && !above(Cand{ v, (int32_t)col }, a.c[pos])) ++pos; @@ -201,10 +166,9 @@ __device__ __forceinline__ void acc_push(Acc& a, int k, uint32_t col, float v) { if (a.n < k) ++a.n; } -/* The butterfly's merge of two lanes' states: the max is strict, the sum is the two shifted sums, - * and the lists merge on the same order. Ties in the merge (two equal values at equal columns - * cannot happen -- the column is the lane's -- and a NaN is not above anything, so a NaN list - * entry stays in the lane that read it). */ +/* The merge of two lanes' states: a strict max, the sum of both shifted sums, and the lists merged + * in the same order. Equal values at equal columns cannot occur (each column belongs to one lane), + * and a NaN entry is above nothing. */ __device__ __forceinline__ Acc acc_merge(const Acc& a, const Acc& b, int k) { Acc r; r.mx = a.mx > b.mx ? a.mx : b.mx; @@ -234,35 +198,20 @@ __global__ __launch_bounds__(THR) void sample_logprobs_kernel( const float* __restrict__ lr = lg + (size_t)row * lg_ld; for (uint32_t c = threadIdx.x; c < n; c += THR) acc_push(a, (int)k, c, ldg_f32(lr + c)); - /* The k-list and the max meet their partners in the wave's 32-bit lane shuffles, five rounds. + /* The k-list and the max meet their partners by lane shuffle, five rounds. The shuffle mask + * on wave32 is `0xFFFFFFFFull`; `~0ull` would name lanes 32..63, which do not exist. * - * The participation mask of a 64-bit shuffle on this ROCm is an `unsigned long long`, and on - * wave32 it is `0xFFFFFFFFull`: `~0ull` names lanes 32..63, which a wave of 32 does not have. - * `r3d_lanes_check` at the end of this file is the control that proves the lane helpers, and - * `r3d_selftest.cpp` runs it and checks every lane of every wave. - * - * The SUM does not go through a lane shuffle: it meets its partners in LDS, the machinery - * `block_sum` already trusts. A double can cross lanes soundly -- lanes_check_kernel below is - * exact in all 256 lanes of all 8 waves for three forms of it -- but only by moving the value's - * *bits*, never by value: a cast to an integer type converts by value, so - * - * d += (double)r3d_xor_lane_u64((unsigned long long)d); - * - * truncates the partner's term to its integer part, and a wave of fractions then sums to 1, the - * largest term's integer part -- a 40% loss of the row's mass at the band's width, the shape a - * hardware fault takes. The k-list, whose entries are bit patterns by construction (a float's - * pattern and an int in one 8-byte value), crosses lanes as that pattern in one shuffle; the sum, - * which is a number, does not cross lanes at all. */ + * The sum does not cross lanes; it merges in LDS below. A double can cross lanes only as its + * bits: `(unsigned long long)d` converts by value and truncates the partner's term to its + * integer part (see lanes_check_kernel). The k-list entries are bit patterns (a float's + * pattern and an int packed into 8 bytes), so they cross as one 64-bit shuffle. */ #define R3D_ACC_XOR(M) \ { \ Acc b; \ b.mx = r3d_xor_lane(a.mx); \ b.n = xor_i32((int32_t)a.n); \ for (int j = 0; j < k; ++j) { \ - /* One list entry is one 8-byte value -- a float's pattern and a column -- and it - * crosses lanes as that pattern, in one shuffle. Assembling it from the two halves on - * the far side would need each half shuffled and then reassembled by value, which is - * the shape that turns a bit pattern into a number. */ \ + /* One entry, a float's pattern and a column, crosses lanes as one 8-byte pattern. */ \ const unsigned long long packed = \ (unsigned long long)__float_as_uint(a.c[j].v) | \ ((unsigned long long)(uint32_t)a.c[j].i << 32); \ @@ -270,8 +219,7 @@ __global__ __launch_bounds__(THR) void sample_logprobs_kernel( b.c[j] = Cand{ __uint_as_float((uint32_t)got), (int32_t)(uint32_t)(got >> 32) }; \ } \ b.sum = 0.0; \ - const float mx = a.mx > b.mx ? a.mx : b.mx; /* no lane's max is a NaN: a NaN is never \ - adopted by the strict test above */ \ + const float mx = a.mx > b.mx ? a.mx : b.mx; /* no lane's max is a NaN (strict test) */ \ a = acc_merge(a, b, (int)k); \ a.mx = mx; \ } @@ -282,9 +230,9 @@ __global__ __launch_bounds__(THR) void sample_logprobs_kernel( R3D_ACC_XOR(1) #undef R3D_ACC_XOR - /* The wave's sum, in LDS: the wave's max first, then every lane's sum shifted into it, in lane - * order. An empty lane (a row narrower than the block) has max -infinity and sum 0 and - * contributes nothing, which is the reference's own arithmetic on an empty span. */ + /* The wave's sum in LDS: the wave's max, then every lane's sum shifted into it, in lane order. + * An empty lane (a row narrower than the block) has max -infinity and sum 0 and contributes + * nothing. */ __shared__ float s_mx[kThreads]; __shared__ double s_sum[kThreads]; __shared__ float w_mx[kWaves]; @@ -345,16 +293,15 @@ __global__ __launch_bounds__(THR) void sample_logprobs_kernel( /* ================================================================== sample_penalties * - * The law. llama.cpp's ordering, at the token's first occurrence in the window: + * llama.cpp's ordering, applied at the token's first occurrence in the window: * * repetition logit = logit > 0 ? logit / rep : logit * rep * frequency logit -= count * freq * presence logit -= pres * * The repetition penalty is sign-dependent because dividing a negative logit would raise it. The - * count carries the multiplicity, which is why the update runs once per distinct token, and the - * scan for it is the reference's own: walk the window from the front, stop at an earlier - * occurrence, count the ones from here on. + * count carries the multiplicity, so the update runs once per distinct token; the scan is the + * reference's: walk the window from the front, stop at an earlier occurrence, count the rest. * * Columns are global ids less `vocab_off`, so a token on another rank's shard is skipped here and * penalised there. Each distinct token is one column and one thread, so the writes cannot race. @@ -395,15 +342,14 @@ __global__ __launch_bounds__(kPre) void sample_penalties_kernel( /* ================================================================== sample_dry * - * The law, DRY's rule (llama.cpp's llama_sampler_dry_apply): for every earlier position - * j, n_j is how long a suffix of the window also ends at j, capped at the breaker limit; the token - * at j+1 would extend that repeat and is penalised by multiplier * base^(n - allowed), once, by the - * LONGEST repeat it follows. A token that is itself a whole-sequence breaker is never penalised, - * and only lengths at or above `allowed` count. + * DRY (llama.cpp's llama_sampler_dry_apply): for every earlier position j, n_j is how long a suffix + * of the window also ends at j, capped at the repeat limit. The token at j+1 would extend that + * repeat and is penalised once by multiplier * base^(n - allowed), using the longest repeat it + * follows. A breaker token is never penalised, and only lengths >= `allowed` count. * - * A thread a position, the window read from L2. The map the reference keeps is here a maximum over - * the threads that share a token, applied by the thread holding the token's first occurrence, so - * one column is written once. + * A thread a position, the window read from L2. The reference's per-token map becomes a maximum + * over the threads sharing a token, applied by the thread at the token's first occurrence, so each + * column is written once. */ __global__ __launch_bounds__(kPre) void sample_dry_kernel( float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist, @@ -434,8 +380,8 @@ __global__ __launch_bounds__(kPre) void sample_dry_kernel( const int32_t tok = tok_at((int64_t)j + 1); const int64_t col = (int64_t)tok - voff; if (tok < 0 || col < 0 || col >= n) continue; - /* The longest repeat any position attributes to this token, and the first thread that - * carries it pays for it. Equal tokens at equal lengths: the lowest j, so one writer. */ + /* The longest repeat any position attributes to this token; the lowest qualifying j is + * the one writer. */ int64_t longest = m; bool first = true; for (int64_t q = 0; q + 1 < hl; ++q) { @@ -455,18 +401,17 @@ __global__ __launch_bounds__(kPre) void sample_dry_kernel( /* ================================================================== sample_ngram_ban * - * The law, the windowed no-repeat-ngram ban. With the row's window s[0, hl): + * The windowed no-repeat-ngram ban. With the row's window s[0, hl): * * search_start = max(0, hl - w); search_end = hl - n + 1; prefix = s[hl - n + 1, hl) * for idx in [search_start, search_end): s[idx, idx + n - 1) == prefix => ban s[idx + n - 1] * - * The window is on the START index, so the n-gram that straddles the window's edge is searched. A - * banned token's logit becomes -infinity, and the whitelist is removed from the banned set before - * any -inf is written, so a whitelisted column is never touched. n == 1 bans every token in the - * window, the prefix being empty. A row whose n is 0 is left bit for bit as it was. + * The window bounds the start index, so an n-gram straddling the window's edge is searched. A + * banned token's logit becomes -infinity; whitelisted columns are exempt and never touched. n == 1 + * bans every token in the window (empty prefix). A row with n 0 is left unchanged. * - * A thread a search index. Several indices can ban the same token; the write is the same -infinity - * from every one of them, so the race writes one value. + * A thread a search index. Several indices may ban the same token, but all write the same + * -infinity. */ __global__ __launch_bounds__(kPre) void sample_ngram_ban_kernel( float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist, @@ -514,16 +459,12 @@ __global__ __launch_bounds__(kPre) void sample_ngram_ban_kernel( /* ================================================================== sample_mask * - * The law. A set bit means allowed; an unset column's logit becomes -infinity. This is - * the dense row stage: a row of 130560 columns and a bitmask of 4080 words, so a thread takes a - * word and the 32 columns under it, which is one contiguous 128-byte segment a lane. A word that - * is all ones is skipped whole, and a word that is all zeros is a run of eight 16-byte stores; - * either way the row is written in the order the plane is laid out. + * A set bit means allowed; an unset column's logit becomes -infinity. A thread takes one bitmask + * word and its 32 columns, a contiguous 128-byte segment. An all-ones word is skipped; an all-zeros + * word is a straight run of stores. * - * `mask_row` is the row's own row of the bitmask plane, and the reference skips a row index - * outside the plane, -1 included (the shape hook caps `idx_max` at M so a fixture draws a real - * row); the shim bounds the plane to at least M rows, which is the same test at the geometry the - * op's descriptor describes. + * `mask_row` selects the row of the bitmask plane; as in the reference, a row index outside the + * plane (-1 included) leaves the row unmasked. */ __global__ __launch_bounds__(kThreads) void sample_mask_kernel( float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ bm, @@ -556,9 +497,8 @@ static inline int sp_is_word(const RadTensor* t) { return t && (t->dtype == RAD_U32 || t->dtype == RAD_I32 || t->dtype == RAD_F32); } -/* The params plane: [M, 24] words. The dtype test is not decoration -- a 16-bit view of the plane - * passes a byte-count check and then misreads every row, sampling with the top half of one row's - * temp and the bottom of the next. */ +/* The params plane: [M, 24] words. The dtype test matters: a 16-bit view passes a byte-count check + * and then misreads every row. */ static inline int params_ok(const RadTensor* t, long long M) { if (!t || !t->data) return RAD_E_INVAL; if (!sp_is_word(t)) return RAD_E_DTYPE; @@ -600,8 +540,8 @@ static inline int r3d_launch_status(int rc) { /* The logits row count, from the plane and never from the band's M. */ static inline int logits_rows(const RadArgs* a, const RadTensor* lg, long long* n_vocab, long long* rows, long long* lg_ld) { - /* The reference reads the width off the band, falling back to the plane's last dimension, and - * a rank-1 plane has no last dimension to read: the width is absent, which is E_SHAPE. */ + /* As in the reference: the width from the band, else the plane's last dimension; a rank-1 + * plane has none, which is E_SHAPE. */ *n_vocab = r3d_geti_or(a, "n_vocab", lg->rank >= 2 ? r3d_dim(lg, (int)lg->rank - 1) : 0); if (*n_vocab <= 0 || *n_vocab > 0x7fffffffLL) return RAD_E_SHAPE; @@ -697,13 +637,11 @@ extern "C" int r3d_sample_mask(long lg, long params, long bitmask, int M, int n_ if (M <= 0 || n_vocab <= 0) return -2; if (!lg_ld) lg_ld = n_vocab; if (lg_ld < n_vocab) return -3; - if (mask_rows < M) return -3; /* a plane that cannot address row M-1 is not that plane */ + if (mask_rows < M) return -3; /* the plane must hold at least M rows */ const uint32_t words = (uint32_t)((n_vocab + 31) / 32); - /* mask_rows is the bitmask plane's own row count, which is what the reference compares - * mask_row against, and the shim reads it off the operand. It is M at the geometry the shape - * hook draws and the engine builds, and larger when a caller hands a plane of its own, in which - * case a row addressing past M is masked, as the reference masks it. The grid stays M: rows - * past the logits plane's row count have no logits to mask. */ + /* mask_rows is the bitmask plane's own row count, the bound the reference tests mask_row + * against; it may exceed M when a caller passes a larger plane. The grid stays M, the logits + * row count. */ R3D_KLAUNCH(R3D_KNAME(sample_mask_kernel), dim3((uint32_t)M), dim3(kThreads), (hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg, (const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)bitmask, @@ -725,8 +663,7 @@ extern "C" int r3d_rad_sample_logprobs(const RadArgs* a, RadStream stream) { R3D_NEED(logits_ok(lg)); const long long k = r3d_geti_or(a, "k", 0); if (k <= 0) return R3D_NO(RAD_E_SHAPE); - /* The pool is 64 deep per lane, which is above every k the engine requests. A row carrying - * C_LE("k", 64) is what keeps a request above it out of the band. */ + /* The pool is 64 deep per lane; the row's C_LE("k", 64) keeps larger requests out of the band. */ if (k > kKMax) return R3D_NO(RAD_E_UNSUPPORTED); long long n_vocab = 0, rows = 0, lg_ld = 0; R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld)); @@ -770,7 +707,7 @@ extern "C" int r3d_rad_sample_dry(const RadArgs* a, RadStream stream) { R3D_NEED(hist_ok(hi, rows, &hmax)); long long baddr = 0; if (brk && brk->data) { - /* One byte a history position, the exemption matching the history position for position. */ + /* One exemption byte per history position. */ if (!r3d_is_u8(brk)) return R3D_NO(RAD_E_DTYPE); if (!r3d_contig(brk)) return R3D_NO(RAD_E_STRIDE); if (r3d_numel(brk) < rows * hmax) return R3D_NO(RAD_E_SHAPE); @@ -822,8 +759,7 @@ extern "C" int r3d_rad_sample_mask(const RadArgs* a, RadStream stream) { if (!r3d_contig(bm)) return R3D_NO(RAD_E_STRIDE); const long long words = (n_vocab + 31) / 32; if (words <= 0 || r3d_numel(bm) < rows * words) return R3D_NO(RAD_E_SHAPE); - /* The plane's own row count is the bound the reference tests, and the plane may be longer than - * the logits: a caller that hands a plane of its own gets its rows. */ + /* The plane's own row count is the bound the reference tests; it may exceed the logits'. */ const long long mask_rows = r3d_numel(bm) / words; return r3d_launch_status(r3d_sample_mask(r3d_addr(lg), r3d_addr(pr), r3d_addr(bm), (int)rows, (int)n_vocab, lg_ld, (int)mask_rows, @@ -832,32 +768,20 @@ extern "C" int r3d_rad_sample_mask(const RadArgs* a, RadStream stream) { /* ================================================================== the lane helpers, proved * - * Every wave-sum in libr3d is a butterfly over lane shuffles, and the arithmetic that rides on a - * lane shuffle is invisible to a codec sweep: a helper that hands back a stale half of a 64-bit - * value reads as a few percent of a perplexity, in a model nobody suspects. This file - * has one of the shapes in it -- the logprobs k-list crosses lanes as 8-byte values -- so it also - * carries the control that checks the helpers, on the card, one entry per lane per wave. + * Every wave-sum in libr3d is a butterfly over lane shuffles, and an error in a lane helper (say, a + * stale half of a 64-bit value) is invisible to a codec sweep. The logprobs k-list crosses lanes as + * 8-byte values, so this file carries the on-device control for the helpers: one entry per lane of + * all 8 waves, seeds at wave-local lanes 6, 9, 19 and 25, five butterfly rounds, over + * `r3d_xor_lane_u64` (two 32-bit shuffles), and one 64-bit shuffle. * - * On this box (gfx1102, -O2 and -O3, wave32) the control is exact in **all 256 lanes of all 8 - * waves**: seeds at wave-local lanes 6, 9, 19 and 25, five butterfly rounds, and every form of the - * 64-bit exchange -- `r3d_xor_lane_u64` (two 32-bit shuffles of the halves), the same shape written - * as a `__shfl_xor_sync` per half, and one shuffle of the 64-bit value -- with the lane's value - * derived from `threadIdx.x`, loaded from a plane, and accumulated in a grid-stride loop. - * `r3d_xor_lane_u64` is sound; the form it must not be written in converts by value: + * The form that must not be written converts by value: * - * d += (double)r3d_xor_lane_u64((unsigned long long)d); // WRONG + * d += (double)r3d_xor_lane_u64((unsigned long long)d); // wrong * - * `(unsigned long long)d` converts a double to an integer **by value** and `(double)` converts back - * by value, so the partner's term arrives truncated to its integer part. A wave of fractions then - * sums to 1 -- the largest term's integer part -- a 40% loss of the row's mass at the band's width, - * and a loss that vanishes when the terms are integers: an integer survives the round trip. Nothing - * about the lane shuffle is involved, and a codec sweep cannot see it, because the expression is not - * a codec. The correct form moves bits, not values (`bits_of` / `d_from_bits` below), which is what - * the k-list's shuffle does. - * - * The two traps of this shape are the whole content of the warning: summing a - * float's IEEE pattern as an integer, and converting a float's pattern to a value. The control - * catches both, in both directions, on the card, in every lane. + * The partner's term arrives truncated to its integer part, so a wave of fractions sums to the + * largest integer part; the error vanishes for integer terms. The correct form moves bits + * (`bits_of` / `d_from_bits` below), as the k-list's shuffle does. The control catches both traps: + * summing an IEEE pattern as an integer, and converting a pattern to a value. */ __device__ __forceinline__ double d_from_bits(unsigned long long b) { double d; @@ -871,12 +795,11 @@ __device__ __forceinline__ unsigned long long bits_of(double d) { } __global__ __launch_bounds__(256) void lanes_check_kernel(double* __restrict__ out) { - /* kThreads and kWave are this file's anonymous-namespace names and are ambiguous out here, so - * the control spells its own geometry. */ + /* kThreads and kWave are ambiguous outside the anonymous namespace, so the control spells its + * own geometry. */ constexpr uint32_t kLWave = 32, kLBlock = 256; - /* Seeds at wave-local lanes 6, 9, 19, 25: a wave with four non-zero lanes and an expected sum - * of 0.08945 + 1 + 0.5971 + 0.9768, in the butterfly's own order. Every wave carries them, so - * every wave is checked. */ + /* Four non-zero lanes per wave, expected sum 0.08945 + 1 + 0.5971 + 0.9768 in the butterfly's + * order; every wave carries them. */ const uint32_t lane = threadIdx.x & (kLWave - 1); const double seed = (lane == 6) ? 0.08945 : (lane == 9) ? 1.0 : (lane == 19) ? 0.5971 : (lane == 25) ? 0.9768 : 0.0; @@ -886,8 +809,7 @@ __global__ __launch_bounds__(256) void lanes_check_kernel(double* __restrict__ o s_f[threadIdx.x] = (float)seed; __syncthreads(); - /* Form 0: the 32-bit butterfly every wave-sum in the library is built from, over a value read - * out of LDS so it is a memory operand and not a constant. */ + /* Form 0: the 32-bit butterfly, over a value read from LDS so it is not a constant. */ float f = s_f[threadIdx.x]; f += r3d_xor_lane<16>(f); f += r3d_xor_lane<8>(f); @@ -896,24 +818,21 @@ __global__ __launch_bounds__(256) void lanes_check_kernel(double* __restrict__ o f += r3d_xor_lane<1>(f); out[0 * kLBlock + threadIdx.x] = (double)f; - /* Form 1: the halves form over a value derived from the lane index. The pattern goes to the - * helper and back through bits_of/d_from_bits: a cast between double and an integer type - * converts the value, which is what this control guards against. */ + /* Form 1: the halves form over a value derived from the lane index, passed as bits. */ double d = seed; #define R3D_L64(N) d += d_from_bits(r3d_xor_lane_u64(bits_of(d))); R3D_L64(16) R3D_L64(8) R3D_L64(4) R3D_L64(2) R3D_L64(1) #undef R3D_L64 out[1 * kLBlock + threadIdx.x] = d; - /* Form 2: the same halves form over a value loaded from LDS, the shape an accumulator has. */ + /* Form 2: the halves form over a value loaded from LDS, as an accumulator is. */ d = s_d[threadIdx.x]; #define R3D_L64B(N) d += d_from_bits(r3d_xor_lane_u64(bits_of(d))); R3D_L64B(16) R3D_L64B(8) R3D_L64B(4) R3D_L64B(2) R3D_L64B(1) #undef R3D_L64B out[2 * kLBlock + threadIdx.x] = d; - /* Form 3: one shuffle of the 64-bit pattern, the form this file's k-list uses. The mask is - * 0xFFFFFFFFull, the 32 lanes a wave32 wave has. */ + /* Form 3: one 64-bit shuffle, the k-list's form; the mask names wave32's 32 lanes. */ d = s_d[threadIdx.x]; #define R3D_S64(N) d += d_from_bits(__shfl_xor_sync(0xFFFFFFFFull, bits_of(d), N)); R3D_S64(16) R3D_S64(8) R3D_S64(4) R3D_S64(2) R3D_S64(1) @@ -921,9 +840,9 @@ __global__ __launch_bounds__(256) void lanes_check_kernel(double* __restrict__ o out[3 * kLBlock + threadIdx.x] = d; } -/* Four forms x 256 lanes of doubles (8 KiB, which the caller owns: this launcher allocates nothing, - * as every launcher in this file does). 0, -1 null, -4 the launch failed. r3d_selftest.cpp dlsyms - * this by name and compares every lane against a host emulation of the same five rounds. */ +/* Writes four forms x 256 lanes of doubles (8 KiB, caller-owned). 0, -1 null, -4 the launch + * failed. r3d_selftest.cpp resolves this by name and compares every lane against a host emulation + * of the same five rounds. */ extern "C" int r3d_lanes_check(long out, long stream) { if (!out) return -1; R3D_KLAUNCH(R3D_KNAME(lanes_check_kernel), dim3(1), dim3(256), diff --git a/libr3d/r3d_selftest.cpp b/libr3d/r3d_selftest.cpp index b8871575..7954e688 100644 --- a/libr3d/r3d_selftest.cpp +++ b/libr3d/r3d_selftest.cpp @@ -1,57 +1,45 @@ /* r3d_selftest -- dump the libr3d row table, cross-check it, and prove every row links and runs. * * A transcription error in a constraint table stays invisible until a model silently picks the - * wrong kernel, and a codec one bit out on a subnormal shows up as a percentage of a perplexity. So - * the table is printed in full and checked against itself: + * wrong kernel, so the table is printed and checked against itself: * - * - every row's `op` has a schema declared by this plugin, or nothing can select it; - * - every constraint key is a declared parameter of that op. libr3d's constraints and libref's - * schemas are one vocabulary, and a key renamed in only one place yields a row that matches - * nothing; + * - every row's `op` has a schema declared by this plugin; + * - every constraint key is a declared parameter of that op (a key renamed in one place only + * yields a row that matches nothing); * - names are unique, launches exist, an init has a fini, a tunable's default is one of its - * values (the loader refuses a plugin whose default it cannot launch, and it is better to hear - * it here), and no row carries a `layout`, `relayout` or `unrelayout` hook: libr3d repacks - * nothing (r3d_rows.cpp explains why, and a hook appearing means a container format only this - * plugin can read has crept in); - * - every `opd_shape` describes as many operands as its schema declares, for a spread of - * geometries, with positive extents. + * values (the loader refuses a plugin otherwise), and layout hooks appear only on the + * joined-weight rows, always with their relayout writer; + * - every `opd_shape` describes as many operands as its schema declares, with positive extents. * - * The codecs are checked against the ABI's own host versions in `rad_plugin.h` over every bit - * pattern where the domain is small and a sweep where it is not: bf16 and f16 over all 65536, E4M3 - * over all 256 codes and the encoder over the saturating, subnormal, signed-zero and NaN cases, - * int8 against `rad_round_even_sat` over every tie in its band. This is the check `rad-kbench` - * cannot do: it compares whole ops, so a codec's disagreement appears as a diffuse percentage. - * libr3d's codecs are software -- the lane map, not a missing instruction, is the reason, and its - * bf16 packing is `v_perm` and not `v_cvt_pk_bf16_f32` -- so they are the plugin's own - * arithmetic and belong to the tests. + * The codecs are checked against the ABI's host versions in `rad_plugin.h`: bf16 and f16 over all + * 65536 patterns, E4M3 over all 256 codes, the E4M3 encoder over saturating, subnormal, + * signed-zero and NaN cases, int8 against `rad_round_even_sat` over every tie in its band. + * rad-kbench compares whole ops, where a codec error appears only as a diffuse percentage. + * libr3d's codecs are software (its bf16 packing is `v_perm`, not `v_cvt_pk_bf16_f32`), so they + * are the plugin's own arithmetic. * - * Then, on a device, every launch is called with a minimal valid input built from the row's own - * `opd_shape`, and every output plane is read back and checked to be finite. That catches the class - * of bug a table check cannot: a null operand the shim does not test, a stride read from the wrong - * axis, an operand index off by one, an undefined symbol, a kernel that writes where it should not. - * - * The numerical oracle is `rad-kbench`, which replays `kernels.rkb` against libref; this program - * does not duplicate it. What it adds is that the rows are reachable at all -- on this card, from - * this .so, with the geometry their constraints state. + * On a device, every launch is called with a minimal valid input built from the row's own + * `opd_shape`, and every output plane is read back and checked to be finite. That catches what a + * table check cannot: an untested null operand, a stride from the wrong axis, an operand index off + * by one, an undefined symbol, a stray write. * + * The numerical oracle is `rad-kbench` (`kernels.rkb` against libref); this program checks that + * the rows are reachable on this device, from this .so, at the geometry their constraints state. * The plugin is dlopened rather than linked, so an undefined symbol in the .so is caught too. * - * One child process per row. A bad pointer handed to a kernel is a GPU page fault, which ROCr - * reports by printing a line and aborting the process. In one process the first bad row would end - * the run, and with stdout block-buffered down a pipe the fault line can land next to the wrong - * row. So the parent runs the static phase and then re-execs itself once per row with - * `--case `; a child killed by a signal is a FAIL naming the signal, and the run continues. - * posix_spawn rather than fork, because the parent already has the HIP runtime's threads up and - * only exec resets them. + * One child process per row: a GPU page fault makes ROCr print a line and abort the process, so + * the parent runs the static phase and then re-execs itself per row with `--case `. A child + * killed by a signal is a FAIL naming the signal. posix_spawn rather than fork, because the + * parent's HIP runtime threads are already up and only exec resets them. * - * `--case ` is also the reproducer: it runs one row, alone, in the foreground. + * `--case ` also reproduces one row alone in the foreground. */ #include "rad_abi.h" #include "rad_plugin.h" #include "r3d_codecs.h" #include "rad_planes.h" /* the joined scale+zero plane, for the row no shape hook can describe */ -#include "r3d_plugin.h" /* the entry points, for the shape hooks that precede their rows */ +#include "r3d_plugin.h" /* the entry points */ #include #include @@ -83,9 +71,7 @@ static int g_skip = 0; static const char* g_case = nullptr; static const char* g_plugin = nullptr; -/* The plugin's table, reached through the symbols dlopened in main. The program is not linked - * against libr3d: an undefined symbol in the .so must be this program's failure, not its own - * failure to build. */ +/* The plugin's table, through the symbols dlsym'd in main (the program does not link libr3d). */ static int (*P_count)(void) = nullptr; static const RadKernelInfo* (*P_at)(int) = nullptr; static int (*P_scount)(void) = nullptr; @@ -96,8 +82,7 @@ static const RadKernelInfo* row_at(int i) { return P_at ? P_at(i) : nullptr; } static int schemas() { return P_scount ? P_scount() : 0; } static const RadOpSchema* schema_at(int i) { return P_sat ? P_sat(i) : nullptr; } -/* The loader's messages are built with a printf into a string; so are these, so a failure reads - * like the line the engine would have printed. */ +/* printf into a string, as the loader builds its messages. */ static std::string fmt(const char* f, ...) { va_list ap; va_start(ap, f); @@ -140,11 +125,9 @@ static const RadParamSpec* find_param(const RadOpSchema* s, const char* key) { /* ================================================================== the table's own checks * - * Every check here has a failure mode behind it: a constraint on a key the schema does not declare - * (the row matches nothing, silently, and the model falls back to a reference kernel), a tunable - * default outside its axis (the loader refuses the whole plugin), a row whose `op` is spelled for - * another op's schema (one call meaning two things), a description whose operand count disagrees - * with its schema (every case for that op skipped, forever). + * Failure modes: a constraint on an undeclared key (the row silently matches nothing), a tunable + * default outside its axis (the loader refuses the whole plugin), a row whose `op` names another + * op's schema, a description whose operand count disagrees with its schema (every case skipped). */ static void check_table() { const int n = rows(); @@ -167,28 +150,20 @@ static void check_table() { if (!k->launch) fail("row '%s' has no launch", k->name); if (k->init && !k->fini) fail("row '%s' inits without a fini", k->name); if (k->domain != RAD_DOMAIN_DEVICE) fail("row '%s' is not a device row", k->name); - /* No row repacks a weight: the kernel reads the container's stored order, which is the rule that - * stops a plugin quietly demanding its own format. The exception is a class with a name list, and - * the class is the container's quantised weight: codes and scales stored as planes behind one - * operand, which the mapped tier will not place unless a loaded library can read them in place. - * Three rows, one per grid the container uses -- w2a8's {1,group} with a zero, the fp8a8 GEMM's - * {128,128} without, and the lm_head's same form -- each transcribed from the reference's own hook, - * including the case the reference answers nothing for (ref_layout_gemm_q reads zp_grid, and zp_grid - * has no fp8a8 entry). What carries the rule is the pair: every one of these names has a `layout` - * **and** a `relayout`, no row anywhere has an `unrelayout`, and a hook that names a joined layout - * without the writer that produces it is the failure the engine prints at load. A fifth name is a - * rule change, and it should fail here. */ + /* No row repacks a weight; kernels read the container's stored order. The exception is the + * container's quantised weight (codes and scales as planes behind one operand), which the + * mapped tier places only if a loaded library can read it in place. The rows below cover + * w2a8's {1,group} grid with a zero, and the fp8a8 GEMM's and lm_head's {128,128} grid + * without, each transcribed from the reference's hook. Any other name is a rule change and + * should fail here. */ const bool joined = 0 == std::strcmp(k->name, "gemm_nt_q_w2a8_m16") || 0 == std::strcmp(k->name, "logits_gemm_bf16") || 0 == std::strcmp(k->name, "gemm_nt_q_fp8a8_tiled") || 0 == std::strcmp(k->name, "gemm_nt_q_w2a8_tiled"); - /* The query and the writer come as a pair, and the pair is the rule: a row with a hook must - * supply the relayout that produces the form the hook names (abi/rad_abi.h -- a query - * answering RAD_OK is a promise the loader keeps on the row's word), and no row may carry an - * unrelayout, because nothing in this library invents a format a tool would need to invert. - * A hook with a null writer is the failure the engine reports at load -- `could not produce - * 'output.weight' (rad.planes) from fp8_e4m3*bf16[128x128]: unsupported` -- and a relayout - * without a hook is a row repacking a weight nobody asked to have repacked. */ + /* A layout hook and its relayout writer come as a pair (abi/rad_abi.h: a query answering + * RAD_OK promises the loader the writer produces that form; a hook without one fails at + * load). No row may carry an unrelayout, since this library invents no format a tool + * would need to invert. */ if ((k->layout && !joined) || (k->layout && !k->relayout) || (k->relayout && !joined) || (k->relayout && !k->layout) || k->unrelayout) fail("row '%s' declares a layout hook; libr3d stores weights in order", k->name); @@ -207,8 +182,8 @@ static void check_table() { x.key ? x.key : "(null)", k->op); continue; } - /* The selector compares a string constraint against a string parameter and an - * integer one against an integer. A mismatch matches nothing. */ + /* String constraints match string parameters and integer ones integers; a mismatch + * matches nothing. */ if (x.op == RAD_C_IN && p->type != RAD_P_STR) fail("row '%s' matches '%s' with a string list on a non-string parameter", k->name, x.key); @@ -251,21 +226,16 @@ static void check_table() { /* ================================================================== the reference library * - * The loader refuses a plugin whose schema for an op differs from the one the first declarer fixed - * (core/plugin/loader.cpp, `schema_same`), and it refuses the *whole* .so, every row with it. The - * comparison is positional and narrow: parameter count, each parameter's key, type and - * requiredness; operand count, each operand's role and optionality. Operand names and doc strings - * are free, because arguments are positional and names are for diagnostics. - * - * So a schema copied from libref with one operand's role mistyped is a plugin that loads in - * r3d_selftest -- which does not open libref -- and disappears from the engine, with one line in a - * log most people never read. This check is the loader's own comparison, run here, naming the op - * and the slot. + * The loader refuses the whole .so when its schema for an op differs from the first declarer's + * (core/plugin/loader.cpp, `schema_same`). The comparison is positional: parameter count, each + * parameter's key, type and requiredness; operand count, each operand's role and optionality. + * Names and doc strings are free. This repeats that comparison against libref, naming the op and + * the slot, since a mismatch otherwise shows only as one log line at engine load. */ static void check_reference_schemas() { std::printf("== schemas against the reference\n"); - /* The reference library beside the plugin under test, the way the engine's home holds them. */ + /* libref.so beside the plugin under test, as the engine's home holds them. */ std::string path(g_plugin); const size_t slash = path.find_last_of('/'); path = (slash == std::string::npos ? std::string() : path.substr(0, slash + 1)) + "libref.so"; @@ -287,9 +257,7 @@ static void check_reference_schemas() { if (o && o->op && !std::strcmp(o->op, mine->op)) theirs = o; } if (!theirs) { - /* Not a refusal: an op the reference does not serve is an op with nothing to agree - * with, and it is the reason libr3d's rows for a chain libref has no oracle for are - * checked by the selftest's own arithmetic instead. */ + /* Not a refusal: an op the reference does not declare has nothing to agree with. */ skip("'%s' has no schema in the reference, so nothing to compare against", mine->op); continue; } @@ -343,19 +311,11 @@ static void check_reference_schemas() { /* ================================================================== band reachability * - * A row is chosen by matching its constraints against a band's geometry, and the engine's rule - * (core/util/rad_util.cpp, constraint_holds) is that a constraint on a key the geometry lacks does - * not hold, in its own words "a row constraining an optional parameter serves only callers that - * state it, and others get a row without it". The bands an architecture emits carry the parameters - * its graph set, and nothing else, so a row that constrains an optional parameter is a row narrowed - * to the graphs that spell that parameter out. - * - * Nothing in kbench shows this: a fixture case names every parameter the op declares, so the - * constraint is tested against a geometry that has it. A server shows all of it, at startup, as - * "N device band(s) resolved to no kernel" and a model that will not start. So the check is here: - * a constraint on an optional parameter is not an error -- it is how a row says "I serve the form - * that states the parameter" -- but it is a decision, and a row whose author did not make it is a - * row that will silently not serve. + * A constraint on a key the band's geometry lacks does not hold (core/util/rad_util.cpp, + * constraint_holds), and bands carry only the parameters their graph set. So a row that constrains + * an optional parameter serves only graphs that state it. kbench cannot show this, because its + * fixtures name every parameter. Such a constraint is legitimate but must be deliberate, so each one + * is listed here. */ static void check_band_reach() { std::printf("== band reachability\n"); @@ -377,7 +337,7 @@ static void check_band_reach() { const RadOpSchema* o = ra(j); if (o && o->op && !std::strcmp(o->op, k->op)) s = o; } - if (!s) continue; /* the table phase already failed this row */ + if (!s) continue; /* not in the reference: nothing to compare */ for (int ci = 0; ci < k->n_constraints; ++ci) { const RadConstraint& c = k->constraints[ci]; if (!c.key) continue; @@ -399,11 +359,9 @@ static void check_band_reach() { /* ================================================================== the operand descriptions * - * Against the schemas, for one geometry per op taken from the widths a model really has: 4096 - * hidden, 128 head, 11008 intermediate, 128256 vocabulary. A description that returns a count the - * schema disagrees with, a rank of zero, or an extent of zero is a bug in the description or in the - * schema; rad-kbench reports it as a skipped case for every geometry, which is how a broken hook - * hides for years. + * Against the schemas, for one geometry per op at real model widths (4096 hidden, 128 head, 11008 + * intermediate, 128256 vocabulary). A wrong operand count, rank or zero extent is a bug in the + * description or the schema; rad-kbench would only report it as skipped cases. */ static void check_shapes() { /* RadParam is { key, kind, ival, ihi, sval, dval }. */ @@ -439,14 +397,13 @@ static void check_shapes() { PS("act", "silu") } }, { "dequant", { PI("M", 11008), PI("n", 4096), PI("group", 128), PS("dtype", "fp8_e4m3") } }, - { "rmsnorm_quant_fp8", { PI("M", 1792), PI("n", 5120), PI("eps", 1e-5), PI("group", 128), + { "rmsnorm_quant_fp8", { PI("M", 1792), PI("n", 5120), PF("eps", 1e-5), PI("group", 128), PS("dtype", "bf16") } }, { "gemm_nt", { PI("M", 8), PI("N", 11008), PI("K", 4096), PS("dtype", "bf16") } }, { "gemm_nt_q", { PI("M", 8), PI("N", 11008), PI("K", 4096), PI("group", 128), PS("dtype", "fp8a16"), PI("pb1", 128), PI("pb2", 128) } }, - /* The rest are the bands MiniCPM5-2B asks for, in /home/sysadmin/libr3d/bands.txt: the - * model's own widths, not invented ones. The vocab is 130560, the MLP is 6144 wide, the - * head is 128 with 16 heads over 2 KV heads at 16-token blocks. */ + /* The rest are MiniCPM5-2B's bands: vocab 130560, MLP 6144 wide, head 128 with 16 heads + * over 2 KV heads at 16-token blocks. */ { "silu_mul", { PI("M", 1792), PI("n", 6144), PS("dtype", "bf16") } }, { "attn_paged", { PI("q_len", 2048), PI("head_dim", 128), PI("gqa", 8), PI("block_size", 16), PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"), @@ -456,10 +413,8 @@ static void check_shapes() { PI("causal", 0), PI("window", 0), PS("q_dtype", "bf16"), PS("kv_dtype", "fp8_e4m3"), PI("n_head", 16), PI("max_ctx", 4096), PI("max_seqs", 256) } }, - /* The decode band with the context deeper than the query chunk: the walk has to cover keys - * that precede the chunk, which is the only thing in the op a q_len-sized cache cannot - * show. The second is the geometry that found the tile-sharing bug -- a window that starts - * mid-block, over an fp8 cache. */ + /* A context deeper than the query chunk, so the walk covers keys before the chunk; then a + * window that starts mid-block over an fp8 cache, which exercises tile sharing. */ { "attn_paged", { PI("q_len", 7), PI("head_dim", 128), PI("gqa", 8), PI("block_size", 16), PI("causal", 0), PI("window", 0), PS("q_dtype", "bf16"), PS("kv_dtype", "bf16"), PI("n_head", 16), PI("ctx", 4096), @@ -468,9 +423,8 @@ static void check_shapes() { PI("causal", 1), PI("window", 37), PS("q_dtype", "bf16"), PS("kv_dtype", "fp8_e4m3"), PI("n_head", 16), PI("ctx", 512), PI("max_ctx", 4096) } }, - /* The 27B's sliding-window band, in the shape the fixture draws it: the shape hook describes - * the descales as ABSENT, so this is the case where an fp8 cache has no scale plane and the - * reference reads 1.0. It is the geometry kbench caught a refusal on. */ + /* A 27B model's sliding-window band as the fixture draws it: the descales are absent, so an + * fp8 cache has no scale plane and the reference reads 1.0. */ { "attn_paged", { PI("q_len", 1), PI("head_dim", 128), PI("gqa", 4), PI("block_size", 16), PI("causal", 0), PI("window", 2048), PS("q_dtype", "bf16"), PS("kv_dtype", "fp8_e4m3"), PI("n_head", 32), PI("max_seqs", 8), @@ -489,9 +443,8 @@ static void check_shapes() { { "sample_ngram_ban", { PI("M", 2048), PI("n_vocab", 130560) } }, { "sample_mask", { PI("M", 2048), PI("n_vocab", 130560) } }, { "sample_logprobs", { PI("M", 2048), PI("n_vocab", 130560), PI("k", 21) } }, - /* The speculative decoder's band, as MiniCPM5-2B declares it: a 7-token draft block, 16 - * candidates a step, a rank-256 codebook over a 130560-token vocabulary, anchors strided 7 - * apart. The two codebooks are 63.8 MiB each, which is what the op really is. */ + /* MiniCPM5-2B's speculative decoder band: a 7-token draft block, 16 candidates a step, a + * rank-256 codebook over a 130560-token vocabulary (63.8 MiB each), anchors 7 apart. */ { "dflash_select", { PI("M", 256), PI("steps", 7), PI("top_k", 16), PI("rank", 256), PI("n_vocab", 130560), PI("anchor_stride", 7), PS("dtype", "bf16") } }, }; @@ -499,13 +452,8 @@ static void check_shapes() { #undef PF #undef PS - /* The descriptions of the ops whose kernels have not landed: the schemas and the hooks are in - * the library, checked the moment it loads, so a transcription typo is found here and not on the - * day the row lands and kbench skips its cases -- "describes an output differently" is one line - * in a report, and a row nobody exercises is a row nobody tested. */ - /* By symbol name, dlsym'd from the plugin: this program links nothing from the library under - * test -- that is the point of dlopening it -- so a hook is a name and a pointer out of the - * handle, exactly as the rows are. */ + /* Shape hooks for ops with no row in the table, found by symbol name in the plugin, so their + * descriptions are checked even without a kernel. */ static const struct { const char* op; const char* sym; } kHooks[] = { { "silu_mul", "r3d_shape_silu_mul" }, { "attn_paged", "r3d_shape_attn_paged" }, { "row_topk", "r3d_shape_row_topk" }, { "sample_argmax", "r3d_shape_sample_argmax" }, @@ -533,7 +481,7 @@ static void check_shapes() { hook = (int (*)(const RadParam*, int, int, RadOpdDesc*))dlsym(g_h, kHooks[q].sym); if (!hook) { skip("no operand description for '%s' -- no row and no hook", gm.op); continue; } - if (!row) std::printf(" -- '%s': the hook, ahead of its kernel\n", gm.op); + if (!row) std::printf(" -- '%s': operand description from the shape hook (no row)\n", gm.op); bool bad = false; for (int o = 0; o < s->n_operands && !bad; ++o) { @@ -561,23 +509,17 @@ static void check_shapes() { } } -/* ================================================================== the codecs - * - * Against the ABI's host implementations. Exactness is the claim, and it is the claim because the - * widenings are exact (seven mantissa bits into ten, four exponent and three mantissa bits into - * five and ten) and the encoders are mirrors of `rad_plugin.h`, line for line. - */ /* Two floats are the same when their bits are: `a == b` is false for two NaNs, and a codec that - * quiet a NaN the same way the ABI's does is a codec that agrees. */ + * quiets a NaN the way the ABI's does agrees. */ static bool same_float(float a, float b) { return bits_of(a) == bits_of(b); } /* ================================================================== the codecs * - * Against the ABI's host implementations. Exactness is the claim, and it is the claim because the - * widenings are exact (seven mantissa bits into ten, four exponent and three mantissa bits into - * five and ten) and the encoders are mirrors of `rad_plugin.h`, line for line. + * Against the ABI's host implementations, bit for bit: the widenings are exact (seven mantissa bits + * into ten; four exponent and three mantissa bits into five and ten) and the encoders mirror + * `rad_plugin.h`. */ static void check_codecs() { std::printf("== codecs\n"); @@ -587,15 +529,14 @@ static void check_codecs() { for (uint32_t u = 0; u < 0x10000 && !bad; ++u) { const uint16_t b = (uint16_t)u; if (!same_float(bf16_to_f32(b), rad_bf16_to_f32(b))) { ++bad; break; } - /* Encoder against encoder: a NaN's payload is quieted on the way out by both, so a - * round-trip to the original pattern is not the claim. */ + /* Encoder against encoder: both quiet a NaN's payload, so a round trip to the original + * pattern is not the claim. */ if (f32_to_bf16(bf16_to_f32(b)) != rad_f32_to_bf16(rad_bf16_to_f32(b))) { ++bad; break; } } if (bad) fail("bf16: the codecs disagree with rad_plugin.h"); else ok("bf16: 65536 patterns, decode and encode, match rad_plugin.h bit for bit"); - /* f16: the same, subnormals included -- the narrowing keeps them, which the ABI's codec does - * and a naive shift-and-round does not. */ + /* f16: the same, subnormals included (a naive shift-and-round loses them). */ bad = 0; for (uint32_t u = 0; u < 0x10000 && !bad; ++u) { const uint16_t h = (uint16_t)u; @@ -606,13 +547,10 @@ static void check_codecs() { if (bad) fail("f16: the codecs disagree with rad_plugin.h"); else ok("f16: 65536 patterns, both directions, match rad_plugin.h (subnormals included)"); - /* A bf16 pair widened to an f16 pair, in one register, exactly -- the reason the dot2 path is - * sound. Exact over f16's normal range [2^-14, 65504], as r3d_codecs.h states, and the sweep is - * over the patterns in it. Outside, the widening is not exact and is not claimed to be: above - * 65504 it saturates, and below 2^-14 an f16 subnormal's grid is coarser than bf16's, so the - * packing instruction truncates toward zero. Those patterns are counted and named in the - * message, because the number of them -- and the fact that they are the format's range, not a - * bug -- is the thing a reader needs. */ + /* A bf16 pair widened to an f16 pair in one register, which the dot2 path relies on. Exact over + * f16's normal range [2^-14, 65504] (r3d_codecs.h), which is what is swept. Outside it the + * widening saturates above 65504 and truncates toward zero below 2^-14, where f16's subnormal + * grid is coarser than bf16's; those patterns are counted in the message. */ bad = 0; int inside = 0, outside = 0; for (uint32_t u = 0; u < 0x10000 && !bad; ++u) { @@ -630,8 +568,8 @@ static void check_codecs() { else ok("bf16 -> f16 exact over the %d patterns in f16's normal range (the other %d saturate " "or truncate as the format says they must)", inside, outside); - /* E4M3, both directions, over every code. The widening to f16 is exact for every code: e4m3 has - * four exponent and three mantissa bits, f16 five and ten, and 448 is well inside f16. */ + /* E4M3, both directions, over every code, and the exact widening to f16 (448 is well inside + * f16's range). */ bad = 0; for (uint32_t c = 0; c < 256 && !bad; ++c) { if (!same_float(e4m3_to_f32((uint8_t)c), rad_fp8e4m3_to_f32((uint8_t)c))) { ++bad; break; } @@ -645,8 +583,8 @@ static void check_codecs() { if (bad) fail("e4m3: the codecs disagree with rad_plugin.h, or the widening is not exact"); else ok("e4m3: 256 codes both ways, and the f16 widening exact, match rad_plugin.h"); - /* The encoder over the cases that break a naive one: saturation at 448, the subnormals below - * 2^-6, the sign of zero, NaN, and the values a scale lands on. */ + /* The encoder over the cases that break a naive one: saturation at 448, subnormals below 2^-6, + * the sign of zero, NaN, and typical scale values. */ bad = 0; const float sweep[] = { 0.0f, -0.0f, 1.0f / 512, 1.0f / 1024, 1.0f / 6, 0.33f, 1.0f, 1.7f, 2.0f, 3.0f, 447.0f, 448.0f, 449.0f, 1024.0f, 1e30f, -1e30f, @@ -670,18 +608,17 @@ static void check_codecs() { if (bad) fail("int8: the encoder disagrees with rad_round_even_sat"); else ok("int8 encoder: 4804 values, every tie in the band, match rad_round_even_sat"); - /* dot2's order. The device instruction folds the products with guard bits, so the host path is - * the reference's arithmetic and this checks only that the pairs are read low-then-high: the - * GEMMs' accumulation order is checked by rad-kbench against libref. */ + /* dot2's operand order only: the device instruction folds the products with guard bits, so + * this checks that pairs are read low-then-high; accumulation order is rad-kbench's to check. */ float acc = 0.0f; const uint32_t a = f16x2_pack(1.5f, -2.5f), b = f16x2_pack(4.0f, 4.0f); acc = dot2_f16x2(a, b, acc); if (acc != 1.5f * 4.0f + -2.5f * 4.0f) fail("dot2: the pair is not read low-then-high"); else ok("dot2: the pair is read low-then-high, into the accumulator it is handed"); - /* The bf16 store a kernel's epilogue uses: two values, one dword, round to nearest even, the - * high half in the high half. A `v_perm` picking the wrong bytes shows up here and not in a - * kernel's output, where a swapped pair looks like a plausible tensor. */ + /* The epilogue's bf16 store: two values, one dword, round to nearest even, the high value in + * the high half. A `v_perm` picking the wrong bytes shows here; in a kernel's output a swapped + * pair looks plausible. */ bad = 0; for (int i = -500; i < 500 && !bad; ++i) { const float lo = (float)i * 0.001f, hi = (float)i * -0.002f; @@ -704,20 +641,18 @@ struct Case { RadTensor t[MAX_OPD]; RadParam p[32]; std::vector dev; - std::vector host; /* pinned operands: read on the host, read by the kernel too */ + std::vector host; /* pinned operands, read by both host and kernel */ std::vector words; /* the strings out.sval points into; reserved in make_params */ int n_p = 0; }; /* ================================================================== the lane helpers, on the card * - * Every wave-sum in the library is five rounds of a butterfly over lane shuffles, and the - * arithmetic that rides on a shuffle is invisible to a codec sweep: `d += (double)f((unsigned long - * long)d)` moves a *value* where a bit pattern is wanted, and a wave of fractions then sums to 1 -- - * which is a bug this file's own predecessor shipped, in the logprobs sum, and which showed up as - * 40% of a row's probability mass missing at one shape. So the card runs the butterflies through - * `r3d_lanes_check` (r3d_sample_pre_f32.hip) and every lane of every wave is compared with a host - * emulation of the same five rounds, in the same order. + * Every wave-sum in the library is five butterfly rounds over lane shuffles, and an error there is + * invisible to a codec sweep: `d += (double)f((unsigned long long)d)` moves a value where a bit + * pattern is wanted, and a wave of fractions sums to an integer. The device runs the butterflies + * through `r3d_lanes_check` (r3d_sample_pre_f32.hip) and every lane of every wave is compared with + * a host emulation of the same five rounds in the same order. */ static void check_lanes() { std::printf("== lane helpers\n"); @@ -800,9 +735,8 @@ static uint32_t xorshift(uint32_t& s) { return s; } -/* Fill a host plane per its description. "Normals" is a sum of four uniforms: a kernel's - * arithmetic is exercised by any value that is not a special case, and the special cases are what - * the hand-written cases and rad-kbench's sweeps are for. */ +/* Fill a host plane per its description. "Normals" are a sum of four uniforms: any non-special + * value exercises the arithmetic, and special cases are rad-kbench's. */ static void fill_plane(const RadOpdDesc& d, uint8_t* p, size_t nel, uint32_t seed) { uint32_t s = seed ? seed : 1u; const size_t nbyte = d.dtype == RAD_U2 ? nel / 4 @@ -823,8 +757,8 @@ static void fill_plane(const RadOpdDesc& d, uint8_t* p, size_t nel, uint32_t see return; } if (d.dtype == RAD_I4) { - /* Two signed codes a byte, the low nibble first: both grids' -7..7 draw, stored in - * two's complement, which is the low four bits. */ + /* Two signed codes a byte, low nibble first, drawn in -7..7 and stored as the low four bits + * of two's complement. */ for (size_t j = 0; j < nel / 2; ++j) { double v0 = ((double)xorshift(s) / 4294967296.0) * 2.0 - 1.0; double v1 = ((double)xorshift(s) / 4294967296.0) * 2.0 - 1.0; @@ -835,8 +769,8 @@ static void fill_plane(const RadOpdDesc& d, uint8_t* p, size_t nel, uint32_t see return; } if (d.dtype == RAD_FP4E2M1) { - /* Two e2m1 codes a byte, drawn independently: all 16 values, so the unpack's magnitude - * and sign paths are both exercised. */ + /* Two e2m1 codes a byte over all 16 values, exercising the unpack's magnitude and sign + * paths. */ for (size_t j = 0; j < nel / 2; ++j) { const uint8_t lo = (uint8_t)(xorshift(s) & 0xFu); const uint8_t hi = (uint8_t)(xorshift(s) & 0xFu); @@ -864,21 +798,16 @@ static void fill_plane(const RadOpdDesc& d, uint8_t* p, size_t nel, uint32_t see } } -/* The geometry a row is run at: the band's bounds where the row constrains them, the widths a - * model has elsewhere. Reading the row's own constraints is what makes this a test of the - * constraint table and not of a geometry the table happens to admit. */ +/* The geometry a row runs at: the row's constraint values where it has them, real model widths + * elsewhere, so the constraint table itself is what is tested. */ static void make_params(Case& c, const RadKernelInfo* k, const RadOpSchema* s) { c.words.reserve(32); /* more parameters than any op declares, so no string ever moves */ for (int q = 0; q < s->n_params && c.n_p < 32; ++q) { const RadParamSpec& sp = s->params[q]; - /* Only the parameters the geometry has to carry. The engine passes the graph's parameters - * with their ranges collapsed, and an optional parameter the graph did not set is simply - * not in the list: the kernel's own default is then the one libref's `p_*` default is. A - * selftest that filled every optional slot with a value would be testing a geometry no - * graph produces -- and for rope, whose optional `sections` string switches the position - * plane to one row per component, it would be testing a mode the row's constraints - * exclude. Constrained parameters are always passed: the constraint states the row's band, - * so its value is the row's own claim. */ + /* Only required and constrained parameters, as the engine passes them: an optional + * parameter the graph did not set is absent, and the kernel uses libref's `p_*` default. + * Filling every optional slot would test geometries no graph produces (for rope, the + * `sections` string would switch to a mode the row's constraints exclude). */ bool constrained = false; for (int ci = 0; ci < k->n_constraints && !constrained; ++ci) if (k->constraints[ci].key && sp.key && !std::strcmp(k->constraints[ci].key, sp.key)) @@ -911,18 +840,15 @@ static void make_params(Case& c, const RadKernelInfo* k, const RadOpSchema* s) { if (sp.key && !std::strcmp(sp.key, "from")) out.sval = "bf16"; if (sp.key && !std::strcmp(sp.key, "to")) out.sval = "f32"; if (sp.key && !std::strcmp(sp.key, "act")) out.sval = "silu"; - /* A constraint's own value wins: it is the band the row is compiled for, and C_IN spells - * the whole list. A list takes its first word. */ + /* A constraint's own value wins; a C_IN list takes its first word. */ for (int ci = 0; ci < k->n_constraints; ++ci) { const RadConstraint& x = k->constraints[ci]; if (!x.key || !sp.key || std::strcmp(x.key, sp.key)) continue; if (x.op == RAD_C_EQ && sp.type == RAD_P_STR && x.sval) out.sval = x.sval; if ((x.op == RAD_C_EQ || x.op == RAD_C_GE) && sp.type == RAD_P_INT) out.ival = x.ival; if (x.op == RAD_C_IN && sp.type == RAD_P_STR && x.sval && x.sval[0]) { - /* The band's first word. The words outlive the parameter list, so they live in a - * vector that is reserved once: a string built per constraint and pointed at from - * out.sval is a pointer to storage the next constraint reuses, and a row with two - * string constraints reads the second one's value into the first's key. */ + /* out.sval must outlive the loop, so the words live in c.words, reserved once so + * no reallocation moves them. */ c.words.emplace_back(x.sval); std::string& w = c.words.back(); const size_t sp0 = w.find(' '); @@ -936,19 +862,17 @@ static void make_params(Case& c, const RadKernelInfo* k, const RadOpSchema* s) { /* ------------------------------------------------------------------ a row with no shape hook * - * `gemm_q_shape` declines w2a8 for a good reason: the container stores the weight's scale and zero - * as two planes behind the one `b_scale` operand, and a RadOpdDesc names one dtype and one extent - * set, so it cannot describe that. A hook that named only the byte count would have the tool fill a - * container header with random bytes, and the kernel's correct refusal would be reported as a bug. - * So the row's `opd_shape` is null, kbench names the skip, and this is the row's coverage: the band - * MiniCPM5-2B asks for, with the joined plane built by rad_planes_relayout exactly as - * r3d_gemm_nt_q_w2a8_driver.cpp builds it, so the card test and the driver cannot drift apart. */ + * `gemm_q_shape` declines w2a8: the container stores scale and zero as two planes behind the one + * `b_scale` operand, and a RadOpdDesc names one dtype and extent set. A byte-count-only hook would + * fill a container header with random bytes. So the row's `opd_shape` is null and this builds its + * case by hand at MiniCPM5-2B's band, with the joined plane built by rad_planes_relayout as + * r3d_gemm_nt_q_w2a8_driver.cpp builds it. */ static int build_w2a8(Case& c, const RadOpSchema* s) { #define W_PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } #define W_PS(k, v) { (k), RAD_P_STR, 0, 0, (v), 0.0 } const long long M = 16, N = 130560, K = 2048, group = 128, G = K / group; if (s->n_operands != 7) { fail("w2a8: the schema has %d operands, not 7", s->n_operands); return 1; } - c.n_p = 0; /* the band, not the constraint table's minimums */ + c.n_p = 0; /* the model's band, not the constraint minimums */ const RadParam pp[] = { W_PI("M", M), W_PI("N", N), W_PI("K", K), W_PI("group", group), W_PS("dtype", "w2a8") }; for (const RadParam& q : pp) c.p[c.n_p++] = q; @@ -992,12 +916,9 @@ static int build_w2a8(Case& c, const RadOpSchema* s) { fail("w2a8: rad_planes_relayout refused"); return 1; } - /* Slots in the schema's order: a, a_scale, b, b_scale (the joined blob), y, a_sum. y is the - * output and it is pre-filled with a bf16 NaN: a kernel that never launches leaves its status - * RAD_OK behind and the caller's bytes in the plane, and a plane of the caller's own zeros is - * finite, so only a NaN fill says the row ran. */ - /* Schema order: a, a_scale (optional), b, b_scale, y, a_sum (optional), b_ref (an absent - * weight: a null tensor is what an omitted optional means to the shim). */ + /* Schema order: a, a_scale, b, b_scale (the joined blob), y, a_sum, b_ref (absent: a null + * tensor). y is pre-filled with a bf16 NaN, since a shim that returns RAD_OK without launching + * would otherwise leave finite bytes behind. */ struct Slot { long long rows, cols; uint32_t dt; int nan; } q[7] = { { M, K, RAD_I8, 0 }, { M, 1, RAD_F32, 0 }, { N, K, RAD_U2, 0 }, { jb, 1, RAD_U8, 0 }, { M, N, RAD_BF16, 1 }, { G, 16, RAD_F32, 0 }, { 0, 0, RAD_F32, 0 } }; @@ -1022,16 +943,11 @@ static int build_w2a8(Case& c, const RadOpSchema* s) { uint16_t* b16 = (uint16_t*)h.data(); for (size_t i = 0; i < bytes / 2; ++i) b16[i] = 0x7fc0u; } - /* The joined operand stays on the host: the shim reads its header where it lies, which is - * the mapped tier the engine puts a joined weight on, and a device pointer there is a null - * header and a refused geometry. The driver hands it over the same way. The allocation is - * left standing -- this process is short-lived and one blob per run. */ void* d = nullptr; if (o == 3) { - /* Pinned host memory, the mapped tier's shape: the shim reads this operand's header on - * the host, the kernel reads the same bytes as a device pointer, and plain malloc is - * not device-addressable -- it faults with 700. hipHostMalloc is valid on both sides, - * which is what the engine's container mapping gives a joined weight. */ + /* The joined operand is pinned host memory, as the engine's mapped tier holds a joined + * weight: the shim reads its header on the host and the kernel reads the same bytes. + * Plain malloc is not device-addressable. */ if (hipHostMalloc(&d, bytes, 0) != hipSuccess) { fail("w2a8: hipHostMalloc(%zu) failed", bytes); return 1; } c.dev.push_back(d); c.host.push_back(d); @@ -1065,8 +981,7 @@ static int run_row(int i) { skip("built without the HIP runtime: no device run"); return 0; #else - /* No card is not a failure: the static phase above is a third of what this program checks, and - * a build machine, a container and the CI job that builds the plugin all run it without one. */ + /* No device is a skip, not a failure: build machines and CI run the static phase alone. */ int ndev = 0; if (hipGetDeviceCount(&ndev) != hipSuccess || ndev == 0) { skip("no device visible"); @@ -1104,13 +1019,10 @@ static int run_row(int i) { : (size_t)nel * dt_bytes(d.dtype); std::vector h(bytes ? bytes : 1); fill_plane(d, h.data(), (size_t)nel, 0x9E3779B9u + (uint32_t)o * 7919u); - /* Standing to-do, measured and not shipped: filling every OUT plane with the dtype's NaN -- - * which is what says a row that returns RAD_OK without launching has left the caller's bytes - * in the plane, the failure the attention unit's third bug is -- works for 66 of the 68 rows - * and, in the forked child, kills `quant_act_i8_bf16` and `sample_logprobs_f32` on signal 11 - * while both run clean in-process (`--case`), and both write planes the reference pads. It - * is the right check, it needs the padded-plane story finished, and the hand-built geometry - * below already does it for the row whose coverage is this file. */ + /* TODO: pre-fill output planes with the dtype's NaN, to catch a shim that returns RAD_OK + * without launching. Doing so makes `quant_act_i8_bf16` and `sample_logprobs_f32` die on + * signal 11 in the spawned child (both pass with `--case`); both write planes the + * reference pads. build_w2a8 already NaN-fills its output. */ void* p = nullptr; if (hipMalloc(&p, bytes) != hipSuccess) { fail("hipMalloc(%zu) failed", bytes); return 1; } c.dev.push_back(p); @@ -1150,9 +1062,7 @@ launched: skip("the shim declines this geometry (%d)", rc); } else if (rc != RAD_OK) { fail("launch returned %d", rc); - /* The band, spelled out: a shim's mapped code says what kind of answer it gave, not what - * it was given, and the difference between a launch that failed and a geometry nobody - * intended is in the numbers. */ + /* Print the geometry, since the return code alone does not say what the shim was given. */ for (int i = 0; i < c.n_p; ++i) if (c.p[i].kind == RAD_P_STR) std::printf(" param %s = %s\n", c.p[i].key, c.p[i].sval ? c.p[i].sval : "(null)"); @@ -1162,7 +1072,7 @@ launched: const RadTensor& t = c.t[o]; std::printf(" operand %d '%s' dt=%u rank=%u data=%p", o, s->operands[o].name, t.dtype, t.rank, t.data); - for (uint32_t r = 0; r < t.rank; ++r) std::printf(" %lld/%lld", t.shape[r], t.stride[r]); + for (uint32_t r = 0; r < t.rank; ++r) std::printf(" %lld/%lld", (long long)t.shape[r], (long long)t.stride[r]); std::printf("\n"); } ret = 1; @@ -1175,16 +1085,13 @@ launched: if (s->operands[o].role == RAD_OPD_IN) continue; const RadTensor& t = c.t[o]; if (!t.data) continue; - /* A joined plane lives where the mapped tier puts it: pinned host bytes the shim reads - * on the host and the kernel reads over PCIe. It is not a device buffer, so there is - * nothing to copy back, and its contents are the container's, not the row's work. */ + /* A joined plane is pinned host memory holding the container's bytes, not the row's + * output: nothing to read back. */ if (std::find(c.host.begin(), c.host.end(), t.data) != c.host.end()) continue; ++outs; long long nel = 1; for (uint32_t r = 0; r < t.rank; ++r) nel *= t.shape[r]; - /* Sub-byte planes are counted in codes, not bytes: a U2 tensor of 267M codes is - * 66.8 MB on the card, and asking the runtime for 267 MB of it is an out-of-range - * copy, not a large one. */ + /* Sub-byte planes are counted in codes, not bytes (a U2 code is a quarter byte). */ const size_t bytes = t.dtype == RAD_U2 ? (size_t)(nel / 4) : (t.dtype == RAD_U4 || t.dtype == RAD_I4 || t.dtype == RAD_FP4E2M1) ? (size_t)(nel / 2) @@ -1207,24 +1114,20 @@ launched: if (v != v) ++nan; else if (!(v > -1e31f && v < 1e31f)) ++big; } - /* An infinity is the sampler's contract, not a broken number: a dropped candidate is - * `cand_idx` -1 and `cand_val` -inf, a narrowing stage drops by writing -inf, the mask - * and the ban write -inf into the logits, and a slot row_topk cannot fill is -inf. A - * NaN is nobody's contract, so it stays a failure everywhere. */ + /* -infinity is the sampler's contract (a dropped or unfilled candidate, a masked or + * banned logit, an unfilled row_topk slot); a NaN is always a failure. */ const bool sentinel = (k->family && 0 == std::strcmp(k->family, "sample")) || (k->op && 0 == std::strcmp(k->op, "row_topk")); - /* Two planes carry the reference's grid rather than the row's work: `asum`, the int8 - * activation's row sums padded to a 16-row grid, and `stats`, the quantiser's per-group - * statistics. The row writes the rows it was given and leaves the pad, and with outputs - * pre-filled NaN the pad is NaN by construction. Named planes only -- NaN anywhere else - * is exactly the silent no-op the fill exists to find. */ + /* Two planes are padded to the reference's grid: `asum`, the int8 activation's row sums on + * a 16-row grid, and `stats`. The row leaves the pad unwritten, so a NaN there is not + * the row's work. Named planes only; NaN anywhere else is a failure. */ const bool padded = s->operands[o].name && (0 == std::strcmp(s->operands[o].name, "asum") || 0 == std::strcmp(s->operands[o].name, "stats")); if (nan && padded) { ok("ran, %d output plane%s read back with %d pad NaN of %lld on '%s' (the " - "reference's grid, not the row's work)", outs, outs == 1 ? "" : "s", nan, nan == 1 - ? "" : "s", nel, s->operands[o].name); + "reference's grid, not the row's work)", outs, outs == 1 ? "" : "s", nan, + nel, s->operands[o].name); } else if (nan) { fail("operand %d ('%s'): %d NaN of %lld", o, s->operands[o].name, nan, nel); ret = 1; } else if (big && !sentinel) { @@ -1240,16 +1143,18 @@ launched: } if (scratch) (void)hipFree(scratch); - for (void* p : c.dev) (void)hipFree(p); + for (void* p : c.dev) { + if (std::find(c.host.begin(), c.host.end(), p) != c.host.end()) (void)hipHostFree(p); + else (void)hipFree(p); + } return ret; #endif } /* ================================================================== main */ int main(int argc, char** argv) { - /* A row that dies takes the line it was printing with it, and knowing which row died is the - * whole point of the census: stdout is unbuffered, so the last line is the last thing that - * worked. Redirecting the output to a file is exactly when the buffering would hide it. */ + /* Unbuffered stdout, so when a row dies the last line printed is the last thing that worked, + * even when output goes to a file or pipe. */ std::setvbuf(stdout, nullptr, _IONBF, 0); const char* path = nullptr; for (int i = 1; i < argc; ++i) { @@ -1262,7 +1167,7 @@ int main(int argc, char** argv) { if (!path) { std::fprintf(stderr, "r3d_selftest: no plugin given\n"); return 2; } g_plugin = path; - /* dlopen, not link: an undefined symbol in the .so must be this program's failure. */ + /* dlopen, not link, so an undefined symbol in the .so is reported here. */ void* h = dlopen(path, RTLD_NOW | RTLD_LOCAL); if (!h) { std::fprintf(stderr, "r3d_selftest: %s\n", dlerror()); return 2; } g_h = h; diff --git a/libr3d/r3d_shapes.cpp b/libr3d/r3d_shapes.cpp index 4ce8ca37..f7605847 100644 --- a/libr3d/r3d_shapes.cpp +++ b/libr3d/r3d_shapes.cpp @@ -1,45 +1,37 @@ /* r3d_shapes.cpp -- the extent and content domain of each operand of an op at a geometry. * - * This is libr3d's side of the `RadShapeFn` hook: the component that reads an operand is the one - * that knows its extent. The hand-written table in `tools/` describes the ops it was written - * against; a row that exists only here is invisible to it, and a tool that cannot size an operand - * cannot call the op cold. So correctness checks, benchmarks and the coverage census reach these - * rows through this hook. + * libr3d's side of the `RadShapeFn` hook. The component that reads an operand knows its extent, + * and a row that exists only here is invisible to the hand-written table in `tools/`. Correctness + * checks, benchmarks and the coverage census size these rows through this hook. * - * The authority for every extent is the shim, not the prose or the row table. Each `r3d_rad_*` - * entry point unpacks `RadArgs.t[i]` into extents and pitches; if a shim passes `x->shape[1]` as - * `n`, that is what the operand is. Each group names its unit, and a change to a shim's contract - * must be mirrored here. + * The shim is the authority for every extent: each `r3d_rad_*` entry point unpacks `RadArgs.t[i]` + * into extents and pitches, and a change to a shim's contract must be mirrored here. * - * Content matters as much as size. A token id gathers a row of a codebook, a KV slot indexes + * Content matters as much as size. A token id gathers a codebook row, a KV slot indexes * n_blocks * block_size positions, a block-table entry indexes n_blocks. Drawn from the wrong - * range, such an operand tests the kernel's out-of-range handling instead of its arithmetic, and a - * scatter whose indices collide is a race the parallel rerun rightly reports as a failure. - * `RAD_FILL_INDEX` with an explicit `idx_max` states each range, and `RAD_OPD_F_IDX_UNIQUE` marks - * the scatters that need distinct destinations. + * range, such an operand tests out-of-range handling instead of arithmetic, and colliding scatter + * indices are a race. `RAD_FILL_INDEX` with an explicit `idx_max` states each range, and + * `RAD_OPD_F_IDX_UNIQUE` marks scatters that need distinct destinations. * * ============================================================ rows with no description * * A decline is a real answer: the caller skips and counts the case, where an invented extent - * yields a meaningless pass. These rows carry a null `opd_shape`: + * yields a meaningless pass. * * gemm_nt_q at a quantised `a` whose scale plane the row does not name - * Not present in libr3d: both quantised rows state their activation dtype in `dtype`, so - * `a` is bf16 against an fp8 weight (fp8a16) or i8 against an i8 weight (i8a8), and both are - * described below. The case is listed here because it is the one libr4d declines, and a - * reader comparing the two files will look for the difference. + * Does not arise here (libr4d declines it): both quantised rows state their activation + * dtype in `dtype`, so `a` is bf16 against fp8 (fp8a16) or i8 against i8 (i8a8). * * rope at a multi-component mode - * mrope, imrope and axial take one position per component, component-major, and the - * component count comes from the `sections` string. libr3d's kernel implements neox and gptj - * and its row's constraints say so, so a geometry with `sections` set is never routed here. + * mrope, imrope and axial take one position per component, component-major, with the count + * from `sections`. libr3d's kernel implements neox and gptj only and its row's constraints + * say so, so a geometry with `sections` set is never routed here. * - * No tuned axis is read here: this plugin's axes (split counts, wave counts, the streaming mode) - * change how a kernel walks its operands, not their extents. An axis that did would be read from - * `p`, where the core appends the chosen point. + * No tuned axis is read: this plugin's axes (split counts, wave counts, the streaming mode) change + * how a kernel walks its operands, not their extents. An axis that did would be read from `p`, + * where the core appends the chosen point. * - * Pure host code (no r3d.h, no HIP), like r3d_rows.cpp, so the tables compile and can be read - * without ROCm. + * Pure host code (no r3d.h, no HIP), like r3d_rows.cpp, so it compiles without ROCm. */ #include @@ -52,12 +44,12 @@ namespace { /* ==================================================================== building a description * * Each op builds its whole operand list in schema order and hands out the one asked for, so the - * count can be checked by eye against the schema in r3d_rows.cpp (the tool also checks it against + * count can be checked against the schema in r3d_rows.cpp (the tool checks * `RadOpSchema::n_operands`). */ /* A plain operand of up to four extents. A trailing 0 ends the shape; zero is never a legal - * extent (`pick` refuses one), so it cannot be mistaken for a real one. */ + * extent (`pick` refuses one). */ RadOpdDesc opd(uint32_t dt, int64_t d0, int64_t d1 = 0, int64_t d2 = 0, int64_t d3 = 0) { RadOpdDesc d{}; d.dtype = dt; @@ -83,8 +75,7 @@ RadOpdDesc opd_idx(int64_t d0, int64_t idx_max, int64_t konst = -1, uint32_t fla return d; } -/* An optional operand this description does not pass. One entry per schema operand is still - * emitted, so absence needs a spelling; to the ABI it means a null RadTensor. */ +/* An optional operand this description does not pass; to the ABI it means a null RadTensor. */ RadOpdDesc opd_none() { RadOpdDesc d{}; d.idx_const = -1; @@ -92,16 +83,13 @@ RadOpdDesc opd_none() { return d; } -/* Restricts the fill to (0, 1); `RAD_FILL_SIGMOID` is the ABI's only such draw. A scale plane drawn - * from a normal is as likely to be negative as positive, and a negative descale inverts the sign of - * an entire quantised block. */ +/* Restricts the fill to (0, 1); `RAD_FILL_SIGMOID` is the ABI's only such draw. A scale drawn from + * a normal is negative half the time, and a negative descale inverts a whole quantised block. */ RadOpdDesc in_unit(RadOpdDesc d) { d.fill = RAD_FILL_SIGMOID; return d; } -/* Hands out operand `operand` of a list after checking the whole list, so a geometry missing a - * parameter declines every operand rather than describing a few and declining the rest. A - * non-positive extent means a needed parameter was absent or zero: RAD_E_UNSUPPORTED, not - * RAD_E_SHAPE, which would read as a tool bug. An index outside the list is a bug here or in the - * schema, reported as RAD_E_SHAPE. */ +/* Hands out operand `operand` after checking the whole list, so a geometry missing a parameter + * declines every operand. A non-positive extent means a needed parameter was absent or zero + * (RAD_E_UNSUPPORTED); an index outside the list is a bug here or in the schema (RAD_E_SHAPE). */ int pick(RadOpdDesc* out, int operand, const RadOpdDesc* list, int n) { if (!out || !list || n <= 0) return RAD_E_INVAL; for (int i = 0; i < n; ++i) { @@ -119,12 +107,11 @@ int pick(RadOpdDesc* out, int operand, const RadOpdDesc* list, int n) { /* ==================================================================== parameters * - * `M` and the other ranged parameters read as the band's bound, not any one step's row count (as - * in every shim here): buffers must hold the whole band the kernel was selected for. + * `M` and the other ranged parameters read as the band's bound, not one step's row count: buffers + * must hold the whole band the kernel was selected for. * - * Not r3d_pgeti_or(): that reads RAD_P_INT only, which suits a launch (every range has collapsed - * by then), but this hook can see ranges still open. rad_param_getdim (ABI, shared with libr4d) - * reads a RAD_P_RANGE as its high bound. + * Not r3d_pgeti_or(), which reads RAD_P_INT only; this hook can see ranges still open, and + * rad_param_getdim reads a RAD_P_RANGE as its high bound. */ int64_t gi(const RadParam* p, int n_p, const char* k, int64_t dflt) { return rad_param_getdim(p, n_p, k, dflt); @@ -134,10 +121,9 @@ const char* gs(const RadParam* p, int n_p, const char* k) { return rad_param_gets(p, n_p, k, nullptr); } -/* The activation dtype, from `dtype` and its attention spellings; bf16 when the geometry names - * none. A quantisation-scheme string ("fp8a16", "w8a16") is not a dtype and lands on bf16, which - * is what the quantised rows use it to mean: the scheme picks the weight's dtype, the row states - * the activation's. */ +/* The activation dtype, from `dtype` or `q_dtype`; bf16 when the geometry names none. A + * quantisation-scheme string ("fp8a16", "w8a16") is not a dtype and lands on bf16, which is what + * the quantised rows mean by it: the scheme picks the weight's dtype. */ uint32_t act_dt(const RadParam* p, int n_p) { const char* s = gs(p, n_p, "dtype"); if (!s) s = gs(p, n_p, "q_dtype"); @@ -161,8 +147,8 @@ int64_t scale_groups(int64_t n, int64_t group) { extern "C" { -/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. The gain is described at its full width; the - * form with no gain at all is a hand case, since a null optional operand is not a fill domain. */ +/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. The gain is described at full width; the + * form with no gain is a hand case, since a null optional operand is not a fill domain. */ int r3d_shape_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -170,8 +156,7 @@ int r3d_shape_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) R3D_PICK(list); } -/* The two-pass form. `b` is optional and passed: the biased form covers strictly more code, and a - * null optional operand is not a fill domain a tool can draw. */ +/* The two-pass form. `b` is optional and passed: the biased form covers strictly more code. */ int r3d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -180,8 +165,7 @@ int r3d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out } /* add / mul share a schema and a description. `b` is described at full extent; the row-broadcast - * form is not described, since a buffer of n elements against M rows cannot be told from a shape - * bug by a tool that sizes by shape alone. */ + * form is not, since a tool that sizes by shape alone cannot tell it from a shape bug. */ static int binary_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -196,9 +180,8 @@ int r3d_shape_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { return binary_shape(p, n_p, operand, out); } -/* y = act(gate) * up over two [M, n] operands. The fused [M, 2n] form is the one the model - * issues; describing it here would be a second spelling of a geometry the row's `n` is about, so - * the two halves are described as the kernel sees them. */ +/* y = act(gate) * up over two [M, n] operands, the halves as the kernel sees them (the model + * issues the fused [M, 2n] form). */ int r3d_shape_act_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { return binary_shape(p, n_p, operand, out); } @@ -236,7 +219,7 @@ int r3d_shape_softmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return unary_shape(p, n_p, operand, out); } -/* y = x * s. `s` is one element, broadcast over everything; a row of them would be a different op. */ +/* y = x * s with `s` a single broadcast element. */ int r3d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -244,7 +227,7 @@ int r3d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { R3D_PICK(list); } -/* y = value. The only operand is the output, so a case's whole content is the kernel's. */ +/* y = value. The only operand is the output. */ int r3d_shape_fill(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -256,10 +239,9 @@ int r3d_shape_fill(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { * r3d_model_bf16.hip */ -/* In-place rotary over a fused qkv row: n_head q heads, then n_head_kv each of k and v. The - * positions are drawn over the row count, which for a single step is its own positions; a step - * crossing a context boundary is a hand case, since a fill cannot spell "contiguous from an - * arbitrary start". */ +/* In-place rotary over a fused qkv row: n_head q heads, then n_head_kv each of k and v. Positions + * are drawn over the row count; positions contiguous from an arbitrary start are a hand case, + * since no fill domain spells them. */ int r3d_shape_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); @@ -274,8 +256,7 @@ int r3d_shape_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { } /* K and V into a paged cache. Two blocks of slack over the tokens, so the slot mapping is not a - * dense prefix and the block index matters. Only the cache takes `kv_dtype`: k and v are bf16 - * activations whatever the cache stores. */ + * dense prefix. Only the cache takes `kv_dtype`; k and v are always bf16. */ int r3d_shape_kv_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); @@ -311,8 +292,8 @@ int r3d_shape_embed_lookup(const RadParam* p, int n_p, int operand, RadOpdDesc* R3D_PICK(list); } -/* The source is 4x the gathered height so the gather is not the identity, which would pass while - * broken; `idx` draws over those 4M rows. */ +/* The source is 4x the gathered height so the gather is not the identity; `idx` draws over those + * 4M rows. */ int r3d_shape_gather_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -320,9 +301,9 @@ int r3d_shape_gather_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* o R3D_PICK(list); } -/* Onto exactly M rows a scatter is a permutation, which a kernel ignoring `idx` could pass, so the - * destination is 4x the scattered height and unnamed rows must come back unchanged. The indices are - * distinct: two rows drawing one destination is a race. */ +/* The destination is 4x the scattered height, since onto exactly M rows a kernel ignoring `idx` + * could pass; unnamed rows must come back unchanged. Indices are distinct, as a shared destination + * is a race. */ int r3d_shape_scatter_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -348,14 +329,10 @@ int r3d_shape_quant_act_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* R3D_PICK(list); } -/* The int8 twin, with the optional row-sum plane beside it. `asum` is described whenever `group` - * divides n, so a case checks the row sums as well; it is group-major, the layout libref's - * quant_act_i8 writes. */ -/* The per-row int8: one scale per row, in a [M, 1] plane (the reference writes it at pitch 1, so a - * plane with more room is legal and this states the tightest one), and the optional `asum` described - * whenever `group` divides n, so a case exercises the row sums too. `q` is in the step order -- - * described by its extent, because a description states a plane's size and content domain, not a - * permutation; the row's `shape` prose names the order. */ +/* The per-row int8: one scale per row in the tightest [M, 1] plane (the reference writes it at + * pitch 1). The optional `asum`, group-major as libref's quant_act_i8 writes it, is described + * whenever `group` divides n so a case checks the row sums too. `q` is in the step order; a + * description states size and content domain, not a permutation, so it is described by extent. */ int r3d_shape_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), g = gi(p, n_p, "group", 0); @@ -368,8 +345,7 @@ int r3d_shape_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* R3D_PICK(list); } -/* The per-group int8, the activation the i8a8 GEMM reads: the fp8 quantiser's extents at int8 codes - * and a 127 denominator. */ +/* The per-group int8 the i8a8 GEMM reads: the fp8 quantiser's extents with int8 codes. */ int r3d_shape_quant_act_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -395,9 +371,8 @@ int r3d_shape_gated_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDes R3D_PICK(list); } -/* y = code * scale. `dtype` names the code: E4M3 and E5M2 are the checkpoint's fp8, i8 the int8 - * twin. The scale is a dequant multiplier, so its draw is restricted to (0, 1) -- a normal draw is - * as likely to be negative, and a negative scale inverts a whole block. */ +/* y = code * scale. `dtype` names the code: E4M3 or E5M2 (checkpoint fp8) or i8. The scale is + * drawn in (0, 1), see in_unit(). */ int r3d_shape_dequant(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); const int64_t g = gi(p, n_p, "group", 0); @@ -414,8 +389,7 @@ int r3d_shape_dequant(const RadParam* p, int n_p, int operand, RadOpdDesc* out) * r3d_gemm_bf16_nt_m16.hip, r3d_gemm_bf16_nt_tiled.hip, r3d_gemm_fp8a16_nt_m1.hip */ -/* y[M,N] = a[M,K] @ b[N,K]^T. Both operands are k-contiguous, which is what the transposed spelling - * in the op's name means and why neither is described as [K, N]. */ +/* y[M,N] = a[M,K] @ b[N,K]^T. Both operands are k-contiguous (the "nt" in the name). */ int r3d_shape_gemm_nt(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); @@ -424,15 +398,10 @@ int r3d_shape_gemm_nt(const RadParam* p, int n_p, int operand, RadOpdDesc* out) } /* The vocabulary projection, transcribed from ref_logits_gemm_shape: x [M, n_embd] and the head - * [n_vocab, n_embd] in the activation's dtype, the logits in f32 -- the dtype the schema states, not - * the one a GEMM would narrow to, because every sampler stage downstream reads f32 and a prefill - * band's plane is 1.07 GB of it at M=2048. The reference's own logits row answers a placement - * question (`ref_layout_head`: where the head lives) and so carries a layout hook; this row has - * nothing to place, it reads the head where it is stored, which is why the hook it declares is the - * shape and nothing else. A hook is the right thing to write *because* all three operands are - * describable: the extents the hook names are the ones that get filled, which is the opposite of - * the joined w2a8 plane, where a describable byte count is a container header waiting to be filled - * with random bytes. */ + * [n_vocab, n_embd] in the activation's dtype, logits in f32 because every sampler stage reads + * f32 (a prefill band's plane is 1.07 GB at M=2048). Unlike the reference row, which also places + * the head (`ref_layout_head`), this row reads the head where it is stored, so it declares only a + * shape hook. */ int r3d_shape_logits_gemm_bf16(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), nv = gi(p, n_p, "n_vocab", 0), ne = gi(p, n_p, "n_embd", 0); if (M <= 0 || nv <= 0 || ne <= 0) return RAD_E_UNSUPPORTED; @@ -441,17 +410,17 @@ int r3d_shape_logits_gemm_bf16(const RadParam* p, int n_p, int operand, RadOpdDe R3D_PICK(list); /* x, lm_head, logits */ } -/* The quantised GEMM. `dtype` names the scheme, and the scheme fixes which operands are coded: +/* The quantised GEMM. `dtype` names the scheme, which fixes which operands are coded: * * fp8a16 a bf16, b the checkpoint's E4M3 [N][K], b_scale one f32 per 128x128 block (the * container's `weight_scale_inv`, whose dtype the container states: f32 at fp8a8f32, * bf16 as DeepSeek's own scales are). - * fp8a8 a E4M3 against a_scale, one f32 per (row, `group` of K) -- quant_act_fp8's output - * feeding the GEMM, which is the reason the two rows state the same group. + * fp8a8 a E4M3 against a_scale, one f32 per (row, `group` of K): quant_act_fp8's output, so + * the two rows state the same group. * i8a8 i8 codes on both axes with an f32 scale per (row, `group`). * - * `b_scale`'s plane is block-major [ceil(N/pb), ceil(K/pb)] for fp8 and row-major [N, ceil(K/group)] - * for i8: the two checkpoints spell it differently and both are the bytes on disk. */ + * `b_scale` is block-major [ceil(N/pb), ceil(K/pb)] for fp8 and row-major [N, ceil(K/group)] for + * i8, as each checkpoint stores it. */ int r3d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED; @@ -474,11 +443,10 @@ int r3d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out return pick(out, operand, list, R3D_GEMM_Q_NOPERAND); } -/* The OCP-MXFP4 grid, libref's description for the dtype: the weight is e2m1, two a byte, with - * one e8m0 exponent per 32 of K, so the weight's planes are [N, K] of fp4_e2m1 and [N, K/32] of - * e8m0; `b_ref` is the same exponent plane, accepted beside an e2m1 weight and ignored. The - * activation is the fp8a8 row's -- E4M3 against one f32 per (row, 128 of K), drawn in (0, 1) as - * a quantiser's is. Both zero-point operands are absent: the scale is symmetric. */ +/* The OCP-MXFP4 grid, as libref describes it: an e2m1 weight [N, K], two a byte, with one e8m0 + * exponent per 32 of K ([N, K/32]); `b_ref` is the same exponent plane, accepted and ignored. The + * activation is the fp8a8 row's: E4M3 against one f32 per (row, 128 of K), drawn in (0, 1). Both + * zero-point operands are absent since the scale is symmetric. */ int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0); if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED; @@ -492,9 +460,9 @@ int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdD as.fill = RAD_FILL_SIGMOID; /* a quantiser's (0, 1) */ list[1] = as; list[2] = opd((uint32_t)RAD_FP4E2M1, N, K); /* b: e2m1, two a byte */ - /* The e8m0 scale, filled with 127: the factor 2^0. A normal draw of the u8 grid is an exponent - * as high as 227, a factor 2^100, and the plane would scale the output past the finiteness - * bound the run checks; 127 is the checkpoint's own cluster and no reserved value. */ + /* The e8m0 scale is filled with 127, the factor 2^0. A normal draw of the u8 grid reaches + * exponents near 227 (2^100) and overflows the output's finiteness check; 127 is where real + * checkpoints cluster and is not a reserved value. */ RadOpdDesc e8 = opd((uint32_t)RAD_E8M0, N, K / 32); /* b_scale: e8m0 */ e8.fill = RAD_FILL_INDEX; e8.idx_const = 127; @@ -505,10 +473,10 @@ int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdD return pick(out, operand, list, R3D_GEMM_Q_NOPERAND); } -/* The symmetric int4 / int8 weight grids, libref's descriptions: int8 activations in the step - * order against signed codes (I4, two a byte, or I8, one a byte) with one f16 scale per (row, - * 128 of K) and one f32 activation scale per row, drawn in (0, 1) as a quantiser's is. There is - * no zero point and no a_sum: the dequant is code times scale. */ +/* The symmetric int4 / int8 weight grids, as libref describes them: int8 activations in the step + * order against signed codes (I4 two a byte, or I8) with one f16 scale per (row, 128 of K) and one + * f32 activation scale per row, drawn in (0, 1). No zero point and no a_sum: the dequant is code + * times scale. */ static int shape_inta8(const RadParam* p, int n_p, int operand, RadOpdDesc* out, const char* q, uint32_t bdt) { @@ -546,18 +514,14 @@ int r3d_shape_gemm_nt_q_w8a8(const RadParam* p, int n_p, int operand, RadOpdDesc /* ==================================================================== r3d_sample_f32.hip, r3d_attn_paged_h128.hip * - * The vocabulary and the sampler. The schemas in r3d_rows.cpp are transcribed from libref and - * checked against it, and these are the other half of that transcription. Every extent, dtype, - * fill domain and flag below is libref's: a description that differs from libref's is a case - * kbench skips, with one line saying so, and a row that is never exercised is a row that is not - * tested. + * The vocabulary and the sampler. The schemas in r3d_rows.cpp are transcribed from libref, and + * every extent, dtype, fill domain and flag below is libref's: a description that differs is a + * case kbench skips with a one-line notice. * - * The sampler's `params` operand is one plane with one fill domain, `RAD_FILL_SAMPLE_PARAMS`: the - * ABI's `RadSampleParams`, 96 bytes, 24 f32 words a row, whose fields the stages read by name. The - * history window and the mask-row count are placed *inside* that plane by `fill_chunk` and - * `idx_max`, so the draw produces a window that fits the plane and a `mask_row` that is a row of - * the bitmask plane (or -1, the unconstrained row sharing a short plane). Both are the stage's - * parameters to obey, not this file's invention. + * The sampler's `params` operand is one plane with fill domain `RAD_FILL_SAMPLE_PARAMS`: the ABI's + * `RadSampleParams`, 96 bytes (24 f32 words) a row. `fill_chunk` and `idx_max` place the history + * window and the mask-row count inside it, so the draw yields a window that fits and a `mask_row` + * that is a row of the bitmask plane (or -1, an unconstrained row). */ /* The sampler's parameter plane: [M, 24] f32, one RadSampleParams a row. */ @@ -569,13 +533,11 @@ RadOpdDesc opd_params(int64_t M, int64_t hist, int64_t mask_rows) { return d; } -/* The widths libref's shapes choose, and the reasons it gives for them: the history window is what - * a deployment sizes the plane to, 64 is plausible; the candidate width is narrower than the - * vocabulary and wide enough for the narrowing stages. */ +/* libref's widths: a plausible deployment history window, and a candidate width narrower than the + * vocabulary but wide enough for the narrowing stages. */ enum { kHist = 64, kCand = 64 }; -/* `n_vocab` rows of f32 logits, and the parameter plane, the pair every vocabulary-width stage - * opens with. */ +/* Reads M and n_vocab, the extents every vocabulary-width stage opens with. */ int sample_vocab(const RadParam* p, int n_p, int64_t* M, int64_t* nv) { *M = gi(p, n_p, "M", 0); *nv = gi(p, n_p, "n_vocab", 0); @@ -590,10 +552,8 @@ int r3d_shape_silu_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) R3D_PICK(list); } -/* The fused add + norm + quantiser. `residual` is INOUT and the sum it holds is the bf16 one the - * variance reads, so x and residual are the same shape by the op's meaning, not by convenience; - * `out_bf16`, optional, is what the codes were taken over, and it exists so a test can read the - * value the quantiser saw. */ +/* The fused add + norm + quantiser. `residual` is INOUT and holds the bf16 sum the variance reads, + * so it has x's shape. The optional `out_bf16` is the value the codes were taken over, for tests. */ int r3d_shape_rmsnorm_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -604,11 +564,9 @@ int r3d_shape_rmsnorm_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdD R3D_PICK(list); /* x, residual, w, q, scale, out_bf16 */ } -/* Paged attention. The context is deeper than the query: one sequence whose context is its query - * length is the smallest geometry, and the one that exercises nothing -- no deep paging, no KV - * split, no window -- so `ctx`, when a harness passes it, wins, and is never below the query. - * `q_len` is the ranged parameter; a decode row and a 2048-token prefill chunk are different - * kernels (docs/OPS.md). */ +/* Paged attention over one sequence. A context equal to the query length exercises no deep paging, + * KV split or window, so `ctx` wins when given and is never below the query. `q_len` is the ranged + * parameter; decode and prefill chunks are different kernels (docs/OPS.md). */ int r3d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "q_len", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); @@ -618,9 +576,8 @@ int r3d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* ou if (M <= 0 || hd <= 0 || bs <= 0 || gqa <= 0 || nh <= 0 || nh % gqa) return RAD_E_UNSUPPORTED; const int64_t kvh = nh / gqa; const int64_t S = 1; - /* `ctx`, as the reference spells it -- and it is NOT the band's `max_ctx`, which is why a - * geometry that wants a context deeper than its query chunk has to name `ctx`. When no case - * names it, the context is the query chunk. */ + /* `ctx` as the reference spells it, not the band's `max_ctx`; absent, the context is the + * query chunk. */ int64_t ctx = gi(p, n_p, "ctx", 0); if (ctx < M) ctx = M; const int64_t max_blocks = (ctx + bs - 1) / bs; @@ -644,8 +601,8 @@ int r3d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* ou R3D_PICK(list); } -/* Exact per-row top-R. `pairs` is described because its packing is checked: an int32 id's bits in - * the first slot beside its value, so the plane is f32 to hold the value. */ +/* Exact per-row top-R. `pairs` packs an int32 id's bits in the first slot beside its value, in an + * f32 plane. */ int r3d_shape_row_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), R = gi(p, n_p, "R", 0); if (M <= 0 || N <= 0 || R <= 0) return RAD_E_UNSUPPORTED; @@ -673,15 +630,11 @@ int r3d_shape_sample_temp(const RadParam* p, int n_p, int operand, RadOpdDesc* o R3D_PICK(list); /* logits INOUT, params */ } -/* DFlash2's candidate walk, slot for slot from libref's shape hook. `cand` and `anchor` hold token - * ids bounded by n_vocab so the codebook gather stays inside the plane, and cand/unary/hp carry one - * row per (sequence, step), M * steps. */ /* The gated MLP band, slot for slot from libref's shape hook: n = N/2, the weight's scales per - * (ceil(N/group), ceil(K/group)) in **bf16** (the container's `weight_scale_inv`, which writes - * `o.t(RAD_BF16, {nb, kb})`), the output's codes per (M, n) and its scales per (M, ceil(n/group)). - * The row's set is fp8a8 only, group a power of two in [32, 256], no wider than n, and K a whole - * number of groups -- a hook that describes a shape the kernel refuses is the bug class this file - * exists to prevent. */ + * (ceil(N/group), ceil(K/group)) in bf16 (the container's `weight_scale_inv`), the output's codes + * per (M, n) and its scales per (M, ceil(n/group)). The checks mirror the kernel's: fp8a8 only, + * group a power of two in [32, 256] no wider than n, and K a whole number of groups, so the hook + * never describes a shape the kernel refuses. */ int r3d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t N = gi(p, n_p, "N", 0); @@ -707,6 +660,9 @@ int r3d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand, RadOpdDes R3D_PICK(list); } +/* DFlash2's candidate walk, slot for slot from libref's shape hook. `cand` and `anchor` hold token + * ids bounded by n_vocab so the codebook gather stays inside the plane; cand/unary/hp carry one + * row per (sequence, step), M * steps. */ int r3d_shape_dflash_select(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t steps = gi(p, n_p, "steps", 0); @@ -760,10 +716,9 @@ int r3d_shape_sample_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* o R3D_PICK(list); } -/* The four narrowing stages -- top-p, min-p, typical, XTC -- in place over the candidate set. - * The set is drawn, not sorted: the ABI has no descending fill domain, and top-p is a prefix rule - * in candidate order, which applies equally to a random order. An implementation that sorted - * internally would genuinely disagree with the schema. */ +/* The four narrowing stages (top-p, min-p, typical, XTC), in place over the candidate set. The set + * is drawn, not sorted: the ABI has no descending fill domain, and top-p is a prefix rule in + * candidate order, which applies to any order. */ int r3d_shape_narrow(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t nc = gi(p, n_p, "n_cand", 0); @@ -782,9 +737,8 @@ int r3d_shape_sample_pick(const RadParam* p, int n_p, int operand, RadOpdDesc* o R3D_PICK(list); /* cand_idx, cand_val, params (seed and pos), token */ } -/* Penalties and DRY: logits, params with a history window inside it, and the history itself -- real - * token ids that repeat as text repeats. DRY's breaker plane marks about half its positions, so the - * exemption runs as well as the penalty. */ +/* Penalties and DRY: logits, params with a history window, and the history of token ids. DRY's + * breaker plane marks about half its positions, so the exemption runs as well as the penalty. */ int r3d_shape_sample_penalties(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { int64_t M = 0, nv = 0; if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; @@ -798,8 +752,8 @@ int r3d_shape_sample_penalties(const RadParam* p, int n_p, int operand, RadOpdDe int r3d_shape_sample_dry(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { int64_t M = 0, nv = 0; if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; - const RadOpdDesc brk = opd_idx(M, 2, -1, 0, kHist); - const_cast(brk).dtype = (uint32_t)RAD_U8; + RadOpdDesc brk = opd_idx(M, 2, -1, 0, kHist); + brk.dtype = (uint32_t)RAD_U8; const RadOpdDesc list[] = { opd((uint32_t)RAD_F32, M, nv), opd_params(M, kHist, 0), opd_idx(M, nv, -1, RAD_OPD_F_IDX_HISTORY, kHist), brk @@ -820,8 +774,7 @@ int r3d_shape_sample_ngram_ban(const RadParam* p, int n_p, int operand, RadOpdDe R3D_PICK(list); } -/* The four narrowing stages share the description above; the op names which predicate the kernel - * applies, and the schema they share says the operands are the same. */ +/* The four narrowing stages share one description; the op names the predicate. */ int r3d_shape_sample_topp(const RadParam* p, int n_p, int o, RadOpdDesc* out) { return r3d_shape_narrow(p, n_p, o, out); } diff --git a/libr3d/r3d_tiling.h b/libr3d/r3d_tiling.h index 684e6e5e..32ac474a 100644 --- a/libr3d/r3d_tiling.h +++ b/libr3d/r3d_tiling.h @@ -1,38 +1,26 @@ -/* r3d_tiling.h -- the tiled rows' LDS row law, in one place. +/* r3d_tiling.h -- the LDS swizzle shared by libr3d's tiled rows. * - * Every tiled row in libr3d stages an [rows x pitch] f16 tile in LDS and then reads it back two - * elements at a time for dot2_f16x2. Two functions spell that out and they must agree exactly, so - * they live here and the rows include this file. + * A tiled row stages an [rows x pitch] f16 tile in LDS and reads it back in pairs for dot2_f16x2. + * The store and the load must use the same swizzle, so both are defined here: * - * srow(row, c8, pitch) the element offset of the c8-th run of EIGHT elements of `row` - * srow_pair(row, kc, pitch) the element offset of the pair (kc, kc+1) of `row`, kc even + * srow(row, c8, pitch) element offset of the c8-th run of eight elements of `row` + * srow_pair(row, kc, pitch) element offset of the pair (kc, kc+1) of `row`, kc even * - * The law, and why it is shaped like this: + * - Granularity is eight elements (16 bytes at f16) because staging writes one uint4 per step; a + * finer swizzle would split the store and make it unaligned. + * - The XOR with (row & 7) rotates the runs of eight consecutive rows by one slot each. A wavefront + * reads 32 rows at the same kc, and the rotation spreads those reads over 32 distinct 16-byte + * slots instead of the four a plain row-major tile uses, which removes the bank conflict. + * - The mask (pitch / 8 - 1) keeps the rotated index inside the row. pitch is in elements and + * pitch/8 must be a power of two (32 or 128 for every tile in the library). Without the mask the + * index reads a neighbouring row, a silent, data-dependent error. + * - srow_pair finds the run the pair lives in (kc >> 3) and adds the element inside it (kc & 7). * - * - Granularity is EIGHT elements (16 bytes at f16): staging writes a uint4 a step, so the XOR has - * to move whole uint4s and never split one. A swizzle at pair granularity would make the store - * unaligned and the compiler would say so in bytes of spill. - * - The XOR is with (row & 7), so eight consecutive rows rotate the runs by one slot each. That is - * what kills the dot loop's bank conflict: a wavefront reads 32 rows at the same kc, and with the - * rotation the 32 reads land on 32 distinct 16-byte slots instead of the four a plain row-major - * tile puts them on. - * - The mask (pitch / 8 - 1) keeps the rotated index INSIDE the row. pitch is in elements, so a - * row has pitch/8 runs, and pitch/8 is a power of two for every tile in the library (32, 128). - * Without the mask a rotated index leaves the row and reads a neighbour's, which is the bug this - * header exists to prevent: it is silent, it is data-dependent, and it measures 30x off. - * - srow_pair takes the pair index kc>>3 -- the run the pair lives in -- and adds (kc & 7), the - * element inside the run. Reading pairs through srow is what keeps the store, the load and the - * swizzle one statement each. + * With dot2_f16x2 accumulating into f32, a row using these functions matches ref_gemm_nt_q at a + * bf16 output to rel_l2 1.7e-03 (bounded by the store's rounding); a wrong swizzle gives rel_l2 3e+01. * - * Measured law, in the family's numbers: a row that stages through srow and reads through - * srow_pair, with dot2_f16x2 accumulating into f32, lands at rel_l2 1.7e-03 against - * ref_gemm_nt_q's body at a bf16 output (the store's ulp binding, not the fold's) with 83% of - * outputs bit-exact. A row that gets the swizzle wrong, in either direction, lands at rel_l2 3e+01. - * - * Header-only, like the rest of libr3d. Include it in a .hip at file scope, before the kernels; the - * definitions are in an unnamed namespace, so each translation unit gets its own copy -- which is - * what the rows had before this header existed, spelled the same way, so the host pass does not see - * an unused static and the inliner sees the same function it always did. + * Include at file scope in a .hip before the kernels. The definitions are in an unnamed namespace, + * so each translation unit gets its own copy. */ #ifndef R3D_TILING_H #define R3D_TILING_H diff --git a/libr3d/r3d_vocab_bf16.hip b/libr3d/r3d_vocab_bf16.hip index 36b6d657..7de9a44b 100644 --- a/libr3d/r3d_vocab_bf16.hip +++ b/libr3d/r3d_vocab_bf16.hip @@ -3,235 +3,119 @@ * * y[M,N] = x[M,K] @ w[N,K]^T, f32 accumulate, k ascending. * - * `logits_gemm` spells N and K as n_vocab and n_embd and its y is **f32**: the schema says so - * (`ref_logits_gemm_shape` writes `o.t(RAD_F32, {M, nv})`, "f32 logits, as every sampler stage reads - * them"), and none of those stages wants a bf16 logit. `gemm_nt` is the same arithmetic with a bf16 - * y, narrowed once by the store. Both entries are the same two kernels; `YF32` is the only - * difference in the code and the only difference in what the board has to report. + * `logits_gemm` spells N and K as n_vocab and n_embd, and its y is f32 because the schema says so + * (`ref_logits_gemm_shape`) and every sampler stage reads f32 logits. `gemm_nt` is the same + * arithmetic with a bf16 y, narrowed once by the store. Both entries run the same two kernels; + * `YF32` is the only difference. * - * ---- why this row exists ------------------------------------------------------------------------ - * - * The probe of the served checkpoint refuses exactly one op: `logits_gemm`. libref's - * `ref_logits_gemm` is - * `gemm_nt_impl(a, false, "n_vocab", "n_embd")` on 32 OpenMP threads: 1.1 TFLOP for the band's shape - * (M=2048, n_vocab=130560, n_embd=2048), which this card does in about a second and the CPU in - * tens. For decode it is the 535 MB vocabulary head read once a token -- one call per token, the - * head the model cannot answer without. This row is not a speed decision. It is - * a read of the container's own form, and the head is stored in two of them: bf16 plain, with - * `layout`, `relayout` and `unrelayout` all null; and E4M3 codes with a bf16 scale per 128x128 block - * as two planes of one `rad.planes` container, which is the form the served checkpoint ships and - * which is answered by `r3d_layout_logits_head`, this file's transcription of `ref_layout_head`. - * Nothing is repacked in either case, and no operand description is declined. + * libref's `ref_logits_gemm` is a CPU GEMM (OpenMP), about 1.1 TFLOP at the M=2048, + * n_vocab=130560, n_embd=2048 band. The head is read in either of its stored forms, with nothing + * repacked: plain bf16 (no layout hook), or E4M3 codes with a bf16 scale per 128x128 block as two + * planes of one `rad.planes` container, answered by r3d_layout_logits_head below. * * ---- the prefill arm (M > 16) ------------------------------------------------------------------- * - * A block is TM x TN = 128 x 128 outputs, 256 threads, eight waves, eight outputs a side a lane: 64 - * f32 accumulators a lane, grid (N/TN) x (M/TM). Lane `tid` owns rows m0 + (tid/16)*8 .. +7 by - * columns n0 + (tid%16)*8 .. +7, so its 64 outputs are one 8x8 square of the tile and its stores are - * 32-byte runs of f32 (16-byte runs of bf16). + * A block is TM x TN = 128 x 128 outputs, 256 threads (eight waves), grid (N/TN) x (M/TM). Lane + * `tid` owns rows m0 + (tid/16)*8 .. +7 by columns n0 + (tid%16)*8 .. +7: 64 f32 accumulators, one + * 8x8 square, stored as 32-byte runs of f32 (16-byte runs of bf16). * - * k is walked in KC = 32 code chunks. Both tiles are stored row-major in f16 -- a row is the 32 - * k-values of one m, 64 bytes -- because the global load that fills them is 8 contiguous k of one - * row: one `uint4` a thread, sixteen bytes, widened on the way in by four `bf16x2_to_f16x2`, which - * is exact for everything f16 can hold (bf16 has eight mantissa bits, f16 ten) and arrives as an inf - * for what it cannot, which the board counts rather than assumes away. The compute then reads those - * 64-byte rows in f16x2 pairs: eight activation pairs and eight weight pairs per two codes, - * sixty-four `fdot2` per two codes -- one pair-dot per output per two codes, 16 LDS reads against - * 64 dots. + * k is walked in KC = 32 chunks. Both tiles are row-major f16 (a row is 32 k-values, 64 bytes), + * filled by one `uint4` load of 8 contiguous k a thread and widened by `bf16x2_to_f16x2`, which is + * exact for every value f16 can hold and gives inf for the rest. The compute reads f16x2 pairs: + * 16 LDS reads against 64 `fdot2` per two k. * - * The tile pitch is KC elements and the rows are XOR-swizzled in eight-element units, which is the - * only arrangement that satisfies both ends at once. The staging store is a `uint4`, so a row's - * chunk offset has to stay a multiple of eight elements; an unswizzled 64-byte row stride puts all - * eight rows a lane reads on the same bank, 32-way. `srow` moves whole eight-element chunks by - * `row & 7`, which preserves the 16-byte alignment and brings the compute reads to two-way. Two-way - * and not conflict-free: the eight rows a lane owns sit at stride eight, so a period-8 swizzle - * repeats inside a lane's own set. The cost is 512 LDS cycles a block-chunk against 2048 of - * dots, a quarter, which is what the vectorised staging store buys. - * - * At the band, M=2048 n_vocab=130560 n_embd=2048, 16 x 1020 blocks of 256 threads: - * 272.24 ms = 4023 GFLOP/s, which is 37% of the 10.8 TFLOP/s this card's 32 CUs do dense f16 with - * f32 accumulate. At M=46 -- one tile row, 1020 blocks -- the same kernel does 16.64 ms = - * 1478 GFLOP/s, and the shortfall is the shape, not the kernel: 46 rows against a 128-row tile - * leaves 5/8 of every block's arithmetic idle. The host row for this op is `ref_logits_gemm`: 1.1 - * TFLOP per forward pass across the whole vocabulary, on OpenMP threads; this row is the card's - * answer to that comparison. + * Tile rows are XOR-swizzled in eight-element units (`srow`, r3d_tiling.h). The staging store is a + * `uint4`, so chunks must stay eight-element aligned; unswizzled, the 64-byte row stride puts the + * eight rows a lane reads on one bank (32-way). Swizzling by `row & 7` brings that to two-way (a + * lane's rows sit at stride eight, so a period-8 swizzle repeats within them): 512 LDS cycles a + * block-chunk against 2048 of dots. * * ---- the decode arm (M <= 16) ------------------------------------------------------------------- * - * The prefill tile reads the head M/TM times; at M=1 it would read 127/128 of it for nothing. At - * M <= 16 the block is the decode shape `r3d_gemm_bf16_nt_m16.hip` uses: a wave is MT activation - * rows by 32/MT weight rows, lane l owns (m = l % MT, n = n0 + l / MT), one accumulator a lane from - * k=0 to K, and no wave reduction anywhere -- so each output's sum is the reference's ascending - * chain, summand for summand, in the pair-dot's grouping. The activation arrives in 128-code chunks - * and stays in LDS for the chunk (MT x 128 f16, 4 KiB at MT=16, the same eight-element swizzle at - * the wider pitch); the weight goes straight from global to registers in 16-byte loads, eight codes - * at a time, widened where it lands. A wave keeps 32/MT weight rows in flight -- 4 KiB at MT=1 -- - * which is what makes 16-byte strided reads across rows cost what they fetch. `nt=1` asks for - * non-temporal head loads, the honest hint for bytes read once a token; on this card it is worth - * nothing: 3.316 ms against 3.290 ms at M=1, 0.8% the other way. It is implemented - * because the ABI names it, and left off by default because the number says to. + * The prefill tile reads the head M/TM times, so at M=1 it would read 127/128 of it for nothing. + * At M <= 16 the block uses r3d_gemm_bf16_nt_m16.hip's decode shape: a wave is MT activation rows + * by 32/MT weight rows, lane l owns (m = l % MT, n = n0 + l / MT), one accumulator from k=0 to K + * and no wave reduction, so each sum is the reference's ascending chain in the pair-dot's grouping. + * The activation is staged in 128-k chunks in LDS (MT x 128 f16, 4 KiB at MT=16, same swizzle); + * the weight goes from global to registers in 16-byte loads, eight values at a time. * - * At n_vocab = 130560, n_embd = 2048 the arm is M = 1 in 3.226 ms = 166 GB/s of head, and M = 16 in - * 8.151 ms = 1050 GFLOP/s, 66 GB/s of bytes. The w2a8 row's 22 GB/s is not this arm's bound: it is - * that kernel's own limit -- an ALU-bound pair-dot with one 16-byte weight load per 64 codes -- and - * the card's DRAM is 256 GB/s. This arm is the streaming shape, 16 bytes a lane a step with the - * activation in LDS, and it runs at two thirds of the card. + * `nt=1` requests non-temporal head loads. On gfx1102 it measures within 1% of the default at M=1, + * so it is off by default. * - * So the bf16 head costs 3.23 ms per decode token, and M = 16 (a speculative verify) costs 0.51 ms - * a token. The quantised head is the same op in half the bytes: the codes are 130560 x 2048 = - * 267,386,880 bytes (255.0 MiB) and the scales 1020 x 16 bf16 = 32,640 bytes (31.9 KiB), so a decode - * reads 255.03 MiB where the bf16 head reads 510.0 MiB. At the 163 GB/s this row's bf16 arm runs at - * the floor that is 1.64 ms a token, and at the card's 256 GB/s, 1.04 ms. (The 66.8 MB figure is the - * w2a8 row's 2-bit grid, a different head form.) Every number below says which of the three - * placements the bytes were in, because the placement is worth more than anything in the kernel, and - * all three are on this page so the choice between the head's forms is made on measurement. + * The quantised head is half the bytes of the bf16 one (255 MiB of codes plus 32 KiB of scales + * against 510 MiB at the band), which is its case for decode. * - * ---- the accumulation, and what it is exact against --------------------------------------------- + * ---- the accumulation --------------------------------------------------------------------------- * - * libref's law per output is `acc += a*b` over ascending k from zero, and for this op with no bias. - * One accumulator per output, k ascending, no reassociation across lanes, in both arms. The pair-dot - * folds two products into the accumulator per step (`acc + a0*b0 + a1*b1` in one rounding) where the - * reference rounds each product in, so the sums agree closely and are not bit-equal. f32 output, - * K = 2048: rel_l2 1.77e-06 against the reference's law, identical -- 1.77e-06, to the - * digits -- against the same law with the operands widened to f16 first, so the widening - * contributes nothing and the fusion is the whole of it. 1.77e-06 is about 30 - * f32 ulps on a sum of 2048 terms, and a random walk of one rounding per 1024 steps predicts - * sqrt(1024) * 6e-8 = 1e-6, which is where it lands. At K = 320 it is 2.0e-07, which scales the same - * way. What it means for the sampler: the head's bf16 values carry 4.9e-4 of quantisation each, so - * this is 300x finer than the input, and a top-k decision flips only on a tie tighter than 1e-6. + * libref's law per output is `acc += a*b` over ascending k from zero, no bias. Both arms keep one + * accumulator per output, k ascending, no reassociation across lanes. The pair-dot folds two + * products per rounding (`acc + a0*b0 + a1*b1`) where the reference rounds each, so results are + * close but not bit-equal: rel_l2 about 1.8e-6 at K = 2048 with f32 output (the widening to f16 + * contributes nothing), far below the 4.9e-4 quantisation of the head's bf16 values. * - * Nothing here is integer arithmetic, so the v_fdot2_f32_f16 mantissa rule that bounds - * r3d_gemm_nt_q_w2a8.hip does not bite: the products are not integers, so there is no 2^20 wall, and - * the board's tail is ordinary rounding, counted with the plane pre-filled at 0x7fc0 -- no non-finite - * output at any size, including the 268-million-output band. + * This is not integer arithmetic, so the v_fdot2_f32_f16 mantissa limit that bounds + * r3d_gemm_nt_q_w2a8.hip does not apply. * - * ---- the head's stored form, and who answers it --------------------------------------------------- + * ---- the quantised head ------------------------------------------------------------------------- * - * The band's `dtype=bf16` is the ACTIVATION's dtype. The head is quantised: the graph reads - * 'output.weight' as two planes of fp8_e4m3 * bf16[128x128], and the mapped tier reads the - * container where it lies, and its stored form is not the container's (rad.planes). The placement - * needs a reader for the head's stored form, and a layout hook is what a reader is. So: + * The band's `dtype=bf16` is the activation's dtype; the head may be stored quantised. * - * r3d_layout_logits_head (operand 1 -- `ref_layout_head` is `layout_scaled(operand, 1, -1, ...)`) - * tag `rad.planes`; codes E4M3 (libref's `scaled_rows` also admits int8) with a float scale -- - * bf16, f16 or f32 -- on a block of {128, 128} (`R3D_FP8_BLOCK`); ends in `rad_planes_layout`. - * It moves no byte and `relayout` stays null. `ref_layout_head` is libref-internal-static, so - * its body, and `layout_scaled`'s, and `enc_scaled_rows`' and `float_scale_dt`' with it, are - * transcribed here as the w2a8 hook transcribed `ref_layout_gemm_q`: checks and their order, - * unchanged. Two fields are worth naming: `rad_enc_is` - * compares `scheme`, and `transform` is the optional pre-transform. The - * encoding is affine with an EMPTY transform; a fixture that writes "affine" into `transform` - * makes the hook decline every head. + * r3d_layout_logits_head (operand 1, as `ref_layout_head` is `layout_scaled(operand, 1, -1, ...)`) + * Tag `rad.planes`; codes E4M3 (libref's `scaled_rows` also admits int8) with a bf16, f16 or + * f32 scale on a {128, 128} block (`R3D_FP8_BLOCK`); ends in `rad_planes_layout` and moves no + * byte. `ref_layout_head` is static inside libref, so it and `layout_scaled`, + * `enc_scaled_rows` and `float_scale_dt` are transcribed here with their checks in order. + * `rad_enc_is` compares `scheme`, and `transform` is the optional pre-transform: the encoding + * is affine with an empty transform, so a fixture that writes "affine" into `transform` makes + * the hook decline every head. * - * The law. `ScaledRows::at(r, c) = codes.at(r, c) * scale.cover(r, c)`: the code widened exactly, - * multiplied by the scale covering it, one f32 rounding, then the plain ascending-k GEMM in f32. - * The widening is exact both ways -- E4M3 is 4 exponent and 3 mantissa bits, f16 is 5 and 10, and - * int8 lands in f16 whole -- so the codes reach the dot as the numbers the checkpoint means, and - * the only divergence stays the dot's fused rounding: rel_l2 2.77e-04 at M=1, K=2048, - * which is one f16 ulp's worth (2^-12 = 2.44e-04) and is the fold, not the dot; against the fold - * law, below, it is 4.5e-06, and `<=2 ulps` is 1.000 with `>6 ulps` 0 at every size, - * 268-million-output band included. y stays f32: logits are f32 and the reference's store is f32. + * The law is `ScaledRows::at(r, c) = codes.at(r, c) * scale.cover(r, c)` in f32, then the plain + * ascending-k GEMM. Decoding a code to f16 is exact (E4M3 has 4 exponent and 3 mantissa bits, f16 + * 5 and 10; int8 fits whole). Here the scale is folded into the staged f16 weight instead (see + * scale_pair): once per staged 8-column group in the tiled arm and once per 128-k chunk in the + * decode arm, both inside one 128-column block. That costs one f16 rounding per weight, rel_l2 + * about 2.8e-4 at M=1, K=2048 against the reference, 250x finer than the E4M3 quantum (2^-4). + * An f32 scale plane adds one rounding (the scale to f16); a bf16 scale is f16-exact. y stays f32. * - * The fold, and the hardware rule it obeys. The reference dequantises each element into f32; the - * tile is f16, so the scale enters as a f16 multiply at staging -- the tiled arm once per staged - * 8-column group, the decode arm once per 128-code chunk, and a chunk of 32 sits inside one - * 128-column block (128 % 32 == 0, 128 % 128 == 0), so one scale per staged row. That costs no - * registers: the prefill arm is the register file's at 237 VGPRs, and per-k-block partials would - * need 64 more accumulators and spill. The multiply must be a hardware f16 multiply - * (`v_mul_f16`, round to nearest, subnormals kept), not `f16x2_pack`: that builtin is - * `v_cvt_pkrtz_f16_f32`, ROUNDS TOWARD ZERO, and r3d_codecs.h says so and says to call it only - * with values f16 already represents exactly. A folded weight is not one of those -- code 431 by - * a scale of 4.5e-5 is eleven significant bits -- and a toward-zero packer biases every product - * toward zero and flushes the subnormal end: rel_l2 2.8e-04 against the fold law with only 0.53 of - * outputs within 2 ulps. The f16 multiply is one rounding in the right direction and one - * instruction: 4.5e-06 and 1.000. The number and the verdict: 2.77e-04 against the reference's - * exact law is the fold's cost, 250x finer than the E4M3 code's own quantum (2^-4 = 6.25e-2), so - * the fold does not move the logits by anything the quantisation did not already move. An f32 - * scale plane costs one more rounding (the scale to f16, 1.75e-04 against a model that folds - * after the multiply); the shipped form's bf16 scale is f16-exact and pays nothing. + * Placement dominates the kernel: a head on the mapped tier (hipHostMalloc, read over PCIe) runs + * about 50x slower than in VRAM, and an unprefetched managed head faults page by page because + * this ROCm does not migrate managed pages for read-mostly device access. * - * With the head's bytes where the engine would put them (VRAM, with the header page - * read by the shim on the host): prefill M=2048 in 325.06 ms = 3369 GFLOP/s against the bf16 head's - * 269.31 ms = 4067 -- 17% slower, all of it staging, and the case for the quantised head at prefill - * is the 255 MiB of weight traffic, not the FLOPs. M=46: 22.43 ms = 0.488 ms a token against - * 0.361. Decode M=1: 13.603 ms a token, 19.7 GB/s of codes, 8x above the 1.64 ms floor, and the - * cause is the E4M3 decoder. `__builtin_amdgcn_cvt_pk_f16_fp8` exists in clang and expands - * to software on gfx1102 -- zero `v_cvt_pk_f16_fp8` in the ISA -- so eight codes cost - * ~100 instructions of `e4m3_to_f32` against the bf16 arm's four, and the arm is ALU-bound. The - * fix has a size: a 256-entry f16 table in LDS is 512 bytes, 8 LDS reads a staged group against - * ~100 ALU, which puts the arm back near its floor; that is a tiling pass, not this row's work. - * The speculation block is where the form already pays: M=8 (7 drafts + 1) reads the head ONCE and - * costs 21.67 ms = 2.708 ms a token, 5x cheaper per token than M=1 on the same kernel. + * The container header picks the form: the shim calls `rad_planes_header(w)` and a plain bf16 + * operand takes the bf16 path. The shim reads the header on the host (as `scaled_rows()` does) + * and the kernel reads the same bytes on the device, so the operand must be managed memory + * (prefetched) or hipHostMalloc; plain malloc faults on the kernel's first read. * - * Where the bytes live, on this box, at M=1: in VRAM 13.6 ms; on the mapped tier - * (hipHostMalloc, read over PCIe by 8-byte strided loads) 643 ms a token; managed and left alone - * 2071 ms a token, 122 MB/s, because managed pages do not migrate for a read-mostly device access - * on this ROCm and the kernel faults page by page. The head is placed on - * the mapped tier. A hook makes that placement legal; it does not make it fast, and these three - * numbers are the argument for uploading the head. The board takes the timed number after - * `hipMemPrefetchAsync` and says so on every line. + * gfx1102 has no v_cvt_pk_f16_fp8 (clang lists the builtin but it expands to software), so the + * E4M3 decode uses r3d_fp8_dequant.h's 256-entry f16 table in LDS (512 bytes, eight reads per + * eight codes). The table is built from the codec, so results are bit-identical; it pays most at + * M=8 (about 2.7x per token), where decoding is the binding resource. At M=1 the quantised arm + * runs far below memory bandwidth; the likely limit is its 8-byte code load (the bf16 arm + * loads 16 bytes a lane). * - * Both forms are served, chosen by the header: `rad_planes_header(w)` at the shim's head branch - * dispatches on it, and a plain bf16 operand goes down the bf16 path untouched. The choice is - * the container's, not the row's. The shim reads the container's header - * (which is why the operand's bytes must be host-readable: `scaled_rows()` does the same host read, - * so this is the engine's convention, not this row's invention); the kernel reads the same bytes on - * the card, so the fixture is hipMallocManaged + prefetch, or hipHostMalloc, never plain malloc -- - * plain malloc faults 700 on the kernel's first read. + * ---- refusals ----------------------------------------------------------------------------------- * - * ---- the decoder is a table, and what the table moved -------------------------------------------- - * - * r3d_fp8_dequant.h replaces the E4M3 codec with a 256-entry f16 table in LDS (512 bytes, eight - * reads an eight-code group) because clang lists __builtin_amdgcn_cvt_pk_f16_fp8 for gfx1102 and a - * build that calls it contains ZERO v_cvt_pk_f16_fp8: the builtin is software here. The A/B is one - * source built twice (-DR3D_NO_E4M3_TBL selects the codec), same fixture, same seed: - * - * M=8 speculation 2.500 -> 0.924 ms/token (20.002 -> 7.395 ms) 2.70x THE WIN - * M=2048 prefill 323.978 -> 322.661 ms (3380 -> 3394 GFLOP/s) flat, -0.4% - * M=1 decode 12.999 -> 13.293 ms/token (20.6 -> 20.2 GB/s) NOT moved, 2.3% worse - * M=46 prefill 21.603 -> 21.792 ms (1139 -> 1129 GFLOP/s) flat - * - * The table is exact by construction -- the codec, evaluated once per bit pattern at block start -- - * and rel_l2 is bit-identical between the two binaries (2.770e-04 vs the fold law / 4.452e-06 vs the - * fold model at prefill; 2.758e-04 / 4.559e-06 at M=1), which is the check that the swap moved work - * and not arithmetic. It is a 2.70x win where the decoder was the binding resource (MT=8: four - * decodes and four folds a lane per eight codes, no memory wall in reach) and a NAMED NON-RESULT at - * M=1: 13 ms at 20 GB/s of codes is 8x off the 1.64 ms floor this row's own 163 GB/s implies, and - * removing ~100 ALU instructions an eight-code group does not move it. The suspect at M=1 is the - * load width -- eight codes a lane through an 8-byte load, where the bf16 arm takes sixteen bytes a - * lane and streams at 163 GB/s -- so the shape to try there is a 16-byte code load (16 codes, eight - * pairs, half the wavefronts), not more ALU. 44 kernels, all vgpr_spill_count: 0, both builds. - * - * ---- what is refused, and where ------------------------------------------------------------------ - * - * sk > 1: the grid is vocab-wide at every M -- 1020 blocks in x at the band for the prefill arm, - * 8160 for the decode arm at MT=16 -- so no shape this row serves is short of parallelism, and a - * split would buy a second kernel and a documented order change for nothing. kb: KC = 32 only; a - * tile pitched at anything else is a different swizzle, not a knob, and the launcher enumerates the - * values it accepts and refuses the rest. K not a multiple of KC, an x pitch not a multiple of 8, a - * y pitch not a multiple of 4 (f32) or 8 (bf16), a weight that is not contiguous, and quantised - * heads that are not this form. The head branch, in its order: - * a quantised head on the bf16-y row -- logits are f32; the tiled row keeps a bf16 head - * a `zero` plane on the head -- codes+scale+zero is gemm_nt_q's asymmetric grid, and the row - * that reads it is r3d_gemm_nt_q_w2a8.hip; that is w2a8's grid, not this op + * sk > 1: the grid is vocab-wide at every M (1020 blocks at the band for the prefill arm, 8160 for + * the decode arm at MT=16), so a split would buy nothing. kb: KC = 32 only, since another pitch is + * a different swizzle. Also refused: K not a multiple of KC, an x pitch not a multiple of 8, a y + * pitch not a multiple of 4 (f32) or 8 (bf16), a non-contiguous weight. The head branch, in order: + * a quantised head on the bf16-y row (logits are f32) + * a `zero` plane: codes+scale+zero is gemm_nt_q's asymmetric grid (r3d_gemm_nt_q_w2a8.hip) * a joined operand that is not two planes - * a joined head whose planes are not codes + scale (a `table`, a `bias`: names it) + * planes that are not codes + scale (a `table`, a `bias`) * codes tiled by anything but one code a cell - * sub-byte codes (4-bit: w4a16's ground, and the row that reads it is w2a8's neighbour) + * sub-byte codes (4-bit) * e5m2 and every other code dtype: no decoder here * a scale plane that is a table, not a tiling - * an integer scale: not float_scale_dt's set - * a scale block that is not 128x128 -- per-(row, group) scales are gemm_nt_q's grid, and a - * per-row scale is a different indexing of the plane than ScaledRows::cover is - * a plane that does not cover the band (codes must be N x K, scales ceil(N/128) x - * ceil(K/128)); a plane whose row_bytes is shorter than its row - * and the bf16 branch's: a plain head that is not bf16, x and y dtypes, - * no axes, pitches, the head's numel and contiguity, absurd shapes, - * alignment, sk > 1. The launcher's own: a head with a null plane, a dtype - * outside the served set, a row pitch a vector load cannot walk (a 16-bit scale row is 2 - * bytes a column, so K = 320 -- 3 scale columns, 6 bytes -- is legal), addresses. - * 24 refusals, 24 as stated, and the hook's two served encodings answer RAD_OK with - * tag `rad.planes` and the codes' dtype. + * an integer scale (not in float_scale_dt's set) + * a scale block that is not 128x128: per-(row, group) scales are gemm_nt_q's grid, and a per-row + * scale indexes the plane differently from ScaledRows::cover + * planes that do not cover the band (codes N x K, scales ceil(N/128) x ceil(K/128)), or a + * row_bytes shorter than the row + * The bf16 branch refuses a plain head that is not bf16, wrong x and y dtypes, bad pitches, a short + * or non-contiguous head, absurd shapes, misalignment and sk > 1. The launcher refuses a head with + * a null plane, a dtype outside the served set, a row pitch a vector load cannot walk (a 16-bit + * scale row is 2 bytes a column, so K = 320, 6 bytes a row, is legal), and misaligned addresses. */ #include @@ -239,8 +123,8 @@ #include "r3d.h" #include "r3d_common.h" #include "r3d_codecs.h" -#include "r3d_fp8_dequant.h" /* the E4M3 -> f16 table: 512 bytes of LDS for ~100 ALU a group */ -#include "r3d_tiling.h" /* the LDS row law: srow, srow_pair */ +#include "r3d_fp8_dequant.h" /* the E4M3 -> f16 LDS table */ +#include "r3d_tiling.h" /* LDS tile addressing: srow, srow_pair */ #include "r3d_args.h" #include "r3d_launch.h" @@ -265,10 +149,8 @@ constexpr int kChunkK = 128; /* the decode arm's activ # define R3D_HAS_NT 0 #endif -/* The tile address, in f16 elements: `pitch`-wide rows whose eight-element chunks are XORed by the - * row's low bits. Multiples of eight in, so a uint4 store and an f16x2 read are both aligned by - * construction, at both pitches this file uses (32 and 128). */ -/* srow / srow_pair: r3d_tiling.h, the family's law in one place. */ +/* Tile addressing (srow, srow_pair) is r3d_tiling.h's: `pitch`-wide f16 rows whose eight-element + * chunks are XORed by the row's low bits, used here at pitches 32 and 128. */ /* Eight bf16 -> eight f16, exact for every value f16 can hold. */ __device__ __forceinline__ uint4 widen8(uint4 w) @@ -279,10 +161,9 @@ __device__ __forceinline__ uint4 widen8(uint4 w) constexpr int kFp8Block = 128; /* the head's scale block: R3D_FP8_BLOCK, llama_dense_fp8 */ -/* The head as the container stores it: E4M3 codes with one float scale per (128 x 128) block. - * Passed by value; every pointer in it is a device address, resolved by the shim out of the joined - * bytes (rad_planes_find), which is what a layout hook's absence asks of a kernel -- the container's - * own form, read where it lies, no byte moved. */ +/* The head as the container stores it: E4M3 (or int8) codes with one float scale per 128x128 + * block. Passed by value; the pointers are device addresses the shim resolved out of the joined + * bytes (rad_planes_find). */ struct HeadQ { const uint8_t* codes; /* [N][K] */ const uint8_t* scale; /* [ceil(N/128)][ceil(K/128)] */ @@ -292,9 +173,8 @@ struct HeadQ { int cdt; /* the codes' dtype: 0 E4M3, 1 int8 */ }; -/* The scale covering logical (n, k): `scale.cover` from the reference's ScaledRows, one scalar load a - * row a chunk. The plane is 32 KiB at the band, so it is in cache from the first block that touches - * a row and the load is not the traffic; the codes are. */ +/* The scale covering logical (n, k), the reference's `ScaledRows::cover`. The plane is 32 KiB at + * the band and stays in cache, so the codes are the traffic, not these loads. */ __device__ __forceinline__ float scale_at(const HeadQ h, int n, int k) { const uint8_t* p = h.scale + (long long)(n >> 7) * h.scale_row @@ -304,16 +184,12 @@ __device__ __forceinline__ float scale_at(const HeadQ h, int n, int k) return h.sdt == 1 ? f16_to_f32(u) : bf16_to_f32(u); } -/* Eight codes -> eight f16, exact. E4M3 is four exponent and three mantissa bits and f16 is five and - * ten, and int8 lands in f16 whole, so the decoder is a widening, not a rounding: the numbers the - * checkpoint means are the numbers multiplied (r3d_gemm_fp8a16_nt_m1.hip says the same about the - * same codec). e4m3x2_to_f16x2 decodes the two codes in a dword's LOW half, so the pairs straddle - * dwords: two dwords in, four pairs out. Feeding it whole dwords decodes eight codes and leaves the - * rest of the step multiplying registers that were never written -- the shape the sibling unit - * documents, and the reason this helper takes the pair the way it does. */ +/* Eight codes -> eight f16, exact: E4M3 (4 exponent, 3 mantissa bits) and int8 both fit f16, so + * decoding is a widening, not a rounding. The pair decoder reads the two codes in a dword's low + * half, so each dword is decoded as two pairs (d and d >> 16): two dwords in, four pairs out. */ #if defined(__has_builtin) # if __has_builtin(__builtin_amdgcn_cvt_pk_f16_fp8) -# define R3D_HAS_FP8CVT 1 /* gfx11+: v_cvt_pk_f16_fp8, two codes to two f16, one instruction */ +# define R3D_HAS_FP8CVT 1 /* two codes to two f16; software on gfx1102, see the header */ # endif #endif #ifndef R3D_HAS_FP8CVT @@ -334,21 +210,15 @@ __device__ __forceinline__ void codes8_to_f16x4(const uint2 c, int cdt, const ui { const uint32_t d[2] = { c.x, c.y }; if (tbl && !cdt) { - /* The table: eight LDS reads for eight codes. Exact by construction -- the table is built - * from the codec below, one entry per bit pattern -- so a row's numbers do not move; what - * moves is where the work happens. r3d_fp8_dequant.h carries the reason and the measurement. - * Passing null tbl asks for the codec, which is how the board A/Bs the two in one binary. */ + /* The LDS table: eight reads for eight codes, built from the codec below, so the results + * are identical (r3d_fp8_dequant.h). A null tbl selects the codec. */ r3d_e4m3x8_ld(tbl, c, w); return; } if (!cdt) { - /* The instruction this wants: two codes to two f16, one op. clang has the builtin on this - * target's list and gfx1102 does not have the instruction: the ISA of this build contains - * zero v_cvt_pk_f16_fp8, so the builtin expands to the software decode below and - * eight codes cost ~100 instructions of exponent work. At M=1: 19.7 GB/s of codes, - * 8x above the 1.64 ms floor, ALU-bound. The builtin stays because it says what the operation - * is and a card with the instruction gets it for free; the fix for THIS card is a 256-entry - * f16 table in LDS, 512 bytes, 8 LDS reads where the ~100 ALU are, which is a tiling pass. */ + /* The codec: on gfx1102 the builtin expands to software, about 100 instructions per eight + * codes, which is why the table path exists. A target with v_cvt_pk_f16_fp8 gets the + * single instruction. */ w[0] = cvt_pk_f16_fp8(d[0]); w[1] = cvt_pk_f16_fp8(d[0] >> 16); w[2] = cvt_pk_f16_fp8(d[1]); @@ -364,25 +234,19 @@ __device__ __forceinline__ void codes8_to_f16x4(const uint2 c, int cdt, const ui /* The fold: the decoded code times the scale covering it, in f16 pairs. * - * The reference dequantises per element into f32 (`ScaledRows::at` = code * scale, one rounding) and - * then multiplies. Folding into the staged f16 costs one f16 rounding per weight -- half an ulp, - * 2.4e-4 relative, on a code whose own quantum is 2^-4 = 6.3e-2, a factor of 250. It buys the whole - * structure: the tile stays f16, the dot loop is untouched, the accumulators do not double, and the - * register file, which is the tightest thing in the prefill arm at 237 VGPRs, does not move. The - * alternative -- a per-block partial summed separately and scaled -- needs 64 more accumulators and - * spills. The number the board prints is this fold's. */ + * The reference dequantises each element into f32 (`ScaledRows::at`). Folding into the staged f16 + * costs one f16 rounding per weight (2.4e-4 relative, against the code's own 2^-4 quantum) and + * keeps the tile f16, the dot loop unchanged and the prefill arm's 237 VGPRs as they are. A + * per-block partial summed and scaled separately would need 64 more accumulators and spill. */ __device__ __forceinline__ uint32_t scale_pair(uint32_t w, float sc) { #if defined(__HIP_DEVICE_COMPILE__) - /* One f16 multiply, hardware, round-to-nearest. + /* One hardware f16 multiply (v_mul_f16), round to nearest, subnormals kept. * - * It is NOT f16x2_pack of an f32 product: that builtin is v_cvt_pkrtz_f16_f32, rounds toward - * zero, and r3d_codecs.h says out loud to call it only with values f16 already represents - * exactly. A folded weight is not one of those -- code 431 times a scale of 4.5e-5 is a product - * with eleven significant bits -- so the packer truncates, and truncation is a bias: every - * product moves toward zero, and it shows as rel_l2 2.8e-04 (half an f16 ulp, the - * whole of it) with the subnormal end flushed to zero on top. F16 arithmetic is one v_mul_f16 - * an element and rounds the way the reference's f32 multiply rounds. + * Not f16x2_pack of an f32 product: that is v_cvt_pkrtz_f16_f32, which rounds toward zero and + * is only for values f16 represents exactly (r3d_codecs.h). A folded weight generally is not + * (code 431 times a scale of 4.5e-5 has eleven significant bits), and truncation biases every + * product toward zero and flushes the subnormal end. */ const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16); const _Float16 a = __builtin_bit_cast(_Float16, lo16); @@ -416,9 +280,7 @@ __device__ __forceinline__ uint4 loadw8(const uint16_t* p) return *(const uint4*)p; } -/* Eight codes, the quantised head's 8-byte load, ordinary or streamed-once: the same builtin - * requirement as the 16-byte one, a native vector. Half the bytes of the bf16 head is the whole - * point of the form, and it is the load that changes. */ +/* The quantised head's 8-byte load of eight codes, ordinary or streamed-once. */ template __device__ __forceinline__ uint2 loadc8(const uint8_t* p) { @@ -438,7 +300,7 @@ __device__ __forceinline__ uint2 loadc8(const uint8_t* p) /* ============================================================ the prefill arm, M > 16 * - * y is f32 for logits_gemm and bf16 for gemm_nt; `YF32` is that choice, and it is the only one. + * y is f32 for logits_gemm and bf16 for gemm_nt (`YF32`). WQ reads the quantised head through h. */ template __global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) @@ -451,13 +313,8 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b const int tid = (int)threadIdx.x; __shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; /* the E4M3 decoder, 512 bytes */ -#ifndef R3D_NO_E4M3_TBL - if (WQ) r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* fills, then the barrier it holds */ + if (WQ) r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* fills, then barriers */ const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr; -#else - (void)sTbl; /* the board's A/B: the codec, unbuilt */ - const uint16_t* const r3d_tbl = (const uint16_t*)nullptr; -#endif const int m0 = (int)blockIdx.y * kTM; const int n0 = (int)blockIdx.x * kTN; const int rg = tid >> 4, cg = tid & 15; /* this lane's 8x8 square */ @@ -471,9 +328,8 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b const int m_r = m0 + rg * 8, n_c = n0 + cg * 8; for (int k0 = 0; k0 < K; k0 += kKC) { - /* Stage 128 rows x 4 chunks of eight a side: one uint4 a thread a side, two a side. Rows - * past M and codes past K stage as zeros, which is the clamping a ragged tail needs, keeps - * the loads straight-line and contributes nothing to a sum. */ + /* Stage 128 rows x 4 chunks of eight per side, two uint4 a thread a side. Rows past M and + * k past K stage as zeros, which contribute nothing to a sum. */ #pragma unroll for (int j = tid; j < kTM * (kKC / 8); j += kBlockThreads) { const int mm = j / (kKC / 8), c8 = j % (kKC / 8); @@ -489,10 +345,8 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b uint4 staged = make_uint4(0, 0, 0, 0); if (n < N && k < K) { if (WQ) { - /* Eight codes, one scale: a group of 8 sits inside one 128-column block, so - * the whole staged run shares the scale, and the tile's 32-code chunk sits - * inside one block too (128 % 32 == 0). The scale indexes the tile's row, not - * the lane's: the plane is (n-block, k-block), and this row is n. */ + /* Eight codes, one scale: the staged run lies inside one 128x128 block, and + * the scale is indexed by this staged row n, not the lane's output row. */ const uint2 c = *(const uint2*)(h.codes + (long long)n * h.code_row + k); uint32_t w[4]; codes8_to_f16x4(c, h.cdt, r3d_tbl, w); @@ -524,8 +378,8 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b __syncthreads(); } - /* The store, eight columns at a time: 32 bytes of f32, 16 of bf16. Guarded row by row, so a - * ragged M writes nothing and a ragged N writes whole runs of columns it owns. */ + /* The store, eight columns at a time: 32 bytes of f32, 16 of bf16. Rows past M are skipped + * and a ragged N tail is written column by column. */ #pragma unroll for (int i = 0; i < 8; ++i) { const int m = m_r + i; @@ -548,8 +402,8 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b *(uint4*)(row + n_c) = make_uint4(p[0], p[1], p[2], p[3]); } } else { - /* The ragged N tail, unrolled: a dynamic index into acc would put the 64 accumulators - * in local memory, and the compiler says so -- 80 KiB of spill against a 64 KiB limit. */ + /* Unrolled: a dynamic index into acc would put the 64 accumulators in local memory + * (80 KiB of spill against a 64 KiB limit). */ #pragma unroll for (int j = 0; j < 8; ++j) { if (n_c + j < N) { @@ -563,10 +417,9 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b /* ============================================================ the decode arm, M <= 16 * - * A wave is MT activation rows by KLW = 32/MT weight rows, one accumulator a lane, the whole of k in - * ascending order. The activation tile is block-wide, so every wave stages it -- a wave whose row is - * past the vocabulary stages too and simply does not read, which is the rule that keeps a tile from - * coming up with holes. + * A wave is MT activation rows by KLW = 32/MT weight rows, one accumulator a lane over all of k in + * ascending order. The activation tile is block-wide, so every thread stages it, including lanes + * whose weight row is past the vocabulary; those lanes skip the dot and the store. */ template __global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(4) @@ -578,13 +431,8 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_ __shared__ __align__(16) uint16_t sX[MT * kChunkK]; /* f16, MT rows x chunk, swizzled */ __shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; -#ifndef R3D_NO_E4M3_TBL if (WQ) r3d_e4m3_f16_init(sTbl, (int)threadIdx.x, kBlockThreads); const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr; -#else - (void)sTbl; - const uint16_t* const r3d_tbl = (const uint16_t*)nullptr; -#endif const int lane = (int)threadIdx.x & (kWave - 1); const int warp = (int)threadIdx.x / kWave; @@ -592,8 +440,7 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_ const int n = (int)blockIdx.x * (kWaves * KLW) + warp * KLW + lane / MT; const bool live = n < N; - /* A dead lane reads row N-1, a row that exists: the loads stay uniform and nothing is read out - * of bounds; its result is dropped at the store. */ + /* A dead lane's row pointer is clamped to N-1 so it never points past the head. */ const uint16_t* wrow = w + (long long)(live ? n : N - 1) * K; const int nsteps = M < MT ? M : MT; float acc = 0.0f; @@ -611,8 +458,8 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_ if (live) { const uint16_t* wp = wrow + k0; const uint8_t* cp = h.codes + (long long)(live ? n : N - 1) * h.code_row + k0; - /* One scale a chunk: kChunkK is the scale block, so the lane's 128 codes are inside a - * single (n-block, k-block) and the load is one scalar per 128 codes. */ + /* One scale a chunk: kChunkK equals the scale block, so a lane's 128 codes share one + * (n-block, k-block). */ const float sc = WQ ? scale_at(h, live ? n : N - 1, k0) : 0.0f; const int kend = K - k0 < kChunkK ? K - k0 : kChunkK; /* a multiple of 8: the * launcher takes K % 8 == 0 */ @@ -673,9 +520,9 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ void* y = (void*)(uintptr_t)yv; hipStream_t s = (hipStream_t)(uintptr_t)stream; - /* The head's form is the shim's answer, resolved out of the container before the launch; this - * is where its pointers are checked as pointers. The declared entries pass null and get the - * plain bf16 head, which is what r3d.h's signature for them describes. */ + /* `hq` is the quantised head the shim resolved from the container; its pointers are checked + * here. The declared entries pass null and get the plain bf16 head their r3d.h signature + * describes. */ HeadQ h; std::memset(&h, 0, sizeof h); const int wq = hq != nullptr; @@ -685,9 +532,8 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ if (h.sdt < 0 || h.sdt > 2 || h.cdt < 0 || h.cdt > 1) return -2; if (h.code_row & 7) return -3; /* 8-byte code loads, one row a stride */ if (h.scale_row & (h.sdt == 2 ? 3 : 1)) - return -3; /* a scale row is 4 bytes a column for f32, 2 for - * bf16/f16: a plane of 3 columns is 6 bytes and the - * loads land on even addresses. K = 320 is legal. */ + return -3; /* scale loads are 4 bytes (f32) or 2 (bf16/f16), so a + * 3-column 16-bit row (6 bytes, K = 320) is legal */ if (((long long)(uintptr_t)h.codes & 7) || ((long long)(uintptr_t)h.scale & 3)) return -5; } @@ -725,10 +571,9 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ return hipGetLastError() == hipSuccess ? 0 : -4; } -/* The shim's shared body: the checks the two ops agree on, then the launch. `y_is_f32` is the op's - * schema (logits are f32 because every sampler stage reads f32; gemm_nt's y is bf16), nkey/kkey the - * axis names libref spells them with ("n_vocab"/"n_embd" and "N"/"K" -- ref_logits_gemm is - * gemm_nt_impl with the axes renamed, so this body is shared by construction, not by imitation). */ +/* The shim body both ops share (ref_logits_gemm is gemm_nt_impl with the axes renamed). + * `y_is_f32` is the op's output dtype; nkey/kkey are libref's axis names ("n_vocab"/"n_embd" or + * "N"/"K"). */ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, const char* kkey) { if (a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data) @@ -744,23 +589,16 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, int joined = 0; /* ---- the head's stored form --------------------------------------------------------------- - * The band's `dtype` key is the ACTIVATION's dtype: on this graph `dtype=bf16` with the head - * stored as E4M3 codes and a bf16 scale per 128x128 block, in two planes of one container. The - * stored form is answered by a layout hook -- `ref_layout_head`, transcribed below as - * r3d_layout_logits_head, the way the w2a8 hook transcribed ref_layout_gemm_q -- and this is - * its launch-side twin: read the header, read the two planes, dispatch on what they are. The - * checks and their order are the reference's `scaled_rows`: the roles, then the dtypes and - * blocks, then the coverage (which needs N and K, so it sits below, where the reference has - * them already). - * - * The bf16 head is served as is: the container's header, not the row's preference, picks - * the form. Two forms, one row, chosen by the bytes. + * The launch-side twin of r3d_layout_logits_head: a `rad.planes` header means the quantised + * head, read as its two planes; no header means a plain bf16 head. The checks follow the + * reference's `scaled_rows` in order: roles, then dtypes and blocks, then coverage (below, + * once N and K are known). */ const RadPlanesHeader* ph = rad_planes_header(r3d_p(w)); if (ph) { - if (!y_is_f32) return R3D_NO(RAD_E_DTYPE); /* logits are f32; the bf16-y row keeps a bf16 head */ + if (!y_is_f32) return R3D_NO(RAD_E_DTYPE); /* the bf16-y row takes a bf16 head only */ if (rad_planes_find(r3d_p(w), "zero", nullptr)) - return R3D_NO(RAD_E_DTYPE); /* codes+scale+zero is gemm_nt_q's asymmetric grid: w2a8 */ + return R3D_NO(RAD_E_DTYPE); /* codes+scale+zero: gemm_nt_q's asymmetric grid */ if (ph->n_planes != 2) return R3D_NO(RAD_E_DTYPE); const uint8_t* cb = (const uint8_t*)rad_planes_find(r3d_p(w), "codes", &ce); const uint8_t* sb = (const uint8_t*)rad_planes_find(r3d_p(w), "scale", &se); @@ -770,17 +608,16 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, return R3D_NO(RAD_E_DTYPE); /* codes must be one code an element, tiled plain */ if (ce->dtype != RAD_F8E4M3 && ce->dtype != RAD_I8) { if (rad_dtype_bytes(ce->dtype, 8) < 8) - return R3D_NO(RAD_E_DTYPE); /* sub-byte codes: w4a16's ground, not this form */ + return R3D_NO(RAD_E_DTYPE); /* sub-byte codes */ return R3D_NO(RAD_E_DTYPE); /* e5m2 and the rest: no decoder here */ } if (se->kind != RAD_PLANE_TILED) return R3D_NO(RAD_E_DTYPE); if (se->dtype == RAD_BF16) h.sdt = 0; else if (se->dtype == RAD_F16) h.sdt = 1; else if (se->dtype == RAD_F32) h.sdt = 2; - else return R3D_NO(RAD_E_DTYPE); /* an integer scale is not a float_scale_dt */ + else return R3D_NO(RAD_E_DTYPE); /* not in float_scale_dt's set */ if (se->block[0] != kFp8Block || se->block[1] != kFp8Block) - return R3D_NO(RAD_E_SHAPE); /* per-(row,group) scales are gemm_nt_q's grid; per-row - * is not the indexing this kernel does */ + return R3D_NO(RAD_E_SHAPE); /* only 128x128 blocks; other grids are gemm_nt_q's */ h.codes = cb; h.scale = sb; h.code_row = ce->row_bytes; h.scale_row = se->row_bytes; h.cdt = ce->dtype == RAD_I8 ? 1 : 0; joined = 1; @@ -804,9 +641,8 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, if (r3d_numel(w) < N * K) return R3D_NO(RAD_E_SHAPE); if (!r3d_contig(w)) return R3D_NO(RAD_E_STRIDE); /* N rows of K contiguous codes */ if (joined) { - /* The coverage checks, `scaled_rows`' last block: the planes must cover the band, and the - * scale plane covers it by blocks -- ceil, so a ragged vocabulary is fine (131 rows need 2 - * scale rows) and a plane one row short is not. */ + /* `scaled_rows`' coverage checks: the planes must cover the band, the scale plane by + * ceil-divided blocks, so a ragged vocabulary is fine (131 rows need 2 scale rows). */ const long long sb_r = (N + kFp8Block - 1) / kFp8Block; const long long sb_c = (K + kFp8Block - 1) / kFp8Block; if (ce->rows != N || ce->cols != K) return R3D_NO(RAD_E_SHAPE); @@ -820,7 +656,7 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, return R3D_NO(RAD_E_ALIGN); const int sk = (int)r3d_geti_or(a, "sk", 1); - if (sk > 1) return R3D_NO(RAD_E_SHAPE); /* the grid is vocab-wide at every M, see the header */ + if (sk > 1) return R3D_NO(RAD_E_SHAPE); /* see the header's refusals */ const int kb = (int)r3d_geti_or(a, "kb", 0); const int nt = (int)r3d_geti_or(a, "nt", 0); @@ -835,10 +671,9 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, : e == -3 ? RAD_E_STRIDE : e == -5 ? RAD_E_ALIGN : RAD_E_DEVICE); } -/* The reference's `enc_scaled_rows` and `float_scale_dt`, inlined: libref keeps them static inline in - * its own header, so a plugin that transcribes ref_layout_head transcribes them with it. Checks and - * order are its, unchanged: affine, untransformed, two planes, the roles in order, codes tiled with - * block {1,1} and a code dtype it admits, the scale tiled with a float dtype. */ +/* The reference's `enc_scaled_rows` and `float_scale_dt`, transcribed (libref keeps them static + * inline), checks in its order: affine, untransformed, two planes, the roles in order, codes tiled + * with block {1,1} in an admitted dtype, the scale tiled with a float dtype. */ bool float_scale_dt(uint32_t dt) { return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32; @@ -889,22 +724,12 @@ extern "C" int r3d_rad_gemm_nt_bf16_tiled(const RadArgs* a, RadStream s) return rad_gemm_run(a, s, 0, "N", "K"); } -/* The head's layout hook, `ref::ref_layout_head` transcribed: operand 1 of - * logits_gemm, two planes, codes and one scale, untransformed -- and the answer is the container's - * own form. It moves no byte, and its `relayout` writer (below) exists for the round-trip: this is - * a reader, which is what - * the mapped tier asks for when a weight's stored form is not the container's. Operand 0 (the - * activations) and a one-plane selection are declined as `layout_scaled` declines them, and so is - * every other encoding: a silent no-op on a head is the worst failure a row can have. */ -/* The head's WRITER. A layout query that answers RAD_OK is a promise the ABI makes to the loader -- - * "out describes the stored form, and relayout will produce it" (rad_abi.h) -- and the load step - * holds the row to it. The container stores the quantiser's pair; the plan wants one operand; the - * row that owns the band assembles it, losslessly, with rad_planes_relayout: the header, the - * entries and each plane's rows, copied. - * No code is transformed and no number is derived -- a kernel doing arithmetic - * here would make the served numbers depend on which library loaded the container (rad_abi.h). - * The query and the writer share the plan through rad_planes_plan, so they cannot disagree. The - * operand guard is the hook's own rule repeated: a call routed to the wrong slot writes nothing. */ +/* The head's relayout writer. A layout query that answers RAD_OK promises the loader that + * relayout will produce the described form (rad_abi.h). The container stores the quantiser's + * pair and the plan wants one operand, so rad_planes_relayout assembles it losslessly: the header, + * the entries and each plane's rows, copied. No code is transformed, so the served numbers do not + * depend on which library loaded the container. The query and the writer share one plan + * (rad_planes_plan). The operand guard repeats the hook's, so a misrouted call writes nothing. */ extern "C" int r3d_relayout_logits_head(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* planes, int n_planes, void* dst, @@ -915,6 +740,10 @@ extern "C" int r3d_relayout_logits_head(const RadParam* p, int n_p, int operand, return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes); } +/* The head's layout hook, `ref::ref_layout_head` transcribed: operand 1 of logits_gemm, two planes + * (codes and one scale), untransformed, answered with the container's own form and no byte moved. + * Operand 0 (the activations), a one-plane selection and every other encoding are declined, as + * `layout_scaled` declines them. */ extern "C" int r3d_layout_logits_head(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* planes, int n, RadLayout* out) diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index e8084729..5903982f 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -198,6 +198,7 @@ set(R4D_UNITS "r4d_lora_bf16|" "r4d_dflash_conv_t2_g16_bf16|" "r4d_dflash_select_bf16|" + "r4d_dflash_tree_bf16|" # Routed MoE: router, scatter, the grouped block-scaled fp8 GEMM and gather, in one unit because # the other three only feed the GEMM. "r4d_moe|" diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 546973d0..64350406 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -82,6 +82,10 @@ struct R4DArgs { // The engine's chained launch (RadKernelChainFn, r4d_chain.h): the decode path launches its // chained forms. fill_paged sets it from the resolved `chain` parameter. int chain; + // A tree verify (attn_paged_qrow_tree, docs/OPS.md): RadBatch::spec_parent, one int32 a query + // row, -2 for an ordinary causal row, else the row's parent's index within its sequence's rows + // (-1 for the block's first). Read only by the O_TREE instances; null elsewhere. + const int* spec_parent; }; // Rows of q and out. The split-KV scratch is laid out by dense query row, so the host sizing hook @@ -129,6 +133,9 @@ long r4d_attn_decode_h128_gqa2w_scratch_bytes(const R4DArgs* a); // ...with q at R4DArgs::q_ld (attn_paged_qrow). int r4d_attn_decode_h256_gqa2_qld_fp8kv (const R4DArgs* a, hipStream_t stream); int r4d_attn_decode_h256_gqa2_qld_bf16kv (const R4DArgs* a, hipStream_t stream); +// ...and a tree verify's mask from R4DArgs::spec_parent (attn_paged_qrow_tree). +int r4d_attn_decode_h256_gqa2_qld_tree_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h256_gqa2_qld_tree_bf16kv (const R4DArgs* a, hipStream_t stream); // The geometry the attention kernels above are compiled for, so a caller can check a model // before the first launch. void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows); @@ -291,18 +298,22 @@ void r4d_ar_ipc_enable_peer(long peer); // VRAM. Zeroed; the address is valid on every card and the CPU. Startup-only. long r4d_ar_host_alloc(long size); void r4d_ar_host_free(long p); +// `stage`, the last argument of every 2-rank kernel below: 0, or a host-mailbox instance's mirror +// of its slots in this card's VRAM (same layout), which the reader's push check fills as it reads +// the slot so the reduce reads VRAM instead of the link a second time (r4d_ar_seq.h). // Exact sum, fp32 accumulate, bf16 / fp16 / fp32 payload (dtype 0 / 1 / 2). void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long stream, long nblocks, long nthreads, long drain, - long acq); + long acq, long stage = 0); // Same topology, with the wire payload Walsh-Hadamard rotated and quantised to 6 bits per element // in groups of 64 (plus a bf16 scale per group). Lossy; bf16 / fp16 payload only. loc_pack is this // rank's own packed copy, so the reduce folds exactly the bytes it sent. void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long loc_pack, long slot_stride_bytes, long scale_off_bytes, long inp, long out, long n_elem, long dtype, - long stream, long nblocks, long nthreads, long drain, long acq); + long stream, long nblocks, long nthreads, long drain, long acq, + long stage = 0); // The exact all-reduce of `y` [M][n] bf16 with hc_write as its epilogue: h[r][c*n + i] += // inj[r][c] * y[r][i] over the reduced y, byte-identical to all_reduce then hc_write. `irow` and // `hrow` are the pitches of inj [M][hc] and h [M][hc*n] in elements; y is tight. A non-zero `gate` @@ -311,7 +322,7 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_fla void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long stream, long nblocks, long nthreads, - long drain, long acq, long gate, long gate_ctr); + long drain, long acq, long gate, long gate_ctr, long stage = 0); // The same with the MoE gather as its prologue: y is produced, not read, from the routed experts' // rows `ye` [M*top_k][ye_ld] summed to token order by weights `ew` [M][ew_ld] and `sorted` // [M*top_k], with the shared arm `sh` [M][sh_ld] and its gate `sg` folded when both are non-zero. @@ -323,7 +334,8 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long n, long hc, long irow, long hrow, long ye, long ew, long sorted, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long stream, long nblocks, long nthreads, - long drain, long acq, long inv, long gate, long gate_ctr); + long drain, long acq, long inv, long gate, long gate_ctr, + long stage = 0); // r4d_ar_hc_write and r4d_ar_gather_hc_write on the rotated 6-bit wire (r4d_ar_oneshot_2rank_wht6's // format, loc_pack and scratch split): byte-identical to all_reduce on that wire then hc_write, // with `ye` non-zero preceded by moe_gather. Gather operands as r4d_ar_gather_hc_write; its slot @@ -336,7 +348,7 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, l long irow, long hrow, long ye, long ew, long sorted, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long stream, long nblocks, long nthreads, long drain, long acq, - long gate, long gate_ctr); + long gate, long gate_ctr, long stage = 0); int r4d_ar_max_blocks(void); // the two 2-rank kernels void r4d_ar_wht6_dims(int* group, int* bits, int* chunk_elems); // rotated-6-bit payload only @@ -349,7 +361,7 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream, long nblocks, long nthreads, long drain, long acq, long dpitch, - long spitch); + long spitch, long stage = 0); // ---- all-reduce: one-shot, push, 4 or 8 ranks over P2P ------------------------------------- // The same algorithm at width (r4d_ar_oneshot_Nrank_exact.hip). Peer arguments are in ascending @@ -703,8 +715,8 @@ void r4d_moe_gemm_pin_down_dec(int pin); void r4d_hc_read_pin_prefill(int form); // Test hook: pins the gated residual read's decode kernels. 0 is the launcher's rule (kernels A and // B as one grid at one to seven rows where the per-stream counters exist, the tiled up-mix's K -// passes pipelined from eight rows), 1 the kernels the rule replaced (A, then the up-mix in a second -// launch; the tiled up-mix's passes in sequence). Bit-identical; r4d_selftest compares their bytes +// passes pipelined from eight rows), 1 the two-grid form (A, then the up-mix in a second launch; +// the tiled up-mix's passes unpipelined). Bit-identical; r4d_selftest compares their bytes // and --perfhc times both. void r4d_hc_read_pin_decode(int form); // Test hook: pins the MLA matrix row's key load. 0 is the launcher's rule (sixteen-byte vectors @@ -821,7 +833,7 @@ int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flag int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int q_ld, int s_ld, long stream, int nblocks, int nthreads, int drain, int acq, int wire, - long loc_pack, long loc_scale_off, long wp = 0); + long loc_pack, long loc_scale_off, long wp = 0, long stage = 0); int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void); // Its rotated int8 form, as r4d_rmsnorm_had_quant_i8g: the reduction and the norm unchanged, the // norm's pass quantised by had_quant_act_i8g's rule. No post-norm. @@ -831,7 +843,7 @@ int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch, long peer_ int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int q_ld, int s_ld, long stream, int nblocks, int nthreads, int drain, int acq, int wire, - long loc_pack, long loc_scale_off); + long loc_pack, long loc_scale_off, long stage = 0); // The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of // the reduced `x` (`wp`), the residual add, the [1] scalar (`sc`), the norm (`w`) and the w4a8 @@ -840,7 +852,7 @@ int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags long seq_ctrs, long slot_stride16, long x, long res, long w, long wp, long sc, int sc_f32, long y, long q, long s, int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks, - int drain, int acq); + int drain, int acq, long stage = 0); // ...and at four ranks, on the wide family's transport: r4d_ar_oneshot_4rank_exact's IPC // arguments (peers in ascending rank, this rank's own, the counters, the slot stride), `pub`, the // engine's link gate with the instance's landed counter (0 for none; r4d_ar_seq.h), and, with @@ -913,7 +925,7 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags, long x, long residual, long wgain, long out_bf16, long q, long s, int M, int K, int had, float eps, float wadd, long stream, int nblocks, int nthreads, int drain, int acq, - int wire = 0); + int wire = 0, long stage = 0); // An elementwise gated product, then the same Hadamard and int8 quantiser. Mode 0 is silu(a)*b // (down_proj's input, vLLM's silu_and_mul); mode 1 is sigmoid(a)*b (o_proj's input, since // Qwen3_5Attention computes attn_output * sigmoid(gate)). Strides are in elements and may be 0 for diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 471cd894..3ca844b9 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -99,6 +99,8 @@ int rv_barrier(int world) { struct ArInst { int rank = 0, world = 0; long my_scratch = 0, my_flags = 0, my_seq = 0, locpack = 0; + /* A 2-rank host-mailbox instance's VRAM mirror of its slots, 0 otherwise (r4d_ar_seq.h). */ + long my_stage = 0; long peer_scratch[R4D_MAX_PEERS] = { 0 }; long peer_flags [R4D_MAX_PEERS] = { 0 }; long slot_bytes = 0; /* per-slot capacity, 16-byte aligned */ @@ -350,6 +352,17 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, } sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen)); + /* A host mailbox is read over the link past every cache, so the 2-rank kernels' push check + * copies what it reads into this VRAM mirror for the reduce, crossing the link once + * (r4d_ar_seq.h). Coarse-grained: only this rank's kernels touch it, each block its own words. + * The wide family has no push check and reads its slots once. Host-memory slots free the same + * VRAM over P2P, so the mirror keeps the footprint where the P2P instance has it. */ + long stg = 0; + if (host && world == 2) { + R4D_TRY("ar_ipc_alloc(stage)", + stg = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 0, handle, &hlen)); + } + /* This rank's own packed copy, for the rotated 6-bit wire only: the reduce must fold exactly * the bytes it sent. The 6-bit payload is 3/8 of the bf16 message and the f32 scales 1/32 of * it, laid out from half the slot; a row padded to whole 512-element chunks @@ -365,6 +378,7 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, in->my_flags = fl; in->my_seq = sq; in->locpack = lp; + in->my_stage = stg; in->gate_ctr = sq + 2L * maxb * 4; /* the word after the sequence counters (r4d_ar_seq.h) */ { @@ -475,6 +489,7 @@ void release(ArInst* in) { } r4d_ar_ipc_free(in->my_seq); r4d_ar_ipc_free(in->locpack); + r4d_ar_ipc_free(in->my_stage); delete in; } @@ -799,7 +814,7 @@ extern "C" int r4d_rad_ar_gather_2rank(const RadArgs* a, RadStream s) { r4d_ar_gather_2rank(in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq, in->slot16, c.inp, c.out, c.numel, in->dtype, in->rank, (long)row, (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, - c.acq, (long)dpitch, (long)spitch)); + c.acq, (long)dpitch, (long)spitch, in->my_stage)); return RAD_OK; } @@ -869,7 +884,8 @@ extern "C" int r4d_rad_ar_oneshot_2rank_exact(const RadArgs* a, RadStream s) { r4d_ar_oneshot_2rank_exact(c.in->peer_scratch[0], c.in->my_scratch, c.in->peer_flags[0], c.in->my_flags, c.in->my_seq, c.in->slot16, c.inp, c.out, c.numel, c.in->dtype, - (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq)); + (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, + c.in->my_stage)); return RAD_OK; } @@ -911,7 +927,8 @@ extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) { r4d_ar_oneshot_2rank_exact(c.in->peer_scratch[0], c.in->my_scratch, c.in->peer_flags[0], c.in->my_flags, c.in->my_seq, c.in->slot16, c.inp, c.out, c.numel, c.in->dtype, - (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq)); + (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, + c.in->my_stage)); return RAD_OK; } @@ -928,7 +945,8 @@ extern "C" int r4d_rad_ar_oneshot_2rank_wht6(const RadArgs* a, RadStream s) { c.in->peer_flags[0], c.in->my_flags, c.in->my_seq, c.in->locpack, c.in->slot_bytes, c.in->slot_bytes / 2, c.inp, c.out, c.numel, c.in->dtype, - (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq)); + (long)(uintptr_t)s, c.nblocks, c.nthreads, c.drain, c.acq, + c.in->my_stage)); return RAD_OK; } @@ -1283,7 +1301,7 @@ extern "C" int r4d_rad_ar_ln_had_quant_i8(const RadArgs* a, RadStream s) { r4d_addr(q), r4d_addr(sc), (int)M, (int)K, (int)had, eps, wadd, (long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, - wire)); + wire, in->my_stage)); return RAD_OK; } @@ -1404,7 +1422,7 @@ static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) { r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32, (int)rp, (int)yp, (int)qp, (int)sp, (long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire, - in->locpack, in->slot_bytes / 2) + in->locpack, in->slot_bytes / 2, in->my_stage) : r4d_ar_rmsnorm_quant_fp8( in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq, @@ -1412,7 +1430,7 @@ static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) { r4d_addr(sc), (int)M, (int)K, eps, wadd, w_f32, (int)rp, (int)yp, (int)qp, (int)sp, (long)(uintptr_t)s, nblocks, nthreads, cfgv.drain, cfgv.acq, wire, - in->locpack, in->slot_bytes / 2, wpo ? r4d_addr(wpo) : 0); + in->locpack, in->slot_bytes / 2, wpo ? r4d_addr(wpo) : 0, in->my_stage); return e == 0 ? RAD_OK : RAD_E_SHAPE; } @@ -1491,7 +1509,7 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) { v.sl ? (v.sl->dtype == RAD_F32) : 0, r4d_addr(v.ob), r4d_addr(v.q), r4d_addr(v.sc), (int)M, (int)K, (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), v.w->dtype == RAD_F32, (int)v.rp, (int)v.yp, (long)(uintptr_t)s, nblocks, cfgv.drain, - cfgv.acq); + cfgv.acq, in->my_stage); return e == 0 ? RAD_OK : RAD_E_SHAPE; } @@ -1672,7 +1690,7 @@ extern "C" int r4d_rad_ar_gather_hc_write(const RadArgs* a, RadStream s) { r4d_addr(ew), r4d_addr(so), sh ? r4d_addr(sh) : 0L, sh ? r4d_addr(sg) : 0L, (long)ye_ld, (long)ew_ld, (long)sh_ld, (long)sg_ld, (long)top_k, (long)sig, (long)(uintptr_t)s, nblocks, R4D_AR_WHT6_FUSED_THREADS, cfgv.drain, cfgv.acq, - early, early ? in->gate_ctr : 0L); + early, early ? in->gate_ctr : 0L, in->my_stage); if (rc != 0) return RAD_E_SHAPE; return early ? RAD_LINK_ENDED : RAD_OK; } @@ -1687,7 +1705,7 @@ extern "C" int r4d_rad_ar_gather_hc_write(const RadArgs* a, RadStream s) { sh ? r4d_addr(sh) : 0L, sh ? r4d_addr(sg) : 0L, (long)ye_ld, (long)ew_ld, (long)sh_ld, (long)sg_ld, (long)top_k, (long)sig, (long)(uintptr_t)s, nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq, has_inv ? (long)(uintptr_t)a->scratch : 0L, early, - early ? in->gate_ctr : 0L); + early ? in->gate_ctr : 0L, in->my_stage); if (rc != 0) return RAD_E_SHAPE; return early ? RAD_LINK_ENDED : RAD_OK; } @@ -1803,7 +1821,7 @@ extern "C" int r4d_rad_ar_hc_write(const RadArgs* a, RadStream s) { in->locpack, in->slot_bytes, in->slot_bytes / 2, r4d_addr(y), r4d_addr(inj), r4d_addr(h), (long)M, (long)n, (long)hc, (long)irow, (long)hrow, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, (long)(uintptr_t)s, nblocks, R4D_AR_WHT6_FUSED_THREADS, - cfgv.drain, cfgv.acq, early, early ? in->gate_ctr : 0L); + cfgv.drain, cfgv.acq, early, early ? in->gate_ctr : 0L, in->my_stage); if (rc != 0) return RAD_E_SHAPE; return early ? RAD_LINK_ENDED : RAD_OK; } @@ -1816,7 +1834,7 @@ extern "C" int r4d_rad_ar_hc_write(const RadArgs* a, RadStream s) { in->my_seq, in->slot16, r4d_addr(y), r4d_addr(inj), r4d_addr(h), (long)M, (long)n, (long)hc, (long)irow, (long)hrow, (long)(uintptr_t)s, nblocks, cfgv.nthreads, cfgv.drain, cfgv.acq, early, - early ? in->gate_ctr : 0L)); + early ? in->gate_ctr : 0L, in->my_stage)); return early ? RAD_LINK_ENDED : RAD_OK; } diff --git a/libr4d/r4d_ar_gather_2rank.hip b/libr4d/r4d_ar_gather_2rank.hip index d6fb113f..1f9d6ceb 100644 --- a/libr4d/r4d_ar_gather_2rank.hip +++ b/libr4d/r4d_ar_gather_2rank.hip @@ -60,7 +60,7 @@ __global__ void r4d_ar_gather_2rank_kernel( const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, int n16, int slot_stride16, int rank, int row16, int dp16, int sp16, int drain, int acq, - unsigned int nbw) { + unsigned int nbw, long stage) { const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe @@ -68,6 +68,7 @@ __global__ void r4d_ar_gather_2rank_kernel( const int slot = (int)s_slot; int4* ps = peer_base + (size_t)slot * slot_stride16; const int4* ms = my_base + (size_t)slot * slot_stride16; + const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h) const int w = (n16 + nb - 1) / nb; const int start = b * w; @@ -116,8 +117,10 @@ __global__ void r4d_ar_gather_2rank_kernel( __syncthreads(); if (acq) __threadfence_system(); r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { - for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + for (int k = start + tid; k < end; k += nt) + h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k); }); + ms = r4d_archk_moved(ms, md); // Place the peer's slice, now staged in this rank's scratch. { @@ -136,7 +139,8 @@ __global__ void r4d_ar_gather_2rank_kernel( void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long rank, long row_elems, long stream_i, long nblocks, - long nthreads, long drain, long acq, long dpitch, long spitch) { + long nthreads, long drain, long acq, long dpitch, long spitch, + long stage) { hipStream_t st = (hipStream_t)stream_i; const int esize = (dtype == 2) ? 4 : 2; const long nbytes = (long)n_elem * esize; @@ -177,5 +181,5 @@ void r4d_ar_gather_2rank(long peer_scratch, long my_scratch, long peer_flags, lo r4d_ar_gather_2rank_kernel<<>>( (const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, - (int)slot_stride16, (int)rank, row16, dp16, sp16, (int)drain, (int)acq, nbw); + (int)slot_stride16, (int)rank, row16, dp16, sp16, (int)drain, (int)acq, nbw, stage); } diff --git a/libr4d/r4d_ar_ln_had_quant_i8.hip b/libr4d/r4d_ar_ln_had_quant_i8.hip index ccf5c776..1828eeab 100644 --- a/libr4d/r4d_ar_ln_had_quant_i8.hip +++ b/libr4d/r4d_ar_ln_had_quant_i8.hip @@ -125,7 +125,7 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, int M, int K, int slot_stride16, int drain, int acq, - float eps, float wadd, float rnorm, unsigned int nbw) { + float eps, float wadd, float rnorm, unsigned int nbw, long stage) { constexpr int VPL = HAD / 32, NW = THR / 32; constexpr int MAXB = R4D_ARN_MAXVALS / VPL; extern __shared__ float lds[]; @@ -146,6 +146,7 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( const unsigned int sq = s_seq; int4* ps = peer_base + (size_t)s_slot * slot_stride16; const int4* ms = my_base + (size_t)s_slot * slot_stride16; + const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h) // WIRE == 6 only. The slot is split as in the standalone compressed all-reduce: packed symbols // from the base, bf16 group scales from halfway. Chunk indices are global over the [M, K] @@ -263,7 +264,8 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) { if constexpr (WIRE == 0) { const int wpr = K >> 3; - for (int k = r0 * wpr + tid; k < r1 * wpr; k += THR) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + for (int k = r0 * wpr + tid; k < r1 * wpr; k += THR) + h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k); } else { for (int ci = wave; ci < cpb; ci += NW) { const int c = c00 + ci; @@ -271,25 +273,32 @@ __global__ __launch_bounds__(THR) void r4d_ar_ln_had_quant_i8_kernel( const unsigned int cd = (unsigned)c * (ARN_CBYTES / 4); #pragma unroll for (int w4 = 0; w4 + 4 <= ARN_NWORD; w4 += 4) - h += r4d_archk_u4(*(const uint4*)(pb + w4 * 4 * ARN_WV + lane * 16), + h += r4d_archk_u4(r4d_archk_keep((const uint4*)(pb + w4 * 4 * ARN_WV + lane * 16), md), cd + (unsigned)(w4 * ARN_WV + lane * 4)); if constexpr (ARN_NWORD % 4 >= 2) { - const uint2 u = *(const uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8); + const uint2 u = + r4d_archk_keep((const uint2*)(pb + (ARN_NWORD & ~3) * 4 * ARN_WV + lane * 8), md); const unsigned int e = cd + (unsigned)((ARN_NWORD & ~3) * ARN_WV + lane * 2); h += r4d_archk_mix(u.x, e) + r4d_archk_mix(u.y, e + 1u); } if constexpr (ARN_NWORD % 2 == 1) - h += r4d_archk_mix(*(const unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4), + h += r4d_archk_mix( + r4d_archk_keep((const unsigned int*)(pb + (ARN_NWORD - 1) * 4 * ARN_WV + lane * 4), md), cd + (unsigned)((ARN_NWORD - 1) * ARN_WV + lane)); #pragma unroll for (int t = 0; t < ARN_ITERS; ++t) { const int gl = t * ARN_GPW + gw; - if (lig == 0) h += r4d_archk_mix(m_sc[c * ARN_CG + gl], R4D_ARCHK_U16 + (unsigned)(c * ARN_CG + gl)); + if (lig == 0) + h += r4d_archk_mix(r4d_archk_keep(&m_sc[c * ARN_CG + gl], md), + R4D_ARCHK_U16 + (unsigned)(c * ARN_CG + gl)); } } } }); + ms = r4d_archk_moved(ms, md); + m_pay = r4d_archk_moved(m_pay, md); + m_sc = r4d_archk_moved(m_sc, md); // The peer's rows are now in my scratch, in the same [M, K] layout as X. const __hip_bfloat16* P = (const __hip_bfloat16*)ms; @@ -475,7 +484,8 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags, long seq_ctrs, long slot_stride16, long x, long residual, long wgain, long out_bf16, long q, long s, int M, int K, int had, float eps, float wadd, - long stream, int nblocks, int nthreads, int drain, int acq, int wire) { + long stream, int nblocks, int nthreads, int drain, int acq, int wire, + long stage) { if (K % 16) throw std::runtime_error("r4d ar_ln_had_quant_i8: K must be a multiple of 16"); if (M < 1) throw std::runtime_error("r4d ar_ln_had_quant_i8: M must be positive"); if (had < 2 || (had & (had - 1))) throw std::runtime_error( @@ -509,7 +519,7 @@ void r4d_ar_ln_had_quant_i8(long peer_scratch, long my_scratch, long peer_flags, (__hip_bfloat16*)residual, (const __hip_bfloat16*)wgain, (__hip_bfloat16*)out_bf16, \ (signed char*)q, (float*)s, (int4*)peer_scratch, (const int4*)my_scratch, \ (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, M, K, (int)slot_stride16, \ - drain, acq, eps, wadd, rn, (unsigned)nbw) + drain, acq, eps, wadd, rn, (unsigned)nbw, stage) #define R4D_ARN_T(H, W, R) switch (thr) { \ case 128: R4D_ARN_LAUNCH(H, 128, W, R); break; \ case 256: R4D_ARN_LAUNCH(H, 256, W, R); break; \ diff --git a/libr4d/r4d_ar_oneshot_2rank_exact.hip b/libr4d/r4d_ar_oneshot_2rank_exact.hip index 67f36d71..8a3da1b6 100644 --- a/libr4d/r4d_ar_oneshot_2rank_exact.hip +++ b/libr4d/r4d_ar_oneshot_2rank_exact.hip @@ -64,7 +64,7 @@ template __global__ void r4d_ar_oneshot_2rank_exact_kernel( const int4* __restrict__ in4, int4* peer_base, const int4* my_base, int4* __restrict__ out4, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, - int n16, int slot_stride16, int drain, int acq, unsigned int nbw) { + int n16, int slot_stride16, int drain, int acq, unsigned int nbw, long stage) { const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe @@ -72,6 +72,7 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( const int slot = (int)s_slot; int4* ps = peer_base + (size_t)slot * slot_stride16; const int4* ms = my_base + (size_t)slot * slot_stride16; + const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h) const int w = (n16 + nb - 1) / nb; // 16B words per block const int start = b * w; @@ -121,8 +122,10 @@ __global__ void r4d_ar_oneshot_2rank_exact_kernel( __syncthreads(); if (acq) __threadfence_system(); r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { - for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + for (int k = start + tid; k < end; k += nt) + h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k); }); + ms = r4d_archk_moved(ms, md); // Reduce the chunk, 4x unrolled: out = local input + peer input (staged in local scratch). { int k = start + tid; @@ -149,7 +152,7 @@ __global__ void r4d_ar_hc_write_kernel( unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, int slot_stride16, int drain, int acq, unsigned int nbw, long long* gate, - unsigned int* gate_ctr) { + unsigned int* gate_ctr, long stage) { const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); @@ -158,6 +161,7 @@ __global__ void r4d_ar_hc_write_kernel( const int slot = (int)s_slot; int4* ps = peer_base + (size_t)slot * slot_stride16; const int4* ms = my_base + (size_t)slot * slot_stride16; + const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h) const int w = (n16 + nb - 1) / nb; // 16B words per block const int start = b * w; @@ -189,8 +193,10 @@ __global__ void r4d_ar_hc_write_kernel( __syncthreads(); if (acq) __threadfence_system(); r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { - for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + for (int k = start + tid; k < end; k += nt) + h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k); }); + ms = r4d_archk_moved(ms, md); r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); const int wpr = n >> 3; // 16B words a row @@ -237,7 +243,7 @@ __global__ void r4d_ar_gather_hc_write_kernel( unsigned int* my_flags, unsigned int* seq_ctrs, const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n16, int n, int hc, long irow, long hrow, int slot_stride16, int drain, int acq, unsigned int nbw, R4dArGather G, - const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr) { + const int* __restrict__ inv, long long* gate, unsigned int* gate_ctr, long stage) { const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; __shared__ unsigned int s_seq, s_slot; __shared__ int s_i[R4D_ARG_ROWS * R4D_ARG_SLOTS]; @@ -249,6 +255,7 @@ __global__ void r4d_ar_gather_hc_write_kernel( const int slot = (int)s_slot; int4* ps = peer_base + (size_t)slot * slot_stride16; const int4* ms = my_base + (size_t)slot * slot_stride16; + const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h) const int w = (n16 + nb - 1) / nb; // 16B words per block const int start = b * w; @@ -304,8 +311,10 @@ __global__ void r4d_ar_gather_hc_write_kernel( __syncthreads(); if (acq) __threadfence_system(); r4d_archk_wait(my_flags, nbw, (unsigned)slot, (unsigned)b, s, [&](unsigned int& h) { - for (int k = start + tid; k < end; k += nt) h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + for (int k = start + tid; k < end; k += nt) + h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k); }); + ms = r4d_archk_moved(ms, md); r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); for (int k = start + tid; k < end; k += nt) { @@ -411,7 +420,7 @@ int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, lon void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long slot_stride16, long y, long inj, long h, long M, long n, long hc, long irow, long hrow, long stream_i, long nblocks, long nthreads, - long drain, long acq, long gate, long gate_ctr) { + long drain, long acq, long gate, long gate_ctr, long stage) { hipStream_t st = (hipStream_t)stream_i; if (n <= 0 || M <= 0 || n % 8) throw std::runtime_error("ar_hc_write: n must be a positive multiple of 8"); if (hc < 1 || hrow % 8) throw std::runtime_error("ar_hc_write: the streams must be whole 16B words"); @@ -431,7 +440,7 @@ void r4d_ar_hc_write(long peer_scratch, long my_scratch, long peer_flags, long m (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, - (long long*)gate, (unsigned int*)gate_ctr); + (long long*)gate, (unsigned int*)gate_ctr, stage); } int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long my_flags, @@ -439,7 +448,7 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, long n, long hc, long irow, long hrow, long ye, long ew, long sorted, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long stream_i, long nblocks, long nthreads, - long drain, long acq, long inv, long gate, long gate_ctr) { + long drain, long acq, long inv, long gate, long gate_ctr, long stage) { hipStream_t st = (hipStream_t)stream_i; if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1; if (top_k < 1 || top_k > R4D_ARG_SLOTS) return -2; @@ -483,13 +492,13 @@ int r4d_ar_gather_hc_write(long peer_scratch, long my_scratch, long peer_flags, (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G, - (const int*)inv, (long long*)gate, (unsigned int*)gate_ctr); + (const int*)inv, (long long*)gate, (unsigned int*)gate_ctr, stage); } else { r4d_ar_gather_hc_write_kernel<<>>( (int4*)y, (int4*)peer_scratch, (const int4*)my_scratch, (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, (unsigned short*)h, n16, (int)n, (int)hc, irow, hrow, (int)slot_stride16, (int)drain, (int)acq, nbw, G, - nullptr, (long long*)gate, (unsigned int*)gate_ctr); + nullptr, (long long*)gate, (unsigned int*)gate_ctr, stage); } return (int)hipGetLastError(); } @@ -544,7 +553,7 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl long my_flags, long seq_ctrs, long slot_stride16, long inp, long out, long n_elem, long dtype, long stream_i, long nblocks, long nthreads, - long drain, long acq) { + long drain, long acq, long stage) { hipStream_t st = (hipStream_t)stream_i; const int esize = (dtype == 2) ? 4 : 2; const long nbytes = (long)n_elem * esize; @@ -569,7 +578,7 @@ void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_fl #define L(T, LN) r4d_ar_oneshot_2rank_exact_kernel<<>>( \ (const int4*)inp, (int4*)peer_scratch, (const int4*)my_scratch, (int4*)out, \ (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n16, \ - (int)slot_stride16, (int)drain, (int)acq, nbw) + (int)slot_stride16, (int)drain, (int)acq, nbw, stage) if (dtype == 0) L(__hip_bfloat16, 8); else if (dtype == 1) L(__half, 8); else if (dtype == 2) L(float, 4); diff --git a/libr4d/r4d_ar_oneshot_2rank_wht6.h b/libr4d/r4d_ar_oneshot_2rank_wht6.h index 0a2844cc..0e1047a9 100644 --- a/libr4d/r4d_ar_oneshot_2rank_wht6.h +++ b/libr4d/r4d_ar_oneshot_2rank_wht6.h @@ -219,26 +219,27 @@ __device__ __forceinline__ void wht6_handshake(unsigned int* peer_flags, unsigne template __device__ __forceinline__ void wht6_rehash_chunk(unsigned int& h, int c, int n_groups, int lane, int lig, int gw, const uint4* m_pay, - const unsigned short* m_sc) { + const unsigned short* m_sc, long md) { using Ch = Wht6Chunk; if constexpr (Ch::U4) { #pragma unroll for (int u = 0; u < Ch::NW / 4; ++u) { const long o = (long)c * (Ch::NW / 4 * WAVE) + (long)u * WAVE + lane; - h += r4d_archk_u4(m_pay[o], 4u * (unsigned)o); + h += r4d_archk_u4(r4d_archk_keep(&m_pay[o], md), 4u * (unsigned)o); } } else { const unsigned int* mp = reinterpret_cast(m_pay); #pragma unroll for (int u = 0; u < Ch::NW; ++u) { const long o = (long)c * (Ch::NW * WAVE) + (long)u * WAVE + lane; - h += r4d_archk_mix(mp[o], (unsigned)o); + h += r4d_archk_mix(r4d_archk_keep(&mp[o], md), (unsigned)o); } } #pragma unroll for (int t = 0; t < Ch::ITERS; ++t) { const int g = c * CG + t * GPW + gw; - if (lig == 0 && g < n_groups) h += r4d_archk_mix(m_sc[g], R4D_ARCHK_U16 + (unsigned)g); + if (lig == 0 && g < n_groups) + h += r4d_archk_mix(r4d_archk_keep(&m_sc[g], md), R4D_ARCHK_U16 + (unsigned)g); } } @@ -295,6 +296,11 @@ struct Wht6Slot { uint4* p_pay; unsigned short* p_sc; // the peer's scratch: payload, bf16 scales const uint4* m_pay; const unsigned short* m_sc; // this rank's scratch, which the peer filled uint4* l_pay; float* l_sc; // this rank's own half, local only + // Onto the host mailbox's VRAM mirror once the check has passed (r4d_ar_seq.h). + __device__ __forceinline__ void moved(long md) { + m_pay = r4d_archk_moved(m_pay, md); + m_sc = r4d_archk_moved(m_sc, md); + } }; __device__ __forceinline__ Wht6Slot wht6_slot(char* peer_scratch, const char* my_scratch, char* loc_pack, int slot, long slot_stride_bytes, @@ -316,15 +322,16 @@ __global__ void r4d_ar_oneshot_2rank_wht6_kernel( const T* __restrict__ in, char* peer_scratch, const char* my_scratch, char* loc_pack, T* __restrict__ out, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, int n_groups, int n_chunks, long slot_stride_bytes, long scale_off_bytes, int drain, int acq, - unsigned int nbw) { + unsigned int nbw, long stage) { const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; const int lane = tid & (WAVE - 1), wid = tid / WAVE, nwarp = nt / WAVE; const int lig = lane & (LPG - 1), gw = lane / LPG; __shared__ unsigned int s_seq, s_slot; r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; - const Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot, - slot_stride_bytes, scale_off_bytes); + Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot, + slot_stride_bytes, scale_off_bytes); + const long md = r4d_archk_md(stage, my_scratch); // the host mailbox's VRAM mirror const int cpb = (n_chunks + nb - 1) / nb; // block b owns chunks [c0,c1) const int c0 = b * cpb; int c1 = c0 + cpb; if (c1 > n_chunks) c1 = n_chunks; @@ -341,8 +348,9 @@ __global__ void r4d_ar_oneshot_2rank_wht6_kernel( wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq); r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) { for (int c = c0 + wid; c < c1; c += nwarp) - wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc); + wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc, md); }); + w.moved(md); const auto st = [&](long off, const float* v) { #pragma unroll @@ -366,7 +374,8 @@ static void r4d_ar_wht6_launch(int64_t peer_scratch, int64_t my_scratch, int64_t int64_t my_flags, int64_t seq_ctrs, int64_t loc_pack, int64_t slot_stride_bytes, int64_t scale_off_bytes, int64_t inp, int64_t out, int64_t n_elem, int64_t dtype, int64_t stream_i, - int64_t nblocks, int64_t nthreads, int64_t drain, int64_t acq) { + int64_t nblocks, int64_t nthreads, int64_t drain, int64_t acq, + int64_t stage = 0) { hipStream_t st = (hipStream_t)stream_i; if (dtype != 0 && dtype != 1) throw std::runtime_error("pack ar: only bf16/fp16 payloads"); if (n_elem % GROUP != 0) throw std::runtime_error("pack ar: n_elem not a multiple of GROUP"); @@ -378,7 +387,7 @@ static void r4d_ar_wht6_launch(int64_t peer_scratch, int64_t my_scratch, int64_t (const T*)inp, (char*)peer_scratch, (const char*)my_scratch, (char*)loc_pack, (T*)out, \ (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, n_groups, n_chunks, \ (long)slot_stride_bytes, (long)scale_off_bytes, (int)drain, (int)acq, \ - (unsigned)R4D_AR_MAX_BLOCKS) + (unsigned)R4D_AR_MAX_BLOCKS, (long)stage) if (dtype == 0) LF(__hip_bfloat16); else LF(__half); #undef LF diff --git a/libr4d/r4d_ar_oneshot_2rank_wht6.hip b/libr4d/r4d_ar_oneshot_2rank_wht6.hip index 0047c121..7f4b68d8 100644 --- a/libr4d/r4d_ar_oneshot_2rank_wht6.hip +++ b/libr4d/r4d_ar_oneshot_2rank_wht6.hip @@ -11,10 +11,11 @@ void r4d_ar_oneshot_2rank_wht6(long peer_scratch, long my_scratch, long peer_flags, long my_flags, long seq_ctrs, long loc_pack, long slot_stride_bytes, long scale_off_bytes, long inp, long out, long n_elem, long dtype, - long stream, long nblocks, long nthreads, long drain, long acq) { + long stream, long nblocks, long nthreads, long drain, long acq, + long stage) { r4d_ar_wht6_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs, loc_pack, slot_stride_bytes, scale_off_bytes, inp, out, n_elem, dtype, stream, nblocks, - nthreads, drain, acq); + nthreads, drain, acq, stage); } // Block cap of both all-reduce kernels (the flag array is sized from it). @@ -74,7 +75,7 @@ __global__ void r4d_ar_hc_write_wht6_kernel( const unsigned short* __restrict__ inj, unsigned short* __restrict__ h, int n, int hc, long irow, long hrow, int n_groups, int n_chunks, long slot_stride_bytes, long scale_off_bytes, int drain, int acq, unsigned int nbw, R4dArGather G, int rows_max, - long long* gate, unsigned int* gate_ctr) { + long long* gate, unsigned int* gate_ctr, long stage) { const int b = blockIdx.x, nb = gridDim.x, tid = threadIdx.x, nt = blockDim.x; const int lane = tid & (WAVE - 1), wid = tid / WAVE, nwarp = nt / WAVE; const int lig = lane & (LPG - 1), gw = lane / LPG; @@ -83,8 +84,9 @@ __global__ void r4d_ar_hc_write_wht6_kernel( const long long gate_word = r4d_ar_link_word(gate, (unsigned int)tid); r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); // device-resident, replay-safe const unsigned int s = s_seq; - const Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot, - slot_stride_bytes, scale_off_bytes); + Wht6Slot w = wht6_slot(peer_scratch, my_scratch, loc_pack, (int)s_slot, + slot_stride_bytes, scale_off_bytes); + const long md = r4d_archk_md(stage, my_scratch); // the host mailbox's VRAM mirror const int cpb = (n_chunks + nb - 1) / nb; // block b owns chunks [c0,c1) const int c0 = b * cpb; int c1 = c0 + cpb; if (c1 > n_chunks) c1 = n_chunks; @@ -147,8 +149,9 @@ __global__ void r4d_ar_hc_write_wht6_kernel( wht6_handshake(peer_flags, my_flags, b, s, tid, drain, acq); r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, s, [&](unsigned int& h) { for (int c = c0 + wid; c < c1; c += nwarp) - wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc); + wht6_rehash_chunk(h, c, n_groups, lane, lig, gw, w.m_pay, w.m_sc, md); }); + w.moved(md); r4d_ar_link_landed(gate, gate_word, gate_ctr, (unsigned int)nb, (unsigned int)tid); for (int c = c0 + wid; c < c1; c += nwarp) @@ -161,7 +164,7 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo long irow, long hrow, long ye, long ew, long sorted, long sh, long sg, long ye_ld, long ew_ld, long sh_ld, long sg_ld, long top_k, long sig, long stream_i, long nblocks, long nthreads, long drain, long acq, - long gate, long gate_ctr) { + long gate, long gate_ctr, long stage) { hipStream_t st = (hipStream_t)stream_i; if (n <= 0 || M <= 0 || n % 8 || hc < 1 || hrow % 8) return -1; if ((M * n) % GROUP) return -1; @@ -207,7 +210,7 @@ int r4d_ar_hc_write_wht6(long peer_scratch, long my_scratch, long peer_flags, lo (unsigned*)peer_flags, (unsigned*)my_flags, (unsigned*)seq_ctrs, (const unsigned short*)inj, \ (unsigned short*)h, (int)n, (int)hc, irow, hrow, n_groups, n_chunks, slot_stride_bytes, \ scale_off_bytes, (int)drain, (int)acq, (unsigned)R4D_AR_MAX_BLOCKS, G, rows_max, \ - (long long*)gate, (unsigned int*)gate_ctr) + (long long*)gate, (unsigned int*)gate_ctr, stage) if (gather) LF(true, kWht6FusedCG); else LF(false, kWht6FusedCG); #undef LF diff --git a/libr4d/r4d_ar_seq.h b/libr4d/r4d_ar_seq.h index 82f9b339..a45f731f 100644 --- a/libr4d/r4d_ar_seq.h +++ b/libr4d/r4d_ar_seq.h @@ -197,3 +197,27 @@ __device__ __forceinline__ void r4d_archk_wait(unsigned int* my_flags, unsigned __builtin_amdgcn_s_sleep(2); } } + +// ---- The host mailbox's one read. A host twin's slots are pinned host memory (r4d_ar_entry.hip), +// which the card reads past every cache over its own link, so reading the slot for the check and +// again for the reduce crosses the link twice: at --p2p off a prefill all-reduce's reads doubled +// (#323). Such an instance also has a mirror of its slots in this rank's VRAM, `md` bytes from +// them (`stage` - my_scratch; 0 over P2P, where the slots are VRAM already). The re-hash reads each +// word through r4d_archk_keep, which also stores it into the mirror, and once the check passes the +// kernel moves its slot pointers onto the mirror (r4d_archk_moved) for the reduce. Only this block +// writes and reads its words of the mirror, and the check's barriers order the two; a failed try's +// copy is overwritten by the next. +template +__device__ __forceinline__ V r4d_archk_keep(const V* p, long md) { + const V v = *p; + if (md) *reinterpret_cast(reinterpret_cast(p) + md) = v; + return v; +} +template +__device__ __forceinline__ const V* r4d_archk_moved(const V* p, long md) { + return reinterpret_cast(reinterpret_cast(p) + md); +} +// The offset of an instance's mirror from its slots, from the launcher's `stage` (0: none). +__device__ __forceinline__ long r4d_archk_md(long stage, const void* my_scratch) { + return stage ? stage - (long)reinterpret_cast(my_scratch) : 0; +} diff --git a/libr4d/r4d_attn_decode_h256_gqa6.hip b/libr4d/r4d_attn_decode_h256_gqa6.hip index 93e8662a..80952e4a 100644 --- a/libr4d/r4d_attn_decode_h256_gqa6.hip +++ b/libr4d/r4d_attn_decode_h256_gqa6.hip @@ -64,6 +64,10 @@ // Neither changes the arithmetic. #define O_QLD 134217728 #define O_KVREP 268435456 +// TREE: a tree verify (attn_paged_qrow_tree; R4DArgs::spec_parent). A row whose entry is not -2 +// sees, inside its sequence's query block, only itself and its ancestors, and its window is +// measured from the block's first position plus its depth. Compiled in only where a row asks. +#define O_TREE 536870912 __host__ __device__ __forceinline__ int r4d_attn_tiles(int ctx, int tile) { return (ctx + tile - 1) / tile; } __host__ __device__ __forceinline__ int r4d_attn_tps(int ctx, int tile, int splits) { int t = r4d_attn_tiles(ctx, tile); return (t + splits - 1) / splits; @@ -112,6 +116,7 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) static_assert(!V4 || (OPT & O_F16), "fp8_v4 widens to f16"); constexpr int QLD = (OPT & O_QLD) ? 1 : 0; constexpr int KVREP = (OPT & O_KVREP) ? 1 : 0; + constexpr int TREE = (OPT & O_TREE) ? 1 : 0; typedef DT16 D; typedef typename D::frag frag16; @@ -177,6 +182,16 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) if (t_lo >= ntl) return; const int t_hi = min(t_lo + tps, ntl); + // TREE: the block's parents staged once, so each row's walk below reads LDS rather than a + // chain of dependent global loads. Every early return above is uniform across the block. + __shared__ int s_tpar[TREE ? 64 : 1]; + if constexpr (TREE) { + if (a.spec_parent) { + for (int r = tid; r < qlen && r < 64; r += NTHR) s_tpar[r] = a.spec_parent[qoff + r]; + __syncthreads(); + } + } + const int row = warp * 16 + c; const int qi = row / GQA, hi = row - qi * GQA; const bool live = (qi < qlen); @@ -214,8 +229,28 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) const int klimit = cz ? pos : ((WIN && a.window > 0) ? min(ctx - 1, pos + a.window - 1) : ctx - 1); - const int wlo = (WIN && a.window > 0) ? (pos - a.window + 1 > 0 - ? pos - a.window + 1 : 0) : 0; + // A tree verify's row (TREE): a bit per row of the block for itself and each ancestor, and + // its depth, from which its window is measured. Parents precede children, so the walk ends. + const int tbase = ctx - qlen; + uint64_t tmask = 0; + int tdep = 0; + bool trow = false; + if (TREE && a.spec_parent && qrow < 64) { + int pj = s_tpar[qrow]; + if (pj != -2) { + trow = true; + tmask = 1ull << qrow; + for (int at = qrow; pj >= 0 && pj < at; ) { + tmask |= 1ull << pj; + ++tdep; + at = pj; + pj = s_tpar[pj]; + } + } + } + const int wpos = (TREE && trow) ? tbase + tdep : pos; + const int wlo = (WIN && a.window > 0) ? (wpos - a.window + 1 > 0 + ? wpos - a.window + 1 : 0) : 0; float m_ref = -3.0e38f; float off = PSHIFT + 3.0e38f; float l_i = 0.0f; @@ -482,10 +517,13 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits) for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[e] : s[e] * mul; const int kbase = k0 + mt * 16 + 8 * h; - if (!MSKIP || wave_any(kbase + 7 > klimit) || (WIN && wave_any(kbase < wlo))) { + if (!MSKIP || wave_any(kbase + 7 > klimit) || (WIN && wave_any(kbase < wlo)) || + (TREE && wave_any(trow && kbase + 7 >= tbase))) { #pragma unroll for (int e = 0; e < 8; ++e) - sc[e] = ((kbase + e <= klimit) && (!WIN || kbase + e >= wlo)) + sc[e] = ((kbase + e <= klimit) && (!WIN || kbase + e >= wlo) && + (!TREE || !trow || kbase + e < tbase || + ((tmask >> (kbase + e - tbase)) & 1ull))) ? sc[e] : -INFINITY; } float smax = sc[0]; diff --git a/libr4d/r4d_attn_paged_gqa8.hip b/libr4d/r4d_attn_paged_gqa8.hip index 61a1dc8b..6ef8f8e1 100644 --- a/libr4d/r4d_attn_paged_gqa8.hip +++ b/libr4d/r4d_attn_paged_gqa8.hip @@ -280,8 +280,11 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, Rad /* Split-KV partial buffer size at declare time, from the band's upper bound. Declare passes * parameters and no tensors, so parameters come first and tensors are the fallback (see the - * h256/gqa6 dispatch). The size is the maximum over every sequence count up to max_seqs, because - * S * floor(128 / (kv_heads * S)) is not monotone in S. */ + * h256/gqa6 dispatch). The size is the maximum over every sequence count up to max_seqs and every + * query length up to the band's: S * floor(128 / (kv_heads * S)) is not monotone in S, and the + * split law's targets (r4d_decode_splits: 256 workgroups at q_len * gqa <= 32; above, 128 to 16384 + * tokens deep and more past it) can give a shorter query more splits: at gqa 8 a 4-row step needs + * 1.6x the partials of the band bound 5. */ /* `row` is a token's bytes in a (block, head) page, 0 for the 16-bit and E4M3 caches' 2 * head_dim * (fill_paged_row). */ static int64_t g8_decode_scratch(const RadArgs* a, int head_dim, long long row = 0) { @@ -298,17 +301,19 @@ static int64_t g8_decode_scratch(const RadArgs* a, int head_dim, long long row = const long long gqa = r4d_geti_or(a, "gqa", 1); r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head); r.num_seqs = (int)max_seqs; - r.q_len = (int)r4d_geti_or(a, "q_len", 1); + const long long q_hi = std::max(1LL, r4d_geti_or(a, "q_len", 1)); r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0); r.block_size = (int)r4d_geti_or(a, "block_size", 16); r.splits = sp; if (r.max_ctx <= 0) return R4D_NO(RAD_E_INVAL); int64_t worst = 0; - for (long long n = 1; n <= max_seqs; ++n) { - r.num_seqs = (int)n; - const int64_t need = GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(&r); - if (need > worst) worst = need; - } + for (long long q = 1; q <= q_hi; ++q) + for (long long n = 1; n <= max_seqs; ++n) { + r.q_len = (int)q; + r.num_seqs = (int)n; + const int64_t need = GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(&r); + if (need > worst) worst = need; + } return worst; } const int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim); diff --git a/libr4d/r4d_attn_paged_h256_gqa2.hip b/libr4d/r4d_attn_paged_h256_gqa2.hip index aedccc3e..91d9ec9d 100644 --- a/libr4d/r4d_attn_paged_h256_gqa2.hip +++ b/libr4d/r4d_attn_paged_h256_gqa2.hip @@ -45,6 +45,13 @@ extern "C" int r4d_attn_decode_h256_gqa2_qld_fp8kv(const R4DArgs* a, hipStream_t extern "C" int r4d_attn_decode_h256_gqa2_qld_bf16kv(const R4DArgs* a, hipStream_t s) { return r4d_decode_launch_win(a, s); } +// ...and a tree verify's mask (O_TREE, attn_paged_qrow_tree), again its own instances. +extern "C" int r4d_attn_decode_h256_gqa2_qld_tree_fp8kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} +extern "C" int r4d_attn_decode_h256_gqa2_qld_tree_bf16kv(const R4DArgs* a, hipStream_t s) { + return r4d_decode_launch_win(a, s); +} // ---- prefill --------------------------------------------------------------------------------- // The h256/gqa6 prefill option set but at K prefetch 4 (P_OPT there is 3954187); O_KWIDE is valid diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index c633901c..be0869d3 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -301,9 +301,12 @@ extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) { * row with "invalid argument". q_len is the band's upper bound, since the region is sized once * for the worst step. * - * The size is the maximum over every sequence count up to max_seqs: S * splits(S) is not monotone - * in S (at kv_heads 2 the h256 law gives 60 at twelve sequences and 63 at nine, and the h128 law's - * step-up doubles splits at one count only). The laws are closed forms, so the sweep is cheap. */ + * The size is the maximum over every sequence count up to max_seqs and every query length up to + * the band's: S * splits(S) is not monotone in S (at kv_heads 2 the h256 law gives 60 at twelve + * sequences and 63 at nine, and the h128 law's step-up doubles splits at one count only), and the + * h256 law's targets (r4d_decode_splits: 256 workgroups at q_len * gqa <= 32; above, 128 to 16384 + * tokens deep and more past it) can give a shorter query more splits (at gqa 6 and 16384 tokens, 5 + * rows a sequence need 1.67x the band bound 6's). The laws are closed forms, so the sweep is cheap. */ // Per-geometry byte counts over the shared partial layout, so one sweep serves all. // which: 0 = h256/gqa6, 1 = h128/gqa4, 2 = h256/gqa2 (Gemma 4 windowed). static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) { @@ -332,7 +335,7 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long lo r.kv_heads = (int)(gqa > 0 ? n_head / gqa : n_head) * rep; r.kv_rep = rep; r.num_seqs = (int)max_seqs; - r.q_len = (int)r4d_geti_or(a, "q_len", 1); + const long long q_hi = std::max(1LL, r4d_geti_or(a, "q_len", 1)); r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0); r.block_size = (int)r4d_geti_or(a, "block_size", 16); r.splits = sp; @@ -340,11 +343,13 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which, long lo * for a launch that later picks more, so refuse. */ if (r.max_ctx <= 0) return R4D_NO(RAD_E_INVAL); int64_t worst = 0; - for (long long n = 1; n <= max_seqs; ++n) { - r.num_seqs = (int)n; - const int64_t need = decode_scratch_bytes_of(&r, which); - if (need > worst) worst = need; - } + for (long long q = 1; q <= q_hi; ++q) + for (long long n = 1; n <= max_seqs; ++n) { + r.q_len = (int)q; + r.num_seqs = (int)n; + const int64_t need = decode_scratch_bytes_of(&r, which); + if (need > worst) worst = need; + } return worst; } @@ -517,6 +522,32 @@ extern "C" int r4d_rad_attn_qrow_decode_h256_gqa2_bf16(const RadArgs* a, RadStre return r4d_attn_decode_h256_gqa2_qld_bf16kv(&r, (hipStream_t)s); } +/* ...under attn_paged_qrow_tree: the same, with the tree verify's mask from `spec_parent` (operand + * 8, one int32 a query row; docs/OPS.md). Causal only, as the op is. */ +static int tree_operand(const RadArgs* a, R4DArgs* r) { + const RadTensor* tp = a->n_t > 8 ? r4d_opt(a, 8) : nullptr; + if (!tp || !tp->data) return R4D_NO(RAD_E_INVAL); + if (tp->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + if (r4d_numel(tp) < r4d_q_total(*r)) return R4D_NO(RAD_E_SHAPE); + if (r->causal != 1 || r->causal_seq) return R4D_NO(RAD_E_UNSUPPORTED); + r->spec_parent = (const int*)tp->data; + return RAD_OK; +} +extern "C" int r4d_rad_attn_qrow_tree_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 256, 2, 0, 1, true); + if (rc == RAD_OK) rc = tree_operand(a, &r); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h256_gqa2_qld_tree_fp8kv(&r, (hipStream_t)s); +} +extern "C" int r4d_rad_attn_qrow_tree_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 256, 2, 0, 1, true); + if (rc == RAD_OK) rc = tree_operand(a, &r); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h256_gqa2_qld_tree_bf16kv(&r, (hipStream_t)s); +} + /* Head_dim 128 at 8 queries per kv head, any window, causal or not, q_len up to 16, under * attn_paged_qrow: the gqa-4 kernel with each kv head mapped onto two query groups * (R4DArgs::kv_rep = 2), the 31B's DFlash drafter's attention over a cache that holds each kv head diff --git a/libr4d/r4d_attn_paged_window.hip b/libr4d/r4d_attn_paged_window.hip index fa84c622..6e144ec5 100644 --- a/libr4d/r4d_attn_paged_window.hip +++ b/libr4d/r4d_attn_paged_window.hip @@ -194,6 +194,9 @@ struct AttnArgs { int* tinfo; /* [tile] = (first row, positions) */ float qscale; /* softmax scale * log2(e) */ int max_blocks, n_seq, q_len, tps, kv_heads, causal, window, n_split; + /* A tree verify (attn_paged_qrow_tree): RadBatch::spec_parent, one a query row; read only by + * the TREE instances. */ + const int* tpar; }; /* Tile `tile` of a ragged batch: its sequence and which BQ-position slice of that sequence's query @@ -240,7 +243,7 @@ __device__ void find_tile(const int* cu, int n_seq, int tile, int* s_scan, int* /* ------------------------------------------------------------------ the attention kernel */ /* The body; attn_kernel and its chained form r4dchain_attn_window (r4d_chain.h) wrap it below, * since its blocks return early. */ -template +template __device__ __forceinline__ void attn_body(AttnArgs A) { constexpr int R = Geo::R, BK = Geo::BK, RW = R / kWaves, BQ = R / GQA; constexpr int NC = HD / 128; /* 4-element chunks a lane holds of a row */ @@ -284,6 +287,17 @@ __device__ __forceinline__ void attn_body(AttnArgs A) { } if (npos <= 0) return; /* uniform across the block */ + /* TREE: the sequence's first rows' parents staged once (a tree block is at most 64 rows), so + * each row's walk below reads LDS rather than a chain of dependent global loads. */ + __shared__ int s_tpar[TREE ? 64 : 1]; + if constexpr (TREE) { + if (A.tpar) { + const int nst = imin(qlen, 64); + for (int r = tid; r < nst; r += kThreads) s_tpar[r] = A.tpar[tokb + r]; + __syncthreads(); + } + } + const int tok0 = tokb + pfirst; const int qbase = ctx - qlen + pfirst; /* absolute position of the tile's first query */ const int plast = qbase + npos - 1; @@ -293,7 +307,10 @@ __device__ __forceinline__ void attn_body(AttnArgs A) { int hi = causal ? plast + 1 : ctx; if (!causal && window > 0) hi = imin(hi, plast + window); hi = imin(imin(hi, ctx), A.max_blocks * 16); - const int lo = window > 0 ? imax(0, qbase - window + 1) : 0; + /* A tree row's window is measured from the block's first position plus its depth, which can + * be below its own position, so a tree launch starts every tile at the block's first. */ + const int tbase = ctx - qlen; + const int lo = window > 0 ? imax(0, ((TREE && A.tpar) ? tbase : qbase) - window + 1) : 0; const int lo_a = lo & ~(BK - 1); const int nkt = hi > lo_a ? (hi - lo_a + BK - 1) / BK : 0; const int per = (nkt + A.n_split - 1) / A.n_split; @@ -306,6 +323,11 @@ __device__ __forceinline__ void attn_body(AttnArgs A) { float qf[RW][NC][4], o[RW][NC][4], m[RW], l[RW]; int pos[RW]; bool val[RW]; + /* TREE: each row's ancestors inside the block (a bit per row of the block, itself included), + * whether it is a tree row at all, and the position its window is measured from. */ + uint64_t tm[RW]; + int wq[RW]; + bool tr[RW]; #pragma unroll for (int i = 0; i < RW; ++i) { const int r = wave * RW + i, p = r / GQA, g = r - p * GQA; @@ -313,6 +335,28 @@ __device__ __forceinline__ void attn_body(AttnArgs A) { pos[i] = qbase + p; m[i] = -__builtin_inff(); l[i] = 0.0f; + tm[i] = 0; + wq[i] = pos[i]; + tr[i] = false; + if constexpr (TREE) { + const int rel = pfirst + p; /* the row within its sequence's rows */ + if (A.tpar && val[i] && rel < 64) { + int pj = s_tpar[rel]; + if (pj != -2) { + uint64_t mk = 1ull << rel; + int dep = 0; + for (int at = rel; pj >= 0 && pj < at; ) { + mk |= 1ull << pj; + ++dep; + at = pj; + pj = s_tpar[pj]; + } + tr[i] = true; + tm[i] = mk; + wq[i] = tbase + dep; + } + } + } const uint16_t* qp = A.q + (long long)(tok0 + p) * A.q_rs + (long long)(kh * GQA + g) * A.q_hs; const float qs = A.qscale * kds; /* k_descale folds into the query */ #pragma unroll @@ -391,7 +435,10 @@ __device__ __forceinline__ void attn_body(AttnArgs A) { } const int pq = pos[i]; bool vis = kok && (causal ? kk <= pq : true); - if (window > 0) vis = vis && (pq - kk < window) && (causal || kk - pq < window); + if constexpr (TREE) + if (tr[i] && vis && kk >= tbase) vis = ((tm[i] >> (kk - tbase)) & 1ull) != 0; + const int wpq = TREE ? wq[i] : pq; + if (window > 0) vis = vis && (wpq - kk < window) && (causal || kk - wpq < window); const float sv = vis ? sc[0] : -__builtin_inff(); const float mn = __builtin_fmaxf(m[i], wave_max(sv)); if (mn == -__builtin_inff()) return; /* nothing visible yet: uniform */ @@ -974,12 +1021,14 @@ static constexpr int64_t scratch_need() { /* The plain kernels and their chained forms (r4dchain*, RadKernelChainFn): the chained ones wait * for the kernels before them on the queue in their prologue and count themselves in at the end. */ -template -__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { attn_body(A); } -template +template +__global__ __launch_bounds__(kThreads) void attn_kernel(AttnArgs A) { + attn_body(A); +} +template __global__ __launch_bounds__(kThreads) void r4dchain_attn_window(AttnArgs A) { r4d_chain_wait(); - attn_body(A); + attn_body(A); r4d_chain_done(); } template @@ -991,10 +1040,15 @@ __global__ __launch_bounds__(kThreads) void r4dchain_merge_window(AttnArgs A) { r4d_chain_done(); } -template +template static int launch_attn(const RadArgs* a, RadStream stream) { constexpr int R = Geo::R, BK = Geo::BK, BQ = R / GQA, ESZ = KV8 ? 1 : 2; - if (!a || a->n_t < 8) return RAD_E_INVAL; + if (!a || a->n_t < (TREE ? 9 : 8)) return RAD_E_INVAL; + /* attn_paged_qrow_tree's ninth operand: one int32 a query row (docs/OPS.md). Causal only. */ + const RadTensor* tp = TREE ? rad_arg_in(a, 8) : nullptr; + if (TREE && (!tp || !tp->data)) return RAD_E_INVAL; + if (TREE && tp->dtype != RAD_I32) return RAD_E_DTYPE; + if (TREE && rad_args_geti_or(a, "causal", 1) != 1) return RAD_E_UNSUPPORTED; const RadTensor* q = rad_arg_in(a, 0); const RadTensor* kv = rad_arg_in(a, 1); const RadTensor* bt = rad_arg_in(a, 2); @@ -1028,6 +1082,7 @@ static int launch_attn(const RadArgs* a, RadStream stream) { if (!head_view(q, qh, HD, &rows, &q_rs, &q_hs) || !head_view(o, qh, HD, &orows, &o_rs, &o_hs)) return RAD_E_SHAPE; if (orows < rows) return RAD_E_SHAPE; + if (TREE && rad_tensor_numel(tp) < rows) return RAD_E_SHAPE; const int64_t n_seq = rad_tensor_numel(su); if (rows == 0) return RAD_OK; if (n_seq <= 0 || n_seq > (1 << 24)) return RAD_E_SHAPE; @@ -1081,7 +1136,8 @@ static int launch_attn(const RadArgs* a, RadStream stream) { qmax_w = rad_args_geti_or(a, "q_len", rows); if (qmax_w <= 0 || qmax_w > rows) qmax_w = rows; } - const bool shaped = qmax_w >= kWmmaMinQ && rows >= n_seq * (kWmmaMinQ / 2); + /* Never a tree: its verify blocks are decode-sized, and only the scalar kernel reads one. */ + const bool shaped = !TREE && qmax_w >= kWmmaMinQ && rows >= n_seq * (kWmmaMinQ / 2); const bool aligned = rad_ptr_aligned(q->data, 16) && rad_ptr_aligned(o->data, 16) && (q_rs | q_hs | o_rs | o_hs) % 8 == 0; if (shaped && aligned) { @@ -1159,16 +1215,17 @@ static int launch_attn(const RadArgs* a, RadStream stream) { A.causal = (int)causal; A.window = (int)window; A.n_split = (int)ns; + A.tpar = TREE ? (const int*)tp->data : nullptr; hipStream_t s = (hipStream_t)stream; /* The chained forms where the row resolved with `chain` (launches chain), at decode heights * only: the 31B's full layers at a verify. */ const bool chain = rad_args_geti_or(a, "chain", 0) != 0 && rows <= 64; if (chain) - R4D_KLAUNCH(R4D_KNAME(r4dchain_attn_window), + R4D_KLAUNCH(R4D_KNAME(r4dchain_attn_window), dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), dim3(kThreads), s, A); else - R4D_KLAUNCH(R4D_KNAME(attn_kernel), + R4D_KLAUNCH(R4D_KNAME(attn_kernel), dim3((unsigned)nt, (unsigned)kvh, (unsigned)ns), dim3(kThreads), s, A); if (ns > 1) { if (chain) @@ -1198,6 +1255,18 @@ R4D_WIN_DEF(256, 1) R4D_WIN_DEF(256, 2) R4D_WIN_DEF(256, 4) R4D_WIN_DEF(256, 8) R4D_WIN_DEF(512, 1) R4D_WIN_DEF(512, 2) R4D_WIN_DEF(512, 4) R4D_WIN_DEF(512, 8) #undef R4D_WIN_DEF +/* attn_paged_qrow_tree: the scalar kernel with a tree verify's mask (TREE). */ +#define R4D_WIN_TREE_DEF(HD, G) \ + int r4d_rad_attn_window_tree_h##HD##_gqa##G##_bf16(const RadArgs* a, RadStream s) { \ + return r4d_win::launch_attn(a, s); \ + } \ + int r4d_rad_attn_window_tree_h##HD##_gqa##G##_fp8(const RadArgs* a, RadStream s) { \ + return r4d_win::launch_attn(a, s); \ + } +R4D_WIN_TREE_DEF(256, 1) R4D_WIN_TREE_DEF(256, 2) R4D_WIN_TREE_DEF(256, 4) R4D_WIN_TREE_DEF(256, 8) +R4D_WIN_TREE_DEF(512, 1) R4D_WIN_TREE_DEF(512, 2) R4D_WIN_TREE_DEF(512, 4) R4D_WIN_TREE_DEF(512, 8) +#undef R4D_WIN_TREE_DEF + /* Called at declare with no tensors. Partials are capped at kPartBudget (tile, head, split) * triples for any batch, so the size is a constant. */ int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*) { return r4d_win::scratch_need<128>(); } diff --git a/libr4d/r4d_dflash_tree_bf16.hip b/libr4d/r4d_dflash_tree_bf16.hip new file mode 100644 index 00000000..477f10cd --- /dev/null +++ b/libr4d/r4d_dflash_tree_bf16.hip @@ -0,0 +1,259 @@ +// DFlash2's candidate lattice grown best-first into a tree (rad_drafter_tree), one workgroup per +// sequence. docs/OPS.md, `dflash_tree`, is the contract; libref's ref_dflash_tree the reference. +// +// The selector (r4d_dflash_select_bf16.hip) walks one path: at each position the candidate with the +// best edge score after the previous pick. A tree keeps more than one way forward where the walk is +// unsure. Node 0 is the anchor. Expanding a node at lattice position l with token t scores every +// candidate c at l + 1 exactly as the walk scores it after t, +// +// score[c] = unary[l+1, c] + sum_r pred[t][r] * hp[l+1][r] * succ[cand[l+1, c]][r] +// +// and pushes each valid candidate as a child with log probability parent + log_softmax(score/temp) +// over the valid candidates. Each round takes the untaken child with the largest log probability +// (ties to the one pushed first), until `nodes` are taken; the taken nodes, in order, are the +// proposal, each with its parent's node index. A parent is always taken before its child. +// +// The same latency-kernel shape as the walk: `nodes` expansions of K dot products of R each, and a +// reduction over a frontier of at most nodes * K entries per round, all in LDS. +#include +#include "r4d_gdn_args.h" +#include "r4d_dflash_conv_body.h" // r4d_bf2f, r4d_u16 +#include "r4d_common.h" // r4d_wave_sum +#include "r4d_chain.h" + +#define DTR_THREADS 256 +#define DTR_WAVE 32 +#define DTR_WAVES (DTR_THREADS / DTR_WAVE) +#define DTR_MAX_K 32 // the entry point rejects more +#define DTR_MAX_R 512 +#define DTR_MAX_N 63 // nodes and steps: the node table and the frontier below +#define DTR_FRONT (DTR_MAX_N * DTR_MAX_K) + +// cand [rows, cand_ld] i32 row = s * steps + l +// unary [rows, cand_ld] f32 +// hp [rows, hp_ld] bf16 (null: ones, the bigram form) +// anchor [M * anchor_stride] i32 +// pred, succ [vocab, R] bf16 +// tok, par [M, out_ld] i32 the taken nodes' tokens and parents, nodes a row +__device__ __forceinline__ void r4d_dflash_tree_body( + const int* __restrict__ cand, const float* __restrict__ unary, + const r4d_u16* __restrict__ hp, const int* __restrict__ anchor, + const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ, + int* __restrict__ tok_out, int* __restrict__ par_out, int steps, int K, int R, int V, int N, + float inv_temp, int cand_ld, int hp_ld, int out_ld, int anchor_stride) +{ + const int s = blockIdx.x; + const int tid = threadIdx.x; + const int lane = tid & (DTR_WAVE - 1); + const int wave = tid / DTR_WAVE; + + __shared__ float sa[DTR_MAX_R]; + __shared__ float ssc[DTR_MAX_K]; + // the frontier: every child pushed so far, in push order; a taken one's lp becomes -inf + __shared__ float f_lp[DTR_FRONT]; + __shared__ int f_tok[DTR_FRONT]; + __shared__ short f_par[DTR_FRONT]; + __shared__ short f_l[DTR_FRONT]; + __shared__ int n_front; + // the taken nodes, node 0 the anchor + __shared__ int n_tok[DTR_MAX_N + 1]; + __shared__ int n_l[DTR_MAX_N + 1]; + __shared__ float n_lp[DTR_MAX_N + 1]; + // the round's reduction + __shared__ float r_lp[DTR_WAVES]; + __shared__ int r_ix[DTR_WAVES]; + __shared__ int take; + + constexpr int CPW = (DTR_MAX_K + DTR_WAVES - 1) / DTR_WAVES; + + if (tid == 0) { + n_tok[0] = anchor[(long)s * anchor_stride]; + n_l[0] = -1; + n_lp[0] = 0.0f; + n_front = 0; + } + __syncthreads(); + + // Push node n's children: every valid candidate at its next position. Uniform across the block. + auto expand = [&](int n) { + const int l = n_l[n] + 1; + if (l >= steps) return; + const long row = (long)s * steps + l; + const int pid = n_tok[n]; + const bool pid_ok = pid >= 0 && pid < V; + const r4d_u16* __restrict__ prow = pred + (long)(pid_ok ? pid : 0) * R; + if (!pid_ok) { + for (int r = tid; r < R; r += DTR_THREADS) sa[r] = 0.0f; + } else if (hp) { + const r4d_u16* __restrict__ hrow = hp + row * hp_ld; + for (int r = tid; r < R; r += DTR_THREADS) sa[r] = r4d_bf2f(prow[r]) * r4d_bf2f(hrow[r]); + } else { + for (int r = tid; r < R; r += DTR_THREADS) sa[r] = r4d_bf2f(prow[r]); + } + __syncthreads(); +#pragma unroll + for (int i = 0; i < CPW; ++i) { + const int c = wave + i * DTR_WAVES; + if (c < K) { + const long at = row * cand_ld + c; + const int cid = cand[at]; + const bool ok = cid >= 0 && cid < V; + const r4d_u16* __restrict__ srow = succ + (long)(ok ? cid : 0) * R; + float acc = 0.0f; +#pragma unroll 8 + for (int r = lane; r < R; r += DTR_WAVE) acc += sa[r] * r4d_bf2f(srow[r]); + acc = r4d_wave_sum(ok ? acc : 0.0f); + if (lane == 0) ssc[c] = ok ? (acc + unary[at]) * inv_temp : -INFINITY; + } + } + __syncthreads(); + // log_softmax over the valid candidates and the push, in c order, by one thread (K <= 32) + if (tid == 0) { + float mx = -INFINITY; + for (int c = 0; c < K; ++c) mx = fmaxf(mx, ssc[c]); + if (mx > -INFINITY) { + float sum = 0.0f; + for (int c = 0; c < K; ++c) if (ssc[c] > -INFINITY) sum += expf(ssc[c] - mx); + const float lse = mx + logf(sum); + int f = n_front; + for (int c = 0; c < K && f < DTR_FRONT; ++c) { + if (!(ssc[c] > -INFINITY)) continue; + f_lp[f] = n_lp[n] + (ssc[c] - lse); + f_tok[f] = cand[row * cand_ld + c]; + f_par[f] = (short)n; + f_l[f] = (short)l; + ++f; + } + n_front = f; + } + } + __syncthreads(); + }; + + expand(0); + for (int j = 1; j <= N; ++j) { + // the round: the largest untaken log probability, the earliest pushed among equals + float best = -INFINITY; + int bix = -1; + const int nf = n_front; + for (int f = tid; f < nf; f += DTR_THREADS) { + const float v = f_lp[f]; + if (v > best) { best = v; bix = f; } // ascending f: the first of equals stays + } + for (int d = DTR_WAVE / 2; d > 0; d >>= 1) { + const float ov = __shfl_xor(best, d); + const int oi = __shfl_xor(bix, d); + if (ov > best || (ov == best && oi >= 0 && (bix < 0 || oi < bix))) { best = ov; bix = oi; } + } + if (lane == 0) { r_lp[wave] = best; r_ix[wave] = bix; } + __syncthreads(); + if (tid == 0) { + float b = -INFINITY; + int bi = -1; + for (int w = 0; w < DTR_WAVES; ++w) + if (r_lp[w] > b || (r_lp[w] == b && r_ix[w] >= 0 && (bi < 0 || r_ix[w] < bi))) { + b = r_lp[w]; bi = r_ix[w]; + } + int t, p, l; + float lp; + if (bi < 0 || !(b > -INFINITY)) { + // a dry frontier: token 0 under the last node, never expanded + t = 0; p = j - 1; l = steps; lp = -INFINITY; + } else { + t = f_tok[bi]; p = f_par[bi]; l = f_l[bi]; lp = f_lp[bi]; + f_lp[bi] = -INFINITY; + } + n_tok[j] = t; n_l[j] = l; n_lp[j] = lp; + tok_out[(long)s * out_ld + (j - 1)] = t; + par_out[(long)s * out_ld + (j - 1)] = p; + take = (bi >= 0 && b > -INFINITY) ? 1 : 0; + } + __syncthreads(); + if (take && j < N) expand(j); + } +} + +__global__ __launch_bounds__(DTR_THREADS) void r4d_dflash_tree_kernel( + const int* __restrict__ cand, const float* __restrict__ unary, + const r4d_u16* __restrict__ hp, const int* __restrict__ anchor, + const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ, + int* __restrict__ tok, int* __restrict__ par, int steps, int K, int R, int V, int N, + float inv_temp, int cand_ld, int hp_ld, int out_ld, int anchor_stride) { + r4d_dflash_tree_body(cand, unary, hp, anchor, pred, succ, tok, par, steps, K, R, V, N, inv_temp, + cand_ld, hp_ld, out_ld, anchor_stride); +} +__global__ __launch_bounds__(DTR_THREADS) void r4dchain_dflash_tree( + const int* __restrict__ cand, const float* __restrict__ unary, + const r4d_u16* __restrict__ hp, const int* __restrict__ anchor, + const r4d_u16* __restrict__ pred, const r4d_u16* __restrict__ succ, + int* __restrict__ tok, int* __restrict__ par, int steps, int K, int R, int V, int N, + float inv_temp, int cand_ld, int hp_ld, int out_ld, int anchor_stride) { + r4d_chain_wait(); + r4d_dflash_tree_body(cand, unary, hp, anchor, pred, succ, tok, par, steps, K, R, V, N, inv_temp, + cand_ld, hp_ld, out_ld, anchor_stride); + r4d_chain_done(); +} + +// ============================================================== the plugin ABI entry point +enum { DT_CAND = 0, DT_UNARY, DT_HP, DT_ANCHOR, DT_PRED, DT_SUCC, DT_TOK, DT_PAR }; + +static long long dt_plane(const RadTensor* t, uint32_t dtype, long long width, long long rows) { + if (!t || !t->data || t->rank != 2) return -1; + if (t->dtype != dtype) return -1; + if (t->shape[1] < width || t->shape[0] < rows) return -1; + const long long pitch = r4d_row_pitch(t); + return (pitch >= width) ? pitch : -1; +} + +extern "C" int r4d_rad_dflash_tree(const RadArgs* a, RadStream st) { + const RadTensor* cand = r4d_opt(a, DT_CAND); + const RadTensor* un = r4d_opt(a, DT_UNARY); + const RadTensor* hp = r4d_opt(a, DT_HP); + const RadTensor* anc = r4d_opt(a, DT_ANCHOR); + const RadTensor* pr = r4d_opt(a, DT_PRED); + const RadTensor* sc = r4d_opt(a, DT_SUCC); + const RadTensor* tok = r4d_opt(a, DT_TOK); + const RadTensor* par = r4d_opt(a, DT_PAR); + if (!cand || !un || !anc || !pr || !sc || !tok || !par) return R4D_NO(RAD_E_INVAL); + + const long long steps = r4d_geti_or(a, "steps", 0); + const long long K = r4d_geti_or(a, "top_k", 0); + const long long R = r4d_geti_or(a, "rank", 0); + const long long V = r4d_geti_or(a, "n_vocab", 0); + const long long N = r4d_geti_or(a, "nodes", steps); + const double temp = rad_args_getf_or(a, "temp", 1.0); + /* M from the output plane, as dflash_select: the parameter is the band's bound. */ + if (tok->rank != 2 || par->rank != 2) return R4D_NO(RAD_E_SHAPE); + const long long M = tok->shape[0]; + if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || V <= 0 || N <= 0) return R4D_NO(RAD_E_INVAL); + if (K > DTR_MAX_K || R < DTR_WAVE || R > DTR_MAX_R || (R % DTR_WAVE) || N > DTR_MAX_N || + steps > DTR_MAX_N || !(temp > 0.0)) + return R4D_NO(RAD_E_SHAPE); + + const long long rows = M * steps; + const long long cand_ld = dt_plane(cand, RAD_I32, K, rows); + const long long un_ld = dt_plane(un, RAD_F32, K, rows); + const long long out_ld = dt_plane(tok, RAD_I32, N, M); + const long long par_ld = dt_plane(par, RAD_I32, N, M); + const bool has_hp = hp && hp->data; + const long long hp_ld = has_hp ? dt_plane(hp, RAD_BF16, R, rows) : 0; + if (cand_ld < 0 || un_ld < 0 || hp_ld < 0 || out_ld < 0 || par_ld < 0) return R4D_NO(RAD_E_SHAPE); + if (cand_ld != un_ld || out_ld != par_ld) return R4D_NO(RAD_E_STRIDE); + if (pr->dtype != RAD_BF16 || sc->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(pr) || !r4d_contig(sc)) return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(pr) < V * R || r4d_numel(sc) < V * R) return R4D_NO(RAD_E_SHAPE); + const long long astr = r4d_geti_or(a, "anchor_stride", 1); + if (anc->dtype != RAD_I32 && anc->dtype != RAD_U32) return R4D_NO(RAD_E_DTYPE); + if (astr < 1 || !r4d_contig(anc)) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(anc) < (M - 1) * astr + 1) return R4D_NO(RAD_E_SHAPE); + + const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64; + hipLaunchKernelGGL((ch ? r4dchain_dflash_tree : r4d_dflash_tree_kernel), dim3((unsigned)M), + dim3(DTR_THREADS), 0, (hipStream_t)st, + (const int*)cand->data, (const float*)un->data, + has_hp ? (const r4d_u16*)hp->data : nullptr, (const int*)anc->data, + (const r4d_u16*)pr->data, (const r4d_u16*)sc->data, + (int*)tok->data, (int*)par->data, (int)steps, (int)K, (int)R, (int)V, (int)N, + (float)(1.0 / temp), (int)cand_ld, (int)hp_ld, (int)out_ld, (int)astr); + return R4D_RAW((int)hipGetLastError()); +} diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index 79d8e483..d734c42a 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -382,8 +382,8 @@ __device__ __forceinline__ unsigned int arq_load_acq(const unsigned int* p) { // HI8: ar_rmsnorm_had_quant_i8g, pass two in norm_quant_row's rotated int8 form. The reduction and // the norm are untouched, so `x`, the residual and `y` are ar_rmsnorm_quant_fp8's bytes. // PAD (wire 6 only): the row is whole 64-element groups but not whole chunks, so its last chunk is -// padded and a chunk's elements are found by (row, chunk in row). Without it the flat index is the -// element offset, the code a row of whole chunks has always run. +// padded and a chunk's elements are found by (row, chunk in row). Without it, for a row of whole +// chunks, the flat chunk index gives the element offset. template __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( @@ -393,7 +393,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, char* loc_pack, long loc_scale_off, int M, uint32_t n, uint32_t nkb, float eps, float wadd, uint32_t r_ld, uint32_t y_ld, uint32_t q_ld, uint32_t s_ld, - int slot_stride16, int drain, int acq, unsigned int nbw) { + int slot_stride16, int drain, int acq, unsigned int nbw, long stage) { __shared__ float lds[THR / kWave]; __shared__ unsigned int s_seq, s_slot; const int b = (int)blockIdx.x, nb = (int)gridDim.x; @@ -412,14 +412,15 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); /* device-resident, replay-safe */ const unsigned int sq = s_seq; int4* const ps = peer_base + (size_t)s_slot * slot_stride16; - const int4* const ms = my_base + (size_t)s_slot * slot_stride16; + const int4* ms = my_base + (size_t)s_slot * slot_stride16; + const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h) /* The slot is split as in the standalone compressed all-reduce: packed symbols from the base, * bf16 group scales from half way up. Group indices are global over the [M][n] message. */ char* const p_pay = (char*)ps; - const char* const m_pay = (const char*)ms; + const char* m_pay = (const char*)ms; unsigned short* const p_sc = (unsigned short*)((char*)ps + (size_t)(slot_stride16 >> 1) * 16); - const unsigned short* const m_sc = + const unsigned short* m_sc = (const unsigned short*)((const char*)ms + (size_t)(slot_stride16 >> 1) * 16); /* This rank's own packed half, laid out like the peer slot (symbols from the base, scales from * `loc_scale_off`) and indexed by global chunk and group, so blocks never overlap. */ @@ -538,7 +539,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( const int wpr = (int)(n >> 3); const int4* const m4 = (const int4*)ms; for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) - h += r4d_archk_u4(m4[k], 4u * (unsigned)k); + h += r4d_archk_u4(r4d_archk_keep(&m4[k], md), 4u * (unsigned)k); } else { for (int ci = (int)wave; ci < cpb; ci += (int)(THR / ARQ_WV)) { const int c = c00 + ci; @@ -546,24 +547,33 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel( const unsigned int cd = (unsigned)c * (ARQ_CBYTES / 4); #pragma unroll for (int w4 = 0; w4 + 4 <= ARQ_NWORD; w4 += 4) - h += r4d_archk_u4(*(const uint4*)(pb + w4 * 4 * ARQ_WV + lane * 16), - cd + (unsigned)(w4 * ARQ_WV) + lane * 4u); + h += r4d_archk_u4( + r4d_archk_keep((const uint4*)(pb + w4 * 4 * ARQ_WV + lane * 16), md), + cd + (unsigned)(w4 * ARQ_WV) + lane * 4u); if constexpr (ARQ_NWORD % 4 >= 2) { - const uint2 u = *(const uint2*)(pb + (ARQ_NWORD & ~3) * 4 * ARQ_WV + lane * 8); + const uint2 u = r4d_archk_keep( + (const uint2*)(pb + (ARQ_NWORD & ~3) * 4 * ARQ_WV + lane * 8), md); const unsigned int e = cd + (unsigned)((ARQ_NWORD & ~3) * ARQ_WV) + lane * 2u; h += r4d_archk_mix(u.x, e) + r4d_archk_mix(u.y, e + 1u); } if constexpr (ARQ_NWORD % 2 == 1) - h += r4d_archk_mix(*(const unsigned int*)(pb + (ARQ_NWORD - 1) * 4 * ARQ_WV + lane * 4), - cd + (unsigned)((ARQ_NWORD - 1) * ARQ_WV) + lane); + h += r4d_archk_mix( + r4d_archk_keep((const unsigned int*)(pb + (ARQ_NWORD - 1) * 4 * ARQ_WV + + lane * 4), md), + cd + (unsigned)((ARQ_NWORD - 1) * ARQ_WV) + lane); #pragma unroll for (int t = 0; t < ARQ_ITERS; ++t) { const int g = c * ARQ_CG + t * ARQ_GPW + gw; - if (lig == 0) h += r4d_archk_mix(m_sc[g], R4D_ARCHK_U16 + (unsigned)g); + if (lig == 0) + h += r4d_archk_mix(r4d_archk_keep(&m_sc[g], md), + R4D_ARCHK_U16 + (unsigned)g); } } } }); + ms = r4d_archk_moved(ms, md); + m_pay = r4d_archk_moved(m_pay, md); + m_sc = r4d_archk_moved(m_sc, md); if constexpr (WIRE == 6) { /* Reduce: unpack both halves of every chunk this block owns, add in fp32, inverse-rotate, @@ -889,7 +899,8 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int q_ld, int s_ld, long stream, int nblocks, int nthreads, int drain, int acq, int wire, - long loc_pack, long loc_scale_off, long wp, bool hi8) { + long loc_pack, long loc_scale_off, long wp, bool hi8, + long stage) { if (!x || !w || !q || !s) return -1; if (wp && !res) return -10; // a post-norm needs the stream if (hi8 && wp) return -11; @@ -928,7 +939,7 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer (unsigned int*)my_flags, (unsigned int*)seq_ctrs, (char*)loc_pack, \ (long)loc_scale_off, M, (uint32_t)n, \ (uint32_t)nkb, eps, wadd, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \ - (uint32_t)s_ld, (int)slot_stride16, drain, acq, (unsigned)nbw) + (uint32_t)s_ld, (int)slot_stride16, drain, acq, (unsigned)nbw, stage) #define R4D_ARQ_H(wf, rs, T, W, PO, H) \ do { if (pad) R4D_ARQ_HP(wf, rs, T, W, PO, H, (W == 6)); \ else R4D_ARQ_HP(wf, rs, T, W, PO, H, false); } while (0) @@ -962,11 +973,11 @@ extern "C" int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int q_ld, int s_ld, long stream, int nblocks, int nthreads, int drain, int acq, int wire, - long loc_pack, long loc_scale_off, long wp) { + long loc_pack, long loc_scale_off, long wp, long stage) { return ar_rmsnorm_quant_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs, slot_stride16, x, res, w, y, q, s, M, n, eps, wadd, w_f32, r_ld, y_ld, q_ld, s_ld, stream, nblocks, nthreads, drain, acq, - wire, loc_pack, loc_scale_off, wp, false); + wire, loc_pack, loc_scale_off, wp, false, stage); } // The same with had_quant_act_i8g's quantiser on the norm's pass (no post-norm). @@ -976,11 +987,12 @@ extern "C" int r4d_ar_rmsnorm_had_quant_i8g(long peer_scratch, long my_scratch, int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, int q_ld, int s_ld, long stream, int nblocks, int nthreads, int drain, int acq, - int wire, long loc_pack, long loc_scale_off) { + int wire, long loc_pack, long loc_scale_off, + long stage) { return ar_rmsnorm_quant_launch(peer_scratch, my_scratch, peer_flags, my_flags, seq_ctrs, slot_stride16, x, res, w, y, q, s, M, n, eps, wadd, w_f32, r_ld, y_ld, q_ld, s_ld, stream, nblocks, nthreads, drain, acq, - wire, loc_pack, loc_scale_off, 0, true); + wire, loc_pack, loc_scale_off, 0, true, stage); } // ============================================================== the plugin ABI entry points diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index fb3a37f8..5ead5e9c 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -159,11 +159,11 @@ constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bo if (fk == 128u) return nt == 1u ? 16u : nt == 2u ? (full ? 16u : 12u) : nt == 3u ? 10u : (full && mw >= 8u) ? 10u : 9u; - /* The gated three-tile form at 8, not 9. At 9 waves' 168 registers its epilogue spilled - * 57 at the full tile (48 rows), which ran gate_up 51 % slower than 56 rows, and 10 below - * it, 70 with the LDS-staged scales. 8 waves leave 192, where it spills 9 and 10. The gated - * form is always MW 16, four waves a SIMD a block, so 8 and 9 both hold two blocks a WGP: - * no occupancy is lost. */ + /* The gated three-tile form pins 8 waves, not 9. At 9 waves (168 registers) its epilogue + * spills 57 registers at the full tile (48 rows) and 10 below it, 70 with the LDS-staged + * scales; the full-tile spill makes gate_up 51% slower than at 56 rows. At 8 waves (192 + * registers) it spills 9 and 10. The gated form is always MW 16, four waves a SIMD a + * block, so 8 and 9 waves both hold two blocks a WGP and no occupancy is lost. */ return nt == 1u ? 12u : nt == 2u ? 10u : nt == 3u ? (gated ? 8u : 9u) : mw == 4u ? 7u : 8u; } @@ -171,7 +171,7 @@ constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bo return nt == 1u ? 16u : nt == 2u ? (full ? 10u : 12u) : nt == 3u ? (full ? 9u : 10u) : full ? 7u : 9u; /* 10, not 12. The fold's LDS-staged scales (gemm_fp8a8_kernel) need a few more - * registers than 12 waves' 120 leave, and spilled. gfx12 allocates registers 24 at a time, so + * registers than the 120 that 12 waves leave, and spill there. gfx12 allocates registers 24 at a time, so * 11 waves leave 120 as well and 10 is the next step (144). No decode shape puts more than 8 of * these waves on a SIMD, so the lower pin costs no occupancy. */ if (nt == 1u) return 10u; @@ -294,16 +294,15 @@ __device__ __forceinline__ void gemm_fp8a8_body( afrag + (size_t)(arow * ksuper + st) * r4d_fp8::kTileBytes, alive && st < ksuper); } - /* The fold's scales are staged through LDS a K tile ahead, beside the B tile. The - * fold loaded them itself, after the next tile's prefetch had been issued; loads return in - * order, so each fold waited for that whole prefetch, twice a tile at FK = 256, and the "one - * tile ahead" overlapped nothing. Now the block's threads each load one weight-scale dword and - * one activation scale of tile c0+FK with its B prefetch (a few each only in the selftest's - * one- and two-wave pins) and store them at the top of the next pass with the B tile, so a fold - * reads LDS. Two registers a thread: holding a tile's scales a lane (8 + 2*NT registers) - * spilled at the decode shapes' register pins. Same values as before: bit-identical. A dead - * wave's fp8 block scale reads as 0 instead of the plane row past the end it used to read; its - * rows are never stored. + /* The fold's scales are staged through LDS one K tile ahead, beside the B tile. A fold that + * loaded its own scales after the next tile's prefetch was issued would wait for that whole + * prefetch (loads return in order), twice a tile at FK = 256. Instead each thread loads one + * weight-scale dword and one activation scale of tile c0+FK with its B prefetch (a few each + * only in the selftest's one- and two-wave pins) and stores them with the B tile at the top of + * the next pass, so a fold reads LDS. That costs two registers a thread; holding a tile's + * scales per lane (8 + 2*NT registers) spills at the decode shapes' register pins. The staged + * values are the ones a direct load reads, so results are bit-identical. A dead wave's fp8 + * block scale reads as 0; its rows are never stored. * * A tile holds kFolds = FK / kBlock scale blocks, and the fold at `ks` uses block ks / kBlock * of its tile. s_ws: I8, each wave's 16 bf16 row scales a block, [MW][kFolds][8] dwords @@ -647,12 +646,10 @@ __device__ __forceinline__ void gemm_fp8a8_body( const float* const w0 = (const float*)Y; uint16_t* const cy = (uint16_t*)C; /* Consecutive threads take consecutive weight rows, which are adjacent in a - * partial plane ([nb][rows]), four rows a thread as one 16-byte load and kFinU quads in - * flight at each z. The loop walked the token index fastest, `rows` floats apart, one - * element a thread at a time: a cache line a load and a round trip each, which at - * N = 512, M = 64 (four columns of blocks finishing 8,192 elements over four planes) - * was most of a 45 us call. Each element is still summed from 0.0f in ascending z: - * bit-identical. */ + * partial plane ([nb][rows]): four rows a thread as one 16-byte load, kFinU quads in + * flight at each z. Walking the token index fastest would put consecutive threads + * `rows` floats apart, a cache line and a round trip per element. Both branches sum + * each element from 0.0f in ascending z, so they are bit-identical. */ const uint32_t nr = rhi - rlo; const size_t zs = (size_t)rows * nb; if ((rows & 3u) == 0u && (nr & 3u) == 0u && ((uintptr_t)C & 7u) == 0u diff --git a/libr4d/r4d_hc_bf16.hip b/libr4d/r4d_hc_bf16.hip index f8cda02a..dfbd15ff 100644 --- a/libr4d/r4d_hc_bf16.hip +++ b/libr4d/r4d_hc_bf16.hip @@ -17,6 +17,8 @@ // // `x` depends on all of `d`, so no workgroup can produce a channel of `x` before every column of // `d` exists. The kernel boundary serves as the grid-wide barrier, without cooperative launch. +// For a small decode step (E4M3, hc 4, n 2560, up to seven rows), hc_read_fused_kernel runs A and +// B as one grid instead, its B blocks waiting on a ticket-ordered counter (see that kernel's note). // // Weight traffic, not arithmetic, decides the decomposition. At Qwen3.8-Flash-Next's shape // (n 2560, hc 4, LR 320) each mixing matrix is 6.55 MB and there are 96 connections: 1.27 GB per @@ -207,9 +209,10 @@ __device__ __forceinline__ float hc8_dot_down(const unsigned short* __restrict__ return acc; } -/* hc8_dot_down for two rows of W_down at once, one read of N from LDS feeding both. A - * wave owning two columns (four rows of a decode step) read the 20 KB vector once per column, and - * kernel A's dots were LDS-bound. Each row's sum is the same fmaf sequence as hc8_dot_down's. */ +/* hc8_dot_down for two rows of W_down at once, one read of N from LDS feeding both, so a wave + * owning two columns (four rows of a decode step) reads the 20 KB vector once rather than once per + * column; kernel A's dots are LDS-bound. Each row's sum is the same fmaf sequence as + * hc8_dot_down's. */ __device__ __forceinline__ float hc8_dot16n(const float* nf, uint4 c) { float wf[16]; e4m3x8(c.x, c.y, wf); @@ -320,9 +323,8 @@ __device__ __forceinline__ void hc8_up_load(const unsigned char* __restrict__ wr /* RPT rows of W_up with the same quarter against RG rows of `d`: each value of `d` read from LDS * feeds RPT products, and `d` sits in LDS as the bf16 it is, sixteen values in two 16-byte reads * (the quarter, its group and lr are multiples of 16 by r4d_hc8::group_ok, and the base is aligned). - * Read as floats a value at a time, the dot was a chain of LDS round trips: 7.4 of the 22.8 us at - * four rows with every byte cache-resident. Each (row, r) accumulates the same fmaf sequence on the - * same values as hc8_dot_up. */ + * Read as floats a value at a time, the dot would be a chain of LDS round trips. Each (row, r) + * accumulates the same fmaf sequence on the same values as hc8_dot_up. */ template __device__ __forceinline__ void hc8_up_dot_rows(const unsigned short* __restrict__ sdh, long lr, const Hc8UpQuarter* o, int q4, @@ -373,7 +375,7 @@ __device__ __forceinline__ float wave_sum(float v) { return r4d_wave_sum(v); } /* A barrier that orders LDS only. __syncthreads() fences at workgroup scope, which in * WGP mode on gfx12 waits for every outstanding global load: a load issued for the next pass of a - * K loop could not stay in flight across it, and a software-pipelined loop ran as serially as the + * K loop cannot stay in flight across it, so a software-pipelined loop runs as serially as the * plain one. Where a barrier guards only LDS tiles, this one leaves global loads in flight. */ __device__ __forceinline__ void hc_lds_barrier() { __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); @@ -882,9 +884,9 @@ constexpr long kHcReadAStaticLds = (long)(kWaves * kHcMax + kHcMax) * (long)size * Flash-Next's shape). Thread t's elements of `h` are then t + e * kThreads for e < HCP * PER, the * stream being e / PER, so every one of them and of the norm weight can be loaded before the first * is used: one round trip from the cache instead of one per stream for the sums of squares and - * again for N, the ten-odd dependent latencies that set the decode step's time here (the kernel - * ran 8.3 us at one row with every byte cache-resident). The sums and N take the same values in - * the same order, so the output is bit-identical to the loops below. */ + * again for N. Those ten-odd dependent latencies, not bytes, set the kernel's time at decode. The + * sums and N take the same values in the same order, so the output is bit-identical to the loops + * below. */ template __device__ __forceinline__ void hc_read_a_body(const unsigned short* __restrict__ h, const float* __restrict__ w, const void* __restrict__ downv, long dld, @@ -896,7 +898,7 @@ __device__ __forceinline__ void hc_read_a_body(const unsigned short* __restrict_ unsigned xpub) { /* 16-byte aligned, for the 16-byte LDS reads of the dots. The dynamic region starts * after the kernel's static LDS, which in hc_read_fused_kernel is not a multiple of 16; a - * misaligned base ran the fused form's A blocks three times slower at four rows. */ + * misaligned base makes the fused form's A blocks three times slower at four rows. */ extern __shared__ __attribute__((aligned(16))) unsigned short sN[]; /* [hc * n], transposed per 256-element chunk */ __shared__ float s_part[kWaves][kHcMax]; __shared__ float s_scale[kHcMax]; @@ -1289,14 +1291,14 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon const int ipb = kBR / hc; /* channels this workgroup owns */ const long i0 = (long)bx * ipb; - /* Every load this kernel makes before its first barrier, issued together. At - * decode it is a chain of dependent latencies, not a stream of bytes (12 us at four rows with - * every byte cache-resident). `d` goes first, all of a thread's share at once (lr is at most - * two thread strides here), since loads return in order and `d` is what the barrier waits on; - * then this thread's quarter row of W_up, which does not depend on `d`; then, when one mix item - * a thread covers the block's (RG * ipb <= the thread count, always at hc 4), the hc values N - * of its channel from `h`, the norm gain and kernel A's scales. Same values, same order: - * bit-identical. */ + /* Every load this kernel makes before its first barrier, issued together: at decode the + * kernel is a chain of dependent latencies, not a stream of bytes. `d` goes first, all of a + * thread's share at once (lr is at most two thread strides here), since loads return in order + * and `d` is what the barrier waits on; then this thread's quarter row of W_up, which does not + * depend on `d`; then, when one mix item a thread covers the block's (RG * ipb <= the thread + * count, always at hc 4), the hc values N of its channel from `h`, the norm gain and kernel + * A's scales. Only the issue order moves; the arithmetic sees the same values in the same + * order, so the result is bit-identical. */ constexpr int kDStage = 2; const bool dpre = lr <= (long)kDStage * kThreads; unsigned short dv[RG][kDStage]; /* bf16 bits; the E4M3 dot keeps them as is */ @@ -1325,7 +1327,7 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon const bool one = RG * ipb <= kThreads; float Npre[kHcMax]; if constexpr (WAIT) { - /* The fused form (hc_read_fused_kernel): `h` and the gain now, kernel A's half after it. */ + /* The fused form (hc_read_fused_kernel): `h` and the gain here, kernel A's half after it. */ float hv[kHcMax], wv[kHcMax]; const int rl = one && tid < RG * ipb ? tid / ipb : 0, ii = tid - rl * ipb; const long r = r0 + rl < rows ? r0 + rl : rows - 1; @@ -1475,9 +1477,9 @@ __device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, lon if (r >= rows) return; const long base = (i0 / kUpTB) * kUpTB; const unsigned short* const xr = x + r * xrow + base; - /* A lane's four channels, read once for the amax, the codes and the rotation (it - * read the group three times, each a dependent round trip at the end of the step's chain). The - * amax is over the same 128 values and max is exact, so this is bit-identical. */ + /* A lane's four channels, read once for the amax, the codes and the rotation; separate reads + * would each be a dependent round trip at the end of the step's chain. The amax is over the + * same 128 values and max is exact, so the result is bit-identical. */ static_assert(kUpTB == 4 * kWave, "a lane holds four channels of the group"); float v[4]; #pragma unroll @@ -1598,10 +1600,9 @@ static inline int hc_up_launch(const RadTensor* up, long uld, bool f8, const uns } /* Rows of W_up a thread (hc_up_mix_kernel's RPT), where the wider workgroup's channels - * still divide a scale group and the width. Two, measured at Flash-Next's shape (rad-kbench, cold, - * the fused form at one, two and four rows): one row 18.4 / 18.9 / 20.6 us, two 17.0 / 17.8 / - * 20.4; four, before the bf16 dot, lost to two at every count (27.0 us at four rows, past the - * registers). */ + * still divide a scale group and the width. Two: at Flash-Next's shape (cold caches, the fused + * form at one, two and four rows) two beats one at every row count, and four runs past the + * register budget and loses to two. */ constexpr int kUpRpt = 2; static inline int hc_up_rpt(bool f8, int hc, long n) { int rpt = f8 ? kUpRpt : 1; @@ -1611,20 +1612,18 @@ static inline int hc_up_rpt(bool f8, int hc, long n) { return rpt; } -/* hc_up_mix_kernel's launch: hc_up's row group; counter slots are (rows / rg) row groups of - * n / kUpTB scale groups. */ -/* ============================================================== the previous decode kernels +/* ============================================================== the two-grid decode kernels * - * hc_read's decode kernels as they were before the one-grid form and the pipelined tiled up-mix: - * kernel A, then the up-mix kernel in a second launch, and the tiled up-mix with its K passes in - * sequence. Kept verbatim behind r4d_hc_read_pin_decode(1) so r4d_selftest can compare the - * current forms with them byte for byte and --perfhc can time both from one build. */ + * hc_read's decode path as two launches: kernel A, then the up-mix kernel in a second launch, and + * the tiled up-mix with its K passes unpipelined. r4d_hc_read_pin_decode(1) selects them, so + * r4d_selftest can compare the served forms against them byte for byte and --perfhc can time both + * from one build. They are the reference for that comparison; keep them as they are. */ static int g_hc_decode_form = 0; template __global__ __launch_bounds__(kThreads) __attribute__((amdgpu_waves_per_eu(F8 ? 9 : 1, F8 ? 9 : 16))) -void hc_read_a_prev_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, +void hc_read_a_2grid_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, const void* __restrict__ downv, long dld, const unsigned short* __restrict__ injw, unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, @@ -1767,7 +1766,7 @@ void hc_read_a_prev_kernel(const unsigned short* __restrict__ h, const float* __ template __global__ __launch_bounds__(kThreads) -void hc_up_mix_prev_kernel(const void* __restrict__ upv, long uld, +void hc_up_mix_2grid_kernel(const void* __restrict__ upv, long uld, const unsigned short* __restrict__ dbuf, const unsigned short* __restrict__ h, const float* __restrict__ w, const float* __restrict__ scalein, @@ -1877,7 +1876,7 @@ void hc_up_mix_prev_kernel(const void* __restrict__ upv, long uld, } } -static inline int hc_up_mix_prev_launch(const RadTensor* up, long uld, bool f8, bool i8, +static inline int hc_up_mix_2grid_launch(const RadTensor* up, long uld, bool f8, bool i8, const unsigned short* dbuf, const unsigned short* h, const float* w, const float* scale, unsigned short* x, unsigned char* q, float* qs, @@ -1892,7 +1891,7 @@ static inline int hc_up_mix_prev_launch(const RadTensor* up, long uld, bool f8, const unsigned lds = (unsigned)(rg * lr * sizeof(float)); const void* upp = up->data; #define HC_UPMIX_CASE3(RG_, F8_, I8_) \ - emit_rc = R4D_EMIT(stream, (hc_up_mix_prev_kernel), grid, dim3(kThreads), lds, \ + emit_rc = R4D_EMIT(stream, (hc_up_mix_2grid_kernel), grid, dim3(kThreads), lds, \ upp, uld, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, (long)rows, (long)n, \ hc, \ (long)lr, (long)hrow, (long)xrow, (long)qrow, (long)srow, (long)rqrow, \ @@ -1914,6 +1913,8 @@ static inline int hc_up_mix_prev_launch(const RadTensor* up, long uld, bool f8, return emit_rc; } +/* hc_up_mix_kernel's launch: hc_up's row group; counter slots are (rows / rg) row groups of + * n / kUpTB scale groups. */ static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool i8, const unsigned short* dbuf, const unsigned short* h, const float* w, const float* scale, @@ -1924,7 +1925,7 @@ static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool long long srow, long long rqrow, long long rsrow, float wadd, RadStream stream) { if (g_hc_decode_form == 1) - return hc_up_mix_prev_launch(up, uld, f8, i8, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, + return hc_up_mix_2grid_launch(up, uld, f8, i8, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd, stream); int emit_rc = RAD_OK; @@ -2598,11 +2599,10 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, /* At the decode tile (RT 32, E4M3, lr a whole number of passes) the K loop is * software-pipelined: a pass issues the next pass's loads before staging its own from - * registers, and the mix's operands are loaded with the first pass, where each pass waited - * on its own loads. Addresses are computed once, nothing branches and the barriers order LDS - * only (hc_lds_barrier), so the waits stay partial. 17.8 -> 16.6 us at 32 rows (rad-kbench, - * cold): the kernel is bound less by memory than by its staging, barriers and WMMA. The staged - * values are the loop's own, in the same order: bit-identical. */ + * registers, and the mix's operands are loaded with the first pass. Addresses are computed + * once, nothing branches and the barriers order LDS only (hc_lds_barrier), so the waits stay + * partial; the kernel is bound less by memory than by its staging, barriers and WMMA. The + * staged values are the loop's own, in the same order: bit-identical. */ constexpr int kAPer = RT * (kTKT / 8) / kThreads, kBPer = NT * (kTKT / 8) / kThreads; constexpr int kNPer = RT * NT / kThreads; constexpr bool kPipe = F8 && RT == 32 && kAPer == 1 && kBPer * kThreads == NT * (kTKT / 8) @@ -2767,10 +2767,10 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, /* The rotated codes need a whole wave per row, while the codes below use kThreads / RT threads * per row, so the rotation walks the tile's rows a wave at a time first. */ - /* Both finishers below load what they read before using any of it -- the - * rotation every row of the wave's, the codes a thread's four-channel runs -- where they - * walked rows and channels a dependent load at a time; the codes' amax is over the same 128 - * values. The tail of this kernel is one block's chain, so these were its links. Bit-identical. */ + /* Both finishers below load what they read before using any of it (the rotation every row + * of the wave's, the codes a thread's four-channel runs) rather than one dependent load at a + * time, since the tail of this kernel is one block's latency chain. The codes' amax is over + * the same 128 values, so the result is bit-identical. */ if (rq) { const long gb = (i0 / kUpTB) * kUpTB; constexpr int kRPW = (RT + kWaves - 1) / kWaves; /* rows a wave */ @@ -2819,11 +2819,11 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, } } -/* The tiled up-mix as it was before its K passes were pipelined (see the previous decode - * kernels above; r4d_hc_read_pin_decode(1)). */ +/* The tiled up-mix with its K passes unpipelined, for r4d_hc_read_pin_decode(1) (see the + * two-grid decode kernels above). */ template __global__ __launch_bounds__(kThreads) -void hc_up_mix_tiled_prev_kernel(const void* __restrict__ upv, long uld, +void hc_up_mix_tiled_2grid_kernel(const void* __restrict__ upv, long uld, const unsigned short* __restrict__ dbuf, const unsigned short* __restrict__ h, const float* __restrict__ w, const float* __restrict__ scalein, @@ -3246,7 +3246,7 @@ static inline void hc_up_mix_tiled_launch(int rt, bool f8, bool i8, const void* rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd) #define HC_UM_CASE3(RT_, F8_, I8_) \ do { \ - if (g_hc_decode_form == 1) HC_UM_K((hc_up_mix_tiled_prev_kernel)); \ + if (g_hc_decode_form == 1) HC_UM_K((hc_up_mix_tiled_2grid_kernel)); \ else HC_UM_K((hc_up_mix_tiled_kernel)); \ } while (0) #define HC_UM_CASE(RT_, F8_) \ @@ -4812,7 +4812,7 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { inj ? (unsigned short*)inj->data : nullptr, scale, (long)rows, (long)n, (int)hc, \ (long)lr, (long)ta, (long)hrow, (long)irow, eps, wadd) if (g_hc_decode_form == 1) - emit_rc = f8 ? HC_READ_A(hc_read_a_prev_kernel) : HC_READ_A(hc_read_a_prev_kernel); + emit_rc = f8 ? HC_READ_A(hc_read_a_2grid_kernel) : HC_READ_A(hc_read_a_2grid_kernel); else if (pre) emit_rc = HC_READ_A((hc_read_a_kernel)); else emit_rc = f8 ? HC_READ_A(hc_read_a_kernel) : HC_READ_A(hc_read_a_kernel); #undef HC_READ_A diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 91418315..2bc3253e 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -175,6 +175,18 @@ int r4d_rad_attn_window_h512_gqa8_fp8 (const RadArgs*, RadStream); int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*); int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*); int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*); +/* attn_paged_qrow_tree (docs/OPS.md): the h256/gqa2 split-KV decode and the windowed kernels with a + * tree verify's mask from operand 8, `spec_parent`. */ +int r4d_rad_attn_qrow_tree_decode_h256_gqa2_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_qrow_tree_decode_h256_gqa2_bf16(const RadArgs*, RadStream); +#define R4D_WIN_TREE_DECL(HD, G) \ + int r4d_rad_attn_window_tree_h##HD##_gqa##G##_bf16(const RadArgs*, RadStream); \ + int r4d_rad_attn_window_tree_h##HD##_gqa##G##_fp8 (const RadArgs*, RadStream); +R4D_WIN_TREE_DECL(256, 1) R4D_WIN_TREE_DECL(256, 2) R4D_WIN_TREE_DECL(256, 4) R4D_WIN_TREE_DECL(256, 8) +R4D_WIN_TREE_DECL(512, 1) R4D_WIN_TREE_DECL(512, 2) R4D_WIN_TREE_DECL(512, 4) R4D_WIN_TREE_DECL(512, 8) +#undef R4D_WIN_TREE_DECL +/* dflash_tree (r4d_dflash_tree_bf16.hip): dflash_select's lattice grown best-first into a tree. */ +int r4d_rad_dflash_tree(const RadArgs*, RadStream); /* The top-1 of a row of all-gathered (id, value) pairs, written one id a row: the vocab-sharded * draft head's merge (r4d_pair_argmax_f32.hip). */ int r4d_rad_pair_argmax_f32(const RadArgs*, RadStream); diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip index ef4371cf..4638c916 100644 --- a/libr4d/r4d_rmsnorm_quant_i8.hip +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -308,7 +308,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel( signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags, unsigned int* seq_ctrs, int M, uint32_t n, float eps, float wadd, uint32_t r_ld, uint32_t y_ld, - int slot_stride16, int drain, int acq, unsigned int nbw) { + int slot_stride16, int drain, int acq, unsigned int nbw, long stage) { extern __shared__ uint16_t ybuf[]; __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; __shared__ unsigned int s_seq, s_slot; @@ -319,7 +319,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel( r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); /* device-resident, replay-safe */ const unsigned int sq = s_seq; int4* const ps = peer_base + (size_t)s_slot * slot_stride16; - const int4* const ms = my_base + (size_t)s_slot * slot_stride16; + const int4* ms = my_base + (size_t)s_slot * slot_stride16; + const long md = r4d_archk_md(stage, my_base); // the host mailbox's VRAM mirror (r4d_ar_seq.h) /* push my rows into the peer's slot; `x` is a tight [M][n] of bf16 */ const int wpr = (int)(n >> 3); @@ -346,8 +347,9 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel( if (acq) __threadfence_system(); r4d_archk_wait(my_flags, nbw, s_slot, (unsigned)b, sq, [&](unsigned int& h) { for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) - h += r4d_archk_u4(ms[k], 4u * (unsigned)k); + h += r4d_archk_u4(r4d_archk_keep(&ms[k], md), 4u * (unsigned)k); }); + ms = r4d_archk_moved(ms, md); const uint16_t* __restrict__ P = (const uint16_t*)ms; /* the peer's rows, in my scratch */ const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f; @@ -938,7 +940,7 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long long x, long res, long w, long wp, long sc, int sc_f32, long y, long q, long s, int M, int n, float eps, float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks, - int drain, int acq) { + int drain, int acq, long stage) { if (!x || !w || !q || !s) return -1; if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1; if (M <= 0 || n <= 0) return -2; @@ -961,7 +963,7 @@ extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long (const int4*)my_scratch, (unsigned int*)peer_flags, \ (unsigned int*)my_flags, (unsigned int*)seq_ctrs, M, (uint32_t)n, eps, \ wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, drain, acq, \ - (unsigned)nbw) + (unsigned)nbw, stage) #define R4D_ARQ8(WF, RS, PO, SC) \ do { if (thr == 1024) R4D_ARQ8_T(WF, RS, PO, SC, 1024); \ else if (thr == 512) R4D_ARQ8_T(WF, RS, PO, SC, 512); \ diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 114c5b4d..6a3710aa 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -123,6 +123,18 @@ static const RadOperandSpec oAttnPaged[] = { { "cu_seqlens", RAD_OPD_IN, 1 }, /* absent = one q_len for the whole batch */ { "out", RAD_OPD_OUT, 0 }, }; +/* attn_paged_qrow with a tree verify's parents (RadBatch::spec_parent, rad_drafter_tree). */ +static const RadOperandSpec oAttnPagedTree[] = { + { "q", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_IN, 0 }, + { "block_table", RAD_OPD_IN, 0 }, + { "seqused", RAD_OPD_IN, 0 }, + { "k_descale", RAD_OPD_IN, 1 }, + { "v_descale", RAD_OPD_IN, 1 }, + { "cu_seqlens", RAD_OPD_IN, 1 }, + { "out", RAD_OPD_OUT, 0 }, + { "spec_parent", RAD_OPD_IN, 0 }, +}; /* attn_paged with gate_quant_fp8 folded into its merge: attn_paged's parameters plus the two of * gate_quant_fp8's that are not implied (its `n` is `head_dim`, its rows attn_paged's (token, @@ -700,6 +712,28 @@ static const RadOperandSpec oDflashSelect[] = { { "succ", RAD_OPD_WEIGHT, 0 }, { "tokens", RAD_OPD_OUT, 0 }, }; +/* dflash_tree: dflash_select's, plus the node count, the softmax temperature and the parents. */ +static const RadParamSpec pDflashTree[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "steps", RAD_P_INT, RAD_REQUIRED }, + { "top_k", RAD_P_INT, RAD_REQUIRED }, + { "rank", RAD_P_INT, RAD_REQUIRED }, + { "n_vocab", RAD_P_INT, RAD_REQUIRED }, + { "anchor_stride", RAD_P_INT, RAD_OPTIONAL }, + { "nodes", RAD_P_INT, RAD_REQUIRED }, + { "temp", RAD_P_F64, RAD_OPTIONAL }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadOperandSpec oDflashTree[] = { + { "cand", RAD_OPD_IN, 0 }, + { "unary", RAD_OPD_IN, 0 }, + { "hp", RAD_OPD_IN, 1 }, + { "anchor", RAD_OPD_IN, 0 }, + { "pred", RAD_OPD_WEIGHT, 0 }, + { "succ", RAD_OPD_WEIGHT, 0 }, + { "tokens", RAD_OPD_OUT, 0 }, + { "parents", RAD_OPD_OUT, 0 }, +}; /* ------------------------------------------------------------------------------ collectives */ static const RadParamSpec pAllReduce[] = { @@ -3131,6 +3165,11 @@ static const RadOpSchema kSchemas[] = { "attn_paged, parameter for parameter and value for value, with q read at its own row " "pitch: a column slice of a wider row -- the q part of a fused [q|k|v] projection -- read " "where it lies rather than lifted into a dense block first."), + SCHEMA("attn_paged_qrow_tree", pAttnPaged, oAttnPagedTree, + "attn_paged_qrow 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 row). 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."), SCHEMA("attn_paged_gate_quant", pAttnPagedGq, oAttnPagedGq, "attn_paged followed by gate_quant_fp8 over its output, in the split-KV merge: each " "merged (token, head) row is gated, rounded, written to `out` and quantised to E4M3 " @@ -3237,6 +3276,12 @@ static const RadOpSchema kSchemas[] = { "positions, and the greedy walk that turns a block of independent top-k sets into one " "path. Only the K edges leaving the previous pick are scored, because the walk is " "serial and the other K-1 rows of the score matrix are never read."), + SCHEMA("dflash_tree", pDflashTree, oDflashTree, + "dflash_select's lattice and edge scores grown best-first into a tree of `nodes` nodes: " + "a taken node's children are the valid candidates at the next position, each with log " + "probability parent + log_softmax(score / temp) over them; 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, 0 for the anchor."), SCHEMA("all_reduce", pAllReduce, oAllReduce, "sum over the tensor-parallel group. `exact` separates the exact sum from the " "quantised wire and a caller that does not declare it gets no kernel. At 4 and 8 ranks " @@ -3907,6 +3952,15 @@ static const RadConstraint cAttnDecodeH256Gqa2Fp8[] = { C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), }; +/* attn_paged_qrow_tree on the same kernel: causal only (a tree has no two-sided reading). */ +static const RadConstraint cAttnTreeDecodeH256Gqa2Fp8[] = { + C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_EQ("causal", 1), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnTreeDecodeH256Gqa2Bf16[] = { + C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_EQ("causal", 1), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; static const RadConstraint cAttnDecodeH256Gqa2Bf16[] = { C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), @@ -4442,6 +4496,12 @@ static const RadConstraint cDflashSelect[] = { C_GE("steps", 1), C_GE("top_k", 1), C_LE("top_k", 32), C_DIV("rank", 32), C_LE("rank", 512), C_IN("dtype", "bf16"), }; +/* dflash_tree's frontier (nodes x top_k children) and its node table live in LDS. */ +static const RadConstraint cDflashTree[] = { + C_GE("steps", 1), C_LE("steps", 63), C_GE("top_k", 1), C_LE("top_k", 32), + C_DIV("rank", 32), C_LE("rank", 512), C_GE("nodes", 1), C_LE("nodes", 63), + C_IN("dtype", "bf16"), +}; /* The sandwich-norm joins hold 24 elements a thread over a 256-thread block (n <= 6144), and the * route form quantises in whole 128-column groups. pair_argmax takes any row; expert_scale's top_k * is the router's, at most 64. */ @@ -6630,6 +6690,28 @@ static const RadKernelInfo kKernels[] = { r4d_rad_attn_qrow_decode_h256_gqa2_scratch, nullptr, nullptr, nullptr }, +/* The same under attn_paged_qrow_tree: a tree verify's mask (O_TREE instances), causal only. */ +{ "attn_qrow_tree_decode_h256_gqa2_fp8kv", "attn_paged_qrow_tree", "attn", + "paged attention over a tree verify, q at its own row pitch, sliding window, split-KV", + "head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, causal", + "bf16 query (any row pitch, a multiple of 4), fp8-e4m3 kv cache with per-(seq,head) descales, " + "i32 parents, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnTreeDecodeH256Gqa2Fp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_qrow_tree_decode_h256_gqa2_fp8, + r4d_rad_attn_qrow_decode_h256_gqa2_scratch, + nullptr, nullptr, nullptr }, + +{ "attn_qrow_tree_decode_h256_gqa2_bf16kv", "attn_paged_qrow_tree", "attn", + "paged attention over a tree verify, q at its own row pitch, sliding window, split-KV", + "head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, causal", + "bf16 query (any row pitch, a multiple of 4), bf16 kv cache, i32 parents, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnTreeDecodeH256Gqa2Bf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_qrow_tree_decode_h256_gqa2_bf16, + r4d_rad_attn_qrow_decode_h256_gqa2_scratch, + nullptr, nullptr, nullptr }, + /* Head_dim 128 at gqa 8 under attn_paged_qrow (cAttnQrowH128G8Fp8 says why). */ { "attn_qrow_h128_gqa8_fp8kv", "attn_paged_qrow", "attn", "paged attention, any window, causal or not, split-KV (draft block); q at any row pitch", @@ -6818,6 +6900,27 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, #undef R4D_WIN_PAIR #undef R4D_WIN_ROW +/* ...and under attn_paged_qrow_tree, the scalar kernel with a tree verify's mask (the launch + * refuses a non-causal one and never takes the WMMA kernel). */ +#define R4D_WIN_TREE_ROW(HD, G, KVN, KVS, C, KVDOC) \ +{ "attn_qrow_tree_h" #HD "_gqa" #G "_" #KVN, "attn_paged_qrow_tree", "attn", \ + "paged attention over a tree verify, q at its own row pitch, any window, causal", \ + "head_dim " #HD ", " #G " queries per kv head, paged block 16, any q_len, varlen", \ + "bf16 query (any row pitch), " KVDOC " kv cache, i32 parents, bf16 out, f32 partials", \ + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, \ + ROW(C), NOTUNE, \ + nullptr, nullptr, r4d_rad_attn_window_tree_h##HD##_gqa##G##_##KVS, \ + r4d_rad_attn_window_h##HD##_scratch, \ + nullptr, nullptr, nullptr }, +#define R4D_WIN_TREE_PAIR(HD, GQ) \ + R4D_WIN_TREE_ROW(HD, GQ, bf16kv, bf16, cWinH##HD##G##GQ##Bf16, "bf16") \ + R4D_WIN_TREE_ROW(HD, GQ, fp8kv, fp8, cWinH##HD##G##GQ##Fp8, "fp8-e4m3 (per-(seq,head) descales)") +R4D_WIN_TREE_PAIR(256, 1) R4D_WIN_TREE_PAIR(256, 2) R4D_WIN_TREE_PAIR(256, 4) +R4D_WIN_TREE_PAIR(256, 8) R4D_WIN_TREE_PAIR(512, 1) R4D_WIN_TREE_PAIR(512, 2) +R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8) +#undef R4D_WIN_TREE_PAIR +#undef R4D_WIN_TREE_ROW + { "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 256, 12 queries per kv head, paged block 4, varlen", @@ -9015,6 +9118,16 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_dflash_select, nullptr, nullptr, nullptr, r4d_shape_dflash_select }, +{ "dflash_tree_bf16", "dflash_tree", "dflash", + "DFlash2's candidate lattice grown best-first into a tree (rad_drafter_tree): the selector's " + "edge scores for each taken node's children, one workgroup a sequence", + "top_k <= 32, rank a multiple of 32 and <= 512, steps and nodes <= 63: the frontier and the " + "node table are LDS extents", + "i32 candidate ids, f32 unary logits, bf16 hp and both codebooks, i32 tokens and parents out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cDflashTree), NOTUNE, + nullptr, nullptr, r4d_rad_dflash_tree, nullptr, nullptr, nullptr, nullptr }, + /* pair_argmax, the sandwich-norm joins and expert_scale. The joins and expert_scale have no * opd_shape: libref has no row for them, and tests/r4d_emu holds their source to the replaced chain * bit for bit on the host. pair_argmax is described as libref describes it. */ @@ -10034,6 +10147,8 @@ extern "C" int rad_kernel_chain(int i) { * plain, and the backend chains only the kernels named r4dchain* */ "attn_decode_h256_gqa2_fp8kv", "attn_decode_h256_gqa2_bf16kv", "attn_qrow_decode_h256_gqa2_fp8kv", "attn_qrow_decode_h256_gqa2_bf16kv", + /* ...and their tree verify forms (O_TREE instances, the same launch) */ + "attn_qrow_tree_decode_h256_gqa2_fp8kv", "attn_qrow_tree_decode_h256_gqa2_bf16kv", /* the fused junction: its tail form (the two-shot with the junction after it) only */ "ar_rmsnorm_quant_i8", "ar_rmsnorm_quant_i8_4rank", /* the 31B's full layers: the windowed attention and its merge (r4d_attn_paged_window.hip, @@ -10041,6 +10156,9 @@ extern "C" int rad_kernel_chain(int i) { "attn_qrow_h512_gqa2_fp8kv", "attn_qrow_h512_gqa2_bf16kv", "attn_qrow_h512_gqa4_fp8kv", "attn_qrow_h512_gqa4_bf16kv", "attn_qrow_h512_gqa8_fp8kv", "attn_qrow_h512_gqa8_bf16kv", + "attn_qrow_tree_h512_gqa2_fp8kv", "attn_qrow_tree_h512_gqa2_bf16kv", + "attn_qrow_tree_h512_gqa4_fp8kv", "attn_qrow_tree_h512_gqa4_bf16kv", + "attn_qrow_tree_h512_gqa8_fp8kv", "attn_qrow_tree_h512_gqa8_bf16kv", "quant_act_i8", /* DFlash2's query and context passes: the narrow fp8 GEMMs (the gated gate_up among * them), the activation quantiser, the norms, the conv projection, the opening @@ -10058,7 +10176,7 @@ extern "C" int rad_kernel_chain(int i) { * selector */ "sample_temp_f32", "sample_topk_f32", "sample_merge_topk_f32", "sample_pick_f32", "ar_gather_4rank", "gemm_w8a8_nt_m64", "rowtopk_bf16", "rowtopk_merge", - "dflash_select_bf16", + "dflash_select_bf16", "dflash_tree_bf16", /* the weight read beside a collective (its blocks add before reading, r4d_prefetch.hip) */ "prefetch", }; diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index cb167be2..ac230994 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -1052,14 +1052,19 @@ static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8 * extent, is 1024. 90ede42 read the parameter, trimmed a 2048-key context to 0, and the attention * over slice A's rows wrote nothing. */ /* The full-attention decode split law (r4d_decode_splits), read through the scratch hook's declare - * path, where the depth is the declared max_ctx: the region the law sizes over the region at one - * forced segment is the law's segment count (the region is the worst over 1..max_seqs sequences, - * which is the last count wherever n * splits(n) peaks there or ties, as in every batch below). - * Qwen3.8-27B's TP2 rank: 12 query heads over 2 KV heads, head_dim 256. An 8-row verify (three - * waves at gqa 6) splits by depth: up to 16384 tokens 128 / units (x4: 16), then at least 64, and - * past 65536 512 / units capped at 256 (x1: 256, x2: 128, x4 and more: 64). A plain decode and - * the short block's 4-row verify keep the 256-workgroup target, and the two-tiles-a-segment cap - * still binds a short context (1024 tokens: 64 tiles of 16, at most 32 segments). */ + * path, where the depth is the declared max_ctx. Qwen3.8-27B's TP2 rank: 12 query heads over 2 KV + * heads, head_dim 256. An 8-row verify (three waves at gqa 6) splits by depth: up to 16384 tokens + * 128 / units (x4: 16), then at least 64, and past 65536 512 / units capped at 256 (x1: 256, x2: + * 128, x4 and more: 64). A plain decode and the short block's 4-row verify keep the 256-workgroup + * target, and the two-tiles-a-segment cap still binds a short context (1024 tokens: 64 tiles of + * 16, at most 32 segments). + * + * The declared region is the worst over every sequence count up to max_seqs and every query length + * up to q_len (a shorter step can split more: attn_decode_scratch), so the region over the region + * at one forced segment is that worst, in the batch's own rows: `splits` is the law at the batch, + * `region` what the declare path must hold, at least `splits`. Where a 5-row step at shallow depth + * splits more per row than the 8-row verify (x1 at 65536, x2 and x4 at 16384, x4 at 1024), the + * region is the shorter step's. */ static void decode_split_law_case(const Plugin& pl) { const char* name = "attn_decode_h256_gqa6_bf16kv"; if (!sel(name)) return; @@ -1077,23 +1082,25 @@ static void decode_split_law_case(const Plugin& pl) { a.world_size = 1; return r->scratch(&a); }; - struct Want { int64_t seqs, q_len, ctx, splits; }; + struct Want { int64_t seqs, q_len, ctx, splits, region; }; const Want want[] = { - { 1, 8, 100000, 256 }, { 2, 8, 100000, 128 }, { 4, 8, 100000, 64 }, { 6, 8, 100000, 64 }, - { 8, 8, 100000, 64 }, { 2, 8, 65536, 64 }, { 2, 8, 65552, 128 }, { 1, 8, 65536, 64 }, - { 2, 8, 32768, 64 }, { 4, 8, 32768, 64 }, { 7, 8, 32768, 64 }, { 4, 8, 16400, 64 }, - { 4, 8, 16384, 16 }, { 2, 8, 16384, 32 }, { 4, 8, 1024, 16 }, { 1, 8, 1024, 32 }, - { 4, 8, 640, 16 }, { 8, 4, 100000, 16 }, { 16, 4, 100000, 8 }, { 4, 1, 100000, 32 }, - { 1, 1, 100000, 128 }, + { 1, 8, 100000, 256, 256 }, { 2, 8, 100000, 128, 128 }, { 4, 8, 100000, 64, 64 }, + { 6, 8, 100000, 64, 64 }, { 8, 8, 100000, 64, 64 }, { 2, 8, 65536, 64, 64 }, + { 2, 8, 65552, 128, 128 }, { 1, 8, 65536, 64, 80 }, { 2, 8, 32768, 64, 64 }, + { 4, 8, 32768, 64, 64 }, { 7, 8, 32768, 64, 64 }, { 4, 8, 16400, 64, 64 }, + { 4, 8, 16384, 16, 20 }, { 2, 8, 16384, 32, 40 }, { 4, 8, 1024, 16, 20 }, + { 1, 8, 1024, 32, 32 }, { 4, 8, 640, 16, 16 }, { 8, 4, 100000, 16, 16 }, + { 16, 4, 100000, 8, 8 }, { 4, 1, 100000, 32, 32 }, { 1, 1, 100000, 128, 128 }, }; int bad = 0; for (const Want& w : want) { const int64_t law = bytes(w.seqs, w.q_len, w.ctx, 0), one = bytes(w.seqs, w.q_len, w.ctx, 1); - const int64_t got = one > 0 && law > 0 ? law / one : -1; - if (got != w.splits) { - std::printf(" FAIL decode split law: %lld x %lld rows over %lld: %lld segments, want %lld\n", + const int64_t got = one > 0 && law > 0 && law % one == 0 ? law / one : -1; + if (got != w.region || w.region < w.splits) { + std::printf(" FAIL decode split law: %lld x %lld rows over %lld: a region of %lld " + "segments, want %lld (the batch's own %lld)\n", (long long)w.seqs, (long long)w.q_len, (long long)w.ctx, (long long)got, - (long long)w.splits); + (long long)w.region, (long long)w.splits); ++bad; } } @@ -1756,6 +1763,80 @@ static void attn_split_scratch_case(const Plugin& pl, const SplitGeo& g, const c } } +/* Every split-KV decode row's scratch at declare (the band's bound, parameters only, as the core + * sizes it) against what its launch checks at issue (the same hook over the issue's tensors): for + * each band bound up to 64 / gqa rows, every query length up to it and every sequence count up to + * max_seqs must fit. Host only; the tensors carry shapes and aligned placeholder addresses. The + * h256 split law targets 256 workgroups at q_len * gqa <= 32 and 128 above, so a step shorter than + * its band's bound can need more partials than the bound: 1.13.0 sized the bound only, and an MTP + * step of 4 rows at gqa 8 (band 5) refused with RAD_E_SCRATCH at issue (#293). */ +static void attn_decode_scratch_band_case(const Plugin& pl) { + for (int k = 0; k < pl.kernel_count(); ++k) { + const RadKernelInfo* r = pl.kernel_at(k); + int hd = 0, gqa = 0; + if (std::strncmp(r->name, "attn_decode_h", 13) || !r->scratch || + std::sscanf(r->name, "attn_decode_h%d_gqa%d", &hd, &gqa) != 2 || hd <= 0 || gqa <= 0) + continue; + if (!sel(r->name) && !sel("attn_decode_scratch")) continue; + const char* kvs = std::strrchr(r->name, '_') + 1; + const bool bf = !std::strcmp(kvs, "bf16kv"); + const int64_t rowe = !std::strcmp(kvs, "fp8v4") ? 25 * hd / 16 + : !std::strcmp(kvs, "k6v4") ? 22 * hd / 16 : 2 * hd; + const int64_t bs = std::strstr(r->name, "_bs4_") ? 4 : 16; + const int64_t max_seqs = 32, max_ctx = 200000, mb = (max_ctx + bs - 1) / bs; + const int top = std::max(1, 64 / gqa); + void* const fake = (void*)(uintptr_t)4096; /* aligned, never dereferenced */ + std::string why; + int checked = 0; + for (const int64_t kv : { 1, 2 }) { + const int64_t n_head = kv * gqa; + for (int band = 1; band <= top; ++band) { + std::vector ps = { + PI("q_len", band), PI("head_dim", hd), PI("gqa", gqa), PI("n_head", n_head), + PI("max_seqs", max_seqs), PI("max_ctx", max_ctx), PI("block_size", bs), + PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"), + PS("kv_dtype", bf ? "bf16" : "fp8_e4m3") }; + RadArgs d; + std::memset(&d, 0, sizeof(d)); + d.p = ps.data(); d.n_p = (int)ps.size(); d.world_size = 1; + const int64_t declared = r->scratch(&d); + if (declared < 0) { why += fmt("; kv%lld band %d: declare refused %lld", (long long)kv, + band, (long long)declared); continue; } + /* the issue: no n_head / max_seqs, so the hook reads the tensors */ + std::vector pi = { + PI("q_len", band), PI("head_dim", hd), PI("gqa", gqa), PI("max_ctx", max_ctx), + PI("block_size", bs), PI("causal", 1), PI("window", 0) }; + for (int q = 1; q <= band; ++q) + for (int64_t n = 1; n <= max_seqs; ++n) { + std::vector ts = { + T(fake, RAD_BF16, { n * q, n_head, hd }), + T(fake, bf ? RAD_BF16 : RAD_F8E4M3, { n * mb, kv, bs, rowe }), + T(fake, RAD_I32, { n, mb }), T(fake, RAD_I32, { n }), + T(fake, RAD_F32, { n, kv }), T(fake, RAD_F32, { n, kv }), + T(nullptr, RAD_I32, { n + 1 }), + T(fake, RAD_BF16, { n * q, n_head, hd }) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = pi.data(); a.n_p = (int)pi.size(); a.world_size = 1; + const int64_t need = r->scratch(&a); + ++checked; + if (need < 0 || need > declared) { + why += fmt("; kv%lld band %d: q_len %d x %lld sequences needs %lld, " + "declared %lld", (long long)kv, band, q, (long long)n, + (long long)need, (long long)declared); + q = band; + break; + } + } + } + } + ok(fmt("%s: decode scratch at declare covers every shorter step", r->name).c_str(), + why.empty() && checked > 0, + why.empty() ? fmt("%d issue geometries", checked) : why.substr(2)); + } +} + /* The h256/gqa6 prefill over an 8-bit cache with e4m3 products (`prefill_fp8` 1 Q.K^T, 2 P.V, 3 * both), against the inline oracle and against `exact`, the cache's exact row, on the same data. @@ -18141,13 +18222,13 @@ static void hc_read_i8(const Plugin& pl, int64_t M, bool real_stream, int form) } /* The gated residual's read at its decode kernels, byte for byte: the launcher's rule (kernels A and - * B as one grid at one to seven rows, the tiled up-mix pipelined from eight) against the kernels it - * replaced, pinned through r4d_hc_read_pin_decode(1). E4M3 or int8 codes, on a real stream (the + * B as one grid at one to seven rows, the tiled up-mix pipelined from eight) against the two-grid + * form, pinned through r4d_hc_read_pin_decode(1). E4M3 or int8 codes, on a real stream (the * one-grid form keys its counters on it). The two forms must dispatch different kernels, so a pin * that is ignored cannot pass by comparing a form with itself. */ static void hc_decode_forms(const Plugin& pl, int64_t M, bool i8) { const std::string nm = fmt("hc_read_e4m3 decode kernels at M=%lld, %s codes: the rule " - "byte-identical to the previous kernels", (long long)M, + "byte-identical to the two-grid form", (long long)M, i8 ? "int8" : "E4M3"); const RadKernelInfo* r = find(pl, "hc_read_e4m3"); if (!r) { skip(nm.c_str(), "row absent"); return; } @@ -18232,7 +18313,7 @@ static void hc_decode_forms(const Plugin& pl, int64_t M, bool i8) { const int rc = r->launch(&a, (RadStream)hs); const int nd = pl.record(nullptr, 0); if (rc != RAD_OK || st_stream_sync(hs) != hipSuccess) { - ok(nm.c_str(), false, fmt("%s rc=%d", form ? "the previous kernels" : "the rule", rc)); + ok(nm.c_str(), false, fmt("%s rc=%d", form ? "the two-grid form" : "the rule", rc)); pl.pin_hc_dec(0); (void)hipStreamDestroy(hs); return; @@ -18446,12 +18527,12 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool if (pl.pin_hc) pl.pin_hc(form); time_now(kForm[form]); } - /* The decode kernels against the ones they replaced (r4d_hc_read_pin_decode), under the + /* The two-grid decode form (r4d_hc_read_pin_decode(1)) against the served one, under the * launcher's prefill rule. */ if (pl.pin_hc_dec && f8) { if (pl.pin_hc) pl.pin_hc(0); pl.pin_hc_dec(1); - time_now("the previous decode kernels"); + time_now("the two-grid decode form"); pl.pin_hc_dec(0); time_now("the launcher's rule"); } @@ -25538,7 +25619,8 @@ struct ArThread { * The engine carries this fact (device.p2p, RAD_FACT_P2P) and selects around its absence; a card * count is not enough. hipDeviceCanAccessPeer answers it without a kernel: on a box with the IOMMU * off the peer path is absent, the enable call throws `enable_peer: invalid device ordinal`, and - * init returns RAD_E_DEVICE — a skip line, like the card-count gates, not a failure. */ + * init returns RAD_E_DEVICE. A missing path is a skip line, like the card-count gates, not a + * failure. */ static bool ar_peer_path_ok(const std::vector& devs, int world) { if (world < 2 || (int)devs.size() < world) return false; for (int a = 0; a < world; ++a) @@ -28822,6 +28904,7 @@ static void device_phase(const Plugin& pl) { std::make_pair(8, 53), std::make_pair(1, 300), std::make_pair(15, 640) }) attn_mixed_step_case(pl, *mr.g, mr.dec, mr.pre, mr.kv, c.first, c.second, 2048); + attn_decode_scratch_band_case(pl); /* Flash-Next's QSA layers: twelve queries per KV head over 4-token pages, and six at * four ranks, each layout's prefill (a long history and a ragged last tile), decode, and the * widest verify (q_len 5 at gqa 12, 10 at gqa 6). */ @@ -31144,8 +31227,8 @@ static void device_phase(const Plugin& pl) { for (int form : { 1, 2 }) hc_read_i8(pl, m, true, form); for (int64_t m : { 700, 2048 }) hc_read_i8(pl, m, true, 3); } - /* The decode kernels against the ones they replaced: each one-grid instantiation (1 to 7 - * rows) and the tiled up-mix at both of its row tiles. */ + /* The served decode kernels against the two-grid form: each one-grid instantiation (1 to + * 7 rows) and the tiled up-mix at both of its row tiles. */ for (int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 33, 64 }) for (bool i8 : { false, true }) hc_decode_forms(pl, m, i8); } @@ -31613,7 +31696,7 @@ static void usage(void) { " --perfhc M [iters]: hc_read_e4m3 at Qwen3.8-Flash-Next's shape and M rows, every\n" " prefill-tile form that serves M (the wide kernels at the wide tile,\n" " PF2 from M=512) compared byte for byte and timed as one op each,\n" - " then the previous decode kernels against the launcher's rule;\n" + " then the two-grid decode form against the launcher's rule;\n" " run it under libr4d/isa/trace.sh for its launches.\n" " --cold MIB: with a --perf mode, time cold: read MIB through the caches before\n" " every timed launch (256 empties this card's L2 and last level) and\n" diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index ea20cbd0..ae0e7e74 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -75,12 +75,19 @@ struct KvDyn { } /* namespace */ /* ------------------------------------------------------------------ attn_paged */ +/* attn_paged_tree's ninth operand, `spec_parent` (RadBatch::spec_parent, rad_drafter_tree), is + * read here too: a row whose entry is -2 is an ordinary causal row; any other row is a node of its + * sequence's verify block, whose entry is its parent's row within the sequence's rows (-1 for the + * root, the block's first row). 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 -- the position its + * token has if its path is committed -- rather than from its row. */ int ref_attn_paged(const RadArgs* a, RadStream) { 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 = t_in(a, 4); const RadTensor* vdes = t_in(a, 5); const RadTensor* cus = t_in(a, 6); + const RadTensor* tpar = a->n_t > 8 ? t_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); @@ -162,6 +169,27 @@ int ref_attn_paged(const RadArgs* a, RadStream) { const int64_t qb = tok * q_rs + h * q_hs; const int64_t ob = tok * o_rs + h * o_hs; + /* 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) { + const int64_t first = tok - i; + int64_t pj = ld_int(tpar->dtype, tpar->data, 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 = ld_int(tpar->dtype, tpar->data, offlin(tpar, first + 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; @@ -171,8 +199,9 @@ int ref_attn_paged(const RadArgs* a, RadStream) { * unmapped. */ auto key_at = [&](int64_t j) -> int64_t { if (causal && j > pos) return -1; + if (tree && j >= base && !((tmask >> (j - base)) & 1)) return -1; if (window > 0) { - const int64_t d = pos - j; + const int64_t d = wpos - j; if (causal ? (d >= window) : (d >= window || d <= -window)) return -1; } const int64_t blk = @@ -247,6 +276,14 @@ int ref_attn_paged(const RadArgs* a, RadStream) { return RAD_OK; } +/* attn_paged with its tree operand present: ref_attn_paged reads it (see there). Refused without + * one, and for a non-causal layer, whose two-sided window has no tree reading here. */ +int ref_attn_paged_tree(const RadArgs* a, RadStream s) { + if (a->n_t < 9 || !t_in(a, 8)) return RAD_E_INVAL; + if (p_int(a, "causal", 1) != 1) return RAD_E_UNSUPPORTED; + return ref_attn_paged(a, s); +} + /* ------------------------------------------------------------------ attn_dense */ /* For the vision tower: unpaged, unquantised, `cu_seqlens` bounding one image (or attention window) * per entry so a whole batch is one launch. Causal is a parameter so a dense decoder-only prefill diff --git a/libref/ref_gemm.cpp b/libref/ref_gemm.cpp index d3b74e6f..32536b97 100644 --- a/libref/ref_gemm.cpp +++ b/libref/ref_gemm.cpp @@ -286,7 +286,7 @@ static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, c * acc += (sub * a_scale[m]) * scale * ZP_I8_GROUP sub = sum(a * (code - zero)) exact * acc += (sub * a_scale[m][g]) * scale - * ZP_F16 BF16 inputs are first narrowed to F16 (as by the graph's former cast); sub is + * ZP_F16 BF16 inputs are first narrowed to F16 (the cast kernel's rounding); sub is * the sum over ascending k of a * (code - zero), then acc += sub * scale * * `a` is already in column order (the caller undoes the step order). `a_sum` is quant_act_i8's, @@ -321,8 +321,8 @@ static int gemm_zp(const ZpGrid& zg, const RadTensor* A, const RadTensor* as_, 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. Preserve the former - * explicit BF16->F16 cast semantics on host backends before evaluating 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 narrowed; RadTensor a_f16{}; if (zg.act == ZP_F16 && A->dtype == RAD_BF16) { diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 4facdc4f..e85d36cf 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -126,6 +126,7 @@ int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream); int ref_gated_quant_fp8 (const RadArgs*, RadStream); int ref_gemm_nt_q_gated (const RadArgs*, RadStream); int ref_dflash_select (const RadArgs*, RadStream); +int ref_dflash_tree (const RadArgs*, RadStream); int ref_gram_accum (const RadArgs*, RadStream); int ref_rmsnorm_had_quant_i8(const RadArgs*, RadStream); int ref_gated_had_quant_i8 (const RadArgs*, RadStream); @@ -146,6 +147,7 @@ int ref_logits_gemm (const RadArgs*, RadStream); /* ---- attention */ int ref_attn_paged (const RadArgs*, RadStream); +int ref_attn_paged_tree (const RadArgs*, RadStream); int ref_attn_dense (const RadArgs*, RadStream); int ref_attn_cross (const RadArgs*, RadStream); int ref_table_add (const RadArgs*, RadStream); @@ -393,6 +395,7 @@ REF_SHAPE_FN(ref_rmsnorm_quant_fp8); REF_SHAPE_FN(ref_gated_quant_fp8); REF_SHAPE_FN(ref_gemm_nt_q_gated); REF_SHAPE_FN(ref_dflash_select); +REF_SHAPE_FN(ref_dflash_tree); REF_SHAPE_FN(ref_gram_accum); REF_SHAPE_FN(ref_rmsnorm_had_quant_i8); REF_SHAPE_FN(ref_gated_had_quant_i8); @@ -410,6 +413,7 @@ REF_SHAPE_FN(ref_embed_lookup_q); REF_SHAPE_FN(ref_logits_gemm); REF_SHAPE_FN(ref_attn_paged); +REF_SHAPE_FN(ref_attn_paged_tree); REF_SHAPE_FN(ref_attn_dense); REF_SHAPE_FN(ref_attn_cross); REF_SHAPE_FN(ref_table_add); diff --git a/libref/ref_quant.cpp b/libref/ref_quant.cpp index 85160e77..1088e7f1 100644 --- a/libref/ref_quant.cpp +++ b/libref/ref_quant.cpp @@ -820,3 +820,117 @@ int ref_dflash_select(const RadArgs* a, RadStream) { } return RAD_OK; } + +/* ------------------------------------------------------------- dflash_tree */ +/* `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w -> `tokens`, `parents` + * + * dflash_select's lattice and edge scores, grown into a tree of `nodes` nodes instead of walked + * into 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 valid candidate c at + * position l + 1, scored as dflash_select scores it after t, with log probability its parent's + * plus log_softmax(score / temp)[c] over the valid candidates there. Best-first: each round + * selects the not-yet-selected child of any selected node with the largest log probability (ties + * to the one pushed first: lower parent, then lower c), until `nodes` are selected. Selected node + * j (1-based, in selection order, so a parent always precedes its child) is written as + * tokens[j-1] and parents[j-1], the parent's node index (0 the anchor). A frontier that runs dry + * (every candidate invalid) pads with token 0 under the last node, which the verify rejects. + * + * In f32: score as dflash_select; x = score / temp; m = max x; lse = m + log(sum exp(x - m)) over + * the valid candidates, summed in c order; child = parent + (x - lse). */ +int ref_dflash_tree(const RadArgs* a, RadStream) { + 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 = t_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); + const int64_t ps = laststride(pred), sxs = laststride(succ); + const int64_t hs = hp ? laststride(hp) : 1; + + REF_PAR_FOR(M * N * K * R) + 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 sel; /* selected, node 0 the anchor */ + std::vector front; /* every child pushed so far, in push order */ + std::vector ax((size_t)R), x((size_t)K); + sel.push_back({ -1, ld_int(anc->dtype, anc->data, 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 int64_t hb = hp ? rowoff(hp, r, R) : 0; + const bool ok = nd.tok >= 0 && nd.tok < nv; + for (int64_t i = 0; i < R; ++i) + ax[(size_t)i] = (ok ? ldt(pred, rowoff(pred, nd.tok, R) + i * ps) : 0.0f) * + (hp ? ldt(hp, hb + i * hs) : 1.0f); + float mx = -INFINITY; + for (int64_t c = 0; c < K; ++c) { + const int64_t tok = ld_int(cand->dtype, cand->data, cb + c * cs); + float sc = ldt(un, ub + c * us); + const bool valid = tok >= 0 && tok < nv; + if (valid) { + const int64_t sb = rowoff(succ, tok, R); + for (int64_t i = 0; i < R; ++i) sc += ax[(size_t)i] * ldt(succ, sb + i * sxs); + } + 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(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 }); + expand((int64_t)sel.size() - 1); + } + const Node& nd = sel.back(); + st_int(out->dtype, out->data, rowoff(out, m, N) + (j - 1) * os, nd.tok); + st_int(par->dtype, par->data, rowoff(par, m, N) + (j - 1) * pps, nd.parent); + } + } + return RAD_OK; +} diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 819428dc..cdd2f8e9 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -287,6 +287,13 @@ static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_INT( 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") }; static const RadParamSpec pRmsHadQuant[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), P_STR("dtype"), P_F64O("wadd") }; @@ -366,6 +373,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 the verify block's tree (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") +}; /* Effective on kv_store, where `block_size` is RAD_REQUIRED: admits every value and refuses only a * query that omits it. On attn_paged the key is RAD_DERIVED and the constraint is skipped * (core/plugin/select.cpp). See the file header for the spec §7.2 consequence. */ @@ -1316,6 +1328,12 @@ static const RadOpSchema kSchemas[] = { "previous pick. `hp` absent is a plane of ones, which drops the form to a plain low-rank " "bigram. Serial in l by construction -- the predecessor is not known until the previous step " "has been decided." }, +{ "dflash_tree", ARR(pDflashTree), ARR(oDflashTree), + "dflash_select's lattice and edge scores grown best-first into a tree of `nodes` nodes: node 0 " + "is the anchor, each selected node's children are the valid candidates at the next position " + "with log probability parent + log_softmax(score / temp) over them, and each round selects the " + "unselected child with the largest (ties to the first pushed). tokens[j-1] and parents[j-1] are " + "the j-th selected node and its parent's index (0 the anchor)." }, { "givens_dense_quant", ARR(pGivensDense), ARR(oGivensDense), "ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / " "rscale) for each of `parts` rotated copies, T the [128, 128] f16 matrix a (part, 128-column " @@ -1401,6 +1419,11 @@ static const RadOpSchema kSchemas[] = { "one kernel serves decode, speculative verify and prefill. seqused is the TOTAL key count " "including this step's query rows. k_descale / v_descale are optional and apply to an fp8 " "cache. `scale` is not in docs/OPS.md and defaults to 1/sqrt(head_dim)." }, +{ "attn_paged_tree", ARR(pAttnPaged), ARR(oAttnPagedTree), + "attn_paged over a tree verify (rad_drafter_tree): spec_parent[row] 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 row). 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." }, { "attn_dense", ARR(pAttnDense), ARR(oAttnDense), "Dense varlen attention over cu_seqlens segments (rows cu/cu_div). Nothing paged. `window` is " "attn_paged's rule over a segment's positions: causal, i - j < window; non-causal, |i - j| < " @@ -2275,6 +2298,9 @@ SIMPLE("ref_gemm_nt_q_gated", "gemm_nt_q_gated", "gemm", SIMPLE("ref_dflash_select", "dflash_select", "draft", "DFlash2's greedy walk over the candidate lattice", "i32 candidates, bf16 codebooks, i32 tokens out", ref_dflash_select), +SIMPLE("ref_dflash_tree", "dflash_tree", "draft", + "DFlash2's candidate lattice grown best-first into a tree", + "i32 candidates, bf16 codebooks, i32 tokens and parents out", ref_dflash_tree), SIMPLE("ref_givens_rotate", "givens_rotate", "quant", "channel scale and Givens rotations per part, in the output's dtype", "float in, float out; int32 pairs, f32 angles and channel scales", ref_givens_rotate), @@ -2332,6 +2358,11 @@ ROW("ref_attn_paged", "attn_paged", "attn", "any q and out dtype; bf16 or fp8 kv cache with optional per-(seq,head) descales", cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), nullptr, nullptr, ref_attn_paged, nullptr), +ROW("ref_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])), + nullptr, nullptr, ref_attn_paged_tree, nullptr), SIMPLE("ref_attn_dense", "attn_dense", "attn", "dense varlen attention over cu_seqlens", DT_FLOAT, ref_attn_dense), SIMPLE("ref_attn_cross", "attn_cross", "attn", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 12259e2d..9559db14 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1331,6 +1331,18 @@ int ref_attn_paged_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("attn_paged", operand, out); } +/* attn_paged's operands and its tree's parents, each row an ordinary causal one (-2): a drawn + * plane would name parents that are not a tree. */ +int ref_attn_paged_tree_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + if (operand < 8) return ref_attn_paged_shape(p, n_p, operand, out); + const int64_t M = gi(p, n_p, "q_len", 0); + if (M <= 0) return RAD_E_UNSUPPORTED; + Opd o; + for (int i = 0; i < 8; ++i) o.skip(); + o.t_idx({ M }, 0, -2, 0); /* spec_parent */ + return o.finish("attn_paged_tree", operand, out); +} + int ref_attn_dense_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); @@ -2103,6 +2115,30 @@ int ref_dflash_select_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* return o.finish("dflash_select", operand, out); } +/* dflash_select's operands, then `nodes` tokens and parents a sequence. */ +int ref_dflash_tree_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t steps = gi(p, n_p, "steps", 0); + const int64_t K = gi(p, n_p, "top_k", 0); + const int64_t R = gi(p, n_p, "rank", 0); + const int64_t nv = gi(p, n_p, "n_vocab", 0); + const int64_t astr = gi(p, n_p, "anchor_stride", 1); + const int64_t N = gi(p, n_p, "nodes", steps); + if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0 || N <= 0) + return RAD_E_UNSUPPORTED; + const int64_t rows = M * steps; + Opd o; + o.t_idx_dt((uint32_t)RAD_I32, { rows, K }, nv, -1, 0); /* cand */ + o.t((uint32_t)RAD_F32, { rows, K }); /* unary */ + o.t((uint32_t)RAD_BF16, { rows, R }); /* hp */ + o.t_idx_dt((uint32_t)RAD_I32, { M * astr }, nv, -1, 0); /* anchor */ + o.t((uint32_t)RAD_BF16, { nv, R }); /* pred */ + o.t((uint32_t)RAD_BF16, { nv, R }); /* succ */ + o.t_idx_dt((uint32_t)RAD_I32, { M, N }, nv, -1, 0); /* tokens */ + o.t_idx_dt((uint32_t)RAD_I32, { M, N }, N + 1, -1, 0); /* parents */ + return o.finish("dflash_tree", operand, out); +} + /* ================================================================== gated delta net * * The layouts are libref/ref_gdn.cpp's: diff --git a/spec.md b/spec.md index 9ff1e7e2..bf6cddaf 100644 --- a/spec.md +++ b/spec.md @@ -1057,23 +1057,27 @@ token when it sits at `i * block_size`. This engine changes two things: The scheduler here splits a chunk at the interval (§7.1) and always writes one, at the cost of an occasional short chunk. -On a model with sliding-window attention and no linear state, a checkpoint snapshots the window -behind a prompt's tail instead, and chunks are not split at the interval. +On a model with sliding-window attention a checkpoint slot also carries the trunk's window, after +any linear state. Without linear state the window is snapshotted behind a prompt's tail and, +unless `--checkpoint-policy tip-only`, at the interval, where chunks then split. -**Exact resume.** A hit recomputes the tokens past where it resumes, and a kernel can round a row +**Resume modes.** A hit recomputes the tokens past where it resumes, and a kernel can round a row differently at another chunk length (§17), so a hit is bit-identical to a cold run of the same -prompt only if it recomputes the cold run's own chunks. With `--prefix-resume exact` (the default) -a hit resumes only on the grid an idle server's cold prefill chunks on: the budget's chunk -(`--max-num-batched-tokens` rounded down to the quantum), or the interval where chunks split at it -and it is the smaller, times the span from the second interval on. Every snapshot the scheduler -writes is on that grid: interval checkpoints (the interval, when past the chunk, is rounded up to a -multiple of it), and the prompt's tail snapshot, which is taken where its last chunk starts rather -than at its last quantum boundary. That boundary is one the cold chunk already ends on, so the tail -snapshot costs no extra step; an exact repeat re-prefills the last chunk, an appended turn that -chunk and its own tokens, up to one chunk more than `--prefix-resume nearest` (the deepest snapshot -or block). A hit with no snapshot to resume from (full attention) steps back to the grid. The -property holds for a prefill alone in its steps; one sharing its steps with other work is cut -differently, as greedy text under batching already differs (§17). +prompt only if it recomputes the cold run's own chunks. `--prefix-resume` selects the mode: + +- `exact` (the default): a hit resumes only on the grid an idle server's cold prefill chunks on: + the budget's chunk (`--max-num-batched-tokens` rounded down to the quantum), or, where chunks + split at the interval and it is the smaller, the interval times the span from the second + interval on. Every snapshot the scheduler writes is on that grid: interval checkpoints (an + interval past the chunk is rounded up to a multiple of it), and the prompt's tail snapshot, + taken where its last chunk starts. The cold chunk already ends there, so the tail snapshot costs + no extra step. An exact repeat re-prefills the last chunk, an appended turn that chunk and its + own tokens. A hit with no snapshot to resume from (full attention) steps back to the grid. +- `nearest`: a hit resumes at the deepest snapshot or block, and the tail snapshot is at the + prompt's last quantum boundary, up to one chunk less re-prefilled a turn. + +Exactness holds for a prefill alone in its steps; one sharing its steps with other work is cut +differently, as greedy text under batching differs (§17). Snapshots are large (at a 2048-token interval a 128K session on Qwen3.5-27B is 64 checkpoints, about 9 GiB), so retention is budgeted. Retention keeps the session tip, which an appending agent @@ -1663,8 +1667,8 @@ It does not give bit-exactness. The fp8 GEMM's split-K finisher sums in index or repeats, but the split count is chosen from `M`, so a row computed at `M = 1` and at `M = 8` can differ in the last bits. A speculative decode can therefore diverge from a non-speculative one on a near-tie, and a request at a different batch position can take a different reduction order. Nothing -pins it (§19.7). A prefix hit is held to the cold run's chunks (§7.3, exact resume), so on an idle -server it repeats the cold run's output. +pins it (§19.7). Under `--prefix-resume exact` a prefix hit is held to the cold run's chunks +(§7.3), so on an idle server it repeats the cold run's output. --- diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 4316c2d9..95314054 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -594,9 +594,9 @@ set_tests_properties(ops_doc PROPERTIES TIMEOUT ${RAD_TEST_TIMEOUT} ENVIRONMENT "ROCR_VISIBLE_DEVICES=99") -# docs/KERNELS.md is generated by rad-kbench and merged by hand; a partial merge leaves a -# library's "rows not reached" header from one run above a table from another (v1.13.0: 239 -# against 243 rows). The counts must agree with each other and with the headline; cheap. +# docs/KERNELS.md is generated by rad-kbench and merged by hand; a partial merge can leave a +# library's "rows not reached" header from one run above a table from another. The counts must +# agree with each other and with the headline; cheap. if(EXISTS ${CMAKE_SOURCE_DIR}/docs/KERNELS.md) add_test(NAME kernel_report_check COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/kernel_report_check.sh diff --git a/tests/abi_layout_rows.h b/tests/abi_layout_rows.h index 3d03886d..e862eece 100644 --- a/tests/abi_layout_rows.h +++ b/tests/abi_layout_rows.h @@ -22,6 +22,7 @@ ABI_FIELD(RadArchProbe, kv_stream_ok) ABI_FIELD(RadArchProbe, control_vector_ok) ABI_FIELD(RadArchProbe, tp_attn_rows_ok) ABI_FIELD(RadArchProbe, state_f16_ok) +ABI_FIELD(RadArchProbe, tree_pays) ABI_STRUCT(RadArgs) ABI_FIELD(RadArgs, t) ABI_FIELD(RadArgs, n_t) @@ -117,6 +118,7 @@ ABI_FIELD(RadBuildCtx, tp_attn_rows) ABI_FIELD(RadBuildCtx, state_dtype) ABI_FIELD(RadBuildCtx, draft_coupling) ABI_FIELD(RadBuildCtx, weight_prefetch_off) +ABI_FIELD(RadBuildCtx, draft_tree) ABI_STRUCT(RadAudioGenBatch) ABI_FIELD(RadAudioGenBatch, n_lane) ABI_FIELD(RadAudioGenBatch, lane) diff --git a/tests/advance_test.cpp b/tests/advance_test.cpp index 92bf0d8b..1093e947 100644 --- a/tests/advance_test.cpp +++ b/tests/advance_test.cpp @@ -40,7 +40,8 @@ struct Slab { USED = SLOT + kGroups * kTok, /* [kGroups][kSeq] */ BT = USED + kGroups * kSeq, /* [kGroups][kSeq][kPitch] */ FIRST = BT + kGroups * kSeq * kPitch, /* [kGroups][kSeq] */ - END = FIRST + kGroups * kSeq + PAR = FIRST + kGroups * kSeq, /* [kTok] spec_parent, when a test stages trees */ + END = PAR + kTok }; alignas(16) int32_t w[END] = {}; StepSlot st[kSeq]; @@ -219,6 +220,83 @@ TEST(the_cards_acceptance_is_accept_greedy_and_the_end_of_generation_cut) { CHECK(partial > 100); } +/* The same over trees (rad_drafter_tree): a row whose spec_parent marks a tree verify is accepted + * by accept_tree's walk (the lowest-numbered child that is the target's pick at its parent, from + * the bonus token down), cut at the first end-of-generation token, and the StepSlot carries the + * accepted nodes for ADV_COMPACT. Random trees of 0-8 nodes over {1, 2, 3}, so siblings often + * share a token and the lowest-numbered one must win. Seeded; a failure prints the case. */ +TEST(the_cards_tree_acceptance_is_accept_tree_and_the_end_of_generation_cut) { + const uint32_t seed = 0x7ee5eedu; + uint32_t rng = seed; + int bad = 0, deep = 0, branched = 0, cut_cases = 0; + for (int c = 0; c < 10000 && !bad; ++c) { + Slab s(ADV_ACCEPT); + s.a.parent_off = Slab::PAR * 4; + for (int t = 0; t < Slab::kTok; ++t) s.w[Slab::PAR + t] = -2; + int n_eog = 0; + int32_t eog_ids[3]; + for (int32_t t : { 2, 3, 8 }) if (lcg(rng) % 4 == 0) eog_ids[n_eog++] = t; + for (int j = 0; j < n_eog; ++j) s.eog[j] = eog_ids[j]; + s.a.n_eog = n_eog; + auto is_eog = [&](int32_t t) { + return std::find(eog_ids, eog_ids + n_eog, t) != eog_ids + n_eog; + }; + + const int n_rows = 1 + (int)(lcg(rng) % 4); + int k = 0, out_row = 0; + struct Want { int card, acc, tok, head; int32_t path[8]; } want[4]; + for (int i = 0; i < n_rows; ++i) { + const int n_spec = (int)(lcg(rng) % 9); + const int n_tok = 1 + n_spec; + const int ctx = (int)(lcg(rng) % 1000); + const int rtok = k; /* a decode row: its first token is the bonus */ + s.row(i, true, k, n_tok, ctx, i, rtok, out_row, n_spec); + int32_t draft[8] = {}, parent[8] = {}, target[9] = {}; + s.w[Slab::TOK + rtok] = 50; + s.w[Slab::PAR + rtok] = -1; /* the root: this row is a tree verify */ + for (int j = 1; j <= n_spec; ++j) { + parent[j - 1] = (int32_t)(lcg(rng) % (uint32_t)j); + draft[j - 1] = 1 + (int32_t)(lcg(rng) % 3); + s.w[Slab::TOK + rtok + j] = draft[j - 1]; + s.w[Slab::PAR + rtok + j] = (rtok - k) + parent[j - 1]; + branched += parent[j - 1] != j - 1; + } + for (int r = 0; r <= n_spec; ++r) { + target[r] = 1 + (int32_t)(lcg(rng) % 3); + s.src[out_row + r] = target[r]; + } + int32_t out[9] = {}, path[8] = {}, acc = -1; + CHECK_OK(accept_tree(draft, parent, n_spec, target, out, path, &acc)); + const int32_t cut = accept_cut_at_eog(out, acc, is_eog); + deep += cut >= 2; + cut_cases += cut < acc; + want[i] = { i, cut, out[cut], ctx + cut, {} }; + std::memcpy(want[i].path, path, sizeof path); + out_row += 1 + n_spec; + k += n_tok; + } + s.run(); + for (int i = 0; i < n_rows && !bad; ++i) { + const StepSlot& S = s.st[want[i].card]; + bool ok = S.acc == want[i].acc && S.tok[0] == want[i].tok && S.n_acc == want[i].acc + 1 && + S.head == want[i].head && S.ctx == want[i].head + 1 && S.npath == want[i].acc; + for (int t = 0; ok && t < want[i].acc; ++t) ok = S.path[t] == want[i].path[t]; + if (!ok) { + bad = 1; + CHECK(ok); + std::fprintf(stderr, " seed 0x%x, case %d, row %d: card acc %d tok %d npath %d; " + "host acc %d tok %d\n", seed, c, i, S.acc, S.tok[0], S.npath, + want[i].acc, want[i].tok); + } + } + } + CHECK_EQ(bad, 0); + /* The draw reaches branching trees, accepted paths of two nodes or more, and the cut. */ + CHECK(branched > 1000); + CHECK(deep > 100); + CHECK(cut_cases > 100); +} + /* ================================================================== ADV_TRUNK */ /* A verify step issued ahead takes its rows from the StepSlots: the bonus token and the head's diff --git a/tests/arch_fakes.h b/tests/arch_fakes.h index d4afb5a5..6a49d182 100644 --- a/tests/arch_fakes.h +++ b/tests/arch_fakes.h @@ -119,6 +119,8 @@ struct RadBuilder { bool drafter_shared = false; int drafter_pos = -1; int64_t drafter_short = 0; /* rad_drafter_short_block */ + /* A tree drafter's parents buffer (rad_drafter_tree), 0 for a chain. */ + rad_buf drafter_parents = 0; /* The buffers named to rad_buf_concurrent: the ones a second lane touches. */ std::vector concurrent; @@ -399,6 +401,11 @@ extern "C" int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) { b->drafter_pos = pos_offset; return RAD_OK; } +extern "C" int rad_drafter_tree(RadBuilder* b, rad_buf parents) { + if (!b || b->drafter.kind != RAD_DRAFT_BLOCK || parents == 0) return RAD_E_STATE; + b->drafter_parents = parents; + return RAD_OK; +} /* The core's chaining decision as the recorder answers it (it has no chaining backend): 0 unless a * test holds a ChainOn, to see where a plugin places work when launches chain. */ static int g_chain_on = 0; @@ -411,7 +418,9 @@ struct ChainOn { extern "C" int rad_drafter_short_block(RadBuilder* b, int64_t block) { const int64_t full = b ? (b->drafter.block > 0 ? b->drafter.block : b->drafter.depth + 1) : 0; if (!b || b->drafter.kind != RAD_DRAFT_BLOCK) return RAD_E_STATE; - if (block >= full || block - (full - b->drafter.depth) < 1) return RAD_E_INVAL; + if (b->drafter_parents ? (block < 2 || block >= full) + : (block >= full || block - (full - b->drafter.depth) < 1)) + return RAD_E_INVAL; b->drafter_short = block; return RAD_OK; } diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index da8ea881..2b643268 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -4705,8 +4705,8 @@ TEST(the_gemma4_e4b_form_replicates_kv_heads_at_four_ranks) { /* A double-wide MLP is per layer: layers 0..7 declare gate_up [2F, E] and down [E, F] with F = * intermediate_size, layers 8..11 [4F, E] and [E, 2F], and every activation op carries its layer's - * width. The shared `gate_up` and `ffn` buffers hold the widest layer, so a narrow layer's slice - * keeps the wide row pitch. */ + * width. The narrow layers use the `gate_up` and `ffn` buffers and the wide ones `gate_up_wide` + * and `ffn_wide`, each at its own row width. */ TEST(a_gemma4_e2b_form_declares_the_double_wide_layers) { RadBuilder b; RadModelMeta meta = gemma4_e2b_meta(); @@ -7120,6 +7120,52 @@ TEST(gemma4_31b_dflash2_folds_both_passes_prologues) { } } +/* The block-16 DFlash2 drafter (the DBloom fine-tune) as a tree: its query pass also runs at its + * short block of 8 rows (rad_drafter_short_block), whose selector grows a 7-node tree at an anchor + * stride of 8, beside its own block's 15 at 16; a block it has no ops for fails the step. A + * 7-node tree over the block-16 drafter (--num-speculative-tokens 7) declares the same short + * block. At block 8 the drafter declares none. */ +TEST(gemma4_31b_dflash2_block16_tree_runs_its_short_block) { + for (int b16 = 0; b16 < 3; ++b16) + for (int world : { 1, 4 }) { + G431Df2 f; + for (size_t i = 0; i < f.keys.size(); ++i) + if (!std::strcmp(f.keys[i], "draft.block_size")) f.vals[i] = b16 ? "16" : "8"; + const int64_t own = b16 == 2 ? 7 : b16 ? 15 : 7; /* the tree's nodes */ + const RadModelMeta meta = f.meta(); + RadBuilder b; + g431df2_encs(b, true); + RadBuildCtx ctx = build_ctx(0, world); + ctx.max_tok = 2048; + ctx.max_spec = (int)own; + ctx.draft_tree = 1; + REQUIRE_EQ(gemma4_bf16::declare(&b, &meta, &ctx), RAD_OK); + REQUIRE(b.drafter_parents != 0); + CHECK_EQ(b.drafter_short, b16 ? 8 : 0); + const int64_t full = b16 ? 16 : 8; + std::vector blocks = { full }; + if (b16) blocks.push_back(8); + for (int64_t rows : blocks) { + const auto qry = query_pass(b, 2, rows, rows - 1); + const auto v = run_passes(b, gemma4_bf16::step, { qry.get() }, 0, world); + REQUIRE(steps_ok(v)); + int64_t nodes = -1, stride = -1, n_tree = 0; + for (const RecIssue& is : v[0]->issues) + if (const RecOp* o = b.op_of(is.op); o && o->op == "dflash_tree") { + nodes = pint(o, "nodes"); + stride = pint(o, "anchor_stride"); + ++n_tree; + } + CHECK_EQ(n_tree, 1); + CHECK_EQ(nodes, std::min(own, rows - 1)); + CHECK_EQ(stride, rows); + } + const auto qbad = query_pass(b, 2, 4, 3); + const auto vb = run_passes(b, gemma4_bf16::step, { qbad.get() }, 0, world); + CHECK(!vb[0]->step_fail.empty()); + } +} + /* DFlash2's query pass issues each residual add with the norm after it, as one add_rmsnorm where it * resolves: after every attention (the feed-forward norm) and every feed-forward (the next layer's * attention norm, after the last the final norm), ten on the 31B's five layers, no add left and diff --git a/tests/build_test.cpp b/tests/build_test.cpp index 1aa3a6f8..cd9a34b1 100644 --- a/tests/build_test.cpp +++ b/tests/build_test.cpp @@ -1105,6 +1105,37 @@ TEST(a_block_drafters_short_block_is_shorter_and_still_proposes) { } } +/* A tree drafter (rad_drafter_tree) takes a short block too: a block-16 tree of 15 nodes declares + * one of 8 rows, over which the drafter grows a tree of its own of up to 7 nodes; and a tree of 7 + * nodes over the same block, where a chain's rule (rows past the 9 that propose nothing) would refuse + * it. */ +TEST(a_tree_drafter_takes_a_short_block) { + Registry reg; + Builder b(reg, make_meta(), make_ctx()); + RadBufDecl bd{}; + bd.dtype = RAD_I32; bd.rank = 2; bd.shape[0] = 256; bd.shape[1] = 15; + const rad_buf prop = rad_decl_buffer(&b, "prop", &bd); + const rad_buf par = rad_decl_buffer(&b, "par", &bd); + RadDrafterDecl d{}; + d.kind = RAD_DRAFT_BLOCK; d.name = "df"; d.depth = 15; d.block = 16; d.mask_token = 5; + d.proposal = prop; d.proposal_pitch = 15; + CHECK_OK(rad_declare_drafter(&b, &d)); + CHECK_OK(rad_drafter_tree(&b, par)); + CHECK_EQ(rad_drafter_short_block(&b, 16), RAD_E_INVAL); /* not shorter */ + CHECK_EQ(rad_drafter_short_block(&b, 1), RAD_E_INVAL); /* no row to propose */ + CHECK_OK(rad_drafter_short_block(&b, 8)); + CHECK_EQ(b.program().drafter_short_block, 8); + Builder b7(reg, make_meta(), make_ctx()); + const rad_buf prop7 = rad_decl_buffer(&b7, "prop", &bd); + const rad_buf par7 = rad_decl_buffer(&b7, "par", &bd); + RadDrafterDecl d7 = d; + d7.depth = 7; d7.proposal = prop7; + CHECK_OK(rad_declare_drafter(&b7, &d7)); + CHECK_OK(rad_drafter_tree(&b7, par7)); + CHECK_OK(rad_drafter_short_block(&b7, 8)); + CHECK_EQ(b7.program().drafter_short_block, 8); +} + /* A block drafter's proposal pitch is its row pitch, which the engine reads row s at: left at 0 it * defaults to depth, and under depth it is refused, since a row could not hold the proposals. */ TEST(a_block_drafters_proposal_pitch_holds_its_proposals) { @@ -1826,8 +1857,9 @@ TEST(a_widened_weight_cannot_also_be_relayouted) { CHECK(any_error(b, "a widening and a relayout")); } -/* The other direction, the d3 readout: an f32 checkpoint tensor declared bf16 (what the device - * logits kernel reads) is narrowed by the loader, and the stored form is one plain bf16 plane. */ +/* The other direction: an f32 checkpoint tensor declared bf16 (a readout head, which the device + * logits kernel reads as bf16) is narrowed by the loader, and the stored form is one plain bf16 + * plane. */ TEST(an_f32_source_declared_bf16_is_narrowed_at_load) { NEED_EXTRA(reg) Builder b(reg, make_meta(), make_ctx()); @@ -2208,7 +2240,9 @@ TEST(the_home_search_path_splits_on_colons_and_the_first_home_with_a_file_wins) * weight by weight names its producing tool, which no plugin claims: the family's one quantised * plugin serves it (or its only plugin), and two quantised plugins are refused by name rather than * chosen between. A plugin that declines imports (rad_arch_serves_imports, radtest_archq_w8) is - * still selected by its own descriptor, but is neither counted nor picked for an import. */ + * still selected by its own descriptor, but is neither counted nor picked for an import. Block fp8 + * (`fp8_e4m3`) reads stock, so a family that claims no plugin for it is served the same way + * without the import flag. */ TEST(the_architecture_plugin_is_picked_by_id_and_quantisation) { const std::string archq = home() + "/testarchq"; NEED_ARTIFACT(archq + "/radtest_archq_fp8.so"); @@ -2266,6 +2300,14 @@ TEST(the_architecture_plugin_is_picked_by_id_and_quantisation) { CHECK_OK(pick(bare, "quark-mxfp4", true, &lp, &log)); CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_plain")); CHECK_EQ(pick(all, "fp8", false, &lp, &log), RAD_OK); + CHECK_OK(pick(bare, "fp8_e4m3", false, &lp, &log)); + CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_plain")); + CHECK_EQ(lp.arch_quant, std::string()); + CHECK_OK(pick(one, "fp8_e4m3", false, &lp, &log)); + CHECK_EQ(lp.arch_plugin, std::string("radtest_archq_fp8")); + CHECK_EQ(pick(all, "fp8_e4m3", false, &lp, &log), RAD_E_NOTFOUND); + CHECK_EQ(pick(bare, "w4", false, &lp, &log), RAD_E_NOTFOUND); + CHECK(has(log, "is served at")); /* A second quantised plugin that declines imports leaves them to the first. */ CHECK_OK(pick(w8, "quark-mxfp4", true, &lp, &log)); diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index cb612d21..227d1a40 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -152,7 +152,9 @@ TEST(routed_expert_metadata_accepts_the_deepseek_and_glm_config_spellings) { /* The descriptor derives from quant_method and fmt whoever set them, including rad-convert's * --set: a bf16 checkpoint converted to block fp8 states that format and selects the fp8 plugin, - * so the container never names one format and selects another's plugin. */ + * so the container never names one format and selects another's plugin. transformers' fp8 states + * no fmt and is E4M3 (Qwen3.8-Flash-Next-FP8), so it is the same descriptor; another method + * without a fmt is its name alone. */ TEST(the_descriptor_is_quant_method_and_fmt_whoever_set_them) { const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) }, "{\"model_type\":\"qwen3_5\",\"hidden_size\":256}"); @@ -161,9 +163,12 @@ TEST(the_descriptor_is_quant_method_and_fmt_whoever_set_them) { CHECK_EQ(ck.meta().quant, std::string()); MetaOwn m = ck.meta(); m.set("quantization_config.quant_method", "fp8"); - CHECK_EQ(quant_descriptor(m), std::string("fp8")); + CHECK_EQ(quant_descriptor(m), std::string("fp8_e4m3")); m.set("quantization_config.fmt", "e4m3"); CHECK_EQ(quant_descriptor(m), std::string("fp8_e4m3")); + MetaOwn ct = ck.meta(); + ct.set("quantization_config.quant_method", "compressed-tensors"); + CHECK_EQ(quant_descriptor(ct), std::string("compressed-tensors")); } /* Google's bf16 E2B needs no `--set quantization_config.quant_method`: its per-layer embeddings @@ -3043,6 +3048,45 @@ TEST(a_compressed_tensors_fp8_release_reads_stock_with_no_import_refusal) { CHECK_EQ(f[5], (float)((128 + 5) % 7 - 3) * -2.0f); } +/* Qwen3.8-Flash-Next-FP8 ships its n-gram table as FP8 shards, `X.shard_.weight`, under one + * scale, `X.weight_scale`. Joined along rows they are one table with one scale, byte for byte: + * `fp8_e4m3*bf16[*x*]`, the scale plane its single element, and the rows decode by it. */ +TEST(fp8_shards_under_one_shared_scale_are_one_table_with_one_scale) { + T sc{ "t.weight_scale", "BF16", { 1 }, {} }; + sc.bytes.resize(2); + rad_store_f32(sc.bytes.data(), RAD_BF16, 0, 0.5f); + const std::string dir = write_checkpoint( + { fp8("t.shard_0.weight", { 3, 128 }), fp8("t.shard_1.weight", { 2, 128 }), sc }, kConfig); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + Program prog; + prog.name_map.push_back(map("t", RAD_MAP_CONCAT, { "t.shard_0.weight", "t.shard_1.weight" })); + CkptWeight w; + std::string why; + REQUIRE_EQ(ckpt_resolve(ck, prog, "t", false, &w, &why), RAD_OK); + CHECK(w.trivial && !w.imported); + REQUIRE_EQ(w.enc.n_planes, 2); + CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_F8E4M3); + CHECK_EQ(w.enc.plane[1].dtype, (uint32_t)RAD_BF16); + CHECK_EQ(w.enc.plane[1].block[0], (int64_t)0); + CHECK_EQ(w.enc.plane[1].block[1], (int64_t)0); + CHECK_EQ(w.rows, (int64_t)5); + std::vector f(128); + REQUIRE_EQ(ckpt_rows_f32(w, 3, 1, f.data(), &why), RAD_OK); /* shard 1's row 0 */ + CHECK_EQ(f[5], (float)(5 % 7 - 3) * 0.5f); + std::vector sp(1); + REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 1, sp.data(), &why), RAD_OK); + CHECK_EQ(rad_load_f32(sp.data(), RAD_BF16, 0), 0.5f); + std::vector raw(128); + REQUIRE_EQ(ckpt_plane_rows(w, 0, 3, 1, raw.data(), &why), RAD_OK); + CHECK_EQ(rad_load_f32(raw.data(), RAD_F8E4M3, 5), (float)(5 % 7 - 3)); + + /* One shard alone is the same table, and a scale of another name is not borrowed. */ + prog.name_map.push_back(map("u", RAD_MAP_COPY, { "t.shard_1.weight" })); + REQUIRE_EQ(ckpt_resolve(ck, prog, "u", false, &w, &why), RAD_OK); + CHECK(w.trivial); +} + /* Per-row FP8 is `fp8_e4m3*[1x*]` whether the scale ships as [N, 1] (compressed-tensors' * channel strategy) or [N], and byte for byte: the plane is the shipped scales in row order. */ TEST(a_per_row_fp8_weight_is_one_scale_per_row_in_either_shape) { diff --git a/tests/config_test.cpp b/tests/config_test.cpp index c1f88a8e..579281fd 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -101,6 +101,21 @@ TEST(a_flag_missing_its_argument_is_refused_rather_than_read_past) { CHECK_EQ(config_parse(a.argc(), a.argv.data(), &c), RAD_E_INVAL); } +/* --draft-short-from takes a count, 0 for never, or auto (the default): the engine resolves auto to + * never for a chain and to two decoding sequences for a tree drafter. */ +TEST(draft_short_from_takes_a_count_never_or_auto) { + Config c; + CHECK_EQ(c.draft_short_from, -1ll); + CHECK_OK(parse({ "--draft-short-from", "4" }, &c)); + CHECK_EQ(c.draft_short_from, 4ll); + CHECK_OK(parse({ "--draft-short-from", "0" }, &c)); + CHECK_EQ(c.draft_short_from, 0ll); + CHECK_OK(parse({ "--draft-short-from", "auto" }, &c)); + CHECK_EQ(c.draft_short_from, -1ll); + CHECK_EQ(parse_fresh({ "--draft-short-from", "-2" }), RAD_E_INVAL); + CHECK_EQ(parse_fresh({ "--draft-short-from", "some" }), RAD_E_INVAL); +} + /* KL mode records or scores, never both, and requires that direction's inputs. Guessing between * them could make a quantised model the reference. */ TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) { @@ -792,6 +807,25 @@ TEST(the_embedding_is_ram_or_vram_and_the_ngram_table_takes_four) { CHECK_EQ(parse({ "--ngram-placement" }, &c), RAD_E_INVAL); } +/* ram=DIR is ram whose pinned copy is a shared file in DIR; a later plain placement drops the + * directory, and no other tier takes one. */ +TEST(the_ngram_table_takes_a_directory_for_a_shared_ram_copy) { + Config d; + CHECK_EQ(parse({}, &d), RAD_OK); + CHECK(d.ngram_share_dir.empty()); + Config s; + CHECK_EQ(parse({ "--ngram-placement", "ram=/tmp/x" }, &s), RAD_OK); + CHECK(s.ngram_placement == TablePlacement::Ram); + CHECK_EQ(s.ngram_share_dir, std::string("/tmp/x")); + CHECK_EQ(parse({ "--ngram-placement", "ram=/tmp/x", "--ngram-placement", "ram" }, &s), RAD_OK); + CHECK(s.ngram_placement == TablePlacement::Ram); + CHECK(s.ngram_share_dir.empty()); + Config c; + for (const char* bad : { "ram=", "vram=/tmp/x", "disk=/tmp/x", "auto=/tmp/x" }) + CHECK_EQ(parse({ "--ngram-placement", bad }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--embedding-placement", "ram=/tmp/x" }, &c), RAD_E_INVAL); +} + /* --draft-window takes exactly two names; the default is kDraftWindowDefault, which the help text * also states. Whether the window can adapt (a serial drafter, depth above zero) is decided by the * scheduler with the program in hand, not the parser. */ diff --git a/tests/dashboard_test.cpp b/tests/dashboard_test.cpp index b1f027f9..606a9bf7 100644 --- a/tests/dashboard_test.cpp +++ b/tests/dashboard_test.cpp @@ -113,6 +113,7 @@ void populated(LiveSnapshot& s) { s.link.ar_calls = 50; s.link.ar_bytes = 5000; s.link.h2d_bytes = 900; s.link.d2h_bytes = 800; s.link.ssd_reads = 4; s.link.ssd_bytes = 400; s.link.stream_bytes = 700; s.link.prefetched = 2; s.link.prefetch_bytes = 300; s.link.staged_bytes = 200; + s.link.kv_streaming = true; s.link.kv_stream_active = true; s.link.kv_stream_bytes = 600; s.passes.present = true; s.passes.played = 10; s.passes.recorded = 2; } @@ -228,6 +229,9 @@ TEST(stats_carries_the_engine_the_requests_and_the_snapshot) { CHECK_EQ(s["experts"]["tiers"][t].value("units", (int64_t)0), (int64_t)(t + 1)); } CHECK_EQ(s["link"].value("stream_bytes", (int64_t)0), (int64_t)700); + CHECK_EQ(s["link"].value("kv_stream_bytes", (int64_t)0), (int64_t)600); + CHECK(s["link"].value("kv_streaming", false)); + CHECK(s["link"].value("kv_stream_active", false)); CHECK_EQ(s["passes"].value("played", (int64_t)0), (int64_t)10); CHECK_EQ(s["ckpt_evictions"].value("store_full", (int64_t)0), (int64_t)3); CHECK_EQ(s["hit_cuts"].value("no_snapshot", (int64_t)0), (int64_t)2); diff --git a/tests/engine_e2e_test.cpp b/tests/engine_e2e_test.cpp index 01a82457..f4ff2ace 100644 --- a/tests/engine_e2e_test.cpp +++ b/tests/engine_e2e_test.cpp @@ -205,6 +205,14 @@ struct World { std::string qwen35_spec; /* Qwen3-ASR: an audio tower over a Qwen3 decoder, served from the checkpoint. */ std::string qwen3asr; + /* The 31B's shape at toy sizes (five sliding layers and a global one, a 64-token window) with + * a DFlash2 drafter on a 64-token window (tiny_model.h: DFlash2), converted as + * data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe converts the 31B: served by gemma4_bf16, + * the trunk w4a8 and the drafter block fp8. */ + std::string g31, g31_draft, g31_df2; + /* The same with a 1024-token window, the 31B's own: a snapshot at 512-1023 lies inside it and + * holds every row from position 0. */ + std::string g31w, g31w_df2; std::string corpus; /* six documents, two sharing a 300-token head; 1820 tokens */ std::string corpus_short; /* four documents, 760 tokens */ std::string corpus_tiny; /* two documents, 300 tokens, for libref's slow fp8 GEMMs */ @@ -230,8 +238,13 @@ struct World { gemma4_kv = dir / "gemma4_kv"; qwen35_spec = dir / "qwen35_spec"; qwen3asr = dir / "qwen3asr"; + g31 = dir / "g31"; + g31_draft = dir / "g31_draft"; + g31_df2 = dir / "g31_df2.rad"; + g31w = dir / "g31w"; + g31w_df2 = dir / "g31w_df2.rad"; for (const std::string* d : { &qwen35, &lfm2, &gemma4, &llama, &qwen35_kv, &gemma4_kv, - &qwen35_spec, &qwen3asr, &llama_int4 }) + &qwen35_spec, &qwen3asr, &llama_int4, &g31, &g31_draft, &g31w }) if (mkdir(d->c_str(), 0755) != 0) return; tiny::Qwen35 qkv; qkv.head_dim = 128; @@ -242,6 +255,17 @@ struct World { gkv.head_dim = 64; gkv.global_kv_heads = 2; gkv.global_head_dim = 128; + tiny::Gemma4 g31s; + g31s.layers = 6; + g31s.interval = 6; + g31s.hidden = 256; + g31s.ffn = 512; + g31s.heads = 2; + g31s.head_dim = 128; + g31s.global_head_dim = 256; + g31s.window = 64; + tiny::Gemma4 g31ws = g31s; + g31ws.window = 1024; if (!tiny::write_qwen35(qwen35, {}) || !tiny::write_lfm2(lfm2, {}) || !tiny::write_gemma4(gemma4, {}) || !tiny::write_llama(llama, {}) || !tiny::write_qwen35(qwen35_kv, qkv) || !tiny::write_gemma4(gemma4_kv, gkv) || @@ -253,7 +277,9 @@ struct World { std::string(tiny::kLlamaFp8Recipe) + tiny::kLlamaI8HeadRule) || !tiny::write_llama_ct_int4(llama_int4, {}, true) || !tiny::write_text(dir / "llama_int4.recipe", tiny::kInt4ImportRecipe) || - !tiny::write_text(dir / "llama_mxfp4.recipe", tiny::kLlamaMxfp4Recipe)) + !tiny::write_text(dir / "llama_mxfp4.recipe", tiny::kLlamaMxfp4Recipe) || + !tiny::write_gemma4(g31, g31s) || !tiny::write_gemma4(g31w, g31ws) || + !tiny::write_dflash2(g31_draft, {})) return; tiny::Rng r(11); @@ -286,6 +312,22 @@ struct World { return; } } + std::string recipes = __FILE__; + recipes = recipes.substr(0, recipes.find_last_of('/')) + "/../data/recipes/"; + /* Checked against libref, which serves it here: a card's library serves none of these + * toy shapes. */ + for (const auto& [ckpt, out] : { std::pair{ g31, g31_df2 }, + std::pair{ g31w, g31w_df2 } }) { + const int st = tiny::run({ RAD_E2E_CONVERT, ckpt, "--draft-model", g31_draft, "-o", out, + "--recipe", recipes + "gemma4-31b-dense-bf16-w4a8-df2.recipe", + "--set", "quantization_config.quant_method=compressed-tensors", + "--kernels", "libref" }, + engine_env(), &convert_log); + if (st != 0) { + fprintf(stderr, " rad-convert exited %d:\n%s\n", st, tail(convert_log).c_str()); + return; + } + } ok = true; } @@ -768,13 +810,13 @@ TEST(an_attention_row_split_no_plugin_serves_is_refused_at_startup) { TEST(the_coupling_flag_refuses_what_it_cannot_serve_at_startup) { World& w = world(); REQUIRE(w.ok); - /* qwen35's tiny checkpoint declares no draft head: no serial chain to couple. The spechub + /* qwen35's tiny checkpoint declares no draft head: no chain to couple. The spechub * kernels are loaded beside libref, so the refusal is the drafter's shape and not a missing * coupling kernel. */ const Ran on = radiance(w.qwen35, { "--kernels", "libref,spechub", "--draft-coupling", "on" }, {}, 120); - const std::string want = "--draft-coupling on requires the linear serial draft chain " - "(RAD_DRAFT_SERIAL with depth > 0)"; + const std::string want = "--draft-coupling on requires a linear draft chain (a serial head or " + "a block drafter with a coupled walk, depth > 0)"; if (on.status == 0 || on.status == 124 || !has(on.log, want)) fprintf(stderr, " --draft-coupling on exited %d:\n%s\n", on.status, tail(on.log, 20).c_str()); @@ -1792,6 +1834,144 @@ TEST(a_prompt_resumed_from_the_prefix_cache_returns_what_a_cold_run_does) { CHECK_EQ(s.stop(), 0); } +/* What a -v server's block drafter proposed ("drafter 'dflash2': sequence N proposes t1 .. tk"), + * by request in the order they were sent: the server numbers requests consecutively, and the + * first one proposes in every case below. Read after stop(), so every line is in. */ +std::vector> proposals(const std::string& log, size_t n_req) { + std::map> by_id; + static const std::string kSeq = ": sequence ", kProp = " proposes"; + for (size_t at = log.find(kProp); at != std::string::npos; at = log.find(kProp, at + 1)) { + const size_t sol = log.rfind('\n', at) + 1, eol = log.find('\n', at); + const size_t s = log.find(kSeq, sol); + if (s == std::string::npos || s > at || log.find("drafter '", sol) > s) continue; + const uint64_t id = std::strtoull(log.c_str() + s + kSeq.size(), nullptr, 10); + by_id[id].push_back(log.substr(at, eol == std::string::npos ? std::string::npos : eol - at)); + } + std::vector> out(n_req); + if (by_id.empty()) return out; + const uint64_t first = by_id.begin()->first; + for (size_t i = 0; i < n_req; ++i) { + auto it = by_id.find(first + i); + if (it != by_id.end()) out[i] = it->second; + } + return out; +} + +/* A block drafter after a prefix hit, on the tiny 31B with its DFlash2 drafter: a follow-up turn + * and a repeat of a prompt each resume from the window snapshot taken at the earlier prompt's tail, + * and add fewer tokens than the drafter's 64-token window. The drafter's window rides in that + * snapshot, saved behind the drafter's context pass, so the hit is kept whole, and the drafter + * drafts from the first decode step and proposes, draft by draft, what a cold run's does. Without + * its window in the snapshot the hit leaves a hole in the drafter's own cache, and draft refill + * ends it at an interval snapshot at least that window before the prompt's end, recomputing what + * the hit had cached: the drafts are a cold run's, but the hit is not whole. With the snapshot + * saved before the context pass, it would propose from rows that pass had not yet written; the + * drafts would differ and, rejected, change no token. The warm server runs --prefix-resume + * nearest, which takes the tail snapshot a block short of the prompt's end; exact takes it where + * the prompt's last chunk starts, more than the drafter's window short here. */ +TEST(a_block_drafter_after_a_prefix_hit_proposes_what_a_cold_run_does) { + REQUIRE(world().ok); + const std::vector first = prompt_ids(41, 300), repeat = prompt_ids(43, 200); + std::vector follow = first; + json warm[2], cold[2]; + std::vector> warm_p, cold_p; + { + Server s; + REQUIRE(s.start(world().g31_df2, { "--num-speculative-tokens", "7", + "--checkpoint-interval", "64", "--max-num-seqs", "4", + "--prefix-resume", "nearest", "-v" })); + for (int32_t t : tokens_of(post(s.port, "/completion", completion(first, 16)))) + follow.push_back(t); + for (int32_t t : prompt_ids(42, 8)) follow.push_back(t); + (void)post(s.port, "/completion", completion(repeat, 16)); + warm[0] = post(s.port, "/completion", completion(follow, 24)); + warm[1] = post(s.port, "/completion", completion(repeat, 24)); + CHECK_EQ(s.stop(), 0); + warm_p = proposals(s.output(), 4); + } + { + Server s; + REQUIRE(s.start(world().g31_df2, { "--num-speculative-tokens", "7", "--no-prefix-cache", + "--max-num-seqs", "4", "-v" })); + cold[0] = post(s.port, "/completion", completion(follow, 24)); + cold[1] = post(s.port, "/completion", completion(repeat, 24)); + CHECK_EQ(s.stop(), 0); + cold_p = proposals(s.output(), 2); + } + /* The warm server's third and fourth requests are the cold one's first and second. */ + const char* what[2] = { "follow-up turn", "repeated prompt" }; + const int64_t n_prompt[2] = { (int64_t)follow.size(), (int64_t)repeat.size() }; + for (int i = 0; i < 2; ++i) { + const int64_t cached = timing(warm[i], "cache_n"); + /* Whole: draft refill would end the hit at least the drafter's 64-token window short. */ + const bool whole = cached > n_prompt[i] - 64; + const int64_t d = timing(warm[i], "draft_n"), dc = timing(cold[i], "draft_n"); + const std::vector& wp = warm_p[(size_t)i + 2]; + const std::vector& cp = cold_p[(size_t)i]; + if (!(whole && dc > 0 && d == dc && wp == cp)) + fprintf(stderr, " %s: %lld of %lld tokens cached, %lld drafted (cold %lld), %zu " + "proposals (cold %zu), %s\n", what[i], (long long)cached, + (long long)n_prompt[i], (long long)d, (long long)dc, wp.size(), cp.size(), + wp == cp ? "the same" : "not the same"); + CHECK(whole); + CHECK(dc > 0); + CHECK_EQ(d, dc); + CHECK(wp == cp); + CHECK(tokens_of(warm[i]) == tokens_of(cold[i])); + } +} + +/* A prompt resumed from a window snapshot, on the tiny 31B: gemma4_bf16 declares the sliding layers + * windowed, and the cache does not index them (arch/gemma4's tiny model declares them full and takes + * no snapshot). A 600-token prompt takes a snapshot a block short of its end at the default + * 2048-token interval, and a longer prompt that shares it resumes there: the sliding layers from + * the snapshot, the global ones from the cached blocks, the rest of the prompt as a prefill from the + * snapshot. The reply, and every probability in it, equals a cold run's; so does a repeat of the + * longer prompt, which resumes from its own snapshot. Under a 64-token window the snapshot holds the + * window behind its position, and under a 1024-token one (the 31B's) every row from 0; with the + * drafter off and on. The snapshot floor (Scheduler::kWindowSnapshotMin) is --prefix-resume + * nearest's: under exact, a prompt shorter than one prefill chunk takes no tail snapshot. */ +TEST(a_prompt_resumed_from_a_window_snapshot_returns_what_a_cold_run_does) { + REQUIRE(world().ok); + const std::vector a = prompt_ids(51, 600); + std::vector b = a; + for (int32_t t : prompt_ids(52, 60)) b.push_back(t); + for (const std::string* model : { &world().g31_df2, &world().g31w_df2 }) { + for (const char* spec : { "0", "7" }) { + json cold; + { + Server s; + REQUIRE(s.start(*model, { "--num-speculative-tokens", spec, "--no-prefix-cache" })); + cold = post(s.port, "/completion", completion(b, 24, 0.0, 0, 3)); + CHECK_EQ(s.stop(), 0); + } + Server s; + REQUIRE(s.start(*model, { "--num-speculative-tokens", spec, + "--prefix-resume", "nearest" })); + (void)post(s.port, "/completion", completion(a, 24, 0.0, 0, 3)); + const json shared = post(s.port, "/completion", completion(b, 24, 0.0, 0, 3)); + const json again = post(s.port, "/completion", completion(b, 24, 0.0, 0, 3)); + const int64_t c1 = timing(shared, "cache_n"), c2 = timing(again, "cache_n"); + /* The snapshot sits at Scheduler::kWindowSnapshotMin (512) or above. */ + const bool same = tokens_of(shared) == tokens_of(cold) && + tokens_of(again) == tokens_of(cold) && + shared["completion_probabilities"] == cold["completion_probabilities"] && + again["completion_probabilities"] == cold["completion_probabilities"]; + if (!(c1 >= 512 && c1 < 600 && c2 > c1 && same)) + fprintf(stderr, " %s, %s drafts: cached %lld then %lld, %s a cold run's\n", + model->c_str(), spec, (long long)c1, (long long)c2, + same ? "equal to" : "NOT equal to"); + CHECK(c1 >= 512); + CHECK(c1 < 600); + CHECK(c2 > c1); + REQUIRE(cold.contains("completion_probabilities")); + CHECK_EQ(tokens_of(cold).size(), (size_t)24); + CHECK(same); + CHECK_EQ(s.stop(), 0); + } + } +} + /* The row a running server's /diagnostics reports for `option`, or null. */ json config_row(int port, const std::string& option) { Call c; diff --git a/tests/format_test.cpp b/tests/format_test.cpp index ce62c3bc..962b86b9 100644 --- a/tests/format_test.cpp +++ b/tests/format_test.cpp @@ -8,17 +8,20 @@ #include "rad_test.h" #include "format/radfile.h" #include "format/table_copy.h" +#include "format/table_share.h" #include "format/tunecache.h" #include "format/imatrix.h" #include "format/safetensors.h" #include "format/checkpoint.h" +#include #include #include #include #include #include #include +#include #include #include #include @@ -450,6 +453,160 @@ TEST(a_table_copied_into_locked_memory_is_the_mapping_byte_for_byte) { f.close(); } +/* --ngram-placement ram=DIR: the first holder to open the file fills it, a later one finds it + * ready (a second descriptor in one process is a second holder, since flock locks belong to the + * open file description), and the file goes when the last holder leaves. A file whose header is + * not this table's is never overwritten, since a live engine may have it mapped. */ +TEST(a_shared_table_file_is_filled_once_and_deleted_by_the_last_holder) { + const std::string dir = radtest::tmp_path("share"); + REQUIRE(::mkdir(dir.c_str(), 0777) == 0 || errno == EEXIST); + const std::string container = write_tmp("share-container", ramp(8192, 1)); + REQUIRE(!container.empty()); + const int64_t n = 64 << 10; + const std::string id = table_share_id(container, 4096, n); + CHECK_EQ(id.size(), (size_t)16); + CHECK_EQ(table_share_id(container, 4096, n), id); + CHECK(table_share_id(container, 8192, n) != id); + CHECK(table_share_id(container, 4096, n + 1) != id); + CHECK(table_share_id(radtest::tmp_path("share-absent"), 4096, n).empty()); + + TableShare a, b, bad; + std::string why; + CHECK_OK(table_share_open(dir, id, n, &a, &why)); + CHECK(a.filler && !a.ready); + CHECK(!table_share_is_ready(dir, id, n)); + const std::vector table = ramp(n, 3); + REQUIRE_EQ(::pwrite(a.fd, table.data(), (size_t)n, kTableShareHeader), (ssize_t)n); + CHECK_OK(table_share_mark_ready(&a, n, id, &why)); + CHECK(a.ready); + CHECK(table_share_is_ready(dir, id, n)); + CHECK(!table_share_is_ready(dir, id, n * 2)); + struct stat st{}; + REQUIRE_EQ(::stat(a.path.c_str(), &st), 0); + CHECK_EQ((int64_t)st.st_size, table_share_file_bytes(n)); + CHECK_EQ(table_share_file_bytes(n), kTableShareHeader + ((int64_t)2 << 20)); + + CHECK_OK(table_share_open(dir, id, n, &b, &why)); + CHECK(b.ready && !b.filler); + CHECK_EQ(b.lock_fd, -1); + std::vector back((size_t)n); + REQUIRE_EQ(::pread(b.fd, back.data(), (size_t)n, kTableShareHeader), (ssize_t)n); + CHECK(back == table); + + /* The same name, asked for a table of another length. */ + CHECK_EQ(table_share_open(dir, id, n * 2, &bad, &why), (int)RAD_E_INVAL); + CHECK(bad.fd == -1); + CHECK(why.find("exists") != std::string::npos); + + /* A file at another table's name whose header names this one: the id in the header is checked. */ + const std::string other = table_share_id(container, 0, n); + const std::string other_path = dir + "/ngram-" + other + ".tab"; + std::vector head(4096); + REQUIRE_EQ(::pread(a.fd, head.data(), head.size(), 0), (ssize_t)head.size()); + { + const int fd = ::open(other_path.c_str(), O_RDWR | O_CREAT, 0644); + REQUIRE(fd >= 0); + REQUIRE_EQ(::pwrite(fd, head.data(), head.size(), 0), (ssize_t)head.size()); + REQUIRE_EQ(::ftruncate(fd, table_share_file_bytes(n)), 0); + ::close(fd); + } + CHECK_EQ(table_share_open(dir, other, n, &bad, &why), (int)RAD_E_INVAL); + CHECK_EQ(::access(other_path.c_str(), F_OK), 0); + ::unlink(other_path.c_str()); + + const std::string path = a.path, lock_path = a.lock_path; + table_share_close(&a); + CHECK(a.fd == -1); + CHECK_EQ(::access(path.c_str(), F_OK), 0); /* b still holds it, after a's wait for it */ + table_share_close(&b); + CHECK(::access(path.c_str(), F_OK) != 0); + CHECK(::access(lock_path.c_str(), F_OK) != 0); + + /* A filler that leaves without marking the table ready leaves nothing behind, and the next + * holder fills. */ + TableShare c, d; + CHECK_OK(table_share_open(dir, id, n, &c, &why)); + CHECK(c.filler); + table_share_close(&c); + CHECK(::access(path.c_str(), F_OK) != 0); + CHECK_OK(table_share_open(dir, id, n, &d, &why)); + CHECK(d.filler && !d.ready); + table_share_close(&d); +} + +/* A shared file costs the header and the table's rounding to 2 MiB. From kTableShareMin on that is + * under an eighth of the table, and kTableShareMin is the least such bound for every size above + * it; the n-gram gather's two-byte scale would be a 4 MiB file, so it keeps a private copy. */ +TEST(a_table_is_shared_only_where_the_file_costs_little_beside_it) { + CHECK(2 < kTableShareMin); + CHECK_EQ(table_share_file_bytes(2), (int64_t)4 << 20); + const int64_t huge = (int64_t)2 << 20; + for (int64_t n : { kTableShareMin, kTableShareMin + 1, kTableShareMin + huge - 1, + (int64_t)47 << 30 }) + CHECK((table_share_file_bytes(n) - n) * 8 < n); + const int64_t below = kTableShareMin - huge + 1; + CHECK((table_share_file_bytes(below) - below) * 8 >= below); +} + +/* Engines stopped together leave together. A holder that leaves while another still holds the + * file waits for it, so the file goes even when the other dies before its own close (killed at a + * stop timeout; its locks go with it). A holder that gets the lock on a file already deleted, with + * a new engine's file at the name, leaves the new one alone. */ +TEST(a_shared_table_file_goes_when_its_holders_leave_together) { + const std::string dir = radtest::tmp_path("share-leave"); + REQUIRE(::mkdir(dir.c_str(), 0777) == 0 || errno == EEXIST); + const std::string container = write_tmp("share-leave-container", ramp(8192, 1)); + REQUIRE(!container.empty()); + const int64_t n = 64 << 10; + const std::string id = table_share_id(container, 4096, n); + REQUIRE(!id.empty()); + std::string why; + + TableShare a; + CHECK_OK(table_share_open(dir, id, n, &a, &why)); + REQUIRE(a.filler); + CHECK_OK(table_share_mark_ready(&a, n, id, &why)); + const std::string path = a.path, lock_path = a.lock_path; + int ready[2]; + REQUIRE_EQ(::pipe(ready), 0); + const pid_t child = ::fork(); + REQUIRE(child >= 0); + if (child == 0) { + TableShare b; + std::string bwhy; + char c = table_share_open(dir, id, n, &b, &bwhy) == RAD_OK && b.ready ? 'y' : 'n'; + (void)!::write(ready[1], &c, 1); + ::usleep(300 * 1000); + ::_exit(0); + } + char c = 0; + CHECK_EQ(::read(ready[0], &c, 1), (ssize_t)1); + CHECK_EQ(c, 'y'); + table_share_close(&a); + CHECK(::access(path.c_str(), F_OK) != 0); + CHECK(::access(lock_path.c_str(), F_OK) != 0); + ::waitpid(child, nullptr, 0); + ::close(ready[0]); + ::close(ready[1]); + + TableShare p, q, r; + CHECK_OK(table_share_open(dir, id, n, &p, &why)); + REQUIRE(p.filler); + CHECK_OK(table_share_mark_ready(&p, n, id, &why)); + CHECK_OK(table_share_open(dir, id, n, &q, &why)); + CHECK(q.ready); + REQUIRE_EQ(::flock(q.fd, LOCK_UN), 0); /* q is on its way out too */ + table_share_close(&p); + CHECK(::access(path.c_str(), F_OK) != 0); + CHECK_OK(table_share_open(dir, id, n, &r, &why)); + CHECK(r.filler); + table_share_close(&q); + CHECK_EQ(::access(path.c_str(), F_OK), 0); + CHECK_EQ(::access(lock_path.c_str(), F_OK), 0); + table_share_close(&r); + CHECK(::access(path.c_str(), F_OK) != 0); +} + /* ------------------------------------------------------------------ reserving and writing */ TEST(a_weight_is_written_in_pieces_in_any_order) { const std::string p = radtest::tmp_path("pieces"); diff --git a/tests/gbnf_test.cpp b/tests/gbnf_test.cpp index 97b3744b..911420d2 100644 --- a/tests/gbnf_test.cpp +++ b/tests/gbnf_test.cpp @@ -1434,9 +1434,9 @@ TEST(gbnf_a_length_bound_past_two_thousand_is_held_exactly) { } /* Bounded repetitions of one operand share one chain of links, so a schema's many length bounds - * cost its longest once rather than their sum. 200 properties at `maxLength: 4000` were 200 chains, - * past the compile budget (a tool schema like that is refused in full); shared, they compile, and - * every bound, short or long, string or array, is still held exactly. */ + * cost its longest once rather than their sum. 200 properties at `maxLength: 4000` as 200 chains + * would exceed the compile budget; shared, they compile, and every bound, short or long, string + * or array, is held exactly. */ TEST(gbnf_bounds_over_one_operand_share_their_links) { auto bv = bpe_like(59, 1500); std::string props = R"("a":{"type":"string","maxLength":4000},"b":{"type":"string","maxLength":7},)" diff --git a/tests/kernel_report_check.sh b/tests/kernel_report_check.sh index 8bdd2326..d2586a89 100755 --- a/tests/kernel_report_check.sh +++ b/tests/kernel_report_check.sh @@ -3,13 +3,9 @@ # # docs/KERNELS.md is generated by `rad-kbench --report` and reviewed by hand. A hand-merged # regeneration can carry a per-library "N row(s) not reached" header from one run and the table -# below it from another: at v1.13.0 the libr4d header says 239 while its table lists 243 rows -# (the four kv_store_streamed rows landed in 486c9331 without the count moving), so the section -# total (378) and the headline "132 of 510 declared row(s) were reached" both read four rows -# short of the tables. The generator cannot produce this from one run -- header and table come -# from one vector -- so the report is checked here, and a partially regenerated file fails. -# -# A check that cannot fail is not a check (docs/DEVLOG-decode-floor.md). +# below it from another, so the section total and the headline "R of D declared row(s) were +# reached" disagree with the tables. One run cannot produce this (header and table come from one +# vector), so a partially regenerated file fails here. set -u REPORT=$1 test -f "$REPORT" || { echo "kernel_report_check: no report at $REPORT"; exit 1; } diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index b38a8ee2..1b14bfbf 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -1857,6 +1857,35 @@ TEST(kv_window_snapshot_only_where_a_hit_resumes_from_it) { CHECK_OK(kv.configure(g, cfg, p.kv())); CHECK(!kv.has_window_snapshot()); CHECK_EQ(kv.checkpoint_bytes(), 0ll); + CHECK(!kv.drafter_window_snapshot()); + } + { /* the same, where the engine saves behind the drafter's context pass: the drafter's window + * rides in the snapshot, every page of it */ + std::vector g = hybrid_groups(/*with_linear=*/false); + w.drafter = true; + g.push_back(w); + Pools p; + CHECK_OK(configure_pools(p, cfg)); + KVManager kv; + kv.set_drafter_window_snapshot(true); + CHECK_OK(kv.configure(g, cfg, p.kv())); + CHECK(kv.has_window_snapshot()); + CHECK(kv.drafter_window_snapshot()); + const KVGroupPlan* d = kv.plan((int32_t)g.size() - 1); + REQUIRE(d && d->win_snap && d->drafter); + CHECK_EQ(kv.checkpoint_bytes(), d->window_blocks * d->bytes_per_block); + } + { /* beside linear state the flag changes nothing: a hit there re-prefills the window */ + std::vector g = hybrid_groups(); + w.drafter = true; + g.push_back(w); + Pools p; + CHECK_OK(configure_pools(p, cfg)); + KVManager kv; + kv.set_drafter_window_snapshot(true); + CHECK_OK(kv.configure(g, cfg, p.kv())); + CHECK(!kv.has_window_snapshot()); + CHECK(!kv.drafter_window_snapshot()); } } @@ -2364,6 +2393,64 @@ TEST(a_capped_lookup_lands_on_a_checkpoint_at_or_below_the_cap) { CHECK_EQ(f.pc.lookup(prompt, {}, nullptr, &cap).n_attn_tokens, 320); } +/* tip-only under a drafter whose KV the cache does not hold (--draft-refill): a hit must end the + * drafter's window before the prompt's end, on a snapshot no more than max_give_back below the tip. + * Keeping the tip alone leaves no such snapshot once retention runs, the capped lookup keeps the + * whole hit, and the request decodes without drafts (measured: 8 x 22k-token sessions, 5 of 8 ran + * unspeculated, decode 424-521 t/s against 738-754 under geometric backoff). With the floor set, + * the policy also keeps the deepest snapshot at or below tip - floor. */ +TEST(tip_only_keeps_a_snapshot_below_the_drafter_floor) { + std::vector keep; + KeepTipOnly bare; + bare.select({64, 128, 192, 256}, &keep); + CHECK_EQ(keep.size(), (size_t)1); + CHECK_EQ(keep[0], 256ll); + + KeepTipOnly floored; + floored.set_floor(100); + floored.select({64, 128, 192, 256}, &keep); + CHECK_EQ(keep.size(), (size_t)2); + CHECK_EQ(keep[0], 128ll); /* the deepest at or below 256 - 100 */ + CHECK_EQ(keep[1], 256ll); + floored.select({200, 256}, &keep); /* nothing below the floor: the tip alone */ + CHECK_EQ(keep.size(), (size_t)1); + CHECK_EQ(floored.held(4096, 64), 2ll); + CHECK_EQ(bare.held(4096, 64), 1ll); +} + +TEST(a_refill_capped_hit_after_tip_only_retention_still_gives_the_drafter_its_window) { + Fixture f; + CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/4)); + f.pc.set_policy(std::make_unique()); + f.pc.set_drafter_floor(100); + auto prompt = tok_run(7000, 336); + publish(f, 1, prompt, 320); + const std::vector hs = chain_of(prompt); + for (int64_t pos = 64; pos <= 256; pos += 64) { + f.pc.begin_step(); + ckpt_at(f, 1, hs, pos); + } + /* Another session's reservation finds the store full: retention runs over every session. */ + auto other = tok_run(90000, 128); + const std::vector ho = chain_of(other); + f.pc.begin_step(); + int32_t s = -1; + CHECK_OK(f.pc.reserve_checkpoint(2, 64, ho[3], &s)); + const std::vector left = f.pc.checkpoints(1); + CHECK_EQ(left.size(), (size_t)2); + CHECK_EQ(left[0], 128ll); + CHECK_EQ(left[1], 256ll); + + /* Scheduler::admit_one's cap for a drafter window of 100: end the hit 100 before the prompt's + * end, give back at most 200. */ + HitCap cap; + cap.tokens = (int64_t)prompt.size() - 100; + cap.max_give_back = 200; + const CacheHit c = f.pc.lookup(prompt, {}, nullptr, &cap); + CHECK_EQ(c.n_linear_tokens, 128); + CHECK_EQ(c.given_back, 128); +} + /* A checkpoint at a prompt's tail, off the interval, is one the next turn resumes from: lookup * takes the deepest snapshot under the hit at any block boundary. */ TEST(a_checkpoint_at_the_tail_of_a_prompt_is_found_and_the_deepest_wins) { @@ -2430,8 +2517,8 @@ TEST(checkpoint_interval_must_be_a_block_multiple) { * A model can keep KV at different strides: DeepSeek-V4's compressed attention stores one row per * r tokens (a block of r) beside groups at one row a token. The cache indexes every such group at * the lcm of their blocks, an entry holding lcm / B blocks of a B-token group, so a hit ends on a - * block of each and adopt() takes every group. Leaving the finer groups out left the trunk a hole - * the scheduler refuses every hit for. + * block of each and adopt() takes every group. A group left out would leave the trunk a hole, and + * the scheduler refuses every hit on such a model. */ static KVGroupInfo gdn_group(std::vector layers) { KVGroupInfo k; diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index ca87ddf0..cd5b7ea7 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -982,6 +982,8 @@ TEST(op_vocabulary) { /* The fused fp8 forms. A host run needs every op covered, so these keep a host-backend run * from failing with "site 'host' is unavailable for this band". */ "rmsnorm_quant_fp8", "gated_quant_fp8", "gemm_nt_q_gated", "dflash_select", + /* Tree verification (rad_drafter_tree): the drafter's tree and the attention over it. */ + "dflash_tree", "attn_paged_tree", "rmsnorm_had_quant_i8", "gated_had_quant_i8", "dequant", @@ -1064,15 +1066,17 @@ TEST(op_vocabulary) { } CHECK_EQ(api().kernel_count(), (int)(sizeof(kOps) / sizeof(kOps[0]))); - /* The two structural constraints, and only those; everything else must match anything. */ + /* The structural constraint on the paged block, and only that; everything else must match + * anything. attn_paged_tree is attn_paged's row with the tree operand, the same constraint. */ CHECK_EQ(kern("attn_paged")->n_constraints, 1); CHECK(std::strcmp(kern("attn_paged")->constraints[0].key, "block_size") == 0); + CHECK_EQ(kern("attn_paged_tree")->n_constraints, 1); CHECK_EQ(kern("kv_store")->n_constraints, 1); CHECK_EQ(kern("gemm_nt")->n_constraints, 0); CHECK_EQ(kern("gdn_chunk_scan")->n_constraints, 0); int constrained = 0; for (int i = 0; i < api().kernel_count(); ++i) constrained += api().kernel_at(i)->n_constraints > 0; - CHECK_EQ(constrained, 2); + CHECK_EQ(constrained, 3); } /* ================================================================== the numerics @@ -9670,6 +9674,8 @@ std::vector geometries() { .s("dtype", "fp8a8").s("act", "silu")), G("dflash_select", "M", 2, a.i("M", R).i("steps", 3).i("top_k", 4).i("rank", 8) .i("n_vocab", 30).s("dtype", "bf16")), + G("dflash_tree", "M", 2, a.i("M", R).i("steps", 3).i("top_k", 4).i("rank", 8) + .i("n_vocab", 30).i("nodes", 3).s("dtype", "bf16")), G("gemm_nt", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "f32")), G("gemm_nt_bias", "M", 3, a.i("M", R).i("N", 20).i("K", 40).s("dtype", "f32")), G("gemm_nt_q", "M", 3, a.i("M", R).i("N", 20).i("K", 256).i("group", 128).s("dtype", "fp8a8")), @@ -9681,6 +9687,10 @@ std::vector geometries() { G("attn_paged", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2).i("block_size", 4) .i("causal", 1).i("window", 0).s("q_dtype", "f32") .s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)), + G("attn_paged_tree", "q_len", 3, a.i("q_len", R).i("head_dim", 8).i("gqa", 2) + .i("block_size", 4).i("causal", 1).i("window", 0) + .s("q_dtype", "f32").s("kv_dtype", "f32").i("n_head", 4) + .i("ctx", 9)), G("attn_dense", "M", 6, a.i("M", R).i("head_dim", 8).i("gqa", 2).i("causal", 1) .s("dtype", "f32").i("n_head", 4)), /* One-row segments, so M is also the segment count (n_seq, the description's hint for diff --git a/tests/sample_test.cpp b/tests/sample_test.cpp index cf1359e7..6ce05b86 100644 --- a/tests/sample_test.cpp +++ b/tests/sample_test.cpp @@ -3012,6 +3012,92 @@ TEST(a_grammar_masks_each_draft_position_against_the_drafts_before_it) { CHECK_EQ(p[3].flags & RAD_SP_MASK, 0); } +/* The same over a tree (rad_drafter_tree): row k is masked against the state after its own + * ancestors, not after drafts 0..k-1, a refused path kills that row only, and the grammar's request + * still speculates. The tree: a, then b and c both after a, then x after c. */ +TEST(a_grammar_masks_each_tree_row_against_its_ancestors) { + SimpleVocab v({ "a", "b", "c", "x", "", "z" }); + HostChain ch(6, 1, 4, &v); + NEED_CHAIN(ch) + auto row = [](std::initializer_list> hot) { + std::vector r(6, 0.0f); + for (auto [t, x] : hot) r[(size_t)t] = x; + return r; + }; + std::vector lg; + for (const auto& r : { row({ { 1, 5.0f } }), /* root: only a */ + row({ { 3, 5.0f }, { 2, 1.0f } }), /* after a: b or c */ + row({ { 0, 5.0f } }), /* after a b: only x */ + row({ { 1, 5.0f } }), /* after a c: only x */ + row({ { 5, 5.0f } }) }) /* after a c x: nothing */ + lg.insert(lg.end(), r.begin(), r.end()); + + SamplingParams sp = greedy_params(); + sp.grammar = "root ::= \"a\" ( \"b\" | \"c\" ) \"x\""; + Request a = make_req(1, { 5 }, sp); + const int32_t da[4] = { 0, 1, 2, 3 }; + const int32_t pa[4] = { 0, 1, 1, 3 }; + a.n_draft = 4; + a.draft = da; + a.draft_parent = pa; + CHECK(ch.s.allows_speculation(1)); + std::vector tok; + int64_t n = 0; + CHECK_OK(ch.step({ &a }, lg, &tok)); + /* Row 2 (a b) and row 3 (a c) take the same mask though a chain would have walked b then c; + * row 4's path is complete, so it stays unmasked without failing the request. */ + CHECK(tok == (std::vector{ 0, 2, 3, 3, 5 })); + const DeviceSampleParams* p = ch.s.staged_params(&n); + for (int k = 0; k < 4; ++k) CHECK((p[k].flags & RAD_SP_MASK) != 0); + CHECK_EQ(p[4].flags & RAD_SP_MASK, 0); + CHECK(ch.s.take_failed().empty()); + /* Rolled back: the grammar accepts a path from its start. */ + CHECK_OK(ch.s.accept_token(1, 0)); + CHECK_OK(ch.s.accept_token(1, 2)); + CHECK_OK(ch.s.accept_token(1, 3)); +} + +/* accept_tree walks from the bonus token to the lowest-numbered child that is the target's pick at + * its parent, as long as one is; the emitted tokens are the target's picks along that path. A + * chain-shaped tree (or no parents) accepts what accept_greedy does. */ +TEST(accept_tree_follows_the_lowest_child_the_target_agrees_with) { + /* node 1: 7 (under 0), node 2: 8 (under 0), node 3: 9 (under 2), node 4: 9 (under 1), + * node 5: 4 (under 3) */ + const int32_t draft[5] = { 7, 8, 9, 9, 4 }; + const int32_t parent[5] = { 0, 0, 2, 1, 3 }; + int32_t out[6] = {}, path[5] = {}, n = -1; + /* The target picks 8 at the bonus, 9 at node 2, 4 at node 3, 6 at node 5. */ + const int32_t t1[6] = { 8, 1, 9, 4, 1, 6 }; + CHECK_OK(accept_tree(draft, parent, 5, t1, out, path, &n)); + CHECK_EQ(n, 3); + CHECK((std::vector(path, path + 3) == std::vector{ 2, 3, 5 })); + CHECK((std::vector(out, out + 4) == std::vector{ 8, 9, 4, 6 })); + /* Both children of the bonus carry the target's pick: the lower-numbered one is taken. */ + const int32_t d2[3] = { 5, 5, 6 }; + const int32_t p2[3] = { 0, 0, 2 }; + const int32_t t2[4] = { 5, 3, 6, 2 }; + CHECK_OK(accept_tree(d2, p2, 3, t2, out, path, &n)); + CHECK_EQ(n, 1); + CHECK_EQ(path[0], 1); + CHECK((std::vector(out, out + 2) == std::vector{ 5, 3 })); + /* No child agrees: only the bonus token's pick is emitted. */ + const int32_t t3[6] = { 1, 1, 1, 1, 1, 1 }; + CHECK_OK(accept_tree(draft, parent, 5, t3, out, path, &n)); + CHECK_EQ(n, 0); + CHECK_EQ(out[0], 1); + /* A chain, with or without parents, is accept_greedy. */ + const int32_t dc[3] = { 4, 5, 6 }; + const int32_t pc[3] = { 0, 1, 2 }; + const int32_t tc[4] = { 4, 5, 9, 1 }; + int32_t og[4] = {}, ng = -1; + CHECK_OK(accept_greedy(dc, 3, tc, og, &ng)); + for (const int32_t* pp : { pc, (const int32_t*)nullptr }) { + CHECK_OK(accept_tree(dc, pp, 3, tc, out, path, &n)); + CHECK_EQ(n, ng); + CHECK((std::vector(out, out + n + 1) == std::vector(og, og + ng + 1))); + } +} + /* A grammar that admits nothing (complete, and no end-of-generation token in the vocabulary) * fails its request, not the step: the step returns success, the request is reported once, and * the next take is empty. */ diff --git a/tests/sched_fakes.h b/tests/sched_fakes.h index 5ed703fb..e45a27e5 100644 --- a/tests/sched_fakes.h +++ b/tests/sched_fakes.h @@ -363,6 +363,7 @@ struct FakePC : IPrefixCache { FakeKV* kv = nullptr; int32_t attn = 0, lin = 0, src = -1; int32_t branch_at = 0; /* CacheHit::branch_at, as the real cache reports it */ + int64_t drafter_floor = -1; /* set_drafter_floor's last value, -1 never called */ int32_t next_slot = 0; int32_t reserved = 0; int64_t evicted = 0, ckpt_evicted = 0; @@ -427,6 +428,7 @@ struct FakePC : IPrefixCache { return h; } const std::vector& cached_groups() const override { return groups; } + void set_drafter_floor(int64_t tokens) override { drafter_floor = tokens; } /* What the scheduler published and asked to be evicted, recorded rather than acted on: these * tests check that the scheduler publishes before it frees and evicts before it preempts, not diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 5578f518..e8dba134 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -166,9 +166,9 @@ struct Fixture { cfg.max_ctx = max_ctx; cfg.checkpoint_interval = 256; cfg.prefix_cache = true; - /* The tests below were written for the nearest resume rule (a tail snapshot at the last - * quantum boundary, a hit at any snapshot or block); the exact rule's own tests set - * prefix_exact (--prefix-resume exact, the default). */ + /* The fixture runs --prefix-resume nearest (a tail snapshot at the last quantum + * boundary, a hit at any snapshot or block); the exact-resume tests set prefix_exact + * (--prefix-resume exact, the engine's default) themselves. */ cfg.prefix_exact = false; /* Config::n_spec defaults to -1 (`auto`), which engine_bringup resolves; this fixture * skips that, and DraftController::configure refuses a negative depth. Speculation tests @@ -314,8 +314,8 @@ TEST(chunk_geometry_rounds_the_checkpoint_interval_up_to_a_legal_chunk) { } /* A model with no linear state checkpoints only for a trunk window: the snapshot of the window - * behind a prompt's tail is what a prefix hit resumes from. A drafter's own window is recomputed - * by draft refill, so it takes no checkpoint and leaves the hit at any block. */ + * behind a prompt's tail is what a prefix hit resumes from. A drafter's own window alone takes no + * checkpoint and leaves the hit at any block: draft refill recomputes it. */ TEST(chunk_geometry_snapshots_a_trunk_window_and_not_a_drafters) { for (int drafter = 0; drafter < 2; ++drafter) { Program prog; @@ -343,6 +343,12 @@ TEST(chunk_geometry_snapshots_a_trunk_window_and_not_a_drafters) { CHECK_OK(chunk_geometry_resolve(prog, cfg, &g)); CHECK_EQ(g.checkpoint_interval, drafter ? 0ll : 256ll); CHECK(g.window_ckpt == !drafter); + /* Bring-up asks the same before the geometry is resolved (window_snapshots), and puts a + * block drafter's window in the snapshot only where it answers yes: a full-attention + * trunk takes no snapshot for its drafter's window alone. */ + CHECK(window_snapshots(prog, cfg) == g.window_ckpt); + cfg.prefix_cache = false; + CHECK(!window_snapshots(prog, cfg)); } } @@ -379,7 +385,9 @@ TEST(window_prefill_writes_interval_snapshots_before_the_tail) { REQUIRE(n > 0); pos += n; if (ckpt > 0) { - CHECK_EQ(ckpt, pos); + /* An interval snapshot ends its chunk; the tail's rides inside the last one. */ + CHECK(ckpt == pos || pos == 1100); + CHECK(ckpt > pos - n); snapshots.push_back(ckpt); } } @@ -387,9 +395,10 @@ TEST(window_prefill_writes_interval_snapshots_before_the_tail) { CHECK(snapshots == expected); /* An aligned prompt must still snapshot before its last block: that block's - * generation marker changes when the client replays the assistant reply. */ + * generation marker changes when the client replays the assistant reply. The snapshot + * is taken inside the chunk, which is not split for it. */ int64_t ckpt = -1; - CHECK_EQ(f.sch.plan_chunk(768, 1024, 512, &ckpt), 240ll); + CHECK_EQ(f.sch.plan_chunk(768, 1024, 512, &ckpt), 256ll); CHECK_EQ(ckpt, 1008ll); /* A shared step may end before the boundary; the next chunk must reach it. */ CHECK_EQ(f.sch.plan_chunk(0, 1100, 160, &ckpt), 160ll); @@ -419,12 +428,12 @@ TEST(tip_only_window_prefill_writes_only_the_tail_snapshot) { CHECK_EQ(ckpt, -1ll); CHECK_EQ(f.sch.plan_chunk(512, 1100, 512, &ckpt), 512ll); CHECK_EQ(ckpt, -1ll); - CHECK_EQ(f.sch.plan_chunk(1024, 1100, 512, &ckpt), 48ll); + CHECK_EQ(f.sch.plan_chunk(1024, 1100, 512, &ckpt), 76ll); CHECK_EQ(ckpt, 1072ll); CHECK_EQ(f.sch.plan_chunk(1072, 1100, 512, &ckpt), 28ll); CHECK_EQ(ckpt, -1ll); - CHECK_EQ(f.sch.plan_chunk(768, 1024, 512, &ckpt), 240ll); + CHECK_EQ(f.sch.plan_chunk(768, 1024, 512, &ckpt), 256ll); CHECK_EQ(ckpt, 1008ll); CHECK_EQ(f.sch.plan_chunk(0, 256, 512, &ckpt), 256ll); CHECK_EQ(ckpt, -1ll); @@ -799,6 +808,105 @@ TEST(a_span_needs_an_interval_grid) { CHECK_EQ((int64_t)f.sch.plan().e.size(), 2ll); } +/* A Gemma-like model (a sliding window over a full-attention trunk, no linear state) resumes a + * prefix hit only from a window snapshot at an earlier prompt's tail. One is taken wherever that + * position, a block short of the prompt's end, is kWindowSnapshotMin or more, at the default + * 2048-token interval too, so a short conversation's next turn resumes: the shortest prompt takes + * its snapshot at the floor and one token less takes none, and a prompt past an interval takes the + * one it always did. An interval under the floor is the floor. A 1000-token prompt runs whole, its + * snapshot taken inside the chunk: the window's rows are still held when it ends, so unlike linear + * state nothing makes the prompt split there. */ +TEST(a_window_snapshot_is_taken_at_the_tail_of_a_short_prompt_too) { + Fixture f; + f.build(4096, 64, /*max_tok=*/2048, 4096, /*windowed=*/true, /*linear=*/false); + f.cfg.checkpoint_interval = 2048; + CHECK_OK(f.start()); + CHECK(f.sch.geometry().window_ckpt); + const int64_t Q = f.sch.geometry().quantum, back = std::max(Q, 16); + const int64_t floor = Scheduler::kWindowSnapshotMin, shortest = floor + back; + CHECK_EQ(floor % Q, (int64_t)0); + CHECK_EQ(f.sch.tail_checkpoint(shortest), floor); + CHECK_EQ(f.sch.tail_checkpoint(shortest - 1), (int64_t)-1); + CHECK_EQ(f.sch.tail_checkpoint(400), (int64_t)-1); + CHECK_EQ(f.sch.tail_checkpoint(3000), (3000 - back) / Q * Q); + const int64_t t = (1000 - back) / Q * Q; + CHECK_EQ(f.sch.tail_checkpoint(1000), t); + f.submit(1000, 8); + const RadBatch* b = f.sch.step(); + CHECK(b != nullptr); + CHECK_EQ(b->n_tok, 1000); + CHECK_EQ(b->n_checkpoints, 1); + CHECK_EQ(b->checkpoint_tok[0], t - 1); + + Fixture g; + g.build(4096, 64, /*max_tok=*/2048, 4096, /*windowed=*/true, /*linear=*/false); + g.cfg.checkpoint_interval = 256; + CHECK_OK(g.start()); + const int64_t I = g.sch.geometry().checkpoint_interval; + CHECK_EQ(I, (int64_t)256); + CHECK_EQ(g.sch.tail_checkpoint(I + back), I); + CHECK_EQ(g.sch.tail_checkpoint(I + back - 1), (int64_t)-1); +} + +/* A prompt longer than the step budget takes its window snapshot inside its last chunk: the chunks + * before it are the budget's, and the last runs to the prompt's end with the snapshot at its tail + * row. */ +TEST(a_long_prompt_takes_its_window_snapshot_inside_its_last_chunk) { + Fixture f; + f.build(4096, 64, /*max_tok=*/512, 4096, /*windowed=*/true, /*linear=*/false); + f.cfg.checkpoint_interval = 2048; + CHECK_OK(f.start()); + const int64_t Q = f.sch.geometry().quantum, back = std::max(Q, 16); + const int64_t t = (1000 - back) / Q * Q; + f.submit(1000, 8); + const RadBatch* b = f.sch.step(); + CHECK(b != nullptr); + CHECK_EQ(b->n_tok, 512); + CHECK_EQ(b->n_checkpoints, 0); + f.commit_plain(); + b = f.sch.step(); + CHECK(b != nullptr); + CHECK_EQ(b->n_tok, 1000 - 512); + CHECK_EQ(b->n_checkpoints, 1); + CHECK_EQ(b->checkpoint_tok[0], t - 512 - 1); +} + +/* Under load a prompt's chunks are held back for the speculating decode rows behind it. Every prompt + * takes its window snapshot once, at its tail row, in whichever chunk carries that row: the final + * one, or a held-back one cut short of the prompt's end on a quantum. */ +TEST(a_window_snapshot_under_load_lands_at_the_tail_whatever_chunk_carries_it) { + for (int64_t n = 600; n <= 1000; n += 24) { + Fixture f; + f.build(4096, 64, /*max_tok=*/256, 8192, /*windowed=*/true, /*linear=*/false); + f.cfg.checkpoint_interval = 2048; + f.cfg.n_spec = 7; + f.cfg.busy_prefill_chunk = -1; + CHECK_OK(f.start()); + const int64_t Q = f.sch.geometry().quantum, back = std::max(Q, 16); + const int64_t t = (n - back) / Q * Q; + for (int d = 0; d < 4; ++d) f.submit(40, 4000); + for (int k = 0; k < 2; ++k) { CHECK(f.sch.step() != nullptr); f.commit_plain(11); } + const uint64_t p = f.submit(n, 8); + int snaps = 0; + for (int k = 0; k < 64 && f.sch.find(p) && f.sch.find(p)->n_computed < n; ++k) { + CHECK(f.sch.step() != nullptr); + for (const StepEntry& e : f.sch.plan().e) { + if (e.seq != p || e.ckpt_slot < 0) continue; + ++snaps; + if (!(e.ctx_len < t && e.ctx_len + e.n_tokens >= t && e.ctx_len + e.ckpt_tok + 1 == t)) + fprintf(stderr, " n %lld: chunk [%d, %d), snapshot at %d, tail %lld\n", + (long long)n, (int)e.ctx_len, (int)(e.ctx_len + e.n_tokens), + (int)(e.ctx_len + e.ckpt_tok + 1), (long long)t); + CHECK((int64_t)e.ctx_len < t && (int64_t)e.ctx_len + e.n_tokens >= t); + CHECK_EQ((int64_t)e.ctx_len + e.ckpt_tok + 1, t); + } + f.commit_plain(11); + } + if (snaps != 1) fprintf(stderr, " n %lld: %d snapshots\n", (long long)n, snaps); + CHECK_EQ(snaps, 1); + } +} + /* ================================================================== exact resume */ /* --prefix-resume exact (the default): a hit resumes only where an idle server's cold prefill of * the same prompt starts a chunk, and a prompt's tail snapshot is where its last chunk starts. A @@ -925,7 +1033,7 @@ TEST(an_exact_tail_snapshot_is_where_the_last_chunk_starts) { /* One ending on the grid: the last chunk is [1536, 2048), and its end is an interval. */ c = cut_from(f.sch, 0, 2048, 512); CHECK((c.ckpts == std::vector{ 1024, 1536, 2048 })); - /* Inside the first interval nothing (as before, cheap to prefill again). */ + /* Inside the first interval nothing (as under nearest: cheap to prefill again). */ c = cut_from(f.sch, 0, 900, 512); CHECK(c.ckpts.empty()); /* A step sharing its budget may straddle the tail: split there, the snapshot written. */ @@ -1366,8 +1474,7 @@ TEST(a_hit_on_a_model_with_a_windowed_group_reuses_nothing) { /* The same model with the trunk's window in the checkpoint slot (KVGroupPlan::win_snap beside * linear state, as DeepSeek-V4.1's sliding layers beside its compressor state): the hit resumes at * the snapshot, which restores the linear state and the window together, and the cached group's - * blocks are adopted. Before, a model with linear state never put its window in the slot, so this - * clamp refused every hit on it. */ + * blocks are adopted. */ TEST(a_hit_on_a_hybrid_whose_slot_carries_the_window_resumes_at_the_snapshot) { Fixture f; f.build(4096, 64, 512, 4096, /*windowed=*/true); @@ -1405,8 +1512,7 @@ TEST(a_hit_on_a_hybrid_whose_slot_carries_the_window_resumes_at_the_snapshot) { } /* A trunk group the cache does not index and no slot carries is a hole no snapshot fills: a full - * group left out (as a group at another block size was before the cache took every block size) - * refuses the hit even where the window is in the slot. */ + * group left out refuses the hit even where the window is in the slot. */ TEST(a_trunk_group_neither_cached_nor_in_the_slot_refuses_the_hit) { Fixture f; f.build(4096, 64, 512, 4096, /*windowed=*/true); @@ -1958,6 +2064,28 @@ RefillRun refill_run(int n_prompt, int32_t seeded, int64_t ckpt_lo = 0) { } } /* namespace */ +TEST(the_refill_window_is_the_retention_policys_drafter_floor) { + /* tip-only keeps a snapshot this deep below the tip, or a refill-capped hit has nothing to end + * on and the request decodes without drafts (KeepTipOnly). Without a refill the floor is 0. */ + for (int spec : { 7, 0 }) { + Fixture f; + f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/512, /*max_ctx=*/8192); + f.cfg.n_spec = spec; + f.prog.drafter.kind = RAD_DRAFT_BLOCK; + f.prog.drafter.window = 512; + KVGroupInfo w; + w.name = "draft"; + w.decl.kind = RAD_KV_WINDOW; + w.decl.window = 512; + w.block_size = 16; + f.prog.kv_groups.push_back(w); + f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64); + f.pc.groups = { 0 }; + CHECK_OK(f.start()); + CHECK_EQ(f.pc.drafter_floor, spec ? (int64_t)512 : (int64_t)0); + } +} + TEST(a_prefix_hit_ends_a_drafter_window_before_the_prompt_and_the_drafter_drafts_at_once) { const RefillRun r = refill_run(/*prompt=*/1100, /*seeded=*/1024); /* The cap is 1100 - 512 = 588: attention 576, and the checkpoint under it 512. */ @@ -1985,6 +2113,51 @@ TEST(a_prefix_hit_with_no_checkpoint_near_the_cap_is_kept_whole) { CHECK_EQ(r.rows, 0); } +/* A Gemma-like model: a full-attention trunk with a sliding window and no linear state, so a hit + * resumes from the window snapshot taken at an earlier prompt's tail (ChunkGeometry::window_ckpt), + * and a windowed block drafter. When that snapshot carries the trunk's window only, draft refill + * cannot cut the hit (no snapshot a window back), the whole hit stands and the drafter waits for + * its window; when it carries the drafter's window too (a block drafter on the card's driver, + * KVManager::set_drafter_window_snapshot), there is no hole, no refill, and the drafter drafts from + * the first decode. */ +TEST(a_prefix_hit_whose_window_snapshot_carries_the_drafters_window_drafts_at_once) { + for (int with_drafter = 0; with_drafter < 2; ++with_drafter) { + Fixture f; + f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/512, /*max_ctx=*/8192, + /*windowed=*/true, /*linear=*/false); + f.cfg.n_spec = 7; + f.prog.drafter.kind = RAD_DRAFT_BLOCK; + f.prog.drafter.window = 512; + KVGroupInfo w; + w.name = "draft"; + w.decl.kind = RAD_KV_WINDOW; + w.decl.window = 512; + w.block_size = 16; + f.prog.kv_groups.push_back(w); + f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64); + const int32_t swa = 1, draft = 2; + f.kv.snap = with_drafter ? std::vector{ swa, draft } : std::vector{ swa }; + f.pc.groups = { 0 }; + f.pc.ckpt_lo = 2048; /* the earlier prompt's tail snapshot, none below it */ + CHECK_OK(f.start()); + CHECK(f.sch.geometry().window_ckpt); + f.pc.seed(2048); f.pc.lin = 2048; f.pc.src = 3; + const uint64_t a = f.submit(2200, 64); + Scheduler::BlockRow rows[4]; + int n_rows = -1; + for (int st = 0; st < 40; ++st) { + CHECK(f.sch.step() != nullptr); + if (st == 0) CHECK_EQ(f.sch.find(a)->n_computed, (int64_t)2048); + f.commit_plain(11); + const int n = f.sch.block_begin(8, 7, 512, 99, rows, 4); + f.sch.block_end(); + if (!f.sch.find(a)->output.empty()) { n_rows = n; break; } + } + CHECK_EQ(f.sch.metrics().draft_refills, (int64_t)0); + CHECK_EQ(n_rows, with_drafter ? 1 : 0); + } +} + /* z-lab's DFlash on the Gemma 4 31B: a full-attention block drafter (no window), whose own group the * prefix cache indexes like the trunk's full layers. A hit resumes the trunk's window from the * window snapshot, so no paged group is left with a hole and the drafter drafts from the first @@ -2028,6 +2201,23 @@ TEST(a_full_attention_drafter_drafts_at_once_after_a_hit_the_window_snapshot_res } } +/* The short block's switch (--draft-short-from): on from the threshold, off again two below, and + * off at one decoding sequence whatever the threshold, where the long block pays. From 2 (a tree's + * auto) a load of 2, 1, 1 runs it, then not; from 8, 8 then 7 keeps it and 6 drops it. */ +TEST(the_short_block_switches_off_at_one_sequence) { + bool on = false; + on = Scheduler::short_block_on(on, 2, 2); CHECK(on); + on = Scheduler::short_block_on(on, 1, 2); CHECK(!on); + on = Scheduler::short_block_on(on, 1, 2); CHECK(!on); + on = Scheduler::short_block_on(on, 0, 2); CHECK(!on); + on = Scheduler::short_block_on(false, 8, 8); CHECK(on); + on = Scheduler::short_block_on(on, 7, 8); CHECK(on); + on = Scheduler::short_block_on(on, 6, 8); CHECK(!on); + on = Scheduler::short_block_on(on, 7, 8); CHECK(!on); + CHECK(Scheduler::short_block_on(false, 1, 1)); /* from 1: every sequence runs it */ + CHECK(!Scheduler::short_block_on(true, 0, 1)); +} + TEST(no_prefix_hit_gives_nothing_back) { const RefillRun r = refill_run(1100, 0); CHECK_EQ(r.m.draft_refills, (int64_t)0); diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 298d9c03..5cfa4352 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -2848,6 +2848,7 @@ TEST(the_live_view_prints_ordinary_lines_when_it_is_not_a_terminal) { * GEMM streaming across the link. */ s.experts.routed = 200; s.experts.routed_resident = 150; s.link.stream_bytes = 700; + s.link.kv_streaming = true; s.link.kv_stream_bytes = 600; /* A pipe is not a terminal, so the constructor picks the line renderer and the frame must * contain no escape sequence: a log full of cursor-home codes is ungreppable, and the breakage @@ -2871,11 +2872,12 @@ TEST(the_live_view_prints_ordinary_lines_when_it_is_not_a_terminal) { /* Hit rate is not residency: 37.50% of the units are in VRAM and 75% of the routing found one * there, which is the placement working. Both numbers, since either alone misleads. */ CHECK(line.find("hit=75.00%") != std::string::npos); - /* The link, cumulative, with all three of the things that share it. */ + /* The link, cumulative, with all four of the things that share it. */ CHECK(line.find("link ar=5000") != std::string::npos); CHECK(line.find("h2d=900") != std::string::npos); CHECK(line.find("d2h=800") != std::string::npos); CHECK(line.find("stream=700") != std::string::npos); + CHECK(line.find("kv=600") != std::string::npos); CHECK(line.back() == '\n'); /* The terminal renderer is the one that may use escapes, and it colours by tier. */ diff --git a/tests/text_test.cpp b/tests/text_test.cpp index 618f5897..777fc6a1 100644 --- a/tests/text_test.cpp +++ b/tests/text_test.cpp @@ -2242,9 +2242,9 @@ TEST(the_normal_forms_agree_with_an_independent_implementation) { CHECK(rows > 2500); } -/* A release that ships no chat template (DeepSeek's) is why --chat-template exists: the file is - * read, trailing newlines stripped exactly as the checkpoint's own file is, and an unreadable or - * empty file is refused rather than skipped. */ +/* --chat-template serves a release that ships no chat template (DeepSeek's): the file is read, + * trailing newlines stripped exactly as the checkpoint's own file is, and an unreadable or empty + * file is refused rather than skipped. */ TEST(read_chat_template_path_strips_newlines_and_refuses_empty) { VocabBuild vb; const std::string p = radtest::tmp_path("chat_template.jinja"); diff --git a/tests/tiny_model.h b/tests/tiny_model.h index 91a10016..26095e4d 100644 --- a/tests/tiny_model.h +++ b/tests/tiny_model.h @@ -480,6 +480,111 @@ inline bool write_gemma4(const std::string& dir, const Gemma4& s) { return write_checkpoint(dir, c, ts); } +/* ------------------------------------------------------------------ dflash2: a block drafter */ + +/* A DFlash2 drafter in vLLM's speculators layout, RedHatAI/gemma-4-31B-it-speculator.dflash2's at + * toy sizes, for a write_gemma4 target of the same `hidden` and `vocab`: Qwen3-shaped layers on a + * non-causal sliding window, an fc over the target's residual stream after the `taps` layers, a + * grouped dynamic convolution around each sublayer (a prepare and a finish half, `conv_kernel` + * taps a group of `conv_group` channels) and a candidate selector. It ships no embedding or head: + * it reads the target's. rad-convert merges it (--draft-model) into a container the 31B's plugin + * serves (gemma4_bf16, under the w4a8 DFlash2 recipe). */ +struct DFlash2 { + int64_t layers = 2, hidden = 256, heads = 4, kv_heads = 2, head_dim = 64, ffn = 512; + int64_t window = 64, block = 8, conv_group = 16, conv_kernel = 2, rank = 16, top_k = 16; + int64_t vocab = 320, ctx = 4096, mask_id = 4; + std::vector taps = { 1, 3, 5 }; + /* The gain of o_proj and down_proj, and the q/k norms' centre. A random drafter's residual is + * otherwise its input embedding, which its head (the target's table) answers with the mask + * token at every position whatever the context: sharp attention and strong branches make + * what it proposes follow the context it attends to. */ + float branch = 4.0f, qk = 3.0f; + uint64_t seed = 6; +}; + +inline bool write_dflash2(const std::string& dir, const DFlash2& s) { + Rng r(s.seed); + const int64_t H = s.hidden, q = s.heads * s.head_dim, kv = s.kv_heads * s.head_dim; + nlohmann::ordered_json types = nlohmann::ordered_json::array(); + for (int64_t l = 0; l < s.layers; ++l) types.push_back("sliding_attention"); + nlohmann::ordered_json t; + t["attention_bias"] = false; + t["head_dim"] = s.head_dim; + t["hidden_act"] = "silu"; + t["hidden_size"] = H; + t["intermediate_size"] = s.ffn; + t["layer_types"] = types; + t["max_position_embeddings"] = s.ctx; + t["model_type"] = "qwen3"; + t["num_attention_heads"] = s.heads; + t["num_hidden_layers"] = s.layers; + t["num_key_value_heads"] = s.kv_heads; + t["rms_norm_eps"] = 1e-6; + t["rope_parameters"] = { { "rope_theta", 10000.0 }, { "rope_type", "default" } }; + t["sliding_window"] = s.window; + t["use_sliding_window"] = true; + t["vocab_size"] = s.vocab; + nlohmann::ordered_json greedy; + greedy["proposal_type"] = "greedy"; + greedy["speculative_tokens"] = s.block - 1; + nlohmann::ordered_json verifier; + verifier["architectures"] = { "Gemma4ForConditionalGeneration" }; + verifier["name_or_path"] = "tiny"; + nlohmann::ordered_json spec; + spec["algorithm"] = "dflash2"; + spec["default_proposal_method"] = "greedy"; + spec["proposal_methods"] = nlohmann::ordered_json::array({ greedy }); + spec["verifier"] = verifier; + nlohmann::ordered_json c; + c["architectures"] = { "DFlash2DraftModel" }; + c["aux_hidden_state_layer_ids"] = s.taps; + c["block_size"] = s.block; + c["conv_group_size"] = s.conv_group; + c["conv_kernel_size"] = s.conv_kernel; + c["draft_vocab_size"] = s.vocab; + c["dtype"] = "bfloat16"; + c["mask_token_id"] = s.mask_id; + c["sample_from_anchor"] = false; + c["selector_rank"] = s.rank; + c["selector_top_k"] = s.top_k; + c["sliding_window_non_causal"] = true; + c["speculators_config"] = spec; + c["speculators_model_type"] = "dflash2"; + c["tie_word_embeddings"] = false; + c["transformer_layer_config"] = t; + + /* The convolution's coefficients: a prepare and a finish half, each conv_kernel taps for every + * group of conv_group channels. */ + const int64_t coef = 2 * s.conv_kernel * (H / s.conv_group); + std::vector ts; + ts.push_back(linear("candidate_selector.hidden_projection.weight", s.rank, H, r)); + ts.push_back(noise("candidate_selector.predecessor_codebook", { s.vocab, s.rank }, r, 0.5f)); + ts.push_back(noise("candidate_selector.successor_codebook", { s.vocab, s.rank }, r, 0.5f)); + ts.push_back(linear("fc.weight", H, (int64_t)s.taps.size() * H, r)); + ts.push_back(noise("hidden_norm.weight", { H }, r, 0.1f, 1.0f)); + for (int64_t l = 0; l < s.layers; ++l) { + const std::string p = "layers." + std::to_string(l) + "."; + for (const char* conv : { "attention_conv.", "mlp_conv." }) { + ts.push_back(noise(p + conv + "base_kernel", { 2, s.conv_kernel, H }, r, 0.3f)); + ts.push_back(linear(p + conv + "kernel_projection.weight", coef, H, r, 0.3f)); + } + ts.push_back(noise(p + "input_layernorm.weight", { H }, r, 0.1f, 1.0f)); + ts.push_back(noise(p + "post_attention_layernorm.weight", { H }, r, 0.1f, 1.0f)); + ts.push_back(linear(p + "self_attn.q_proj.weight", q, H, r)); + ts.push_back(linear(p + "self_attn.k_proj.weight", kv, H, r)); + ts.push_back(linear(p + "self_attn.v_proj.weight", kv, H, r)); + ts.push_back(linear(p + "self_attn.o_proj.weight", H, q, r, s.branch)); + ts.push_back(noise(p + "self_attn.q_norm.weight", { s.head_dim }, r, 0.1f, s.qk)); + ts.push_back(noise(p + "self_attn.k_norm.weight", { s.head_dim }, r, 0.1f, s.qk)); + ts.push_back(linear(p + "mlp.gate_proj.weight", s.ffn, H, r)); + ts.push_back(linear(p + "mlp.up_proj.weight", s.ffn, H, r)); + ts.push_back(linear(p + "mlp.down_proj.weight", H, s.ffn, r, s.branch)); + } + ts.push_back(noise("norm.weight", { H }, r, 0.1f, 1.0f)); + return write_text(dir + "/config.json", c.dump(2)) && + write_safetensors(dir + "/model.safetensors", ts); +} + /* ------------------------------------------------------------------ llama: dense attention */ /* LLaMA (`llama`, served by llama_dense_fp8 once rad-convert has made its linears block fp8): diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index e0b7c6ff..caae4621 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -492,9 +492,10 @@ int main(int argc, char** argv) { "recipe is checked against"); return 1; } - /* An imported quantisation is recorded as the descriptor of the plugin serving it; the engine - * selects by exact match, and each weight states its own encoding. */ - if (imported) { + /* An imported quantisation, or block fp8 served by a family that claims no descriptor for it, + * is recorded as the descriptor of the plugin serving it; the engine selects by exact match, + * and each weight states its own encoding. */ + if (!plugins.arch_plugin.empty() && plugins.arch_quant != meta.quant) { meta.quant = plugins.arch_quant; meta.finish(); } @@ -1080,11 +1081,18 @@ int main(int argc, char** argv) { /* An imported weight is re-laid row by row (ckpt_plane_rows); its bytes are not * the plane's. */ if (!L.src.imported && (L.src.concat_dim == 0 || src.size() == 1)) { + /* Pieces that share one scale tensor (shards under `X.weight_scale`) have + * that one plane, written once. */ + const bool shared = k > 0 && std::all_of(src.begin(), src.end(), + [&](const SrcTensor* s) { + return s == src[0]; + }); int64_t off = 0; for (const SrcTensor* s : src) { if (w.write_plane(idx, k, off, s->data, s->bytes) != RAD_OK) return RAD_E_IO; off += s->bytes; + if (shared) break; } if (off != pb) { RAD_ERR("'%s': its sources hold %lld bytes of plane '%s' and the " diff --git a/tools/rad_kbench.cpp b/tools/rad_kbench.cpp index 5b47d678..3cd38338 100644 --- a/tools/rad_kbench.cpp +++ b/tools/rad_kbench.cpp @@ -358,9 +358,9 @@ int write_report(const std::string& path, const std::vector& rows, std::string s; s += "# radiance kernel libraries\n\n"; - /* The header may claim only what this pass measured. The counts are the same ones the - * Rows nothing ran section prints from this data below; the sentence claiming every - * kernel ran is true only when no declared row was left unreached. */ + /* The header claims only what this pass measured: its counts are the ones the *Rows nothing + * ran* section prints below, and "every kernel ran" only when no declared row went + * unreached. */ size_t declared_rows = 0, reached_rows = 0; for (const LibRow& l : libs) { declared_rows += l.rows.size(); reached_rows += l.ran.size(); } const bool all_ran = reached_rows == declared_rows;