Archived
Merge main into laya-arch-plugin
This commit is contained in:
commit
ec243c2a7d
189 files changed
+11212
-7060
No files matched your search
+3
-4
@@ -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()
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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` |
|
||||
|
||||
+55
-4
@@ -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);
|
||||
|
||||
+16
-1
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -123,6 +123,16 @@ struct Dflash2 {
|
||||
int64_t group = 16;
|
||||
int64_t sel_rank = 256; /* the codebooks' width */
|
||||
int64_t sel_topk = 16; /* candidates kept per position */
|
||||
/* Propose a tree of `steps()` nodes instead of the selector's one path (`dflash_tree`,
|
||||
* rad_drafter_tree): best-first over the candidate lattice by path probability, each
|
||||
* edge's probability the softmax of its scores over the K candidates divided by
|
||||
* `tree_temp`. False: the greedy walk. */
|
||||
bool tree = false;
|
||||
double tree_temp = 1.0;
|
||||
/* A tree's draft nodes a step, 0 for `steps()`. More than the block drafts is a wider tree
|
||||
* over the same lattice (its depth is still at most `steps()`); the proposal buffers, the
|
||||
* drafter's declared depth and the verify are this wide. */
|
||||
int64_t tree_nodes = 0;
|
||||
int64_t window = 0; /* sliding attention width, 0 for none */
|
||||
int causal = 0;
|
||||
/* The target's embedding scale, applied to the query block as the drafter was trained
|
||||
@@ -132,15 +142,18 @@ struct Dflash2 {
|
||||
* pass (prefetch_beside, rad_arch.h); 0 reads none. */
|
||||
int64_t prefetch = 0;
|
||||
|
||||
/* Also declare the short block's query pass (kShortBlock rows) for --draft-short-from; an
|
||||
* architecture that does not call rad_drafter_short_block leaves it off and its graph as
|
||||
* it was. */
|
||||
/* Also declare the short block's query pass (kShortBlock rows, or `short_rows`) for
|
||||
* --draft-short-from; an architecture that does not call rad_drafter_short_block leaves
|
||||
* it off and its graph as it was. A tree's selector at that block grows a tree of its own
|
||||
* over the shorter pass, `short_rows - 1` nodes or fewer. */
|
||||
int short_block = 0;
|
||||
/* --draft-coupling: the temperature of the draft law Q the coupled walk samples from
|
||||
* (dflash_couple_propose's `q_temp`). Any value keeps the output exact; it only moves
|
||||
* acceptance, sum min(P, Q). */
|
||||
double q_temp = 1.0;
|
||||
int64_t short_rows = 0;
|
||||
int64_t steps() const { return block - 1; }
|
||||
int64_t nodes() const { return tree && tree_nodes > 0 ? tree_nodes : steps(); }
|
||||
int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; }
|
||||
/* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's);
|
||||
* `dflash_conv` reads a slice of it at the full row pitch. */
|
||||
@@ -198,6 +211,8 @@ struct Dflash2 {
|
||||
/* --draft-coupling: [max_seqs, DRAW_WORDS] draws the engine stages, and [steps, max_seqs,
|
||||
* STATE_WORDS] states it reads back (abi/rad_spechub.h). Both or neither. */
|
||||
rad_buf couple_draws = 0, couple_state = 0;
|
||||
/* [max_seqs, steps] i32 a tree's parents (Config::tree, rad_drafter_tree); 0 otherwise */
|
||||
rad_buf parents = 0;
|
||||
};
|
||||
|
||||
/* Whether the 2-bit draft head is vocab-sharded (rad_arch.h: vocab_head_sharded), so whoever
|
||||
@@ -277,6 +292,7 @@ struct Dflash2 {
|
||||
* and the selector strides by it, so each has an op of its own; every other op is per row. */
|
||||
rad_op op_aconv_lo[MAX_LAYERS] = {}, op_fconv_lo[MAX_LAYERS] = {}, op_sel_lo = 0;
|
||||
int64_t block_lo = 0;
|
||||
int64_t sel_lo_nodes = 0; /* a tree's nodes at the short block (op_sel_lo) */
|
||||
rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0;
|
||||
rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0;
|
||||
/* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and
|
||||
@@ -718,7 +734,10 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* layers. Planned from those alone, its range would end before the coefficients' begins and
|
||||
* the plan could lay one over the other. Read by the last convolution as well, it is live
|
||||
* wherever the coefficients are. */
|
||||
block_lo = cfg.short_block && cfg.block > kShortBlock ? kShortBlock : 0;
|
||||
{
|
||||
const int64_t rows = cfg.short_rows > 0 ? cfg.short_rows : kShortBlock;
|
||||
block_lo = cfg.short_block && rows >= 2 && cfg.block > rows ? rows : 0;
|
||||
}
|
||||
for (int64_t l = 0; block_lo && l < g.n_layer; ++l) {
|
||||
const int i = (int)l;
|
||||
op_aconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv",
|
||||
@@ -943,15 +962,65 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_selp)),
|
||||
{w.sel_h}, {w.hp});
|
||||
/* `anchor_stride` is `block`: the operand is the step's token_ids, `block` per sequence with
|
||||
* the anchor first. */
|
||||
op_sel = rw(b, RAD_OP(b, "dflash_select",
|
||||
* the anchor first.
|
||||
*
|
||||
* A tree (Config::tree): `dflash_tree` grows `steps` nodes best-first over the same lattice
|
||||
* and the same edge scores, writing each node's parent beside its token. Where no library
|
||||
* serves it the block falls back to the chain and says so; the caller reads `cfg.tree` after
|
||||
* declare to decide whether to tell the core (rad_drafter_tree). --draft-coupling samples one
|
||||
* path per sequence, so a coupled drafter proposes the chain. */
|
||||
if (cfg.tree && (w.couple_draws || w.couple_state)) {
|
||||
rad_note(b, "DFlash2: --draft-coupling samples a chain; the drafter proposes no tree");
|
||||
cfg.tree = false;
|
||||
}
|
||||
if (cfg.tree) {
|
||||
op_sel = RAD_OP(b, "dflash_tree",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block),
|
||||
RAD_INT("nodes", cfg.nodes()), RAD_F64("temp", cfg.tree_temp),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ));
|
||||
if (op_sel && rad_op_resolved(b, op_sel)) {
|
||||
rw(b, op_sel, {w.cand, w.unary, w.hp}, {w.tokens, w.parents});
|
||||
} else {
|
||||
rad_note(b, "DFlash2: no library serves dflash_tree here; the drafter proposes its "
|
||||
"selector's chain");
|
||||
cfg.tree = false;
|
||||
op_sel = 0;
|
||||
}
|
||||
}
|
||||
if (!cfg.tree) op_sel = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", cfg.steps()),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ)),
|
||||
{w.cand, w.unary, w.hp}, {w.tokens});
|
||||
if (block_lo)
|
||||
if (block_lo && cfg.tree) {
|
||||
/* A tree over the short block's own lattice (the pass attends across its block, so it is
|
||||
* not the full pass's prefix): as many nodes as the block drafts, or the tree's own count
|
||||
* where that is fewer. */
|
||||
sel_lo_nodes = std::min<int64_t>(cfg.nodes(), block_lo - 1);
|
||||
op_sel_lo = RAD_OP(b, "dflash_tree",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
RAD_INT("n_vocab", g.n_vocab_all),
|
||||
RAD_INT("anchor_stride", block_lo),
|
||||
RAD_INT("nodes", sel_lo_nodes), RAD_F64("temp", cfg.tree_temp),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_pred, w_succ));
|
||||
if (op_sel_lo && rad_op_resolved(b, op_sel_lo)) {
|
||||
rw(b, op_sel_lo, {w.cand, w.unary, w.hp}, {w.tokens, w.parents});
|
||||
} else {
|
||||
rad_note(b, "DFlash2: no library serves dflash_tree at the short block; the tree keeps "
|
||||
"its own block under load");
|
||||
op_sel_lo = 0;
|
||||
block_lo = 0;
|
||||
sel_lo_nodes = 0;
|
||||
}
|
||||
} else if (block_lo)
|
||||
op_sel_lo = rw(b, RAD_OP(b, "dflash_select",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1),
|
||||
RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank),
|
||||
@@ -1197,10 +1266,19 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const {
|
||||
}
|
||||
|
||||
RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S));
|
||||
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
/* A tree's outputs as views exactly its nodes wide, at the buffers' row pitch: at the short
|
||||
* block it grows fewer nodes than a row holds, and the proposals are read at the full pitch. */
|
||||
const int64_t nn = lo ? sel_lo_nodes : cfg.nodes();
|
||||
if (cfg.tree)
|
||||
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
bcol(w.tokens, 0, nn, batch->n_seq), bcol(w.parents, 0, nn, batch->n_seq));
|
||||
else
|
||||
RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S),
|
||||
bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S),
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ),
|
||||
brows(w.tokens, batch->n_seq));
|
||||
if (op_couple)
|
||||
RAD_ISSUE_N(c, lo ? op_couple_lo : op_couple, batch->n_seq,
|
||||
bcol(w.cand, 0, cfg.sel_topk, S), bcol(w.unary, 0, cfg.sel_topk, S),
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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<rad_buf>{ w.ffn.q, w.ffn.s, w.ffn.x }
|
||||
: std::initializer_list<rad_buf>{ 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 },
|
||||
|
||||
@@ -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")),
|
||||
|
||||
@@ -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);
|
||||
|
||||
+38
-18
@@ -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<rad_buf> reads,
|
||||
std::initializer_list<rad_buf> writes, int64_t* gated_rows) {
|
||||
const int64_t hi = rows < 64 ? rows : 64;
|
||||
std::initializer_list<rad_buf> 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<rad_buf> reads,
|
||||
std::initializer_list<rad_buf> 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 */
|
||||
|
||||
@@ -188,6 +188,10 @@ inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
out->draft_depth = (int)(bs - 1);
|
||||
out->draft_depth_fixed = 1;
|
||||
out->chain_pays = 1;
|
||||
/* Its proposals verified as a tree of the same node count (dflash_tree, rad_drafter_tree): on
|
||||
* 4x R9700 +7% single-stream decode and +6-9% aggregate at 1-16 users over the selector's
|
||||
* chain (BetterBench, thinking off; on two cards +4% and +6-12%). */
|
||||
out->tree_pays = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
+10
-12
@@ -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),
|
||||
|
||||
@@ -423,6 +423,12 @@ struct Gemma4Attn {
|
||||
* the copies of k and v too, ahead of the unfused prologue, which reads them dense. */
|
||||
rad_op op_attn_row = 0, op_attn_dec = 0, op_lift_q = 0, op_lift_k = 0, op_lift_v = 0;
|
||||
int64_t dec_hi = 0;
|
||||
/* Tree verification (rad_drafter_tree): attention that honours RadBatch::spec_parent over a
|
||||
* step's decode rows, reading q in the row (attn_paged_qrow_tree) or dense (attn_paged_tree,
|
||||
* after op_tree_lift copies it out). Declared only when `tree` is set before declare; 0 where
|
||||
* no library serves it, which the model reads as "no trees". */
|
||||
bool tree = false;
|
||||
rad_op op_attn_tree = 0, op_tree_lift = 0;
|
||||
/* the feed-forward's gate_up read into the cache beside this block's all-reduce, or 0 (see
|
||||
* "Prefetch beside the reductions") */
|
||||
rad_op op_pf = 0;
|
||||
@@ -697,6 +703,20 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
}
|
||||
}
|
||||
|
||||
/* The tree form over the decode rows: a verify block of 1 + n_spec rows a sequence, so the
|
||||
* split-KV band (q_len * gqa <= 64) covers it at every class here. In the row where the
|
||||
* prologue leaves q there, else dense after a copy. */
|
||||
if (tree) {
|
||||
const int64_t thi = std::min<int64_t>(
|
||||
g.max_tok, std::max<int64_t>({ (int64_t)1, 64 / cls.gqa(), (int64_t)g.max_spec + 1 }));
|
||||
if (fused && op_qnr && rad_op_declared(b, "attn_paged_qrow_tree"))
|
||||
op_attn_tree = attn("attn_paged_qrow_tree", {w.qkv}, thi);
|
||||
if (!op_attn_tree && rad_op_declared(b, "attn_paged_tree")) {
|
||||
op_attn_tree = attn("attn_paged_tree", {w.q}, thi);
|
||||
if (op_attn_tree && fused && op_qnr) op_tree_lift = lift(qd, w.q);
|
||||
}
|
||||
}
|
||||
|
||||
/* With the cache store folded into the prologue where a library serves it
|
||||
* (qkv_norm_rope_kv_store: the same prologue, then kv_store of the finished k and v from the
|
||||
* same launch, byte for byte), one launch a layer fewer. Declared after the attention ops,
|
||||
@@ -947,26 +967,51 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
if (op_kv) RAD_ISSUE(c, op_kv, K, V, praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
|
||||
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
|
||||
rad_op a_op = op_attn;
|
||||
RadOperand a_q = brows(w.q, T);
|
||||
if (op_attn_row) {
|
||||
a_op = op_attn_row;
|
||||
a_q = Q;
|
||||
} else if (op_attn_dec && batch->max_q_len <= dec_hi) {
|
||||
a_op = op_attn_dec;
|
||||
a_q = Q;
|
||||
} else if (row) {
|
||||
if (T == 1) a_q = Q;
|
||||
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
|
||||
/* A tree step (rad_drafter_tree): every decode row's verify block sees, inside the block,
|
||||
* only that row's ancestors (RadBatch::spec_parent), so the decode rows go through the tree
|
||||
* form. On a step of decode rows alone that is the step's attention; beside a prefill chunk the
|
||||
* ordinary form runs over every row first and the tree form then rewrites the decode rows,
|
||||
* which come first (spec §8). */
|
||||
const bool tree_step = op_attn_tree && batch->spec_parent && batch->draft_pass == 0 &&
|
||||
batch->n_seq_decode > 0;
|
||||
if (!tree_step || batch->n_seq_decode < batch->n_seq) {
|
||||
/* attn_paged reads q dense: one row of the row's slice is, a taller step copies q out. */
|
||||
rad_op a_op = op_attn;
|
||||
RadOperand a_q = brows(w.q, T);
|
||||
if (op_attn_row) {
|
||||
a_op = op_attn_row;
|
||||
a_q = Q;
|
||||
} else if (op_attn_dec && batch->max_q_len <= dec_hi) {
|
||||
a_op = op_attn_dec;
|
||||
a_q = Q;
|
||||
} else if (row) {
|
||||
if (T == 1) a_q = Q;
|
||||
else RAD_ISSUE_N(c, op_lift_q, T, Q, brows(w.q, T));
|
||||
}
|
||||
RAD_ISSUE_N(c, a_op, batch->max_q_len,
|
||||
a_q, kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
}
|
||||
if (tree_step) {
|
||||
const int64_t Td = batch->n_tok_decode, Sd = batch->n_seq_decode;
|
||||
RadOperand tq = row ? bcol(w.qkv, 0, qd, Td) : brows(w.q, Td);
|
||||
if (op_tree_lift) {
|
||||
RAD_ISSUE_N(c, op_tree_lift, Td, bcol(w.qkv, 0, qd, Td), brows(w.q, Td));
|
||||
tq = brows(w.q, Td);
|
||||
}
|
||||
RAD_ISSUE_N(c, op_attn_tree, batch->max_q_len_decode,
|
||||
tq, kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, Sd, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, Sd),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, Sd + 1),
|
||||
brows(w.attn, Td),
|
||||
praw(batch->spec_parent, RAD_I32, Td));
|
||||
}
|
||||
RAD_ISSUE_N(c, a_op, batch->max_q_len,
|
||||
a_q, kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
}
|
||||
|
||||
/* A slice's rows see exactly the keys they see in the whole step: the cache holds the step's
|
||||
@@ -1811,6 +1856,9 @@ struct Model {
|
||||
Dflash2 df2{};
|
||||
Dflash2::Wire df2w{};
|
||||
bool have_df2 = false;
|
||||
/* Tree verification (RadBuildCtx::draft_tree): every layer's attention has its tree form, and
|
||||
* the drafter proposes trees once it has declared dflash_tree too. */
|
||||
bool tree = false;
|
||||
/* The prefill overlap runs attention per slice: a trim a KV group (sliding, global). */
|
||||
SliceTrim trim[2]{};
|
||||
int n_trim = 0;
|
||||
@@ -1877,6 +1925,13 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
Dflash2::Config dc{};
|
||||
dc.n_taps = m.n_taps;
|
||||
dc.block = ctx->max_spec + 1;
|
||||
/* A tree (m.tree, asked before the trunk) is `max_spec` nodes grown over the lattice of the
|
||||
* block the drafter was trained at, whatever its width: the block is the trained one and
|
||||
* --num-speculative-tokens counts nodes. */
|
||||
if (m.tree && gemma4::dflash_block(meta) > 1) {
|
||||
dc.block = gemma4::dflash_block(meta);
|
||||
dc.tree_nodes = ctx->max_spec;
|
||||
}
|
||||
dc.taps = df2_geti(meta, "conv_kernel_size", 2);
|
||||
dc.group = df2_geti(meta, "conv_group_size", 16);
|
||||
dc.sel_rank = df2_geti(meta, "selector_rank", 0);
|
||||
@@ -1985,13 +2040,39 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dw.dpair = decl_b(b, nm.f("df_dpair"), RAD_F32, {sr, tw, 2});
|
||||
dw.dgath = decl_b(b, nm.f("df_dgath"), RAD_F32, {sr, (int64_t)dg.world * tw, 2});
|
||||
}
|
||||
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, dc.steps()});
|
||||
const int64_t nodes = dc.tree_nodes > 0 ? dc.tree_nodes : dc.steps();
|
||||
dw.tokens = decl_b(b, nm.f("dflash_tokens"), RAD_I32, {dg.max_seqs, nodes});
|
||||
/* Trees (RadBuildCtx::draft_tree; the trunk's attention already has its tree form): the
|
||||
* selector's lattice grown best-first into `steps` nodes, each edge weighed by the softmax of
|
||||
* its scores over a temperature. 1.25 measured best at 7 nodes on the speculator benchmarks
|
||||
* (greedy, and sampled at 0.7 and 1.0); its path probabilities are calibrated there. */
|
||||
if (m.tree) {
|
||||
dc.tree = true;
|
||||
dc.tree_temp = 1.25;
|
||||
dw.parents = decl_b(b, nm.f("dflash_parents"), RAD_I32, {dg.max_seqs, nodes});
|
||||
/* A block of 16 (the DBloom drafter): its 15-node tree's verify rows pay at one sequence
|
||||
* and not at many, so the query pass is declared at half the block too, over which the
|
||||
* drafter grows a 7-node tree of its own: the drafter's short block
|
||||
* (rad_drafter_short_block), which the core runs from two decoding sequences on
|
||||
* (--draft-short-from auto). A shorter block's tree verifies as few rows as that already. */
|
||||
if (dc.block >= 16 && (dc.block & (dc.block - 1)) == 0) {
|
||||
dc.short_block = 1;
|
||||
dc.short_rows = dc.block / 2;
|
||||
}
|
||||
}
|
||||
|
||||
/* The head copy comes from the tied table, under the block's own name; the recipe makes it
|
||||
* 8-bit. */
|
||||
RAD_ARCH_TRY(m.df2.declare(b, nm, dg, dc, (int)m.n_main, m.kv_draft, m.w_tok, "draft",
|
||||
nm.ckpt("model.language_model.embed_tokens.weight"), dw));
|
||||
m.have_df2 = true;
|
||||
m.tree = m.df2.cfg.tree; /* false where dflash_tree did not resolve */
|
||||
if (!m.tree && nodes != dc.steps()) {
|
||||
fprintf(stderr, "radiance: gemma4: a DFlash2 tree of %lld nodes needs dflash_tree, which no "
|
||||
"library serves here; the block's chain is %lld\n", (long long)nodes,
|
||||
(long long)dc.steps());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
RadDrafterDecl drf{};
|
||||
drf.name = "dflash2";
|
||||
@@ -1999,7 +2080,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
drf.depth = ctx->max_spec;
|
||||
drf.block = dc.block;
|
||||
drf.proposal = dw.tokens;
|
||||
drf.proposal_pitch = dc.steps();
|
||||
drf.proposal_pitch = nodes;
|
||||
drf.window = dc.window;
|
||||
drf.mask_token = (int32_t)df2_geti(meta, "mask_token_id", -1);
|
||||
if (drf.mask_token < 0) {
|
||||
@@ -2008,6 +2089,17 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
if (m.tree) {
|
||||
RAD_ARCH_TRY(rad_drafter_tree(b, dw.parents));
|
||||
if (m.df2.block_lo > 0) {
|
||||
RAD_ARCH_TRY(rad_drafter_short_block(b, m.df2.block_lo));
|
||||
rad_note(b, "DFlash2 drafter: a short block of %lld rows, a tree of %lld nodes over it",
|
||||
(long long)m.df2.block_lo, (long long)m.df2.sel_lo_nodes);
|
||||
}
|
||||
rad_note(b, "DFlash2 drafter: a tree of %lld nodes a step (softmax temperature %.3g) over "
|
||||
"the lattice of its %lld-row block, verified in %lld rows", (long long)nodes,
|
||||
dc.tree_temp, (long long)dc.block, (long long)nodes + 1);
|
||||
}
|
||||
|
||||
rad_note(b, "DFlash2 drafter: %lld layers at absolute %lld.., %lld heads / %lld kv x %lld, ffn "
|
||||
"%lld, %s attention with a %lld-token window, %d trunk taps; one forward proposes "
|
||||
@@ -2351,6 +2443,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
Gemma4Attn::Wire gw{}; gw.x = m.b_x; gw.h = m.b_h; gw.q = m.b_qg; gw.k = m.b_kg; gw.v = m.b_vg; gw.attn = m.b_atting;
|
||||
Gemma4Mlp::Wire mw{}; mw.x = m.b_x; mw.h = m.b_h; mw.gu = m.b_gu; mw.ffn = m.b_ffn;
|
||||
|
||||
/* Tree verification for a DFlash2 drafter (RadBuildCtx::draft_tree, which the engine sets
|
||||
* from this plugin's probe; rad_drafter_tree): asked of every layer's attention here, before
|
||||
* the drafter, and used only if every layer has it. Not where a layer reads another layer's
|
||||
* cache (KV sharing, Gemma 4 E2B/E4B): untested there. */
|
||||
const bool tree_want = ctx->max_spec > 0 && m.n_taps > 0 && gemma4::dflash_kind(meta) == 2 &&
|
||||
kv_shared == 0 && ctx->draft_tree != 0;
|
||||
bool tree_all = tree_want;
|
||||
|
||||
m.layers.resize((size_t)m.n_main);
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
@@ -2360,8 +2460,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
const Gemma4Attn::Wire& aw = lay.global ? gw : sw;
|
||||
/* A KV-shared layer is not bound: the group's pages hold only the layers that write. */
|
||||
if (kv_src[(size_t)l] < 0) RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
|
||||
lay.attn.tree = tree_want;
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre,
|
||||
lay.global ? &m.b_qkvg : &m.b_qkvs, kv_src[(size_t)l]));
|
||||
if (tree_want && !lay.attn.op_attn_tree) tree_all = false;
|
||||
/* The double-wide layers write their own pair of buffers (see b_gu_w). */
|
||||
Gemma4Mlp::Wire lw = mw;
|
||||
const bool wide = wide_mlp && l >= first_shared;
|
||||
@@ -2626,6 +2728,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* declaration order is the buffer planner's liveness. It reads the taps the trunk copied into
|
||||
* `dflash_src` and the trunk's tied table, as its embedding and, where the container holds no
|
||||
* 8-bit copy, as its head. */
|
||||
if (tree_want && !tree_all)
|
||||
rad_note(b, "DFlash2 tree: no library serves tree attention for every layer here "
|
||||
"(attn_paged_qrow_tree / attn_paged_tree); the drafter proposes a chain");
|
||||
m.tree = tree_all;
|
||||
if (m.n_taps > 0 && gemma4::dflash_kind(meta) == 2) {
|
||||
RAD_ARCH_TRY(declare_dflash2(b, meta, ctx, m));
|
||||
} else if (m.n_taps > 0) {
|
||||
|
||||
+260
-75
@@ -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 <arch/rad_arch.h>
|
||||
#include <arch/rad_block_mlp.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
#include <arch/rad_block_mlp_fp8.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
|
||||
#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<int64_t> 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<const char*> src, const ActFP8& a, rad_buf y,
|
||||
std::initializer_list<int64_t> 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
|
||||
@@ -6,7 +6,7 @@
|
||||
* returns each sequence's pooled row. Attention is bidirectional on every layer, so nothing is
|
||||
* paged: a token attends to later tokens, and there is nothing to carry between steps.
|
||||
*
|
||||
* ============================== THE SHAPE ==============================
|
||||
* Shape:
|
||||
*
|
||||
* 12 layers, hidden 768, 12 heads of 64, ffn 3072, vocab 250048, type vocab 1
|
||||
* post-norm block, the config's `prenorm: false`:
|
||||
@@ -20,14 +20,12 @@
|
||||
* output: the mean of every real token, then cast to the f32 pooled buffer
|
||||
*
|
||||
* The expert tables are one concatenated tensor each: w1 [8 * 3072, 768] as [out, in], w2
|
||||
* [8 * 3072, 768] as [in, out] per expert, so w2 is sliced then transposed at convert
|
||||
* (RAD_MAP_TRANSPOSE with src_index and src_rows). Every expert's two tensors take distinct group
|
||||
* slots.
|
||||
* [8 * 3072, 768] as [in, out] per expert, so w2 is sliced, then transposed (RAD_MAP_TRANSPOSE
|
||||
* with src_index and src_rows). Every expert's two tensors take distinct group slots.
|
||||
*
|
||||
* The block order and the unused shared experts.bias were settled against the production
|
||||
* llama.cpp embedder by scripts/nomic_ref.py; the winning variant and the vectors it produced are
|
||||
* in tests/data/nomic/golden.json (norm=post, bias=none). The checkpoint's `experts.bias` tensors
|
||||
* are therefore not declared and stay unconverted.
|
||||
* The block order and the omitted shared bias match llama.cpp's embedder for this model
|
||||
* (post-norm, no expert bias). The checkpoint's `experts.bias` tensors are not declared and stay
|
||||
* unconverted.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
@@ -40,10 +38,8 @@ namespace nomicbert {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
/* Post-norm, the reading scripts/nomic_ref.py and tests/data/nomic/golden.json settle: the
|
||||
* attention is on the raw stream, then LN1, then the feed-forward on LN1's output, then LN2 over
|
||||
* that output plus the feed-forward's. The shared experts.bias is not applied (bias=none there). */
|
||||
constexpr bool kPostNorm = true;
|
||||
/* Post-norm: attention on the raw stream, then LN1, then the feed-forward on LN1's output, then
|
||||
* LN2 over that output plus the feed-forward's. */
|
||||
|
||||
struct Layer {
|
||||
bool moe = false;
|
||||
@@ -77,10 +73,9 @@ struct Model {
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* The layer schedule, read rather than derived: a wrong interval would turn a dense layer into a
|
||||
* MoE layer whose tensors the checkpoint does not hold, which convert refuses but only after the
|
||||
* graph was built. Layer l is routed when (l + 1) % moe_every_n_layers == 0, as nomic's
|
||||
* modeling_hf_nomic_bert builds it. */
|
||||
/* The layer schedule, read from moe_every_n_layers rather than derived: a wrong interval would
|
||||
* declare a MoE layer whose tensors the checkpoint does not hold. Layer l is routed when
|
||||
* (l + 1) % moe_every_n_layers == 0, as nomic's modeling_hf_nomic_bert builds it. */
|
||||
static bool is_moe_layer(int64_t l, int64_t every) {
|
||||
return every > 0 && (l + 1) % every == 0;
|
||||
}
|
||||
@@ -99,7 +94,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
/* One 475M-parameter encoder on one card; tensor parallelism would only add an all-reduce per
|
||||
/* A 475M-parameter encoder fits one card; tensor parallelism would only add an all-reduce per
|
||||
* layer. */
|
||||
if (ctx->world_size > 1) {
|
||||
fprintf(stderr, "radiance: nomicbert runs on one card (--tp 1); the model is 475M "
|
||||
@@ -325,8 +320,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
src("mlp.router.layer.weight")));
|
||||
y.w_router = decl_w(b, nm.f("blk.%lld.ffn_router.weight", ll), RAD_BF16,
|
||||
{m.n_expert, E}, A, N, gl);
|
||||
/* mlp.experts.bias is deliberately not mapped: the verified variant applies no
|
||||
* expert bias, so the tensor is left in the checkpoint. */
|
||||
/* mlp.experts.bias is not mapped (no expert bias, see the header). */
|
||||
/* Each projection is a consecutive run of expert handles: all w1 in expert order,
|
||||
* then all w2. A grouped GEMM takes the run's first handle and its length. The name
|
||||
* maps come first: declare reads a weight's planned encoding when the weight is
|
||||
@@ -356,9 +350,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
}
|
||||
|
||||
const rad_buf att_in = kPostNorm ? m.b_x : m.b_h;
|
||||
y.op_qkv = rw(b, gemm_bias_op(3 * E, E, y.w_qkv, y.b_qkv, nullptr),
|
||||
{att_in}, {m.b_qkv});
|
||||
{m.b_x}, {m.b_qkv});
|
||||
y.op_rope = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head),
|
||||
@@ -381,12 +374,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (!y.moe) {
|
||||
y.op_fc1 = rw(b, gemm_bias_op(g.n_ff, E, y.w_fc1, y.b_fc1, "gelu"),
|
||||
{m.b_h}, {m.b_ff});
|
||||
if constexpr (kPostNorm)
|
||||
y.op_fc2 = rw(b, gemm_bias_op(E, g.n_ff, y.w_fc2, y.b_fc2, nullptr),
|
||||
{m.b_ff, m.b_h}, {m.b_o});
|
||||
else
|
||||
y.op_fc2 = rw(b, gemm_bias_op(E, g.n_ff, y.w_fc2, y.b_fc2, nullptr),
|
||||
{m.b_ff, m.b_x}, {m.b_x});
|
||||
y.op_fc2 = rw(b, gemm_bias_op(E, g.n_ff, y.w_fc2, y.b_fc2, nullptr),
|
||||
{m.b_ff, m.b_h}, {m.b_o});
|
||||
} else {
|
||||
y.op_router = rw(b, gemm_op(m.n_expert, E, y.w_router), {m.b_h}, {m.b_logits});
|
||||
y.op_topk = rw(b, RAD_OP(b, "router_topk",
|
||||
@@ -416,16 +405,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_STR("act", "none")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_edn, m.b_ew, m.b_sorted}, {m.b_emoe});
|
||||
if constexpr (kPostNorm)
|
||||
y.op_add = add_op(m.b_h, m.b_emoe, m.b_o);
|
||||
else
|
||||
y.op_add = add_op(m.b_x, m.b_emoe, m.b_x);
|
||||
y.op_add = add_op(m.b_h, m.b_emoe, m.b_o);
|
||||
}
|
||||
|
||||
if constexpr (kPostNorm)
|
||||
y.op_norm2 = rw(b, layernorm_op(y.w_norm2, y.b_norm2), {m.b_o}, {m.b_x});
|
||||
else
|
||||
y.op_norm2 = rw(b, layernorm_op(y.w_norm2, y.b_norm2), {m.b_x}, {m.b_h});
|
||||
y.op_norm2 = rw(b, layernorm_op(y.w_norm2, y.b_norm2), {m.b_o}, {m.b_x});
|
||||
|
||||
if (!y.op_qkv || !y.op_rope || !y.op_attn || !y.op_out || !y.op_norm1 || !y.op_norm2)
|
||||
return RAD_E_INVAL;
|
||||
@@ -446,13 +429,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_mean}, {m.b_pooled});
|
||||
|
||||
rad_note(b, "embedding model: %lld layers (%lld routed every %lld), hidden %lld, ffn %lld, "
|
||||
"%lld heads of %lld, %lld experts top %lld; post-norm %d, no expert bias; "
|
||||
int64_t n_routed = 0;
|
||||
for (const Layer& y : m.layers) n_routed += y.moe ? 1 : 0;
|
||||
rad_note(b, "embedding model: %lld layers (%lld routed, every %lld), hidden %lld, ffn %lld, "
|
||||
"%lld heads of %lld, %lld experts top %lld; post-norm, no expert bias; "
|
||||
"mean-pooled to %lld",
|
||||
(long long)g.n_layer, (long long)m.n_expert, (long long)every, (long long)E,
|
||||
(long long)g.n_layer, (long long)n_routed, (long long)every, (long long)E,
|
||||
(long long)g.n_ff, (long long)g.n_head, (long long)g.head_dim,
|
||||
(long long)m.n_expert, (long long)m.n_expert_used, kPostNorm ? 1 : 0,
|
||||
(long long)E);
|
||||
(long long)m.n_expert, (long long)m.n_expert_used, (long long)E);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -474,43 +458,22 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
const Layer& y = m.layers[(size_t)l];
|
||||
|
||||
auto attention = [&] {
|
||||
const rad_buf att_in = kPostNorm ? m.b_x : m.b_h;
|
||||
RAD_ISSUE_N(c, y.op_qkv, T, brows(att_in, T), RAD_W(y.w_qkv), RAD_W(y.b_qkv),
|
||||
RAD_NONE, brows(m.b_qkv, T));
|
||||
RAD_ISSUE(c, y.op_rope, brows(m.b_qkv, T), pos);
|
||||
RAD_ISSUE(c, y.op_attn, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
|
||||
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
|
||||
RAD_ISSUE_N(c, y.op_out, T, brows(m.b_att, T), RAD_W(y.w_out), RAD_W(y.b_out),
|
||||
brows(m.b_x, T), brows(m.b_x, T));
|
||||
};
|
||||
|
||||
if constexpr (kPostNorm) {
|
||||
attention();
|
||||
RAD_ISSUE(c, y.op_norm1, brows(m.b_x, T), RAD_W(y.w_norm1), RAD_W(y.b_norm1),
|
||||
brows(m.b_h, T));
|
||||
} else {
|
||||
RAD_ISSUE(c, y.op_norm1, brows(m.b_x, T), RAD_W(y.w_norm1), RAD_W(y.b_norm1),
|
||||
brows(m.b_h, T));
|
||||
attention();
|
||||
}
|
||||
RAD_ISSUE_N(c, y.op_qkv, T, brows(m.b_x, T), RAD_W(y.w_qkv), RAD_W(y.b_qkv),
|
||||
RAD_NONE, brows(m.b_qkv, T));
|
||||
RAD_ISSUE(c, y.op_rope, brows(m.b_qkv, T), pos);
|
||||
RAD_ISSUE(c, y.op_attn, bcol(m.b_qkv, 0, E, T), bcol(m.b_qkv, E, E, T),
|
||||
bcol(m.b_qkv, 2 * E, E, T), cu, brows(m.b_att, T));
|
||||
RAD_ISSUE_N(c, y.op_out, T, brows(m.b_att, T), RAD_W(y.w_out), RAD_W(y.b_out),
|
||||
brows(m.b_x, T), brows(m.b_x, T));
|
||||
RAD_ISSUE(c, y.op_norm1, brows(m.b_x, T), RAD_W(y.w_norm1), RAD_W(y.b_norm1),
|
||||
brows(m.b_h, T));
|
||||
|
||||
if (!y.moe) {
|
||||
RAD_ISSUE_N(c, y.op_fc1, T, brows(m.b_h, T), RAD_W(y.w_fc1), RAD_W(y.b_fc1),
|
||||
RAD_NONE, brows(m.b_ff, T));
|
||||
if constexpr (kPostNorm)
|
||||
RAD_ISSUE_N(c, y.op_fc2, T, brows(m.b_ff, T), RAD_W(y.w_fc2),
|
||||
RAD_W(y.b_fc2), brows(m.b_h, T), brows(m.b_o, T));
|
||||
else
|
||||
RAD_ISSUE_N(c, y.op_fc2, T, brows(m.b_ff, T), RAD_W(y.w_fc2),
|
||||
RAD_W(y.b_fc2), brows(m.b_x, T), brows(m.b_x, T));
|
||||
if constexpr (kPostNorm)
|
||||
RAD_ISSUE(c, y.op_norm2, brows(m.b_o, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
|
||||
brows(m.b_x, T));
|
||||
RAD_ISSUE_N(c, y.op_fc2, T, brows(m.b_ff, T), RAD_W(y.w_fc2),
|
||||
RAD_W(y.b_fc2), brows(m.b_h, T), brows(m.b_o, T));
|
||||
} else {
|
||||
if constexpr (!kPostNorm)
|
||||
RAD_ISSUE(c, y.op_norm2, brows(m.b_x, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
|
||||
brows(m.b_h, T));
|
||||
RAD_ISSUE(c, y.op_router, brows(m.b_h, T), RAD_W(y.w_router), brows(m.b_logits, T));
|
||||
RAD_ISSUE(c, y.op_topk, brows(m.b_logits, T), brows(m.b_ids, T), brows(m.b_ew, T));
|
||||
RAD_ISSUE(c, y.op_scatter, brows(m.b_ids, T), brows(m.b_sorted, T * K),
|
||||
@@ -524,14 +487,10 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
brows(m.b_edn, T * K));
|
||||
RAD_ISSUE_N(c, y.op_gather, T, brows(m.b_edn, T * K), brows(m.b_ew, T),
|
||||
brows(m.b_sorted, T * K), RAD_NONE, RAD_NONE, brows(m.b_emoe, T));
|
||||
if constexpr (kPostNorm)
|
||||
RAD_ISSUE(c, y.op_add, brows(m.b_h, T), brows(m.b_emoe, T), brows(m.b_o, T));
|
||||
else
|
||||
RAD_ISSUE(c, y.op_add, brows(m.b_x, T), brows(m.b_emoe, T), brows(m.b_x, T));
|
||||
if constexpr (kPostNorm)
|
||||
RAD_ISSUE(c, y.op_norm2, brows(m.b_o, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
|
||||
brows(m.b_x, T));
|
||||
RAD_ISSUE(c, y.op_add, brows(m.b_h, T), brows(m.b_emoe, T), brows(m.b_o, T));
|
||||
}
|
||||
RAD_ISSUE(c, y.op_norm2, brows(m.b_o, T), RAD_W(y.w_norm2), RAD_W(y.b_norm2),
|
||||
brows(m.b_x, T));
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_mean, brows(m.b_x, T), cu, brows(m.b_mean, S));
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <climits>
|
||||
#include <unordered_map>
|
||||
#include <cstring>
|
||||
@@ -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<const bool>(o.issued).load(std::memory_order_relaxed);
|
||||
j["schema"] = schema_json(o.schema ? o.schema : reg.schema(o.op));
|
||||
|
||||
json ws = json::array();
|
||||
|
||||
@@ -175,8 +175,12 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
|
||||
|
||||
/* An imported quantisation is served by the family's quantised plugin (startup.h). A plugin
|
||||
* that declines imports (rad_arch_serves_imports) is left out of the family here: neither
|
||||
* counted as a second quantised plugin nor picked as the only one. */
|
||||
if (imported && !arch_id.empty() && out->arch_plugin.empty()) {
|
||||
* counted as a second quantised plugin nor picked as the only one. Block-scaled fp8 reads
|
||||
* stock weight by weight, so a family with no plugin claiming it is served the same way: the
|
||||
* plugin declares each weight at the encoding it finds (Qwen3.8-Flash-Next-FP8: fp8 routed
|
||||
* experts beside bf16 linears, served by qwen4exp_fp8). */
|
||||
const bool stock = quant == "fp8_e4m3";
|
||||
if ((imported || stock) && !arch_id.empty() && out->arch_plugin.empty()) {
|
||||
std::vector<const Plugin*> fam, quantised;
|
||||
for (const Plugin& p : r.plugins())
|
||||
if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id && p.arch_serves_imports) {
|
||||
@@ -198,7 +202,7 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
|
||||
out->arch_version = pick->version;
|
||||
out->arch_id = pick->arch_id;
|
||||
out->arch_quant = pick->arch_quant;
|
||||
RAD_INFO("quantisation '%s' is imported weight by weight; '%s' serves it as %s",
|
||||
RAD_INFO("quantisation '%s' is read weight by weight; '%s' serves it as %s",
|
||||
quant.c_str(), pick->name.c_str(),
|
||||
pick->arch_quant.empty() ? "(unquantised)" : pick->arch_quant.c_str());
|
||||
}
|
||||
|
||||
@@ -68,8 +68,9 @@ std::string rad_home_file(const std::string& home, const std::string& rel);
|
||||
* its descriptor names the producing tool and no plugin claims it. The family's quantised plugin
|
||||
* serves it: the one plugin claiming a descriptor, or the only plugin if none does. Two quantised
|
||||
* plugins are refused by name. A plugin whose rad_arch_serves_imports returns 0 is left out of
|
||||
* both counts. `out->arch_quant` is the chosen descriptor, which a container
|
||||
* converted from it records. */
|
||||
* both counts. Block-scaled fp8 (`fp8_e4m3`) that no plugin of the family claims is served the
|
||||
* same way, since its weights read stock. `out->arch_quant` is the chosen descriptor, which a
|
||||
* container converted from it records. */
|
||||
int rad_tools_load_plugins(const std::string& radiance_home,
|
||||
const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id,
|
||||
|
||||
+37
-9
@@ -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; } },
|
||||
|
||||
+103
-26
@@ -3644,6 +3644,43 @@ void* pin_whole(int64_t bytes, const std::vector<hsa_agent_t>& cards) {
|
||||
return p;
|
||||
}
|
||||
|
||||
/* Locks [p, p + len) in pieces of at most kPinPiece for every card, each mapped on the cards at
|
||||
* its host address. On failure sets the device error for `who` (asked for `bytes`), unlocks what
|
||||
* was locked and returns false; the mapping stays the caller's to unmap. */
|
||||
bool lock_pieces(char* p, int64_t len, int64_t bytes, std::vector<hsa_agent_t>& cards,
|
||||
const char* who) {
|
||||
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
|
||||
int done = 0;
|
||||
for (; done < pieces; ++done) {
|
||||
const int64_t off = (int64_t)done * kPinPiece;
|
||||
const int64_t n = std::min(kPinPiece, len - off);
|
||||
void* on_card = nullptr;
|
||||
const hsa_status_t st = hsa_amd_memory_lock_to_pool(p + off, (size_t)n, cards.data(),
|
||||
(int)cards.size(), G().host_fine, 0,
|
||||
&on_card);
|
||||
if (st != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("%s(%s): locking piece %d of %d (%s at +%s): %s", who,
|
||||
humanb(bytes).c_str(), done + 1, pieces, humanb(n).c_str(),
|
||||
humanb(off).c_str(), hsa_why(st));
|
||||
break;
|
||||
}
|
||||
if (on_card != p + off) {
|
||||
++done;
|
||||
device_set_error("%s(%s): piece %d of %d is mapped on the cards at %p, not "
|
||||
"at its host address %p, so the pieces are not one range there, "
|
||||
"although the kernel driver reports the SVM API that maps a lock in "
|
||||
"place",
|
||||
who, humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (done < pieces) {
|
||||
for (int i = 0; i < done; ++i) (void)hsa_amd_memory_unlock(p + (int64_t)i * kPinPiece);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void* pin_pieces(int64_t bytes) {
|
||||
std::vector<hsa_agent_t> cards;
|
||||
for (const Dev& d : G().dev) cards.push_back(d.agent);
|
||||
@@ -3672,33 +3709,61 @@ void* pin_pieces(int64_t bytes) {
|
||||
}
|
||||
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
|
||||
|
||||
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
|
||||
int done = 0;
|
||||
for (; done < pieces; ++done) {
|
||||
const int64_t off = (int64_t)done * kPinPiece;
|
||||
const int64_t n = std::min(kPinPiece, len - off);
|
||||
void* on_card = nullptr;
|
||||
const hsa_status_t st = hsa_amd_memory_lock_to_pool(p + off, (size_t)n, cards.data(),
|
||||
(int)cards.size(), G().host_fine, 0,
|
||||
&on_card);
|
||||
if (st != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("rad_dev_alloc(%s): locking piece %d of %d (%s at +%s): %s",
|
||||
humanb(bytes).c_str(), done + 1, pieces, humanb(n).c_str(),
|
||||
humanb(off).c_str(), hsa_why(st));
|
||||
break;
|
||||
}
|
||||
if (on_card != p + off) {
|
||||
++done;
|
||||
device_set_error("rad_dev_alloc(%s): piece %d of %d is mapped on the cards at %p, not "
|
||||
"at its host address %p, so the pieces are not one range there, "
|
||||
"although the kernel driver reports the SVM API that maps a lock in "
|
||||
"place",
|
||||
humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off));
|
||||
break;
|
||||
}
|
||||
if (!lock_pieces(p, len, bytes, cards, "rad_dev_alloc")) {
|
||||
::munmap(p, (size_t)len);
|
||||
return nullptr;
|
||||
}
|
||||
if (done < pieces) {
|
||||
for (int i = 0; i < done; ++i) (void)hsa_amd_memory_unlock(p + (int64_t)i * kPinPiece);
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
g_pinned.emplace((uintptr_t)p, Pinned{len, nullptr});
|
||||
return p;
|
||||
}
|
||||
|
||||
/* pin_pieces over a shared file mapping instead of private anonymous memory: the pages are the
|
||||
* file's (a tmpfs file other processes map too) and the lock takes them in place. The file maps
|
||||
* onto a 2 MiB boundary inside a reservation made with one alignment extra, then the ends are
|
||||
* trimmed. MADV_HUGEPAGE is advised but shmem follows shmem_enabled, not it. A tmpfs page is
|
||||
* swappable until the lock pins it, so MLOCK_ONFAULT keeps the pages in memory meanwhile; a
|
||||
* refusal (the memlock limit) costs only that. */
|
||||
void* pin_pieces_file(int64_t bytes, int fd, int64_t foff) {
|
||||
std::vector<hsa_agent_t> cards;
|
||||
for (const Dev& d : G().dev) cards.push_back(d.agent);
|
||||
if (!svm_in_place()) {
|
||||
device_set_error("rad_dev_map_file(%s): a file range is pinned in place only through the "
|
||||
"kernel driver's SVM API, which this host lacks, so ram=DIR needs it",
|
||||
humanb(bytes).c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const int64_t align = RAD_ALIGN_POOL;
|
||||
const int64_t len = align_up(bytes, 4096);
|
||||
void* m = ::mmap(nullptr, (size_t)(len + align), PROT_NONE,
|
||||
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
|
||||
if (m == MAP_FAILED) {
|
||||
device_set_error("rad_dev_map_file(%s): mmap: %s", humanb(bytes).c_str(),
|
||||
std::strerror(errno));
|
||||
return nullptr;
|
||||
}
|
||||
const uintptr_t lo = (uintptr_t)m;
|
||||
const uintptr_t at = (lo + (uintptr_t)align - 1) & ~((uintptr_t)align - 1);
|
||||
if (::mmap((void*)at, (size_t)len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd,
|
||||
(off_t)foff) == MAP_FAILED) {
|
||||
device_set_error("rad_dev_map_file(%s): mmap of the file at +%s: %s", humanb(bytes).c_str(),
|
||||
humanb(foff).c_str(), std::strerror(errno));
|
||||
::munmap(m, (size_t)(len + align));
|
||||
return nullptr;
|
||||
}
|
||||
if (at > lo) ::munmap(m, at - lo);
|
||||
if (lo + (uintptr_t)align > at) ::munmap((void*)(at + (uintptr_t)len), lo + (uintptr_t)align - at);
|
||||
char* const p = (char*)at;
|
||||
|
||||
if (len >= ((int64_t)2 << 20)) (void)::madvise(p, (size_t)len, MADV_HUGEPAGE);
|
||||
(void)::madvise(p, (size_t)len, MADV_DONTFORK);
|
||||
if (::mlock2(p, (size_t)len, MLOCK_ONFAULT) != 0)
|
||||
RAD_WARN("device: the shared file range %p (%s) could not be locked against swap (mlock2: "
|
||||
"%s)", (void*)p, humanb(len).c_str(), std::strerror(errno));
|
||||
prefer_numa_node(p, len, current_card_numa_node());
|
||||
|
||||
if (!lock_pieces(p, len, bytes, cards, "rad_dev_map_file")) {
|
||||
::munmap(p, (size_t)len);
|
||||
return nullptr;
|
||||
}
|
||||
@@ -3762,6 +3827,17 @@ void* a_alloc(int64_t bytes, int kind) {
|
||||
return p;
|
||||
}
|
||||
|
||||
void* a_map_file(int fd, int64_t foff, int64_t bytes) {
|
||||
if (fd < 0 || foff < 0 || bytes <= 0) {
|
||||
device_set_error("rad_dev_map_file(%d, %lld, %lld): a file, a non-negative offset and a "
|
||||
"positive size are needed", fd, (long long)foff, (long long)bytes);
|
||||
return nullptr;
|
||||
}
|
||||
void* p = pin_pieces_file(bytes, fd, foff);
|
||||
note_alloc(p, bytes, RAD_MEM_HOST_MAPPED);
|
||||
return p;
|
||||
}
|
||||
|
||||
/* Every free invalidates locate()'s cache first. */
|
||||
void (*g_hip_free)(void*, int) = nullptr;
|
||||
void a_free(void* p, int kind) {
|
||||
@@ -3842,6 +3918,7 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
g_hip_host_ptr = hip->host_ptr;
|
||||
g_hip_device_ptr = hip->device_ptr;
|
||||
g_aql.alloc = a_alloc;
|
||||
g_aql.map_file = a_map_file;
|
||||
g_aql.free = a_free;
|
||||
g_aql.host_ptr = a_host_ptr;
|
||||
g_aql.device_ptr = a_device_ptr;
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
+184
-56
@@ -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<float*>(
|
||||
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<const char*>(r.ctx.buf_ptr(r.program.logits_buf));
|
||||
char* const logits = static_cast<char*>(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<const char*>(r.ctx.buf_ptr(r.program.score_hidden));
|
||||
const char* tab = static_cast<const char*>(r.ctx.weight_ptr(r.program.score_table));
|
||||
if (!hid || !tab) return RAD_E_STATE;
|
||||
char* host = reinterpret_cast<char*>(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<const uint16_t*>(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();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
+44
-5
@@ -33,6 +33,7 @@
|
||||
#include "text/tokenizer.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/table_copy.h"
|
||||
#include "format/table_share.h"
|
||||
#include "lora/adapter.h"
|
||||
#include "lora/slots.h"
|
||||
|
||||
@@ -230,7 +231,7 @@ private:
|
||||
int64_t host_late);
|
||||
/* --ngram-placement ram: one copy of the container's [src, src + n) at file offset `foff`,
|
||||
* shared by every rank. Locked for the host gather, or pinned for a device kernel to read
|
||||
* over the link (`card`). */
|
||||
* over the link (`card`); with ram=DIR the pinned copy is a file other engines map too. */
|
||||
int copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
|
||||
std::string* why);
|
||||
/* An auto-chosen pinned copy failed: move every rank's n-gram gather to the host. */
|
||||
@@ -240,6 +241,9 @@ private:
|
||||
* the ranks that read them are gone. */
|
||||
std::vector<TableCopy> table_copies_;
|
||||
std::vector<void*> card_copies_;
|
||||
/* The files behind the card copies made under --ngram-placement ram=DIR. Closed after the
|
||||
* copies are freed, because the holder that leaves last deletes the file. */
|
||||
std::vector<TableShare> table_shares_;
|
||||
std::vector<std::pair<const void*, void*>> table_copy_of_;
|
||||
/* --expert-profile: the decode ranking loaded once, before any rank plans, and handed to every
|
||||
* rank's planner in place of the container's activation profile. */
|
||||
@@ -268,6 +272,9 @@ private:
|
||||
/* The ids' copy recorded tok_end_ ahead of the drafter's passes: collect_step waits for
|
||||
* it alone, and the step loop for step_end_ after the commit. */
|
||||
bool early = false;
|
||||
/* [n_seq][RAD_SCHED_MAX_SPEC] on a tree step (StepPlan::spec_is_tree): each entry's
|
||||
* accepted nodes in commit order (accept_tree's path). Empty on a chain step. */
|
||||
std::vector<int32_t> path;
|
||||
};
|
||||
|
||||
/* The text frontend, loaded from the container. The sampler's grammars walk `vocab_view_`,
|
||||
@@ -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<std::pair<int32_t, TokenScores*>> 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<int32_t> 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). */
|
||||
|
||||
+206
-45
@@ -19,6 +19,7 @@
|
||||
#include "format/rope_override.h"
|
||||
#include "format/share.h"
|
||||
#include "format/table_copy.h"
|
||||
#include "format/table_share.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "mem/vram_budget.h"
|
||||
#include "kvstream/bringup.h"
|
||||
@@ -399,15 +400,59 @@ static int64_t lockable_bytes(int64_t still, int64_t margin, std::string* limit)
|
||||
}
|
||||
|
||||
/* The copy is table_copy_make's (core/format/table_copy.h), or for a card, table_copy_fill into
|
||||
* pinned memory every card maps (rad_dev_alloc RAD_MEM_HOST_MAPPED, locked in pieces). One copy
|
||||
* per container address, shared by every rank; freed in ~Engine. */
|
||||
* pinned memory every card maps (rad_dev_alloc RAD_MEM_HOST_MAPPED, locked in pieces). With
|
||||
* --ngram-placement ram=DIR the pinned memory is a file in DIR mapped shared (core/format/
|
||||
* table_share.h): this engine fills it or, if another engine did, checks samples of it against the
|
||||
* container, and pins it either way. Only a table of kTableShareMin or more is shared: the gather's
|
||||
* scale is an n-gram weight too, since it moves with the table between gather sites, and as a file
|
||||
* its two bytes would cost the 2 MiB header and a 2 MiB page. One copy per container address,
|
||||
* shared by every rank; freed in ~Engine. */
|
||||
int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
|
||||
std::string* why) {
|
||||
for (const auto& c : table_copy_of_)
|
||||
if (c.first == src) { *out = c.second; return RAD_OK; }
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
auto since = [&] {
|
||||
return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
};
|
||||
void* base = nullptr;
|
||||
if (card) {
|
||||
if (card && !cfg_.ngram_share_dir.empty() && n >= kTableShareMin) {
|
||||
const std::string id = table_share_id(file_->path(), foff, n);
|
||||
if (id.empty()) {
|
||||
*why = fmt("the container %s cannot be stat'ed, which names the shared table",
|
||||
file_->path());
|
||||
return RAD_E_IO;
|
||||
}
|
||||
TableShare s;
|
||||
int rc = table_share_open(cfg_.ngram_share_dir, id, n, &s, why);
|
||||
if (rc != RAD_OK) return rc;
|
||||
base = rad_dev_map_file(s.fd, kTableShareHeader, n);
|
||||
if (!base) {
|
||||
*why = fmt("pinning %s of %s: %s", humanb(n).c_str(), s.path.c_str(),
|
||||
rad_dev_last_error());
|
||||
table_share_close(&s);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
if (s.filler) {
|
||||
rc = table_copy_fill(*file_, src, n, foff, static_cast<uint8_t*>(base), why);
|
||||
if (rc == RAD_OK) rc = table_share_mark_ready(&s, n, id, why);
|
||||
} else {
|
||||
rc = table_copy_check(src, n, static_cast<const uint8_t*>(base), why);
|
||||
if (rc != RAD_OK)
|
||||
*why = fmt("the shared file %s does not match the container (%s)", s.path.c_str(),
|
||||
why->c_str());
|
||||
}
|
||||
if (rc != RAD_OK) {
|
||||
rad_dev_free(base, RAD_MEM_HOST_MAPPED);
|
||||
table_share_close(&s);
|
||||
return rc;
|
||||
}
|
||||
card_copies_.push_back(base);
|
||||
table_shares_.push_back(s);
|
||||
RAD_INFO("placement: n-gram table in pinned memory the cards read, %s in shared file %s, "
|
||||
"%s in %.1f s", humanb(n).c_str(), s.path.c_str(),
|
||||
s.filler ? "filled" : "reused (probes match)", since());
|
||||
} else if (card) {
|
||||
base = rad_dev_alloc(n, RAD_MEM_HOST_MAPPED);
|
||||
if (!base) {
|
||||
*why = fmt("pinning %s: %s", humanb(n).c_str(), rad_dev_last_error());
|
||||
@@ -419,16 +464,17 @@ int Engine::copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, v
|
||||
return rc;
|
||||
}
|
||||
card_copies_.push_back(base);
|
||||
RAD_INFO("placement: n-gram table copied into pinned memory the cards read, %s in %.1f s",
|
||||
humanb(n).c_str(), since());
|
||||
} else {
|
||||
TableCopy tc;
|
||||
const int rc = table_copy_make(*file_, src, n, foff, &tc, why);
|
||||
if (rc != RAD_OK) return rc;
|
||||
table_copies_.push_back(tc);
|
||||
base = tc.base;
|
||||
RAD_INFO("placement: n-gram table copied into locked memory, %s in %.1f s",
|
||||
humanb(n).c_str(), since());
|
||||
}
|
||||
RAD_INFO("placement: n-gram table copied into %s, %s in %.1f s",
|
||||
card ? "pinned memory the cards read" : "locked memory", humanb(n).c_str(),
|
||||
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count());
|
||||
table_copy_of_.push_back({ src, base });
|
||||
*out = base;
|
||||
return RAD_OK;
|
||||
@@ -564,8 +610,43 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
* then the container. */
|
||||
const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_total_mib() * MiB +
|
||||
cfg_.prefix_cache_mib * MiB + host_late;
|
||||
const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
|
||||
int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
|
||||
const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy";
|
||||
/* ram=DIR: the copy is a file other engines map too. One already complete costs this engine
|
||||
* no host memory for the table; a weight under kTableShareMin beside it (the scale) is a
|
||||
* private copy either way. */
|
||||
std::string share_note;
|
||||
if (!cfg_.ngram_share_dir.empty() && ngram_bytes > 0) {
|
||||
if (!ngram_device) {
|
||||
RAD_ERR("--ngram-placement ram=%s: only the pinned copy a card reads is shared, and no "
|
||||
"loaded kernel plugin reads an n-gram table on a card (embed_lookup_q has host "
|
||||
"kernels only), so the host gather would read a private locked copy. Use ram "
|
||||
"or disk.", cfg_.ngram_share_dir.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
share_note = fmt("a file in %s that other engines share", cfg_.ngram_share_dir.c_str());
|
||||
if (file_ && !ranks_.empty()) {
|
||||
const Program& prog = ranks_.front()->program;
|
||||
for (size_t i = 1; i < prog.weights.size(); ++i) {
|
||||
const WeightInfo& w = prog.weights[i];
|
||||
if (!is_ngram_table(prog, (rad_weight)i) || w.n_sel < 1) continue;
|
||||
const RadFileEntry* e = file_->find(w.source);
|
||||
if (!e) continue;
|
||||
const RadFilePlane& p0 = file_->plane(*e, w.sel[0]);
|
||||
if ((int64_t)p0.bytes < kTableShareMin) continue;
|
||||
const std::string id =
|
||||
table_share_id(file_->path(), (int64_t)p0.offset, (int64_t)p0.bytes);
|
||||
if (table_share_is_ready(cfg_.ngram_share_dir, id, (int64_t)p0.bytes)) {
|
||||
need = align_up(std::max<int64_t>(ngram_bytes - (int64_t)p0.bytes, 0),
|
||||
(int64_t)2 << 20);
|
||||
share_note = fmt("a complete shared file in %s already holds it, which "
|
||||
"takes no memory of this engine's own for the table",
|
||||
cfg_.ngram_share_dir.c_str());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
auto card_holds = [&](std::string* why) {
|
||||
std::vector<VramFacts> with = facts;
|
||||
int64_t fixed = 0;
|
||||
@@ -640,7 +721,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
"%s: %s", humanb(ngram_bytes).c_str(), copy, ram_why.c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
ng_why = "as asked";
|
||||
ng_why = share_note.empty() ? std::string("as asked") : "as asked, as " + share_note;
|
||||
} else if (card) {
|
||||
ng = TablePlacement::Vram;
|
||||
ng_why = "the card holds it beside the other weights and a KV pool for one "
|
||||
@@ -896,6 +977,7 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
bc.max_seqs = cfg_.max_seqs;
|
||||
bc.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
bc.max_spec = cfg_.n_spec;
|
||||
bc.draft_tree = draft_tree_ ? 1 : 0;
|
||||
bc.tp_wire_lossy = cfg_.tp_wire_exact ? 0 : 1;
|
||||
/* The engine always states the KV dtype. RAD_DT_INVALID (zero) remains valid in the ABI for
|
||||
* other callers and means the plugin's default. */
|
||||
@@ -1125,6 +1207,22 @@ int Engine::declare() {
|
||||
RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why);
|
||||
decide("chained launches", on ? "on" : "off", why);
|
||||
}
|
||||
/* Trees: a block drafter's proposals verified as a tree, where the model's plugin measured a
|
||||
* gain with one (RadArchProbe::tree_pays; the Gemma 4 31B with DFlash2: +7% single-stream
|
||||
* decode, +6-9% aggregate at 1-16 users on 4x R9700) and the drafter decodes speculatively.
|
||||
* A tree changes no token, only how many drafts land a step. */
|
||||
{
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
/* A tree is verified only behind a step issued ahead (step_loop). The KL mode, which issues
|
||||
* none, drafts nothing either (n_spec is 0 there by now), so this never runs under it. */
|
||||
draft_tree_ = cfg_.n_spec > 0 && pb.tree_pays != 0;
|
||||
if (draft_tree_) {
|
||||
const char* why = "the model's plugin measured a gain with them";
|
||||
RAD_INFO("draft trees: asked -- %s", why);
|
||||
decide("draft trees", "asked", why);
|
||||
}
|
||||
}
|
||||
/* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio
|
||||
* encoder (`radiance.encoder` names one) and the deployment is not text-only. */
|
||||
if (cfg_.mm_audio_frames < 0) {
|
||||
@@ -1364,7 +1462,14 @@ int Engine::declare() {
|
||||
drafter_name_ = p0.drafter_name;
|
||||
drafter_.name = drafter_name_.c_str();
|
||||
if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{};
|
||||
drafter_short_ = drafter_.kind == RAD_DRAFT_BLOCK && cfg_.draft_short_from > 0
|
||||
/* A tree drafter (rad_drafter_tree): its parents plane rides with the proposal. */
|
||||
tree_ = drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0 && p0.drafter_tree;
|
||||
tree_parents_ = tree_ ? p0.drafter_parents : 0;
|
||||
/* --draft-short-from auto: a chain keeps its own block, a tree runs its short block from two
|
||||
* decoding sequences on. Its nodes are verify rows every drafting sequence pays for, which a
|
||||
* wide tree's extra nodes repay at one sequence and not at many. */
|
||||
short_from_ = cfg_.draft_short_from >= 0 ? cfg_.draft_short_from : (tree_ ? 2 : 0);
|
||||
drafter_short_ = drafter_.kind == RAD_DRAFT_BLOCK && short_from_ > 0
|
||||
? p0.drafter_short_block : 0;
|
||||
if (cfg_.draft_short_from > 0 && drafter_.kind == RAD_DRAFT_NONE)
|
||||
RAD_WARN("--draft-short-from %lld: this deployment runs no drafter, so there is no block "
|
||||
@@ -1374,14 +1479,23 @@ int Engine::declare() {
|
||||
drafter_name_.c_str(),
|
||||
drafter_.kind == RAD_DRAFT_BLOCK ? "declares no shorter block, so it keeps its own"
|
||||
: "is a serial head, which proposes no block");
|
||||
if (drafter_short_)
|
||||
if (drafter_short_ && tree_)
|
||||
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
|
||||
"row(s), %lld token(s)", (long long)cfg_.draft_short_from,
|
||||
"row(s), a tree of %lld node(s) over it", (long long)short_from_,
|
||||
drafter_name_.c_str(), (long long)drafter_short_,
|
||||
(long long)std::min<int64_t>(drafter_.depth, drafter_short_ - 1));
|
||||
else if (drafter_short_)
|
||||
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
|
||||
"row(s), %lld token(s)", (long long)short_from_,
|
||||
drafter_name_.c_str(),
|
||||
(long long)drafter_short_,
|
||||
(long long)(drafter_short_ - ((drafter_.block > 0 ? drafter_.block
|
||||
: drafter_.depth + 1) -
|
||||
drafter_.depth)));
|
||||
if (tree_)
|
||||
RAD_INFO("speculation: '%s' proposes a tree of %d node(s); each verify follows the deepest "
|
||||
"path the target agrees with, and that path's K and V move into place",
|
||||
drafter_.name, drafter_.depth);
|
||||
if (drafter_.kind != RAD_DRAFT_NONE) {
|
||||
/* A zero proposal handle means the sampler's token buffer: the head's logits go through
|
||||
* the ordinary sampler chain. */
|
||||
@@ -1610,6 +1724,7 @@ int Engine::plan() {
|
||||
* memory, and the real pool does not exist yet. */
|
||||
KVManager probe;
|
||||
host_arenas += arena_host_bytes(r->program);
|
||||
probe.set_drafter_window_snapshot(drafter_window_snap(r->program));
|
||||
if (declare_ring_windows(probe, r->program) == RAD_OK &&
|
||||
probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
|
||||
ck_slot += probe.checkpoint_bytes();
|
||||
@@ -1702,9 +1817,9 @@ int Engine::plan() {
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes,
|
||||
ngram_device, ngram_host, ck_store + host_arenas));
|
||||
/* --draft-expert-placement host: the drafter's experts are pinned in the host pool before
|
||||
* the strategy runs, so they are not part of the elastic plane the card must hold and the
|
||||
* pool must have room for them on top of the trunk's spill. Growing the pool here, before
|
||||
* the split, is what lets a drafter fit beside a trunk that already fills the card. */
|
||||
* the strategy runs, so they leave the elastic plane the card must hold and the pool must
|
||||
* have room for them on top of the trunk's spill. The pool grows here, before the split,
|
||||
* so a drafter fits beside a trunk that already fills the card. */
|
||||
if (cfg_.draft_expert_placement == "host") {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
int64_t draft_max = 0;
|
||||
@@ -1715,10 +1830,9 @@ int Engine::plan() {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (draft_max > 0) {
|
||||
/* The pool must hold the drafter on top of the trunk's own spill, so it grows by
|
||||
* the drafter's bytes and the floor is recomputed against that larger room with
|
||||
* the drafter taken out of the plane the card places. */
|
||||
const int64_t add = (align_up(draft_max, MiB) + MiB - 1) / MiB;
|
||||
/* The pool grows by the drafter's bytes, and each rank's floor is recomputed
|
||||
* against that room with the drafter out of the plane the card places. */
|
||||
const int64_t add = align_up(draft_max, MiB) / MiB;
|
||||
cfg_.host_pool_mib += add;
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
int64_t room = cfg_.host_pool_mib * MiB;
|
||||
@@ -1797,6 +1911,7 @@ int Engine::plan() {
|
||||
* its carve). */
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
probes[i] = std::make_unique<KVManager>();
|
||||
probes[i]->set_drafter_window_snapshot(drafter_window_snap(ranks_[i]->program));
|
||||
if (declare_ring_windows(*probes[i], ranks_[i]->program) != RAD_OK ||
|
||||
probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
|
||||
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
|
||||
@@ -1882,14 +1997,22 @@ int Engine::plan() {
|
||||
in.profile = file_->profile();
|
||||
in.n_profile = (int64_t)file_->header().prof_count;
|
||||
}
|
||||
/* --expert-profile replaces the container's activation profile, which is prefill-heavy:
|
||||
* decode-hot experts differ, and the pin below keeps them resident. Loaded once, before
|
||||
* any rank plans, so every rank ranks the same way. */
|
||||
/* --expert-profile replaces the container's activation profile, which is prefill-heavy
|
||||
* while decode-hot experts differ (--expert-pin-top keeps them resident). Loaded once, at
|
||||
* the first rank's plan, so every rank ranks the same way. */
|
||||
if (!cfg_.expert_profile.empty()) {
|
||||
if (expert_profile_.empty() && ri == 0) {
|
||||
int32_t trunk = -1;
|
||||
const int pr = xs_profile_load(cfg_.expert_profile, &expert_profile_, &trunk);
|
||||
if (pr < 0) return pr;
|
||||
/* A profile from another model would rank its layers onto this one's. */
|
||||
if (trunk >= 0 && trunk != (int32_t)meta_.n_layers) {
|
||||
RAD_ERR("--expert-profile: %s counts %d trunk layers and this model has %d: "
|
||||
"it was recorded on another model", cfg_.expert_profile.c_str(),
|
||||
(int)trunk, (int)meta_.n_layers);
|
||||
expert_profile_.clear();
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (!expert_profile_.empty()) {
|
||||
in.profile = expert_profile_.data();
|
||||
@@ -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<int64_t>(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<int64_t>(checkpoint_slots_want(*pol, cfg_.max_seqs, ctx, interval),
|
||||
kCheckpointSlotsFloor);
|
||||
const int64_t floor_bytes =
|
||||
slot > INT64_MAX / std::max<int64_t>(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<int64_t>(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());
|
||||
|
||||
+88
-7
@@ -175,6 +175,14 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
|
||||
: rk.ctx.buf_ptr(rk.tok_buf));
|
||||
a.src_pitch = (drafter_.proposal && drafter_.proposal_pitch > 0)
|
||||
? drafter_.proposal_pitch : 1;
|
||||
/* A tree drafter's parents, at the proposal's pitch (rad_drafter_tree). */
|
||||
if (tree_ && mode == ADV_BTAKE) {
|
||||
a.par = static_cast<const int32_t*>(rk.ctx.buf_ptr(tree_parents_));
|
||||
if (!a.par) {
|
||||
RAD_ERR("drafter '%s': rank %zu has no parents buffer", drafter_.name, i);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
a.src = static_cast<const int32_t*>(rk.ctx.buf_ptr(rk.tok_buf));
|
||||
}
|
||||
@@ -188,6 +196,49 @@ int Engine::advance_all(int mode, int round, bool from_proposal, int rows) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ADV_COMPACT on every rank, against the scheduler's latest build (the tree step just accepted):
|
||||
* the accepted paths' K and V into place in every paged group. Each rank's pools are its own. */
|
||||
int Engine::tree_compact(int rows) {
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
Rank& rk = *ranks_[i];
|
||||
AdvanceArgs a = sched_.advance_args((int)i);
|
||||
if (rows >= 0 && rows < a.n_seq) a.n_seq = rows;
|
||||
a.mode = 0;
|
||||
a.st = rk.step_slots;
|
||||
const Program& p = rk.program;
|
||||
for (size_t g = 1; g < p.kv_groups.size() && (int)g < a.n_groups; ++g) {
|
||||
const int kind = p.kv_groups[g].decl.kind;
|
||||
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) continue;
|
||||
const KVPoolBinding* b = rk.ctx.kv_binding((uint32_t)g);
|
||||
if (!b || !b->base || b->rank != 4) continue; /* a zero group on this rank */
|
||||
const int bits = rad_dtype_bits(b->dtype);
|
||||
const int64_t row = bits > 0 ? b->shape[3] * bits / 8 : 0;
|
||||
int32_t layers = 0;
|
||||
for (int32_t s : b->layer_slot) layers += s >= 0;
|
||||
if (row <= 0 || row % 16 || (bits != 8 && bits != 16 && bits != 32) ||
|
||||
(b->bytes && (int64_t)layers * b->layer_stride > b->bytes)) {
|
||||
RAD_ERR("speculation: KV group %zu's cache (%s, %lld-byte rows) is not one a tree's "
|
||||
"acceptance can move", g, rad_dtype_name(b->dtype), (long long)row);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (a.n_pool >= kAdvMaxPools) {
|
||||
RAD_ERR("speculation: more than %d paged KV groups for a tree's acceptance",
|
||||
(int)kAdvMaxPools);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
AdvPool& q = a.pool[a.n_pool++];
|
||||
q.base = static_cast<char*>(b->base);
|
||||
q.layer_stride = b->layer_stride;
|
||||
q.n_layers = layers;
|
||||
q.n_head = (int32_t)b->shape[1];
|
||||
q.row_bytes = (int32_t)row;
|
||||
q.grp = (int32_t)g;
|
||||
}
|
||||
RAD_TRY(step_compact(a, rk.ctx.stream()));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Issue the step's draft passes behind it, without waiting. After the trunk's ranks join: the
|
||||
* acceptance on every rank, the sampled-id readback (before a round can overwrite them), the
|
||||
* history pass and every round, then the final proposal into the slots and their readback.
|
||||
@@ -496,9 +547,13 @@ void Engine::block_shape(int* block, int* steps) {
|
||||
* fewer proposals as rows. The load is the step just run's, which the next step, the one these
|
||||
* proposals are for, mostly repeats (Scheduler::short_block_on). */
|
||||
if (drafter_short_ <= 0) return;
|
||||
short_on_ = Scheduler::short_block_on(short_on_, sched_.decoded_seqs(), cfg_.draft_short_from);
|
||||
short_on_ = Scheduler::short_block_on(short_on_, sched_.decoded_seqs(), short_from_);
|
||||
if (short_on_) {
|
||||
*steps -= *block - (int)drafter_short_;
|
||||
/* A tree (rad_drafter_tree) grows a tree of its own over the shorter pass, at most its
|
||||
* draft positions of nodes (DFlash2 attends across its block, so the short pass is not the
|
||||
* full pass's prefix); the verify takes that many. */
|
||||
if (tree_) *steps = std::min(*steps, (int)drafter_short_ - 1);
|
||||
else *steps -= *block - (int)drafter_short_;
|
||||
*block = (int)drafter_short_;
|
||||
}
|
||||
}
|
||||
@@ -508,6 +563,9 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
|
||||
if (!block_drafting()) return RAD_OK;
|
||||
|
||||
RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
|
||||
/* A tree's accepted path into place in the trunk's cache, against the same build (the step
|
||||
* just accepted), before any later pass reads it. */
|
||||
if (tree_) RAD_TRY(tree_compact(-1));
|
||||
/* The sampled ids before either pass, as the serial driver reads them. */
|
||||
RAD_TRY(collect_issue(so, /*fence=*/true));
|
||||
|
||||
@@ -518,15 +576,25 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
|
||||
block_shape(&block, &steps);
|
||||
block_steps_ = steps;
|
||||
block_row_.resize((size_t)cfg_.max_seqs);
|
||||
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
|
||||
/* The head reads the block's draft rows. A tree (rad_drafter_tree; DFlash2's convention, the
|
||||
* anchor predicts nothing) reads all block - 1 of them whatever its node count. */
|
||||
const int head = tree_ ? block - 1 : steps;
|
||||
const int n = sched_.block_begin(block, head, (int)drafter_.window, drafter_.mask_token,
|
||||
block_row_.data(), (int)block_row_.size(), /*on_card=*/true);
|
||||
|
||||
/* --draft-coupling: the draws before the query pass reads them (stage_couple_draws). */
|
||||
if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(block_row_.data(), n));
|
||||
|
||||
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
|
||||
* drafter will need, and skipping would leave a permanent hole in its cache. */
|
||||
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
|
||||
* drafter will need, and skipping would leave a permanent hole in its cache. A tree verify's
|
||||
* context rows store only the accepted path, at its committed positions (ADV_CTXTREE). */
|
||||
if (const RadBatch* cb = sched_.block_context(step)) {
|
||||
if (tree_) RAD_TRY(advance_all(ADV_CTXTREE, 0, false));
|
||||
RAD_TRY(block_pass(cb, "context", step));
|
||||
}
|
||||
/* A snapshot carrying the drafter's window is saved now, with the step's context rows stored
|
||||
* and before the query pass and the step issued ahead (save_checkpoints). */
|
||||
if (drafter_snap_) RAD_TRY(save_checkpoints());
|
||||
if (n <= 0) return RAD_OK;
|
||||
const RadBatch* qb = sched_.block_query(step);
|
||||
if (!qb) return RAD_OK;
|
||||
@@ -581,12 +649,25 @@ int Engine::finish_block_drafter(const StepOut& so) {
|
||||
for (int j = 0; j < steps; ++j)
|
||||
draft_out_[(size_t)i * (size_t)steps + (size_t)j] = S.tok[1 + j];
|
||||
}
|
||||
/* -v: what each block pass proposed, a line a sequence, so two runs can be compared draft by
|
||||
* draft where acceptance alone cannot tell them apart (a drafter whose context is wrong still
|
||||
* drafts, and its rejected drafts change no token). */
|
||||
const bool show = (int)log_level() >= (int)Log::Debug;
|
||||
for (int i = 0; i < block_rows_; ++i) {
|
||||
const int32_t* d = &draft_out_[(size_t)i * (size_t)steps];
|
||||
if (show) {
|
||||
std::string t;
|
||||
for (int j = 0; j < steps; ++j) t += fmt(" %d", (int)d[j]);
|
||||
RAD_DEBUG("drafter '%s': sequence %llu proposes%s", drafter_.name,
|
||||
(unsigned long long)block_row_[(size_t)i].seq, t.c_str());
|
||||
}
|
||||
/* As in finish_serial_drafter: the step issued ahead only carries a request whose answer
|
||||
* is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. */
|
||||
* is fixed (Scheduler::step_next_locked), so this agrees with the count it verifies. A
|
||||
* tree's parents come from the same slot, as ADV_BTAKE took them. */
|
||||
if (!r0.sampler.allows_speculation(block_row_[(size_t)i].seq)) continue;
|
||||
const uint64_t seq = block_row_[(size_t)i].seq;
|
||||
const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)steps], steps);
|
||||
const StepSlot& S = slots_host_[block_row_[(size_t)i].card];
|
||||
const int rc = sched_.set_draft(seq, d, steps, tree_ ? S.par : nullptr);
|
||||
if (mtp_couple_)
|
||||
RAD_TRY(bind_couple(seq, i, steps, rc == RAD_OK, block_row_[(size_t)i].card));
|
||||
}
|
||||
|
||||
+39
-12
@@ -237,8 +237,8 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
|
||||
RadModelMeta& m = out->m;
|
||||
/* Nomic BERT states its geometry with n_layer, n_embd, n_head, n_inner, n_positions and
|
||||
* moe_top_k. They are fallbacks in the same chain, so a config carrying both spellings keeps
|
||||
* the HuggingFace one and every existing checkpoint reads byte for byte as before. */
|
||||
* moe_top_k. They are the last fallbacks in each chain, so a config carrying both spellings
|
||||
* reads the HuggingFace one. */
|
||||
m.n_layers = gi("num_hidden_layers", gi("n_layer", 0));
|
||||
m.n_embd = gi("hidden_size", gi("n_embd", 0));
|
||||
m.n_head = gi("num_attention_heads", gi("n_head", 0));
|
||||
@@ -274,18 +274,21 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
|
||||
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4): the
|
||||
* quant_method plus its fmt ("fp8_e4m3"), so the checkpoint, not a flag, distinguishes fp8 from
|
||||
* bf16 releases.
|
||||
* bf16 releases. transformers' fine-grained FP8 states no fmt (Qwen3.8-Flash-Next-FP8's config)
|
||||
* and is always E4M3, so a bare "fp8" is "fp8_e4m3", as a release that states it is.
|
||||
*
|
||||
* A Gemma 4 E2B/E4B checkpoint states no quantization_config: it is the bf16 release that
|
||||
* arch/gemma4_bf16 serves as compressed-tensors, which is what rad-convert's
|
||||
* `--set quantization_config.quant_method=compressed-tensors` said by hand. Its per-layer
|
||||
* embeddings or shared KV layers name the E form; arch/gemma4 serves only the 26B-A4B/31B shape
|
||||
* and refuses those two keys, so the bare (gemma4, "") descriptor must not win. */
|
||||
* A Gemma 4 E2B/E4B checkpoint states no quantization_config: it is a bf16 release that
|
||||
* arch/gemma4_bf16 serves under "compressed-tensors", so it needs no
|
||||
* `--set quantization_config.quant_method=compressed-tensors`. Its per-layer embeddings or shared
|
||||
* KV layers name the E form; arch/gemma4 serves only the 26B-A4B/31B shape and refuses those two
|
||||
* keys, so the bare (gemma4, "") descriptor must not win. */
|
||||
std::string quant_descriptor(const MetaOwn& m) {
|
||||
std::string q;
|
||||
if (const char* qm = m.get("quantization_config.quant_method")) {
|
||||
q = qm;
|
||||
if (const char* fm = m.get("quantization_config.fmt")) { q += "_"; q += fm; }
|
||||
const char* fm = m.get("quantization_config.fmt");
|
||||
if (!fm && q == "fp8") fm = "e4m3";
|
||||
if (fm) { q += "_"; q += fm; }
|
||||
return q;
|
||||
}
|
||||
if (m.arch == "gemma4") {
|
||||
@@ -2401,6 +2404,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
* RAD_MAP_COPY alternatives, first present wins (a tied lm_head is output.weight when
|
||||
* shipped, else the embedding). */
|
||||
const bool alternatives = maps.front()->mode == RAD_MAP_COPY && srcs.size() > 1;
|
||||
/* Pieces whose scale is one `X.weight_scale` their shards share (below). */
|
||||
bool shard_scaled = false;
|
||||
for (const Src1& s1 : srcs) {
|
||||
const SrcTensor* st = ck.find(s1.name);
|
||||
/* An FP8 weight's scale plane: `X.weight_scale_inv` (block-scaled releases) or
|
||||
@@ -2410,6 +2415,17 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
const SrcTensor* sc = st ? ck.find(std::string(s1.name) + "_scale_inv") : nullptr;
|
||||
if (!sc && st && (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2))
|
||||
sc = ck.find(std::string(s1.name) + "_scale");
|
||||
/* A table split into shards, `X.shard_<i>.weight`, under one scale for all of them,
|
||||
* `X.weight_scale` (Qwen3.8-Flash-Next-FP8's n-gram table). */
|
||||
if (!sc && st && (st->rad_dtype == RAD_F8E4M3 || st->rad_dtype == RAD_F8E5M2)) {
|
||||
const std::string n = s1.name;
|
||||
const size_t at = n.rfind(".shard_");
|
||||
const size_t end = n.size() >= 7 ? n.size() - 7 : 0;
|
||||
if (at != std::string::npos && end > at + 7 && n.compare(end, 7, ".weight") == 0 &&
|
||||
std::all_of(n.begin() + (long)at + 7, n.begin() + (long)end,
|
||||
[](char c) { return c >= '0' && c <= '9'; }))
|
||||
if ((sc = ck.find(n.substr(0, at) + ".weight_scale"))) shard_scaled = true;
|
||||
}
|
||||
/* A weight shipped in an imported form is read through that form's views. */
|
||||
{
|
||||
const SrcTensor *ic = nullptr, *is = nullptr;
|
||||
@@ -2501,8 +2517,8 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
out->why = std::string("'") + p0.name + "' is a GGUF " +
|
||||
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
|
||||
/* Q8_0, Q4_K and Q6_K become their planes when every piece is of that type and they join
|
||||
* along rows, so each row of the weight is one source row of blocks; the loader still
|
||||
* refuses them, since the blocks interleave what the planes hold apart. */
|
||||
* along rows, so each row of the weight is one source row of blocks. rad-convert imports
|
||||
* them; the loader refuses them, since the blocks interleave what the planes hold apart. */
|
||||
bool one_type = true;
|
||||
for (const SrcTensor* pk : out->pieces) one_type = one_type && pk->ggml == p0.ggml;
|
||||
RadEncoding enc;
|
||||
@@ -2693,7 +2709,18 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
bad = true;
|
||||
out->why = "its FP8 pieces are joined along a column, across their scale planes";
|
||||
}
|
||||
if (!bad) {
|
||||
/* Shards under the one scale they share are one tensor with one scale, byte for byte:
|
||||
* `fp8_e4m3*<s>[*x*]`. */
|
||||
bool one_scale = !bad && shard_scaled && n_one == (int)out->pieces.size();
|
||||
for (size_t k = 1; one_scale && k < out->scales.size(); ++k)
|
||||
one_scale = out->scales[k] == out->scales[0];
|
||||
if (one_scale) {
|
||||
out->trivial = out->why.empty();
|
||||
rad_enc_clear(&out->enc);
|
||||
rad_enc_copy_str(out->enc.scheme, "affine");
|
||||
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
|
||||
rad_enc_add_plane(&out->enc, "scale", sdt, 0, 0);
|
||||
} else if (!bad) {
|
||||
out->trivial = out->why.empty() && n_one == 0;
|
||||
/* A per-tensor scale is written once a row (ckpt_plane_rows). */
|
||||
if (n_one) {
|
||||
|
||||
@@ -63,13 +63,13 @@ inline void put_nibbles(uint8_t* row, const uint8_t* q, int n) {
|
||||
row[k] = (uint8_t)((q[2 * k] & 15) | ((q[2 * k + 1] & 15) << 4));
|
||||
}
|
||||
|
||||
/* Q4_K: value v is a nibble of qs[32*(v/64) + v%32], the low one for the first 32 of each 64. The
|
||||
* 6-bit scale and min of sub-block j are get_scale_min_k4's. */
|
||||
/* Q4_K: value v is a nibble of qs[32*(v/64) + v%32], the low one for the first 32 of each 64. */
|
||||
inline uint32_t k_low4(const uint8_t* qs, int v) {
|
||||
const uint8_t q = qs[32 * (v / 64) + v % 32];
|
||||
return (uint32_t)((v % 64) < 32 ? q & 15 : q >> 4);
|
||||
}
|
||||
|
||||
/* Q4_K: the 6-bit scale and min of sub-block j, as llama.cpp's get_scale_min_k4 unpacks them. */
|
||||
inline void k4_scale_min(int j, const uint8_t* q, uint32_t* d, uint32_t* m) {
|
||||
if (j < 4) {
|
||||
*d = q[j] & 63u;
|
||||
|
||||
+15
-10
@@ -14,6 +14,20 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
int table_copy_check(const uint8_t* src, int64_t n, const uint8_t* buf, std::string* why) {
|
||||
if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
|
||||
const int64_t probe = std::min<int64_t>(n, 4096);
|
||||
bool same = std::memcmp(buf, src, (size_t)probe) == 0 &&
|
||||
std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0;
|
||||
for (int64_t o = 0; same && o + 4096 <= n; o += std::max<int64_t>(n / 64, 4096))
|
||||
same = std::memcmp(buf + o, src + o, 4096) == 0;
|
||||
if (!same) {
|
||||
*why = "the copy does not match the container's mapping";
|
||||
return RAD_E_IO;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
|
||||
uint8_t* buf, std::string* why) {
|
||||
if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
|
||||
@@ -45,16 +59,7 @@ int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t
|
||||
*why = fmt("reading the container failed (%s)", rad_strerror(err.load()));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
const int64_t probe = std::min<int64_t>(n, 4096);
|
||||
bool same = std::memcmp(buf, src, (size_t)probe) == 0 &&
|
||||
std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0;
|
||||
for (int64_t o = 0; same && o + 4096 <= n; o += std::max<int64_t>(n / 64, 4096))
|
||||
same = std::memcmp(buf + o, src + o, 4096) == 0;
|
||||
if (!same) {
|
||||
*why = "the copy does not match the container's mapping";
|
||||
return RAD_E_IO;
|
||||
}
|
||||
return RAD_OK;
|
||||
return table_copy_check(src, n, buf, why);
|
||||
}
|
||||
|
||||
int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
/* table_share.cpp -- see table_share.h. */
|
||||
#include "table_share.h"
|
||||
|
||||
#include "../rad_internal.h"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <sys/file.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/vfs.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
namespace {
|
||||
|
||||
constexpr char kMagic[8] = { 'R', 'A', 'D', 'N', 'G', 'R', 'M', '1' };
|
||||
constexpr uint32_t kVersion = 1;
|
||||
constexpr int64_t kHuge = (int64_t)2 << 20;
|
||||
/* A leaving holder tries for LOCK_EX for about a second (table_share_close). */
|
||||
constexpr int kLeaveTries = 10;
|
||||
constexpr unsigned kLeaveWaitUs = 100 * 1000;
|
||||
|
||||
/* All integers host-endian: the file lives in a tmpfs, so it never leaves the machine. */
|
||||
struct Header {
|
||||
char magic[8];
|
||||
uint32_t version;
|
||||
uint32_t ready;
|
||||
uint64_t bytes;
|
||||
uint64_t filler_pid; /* for whoever reads the file by hand; nothing depends on it */
|
||||
char id[24]; /* the 16 hex digits and a NUL */
|
||||
};
|
||||
static_assert(sizeof(Header) <= 4096, "the header must fit the first page");
|
||||
|
||||
enum class Seen { Fresh, Partial, Ready, Foreign };
|
||||
|
||||
std::string errno_text() { return std::strerror(errno); }
|
||||
|
||||
/* What the open data file holds. A fresh file and a half-filled one have a zero header; a header
|
||||
* that is not this protocol's or not for this table is Foreign. */
|
||||
Seen classify(int fd, const std::string& id, int64_t n, std::string* why) {
|
||||
struct stat st{};
|
||||
if (::fstat(fd, &st) != 0) {
|
||||
*why = fmt("fstat: %s", errno_text().c_str());
|
||||
return Seen::Foreign;
|
||||
}
|
||||
if (st.st_size == 0) return Seen::Fresh;
|
||||
Header h{};
|
||||
const ssize_t got = ::pread(fd, &h, sizeof h, 0);
|
||||
if (got != (ssize_t)sizeof h) {
|
||||
*why = fmt("its header is %lld bytes short", (long long)(sizeof h - (got < 0 ? 0 : got)));
|
||||
return Seen::Foreign;
|
||||
}
|
||||
Header zero{};
|
||||
if (std::memcmp(&h, &zero, sizeof h) == 0) return Seen::Partial;
|
||||
if (std::memcmp(h.magic, kMagic, sizeof kMagic) != 0 || h.version != kVersion) {
|
||||
*why = "it is not a table file of this version";
|
||||
return Seen::Foreign;
|
||||
}
|
||||
if (h.bytes != (uint64_t)n || std::strncmp(h.id, id.c_str(), sizeof h.id) != 0) {
|
||||
*why = fmt("it holds %s of table '%.16s', not %s of '%s'", humanb((int64_t)h.bytes).c_str(),
|
||||
h.id, humanb(n).c_str(), id.c_str());
|
||||
return Seen::Foreign;
|
||||
}
|
||||
if (!h.ready) return Seen::Partial;
|
||||
if (st.st_size != table_share_file_bytes(n)) {
|
||||
*why = fmt("it is marked ready but is %lld bytes long, not %lld", (long long)st.st_size,
|
||||
(long long)table_share_file_bytes(n));
|
||||
return Seen::Foreign;
|
||||
}
|
||||
return Seen::Ready;
|
||||
}
|
||||
|
||||
std::string file_path(const std::string& dir, const std::string& id) {
|
||||
const bool slash = !dir.empty() && dir.back() == '/';
|
||||
return dir + (slash ? "" : "/") + "ngram-" + id + ".tab";
|
||||
}
|
||||
|
||||
void fail(TableShare* s) {
|
||||
if (s->lock_fd >= 0) ::close(s->lock_fd);
|
||||
if (s->fd >= 0) ::close(s->fd);
|
||||
*s = TableShare{};
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int64_t table_share_file_bytes(int64_t n) {
|
||||
return kTableShareHeader + ((n + kHuge - 1) & ~(kHuge - 1));
|
||||
}
|
||||
|
||||
std::string table_share_id(const std::string& container_path, int64_t foff, int64_t n) {
|
||||
char real[PATH_MAX];
|
||||
const std::string path = ::realpath(container_path.c_str(), real) ? std::string(real)
|
||||
: container_path;
|
||||
struct stat st{};
|
||||
if (::stat(path.c_str(), &st) != 0) return std::string();
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
auto feed = [&](const void* p, size_t len) {
|
||||
const unsigned char* b = static_cast<const unsigned char*>(p);
|
||||
for (size_t i = 0; i < len; ++i) h = (h ^ b[i]) * 1099511628211ull;
|
||||
};
|
||||
const int64_t parts[] = { (int64_t)st.st_size, (int64_t)st.st_mtim.tv_sec,
|
||||
(int64_t)st.st_mtim.tv_nsec, foff, n };
|
||||
feed(path.data(), path.size());
|
||||
feed(parts, sizeof parts);
|
||||
return fmt("%016llx", (unsigned long long)h);
|
||||
}
|
||||
|
||||
int table_share_open(const std::string& dir, const std::string& id, int64_t n, TableShare* out,
|
||||
std::string* why) {
|
||||
if (!out || !why || dir.empty() || id.empty() || n <= 0) return RAD_E_INVAL;
|
||||
*out = TableShare{};
|
||||
out->path = file_path(dir, id);
|
||||
out->lock_path = out->path + ".lock";
|
||||
|
||||
/* A holder that left last deletes the file while we open it: its unlink comes with LOCK_EX, so
|
||||
* once we hold LOCK_SH the link count says whether the file is still the one in the directory. */
|
||||
for (;;) {
|
||||
out->fd = ::open(out->path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
|
||||
if (out->fd < 0) {
|
||||
*why = fmt("opening %s: %s", out->path.c_str(), errno_text().c_str());
|
||||
*out = TableShare{};
|
||||
return RAD_E_IO;
|
||||
}
|
||||
if (::flock(out->fd, LOCK_SH) != 0) {
|
||||
*why = fmt("locking %s: %s", out->path.c_str(), errno_text().c_str());
|
||||
fail(out);
|
||||
return RAD_E_IO;
|
||||
}
|
||||
struct stat st{};
|
||||
if (::fstat(out->fd, &st) != 0) {
|
||||
*why = fmt("fstat %s: %s", out->path.c_str(), errno_text().c_str());
|
||||
fail(out);
|
||||
return RAD_E_IO;
|
||||
}
|
||||
if (st.st_nlink > 0) {
|
||||
struct statfs fs{};
|
||||
if (::fstatfs(out->fd, &fs) == 0 && (long)fs.f_type != 0x01021994L &&
|
||||
(long)fs.f_type != 0x858458f6L)
|
||||
RAD_WARN("n-gram table share: %s is not on a tmpfs or ramfs, so the table is "
|
||||
"written to its disk and held in the page cache", dir.c_str());
|
||||
break;
|
||||
}
|
||||
::close(out->fd);
|
||||
}
|
||||
|
||||
std::string seen_why;
|
||||
Seen seen = classify(out->fd, id, n, &seen_why);
|
||||
if (seen == Seen::Foreign) {
|
||||
*why = fmt("%s exists, and %s", out->path.c_str(), seen_why.c_str());
|
||||
fail(out);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (seen == Seen::Ready) {
|
||||
out->ready = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
out->lock_fd = ::open(out->lock_path.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0644);
|
||||
if (out->lock_fd < 0) {
|
||||
*why = fmt("opening %s: %s", out->lock_path.c_str(), errno_text().c_str());
|
||||
fail(out);
|
||||
return RAD_E_IO;
|
||||
}
|
||||
if (::flock(out->lock_fd, LOCK_EX) != 0) {
|
||||
*why = fmt("locking %s: %s", out->lock_path.c_str(), errno_text().c_str());
|
||||
fail(out);
|
||||
return RAD_E_IO;
|
||||
}
|
||||
/* The holder we waited for may have finished. */
|
||||
seen = classify(out->fd, id, n, &seen_why);
|
||||
if (seen == Seen::Foreign) {
|
||||
*why = fmt("%s exists, and %s", out->path.c_str(), seen_why.c_str());
|
||||
fail(out);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (seen == Seen::Ready) {
|
||||
::close(out->lock_fd);
|
||||
out->lock_fd = -1;
|
||||
out->ready = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (::ftruncate(out->fd, table_share_file_bytes(n)) != 0) {
|
||||
*why = fmt("sizing %s to %s: %s", out->path.c_str(),
|
||||
humanb(table_share_file_bytes(n)).c_str(), errno_text().c_str());
|
||||
fail(out);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
out->filler = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int table_share_mark_ready(TableShare* s, int64_t n, const std::string& id, std::string* why) {
|
||||
if (!s || !why || s->fd < 0 || !s->filler || id.size() >= sizeof(Header::id))
|
||||
return RAD_E_INVAL;
|
||||
Header h{};
|
||||
std::memcpy(h.magic, kMagic, sizeof kMagic);
|
||||
h.version = kVersion;
|
||||
h.ready = 1;
|
||||
h.bytes = (uint64_t)n;
|
||||
h.filler_pid = (uint64_t)::getpid();
|
||||
std::memcpy(h.id, id.c_str(), id.size());
|
||||
if (::pwrite(s->fd, &h, sizeof h, 0) != (ssize_t)sizeof h) {
|
||||
*why = fmt("writing the header of %s: %s", s->path.c_str(), errno_text().c_str());
|
||||
return RAD_E_IO;
|
||||
}
|
||||
if (s->lock_fd >= 0) {
|
||||
::close(s->lock_fd);
|
||||
s->lock_fd = -1;
|
||||
}
|
||||
s->ready = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void table_share_close(TableShare* s) {
|
||||
if (!s) return;
|
||||
if (s->lock_fd >= 0) ::close(s->lock_fd);
|
||||
if (s->fd >= 0) {
|
||||
/* Engines stopped together (a compose recreate) leave together: one that tries while the
|
||||
* other still holds LOCK_SH, unpinning the table, is not the last, and the other may be
|
||||
* killed at the stop timeout before its own try, which leaves the table in the tmpfs. So
|
||||
* this holder lets go of LOCK_SH and tries for a while. It holds no lock from here on
|
||||
* until LOCK_EX is granted; a conversion would not keep it either, since a refused one
|
||||
* has already dropped LOCK_SH (flock(2): not atomic). LOCK_EX may then come on a file
|
||||
* another holder already deleted, with a new engine's file at its name, so only the file
|
||||
* the name still points to is deleted. The lock file goes first: nobody gets past
|
||||
* LOCK_SH on this file to use it, while a file made anew at the name the moment this one
|
||||
* is gone could already have a filler on it. */
|
||||
(void)::flock(s->fd, LOCK_UN);
|
||||
for (int i = 0; i < kLeaveTries; ++i) {
|
||||
if (::flock(s->fd, LOCK_EX | LOCK_NB) == 0) {
|
||||
struct stat mine{}, named{};
|
||||
if (::fstat(s->fd, &mine) == 0 && ::stat(s->path.c_str(), &named) == 0 &&
|
||||
mine.st_dev == named.st_dev && mine.st_ino == named.st_ino) {
|
||||
::unlink(s->lock_path.c_str());
|
||||
::unlink(s->path.c_str());
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (errno != EWOULDBLOCK && errno != EINTR) break;
|
||||
if (i + 1 < kLeaveTries) ::usleep(kLeaveWaitUs);
|
||||
}
|
||||
::close(s->fd);
|
||||
}
|
||||
*s = TableShare{};
|
||||
}
|
||||
|
||||
bool table_share_is_ready(const std::string& dir, const std::string& id, int64_t n) {
|
||||
if (dir.empty() || id.empty() || n <= 0) return false;
|
||||
const int fd = ::open(file_path(dir, id).c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return false;
|
||||
std::string why;
|
||||
const bool ready = classify(fd, id, n, &why) == Seen::Ready;
|
||||
::close(fd);
|
||||
return ready;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,69 @@
|
||||
/* table_share.h -- an n-gram table as a file in a tmpfs that engines on separate cards share
|
||||
* (--ngram-placement ram=DIR). Each engine maps the file MAP_SHARED and pins it for its own cards,
|
||||
* so the host holds one copy however many engines read it. This is the file protocol only; the
|
||||
* mapping and the pinning are the device layer's (rad_dev_map_file).
|
||||
*
|
||||
* The file is `DIR/ngram-<id>.tab`: a header in its first 2 MiB, the table from kTableShareHeader
|
||||
* on, so the table keeps the 2 MiB alignment the pinned ranges want. The id names the container
|
||||
* and the table's place in it, so a file never serves another model.
|
||||
*
|
||||
* Every holder keeps LOCK_SH on the data file for its life, which counts the readers. The first
|
||||
* engine to find the file unready takes the fill lock (LOCK_EX on `<file>.lock`, a file of its
|
||||
* own so that a later engine arriving while the table is read never waits behind the readers),
|
||||
* fills the table and marks it ready; an engine arriving meanwhile waits on the fill lock and then
|
||||
* finds it ready. The holder that gets LOCK_EX on the data file when it leaves is the last, and
|
||||
* deletes the file and the lock file; one that leaves while another still holds LOCK_SH waits a
|
||||
* moment for it, since engines stopped together leave together. A holder that died took its locks
|
||||
* with it: a half-filled file is filled again, a ready one is reused after the same sample check
|
||||
* as a fresh copy. */
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* The table's offset in the file. */
|
||||
constexpr int64_t kTableShareHeader = (int64_t)2 << 20;
|
||||
|
||||
/* The file's length for an n-byte table: the header, then the table rounded up to 2 MiB. */
|
||||
int64_t table_share_file_bytes(int64_t n);
|
||||
|
||||
/* The smallest table worth a shared file. A file costs the header and the table's rounding to
|
||||
* 2 MiB, up to 4 MiB beside the table, and a tmpfs entry that outlives a crash; a weight of a few
|
||||
* bytes the gather reads beside the table (its one-element scale) would cost more that way than as
|
||||
* a private copy in every engine. From 16 headers on the file's overhead is under an eighth of the
|
||||
* table; a smaller one takes the private pinned copy. */
|
||||
constexpr int64_t kTableShareMin = 16 * kTableShareHeader;
|
||||
|
||||
struct TableShare {
|
||||
int fd = -1; /* the data file, LOCK_SH held until table_share_close */
|
||||
int lock_fd = -1; /* the fill lock, held while `filler` and not yet marked ready */
|
||||
std::string path, lock_path;
|
||||
bool ready = false; /* the table in the file is complete */
|
||||
bool filler = false; /* this holder fills it, then calls table_share_mark_ready */
|
||||
};
|
||||
|
||||
/* FNV-1a 64 over the container's real path, size and mtime (to the nanosecond), the table's file
|
||||
* offset and its length, as 16 hex digits; empty if the container cannot be stat'ed. */
|
||||
std::string table_share_id(const std::string& container_path, int64_t foff, int64_t n);
|
||||
|
||||
/* Open or create DIR/ngram-<id>.tab for an n-byte table and take part in the protocol: afterwards
|
||||
* `out->ready` (map it and check samples) or `out->filler` (map it, fill [kTableShareHeader, +n),
|
||||
* mark it ready). RAD_E_INVAL if a file of that name does not hold a table of this id and length
|
||||
* (another program's, or another version's; never overwritten, since a live engine may map it),
|
||||
* RAD_E_IO if the directory or file cannot be used. `why` carries the reason. */
|
||||
int table_share_open(const std::string& dir, const std::string& id, int64_t n, TableShare* out,
|
||||
std::string* why);
|
||||
|
||||
/* The filler's table is complete: write the header, release the fill lock. */
|
||||
int table_share_mark_ready(TableShare* s, int64_t n, const std::string& id, std::string* why);
|
||||
|
||||
/* Leave. The last holder deletes the file and its lock file; while another still holds the file,
|
||||
* this waits up to about a second for it to leave first. Safe on a TableShare never opened. */
|
||||
void table_share_close(TableShare* s);
|
||||
|
||||
/* Whether DIR/ngram-<id>.tab is a complete table of n bytes now, read from its header without
|
||||
* taking part: for the placement decision, which must know before anything is pinned. */
|
||||
bool table_share_is_ready(const std::string& dir, const std::string& id, int64_t n);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -186,8 +186,8 @@ void KVStreamStore::release(MemAllocator& host_alloc) {
|
||||
|
||||
KVStreamStats KVStreamStore::stats(const std::vector<KVGroupPlan>& plans) const {
|
||||
KVStreamStats st;
|
||||
st.misses = misses_;
|
||||
st.bytes_in = bytes_in_;
|
||||
st.misses = (int64_t)misses_.load(std::memory_order_relaxed);
|
||||
st.bytes_in = (int64_t)bytes_in_.load(std::memory_order_relaxed);
|
||||
for (const auto& p : plans)
|
||||
if (p.streamed()) st.resident_blocks += p.pool_blocks();
|
||||
return st;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#pragma once
|
||||
#include "mem/pools.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
@@ -85,17 +86,19 @@ public:
|
||||
|
||||
KVStreamStats stats(const std::vector<KVGroupPlan>& plans) const;
|
||||
|
||||
/* Charged by the engine, which reads the resolve's counters where a step has drained. */
|
||||
/* Charged by the engine, which reads the resolve's counters where a step has drained. Atomic
|
||||
* (relaxed): stats() is also read by the dashboard's snapshot on an HTTP thread while a step
|
||||
* may be in flight; only the values carry meaning, not their order. */
|
||||
void note_traffic(int64_t misses, int64_t bytes) {
|
||||
if (misses > 0) misses_ += (uint64_t)misses;
|
||||
if (bytes > 0) bytes_in_ += (uint64_t)bytes;
|
||||
if (misses > 0) misses_.fetch_add((uint64_t)misses, std::memory_order_relaxed);
|
||||
if (bytes > 0) bytes_in_.fetch_add((uint64_t)bytes, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<int64_t> resident_tokens_; /* by group handle: its pool's depth in tokens */
|
||||
std::vector<Map> maps_; /* set_map(), by group handle */
|
||||
uint64_t misses_ = 0; /* note_traffic() */
|
||||
uint64_t bytes_in_ = 0;
|
||||
std::atomic<uint64_t> misses_{0}; /* note_traffic() */
|
||||
std::atomic<uint64_t> bytes_in_{0};
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+37
-3
@@ -272,11 +272,15 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
for (const auto& p : plans_) if (p.stateful()) checkpoint_bytes_ += p.bytes_per_state;
|
||||
/* Then the window behind a checkpoint, after the linear state (see has_window_snapshot). A
|
||||
* trunk's window rides in the slot whether or not linear state is beside it: a hit resumes at
|
||||
* a snapshot either way, and without the window there it could not resume at all. */
|
||||
* a snapshot either way, and without the window there it could not resume at all. A drafter's
|
||||
* window rides there only on a model without linear state (set_drafter_window_snapshot). */
|
||||
bool has_state = false;
|
||||
for (const auto& p : plans_) has_state = has_state || p.stateful();
|
||||
for (size_t i = 1; i < plans_.size(); ++i) {
|
||||
KVGroupPlan& p = plans_[i];
|
||||
p.win_snap = p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
|
||||
!p.runtime_win && !groups[i].drafter;
|
||||
p.drafter = groups[i].drafter;
|
||||
p.win_snap = p.kind == RAD_KV_WINDOW && p.window_blocks > 0 && !p.runtime_win &&
|
||||
(!groups[i].drafter || (snap_drafter_ && !has_state));
|
||||
if (p.win_snap && !p.zero && p.n_layers > 0)
|
||||
window_ck_bytes_ += p.window_blocks * p.bytes_per_block;
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
+23
-4
@@ -122,9 +122,12 @@ struct KVGroupPlan {
|
||||
? (runtime_tokens + block_size - 1) / block_size : 0;
|
||||
}
|
||||
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot), after any
|
||||
* linear state. Set for a trunk group; a drafter's window is recomputed by draft refill, so
|
||||
* its snapshot would not be read. */
|
||||
* linear state. Set for a trunk group, and for a drafter's group on a model without linear
|
||||
* state where the engine saves the snapshot behind the drafter's context pass
|
||||
* (set_drafter_window_snapshot). Elsewhere a drafter's window is recomputed by draft refill,
|
||||
* so its snapshot would not be read. */
|
||||
bool win_snap = false;
|
||||
bool drafter = false; /* a drafter's group (KVGroupInfo::drafter) */
|
||||
|
||||
int64_t n_blocks = 0; /* paged groups: blocks the group addresses (its context) */
|
||||
/* Paged groups: blocks the device pool backs, fewer than `n_blocks` when the group streams
|
||||
@@ -230,6 +233,17 @@ public:
|
||||
* is sized and capped from these two alone (core/mem/vram_budget.cpp); VRAM above the ceiling
|
||||
* would never be addressed. carve() spends the pool it is given. */
|
||||
int plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg);
|
||||
/* Whether a drafter's WINDOW group rides in the window snapshot too (KVGroupPlan::win_snap).
|
||||
* The engine sets it, before plan_groups, where the drafter stores its context right behind
|
||||
* the trunk step and the snapshot is saved after that (a block drafter on the card's driver);
|
||||
* a snapshot taken before would hold the window without the step's rows. Kept across
|
||||
* forget(). */
|
||||
void set_drafter_window_snapshot(bool on) { snap_drafter_ = on; }
|
||||
/* Some drafter group rides in the window snapshot (after plan_groups). */
|
||||
bool drafter_window_snapshot() const {
|
||||
for (const auto& p : plans_) if (p.win_snap && p.drafter) return true;
|
||||
return false;
|
||||
}
|
||||
int64_t ceiling(int64_t ctx) const;
|
||||
/* The context-independent part of every ceiling: recurrent and conv state for max_seqs
|
||||
* sequences, plus alignment padding. Set by plan_groups(). */
|
||||
@@ -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<int64_t> bucket_blocks_; /* per group: blocks one held_hist_ bucket covers */
|
||||
std::vector<std::vector<int32_t>> 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;
|
||||
|
||||
+36
-6
@@ -77,7 +77,13 @@ void GeometricBackoff::select(const std::vector<int64_t>& pos, std::vector<int64
|
||||
|
||||
void KeepTipOnly::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep) const {
|
||||
keep->clear();
|
||||
if (!pos.empty()) keep->push_back(pos.back());
|
||||
if (pos.empty()) return;
|
||||
const int64_t tip = pos.back();
|
||||
if (floor_ > 0) {
|
||||
const auto it = std::upper_bound(pos.begin(), pos.end(), tip - floor_);
|
||||
if (it != pos.begin()) keep->push_back(*(it - 1));
|
||||
}
|
||||
keep->push_back(tip);
|
||||
}
|
||||
|
||||
void KeepAll::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep) const {
|
||||
@@ -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<int64_t>(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<int64_t>(share_bytes, 0) / slot_bytes;
|
||||
const int64_t room = std::max<int64_t>(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<int64_t>(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<CheckpointPolicy> p) {
|
||||
if (p) policy_ = std::move(p);
|
||||
if (policy_) policy_->set_floor(drafter_floor_);
|
||||
}
|
||||
|
||||
void PrefixCache::set_drafter_floor(int64_t tokens) {
|
||||
drafter_floor_ = tokens > 0 ? tokens : 0;
|
||||
if (policy_) policy_->set_floor(drafter_floor_);
|
||||
}
|
||||
|
||||
std::string PrefixCache::report() const { return report_; }
|
||||
|
||||
+37
-3
@@ -127,6 +127,10 @@ public:
|
||||
* of the store. The base applies select() to its own output one checkpoint at a time, which
|
||||
* is cheap only for a policy that keeps few. */
|
||||
virtual int64_t held(int64_t ctx, int64_t interval) const;
|
||||
/* Tokens before the tip a hit must be able to end at: a drafter whose KV the cache does not
|
||||
* hold recomputes that much of the prompt's tail (Scheduler::init, HitCap). 0: none. A policy
|
||||
* that would otherwise keep nothing that deep keeps one snapshot there. */
|
||||
virtual void set_floor(int64_t) {}
|
||||
};
|
||||
|
||||
/* Keep the tip and, at every scale S = interval x 2^k, the shallowest checkpoint in the tip's
|
||||
@@ -146,12 +150,18 @@ private:
|
||||
int64_t interval_;
|
||||
};
|
||||
|
||||
/* The two ends of the trade, for comparison. */
|
||||
/* The two ends of the trade, for comparison. tip-only under a drafter floor also keeps the deepest
|
||||
* snapshot at or below tip - floor: without it a refill-capped hit finds nothing to end on, keeps
|
||||
* the whole hit, and the request decodes with no drafts (8 sessions of 22k tokens: 5 ran
|
||||
* unspeculated, decode 424-521 t/s against 738-754 under geometric backoff). */
|
||||
class KeepTipOnly final : public CheckpointPolicy {
|
||||
public:
|
||||
const char* name() const override { return "tip-only"; }
|
||||
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
|
||||
int64_t held(int64_t, int64_t) const override { return 1; }
|
||||
int64_t held(int64_t, int64_t) const override { return floor_ > 0 ? 2 : 1; }
|
||||
void set_floor(int64_t tokens) override { floor_ = tokens > 0 ? tokens : 0; }
|
||||
private:
|
||||
int64_t floor_ = 0;
|
||||
};
|
||||
class KeepAll final : public CheckpointPolicy {
|
||||
public:
|
||||
@@ -174,6 +184,9 @@ std::unique_ptr<CheckpointPolicy> 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<CheckpointPolicy> p);
|
||||
/* The drafter's refill window (CheckpointPolicy::set_floor), held across set_policy. */
|
||||
void set_drafter_floor(int64_t tokens);
|
||||
const CheckpointPolicy& policy() const { return *policy_; }
|
||||
|
||||
/* ---------------- full attention ---------------- */
|
||||
@@ -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<int32_t> blocks;
|
||||
std::vector<int32_t> tokens; /* the block's token ids, compared on hit */
|
||||
std::vector<int32_t> tokens; /* the entry's token ids, compared on hit */
|
||||
/* On the LRU exactly while the cache holds the blocks; `lru` is valid only then. An
|
||||
* off-device entry owns no block, so eviction must not reach it. */
|
||||
bool in_lru = false;
|
||||
@@ -530,6 +563,7 @@ private:
|
||||
}
|
||||
mutable uint64_t clock_ = 0;
|
||||
std::unique_ptr<CheckpointPolicy> policy_;
|
||||
int64_t drafter_floor_ = 0;
|
||||
mutable Stats stats_;
|
||||
std::string report_;
|
||||
};
|
||||
|
||||
+3
-3
@@ -36,9 +36,9 @@ struct FrameRGBA {
|
||||
/* Whether this build has a decoder. */
|
||||
bool decoder_available();
|
||||
|
||||
/* "libavformat <version>" when the decoder is built in, "absent (built without libav*)"
|
||||
* when it is not: one string for the startup report and /diagnostics, so a media 500 can be
|
||||
* read off the report instead of bisected. */
|
||||
/* "libavformat <version>" when the decoder is built in, "absent (built without libav*)" when it
|
||||
* is not: one string for the startup report and /diagnostics, so a build that refuses every media
|
||||
* part shows it there. */
|
||||
std::string decoder_version();
|
||||
|
||||
/* The first frame of an image (or of anything with a video stream). Refuses a source over
|
||||
|
||||
+4
-1
@@ -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);
|
||||
|
||||
|
||||
+112
-4
@@ -31,6 +31,8 @@
|
||||
#include "planner.h"
|
||||
|
||||
#include <string>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
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<uint64_t> dispatches{0};
|
||||
std::atomic<uint64_t> proposed{0}, promotions{0}, demotions{0};
|
||||
std::atomic<uint64_t> refused{0}, no_candidate{0};
|
||||
std::atomic<uint64_t> distinct_promoted{0}, readmits{0};
|
||||
std::atomic<uint64_t> 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<std::atomic<uint8_t>[]> a;
|
||||
size_t n = 0;
|
||||
|
||||
void assign(size_t m) {
|
||||
n = m;
|
||||
a.reset(m ? new std::atomic<uint8_t>[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<int64_t> bytes_;
|
||||
std::vector<Tier> 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<uint8_t> busy_;
|
||||
std::vector<uint8_t> movable_;
|
||||
/* --expert-pin-top: a decode-hot resident the planner marked unmovable is never a demotion
|
||||
* candidate, even where a later pass made its unit movable again. */
|
||||
/* --expert-pin-top: a decode-hot resident the planner pinned is never a demotion candidate,
|
||||
* even where a later pass made its unit movable again. */
|
||||
std::vector<uint8_t> pinned_;
|
||||
std::vector<int32_t> layer_of_;
|
||||
/* Bit 0: promoted before. Bit 1: demoted before. Feeds the readmit counters. */
|
||||
|
||||
@@ -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)");
|
||||
|
||||
|
||||
+90
-2
@@ -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<uint64_t> dispatches{0};
|
||||
std::atomic<uint64_t> promotions{0}, demotions{0};
|
||||
std::atomic<uint64_t> h2d_bytes{0}, d2h_bytes{0};
|
||||
std::atomic<uint64_t> prefetched{0}, prefetch_bytes{0};
|
||||
std::atomic<uint64_t> no_record{0}, starved_slab{0}, starved_pool{0};
|
||||
std::atomic<uint64_t> quarantined{0};
|
||||
std::atomic<uint64_t> dropped{0};
|
||||
std::atomic<uint64_t> donated{0}, relocated{0}, stranded{0};
|
||||
std::atomic<uint64_t> ssd_reads{0}, ssd_bytes{0};
|
||||
std::atomic<uint64_t> stage_layers{0}, staged_units{0}, staged_bytes{0}, stage_overflow{0};
|
||||
std::atomic<uint64_t> stage_copies{0};
|
||||
std::atomic<uint64_t> file_layers{0}, file_units{0}, file_bytes{0}, file_preads{0};
|
||||
std::atomic<uint64_t> 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. */
|
||||
|
||||
+9
-14
@@ -1053,10 +1053,9 @@ int Planner::pin_towers(const Config& cfg, Plan* p) const {
|
||||
|
||||
/* --draft-expert-placement host: a draft head's routed experts (layers at meta.n_layers and above,
|
||||
* and only when the program declares a drafter) go to the pinned host pool before any strategy
|
||||
* runs. The card reads them in place at the DeviceZeroCopy site, the same way it reads a pooled
|
||||
* expert, so a drafter's experts fit beside a trunk that already fills the card instead of the
|
||||
* strategy having to make room for them on it. They are not movable: heat never promotes a draft
|
||||
* expert onto the card and into the trunk's slab. */
|
||||
* runs. The card reads them in place at the DeviceZeroCopy site, as it reads a pooled expert, so
|
||||
* a drafter's experts fit beside a trunk that already fills the card. They are not movable: heat
|
||||
* never promotes a draft expert onto the card and into the trunk's slab. */
|
||||
int Planner::pin_draft_experts(const Program& prog, const Config& cfg, Plan* p) const {
|
||||
if (cfg.draft_expert_placement != "host") return RAD_OK;
|
||||
if (prog.drafter.kind == RAD_DRAFT_NONE || prog.meta.n_layers == 0) {
|
||||
@@ -1107,12 +1106,12 @@ int Planner::pin_draft_experts(const Program& prog, const Config& cfg, Plan* p)
|
||||
|
||||
/* --expert-pin-top F: the hottest fraction of the routed experts, ranked by the profile the planner
|
||||
* was given (the container's, or --expert-profile's decode counts), stay resident. They are marked
|
||||
* unmovable, so the heat engine never demotes them and the decode-hot set stops paying the host
|
||||
* unmovable, so the heat engine never demotes them and the decode-hot set never pays the host
|
||||
* pool's PCIe read. The cut keeps the hottest ceil(F * n), and a tie at the cut stays movable: the
|
||||
* threshold is the share just below the hot set, and only a share strictly above it pins. Runs
|
||||
* after the strategy, which has already put the hot set in VRAM; a hot unit the strategy had to
|
||||
* leave on the host is left there and counted, since pinning it would need VRAM the card does not
|
||||
* have. */
|
||||
* leave on the host stays there and is counted, since pinning it would need VRAM the card does
|
||||
* not have. */
|
||||
void Planner::pin_hot(const Config& cfg, Plan* p) const {
|
||||
if (cfg.expert_pin_top <= 0.0f) return;
|
||||
std::vector<float> shares;
|
||||
@@ -1120,9 +1119,7 @@ void Planner::pin_hot(const Config& cfg, Plan* p) const {
|
||||
if (mu.expert >= 0 && mu.tier != Tier::Mapped) shares.push_back(mu.profile_share);
|
||||
if (shares.empty()) return;
|
||||
std::sort(shares.begin(), shares.end());
|
||||
/* The cut sits after the coldest (1 - F) of the plane, so the hottest F are pinned. A tie at
|
||||
* the cut stays movable: the threshold is the share just below the hot set, and only a share
|
||||
* strictly above it pins. */
|
||||
/* The cut sits after the coldest (1 - F) of the plane, so the hottest F are pinned. */
|
||||
const double keep = (double)cfg.expert_pin_top * (double)shares.size();
|
||||
const size_t hot = keep <= 0.0 ? 0 : std::min(shares.size(), (size_t)std::ceil(keep));
|
||||
const float threshold = hot == 0 ? shares.back() + 1.0f
|
||||
@@ -1174,7 +1171,8 @@ int Planner::plan(Plan* out) {
|
||||
build_classes(out);
|
||||
|
||||
/* After build_classes: a unit's slot_bytes is its class's stride, and the pins below charge
|
||||
* the host pool that. Before it the charge would be zero and the pool would not hold them. */
|
||||
* the host pool that. Before it the charge would be zero and the pool would not hold them.
|
||||
* Not RAD_TRY: a refusal still leaves `out` filled in far enough to print. */
|
||||
int hrc = pin_embedding(prog, cfg, out);
|
||||
const int trc = pin_towers(cfg, out);
|
||||
if (hrc >= 0) hrc = trc;
|
||||
@@ -1212,9 +1210,6 @@ int Planner::plan(Plan* out) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Not RAD_TRY: a refusal still leaves `out` filled in far enough to print. The pins ran above,
|
||||
* once slot_bytes was known. */
|
||||
|
||||
int rc = assign(out);
|
||||
enforce_op_site_agreement(prog, out);
|
||||
schedule_prefetch(out);
|
||||
|
||||
@@ -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;
|
||||
|
||||
+31
-13
@@ -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-<id>.tab (a tmpfs),
|
||||
* mapped shared, so engines on separate cards hold one table. Empty: a private copy. */
|
||||
std::string ngram_share_dir;
|
||||
TablePlacement embedding_resolved = TablePlacement::Vram;
|
||||
TablePlacement ngram_resolved = TablePlacement::Disk;
|
||||
/* Set by the resolver: pinned host MiB per rank for the token embedding when it resolves to
|
||||
@@ -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. */
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<bool>(program_->ops[i].issued).store(true, std::memory_order_relaxed);
|
||||
else
|
||||
unflushed_[w++] = i;
|
||||
}
|
||||
|
||||
+3
-1
@@ -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). */
|
||||
|
||||
@@ -38,6 +38,36 @@ namespace rad {
|
||||
int accept_greedy(const int32_t* draft, int n_draft, const int32_t* target,
|
||||
int32_t* out, int32_t* n_accepted);
|
||||
|
||||
/* The same rule over a tree (rad_drafter_tree). Node 0 is the verify's first row (the bonus token
|
||||
* it starts from); node j, 1 <= j <= n_draft, is draft[j - 1], verified at row j, and its parent
|
||||
* is node parent[j - 1] (< j), or node j - 1 when `parent` is null (a chain). `target[r]` is the
|
||||
* target's token after node r's row.
|
||||
*
|
||||
* From node 0, take the lowest-numbered child whose token is the target's at the current node,
|
||||
* while there is one. Writes the walk's nodes to path[0..n_accepted) and the emitted tokens to
|
||||
* out[0..n_accepted]: out[t] is the target's token at path[t - 1] (node 0 for t = 0), which equals
|
||||
* the accepted draft there, and out[n_accepted] is the bonus. The card's acceptance
|
||||
* (sched/advance_impl.h, ADV_ACCEPT) walks the same way. */
|
||||
inline int accept_tree(const int32_t* draft, const int32_t* parent, int n_draft,
|
||||
const int32_t* target, int32_t* out, int32_t* path, int32_t* n_accepted) {
|
||||
if (!draft || !target || !out || !path || !n_accepted || n_draft < 0) return RAD_E_INVAL;
|
||||
int32_t cur = 0, acc = 0;
|
||||
for (;;) {
|
||||
int32_t nxt = -1;
|
||||
for (int32_t j = cur + 1; j <= n_draft; ++j) {
|
||||
int32_t p = parent ? parent[j - 1] : j - 1;
|
||||
if (p < 0 || p >= j) p = j - 1; /* as the builder and ADV_TRUNK read it */
|
||||
if (p == cur && draft[j - 1] == target[cur]) { nxt = j; break; }
|
||||
}
|
||||
if (nxt < 0) break;
|
||||
path[acc++] = nxt;
|
||||
cur = nxt;
|
||||
}
|
||||
for (int32_t t = 0; t <= acc; ++t) out[t] = target[t == 0 ? 0 : path[t - 1]];
|
||||
*n_accepted = acc;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Where a verify step's emission ends: at the first end-of-generation token among `out`'s
|
||||
* n_accepted + 1 tokens (accept_greedy's output), which is emitted, or after all of them. Returns
|
||||
* the number of accepted drafts to commit, at most `n_accepted`. A drafter that predicts the stop
|
||||
|
||||
+49
-11
@@ -3,6 +3,7 @@
|
||||
*/
|
||||
#include "sampler.h"
|
||||
#include "gbnf.h"
|
||||
#include "../sched/draft.h" /* RAD_SCHED_MAX_SPEC */
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
@@ -618,8 +619,8 @@ int Sampler::accept_token(uint64_t req_id, int32_t token) {
|
||||
}
|
||||
|
||||
/* A constraining grammar does not rule out speculation: build_step masks draft position i
|
||||
* against the state after drafts 0..i-1 and then rewinds. Only a backend that cannot rewind is
|
||||
* refused. */
|
||||
* against the state after drafts 0..i-1 (on a tree, after row i's ancestors) and then rewinds.
|
||||
* Only a backend that cannot rewind is refused. */
|
||||
bool Sampler::allows_speculation(uint64_t req_id) const {
|
||||
auto it = seqs_.find(req_id);
|
||||
if (it == seqs_.end() || !it->second.grammar) return true;
|
||||
@@ -729,7 +730,13 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
|
||||
* `dead` is not a failure: a draft the grammar forbids will be rejected at verification
|
||||
* and every later position discarded, so masking stops for the rest of the window. */
|
||||
GrammarBackend* gr = st && st->grammar ? st->grammar.get() : nullptr;
|
||||
const bool walk = gr && n_pos > 1;
|
||||
/* A tree (rad_drafter_tree) is walked per row instead: row k's prefix is its ancestors,
|
||||
* not drafts 0..k-1, so each row pushes the committed state, advances over its own path,
|
||||
* is masked, and rolls back. A refused ancestor kills that row only: verification never
|
||||
* reaches it, while a sibling's path may still be admissible. */
|
||||
const int32_t* tpar = r->draft_parent;
|
||||
const bool walk = gr && n_pos > 1 && !tpar;
|
||||
const bool walk_tree = gr && n_pos > 1 && tpar;
|
||||
if (walk) gr->push_state();
|
||||
bool dead = false;
|
||||
|
||||
@@ -746,10 +753,38 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
|
||||
st->think.push(sp.reasoning, r->output[st->think_seen]);
|
||||
think = st->think;
|
||||
}
|
||||
const ReasoningCount think0 = think;
|
||||
|
||||
for (int k = 0; k < n_pos; ++k) {
|
||||
/* Row k's drafts before it: 0..k-1 on a chain, its ancestors (root first) on a tree. */
|
||||
int32_t anc[RAD_SCHED_MAX_SPEC];
|
||||
int32_t dk = 0;
|
||||
if (tpar) {
|
||||
int32_t chain[RAD_SCHED_MAX_SPEC];
|
||||
for (int32_t j = k; j > 0 && dk < RAD_SCHED_MAX_SPEC;) {
|
||||
chain[dk++] = j;
|
||||
int32_t pj = tpar[j - 1];
|
||||
j = (pj < 0 || pj >= j) ? j - 1 : pj;
|
||||
}
|
||||
for (int32_t t = 0; t < dk; ++t) anc[t] = r->draft[chain[dk - 1 - t] - 1];
|
||||
} else {
|
||||
for (; dk < k; ++dk) anc[dk] = r->draft[dk];
|
||||
}
|
||||
if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true;
|
||||
if (budget && k > 0) think.push(sp.reasoning, r->draft[k - 1]);
|
||||
bool row_dead = false; /* a tree row whose path the grammar refuses */
|
||||
bool pushed = false;
|
||||
if (walk_tree && dk > 0) {
|
||||
RAD_TRY(gr->push_state());
|
||||
pushed = true;
|
||||
for (int32_t t = 0; t < dk && !row_dead; ++t)
|
||||
row_dead = gr->accept_token(anc[t]) < 0;
|
||||
}
|
||||
if (budget && tpar) {
|
||||
think = think0;
|
||||
for (int32_t t = 0; t < dk; ++t) think.push(sp.reasoning, anc[t]);
|
||||
} else if (budget && k > 0) {
|
||||
think.push(sp.reasoning, r->draft[k - 1]);
|
||||
}
|
||||
const int64_t row = n_seq_++;
|
||||
/* Row k verifies draft k against the state its round left. A row with no bound state
|
||||
* (the bonus row, a greedy row, an uncoupled step) gets a zeroed one, and the verify
|
||||
@@ -781,8 +816,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
|
||||
|
||||
p.seed = sp.seed;
|
||||
/* Output position: draft position k is token n_out + k, so its draw is the same with
|
||||
* or without speculation. */
|
||||
p.pos = (uint64_t)(n_out + k);
|
||||
* or without speculation. On a tree it is the row's depth: siblings share a prefix
|
||||
* length, hence a coordinate, hence the target's draw there. */
|
||||
p.pos = (uint64_t)(n_out + dk);
|
||||
|
||||
p.temp = sp.temp;
|
||||
p.top_p = sp.top_p;
|
||||
@@ -857,14 +893,14 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
|
||||
* this span, so the reference's update order holds at a verify: position k sees the
|
||||
* drafts before it, as the processor would after emitting them. */
|
||||
if (pen || dry || ngram) {
|
||||
const int64_t len = n_total + k;
|
||||
const int64_t len = n_total + dk;
|
||||
const int64_t take = std::min<int64_t>(len, cfg_.max_hist);
|
||||
int32_t* h = hist_stage_ + row * cfg_.max_hist;
|
||||
for (int64_t i = 0; i < take; ++i) {
|
||||
const int64_t src = len - take + i;
|
||||
h[i] = src < n_prompt ? r->prompt[(size_t)src]
|
||||
: src < n_total ? r->output[(size_t)(src - n_prompt)]
|
||||
: r->draft[src - n_total];
|
||||
: anc[src - n_total];
|
||||
}
|
||||
p.hist_len = (int32_t)take;
|
||||
if (pen) p.flags |= RAD_SP_PENALTY;
|
||||
@@ -874,7 +910,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
|
||||
if (ngram && take >= sp.ngram_ban_n) any_ngram_ = true;
|
||||
}
|
||||
|
||||
if (gr && !dead && gr->constrains()) {
|
||||
if (gr && !dead && !row_dead && gr->constrains()) {
|
||||
uint32_t* dst = mask_stage_ + row * mask_words_;
|
||||
int s;
|
||||
/* Mask cost, reported at Debug per 256 masks (mean and worst). It runs on the
|
||||
@@ -914,8 +950,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
|
||||
}
|
||||
if (s < 0 && k > 0) {
|
||||
/* At a draft position this only means a draft is wrong; verification
|
||||
* rejects at or before here, so stop masking the rest of the window. */
|
||||
dead = true;
|
||||
* rejects at or before here, so stop masking the rest of the window. On a
|
||||
* tree only this row's path is wrong; its siblings are masked on. */
|
||||
if (!tpar) dead = true;
|
||||
} else if (s < 0) {
|
||||
/* A dead grammar fails its request, not the step: an error status would stop
|
||||
* the step loop for every client. The row stays unmasked and the engine
|
||||
@@ -939,6 +976,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs, int64_t step) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pushed) RAD_TRY(gr->rollback()); /* back to the committed state for the next row */
|
||||
|
||||
if (budget && think.inside() && think.body >= sp.thinking_budget)
|
||||
force_close(p, row, sp.reasoning.close);
|
||||
|
||||
@@ -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). */
|
||||
|
||||
@@ -23,4 +23,24 @@ int step_advance(const AdvanceArgs& a, RadStream s) {
|
||||
#endif
|
||||
}
|
||||
|
||||
int step_compact(const AdvanceArgs& a, RadStream s) {
|
||||
if (a.n_seq <= 0 || a.n_pool <= 0) return RAD_OK;
|
||||
if (device_is_host()) {
|
||||
RAD_TRY(rad_stream_sync(s));
|
||||
const int items = adv_compact_items(a);
|
||||
for (int i = 0; i < a.n_seq; ++i)
|
||||
for (int w = 0; w < items; ++w) {
|
||||
int p = 0, l = 0, h = 0;
|
||||
if (adv_compact_item(a, w, &p, &l, &h)) adv_compact(a, i, p, l, h, 0, 1);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
|
||||
return rad_step_compact_launch(&a, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
#else
|
||||
(void)s;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
#endif
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+53
-1
@@ -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);
|
||||
@@ -59,8 +59,51 @@ __global__ __launch_bounds__(kThreads) void r4dchain_step_advance(rad::AdvanceAr
|
||||
}
|
||||
}
|
||||
|
||||
/* ADV_COMPACT: block (x, y) is work item x (a pool, layer and head) of batch row y; its threads
|
||||
* split the K|V row into 16-byte chunks. Chained like the advance where launches chain, every
|
||||
* block waiting for the kernels before it and counting itself in after its moves. */
|
||||
constexpr int kCompactThreads = 64;
|
||||
__device__ __forceinline__ void step_compact_body(const rad::AdvanceArgs& a) {
|
||||
int p = 0, l = 0, h = 0;
|
||||
if (!rad::adv_compact_item(a, (int)blockIdx.x, &p, &l, &h)) return;
|
||||
rad::adv_compact(a, (int)blockIdx.y, p, l, h, (int)threadIdx.x, kCompactThreads);
|
||||
}
|
||||
__global__ __launch_bounds__(kCompactThreads) void rad_step_compact(rad::AdvanceArgs a) {
|
||||
step_compact_body(a);
|
||||
}
|
||||
__global__ __launch_bounds__(kCompactThreads) void r4dchain_step_compact(rad::AdvanceArgs a) {
|
||||
const ChainRec* r = chain_rec();
|
||||
if (r) {
|
||||
if (threadIdx.x == 0)
|
||||
while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target)
|
||||
__builtin_amdgcn_s_sleep(1);
|
||||
__syncthreads();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
|
||||
}
|
||||
step_compact_body(a);
|
||||
if (r) {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0)
|
||||
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int rad_step_compact_launch(const rad::AdvanceArgs* args, void* stream) {
|
||||
if (!args || args->n_seq <= 0) return 0;
|
||||
const int items = rad::adv_compact_items(*args);
|
||||
if (items <= 0) return 0;
|
||||
if (!rad_dev_chain_enabled())
|
||||
hipLaunchKernelGGL(rad_step_compact, dim3((unsigned)items, (unsigned)args->n_seq),
|
||||
dim3(kCompactThreads), 0, (hipStream_t)stream, *args);
|
||||
else
|
||||
hipLaunchKernelGGL(r4dchain_step_compact, dim3((unsigned)items, (unsigned)args->n_seq),
|
||||
dim3(kCompactThreads), 0, (hipStream_t)stream, *args);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -1;
|
||||
}
|
||||
|
||||
extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream) {
|
||||
if (!args || args->n_seq <= 0) return 0;
|
||||
const unsigned blocks = (unsigned)((args->n_seq + kThreads - 1) / kThreads);
|
||||
|
||||
+171
-13
@@ -28,6 +28,20 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
|
||||
return lo < a.n_eog && a.eog[lo] == t;
|
||||
}
|
||||
|
||||
/* Group `e`'s slot for position `p` of batch row `i`, or -1 past its block table. A runtime
|
||||
* window's position at or past ring_pos is in its ring (see adv_groups). */
|
||||
RAD_ADV_FN int32_t adv_slot(const AdvanceArgs& a, const AdvGroup& e, int i, int32_t p) {
|
||||
const int32_t first = adv_i32(a, e.first_off)[i];
|
||||
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
|
||||
int32_t bi = (p - first) / e.block_size;
|
||||
if (e.ring && e.ring_blocks > 0 && adv_i32(a, e.tlen_off)[i] > 0) {
|
||||
const int32_t rpos = adv_i32(a, e.rpos_off)[i];
|
||||
if (p >= rpos) bi = rpos / e.block_size + ((p - rpos) / e.block_size) % e.ring_blocks;
|
||||
}
|
||||
return (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
|
||||
? bt[bi] * e.block_size + p % e.block_size : -1;
|
||||
}
|
||||
|
||||
/* Every group's slots for the row's `n` positions (from the positions just written) and its
|
||||
* length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes
|
||||
* tables for the furthest reachable position, so only a row whose output is unused hits this.
|
||||
@@ -43,16 +57,18 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
|
||||
* off the table once the ring wraps.
|
||||
*
|
||||
* `len`, when given, is the length's count from `base` in place of `n` (ADV_HIST: rows that
|
||||
* repeat a position must not lengthen the context). */
|
||||
* repeat a position must not lengthen the context). `at`, when given, is where each row stores its
|
||||
* K and V instead of its position: a tree verify's rows rotate at their depth but store at their
|
||||
* row index, since siblings share a depth (ADV_TRUNK), and a context row the tree rejected stores
|
||||
* nowhere (-1, ADV_CTXTREE). */
|
||||
RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n,
|
||||
int32_t len = -1) {
|
||||
int32_t len = -1, const int32_t* at = nullptr) {
|
||||
const AdvGroup* G = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off);
|
||||
const int32_t* pos = adv_i32(a, a.pos_off);
|
||||
for (int g = 0; g < a.n_groups; ++g) {
|
||||
const AdvGroup& e = G[g];
|
||||
const int32_t first = adv_i32(a, e.first_off)[i];
|
||||
/* Per sequence: each prompt has its own floor and its own table (advance.h). */
|
||||
const int32_t rpos = e.ring ? adv_i32(a, e.rpos_off)[i] : 0;
|
||||
const int32_t tlen = e.ring ? adv_i32(a, e.tlen_off)[i] : 0;
|
||||
const bool ring = e.ring && tlen > 0;
|
||||
int64_t used = (int64_t)base + (len >= 0 ? len : n) - first;
|
||||
@@ -62,20 +78,22 @@ RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base,
|
||||
}
|
||||
adv_i32(a, e.used_off)[i] = (int32_t)used;
|
||||
if (!e.paged) continue;
|
||||
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
|
||||
int32_t* slot = adv_i32(a, e.slot_off);
|
||||
for (int32_t j = 0; j < n; ++j) {
|
||||
const int32_t p = pos[k + j];
|
||||
int32_t bi = (p - first) / e.block_size;
|
||||
if (ring && p >= rpos && e.ring_blocks > 0)
|
||||
bi = rpos / e.block_size +
|
||||
((p - rpos) / e.block_size) % e.ring_blocks;
|
||||
slot[k + j] = (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
|
||||
? bt[bi] * e.block_size + p % e.block_size : -1;
|
||||
const int32_t p = at ? at[j] : pos[k + j];
|
||||
slot[k + j] = p >= 0 ? adv_slot(a, e, i, p) : -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* A tree's node depths from its parents: node 0 (the bonus token) at 0, node j + 1 one below
|
||||
* par[j]. A parent outside [0, j] is a drafter bug; it is read as the previous node, so the row
|
||||
* still stores and rotates somewhere sane, and the verify rejects whatever it proposed. */
|
||||
RAD_ADV_FN int32_t adv_parent(const StepSlot& S, int32_t j) {
|
||||
const int32_t p = S.par[j - 1];
|
||||
return (p < 0 || p >= j) ? j - 1 : p;
|
||||
}
|
||||
|
||||
/* Writes a row's position and moves its rotary components by the same amount. A row whose
|
||||
* position does not change keeps the host's components. */
|
||||
RAD_ADV_FN void adv_pos(const AdvanceArgs& a, int32_t* pos, int32_t row, int32_t p) {
|
||||
@@ -108,10 +126,39 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
|
||||
switch (a.mode) {
|
||||
case ADV_ACCEPT: {
|
||||
const int32_t* y = a.src + rout;
|
||||
/* A tree verify, which the trunk's spec_parent row says (its first entry is -1, the root,
|
||||
* whoever staged it: ADV_TRUNK for a card row, the builder for a host row): accept_tree's
|
||||
* rule. From the bonus token, follow the first child (lowest node index) whose token is
|
||||
* the target's pick at its parent's row, as long as one is; then the same
|
||||
* end-of-generation cut over the tokens that walk emits. */
|
||||
const int32_t* tp = a.parent_off >= 0 ? adv_i32(a, a.parent_off) + rtok : nullptr;
|
||||
if (tp && aux > 0 && tp[0] == -1) {
|
||||
const int32_t* d = tok + rtok; /* node j's token is d[j], 1 <= j <= aux */
|
||||
const int32_t a0 = rtok - k; /* parents count rows from the sequence's first */
|
||||
int32_t cur = 0, acc = 0;
|
||||
for (;;) {
|
||||
int32_t nxt = -1;
|
||||
for (int32_t j = cur + 1; j <= aux; ++j)
|
||||
if (tp[j] - a0 == cur && d[j] == y[cur]) { nxt = j; break; }
|
||||
if (nxt < 0) break;
|
||||
S.path[acc++] = nxt;
|
||||
cur = nxt;
|
||||
}
|
||||
for (int32_t t = 0; t <= acc; ++t)
|
||||
if (adv_is_eog(a, y[t == 0 ? 0 : S.path[t - 1]])) { acc = t; break; }
|
||||
const int32_t head = ctx[i] + (rtok - k) + acc;
|
||||
S.acc = acc;
|
||||
S.head = head;
|
||||
S.ctx = head + 1;
|
||||
S.n_acc = acc + 1;
|
||||
S.tok[0] = y[acc == 0 ? 0 : S.path[acc - 1]];
|
||||
S.npath = acc;
|
||||
return;
|
||||
}
|
||||
/* accept_greedy's rule, then collect_step's end-of-generation cut: a draft is accepted
|
||||
* while it equals the target's pick at its position, and the run stops at an
|
||||
* end-of-generation token, not after it. */
|
||||
const int32_t* y = a.src + rout;
|
||||
const int32_t* d = tok + rtok + 1;
|
||||
int32_t acc = 0;
|
||||
while (acc < aux && d[acc] == y[acc]) ++acc;
|
||||
@@ -123,16 +170,64 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
S.ctx = head + 1;
|
||||
S.n_acc = acc + 1;
|
||||
S.tok[0] = y[acc];
|
||||
S.npath = 0;
|
||||
return;
|
||||
}
|
||||
case ADV_TRUNK: {
|
||||
const int32_t base = S.ctx;
|
||||
if (a.parent_off >= 0) {
|
||||
int32_t* par = adv_i32(a, a.parent_off);
|
||||
/* A row verifying fewer nodes than the drafter proposed (a window cut it) verifies
|
||||
* their prefix, which is a tree too: every parent precedes its child. */
|
||||
if (n > 1 && S.ntree >= n - 1) {
|
||||
/* A tree: node j stores its K and V at base + j (siblings share a depth, so the
|
||||
* position cannot address them) and rotates at base + its depth, the position the
|
||||
* token would have if its path were committed. Attention reads spec_parent to see
|
||||
* only a row's own ancestors inside the block. */
|
||||
int32_t dep[1 + RAD_SCHED_MAX_SPEC], at[1 + RAD_SCHED_MAX_SPEC];
|
||||
for (int32_t j = 0; j < n; ++j) {
|
||||
const int32_t p = j == 0 ? -1 : adv_parent(S, j);
|
||||
dep[j] = j == 0 ? 0 : dep[p] + 1;
|
||||
tok[k + j] = S.tok[j];
|
||||
par[k + j] = p;
|
||||
adv_pos(a, pos, k + j, base + dep[j]);
|
||||
at[j] = base + j;
|
||||
}
|
||||
ctx[i] = base;
|
||||
adv_i32(a, a.acc_off)[i] = S.n_acc;
|
||||
adv_groups(a, i, k, base, n, -1, at);
|
||||
return;
|
||||
}
|
||||
for (int32_t j = 0; j < n; ++j) par[k + j] = -2;
|
||||
}
|
||||
for (int32_t j = 0; j < n; ++j) { tok[k + j] = S.tok[j]; adv_pos(a, pos, k + j, base + j); }
|
||||
ctx[i] = base;
|
||||
adv_i32(a, a.acc_off)[i] = S.n_acc;
|
||||
adv_groups(a, i, k, base, n);
|
||||
return;
|
||||
}
|
||||
case ADV_CTXTREE: {
|
||||
/* The drafter's context pass over a tree verify's rows (one per node, in node order, as
|
||||
* the trunk tapped them), a card row only where the host marked the step's entry as one.
|
||||
* Only the accepted path is context: path node t's row writes at the anchor + t + 1,
|
||||
* rotated there, which is where its token now sits, and every rejected node's row stores
|
||||
* nowhere. Run after ADV_ACCEPT, which wrote the path, and before ADV_BTAKE. A chain
|
||||
* verify's path is its first `acc` rows (npath 0). */
|
||||
const int32_t base = S.head - S.acc;
|
||||
int32_t at[1 + RAD_SCHED_MAX_SPEC];
|
||||
at[0] = base;
|
||||
adv_pos(a, pos, k, base);
|
||||
for (int32_t j = 1; j < n; ++j) { at[j] = -1; adv_pos(a, pos, k + j, base); }
|
||||
for (int32_t t = 0; t < S.acc; ++t) {
|
||||
const int32_t r = t < S.npath ? S.path[t] : t + 1;
|
||||
if (r < 1 || r >= n) continue;
|
||||
at[r] = base + t + 1;
|
||||
adv_pos(a, pos, k + r, base + t + 1);
|
||||
}
|
||||
ctx[i] = base;
|
||||
adv_groups(a, i, k, base, n, -1, at);
|
||||
return;
|
||||
}
|
||||
case ADV_HIST: {
|
||||
if (a.shared_kv) {
|
||||
/* A head that reads the trunk's cache and keeps none (rad_drafter_shared_kv). With no
|
||||
@@ -205,13 +300,76 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
return;
|
||||
}
|
||||
case ADV_BTAKE:
|
||||
/* Row i is the query pass's i-th block, which is the i-th drafting sequence. */
|
||||
/* Row i is the query pass's i-th block, which is the i-th drafting sequence. A tree
|
||||
* drafter's parents come with the tokens, at the same pitch. */
|
||||
for (int32_t j = 0; j < a.round; ++j)
|
||||
S.tok[1 + j] = a.src[(int64_t)i * a.src_pitch + j];
|
||||
if (a.par) {
|
||||
for (int32_t j = 0; j < a.round; ++j) S.par[j] = a.par[(int64_t)i * a.src_pitch + j];
|
||||
S.ntree = a.round;
|
||||
} else {
|
||||
S.ntree = 0;
|
||||
}
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/* ADV_COMPACT for one (batch row, pool, layer, head): the moves the row's accepted path asks
|
||||
* for, `c0` and every `cstep`-th 16-byte chunk of each K|V row. Node path[t] stored at
|
||||
* base + path[t] and belongs at base + t + 1. path[] increases (a parent's index is below its
|
||||
* child's) and path[t] >= t + 1, so in t order no move overwrites a node a later move still reads:
|
||||
* a destination base + t + 1 is either the node's own place or a place a node already moved out
|
||||
* of. Each caller keeps one chunk set across every t, so its reads and writes stay in order. */
|
||||
RAD_ADV_FN void adv_compact(const AdvanceArgs& a, int i, int p, int l, int h, int c0, int cstep) {
|
||||
/* Only a row that sampled in this step: ADV_ACCEPT just wrote its slot. Any other row's slot
|
||||
* may hold a path from an earlier request that used the same slot. */
|
||||
const int32_t* rows = adv_i32(a, a.row_off);
|
||||
if (rows[2 * a.row_pitch + i] < 0) return;
|
||||
const StepSlot& S = a.st[adv_i32(a, a.sid_off)[i]];
|
||||
const int32_t np = S.npath < S.acc ? S.npath : S.acc;
|
||||
if (np <= 0) return;
|
||||
const AdvPool& P = a.pool[p];
|
||||
if (!P.base || l >= P.n_layers || h >= P.n_head) return;
|
||||
const AdvGroup& e = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off)[P.grp];
|
||||
if (!e.paged) return;
|
||||
const int32_t base = S.head - S.acc;
|
||||
const int32_t bs = e.block_size;
|
||||
char* lay = P.base + (int64_t)l * P.layer_stride;
|
||||
const int32_t chunks = P.row_bytes / 16;
|
||||
for (int32_t t = 0; t < np; ++t) {
|
||||
const int32_t src = base + S.path[t], dst = base + t + 1;
|
||||
if (src == dst) continue;
|
||||
const int32_t ss = adv_slot(a, e, i, src), ds = adv_slot(a, e, i, dst);
|
||||
if (ss < 0 || ds < 0) continue;
|
||||
const uint32_t* from = reinterpret_cast<const uint32_t*>(
|
||||
lay + (((int64_t)(ss / bs) * P.n_head + h) * bs + ss % bs) * P.row_bytes);
|
||||
uint32_t* to = reinterpret_cast<uint32_t*>(
|
||||
lay + (((int64_t)(ds / bs) * P.n_head + h) * bs + ds % bs) * P.row_bytes);
|
||||
for (int32_t c = c0; c < chunks; c += cstep) {
|
||||
const uint32_t v0 = from[4 * c], v1 = from[4 * c + 1], v2 = from[4 * c + 2],
|
||||
v3 = from[4 * c + 3];
|
||||
to[4 * c] = v0; to[4 * c + 1] = v1; to[4 * c + 2] = v2; to[4 * c + 3] = v3;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* The (pool, layer, head) of ADV_COMPACT's work item `w`, counting every pool's layers x heads in
|
||||
* order; false past the last. */
|
||||
RAD_ADV_FN bool adv_compact_item(const AdvanceArgs& a, int w, int* p, int* l, int* h) {
|
||||
for (int q = 0; q < a.n_pool; ++q) {
|
||||
const int n = a.pool[q].n_layers * a.pool[q].n_head;
|
||||
if (w < n) { *p = q; *l = w / a.pool[q].n_head; *h = w % a.pool[q].n_head; return true; }
|
||||
w -= n;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
RAD_ADV_FN int adv_compact_items(const AdvanceArgs& a) {
|
||||
int n = 0;
|
||||
for (int q = 0; q < a.n_pool; ++q) n += a.pool[q].n_layers * a.pool[q].n_head;
|
||||
return n;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+45
-10
@@ -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_) {
|
||||
|
||||
@@ -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> derived_;
|
||||
|
||||
+34
-20
@@ -38,6 +38,30 @@ int64_t prefill_shared_tok(const Config& cfg) {
|
||||
return std::max(std::min(cfg.max_tok, I), cfg.max_tok - (cfg.prefill_span - 1) * I);
|
||||
}
|
||||
|
||||
/* What a prefix hit restores beside the cached blocks: linear state, or a trunk's sliding window.
|
||||
* Only the trunk's window makes a model take window snapshots; a block drafter's rides in them
|
||||
* where they exist (KVManager::set_drafter_window_snapshot) and is recomputed by draft refill
|
||||
* where they do not. A RAD_KV_RING group has no snapshot at all
|
||||
* (KVManager::declare_runtime_window): its window is each sequence's own prompt length, which no
|
||||
* slot could describe, so it is sized for the context plus a ring and is never checkpointed. */
|
||||
static void restored_state(const Program& prog, bool* linear, bool* window) {
|
||||
*linear = *window = false;
|
||||
for (const KVGroupInfo& kg : prog.kv_groups) {
|
||||
if (kg.decl.kind != RAD_KV_FULL && kg.decl.kind != RAD_KV_WINDOW &&
|
||||
kg.decl.kind != RAD_KV_RING)
|
||||
*linear = true;
|
||||
else if (kg.decl.kind == RAD_KV_WINDOW && kg.block_size > 0 && !kg.layers.empty() &&
|
||||
!kg.drafter)
|
||||
*window = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool window_snapshots(const Program& prog, const Config& cfg) {
|
||||
bool linear = false, window = false;
|
||||
restored_state(prog, &linear, &window);
|
||||
return !linear && window && cfg.prefix_cache && cfg.checkpoint_interval > 0;
|
||||
}
|
||||
|
||||
int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
ChunkGeometry g;
|
||||
@@ -46,22 +70,12 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
/* lcm across every paged group. libr4d uses 16 for all of them, but a sliding-window group
|
||||
* served by a different kernel may differ (§7.2). */
|
||||
bool has_linear = false, has_window = false;
|
||||
restored_state(prog, &has_linear, &has_window);
|
||||
for (const KVGroupInfo& kg : prog.kv_groups) {
|
||||
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
|
||||
kg.decl.kind == RAD_KV_RING) {
|
||||
if (kg.block_size > 0) {
|
||||
g.attn_block = lcm64(g.attn_block, kg.block_size);
|
||||
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
|
||||
/* A drafter's window is recomputed by draft refill; only the trunk's needs a
|
||||
* snapshot for a prefix hit to resume. A RAD_KV_RING group has no snapshot at all
|
||||
* (KVManager::declare_runtime_window): its window is each sequence's own prompt
|
||||
* length, which no slot could describe, so it is sized for the context plus a ring
|
||||
* and is never checkpointed. */
|
||||
if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter)
|
||||
has_window = true;
|
||||
}
|
||||
} else {
|
||||
has_linear = true;
|
||||
if ((kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
|
||||
kg.decl.kind == RAD_KV_RING) && kg.block_size > 0) {
|
||||
g.attn_block = lcm64(g.attn_block, kg.block_size);
|
||||
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,11 +166,11 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
}
|
||||
|
||||
/* The resume grid (--prefix-resume exact): where an idle server's prefill chunks start. A
|
||||
* prefill alone in its step takes the budget, rounded down to the quantum, and stops at every
|
||||
* interval boundary it reaches where chunks split at the interval (linear state, or periodic
|
||||
* window snapshots); a span carries h intervals from the second one on. An interval past the
|
||||
* budget must then be a multiple of the budget's chunk, or the chunk after a checkpoint would
|
||||
* start off the grid every cold run cuts: rounded up, as the quantum rounds it, since a longer
|
||||
* prefill alone in its step takes the budget, rounded down to the quantum. Where chunks split
|
||||
* at the interval (linear state, or periodic window snapshots) it stops at every interval
|
||||
* boundary it reaches, and a span carries h intervals from the second one on. An interval past
|
||||
* the budget must be a multiple of the budget's chunk, or the chunk after a checkpoint would
|
||||
* start off the cold run's grid; it is rounded up, as the quantum rounds it, since a longer
|
||||
* interval costs only retention. */
|
||||
const int64_t I0 = g.checkpoint_interval;
|
||||
const bool splits = I0 > 0 && (!g.window_ckpt || g.window_periodic);
|
||||
|
||||
+13
-8
@@ -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
|
||||
|
||||
+15
-1
@@ -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<int32_t>& 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<std::vector<int32_t>>* blocks_out,
|
||||
const HitCap* cap) const = 0;
|
||||
virtual const std::vector<int32_t>& cached_groups() const = 0;
|
||||
/* The drafter's refill window (Scheduler::init): retention keeps a snapshot that deep below a
|
||||
* session's tip, so a refill-capped hit has one to end on (PrefixCache::set_drafter_floor). */
|
||||
virtual void set_drafter_floor(int64_t) {}
|
||||
|
||||
/* Publish what this sequence computed so a later request sharing the prefix can adopt it.
|
||||
* `blocks[i]` is the block table of cached_groups()[i]; `n_tokens` is how many tokens are
|
||||
@@ -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<int32_t>& 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<int32_t>& cached_groups() const override { return m->cached_groups(); }
|
||||
void set_drafter_floor(int64_t tokens) override { m->set_drafter_floor(tokens); }
|
||||
|
||||
/* Indexes prompt ++ output: the next turn sends the reply back in its prompt, so indexing the
|
||||
* prompt alone would stop hitting at the first assistant token. */
|
||||
|
||||
+161
-43
@@ -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<Request> 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<std::mutex> lk(mu_);
|
||||
auto it = by_id_.find(id);
|
||||
if (it == by_id_.end()) return RAD_E_NOTFOUND;
|
||||
SchedReq& s = *reqs_[(size_t)it->second];
|
||||
if (n < 0) return RAD_E_INVAL;
|
||||
/* A tree's parents travel with its tokens; a prefix of a tree is a tree (every parent
|
||||
* precedes its child), so the caps below keep them valid. */
|
||||
s.draft_tree = parents != nullptr;
|
||||
if (parents)
|
||||
for (int i = 0; i < n && i < RAD_SCHED_MAX_SPEC; ++i) s.draft_par[i] = parents[i];
|
||||
s.req->draft_parent = parents ? s.draft_par : nullptr;
|
||||
|
||||
/* The step issued ahead already verifies these: it was planned with the drafter's count and
|
||||
* the card has the tokens. The host copy is what its commit emits accepted tokens from, so it
|
||||
@@ -479,9 +499,9 @@ void Scheduler::trim_prefix_cache() {
|
||||
if (!pc_ || !cfg_.prefix_cache) return;
|
||||
const std::vector<int32_t>& cg = pc_->cached_groups();
|
||||
if (cg.empty()) return;
|
||||
/* An entry covers the lcm of the cached groups' blocks and holds that over a group's block of
|
||||
* its blocks (PrefixCache::blocks_per_entry); the trim asks for entries, as many as the group
|
||||
* furthest short needs. */
|
||||
/* An entry covers the lcm of the cached groups' block sizes and holds lcm / B blocks of a
|
||||
* group with B-token blocks (PrefixCache::blocks_per_entry). The trim asks for entries, as
|
||||
* many as the group furthest short needs. */
|
||||
int64_t entry = 0;
|
||||
for (int32_t g : cg) {
|
||||
const int64_t bs = kvgeom_.g[(size_t)g].block_size;
|
||||
@@ -874,10 +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<int64_t>(Q, 16) : 1;
|
||||
const int64_t t = geo_.grid_floor(target - margin);
|
||||
if (geo_.window_ckpt) return t >= I ? t : -1;
|
||||
return t > I ? t : -1;
|
||||
}
|
||||
const int64_t tail = target / Q * Q;
|
||||
/* A window snapshot is taken at the tail of any prompt of an interval or more, a block short
|
||||
* of the end: the next turn re-renders the last few tokens (the generation prompt is replaced
|
||||
* by the reply), and a snapshot past where the two renderings diverge is unreachable. Prompts
|
||||
* that left fewer than ~8 tokens in their last block always missed. */
|
||||
/* A window snapshot is taken at the tail of a prompt, a block short of its end: the next turn
|
||||
* re-renders the last few tokens (the generation prompt is replaced by the reply), and a
|
||||
* snapshot past where the two renderings diverge is unreachable. Prompts that left fewer than
|
||||
* ~8 tokens in their last block always missed. It is taken where that position is at least
|
||||
* kWindowSnapshotMin, or an interval where that is lower: from a 528-token prompt at a quantum
|
||||
* of 16. The snapshot is the only way a hit resumes on a model whose windowed layers the cache
|
||||
* does not index, so the floor is low: copying the window out and back costs a few
|
||||
* milliseconds, recomputing the prompt a prefill. */
|
||||
if (geo_.window_ckpt) {
|
||||
const int64_t t = (target - std::max<int64_t>(Q, 16)) / Q * Q;
|
||||
return t >= I ? t : -1;
|
||||
return t >= std::min<int64_t>(I, kWindowSnapshotMin) ? t : -1;
|
||||
}
|
||||
return tail > I && tail - tail / I * I >= std::max<int64_t>(Q, I / 4) ? tail : -1;
|
||||
}
|
||||
@@ -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<std::mutex> 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;
|
||||
}
|
||||
|
||||
+30
-5
@@ -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<size_t> took_;
|
||||
/* A step's prefill entries while step() moves its decode entries first; reserved at init,
|
||||
|
||||
@@ -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";
|
||||
|
||||
+100
-36
@@ -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. -->
|
||||
<div class="cell"><div class="n" id="m-kv">–<u></u></div>
|
||||
<span class="cap">kv cache in vram</span>
|
||||
<span class="cap" id="m-kvcap">kv cache in vram</span>
|
||||
<span class="det" id="m-kvdet"></span>
|
||||
<svg viewBox="0 0 200 22" preserveAspectRatio="none"><path/></svg></div>
|
||||
<div class="cell"><div class="n" id="m-accept">–<u>%</u></div>
|
||||
@@ -1353,7 +1359,7 @@ nav button.on { color:var(--fg); background:var(--track); }
|
||||
<span class="cap">conversations can resume</span>
|
||||
<span class="det" id="s-livedet"></span></div>
|
||||
<div class="cell"><div class="n" id="s-vram">–<u>tok</u></div>
|
||||
<span class="cap">context in vram</span>
|
||||
<span class="cap" id="s-vramcap">context in vram</span>
|
||||
<span class="det" id="s-vramdet"></span></div>
|
||||
<div class="cell" id="s-hostcell"><div class="n" id="s-host">–<u></u></div>
|
||||
<span class="cap">moved to host ram</span>
|
||||
@@ -1638,6 +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 <total>" is VRAM and the carve is its ceiling. With it the card holds only the
|
||||
* ring and every other block's K/V sits in a pinned host mirror: the figure above is the
|
||||
* mirror, which is the whole context and therefore larger than the carve -- printing the carve
|
||||
* beside it as a "max", or below as "can grow to", put a smaller number next to the larger one,
|
||||
* and the pool read full the moment the mirror did. The line names the tier instead, and the
|
||||
* ring keeps its own figure. */
|
||||
const kvStream = !!(s.link && s.link.kv_stream_active);
|
||||
/* THE TIER THE NUMBER IS IN, spelled. A streamed group's held context lives in the host mirror,
|
||||
* so the same figure is "in ram" on this card; without streaming every block is on the card and
|
||||
* it stays "in vram". The sessions view asks the same question of the same pool and renames its
|
||||
* cell from the flag this poll settles. `kvStream` is the ring's actual state, not the switch. */
|
||||
kvStreamOn = kvStream;
|
||||
$("m-kvcap").textContent = kvStream ? "kv cache in ram" : "kv cache in vram";
|
||||
$("m-kvdet").textContent = s.kv_bytes_total > 0
|
||||
? "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
|
||||
+ cnt3(s.kv_tokens_used) + " tok"
|
||||
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : "")
|
||||
? (kvStream
|
||||
? "of " + hb(s.kv_bytes_total) + " in host mirror · " + cnt3(s.kv_tokens_used) + " tok"
|
||||
+ " · " + hb(s.kv_bytes_carved || 0) + " VRAM ring"
|
||||
: "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
|
||||
+ cnt3(s.kv_tokens_used) + " tok"
|
||||
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : ""))
|
||||
: "";
|
||||
const aw = accWindow(s);
|
||||
const awR = aw ? aw.ratio : null;
|
||||
@@ -2298,29 +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 <style> and <script>;
|
||||
* frame-ancestors keeps a hostile page from framing the Model view and clickjacking its
|
||||
* guardrail toggle. */
|
||||
r.set_header("Content-Security-Policy",
|
||||
"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; "
|
||||
"connect-src 'self'; img-src 'self'; frame-ancestors 'none'; base-uri 'none'; "
|
||||
"form-action 'none'");
|
||||
r.set_header("X-Frame-Options", "DENY");
|
||||
return r;
|
||||
}
|
||||
|
||||
|
||||
+41
-5
@@ -433,6 +433,14 @@ static std::string lower_ascii(std::string s) {
|
||||
return s;
|
||||
}
|
||||
|
||||
bool HttpRequest::is_cross_origin() const {
|
||||
const std::string origin = header("Origin");
|
||||
if (origin.empty()) return false;
|
||||
const size_t at = origin.find("://");
|
||||
const std::string auth = at == std::string::npos ? origin : origin.substr(at + 3);
|
||||
return lower_ascii(auth) != lower_ascii(header("Host"));
|
||||
}
|
||||
|
||||
/* The API key a browser's socket carries. A browser cannot set a header on a WebSocket, so
|
||||
* OpenAI's browser clients offer it as a subprotocol, `openai-insecure-api-key.<key>`, beside
|
||||
* `realtime`; the subprotocol chosen is never that one. Compared in constant time, as the header
|
||||
@@ -486,6 +494,11 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
const size_t queued = (size_t)std::max<int64_t>(o.max_queued, 0);
|
||||
svr.new_task_queue = [nt, most, queued] { return new ConnectionPool((size_t)nt, most, queued); };
|
||||
|
||||
/* Every response, refusals and preflights included: no browser may second-guess the type.
|
||||
* The JSON routes answer only the dashboard's own fetch, and a body sniffed as HTML would
|
||||
* otherwise execute where it was only meant to be read. */
|
||||
svr.set_default_headers({{"X-Content-Type-Options", "nosniff"}});
|
||||
|
||||
/* An exception escaping a handler would close the connection with no body; answer 500 with
|
||||
* an error object instead. */
|
||||
svr.set_exception_handler([](const httplib::Request& req, httplib::Response& res,
|
||||
@@ -494,7 +507,9 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
try { std::rethrow_exception(ep); }
|
||||
catch (const std::exception& e) { what = e.what(); }
|
||||
catch (...) {}
|
||||
RAD_ERR("server: %s", what.c_str());
|
||||
/* e.what() can carry request text (a path, a header): keep it off the log as an
|
||||
* escape-sequence vector. */
|
||||
RAD_ERR("server: %s", log_sanitize(what).c_str());
|
||||
res.status = 500;
|
||||
res.set_content(error_body(req.path, 500, "internal_server_error", what),
|
||||
"application/json");
|
||||
@@ -534,10 +549,17 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
/* The probe paths and the dashboard page are exempt. A load balancer cannot send a
|
||||
* bearer token, and a browser opening the page cannot send a header; the page holds no
|
||||
* data and sends the key on every data fetch. Everything else is guarded, including
|
||||
* /tokenize, which vLLM leaves open (it only guards /v1). */
|
||||
* /tokenize, which vLLM leaves open (it only guards /v1).
|
||||
*
|
||||
* The exemption follows the methods those paths actually answer — reads, plus the POST
|
||||
* /ping of the health-check convention — so it cannot ride a method the router might
|
||||
* one day put behind one of these paths. */
|
||||
const std::string& p = hreq.path;
|
||||
if (!api_key.empty() && p != "/health" && p != "/v1/health" && p != "/ping" && p != "/" &&
|
||||
p != "/dashboard") {
|
||||
const std::string& m = hreq.method;
|
||||
const bool reads = m == "GET" || m == "HEAD";
|
||||
const bool probe = p == "/health" || p == "/v1/health" || p == "/" || p == "/dashboard";
|
||||
const bool exempt = (reads && (probe || p == "/ping")) || (p == "/ping" && m == "POST");
|
||||
if (!api_key.empty() && !exempt) {
|
||||
if (!key_ok(hreq)) {
|
||||
/* Logged in Server::error_response's format; the gate answers before the router. */
|
||||
RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
|
||||
@@ -582,8 +604,22 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
hres.set_chunked_content_provider(
|
||||
st->content_type,
|
||||
[st](size_t /*offset*/, httplib::DataSink& sink) -> bool {
|
||||
/* In the vendored 0.46 an exception escaping the provider unwinds the task queue
|
||||
* and aborts the process (upstream's 0.54.0 serve_guarded fixed exactly this);
|
||||
* until the lift moves, a throwing next() ends this response, not the server. */
|
||||
std::string chunk;
|
||||
bool more = st->next(chunk);
|
||||
bool more = true;
|
||||
try {
|
||||
more = st->next(chunk);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_ERR("server: stream provider threw: %s", log_sanitize(e.what()).c_str());
|
||||
sink.done();
|
||||
return true;
|
||||
} catch (...) {
|
||||
RAD_ERR("server: stream provider threw a non-standard exception");
|
||||
sink.done();
|
||||
return true;
|
||||
}
|
||||
if (!chunk.empty()) {
|
||||
if (!sink.write(chunk.data(), chunk.size())) return false; /* peer gone */
|
||||
}
|
||||
|
||||
@@ -52,6 +52,11 @@ struct HttpRequest {
|
||||
bool peer_gone() const { return closed && closed(); }
|
||||
/* True for 127.0.0.0/8, ::1, an IPv4-mapped 127.x address, and an in-process request. */
|
||||
bool peer_is_loopback() const;
|
||||
/* True when the request comes from a browser on another origin: an `Origin` header whose
|
||||
* authority differs from `Host`. Scripts send no Origin, so this never fires for curl or an
|
||||
* SDK. Through a proxy that rewrites Host, every browser reads as cross-origin — which is
|
||||
* exactly the case the "loopback-only" guards must not wave through. */
|
||||
bool is_cross_origin() const;
|
||||
};
|
||||
|
||||
struct HttpResponse {
|
||||
|
||||
+26
-6
@@ -92,10 +92,13 @@ json form_value(const std::string& key, const std::string& v) {
|
||||
if (v == "true" || v == "1") return json(true);
|
||||
if (v == "false" || v == "0") return json(false);
|
||||
}
|
||||
/* `loras` as JSON text, or one adapter's name. */
|
||||
/* `loras` as JSON text, or one adapter's name. Bounded like a request body: a form field
|
||||
* under the body cap can be brackets alone, and the deep tree's teardown would take the
|
||||
* process with it. Over-deep or over-budget reads as plain text, as a discarded parse did. */
|
||||
if ((key == "loras" || key == "lora") && !v.empty() && (v[0] == '[' || v[0] == '{')) {
|
||||
json j = json::parse(v, nullptr, false);
|
||||
if (!j.is_discarded()) return j;
|
||||
bool over = false, deep = false;
|
||||
json j = parse_json_bounded(v, 0, &over, &deep);
|
||||
if (!j.is_discarded() && !over && !deep) return j;
|
||||
}
|
||||
return json(v);
|
||||
}
|
||||
@@ -623,7 +626,16 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
src_px = std::move(src.rgba);
|
||||
}
|
||||
|
||||
auto render = [&](const std::string& prompt, gen::Branch* out, ApiError* err) -> int {
|
||||
auto render = [&](const std::string& prompt, const char* field, gen::Branch* out,
|
||||
ApiError* err) -> int {
|
||||
/* A prompt spelling the media marker would be scanned for pictures this request never
|
||||
* uploaded, and the scan would walk off the item list: refuse the text, as the chat and
|
||||
* embeddings paths refuse marker text (oai.cpp). */
|
||||
if (prompt.find(RAD_MEDIA_MARKER) != std::string::npos) {
|
||||
*err = err_bad(field, std::string("contains \"") + RAD_MEDIA_MARKER +
|
||||
"\": it names a picture this request did not upload");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::string text = r.background == "transparent" && !info.tmpl_transparent.empty()
|
||||
? replace_all(info.tmpl_transparent, "{prompt}", prompt)
|
||||
: prompt;
|
||||
@@ -651,6 +663,14 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
out->tokens.insert(out->tokens.end(), ids.begin(), ids.end());
|
||||
}
|
||||
if (at == std::string::npos) break;
|
||||
if (mi >= items.size()) {
|
||||
/* Unreachable for any request: the prompt text is refused above, so only a model
|
||||
* template that spells the marker past its pictures could reach it. Belt for the
|
||||
* day one does. */
|
||||
*err = err_internal("the render template spells the media marker more times "
|
||||
"than the request has pictures");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
mm::Placed pl;
|
||||
pl.item = items[mi++];
|
||||
pl.tok = (int32_t)out->tokens.size();
|
||||
@@ -716,8 +736,8 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
};
|
||||
{
|
||||
ApiError err;
|
||||
if (render(r.prompt, &g->pos, &err) < 0) return error_response(err, req.peer);
|
||||
if (r.has_neg && render(r.negative, &g->neg, &err) < 0)
|
||||
if (render(r.prompt, "prompt", &g->pos, &err) < 0) return error_response(err, req.peer);
|
||||
if (r.has_neg && render(r.negative, "negative_prompt", &g->neg, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
}
|
||||
|
||||
|
||||
@@ -260,15 +260,18 @@ std::string LiveView::render_line(const LiveSnapshot& s) const {
|
||||
o += " readmit=" + std::to_string(s.experts.readmits);
|
||||
}
|
||||
}
|
||||
/* Link traffic by consumer (collective, mover, MoE GEMM streaming), cumulative so a `| tee`
|
||||
* of these lines can be differenced into rates. */
|
||||
/* Link traffic by consumer (collective, mover, MoE GEMM streaming, KV streaming), cumulative
|
||||
* so a `| tee` of these lines can be differenced into rates. */
|
||||
if (s.link.present &&
|
||||
(s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes)) {
|
||||
(s.link.ar_bytes || s.link.h2d_bytes || s.link.d2h_bytes || s.link.stream_bytes ||
|
||||
s.link.kv_streaming)) {
|
||||
o += " link ar=" + std::to_string(s.link.ar_bytes);
|
||||
o += " h2d=" + std::to_string(s.link.h2d_bytes);
|
||||
o += " d2h=" + std::to_string(s.link.d2h_bytes);
|
||||
if (s.link.stream_bytes) o += " stream=" + std::to_string(s.link.stream_bytes);
|
||||
if (s.link.ssd_bytes) o += " ssd=" + std::to_string(s.link.ssd_bytes);
|
||||
/* Printed at zero when the switch is on: the zero is the measurement. */
|
||||
if (s.link.kv_streaming) o += " kv=" + std::to_string(s.link.kv_stream_bytes);
|
||||
}
|
||||
o += "\n";
|
||||
return o;
|
||||
|
||||
+20
-5
@@ -95,11 +95,12 @@ struct ExpertPlane {
|
||||
|
||||
/* Interconnect traffic by consumer.
|
||||
*
|
||||
* Three things share the link: the tensor-parallel all-reduce (set by model width and batch), the
|
||||
* expert mover's promotions and demotions (set by placement policy), and the MoE GEMM streaming a
|
||||
* routed expert that is not in VRAM (what the moves try to avoid). All are cumulative byte counts
|
||||
* on one clock, so rates from two polls compare directly: is the link busy because the model is
|
||||
* wide or because placement is thrashing?
|
||||
* Four things share the link: the tensor-parallel all-reduce (set by model width and batch), the
|
||||
* expert mover's promotions and demotions (set by placement policy), the MoE GEMM streaming a
|
||||
* routed expert that is not in VRAM (what the moves try to avoid), and --kv-resident's per-step
|
||||
* resolve, which copies the blocks a streamed KV group missed from its host mirror into the VRAM
|
||||
* ring (core/kvstream). All are cumulative byte counts on one clock, so rates from two polls
|
||||
* compare directly: is the link busy because the model is wide or because placement is thrashing?
|
||||
*
|
||||
* `ar_bytes` is the message payload summed over issues (see Ctx::ar_bytes). `h2d`/`d2h` are the
|
||||
* mover's measured copy sizes.
|
||||
@@ -117,6 +118,20 @@ struct LinkStat {
|
||||
/* The prefill stager's copies of the next layer's pooled experts (core/place/stager.h).
|
||||
* Included in `h2d_bytes`, like `prefetch_bytes`; subtract both for promotions alone. */
|
||||
int64_t staged_bytes = 0;
|
||||
/* KV streaming (--kv-resident): the bytes the resolves copied from the host mirror into the
|
||||
* ring. Rank 0's counters -- the ranks resolve the same block ids through maps brought up
|
||||
* identically, so one rank's answer is every rank's (see Engine::stream_probe_take) -- times
|
||||
* the world, to sit on every card's link like the move rows. `kv_streaming` says the switch
|
||||
* was asked for; a renderer then shows the row at zero included, because a zero with the
|
||||
* switch on is the answer to "does this model's pipeline ever stream?".
|
||||
*
|
||||
* `kv_stream_active` is the DIFFERENT question: whether a group's device pool really is a
|
||||
* resident window under its context. The switch is a preference -- it is zeroed when the
|
||||
* architecture refuses it, and --kv-resident at or above the group's context leaves a plain
|
||||
* resident pool -- so text that names a memory tier must read this, never the flag. */
|
||||
int64_t kv_stream_bytes = 0;
|
||||
bool kv_streaming = false;
|
||||
bool kv_stream_active = false;
|
||||
};
|
||||
|
||||
/* How the ranks ran their passes, summed over ranks (see Ctx::PassCounts). A played pass costs
|
||||
|
||||
+22
-10
@@ -163,7 +163,11 @@ std::string ApiError::dump() const {
|
||||
if (n_ctx >= 0) e["n_ctx"] = n_ctx;
|
||||
json o;
|
||||
o["error"] = e;
|
||||
return o.dump();
|
||||
/* A message can carry raw request text (a URL-decoded label, an echoed field name): dump
|
||||
* must survive invalid UTF-8 by replacing it rather than throwing and turning a 404 into
|
||||
* a 500. The JSON parsers refuse invalid UTF-8 in bodies, but URL-decoded params do not
|
||||
* pass through one. */
|
||||
return o.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
}
|
||||
|
||||
ApiError err_bad(const std::string& param, const std::string& why) {
|
||||
@@ -431,13 +435,16 @@ std::string str_or(const json& o, const char* k, const std::string& def = std::s
|
||||
}
|
||||
|
||||
/* A conversation's label for /sessions: at most 128 bytes, cut at a UTF-8 character boundary
|
||||
* because the label is serialised into JSON. */
|
||||
* because the label is serialised into JSON. Control bytes are dropped at the door: the label
|
||||
* is logged on release and shown on the dashboard, and an embedded ESC sequence would drive
|
||||
* whatever terminal renders it. */
|
||||
std::string session_label_of(const std::string& s) {
|
||||
std::string t = log_sanitize(s);
|
||||
constexpr size_t kMax = 128;
|
||||
if (s.size() <= kMax) return s;
|
||||
if (t.size() <= kMax) return t;
|
||||
size_t cut = kMax;
|
||||
while (cut > 0 && ((unsigned char)s[cut] & 0xC0) == 0x80) --cut;
|
||||
return s.substr(0, cut);
|
||||
while (cut > 0 && ((unsigned char)t[cut] & 0xC0) == 0x80) --cut;
|
||||
return t.substr(0, cut);
|
||||
}
|
||||
|
||||
/* One field under several spellings (OpenAI's, vLLM's, llama.cpp's), read as a number (double)
|
||||
@@ -1053,8 +1060,11 @@ void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt) {
|
||||
if (lim.reasoning_effort_map.empty()) return;
|
||||
auto it = opt->template_kwargs.find("reasoning_effort");
|
||||
if (it == opt->template_kwargs.end()) return;
|
||||
const json v = json::parse(it->second, nullptr, false);
|
||||
if (!v.is_string()) return;
|
||||
/* The kwarg is client text re-parsed as JSON: bound it like a body, a string of brackets
|
||||
* would overflow this worker's stack when the tree comes down. */
|
||||
bool over = false, deep = false;
|
||||
const json v = parse_json_bounded(it->second, 0, &over, &deep);
|
||||
if (over || deep || !v.is_string()) return;
|
||||
auto m = lim.reasoning_effort_map.find(v.get<std::string>());
|
||||
if (m == lim.reasoning_effort_map.end()) return;
|
||||
if (m->second == "none" || m->second == "minimal") {
|
||||
@@ -1071,9 +1081,11 @@ ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, in
|
||||
* variable was in the render. The set is more actionable than the template's traceback. */
|
||||
auto it = opt.template_kwargs.find("reasoning_effort");
|
||||
if (it != opt.template_kwargs.end() && !lim.reasoning_efforts.empty()) {
|
||||
const json v = json::parse(it->second, nullptr, false);
|
||||
bool over = false, deep = false;
|
||||
const json v = parse_json_bounded(it->second, 0, &over, &deep);
|
||||
const std::vector<std::string>& set = lim.reasoning_efforts;
|
||||
if (v.is_string() && std::find(set.begin(), set.end(), v.get<std::string>()) == set.end()) {
|
||||
if (!over && !deep && v.is_string() &&
|
||||
std::find(set.begin(), set.end(), v.get<std::string>()) == set.end()) {
|
||||
std::string list;
|
||||
for (size_t i = 0; i < set.size(); ++i)
|
||||
list += (i ? (i + 1 == set.size() ? " and " : ", ") : "") + ("'" + set[i] + "'");
|
||||
@@ -3782,7 +3794,7 @@ std::string anthropic_error_body(const ApiError& e) {
|
||||
json o;
|
||||
o["type"] = "error";
|
||||
o["error"] = json{ { "type", anthropic_error_type(e.status) }, { "message", e.message } };
|
||||
return o.dump();
|
||||
return o.dump(-1, ' ', false, json::error_handler_t::replace); /* see ApiError::dump */
|
||||
}
|
||||
|
||||
AnthropicStream::AnthropicStream(const OaiRequest& r, int index, const IReplyParser* parser)
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
*/
|
||||
#include "server.h"
|
||||
#include "server_priv.h"
|
||||
#include "oai.h"
|
||||
|
||||
#include "mm/processor.h"
|
||||
#include "mm/resample.h"
|
||||
@@ -658,8 +659,12 @@ bool Server::realtime_loop(RealtimeSession& s, WsConn& ws) {
|
||||
|
||||
auto handle = [&](const std::string& msg, bool binary) {
|
||||
if (binary) return append_pcm((const uint8_t*)msg.data(), msg.size(), nullptr);
|
||||
const ojson j = ojson::parse(msg, nullptr, /*allow_exceptions=*/false);
|
||||
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string())
|
||||
/* Bounded like a request body: 2 MiB of brackets is a legal WebSocket frame, and the
|
||||
* recursive teardown of a deep tree would take the whole process down with it. */
|
||||
bool over = false, deep = false;
|
||||
const ojson j = parse_json_bounded(msg, 0, &over, &deep);
|
||||
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("type") ||
|
||||
!j["type"].is_string())
|
||||
return error("invalid_request_error", "invalid_json",
|
||||
"a client event is a JSON object with a string `type`", "", nullptr);
|
||||
const std::string type = j["type"].get<std::string>();
|
||||
|
||||
+21
-10
@@ -406,13 +406,15 @@ static std::string from_peer(const std::string& peer) {
|
||||
HttpResponse Server::error_response(const ApiError& e, const std::string& peer, ApiShape shape) {
|
||||
metrics_.observe_http(e.status);
|
||||
/* Log every refusal with status, type, message and peer: 4xx at info (the client's doing),
|
||||
* 5xx as a warning (ours). */
|
||||
* 5xx as a warning (ours). The message can echo request text (a URL-decoded label, a field
|
||||
* name), so the log copy is control-byte-clean; the wire copy keeps the bytes. */
|
||||
const std::string msg = log_sanitize(e.message), typ = log_sanitize(e.type);
|
||||
if (e.status >= 500)
|
||||
RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
|
||||
e.message.c_str());
|
||||
RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, typ.c_str(),
|
||||
msg.c_str());
|
||||
else
|
||||
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
|
||||
e.message.c_str());
|
||||
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, typ.c_str(),
|
||||
msg.c_str());
|
||||
HttpResponse r = HttpResponse::json_body(
|
||||
e.status, shape == ApiShape::Anthropic ? anthropic_error_body(e) : e.dump());
|
||||
if (e.status == 429) r.set_header("Retry-After", std::to_string(opt_.retry_after_s));
|
||||
@@ -1791,6 +1793,7 @@ HttpResponse Server::handle_systemone(const HttpRequest& req) {
|
||||
}
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(json{
|
||||
{ "model", opt_.model_id },
|
||||
{ "answers", std::move(answers) },
|
||||
{ "usage", { { "input_tokens", r.input_tokens }, { "output_tokens", 0 } } } }));
|
||||
}
|
||||
@@ -1969,6 +1972,7 @@ HttpResponse Server::handle_mica(const HttpRequest& req) {
|
||||
if (mica_answers(r, dist, &answers, &err) < 0) return error_response(err, req.peer);
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(json{
|
||||
{ "model", opt_.model_id },
|
||||
{ "answers", std::move(answers) },
|
||||
{ "usage", { { "input_tokens", input_tokens }, { "output_tokens", 0 } } } }));
|
||||
}
|
||||
@@ -2056,6 +2060,7 @@ HttpResponse Server::handle_clef(const HttpRequest& req) {
|
||||
release(1);
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(json{
|
||||
{ "model", opt_.model_id },
|
||||
{ "answers", std::move(answers) },
|
||||
{ "usage", { { "input_tokens", (int64_t)r.tokens.size() }, { "output_tokens", 0 } } } }));
|
||||
}
|
||||
@@ -2150,7 +2155,8 @@ HttpResponse Server::handle_laya(const HttpRequest& req) {
|
||||
retire(gens);
|
||||
release(n);
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(json{ { "answers", std::move(answers) },
|
||||
return HttpResponse::json_body(200, json_dump(json{ { "model", opt_.model_id },
|
||||
{ "answers", std::move(answers) },
|
||||
{ "usage", laya_usage(r) } }));
|
||||
}
|
||||
|
||||
@@ -2206,7 +2212,6 @@ HttpResponse Server::handle_loras(const HttpRequest& req) {
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
|
||||
using json = nlohmann::json;
|
||||
auto fail = [&](int status, const char* type, const std::string& msg) {
|
||||
ApiError e;
|
||||
e.status = status;
|
||||
@@ -2217,12 +2222,18 @@ HttpResponse Server::handle_lora_admin(const HttpRequest& req, bool load) {
|
||||
if (!opt_.lora_load || !opt_.lora_unload)
|
||||
return fail(404, "not_found_error", "this server was started without runtime LoRA (--lora or "
|
||||
"--max-loras)");
|
||||
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 counts as neither loopback nor local: the victim's own browser
|
||||
* is loopback to this port, and that is exactly how a hostile page would reach here. */
|
||||
return fail(403, "permission_error", "loading an adapter reads a path on this machine, and a "
|
||||
"server started without --api-key takes it only from a "
|
||||
"loopback client");
|
||||
const json j = json::parse(req.body, nullptr, false);
|
||||
if (j.is_discarded() || !j.is_object() || !j.contains("lora_name") || !j["lora_name"].is_string())
|
||||
/* Bounded like a generation body: this parses client text the same way, and a deep bracket
|
||||
* nest would overflow this worker's stack when the tree is torn down. */
|
||||
bool over = false, deep = false;
|
||||
const json j = parse_json_bounded(req.body, 0, &over, &deep);
|
||||
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("lora_name") ||
|
||||
!j["lora_name"].is_string())
|
||||
return fail(400, "invalid_request_error", "the body must be a JSON object with lora_name");
|
||||
const std::string name = j["lora_name"].get<std::string>();
|
||||
if (name.empty() || name == opt_.model_id)
|
||||
|
||||
@@ -149,9 +149,10 @@ struct ServerOptions {
|
||||
* a string rendered once: the dump includes `OpInfo::issued`, which a pre-first-step snapshot
|
||||
* would report as false for every op, hiding dead declarations.
|
||||
*
|
||||
* Regenerating reads the Program on the HTTP thread while the step path writes that field. It
|
||||
* is a monotonic false -> true bool, so at worst a mid-step fetch shows an op unissued one step
|
||||
* early. Registry::select is called with record = false and mutates nothing else. */
|
||||
* Regenerating reads the Program on the HTTP thread while the step path writes that field;
|
||||
* both sides go through std::atomic_ref (Ctx::flush_issued, rad_graph.cpp), so the pairing is
|
||||
* a relaxed exchange rather than a data race. Registry::select is called with record = false
|
||||
* and mutates nothing else. */
|
||||
std::function<std::string()> graph_json;
|
||||
/* The startup report as JSON (core/diag/diag.h): options in force, the machine as it is now
|
||||
* (the provider may reuse a reading for a second), and what on it costs speed. Without an API
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
*/
|
||||
#include "server.h"
|
||||
#include "server_priv.h"
|
||||
#include "oai.h"
|
||||
#include "text_split.h"
|
||||
|
||||
#include "gen/audio.h"
|
||||
@@ -279,8 +280,12 @@ bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) {
|
||||
"session.close");
|
||||
return false;
|
||||
}
|
||||
const json j = json::parse(msg, nullptr, /*allow_exceptions=*/false);
|
||||
if (j.is_discarded() || !j.is_object() || !j.contains("type") || !j["type"].is_string()) {
|
||||
/* Bounded like a request body: a deep bracket nest is a legal frame, and tearing its
|
||||
* tree down recurses once per level. */
|
||||
bool over = false, deep = false;
|
||||
const json j = parse_json_bounded(msg, 0, &over, &deep);
|
||||
if (j.is_discarded() || over || deep || !j.is_object() || !j.contains("type") ||
|
||||
!j["type"].is_string()) {
|
||||
error("a client message is a JSON object with a string `type`");
|
||||
return false;
|
||||
}
|
||||
|
||||
+2
-3
@@ -24,6 +24,8 @@ struct ChatTemplate::Impl {
|
||||
bool add_bos = false, add_eos = false;
|
||||
};
|
||||
|
||||
/* The template's own words: the lifted autoparser wraps whatever the render threw in a sentence
|
||||
* about parser generation, which the render's failure is not. */
|
||||
static std::string template_words(const char* what) {
|
||||
static const char kWrap[] = "Unable to generate parser for this template. Automatic parser "
|
||||
"generation failed: ";
|
||||
@@ -190,9 +192,6 @@ static bool lead_system(const ojson& messages, ojson* out) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* The template's own words: the lifted autoparser wraps whatever the render threw in a sentence
|
||||
* about parser generation, which the render's failure is not. */
|
||||
|
||||
int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt,
|
||||
ChatPrompt* out) const {
|
||||
if (!ready()) {
|
||||
|
||||
@@ -68,6 +68,15 @@ LogRank::~LogRank() { g_log_rank = prev_; }
|
||||
static std::atomic<uint64_t> g_last_line_ns{0};
|
||||
uint64_t log_last_line_ns() { return g_last_line_ns.load(std::memory_order_relaxed); }
|
||||
|
||||
std::string log_sanitize(const std::string& s) {
|
||||
std::string out = s;
|
||||
for (char& c : out) {
|
||||
const unsigned char b = (unsigned char)c;
|
||||
if ((b < 0x20 && b != '\t') || b == 0x7f) c = '?';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
|
||||
const char* base = std::strrchr(file, '/');
|
||||
base = base ? base + 1 : file;
|
||||
|
||||
@@ -15,8 +15,8 @@ rest U64 in the GGUF, which the core reads as I64):
|
||||
engram.head_vocab_sizes I64 [n_engram_layers * (max_ngram - 1) * n_heads]
|
||||
engram.head_offsets I64 [same] (absolute row offsets into the joined table)
|
||||
|
||||
The deepseek41 plugin reads them under these names when the checkpoint is the release
|
||||
(arch/deepseek41 ckpt_name). Reads config.json and tokenizer.json only (small).
|
||||
The deepseek41 architecture plugin, which this tree does not include, reads them under these names
|
||||
when the checkpoint is the release. Reads config.json and tokenizer.json only (small).
|
||||
|
||||
usage: python3 data/engram_tables.py RELEASE_DIR OUT.safetensors
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# d1-3b-fp8.recipe -- LiquidAI d1-3B (LFM2) with block-scaled fp8 linears.
|
||||
#
|
||||
# rad-convert <LiquidAI/d1-3B> -o d1-3b-fp8.rad --set decision.type=d1 \
|
||||
# --recipe data/recipes/d1-3b-fp8.recipe
|
||||
#
|
||||
# Every linear of the 30 layers (attention q, k, v and output; the convolutions' in and out
|
||||
# projections; gate|up and down) becomes E4M3 codes with a bf16 scale a 128 x 128 block, read by the
|
||||
# fp8a8 GEMMs over activations quantised per 128 columns. The lm_head (tied to the embedding, so the
|
||||
# embedding itself stays bf16) becomes int8 with a bf16 scale per row per 128 columns, read by
|
||||
# logits_gemm_i8: as fast as an E4M3 head and closer to bf16 (84 d1 decisions against the bf16
|
||||
# model: no decision moved, mean |dP| 0.0086 against 0.0085 with a bf16 head). The short
|
||||
# convolution and the norms stay bf16.
|
||||
|
||||
blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.conv_in.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.conv_out.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
output.weight rtn codes=i8 group=128 scale=bf16
|
||||
@@ -8,7 +8,7 @@
|
||||
# rad-convert <DeepSeek-V4.1-Flash-1017 dir> --add engram-tables.safetensors \
|
||||
# --recipe data/recipes/deepseek41-ud-iq1s.recipe --imatrix <imatrix.gguf> -o deepseek41-ud-iq1s.rad
|
||||
#
|
||||
# The imatrix is Unsloth's with entries for the fused weights added (docs/deepseek41-wip.md). One rule per weight,
|
||||
# The imatrix is Unsloth's with entries for the fused weights added (data/imatrix_merge.py, docs/deepseek41-hf-direct.md). One rule per weight,
|
||||
# experts collapsed per layer; first match wins.
|
||||
# PATTERN QUANTISER OPTIONS
|
||||
dspark.enc.output_norm.weight cast dtype=f32
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
# speculator merged in (gemma-4-31B-it-speculator.dflash2: block 8, 7 drafts a pass, int8 head), and
|
||||
# the vision tower. Converted with data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe, or downloaded
|
||||
# from https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2. The drafter
|
||||
# serves the depth it was trained at (`auto`). Sampling defaults are the checkpoint's
|
||||
# generation_config; thinking is switched per request (chat_template_kwargs).
|
||||
# serves the depth it was trained at (`auto`), its proposals verified as a 7-node tree a step (on
|
||||
# by default for this drafter). Sampling defaults are the
|
||||
# checkpoint's generation_config; thinking is switched per request (chat_template_kwargs).
|
||||
#
|
||||
# --tp 4 over four cards; chained launches, the weight reads beside the collectives and the prefill
|
||||
# overlap turn themselves on there.
|
||||
@@ -12,9 +13,10 @@
|
||||
# tokens of a step, with one decode-only step after it, so a long prompt holds the others up by a
|
||||
# fraction of a chunk rather than all of it. 16 sequences, as measured below.
|
||||
#
|
||||
# On 4x R9700 (PCIe 4.0 x16): one user 390 code / 288 prose / 208 story tok/s, and
|
||||
# 590 after a 6442-token prompt (prefill 5962 tok/s); 302 / 512 / 658 / 835 / 981 tok/s aggregate
|
||||
# at 1 / 2 / 4 / 8 / 16 users (BetterBench, thinking off).
|
||||
# On 4x R9700 (PCIe 4.0 x16), BetterBench with thinking off: 378 tok/s single-stream (weighted
|
||||
# over its categories; JSON 593, math 496, code 417, prose 230) and 341 / 552 / 727 / 877 / 960
|
||||
# tok/s aggregate at 1 / 2 / 4 / 8 / 16 users. The chain on the same cards: 352, and 315 / 505 /
|
||||
# 680 / 816 / 907. Prefill of a 6442-token prompt: about 5960 tok/s.
|
||||
#
|
||||
# Measured with the host CPU's performance governor and its idle states past C1 off. The cards'
|
||||
# peer-to-peer traffic crosses the root complex, so the host's power state shows in every step, and
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
# Gemma 4 31B-it on two cards with a block-16 DFlash2 drafter: the int4 trunk of
|
||||
# gemma4-31b-w4a8-df2-tp4.yaml (round-to-nearest with a scale search, from the bf16 checkpoint; q, k
|
||||
# and v as one linear) with int8 activations and lm_head, and the vision tower, with RedHatAI's DFlash2
|
||||
# speculator fine-tuned from block 8 to block 16
|
||||
# (https://huggingface.co/Ashlyn4202025/gemma-4-31B-it-speculator.dflash2-b16: 15 drafts a pass, int8
|
||||
# head). Converted with data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe and that drafter, or
|
||||
# downloaded from https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2-b16. Sampling defaults
|
||||
# are the checkpoint's generation_config; thinking is switched per request (chat_template_kwargs).
|
||||
#
|
||||
# The drafter's proposals are verified as a 15-node tree a step (`auto`). From two users on, each
|
||||
# tree is a 7-node one over the drafter's short block of 8 rows, so a busy server verifies and
|
||||
# drafts the block-8 tree's shape, from the block-16 drafter. It turns itself on for this container
|
||||
# (--draft-short-from auto; --draft-short-from 0 keeps the whole tree under load, for an A/B).
|
||||
#
|
||||
# --tp 2 over two cards. The token embedding stays in pinned host memory (the default), which leaves
|
||||
# its VRAM to the KV cache. 16 sequences, as measured below. --gpu-headroom-mib 160 keeps room for
|
||||
# the page tables the cards hold for pinned host memory, which the VRAM budget does not yet charge:
|
||||
# without it a two-card start settles ~55 MiB short, and the prefill overlap's second lane can fail
|
||||
# mid-serve.
|
||||
#
|
||||
# On 2x R9700 (PCIe 4.0 x16), BetterBench with thinking off, the box's other two cards serving a
|
||||
# second server at the same time, the mean of two runs with the card pairs swapped: 253 tok/s
|
||||
# single-stream (weighted over its categories; JSON 450, math 360, code 280, prose 131) and
|
||||
# 217 / 328 / 518 / 559 / 776 tok/s aggregate at 1 / 2 / 4 / 8 / 16 users. The block-8 container,
|
||||
# measured the same way: 199, and 180 / 323 / 494 / 530 / 682.
|
||||
#
|
||||
# Measured with the host CPU's performance governor and its idle states past C1 off. The cards'
|
||||
# peer-to-peer traffic crosses the root complex, so the host's power state shows in every step, and
|
||||
# a compose file can't set it.
|
||||
name: radiance-gemma4-31b-w4a8-df2b16-tp2
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-gemma4-31b-w4a8-df2b16-tp2
|
||||
command: >
|
||||
--model /models/gemma4-31b-dense-w4a8-df2b16-qkv.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 2 --max-num-seqs 16 --max-model-len 65536 --kv-cache-dtype fp8
|
||||
--num-speculative-tokens auto --max-num-batched-tokens 8192
|
||||
--busy-prefill-chunk 512 --prefill-interleave 1 --gpu-headroom-mib 160
|
||||
--temp 1.0 --top-p 0.95 --top-k 64
|
||||
@@ -0,0 +1,38 @@
|
||||
# Gemma 4 31B-it on four cards with a block-16 DFlash2 drafter: the int4 trunk of
|
||||
# gemma4-31b-w4a8-df2-tp4.yaml (round-to-nearest with a scale search, from the bf16 checkpoint; q, k
|
||||
# and v as one linear) with int8 activations and lm_head, and the vision tower, with RedHatAI's DFlash2
|
||||
# speculator fine-tuned from block 8 to block 16
|
||||
# (https://huggingface.co/Ashlyn4202025/gemma-4-31B-it-speculator.dflash2-b16: 15 drafts a pass, int8
|
||||
# head). Converted with data/recipes/gemma4-31b-dense-bf16-w4a8-df2.recipe and that drafter, or
|
||||
# downloaded from https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2-b16. Sampling defaults
|
||||
# are the checkpoint's generation_config; thinking is switched per request (chat_template_kwargs).
|
||||
#
|
||||
# The drafter's proposals are verified as a 15-node tree a step (`auto`). From two users on, each
|
||||
# tree is a 7-node one over the drafter's short block of 8 rows, so a busy server verifies and
|
||||
# drafts the block-8 tree's shape, from the block-16 drafter. It turns itself on for this container
|
||||
# (--draft-short-from auto; --draft-short-from 0 keeps the whole tree under load, for an A/B).
|
||||
#
|
||||
# --tp 4 over four cards, with everything else as in gemma4-31b-w4a8-df2-tp4.yaml: chained launches,
|
||||
# the weight reads beside the collectives and the prefill overlap turn themselves on there. 16
|
||||
# sequences, as measured below.
|
||||
#
|
||||
# On 4x R9700 (PCIe 4.0 x16), BetterBench with thinking off: 446 tok/s single-stream (weighted
|
||||
# over its categories; JSON 801, math 624, code 520, prose 228) and 376 / 553 / 727 / 870 / 965
|
||||
# tok/s aggregate at 1 / 2 / 4 / 8 / 16 users. The block-8 file, measured alongside: 389, and
|
||||
# 338 / 560 / 716 / 873 / 970.
|
||||
#
|
||||
# Measured with the host CPU's performance governor and its idle states past C1 off. The cards'
|
||||
# peer-to-peer traffic crosses the root complex, so the host's power state shows in every step, and
|
||||
# a compose file can't set it.
|
||||
name: radiance-gemma4-31b-w4a8-df2b16-tp4
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-gemma4-31b-w4a8-df2b16-tp4
|
||||
command: >
|
||||
--model /models/gemma4-31b-dense-w4a8-df2b16-qkv.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 4 --max-num-seqs 16 --max-model-len 65536 --kv-cache-dtype fp8
|
||||
--num-speculative-tokens auto --max-num-batched-tokens 8192
|
||||
--busy-prefill-chunk 512 --prefill-interleave 1
|
||||
--temp 1.0 --top-p 0.95 --top-k 64
|
||||
+27
-18
@@ -16,7 +16,7 @@ plugin claims.
|
||||
| `arch/hyv3_gguf` | `hyv3` | `gguf_ftype_15` | llama.cpp Hy-Memory Q4_K_M GGUF, dequantized and recipe-converted to native Radiance weights; TP1/2 |
|
||||
| `arch/qwen35_w8a8` | `qwen35` | `w8a8_fwht128` | `qwen35_fp8` with an int8 trunk: i8 weights with a bf16 scale per 128 of K, rotated by a 128-wide Hadamard, against int8 activations under the same rotation (`data/recipes/q38-27b-w8a8-df2.recipe`) |
|
||||
| `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed |
|
||||
| `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert |
|
||||
| `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert, or Qwen's FP8 release as it ships |
|
||||
| `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Pictures through its vision tower (`arch/common/rad_block_glm_vision.h`); bf16 KV |
|
||||
| `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank |
|
||||
| `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector |
|
||||
@@ -345,8 +345,11 @@ Architecture tests cover geometry, GGUF tensor maps, dense-to-MoE scheduling, TP
|
||||
and FP32 combine order; checkpoint tests cover Q4_K/Q6_K block decoding. Numerical parity against Tencent/llama.cpp
|
||||
remains untested.
|
||||
|
||||
See [HYV3 W4 decode optimizations](benchmarks/hyv3-w4-decode.md) for affected paths,
|
||||
historical measurements, validation limits and the remaining benchmark/quality gates.
|
||||
Decode on the full-GPTQ W4 model, TP1 on one R9700 (10,030-token prompt, 2,000 generated tokens,
|
||||
greedy, no drafter): 76.6 tok/s before the per-128 I4 expert packing, the one-row W4/W5 epilogue,
|
||||
the in-GEMM BF16 narrowing, the fused Q/K norm + RoPE + KV store and the residual and shared-expert
|
||||
folds; 109.6 tok/s with them, prefill unchanged (7,876 to 7,927 tok/s). The answer is byte-identical,
|
||||
and on an eight-document teacher-forced corpus the two builds agree at every top-1 (mean KL 7.6e-8).
|
||||
|
||||
## `qwen35_w8a8`
|
||||
|
||||
@@ -415,6 +418,13 @@ plugin reads each weight's encoding from the container and declares the op that
|
||||
- bf16: every norm gain, `A_log`, `dt_bias`, `conv1d`, `in_proj_a` and `in_proj_b` (48 rows is not
|
||||
a whole scale block), the router, `shared_expert_gate` and `embed_tokens`.
|
||||
|
||||
Qwen's own `Qwen3.8-Flash-Next-FP8` converts without a recipe too. Its `quantization_config`
|
||||
(`quant_method: fp8`, no `fmt`) is block-scaled E4M3, descriptor `fp8_e4m3`; no `qwen4exp` plugin
|
||||
claims it, so each weight is read as it ships and this plugin serves it: the routed experts (MTP
|
||||
head's included) at block FP8 with their bf16 `weight_scale_inv`, the n-gram table's 128 FP8
|
||||
shards under its one `ngram_embedding.weight_scale`, and every other weight bf16. A recipe applies
|
||||
to it as to the bf16 checkpoint, with each FP8 weight read through its scales.
|
||||
|
||||
**The attention cache takes `--kv-cache-dtype fp8_v4` or `k6_v4`.** The QSA layers' cache (and the
|
||||
MTP head's layer, which shares it) is then declared at head_dim 200 or 176, a token's quantised row
|
||||
over two, and read by the gqa12 rows (gqa6 with 4-token pages at four ranks) of those layouts
|
||||
@@ -872,9 +882,9 @@ text 12 layers, hidden 768, ffn 3072, vocab 250048, 12 heads of 64, type vo
|
||||
mean over every real token, cast to the f32 pooled buffer; the server L2-normalises
|
||||
```
|
||||
|
||||
The block order is the one the verified variant uses: attention on the raw stream, then LN1, the
|
||||
feed-forward on LN1's output, then LN2 over that output plus the feed-forward's. The checkpoint's
|
||||
shared `experts.bias` is not applied, and the plugin does not map it. A container that sets
|
||||
Block order: attention on the raw stream, then LN1, the feed-forward on LN1's output, then LN2
|
||||
over that output plus the feed-forward's. The checkpoint's shared `experts.bias` is not applied,
|
||||
and the plugin does not map it. A container that sets
|
||||
`prenorm`, `causal`, interleaved, partial or scaled rotary, a gelu variant, renormalised routing
|
||||
or a shared expert is refused at declare.
|
||||
|
||||
@@ -895,10 +905,10 @@ reads a bf16 table. The token embedding, linears, router and expert tables are b
|
||||
| `blk.N.ffn_exp_w2.E.weight` (odd N) | `encoder.layers.N.mlp.experts.mlp.w2` | [768, 3072] | slice E, transpose |
|
||||
| not declared (odd N) | `encoder.layers.N.mlp.experts.bias` | [768] | not mapped |
|
||||
|
||||
The checkpoint stores `w1` and `w2` as one stacked tensor each, `[24576, 768]`; `E` takes the
|
||||
expert's dim-0 slice, and `w2` is transposed to `[768, 3072]` for the grouped GEMM. Every expert
|
||||
has two group slots, one for each projection. Nothing else is mapped: there is no final norm, no
|
||||
pooler, no position table and no output head.
|
||||
The checkpoint stores `w1` and `w2` as one stacked tensor each, `[24576, 768]`; expert `E` is rows
|
||||
`[E * 3072, (E + 1) * 3072)`, and `w2`'s block is transposed to `[768, 3072]` for the grouped GEMM.
|
||||
Every expert has two group slots, one for each projection. Nothing else is mapped: there is no
|
||||
final norm, no pooler, no position table and no output head.
|
||||
|
||||
**The recipe.** The checkpoint is f32 (1.9 GB).
|
||||
|
||||
@@ -907,15 +917,14 @@ rad-convert <checkpoint dir> --recipe data/recipes/nomic-embed-v2-moe-bf16.recip
|
||||
-o nomic-embed-v2-moe-bf16.rad
|
||||
```
|
||||
|
||||
It takes 3.5 s and writes a 959 MB container (907 MiB of weights). The checkpoint directory must
|
||||
contain `tokenizer.json`. The recipe casts the token embedding, the token-type table, the
|
||||
attention, dense MLP and expert weights to bf16 and leaves the norms and biases f32.
|
||||
It writes a 959 MB container (907 MiB of weights). The checkpoint directory must contain
|
||||
`tokenizer.json`. The recipe casts the token embedding, the token-type table, the attention,
|
||||
dense MLP and expert weights to bf16 and leaves the norms and biases f32.
|
||||
|
||||
**Verified.** 20 texts against a pure-float32 reference: mean cosine 0.99995, min 0.99983 on a
|
||||
gfx1201 card, with libavx and libref the same to 4 decimals. Against a Q6_K quantisation of the
|
||||
same model the mean is 0.9944 (min 0.990); the Q8_0 one agrees with the reference at 0.9994, so
|
||||
the Q6_K quantisation is the outlier, about 0.006 off the true model, and stored vectors from a
|
||||
Q6_K server drift by about that much.
|
||||
**Verified.** On 20 texts against a pure-float32 reference, on a gfx1201 card: mean cosine
|
||||
0.99995, min 0.99983; libavx and libref agree with it to 4 decimals. Against the same reference a
|
||||
Q8_0 quantisation of the model scores a mean of 0.9994 and a Q6_K one 0.9944 (min 0.990), so
|
||||
vectors stored from a Q6_K server differ by about 0.006.
|
||||
|
||||
**Measured.** On one gfx1201 card, short texts take 2 ms a request at one client, 3854 requests/s
|
||||
at 64 concurrent clients and 4400 texts/s for a batch of 32 in one request; a 1354-character text
|
||||
|
||||
+122
-50
@@ -52,7 +52,7 @@ driver. [`DOCKER.md`](DOCKER.md) covers it, with compose files per model.
|
||||
| Optional | ROCm with `hipcc`, for AMD device kernels; without it you get the host backend. Set `ROCM_PATH` if ROCm is not at `/opt/rocm` |
|
||||
| With a card | Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The host writes every dispatch's arguments into VRAM there. On a card whose BAR is smaller than its VRAM they stay in pinned host memory and every dispatch reads them over the link: on R9700s, Qwen3.8-27B fp8 decode steps take 0.4-1.8% longer at `--tp 1` and 2 than with the arguments in VRAM. Peer access needs the large BAR too, so at `--tp 2` and above such a card takes the collectives through host memory (§4.7) |
|
||||
| Optional | OpenMP, used by the host kernel libraries if present |
|
||||
| Optional | `libavformat-dev libavcodec-dev libavutil-dev libswscale-dev libswresample-dev` (ffmpeg 6+), for image, video and audio input. The probe is `RAD_WITH_FFMPEG` (`ON` fatal, `OFF` off, default `AUTO`): built without them the engine boots normal, serves text, and refuses every image/video/audio part with HTTP 500 — the configure log is the only warning (`radiance: no libavformat ...`). `GET /diagnostics` shows `media decoders` |
|
||||
| Optional | `libavformat-dev libavcodec-dev libavutil-dev libswscale-dev libswresample-dev` (ffmpeg 6+), for image, video and audio input. CMake option `RAD_WITH_FFMPEG`: `AUTO` (default) uses them when found, `ON` fails the configure without them, `OFF` builds without. A build without them starts and serves text, and refuses every image, video and audio part with HTTP 500; the only warning is the configure log line `radiance: no libavformat ...`. The diagnostics report says which (`media decoders`; `host.media` in `GET /diagnostics`) |
|
||||
| Optional | `clang++` (or ROCm's), for `tests/r4d_emu` when the C++ compiler is g++; CMake 3.25+ for `CMakePresets.json` |
|
||||
| Shell harnesses | `curl` and `jq` |
|
||||
|
||||
@@ -93,10 +93,10 @@ cmake --build build -j
|
||||
ctest --test-dir build -L fast -j8 --output-on-failure
|
||||
```
|
||||
|
||||
A ROCm SDK installed outside `/opt/rocm` — a userspace SDK tree under a virtualenv, a core-only
|
||||
system install — needs more than `ROCM_PATH`: hipcc is found, then device compilation dies inside
|
||||
`cuda_wrappers/cmath` with `Could not find standard C++ header 'cmath'`, because ROCm's clang
|
||||
does not pick up the distro gcc's libstdc++ headers on its own. The flags that make it work:
|
||||
A ROCm SDK installed outside `/opt/rocm` (a userspace SDK tree under a virtualenv, or a core-only
|
||||
system install) needs more than `ROCM_PATH`. hipcc is found, but device compilation fails inside
|
||||
`cuda_wrappers/cmath` with `Could not find standard C++ header 'cmath'`, because ROCm's clang does
|
||||
not pick up the distro gcc's libstdc++ headers on its own. Configure with:
|
||||
|
||||
```sh
|
||||
ROCM=/path/to/_rocm_sdk_devel # the SDK root (the venv's site-packages/_rocm_sdk_devel)
|
||||
@@ -108,11 +108,11 @@ cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
|
||||
export LD_LIBRARY_PATH=$ROCM/lib:$LD_LIBRARY_PATH
|
||||
```
|
||||
|
||||
`--gcc-install-dir` takes the distro gcc's directory (the installed gcc-15's; after a distro gcc
|
||||
upgrade it must be repointed, and the configure cached in `build/CMakeCache.txt` reset with
|
||||
`-c`). The device-lib path is where the SDK tree keeps `amdgcn/bitcode` (under `lib/llvm/` in a
|
||||
userspace SDK, `$ROCM/amdgcn/bitcode` in a core system install). The flags are not needed for a
|
||||
full `/opt/rocm` install, and `DOCKER.md`'s container sidesteps them.
|
||||
`--gcc-install-dir` is the distro gcc's directory (gcc 15 in the example). After a gcc upgrade,
|
||||
repoint it and reset the configure cached in `build/CMakeCache.txt` (`-c`). The device-lib path is
|
||||
where the SDK keeps `amdgcn/bitcode`: under `lib/llvm/` in a userspace SDK, `$ROCM/amdgcn/bitcode`
|
||||
in a core system install. A full `/opt/rocm` install needs none of these flags, and the container
|
||||
in `DOCKER.md` avoids them.
|
||||
|
||||
### 1.3 Check that it works
|
||||
|
||||
@@ -368,7 +368,7 @@ planes, with the tokeniser and chat template.
|
||||
|
||||
**A recipe decides what is quantised**, in rules from weight names to quantisers. Without one,
|
||||
every weight keeps the checkpoint's encoding, which suits a bf16 or block-fp8 checkpoint served at
|
||||
its own precision. Flash-Next's four-bit experts need one:
|
||||
its own precision (Qwen3.8-Flash-Next-FP8 included). Flash-Next's four-bit experts need one:
|
||||
|
||||
```sh
|
||||
rad-convert /srv/models/Qwen/Qwen3.8-Flash-Next -o /srv/models/rad/flashnext-w4.rad \
|
||||
@@ -835,6 +835,22 @@ for the gather (no libr4d) the table is read on the host: `vram` is refused, and
|
||||
locked huge pages, which also needs a memlock limit that large (`--ulimit memlock=-1` in Docker,
|
||||
`LimitMEMLOCK=infinity` under systemd).
|
||||
|
||||
`--ngram-placement ram=DIR` makes the pinned copy a file, `DIR/ngram-<id>.tab`, in a tmpfs, mapped
|
||||
`MAP_SHARED` and pinned for the cards as `ram` pins it, so two engines on separate card sets
|
||||
(`ROCR_VISIBLE_DEVICES`) hold one table in host memory. The first engine to start fills the file
|
||||
from the container; a second finds it complete, checks samples of it against its own container and
|
||||
only pins it. The `<id>` is a hash of the container's path, size and mtime and the table's place in
|
||||
it, so a file never serves another model. A weight under 32 MiB the gather reads beside the table
|
||||
(its scale) keeps a private pinned copy, since its file would be mostly header. The engine that
|
||||
leaves last deletes the file, and one that leaves while another still holds it waits up to a second
|
||||
for it, so two engines stopped together still remove it; after a crash a complete file stays and is
|
||||
reused, or removed by hand. `DIR` must be a tmpfs (`/dev/shm`, or a tmpfs mounted for it, sized for
|
||||
the table); `ram=DIR` needs the card gather kernel and the driver's SVM API, and is refused
|
||||
otherwise. The driver counts a shared page against every process that pins it, so with two engines
|
||||
the pinned total is twice the table: set `amdgpu.no_system_mem_limit=1` (the cap is RAM less 1/64
|
||||
and 1.5 GiB) or the second pin can be refused. The kernel charges the tmpfs pages to the memory
|
||||
cgroup of the engine that filled them.
|
||||
|
||||
**`--weights-disk-tier`** serves a model larger than the card and the host pool together, with every
|
||||
step paced by the drive. A routed expert that fits neither lives only in the container. Before each
|
||||
routed layer's first expert op, on every pass, the engine reads all that layer's on-disk experts into
|
||||
@@ -1193,30 +1209,32 @@ snapshot lets it skip at least 256 tokens of that head, the request takes one wh
|
||||
ends, at the cost of one chunk split, and the requests after it resume there. A conversation's
|
||||
next turn has only its own earlier turn past that point, so it splits nothing extra.
|
||||
|
||||
A prefix hit answers exactly as the same prompt prefilled cold, by default
|
||||
(`--prefix-resume exact`). A kernel can round a row differently at another chunk
|
||||
length (the fp8 GEMM's split-K count is chosen from `M`, spec §17), so a hit that
|
||||
recomputes its tail in other chunks than a cold prefill can flip a near-tie in
|
||||
greedy text. The hit therefore resumes only where an idle server's cold prefill of
|
||||
that prompt starts a chunk: every `--max-num-batched-tokens` tokens (rounded down
|
||||
to the chunk quantum), or every `--checkpoint-interval` when that is smaller. A
|
||||
prompt's tail snapshot is taken where its last chunk starts, a boundary the chunk
|
||||
already ends on, so it costs a copy and no step. An exact repeat re-prefills the
|
||||
cold run's last chunk; an appended turn, that chunk and what the turn added: up to
|
||||
one chunk more than `--prefix-resume nearest`, which resumes at the deepest
|
||||
snapshot or block and splits a prompt's last chunk at its last quantum boundary.
|
||||
The interval must be a multiple of the chunk when it is larger; otherwise it is
|
||||
rounded up, and startup says so:
|
||||
**Where a hit resumes** (`--prefix-resume`). A kernel can round a row differently at another
|
||||
chunk length (the fp8 GEMM's split-K count is chosen from `M`, spec §17), so a hit that recomputes
|
||||
its tail in other chunks than a cold prefill can flip a near-tie in greedy text. Two modes:
|
||||
|
||||
- `exact` (the default): a hit answers exactly as the same prompt prefilled cold. It resumes only
|
||||
where an idle server's cold prefill of that prompt starts a chunk: every
|
||||
`--max-num-batched-tokens` tokens (rounded down to the chunk quantum), or every
|
||||
`--checkpoint-interval` when that is smaller. A prompt's tail snapshot is taken where its last
|
||||
chunk starts, a boundary the chunk already ends on, so it costs a copy and no step. An exact
|
||||
repeat re-prefills the cold run's last chunk; an appended turn re-prefills that chunk and what
|
||||
the turn added.
|
||||
- `nearest`: a hit resumes at the deepest snapshot or block, and a prompt's tail snapshot is at
|
||||
its last quantum boundary. A turn re-prefills up to one chunk less than under `exact`.
|
||||
|
||||
Under `exact` an interval larger than the chunk must be a multiple of it; otherwise it is rounded
|
||||
up, and startup says so:
|
||||
|
||||
```
|
||||
--checkpoint-interval 6144 resolves to 8192: --prefix-resume exact needs it a multiple of the
|
||||
4096-token prefill chunk (--max-num-batched-tokens 4096) ...
|
||||
```
|
||||
|
||||
It is an idle-server property, as greedy batching is: a prefill that shares its
|
||||
steps with other requests or decode rows (`--busy-prefill-chunk`,
|
||||
`--prefill-interleave`) is cut differently, and a request's own checkpoint
|
||||
(`/v1/systemone`'s shared head) resumes where it was asked.
|
||||
Exactness holds on an idle server, as greedy batching does: a prefill that shares its steps with
|
||||
other requests or decode rows (`--busy-prefill-chunk`, `--prefill-interleave`) is cut
|
||||
differently, and a request's own checkpoint (`/v1/systemone`'s shared head) resumes where it was
|
||||
asked.
|
||||
|
||||
**One prefill sequence in two pieces.** At two ranks, on `qwen35_fp8` (and `qwen35_w8a8`, built
|
||||
from it, where its norms do not write rotated int8 codes) and on `gemma3`'s MXFP4 trunk with the
|
||||
@@ -1296,10 +1314,15 @@ head inside the target checkpoint, which needs no flag. `radiance --draft-model`
|
||||
says so. Measure speculation by step time, not tokens per second.
|
||||
|
||||
A drafter with a sliding window over its own cache (DFlash2) keeps that cache outside the prefix
|
||||
cache, so after a prefix hit it cannot draft until its window has slid past the hit, which on a
|
||||
chat's follow-up turn is most of the reply. Such a hit is therefore ended one drafter window before
|
||||
the end of the prompt, at a checkpoint, and the window is recomputed; the reply is the same. A hit
|
||||
whose nearest checkpoint below that point would give back more than two windows is kept whole.
|
||||
cache. Where a hit resumes from a window snapshot (a model whose sliding layers the cache does not
|
||||
index and that keeps no linear state, as the Gemma 4 31B under gemma4_bf16; the 26B-A4B declares
|
||||
its sliding layers full and takes no snapshot), the snapshot carries the drafter's window with the
|
||||
trunk's, so the hit leaves it whole and it drafts from the first decoded token. Elsewhere (a
|
||||
model with linear state, as Qwen3.8), after a prefix hit it could not draft until its window had
|
||||
slid past the hit, which on a chat's follow-up turn is most of the reply. Such a hit is therefore
|
||||
ended one drafter window before the end of the prompt, at a checkpoint, and the window is
|
||||
recomputed; the reply is the same. A hit whose nearest checkpoint below that point would give back
|
||||
more than two windows is kept whole. The startup line `draft floor` says which applies;
|
||||
`radiance:draft_refills_total` counts the hits ended early and `radiance:draft_refill_tokens_total`
|
||||
the tokens recomputed.
|
||||
|
||||
@@ -1332,14 +1355,31 @@ behind the packet processor's barrier bit, which saves most of the launch gap be
|
||||
kernels. The bytes are the same. Plain decode measured slower with them, so they stay off there
|
||||
and on every other model; the startup report's `chained launches` row says which and why.
|
||||
|
||||
**Draft trees.** Where the model's plugin measured a gain (the Gemma 4 31B with DFlash2: +7%
|
||||
single-stream decode and +6-9% aggregate at 1-16 users on 4x R9700, +4% and +6-12% on two,
|
||||
BetterBench with thinking off), a block drafter's proposals are verified as a tree: grown best-first
|
||||
over the drafter's candidates, the deepest path the target agrees with is accepted, and its K and V
|
||||
move into place. A tree changes no token, only how many drafts land a step; the startup report's
|
||||
`draft trees` row says when it is on. Under a tree `--num-speculative-tokens` counts the tree's
|
||||
nodes, grown over the block the drafter was trained at. A request with a grammar (`response_format`,
|
||||
tools) speculates on a tree too: each row is masked against the grammar after its own ancestors.
|
||||
`--draft-coupling on` samples one path, so a coupled drafter proposes the chain.
|
||||
|
||||
**A shorter block under load: `--draft-short-from N`.** A block drafter's block is paid for by
|
||||
every drafting sequence, whatever each one verifies. At one sequence a long block pays; at many, its
|
||||
drafter rows and its weaker first positions cost more than the extra drafts bring. A drafter that also
|
||||
serves a shorter block declares it (PLUGIN.md §11); DFlash2 declares a block of 4 (3 drafts) wherever its
|
||||
own is longer, on `qwen35_fp8` and `gemma3`. With `--draft-short-from N` the engine runs that short block
|
||||
once N sequences decoded in the step just run, and the drafter's own block again only once the count
|
||||
falls two below N, so a load wavering at N does not change the pass shape every step. `0`, the default,
|
||||
never switches. Startup names what it will run:
|
||||
own is longer, on `qwen35_fp8` and `gemma3`, and the Gemma 4 31B's block-16 DFlash2 drafter, as a tree of
|
||||
15 nodes, a block of 8 (a 7-node tree over it). With `--draft-short-from N` the engine runs that short block
|
||||
once N sequences decoded in the step just run, and the drafter's own block again once the count
|
||||
falls two below N or to one sequence, where the long block pays. From N of 3 on, a load wavering at
|
||||
N does not change the pass shape every step; at 2, a load between one and two sequences does, which
|
||||
costs only the other shape's pass. `0` never
|
||||
switches. `auto`, the default, never switches a chain and switches a tree drafter
|
||||
from 2: a tree's nodes are verify rows every drafting sequence pays for, which a wide tree's extra nodes
|
||||
repay at one sequence and not at many; it switches back at one decoding sequence. At the short block the
|
||||
drafter grows a tree of its own over the shorter pass, at most `block - 1` nodes. Startup names what it
|
||||
will run:
|
||||
|
||||
```
|
||||
speculation: from 16 decoding sequences on, 'dflash2' runs its short block of 4 row(s), 3 token(s)
|
||||
@@ -1572,6 +1612,17 @@ hit. Snapshots never take VRAM: each is copied to host memory after the step tha
|
||||
back before the step that resumes from it. `/sessions` shows what is stored, where, and whether the
|
||||
linear half is served.
|
||||
|
||||
On a model with sliding-window layers and no linear state (Gemma 3, and the Gemma 4 31B as gemma4_bf16
|
||||
declares it), the cache does not
|
||||
index the sliding layers, so a hit resumes only from a window snapshot, taken a block short of a
|
||||
prompt's end, where the next turn's rendering still agrees. Under `--prefix-resume nearest` one is
|
||||
taken at the end of every prompt of 528 tokens or more (with `--checkpoint-interval` under 512,
|
||||
from that interval plus a block). Under `exact` it is taken at the start of the prompt's last
|
||||
chunk, once that lies at least one checkpoint interval in, so a conversation whose prompts stay
|
||||
under one prefill chunk reuses nothing there; serve such a model with `--prefix-resume nearest`
|
||||
where short chats matter more than bit-identical hits. A shorter prompt is recomputed: its
|
||||
prefill is cheap, and its snapshot would take a slot from a longer conversation.
|
||||
|
||||
**How many snapshots.** The snapshot store (`--checkpoint-slots`) is shared by every conversation,
|
||||
running or not, and a conversation without a snapshot under its next prompt reuses nothing. With
|
||||
`auto`, the default, each of `--max-num-seqs` gets what `--checkpoint-policy` keeps for one
|
||||
@@ -1589,6 +1640,23 @@ none of it on the card; 10 a sequence for --max-num-seqs 8: geometric-backoff ke
|
||||
200000-token session at a 2048-token interval, and one more for a running turn
|
||||
```
|
||||
|
||||
**The floor outranks the reserve.** A store one snapshot short of its floor is not a smaller store:
|
||||
it is every prefix hit prefilling from the start. `--host-headroom-mib` is a courtesy to the system
|
||||
— the unpooled allocations, the load's staging, the page cache — and it may not, alone, decide the
|
||||
feature off. So when the floor does not fit with the reserve held free, the reserve gives back
|
||||
exactly the shortfall, never below 1 GiB and never above the margin asked for, and the startup line
|
||||
says how much it gave:
|
||||
|
||||
```
|
||||
checkpoint slots: auto: 8 linear-state snapshot(s) of 112.73 MiB ... ; 16 wanted, held to what the
|
||||
host can pin: ... ; the host reserve gave back 835.00 MiB of its 4.00 GiB for the floor of 8
|
||||
snapshot(s), holding 3.19 GiB
|
||||
```
|
||||
|
||||
It is a byte rule over the host's own measurement, so it needs no second case for a wider slot (a
|
||||
model with more linear state), a wider streaming mirror (any KV encoding), or a larger `--tp`: a
|
||||
host that can pin the floor gets it, and one that cannot says what it is short.
|
||||
|
||||
A line that says `held to an eighth of host memory`, or (a warning) `held to what the host can
|
||||
pin`, means the store is smaller than the policy wants; `--checkpoint-slots N` sets the count
|
||||
outright. An agent client with subagents keeps more
|
||||
@@ -1939,7 +2007,7 @@ by 0.002-0.003 nats.
|
||||
| `--attn-prefill-fp8 MODE` | off | `off`, `qk`, `pv` or `both`: the prefill attention's Q·Kᵀ, P·V or both in E4M3 over an `fp8`, `fp8_v4` or `k6_v4` cache; lossy, Qwen3.8-27B (§4.4) |
|
||||
| `--host-pool-mib N` | 0 | pinned host tier (weights) |
|
||||
| `--kv-resident N` | 0 (off) | stream the sparse attention group's KV from pinned host memory, keeping a ring of N tokens on the card. Raised to 32 768 and to one decode step's selection; a ring that covers the context streams nothing. Ignored with a warning on an architecture that cannot stream (§4.4.1, [KV-STREAMING.md](KV-STREAMING.md)) |
|
||||
| `--host-headroom-mib N` | 4096 | host RAM left free for the system when startup pins host memory — kept for the unpooled allocations, staging and page cache (§4.3) |
|
||||
| `--host-headroom-mib N` | 4096 | host RAM left free for the system when startup pins host memory — kept for the unpooled allocations, staging and page cache (§4.3). A snapshot store's floor takes back the shortfall from it, down to 1 GiB, rather than come up with none (`--checkpoint-slots`, §4.8) |
|
||||
| `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card (§4.3) |
|
||||
| `--ngram-placement WHERE` | auto | `auto`, `vram`, `ram` or `disk`: an n-gram table on the card, as a copy in RAM made at load and read by the card, or read from the container (§4.3) |
|
||||
| `--vision-tower-placement WHERE` | vram | `vram` or `ram`: the encoder towers (vision, and audio where a model has one) on the card, or pinned in host memory beside `--host-pool-mib` and read in place once an image (§4.3) |
|
||||
@@ -1970,7 +2038,7 @@ by 0.002-0.003 nats.
|
||||
| `--deterministic` | off | pin placement to the loader's plan, so the resident set cannot change under the heat engine |
|
||||
| `--checkpoint-interval N` | 2048 | linear-attention state checkpoint interval, in tokens |
|
||||
| `--prefill-span N` | 1 | checkpoint intervals one step may carry of a prefill alone in its step, from the prompt's second interval on; needs `--max-num-batched-tokens` of N intervals. Every other step is planned at the budget less the extra intervals, and the checkpoints inside a span are not written (§4.5) |
|
||||
| `--checkpoint-slots N` | auto | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`, 144 MiB on Qwen3.8-27B; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`). `auto` gives each of `--max-num-seqs` what `--checkpoint-policy` keeps for a `--max-model-len` session plus one (10 at 200K tokens under geometric backoff), within an eighth of host memory and what the host can pin; the startup line and the report say what it chose and why (§4.8). A full store retires its least recently used snapshot. A count is taken as given: a store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start |
|
||||
| `--checkpoint-slots N` | auto | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`, 144 MiB on Qwen3.8-27B; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB, and with its DFlash2 drafter that drafter's 2048-token window too, 487 MiB). `auto` gives each of `--max-num-seqs` what `--checkpoint-policy` keeps for a `--max-model-len` session plus one (10 at 200K tokens under geometric backoff), within an eighth of host memory and what the host can pin; a floor of 8 (or what the policy wants, if fewer) outranks `--host-headroom-mib`, which gives back exactly the shortfall down to 1 GiB rather than take the store to none, and the startup line says so. The startup line and the report say what it chose and why (§4.8). A full store retires its least recently used snapshot. A count is taken as given: a store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start |
|
||||
| `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` |
|
||||
| `--prefix-resume MODE` | exact | `exact`: a prefix hit resumes only where an idle server's cold prefill of the prompt starts a chunk, and a prompt's tail snapshot is taken where its last chunk starts, so a hit answers bit-identically to a cold run; an interval past the chunk is rounded up to a multiple of it. `nearest`: the deepest snapshot or block, up to a chunk less re-prefilled a turn |
|
||||
| `--no-prefix-cache` | prefix cache on | disable prefix caching |
|
||||
@@ -1992,8 +2060,8 @@ by 0.002-0.003 nats.
|
||||
|---|---|---|
|
||||
| `--num-speculative-tokens N` | auto | speculative window; 0 disables. The ceiling under `--draft-window adaptive` |
|
||||
| `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, serial draft heads only (§4.6) |
|
||||
| `--draft-short-from N` | 0 | a block drafter that declares a shorter block runs it from N decoding sequences on, its own block again two below; 0 never (§4.6) |
|
||||
| `--draft-coupling MODE` | off | `on`: a linear MTP drafter with a 2-bit candidate head (Qwen3.8-Flash-Next) samples each proposal from its reranked top-8 and the sampler maximally couples the target's draw to it. The output distribution is unchanged and a fixed seed yields other tokens than `off`. The head's law is taken at temperature 1, so it pays at high request temperatures and costs at low ones: on Flash-Next TP2 at 2x R9700, tokens per decode step +18% at temperature 1.0 and c1, +11% at 0.7 and c4, -4% at 0.3. Greedy rows are unchanged. A DFlash2 drafter (Qwen3.5/3.8) couples its candidate walk instead: each position is sampled from the softmax of the walk's own scores over its best eight candidates, at temperature `RADIANCE_DFLASH_Q_TEMP` (default 0.6, where acceptance peaked); on Qwen3.8-27B MXFP4 TP2 at 2x R9700 and request temperature 1, tokens per verify step +8% on held-out prompts at c4 (3.53 to 3.82) and decode +2..8% per stream at c1/c4. Any other drafter is refused at startup |
|
||||
| `--draft-short-from N` | auto | a block drafter that declares a shorter block runs it from N decoding sequences on, its own block again two below or at one sequence; 0 never; auto never for a chain and 2 for a tree drafter, which then verifies the short block's nodes (§4.6) |
|
||||
| `--draft-coupling MODE` | off | `on`: a linear MTP drafter with a 2-bit candidate head (Qwen3.8-Flash-Next) samples each proposal from its reranked top-8 and the sampler maximally couples the target's draw to it. The output distribution is unchanged and a fixed seed yields other tokens than `off`. The head's law is taken at temperature 1, so it pays at high request temperatures and costs at low ones: on Flash-Next TP2 at 2x R9700, tokens per decode step +18% at temperature 1.0 and c1, +11% at 0.7 and c4, -4% at 0.3. Greedy rows are unchanged. A DFlash2 drafter (Qwen3.5/3.8) couples its candidate walk instead: each position is sampled from the softmax of the walk's own scores over its best eight candidates, at temperature 0.6 (where acceptance peaked); on Qwen3.8-27B MXFP4 TP2 at 2x R9700 and request temperature 1, tokens per verify step +8% on held-out prompts at c4 (3.53 to 3.82) and decode +2..8% per stream at c1/c4. Any other drafter is refused at startup |
|
||||
| `--draft-model PATH` | | not implemented: merge the drafter at convert time |
|
||||
|
||||
**Server**
|
||||
@@ -2002,7 +2070,7 @@ by 0.002-0.003 nats.
|
||||
|---|---|---|
|
||||
| `--host ADDR` | 0.0.0.0 | listen address |
|
||||
| `--port N` | 8000 | listen port |
|
||||
| `--api-key KEY` | none | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6) |
|
||||
| `--api-key KEY` | none | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6); the key must be non-empty |
|
||||
| `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the loaded one serves it |
|
||||
| `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels, 14x14 on GLM-5.3). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card. A pass is not one tower invocation: inside it the tower batches at most 8 tiles per weight read, and the pass size may reduce that (4 tiles at the 64-pixel grid with the default 16384 patches); a picture contributes a separate pass per grid. See the concurrency notes for Unlimited-OCR (§5.17) |
|
||||
| `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the container's. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup |
|
||||
@@ -2287,12 +2355,11 @@ returns the text as both `prompt` (vLLM) and `content` (llama-server).
|
||||
completions and chat answer 501. One input is one vector and must fit one step
|
||||
(`--max-num-batched-tokens`); a longer one is refused with `context_length_exceeded`.
|
||||
|
||||
nomic-embed-text-v2-moe is converted from its f32 checkpoint with `rad-convert <checkpoint dir>
|
||||
nomic-embed-text-v2-moe converts from its f32 checkpoint with `rad-convert <checkpoint dir>
|
||||
--recipe data/recipes/nomic-embed-v2-moe-bf16.recipe -o nomic-embed-v2-moe-bf16.rad` (959 MB);
|
||||
the directory must contain `tokenizer.json`. The `search_query: ` and `search_document: ` prefixes
|
||||
are the client's text and the engine adds neither; the checkpoint's prompt names work through
|
||||
`prompt_name`. The checkpoint's shared `experts.bias` tensors are not applied and stay in the
|
||||
checkpoint.
|
||||
the directory must contain `tokenizer.json`. The engine adds neither the `search_query: ` nor the
|
||||
`search_document: ` prefix: the client sends it, or names the checkpoint's prompt with
|
||||
`prompt_name`. The checkpoint's shared `experts.bias` tensors are not applied.
|
||||
|
||||
```sh
|
||||
# text, a batch of texts, or token ids
|
||||
@@ -3603,11 +3670,16 @@ With a key, every request must carry `Authorization: Bearer KEY` (or Anthropic's
|
||||
or it is answered 401, `/tokenize` and `/server_info` included. Exempt are `/health`, `/v1/health` and
|
||||
`/ping`, because load balancers cannot send a bearer token, and the dashboard page (`/`,
|
||||
`/dashboard`), which holds no data: on a 401 it asks for the key, keeps it in the browser's storage
|
||||
and sends it on every data fetch.
|
||||
and sends it on every data fetch. The exemption follows those paths' methods -- reads, plus the
|
||||
`POST /ping` of the health-check convention -- so it cannot follow a method no route answers.
|
||||
An empty `--api-key` value is a startup error: it would guard nothing.
|
||||
|
||||
Without a key, `/diagnostics` answers only loopback clients (others get 403), because it describes
|
||||
the host: kernel, boot parameters, PCI layout, memory limits. Read it on the machine, or start the
|
||||
server with `--api-key`.
|
||||
server with `--api-key`. The same loopback-only rule covers the control-vector default and runtime
|
||||
LoRA loads, and a browser page on another origin does not qualify as a loopback client even when
|
||||
its own machine serves the port: that is how a hostile web page would reach these routes through a
|
||||
victim's browser, and a request that says `Origin: http://evil` is refused the way a remote one is.
|
||||
|
||||
The key is not encrypted in transit. On a network you do not control, bind to localhost behind a
|
||||
TLS-terminating reverse proxy:
|
||||
@@ -3651,7 +3723,7 @@ is the part of a log to paste into an issue. Its sections:
|
||||
warning is also printed as a `W` line of its own.
|
||||
|
||||
```
|
||||
I STARTUP REPORT -- radiance 1.13.0
|
||||
I STARTUP REPORT -- radiance 1.14.0
|
||||
I CONFIGURATION -- every option, the value in force, and where it came from
|
||||
I --model /models/flashnext.rad [command line]
|
||||
I --tp 2 [command line]
|
||||
|
||||
+35
-2
@@ -190,6 +190,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`, `w`w? → `y` (no gain operand: a gain of one) |
|
||||
| `rmsnorm_rows` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`, `w`w? → `y` (the same norm; at n <= 256 with 1024+ rows a wave a row, byte-identical) |
|
||||
| `rmsnorm_p` | `M`(range) `n` `eps`:f64 `dtype` | `x` → `y` |
|
||||
| `rmsnorm_add` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`, `w`w → `y`, `residual_out` |
|
||||
| `hc_enter` | `M`(range) `n` `hc` `dtype` | `x` → `h` |
|
||||
@@ -472,7 +473,25 @@ at h128/gqa8 up to q_len 16 by reading each kv head for two query groups of 4 (a
|
||||
then holds each kv head once). Since no host library declares the op, a plugin that asks for it
|
||||
learns whether a card serves the geometry.
|
||||
|
||||
libref has no row for any of them, deliberately. An architecture asks for a fusion and declares
|
||||
Tree verification (`rad_drafter_tree`, abi/rad_builder.h) adds one operand to both: the step's
|
||||
`RadBatch::spec_parent`, `[rows]` i32.
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `attn_paged_tree` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `prefill_fp8`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `spec_parent` |
|
||||
| `attn_paged_qrow_tree` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt `prefill_fp8`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out`; `spec_parent` |
|
||||
|
||||
A row whose `spec_parent` is -2 is an ordinary causal row. Any other row is a node of its sequence's
|
||||
verify block, and its entry names its parent by row within the sequence's rows (`cu_seqlens`), -1
|
||||
for the block's first row, every parent before its child. Inside the block (keys from
|
||||
`seqused - q_len` on) such a row sees itself and its ancestors only; before it, every key as an
|
||||
ordinary row does, except that a window is measured from the block's first position plus the row's
|
||||
depth, the position its token takes once its path is committed. Causal layers only. libref serves
|
||||
`attn_paged_tree`; libr4d `attn_paged_qrow_tree` at h256/gqa2 on the split-KV decode kernel and at
|
||||
every geometry of the windowed kernels, to 64 rows a block.
|
||||
|
||||
Of the ops above, libref serves only `attn_paged_tree`, which is not a fusion but `attn_paged`'s
|
||||
tree form. It has no row for any of the fusions, deliberately. An architecture asks for a fusion and declares
|
||||
the chain where it does not resolve (`rad_op_resolved`); a reference row would make it resolve
|
||||
everywhere, so a model loaded without the serving library would resolve to the reference and be
|
||||
refused at serve, instead of running the chain on libr4d or libavx. libr4d declares them with
|
||||
@@ -607,6 +626,7 @@ and is optional.
|
||||
| `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? |
|
||||
| `swiglu_clamped_quant_fp8` | `M`(range) `n` `limit`:f64 `group` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? |
|
||||
| `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? |
|
||||
| `gemm_nt_q_gated_wide` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? (the same fold at every M: the narrow tile to 64 rows, past them the gated prefill tile) |
|
||||
| `gemm_nt_q_gated_mx` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w, `b_ref`w → `q`, `scale`, `out_bf16`? |
|
||||
|
||||
`quant_cols_fp8` is the same E4M3 quantiser with one scale per column over all `M` rows,
|
||||
@@ -720,6 +740,7 @@ may not have arrived.
|
||||
| `gemm_nt_f32` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` |
|
||||
| `gemm_nt_bias` | `M`(range) `N` `K` `dtype` `act`/opt | `a`, `b`w, `bias`w, `res`? → `y` |
|
||||
| `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt `split_n`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? |
|
||||
| `gemm_nt_q_short` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt `split_n`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? (the narrow fp8 row with the short-prompt split rule: N <= 512, K <= 5120 and 41..64 rows run unsplit) |
|
||||
| `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` |
|
||||
|
||||
`nt` is A row-major `[M,K]` times B transposed `[N,K]`, giving `[M,N]`: the layout every weight in
|
||||
@@ -883,6 +904,7 @@ as the weight's GEMM stored them and claims no form. It changes no value.
|
||||
| `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout |
|
||||
| `kv_store_streamed` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout, `res`, `host`:inout |
|
||||
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` |
|
||||
| `rope_rows` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` (the same rotation; at 64+ rows and 4+ heads one angle a (token, pair), byte-identical) |
|
||||
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` |
|
||||
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? |
|
||||
| `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `v_norm`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w |
|
||||
@@ -2736,7 +2758,7 @@ greedy request's row (draw mode 0) keeps `dflash_select`'s tokens (`status = 0`)
|
||||
another card, or a position whose eight cannot form a `Q`, takes the walk's argmax (`status = -1`)
|
||||
and the ordinary verify. `Q_l` depends on the committed text and on `x_0 .. x_{l-1}`, never on the
|
||||
verify, and is stored exactly, which is all the coupling needs to be lossless; `q_temp` (the
|
||||
architecture's, `RADIANCE_DFLASH_Q_TEMP` on Qwen3.5/3.8) moves acceptance only. Each edge is eight
|
||||
architecture's, 0.6 on Qwen3.5/3.8) moves acceptance only. Each edge is eight
|
||||
partial `fmaf` chains over contiguous slices of the rank, added in order, so the device kernel and
|
||||
the host oracle agree bit for bit.
|
||||
|
||||
@@ -3202,6 +3224,17 @@ candidates, and what enters the head from the trunk.
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `dflash_select` | `M` `steps` `top_k` `rank` `n_vocab` `anchor_stride`/opt `dtype` | `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w → `tokens` |
|
||||
| `dflash_tree` | `M` `steps` `top_k` `rank` `n_vocab` `anchor_stride`/opt `nodes` `temp`:f64/opt `dtype` | `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w → `tokens`, `parents` |
|
||||
|
||||
`dflash_tree` grows the same lattice into a tree of `nodes` nodes instead of walking one path
|
||||
(`rad_drafter_tree`). Node 0 is the anchor at lattice position -1 with log probability 0. A node at
|
||||
position l with token t has a child for every candidate c at l + 1 whose id is in the vocabulary,
|
||||
scored as `dflash_select` scores c after t; with x = score / `temp` (default 1) over those
|
||||
candidates, the child's log probability is its parent's plus x - logsumexp(x). Best-first: each
|
||||
round takes the not-yet-taken child of a taken node with the largest log probability, ties to the
|
||||
one pushed first (lower parent, then lower c), until `nodes` are taken. Taken node j (1-based, so
|
||||
every parent comes before its child) is `tokens[s, j-1]`, and `parents[s, j-1]` its parent's node
|
||||
index, 0 for the anchor. A frontier that runs dry pads with token 0 under the last node.
|
||||
|
||||
`dflash_conv` is the drafter's grouped convolution (coefficient add and every tap in one pass):
|
||||
|
||||
|
||||
+4
-3
@@ -388,9 +388,10 @@ says so with `RAD_ARCH_SERVES_IMPORTS(0)` (`qwen35_w8a8` does), and imports keep
|
||||
- **A block drafter may serve a shorter block.** `rad_drafter_short_block(b, block)`, called once
|
||||
after `rad_declare_drafter`, says the plugin declared its query pass at `block` rows a sequence as
|
||||
well as at `RadDrafterDecl::block`, with the same anchor convention, so the core may stage a step
|
||||
at either; the short block proposes `block - (RadDrafterDecl::block - depth)` tokens. The builder
|
||||
refuses it without a block drafter, at or above the drafter's own block, and where it would
|
||||
propose nothing. The engine runs it under `--draft-short-from` (GUIDE §4.6) and reads row `s` of
|
||||
at either; the short block proposes `block - (RadDrafterDecl::block - depth)` tokens. A tree
|
||||
drafter (`rad_drafter_tree`, called first) grows a tree of its own over the shorter pass, at most
|
||||
`block - 1` nodes, and its short block needs only 2 rows. The builder refuses it without a block
|
||||
drafter, at or above the drafter's own block, and where it would propose nothing. The engine runs it under `--draft-short-from` (GUIDE §4.6) and reads row `s` of
|
||||
the proposals at `s * proposal_pitch`; a block drafter's `proposal_pitch` defaults to its
|
||||
depth (a row holds the whole block's proposals and a short block fills its front) and is refused
|
||||
below it. The pass's block is `n_tok / n_seq`; a block the plugin has no ops for should fail the
|
||||
|
||||
+5
-4
@@ -191,10 +191,11 @@ drops blocks.
|
||||
## Checking
|
||||
|
||||
There is deliberately no switch that forces dense attention above the bound, where it is not the
|
||||
model the checkpoint was trained as. libref implements all five QSA ops — `ref_qsa_block_key`,
|
||||
`ref_qsa_score`, `ref_qsa_select`, `ref_qsa_tail_store`, `ref_qsa_work` (`libref/ref_qsa.cpp`) — so
|
||||
each device kernel has a row to compare against; what no oracle gives is the whole-subsystem
|
||||
comparison, a dense run against a sparse one above the bound. Changes are checked with:
|
||||
model the checkpoint was trained as. libref implements all five QSA ops (`ref_qsa_block_key` in
|
||||
`libref/ref_attn.cpp`; `ref_qsa_score`, `ref_qsa_select`, `ref_qsa_tail_store` and `ref_qsa_work`
|
||||
in `libref/ref_qsa.cpp`), so each device kernel has a row to compare against. No oracle gives the
|
||||
whole-subsystem comparison, a dense run against a sparse one above the bound. Changes are checked
|
||||
with:
|
||||
|
||||
- **`r4d_selftest` oracles**: `qsa_block_key` and `qsa_score` against f64 evaluations,
|
||||
`qsa_work` and `qsa_tail_store` against a host walk of the batch, `qsa_select` against a host
|
||||
|
||||
@@ -974,3 +974,12 @@ scripts/mctools.sh && scripts/mcstream.sh
|
||||
`tools/kbench-analysis.sh` produces the static- and dynamic-analysis fragment that
|
||||
`rad-kbench --analysis` splices into its report. `tools/ops_doc_check.sh` is the `ops_doc` test: it
|
||||
checks `docs/OPS.md` against the schemas the plugins declare.
|
||||
|
||||
`rad-chatparse` (built into the build's `bin/`) answers where a tool call goes wrong without loading
|
||||
weights. `rad-chatparse --request REQ.json --rad MODEL.rad --reply R.txt` renders one OpenAI chat
|
||||
request as the server would (the container's template or `--override-chat-template`,
|
||||
`--chat-template-kwargs`, the plugin's declared reply format, or the template's own with
|
||||
`--no-plugin`), then reads each reply file as the model's output: parsed whole, parsed through the
|
||||
SSE stream as a client reassembles it, and run through the request's tool-call grammar. It prints one
|
||||
JSON object; the exit status is 1 when the two parses disagree or the grammar refuses a token.
|
||||
`--render-raw T.jinja --context CTX.json` renders a template with any context.
|
||||
+7
-8
@@ -9,14 +9,13 @@ All numbers: paired within-session windows, bar ≥0.5% + sign test, geometry
|
||||
`--prefill-span 2 --tp-wire wht6 --placement all_vram` iq4r MoE unless stated.
|
||||
Every "dead" row is a *measured* dead — the mechanism, not a guess.
|
||||
|
||||
Shorthand used in the table and the prose (glossed once, used everywhere):
|
||||
`pp` prefill; `c1/c2/c8/c16` concurrency (live streams) 1/2/8/16; `M` rows in a collective
|
||||
(batch tokens at a step, rows in a MoE launch); `I` `--checkpoint-interval`; `T` tokens
|
||||
(`T<=25` at most 25 tokens); `ti8` the int8 peer wire (`--tp-wire wht6`'s coding); `FK` the
|
||||
MoE fast band; `W4` the 4-bit weight format; `iq4r` the shipped MoE quantisation; `hc_write`
|
||||
the fused all-reduce + residual-write row; `pp64K` a 64 K-token prefill; `QSA` the sparse
|
||||
indexer (docs/QSA.md); `L0..L3` kill levels, defined under *Kill levels*; `W#`/`R#` the
|
||||
experiment rows of this table.
|
||||
Shorthand: `pp` prefill; `c1/c2/c8/c16` concurrency (live streams) 1/2/8/16; `M` rows in a
|
||||
collective (batch tokens at a step, rows in a MoE launch); `I` `--checkpoint-interval`; `T` tokens
|
||||
(`T<=25` at most 25 tokens); `ti8` the int8 peer wire (`--tp-wire wht6`'s coding); `FK` the MoE fast
|
||||
band; `W4` the 4-bit weight format; `iq4r` the shipped MoE quantisation; `hc_write` the fused
|
||||
all-reduce + residual-write row; `pp64K` a 64 K-token prefill; `QSA` the sparse indexer
|
||||
(docs/QSA.md); `L0..L3` kill levels, defined under *Kill levels*; `W#`/`R#` the experiment rows of
|
||||
this table.
|
||||
|
||||
## The table
|
||||
|
||||
|
||||
@@ -1,270 +0,0 @@
|
||||
# HYV3 W4 decode optimizations
|
||||
|
||||
These changes optimize the existing HYV3 path and shared asymmetric W4/W5 and signed-I4 expert
|
||||
kernels. They do not change the canonical `.rad` weight encodings, precision, default split-K
|
||||
selection, or speculative decoding settings.
|
||||
|
||||
## Scope and affected paths
|
||||
|
||||
| Change | Affected paths | What remains to measure |
|
||||
| --- | --- | --- |
|
||||
| Compact one-row W4/W5 epilogue | Callers of the asymmetric W4/W5 GEMM at one live row and a compatible tile; includes Gemma callers | Fresh whole-model W4/W5 comparisons outside HYV3 |
|
||||
| BF16-to-F16 narrowing inside W4 GEMM | Non-rotated group-128 asymmetric W4 `LinearFP8` decode through 64 rows | Other models using this path; Gemma's separate a4 graph still keeps its cast |
|
||||
| Fragment-tiled expert I4 and one-row register loads | Per-128-scale signed-I4 experts, including plain and Hadamard-rotated formats | Other models/recipes that actually use this encoding, plus prefill and TP regressions |
|
||||
| Fused Q/K prologue and residual/shared-combine folding | HYV3's graph; TP2 keeps separate routed/shared reductions | Fresh TP2 whole-model A/B; other models affected by shared-kernel changes |
|
||||
|
||||
Subgroup-scaled codebooks retain their row-major packing. In particular, the served Flash-Next
|
||||
W5DN64 recipe is not evidence for the per-128 I4 kernel: its routed experts use a different
|
||||
subgroup-scaled path. No speedup is claimed for it or for any unmeasured model.
|
||||
|
||||
## Historical HYV3 measurements
|
||||
|
||||
These are earlier measurements of the original optimization branch, **not a benchmark of this
|
||||
rebased PR**. They establish motivation only.
|
||||
|
||||
- One Radeon AI PRO R9700 (`gfx1201`), TP1, full-GPTQ W4 HYV3.
|
||||
- BF16 KV, 65,536 maximum context, one sequence, 4,096 batched tokens, no drafter or launch cache.
|
||||
- Matched 10,030-token prompt and 2,000 generated tokens, temperature zero; reported decode
|
||||
medians are from three repetitions.
|
||||
- The frozen request SHA-256 is
|
||||
`e04af05fd7952b5c1e8a38927bb53ab8621ca3e90a2713285eb98122c849ed47`.
|
||||
The first repetition was uncached; later repetitions reused a 16-token prefix.
|
||||
- The frozen prompt repeatedly requests the word `alpha`, and the generated answer repeats it.
|
||||
This is a narrow synthetic workload, not representative prose, code or tool-use throughput.
|
||||
|
||||
| Historical stage | Median decode tokens/s |
|
||||
| --- | ---: |
|
||||
| Initial model path | 90.290 |
|
||||
| Fresh pre-packing control after earlier graph work | 95.392 |
|
||||
| Coalesced per-128 I4 expert packing | 103.364 |
|
||||
| Rebuilt cast-free graph | 111.922 |
|
||||
| Final untuned optimization stack | 115.678 |
|
||||
|
||||
The frozen answer SHA-256 was
|
||||
`caca914b1bced70b2f9d8bf32d476179f18cef456201b02f55f16b9863bedbf0` in every repetition.
|
||||
That establishes parity for this answer, not numerical or semantic equivalence on arbitrary input. An intermediate 104.744 tokens/s
|
||||
cast-fusion result used a stale architecture plugin and must not be used to quantify removal of
|
||||
graph casts. A separate launch-cache experiment near 120.5 tokens/s changed reduction order and
|
||||
is not part of this patch.
|
||||
|
||||
The earlier native-tool comparison was unmatched: the untuned stack scored 102/113 exact and
|
||||
112/113 executable cases versus 105/113 and 113/113 in an older baseline. The matched release-tag
|
||||
A/B below supersedes it for this PR validation: both arms scored 102/113 and 112/113, with identical
|
||||
per-case results. This remains a small curated subset, not a broad quality test.
|
||||
|
||||
## Validation on the rebased optimization branch
|
||||
|
||||
The full-suite GPU, layout and reference results below were recorded with the candidate based on
|
||||
merged main `2d2f638`. The PR was later rebased onto `d650eca` and then onto current `origin/main`
|
||||
`96bc046`. The full unit, GPU and inference suites have not been rerun on that latest base. Its
|
||||
`radiance` target remains blocked by the missing KV-stream headers noted below; focused validation
|
||||
of the latest source is recorded separately here.
|
||||
|
||||
### Code-review follow-up on current main
|
||||
|
||||
The review found that removing the explicit BF16-to-F16 graph cast changed CPU/reference results for
|
||||
BF16 values in F16's subnormal range. The host backends now explicitly narrow BF16 activations to
|
||||
F16 before W4/W5 asymmetric GEMM, preserving the old cast semantics. This does not change the HIP
|
||||
kernel path.
|
||||
|
||||
On the latest rebased source (`origin/main` `96bc046` plus this PR):
|
||||
|
||||
- Built the updated `libref`, `libavx`, and `rad-avx-check` host plugins, plus the complete `gfx1201`
|
||||
`libr4d` HIP plugin and `r4d_selftest`. The full Radiance engine build is still blocked by the
|
||||
missing upstream KV-stream headers.
|
||||
- The new direct `libref` regression test passed 7 checks: BF16-subnormal W4 output matched the
|
||||
explicit-F16 input byte-for-byte and produced BF16 `0x3900`.
|
||||
- `rad-avx-check --op gemm_nt_q` passed 26 generated geometries and 46 hand-built cases at scalar,
|
||||
AVX and AVX2 levels, with four-thread reruns byte-identical. This CPU exposes AVX2 but not AVX-512.
|
||||
- Stored-layout parity passed 1,145 checks over 20 cases.
|
||||
- On the authorized GPU, focused W4 checks passed 341/341, including finite and raw-bit BF16-to-F16
|
||||
cast parity. The signed-I4/MoE `moe_gemm_w4a8` test had 647 passes, zero failures and 12 expected
|
||||
skips for unsupported aligned prefill tiles above the 512-expert run-map limit (the harness exits
|
||||
2 when skips occur).
|
||||
- A short post-fix HYV3 full-GPTQ W4 compatibility smoke on the existing release-plus-PR deployment
|
||||
build returned `42`; it was stopped afterward, the temporary port was free, and no serving route
|
||||
was changed. That build does not include the updated CPU plugins, so this smoke is not evidence
|
||||
for the CPU fix or a current-main A/B.
|
||||
|
||||
### Non-target model dispatch checks (Flash-Next and Qwen3.8-27B)
|
||||
|
||||
These graph-only checks used the local artifacts and the ABI-compatible release-plus-PR engine; the
|
||||
engine exits after `declare`, before placing or loading model weights. The latest-source engine still
|
||||
cannot be built because of the unrelated KV-stream integration gap.
|
||||
|
||||
- **Qwen3.8-Flash-Next IQ4R (QFN):** the graph declared 2,054 ops and contained 98
|
||||
`moe_gemm_q` bands at `w4nl64a8h`; all resolved to the existing `libr4d` row
|
||||
`moe_gemm_w4a8`. This shared row is selected for QFN, so its decode geometry was benchmarked below.
|
||||
The new `moe_w4_rows_kernel` is not selected: QFN's W4NL64 format maps to `moe_gemm_launch<2>`,
|
||||
while its dispatch is guarded by `if constexpr (W4 == 1)`. For W4NL64, the modified loader wrapper
|
||||
takes its `W4 != 1` branch and calls the previous `w4_load_w` implementation.
|
||||
- **Qwen3.8-27B MXFP4:** the graph declared 1,821 ops, with 329 MXFP4 `gemm_nt_q` bands (plus one
|
||||
W2A8 band); it selected existing `gemm_mxfp4a8_*` rows. It had no `moe_gemm_q`, asymmetric W4 or
|
||||
W5 bands. The PR's new expert-I4/W4/W5 paths are therefore not selected for this model; its
|
||||
MXFP4 rows are unchanged.
|
||||
No benchmark was needed for an untouched path.
|
||||
|
||||
For QFN's shared W4NL64 row, `r4d_selftest --perfmoe 1 12 512 10 23 --cold 256` was run three
|
||||
times per arm on the same `gfx1201` device. It uses QFN's TP2 rank-0 gate/up and down widths, one
|
||||
decode token, 512 experts, top-10 routing, and 23% pooled experts. Baseline is `origin/main`
|
||||
`96bc046`; candidate is that base plus this PR. The decode-selected forms had matching output
|
||||
hashes and no measurable regression:
|
||||
|
||||
| QFN W4NL64 decode projection | Baseline median | PR median | Change |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Gate/up, two-K-block decode form | 23.60 us | 23.50 us | -0.4% |
|
||||
| Sorted down decode form | 17.10 us | 17.00 us | -0.6% |
|
||||
|
||||
This is an op-level microbenchmark with synthetic weights at the exact QFN geometry, not a
|
||||
whole-model QFN performance or quality A/B. Logs: `/tmp/pr237-qfn-debug-graph.log`,
|
||||
`/tmp/pr237-qfn-moebench-{candidate,baseline}-cold{1,2,3}.log`, and
|
||||
`/tmp/pr237-qwen27-debug-graph.log`.
|
||||
|
||||
- Release and ASan/UBSan/leak architecture suites, including HYV3 TP1/TP2 graph checks: passed
|
||||
before the base advance.
|
||||
- `gfx1201` `libr4d`, `r4d_selftest`, and all three HYV3 plugins: compiled.
|
||||
- Stored-layout parity: 1,145 checks over 20 cases passed, including independent canonical nibble
|
||||
addresses, GPTQ and rotated experts, subgroup codebooks and unaffected dense formats.
|
||||
- Reference arithmetic: 136,622 checks over 254 cases passed with the incomplete upstream
|
||||
inventory/sweep cases excluded. The new exhaustive BF16-add/cast-chain case passed separately.
|
||||
The unfiltered reference suite's three failed assertions were reproduced with unchanged upstream
|
||||
test source: an operation-count mismatch and missing sweep geometry for `kv_store_streamed` and
|
||||
`kv_resolve`.
|
||||
- Full rebased GPU selftest on the designated last R9700 (`gfx1201`, UUID
|
||||
`GPU-7f082536d27449f3`): 9,057 `ok` results, 194 skips, and two failing assertions in one
|
||||
`hc_read_e4m3` test case at M=2048; overall exit 1. The same untouched HC-read test family
|
||||
failed with the pre-follow-up baseline plugin at M=2048 and M=700 (the particular stream/form
|
||||
varied). The PR does not change that kernel or test. This is not a clean full-suite pass.
|
||||
- Focused GPU checks passed for `gemm_w4a16_asym_nt_m64`, `moe_gather_bf16`,
|
||||
`qkv_norm_rope_kv_store_h128_bf16` (including byte parity to the split norm/RoPE/store chain),
|
||||
and `rmsnorm_bf16`. The signed-I4 `moe_gemm_w4a8` case had no failures; its exit status was the
|
||||
harness's intentional-skip status for unsupported large-expert aligned tiles. The full run also
|
||||
exercised its HYV3 top-8 gate/up and down cases without failures.
|
||||
|
||||
The latest-source `radiance` target build stops at `ctx.cpp:6`, `kvbind.cpp:4`, `issue.cpp:22`,
|
||||
and `tierexec.cpp:4`: the runtime includes `kvstream/bind.h`, `kvstream/stage.h` and
|
||||
`kvstream/plan.h`, but current `main` has no engine-side `core/kvstream/` module. This blocks
|
||||
building the matching ABI-30 HIP engine needed for whole-model tests. The older available GPU
|
||||
engine is ABI 27 and refuses the ABI-30 plugin; the current-main host build has no HIP backend.
|
||||
Accordingly, no fresh HYV3 or Qwen inference A/B ran.
|
||||
|
||||
The user's local Qwen `.rad` was inspected without downloading anything:
|
||||
`/mnt/gostar_data/models/StillDeadcode/qwen3.8-27b-mxfp4/qwen3.8-27b-mxfp4.rad` is a 19.4 GB
|
||||
`Qwen3_5ForConditionalGeneration` container with `n_expert=0` and group-32 MXFP4 weights (SHA-256
|
||||
`a4908940c568f5f9dd24e88f46aefe9ac2ae07dfec023a2eaa1d14dcaa3df4f8`). Its graph-only dispatch check
|
||||
found only unchanged MXFP4 rows, not this PR's asymmetric W4/W5 or per-128 I4 paths. A prior
|
||||
release-tag compatibility smoke answered `42`; neither check is an affected-model A/B. The current-main
|
||||
engine still cannot be built because the KV-stream sources are missing. No model was downloaded and
|
||||
no llama-swap route was edited.
|
||||
|
||||
### Release-tag plus PR build experiment
|
||||
|
||||
To isolate the later mainline KV-stream integration, a temporary worktree was based on release tag
|
||||
`v1.12.0`, then given the HYV3 model-support patch (from `32881da` to `79487d2`) and the PR #237
|
||||
delta (`d650eca` to this PR head). One context conflict in `libr4d/r4d_layout.cpp` came from a
|
||||
post-release MXFP4-gated wrapper absent from the tag; the resolution kept the release's unrelated
|
||||
MXFP4 code and applied the PR's I4 layout changes. No changes were made to the published branch for
|
||||
this experiment.
|
||||
|
||||
- Full Release host build: passed (694 targets).
|
||||
- Full `gfx1201` HIP build: passed (809 targets).
|
||||
- Focused `arch_test`, `chat_test`, `chatparse_test`, and `checkpoint_test`: 4/4 passed.
|
||||
|
||||
Follow-up validation used only the third R9700 (GPU index 2, UUID
|
||||
`GPU-7f082536d27449f3`):
|
||||
|
||||
- `gemm_w4a16_asym_nt_m64`: 341 checks passed, zero failures or skips.
|
||||
- `moe_gemm_w4a8`: 647 checks passed, zero failures, 12 expected skips for unsupported aligned
|
||||
prefill tiles at 640 experts (the run-map limit is 512); HYV3 top-8 gate/up and down geometries
|
||||
were exercised. The selftest exits 2 when skips are present.
|
||||
- The release+PR server loaded the local full-GPTQ W4 HYV3 container at 4096 context on loopback
|
||||
port 18100. `/health` was OK and a chat request asking for 6×7 returned `42`. The process was
|
||||
stopped afterward and the port was confirmed free; no route was changed.
|
||||
|
||||
### Full-suite, performance and quality A/B (completed on the release-tag stack)
|
||||
|
||||
The full CTest suite on the release+HYV3-support+PR candidate passed **121/121** tests, including
|
||||
83 unit tests and all 10 GPU-labelled tests. The full `r4d_selftest` passed on a standalone rerun
|
||||
and again in the final complete suite. An earlier full-suite attempt had an intermittent
|
||||
`hc_read_e4m3` assertion; the same untouched family also failed on the baseline run, while four
|
||||
isolated baseline/candidate reruns passed 38/38 each. The final full-suite run was clean.
|
||||
|
||||
A matched TP1 full-GPTQ W4 A/B used the exact frozen 10,030-token prompt and 2,000-token decode
|
||||
request (`e04af05f...`), on the third R9700, BF16 KV, one sequence, 65,536 context, 4,096 batched
|
||||
tokens, and no launch tune or speculative decoding. The reference was release `v1.12.0` plus HYV3
|
||||
model support; the candidate added only PR #237's delta. Each arm had three repetitions, with the
|
||||
same 16-token prefix-cache behavior after the first run.
|
||||
|
||||
| Arm | Median decode tokens/s | Median prefill tokens/s | Answer SHA-256 |
|
||||
| --- | ---: | ---: | --- |
|
||||
| v1.12.0 + HYV3 support (baseline) | 76.567 | 7,876.292 | `caca914b...` |
|
||||
| v1.12.0 + HYV3 support + PR #237 | 109.618 | 7,926.569 | `caca914b...` |
|
||||
|
||||
That is **+43.17% median decode throughput** and **+0.64% prefill throughput** on this narrow
|
||||
synthetic workload; all six generated-answer hashes were identical. The speed result is specific
|
||||
to this matched release-tag comparison, not a claim about other models or current-main performance.
|
||||
|
||||
Quality comparisons on the same two builds:
|
||||
|
||||
- Greedy output hashes matched **12/12** fixed probes.
|
||||
- Teacher-forced evaluation on the frozen eight-document, 578-position corpus measured mean KL
|
||||
`7.61e-8`, maximum KL `1.57e-6`, **100% top-1 agreement**, and identical PPL `2.875200`.
|
||||
- The 113-case native-tool BFCL subset was identical row-for-row: **102/113** exact calls,
|
||||
**112/113** execution successes, and zero API errors on both arms. This is a curated subset, not
|
||||
broad capability evidence.
|
||||
|
||||
#### Same-build cross-card diagnostic
|
||||
|
||||
At the user's request, I reran the same candidate executable, `.rad` artifact, launch flags, and
|
||||
three 2,000-token repetitions on two individual R9700s. The frozen 10,030-token benchmark used the
|
||||
same per-repetition prefix scheme on both cards; no launch tune or drafter was enabled. The model
|
||||
was loaded separately on each card, with no other Radiance process using either device.
|
||||
|
||||
| Device | Median decode tok/s | Median prefill tok/s | Answer SHA-256 |
|
||||
| --- | ---: | ---: | --- |
|
||||
| PCI `0000:06:00.0`, UUID `GPU-048200e09844fd51` | 118.380 | 8,077.674 | `caca914b...` |
|
||||
| PCI `0000:0f:00.0`, UUID `GPU-7f082536d27449f3` | 109.834 | 8,011.282 | `caca914b...` |
|
||||
|
||||
The same candidate was **7.2% slower on the designated PCI `0f:00.0` card**. A fresh confirmation
|
||||
on that card measured **110.311 tok/s**, within 0.44% of the initial 109.834 tok/s result. The older
|
||||
115.678 tok/s untuned run was on PCI `06:00.0`, so the earlier 115-versus-109 comparison was
|
||||
confounded by card/operating-point differences, not evidence that splitting the branch caused a
|
||||
regression. All three R9700 UUIDs are configured for PPT0=210 W in
|
||||
`/usr/local/sbin/gpu-power-caps`; its AMD cap loop runs before the separate NVIDIA stage where the
|
||||
service fails. So a different *configured* cap is not established as the cause. Per-run live
|
||||
cap/clock telemetry was not captured; card-specific boost, thermal/board behavior, or silicon
|
||||
variation could still matter. PCIe bandwidth is not established as the cause. Raw-request repeats
|
||||
that reused 10,000 cached prompt tokens are retained separately and excluded from this comparison.
|
||||
|
||||
Additional compatibility smokes using the same candidate build passed for the local Qwen4Exp W5
|
||||
container (returned `42`; prompt-lookup drafted 6 tokens and accepted 1), Qwen Flash-Next IQ4R
|
||||
(TP1 and TP2 launchers, answered `42`), Qwen3.8 27B MXFP4 (answered `42`), Breeze-TTS-2 (valid
|
||||
24 kHz mono PCM), and HYV3 (answered `42`). The verified deployment build was moved intact to
|
||||
`/mnt/gostar_data/radiance-builds/radiance-v1.12-hyv3-pr237/build-gfx1201`; all six local model
|
||||
launchers were syntax-checked and updated to use it. The W5 launcher dropped a stale
|
||||
`--draft-coupling on` option rejected by this container (it declares no linear drafter); its
|
||||
six-token prompt-lookup setting remains. These are smoke tests, not matched performance/quality
|
||||
results for those models. No model was downloaded and no llama-swap route was changed.
|
||||
|
||||
Logs, summaries and raw rows are under
|
||||
`/mnt/gostar_data/radiance-calib/hyv3-pr-validation-20261025/pr237/` and
|
||||
`/mnt/gostar_data/radiance-calib/hyv3-w4-round2-20261024/` (labels `release-v112-baseline` and
|
||||
`release-v112-pr`).
|
||||
|
||||
## Integration caveat and scope of claims
|
||||
|
||||
The successful full builds, full test suite and A/B above use the release-tag stack because the
|
||||
current-main source still lacks the engine-side `core/kvstream/` headers introduced by upstream
|
||||
`486c933`; it therefore cannot produce the matching ABI-30 HIP engine. That unrelated upstream
|
||||
build break remains outside this PR, so the A/B must not be described as a current-main-vs-PR run.
|
||||
The PR is validated and ready for review against the buildable release-tag stack, but after the
|
||||
upstream KV-stream integration is restored, current-main builds/tests should be rerun.
|
||||
|
||||
Performance and quality claims are limited to the HYV3 TP1 full-GPTQ W4 A/B above. The Qwen W5,
|
||||
IQ4R and MXFP4 runs were compatibility smokes only; no broad speedup or quality claims are made for
|
||||
other model families or formats. The native BFCL corpus is also a small safe subset, not a broad
|
||||
quality benchmark.
|
||||
|
||||
The cold-weight diagnostics are `r4d_selftest --perfw4`, `--perfw4bf16`, `--perfbf16` and
|
||||
`--perfhyv3moe`; see [libr4d/README.md](../../libr4d/README.md). Their byte/canonical checks and
|
||||
shape-specific timings do not replace whole-model performance or quality comparisons.
|
||||
@@ -1,25 +1,27 @@
|
||||
# DeepSeek-V4.1-Flash: a .rad straight from the release (no GGUF converter)
|
||||
# DeepSeek-V4.1-Flash: a .rad from the release (no GGUF converter)
|
||||
|
||||
The official DeepSeek-V4.1-Flash release converts with `rad-convert` alone: no llama.cpp GGUF is
|
||||
built as an intermediate, and no separate drafter directory is grafted. The pieces are in the tree:
|
||||
built as an intermediate, and no separate drafter directory is grafted. The pieces below prepare
|
||||
and convert the release. Serving the container needs the `deepseek41` architecture plugin, which
|
||||
this tree does not include yet.
|
||||
|
||||
- `data/engram_tables.py` builds the Engram hash tables from the release's own `tokenizer.json` and
|
||||
`config.json`, reimplementing the tokenizer's ByteLevel decode and the normaliser sequence
|
||||
(NFKC, NFD, strip marks, lowercase, collapse spaces, sentinel) and the PCG64 multipliers and
|
||||
prime buckets. Validated against HF `tokenizers`: 0 mismatched token ids of 129280, compressed
|
||||
vocab 99092, the release's two Engram layers [1, 14]. It writes `engram-tables.safetensors`.
|
||||
`config.json`. It reimplements the tokenizer's ByteLevel decode, the normaliser sequence (NFKC,
|
||||
NFD, strip marks, lowercase, collapse spaces, sentinel), the PCG64 multipliers and the prime
|
||||
buckets. Against HF `tokenizers`: 0 mismatched token ids of 129280, compressed vocab 99092, the
|
||||
release's two Engram layers [1, 14]. It writes `engram-tables.safetensors`.
|
||||
- `data/imatrix_merge.py` fuses the imatrix entries llama.cpp's converter writes split
|
||||
(`ffn_gate_exps`, `ffn_up_exps`) into the plugin's fused `ffn_gate_up_*`, summing the two halves
|
||||
(and `shexp`): 1184 entries carried through, 160 fused for 40 layers. IQ1_S refuses a fused
|
||||
weight without one.
|
||||
- `data/recipes/deepseek41-ud-iq1s.recipe` is the UD-IQ1_S per-tensor mix, as rules for libquant's
|
||||
`ggml` quantiser, so the release converts to the same encodings the GGUF gives.
|
||||
(and those of `shexp`): 1184 entries carried through, 160 fused for 40 layers. IQ1_S refuses a
|
||||
fused weight without one.
|
||||
- `data/recipes/deepseek41-ud-iq1s.recipe` is the UD-IQ1_S per-tensor mix as rules for libquant's
|
||||
`ggml` quantiser, so the release converts to the same encodings the GGUF has.
|
||||
- `rad-convert --chat-template FILE` bakes a template into the container's vocab section. The
|
||||
release carries no `chat_template.jinja` and its `tokenizer_config.json` names none, so without
|
||||
this flag an HF-direct container answers `/v1/chat/completions` with 501. Trailing newlines are
|
||||
stripped as for a sibling template, and an unreadable or empty file is refused, not skipped.
|
||||
release carries no `chat_template.jinja` and its `tokenizer_config.json` names none, so a
|
||||
container converted without this flag answers `/v1/chat/completions` with 501. Trailing newlines
|
||||
are stripped as for a sibling template, and an unreadable or empty file is refused.
|
||||
|
||||
## The three steps
|
||||
## Conversion
|
||||
|
||||
```
|
||||
# 1. the Engram tables, from the release's tokenizer (not a GGUF)
|
||||
@@ -28,19 +30,21 @@ python3 data/engram_tables.py <HF release dir> engram-tables.safetensors
|
||||
# 2. fuse the imatrix's split gate/up entries
|
||||
python3 data/imatrix_merge.py imatrix_unsloth.gguf_file imatrix-merged.gguf
|
||||
|
||||
# 3. convert; the template is the model's own, baked into the container
|
||||
# 3. convert, with a chat template for the model baked into the container
|
||||
rad-convert <HF release dir> --add engram-tables.safetensors \
|
||||
--recipe data/recipes/deepseek41-ud-iq1s.recipe \
|
||||
--imatrix imatrix-merged.gguf --tokenizer <HF release dir>/tokenizer.json \
|
||||
--chat-template chat_template.jinja -o deepseek-v4.1-flash-ud-iq1s.rad
|
||||
```
|
||||
|
||||
Measured on the release (DeepSeek-V4.1-Flash-1017, fp8 with e8m0 per 32×32 blocks, MXFP4 experts):
|
||||
plan 32701 weights / **251.07 GiB**, conversion **251.13 GiB in 2h11m** on this host, and the
|
||||
container serves on 4× R9700 at TP4 with its DSpark metadata (block 5, 128 experts, targets
|
||||
37/38/39) and Engram baked. Quality of the converted container, greedy, thinking off: HE 154/164 =
|
||||
.939 (the native UD-IQ1_S reference .963, McNemar p = .125), GSM 194/200 = .970 (reference .960).
|
||||
From DeepSeek-V4.1-Flash-1017 (fp8 with e8m0 scales per 32x32 block, MXFP4 experts) the plan is
|
||||
32701 weights, 251.07 GiB, and the container 251.13 GiB. The `deepseek41` plugin serves it on 4x
|
||||
R9700 at `--tp 4` with its DSpark metadata (block 5, 128 experts, targets 37/38/39) and the Engram
|
||||
tables baked in. Quality, greedy, thinking off: HumanEval 154/164 = 0.939 (the native UD-IQ1_S
|
||||
reference 0.963, McNemar p = 0.125), GSM 194/200 = 0.970 (reference 0.960).
|
||||
|
||||
Serving: nothing else is needed now that the template is baked. A container built before this flag
|
||||
needed `--override-chat-template FILE` at serve time; the file has to be a Radiance-renderable
|
||||
template (the release's own is; llama.cpp-only jinja such as `dict()` in a GGUF's template is not).
|
||||
## Serving
|
||||
|
||||
A container converted with `--chat-template` needs no template at serve time. One converted
|
||||
without it needs `--override-chat-template FILE`; the file must be a template radiance renders
|
||||
(the release's own is; llama.cpp-only Jinja, such as `dict()` in a GGUF's template, is not).
|
||||
+35
-2
@@ -246,12 +246,17 @@ static int attn_paged_prefill(const RadArgs* a, [[maybe_unused]] RadStream strea
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* attn_paged_tree's ninth operand, `spec_parent` (rad_drafter_tree), is read here too, as libref
|
||||
* reads it: -2 an ordinary causal row; else the row's parent's index within its sequence's rows
|
||||
* (-1 for the block's first). Inside the block such a row sees itself and its ancestors only, and
|
||||
* its window is measured from the block's first position plus its depth. */
|
||||
AVX_KERNEL(attn_paged) {
|
||||
if (a->n_t < 8) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
|
||||
const RadTensor* kdes = rad_arg_in(a, 4);
|
||||
const RadTensor* vdes = rad_arg_in(a, 5);
|
||||
const RadTensor* cus = rad_arg_in(a, 6);
|
||||
const RadTensor* tpar = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr;
|
||||
if (!q->data || !kv->data || !bt->data || !su->data || !o->data) return RAD_E_INVAL;
|
||||
|
||||
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
|
||||
@@ -294,7 +299,7 @@ AVX_KERNEL(attn_paged) {
|
||||
|
||||
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
|
||||
/* Uniform long queries take the panel form; ragged (cus) inputs stay here. */
|
||||
if (!cus && q_len >= 32) return attn_paged_prefill(a, stream);
|
||||
if (!cus && q_len >= 32 && !tpar) return attn_paged_prefill(a, stream);
|
||||
/* Work units are (token, kv-head) groups: the gqa query rows of a group share every key and
|
||||
* value row, so each is widened once for gqa dots/axpys. Per-row arithmetic is unchanged. */
|
||||
const int64_t total = rows * kv_heads;
|
||||
@@ -317,6 +322,25 @@ AVX_KERNEL(attn_paged) {
|
||||
if (qlen <= 0) continue;
|
||||
const int64_t ctx = ldi(su, offlin(su, s));
|
||||
const int64_t pos = ctx - qlen + i;
|
||||
/* A tree row: its ancestors inside the block (a bit per row) and its depth. */
|
||||
const int64_t base = ctx - qlen;
|
||||
bool tree = false;
|
||||
uint64_t tmask = 0;
|
||||
int64_t tdep = 0;
|
||||
if (tpar) {
|
||||
int64_t pj = ldi(tpar, offlin(tpar, tok));
|
||||
if (pj != -2 && i < 64) {
|
||||
tree = true;
|
||||
tmask = 1ull << i;
|
||||
for (int64_t at = i; pj >= 0 && pj < at; ) {
|
||||
tmask |= 1ull << pj;
|
||||
++tdep;
|
||||
at = pj;
|
||||
pj = ldi(tpar, offlin(tpar, tok - i + pj));
|
||||
}
|
||||
}
|
||||
}
|
||||
const int64_t wpos = tree ? base + tdep : pos;
|
||||
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
|
||||
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
|
||||
|
||||
@@ -393,8 +417,9 @@ AVX_KERNEL(attn_paged) {
|
||||
|
||||
for (int64_t j = 0; j < ctx; ++j) {
|
||||
if (causal ? (j > pos) : (j >= ctx)) continue;
|
||||
if (tree && j >= base && !((tmask >> (j - base)) & 1)) continue;
|
||||
if (window > 0) {
|
||||
const int64_t d = pos - j;
|
||||
const int64_t d = wpos - j;
|
||||
if (causal ? (d >= window) : (d >= window || d <= -window)) continue;
|
||||
}
|
||||
if (j / block_size >= max_blocks) break; /* past the block table's width */
|
||||
@@ -721,6 +746,14 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
|
||||
}
|
||||
#endif
|
||||
|
||||
/* attn_paged with its tree operand present, which attn_paged reads (see there). Refused without
|
||||
* one, and for a non-causal layer. */
|
||||
AVX_KERNEL(attn_paged_tree) {
|
||||
if (a->n_t < 9 || !rad_arg_in(a, 8)) return RAD_E_INVAL;
|
||||
if (p_int(a, "causal", 1) != 1) return RAD_E_UNSUPPORTED;
|
||||
return AVX_FN(avx_attn_paged)(a, stream);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ attn_dense */
|
||||
/* Unpaged, unquantised attention (vision towers): `cu_seqlens` bounds one image or attention
|
||||
* window per entry, so a whole batch is one launch. `causal` is a parameter so a dense
|
||||
|
||||
@@ -348,6 +348,13 @@ std::vector<Case> build_cases() {
|
||||
HI("block_size", 16), HI("causal", 1), HI("window", window),
|
||||
HS("q_dtype", dt), HS("kv_dtype", dt), HF("scale", 0.125),
|
||||
HI("max_ctx", 128), HI("n_head", 8), HI("max_seqs", 2) });
|
||||
/* The tree form over the same shapes (its described parents are ordinary rows, -2). */
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
for (int qlen : { 1, 17 })
|
||||
add("attn_paged_tree", { HI("q_len", qlen), HI("head_dim", 64), HI("gqa", 4),
|
||||
HI("block_size", 16), HI("causal", 1), HI("window", 8),
|
||||
HS("q_dtype", dt), HS("kv_dtype", dt), HF("scale", 0.125),
|
||||
HI("max_ctx", 128), HI("n_head", 8), HI("max_seqs", 2) });
|
||||
for (const char* dt : { "f32", "bf16" })
|
||||
for (int causal : { 0, 1 })
|
||||
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
|
||||
@@ -752,6 +759,13 @@ std::vector<Case> build_cases() {
|
||||
HI("n_vocab", 300), HI("anchor_stride", 1), HS("dtype", "bf16") });
|
||||
add("dflash_select", { HI("M", 5), HI("steps", 3), HI("top_k", 12), HI("rank", 37),
|
||||
HI("n_vocab", 97), HI("anchor_stride", 2), HS("dtype", "bf16") });
|
||||
/* The same lattices grown into trees: more nodes than steps, and fewer. */
|
||||
add("dflash_tree", { HI("M", 3), HI("steps", 4), HI("top_k", 8), HI("rank", 64),
|
||||
HI("n_vocab", 300), HI("anchor_stride", 1), HI("nodes", 6),
|
||||
HS("dtype", "bf16") });
|
||||
add("dflash_tree", { HI("M", 5), HI("steps", 3), HI("top_k", 12), HI("rank", 37),
|
||||
HI("n_vocab", 97), HI("anchor_stride", 2), HI("nodes", 2),
|
||||
HS("dtype", "bf16") });
|
||||
/* DFlash2's convolution: the 27B drafter's form (2 taps, groups of 16) over a narrower row,
|
||||
* then groups that are no multiple of a vector, three taps and a one-row block. f16 rows take
|
||||
* the path through f32 copies, bf16 and f32 the fused one. */
|
||||
|
||||
@@ -4063,7 +4063,7 @@ void planes_cases(const Check& ck, std::vector<Hand>& hs, Broken& broken) {
|
||||
static const Grid kGrids[] = {
|
||||
{ "w2a8", RAD_U2, 0, 1 }, { "w4a8_asym", RAD_U4, 0, 1 },
|
||||
{ "w4a16_asym", RAD_U4, 2, 1 }, { "w4a16_asym", RAD_U4, 2, 2 },
|
||||
{ "w4a16_asym", RAD_U4, 3, 1 }, /* BF16 input, oracle is the former F16 cast */
|
||||
{ "w4a16_asym", RAD_U4, 3, 1 }, /* BF16 input, narrowed to F16 as the cast kernel does */
|
||||
{ "w5a16", RAD_U5, 2, 1 }, { "w5a16", RAD_U5, 2, 3 },
|
||||
{ "w4a8i8_asym", RAD_U4, 1, 1 }, { "w4a8i8_asym", RAD_U4, 1, 2 },
|
||||
{ "w5a8i8", RAD_U5, 1, 1 }, { "w5a8i8", RAD_U5, 1, 3 },
|
||||
|
||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user