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 7d29b8b9..f39c6204 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 */ @@ -661,6 +671,17 @@ int rad_decl_name_map(RadBuilder* b, const RadNameMap* m); * embedding-only or encoder-only plugin declares none. */ int rad_declare_logits(RadBuilder* b, rad_buf logits); +/* Scored steps (RadBatch::score_only). A plugin whose lm_head is the bf16 table `table` + * ([n_vocab, n_embd], e.g. a tied embedding, whatever encoding the head itself is read at) and + * whose final-normed rows land in `hidden` ([rows, n_embd] bf16, row k the step's k-th sampled row, + * as the lm_head reads them) declares both here. On a step where every sampled row is a scored row + * the core sets RadBatch::score_only, the plugin issues everything but the lm_head, and the core + * reads the hidden rows and the candidates' table rows back and takes the dot products on the host + * in f64: the logits a scored request returns, at no head read on the card (half a gigabyte a step + * at a 128K bf16 vocabulary). Optional; one rank only (the core ignores it at --tp > 1). + * Additive export; RAD_ABI_VERSION does not move. */ +int rad_declare_scores(RadBuilder* b, rad_buf hidden, rad_weight table); + /* Which buffer holds this step's pooled vectors, what an embedding model returns instead of * logits. Row s is sequence s's whole input pooled into one vector, with whatever pooling the * model was trained with (a mean, the last token, a CLS row). The core reads rows [0, n_seq) back @@ -764,6 +785,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 @@ -775,11 +815,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); @@ -1259,8 +1302,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. @@ -1523,6 +1566,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 775a2341..034c3642 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: @@ -291,6 +296,16 @@ typedef struct RadBatch { const int32_t* enc_seg_h; const int32_t* enc_seg_w; + /* ================================================ scored steps */ + + /* Non-zero when every row the sampler wants is a scored row (a /v1/systemone question: the raw + * logits at a few candidate ids, the sampled token discarded) and the program declared where + * the core finds the hidden rows and the head (rad_declare_scores). The plugin then skips its + * lm_head and leaves `rad_declare_scores`' hidden buffer holding the gathered, final-normed + * rows; the core computes the candidates' logits itself. Zero on every other step, and always + * for a program that declared no scores. Appended; an older plugin never sees it set. */ + int32_t score_only; + /* ---- appended in ABI 32 (a request's words for the plugin) */ /* Integer words a request hands the plugin whole (Request::plugin_words), for a head that * needs more of a request than its tokens: clef's joint schema head reads the prompt's diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index 65e48614..5d5d6d18 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -1410,16 +1410,18 @@ inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int6 } /* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them, - * `mode` otherwise. */ + * `mode` otherwise. `op` names the row: "rope" (every caller), or "rope_rows" for a model that + * wants the per-(token, pair) angles form at prefill row counts. */ inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim, - int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) { + int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode, + const char* op = "rope") { const RadParam ps[] = { RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim), RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv), RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), RAD_STR("mode", g.rope_mc ? g.rope_mode : mode), RAD_INT("rotary_dim", rot), RAD_STR("sections", g.rope_sections) }; const int n = (int)(sizeof ps / sizeof ps[0]) - (g.rope_mc ? 0 : 1); - return decl_rotary(b, g, "rope", ps, n, nullptr, 0); + return decl_rotary(b, g, op, ps, n, nullptr, 0); } /* How many of this step's sequences are decode rows, and where their tokens end. 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_gdn_fp8.h b/arch/common/rad_block_gdn_fp8.h index 8b8b4724..5fa76c15 100644 --- a/arch/common/rad_block_gdn_fp8.h +++ b/arch/common/rad_block_gdn_fp8.h @@ -127,6 +127,11 @@ struct GdnFP8 { * the widest decode window the fold serves. */ rad_op op_cr = 0; int64_t cr_rows = 0; + /* Set by the architecture after declare: a `prefetch` of the out-projection's leading bytes + * (decl_prefetch, rad_arch.h), issued on the second lane beside the decode recurrent update on + * steps of up to pf_out_rows rows and pf_out_seqs sequences. 0 where none is declared. */ + rad_op op_pf_out = 0; + int64_t pf_out_rows = 0, pf_out_seqs = 0; rad_op op_ar = 0, op_add = 0; /* The next block absorbs this block's closing all-reduce (see rad_block_attn_gated_fp8.h). */ bool ar_out = false; @@ -481,6 +486,14 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, const int64_t PT = T - DT; const int64_t in_w = conv_dim + v_dim; /* w.in.x's declared row width */ + /* The recurrent update at decode heights runs one workgroup per (sequence, head) and leaves the + * card's memory mostly idle, so the out-projection's weight is read into the on-die cache + * beside it, on the second lane behind a join from lane 0 (as prefetch_beside). */ + if (op_pf_out && D > 0 && D <= pf_out_seqs && P == 0 && T <= pf_out_rows) { + if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) + RAD_ISSUE(c, op_pf_out, RAD_W(out.w)); + rad_lane(c, 0); + } if (D > 0 && op_cr && qd <= cr_rows) { RAD_ISSUE_N(c, op_cr, qd, bcol(w.in.x, 0, conv_dim, DT), RAD_W(w_conv), RAD_NONE, kv_cache(kv_conv, layer), diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index 9433bba2..8c7b4659 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -52,9 +52,9 @@ struct MlpFP8 { rad_op op_ar = 0, op_add = 0; /* gate_up with the gate and quantiser in its epilogue, so the [M, 2*n_ff] bf16 product is * never written (unfused, the extra launch and second pass are a sizeable decode cost). - * Declared beside the pair, not instead of it: the fold is the narrow tile's epilogue and - * serves M <= 64, so prefill chunks take the pair. Byte-identical, as r4d_selftest and - * ref_test check. */ + * Declared beside the pair, not instead of it: the narrow fold serves M <= 64, so prefill + * chunks take the pair -- unless the model asked for `wide_fold`, whose row serves every M. + * Byte-identical, as r4d_selftest and ref_test check. */ rad_op op_gated = 0; int64_t gated_rows = 0; /* The next block absorbs this block's closing all-reduce, so this one must not issue it. @@ -67,9 +67,13 @@ struct MlpFP8 { /* `fold`: a predecessor's delta is still in `w.h.x` and this norm does its residual add * (false for the first block of a chain). `add_out`: issue the trailing add here. See * rad_fp8.h. */ + /* `wide_fold`: declare the gated fold over the whole prompt (gemm_nt_q_gated_wide, whose row + * serves every M) rather than the narrow row's 64-row band. Set by a model that runs whole + * prompts through the fold; every other caller keeps the band and the pair past it. */ int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const Src& src, bool fold = false, bool add_out = true, - int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0); + int ar_in = kArNone, bool ar_out_ = false, double swiglu_limit = 0, + bool wide_fold = false); void step(RadCtx* c, const RadBatch* batch) const; /* The block over the first `T` rows of its buffers (see MoeFP8::step_rows). */ void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); } @@ -93,7 +97,7 @@ struct MlpFP8 { inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const Src& src, bool fold, bool add_out, - int ar_in, bool ar_out_, double swiglu_limit) { + int ar_in, bool ar_out_, double swiglu_limit, bool wide_fold) { g = geom; w = wire; layer = l; ar_out = ar_out_; @@ -120,9 +124,9 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co swiglu_limit)); /* The fold: decl_gated_fold (an fp8a8 tile) for block-fp8 weights, decl_gated_fold_mx for plain - * MXFP4 at one to eight rows. Other gate_up encodings (M2XFP4 included), and a clamped - * (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would take it, which - * would pin the layer's weights to the host. */ + * MXFP4 at one to 16 rows (eight where K is short). Other gate_up encodings (M2XFP4 included), + * and a clamped (swiglu_limit) product, take the pair. Over int8 codes only a host kernel would + * take it, which would pin the layer's weights to the host. */ const bool fold_ok = swiglu_limit <= 0 && !gate_up.f32_scale; if (fold_ok && !gate_up.bf16 && !gate_up.mx && !gate_up.m2x && !gate_up.paro5 && !gate_up.w4 && !gate_up.i8) @@ -131,7 +135,7 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co gq_ffn.want_x ? std::initializer_list{ w.ffn.q, w.ffn.s, w.ffn.x } : std::initializer_list{ w.ffn.q, w.ffn.s }, - &gated_rows); + &gated_rows, wide_fold); else if (fold_ok && gate_up.mx && !gate_up.paro) op_gated = decl_gated_fold_mx(b, g.max_tok, gate_up.N, gate_up.K, gate_up.w, gate_up.ws, gate_up.wref, { w.h.q, w.h.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_fp8.h b/arch/common/rad_fp8.h index a1618d2a..4ecf9da9 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -768,6 +768,11 @@ struct LinearFP8 { /* probe() found an int8 weight; lets a model learn its trunk's format from one linear before * declaring activation buffers (ActFP8::declare_qs's `i8`). */ bool probed_i8 = false; + /* Whether this linear's block-fp8 GEMM takes the short-prompt split rule + * (`gemm_nt_q_short`, narrow_ksplit's `short_unsplit`): at N <= 512, K <= 5120 and 41..64 rows + * the split's per-slice floors dominate, so the row runs unsplit. Opt-in, so every other + * caller keeps the split and its bits. Set before declare(). */ + bool short_split = false; /* Whether this linear reads the input's bf16 plane, known from probe() before the producer is * declared. A producer writes the bf16 plane only when asked, so the block must ask for it when * this is set; otherwise the linear reads unwritten arena bytes. */ @@ -1509,7 +1514,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * caller with a tighter bound (the lm_head, over sampled rows only) passes `max_rows`, so the * narrow kernel's split-K scratch is not sized for max_tok. */ const int64_t hi = max_rows > 0 ? max_rows : g.max_tok; - op = rw(b, RAD_OP(b, "gemm_nt_q", + op = rw(b, RAD_OP(b, short_split && !f32_scale ? "gemm_nt_q_short" : "gemm_nt_q", RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", f32_scale?"fp8a8f32":"fp8a8")), RAD_WEIGHTS(w, ws)), @@ -1724,14 +1729,16 @@ inline int DenseFP8::declare(RadBuilder* b, Names& nm, const char* base, int64_t /* gate_up, silu_mul and the E4M3 quantiser in one GEMM epilogue (`gemm_nt_q_gated`, an fp8a8 * tile over a block-fp8 [2n, K] weight), declared for M up to min(rows, 64): the kernel refuses M - * past that band. Optional: when it does not resolve the caller's unfused ops run, and the issue + * past that band, unless the caller asks for the wide row (`wide`), whose gated prefill tile + * serves every M. Optional: when it does not resolve the caller's unfused ops run, and the issue * site checks `*gated_rows`, set to the band only when the op exists. */ inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, rad_weight ws, std::initializer_list reads, - std::initializer_list writes, int64_t* gated_rows) { - const int64_t hi = rows < 64 ? rows : 64; + std::initializer_list writes, int64_t* gated_rows, + bool wide = false) { + const int64_t hi = wide ? rows : (rows < 64 ? rows : 64); if (hi <= 0) return 0; - const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated", + const rad_op op = rw(b, RAD_OP(b, wide ? "gemm_nt_q_gated_wide" : "gemm_nt_q_gated", RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "fp8a8"), RAD_STR("act", "silu")), @@ -1742,24 +1749,37 @@ inline rad_op decl_gated_fold(RadBuilder* b, int64_t rows, int64_t N, int64_t K, } /* The same fold over an OCP-MXFP4 [2n, K] gate_up weight (`gemm_nt_q_gated_mx`: codes, the E8M0 - * plane and that plane again as the per-row reference), up to min(rows, 8) rows, the band of - * libr4d's one-to-eight-row GEMM. Declared only when a loaded library declares the op (libref - * does not), so a CPU-only engine takes the pair. */ + * plane and that plane again as the per-row reference), declared for M up to min(rows, 16): + * libr4d's gated_gemv serves 1..8 rows and gated_gemv_wide 9..64, each byte-identical to its band's + * GEMM row (gemv, gemv_wide) followed by gated_quant_fp8. 16, not the wide row's 64: Qwen3.8-27B + * at TP2 on 2x R9700 (spec 7, ms a decode step, three interleaved rounds against the 1..8 band) + * gains at 16 rows (two sequences: 1k 20.96 -> 20.78, 16k 21.96 -> 21.70) but loses at 32 (four + * sequences at 1k 23.97 -> 24.10, eight in the short block 24.99 -> 25.14), and 64 lost more + * (16k x16 +2.1 %). The wide row refuses a short K (decode_shortk's corner), so where 1..16 does + * not resolve the band drops to 1..8 rather than lose the fold. Optional like decl_gated_fold, and + * asked for only when a loaded library declares the op: libref does not, so a CPU-only engine takes + * the pair without ever naming it. */ inline rad_op decl_gated_fold_mx(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, rad_weight ws, rad_weight wref, std::initializer_list reads, std::initializer_list writes, int64_t* gated_rows) { - const int64_t hi = rows < 8 ? rows : 8; - if (hi <= 0 || N % 256 || K % RAD_FP8_BLOCK) return 0; + if (rows <= 0 || N % 256 || K % RAD_FP8_BLOCK) return 0; if (!rad_op_declared(b, "gemm_nt_q_gated_mx")) return 0; - const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated_mx", - RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), - RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8"), - RAD_STR("act", "silu")), - RAD_WEIGHTS(w, ws, wref)), - reads, writes); - if (op) *gated_rows = hi; - return op; + for (const int64_t band : { (int64_t)16, (int64_t)8 }) { + const int64_t hi = rows < band ? rows : band; + const rad_op op = rw(b, RAD_OP(b, "gemm_nt_q_gated_mx", + RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_MX_GROUP), + RAD_STR("dtype", "mxfp4a8"), RAD_STR("act", "silu")), + RAD_WEIGHTS(w, ws, wref)), + reads, writes); + if (op) { + *gated_rows = hi; + return op; + } + if (hi <= 8) break; + } + return 0; } /* ================================================== a calibration tap */ 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/lfm2_bf16/lfm2_bf16.cpp b/arch/lfm2_bf16/lfm2_bf16.cpp index 57f1895b..c4ce1f12 100644 --- a/arch/lfm2_bf16/lfm2_bf16.cpp +++ b/arch/lfm2_bf16/lfm2_bf16.cpp @@ -21,14 +21,35 @@ * under `model`. Which one this is comes from the config (a VL checkpoint has a `text_config`), * not the model's name. * + * ============================== 8-BIT LINEARS ============================== + * + * Every linear is a LinearFP8 (rad_fp8.h), so the container's encoding of each weight decides the + * GEMM: plain bf16 is `gemm_nt` over the bf16 activation, exactly as a bf16 model runs; a recipe's + * block E4M3 (`codes=fp8_e4m3 block=128x128 scale=bf16`) is `gemm_nt_q` at fp8a8 over the + * activation quantised per 128 columns (one quant_act_fp8 per activation, shared by the linears + * that read it); int8 (`codes=i8 group=128 scale=bf16`) is `gemm_nt_q` at i8a8, each linear + * quantising its input. The trunk's format is read off layer 0's down projection and every linear + * must match it. The convolution, the norms and attention stay bf16; the lm_head is read at its + * stored codes (bf16, or E4M3 / int8 where a recipe made it so; logits_gemm_fp8 / _i8). At d1-3B + * the linears are 5.8 of the 6.3 GB a token reads, so 8-bit codes nearly halve decode and short + * prefill, both bound by that read. + * + * A block-fp8 trunk also takes the fused producers (rad_fp8.h), which matter once the GEMMs are + * this cheap: each norm quantises in its own pass and does the preceding block's residual add + * (rmsnorm_quant_fp8 with a fold), and the feed-forward is MlpFP8, whose gate|up GEMM applies + * SiLU(gate) * up and quantises in its epilogue at decode and short-prompt rows. Six launches a + * layer become two; the last layer's feed-forward keeps its add for the final norm. The fused + * kernels are byte-identical to the chains they replace. + * * ============================== WHAT IT DOES NOT SERVE ============================== * * Tensor parallelism (a 3B model needs one card). A drafter, MoE (LFM2-8B-A1B), conv bias, or a * checkpoint without the rotary: each is refused by name. */ #include -#include #include +#include +#include #include "siglip2.h" @@ -42,17 +63,32 @@ using namespace rad::arch; struct Layer { bool attention = false; - MlpBF16 mlp; - rad_weight w_norm = 0, w_in = 0, w_out = 0; + rad_weight w_norm = 0; + /* in is q (attention) or the convolution's in_proj; out is the mixer's out-projection */ + LinearFP8 in, out; /* conv */ rad_weight w_conv = 0; rad_op op_gate_in = 0, op_conv = 0, op_gate_out = 0; - /* attention: w_in is q, these are k, v and the two head norms */ - rad_weight w_k = 0, w_v = 0, w_q_norm = 0, w_k_norm = 0; - rad_op op_k = 0, op_v = 0, op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0; + /* `gate_quant_fp8` at act none: C * conv(B * x) and its E4M3 codes in one pass. Absent + * (bf16, int8, or no library serving it), op_gate_out and q_mix run the pair. */ + rad_op op_gate_q = 0; + /* attention: k, v and the two head norms */ + LinearFP8 k, v; + rad_weight w_q_norm = 0, w_k_norm = 0; + rad_op op_q_norm = 0, op_k_norm = 0, op_rope_q = 0, op_rope_k = 0; rad_op op_store = 0, op_attn = 0; /* both */ - rad_op op_norm = 0, op_in = 0, op_out = 0, op_add = 0; + rad_op op_norm = 0, op_add = 0; + /* the feed-forward: norm, gate|up (w1 | w3), SiLU(gate) * up, down (w2), residual add */ + rad_weight w_ffn_norm = 0; + LinearFP8 gate_up, down; + rad_op op_ffn_norm = 0, op_act = 0, op_ffn_add = 0; + /* fp8a8 only: the activation quantisers, one per activation the linears read */ + QuantFP8 q_h, q_mix, q_ffn_h, q_ffn; + /* fp8a8 fused: the mixer's norm (quantising, and adding the previous feed-forward's delta + * from layer 1 on) and the whole feed-forward */ + NormQuantFP8 nq_mix; + MlpFP8 mlp8; }; struct Model { @@ -64,6 +100,12 @@ struct Model { rad_buf b_x = 0, b_h = 0, b_bcx = 0, b_conv_in = 0, b_conv_out = 0; rad_buf b_q = 0, b_k = 0, b_v = 0, b_attn = 0, b_gate_up = 0, b_ffn = 0; rad_buf b_hout = 0, b_logits = 0; + /* The linears' inputs: the bf16 plane plus, for an 8-bit trunk, its codes. a_mix is the + * mixer's output (attention or convolution), the out-projection's input. */ + ActFP8 a_h{}, a_attn{}, a_conv{}, a_ffn{}; + /* The trunk's format, read off layer 0's first linear. `fused`: the fp8 trunk's fused + * producers (see the head of the file). */ + bool q_fp8 = false, q_i8 = false, fused = false; rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0; rad_op op_embed = 0, op_gather = 0, op_final_norm = 0, op_logits = 0; @@ -215,8 +257,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); - m.w_lm_head = decl_w(b, nm.f("output.weight"), RAD_BF16, {g.n_vocab, g.n_embd}, - RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + /* The head at its codes' dtype: bf16, or E4M3 / int8 where a recipe quantised it. */ + m.w_lm_head = decl_w(b, nm.f("output.weight"), + weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16), + {g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); m.op_embed = rw(b, RAD_OP(b, "embed_lookup", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd), @@ -227,66 +271,125 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c m.media = Siglip2::present(meta) && ctx->max_enc_patches > 0; if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x)); - MlpBF16::Wire mw{}; - mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn; - - auto gemm = [&](int64_t N, int64_t K, rad_weight w, rad_buf in, rad_buf out) { - return rw(b, RAD_OP(b, "gemm_nt", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K), - RAD_STR("dtype", g.dtype)), - RAD_WEIGHTS(w)), - {in}, {out}); + /* ---- the trunk's format, from layer 0's first linear: q, or the convolution's in_proj + * (probe() makes its name map and reads its encoding). Plain bf16, or no encoding yet, is a + * bf16 trunk; an int8 weight makes the activations carry int8 codes, any other 8-bit weight + * E4M3 ones. */ + const char* ffn_fmt = "%s.layers.%d.feed_forward.%s"; + { + Layer& L0 = m.layers[0]; + const char* base0 = nm.f(L0.attention ? "blk.%d.attn_q" : "blk.%d.conv_in", 0); + RAD_ARCH_TRY(L0.in.probe(b, nm, g, base0, + { nm.ckpt(L0.attention ? "%s.layers.%d.self_attn.%s" + : "%s.layers.%d.conv.%s", + pre, 0, L0.attention ? "q_proj.weight" + : "in_proj.weight") })); + RadEncoding enc{}; + const bool known = weight_enc(b, nm.f("%s.weight", base0), &enc); + const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 && + enc.plane[0].dtype == RAD_BF16); + g.w_bf16 = plain; + m.q_i8 = !plain && L0.in.probed_i8; + m.q_fp8 = !plain && !m.q_i8; + m.fused = m.q_fp8; + } + m.a_h.x = m.b_h; m.a_attn.x = m.b_attn; m.a_conv.x = m.b_conv_out; m.a_ffn.x = m.b_ffn; + RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, m.q_i8)); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", g.q_dim(), 0, m.q_i8)); + RAD_ARCH_TRY(m.a_conv.declare_qs(b, nm, g, "conv_out", g.n_embd, 0, m.q_i8)); + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, m.q_i8)); + /* An E4M3 activation is quantised once by the model and read by every linear on it; an int8 + * linear quantises its own input (LinearFP8::op_q), and a bf16 one reads the bf16 plane. */ + auto quant = [&](QuantFP8& q, const ActFP8& a, int64_t n) { + return m.q_fp8 ? q.declare(b, g, a, n) : RAD_OK; }; - auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out) { - return rw(b, RAD_OP(b, "rmsnorm", + + /* `op`: "rmsnorm", or "rmsnorm_rows" for the head norms, whose short-row form a prefill's + * thousands of head_dim-wide rows take. */ + auto rmsnorm = [&](int64_t rows, int64_t n, rad_weight w, rad_buf in, rad_buf out, + const char* op = "rmsnorm") { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w)), {in}, {out}); }; + auto add = [&](rad_buf x, rad_buf h) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {x, h}, {x}); + }; auto layer_w = [&](const char* name, int l, std::initializer_list shape, uint32_t dtype) { return decl_w(b, nm.f(name, l), dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); }; + /* One linear: `base` is the declared name without `.weight`. Every linear must have the + * trunk's format; LinearFP8 refuses a bf16 weight in an 8-bit trunk with no bf16 plane, and + * this refuses the other mixes. */ + auto linear = [&](LinearFP8& lin, int l, const char* base_fmt, int64_t N, int64_t K, + std::initializer_list src, const ActFP8& a, rad_buf y, + std::initializer_list parts) -> int { + const char* base = nm.f(base_fmt, l); + RAD_ARCH_TRY(lin.declare(b, nm, g, base, N, K, RAD_SHARD_NONE, grp_layer(l), src, a, y, 0, + parts)); + const bool ok = g.w_bf16 ? lin.bf16 : m.q_i8 ? lin.i8 : (!lin.bf16 && !lin.i8); + if (!ok) { + fprintf(stderr, "radiance: lfm2: '%s.weight' is not in the trunk's format (%s); quantise " + "every linear of the trunk alike\n", + base, g.w_bf16 ? "bf16" : m.q_i8 ? "int8" : "block fp8"); + return RAD_E_DTYPE; + } + return RAD_OK; + }; for (int l = 0; l < (int)m.layers.size(); ++l) { Layer& L = m.layers[(size_t)l]; RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), nm.ckpt("%s.layers.%d.operator_norm.weight", pre, l))); L.w_norm = layer_w("blk.%d.attn_norm.weight", l, {g.n_embd}, RAD_F32); - L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h); + if (m.fused) { + /* From layer 1 on the previous feed-forward's delta is still in h: the norm adds it + * into the stream, then normalises and quantises. */ + const bool fold = l > 0; + RAD_ARCH_TRY(L.nq_mix.declare(b, g, L.w_norm, fold ? m.b_h : m.b_x, m.a_h, g.n_embd, + fold ? m.b_x : 0)); + } else { + L.op_norm = rmsnorm(g.max_tok, g.n_embd, L.w_norm, m.b_x, m.b_h); + RAD_ARCH_TRY(quant(L.q_h, m.a_h, g.n_embd)); + } if (L.attention) { RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_attn)); const char* a = "%s.layers.%d.self_attn.%s"; - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), nm.ckpt(a, pre, l, "q_proj.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), nm.ckpt(a, pre, l, "k_proj.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), nm.ckpt(a, pre, l, "v_proj.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), nm.ckpt(a, pre, l, "q_layernorm.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), nm.ckpt(a, pre, l, "k_layernorm.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), - nm.ckpt(a, pre, l, "out_proj.weight"))); - L.w_in = layer_w("blk.%d.attn_q.weight", l, {g.q_dim(), g.n_embd}, RAD_BF16); - L.w_k = layer_w("blk.%d.attn_k.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16); - L.w_v = layer_w("blk.%d.attn_v.weight", l, {g.kv_dim(), g.n_embd}, RAD_BF16); + RAD_ARCH_TRY(linear(L.in, l, "blk.%d.attn_q", g.q_dim(), g.n_embd, + { nm.ckpt(a, pre, l, "q_proj.weight") }, m.a_h, m.b_q, {})); + /* k and v are the trunk's narrowest linears: past 40 rows the narrow fp8 row's split + * leaves each slice too few waves, so they ask for the short-prompt split rule. */ + L.k.short_split = L.v.short_split = true; + RAD_ARCH_TRY(linear(L.k, l, "blk.%d.attn_k", g.kv_dim(), g.n_embd, + { nm.ckpt(a, pre, l, "k_proj.weight") }, m.a_h, m.b_k, {})); + RAD_ARCH_TRY(linear(L.v, l, "blk.%d.attn_v", g.kv_dim(), g.n_embd, + { nm.ckpt(a, pre, l, "v_proj.weight") }, m.a_h, m.b_v, {})); L.w_q_norm = layer_w("blk.%d.attn_q_norm.weight", l, {g.head_dim}, RAD_F32); L.w_k_norm = layer_w("blk.%d.attn_k_norm.weight", l, {g.head_dim}, RAD_F32); - L.w_out = layer_w("blk.%d.attn_output.weight", l, {g.n_embd, g.q_dim()}, RAD_BF16); - L.op_in = gemm(g.q_dim(), g.n_embd, L.w_in, m.b_h, m.b_q); - L.op_k = gemm(g.kv_dim(), g.n_embd, L.w_k, m.b_h, m.b_k); - L.op_v = gemm(g.kv_dim(), g.n_embd, L.w_v, m.b_h, m.b_v); /* The head norms run over rows of head_dim: a [T, heads * head_dim] buffer is * T * heads rows. */ - L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q); - L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k); + L.op_q_norm = rmsnorm(g.max_tok * g.n_head, g.head_dim, L.w_q_norm, m.b_q, m.b_q, + "rmsnorm_rows"); + L.op_k_norm = rmsnorm(g.max_tok * g.n_head_kv, g.head_dim, L.w_k_norm, m.b_k, m.b_k, + "rmsnorm_rows"); L.op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, - "neox"), {m.b_q}, {m.b_q}); + "neox", "rope_rows"), {m.b_q}, {m.b_q}); L.op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim, - "neox"), {m.b_k}, {m.b_k}); + "neox", "rope_rows"), {m.b_k}, {m.b_k}); /* attn_paged before kv_store: the cache's block size is read from the resolved * attention kernel. */ L.op_attn = rw(b, RAD_OP(b, "attn_paged", @@ -309,21 +412,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_STR("kv_dtype", g.kv_dtype)), RAD_NOWEIGHTS), {m.b_k, m.b_v}, {}); - L.op_out = gemm(g.n_embd, g.q_dim(), L.w_out, m.b_attn, m.b_h); + RAD_ARCH_TRY(quant(L.q_mix, m.a_attn, g.q_dim())); + RAD_ARCH_TRY(linear(L.out, l, "blk.%d.attn_output", g.n_embd, g.q_dim(), + { nm.ckpt(a, pre, l, "out_proj.weight") }, m.a_attn, m.b_h, {})); } else { RAD_ARCH_TRY(rad_bind_layer_kv(b, l, m.kv_conv)); const char* c = "%s.layers.%d.conv.%s"; - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_in.weight", l), nm.ckpt(c, pre, l, "in_proj.weight"))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv.weight", l), nm.ckpt(c, pre, l, "conv.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.conv_out.weight", l), nm.ckpt(c, pre, l, "out_proj.weight"))); - L.w_in = layer_w("blk.%d.conv_in.weight", l, {3 * g.n_embd, g.n_embd}, RAD_BF16); + /* in_proj's row is [B | C | x]: conv(B * x), then C * that. */ + RAD_ARCH_TRY(linear(L.in, l, "blk.%d.conv_in", 3 * g.n_embd, g.n_embd, + { nm.ckpt(c, pre, l, "in_proj.weight") }, m.a_h, m.b_bcx, {})); /* The checkpoint ships [n_embd, 1, width]; the depthwise group axis is squeezed at * convert, as the gated delta net's conv1d is. */ L.w_conv = layer_w("blk.%d.conv.weight", l, {g.n_embd, m.width}, RAD_BF16); - L.w_out = layer_w("blk.%d.conv_out.weight", l, {g.n_embd, g.n_embd}, RAD_BF16); - /* in_proj's row is [B | C | x]: conv(B * x), then C * that. */ - L.op_in = gemm(3 * g.n_embd, g.n_embd, L.w_in, m.b_h, m.b_bcx); L.op_gate_in = rw(b, RAD_OP(b, "mul", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)), @@ -334,25 +436,78 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_INT("width", m.width), RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(L.w_conv)), {m.b_conv_in}, {m.b_conv_out}); - L.op_gate_out = rw(b, RAD_OP(b, "mul", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), - RAD_STR("dtype", g.dtype)), - RAD_NOWEIGHTS), - {m.b_bcx, m.b_conv_out}, {m.b_conv_out}); - L.op_out = gemm(g.n_embd, g.n_embd, L.w_out, m.b_conv_out, m.b_h); + /* C * conv(B * x), then the codes the out projection reads, in one pass. The kernel + * rounds the product to bf16 before taking the codes, so it is byte-identical to the + * mul + quant_act_fp8 pair; the bf16 product has no reader in a block-fp8 trunk. */ + if (m.q_fp8 && rad_op_declared(b, "gate_quant_fp8")) + L.op_gate_q = rw(b, RAD_OP(b, "gate_quant_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), + RAD_INT("n", g.n_embd), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", g.dtype), + RAD_STR("act", "none")), + RAD_NOWEIGHTS), + {m.b_bcx, m.b_conv_out}, {m.a_conv.cq(), m.a_conv.cs()}); + if (!L.op_gate_q) { + L.op_gate_out = rw(b, RAD_OP(b, "mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), + RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_bcx, m.b_conv_out}, {m.b_conv_out}); + RAD_ARCH_TRY(quant(L.q_mix, m.a_conv, g.n_embd)); + } + RAD_ARCH_TRY(linear(L.out, l, "blk.%d.conv_out", g.n_embd, g.n_embd, + { nm.ckpt(c, pre, l, "out_proj.weight") }, m.a_conv, m.b_h, {})); } - L.op_add = rw(b, RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + if (m.fused) { + /* The feed-forward's norm adds the mixer's delta; its own add is left to the next + * layer's norm, except after the last layer, whose output the final norm reads. */ + MlpFP8::Wire mw{}; + mw.x = m.b_x; mw.h = m.a_h; mw.gate_up = m.b_gate_up; mw.ffn = m.a_ffn; + MlpFP8::Src ms{}; + ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l); + ms.gate = nm.ckpt(ffn_fmt, pre, l, "w1.weight"); + ms.up = nm.ckpt(ffn_fmt, pre, l, "w3.weight"); + ms.down = nm.ckpt(ffn_fmt, pre, l, "w2.weight"); + const bool last = l + 1 == (int)m.layers.size(); + /* The whole prompt in the fold: gemm_nt_q_gated_wide serves every M, so a prefill + * chunk does not fall back to the pair past 64 rows. */ + RAD_ARCH_TRY(L.mlp8.declare(b, nm, g, l, mw, ms, /*fold=*/true, /*add_out=*/last, + 0, false, 0, /*wide_fold=*/true)); + if (L.mlp8.gate_up.bf16 || L.mlp8.gate_up.i8 || L.mlp8.down.bf16 || L.mlp8.down.i8) { + fprintf(stderr, "radiance: lfm2: layer %d's feed-forward is not block fp8 like the " + "rest of the trunk; quantise every linear alike\n", l); + return RAD_E_DTYPE; + } + continue; + } + L.op_add = add(m.b_x, m.b_h); + + /* ---- the feed-forward */ + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_norm.weight", l), + nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l))); + L.w_ffn_norm = layer_w("blk.%d.ffn_norm.weight", l, {g.n_embd}, RAD_F32); + L.op_ffn_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(L.w_ffn_norm)), + {m.b_x}, {m.b_h}); + RAD_ARCH_TRY(quant(L.q_ffn_h, m.a_h, g.n_embd)); + RAD_ARCH_TRY(linear(L.gate_up, l, "blk.%d.ffn_gate_up", 2 * g.n_ff, g.n_embd, + { nm.ckpt(ffn_fmt, pre, l, "w1.weight"), + nm.ckpt(ffn_fmt, pre, l, "w3.weight") }, + m.a_h, m.b_gate_up, { g.n_ff, g.n_ff })); + L.op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)), RAD_NOWEIGHTS), - {m.b_x, m.b_h}, {m.b_x}); - - MlpBF16::Src ms{}; - ms.norm = nm.ckpt("%s.layers.%d.ffn_norm.weight", pre, l); - ms.gate = nm.ckpt("%s.layers.%d.feed_forward.w1.weight", pre, l); - ms.up = nm.ckpt("%s.layers.%d.feed_forward.w3.weight", pre, l); - ms.down = nm.ckpt("%s.layers.%d.feed_forward.w2.weight", pre, l); - RAD_ARCH_TRY(L.mlp.declare(b, nm, g, l, mw, ms)); + {m.b_gate_up}, {m.b_ffn}); + RAD_ARCH_TRY(quant(L.q_ffn, m.a_ffn, g.n_ff)); + RAD_ARCH_TRY(linear(L.down, l, "blk.%d.ffn_down", g.n_embd, g.n_ff, + { nm.ckpt(ffn_fmt, pre, l, "w2.weight") }, m.a_ffn, m.b_h, {})); + L.op_ffn_add = add(m.b_x, m.b_h); } /* The final norm runs on the gathered rows only: it is per token, and those are the rows the @@ -363,6 +518,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_NOWEIGHTS), {m.b_x}, {m.b_hout}); m.op_final_norm = rmsnorm(g.max_logit_rows, g.n_embd, m.w_out_norm, m.b_hout, m.b_hout); + /* A tied head is the bf16 embedding table, whatever codes the head itself is read at: a + * scored step (/v1/systemone) leaves the final-normed rows in h_out and the core takes the + * candidates' logits from the table on the host (rad_declare_scores), with no head read. */ + if (text_bool(meta, "tie_word_embeddings", false)) + RAD_ARCH_TRY(rad_declare_scores(b, m.b_hout, m.w_tok)); m.op_logits = rw(b, RAD_OP(b, "logits_gemm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", g.n_embd), @@ -431,12 +591,17 @@ static void step(RadCtx* c, const RadBatch* batch) { for (int l = 0; l < (int)m.layers.size(); ++l) { const Layer& L = m.layers[(size_t)l]; - RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T)); + if (m.fused) { + L.nq_mix.step(c, T); + } else { + RAD_ISSUE(c, L.op_norm, brows(m.b_x, T), RAD_W(L.w_norm), brows(m.b_h, T)); + L.q_h.step(c, T); + } if (L.attention) { const RadKVGroupBatch* kv = kv_batch(batch, m.kv_attn); - RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_q, T)); - RAD_ISSUE(c, L.op_k, brows(m.b_h, T), RAD_W(L.w_k), brows(m.b_k, T)); - RAD_ISSUE(c, L.op_v, brows(m.b_h, T), RAD_W(L.w_v), brows(m.b_v, T)); + L.in.step(c, m.a_h, m.b_q, T); + L.k.step(c, m.a_h, m.b_k, T); + L.v.step(c, m.a_h, m.b_v, T); RAD_ISSUE_N(c, L.op_q_norm, T * g.n_head, brows(m.b_q, T), RAD_W(L.w_q_norm), brows(m.b_q, T)); RAD_ISSUE_N(c, L.op_k_norm, T * g.n_head_kv, brows(m.b_k, T), RAD_W(L.w_k_norm), @@ -453,18 +618,36 @@ static void step(RadCtx* c, const RadBatch* batch) { RAD_NONE, RAD_NONE, praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(m.b_attn, T)); - RAD_ISSUE(c, L.op_out, brows(m.b_attn, T), RAD_W(L.w_out), brows(m.b_h, T)); + L.q_mix.step(c, T); + L.out.step(c, m.a_attn, m.b_h, T); } else { - RAD_ISSUE(c, L.op_in, brows(m.b_h, T), RAD_W(L.w_in), brows(m.b_bcx, T)); + L.in.step(c, m.a_h, m.b_bcx, T); RAD_ISSUE(c, L.op_gate_in, bcol(m.b_bcx, 0, n, T), bcol(m.b_bcx, 2 * n, n, T), brows(m.b_conv_in, T)); conv_step(m, L, c, batch, l); - RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T), - brows(m.b_conv_out, T)); - RAD_ISSUE(c, L.op_out, brows(m.b_conv_out, T), RAD_W(L.w_out), brows(m.b_h, T)); + if (L.op_gate_q) { + RAD_ISSUE(c, L.op_gate_q, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T), + brows(m.a_conv.cq(), T), brows(m.a_conv.cs(), T), RAD_NONE); + } else { + RAD_ISSUE(c, L.op_gate_out, bcol(m.b_bcx, n, n, T), brows(m.b_conv_out, T), + brows(m.b_conv_out, T)); + L.q_mix.step(c, T); + } + L.out.step(c, m.a_conv, m.b_h, T); + } + if (m.fused) { + L.mlp8.step(c, batch); + continue; } RAD_ISSUE(c, L.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T)); - L.mlp.step(c, batch); + + RAD_ISSUE(c, L.op_ffn_norm, brows(m.b_x, T), RAD_W(L.w_ffn_norm), brows(m.b_h, T)); + L.q_ffn_h.step(c, T); + L.gate_up.step(c, m.a_h, m.b_gate_up, T); + RAD_ISSUE(c, L.op_act, brows(m.b_gate_up, T), brows(m.b_ffn, T)); + L.q_ffn.step(c, T); + L.down.step(c, m.a_ffn, m.b_h, T); + RAD_ISSUE(c, L.op_ffn_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T)); } /* The lm_head runs only on the rows the sampler asked for; a prefill chunk that finishes no @@ -474,15 +657,17 @@ static void step(RadCtx* c, const RadBatch* batch) { praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out)); RAD_ISSUE_N(c, m.op_final_norm, batch->n_out, brows(m.b_hout, batch->n_out), RAD_W(m.w_out_norm), brows(m.b_hout, batch->n_out)); - RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out), - RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out)); + if (!batch->score_only) + RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out), + RAD_W(m.w_lm_head), brows(m.b_logits, batch->n_out)); } } } /* namespace lfm2_bf16 */ #ifndef RAD_ARCH_NO_EXPORTS -RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.1.0", - "LiquidAI LFM2 / LFM2-VL, bf16: short gated convolutions and GQA attention in the " - "checkpoint's own schedule, one rank; LFM2-VL's SigLIP2 tower for images") +RAD_ARCH_PLUGIN(lfm2_bf16, "lfm2", "", "0.2.0", + "LiquidAI LFM2 / LFM2-VL, bf16, or with block-fp8 or int8 linears from a recipe: " + "short gated convolutions and GQA attention in the checkpoint's own schedule, one " + "rank; LFM2-VL's SigLIP2 tower for images") #endif 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 d63eec13..91cac2bc 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -114,6 +114,16 @@ using MtpHead = MtpFP8; * wash. The drafter's reads (Dflash2::Config::prefetch) take the same size. */ constexpr int64_t kPrefetchBytes = (int64_t)12 << 20; constexpr int64_t kPrefetchStepRows = 32; +/* The delta net's out-projection read into the on-die cache beside its decode recurrent update + * (GdnFP8::op_pf_out): the update runs one workgroup per (sequence, head) and leaves the memory mostly + * idle, so the whole projection (7.9 MB a rank in MXFP4; the read stops at the weight's end) is read + * there. Qwen3.8-27B MXFP4 + DFlash2 at tp 2, production flags, 1k context, hwgrid ms/step, median of + * five interleaved rounds, none -> whole: x1 19.40 -> 19.10, x2 20.93 -> 20.78, x4 24.26 -> 24.17 + * (every round faster), x8 25.22 -> 25.48 (four rounds of five slower: eight sequences' state traffic + * fills the memory and the read competes with it), so up to four sequences. 4 MB read as the whole + * (x1 19.24 / 19.10 against 19.20 / 19.06); 90k x4 and x16 (64 rows, no read) unchanged. */ +constexpr int64_t kGdnOutPrefetchBytes = (int64_t)8 << 20; +constexpr int64_t kGdnOutPrefetchSeqs = 4; struct Layer { int full = 0; @@ -430,11 +440,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) { @@ -445,15 +455,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, @@ -1097,6 +1098,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c Layer& lay = m.layers[(size_t)l]; lay.pf_gu_w = lay.mlp.gate_up.w; lay.op_pf_gu = decl_prefetch(b, lay.pf_gu_w, kPrefetchBytes); + if (!lay.full) { + lay.gdn.op_pf_out = decl_prefetch(b, lay.gdn.out.w, kGdnOutPrefetchBytes); + lay.gdn.pf_out_rows = kPrefetchStepRows; + lay.gdn.pf_out_seqs = kGdnOutPrefetchSeqs; + } if (l + 1 < m.n_main) { const Layer& nx = m.layers[(size_t)l + 1]; lay.pf_next_w = nx.full ? nx.attn.qg.w : nx.gdn.in.w; diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 44061b0d..4c5ad87a 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -123,6 +123,7 @@ public: int op_declared (const char* op) const; int decl_name_map(const RadNameMap* m); int declare_logits(rad_buf b); + int declare_scores(rad_buf hidden, rad_weight table); int declare_pooled(rad_buf b); int declare_plugin_words(int64_t max_words); int declare_drafter(const RadDrafterDecl* d); @@ -131,6 +132,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 e7d78b39..b7f3983f 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1134,6 +1134,30 @@ int Builder::decl_name_map(const RadNameMap* m) { /* The buffer the core samples from. A second call is refused rather than winning: a target and * its drafter declaring into one builder (spec §10) both have logits, and keeping the second would * sample the draft distribution. The drafter's logits are reached through its scope. */ +int Builder::declare_scores(rad_buf hidden, rad_weight table) { + if (finished_) { err(RAD_E_STATE, "declare_scores after declare finished"); return RAD_E_STATE; } + if (hidden == RAD_NULL_HANDLE || (size_t)hidden >= prog_.buffers.size()) { + err(RAD_E_INVAL, "declare_scores: %u is not a declared buffer", (unsigned)hidden); + return RAD_E_INVAL; + } + if (table == RAD_NULL_HANDLE || (size_t)table >= prog_.weights.size()) { + err(RAD_E_INVAL, "declare_scores: %u is not a declared weight", (unsigned)table); + return RAD_E_INVAL; + } + const RadBufDecl& h = prog_.buffers[hidden].decl; + const auto& w = prog_.weights[table]; + if (h.dtype != RAD_BF16 || h.rank != 2 || w.decl.dtype != RAD_BF16 || w.decl.rank != 2 || + w.decl.shape[1] != h.shape[1]) { + err(RAD_E_INVAL, "declare_scores: the hidden rows ('%s') and the table ('%s') must be bf16 " + "[rows, n_embd] and [n_vocab, n_embd]", prog_.buffers[hidden].name.c_str(), + w.name.c_str()); + return RAD_E_INVAL; + } + prog_.score_hidden = hidden; + prog_.score_table = table; + return RAD_OK; +} + int Builder::declare_logits(rad_buf b) { if (finished_) { err(RAD_E_STATE, "declare_logits after declare finished"); return RAD_E_STATE; } if (b == RAD_NULL_HANDLE || (size_t)b >= prog_.buffers.size()) { @@ -1943,7 +1967,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).", @@ -2077,17 +2104,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); @@ -2442,6 +2500,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(); @@ -2599,6 +2667,11 @@ int rad_declare_logits(RadBuilder* b, rad_buf logits) { return B(b)->declare_logits(logits); } +int rad_declare_scores(RadBuilder* b, rad_buf hidden, rad_weight table) { + if (!b) return RAD_E_INVAL; + return B(b)->declare_scores(hidden, table); +} + int rad_declare_pooled(RadBuilder* b, rad_buf pooled) { if (!b) return RAD_E_INVAL; return B(b)->declare_pooled(pooled); @@ -2630,6 +2703,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/rad_graph.cpp b/core/build/rad_graph.cpp index 5ed7e372..0b0b7d2c 100644 --- a/core/build/rad_graph.cpp +++ b/core/build/rad_graph.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -650,7 +651,9 @@ std::string dump_graph_json(const Program& p) { j["geometry"] = o.base.str(); j["ranged"] = o.ranged_key; if (!o.ranged_key.empty()) { j["range_lo"] = o.range_lo; j["range_hi"] = o.range_hi; } - j["issued"] = o.issued; + /* Read through an atomic_ref: the step path stores this flag from the engine thread + * (Ctx::flush_issued); a plain read here would race it. */ + j["issued"] = std::atomic_ref(o.issued).load(std::memory_order_relaxed); j["schema"] = schema_json(o.schema ? o.schema : reg.schema(o.op)); json ws = json::array(); 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..d9bf217f 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; @@ -751,7 +769,14 @@ int config_parse(int argc, char** argv, Config* c) { } else if (S("--host")) { if (!(v = need(i))) return RAD_E_INVAL; c->host = v; } else if (S("--port")) { if (!num(0, 65535, &c->port)) return RAD_E_INVAL; } - else if (S("--api-key")) { if (!(v = need(i))) return RAD_E_INVAL; c->api_key = v; } + else if (S("--api-key")) { + if (!(v = need(i))) return RAD_E_INVAL; + /* An empty key is no key: --api-key "" or --api-key "$UNSET_VAR" must not start a + * server that looks guarded and answers everything keyless. */ + if (!*v) { RAD_ERR("--api-key takes a non-empty key; an empty value guards nothing"); + return RAD_E_INVAL; } + c->api_key = v; + } else if (S("--served-model-name")) { if (!(v = need(i))) return RAD_E_INVAL; if (!*v) { RAD_ERR("--served-model-name takes a non-empty name"); return RAD_E_INVAL; } @@ -1166,7 +1191,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 +1229,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 cda687d8..e0e30e32 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -110,6 +110,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(); } @@ -554,6 +556,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). */ @@ -789,46 +799,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); } @@ -903,6 +878,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); } @@ -1165,6 +1141,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; @@ -1172,6 +1199,8 @@ int Engine::collect_pooled(const RadBatch* b, StepOut& so) { * row is copied (512 KB at a 128K vocabulary), which is cheaper than one copy per id. */ int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) { score_rows_.clear(); + score_only_ = false; + score_ids_.clear(); if (embedding_) return RAD_OK; for (size_t i = 0; i < plan.e.size(); ++i) { const Request* r = plan.e[i].req; @@ -1180,16 +1209,35 @@ int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) { } if (score_rows_.empty()) return RAD_OK; const int64_t n = (int64_t)score_rows_.size(); + + /* A scored step reads back the hidden rows and the candidates' table rows instead of whole + * logits rows (BatchBuilder set the flag on the same facts). */ + const RadBatch* b0 = sched_.batch_for(0); + score_only_ = b0 && b0->score_only; + if (score_only_) { + const Program& p = ranks_[0]->program; + score_embd_ = p.buffers[p.score_hidden].decl.shape[1]; + for (const auto& sr : score_rows_) + for (int32_t t : sr.second->tokens) score_ids_.push_back(t); + std::sort(score_ids_.begin(), score_ids_.end()); + score_ids_.erase(std::unique(score_ids_.begin(), score_ids_.end()), score_ids_.end()); + } for (auto& rk : ranks_) { - if (n <= rk->score_rows_cap) continue; + const int64_t width = rk->sampler.config().n_vocab_local; + /* In floats: n logits rows, or the bf16 hidden and table rows of a scored step. */ + int64_t rows = n; + if (score_only_) { + const int64_t need = ((n + (int64_t)score_ids_.size()) * score_embd_ + 1) / 2; + rows = std::max(rows, (need + width - 1) / width); + } + if (rows <= rk->score_rows_cap) continue; if (ranks_.size() > 1) RAD_TRY(rad_dev_set(rk->device)); if (rk->score_host) rad_dev_free(rk->score_host, RAD_MEM_HOST_PINNED); - const int64_t width = rk->sampler.config().n_vocab_local; rk->score_host = static_cast( - rad_dev_alloc(n * width * (int64_t)sizeof(float), RAD_MEM_HOST_PINNED)); - rk->score_rows_cap = rk->score_host ? n : 0; + rad_dev_alloc(rows * width * (int64_t)sizeof(float), RAD_MEM_HOST_PINNED)); + rk->score_rows_cap = rk->score_host ? rows : 0; if (!rk->score_host) { - RAD_ERR("scored rows: no pinned memory for %lld logits rows", (long long)n); + RAD_ERR("scored rows: no pinned memory for %lld logits rows", (long long)rows); return RAD_E_NOMEM; } } @@ -1199,8 +1247,27 @@ int Engine::stage_scored_rows(const StepPlan& plan, const StepOut& so) { int Engine::issue_scored_rows(Rank& r) { const int64_t width = r.sampler.config().n_vocab_local; - const char* logits = static_cast(r.ctx.buf_ptr(r.program.logits_buf)); + char* const logits = static_cast(r.ctx.buf_ptr(r.program.logits_buf)); if (!logits || !r.score_host) return RAD_E_STATE; + if (score_only_) { + /* The plugin left the hidden rows and ran no lm_head: read back each scored row's hidden + * state and the table rows its candidates name, then zero the logits rows the sampler is + * about to read, so the token it draws (and the caller discards) is drawn from defined + * values. One rank (BatchBuilder). */ + const int64_t rb = score_embd_ * (int64_t)sizeof(uint16_t); + const char* hid = static_cast(r.ctx.buf_ptr(r.program.score_hidden)); + const char* tab = static_cast(r.ctx.weight_ptr(r.program.score_table)); + if (!hid || !tab) return RAD_E_STATE; + char* host = reinterpret_cast(r.score_host); + const int64_t n = (int64_t)score_rows_.size(); + for (int64_t k = 0; k < n; ++k) + RAD_TRY(rad_memcpy_async(host + k * rb, hid + (int64_t)score_rows_[(size_t)k].first * rb, + rb, r.ctx.stream())); + for (size_t j = 0; j < score_ids_.size(); ++j) + RAD_TRY(rad_memcpy_async(host + (n + (int64_t)j) * rb, tab + (int64_t)score_ids_[j] * rb, + rb, r.ctx.stream())); + return rad_memset_async(logits, 0, n * width * (int64_t)sizeof(float), r.ctx.stream()); + } for (size_t k = 0; k < score_rows_.size(); ++k) RAD_TRY(rad_memcpy_async(r.score_host + (int64_t)k * width, logits + (int64_t)score_rows_[k].first * width * 4, @@ -1208,6 +1275,18 @@ int Engine::issue_scored_rows(Rank& r) { return RAD_OK; } +/* A scored step's logits: the dot product of a row's hidden state with each candidate's table row, + * bf16 operands widened exactly and summed in f64, then rounded once to f32. */ +static float score_dot(const uint16_t* h, const uint16_t* w, int64_t n) { + double acc = 0.0; + for (int64_t i = 0; i < n; ++i) { + const float a = __builtin_bit_cast(float, (uint32_t)h[i] << 16); + const float b = __builtin_bit_cast(float, (uint32_t)w[i] << 16); + acc += (double)a * (double)b; + } + return (float)acc; +} + int Engine::collect_scored_rows() { if (score_rows_.empty()) return RAD_OK; /* collect_step's wait fences rank 0's stream; every other rank's copies are fenced here. */ @@ -1216,6 +1295,23 @@ int Engine::collect_scored_rows() { RAD_TRY(rad_stream_sync(ranks_[i]->ctx.stream())); } if (ranks_.size() > 1) RAD_TRY(rad_dev_set(ranks_[0]->device)); + if (score_only_) { + const uint16_t* host = reinterpret_cast(ranks_[0]->score_host); + const int64_t n = (int64_t)score_rows_.size(); + for (int64_t k = 0; k < n; ++k) { + TokenScores& ts = *score_rows_[(size_t)k].second; + ts.logits.assign(ts.tokens.size(), 0.0f); + for (size_t j = 0; j < ts.tokens.size(); ++j) { + const auto it = std::lower_bound(score_ids_.begin(), score_ids_.end(), ts.tokens[j]); + const int64_t c = it - score_ids_.begin(); + ts.logits[j] = score_dot(host + k * score_embd_, host + (n + c) * score_embd_, + score_embd_); + } + } + score_rows_.clear(); + score_only_ = false; + return RAD_OK; + } for (size_t k = 0; k < score_rows_.size(); ++k) { TokenScores& ts = *score_rows_[k].second; ts.logits.assign(ts.tokens.size(), 0.0f); @@ -1236,10 +1332,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; @@ -1253,6 +1350,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); @@ -1303,7 +1401,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 @@ -1314,11 +1421,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) @@ -2275,8 +2390,8 @@ int Engine::run_server() { s.experts.n_experts = n_expert; s.experts.tier.assign((size_t)n_layer * (size_t)n_expert, (uint8_t)Tier::VRAM); /* The live tier when the heat engine runs, else the plan's (where a unit started). - * HeatEngine::tier is a plain vector written by the dispatch thread at step - * boundaries, so a racing read sees either side of a single store. */ + * tier_published is the HTTP-readable mirror HeatEngine::set_tier keeps; reading + * the dispatch thread's own tier_ here would be a data race. */ const HeatEngine& heat = ranks_[0]->heat; const bool live_tier = heat.enabled(); s.experts.heat_enabled = live_tier; @@ -2285,7 +2400,7 @@ int Engine::run_server() { for (size_t u = 0; u < p.units.size(); ++u) { const MoveUnit& mu = p.units[u]; if (mu.expert < 0 || mu.layer < 0) continue; - const Tier t = live_tier ? heat.tier((int32_t)u) : mu.tier; + const Tier t = live_tier ? heat.tier_published((int32_t)u) : mu.tier; s.experts.tier[(size_t)mu.layer * (size_t)n_expert + (size_t)mu.expert] = (uint8_t)t; /* Count residency over units, not plane cells: the plane is a rectangle a @@ -2352,6 +2467,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; @@ -2363,6 +2484,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..e9038283 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_`, @@ -308,6 +315,12 @@ private: * Written by the scheduler thread while the ranks are parked, read by them during the step, * consumed by collect_step. */ std::vector> score_rows_; + /* A scored step (RadBatch::score_only): the plugin ran no lm_head, and the candidates' logits + * come from the hidden rows and the head table's rows at `score_ids_` (every scored row's + * candidates, sorted and unique), both read back into `score_host`. */ + bool score_only_ = false; + std::vector score_ids_; + int64_t score_embd_ = 0; int stage_scored_rows(const StepPlan& plan, const StepOut& so); int issue_scored_rows(Rank& r); int collect_scored_rows(); @@ -341,7 +354,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 +390,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 +492,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 c28fa5a8..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(); @@ -3087,22 +3210,50 @@ int Engine::size_checkpoint_store(int64_t slot, const char* what) { int64_t still = cfg_.prefix_cache_mib * ((int64_t)1 << 20); for (const auto& r : ranks_) still += arena_host_bytes(r->program); - std::string limit; - int64_t room = lockable_bytes(still, host_headroom_bytes(), &limit); - if (!device_is_host()) { - bool lifted = false; - if (const int64_t cap = amdgpu_pin_cap(&lifted); cap > 0) { - int64_t pinned = 0, mapped = 0; - rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr); - rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr); - const int64_t left = std::max(cap - pinned - mapped - still, 0); - if (left < room) { - room = left; - limit = fmt("the amdgpu driver's pin cap of %s, of which this process holds %s " - "and still pins %s", humanb(cap).c_str(), - humanb(pinned + mapped).c_str(), humanb(still).c_str()); + /* The fewest snapshots the store means to hold, in bytes: the count below which prefix reuse + * is not worth the pinning. It is what the reserve below must not decide away, and it scales + * with the model's own state -- any hybrid's linear layers, any KV encoding's mirror -- since + * it is measured from this rank's slot and the host's own spare memory. */ + const int64_t floor_slots = + std::min(checkpoint_slots_want(*pol, cfg_.max_seqs, ctx, interval), + kCheckpointSlotsFloor); + const int64_t floor_bytes = + slot > INT64_MAX / std::max(floor_slots, 1) ? INT64_MAX : floor_slots * slot; + const int64_t asked = host_headroom_bytes(); + int64_t margin = asked; + std::string limit, gave_way; + /* What the host can pin with `marg` held free: spare memory (MemAvailable and every memory + * cgroup), then the driver's own pin cap. Both are the host's own measurement, so a wider + * mirror, a bigger pool or a larger slot never needs a second rule here. */ + auto room_with = [&](int64_t marg, std::string* why) { + int64_t r = lockable_bytes(still, marg, why); + if (!device_is_host()) { + bool lifted = false; + if (const int64_t cap = amdgpu_pin_cap(&lifted); cap > 0) { + int64_t pinned = 0, mapped = 0; + rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr); + rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr); + const int64_t left = std::max(cap - pinned - mapped - still, 0); + if (left < r) { + r = left; + *why = fmt("the amdgpu driver's pin cap of %s, of which this process holds %s " + "and still pins %s", humanb(cap).c_str(), + humanb(pinned + mapped).c_str(), humanb(still).c_str()); + } } } + return r; + }; + int64_t room = room_with(margin, &limit); + if (const int64_t keep = host_reserve_for_floor(floor_bytes, room, margin); keep < margin) { + /* The host has the bytes, but the reserve stood between them and a store that works. + * Take back exactly the shortfall and say so; a host that cannot pin the floor even + * then still gets the honest warning below. */ + const int64_t wider = room_with(keep, &limit); + gave_way = fmt("; the host reserve gave back %s of its %s for the floor of %lld " + "snapshot(s), holding %s", humanb(margin - keep).c_str(), + humanb(asked).c_str(), (long long)floor_slots, humanb(keep).c_str()); + room = wider; } const int64_t total = meminfo_bytes("MemTotal"); const int64_t share = total > 0 ? total / 8 : room; @@ -3122,19 +3273,19 @@ int Engine::size_checkpoint_store(int64_t slot, const char* what) { else if (c.bound == CheckpointSlots::Bound::Room) bound = fmt("; %lld wanted, held to what the host can pin: %s", (long long)c.want, limit.c_str()); - decide("--checkpoint-slots", std::to_string(c.slots), need + bound); + decide("--checkpoint-slots", std::to_string(c.slots), need + bound + gave_way); if (c.slots == 0) { - RAD_WARN("checkpoint slots: auto finds no room for one %s snapshot of %s (%s), so every " - "prefix hit on this model prefills from the start. Free host memory, or lower " - "--host-pool-mib or --prefix-cache-mib", what, humanb(slot).c_str(), - limit.c_str()); + RAD_WARN("checkpoint slots: the host cannot pin one %s snapshot of %s: %s%s. Every prefix " + "hit on this model prefills from the start. Free host memory, or lower " + "--host-pool-mib, --prefix-cache-mib or --host-headroom-mib", what, + humanb(slot).c_str(), limit.c_str(), gave_way.c_str()); return RAD_OK; } const std::string line = fmt("checkpoint slots: auto: %lld %s snapshot(s) of %s in pinned host memory (%s), none of " - "it on the card; %s%s", (long long)c.slots, what, humanb(slot).c_str(), - humanb(slot * c.slots).c_str(), need.c_str(), bound.c_str()); - if (c.bound == CheckpointSlots::Bound::Room) RAD_WARN("%s", line.c_str()); + "it on the card; %s%s%s", (long long)c.slots, what, humanb(slot).c_str(), + humanb(slot * c.slots).c_str(), need.c_str(), bound.c_str(), gave_way.c_str()); + if (c.slots < floor_slots || c.bound == CheckpointSlots::Bound::Room) RAD_WARN("%s", line.c_str()); else RAD_INFO("%s", line.c_str()); return RAD_OK; } @@ -3167,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. */ @@ -3238,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" @@ -3265,7 +3419,14 @@ int Engine::configure_kv() { }; if (!sized) return refuse("no host has"); std::string why; - if (!lockable_room(slot * n, 0, host_headroom_bytes(), false, &why)) + /* The same reserve rule the sizing used, or a count that auto could fit by giving the + * reserve back would be refused a few lines after it was chosen. */ + std::string guard_why; + const int64_t want_bytes = slot * n; + const int64_t marg = host_reserve_for_floor( + want_bytes, lockable_bytes(0, host_headroom_bytes(), &guard_why), + host_headroom_bytes()); + if (!lockable_room(want_bytes, 0, marg, false, &why)) return refuse("does not fit: " + why); if (ck_store_.open(slot, slot * n) != RAD_OK) return refuse(std::string("the host did not pin: ") + rad_dev_last_error()); 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..2841afad 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; } @@ -984,6 +988,36 @@ bool KVManager::can_ever_fit(int64_t n_tokens) const { return true; } +/* Read-only counterpart of ensure(): can `seq` grow to n_tokens without taking blocks from + * another sequence? Used by the scheduler's preempted-prefill admission gate, which must not + * reserve anything or it would perturb the very pool it is trying to protect. */ +bool KVManager::can_grow(uint64_t id, int64_t n_tokens) const { + const Seq* s = find(id); + if (!s) return false; + if (n_tokens <= s->n_tokens) return true; + for (size_t g = 0; g < plans_.size(); ++g) { + const auto& p = plans_[g]; + if (p.paged()) { + const int64_t first = s->first_block_pos[g] / p.block_size; + const int64_t want = ceil_div(n_tokens, p.block_size) - first; + int64_t need = want - (int64_t)s->blocks[g].size(); + if (need < 0) need = 0; + /* ensure() takes one copy-on-write block for a partially filled block; include it + * here so the gate does not admit a sequence that then has to steal from another. */ + if (s->n_tokens > 0 && s->n_tokens % p.block_size != 0) { + const int64_t bi = s->n_tokens / p.block_size - first; + if (bi >= 0 && bi < (int64_t)s->blocks[g].size() && + refcount_[g][(size_t)s->blocks[g][(size_t)bi]] > 1) + ++need; + } + if (need > available_blocks((int32_t)g)) return false; + } else if (p.stateful() && s->state[g] < 0) { + if (free_states_[g].empty()) return false; + } + } + return true; +} + /* ------------------------------------------------------------------ sequences */ KVManager::Seq* KVManager::find(uint64_t s) { diff --git a/core/mem/kv.h b/core/mem/kv.h index 2f9128d3..1c7a93a6 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(). */ @@ -437,6 +451,12 @@ public: * the request is failed rather than deadlocking the engine (spec §17). */ bool can_ever_fit(int64_t n_tokens) const; + /* Whether `seq` can grow to `n_tokens` without taking blocks from another sequence. */ + bool can_grow(uint64_t seq, int64_t n_tokens) const; + + /* Blocks a paged group can still hand out, including the lendable part. */ + int64_t available_blocks(int32_t group) const; + /* ---------------- the loan ---------------- * * The paged groups lend unheld blocks to the expert slab in place. The carve fixes and backs @@ -668,6 +688,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 */ @@ -707,8 +728,6 @@ private: std::vector bucket_blocks_; /* per group: blocks one held_hist_ bucket covers */ std::vector> held_hist_; /* per group, per bucket: held blocks */ - int64_t available_blocks(int32_t g) const; - /* The buffer this group wants in hand, in blocks. See buffer_bytes(). */ int64_t buf_blocks(size_t i) const; /* One past the highest held block, rounded up to a bucket. */ int64_t held_top(size_t i) const; diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index d73906c7..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 { @@ -122,8 +128,7 @@ CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t ma int64_t share_bytes, int64_t room_bytes) { CheckpointSlots c; c.per_seq = policy.held(ctx, interval) + 1; - const int64_t seqs = std::max(max_seqs, 1); - c.want = seqs > INT64_MAX / c.per_seq ? INT64_MAX : seqs * c.per_seq; + c.want = checkpoint_slots_want(policy, max_seqs, ctx, interval); if (slot_bytes <= 0) return c; const int64_t share = std::max(share_bytes, 0) / slot_bytes; const int64_t room = std::max(room_bytes, 0) / slot_bytes; @@ -136,6 +141,24 @@ CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t ma return c; } +int64_t checkpoint_slots_want(const CheckpointPolicy& policy, int64_t max_seqs, int64_t ctx, + int64_t interval) { + const int64_t per = policy.held(ctx, interval) + 1; + const int64_t seqs = std::max(max_seqs, 1); + return seqs > INT64_MAX / per ? INT64_MAX : seqs * per; +} + +int64_t host_reserve_for_floor(int64_t need_bytes, int64_t room_bytes, int64_t margin_bytes) { + if (need_bytes <= 0 || margin_bytes <= 0 || room_bytes >= need_bytes) return margin_bytes; + /* Whole MiB, the unit --host-headroom-mib takes, and the shortfall rounding up: the reserve + * gives back at least what the floor asked for, so the store is never a byte short of it. */ + const int64_t mib = (int64_t)1 << 20; + const int64_t shortfall = (need_bytes - room_bytes + mib - 1) / mib; + const int64_t margin = margin_bytes / mib; + const int64_t keep = margin - shortfall; + return std::min(margin, std::max(kHostReserveFloor / mib, keep)) * mib; +} + /* ------------------------------------------------------------------ configure */ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval) { @@ -151,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; @@ -160,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) @@ -250,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 792dc7a3..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: @@ -174,6 +184,9 @@ std::unique_ptr make_checkpoint_policy(const std::string& name * the room is a hard bound. */ constexpr int64_t kCheckpointSlotsFloor = 8; +/* The least --host-headroom-mib is reduced to for a store's floor (host_reserve_for_floor). */ +constexpr int64_t kHostReserveFloor = (int64_t)1 << 30; + struct CheckpointSlots { int64_t per_seq = 0; /* snapshots a sequence is given */ int64_t want = 0; /* --max-num-seqs x per_seq */ @@ -181,10 +194,28 @@ struct CheckpointSlots { enum class Bound { Want, Share, Room } bound = Bound::Want; }; +/* What --checkpoint-slots auto wants before any byte budget applies: the policy's hold for one + * --max-model-len session plus one for its running turn, for each of --max-num-seqs. */ +int64_t checkpoint_slots_want(const CheckpointPolicy& policy, int64_t max_seqs, int64_t ctx, + int64_t interval); + CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t max_seqs, int64_t ctx, int64_t interval, int64_t slot_bytes, int64_t share_bytes, int64_t room_bytes); +/* The reserve to charge a store whose floor `need_bytes` must fit. `room_bytes` is what the host + * can pin with `margin_bytes` (--host-headroom-mib) held free; it is what the engine measures, not + * what a model or a KV encoding is assumed to cost. + * + * The reserve is a courtesy to the system -- the process's unpooled allocations, the load's + * staging windows, the page cache -- and a store that turns prefix reuse on or off outranks it: a + * store too small for one snapshot re-prefills the whole conversation on every turn, while the + * reserve it displaced is memory the host would merely have kept. So the reserve gives back + * exactly the shortfall, never below kHostReserveFloor, and never above the margin asked for. + * It answers `margin_bytes` unchanged whenever the floor already fits, so a host with room to + * spare never sees the reserve move. */ +int64_t host_reserve_for_floor(int64_t need_bytes, int64_t room_bytes, int64_t margin_bytes); + /* ------------------------------------------------------------------ a release */ /* What PrefixCache::release_session took out and what it left. Blocks are left for three * reasons, counted apart so a caller can tell a half-shared conversation from a busy one: the @@ -234,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 ---------------- */ @@ -424,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; @@ -530,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.cpp b/core/place/heat.cpp index 301cbde0..f1b2b764 100644 --- a/core/place/heat.cpp +++ b/core/place/heat.cpp @@ -16,10 +16,11 @@ constexpr int32_t kBlock = 64; int HeatEngine::init(const Plan& plan, const HeatParams& params) { params_ = params; - stats_ = HeatStats{}; + stats_.reset(); const size_t n = plan.units.size(); tier_.assign(n, Tier::VRAM); + tier_pub_.assign(n); busy_.assign(n, 0u); movable_.assign(n, 0u); pinned_.assign(n, 0u); @@ -59,6 +60,7 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) { for (size_t u = 0; u < n; ++u) { const MoveUnit& mu = plan.units[u]; tier_[u] = mu.tier; + tier_pub_.set(u, (uint8_t)mu.tier); layer_of_[u] = mu.layer; bytes_[u] = mu.bytes; movable_[u] = mu.movable ? 1u : 0u; @@ -259,6 +261,7 @@ void HeatEngine::set_tier(int32_t unit, Tier t) { else if (was != Tier::VRAM && t == Tier::VRAM) ++res_count_[(size_t)l]; } tier_[(size_t)unit] = t; + tier_pub_.set((size_t)unit, (uint8_t)t); set_place(unit); end_invalidate(unit); diff --git a/core/place/heat.h b/core/place/heat.h index 16c95adf..f57eff5a 100644 --- a/core/place/heat.h +++ b/core/place/heat.h @@ -31,6 +31,8 @@ #include "planner.h" #include +#include +#include #include namespace rad { @@ -111,6 +113,100 @@ struct HeatStats { uint64_t routed = 0, routed_resident = 0, stream_bytes = 0; }; +/* The live twin of HeatStats: every counter an atomic, so the HTTP thread's /stats and LiveView + * reads are relaxed loads beside the dispatch thread's writes rather than a data race. Written + * as plain counters are (++ and +=), read through snapshot(). See MoverCounters, same reasoning. + */ +struct HeatCounters { + std::atomic dispatches{0}; + std::atomic proposed{0}, promotions{0}, demotions{0}; + std::atomic refused{0}, no_candidate{0}; + std::atomic distinct_promoted{0}, readmits{0}; + std::atomic routed{0}, routed_resident{0}, stream_bytes{0}; + + /* HeatEngine is copyable — place_test snapshots engines — so its counters must copy too. + * A copy takes the current values: relaxed loads into the copy's own atomics. */ + HeatCounters() = default; + HeatCounters(const HeatCounters& o) { *this = o; } + HeatCounters& operator=(const HeatCounters& o) { + dispatches.store(o.dispatches.load(std::memory_order_relaxed), std::memory_order_relaxed); + proposed.store(o.proposed.load(std::memory_order_relaxed), std::memory_order_relaxed); + promotions.store(o.promotions.load(std::memory_order_relaxed), std::memory_order_relaxed); + demotions.store(o.demotions.load(std::memory_order_relaxed), std::memory_order_relaxed); + refused.store(o.refused.load(std::memory_order_relaxed), std::memory_order_relaxed); + no_candidate.store(o.no_candidate.load(std::memory_order_relaxed), + std::memory_order_relaxed); + distinct_promoted.store(o.distinct_promoted.load(std::memory_order_relaxed), + std::memory_order_relaxed); + readmits.store(o.readmits.load(std::memory_order_relaxed), std::memory_order_relaxed); + routed.store(o.routed.load(std::memory_order_relaxed), std::memory_order_relaxed); + routed_resident.store(o.routed_resident.load(std::memory_order_relaxed), + std::memory_order_relaxed); + stream_bytes.store(o.stream_bytes.load(std::memory_order_relaxed), + std::memory_order_relaxed); + return *this; + } + + void reset() { + /* Field by field: atomics are not copy-assignable. */ + dispatches.store(0, std::memory_order_relaxed); + proposed.store(0, std::memory_order_relaxed); + promotions.store(0, std::memory_order_relaxed); + demotions.store(0, std::memory_order_relaxed); + refused.store(0, std::memory_order_relaxed); + no_candidate.store(0, std::memory_order_relaxed); + distinct_promoted.store(0, std::memory_order_relaxed); + readmits.store(0, std::memory_order_relaxed); + routed.store(0, std::memory_order_relaxed); + routed_resident.store(0, std::memory_order_relaxed); + stream_bytes.store(0, std::memory_order_relaxed); + } + + HeatStats snapshot() const { + HeatStats s; + s.dispatches = dispatches.load(std::memory_order_relaxed); + s.proposed = proposed.load(std::memory_order_relaxed); + s.promotions = promotions.load(std::memory_order_relaxed); + s.demotions = demotions.load(std::memory_order_relaxed); + s.refused = refused.load(std::memory_order_relaxed); + s.no_candidate = no_candidate.load(std::memory_order_relaxed); + s.distinct_promoted = distinct_promoted.load(std::memory_order_relaxed); + s.readmits = readmits.load(std::memory_order_relaxed); + s.routed = routed.load(std::memory_order_relaxed); + s.routed_resident = routed_resident.load(std::memory_order_relaxed); + s.stream_bytes = stream_bytes.load(std::memory_order_relaxed); + return s; + } +}; + +/* The per-unit tier mirror HeatEngine keeps for the HTTP thread: one relaxed atomic byte per + * unit, written by set_tier and read by tier_published. A type of its own because it must be + * copyable — HeatEngine is copyable, and a copy takes the tier values into an array of its + * own — which a bare unique_ptr of atomics is not. */ +struct TierMirror { + std::unique_ptr[]> a; + size_t n = 0; + + void assign(size_t m) { + n = m; + a.reset(m ? new std::atomic[m] : nullptr); + } + void set(size_t i, uint8_t v) const { a[i].store(v, std::memory_order_relaxed); } + uint8_t get(size_t i) const { return a[i].load(std::memory_order_relaxed); } + + TierMirror() = default; + TierMirror(const TierMirror& o) { + assign(o.n); + for (size_t i = 0; i < n; ++i) set(i, o.get(i)); + } + TierMirror& operator=(const TierMirror& o) { + if (this == &o) return *this; + assign(o.n); + for (size_t i = 0; i < n; ++i) set(i, o.get(i)); + return *this; + } +}; + class HeatEngine { public: /* Binds to the plan. A static plan is a mode, not a failure: init returns RAD_OK and @@ -145,6 +241,12 @@ public: void set_tier(int32_t unit, Tier t); void set_busy(int32_t unit, bool busy); Tier tier(int32_t unit) const { return tier_[(size_t)unit]; } + /* The tier as the HTTP thread may safely read it: set_tier mirrors every change into a + * relaxed atomic, and /stats and LiveView read the mirror. tier_ itself belongs to the + * dispatch thread; reading it from another thread mid-step is a data race. */ + Tier tier_published(int32_t unit) const { + return (Tier)tier_pub_.get((size_t)unit); + } bool busy(int32_t unit) const { return busy_[(size_t)unit] != 0; } /* The best swap available, or false when the guards refuse. */ @@ -165,7 +267,9 @@ public: const int32_t l = (size_t)unit < layer_of_.size() ? layer_of_[(size_t)unit] : -1; return l >= 0 && (size_t)l < res_count_.size() ? res_count_[(size_t)l] : 0; } - const HeatStats& stats() const { return stats_; } + /* A snapshot by value: the counters are atomics read while the dispatch thread writes them. + * Engine-internal decisions must use the individual counters (`warm`), not a snapshot. */ + HeatStats stats() const { return stats_.snapshot(); } /* Exit banner, ending with the per-layer resident counts, which show whether every layer kept * its share of slots. */ @@ -175,7 +279,7 @@ private: HeatParams params_; bool enabled_ = false; int32_t n_layer_ = 0; - HeatStats stats_; + HeatCounters stats_; /* Heat by position, not by unit. Each layer owns a run of positions whose front is indexed by * expert: expert e of layer l is at slot_lo_[l] + e, whether or not the plan has a unit for it @@ -208,10 +312,14 @@ private: /* Unit bytes from the plan, so a miss is priced where it is detected. */ std::vector bytes_; std::vector tier_; + /* Per unit, the tier as a relaxed atomic mirror, for the HTTP thread's reads (tier_published + * reads, set_tier and init write). Sized with tier_; element type uint8_t to keep the read + * lock-free and the mirror one byte per unit. */ + TierMirror tier_pub_; 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/mover.cpp b/core/place/mover.cpp index ea1043d3..f2aa60db 100644 --- a/core/place/mover.cpp +++ b/core/place/mover.cpp @@ -111,7 +111,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P plan_ = &plan; cfg_ = cfg; budget_ = budget; - stats_ = MoverStats{}; + stats_.reset(); if (!budget_) RAD_WARN("mover: no Pools given; allocating the slab and host pool directly (test only)"); diff --git a/core/place/mover.h b/core/place/mover.h index aff35c53..59f75059 100644 --- a/core/place/mover.h +++ b/core/place/mover.h @@ -349,6 +349,93 @@ struct MoverStats { uint64_t file_read_ns = 0, file_wait_ns = 0; }; +/* The live twin of MoverStats: every counter an atomic. The mover writes these through the + * step on its rank thread while the HTTP thread reads them for /stats and LiveView, and reading + * a plain field another thread writes is a data race (UB). Relaxed atomics give exactly the + * "either side of a store" telemetry promises, at no cost on the writer. snapshot() loads them + * all into a plain MoverStats; same reasoning that made flex_used_ atomic, for the same reader. + */ +struct MoverCounters { + std::atomic dispatches{0}; + std::atomic promotions{0}, demotions{0}; + std::atomic h2d_bytes{0}, d2h_bytes{0}; + std::atomic prefetched{0}, prefetch_bytes{0}; + std::atomic no_record{0}, starved_slab{0}, starved_pool{0}; + std::atomic quarantined{0}; + std::atomic dropped{0}; + std::atomic donated{0}, relocated{0}, stranded{0}; + std::atomic ssd_reads{0}, ssd_bytes{0}; + std::atomic stage_layers{0}, staged_units{0}, staged_bytes{0}, stage_overflow{0}; + std::atomic stage_copies{0}; + std::atomic file_layers{0}, file_units{0}, file_bytes{0}, file_preads{0}; + std::atomic file_read_ns{0}, file_wait_ns{0}; + + void reset() { + /* Field by field: atomics are not copy-assignable. */ + dispatches.store(0, std::memory_order_relaxed); + promotions.store(0, std::memory_order_relaxed); + demotions.store(0, std::memory_order_relaxed); + h2d_bytes.store(0, std::memory_order_relaxed); + d2h_bytes.store(0, std::memory_order_relaxed); + prefetched.store(0, std::memory_order_relaxed); + prefetch_bytes.store(0, std::memory_order_relaxed); + no_record.store(0, std::memory_order_relaxed); + starved_slab.store(0, std::memory_order_relaxed); + starved_pool.store(0, std::memory_order_relaxed); + quarantined.store(0, std::memory_order_relaxed); + dropped.store(0, std::memory_order_relaxed); + donated.store(0, std::memory_order_relaxed); + relocated.store(0, std::memory_order_relaxed); + stranded.store(0, std::memory_order_relaxed); + ssd_reads.store(0, std::memory_order_relaxed); + ssd_bytes.store(0, std::memory_order_relaxed); + stage_layers.store(0, std::memory_order_relaxed); + staged_units.store(0, std::memory_order_relaxed); + staged_bytes.store(0, std::memory_order_relaxed); + stage_overflow.store(0, std::memory_order_relaxed); + stage_copies.store(0, std::memory_order_relaxed); + file_layers.store(0, std::memory_order_relaxed); + file_units.store(0, std::memory_order_relaxed); + file_bytes.store(0, std::memory_order_relaxed); + file_preads.store(0, std::memory_order_relaxed); + file_read_ns.store(0, std::memory_order_relaxed); + file_wait_ns.store(0, std::memory_order_relaxed); + } + + MoverStats snapshot() const { + MoverStats s; + s.dispatches = dispatches.load(std::memory_order_relaxed); + s.promotions = promotions.load(std::memory_order_relaxed); + s.demotions = demotions.load(std::memory_order_relaxed); + s.h2d_bytes = h2d_bytes.load(std::memory_order_relaxed); + s.d2h_bytes = d2h_bytes.load(std::memory_order_relaxed); + s.prefetched = prefetched.load(std::memory_order_relaxed); + s.prefetch_bytes = prefetch_bytes.load(std::memory_order_relaxed); + s.no_record = no_record.load(std::memory_order_relaxed); + s.starved_slab = starved_slab.load(std::memory_order_relaxed); + s.starved_pool = starved_pool.load(std::memory_order_relaxed); + s.quarantined = quarantined.load(std::memory_order_relaxed); + s.dropped = dropped.load(std::memory_order_relaxed); + s.donated = donated.load(std::memory_order_relaxed); + s.relocated = relocated.load(std::memory_order_relaxed); + s.stranded = stranded.load(std::memory_order_relaxed); + s.ssd_reads = ssd_reads.load(std::memory_order_relaxed); + s.ssd_bytes = ssd_bytes.load(std::memory_order_relaxed); + s.stage_layers = stage_layers.load(std::memory_order_relaxed); + s.staged_units = staged_units.load(std::memory_order_relaxed); + s.staged_bytes = staged_bytes.load(std::memory_order_relaxed); + s.stage_overflow = stage_overflow.load(std::memory_order_relaxed); + s.stage_copies = stage_copies.load(std::memory_order_relaxed); + s.file_layers = file_layers.load(std::memory_order_relaxed); + s.file_units = file_units.load(std::memory_order_relaxed); + s.file_bytes = file_bytes.load(std::memory_order_relaxed); + s.file_preads = file_preads.load(std::memory_order_relaxed); + s.file_read_ns = file_read_ns.load(std::memory_order_relaxed); + s.file_wait_ns = file_wait_ns.load(std::memory_order_relaxed); + return s; + } +}; + /* ------------------------------------------------------------------ the mover */ class Mover { public: @@ -543,7 +630,8 @@ public: } int64_t file_buffer_bytes() const { return file_vram_ ? file_buf_bytes_ : 0; } - const MoverStats& stats() const { return stats_; } + /* A snapshot by value: the counters are atomics read while the rank thread writes them. */ + MoverStats stats() const { return stats_.snapshot(); } std::string report() const; private: @@ -624,7 +712,7 @@ private: const Plan* plan_ = nullptr; MoverConfig cfg_; Residency res_; - MoverStats stats_; + MoverCounters stats_; Pools* budget_ = nullptr; /* True only when this object called the allocator itself (the test path). A Pool * reservation belongs to the Pool; freeing it here would be a double free. */ 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 215f5d5c..e8c44888 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -367,6 +367,10 @@ public: * encoder-only or embedding-only plugin does; the engine refuses to serve such a program at * startup. */ rad_buf logits_buf = 0; + /* Scored steps (rad_declare_scores): the final-normed hidden rows and the bf16 head table. + * Zero when the plugin declared none. */ + rad_buf score_hidden = 0; + rad_weight score_table = 0; /* The step's pooled vectors (rad_declare_pooled): set only by an embedding program, which has * no logits buffer. */ rad_buf pooled_buf = 0; @@ -403,6 +407,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. @@ -711,6 +719,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 @@ -867,6 +878,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 @@ -907,13 +921,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. */ @@ -953,8 +969,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 @@ -1096,10 +1114,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/rad_internal.h b/core/rad_internal.h index 2b17bc83..a4c9e5c6 100644 --- a/core/rad_internal.h +++ b/core/rad_internal.h @@ -29,6 +29,12 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...) * the first. */ uint64_t log_last_line_ns(); +/* A copy safe to interpolate into a log line: every byte below 0x20 but '\t', and DEL, becomes + * '?'. Client-controlled text reaches the log — session labels, echoed request fields — and an + * unfiltered newline forges a line while an ESC sequence drives the terminal that reads it. + * Multi-byte UTF-8 is left alone; only control bytes are replaced. */ +std::string log_sanitize(const std::string& s); + /* Rank tags on log lines. Per-rank components (pools, planner, mover, sampler) print the same * line once per rank, so under TP each line needs its rank. LogRank sets the tag as a scope * because the printers are several layers down, where threading a rank argument through every diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index 04cff43c..0352f9cc 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -929,7 +929,7 @@ int Ctx::lane_join(int from, int to) { * field added to RadBatch changes its size: decide whether the key must read it, then update the * size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded * (below). */ -static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 400, +static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 408, "RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on"); static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 80, "RadKVGroupBatch changed: check that Ctx::pass_key reads every new field"); @@ -957,7 +957,7 @@ uint64_t Ctx::pass_key(const RadBatch* b) const { mix((uint64_t)b->n_checkpoints); mix((uint64_t)b->n_seq_decode); mix((uint64_t)b->n_tok_decode); mix((uint64_t)b->max_q_len_decode); mix((uint64_t)b->max_q_len_prefill); mix((uint64_t)b->n_draft_out); mix((uint64_t)b->n_ahead); - mix((uint64_t)b->rope_mixed); ptr(b->rope_pos); + mix((uint64_t)b->rope_mixed); ptr(b->rope_pos); mix((uint64_t)b->score_only); ptr(b->token_ids); ptr(b->positions); ptr(b->cu_seqlens); ptr(b->seq_ids); ptr(b->out_ids); ptr(b->q_lens); ptr(b->ctx_lens); ptr(b->num_accepted); ptr(b->spec_parent); ptr(b->checkpoint_tok); ptr(b->checkpoint_slot); ptr(b->draft_out_ids); @@ -1396,7 +1396,9 @@ void Ctx::flush_issued() { for (size_t r = 0; r < unflushed_.size(); ++r) { const uint32_t i = unflushed_[r]; if (i < plans_.size() && i < program_->ops.size() && plans_[i].issued) - program_->ops[i].issued = true; + /* /graph reads this same bool from the HTTP thread: an atomic_ref store keeps that + * pair a relaxed exchange rather than a data race (ctx.h OpInfo::issued). */ + std::atomic_ref(program_->ops[i].issued).store(true, std::memory_order_relaxed); else unflushed_[w++] = i; } diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index db6bf847..a4d82d9d 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -80,7 +80,9 @@ struct OpPlan { * leave out. */ int32_t n_opd_schema = -1; int32_t n_opd_required = -1; - bool issued = false; /* did the run phase ever issue it (spec §16's graph dump) */ + bool issued = false; /* did the run phase ever issue it (spec §16's graph dump); + the step path and the HTTP graph dump meet on it through + std::atomic_ref (Ctx::flush_issued, rad_graph.cpp) */ /* Whether issuing it puts bytes on the interconnect. Set at bind from the resolved rows * (rad_kernel_collective) and the conventional all_reduce. The weight stager's copies share * the link and give way to it while it runs (Ctx::issue_body). */ 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 96642d75..f34a593c 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -866,14 +866,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(); @@ -963,6 +955,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_) { @@ -979,7 +994,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]; @@ -1155,6 +1171,21 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, mm_ev_live_ = true; } + /* A scored step (RadBatch::score_only): every sampled row is a scored request's first row, on + * one rank, in a program that told the core where its hidden rows and head table are. */ + int32_t score_only = 0; + if (n_out > 0 && n_dout == 0 && !plan.draft_pass && ranks_.size() == 1 && + prog_->score_hidden != RAD_NULL_HANDLE && prog_->score_table != RAD_NULL_HANDLE) { + score_only = 1; + for (const StepEntry& e : plan.e) { + if (!e.produces_token) continue; + if (!e.req || !e.req->token_scores || !e.req->output.empty() || e.n_spec > 0) { + score_only = 0; + break; + } + } + } + /* ---------------------------------------------------------- the batch, one per rank */ for (size_t r = 0; r < ranks_.size(); ++r) { void* const base = s.dev[r]; @@ -1170,6 +1201,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, B.seq_ids = on_rank(base, b0, s.d_sid); B.n_out = n_out; B.out_ids = n_out ? on_rank(base, b0, s.d_out) : nullptr; + B.score_only = score_only; B.n_draft_out = n_dout; B.draft_out_ids = n_dout ? on_rank(base, b0, s.d_dout) : nullptr; B.q_lens = on_rank(base, b0, s.d_q); @@ -1188,7 +1220,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; @@ -1232,6 +1265,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; @@ -1263,6 +1297,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 e46f4c5a..da696dbf 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 @@ -319,6 +323,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..af5cd251 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -79,6 +79,13 @@ struct IKVManager { * instead of deadlocking the engine (spec §17). */ virtual bool can_ever_fit(int64_t n_tokens) const = 0; + /* Whether `seq` can be grown to `n_tokens` without taking blocks from another sequence. */ + virtual bool can_grow(uint64_t seq, int64_t n_tokens) const = 0; + + /* How many blocks a paged group can still hand out, including those lent to the expert slab + * and recallable on demand. */ + virtual int64_t available_blocks(int32_t group) const = 0; + virtual const std::vector& block_table(uint64_t seq, int32_t group) const = 0; virtual int32_t state_slot(uint64_t seq, int32_t group) const = 0; @@ -172,10 +179,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 @@ -331,6 +342,7 @@ struct KVBinding final : IKVManager { } int preempt(uint64_t s) override { return m->preempt(s); } bool can_ever_fit(int64_t n) const override { return m->can_ever_fit(n); } + bool can_grow(uint64_t s, int64_t n) const override { return m->can_grow(s, n); } const std::vector& block_table(uint64_t s, int32_t g) const override { return m->block_table(s, g); } @@ -340,6 +352,7 @@ struct KVBinding final : IKVManager { } int64_t state_index_width(int32_t g) const override { return m->state_index_width(g); } int64_t free_blocks(int32_t g) const override { return m->free_blocks(g); } + int64_t available_blocks(int32_t g) const override { return m->available_blocks(g); } int64_t total_blocks(int32_t g) const override { return m->total_blocks(g); } int64_t held_blocks(int32_t g) const override { return m->held_blocks(g); } int64_t held_top_blocks(int32_t g) const override { return m->held_top_blocks(g); } @@ -472,6 +485,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..de39f321 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; @@ -260,6 +263,17 @@ int Scheduler::add_locked(std::unique_ptr r) { /* An embedding input runs in one step or not at all (Request::embed); one longer than a step * could never be admitted. */ if (r->embed && (int64_t)r->prompt.size() > cfg_.max_tok) return RAD_E_INVAL; + /* Every prompt id, tokenised or client-supplied, names a real vocabulary row: an id past the + * embedding table is refused at admission, never staged into a pass. Raw id arrays reach here + * straight from the request body, and an op failing mid-step is a device fault (spec §17) — + * the whole engine would die for one bad number. Same bound as the scored-prompt check below. + */ + for (int32_t t : r->prompt) + if (t < 0 || t >= prog_->meta.n_vocab) { + RAD_WARN("request %llu refused: prompt token id %d is outside the vocabulary [0, %lld)", + (unsigned long long)r->id, t, (long long)prog_->meta.n_vocab); + return RAD_E_INVAL; + } /* Nor could a prompt the KV pool cannot hold even alone: admission takes only what the pool * holds, so it would wait at the head of the queue, and everything behind it, forever. The * prompt is the least a request needs: its first token comes from the prefill's last row. @@ -363,12 +377,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 +499,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 +894,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 +915,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 +949,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 +1003,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; } @@ -1126,6 +1165,12 @@ void Scheduler::preempt_back() { int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { Request& r = *s.req; + /* A REQUEST THAT WAS PREEMPTED WAITS FOR ROOM FOR THE WHOLE RECOMPUTE, plus one block of + * headroom for every sequence already running. Admitting it on a shortfall is what turns + * preemption into a loop: it prefills a chunk, the pool refuses the next step, it is taken + * back to zero, and the same chunk is attempted again. */ + if (r.state == ReqState::Preempted && !preempted_can_prefill(s)) return kAdmitWait; + if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id)); /* R-SWA: the visible set becomes [0, prompt) plus a ring of W once the prompt is placed. The @@ -1248,8 +1293,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; @@ -1392,6 +1439,42 @@ void Scheduler::undo_hit(SchedReq& s) { s.hit_attn = 0; } +/* Whether a preempted request can be admitted without becoming the next victim. The first + * requirement is the whole recompute's blocks; the second is one block per running sequence for + * the step after this one. Without that headroom, a decode step takes the block this prefill + * just reserved, the pool refuses the next chunk, and preempt_back() puts it back to zero again. */ +bool Scheduler::preempted_can_prefill(const SchedReq& s) const { + const Request& r = *s.req; + const int64_t target = s.seq_len(); + + for (size_t g = 0; g < kvgeom_.g.size(); ++g) { + const KVGeom::G& gg = kvgeom_.g[g]; + if (!gg.paged) continue; + int64_t need = (target + gg.block_size - 1) / gg.block_size - + (int64_t)kv_->block_table(r.id, (int32_t)g).size(); + if (need < 0) need = 0; + for (int32_t slot : running_) { + const SchedReq& rs = *reqs_[(size_t)slot]; + if (!rs.req) continue; + const int64_t next = rs.req->n_computed + 1; + const int64_t rows = (next + gg.block_size - 1) / gg.block_size; + const int64_t extra = rows - (int64_t)kv_->block_table(rs.req->id, (int32_t)g).size(); + need += 1; /* the step after this one keeps its block */ + if (extra > 0) need += extra; /* and the block its next token already needs */ + } + if (need > kv_->available_blocks((int32_t)g)) return false; + } + + /* Stateful groups: the recompute needs its state slots back, and every running sequence must + * keep the slot it already holds. */ + if (!kv_->can_grow(r.id, target)) return false; + for (int32_t slot : running_) { + const SchedReq& rs = *reqs_[(size_t)slot]; + if (rs.req && !kv_->can_grow(rs.req->id, rs.req->n_computed + 1)) return false; + } + return true; +} + /* ------------------------------------------------------------------ the step */ const RadBatch* Scheduler::step() { std::lock_guard lk(mu_); @@ -1407,6 +1490,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 +1707,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); @@ -1679,6 +1766,7 @@ const RadBatch* Scheduler::step() { ? share_tok : 0; admit_full_ = 0; const int as = admit_one(s, budget, areserve); + if (as == kAdmitWait) { ++at; continue; } if (as < 0) break; /* head of line: do not admit behind it */ if (admit_full_ > s.sched_tokens && capped_at < 0) { capped_at = (int32_t)plan_.e.size(); @@ -1698,6 +1786,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 +1797,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 +1838,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 +2093,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]; @@ -2012,6 +2103,12 @@ const RadBatch* Scheduler::step_next_locked() { * that cannot rewind decides at commit whether the next step may speculate; one that can, * or no grammar, keeps its answer. */ if (!e.produces_token || !r.speculation_fixed) return nullptr; + /* A SCORED row (Request::token_scores, a /v1/systemone question) that the step in flight + * brings to max_tokens gets no step issued ahead: it would run a whole forward pass for a + * request that finishes at the commit, and max_tokens=1 pays a decode step after its + * prefill. Scored rows only -- every other decode keeps the step of overlap it had. */ + if (r.token_scores && r.max_tokens > 0 && + (int64_t)r.output.size() + 1 >= r.max_tokens) return nullptr; /* The furthest context the row can reach: every position this step verifies committed, * counted from the last commit rather than this step's own bound (which would add a @@ -2034,6 +2131,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 +2179,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 +2344,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 +2800,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 +2920,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..864aedcc 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 @@ -746,12 +764,19 @@ private: /* Both snapshots resolve the same way; the two wrappers exist because the row types differ. */ const Request* live_req(int32_t slot, uint64_t id) const; void preempt_back(); + /* A preempted request waits until the pool can hold its WHOLE remaining recompute plus one + * block of headroom for every running sequence; otherwise admitting it now just gets it + * preempted again next step and the prefill loops. */ + bool preempted_can_prefill(const SchedReq& s) const; /* Give blocks back from the prefix cache until the pool has headroom again. */ void trim_prefix_cache(); /* RAD_OK, or a negative status when the request cannot be admitted now, nor anything behind * it. `reserve`: tokens of the step to leave for the requests queued behind this one * (--busy-prefill-chunk; busy_cap); 0 plans the chunk on the whole budget. */ int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0); + /* Positive sentinel from admit_one: the request waits (its context is still being read off + * disk, or a preempted prefill has no room yet) and the walk may ask the one behind it. */ + static constexpr int kAdmitWait = 1; /* The queue positions one step's admission took, kept to reuse the allocation. */ std::vector took_; /* A step's prefill entries while step() moves its decode entries first; reserved at init, diff --git a/core/server/admin.cpp b/core/server/admin.cpp index fb4483d5..3405f74b 100644 --- a/core/server/admin.cpp +++ b/core/server/admin.cpp @@ -506,7 +506,9 @@ HttpResponse Server::handle_diagnostics(const HttpRequest& req) { return error_response(err_not_implemented( "the server was not given a diagnostics provider; this build has no engine attached"), req.peer); - if (opt_.api_key.empty() && !req.peer_is_loopback()) { + if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) { + /* A cross-origin browser is not a loopback client even when its own machine serves + * this port: the drive-by that guard exists to refuse. */ ApiError e; e.status = 403; e.type = "permission_error"; diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 9993c082..32a2f185 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -13,6 +13,7 @@ * collapsing while the pooled acceptance rate stays plausible. */ #include "server.h" +#include "oai.h" #include "rad_internal.h" @@ -57,8 +58,10 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) { if (req.method == "POST") { /* The default applies to every client's requests that name no choice, so a server * started without --api-key takes the change from a loopback client only, as it does a - * runtime adapter load. */ - if (opt_.api_key.empty() && !req.peer_is_loopback()) { + * runtime adapter load. A browser page on another origin does not qualify even when the + * victim's own browser makes it loopback: that is the drive-by this guard must refuse. + */ + if (opt_.api_key.empty() && (!req.peer_is_loopback() || req.is_cross_origin())) { ApiError e; e.status = 403; e.type = "permission_error"; @@ -67,12 +70,12 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) { "elsewhere"; return error_response(e, req.peer); } - json body; - try { - body = json::parse(req.body.empty() ? "{}" : req.body); - } catch (const std::exception& e) { - return error_response(err_bad("body", std::string("not JSON: ") + e.what()), req.peer); - } + bool over = false, deep = false; + json body = parse_json_bounded(req.body.empty() ? "{}" : req.body, 0, &over, &deep); + if (body.is_discarded()) return error_response(err_bad("body", "not JSON"), req.peer); + if (over || deep) + return error_response(err_bad("body", "expected {\"enabled\": true|false} and " + "nothing deeper than that"), req.peer); const auto it = body.find("enabled"); if (it == body.end() || !it->is_boolean()) return error_response(err_bad("enabled", "a boolean is required"), req.peer); @@ -462,6 +465,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 +1188,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 +1359,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 +1644,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 +1876,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 +2252,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 +2270,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 +2330,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 +2532,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 +2544,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 +2567,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 +2586,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 +3512,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]]) { @@ -3619,6 +3672,17 @@ HttpResponse Server::handle_dashboard(const HttpRequest&) { /* No caching: the page must match the binary's /stats shape, and a stale copy shows only * blank panels. */ r.set_header("Cache-Control", "no-store"); + /* The page is fixed markup that talks only to its own origin, and CSP is how that promise + * becomes enforceable: even a future markup bug could not phone an injected payload's + * findings home, and could not reach the key beyond this origin. script/style 'unsafe-inline' + * is the cost of shipping as one compiled-in literal with its own