diff --git a/CMakeLists.txt b/CMakeLists.txt index 2a95b629..3b37058b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is what /version reports and what a client checks compatibility against. It is NOT the # ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because # a plugin contract and a server release do not move together. -project(radiance VERSION 1.0.13 LANGUAGES C CXX) +project(radiance VERSION 1.1.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/NOTICE b/NOTICE index d52a7378..4d9af9a6 100644 --- a/NOTICE +++ b/NOTICE @@ -4,10 +4,11 @@ Copyright 2026 Deadcode and the radiance contributors Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14 (the MXFP4 GEMM and the GDN kernels' overflow guards), goodman-b (four-rank tensor parallelism for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the fused four-rank -writes, the n-gram table in RAM, the four-class expert split and the Grafana dashboard), -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 baKon (three-rank tensor parallelism and the request -log). +writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard, the routed +GEMM's decode loads and run search, the gated residual's prefill read form and row groups, and +the fused router launch), 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 baKon (three-rank tensor +parallelism, serving any world size from the shipped container, and the request log). This product includes software from the following projects, each under the MIT License. The license text is in the file named beside each. diff --git a/README.md b/README.md index e340ce60..f99f7b11 100644 --- a/README.md +++ b/README.md @@ -81,18 +81,17 @@ prefix-cache tiers: | model | flags | |---|---| -| Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | -| Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | -| Qwen3.8-Flash-Next, three ranks (the checkpoint padded first, [`docs/TP3.md`](docs/TP3.md)) | `--tp 3 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | +| Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | +| Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | +| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `--tp 3 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` | | Qwen3.8-27B FP8, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` | | Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` | | MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` | | Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` | Every model serves up to 32 sequences a step. Two rows keep 8, because on a hybrid model each -sequence holds its own recurrent state and 32 of them leave the attention cache short of one -200K-token request: Flash-Next at ratio 0.82 (`--max-num-seqs 32 --expert-vs-cache-ratio 0.78` -keeps the 200K request and costs single-stream decode about 15%) and the 27B in bf16. See +sequence holds its own recurrent state, and 32 of them take that memory from the attention cache +and, on Flash-Next, from the expert slab: Flash-Next and the 27B in bf16. See [`docs/GUIDE.md`](docs/GUIDE.md) §4.4. At `--tp 4` the gated residual's write carries the exact all-reduce, with the MoE gather in front @@ -107,8 +106,8 @@ tiering flags are the tp2 recipe carried over. Above two ranks each rank still o every expert's width** — each parity's 128-column blocks are cut contiguously over the ranks and the odd block alternates with the parity, so every rank's share is whole blocks and every block has exactly one owner — and the resident expert bytes per rank are smaller, so the elastic window is a -different shape: read the boot log's `elastic` line and re-derive `--expert-vs-cache-ratio` and -`--host-pool-mib` before trusting them. **`--host-pool-mib` is pinned on every card**, so the row +different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before +trusting it. **`--host-pool-mib` is pinned on every card**, so the row above pins 4 × 12 GiB = 48 GiB, and the amdgpu driver caps pinned memory at `ttm.pages_limit`, half of RAM by default: that row needs 96 GiB of RAM or a raised limit ([`docs/GUIDE.md`](docs/GUIDE.md) §7). @@ -156,7 +155,7 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out of tr | [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files | | [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card | | [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | the supported model families and their geometry | -| [`docs/TP3.md`](docs/TP3.md) | padding a checkpoint, exactly, to a world its head counts do not divide; three ranks | +| [`docs/TP3.md`](docs/TP3.md) | any world size: the attention world and uneven delta-net heads; three ranks | | [`docs/OPS.md`](docs/OPS.md), [`docs/KERNELS.md`](docs/KERNELS.md) | the op vocabulary, and what `rad-kbench` last measured | | [`spec.md`](spec.md) | the design | diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 431ea177..e1c92a0e 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -374,13 +374,6 @@ int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi); int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, const int64_t* hi, const int64_t* total, int n); -/* THIS RANK'S SHARE IS ZEROS. The weight is declared with its row or column shard and extent as - * on every other rank, and nothing is read for it: the loader writes zeros. It is for a rank the - * geometry gives no real heads (rad_arch.h: a world size the KV head count does not divide), so - * that rank runs the same program as its peers -- the scheduler sees one program -- and its - * projection contributes exactly nothing to the reduce. Additive export. */ -int rad_weight_shard_zero(RadBuilder* b, rad_weight w); - /* THIS RANK KEEPS NO CACHE FOR THE GROUP. The group is declared as on every other rank -- the * scheduler indexes groups by position and one block table serves every rank, so it must exist * here with the same block size and layers -- and nothing is carved for it: it costs this rank no @@ -691,7 +684,8 @@ typedef struct RadChatFormat { uint32_t string_value; /* RAD_CHAT_VALUE_RAW or _CDATA: a string-typed argument */ uint32_t other_value; /* RAD_CHAT_VALUE_JSON: any other type (or _RAW, as text) */ - /* Non-zero: one newline at each end of a value is punctuation, not part of the value. */ + /* Non-zero: one newline at each end of a value is punctuation, not part of the value -- at + * its start only where the tag before it does not end with that newline itself. */ uint32_t value_newlines; /* The literal words that start constrained decoding of a call. None: no grammar, and the diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index 8cde9a34..eca94953 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -580,10 +580,11 @@ struct Geom { * -- three ranks over Flash-Next's two KV heads -- serves attention on the largest multiple * of the head count below it (`attn_world`, here 2: split, or replicated when that is still * above the count) and the remaining ranks are ATTENTION-ZERO: they declare the same heads and - * the same program as their peers, read nothing for the attention projections - * (rad_weight_shard_zero) and add exactly zero to the reduce. `attn_rank` is this rank's - * index inside the attention world (an attention-zero rank clamps to the last). When - * attn_world == world nothing here is used and every block declares as it always did. */ + * the same program as their peers, compute no attention (a `fill` of the block's output and + * a zero KV group, rad_kv_group_zero) and add exactly zero to the reduce. `attn_rank` is this + * rank's index inside the attention world (an attention-zero rank clamps to the last). When + * attn_world == world nothing here is used and every block declares as it always did. Set + * only for a plugin that asks for it (geom_from's `attn_world_ok`). */ int attn_world = 1; int attn_rank = 0; bool attn_zero = false; @@ -728,20 +729,15 @@ inline long long meta_int2(const RadModelMeta* m, const char* gguf_key, const ch return v == sentinel ? dflt : v; } -/* `arch_splits_ff`: the plugin divides the feed-forward width across the ranks ITSELF (qwen4exp: - * the routed experts' width is cut by whole fp8 blocks, by parity, at any world up to the block - * count). With it set, a width the world does not divide is left whole in g.n_ff and the plugin - * takes its slice from there; without it the refusal stands, because for every other plugin g.n_ff - * IS the per-rank width. A width that does divide is unaffected either way. */ /* THE REMAINDER-FIRST ORDER OF THE RANKS. What does not divide evenly over the world and is a * HEAD'S worth of work -- the extra delta-net head -- goes to the ranks with NO attention first: * they pay nothing for attention (rad_block_attn_gated_fp8.h: one fill) and keep no attention * cache (rad_kv_group_zero), so they have the time for it, and the rank that held the extra head * AND attention -- the step's slowest -- is lighter for it. An expert's extra block is not a - * head's worth (qwen4exp_fp8.cpp says why it stays on the rotation). This is a rank's PLACE in that order: the attention-zero ranks - * take places 0..n-1 whatever `parity` is, and the attention ranks follow in today's rotation by - * `parity` -- so where no rank is attention-zero (every world the heads divide) the place is - * exactly (rank - parity) mod world and every cut is what it always was, byte for byte. */ + * head's worth (qwen4exp_fp8.cpp says why it stays on the rotation). This is a rank's PLACE in + * that order: the attention-zero ranks take places 0..n-1 whatever `parity` is, and the attention + * ranks follow in the rotation by `parity` -- so where no rank is attention-zero (every world the + * heads divide) the place is exactly (rank - parity) mod world and every cut is the even one. */ inline int64_t remainder_place(const Geom& g, int rank, int parity) { const int nz = g.world - g.attn_world; if (rank >= g.attn_world) return rank - g.attn_world; @@ -749,8 +745,19 @@ inline int64_t remainder_place(const Geom& g, int rank, int parity) { return nz + ((rank - parity) % aw + aw) % aw; } +/* `arch_splits_ff`: the plugin divides the feed-forward width across the ranks ITSELF (qwen4exp: + * the routed experts' width is cut by whole fp8 blocks, by parity, at any world up to the block + * count). With it set, a width the world does not divide is left whole in g.n_ff and the plugin + * takes its slice from there; without it the refusal stands, because for every other plugin g.n_ff + * IS the per-rank width. A width that does divide is unaffected either way. */ +/* `attn_world`: the plugin's attention block serves a SMALLER ATTENTION WORLD (Geom::attn_world) + * -- it declares the attention-zero rank's fill and zero KV group and spans the attention + * projections by `attn_rank`. Only rad_block_attn_gated_fp8.h does. Without it a world the KV head + * count neither divides nor is a multiple of is refused here, by name, rather than declared with + * an even shard the block would then cut wrongly. */ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c, - const char* dtype, uint32_t act_dtype, bool arch_splits_ff = false) { + const char* dtype, uint32_t act_dtype, bool arch_splits_ff = false, + bool attn_world_ok = false) { if (!m || !c) return RAD_E_INVAL; if (c->is_draft) { /* A drafter declared into this plugin would need a second set of per-rank handles and a @@ -819,7 +826,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c, g.attn_world = g.world; g.attn_rank = g.rank; g.attn_zero = false; - if (g.world > g.n_head_kv_all && g.world % g.n_head_kv_all != 0) { + if (attn_world_ok && g.world > g.n_head_kv_all && g.world % g.n_head_kv_all != 0) { g.attn_world = (int)(g.n_head_kv_all * (g.world / g.n_head_kv_all)); g.attn_zero = g.rank >= g.attn_world; g.attn_rank = g.attn_zero ? g.attn_world - 1 : g.rank; diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h index e1212f0b..f2481e7f 100644 --- a/arch/common/rad_block_moe_fp8.h +++ b/arch/common/rad_block_moe_fp8.h @@ -76,19 +76,6 @@ namespace arch { * decide, at declare time and identically on both ranks, whether the op exists at all. */ static const int64_t kMoeSortRows = 1024; -/* R4D_ROUTER_FUSED: the router's GEMM in the same launch as `router_topk_scatter` - * (`router_gemm_topk_scatter`), at decode shapes. 1 also computes the shared expert's one-column - * gate in that launch, 2 leaves the gate its own `gemm_nt`; unset or 0 declares nothing new and the - * graph is the one without it. Read once, at declare, so a recorded pass and a live one issue the - * same ops. Every output is byte-identical either way (see libr4d's r4d_moe.hip). */ -inline int moe_router_fused_mode() { - static const int v = [] { - const char* e = std::getenv("R4D_ROUTER_FUSED"); - const int x = e ? std::atoi(e) : 0; - return (x == 1 || x == 2) ? x : 0; - }(); - return v; -} /* The skinny bf16 GEMM's decode band, which is where the fused op's GEMM is that GEMM's own * arithmetic; past it the router runs the tiled kernel and the pair is issued as before. */ static const int64_t kMoeRouterFusedRows = 64; @@ -379,9 +366,10 @@ struct MoeFP8 { * a prefill chunk is past it. */ rad_op op_topk_scatter = 0; int64_t topk_scatter_rows = 0; - /* `router_gemm_topk_scatter` (R4D_ROUTER_FUSED), if declared: the router GEMM in front of the - * pair above, up to `router_fused_rows` tokens, and with `router_fused_gate` the shared - * expert's gate (`op_sgate`'s work) as well. 0 issues the router and the pair as always. */ + /* `router_gemm_topk_scatter`, if it resolves: the router GEMM in front of the pair above, up + * to `router_fused_rows` tokens, and with `router_fused_gate` the shared expert's gate + * (`op_sgate`'s work) as well. 0 -- the op did not resolve -- issues the router and the pair + * as always, and so does a pass of more rows. */ rad_op op_router_fused = 0; int64_t router_fused_rows = 0; bool router_fused_gate = false; @@ -595,6 +583,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, /* A rank whose slice of the shared arm is empty (see Config) declares no arm, and the * all-reduce carries the others' share. */ const bool shared = c.n_ff_shared > 0 && src.shared; + /* Whether `w.sgate` is out of the sharing pool -- set where the shared arm says so, and what + * the fused router's gate write relies on (see there). */ + bool sgate_concurrent = false; /* THE INPUT MAY BE PREPARED BY THE ARCHITECTURE, and `src.norm == nullptr` is how it says so. * @@ -1358,6 +1349,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.x)); RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout)); RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate)); + sgate_concurrent = true; /* The gate/up rows and the down columns of this rank's slice -- the even split, or the * uneven one Config states -- and the split of gate from up stays, because that is a * property of the stacked checkpoint tensor and not of the rank count. */ @@ -1390,66 +1382,51 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, {w.h.x}, {w.sgate}); } - /* ---- R4D_ROUTER_FUSED: the router GEMM and `router_topk_scatter` as one op, and with mode 1 - * the shared gate as well. Declared HERE, after the gate's weight, and not beside the router: - * the op names both weights, and declaring it late only lengthens the planned lifetime of the - * buffers it touches, never shortens one -- each of them is also declared by the op it stands - * in for, at that op's place. Only where the pair itself is declared, and only up to the - * pair's own row bound. */ - if (moe_router_fused_mode() && op_topk_scatter) { + /* ---- THE ROUTER GEMM AND `router_topk_scatter` AS ONE OP, with the shared expert's gate in + * the same launch wherever the layer has one. Asked for wherever the pair itself is declared, + * up to the pair's own row bound and the skinny GEMM's decode band; a plugin that does not + * serve it leaves the handle 0 and the router and the pair are issued as declared above. + * Declared HERE, after the gate's weight, and not beside the router: the op names both + * weights, and declaring it late only lengthens the planned lifetime of the buffers it + * touches, never shortens one -- each of them is also declared by the op it stands in for, at + * that op's place. + * + * EXCEPT `w.sgate`, WHICH THE FUSED OP WRITES AHEAD OF ITS DECLARED WRITER. The gate is issued + * at the router's place, before `op_sgate`'s declared index, so a plan bounded by the linear + * order could lend `w.sgate`'s bytes to a buffer that is live in between. It cannot here + * because the shared arm took `w.sgate` out of the sharing pool (rad_buf_concurrent), and the + * declaration refuses a fused gate on a layer where that has not happened. + * + * NOT rw()'s braced lists and not one RAD_OP per combination: the parameter list (a protect + * list or not), the weights and the write set (the gate or not) are conditional, so each is + * one array cut to its length. */ + if (op_topk_scatter) { router_fused_rows = topk_scatter_rows < kMoeRouterFusedRows ? topk_scatter_rows : kMoeRouterFusedRows; - router_fused_gate = moe_router_fused_mode() == 1 && op_sgate != 0; - const int64_t fr = router_fused_rows; - if (router_fused_gate && !prot_list) - op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter", - RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", g.n_embd), - RAD_INT("n_expert", c.n_expert_all), - RAD_INT("n_local", c.n_expert), - RAD_INT("top_k", c.top_k), - RAD_INT("norm", c.norm_topk), - RAD_STR("dtype", g.dtype), - RAD_INT("expert_base", c.expert_base)), - RAD_WEIGHTS(w_router, w_sgate)), - {w.h.x}, {w.logits, w.ids, w.ew, w.sorted, w.eoff, w.ecnt, - w.sgate}); - else if (router_fused_gate) - op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter", - RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", g.n_embd), - RAD_INT("n_expert", c.n_expert_all), - RAD_INT("n_local", c.n_expert), - RAD_INT("top_k", c.top_k), - RAD_INT("norm", c.norm_topk), - RAD_STR("dtype", g.dtype), - RAD_INT("expert_base", c.expert_base), - RAD_STR("protect", prot_list)), - RAD_WEIGHTS(w_router, w_sgate)), - {w.h.x}, {w.logits, w.ids, w.ew, w.sorted, w.eoff, w.ecnt, - w.sgate}); - else if (!prot_list) - op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter", - RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", g.n_embd), - RAD_INT("n_expert", c.n_expert_all), - RAD_INT("n_local", c.n_expert), - RAD_INT("top_k", c.top_k), - RAD_INT("norm", c.norm_topk), - RAD_STR("dtype", g.dtype), - RAD_INT("expert_base", c.expert_base)), - RAD_WEIGHTS(w_router)), - {w.h.x}, {w.logits, w.ids, w.ew, w.sorted, w.eoff, w.ecnt}); - else - op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter", - RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", g.n_embd), - RAD_INT("n_expert", c.n_expert_all), - RAD_INT("n_local", c.n_expert), - RAD_INT("top_k", c.top_k), - RAD_INT("norm", c.norm_topk), - RAD_STR("dtype", g.dtype), - RAD_INT("expert_base", c.expert_base), - RAD_STR("protect", prot_list)), - RAD_WEIGHTS(w_router)), - {w.h.x}, {w.logits, w.ids, w.ew, w.sorted, w.eoff, w.ecnt}); - if (!op_router_fused) router_fused_gate = false; + const bool gate = op_sgate != 0; + if (gate && !sgate_concurrent) { + fprintf(stderr, "radiance: layer %d: the fused router writes the shared gate ahead of " + "its declared writer, which needs `sgate` out of the sharing pool, " + "and it is not\n", l); + return RAD_E_STATE; + } + const RadParam fp[] = { + RAD_RANGE("M", 1, router_fused_rows), RAD_INT("K", g.n_embd), + RAD_INT("n_expert", c.n_expert_all), RAD_INT("n_local", c.n_expert), + RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm_topk), + RAD_STR("dtype", g.dtype), RAD_INT("expert_base", c.expert_base), + RAD_STR("protect", prot_list), + }; + const int n_fp = (int)(sizeof(fp) / sizeof(fp[0])) - (prot_list ? 0 : 1); + const rad_weight fw[2] = { w_router, w_sgate }; + op_router_fused = rad_decl_op(b, "router_gemm_topk_scatter", fp, n_fp, fw, gate ? 2 : 1); + if (op_router_fused) { + const rad_buf rd[1] = { w.h.x }; + const rad_buf wr[7] = { w.logits, w.ids, w.ew, w.sorted, w.eoff, w.ecnt, w.sgate }; + rad_op_reads (b, op_router_fused, rd, 1); + rad_op_writes(b, op_router_fused, wr, gate ? 7 : 6); + } + router_fused_gate = op_router_fused && gate; } if (g.world > 1) @@ -1486,7 +1463,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, * MlpFP8 slice. */ inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, bool gate_done) const { - /* `gate_done`: the fused router already wrote this pass's gate (R4D_ROUTER_FUSED=1). */ + /* `gate_done`: the fused router already wrote this pass's gate. */ if (!gate_done) RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate), brow_slice(w.sgate, r0, rows, 1)); @@ -1519,8 +1496,9 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const * a routed layer, a whole dependent dispatch for a kilobyte. */ int32_t* const counts = rad_route_counts(c_, layer, ne); const RadOperand ecnt = counts ? praw(counts, RAD_I32, ne) : brows(w.ecnt, ne); - /* R4D_ROUTER_FUSED: the router, the pair below and -- with `router_fused_gate` -- the shared - * gate, in one launch with the operands the three are handed. */ + /* THE FUSED ROUTER where it resolved and the pass is within its rows: the router, the pair + * below and -- with `router_fused_gate` -- the shared gate, in one launch with the operands + * the three are handed. Otherwise the router and the pair, as declared. */ const bool rfused = op_router_fused && rows <= router_fused_rows; if (rfused) RAD_ISSUE_N(c_, op_router_fused, rows, brow_slice(w.h.x, r0, rows, g.n_embd), diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 338bd556..e99aa7cc 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -727,13 +727,6 @@ struct LinearFP8 { int64_t span_lo = 0, int64_t span_hi = 0); void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; - /* THIS RANK READS NOTHING FOR IT: the weight and its scale plane are zeros - * (rad_weight_shard_zero). After declare(); for an attention-zero rank (rad_arch.h). */ - int zero_share(RadBuilder* b) const { - RAD_ARCH_TRY(rad_weight_shard_zero(b, w)); - if (ws) RAD_ARCH_TRY(rad_weight_shard_zero(b, ws)); - return RAD_OK; - } /* A SPAN PER STACKED ROW PART (rad_weight_shard_span_parts), in the weight's rows; the scale * plane takes the same spans in its own rows. After declare(); every span and total has to be * whole scale blocks when the plane is 1/128, which head widths of 128 are. */ diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index 0a2d347b..4a2f4bdf 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -320,8 +320,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c /* arch_splits_ff: the routed experts' width (640 = five fp8 blocks) is split by the plugin * below, by whole blocks and parity, at any world up to the block count -- three ranks included, - * which 640 does not divide. geom_from must not refuse what the plugin then answers. */ - RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16, /*arch_splits_ff=*/true)); + * which 640 does not divide. geom_from must not refuse what the plugin then answers. + * attn_world_ok: every attention block this plugin declares is rad_block_attn_gated_fp8.h's, + * which serves the smaller attention world of a world the two KV heads do not divide. */ + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16, /*arch_splits_ff=*/true, + /*attn_world_ok=*/true)); Geom& g = m.g; /* Qwen4-Exp's norms are all `x_hat * (1 + w)` -- `Qwen3NextRMSNorm.forward` is diff --git a/core/build/rad_build.h b/core/build/rad_build.h index d434fba7..483126e6 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -151,7 +151,6 @@ public: int weight_shard_span(rad_weight w, int64_t lo, int64_t hi); int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi, const int64_t* total, int n); - int weight_shard_zero(rad_weight w); int kv_group_zero(rad_kvgroup g); /* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index ee8607af..ecda5d6d 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -929,20 +929,18 @@ int Builder::weight_shard_span_parts(rad_weight h, const int64_t* lo, const int6 int Builder::kv_group_zero(rad_kvgroup h) { if (finished_) { err(RAD_E_STATE, "kv_group_zero after declare finished"); return RAD_E_STATE; } if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL; - prog_.kv_groups[h].zero = true; - return RAD_OK; -} - -int Builder::weight_shard_zero(rad_weight h) { - if (finished_) { err(RAD_E_STATE, "weight_shard_zero after declare finished"); return RAD_E_STATE; } - if (h == 0 || h >= prog_.weights.size()) return RAD_E_INVAL; - WeightInfo& w = prog_.weights[h]; - if (w.decl.shard != RAD_SHARD_ROW && w.decl.shard != RAD_SHARD_COL) { - err(RAD_E_INVAL, "weight '%s': a zero share on a weight that is not row- or " - "column-sharded", w.name.c_str()); + /* PAGED GROUPS ONLY. A zero group is one whose rank computes nothing that reads or writes it, + * and a paged group's absence is invisible to the others: they index the shared block table + * and this rank has no shard to index. A linear or conv group carries per-sequence state the + * snapshot store saves and the step clears on every rank, and a zero-sized one would make + * each of those copies a size mismatch. */ + const int kind = prog_.kv_groups[h].decl.kind; + if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) { + err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group that is not paged", + prog_.kv_groups[h].name.c_str()); return RAD_E_INVAL; } - w.shard_zero = true; + prog_.kv_groups[h].zero = true; return RAD_OK; } @@ -1675,11 +1673,6 @@ int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, return B(b)->weight_shard_span_parts(w, lo, hi, total, n); } -int rad_weight_shard_zero(RadBuilder* b, rad_weight w) { - if (!b) return RAD_E_INVAL; - return B(b)->weight_shard_zero(w); -} - int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) { if (!b) return RAD_E_INVAL; return B(b)->kv_group_zero(g); diff --git a/core/config.cpp b/core/config.cpp index b5bfcb49..0d0a6f9b 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -44,15 +44,6 @@ static const Flag g_flags[] = { { "--max-model-len", "N", "context bound; 0 takes the model's training context" }, { "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" }, - /* THE FLAG THAT DECIDES WHETHER MULTI-TURN WORKS, which is more than the split it names. - * The KV side is not just concurrency: prefix caching holds a finished sequence's blocks - * so the next turn can reuse them, so when the pool cannot hold the LIVE SESSIONS the - * cache drops prefixes the next turn wanted and that turn re-prefills its whole context. - * At long contexts that is two orders of magnitude of time-to-first-token, bought back for - * a fraction of a percent of the decode step. See core/mem/prefix.h. */ - { "--expert-vs-cache-ratio", "R", "weights vs KV split of what is claimed (default " - "0.75). The KV side also holds cached prefixes, so " - "too little of it makes every agent turn re-prefill" }, { "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" }, { "--vram-kv-mib", "N", "the paged KV pool; 0 derives it from the card" }, { "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" }, @@ -89,13 +80,14 @@ static const Flag g_flags[] = { " this does NOT make the engine bit-reproducible across\n" " batch positions -- see spec §19" }, { "--checkpoint-interval","N", "linear-attention state checkpoint interval, in tokens" }, - /* TOTAL, NOT PER SEQUENCE. `ck_free_` is one global free list of N slots handed out by - * pop_back (core/mem/kv.cpp), so an operator reading "per sequence" and setting 2 gets + /* TOTAL, NOT PER SEQUENCE. The snapshot store is one pool of N slots for the whole server + * (KVManager::set_checkpoint_store), so an operator reading "per sequence" and setting 2 gets * 2 for the whole server rather than 2 x --max-num-seqs. At the default 8 slots and * 8 sequences that is one snapshot a sequence, which is what an append-only chat wants -- * the next turn's hit lands at the end of the last one. */ { "--checkpoint-slots", "N", "linear-state snapshots retained IN TOTAL (not " - "per sequence); compare against --max-num-seqs" }, + "per sequence), in pinned host memory; compare " + "against --max-num-seqs" }, { "--no-prefix-cache", nullptr, "disable prefix caching" }, { "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff " "(default), tip-only, keep-all" }, @@ -389,16 +381,6 @@ int config_parse(int argc, char** argv, Config* c) { } c->kv_cache_dtype = v; } - else if (S("--expert-vs-cache-ratio")) { - if (!(v = need(i))) return RAD_E_INVAL; - c->expert_cache_ratio = atof(v); - if (!(c->expert_cache_ratio > 0.0 && c->expert_cache_ratio < 1.0)) { - RAD_ERR("--expert-vs-cache-ratio is the WEIGHTS share of what is claimed and must " - "be strictly between 0 and 1, not '%s'. 0.75 gives three quarters to " - "weights and a quarter to the KV cache.", v); - return RAD_E_INVAL; - } - } else if (S("--host-pool-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->host_pool_mib = atoll(v); } else if (S("--embedding-placement") || S("--ngram-placement")) { const bool emb = S("--embedding-placement"); diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index 2696df22..18a5303a 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -117,14 +118,17 @@ const char* device_backend_name() { return dev()->name; } * RADIANCE_TRACE_ALLOC=N logs every allocation of at least N bytes as it happens. That is the * instrument; the counters are the summary. * - * RADIANCE_POISON_ALLOC=B fills every fresh DEVICE allocation with byte B (0..255) before it is - * handed out, so a buffer that is read before anything wrote it shows up as garbage rather than - * as the zeros a wiped card hands back by luck. A card that has just been through a driver reset - * ("VRAM is lost") is that garbage for real, which is where such a read is otherwise first seen. - * RADIANCE_POISON_RANGE=lo:hi narrows the fill to device allocations with ordinal in [lo, hi) -- - * ordinals count from 1 in allocation order ON THE ALLOCATING THREAD, the `#n on this thread` the - * trace prints -- to bisect to the one allocation that matters. Both are debug knobs: the fill is synchronous and costs a stream a - * call. */ + * RADIANCE_DEBUG_POISON_ALLOC=B fills every fresh DEVICE allocation with byte B (0..255) before + * it is handed out, so a buffer that is read before anything wrote it shows up as garbage rather + * than as the zeros a wiped card hands back by luck. A card that has just been through a driver + * reset ("VRAM is lost") is that garbage for real, which is where such a read is otherwise first + * seen. A correct engine serves the same output with it set. RADIANCE_DEBUG_POISON_RANGE=lo:hi + * narrows the fill to device allocations with ordinal in [lo, hi) -- ordinals count from 1 in + * allocation order ON THE ALLOCATING THREAD, the `#n on this thread` the trace prints -- to bisect + * to the one allocation that matters. Both are instruments: the fill is synchronous, through one + * stream per thread and device that lives until exit (a stream is a hardware queue, and creating + * and destroying one per allocation is both slow and the queue churn ROCr's Trim path faults on). + * A byte outside 0..255 or a range that does not parse is refused at the first allocation. */ namespace rad { namespace { @@ -152,10 +156,15 @@ int64_t trace_floor() { /* -1 when off; otherwise the byte. */ int poison_byte() { static const int v = [] { - const char* e = std::getenv("RADIANCE_POISON_ALLOC"); + const char* e = std::getenv("RADIANCE_DEBUG_POISON_ALLOC"); if (!e || !*e) return -1; - const long x = std::atol(e); - return (x >= 0 && x <= 255) ? (int)x : 255; + char* end = nullptr; + const long x = std::strtol(e, &end, 0); + if (*end || x < 0 || x > 255) { + RAD_ERR("RADIANCE_DEBUG_POISON_ALLOC=%s is not a byte (0..255)", e); + std::abort(); + } + return (int)x; }(); return v; } @@ -163,9 +172,12 @@ int poison_byte() { /* [lo, hi) over device-allocation ordinals; the whole run when unset. */ bool poison_in_range(int64_t ordinal) { static const std::pair r = [] { - const char* e = std::getenv("RADIANCE_POISON_RANGE"); + const char* e = std::getenv("RADIANCE_DEBUG_POISON_RANGE"); long long lo = 0, hi = INT64_MAX; - if (e && *e && std::sscanf(e, "%lld:%lld", &lo, &hi) < 1) { lo = 0; hi = INT64_MAX; } + if (e && *e && (std::sscanf(e, "%lld:%lld", &lo, &hi) != 2 || lo < 0 || hi <= lo)) { + RAD_ERR("RADIANCE_DEBUG_POISON_RANGE=%s is not lo:hi with 0 <= lo < hi", e); + std::abort(); + } return std::make_pair((int64_t)lo, (int64_t)hi); }(); return ordinal >= r.first && ordinal < r.second; @@ -400,7 +412,14 @@ using rad::dev; extern "C" { int rad_dev_count(void) { return dev()->count(); } -int rad_dev_set(int device) { return dev()->set(device); } +/* The device this thread last selected, for the poison fill's stream (rad_dev_alloc). */ +static thread_local int t_device = 0; +static thread_local std::map t_poison_stream; +int rad_dev_set(int device) { + const int st = dev()->set(device); + if (st == RAD_OK) t_device = device; + return st; +} int rad_dev_props(int device, RadDeviceProps* o) { return dev()->props(device, o); } int rad_dev_enable_peer(int self, int peer) { return dev()->enable_peer(self, peer); } @@ -424,16 +443,15 @@ void* rad_dev_alloc(int64_t bytes, int kind) { * holds on both backends; synchronous, so the bytes are there before the caller sees p. */ const int poison = rad::poison_byte(); if (poison >= 0 && kind == RAD_MEM_DEVICE && rad::poison_in_range(ordinal)) { - RadStream s = nullptr; - if (dev()->stream_create(&s, 0) == RAD_OK) { - if (dev()->memset_async(p, poison, bytes, s) != RAD_OK || dev()->stream_sync(s) != RAD_OK) - RAD_WARN("poison: device allocation #%lld (%s) was not filled", - (long long)ordinal, rad::humanb(bytes).c_str()); - else if (floor_ >= 0 && bytes >= floor_) - RAD_INFO("poison: device allocation #%lld filled with 0x%02x", (long long)ordinal, - poison); - dev()->stream_destroy(s); - } + RadStream& s = t_poison_stream[t_device]; + if (!s && dev()->stream_create(&s, 0) != RAD_OK) s = nullptr; + if (!s || dev()->memset_async(p, poison, bytes, s) != RAD_OK || + dev()->stream_sync(s) != RAD_OK) + RAD_WARN("poison: device allocation #%lld (%s) was not filled", + (long long)ordinal, rad::humanb(bytes).c_str()); + else if (floor_ >= 0 && bytes >= floor_) + RAD_INFO("poison: device allocation #%lld filled with 0x%02x", (long long)ordinal, + poison); } } return p; diff --git a/core/engine.cpp b/core/engine.cpp index 76283672..ec45fa60 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -651,13 +651,13 @@ int Engine::step_loop() { } /* THE RECURRENT HALF OF A PREFIX HIT, restored BEFORE the step that reads it. The adopted - * blocks carry the attention layers; this carries the recurrent ones. Enqueued on each - * rank's own stream ahead of the release, so it is ordered before the kernels without a - * synchronisation -- the same way collect_step's readback is ordered after them. + * blocks carry the attention layers; this carries the recurrent ones, copied out of the + * snapshot's slot in host memory. Enqueued on each rank's own stream ahead of the + * release, so it is ordered before the kernels without a synchronisation -- the same way + * collect_step's readback is ordered after them. * - * UNDER THE SCHEDULER'S LOCK, because it reads the sequence table and backs checkpoint - * slots in rank 0's manager, which an HTTP thread's cancel mutates under that lock. Taken - * only on a step that has a restore in it. */ + * UNDER THE SCHEDULER'S LOCK, because it reads the sequence table, which an HTTP thread's + * cancel mutates under that lock. Taken only on a step that has a restore in it. */ bool any_restore = false; for (const StepEntry& e : plan.e) if (e.ckpt_restore >= 0) { any_restore = true; break; } if (any_restore) { @@ -666,12 +666,7 @@ int Engine::step_loop() { if (e.ckpt_restore < 0) continue; if (!state_slots_of(e.seq, &ckpt_slots_)) continue; for (auto& rk : ranks_) { - /* THIS RANK'S DEVICE, BECAUSE THE COPY MAY HAVE TO MAP MEMORY FIRST. A - * checkpoint slot is backed by the rank that writes it - * (KVManager::back_checkpoint), and a commit must land on the card whose pool - * it backs -- a commit on card 0 mapped into rank 1's range succeeds, grants - * access to the wrong card, and rank 1's next kernel faults on a page that is - * present somewhere else. */ + /* This rank's device, for its own stream and its own state slots. */ if (ranks_.size() > 1) (void)rad_dev_set(rk->device); const int s = rk->kv.checkpoint_restore(ckpt_slots_.data(), (int)ckpt_slots_.size(), @@ -759,8 +754,9 @@ int Engine::step_loop() { /* AND THE SNAPSHOT, taken AFTER the step that produced the state. The chunker split this * chunk so its last token IS the checkpoint position, so what copy 0 holds now is exactly - * the state at that position. It is issued before collect_step's readback synchronises, so - * the copy overlaps whatever is left of the step rather than adding to it. + * the state at that position. It is a copy across the link into the snapshot's slot in host + * memory, issued before collect_step's readback synchronises and ahead of any step issued + * behind this one, which is what orders the next write of the state after it. * * Under the scheduler's lock for the reason the restore above is, and only on a step that * writes a checkpoint. */ @@ -773,8 +769,6 @@ int Engine::step_loop() { if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue; if (!state_slots_of(e.seq, &ckpt_slots_)) continue; for (auto& rk : ranks_) { - /* THIS RANK'S DEVICE, for the reason the restore gives: the copy may have to - * back the slot first, and the pages belong on this rank's card. */ if (ranks_.size() > 1) (void)rad_dev_set(rk->device); const int s = rk->kv.checkpoint_save(ckpt_slots_.data(), (int)ckpt_slots_.size(), @@ -1147,15 +1141,8 @@ void Engine::loan_tick(bool idle) { const auto lk = sched_.hold(); Rank& lead = *ranks_[0]; - /* A FINISHED CONVERSATION'S VRAM GOES FIRST, when the slabs have a use for it. An entry whose - * host copy has landed loses nothing by leaving -- a return restores it from host memory -- - * so while any slab has slots the loan does not yet cover, every such entry is released and - * its blocks count toward what the cache can spare below. Past that point the VRAM would sit - * empty in the slab, and the entries stay where a return finds them for free. */ - int64_t ceiling = 0; - for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV)); - if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean(); - + /* A FINISHED CONVERSATION'S VRAM IS ALREADY FREE by the time this runs: tier_tick gives up + * every entry whose host copy has landed, so what the cache can spare below counts it. */ /* WHAT THE CACHE CAN DO WITHOUT, AND WHAT THE SLABS STILL OCCUPY. A loan grows as soon as the * cache can spare it -- the slots are filled on the next dispatch or the next idle tick -- but * only by at least a prefill chunk, so a cache breathing by a few blocks does not have its @@ -1296,14 +1283,20 @@ void Engine::tier_tick() { { TierIO::Fetch f; while (P.io.take_fetch(&f)) { - for (size_t i = 0; i < f.fences.size() && i < ranks_.size(); ++i) { - if (!f.fences[i]) continue; - (void)rad_dev_set(ranks_[i]->device); - rad_event_destroy(f.fences[i]); - } - if (ranks_.size() > 1) (void)rad_dev_set(lead.device); + destroy_fences(f.fences); const auto lk = sched_.hold(); lead.tierx.report_pass(f.jobs, f.ok, now); + /* A SNAPSHOT READ BACK INTO ITS SLOT goes to the cache's index entry, which the lookup + * then serves. One whose entry went while the read was out has nothing to land in, and + * the record must not go on naming a slot the store will hand to somebody else. */ + for (const TierJob& j : f.jobs) { + if (!j.ck_want || j.ck_slot < 0 || !lead.tiers.snapshot_in_slot(j.key, j.ck_slot)) + continue; + if (lead.prefix.reattach_snapshot(j.key, j.ck_slot) != RAD_OK) { + lead.tiers.snapshot_detached(j.key); + lead.kv.free_checkpoint(j.ck_slot); + } + } P.waiting.erase(std::remove(P.waiting.begin(), P.waiting.end(), f.tag), P.waiting.end()); } } @@ -1312,7 +1305,9 @@ void Engine::tier_tick() { { std::vector jobs; std::vector ok; - if (P.io.take(&jobs, &ok)) { + std::vector fences; + if (P.io.take(&jobs, &ok, &fences)) { + destroy_fences(fences); const auto lk = sched_.hold(); lead.tierx.report_pass(jobs, ok, now); } @@ -1334,6 +1329,22 @@ void Engine::tier_tick() { } } + /* ---- what is not live leaves VRAM -------------------------------------------------------- */ + /* AS SOON AS ITS COPY HAS LANDED, WHILE THE EXPERT SLAB HAS A USE FOR THE BLOCKS. An entry no + * running sequence reads and whose host copy is in place costs nothing to give up -- a later + * turn restores it in a copy -- and its blocks are lent to the slab. With no lender, or a slab + * whose loan already covers every slot it has, the blocks would sit empty in the pool, so the + * entry stays where the next turn finds it for free; a request that needs the room takes it + * through trim, which drops the same entries on demand. + * + * NOT THE SNAPSHOTS: they are in host memory already and hold no VRAM. */ + if (lending_) { + int64_t ceiling = 0; + for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV)); + const auto lk = sched_.hold(); + if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean(); + } + /* ---- the slow half ---------------------------------------------------------------------- */ /* AS SOON AS A DISK COPY IS WAITING, not on the clock: until it lands, the entry's host slot * cannot be given up for nothing, and a full arena is then a restore that cannot read through @@ -1343,7 +1354,25 @@ void Engine::tier_tick() { tier_last_ns_ = now; std::vector jobs; lead.tiers.plan(P.slow_budget, &jobs); - if (!jobs.empty() && !P.io.submit(std::move(jobs))) { + /* A SNAPSHOT'S SLOT IS FILLED BY A COPY ON THE COMPUTE STREAM, issued after the step that + * produced the state and before the cache was told of it; the write waits for that copy to + * land, and every one of its kind is behind this mark. */ + bool snaps = false; + for (const TierJob& j : jobs) snaps = snaps || j.ck_slot >= 0; + int fst = RAD_OK; + std::vector fences = snaps ? rank_fences(false, true, &fst) + : std::vector{}; + /* A mark that could not be made leaves nothing to order the write by: the batch is + * reported failed, and every record keeps what it had. */ + if (fst != RAD_OK) { + destroy_fences(fences); + const std::vector ok(jobs.size(), 0); + const auto lk = sched_.hold(); + lead.tierx.report_pass(jobs, ok, now); + return; + } + if (!jobs.empty() && !P.io.submit(std::move(jobs), std::move(fences))) { + destroy_fences(fences); /* The thread is not running -- no disk tier -- and a plan without one holds only drops, * which move nothing. They are reported here. */ std::vector ok(jobs.size(), 1); @@ -1353,6 +1382,74 @@ void Engine::tier_tick() { } } +std::vector Engine::rank_fences(bool transfer, bool compute, int* st) { + std::vector out; + int rc = RAD_OK; + for (int pass = 0; pass < 2; ++pass) { + if ((pass == 0 && !transfer) || (pass == 1 && !compute)) continue; + for (auto& r : ranks_) { + RadEvent e = nullptr; + const int s = r->tierx.fence(&e, pass == 1 ? r->ctx.stream() : nullptr); + if (s != RAD_OK && rc == RAD_OK) rc = s; + out.push_back(e); + } + } + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + if (st) *st = rc; + return out; +} + +void Engine::destroy_fences(std::vector& f) { + for (size_t i = 0; i < f.size(); ++i) { + if (!f[i]) continue; + (void)rad_dev_set(ranks_[i % ranks_.size()]->device); + rad_event_destroy(f[i]); + } + f.clear(); + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); +} + +bool Engine::flush_copies() { + if (!pump_ || !ranks_[0]->tierx.enabled()) return false; + TierPump& P = *pump_; + Rank& lead = *ranks_[0]; + bool landed = false; + const uint64_t t0 = rad_mono_ns(); + /* Counted only when something was in flight or waiting: a call that found nothing to land + * stalled nobody. */ + struct Note { + IdleTiers& t; uint64_t t0; bool worked = false; + ~Note() { if (worked) t.note_flush((int64_t)(rad_mono_ns() - t0)); } + } note{lead.tiers, t0}; + /* BOUNDED: each round lands one batch of P.max_copy entries, and a pool short of more than + * that many rounds' worth is a pool the tiers cannot relieve in one step. */ + for (int round = 0; round < 64; ++round) { + if (!P.copy.empty()) { + note.worked = true; + bool good = true; + for (size_t i = 0; i < ranks_.size(); ++i) { + if (P.copy_st[i] == 0) P.copy_st[i] = ranks_[i]->tierx.wait_copy(); + if (P.copy_st[i] < 0) good = false; + } + if (ranks_.size() > 1) (void)rad_dev_set(lead.device); + const std::vector ok(P.copy.size(), good ? 1 : 0); + lead.tierx.report_pass(P.copy, ok, rad_mono_ns()); + P.copy.clear(); + landed = landed || good; + } + if (!lead.tiers.writeback_waiting()) break; + lead.tiers.plan_writeback(P.max_copy, &P.copy); + if (P.copy.empty()) break; + P.copy_st.assign(ranks_.size(), 0); + for (size_t i = 0; i < ranks_.size(); ++i) { + const int st = ranks_[i]->tierx.issue_copy(P.copy, ranks_[i]->ctx.stream()); + if (st < 0) P.copy_st[i] = st; + } + if (ranks_.size() > 1) (void)rad_dev_set(lead.device); + } + return landed; +} + /* HAND A READ OFF DISK TO THE IO THREAD, fenced on every rank's transfer stream: the slots it * writes may have been given up by entries a restore is still copying out of. False when it could * not be handed over, and then the reads are reported unstarted -- the records stay on disk and the @@ -1362,25 +1459,20 @@ bool Engine::submit_fetch(uint64_t tag, std::vector&& jobs) { TierIO::Fetch f; f.tag = tag; f.jobs = std::move(jobs); + /* THE TRANSFER STREAMS, for the restores that read block slots, and THE COMPUTE STREAMS when a + * snapshot comes in: its store slot may have been given up by a snapshot a restore on that + * stream is still copying out of. */ + bool snap = false; + for (const TierJob& j : f.jobs) snap = snap || (j.ck_want && j.ck_slot >= 0); int st = RAD_OK; - for (auto& r : ranks_) { - RadEvent e = nullptr; - if (st == RAD_OK) st = r->tierx.fence(&e); - f.fences.push_back(e); - } - if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + f.fences = rank_fences(true, snap, &st); if (st == RAD_OK && P.io.submit_fetch(std::move(f))) { P.waiting.push_back(tag); return true; } RAD_ERR("kv tiers: a read off disk could not be handed to the IO thread (%s); the request is " "admitted with what host memory holds", st < 0 ? rad_strerror(st) : "not running"); - for (size_t i = 0; i < f.fences.size(); ++i) { - if (!f.fences[i]) continue; - (void)rad_dev_set(ranks_[i]->device); - rad_event_destroy(f.fences[i]); - } - if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + destroy_fences(f.fences); const std::vector ok(f.jobs.size(), 0); ranks_[0]->tierx.report_pass(f.jobs, ok, rad_mono_ns()); return false; @@ -1408,11 +1500,12 @@ int Engine::serve() { } /* The scheduler drives ONE block manager. Block ids are pure bookkeeping and identical on - * every rank -- the heads divide equally, so every rank's pool has the same geometry and its - * free list evolves identically. What differs per rank is the pool BASE, and that lives in - * KVPoolBinding. So rank 0's manager owns the bookkeeping and the others exist to own their - * own card's allocation. If the geometries ever disagree the block tables mean different - * things on different cards, so it is checked rather than assumed. */ + * every rank: every rank carves the same block count (Engine::configure_kv caps each at the + * least rank's), so its free list evolves identically even where the ranks' shares of a + * group differ in bytes, or are zero (rad_kv_group_zero). What differs per rank is the pool + * BASE, and that lives in KVPoolBinding. So rank 0's manager owns the bookkeeping and the + * others exist to own their own card's allocation. If the counts ever disagree the block + * tables mean different things on different cards, so it is checked rather than assumed. */ for (size_t i = 1; i < ranks_.size(); ++i) { const auto& a = ranks_[0]->kv.plans(); const auto& c = ranks_[i]->kv.plans(); @@ -1452,12 +1545,9 @@ int Engine::serve() { /* CALLED FROM INSIDE Scheduler::step(), UNDER ITS LOCK -- which is what makes it safe to * touch the cache and rank 0's manager here, and why nothing below may call back into the * scheduler. */ - /* A restored session's state needs a device checkpoint slot, and which snapshot gives - * one up is the cache's decision: it knows which ones a lookup this step handed out. */ - ranks_[0]->tierx.set_checkpoint_room( - [this] { return ranks_[0]->prefix.free_checkpoint_for_restore(); }); b->restore_fn = [this](const Request& req) -> IPrefixCache::Restore { using R = IPrefixCache::Restore; + const uint64_t t0 = rad_mono_ns(); PrefixCache& pc = ranks_[0]->prefix; TierPump& P = *pump_; if (std::find(P.waiting.begin(), P.waiting.end(), req.id) != P.waiting.end()) @@ -1468,13 +1558,27 @@ int Engine::serve() { const std::vector want = pc.restorable_from(req.prompt, mk, &chain); /* THE DISK PART IS READ FIRST, ON THE IO THREAD, while this request waits and every * other one runs; the restore below then copies host memory and nothing else. Asked - * only when something could be on disk or in flight: a chain wholly in VRAM is the - * common case, and it is thousands of keys. */ - if (!want.empty() || !P.waiting.empty()) { + * on every attempt, because a chain wholly in VRAM can still want a read: its deepest + * snapshot may have given its store slot up and be on disk alone. + * + * THAT SNAPSHOT NEEDS A STORE SLOT TO LAND IN, and the store's free list is rank 0's + * manager's: one is taken here -- making room by detaching a snapshot the disk also + * holds, which is the cache's choice -- and handed to the plan, which gives it back + * when it does not read the snapshot after all. */ + { std::vector reads; - if (ranks_[0]->tiers.plan_fetch(chain, &reads, rad_mono_ns())) { - if (reads.empty() || submit_fetch(req.id, std::move(reads))) return R::Wait; + int32_t ck = -1; + if (ranks_[0]->tiers.snapshot_fetch_wanted(chain) && + ranks_[0]->kv.alloc_checkpoint(&ck) != RAD_OK) { + ck = -1; + if (pc.free_checkpoint_for_restore() && + ranks_[0]->kv.alloc_checkpoint(&ck) != RAD_OK) + ck = -1; } + const bool wait = ranks_[0]->tiers.plan_fetch(chain, &reads, rad_mono_ns(), &ck); + if (ck >= 0) ranks_[0]->kv.free_checkpoint(ck); + if (wait && (reads.empty() || submit_fetch(req.id, std::move(reads)))) + return R::Wait; } if (want.empty()) return R::Done; /* THE WHOLE CHAIN IN ONE RESTORE. A 4-token block makes a long conversation tens of @@ -1513,22 +1617,20 @@ int Engine::serve() { * them too, and would be released later from under whoever the pool gives them * to. Both are let go, so the blocks return to the pool and the key is simply * unknown. */ + ranks_[0]->tierx.quiesce(); for (size_t k = 0; k < cg.size() && k < j.blocks.size(); ++k) if (j.blocks[k] >= 0) ranks_[0]->kv.release_block(cg[k], j.blocks[k]); ranks_[0]->tiers.forget(j.key); - if (j.ck_dev >= 0) ranks_[0]->kv.free_checkpoint(j.ck_dev); - continue; } - /* AND THE RECURRENT HALF, into the slot the restore allocated for it. Without this - * the session gets its attention hit back and replays every linear layer from - * token zero, which on a long transcript is most of a prefill. NOBODY ELSE OWNS - * THAT SLOT UNTIL THE CACHE TAKES IT: if the index entry the snapshot belongs to - * was retired, the slot has no path back to the free list. */ - if (j.ck_dev >= 0 && pc.reattach_snapshot(j.key, j.ck_dev) != RAD_OK) - ranks_[0]->kv.free_checkpoint(j.ck_dev); } + ranks_[0]->tiers.note_restore((int64_t)(rad_mono_ns() - t0)); return R::Done; }; + /* AN EVICTION THAT WOULD LOSE AN ENTRY WAITS FOR ITS COPY INSTEAD. Called by the + * prefix cache binding under the scheduler's lock, on this thread, when dropping the + * entries that already have a host copy did not free enough: every copy waiting is + * planned, issued and landed now, so the entries it covers can leave VRAM and be kept. */ + b->flush_fn = [this]() -> bool { return flush_copies(); }; } /* EVERY RANK'S CARD, STREAM AND ARENA. The batch is one build shared by pointer (spec §1) and * that is right for the host side; the DEVICE side is staged per rank, because a rank reading @@ -1539,10 +1641,6 @@ int Engine::serve() { for (auto& rk : ranks_) rio.push_back({ rk->device, rk->ctx.stream(), &rk->program }); RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_)); - /* The step staging the budget kept room for exists now, so a checkpoint slot backed from here - * on leaves the headroom and only what is still to be built on first use. */ - set_checkpoint_floors(std::max(cfg_.gpu_headroom_mib, 0) * (1ll << 20) + - late_lazy_bytes_); for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get()); diff --git a/core/engine.h b/core/engine.h index d16a8575..fb8ad826 100644 --- a/core/engine.h +++ b/core/engine.h @@ -22,6 +22,7 @@ #pragma once #include "rad_core.h" #include "build/startup.h" +#include "mem/hostarena.h" #include "sched/mem_iface.h" #include "sched/scheduler.h" #include "sample/vocab_view.h" @@ -121,7 +122,8 @@ private: /* --embedding-placement and --ngram-placement, resolved into Config before the card is split * (engine_bringup.cpp says how auto chooses). */ int resolve_table_placement(const std::vector& facts, - const std::vector& emb_bytes, int64_t kv_floor, + const std::vector& emb_bytes, + const std::vector& floor_emb_ram, int64_t kv_floor, int64_t ngram_bytes, bool ngram_device, bool ngram_host); /* --ngram-placement ram: the copy of the container's [src, src + n), file offset `foff`, made * once and shared by every rank -- locked for the host gather, or pinned for a device kernel @@ -306,6 +308,15 @@ private: * and the scheduler's lock is held only around the bookkeeping. */ void tier_tick(); bool submit_fetch(uint64_t tag, std::vector&& jobs); + /* A MARK ON EVERY RANK'S STREAMS, for the disk thread to wait on before it touches a slot: + * the transfer streams' when `transfer`, the compute streams' when `compute`, in that order, + * one a rank each; `st` is the first failure to make one. destroy_fences gives them back on + * their own cards. */ + std::vector rank_fences(bool transfer, bool compute, int* st = nullptr); + void destroy_fences(std::vector& f); + /* Every host copy that is waiting, issued and landed now. Under the scheduler's lock, from an + * eviction that would otherwise erase what the copies cover. True when any landed. */ + bool flush_copies(); uint64_t tier_last_ns_ = 0; /* THE LOAN: what the KV cache is not using, lent to every rank's expert slab at the addresses * the cache already owns (KVManager, the loan block). Here rather than inside the scheduler @@ -327,19 +338,16 @@ private: int64_t arena_floor_ = 0; int64_t arena_last_ = 0; uint64_t arena_floor_ns_ = 0; - /* WHETHER THIS DRIVER RETURNS DECOMMITTED VRAM TO THE CARD, for the checkpoint slots -- the - * one part of the KV pool still backed on demand. Measured once at the end of bringup; it is - * not something the API promises. */ - bool release_frees_card_ = true; /* WHAT THE VRAM BUDGET KEPT FOR ALLOCATIONS MADE AFTER start(), on top of --gpu-headroom-mib: * the step batch's staging, which serve() allocates, and what is built on first use, if - * ever -- the KV tiers' copy staging and the second compute lane's queue. The checkpoint - * slots backed at the end of bringup leave both free, and the bringup's closing reading is - * checked against both. */ + * ever -- the KV tiers' copy staging and the second compute lane's queue. The bringup's + * closing reading is checked against both. */ int64_t late_step_bytes_ = 0; int64_t late_lazy_bytes_ = 0; - /* Every rank's checkpoint floor: a slot is backed only while the card keeps `keep` free. */ - void set_checkpoint_floors(int64_t keep); + /* THE LINEAR-STATE SNAPSHOT STORE: pinned host memory, --checkpoint-slots slots, each holding + * every rank's shard of one snapshot (KVManager::set_checkpoint_store). Not on the card: a + * snapshot is read by no kernel, only copied back into a sequence's state. */ + HostArena ck_store_; int run_server(); /* THE KL MODE (core/kld.h), in place of run_server: the corpus's documents submitted as * scoring requests, and every step's scored rows copied to the host and handed to `kld_`. diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index baf0b3d7..08f7896e 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -438,7 +438,8 @@ bool Engine::ngram_gather_to_host() { * RAM's is lockable_room's -- the memory and every cgroup after the pools still to be allocated, * and the memlock limit for a locked copy. */ int Engine::resolve_table_placement(const std::vector& facts, - const std::vector& emb_bytes, int64_t kv_floor, + const std::vector& emb_bytes, + const std::vector& floor_emb_ram, int64_t kv_floor, int64_t ngram_bytes, bool ngram_device, bool ngram_host) { const int64_t MiB = (int64_t)1 << 20; int64_t emb_max = 0; @@ -501,9 +502,13 @@ int Engine::resolve_table_placement(const std::vector& facts, auto card_holds = [&](std::string* why) { std::vector with = facts; int64_t fixed = 0; - for (VramFacts& f : with) { + for (size_t i = 0; i < with.size(); ++i) { + VramFacts& f = with[i]; f.statics += ngram_bytes; - if (emb == TablePlacement::Ram) f.statics -= emb_max; + if (emb == TablePlacement::Ram) { + f.statics -= emb_max; + f.expert_floor = floor_emb_ram[i]; + } fixed = std::max(fixed, f.statics); } /* `fixed` and not the trial's own statics: the split clamps those to what the card can give @@ -511,12 +516,21 @@ int Engine::resolve_table_placement(const std::vector& facts, VramBudget tb; const int st = vram_budget_trial(cfg_, with, &tb); const bool over = st == RAD_OK && fixed >= tb.claimable; - if (st == RAD_OK && !over && (!tb.derived_kv || tb.kv >= kv_floor)) return true; + /* AND THE EXPERTS KEEP A TIER: where the cache lends, those the host pool cannot hold have + * only the card, and a table that took their room would leave them nowhere. */ + const bool starved = st == RAD_OK && tb.lends && tb.expert_ceiling > 0 && + tb.experts < tb.expert_floor; + if (st == RAD_OK && !over && !starved && (!tb.derived_kv || tb.kv >= kv_floor)) + return true; if (st != RAD_OK) *why = "the card cannot hold the other weights with it"; else if (over) *why = fmt("with it the fixed weights want %s of a card that has %s to give", humanb(fixed).c_str(), humanb(tb.claimable).c_str()); + else if (starved) + *why = fmt("with it on the card the experts get %s, short of the %s the pinned host " + "pool cannot hold", humanb(tb.experts).c_str(), + humanb(tb.expert_floor).c_str()); else *why = fmt("with it on the card the KV pool is %s, short of the %s one " "--max-model-len sequence needs", humanb(tb.kv).c_str(), @@ -1064,6 +1078,7 @@ int Engine::plan() { /* The placement flags' tables, per rank where they are sharded (the embedding) and once * where they are not (the n-gram table every rank reads from the one mapping). */ std::vector emb_bytes; + std::vector wfs; int64_t ngram_bytes = 0, kv_floor = 0; bool ngram_device = false, ngram_host = false; const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; @@ -1106,6 +1121,12 @@ int Engine::plan() { weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk); f.statics = wf.statics; f.experts = wf.experts; + /* The expert floor waits for the tables' placement: the embedding may take its share + * of the host pool first. */ + wfs.push_back(wf); + /* THE CACHE LENDS where units move and the pool can give its blocks back in place. */ + f.lends = VMem::supported() && !cfg_.deterministic && + (cfg_.placement == "auto" || cfg_.placement == "expert_tiered"); emb_bytes.push_back(wf.embedding); ngram_bytes = std::max(ngram_bytes, wf.ngram); ngram_device = ngram_device || wf.ngram_device; @@ -1118,8 +1139,10 @@ int Engine::plan() { Config one = cfg_; one.max_seqs = 1; KVManager single; - if (single.plan_groups(r->program.kv_groups, one) == RAD_OK) + if (single.plan_groups(r->program.kv_groups, one) == RAD_OK) { kv_floor = std::max(kv_floor, single.ceiling(ctx)); + f.kv_one = single.ceiling(ctx); + } } /* THE STAGING REGION IS SIZED ONLY WHERE THE ARENA LENDS ITS TOP: with no smaller level * nothing gives the region back to the slab at decode, and a deterministic plan moves @@ -1167,13 +1190,28 @@ int Engine::plan() { late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy); facts.push_back(f); } - RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device, - ngram_host)); + /* THE PINNED HOST POOL IS THE EXPERTS' OTHER HOME, less what Planner::plan takes out of it + * before any expert: the embedding when it is placed there, and the file tier's staging. + * Both floors are known before the tables are placed, so placing them can ask whether the + * experts would still have a tier. */ + std::vector floor_emb_ram(facts.size(), 0); + for (size_t i = 0; i < facts.size(); ++i) { + int64_t room = cfg_.host_pool_mib * ((int64_t)1 << 20); + if (cfg_.weights_disk_tier) + room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed); + facts[i].expert_floor = expert_vram_floor(wfs[i], std::max(room, 0)); + floor_emb_ram[i] = expert_vram_floor(wfs[i], std::max(room - emb_bytes[i], 0)); + } + RAD_TRY(resolve_table_placement(facts, emb_bytes, floor_emb_ram, kv_floor, ngram_bytes, + ngram_device, ngram_host)); /* The n-gram table was counted off the card; on it, it is every rank's whole table. */ if (cfg_.ngram_resolved == TablePlacement::Vram) for (VramFacts& f : facts) f.statics += ngram_bytes; if (cfg_.embedding_resolved == TablePlacement::Ram) - for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i]; + for (size_t i = 0; i < facts.size(); ++i) { + facts[i].statics -= emb_bytes[i]; + facts[i].expert_floor = floor_emb_ram[i]; + } VramBudget vb; RAD_TRY(vram_budget_resolve(cfg_, facts, &vb)); if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str()); @@ -2002,10 +2040,6 @@ static int fill_from_checkpoint(const CkptWeight& cw, const std::vectorprogram; sw.wi = i; @@ -2351,17 +2382,9 @@ int Engine::load_weights() { std::vector sel(w.sel, w.sel + w.n_sel); std::vector offs(sw.plane_off, sw.plane_off + w.n_sel); const std::string name = w.name; - if (zero_share) { - const int64_t bytes = in_bytes; - sw.fill = [bytes](uint8_t* in) -> int { - std::memset(in, 0, (size_t)bytes); - return RAD_OK; - }; - } else { - sw.fill = [cw, shares, sel, offs, name](uint8_t* in) -> int { - return fill_from_checkpoint(*cw, shares, sel, offs, name, in); - }; - } + sw.fill = [cw, shares, sel, offs, name](uint8_t* in) -> int { + return fill_from_checkpoint(*cw, shares, sel, offs, name, in); + }; staged.push_back(std::move(sw)); ++n_loaded; continue; @@ -2447,16 +2470,6 @@ int Engine::load_weights() { const auto rt0 = std::chrono::steady_clock::now(); int sw_st = RAD_OK; if (file_) { - /* A WEIGHT WITH NO BYTES IN THE FILE -- a zero share -- is one the sweep never reaches: no - * run of the container is its source, so nothing would ever arrive for it and its worker - * would never run. It is handed to the workers here, whole, and its own fill writes it - * (the checkpoint branch below does the same for every weight, which is why the hole was - * never seen there). */ - for (size_t k = 0; k < staged.size() && !pool.failed(); ++k) - if (staged[k].fill) { - pool.reserve((int)k); - pool.arrived((int)k, staged[k].remaining); - } sw_st = sweep_container(file_.get(), runs, devices, &pool, &read_bytes); } else { /* every weight to the workers, in declaration order, as fast as the budget lets them in */ @@ -2542,6 +2555,7 @@ int Engine::configure_kv() { LogRank lr(r->index); RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_)); const int64_t t = r->kv.paged_tokens(r->pools.kv().avail()); + if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */ if (least < 0 || t < least) least = t; } for (auto& r : ranks_) { @@ -2549,7 +2563,7 @@ int Engine::configure_kv() { RAD_TRY(rad_dev_set(r->device)); /* allocates on the CURRENT device; see plan() */ if (ranks_.size() > 1) { const int64_t own = r->kv.paged_tokens(r->pools.kv().avail()); - if (own > least) + if (own > least && own != KVManager::kUnboundedTokens) RAD_INFO("kv: rank %d could page %lld tokens and carves %lld, the least rank's, so " "that one block table serves every rank", r->index, (long long)own, (long long)least); @@ -2559,14 +2573,52 @@ int Engine::configure_kv() { /* THE ONE CASE WHERE THE CACHE CANNOT GIVE ANYTHING BACK, said once and named. Every * caller is written against the elastic contract and runs unchanged here -- the pool * simply holds its whole carve -- so nothing fails, and the only symptom is an expert - * plane that never grows and a split that stays where --expert-vs-cache-ratio put it. + * plane that never grows and a split that stays where the budget put it. * That is worth a line, because it is indistinguishable from a working run in every * counter this engine reports. */ if (r->index == 0 && !r->pools.kv().elastic()) RAD_WARN("this device has no virtual memory management, so the KV cache holds its " - "whole carve and the expert slab has nothing to grow into. The split stays " - "where --expert-vs-cache-ratio put it."); + "whole carve and the expert slab has nothing to grow into. The experts were " + "given the card first and the cache one full-length sequence."); if (cfg_.debug_placement) fputs(r->kv.report().c_str(), stderr); + } + + /* ---------------- the linear-state snapshot store ---------------- */ + /* PINNED HOST MEMORY, NOT THE CARD. A snapshot is a copy of a sequence's recurrent state that + * no kernel reads: a save copies the state out after the step that produced it and a hit + * copies it back before the step that resumes from it, each a few milliseconds across the + * link. Holding it in VRAM would charge the KV pool for memory the live cache could use. + * + * One slot holds every rank's shard, each at its own offset, so the disk tier moves a slot as + * one payload; rank 0's manager hands the ids out. Opened only where there is something to + * snapshot and a cache to serve it. */ + { + /* THE SHARDS NEED NOT BE EQUAL: a rank's state holds its own heads of each group, and a + * world the heads do not divide gives the ranks different shares. A slot is the sum of + * the ranks' shards and a rank's starts where the ranks before it end. */ + std::vector shard_off(ranks_.size(), 0); + int64_t slot = 0; + for (size_t i = 0; i < ranks_.size(); ++i) { + shard_off[i] = slot; + slot += ranks_[i]->kv.checkpoint_bytes(); + } + const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0; + if (slot > 0 && n > 0 && cfg_.prefix_cache) { + if (ck_store_.open(slot, slot * n) != RAD_OK) { + RAD_WARN("checkpoint slots: no pinned host memory for %lld snapshot(s) of %s; a " + "hybrid session's prefix hits replay their linear layers from zero. " + "Lower --checkpoint-slots.", (long long)n, humanb(slot).c_str()); + } else { + RAD_INFO("checkpoint slots: %lld linear-state snapshot(s) of %s in pinned host " + "memory (%s), none of it on the card", (long long)n, + humanb(slot).c_str(), humanb(ck_store_.cap_bytes()).c_str()); + } + } + for (auto& r : ranks_) + r->kv.set_checkpoint_store(&ck_store_, shard_off[(size_t)(&r - &ranks_[0])]); + } + for (auto& r : ranks_) { + LogRank lr(r->index); RAD_TRY(r->prefix.configure(cfg_, &r->kv, geo_.checkpoint_interval)); } @@ -2594,23 +2646,19 @@ int Engine::configure_kv() { * at offsets of one entry, as it always was. The sizing below (TierExec::sizes) takes * the largest rank's entry: the staging ring is a rank's own, and the ring that fits * the largest fits every one. */ - std::vector rank_entry(ranks_.size(), 0), rank_ck(ranks_.size(), 0); - std::vector entry_off(ranks_.size(), 0), ck_off(ranks_.size(), 0); - int64_t entry_bytes = 0, slot_bytes = 0, ck_slot_bytes = 0; + std::vector rank_entry(ranks_.size(), 0), entry_off(ranks_.size(), 0); + int64_t entry_bytes = 0, slot_bytes = 0; for (size_t i = 0; i < ranks_.size(); ++i) { for (int32_t g : cg) { const KVGroupPlan* p = ranks_[i]->kv.plan(g); if (p && p->paged()) rank_entry[i] += p->bytes_per_block; } - rank_ck[i] = ranks_[i]->kv.checkpoint_bytes(); entry_off[i] = slot_bytes; - ck_off[i] = ck_slot_bytes; - slot_bytes += rank_entry[i]; - ck_slot_bytes += rank_ck[i]; + slot_bytes += rank_entry[i]; entry_bytes = std::max(entry_bytes, rank_entry[i]); } - /* ---- how the tier is split between the two halves of a session ---- + /* ---- how the disk tier is split between the two halves of a session ---- * * ON THIS BUILD A RESTORED HYBRID SESSION WITH NO SNAPSHOT REUSES NOTHING AT ALL. The * scheduler clamps its reuse to the last reachable checkpoint and says why: RadBatch @@ -2635,8 +2683,12 @@ int Engine::configure_kv() { * * Two thirds is the ceiling. Not because the arithmetic asks for one, but because the * clamp above is a property of THIS build rather than of the design, and a tier with - * almost no room for blocks would be badly sized the day it is lifted. */ - int64_t ck_host_cap = 0, ck_disk_slots = 0; + * almost no room for blocks would be badly sized the day it is lifted. + * + * THE HOST TIER IS NOT SPLIT: snapshots live in the checkpoint store, which + * --checkpoint-slots sizes, and --prefix-cache-host-mib is the blocks' alone. */ + const int64_t ck_slot_bytes = ck_store_.enabled() ? ck_store_.slot_bytes() : 0; + int64_t ck_disk_slots = 0; if (ck_slot_bytes > 0) { const int64_t bs = ranks_[0]->prefix.block_size(); const int64_t iv = ranks_[0]->prefix.checkpoint_interval(); @@ -2649,19 +2701,13 @@ int Engine::configure_kv() { const int64_t sess_blocks = bs > 0 ? (mlen / bs) * slot_bytes : slot_bytes; const int64_t sess_snaps = retained * ck_slot_bytes; const int64_t denom = sess_blocks + sess_snaps; - const int64_t host_cap = cfg_.prefix_cache_host_mib << 20; const int64_t disk_cap = cfg_.prefix_cache_disk_mib << 20; - const int64_t host_ck = std::min(host_cap * 2 / 3, denom > 0 ? host_cap / denom * sess_snaps - + host_cap % denom * sess_snaps / denom - : 0); const int64_t disk_ck = std::min(disk_cap * 2 / 3, denom > 0 ? disk_cap / denom * sess_snaps + disk_cap % denom * sess_snaps / denom : 0); - ck_host_cap = (host_ck / ck_slot_bytes) * ck_slot_bytes; ck_disk_slots = disk_ck / ck_slot_bytes; - /* One of each where there is room for one at all: a tier that holds a session's blocks - * and not one snapshot holds nothing usable. */ - if (ck_host_cap == 0 && host_cap >= ck_slot_bytes * 2) ck_host_cap = ck_slot_bytes; + /* One where there is room for one at all: a tier that holds a session's blocks and not + * one snapshot holds nothing usable. */ if (ck_disk_slots == 0 && disk_cap >= ck_slot_bytes * 2) ck_disk_slots = 1; } if (cg.empty() || entry_bytes <= 0) { @@ -2721,7 +2767,7 @@ int Engine::configure_kv() { tc.disk_cap_bytes = kv_disk_ ? (cfg_.prefix_cache_disk_mib << 20) : 0; tc.entry_bytes = slot_bytes; tc.ckpt_bytes = ck_slot_bytes; - tc.ckpt_cap_bytes = ck_host_cap; + tc.ckpt_slots = ck_store_.capacity(); tc.ckpt_disk_slots = kv_disk_ ? ck_disk_slots : 0; /* THE POLICY IS RANK 0'S AND THE TRANSFER IS EVERY RANK'S. A session is not sharded -- @@ -2774,7 +2820,7 @@ int Engine::configure_kv() { /*leader=*/&r == &ranks_[0], r->device, entry_off[(size_t)(&r - &ranks_[0])], - ck_off[(size_t)(&r - &ranks_[0])], + &ck_store_, /*shared=*/r->mover.transfer_stream()) != RAD_OK) { all = false; @@ -2790,7 +2836,7 @@ int Engine::configure_kv() { T.close(); kv_disk_.reset(); tc.host_cap_bytes = tc.disk_cap_bytes = 0; - tc.ckpt_cap_bytes = tc.ckpt_disk_slots = 0; + tc.ckpt_disk_slots = 0; RAD_TRY(T.configure(tc, nullptr)); } else { /* The tiers can lose an entry without the cache asking: a capacity drop, or a @@ -2799,10 +2845,10 @@ int Engine::configure_kv() { T.set_drop_sink([this](const BlockHash& h) { ranks_[0]->prefix.drop_offdevice(h); }); - /* And the linear half on its own. The snapshot store is far smaller than the - * block store, so it overflows first and by itself; an index entry left - * behind would be a checkpoint the cache goes on offering whose bytes nobody - * holds, which is the recurrent-state form of the same corruption. */ + /* And the linear half on its own: a snapshot whose only copy was on disk and + * that the disk store let go of. An index entry left behind would be a + * checkpoint the cache goes on offering whose bytes nobody holds, which is the + * recurrent-state form of the same corruption. */ T.set_snapshot_drop_sink([this](const BlockHash& h) { ranks_[0]->prefix.drop_snapshot(h); }); @@ -2867,9 +2913,10 @@ int Engine::configure_kv() { * that request is accepted by the API and can never complete, whatever the load. */ RAD_WARN("kv group '%s' holds %lld tokens but the context limit is %lld: ONE request " "longer than %lld tokens is accepted by the API and then refused as too " - "large to ever fit -- this is a hard limit, not a backing ratio. Raise " - "--expert-vs-cache-ratio toward the cache (about %lld MiB more for the whole " - "context), halve the cost a token with --kv-cache-dtype fp8, or lower " + "large to ever fit -- this is a hard limit, not a backing ratio. Give the " + "cache more (about %lld MiB for the whole context: a larger --host-pool-mib " + "takes experts off the card), halve the cost a token with --kv-cache-dtype fp8, " + "or lower " "--max-model-len to %lld.", p->name.c_str(), (long long)cap, (long long)want, (long long)cap, (long long)(((want - cap) / p->block_size * p->bytes_per_block) >> 20), @@ -2938,18 +2985,6 @@ static void bind_kv_pools(const Program& p, const KVManager& kv, std::vectordevice; - r->kv.set_checkpoint_floor([dev](int64_t* free_now) -> int { - RadDeviceProps p{}; - RAD_TRY(rad_dev_props(dev, &p)); - *free_now = p.vram_free; - return RAD_OK; - }, keep); - } -} - int Engine::start() { std::vector devs; std::string inventory; @@ -3150,6 +3185,35 @@ int Engine::start() { } (void)rad_dev_set(ranks_[0]->device); + /* THE MOST THE CACHE CAN HOLD, said once in one line: the whole carve, with every block it lends + * the experts taken back -- which a request that needs them does, the same step. Tokens are the + * paged groups' shared axis, so the smallest of theirs; a windowed group bounds how far back a + * sequence keeps context, not how much fits, and is left out. The /stats and /metrics figures + * (kv_tokens_max, radiance:kv_cache_max_tokens) are the same numbers. */ + { + const KVManager& kv = ranks_[0]->kv; + int64_t bytes = 0, state = 0, tokens = 0; + for (const KVGroupPlan& p : kv.plans()) { + bytes += kv.pool_bytes_carved(p.index); + if (p.stateful()) state += kv.pool_bytes_carved(p.index); + if (!p.paged() || p.kind == RAD_KV_WINDOW || p.block_size <= 0) continue; + const int64_t t = p.n_blocks * p.block_size; + if (tokens == 0 || t < tokens) tokens = t; + } + const int64_t mlen = cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train; + const int64_t lent = lending_ ? ranks_[0]->mover.flex_capacity() : 0; + if (bytes > 0) + RAD_INFO("kv: the cache can grow to %s a card -- %lld tokens of context, %.1f sessions at " + "%lld -- with every block it lends the experts taken back; %s of that is " + "per-sequence state, and %s", + humanb(bytes).c_str(), (long long)tokens, + mlen > 0 ? (double)tokens / (double)mlen : 0.0, (long long)mlen, + humanb(state).c_str(), + lent > 0 ? fmt("up to %s is lent to the experts while no request holds it", + humanb(lent).c_str()).c_str() + : "nothing is lent: it is all the cache's"); + } + /* ---- AND THE TOP OF THE ACTIVATION ARENA, lent while the steps are small ---------------- * * One stretch a rank: from the end of the full plan's transients down to the end of the @@ -3257,83 +3321,7 @@ int Engine::start() { * * A slack of one arena is tolerated silently: MiB rounding and a kernel plugin's own * workspaces live in there, and naming a number this close to right would be noise. */ - /* DOES A DECOMMIT GIVE THE CARD BACK? The checkpoint slots are the one part of the KV pool - * backed on demand, and releasing a freed slot's pages is only worth a driver call where the - * card actually gets them back. That is a claim about the driver rather than about the API, - * so it is measured here, once, on a range nothing else owns: commit it, read the card, - * decommit it, read again. tools/vmemprobe.cpp asks the same question in more detail, and on - * ROCm 7.2 / gfx1201 the answer is no -- hipMemUnmap returns nothing, and a reservation is - * charged for its high-water commit until hipMemAddressFree. - * - * The expert slab does not depend on the answer. It borrows the cache's idle blocks at the - * addresses the cache already owns, so no page ever changes hands (Engine::loan_tick). */ - if (!ranks_.empty() && VMem::supported()) { - VMem v; - const int64_t g = VMem::granularity(); - const int64_t n = std::max(64ll << 20, g > 0 ? g * 16 : 0); - RadDeviceProps a{}, b{}; - release_frees_card_ = false; - if (rad_dev_set(ranks_[0]->device) >= 0 && v.reserve(n) >= 0 && v.commit(0, n) >= 0 && - rad_dev_props(ranks_[0]->device, &a) >= 0 && v.decommit(0, n) >= 0 && - rad_dev_props(ranks_[0]->device, &b) >= 0) - release_frees_card_ = (b.vram_free - a.vram_free) > n / 2; - for (auto& r : ranks_) r->kv.set_release_frees_card(release_frees_card_); - if (!release_frees_card_) - RAD_INFO("this driver does not return decommitted VRAM to the card (%s unmapped, the " - "free counter did not move), so a freed checkpoint slot keeps its pages. The " - "expert slab is unaffected: it borrows the cache's idle blocks in place.", - humanb(n).c_str()); - } - - /* A CHECKPOINT SLOT IS BACKED ON EVERY CARD BEFORE ITS ID IS HANDED OUT, AND NEVER INTO THE - * HEADROOM. Rank 0's free list hands the ids out and every rank writes its shard of a snapshot - * into the same slot of its own pool; backing a slot on one card and meeting a refusal on the - * other at the snapshot copy would stop the engine mid-serve. See - * KVManager::set_checkpoint_floor for why the floor is the headroom. - * - * AND NOT INTO WHAT THE BUDGET KEPT FOR LATER either: the step staging serve() allocates, and - * what is built on first use. serve() lowers the floor once the staging exists. */ const int64_t headroom = std::max(cfg_.gpu_headroom_mib, 0) * (1ll << 20); - const int64_t keep_now = headroom + late_step_bytes_ + late_lazy_bytes_; - if (!ranks_.empty()) { - set_checkpoint_floors(keep_now); - std::vector peers; - for (size_t i = 1; i < ranks_.size(); ++i) peers.push_back(&ranks_[i]->kv); - ranks_[0]->kv.set_checkpoint_peers(std::move(peers)); - } - /* AND ON A DRIVER THAT KEEPS WHAT IT MAPS, BACKED NOW. A slot backed later would cost the card - * exactly what it costs now and could never be given back, so waiting would only move the - * region's cost out of the reading below and into the middle of serving -- where the budget's - * misses (allocations made after it was resolved) may already have taken part of it. Backed - * here, the reading includes the slots, and a slot the cards have no room for is withdrawn - * here and said so. */ - if (!release_frees_card_ && !ranks_.empty() && ranks_[0]->kv.free_checkpoint_slots() > 0) { - KVManager& lead = ranks_[0]->kv; - const int64_t asked = lead.free_checkpoint_slots(); - int64_t gone = 0; - RAD_TRY(lead.back_free_checkpoints(&gone)); - if (gone > 0) { - const int64_t stride = lead.checkpoint_stride(); - int64_t short_by = 0; - for (auto& r : ranks_) { - RadDeviceProps p{}; - if (rad_dev_props(r->device, &p) < 0) continue; - short_by = std::max(short_by, gone * stride - (p.vram_free - keep_now)); - } - RAD_WARN("checkpoint slots: %lld of %lld backed (%s each), %lld withdrawn -- one more " - "would take a card under the %s it has to keep free: the %s " - "--gpu-headroom-mib, the room a kernel's first launch allocates from, and %s " - "the budget kept for the step staging and for what is built on first use. " - "The prefix cache holds %lld linear-state snapshots on the card and its " - "retention policy decides which. The budget counted all %lld; the card is %s " - "short of them, which is allocations made after the budget was resolved.", - (long long)(asked - gone), (long long)asked, humanb(stride).c_str(), - (long long)gone, humanb(keep_now).c_str(), humanb(headroom).c_str(), - humanb(late_step_bytes_ + late_lazy_bytes_).c_str(), (long long)(asked - gone), - (long long)asked, humanb(short_by).c_str()); - } - } - for (auto& r : ranks_) { LogRank lr(r->index); RadDeviceProps props{}; diff --git a/core/format/share.cpp b/core/format/share.cpp index a160bb81..0250f3b2 100644 --- a/core/format/share.cpp +++ b/core/format/share.cpp @@ -13,23 +13,6 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con return RAD_E_SHAPE; }; if (w.n_sel < 1 || w.n_sel > RAD_ENC_MAX_PLANES) return refuse("no planes selected"); - /* A ZERO SHARE: the declaration's own extents of every selected plane, and nothing to read. - * At one rank there is no share to zero -- the weight is whole and real. */ - if (w.shard_zero && world > 1) { - for (int k = 0; k < w.n_sel; ++k) { - const RadEncPlane& p = enc.plane[w.sel[k]]; - PlaneShare& s = out[k]; - s = PlaneShare{}; - s.dtype = p.dtype; - s.rows = w.sel_rows[k]; - s.cols = w.sel_cols[k]; - s.row_bytes = rad_enc_row_bytes(p.dtype, s.cols); - s.zero = true; - if (s.rows <= 0 || s.cols <= 0) - return refuse(fmt("a zero share of the '%s' plane has no extent", p.role)); - } - return RAD_OK; - } int64_t R = 0, C = 0; rad_enc_view(rank, shape, &R, &C); diff --git a/core/format/share.h b/core/format/share.h index dff11074..53672495 100644 --- a/core/format/share.h +++ b/core/format/share.h @@ -27,9 +27,6 @@ struct PlaneShare { uint32_t dtype = RAD_DT_INVALID; int64_t rows = 0, cols = 0; /* the share's extents, in the plane's elements */ int64_t row_bytes = 0; - /* rad_weight_shard_zero: the share has its extents and no rectangles; the loader writes - * dense_bytes() of zeros and reads nothing. */ - bool zero = false; int64_t dense_bytes() const; /* the share laid out dense: rows * a row of `cols` */ }; diff --git a/core/mem/hostarena.cpp b/core/mem/hostarena.cpp new file mode 100644 index 00000000..d6d060fc --- /dev/null +++ b/core/mem/hostarena.cpp @@ -0,0 +1,88 @@ +/* hostarena.cpp -- see hostarena.h. */ +#include "mem/hostarena.h" + +#include "rad_internal.h" + +namespace rad { + +HostArena::~HostArena() { close(); } + +int HostArena::open(int64_t slot_bytes, int64_t cap_bytes) { + close(); + if (slot_bytes <= 0 || cap_bytes < slot_bytes) return RAD_E_INVAL; + const int64_t n = cap_bytes / slot_bytes; + /* PINNED, and the allocation is refused rather than downgraded. A pageable host buffer on + * this path does not fail, it just collapses -- an async copy to pageable memory serialises + * against the stream and the whole point of moving instead of dropping is gone. Better to + * start without the store and say so than to run it at a tenth of the rate it was budgeted + * at. */ + base_ = rad_dev_alloc(n * slot_bytes, RAD_MEM_HOST_PINNED); + if (!base_) return RAD_E_NOMEM; + slot_bytes_ = slot_bytes; + used_ = 0; + cap_slots_ = n; + cursor_ = 0; + bits_.assign((size_t)((n + 63) / 64), 0ull); + return RAD_OK; +} + +void HostArena::close() { + if (base_) rad_dev_free(base_, RAD_MEM_HOST_PINNED); + base_ = nullptr; + slot_bytes_ = 0; + used_ = 0; + cap_slots_ = 0; + cursor_ = 0; + bits_.clear(); +} + +int32_t HostArena::alloc() { + int32_t got = 0; + return alloc_run(1, &got); +} + +/* THE FIRST FREE RUN AT OR AFTER THE CURSOR, wrapping once. A whole word of used slots is skipped + * in one compare, so a nearly full arena costs a scan of its bitmap -- a few thousand words at the + * sizes an operator gives this -- and an arena with room costs nothing. The cursor makes + * consecutive calls hand out consecutive slots, which is what lets a batch be one copy a run. */ +int32_t HostArena::alloc_run(int32_t want, int32_t* got) { + *got = 0; + if (want <= 0 || !base_ || full()) return -1; + int64_t s = -1; + for (int pass = 0; pass < 2 && s < 0; ++pass) { + const int64_t lo = pass == 0 ? cursor_ : 0; + const int64_t hi = pass == 0 ? cap_slots_ : cursor_; + for (int64_t i = lo; i < hi;) { + const uint64_t w = bits_[(size_t)(i >> 6)]; + if ((i & 63) == 0 && w == ~0ull) { i += 64; continue; } + if (!is_used(i)) { s = i; break; } + ++i; + } + } + if (s < 0) return -1; + int64_t n = 0; + while (n < want && s + n < cap_slots_ && !is_used(s + n)) { + bits_[(size_t)((s + n) >> 6)] |= 1ull << ((s + n) & 63); + ++n; + } + used_ += n; + cursor_ = s + n >= cap_slots_ ? 0 : s + n; + *got = (int32_t)n; + return (int32_t)s; +} + +void HostArena::free(int32_t slot) { + if (slot < 0 || slot >= cap_slots_) return; + /* A slot that is already free is refused rather than counted twice: the used count is what the + * sessions view reports and what `full` answers, and a negative one hides the next leak. */ + if (!is_used(slot)) return; + bits_[(size_t)(slot >> 6)] &= ~(1ull << (slot & 63)); + --used_; +} + +void* HostArena::at(int32_t slot) const { + if (!base_ || slot < 0 || slot >= cap_slots_) return nullptr; + return (char*)base_ + (int64_t)slot * slot_bytes_; +} + +} /* namespace rad */ diff --git a/core/mem/hostarena.h b/core/mem/hostarena.h new file mode 100644 index 00000000..fb4b1a37 --- /dev/null +++ b/core/mem/hostarena.h @@ -0,0 +1,63 @@ +/* hostarena.h -- fixed-size slots of pinned host memory. + * + * Two stores are built from it: the KV tiers' block arena (core/mem/kvtier.h), where one slot is + * one cache entry, and the linear-state snapshot store (KVManager::set_checkpoint_store), where + * one slot is one snapshot. Under tensor parallelism a slot holds EVERY rank's shard of its + * object, each rank at its own offset, so the disk store can read and write it as one payload. + * + * Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the + * driver stages an async copy to pageable memory through its own buffer and, on some paths, + * synchronises. Slot-allocated at one fixed size rather than malloc'd per object: every object a + * store holds is the same size for a given model, so a bitmap is the whole allocator. + * + * RUNS, BECAUSE A TRANSFER IS PER RUN. A 4-token block makes a 200K-token conversation fifty + * thousand entries, and a copy per entry is fifty thousand driver calls on the engine thread -- + * the call rate, not the link, is then what a restore costs. Slots taken together are given + * consecutive ids wherever the arena has them, so a batch crosses the link as one strided copy + * a run. */ +#pragma once +#include "rad_core.h" + +#include +#include + +namespace rad { + +class HostArena { +public: + ~HostArena(); + int open(int64_t slot_bytes, int64_t cap_bytes); + void close(); + bool enabled() const { return base_ != nullptr; } + + int64_t slot_bytes() const { return slot_bytes_; } + /* Fixed when the arena is opened. Stored rather than counted from the bitmap, because an + * HTTP thread reads it for the sessions view while the engine thread allocates and frees. */ + int64_t capacity() const { return cap_slots_; } + int64_t used_slots() const { return used_; } + int64_t cap_bytes() const { return slot_bytes_ * capacity(); } + int64_t free_slots() const { return cap_slots_ - used_; } + + /* -1 when the arena is full. The caller evicts and retries; this does not choose victims, + * because the policy that would choose them lives with the store's owner and an allocator + * that reached into it would give each object two owners. */ + bool full() const { return used_ >= cap_slots_; } + int32_t alloc(); + /* UP TO `want` CONSECUTIVE SLOTS, the first free run at or after the cursor. `*got` is how + * many; the caller asks again for the rest. -1 when the arena is full. */ + int32_t alloc_run(int32_t want, int32_t* got); + void free(int32_t slot); + bool in_use(int32_t slot) const { return slot >= 0 && slot < cap_slots_ && is_used(slot); } + void* at(int32_t slot) const; + +private: + bool is_used(int64_t s) const { return (bits_[(size_t)(s >> 6)] >> (s & 63)) & 1ull; } + void* base_ = nullptr; + int64_t slot_bytes_ = 0; + int64_t used_ = 0; + int64_t cap_slots_ = 0; + int64_t cursor_ = 0; + std::vector bits_; +}; + +} /* namespace rad */ diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index 4a7f7aed..e4a3e64e 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -100,7 +100,8 @@ int KVManager::configure(const std::vector& groups, const Config& c } int KVManager::plan_groups(const std::vector& groups, const Config& cfg) { - /* The snapshot count is the operator's, through --checkpoint-slots. Nothing here derives it. */ + /* Only to say it is ignored on a model with no recurrent state: the slots are host memory and + * the engine opens them (set_checkpoint_store). */ const int64_t budget_ckpts = cfg.checkpoint_slots > 0 ? cfg.checkpoint_slots : 0; forget(); @@ -285,37 +286,12 @@ int KVManager::plan_groups(const std::vector& groups, const Config& int64_t fixed = 0; for (const auto& p : plans_) if (p.stateful()) fixed += align_up(p.bytes_per_state * p.n_states, RAD_ALIGN_UNIT); - /* A SLOT IS ELASTIC ONLY WHEN A SNAPSHOT IS WORTH A GRANULE, and the stride follows from - * that. Committing and releasing a slot on its own needs the stride to be a whole number of - * granules: a commit rounds outward and a release rounds inward, so a straddling stride - * would leave every slot's last partial granule backed for the life of the process and let - * one slot's commit back part of its neighbour. - * - * That rounding is free on a linear-attention model, where a snapshot is a sizeable fraction - * of a gigabyte. It is not free on a small one: a 16 KiB snapshot rounded to a 2 MiB granule - * is 128x the address space to manage a charge that was never worth managing. Below a - * granule the slots stay in the eagerly committed region, where they cost what they say - * they cost and nothing reclaims them because there is nothing to reclaim. */ - const int64_t granule = Pool::granule(); - ck_elastic_ = granule > 0 && checkpoint_bytes_ >= granule; - ck_stride_ = align_up(checkpoint_bytes_, ck_align()); - /* AND THE PAD IN FRONT OF THE REGION IS PART OF ITS COST. The slots are reserved LAST, after - * every group, and on a ck_align() boundary -- so the region starts up to one alignment unit - * past wherever the groups happened to end. Where that is cannot be known here, because the - * paged split below is what decides it, so the whole unit is reserved rather than the exact - * pad: it is at most one commit granule against a pool measured in gigabytes, and the - * alternative is a budget the LAST slot falls off the end of -- a refusal at load on some - * models and not others, depending on where the groups happened to end. */ - const int64_t ck_pad = budget_ckpts > 0 ? ck_align() : 0; - const int64_t ck_total = budget_ckpts * ck_stride_ + ck_pad; - fixed += ck_total; /* And one unit a paged group, for the same reason: a page size that is not a multiple of the * alignment pads too, and the carve below hands the groups everything that is left. */ for (const auto& p : plans_) if (p.paged()) fixed += RAD_ALIGN_UNIT; - fixed_ = fixed; - ck_total_ = ck_total; - ckpts_ = budget_ckpts; + fixed_ = fixed; + ckpts_ = budget_ckpts; return RAD_OK; } @@ -361,11 +337,7 @@ void KVManager::forget() { chunk_blocks_.clear(); short_peak_.clear(); pool_ = nullptr; clears_.clear(); - seqs_.clear(); pending_.clear(); ck_slot_base_.clear(); ck_free_.clear(); - ck_stride_ = ck_region_off_ = 0; - ck_elastic_ = false; - ck_high_water_ = 0; - ck_backed_ = 0; + seqs_.clear(); pending_.clear(); configured_ = false; report_.clear(); } @@ -376,8 +348,22 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector* block * run out of full-attention blocks with a window pool still half empty. */ std::vector out(plans_.size(), 0); int64_t remaining = budget_bytes - fixed_; - std::vector open; - for (const auto& p : plans_) if (p.paged()) open.push_back(p.index); + /* A ZERO GROUP COSTS THIS RANK NOTHING, so it takes no part in the split: it holds the + * shared table's block count, which is what the costed groups settle on (here, or under the + * cap, on the rank that does hold the cache). */ + std::vector open, zeros; + for (const auto& p : plans_) + if (p.paged()) (p.zero ? zeros : open).push_back(p.index); + /* Every paged group zero: nothing on this rank limits the token count. The cap is what the + * ranks that hold the cache carve, and without one there is no figure to report. */ + if (open.empty() && !zeros.empty()) { + const int64_t tokens = tokens_cap_ > 0 ? tokens_cap_ : kUnboundedTokens; + if (blocks) { + for (int32_t i : zeros) out[i] = zero_blocks(plans_[i], tokens); + *blocks = std::move(out); + } + return tokens; + } int64_t tokens = 0; while (!open.empty() && remaining > 0) { @@ -404,34 +390,34 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector* block open.erase(std::find(open.begin(), open.end(), capped)); } for (int32_t i : open) out[i] = remaining > 0 ? tokens / plans_[i].block_size : 0; + for (int32_t i : zeros) out[i] = remaining > 0 ? zero_blocks(plans_[i], tokens) : 0; if (blocks) *blocks = std::move(out); return tokens; } +int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const { + if (tokens == kUnboundedTokens) return 0; + const int64_t b = tokens / p.block_size; + if (p.kind == RAD_KV_WINDOW && b > max_seqs_ * p.window_blocks) return max_seqs_ * p.window_blocks; + return b; +} + int KVManager::carve_into(Pool& kv_pool) { /* The pool is whatever the operator stated or the resolver derived; nothing here re-decides * it. What this does decide is how the groups share it, which is arithmetic, not policy. */ const int64_t budget_bytes = kv_pool.avail(); - const int64_t budget_ckpts = ckpts_; const int64_t fixed = fixed_; - const int64_t ck_total = ck_total_; pool_base_ = kv_pool.base(); pool_ = &kv_pool; if (fixed >= budget_bytes) { RAD_ERR("vram_kv does not fit its fixed costs:\n" " linear/conv state %10s (%lld sequences)\n" - " checkpoints %10s (%lld x %s)\n" - " ------------------------------\n" - " fixed %10s\n" " --vram-kv-mib %10s\n" " SHORT BY %10s\n" - "Lower --max-seqs or the checkpoint slot count, or raise --vram-kv-mib. " - "The engine will not shrink one of them for you (spec §6).", - humanb(fixed - ck_total).c_str(), (long long)max_seqs_, - humanb(ck_total).c_str(), (long long)budget_ckpts, - humanb(ck_stride_).c_str(), - humanb(fixed).c_str(), humanb(budget_bytes).c_str(), + "Lower --max-seqs or raise --vram-kv-mib. The engine will not shrink one of them " + "for you (spec §6).", + humanb(fixed).c_str(), (long long)max_seqs_, humanb(budget_bytes).c_str(), humanb(fixed - budget_bytes + 1).c_str()); return RAD_E_NOMEM; } @@ -444,10 +430,16 @@ int KVManager::carve_into(Pool& kv_pool) { for (auto& p : plans_) { if (!p.paged()) continue; + if (p.n_blocks <= 0 && p.zero) { + RAD_ERR("KV group '%s' is zero on this rank and nothing set its block count: a zero " + "group holds what the ranks keeping the cache carve, and no cap from them was " + "given (cap_paged_tokens)", p.name.c_str()); + return RAD_E_STATE; + } if (p.n_blocks <= 0) { RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed " - "linear/conv costs of %s. Raise --vram-kv-mib, lower --expert-vs-cache-ratio, " - "or lower --max-seqs.", + "linear/conv costs of %s. Raise --vram-kv-mib or --host-pool-mib, or lower " + "--max-seqs.", p.name.c_str(), humanb(budget_bytes).c_str(), humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str()); return RAD_E_NOMEM; @@ -456,11 +448,9 @@ int KVManager::carve_into(Pool& kv_pool) { /* ---- carve. Every reservation comes from the KV pool and only from the KV pool: the mover * works inside the weight slab and cannot reach this (spec §6). ---- */ - int64_t paged_taken = 0; for (auto& p : plans_) { int64_t bytes = p.paged() ? p.n_blocks * p.bytes_per_block : p.n_states * p.bytes_per_state; - if (p.paged()) paged_taken += bytes; if (p.zero) { p.base = nullptr; p.pool_offset = 0; @@ -481,30 +471,11 @@ int KVManager::carve_into(Pool& kv_pool) { p.pool_offset = off; p.pool_bytes = bytes; } - /* --checkpoint-slots on a model with no recurrent state buys nothing, and allocating zero-byte + /* --checkpoint-slots on a model with no recurrent state buys nothing, and opening zero-byte * slots for it would leave the operator's flag looking honoured. Ignore it and say so. */ - if (budget_ckpts > 0 && checkpoint_bytes_ <= 0) + if (ckpts_ > 0 && checkpoint_bytes_ <= 0) RAD_WARN("--checkpoint-slots %lld ignored: this model declares no linear-attention state, " - "so there is nothing to snapshot", (long long)budget_ckpts); - for (int64_t i = 0; checkpoint_bytes_ > 0 && i < budget_ckpts; ++i) { - int64_t off = 0; - if (!kv_pool.reserve("linear checkpoint", ck_stride_, ck_align(), &off) - && !kv_pool.accounting_only()) { - /* The arithmetic that is supposed to make this impossible, printed next to the - * failure: `fixed` reserved budget_ckpts * checkpoint_bytes_ up front, so a checkpoint - * that does not fit means the paged carve above spent more than `remaining`. */ - RAD_ERR("linear checkpoint slot %lld (%lld B) did not fit the KV pool: %lld B of " - "%lld B left after the paged groups took %lld B against a %lld B share", - (long long)i, (long long)checkpoint_bytes_, - (long long)kv_pool.avail(), (long long)budget_bytes, - (long long)paged_taken, (long long)(budget_bytes - fixed)); - return RAD_E_NOMEM; - } - if (i == 0) ck_region_off_ = off; - ck_slot_base_.push_back(off); - ck_free_.push_back((int32_t)i); - } - std::reverse(ck_free_.begin(), ck_free_.end()); /* pop_back hands out slot 0 first */ + "so there is nothing to snapshot", (long long)ckpts_); /* ---- free lists ---- */ free_blocks_.resize(plans_.size()); @@ -542,36 +513,13 @@ int KVManager::carve_into(Pool& kv_pool) { * * The fixed part -- recurrent state and conv slots -- is never released. It is sized per * sequence rather than per token, so there is no idle fraction of it to give back, and a - * state slot cannot be re-created on demand the way a page can. - * - * CHECKPOINT SLOTS ARE NOT PART OF THAT. They are a CACHE -- the retention policy creates and - * retires them all run, and a slot nobody has taken holds nothing that has to survive -- so - * backing them all here would make --checkpoint-slots a standing VRAM charge whether or not a - * snapshot exists. On a linear-attention model a slot is a sizeable fraction of a gigabyte, - * and on a card whose experts do not fit that charge is decode step time. The region is left - * unbacked and each slot is committed as it is handed out, which makes the flag a cap. */ + * state slot cannot be re-created on demand the way a page can. */ if (pool_ && pool_->elastic()) { - /* EVERYTHING EXCEPT THE CHECKPOINT REGION. The slots are reserved last, so the - * second range is empty and this is a prefix -- written as a hole anyway, because - * "commit everything below the slots" is the rule and "the slots are at the end" is a - * detail of the carve above that nothing here should depend on. A prefix that stopped at - * a region in the MIDDLE would leave every group past it addressable and unbacked, and - * the paged groups are live from the first step: a fault at a valid-looking address on - * the first write, which is the worst shape this class of bug has. - * - * Both edges are granule-aligned by construction (the slot reserve asks for ck_align() - * and the stride is a whole number of granules), so neither commit rounds outward into - * the region. That alignment is the whole reason it can be skipped at all. */ - const int64_t used = pool_->used(); - const int64_t hole_off = ck_elastic_ && !ck_slot_base_.empty() ? ck_region_off_ : used; - const int64_t hole_end = ck_elastic_ && !ck_slot_base_.empty() - ? ck_slot_base_.back() + ck_stride_ - : used; - int rc = pool_->commit(0, hole_off); - if (rc >= 0 && used > hole_end) rc = pool_->commit(hole_end, used - hole_end); + const int64_t used = pool_->used(); + const int rc = pool_->commit(0, used); if (rc < 0) { RAD_ERR("KV pool: the carve reserved %s of address space and the card would not back " - "it", humanb(used - (hole_end - hole_off)).c_str()); + "it", humanb(used).c_str()); return rc; } } @@ -618,19 +566,12 @@ int KVManager::carve_into(Pool& kv_pool) { } /* WHERE EACH GROUP STARTS, SO A FAULT ADDRESS CAN BE PLACED. A GPU memory fault names an * address and nothing else, and without this the only way to tell "kv_attn layer 7" from - * "checkpoint slot 3" is to reconstruct the carve by hand from the sizes above. One line. */ - report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld, checkpoints at +%lld\n", + * "kv_gdn_state slot 3" is to reconstruct the carve by hand from the sizes above. One line. */ + report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld\n", pool_base_, humanb(pool_ ? pool_->bytes() : 0).c_str(), (long long)(plans_.size() > 1 ? plans_[1].pool_offset : 0), (long long)(plans_.empty() ? 0 : plans_.back().pool_offset + - plans_.back().pool_bytes), - (long long)(ck_slot_base_.empty() ? 0 : ck_slot_base_.front())); - if (checkpoint_bytes_ > 0) - report_ += fmt( -" %-14s %-6s %lld slots x %s = %s%s\n", "checkpoints", "linear", - (long long)ck_slot_base_.size(), humanb(ck_stride_).c_str(), - humanb((int64_t)ck_slot_base_.size() * ck_stride_).c_str(), - ck_elastic_ ? " (address space; backed as slots are taken)" : ""); + plans_.back().pool_bytes)); return RAD_OK; } @@ -781,73 +722,6 @@ int64_t KVManager::buffer_bytes() const { return b; } -int64_t KVManager::ck_reserve_bytes() const { - if (!ck_elastic_ || ck_stride_ <= 0) return 0; - /* Counted from what is BACKED and not from the free list, because a rank that is not the one - * holding the free list still backs the slots it writes, and its reserve has to cover them. */ - const int64_t want = std::min(ckpts_, ck_high_water_ + 1); - return want > ck_backed_ ? (want - ck_backed_) * ck_stride_ : 0; -} - -bool KVManager::ck_backed(int32_t slot) const { - if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return false; - if (!ck_elastic_ || !pool_ || !pool_->elastic() || ck_stride_ <= 0) return true; - return pool_->is_committed(ck_slot_base_[(size_t)slot], ck_stride_); -} - -int KVManager::ck_room(int32_t slot) const { - if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return RAD_E_INVAL; - if (ck_backed(slot) || !ck_free_bytes_ || ck_keep_free_ <= 0) return RAD_OK; - int64_t free_now = 0; - RAD_TRY(ck_free_bytes_(&free_now)); - return free_now - ck_stride_ >= ck_keep_free_ ? RAD_OK : RAD_E_FULL; -} - -int KVManager::ck_commit(int32_t slot) { - if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return RAD_E_INVAL; - if (ck_backed(slot)) return RAD_OK; - if (pool_->commit(ck_slot_base_[(size_t)slot], ck_stride_) < 0) return RAD_E_FULL; - if (++ck_backed_ > ck_high_water_) ck_high_water_ = ck_backed_; - return RAD_OK; -} - -int KVManager::back_checkpoint(int32_t slot) { - RAD_TRY(ck_room(slot)); - return ck_commit(slot); -} - -/* EVERY CARD'S ANSWER BEFORE ANY CARD'S PAGES. Asking first means a slot one card refuses costs - * the others nothing: on a driver that keeps what it maps, pages committed for a slot that is then - * not handed out would be charged to that card for the life of the process. */ -int KVManager::ck_back_everywhere(int32_t slot) { - RAD_TRY(ck_room(slot)); - for (KVManager* p : ck_peers_) RAD_TRY(p->ck_room(slot)); - RAD_TRY(ck_commit(slot)); - for (KVManager* p : ck_peers_) RAD_TRY(p->ck_commit(slot)); - return RAD_OK; -} - -int KVManager::back_free_checkpoints(int64_t* withdrawn) { - std::vector keep; - keep.reserve(ck_free_.size()); - int64_t gone = 0; - for (const int32_t s : ck_free_) { - const int rc = ck_back_everywhere(s); - if (rc == RAD_E_FULL) { ++gone; continue; } - if (rc < 0) return rc; - keep.push_back(s); - } - ck_free_.swap(keep); - if (withdrawn) *withdrawn = gone; - return RAD_OK; -} - -int64_t KVManager::ck_align() const { - if (!ck_elastic_) return (int64_t)RAD_ALIGN_UNIT; - const int64_t g = Pool::granule(); - return g > (int64_t)RAD_ALIGN_UNIT ? g : (int64_t)RAD_ALIGN_UNIT; -} - /* WHAT THE GROUP CAN STILL HAND OUT, WHICH IS NOT WHAT IT HAS BELOW THE MARK. A lent block is * still carved, still addressed and still the operator's budget -- it is one recall away, and the * recall happens on the path that needs it. So every admission decision is made against this @@ -1447,47 +1321,27 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens, * caller sees RAD_E_FULL, which is the answer it already handles -- the retention policy runs and * the allocation is retried. Anything else would turn a card that is momentarily busy into a * failed request. */ +void KVManager::set_checkpoint_store(HostArena* store, int64_t rank_off) { + ck_store_ = store && store->enabled() ? store : nullptr; + ck_rank_off_ = rank_off; +} + int KVManager::alloc_checkpoint(int32_t* slot_out) { - if (ck_free_.empty()) return RAD_E_FULL; - /* A SLOT EVERY CARD HAS BACKED ALREADY, WHERE ONE IS FREE: it costs no commit and no reading - * of the card, and a card at its floor still has every slot it backed before. Otherwise the - * top of the free list, backed on every card or not handed out at all. */ - size_t at = ck_free_.size() - 1; - for (size_t i = ck_free_.size(); i-- > 0;) { - const int32_t s = ck_free_[i]; - bool all = ck_backed(s); - for (const KVManager* p : ck_peers_) all = all && p->ck_backed(s); - if (all) { at = i; break; } - } - const int32_t slot = ck_free_[at]; - const int rc = ck_back_everywhere(slot); - if (rc < 0) return rc; - ck_free_.erase(ck_free_.begin() + (std::ptrdiff_t)at); + if (!ck_store_ || checkpoint_bytes_ <= 0) return RAD_E_FULL; + const int32_t slot = ck_store_->alloc(); + if (slot < 0) return RAD_E_FULL; *slot_out = slot; return RAD_OK; } void KVManager::free_checkpoint(int32_t slot) { - if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return; - for (int32_t f : ck_free_) if (f == slot) return; /* double free: refuse, do not corrupt */ - ck_free_.push_back(slot); - /* AFTER the free list, so a release the driver refuses still leaves the slot allocatable: the - * next commit of the same range is idempotent and the bytes are correct either way. */ - /* AND ONLY WHERE A RELEASE IS WORTH MAKING. See set_release_frees_card: on a driver that does - * not return decommitted VRAM, unmapping these pages buys the card nothing and costs a commit - * on the next allocation of the slot. It is not merely wasted work: the range is unmapped - * while the slot id goes straight back on the free list, so anything still addressing it - * reads a page that is no longer there. */ - if (ck_elastic_ && release_frees_card_ && pool_ && pool_->elastic() && ck_stride_ > 0) { - const int64_t off = ck_slot_base_[(size_t)slot]; - if (pool_->is_committed(off, ck_stride_) && ck_backed_ > 0) --ck_backed_; - (void)pool_->decommit(off, ck_stride_); - } + if (ck_store_) ck_store_->free(slot); } void* KVManager::checkpoint_ptr(int32_t slot) const { - if (!pool_base_ || slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return nullptr; - return (char*)pool_base_ + ck_slot_base_[(size_t)slot]; + if (!ck_store_) return nullptr; + char* p = (char*)ck_store_->at(slot); + return p ? p + ck_rank_off_ : nullptr; } /* One walk, both directions. Keeping save and restore as a single traversal is deliberate: the @@ -1496,14 +1350,16 @@ void* KVManager::checkpoint_ptr(int32_t slot) const { * functions that could stop agreeing. */ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save, RadStream s) { - /* THIS RANK'S PAGES, BEFORE THIS RANK'S COPY. alloc_checkpoint backed the slot on every rank - * before it handed the id out, so this finds it backed; a refusal here is a slot that did not - * come from there. See KVManager::back_checkpoint. */ - RAD_TRY(back_checkpoint(ck_slot)); + /* A SLOT NOBODY HOLDS IS NOT ONE TO WRITE. Rank 0 hands the ids out, so a follower checks the + * shared store rather than a list of its own. */ + if (!ck_store_ || !ck_store_->in_use(ck_slot)) return RAD_E_INVAL; char* ck = (char*)checkpoint_ptr(ck_slot); if (!ck) return RAD_E_INVAL; if (!state_slots || n_slots < (int)plans_.size()) return RAD_E_INVAL; + /* ONE PITCHED COPY A GROUP. Within a group the state of one sequence is a row a layer, one + * layer_stride apart in the pool and packed end to end in the slot, so a group's whole share + * crosses the link as one launch rather than a launch a layer. */ int64_t off = 0; for (size_t g = 0; g < plans_.size(); ++g) { const KVGroupPlan& p = plans_[g]; @@ -1511,19 +1367,19 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t const int32_t slot = state_slots[g]; if (slot < 0) return RAD_E_STATE; /* no state to save, or none to restore into */ const int64_t nbytes = p.layer_bytes_per_state(); - for (int64_t l = 0; l < p.n_layers; ++l) { - void* st = state_ptr((int32_t)g, (int32_t)l, slot); - if (!st) return RAD_E_STATE; - if (off + nbytes > checkpoint_bytes_) { - RAD_ERR("checkpoint slot %d holds %lld bytes and this sequence's linear state " - "needs more than that; configure() sized it from the same plans, so the " - "two have gone out of step", (int)ck_slot, (long long)checkpoint_bytes_); - return RAD_E_STATE; - } - RAD_TRY(save ? rad_memcpy_async(ck + off, st, nbytes, s) - : rad_memcpy_async(st, ck + off, nbytes, s)); - off += nbytes; + void* st = state_ptr((int32_t)g, 0, slot); + if (!st || p.n_layers <= 0) return RAD_E_STATE; + if (off + nbytes * p.n_layers > checkpoint_bytes_) { + RAD_ERR("checkpoint slot %d holds %lld bytes a rank and this sequence's linear state " + "needs more than that; the store was sized from the same plans, so the two " + "have gone out of step", (int)ck_slot, (long long)checkpoint_bytes_); + return RAD_E_STATE; } + RAD_TRY(save ? rad_memcpy_2d_async(ck + off, nbytes, st, p.layer_stride(), nbytes, + p.n_layers, s) + : rad_memcpy_2d_async(st, p.layer_stride(), ck + off, nbytes, nbytes, + p.n_layers, s)); + off += nbytes * p.n_layers; } return RAD_OK; } diff --git a/core/mem/kv.h b/core/mem/kv.h index 94ae2e0a..dd8e4f4d 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -18,6 +18,7 @@ * one of the two allocators keeps handing its state slot to the next request. */ #pragma once +#include "mem/hostarena.h" #include "mem/pools.h" #include "rad_core.h" @@ -155,11 +156,10 @@ public: * exhaust at the same total token count, and any other split strands memory in whichever * group outlasts the others. * - * Both budgets come from the operator and neither is derived here: the byte budget is whatever - * `kv_pool` still has (which is --vram-kv-mib), and the linear-snapshot count is - * Config::checkpoint_slots (--checkpoint-slots). A checkpoint is ~96 MiB on a Qwen3-Next and - * 64 of them is 6 GiB, so how many to retain is a budget decision and therefore not this - * component's to make (spec §6, §7.3). */ + * The byte budget comes from the operator and is not derived here: it is whatever `kv_pool` + * still has (which is --vram-kv-mib). The linear-state snapshots take none of it -- they live + * in pinned host memory (set_checkpoint_store) -- so the pool is the live cache and nothing + * else (spec §6, §7.3). */ int configure(const std::vector& groups, const Config& cfg, Pool& kv_pool); /* configure(), split at the seam the budget resolver needs. plan_groups() sizes every group @@ -170,14 +170,17 @@ public: int plan_groups(const std::vector& groups, const Config& cfg); int64_t ceiling(int64_t ctx) const; /* The part of every ceiling that is not context: recurrent and conv state for max_seqs - * sequences, the checkpoint slots and the padding. Set by plan_groups(). */ + * sequences, and the padding. Set by plan_groups(). */ int64_t fixed_bytes() const { return fixed_; } /* THE TOKEN COUNT THE PAGED GROUPS SETTLE ON for `budget_bytes` of pool -- carve()'s split * with nothing carved. One block table serves every rank, so every rank's paged groups must * hold the SAME number of blocks; under an uneven tensor-parallel split the ranks' pools are * not the same size (a rank with more delta-net heads holds more state and has less left for * pages, and a rank with no attention weights has more). The engine asks each rank this and - * cap_paged_tokens() the least on all of them before carve(). 0 is no cap. */ + * cap_paged_tokens() the least on all of them before carve(). 0 is no cap. + * kUnboundedTokens when every paged group of this rank is zero (rad_kv_group_zero): its pages + * cost it nothing, so it takes what the ranks holding the cache carve and limits nobody. */ + static constexpr int64_t kUnboundedTokens = INT64_MAX; int64_t paged_tokens(int64_t budget_bytes) const { return paged_split(budget_bytes, nullptr); } void cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; } int carve(Pool& kv_pool); @@ -348,12 +351,6 @@ public: * recalled and the request is refused (RAD_E_FULL). */ void set_reclaim(std::function f) { reclaim_ = std::move(f); } - /* WHETHER A DECOMMIT ACTUALLY GIVES THE CARD BACK, for the checkpoint region, which is the one - * part of the pool still backed on demand. Measured once at bringup rather than assumed, - * because it is a property of the driver: where it is false a freed checkpoint slot keeps its - * pages, since unmapping them would cost driver calls and return nothing. */ - void set_release_frees_card(bool yes) { release_frees_card_ = yes; } - /* MATCH A LEADER'S LOAN, FOR A RANK THAT DOES NOT KNOW WHAT IT IS HOLDING. * * Block ids are SHARED ACROSS RANKS -- RadBatch carries one block table and every rank indexes @@ -367,59 +364,6 @@ public: int64_t live_blocks(int32_t group) const; int64_t committed_bytes() const; - /* HOW MUCH OF THE CHECKPOINT REGION MUST STAY AVAILABLE, in bytes, counting only what is not - * committed already. The number is the HIGH WATER MARK PLUS ONE rather than the whole cap: - * the cap is what the operator allows and the high water is what this workload takes, and - * holding one slot past it means the allocation that would advance it always has room. */ - int64_t ck_reserve_bytes() const; - - /* BACK THIS RANK'S COPY OF A SLOT, AND SAY SO IF THE CARD WILL NOT. - * - * A slot's LIFETIME is decided once: rank 0's PrefixCache owns the free list and every other - * rank takes the id it is handed. Its BACKING is per rank, because every rank writes its own - * shard of the snapshot into the same offset of its OWN pool. alloc_checkpoint backs the slot - * on every rank before it hands the id out (set_checkpoint_peers), so on the paths that use a - * slot this is a check that finds it backed. Called before EVERY access rather than once: - * idempotence is what makes that safe, and a commit of a range already committed is a no-op. - * - * RAD_E_FULL when the commit would take the card under its floor (set_checkpoint_floor). */ - int back_checkpoint(int32_t slot); - - /* THE CARD'S FLOOR FOR A CHECKPOINT SLOT'S PAGES: the card is read before a slot is backed, - * and a slot that would leave it under `keep_free` bytes is refused as a full pool. - * - * The budget counts the whole checkpoint region as the cache's, but the region is backed as - * slots are taken, and until then its bytes read as free. The allocations nobody sizes in - * advance -- a kernel's code object and a spilling kernel's scratch, both made on the - * kernel's first launch -- are made out of that same free memory. A slot that took the last - * of it would leave the next first launch nothing, which is a fault inside the HIP runtime - * and not an error. A refused slot is a snapshot fewer on the card, which the retention - * policy answers and the host tier covers. - * - * `free_bytes` reads the card's free memory into its argument: the engine reads the device, a - * test reads a simulated card, and no floor is set on a backend with no card. */ - using FreeBytes = std::function; - void set_checkpoint_floor(FreeBytes free_bytes, int64_t keep_free) { - ck_free_bytes_ = std::move(free_bytes); - ck_keep_free_ = keep_free; - } - - /* THE OTHER RANKS' MANAGERS, given to the one whose free list hands the ids out. Every rank - * writes its shard of a snapshot into the same slot of its own pool, so a slot is backed on - * every card or handed out on none: a card that cannot back it is a full pool at allocation, - * which the prefix cache answers by retiring a snapshot, rather than a failed copy after the - * step that produced the state, which stops the engine. */ - void set_checkpoint_peers(std::vector peers) { ck_peers_ = std::move(peers); } - - /* BACK EVERY FREE SLOT NOW, ON EVERY RANK, and withdraw the ones the cards have no room for. - * For a driver that never takes a mapping's pages back (set_release_frees_card(false)): a - * slot backed later costs exactly what it costs now, and backing it now puts the region's - * cost on the card before serving starts, where the startup reading shows it. A withdrawn - * slot is never handed out. `withdrawn` counts them; RAD_E_FULL is not returned. */ - int back_free_checkpoints(int64_t* withdrawn); - - int64_t checkpoint_stride() const { return ck_stride_; } - /* ---------------- preemption by recompute (spec §7.1, §17) ---------------- */ /* Free the sequence's blocks and take it back to zero tokens. Its state slots are freed too: a * recurrent state that is not snapshotted cannot be resumed, so a preempted sequence replays @@ -470,10 +414,24 @@ public: const std::vector& victims, std::vector* preempted); - /* ---------------- linear-state checkpoints (spec §7.3) ---------------- */ + /* ---------------- linear-state checkpoints (spec §7.3) ---------------- + * + * A SNAPSHOT LIVES IN PINNED HOST MEMORY, NOT ON THE CARD. It is a copy of a sequence's state + * that no kernel reads -- the step reads the live state slots, and a snapshot only ever goes + * back into one of those -- so it has no reason to hold VRAM. Saving it is one copy across the + * link after the step that produced the state, restoring it one copy back before the step + * that resumes from it, each a few milliseconds on a 50-100 MiB snapshot. + * + * THE STORE IS SHARED BY EVERY RANK and owned by the engine: a slot holds every rank's shard + * of one snapshot, each at its own offset (`rank_off`), so the disk tier reads and writes a + * slot as one payload. The slot ids are rank 0's -- its manager hands them out and the others + * address the id they are given. Without a store no slot is ever handed out and a hybrid + * model's prefix hits replay their linear layers from zero. `checkpoint_bytes()` is THIS + * rank's shard. */ + void set_checkpoint_store(HostArena* store, int64_t rank_off); int64_t checkpoint_bytes() const { return checkpoint_bytes_; } - int64_t checkpoint_slots() const { return (int64_t)ck_slot_base_.size(); } - int64_t free_checkpoint_slots() const { return (int64_t)ck_free_.size(); } + int64_t checkpoint_slots() const { return ck_store_ ? ck_store_->capacity() : 0; } + int64_t free_checkpoint_slots() const { return ck_store_ ? ck_store_->free_slots() : 0; } int alloc_checkpoint(int32_t* slot_out); void free_checkpoint(int32_t slot); void* checkpoint_ptr(int32_t slot) const; @@ -495,7 +453,8 @@ public: * * Enqueued on `s`, not synchronous: the save has to follow the step that produced the state * and the restore has to precede the step that consumes it, and both are ordered by the - * stream rather than by waiting. RAD_E_INVAL on a bad slot or an unknown sequence. */ + * stream rather than by waiting. One pitched copy a stateful group between the card and the + * store, at the link's rate. RAD_E_INVAL on a bad slot or an unknown sequence. */ int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s); int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s); @@ -513,6 +472,9 @@ private: * `budget_bytes` of pool, under tokens_cap_, and each group's block count in `blocks` (by group * index; a windowed group capped at its window). carve_into() spends what this says. */ int64_t paged_split(int64_t budget_bytes, std::vector* blocks) const; + /* A zero group's share of `tokens`: the block count of the shared table, capped at the window + * for a windowed group. 0 for kUnboundedTokens, which is not a count. */ + int64_t zero_blocks(const KVGroupPlan& p, int64_t tokens) const; void forget(); /* One traversal serving both checkpoint directions; see checkpoint_save. */ @@ -552,8 +514,8 @@ private: std::unordered_map seqs_; std::vector pending_; - std::vector ck_slot_base_; /* pool offsets of the checkpoint slots */ - std::vector ck_free_; + HostArena* ck_store_ = nullptr; /* set_checkpoint_store */ + int64_t ck_rank_off_ = 0; int64_t checkpoint_bytes_ = 0; std::vector clears_; /* grabbed slots the engine must zero */ void* pool_base_ = nullptr; @@ -563,33 +525,9 @@ private: int64_t max_ctx_ = 0; int64_t max_tok_ = 0; /* --max-num-batched-tokens; the buffer floor is one of these */ /* plan_groups() computes these; carve() spends against them and ceiling() reports on them. */ - int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, checkpoints, padding */ - int64_t ck_total_ = 0; /* the checkpoint part of fixed_, named for the refusal message */ - int64_t ckpts_ = 0; /* --checkpoint-slots, as plan_groups() resolved it */ + 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 */ int64_t tokens_cap_ = 0; /* cap_paged_tokens(): the least any rank can carve; 0 is none */ - /* THE SLOT STRIDE AND WHERE THE SLOTS BEGIN. The stride is checkpoint_bytes_ rounded up to a - * whole number of commit granules, so a slot can be backed and released without touching a - * neighbour; the offset is where the eager startup commit stops, because everything from - * there up is backed as it is handed out. Zero on a model with no linear state. */ - bool release_frees_card_ = true; - bool ck_elastic_ = false; - int64_t ck_high_water_ = 0; - int64_t ck_backed_ = 0; - int64_t ck_stride_ = 0; - int64_t ck_region_off_ = 0; - FreeBytes ck_free_bytes_; /* set_checkpoint_floor */ - int64_t ck_keep_free_ = 0; - std::vector ck_peers_; - /* RAD_OK when this rank has the slot backed or room above the floor to back it. */ - int ck_room(int32_t slot) const; - bool ck_backed(int32_t slot) const; - /* The commit itself, with no floor: callers have asked ck_room on every rank first. */ - int ck_commit(int32_t slot); - /* ck_room on every rank, then ck_commit on every rank. */ - int ck_back_everywhere(int32_t slot); - /* What a checkpoint slot is aligned and sized to. RAD_ALIGN_UNIT on a device with no virtual - * memory management, where nothing is released and the stride is only padding. */ - int64_t ck_align() const; /* ---- the loan. See the public block for what this is and why a block that anything holds * is never lent. ---- diff --git a/core/mem/kvtier.cpp b/core/mem/kvtier.cpp index 6d0f3131..f59141e2 100644 --- a/core/mem/kvtier.cpp +++ b/core/mem/kvtier.cpp @@ -18,87 +18,6 @@ const char* kv_tier_name(KVTier t) { return "?"; } -/* ------------------------------------------------------------------ HostArena */ - -HostArena::~HostArena() { close(); } - -int HostArena::open(int64_t slot_bytes, int64_t cap_bytes) { - close(); - if (slot_bytes <= 0 || cap_bytes < slot_bytes) return RAD_E_INVAL; - const int64_t n = cap_bytes / slot_bytes; - /* PINNED, and the allocation is refused rather than downgraded. A pageable host buffer on - * this path does not fail, it just collapses -- an async copy to pageable memory serialises - * against the stream and the whole point of moving instead of dropping is gone. Better to - * start without the tier and say so than to run it at a tenth of the rate it was budgeted at. */ - base_ = rad_dev_alloc(n * slot_bytes, RAD_MEM_HOST_PINNED); - if (!base_) return RAD_E_NOMEM; - slot_bytes_ = slot_bytes; - used_ = 0; - cap_slots_ = n; - cursor_ = 0; - bits_.assign((size_t)((n + 63) / 64), 0ull); - return RAD_OK; -} - -void HostArena::close() { - if (base_) rad_dev_free(base_, RAD_MEM_HOST_PINNED); - base_ = nullptr; - slot_bytes_ = 0; - used_ = 0; - cap_slots_ = 0; - cursor_ = 0; - bits_.clear(); -} - -int32_t HostArena::alloc() { - int32_t got = 0; - return alloc_run(1, &got); -} - -/* THE FIRST FREE RUN AT OR AFTER THE CURSOR, wrapping once. A whole word of used slots is skipped - * in one compare, so a nearly full arena costs a scan of its bitmap -- a few thousand words at the - * sizes an operator gives this -- and an arena with room costs nothing. The cursor makes - * consecutive calls hand out consecutive slots, which is what lets a batch be one copy a run. */ -int32_t HostArena::alloc_run(int32_t want, int32_t* got) { - *got = 0; - if (want <= 0 || !base_ || full()) return -1; - int64_t s = -1; - for (int pass = 0; pass < 2 && s < 0; ++pass) { - const int64_t lo = pass == 0 ? cursor_ : 0; - const int64_t hi = pass == 0 ? cap_slots_ : cursor_; - for (int64_t i = lo; i < hi;) { - const uint64_t w = bits_[(size_t)(i >> 6)]; - if ((i & 63) == 0 && w == ~0ull) { i += 64; continue; } - if (!is_used(i)) { s = i; break; } - ++i; - } - } - if (s < 0) return -1; - int64_t n = 0; - while (n < want && s + n < cap_slots_ && !is_used(s + n)) { - bits_[(size_t)((s + n) >> 6)] |= 1ull << ((s + n) & 63); - ++n; - } - used_ += n; - cursor_ = s + n >= cap_slots_ ? 0 : s + n; - *got = (int32_t)n; - return (int32_t)s; -} - -void HostArena::free(int32_t slot) { - if (slot < 0 || slot >= cap_slots_) return; - /* A slot that is already free is refused rather than counted twice: the used count is what the - * sessions view reports and what `full` answers, and a negative one hides the next leak. */ - if (!is_used(slot)) return; - bits_[(size_t)(slot >> 6)] &= ~(1ull << (slot & 63)); - --used_; -} - -void* HostArena::at(int32_t slot) const { - if (!base_ || slot < 0 || slot >= cap_slots_) return nullptr; - return (char*)base_ + (int64_t)slot * slot_bytes_; -} - /* ------------------------------------------------------------------ IdleTiers */ int IdleTiers::configure(const Config& c, SSDTier* disk) { @@ -107,46 +26,24 @@ int IdleTiers::configure(const Config& c, SSDTier* disk) { cfg_ = c; disk_ = disk; - /* THE SNAPSHOT STORE IS CARVED OUT OF THE TIER, NOT ADDED TO IT. engine_bringup decides how - * much; what matters here is that the block arena is opened against what is left, so the two - * together never exceed what --prefix-cache-host-mib asked for. */ - if (cfg_.ckpt_bytes > 0 && cfg_.ckpt_cap_bytes >= cfg_.ckpt_bytes && cfg_.host_cap_bytes > 0) { - if (ck_arena_.open(cfg_.ckpt_bytes, cfg_.ckpt_cap_bytes) != RAD_OK) { - RAD_WARN("kv tiers: no pinned host memory for %s of linear-state snapshots; a hybrid " - "session's blocks will tier and its recurrent state will not", - humanb(cfg_.ckpt_cap_bytes).c_str()); - cfg_.ckpt_cap_bytes = 0; - } else { - cfg_.host_cap_bytes -= ck_arena_.cap_bytes(); - } - } else { - cfg_.ckpt_cap_bytes = 0; - } - if (cfg_.host_cap_bytes > 0 && cfg_.entry_bytes > 0) { const int st = arena_.open(cfg_.entry_bytes, cfg_.host_cap_bytes); if (st != RAD_OK) { RAD_WARN("kv tiers: no pinned host memory for %s, the host tier is off", humanb(cfg_.host_cap_bytes).c_str()); cfg_.host_cap_bytes = 0; - /* The snapshot store rides on the host tier: nothing reaches disk except through it, - * so a snapshot arena under no block arena would fill once and never drain. */ - ck_arena_.close(); - cfg_.ckpt_cap_bytes = 0; } } else { cfg_.host_cap_bytes = 0; - ck_arena_.close(); - cfg_.ckpt_cap_bytes = 0; } if (!disk_ || !disk_->enabled()) cfg_.disk_cap_bytes = 0; - /* A disk tier under no host tier is legal and it is not a mistake: the path to disk runs - * through host memory, so with no host tier nothing ever reaches disk, and saying so at + /* A disk tier under no host tier is legal and it is not a mistake: the blocks' path to disk + * runs through host memory, so with no host tier no block ever reaches disk, and saying so at * startup is cheaper than an operator reading a disk tier's zero counters for an afternoon. */ if (!host_on() && disk_on()) RAD_WARN("kv tiers: --prefix-cache-disk-mib is set but --prefix-cache-host-mib is not, and the " - "path to disk runs through host memory -- nothing will be written"); + "blocks' path to disk runs through host memory -- only snapshots will be written"); char buf[512]; if (!any_on()) { @@ -166,19 +63,20 @@ int IdleTiers::configure(const Config& c, SSDTier* disk) { humanb(cfg_.entry_bytes).c_str()); report_ = buf; /* SAID EVEN WHEN IT IS ZERO, on a model that has recurrent state. A hybrid server whose - * snapshots do not tier looks identical from every block counter there is, and the + * snapshots do not reach disk looks identical from every block counter there is, and the * difference it makes is a full linear replay of the transcript on what the hit rate will * happily report as a hit. */ if (cfg_.ckpt_bytes > 0) { std::snprintf(buf, sizeof buf, - "\nkv tiers: a session's linear state moves with its blocks -- %lld " - "snapshot(s) of %s in host memory, %lld on disk", - (long long)ck_arena_.capacity(), humanb(cfg_.ckpt_bytes).c_str(), - (long long)cfg_.ckpt_disk_slots); + "\nkv tiers: a session's linear state is saved to host memory -- %lld " + "snapshot slot(s) of %s -- and %s", + (long long)cfg_.ckpt_slots, humanb(cfg_.ckpt_bytes).c_str(), + ckpt_disk_on() + ? fmt("written on to disk (%lld slots), so a full store detaches " + "the least recently used instead of losing it", + (long long)cfg_.ckpt_disk_slots).c_str() + : "with no disk copy a full store retires the least recently used"); report_ += buf; - if (!ckpt_on()) - report_ += " -- NONE, so an idle hybrid session comes back needing a full " - "linear replay; give --prefix-cache-host-mib more room"; } } return RAD_OK; @@ -197,13 +95,15 @@ void IdleTiers::reset() { host_lru_.clear(); disk_lru_.clear(); wb_q_.clear(); + resume_q_.clear(); dk_q_.clear(); clean_q_.clear(); + ck_reading_.clear(); + ck_free_after_.clear(); ck_frees_.clear(); starved_ = 0; wb_stuck_ = false; arena_.close(); - ck_arena_.close(); disk_ = nullptr; cfg_ = Config{}; report_.clear(); @@ -230,24 +130,17 @@ void IdleTiers::relist(const BlockHash& key, Rec& r) { bool IdleTiers::wants_copy(const Rec& r) const { if (r.pending || r.doomed) return false; - const bool blocks = host_on() && r.tier == KVTier::Device && r.host_slot < 0 && !r.on_disk && - !r.blocks.empty(); - return blocks || wants_ck_copy(r); + return host_on() && r.tier == KVTier::Device && r.host_slot < 0 && !r.on_disk && + !r.blocks.empty(); } -bool IdleTiers::wants_ck_copy(const Rec& r) const { - /* A snapshot on a disk record stays where it is: the record's blocks are already past the - * host tier, and the device slot it still holds is reachable the moment they come back. */ - return ckpt_on() && r.ck_dev >= 0 && r.ck_host < 0 && !r.ck_on_disk && !r.ck_skip && - r.tier != KVTier::Disk; +bool IdleTiers::wants_ck_disk(const Rec& r) const { + return ckpt_disk_on() && !r.doomed && r.ck_slot >= 0 && !r.ck_on_disk && r.ck_disk_src < 0; } bool IdleTiers::wants_disk(const Rec& r) const { if (!disk_on() || r.doomed) return false; - const bool blocks = r.host_slot >= 0 && !r.on_disk && r.disk_src < 0; - const bool snap = cfg_.ckpt_disk_slots > 0 && r.ck_host >= 0 && !r.ck_on_disk && - r.ck_disk_src < 0; - return blocks || snap; + return (r.host_slot >= 0 && !r.on_disk && r.disk_src < 0) || wants_ck_disk(r); } void IdleTiers::queue_copy(const BlockHash& key, Rec& r) { @@ -274,12 +167,6 @@ void IdleTiers::free_host(Rec& r) { r.host_slot = -1; } -void IdleTiers::free_ck_host(Rec& r) { - if (r.ck_host < 0) return; - if (r.ck_host != r.ck_disk_src) ck_arena_.free(r.ck_host); - r.ck_host = -1; -} - /* THE ONE PLACE `on_disk` CHANGES, because the disk figure in the occupancy view is kept beside it * rather than counted, and an entry landing on disk is also what unblocks a stuck write-back. */ void IdleTiers::set_on_disk(Rec& r, bool v) { @@ -295,79 +182,69 @@ void IdleTiers::queue_clean(const BlockHash& key, Rec& r) { r.clean_q = true; } -/* EVERYTHING THIS RECORD HOLDS OFF THE CARD, both halves. The blocks' arena slot and the - * snapshot's are different arenas with different slot sizes; SSDTier owns its own slots either way - * and reclaims them by LRU, so there is nothing to give back for a disk-resident record. +/* EVERYTHING THIS RECORD HOLDS OFF THE CARD. The blocks' arena slot is the tiers'; SSDTier owns + * its own slots and reclaims them by LRU, so there is nothing to give back for a disk-resident + * copy of either half. * - * A snapshot still in its device slot is the CACHE'S, not this object's: the cache retires device - * snapshots by its own retention policy and the slot is still correct and indexed. Only a snapshot - * that exists nowhere but here is lost with the record, and only that loss is announced -- the - * cache learns about a lost ENTRY from set_drop_sink at the sites that erase one, and this is also + * A snapshot in its store slot is the CACHE'S, not this object's: the cache retires snapshots by + * its own retention policy and the slot is still correct and indexed. Only a snapshot that exists + * nowhere but on disk is lost with the record, and only that loss is announced -- the cache + * learns about a lost ENTRY from set_drop_sink at the sites that erase one, and this is also * called from forget(), where the cache is the caller and already knows. */ void IdleTiers::release_storage(const BlockHash& key, Rec& r) { free_host(r); set_on_disk(r, false); - const bool lost_ck = r.ck_dev < 0 && (r.ck_host >= 0 || r.ck_on_disk); - free_ck_host(r); + const bool lost_ck = r.ck_slot < 0 && r.ck_on_disk; r.ck_on_disk = false; if (lost_ck) { ++stats_.ck_drops; if (on_ck_drop_) on_ck_drop_(key); } } /* ------------------------------------------------------------------ the linear half */ -void IdleTiers::note_snapshot(const BlockHash& key, int32_t dev_slot, int64_t pos) { - if (dev_slot < 0) return; +void IdleTiers::note_snapshot(const BlockHash& key, int32_t slot, int64_t pos, bool resume) { + if (slot < 0) return; std::lock_guard lk(mu_); Rec& r = recs_[key]; - /* A FRESH DEVICE SNAPSHOT REPLACES WHATEVER COPY THERE WAS, never joins it. The host copy + /* A FRESH SNAPSHOT REPLACES WHATEVER DISK COPY THERE WAS, never joins it. The disk copy * described the state as it was last written; the slot now holds it as it was just written, - * and a record that called the two the same bytes would restore the older one. The copy goes - * and the snapshot is queued for a new one. - * - * Never while a copy is outstanding, for the same reason: report() owns the slot the job was - * handed and frees it when it sees the record's device slot has changed under it. */ - if (!r.pending) free_ck_host(r); + * and a record that called the two the same bytes would read the older one back. */ r.ck_on_disk = false; - r.ck_dev = dev_slot; + r.ck_slot = slot; r.ck_pos = pos; - r.ck_skip = false; - /* COPIED ONCE ITS RECORD IS PUBLISHED, like the blocks: note_used queues it then. A request - * commits its checkpoints as its prefill passes them, so copying each at commit would send the - * shallow ones across first, one at a time, while the tip does not exist yet -- and the tip is - * the one the next turn resumes from. Published together, they are planned together, and the - * plan takes the deepest first. A record the request had already published takes a new - * commit at once. */ - if (r.tier != KVTier::Device || !r.blocks.empty()) queue_copy(key, r); + /* WRITTEN TO DISK ONCE ITS RECORD IS PUBLISHED, like the blocks: note_used queues it then. A + * request commits its checkpoints as its prefill passes them and the store's retention policy + * thins them as it goes, so writing each at commit would send most of them to disk to be + * retired a moment later. A record the request had already published takes a new commit at + * once. A RESUME POINT does not wait: it is the snapshot the next turn needs, and until it is + * on disk a full store can only retire it. */ + if (r.tier != KVTier::Device || !r.blocks.empty()) queue_disk(key, r); + if (resume && !r.resume_q && wants_ck_disk(r)) { + resume_q_.push_back(key); + r.resume_q = true; + } } -bool IdleTiers::release_snapshot(const BlockHash& key) { +bool IdleTiers::release_snapshot(const BlockHash& key, int32_t slot) { std::lock_guard lk(mu_); - auto it = recs_.find(key); - if (it == recs_.end()) return false; - Rec& r = it->second; - /* A COPY IS READING THE DEVICE SLOT. The record forgets the snapshot now -- the cache no longer - * has it -- but the slot itself is held until the copy reports, because freeing it here lets - * the pool decommit a page an asynchronous transfer is still reading. */ - if (r.ck_reading && r.ck_dev >= 0) { - r.ck_free_after = r.ck_dev; - r.ck_dev = -1; - free_ck_host(r); - r.ck_on_disk = false; - return true; + bool held = false; + if (slot >= 0 && + std::find(ck_reading_.begin(), ck_reading_.end(), slot) != ck_reading_.end()) { + ck_free_after_.push_back(slot); + held = true; } - /* The host copy is the record's to free unless a job is carrying it: a pending host or disk - * record is being restored out of that very slot, and report() gives it back. A pending device - * record is a copy of its blocks, whose snapshot half -- if it has one -- is the record's own. */ - if (!r.pending || r.tier == KVTier::Device) free_ck_host(r); + auto it = recs_.find(key); + if (it == recs_.end()) return held; + Rec& r = it->second; + r.ck_slot = -1; r.ck_on_disk = false; - r.ck_dev = -1; /* A RECORD THAT ONLY EVER EXISTED FOR THE SNAPSHOT GOES WITH IT. note_snapshot creates one at * commit time, which is mid-request and long before the chain is published; a request that * never publishes -- a rebased block table, a cancel before the first whole block -- would * otherwise leave a record with no blocks, no storage and no way to be reached again. */ - if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0) + if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0 && + r.ck_disk_src < 0 && !r.disk_q) recs_.erase(it); - return false; + return held; } void IdleTiers::take_checkpoint_frees(std::vector* out) { @@ -376,66 +253,15 @@ void IdleTiers::take_checkpoint_frees(std::vector* out) { ck_frees_.clear(); } -bool IdleTiers::snapshot_reading(const BlockHash& key) const { +bool IdleTiers::slot_reading(int32_t slot) const { std::lock_guard lk(mu_); - auto it = recs_.find(key); - return it != recs_.end() && it->second.ck_reading; + return slot >= 0 && std::find(ck_reading_.begin(), ck_reading_.end(), slot) != ck_reading_.end(); } -int32_t IdleTiers::evict_snapshot_slot(bool lossless) { - /* EVERY RECORD HOLDING A SNAPSHOT'S HOST COPY IS A CANDIDATE, on the lists or not. A session - * still in VRAM holds its snapshots' host copies from the moment they land, and a search that - * looked only at the off-device lists would not see them: the first snapshot to land would keep - * the slot and every later one -- the running session's own tip among them -- would be refused - * for good. The arena is a few slots deep, so the walk is over the records, once, and only - * when a copy has found the arena full. - * - * THREE PRICES, cheapest first. A copy the disk store also holds costs nothing. A copy of a - * snapshot still in its device slot costs that slot its backing: the checkpoint pool can no - * longer detach it, only retire it, and a restore that needs a device slot can no longer take - * it. A copy that is the snapshot's only one costs the state. A restore takes only the first - * kind -- anything else trades one session's state for another's. - * - * THE TIP IS THE ONE WORTH KEEPING, so within a price the earliest POSITION loses: within a - * session that is exactly "not the tip", which is the one position an appending conversation - * will ask for and the one that makes its replay short. Across sessions it is a choice between - * snapshots that are equally not tips, and the older one goes. - * - * The slot is returned to the caller rather than freed, because the caller is about to - * allocate one: going through the free list would be the same slot and two more operations. */ - Rec* best = nullptr; - const BlockHash* best_key = nullptr; - int best_price = 3; - const uint64_t now = rad_mono_ns(); - for (auto& kv : recs_) { - Rec& r = kv.second; - if (r.pending || r.doomed || r.ck_host < 0 || r.ck_host == r.ck_disk_src || - held_by_fetch(r, now)) - continue; - const int price = r.ck_on_disk ? 0 : r.ck_dev >= 0 ? 1 : 2; - if (lossless && price > 0) continue; - if (best && (price > best_price || - (price == best_price && - (r.ck_pos > best->ck_pos || - (r.ck_pos == best->ck_pos && r.used_ns >= best->used_ns))))) - continue; - best = &r; - best_key = &kv.first; - best_price = price; - } - if (!best) return -1; - Rec& r = *best; - const int32_t s = r.ck_host; - r.ck_host = -1; - if (best_price == 2) { - ++stats_.ck_drops; - if (on_ck_drop_) on_ck_drop_(*best_key); - } else if (best_price == 1) { - /* Still in its device slot and nowhere else off the card: its index entry is as good as - * it was, and it is not queued for another copy (Rec::ck_skip). */ - r.ck_skip = true; - } - return s; +bool IdleTiers::snapshot_in_slot(const BlockHash& key, int32_t slot) const { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + return it != recs_.end() && slot >= 0 && it->second.ck_slot == slot; } /* ------------------------------------------------------------------ the cache's notices */ @@ -455,6 +281,8 @@ void IdleTiers::note_used(const BlockHash& key, const std::vector& bloc relist(key, r); } queue_copy(key, r); + /* A snapshot the request committed under this key goes to disk now that its chain is out. */ + if (wants_ck_disk(r)) queue_disk(key, r); } void IdleTiers::note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns) { @@ -550,12 +378,12 @@ bool IdleTiers::writeback_waiting() const { * to give up, so a plan would pop the queue, find no slot and put it back, every tick, until * a slot is freed or a disk copy lands -- which is what ends the wait. */ if (wb_stuck_ && arena_.full()) return false; - return !wb_q_.empty() && (host_on() || ckpt_on()); + return !wb_q_.empty() && host_on(); } bool IdleTiers::disk_waiting() const { std::lock_guard lk(mu_); - return !dk_q_.empty(); + return !dk_q_.empty() || !resume_q_.empty(); } int64_t IdleTiers::make_room(int64_t n) { @@ -622,14 +450,7 @@ bool IdleTiers::starved() const { void IdleTiers::plan_writeback(int64_t max_entries, std::vector* out) { if (!host_on() || max_entries <= 0) return; std::lock_guard lk(mu_); - /* A SEPARATE, MUCH SMALLER BUDGET FOR SNAPSHOTS, because they are not the same size of thing. - * A block entry is tens of kilobytes; a snapshot on a production hybrid is a hundred megabytes - * or more. Copying a session's whole retained set in one pass would queue most of a second of - * link time ahead of whatever the transfer stream is asked for next. */ - int ck_budget = 2; - std::vector later; /* wanted only a snapshot the budget could not take */ - std::vector ck_jobs; /* jobs whose record wants its snapshot copied too */ - size_t first = out->size(); + const size_t first = out->size(); while (!wb_q_.empty() && (int64_t)(out->size() - first) < max_entries) { const BlockHash key = wb_q_.front(); wb_q_.pop_front(); @@ -642,56 +463,16 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector* out) { j.kind = TierJob::Kind::WriteBack; j.key = key; j.bytes = cfg_.entry_bytes; - if (r.tier == KVTier::Device && r.host_slot < 0 && !r.on_disk) j.blocks = r.blocks; - if (wants_ck_copy(r)) { - j.ck_pos = r.ck_pos; - ck_jobs.push_back(out->size()); - } + j.blocks = r.blocks; out->push_back(std::move(j)); } - /* THE SNAPSHOT BUDGET GOES TO THE DEEPEST FIRST. A session commits its checkpoints in order, - * so the queue holds its shallow ones ahead of its tip -- and the tip is the one its next turn - * resumes from. Taken in queue order, the shallow ones would fill a snapshot arena a few slots - * deep and the tip would be refused for good. Across sessions a position says nothing, and the - * order among them is the queue's, which is as arbitrary as any. */ - std::stable_sort(ck_jobs.begin(), ck_jobs.end(), - [out](size_t a, size_t b) { return (*out)[a].ck_pos > (*out)[b].ck_pos; }); - for (size_t idx : ck_jobs) { - TierJob& j = (*out)[idx]; - if (ck_budget <= 0) continue; /* a later pass; the record is queued again */ - Rec& r = recs_[j.key]; - int32_t cs = ck_arena_.alloc(); - if (cs < 0) cs = evict_snapshot_slot(/*lossless=*/false); - if (cs >= 0) { - j.ck_dev = r.ck_dev; - j.ck_host = cs; - j.ck_bytes = cfg_.ckpt_bytes; - --ck_budget; - } else { - /* Nowhere to put it, and nothing to evict: this snapshot goes without a copy until a - * new commit replaces it. Waiting would retry it every pass for the same answer. */ - ++stats_.ck_starved; - r.ck_skip = true; - } - } - for (size_t i = first; i < out->size();) { - const TierJob& j = (*out)[i]; - if (j.blocks.empty() && j.ck_host < 0) { - later.push_back(j.key); - out->erase(out->begin() + (long)i); - continue; - } - ++i; - } - /* THE HOST SLOTS, AS RUNS. Taken for the whole batch at once so that entries planned together * sit together in the arena and each run crosses the link as one copy. A batch the arena - * cannot hold is cut where the arena ran out: the entries past that point keep only their - * snapshot half, or go back to the front of the queue, and the maintenance plan is told how - * many copies were refused so it can make that much room. */ - int64_t want = 0; - for (size_t i = first; i < out->size(); ++i) if (!(*out)[i].blocks.empty()) ++want; + * cannot hold is cut where the arena ran out: the entries past that point go back to the + * front of the queue, and the maintenance plan is told how many copies were refused so it can + * make that much room. */ + const int64_t want = (int64_t)(out->size() - first); if (want > arena_.free_slots()) make_room_locked(want - arena_.free_slots()); std::vector slots; slots.reserve((size_t)want); @@ -705,42 +486,29 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector* out) { std::vector refused; for (size_t i = first; i < out->size();) { TierJob& j = (*out)[i]; - if (!j.blocks.empty()) { - if (next < slots.size()) { - j.host_slot = slots[next++]; - } else { - ++starved_; - j.blocks.clear(); - if (j.ck_host < 0) { - refused.push_back(j.key); - out->erase(out->begin() + (long)i); - continue; - } - } + if (next < slots.size()) { + j.host_slot = slots[next++]; + ++i; + continue; } - ++i; + ++starved_; + refused.push_back(j.key); + out->erase(out->begin() + (long)i); } if (want > 0 && slots.empty()) wb_stuck_ = true; for (size_t i = first; i < out->size(); ++i) { - const TierJob& j = (*out)[i]; - Rec& r = recs_[j.key]; + Rec& r = recs_[(*out)[i].key]; unlist(r); r.pending = true; - r.ck_reading = j.ck_host >= 0; } - /* Back where they were: the refused ones at the front, in order, so the oldest conversation is - * still the first copied once there is room; the snapshot-only ones at the back, since the - * budget and not the arena is what held them. */ + /* Back where they were, at the front and in order, so the oldest conversation is still the + * first copied once there is room. */ for (auto it = refused.rbegin(); it != refused.rend(); ++it) { auto ri = recs_.find(*it); if (ri == recs_.end() || ri->second.queued) continue; wb_q_.push_front(*it); ri->second.queued = true; } - for (const BlockHash& k : later) { - auto ri = recs_.find(k); - if (ri != recs_.end()) queue_copy(k, ri->second); - } } void IdleTiers::take_clean(std::vector* out) { @@ -779,15 +547,14 @@ bool IdleTiers::snapshot_backed(const BlockHash& key) const { auto it = recs_.find(key); if (it == recs_.end()) return false; const Rec& r = it->second; - return !r.pending && !r.doomed && !r.ck_reading && r.ck_dev >= 0 && - (r.ck_host >= 0 || r.ck_on_disk); + return !r.doomed && r.ck_slot >= 0 && r.ck_on_disk && r.ck_disk_src < 0; } void IdleTiers::snapshot_detached(const BlockHash& key) { std::lock_guard lk(mu_); auto it = recs_.find(key); if (it == recs_.end()) return; - it->second.ck_dev = -1; + it->second.ck_slot = -1; } /* ------------------------------------------------------------------ the slow half */ @@ -795,7 +562,7 @@ void IdleTiers::snapshot_detached(const BlockHash& key) { void IdleTiers::plan(int budget, std::vector* out) { if (!any_on() || budget <= 0) return; std::lock_guard lk(mu_); - /* ---- disk copies, in the order the host copies landed ---------------------------------- */ + /* ---- disk copies: the resume points first, then in the order the host copies landed --- */ /* ONE SNAPSHOT BUDGET FOR THE WAY TO DISK, apart from the blocks'. A snapshot is a hundred * megabytes or more and the disk store copies it twice on the way out (an aligned bounce, then * the write), so a plan that sent a session's whole retained set at once would hold the IO @@ -803,6 +570,34 @@ void IdleTiers::plan(int budget, std::vector* out) { * blocks, and goes to the back of the queue for the rest. */ int ck_disk_budget = 2; int n = 0; + auto take_ck = [&](const BlockHash& key, Rec& r, TierJob& j) { + j.ck_slot = r.ck_slot; + j.ck_pos = r.ck_pos; + j.ck_bytes = cfg_.ckpt_bytes; + r.ck_disk_src = r.ck_slot; + ck_reading_.push_back(r.ck_slot); + --ck_disk_budget; + (void)key; + }; + /* A RESUME POINT IS THE SNAPSHOT THE NEXT TURN NEEDS, and the store can only retire it until + * the disk holds it. Its record's blocks are not waited for: they go through the host tier on + * their own clock. */ + while (ckpt_disk_on() && ck_disk_budget > 0 && !resume_q_.empty() && n < budget) { + const BlockHash key = resume_q_.front(); + resume_q_.pop_front(); + auto ri = recs_.find(key); + if (ri == recs_.end()) continue; + Rec& r = ri->second; + r.resume_q = false; + if (!wants_ck_disk(r)) continue; + TierJob j; + j.kind = TierJob::Kind::ToDisk; + j.key = key; + j.bytes = cfg_.entry_bytes; + take_ck(key, r, j); + out->push_back(std::move(j)); + ++n; + } std::vector later; while (disk_on() && !dk_q_.empty() && n < budget) { const BlockHash key = dk_q_.front(); @@ -821,18 +616,11 @@ void IdleTiers::plan(int budget, std::vector* out) { j.host_slot = r.host_slot; r.disk_src = r.host_slot; } - if (cfg_.ckpt_disk_slots > 0 && r.ck_host >= 0 && !r.ck_on_disk && r.ck_disk_src < 0) { - if (ck_disk_budget > 0) { - j.ck_host = r.ck_host; - j.ck_pos = r.ck_pos; - j.ck_bytes = cfg_.ckpt_bytes; - r.ck_disk_src = r.ck_host; - --ck_disk_budget; - } else { - later.push_back(key); - } + if (wants_ck_disk(r)) { + if (ck_disk_budget > 0) take_ck(key, r, j); + else later.push_back(key); } - if (j.host_slot < 0 && j.ck_host < 0) continue; + if (j.host_slot < 0 && j.ck_slot < 0) continue; out->push_back(std::move(j)); ++n; } @@ -861,7 +649,6 @@ void IdleTiers::plan(int budget, std::vector* out) { j.key = ri->first; j.host_slot = r.host_slot; j.bytes = cfg_.entry_bytes; - j.ck_host = r.ck_host; unlist(r); r.pending = true; out->push_back(std::move(j)); @@ -882,29 +669,44 @@ bool IdleTiers::plan_promote(const BlockHash& key, TierJob* out) { out->key = key; out->host_slot = r.host_slot; out->bytes = cfg_.entry_bytes; - /* THE STATE COMES BACK WITH THE BLOCKS OR THE PROMOTION IS HALF A PROMOTION. `ck_dev` is an - * output: the engine allocates the device slot, because only it holds a KVManager, and fills - * it before this record is told the move succeeded. A snapshot still in its device slot needs - * nothing -- the cache's index entry for it was never detached. */ - out->ck_dev = -1; - out->ck_host = r.ck_host; - out->ck_pos = r.ck_pos; - out->ck_want = r.ck_dev < 0 && (r.ck_host >= 0 || r.ck_on_disk); - out->ck_bytes = cfg_.ckpt_bytes; if (r.fetched_ns) ++stats_.disk_hits; else ++stats_.host_hits; unlist(r); r.pending = true; return true; } +/* THE DEEPEST SNAPSHOT ON THE CHAIN, wherever it is and whatever tier its blocks are on: that is + * the one the hit resumes from, and it is read off disk only when the disk is the one place it + * is. Its record may be in VRAM -- a snapshot can leave its slot while its blocks stay -- and then + * the read is of the snapshot alone. A record with a job out is passed over. */ +size_t IdleTiers::deepest_snapshot(const std::vector& chain) const { + size_t deep = chain.size(); + for (size_t i = 0; i < chain.size(); ++i) { + auto it = recs_.find(chain[i]); + if (it == recs_.end()) continue; + const Rec& r = it->second; + if (r.pending || r.doomed) continue; + if (r.ck_slot >= 0 || r.ck_on_disk) deep = i; + } + return deep; +} + +bool IdleTiers::snapshot_fetch_wanted(const std::vector& chain) const { + if (!ckpt_disk_on() || chain.empty()) return false; + std::lock_guard lk(mu_); + const size_t deep = deepest_snapshot(chain); + if (deep >= chain.size()) return false; + const Rec& r = recs_.find(chain[deep])->second; + return r.ck_slot < 0 && r.ck_on_disk; +} + bool IdleTiers::plan_fetch(const std::vector& chain, std::vector* out, - uint64_t now_ns) { + uint64_t now_ns, int32_t* ck_slot) { if (!disk_on() || chain.empty()) return false; std::lock_guard lk(mu_); bool wait = false; std::vector recs(chain.size(), nullptr); std::vector need; /* chain positions whose blocks are only on disk */ - size_t deep = chain.size(); /* the deepest record a restore wants a snapshot for */ for (size_t i = 0; i < chain.size(); ++i) { auto it = recs_.find(chain[i]); if (it == recs_.end()) continue; @@ -913,16 +715,18 @@ bool IdleTiers::plan_fetch(const std::vector& chain, std::vector= 0 || r.ck_on_disk)) deep = i; } - const bool ck_read = deep < chain.size() && recs[deep]->ck_host < 0 && - cfg_.ckpt_disk_slots > 0 && ck_arena_.enabled(); + const size_t deep = deepest_snapshot(chain); + Rec* deep_rec = deep < chain.size() ? &recs_.find(chain[deep])->second : nullptr; + const bool ck_read = deep_rec && deep_rec->ck_slot < 0 && deep_rec->ck_on_disk && + ckpt_disk_on() && ck_slot && *ck_slot >= 0; if (need.empty() && !ck_read) return wait; /* THE ROOM, OUT OF EVERYTHING BUT THIS CHAIN. What the disk also holds goes for nothing * (make_room); the chain's own host copies are what the restore is about to read, and giving * one up to read another would only move the gap. */ for (Rec* r : recs) if (r) r->keep = true; + if (deep_rec) deep_rec->keep = true; std::vector slots; if (!need.empty()) { const int64_t want = (int64_t)need.size(); @@ -935,12 +739,8 @@ bool IdleTiers::plan_fetch(const std::vector& chain, std::vectorkeep = false; + if (deep_rec) deep_rec->keep = false; /* IN CHAIN ORDER, AND CUT WHERE THE SLOTS RAN OUT: a hit needs a contiguous prefix, so an entry * read past a gap would be read for nothing. */ @@ -953,26 +753,24 @@ bool IdleTiers::plan_fetch(const std::vector& chain, std::vectorpush_back(std::move(j)); } - if (ck_slot >= 0) { - /* Only a snapshot the restore will reach: every disk entry at or before it has a slot. */ - const bool reached = slots.size() == need.size() || need[slots.size()] > deep; - if (!reached) { - ck_arena_.free(ck_slot); - } else { - TierJob* j = nullptr; - for (size_t k = first; k < out->size(); ++k) - if ((*out)[k].key == chain[deep]) { j = &(*out)[k]; break; } - if (!j) { - out->push_back(TierJob{}); - j = &out->back(); - j->kind = TierJob::Kind::ToHost; - j->key = chain[deep]; - j->bytes = cfg_.entry_bytes; - } - j->ck_host = ck_slot; - j->ck_pos = recs[deep]->ck_pos; - j->ck_bytes = cfg_.ckpt_bytes; + /* ONLY A SNAPSHOT THE RESTORE WILL REACH: every disk entry at or before it has a slot. + * Otherwise the store slot stays the caller's. */ + if (ck_read && (slots.size() == need.size() || need[slots.size()] > deep)) { + TierJob* j = nullptr; + for (size_t k = first; k < out->size(); ++k) + if ((*out)[k].key == chain[deep]) { j = &(*out)[k]; break; } + if (!j) { + out->push_back(TierJob{}); + j = &out->back(); + j->kind = TierJob::Kind::ToHost; + j->key = chain[deep]; + j->bytes = cfg_.entry_bytes; } + j->ck_want = true; + j->ck_slot = *ck_slot; + j->ck_pos = deep_rec->ck_pos; + j->ck_bytes = cfg_.ckpt_bytes; + *ck_slot = -1; } for (size_t k = first; k < out->size(); ++k) { Rec& r = recs_[(*out)[k].key]; @@ -1000,40 +798,50 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { if (!r || r->host_slot != job.host_slot) give_slot(job.host_slot); else if (ok) { set_on_disk(*r, true); ++stats_.to_disk; } } - if (job.ck_host >= 0) { - if (r && r->ck_disk_src == job.ck_host) r->ck_disk_src = -1; - if (!r || r->ck_host != job.ck_host) ck_arena_.free(job.ck_host); - else if (ok && job.ck_ok) { r->ck_on_disk = true; ++stats_.ck_to_disk; } + if (job.ck_slot >= 0) { + /* THE STORE SLOT IS FREE TO WRITE AGAIN, and one the cache let go of meanwhile goes + * back now. */ + auto rd = std::find(ck_reading_.begin(), ck_reading_.end(), job.ck_slot); + if (rd != ck_reading_.end()) ck_reading_.erase(rd); + auto fa = std::find(ck_free_after_.begin(), ck_free_after_.end(), job.ck_slot); + if (fa != ck_free_after_.end()) { + ck_free_after_.erase(fa); + ck_frees_.push_back(job.ck_slot); + } + /* ON DISK ONLY IF THE RECORD STILL NAMES THE SLOT THE WRITE READ. A new commit at this + * key, or a release by the cache, moved it while the write ran, and the bytes that + * landed describe a state nobody holds any more; a new commit is written on its own. */ + if (r && r->ck_disk_src == job.ck_slot) { + r->ck_disk_src = -1; + if (ok && job.ck_ok && r->ck_slot == job.ck_slot) { + r->ck_on_disk = true; + ++stats_.ck_to_disk; + } + } + if (r) queue_disk(job.key, *r); } /* A write that failed is not tried again: a store that refused it once will refuse the * next, and the entry stays host-only, which is what it was before. */ return; } + /* A store slot a read was given and nothing took goes back to the store. */ + auto ck_back = [&] { if (job.ck_want && job.ck_slot >= 0) ck_frees_.push_back(job.ck_slot); }; + if (it == recs_.end()) { - /* Nothing names the slots a copy was handed but the job itself. */ - if (job.kind == TierJob::Kind::WriteBack) { - give_slot(job.host_slot); - ck_arena_.free(job.ck_host); - } + /* Nothing names the slots a job was handed but the job itself. */ + if (job.kind == TierJob::Kind::WriteBack) give_slot(job.host_slot); + ck_back(); return; } Rec& r = it->second; r.pending = false; r.fetching = false; - const bool was_reading = r.ck_reading; - r.ck_reading = false; /* A promotion the chain was cut before, or a read that never ran, is not a failure: nothing * was tried. */ const bool may_skip = job.kind == TierJob::Kind::ToDevice || job.kind == TierJob::Kind::ToHost; if (!ok && (!may_skip || job.started)) ++stats_.failures; - /* A device slot the cache let go of while this copy read it is free to go now. */ - if (was_reading && r.ck_free_after >= 0) { - ck_frees_.push_back(r.ck_free_after); - r.ck_free_after = -1; - } - /* A record that was forgotten mid-transfer is finished off here and nowhere else. Doing it at * the top, before the per-kind handling, means no branch below has to remember to check. */ if (r.doomed) { @@ -1042,7 +850,7 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { * slot the record never owned; freeing only the record's would leak those, and freeing * the job's as well where they ARE the record's would return one slot twice. */ if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot); - if (job.ck_host >= 0 && job.ck_host != r.ck_host) ck_arena_.free(job.ck_host); + ck_back(); release_storage(job.key, r); recs_.erase(it); return; @@ -1058,21 +866,10 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { give_slot(job.host_slot); } } - if (job.ck_host >= 0) { - /* THE SNAPSHOT IS KEPT ONLY IF IT IS STILL THE ONE THAT WAS COPIED. A new commit - * at this key, or a release by the cache, moved the record's device slot while the - * copy ran, and the bytes that landed describe a state nobody holds any more. */ - if (ok && job.ck_ok && r.ck_dev == job.ck_dev && r.ck_host < 0) { - r.ck_host = job.ck_host; - ++stats_.ck_to_host; - } else { - ck_arena_.free(job.ck_host); - } - } relist(job.key, r); /* Clean now: the cache is asked whether the VRAM copy can go. */ if (r.tier == KVTier::Device && r.host_slot >= 0) queue_clean(job.key, r); - /* A copy that failed, or a snapshot the budget left behind, is tried again. */ + /* A copy that failed is tried again. */ queue_copy(job.key, r); /* And what landed goes on to disk. */ queue_disk(job.key, r); @@ -1092,30 +889,6 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { /* THE CLOCK RESTARTS: the entry came back because a request is about to hit it. */ if (now_ns) r.used_ns = now_ns; r.fetched_ns = 0; - if (job.ck_dev >= 0) { - r.ck_dev = job.ck_dev; - r.ck_host = job.ck_host; - ++stats_.ck_promoted; - } else if (job.ck_want && job.ck_host >= 0 && job.ck_ok) { - /* THE BLOCKS CAME BACK AND THE STATE DID NOT -- no device slot was free for it. - * This turn replays its linear layers from an older checkpoint or from zero, - * but the host copy is intact and is KEPT: the cache's entry for it stays - * detached, and the next time the blocks leave VRAM and come back the snapshot - * comes with them. Dropping it here would make one full slot pool cost the - * session its state for good. */ - r.ck_host = job.ck_host; - } else if (job.ck_want && job.ck_ok && r.ck_on_disk) { - /* No host slot to read the state through, and every one the arena holds is - * some other session's only copy. It stays on disk, reachable next time. */ - } else if (job.ck_want) { - /* The host copy itself could not be read -- from disk, or it was never there. - * There is nothing left to offer and the cache has to hear so. */ - if (job.ck_host >= 0 && job.ck_host != r.ck_host) ck_arena_.free(job.ck_host); - free_ck_host(r); - r.ck_on_disk = false; - ++stats_.ck_drops; - if (on_ck_drop_) on_ck_drop_(job.key); - } ++stats_.promoted; queue_clean(job.key, r); queue_disk(job.key, r); @@ -1135,22 +908,16 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { * still holds an entry naming blocks that are not ours any more, and left alone it * would serve them. */ if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot); - if (job.ck_host >= 0 && job.ck_host != r.ck_host) ck_arena_.free(job.ck_host); - { - const bool had_ck = r.ck_on_disk || r.ck_host >= 0 || job.ck_want; - free_host(r); - set_on_disk(r, false); - free_ck_host(r); - recs_.erase(it); - if (had_ck) { ++stats_.ck_drops; if (on_ck_drop_) on_ck_drop_(job.key); } - } + release_storage(job.key, r); + recs_.erase(it); if (on_drop_) on_drop_(job.key); return; case TierJob::Kind::DropHost: give_slot(job.host_slot); ++stats_.host_drops; - if (job.ck_host >= 0) { ck_arena_.free(job.ck_host); ++stats_.ck_drops; } + r.host_slot = -1; + release_storage(job.key, r); recs_.erase(it); if (on_drop_) on_drop_(job.key); return; @@ -1159,7 +926,7 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { if (!job.started) { /* NEVER READ: the slots go back and the record is where it was, on disk. */ give_slot(job.host_slot); - if (job.ck_host >= 0) ck_arena_.free(job.ck_host); + ck_back(); relist(job.key, r); return; } @@ -1168,13 +935,9 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { * not tell the tiers, and a slot that fails its verify is dropped by the read. The * record claims bytes nobody has, so it goes, and the cache has to hear so. */ give_slot(job.host_slot); - if (job.ck_host >= 0) ck_arena_.free(job.ck_host); - const bool had_ck = r.ck_dev < 0 && (r.ck_on_disk || r.ck_host >= 0); - free_host(r); - set_on_disk(r, false); - free_ck_host(r); + ck_back(); + release_storage(job.key, r); recs_.erase(it); - if (had_ck) { ++stats_.ck_drops; if (on_ck_drop_) on_ck_drop_(job.key); } if (on_drop_) on_drop_(job.key); return; } @@ -1183,14 +946,17 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) { r.tier = KVTier::Host; ++stats_.fetched; } - if (job.ck_host >= 0) { - if (job.ck_ok && r.ck_host < 0 && r.ck_dev < 0) { - r.ck_host = job.ck_host; + if (job.ck_want && job.ck_slot >= 0) { + /* THE SNAPSHOT IS IN ITS STORE SLOT AGAIN, and keeps its disk copy -- which is what + * lets the slot go again for nothing. The engine hands the slot to the cache's + * index entry (PrefixCache::reattach_snapshot). */ + if (job.ck_ok && r.ck_slot < 0) { + r.ck_slot = job.ck_slot; ++stats_.ck_fetched; } else { - ck_arena_.free(job.ck_host); - if (!job.ck_ok && r.ck_dev < 0 && r.ck_host < 0 && r.ck_on_disk) { - /* The snapshot store lost it; the blocks are still good. */ + ck_back(); + if (!job.ck_ok && r.ck_slot < 0 && r.ck_on_disk) { + /* The disk store lost it; the blocks are still good. */ r.ck_on_disk = false; ++stats_.ck_drops; if (on_ck_drop_) on_ck_drop_(job.key); @@ -1318,11 +1084,11 @@ std::vector IdleTiers::sessions(Occupancy* occ) const { out.push_back(std::move(si)); } } - /* SNAPSHOTS ON DISK, each once. Nothing keeps a running count of them -- a host snapshot has - * an arena slot to count and a disk one has only a flag on its record -- and this walk visits + /* SNAPSHOTS IN THE STORE AND ON DISK, each once. The store is the engine's and is not read + * from this thread, and a disk snapshot has only a flag on its record -- but this walk visits * every record a stored conversation reaches, so it counts them here. They are sparse, one - * per checkpoint interval, so the set stays small beside the walk that fills it. */ - std::unordered_set disk_snaps; + * per checkpoint interval, so the sets stay small beside the walk that fills them. */ + std::unordered_set disk_snaps, host_snaps; size_t kept = 0; for (size_t k = 0; k < out.size(); ++k) { SessionInfo& si = out[k]; @@ -1351,15 +1117,13 @@ std::vector IdleTiers::sessions(Occupancy* occ) const { case KVTier::Disk: ++si.on_disk; break; } /* THE LINEAR HALF, COUNTED WHERE ITS BYTES ACTUALLY ARE and not where the blocks - * are. They normally agree, because a snapshot moves with the record it belongs - * to; when they do not -- a snapshot that could not be placed and stayed on the - * device -- the page says so rather than averaging the two into something neither - * is. */ - const bool ck = rr.ck_dev >= 0 || rr.ck_host >= 0 || rr.ck_on_disk; - if (rr.ck_dev >= 0) { ++si.snapshots; ++si.snap_device; } - else if (rr.ck_host >= 0) { ++si.snapshots; ++si.snap_host; } + * are: a snapshot is in host memory from the moment it is saved, whatever tier + * its blocks are on, and on disk alone once the store has given its slot up. */ + const bool ck = rr.ck_slot >= 0 || rr.ck_on_disk; + if (rr.ck_slot >= 0) { ++si.snapshots; ++si.snap_host; } else if (rr.ck_on_disk) { ++si.snapshots; ++si.snap_disk; } if (rr.ck_on_disk && occ) disk_snaps.insert(h); + if (rr.ck_slot >= 0 && occ) host_snaps.insert(h); if (ck && rr.ck_pos > si.resume_tokens) si.resume_tokens = rr.ck_pos; } if (at >= chain.size()) break; @@ -1377,11 +1141,12 @@ std::vector IdleTiers::sessions(Occupancy* occ) const { if (occ) { Slice lk(mu_); occ->host_bytes = arena_.used_slots() * cfg_.entry_bytes + - ck_arena_.used_slots() * cfg_.ckpt_bytes; + (int64_t)host_snaps.size() * cfg_.ckpt_bytes; occ->disk_bytes = stats_.disk_bytes + (int64_t)disk_snaps.size() * cfg_.ckpt_bytes; - /* The cap the operator gave, which the snapshot store was carved out of -- the same scope - * as `host_bytes` above, which counts both arenas. */ - occ->host_cap_bytes = host_on() ? cfg_.host_cap_bytes + ck_arena_.cap_bytes() : 0; + /* What the operator gave the block arena and the snapshot store -- the same scope as + * `host_bytes` above, which counts both. */ + occ->host_cap_bytes = (host_on() ? cfg_.host_cap_bytes : 0) + + cfg_.ckpt_slots * cfg_.ckpt_bytes; occ->disk_cap_bytes = disk_on() ? cfg_.disk_cap_bytes : 0; } return out; diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h index bcb7194b..b5acbbb1 100644 --- a/core/mem/kvtier.h +++ b/core/mem/kvtier.h @@ -78,6 +78,7 @@ * such a transfer -- it reads host memory and nothing else -- and holds only the slots it reads. */ #pragma once +#include "mem/hostarena.h" #include "mem/kv.h" #include "mem/prefix.h" #include "rad_core.h" @@ -123,30 +124,23 @@ struct TierJob { /* ---- the linear half, on a hybrid model ---- * - * A session's recurrent state lives in a CHECKPOINT SLOT rather than in blocks: one contiguous - * KVManager::checkpoint_bytes() extent, which is why nothing here needs a gather. The snapshot - * belonging to this entry moves with it, so a restored hybrid session gets its attention hit - * AND its state back, instead of an attention hit and a full linear replay from token zero. + * A session's recurrent state lives in a SNAPSHOT SLOT of the checkpoint store -- pinned host + * memory, one contiguous KVManager::checkpoint_bytes() shard a rank -- rather than in blocks, + * so it never crosses the link with them: a lookup restores it straight out of its slot. The + * tiers only move it between that slot and the disk store, on the disk thread: a ToDisk job + * reads `ck_slot`, a ToHost job writes it. * - * `ck_dev` is the device slot: where the bytes are read from on the way out, and where the - * engine put them on the way in -- it is an OUTPUT of a promotion, exactly as `blocks` is. */ - int32_t ck_dev = -1; - int32_t ck_host = -1; /* a slot in the snapshot arena, not the block arena */ + * `ck_slot` is an INPUT to both. A read off disk is planned with `ck_want` and the engine + * allocates the slot before the job leaves its hands (it holds the store's free list); a + * write names the slot the snapshot is in. */ + int32_t ck_slot = -1; int64_t ck_pos = 0; /* the token position, which the disk store verifies on the way back */ - bool ck_want = false; /* a promotion should bring the snapshot back too */ - /* DID THE SNAPSHOT HALF SUCCEED. Separate from the job's own result because the two halves - * fail for different reasons and are repaired differently: a snapshot that could not be copied - * has not been damaged, it is still sitting correct and committed in its device slot and a - * later pass reaches it again for free, so the blocks may as well carry on without it. - * - * A snapshot that is DROPPED is another matter, and it is worth being exact about the cost - * because it is not what it looks like. On this build the scheduler clamps a hybrid session's - * reuse to the last LINEAR CHECKPOINT it can reach, not to the attention hit -- RadBatch - * carries one query length for every KV group, so the linear layers cannot be replayed over a - * longer range than the attention ones (core/sched/scheduler.cpp, admit_one). A session whose - * blocks came back and whose state did not therefore reuses NOTHING. The blocks are not a - * partial win; they are unusable until some checkpoint under them survives. */ + bool ck_want = false; /* a read off disk should bring the snapshot in too */ int64_t ck_bytes = 0; + /* DID THE SNAPSHOT HALF SUCCEED. Separate from the job's own result because the two halves + * fail for different reasons and are repaired differently: a snapshot whose disk write failed + * is still correct in its slot, and one whose read failed costs the session a replay of its + * linear layers, not its blocks. */ bool ck_ok = true; /* A PROMOTION THAT WAS NEVER STARTED, as opposed to one that failed part of the way through. * A restore reserves every block before it moves a byte, and a chain that did not fit is cut @@ -157,54 +151,6 @@ struct TierJob { bool started = false; }; -/* ------------------------------------------------------------------ the host arena */ -/* Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the - * driver stages an async copy to pageable memory through its own buffer and, on some paths, - * synchronises. Slot-allocated at one - * fixed size rather than malloc'd per entry: every entry in a given model holds exactly one block - * per cached group, so the size is a property of the geometry and a bitmap is the whole allocator. - * - * RUNS, BECAUSE A TRANSFER IS PER RUN. A 4-token block makes a 200K-token conversation fifty - * thousand entries, and a copy per entry is fifty thousand driver calls on the engine thread -- - * the call rate, not the link, is then what a restore costs. Entries written together are given - * consecutive slots wherever the arena has them, so a batch crosses the link as one strided copy - * a run. */ -class HostArena { -public: - ~HostArena(); - int open(int64_t slot_bytes, int64_t cap_bytes); - void close(); - bool enabled() const { return base_ != nullptr; } - - int64_t slot_bytes() const { return slot_bytes_; } - /* Fixed when the arena is opened. Stored rather than counted from the bitmap, because an - * HTTP thread reads it for the sessions view while the engine thread allocates and frees. */ - int64_t capacity() const { return cap_slots_; } - int64_t used_slots() const { return used_; } - int64_t cap_bytes() const { return slot_bytes_ * capacity(); } - int64_t free_slots() const { return cap_slots_ - used_; } - - /* -1 when the arena is full. The caller evicts and retries; this does not choose victims, - * because the LRU that would choose them lives in IdleTiers and an allocator that reached - * into it would give each record two owners. */ - bool full() const { return used_ >= cap_slots_; } - int32_t alloc(); - /* UP TO `want` CONSECUTIVE SLOTS, the first free run at or after the cursor. `*got` is how - * many; the caller asks again for the rest. -1 when the arena is full. */ - int32_t alloc_run(int32_t want, int32_t* got); - void free(int32_t slot); - void* at(int32_t slot) const; - -private: - bool is_used(int64_t s) const { return (bits_[(size_t)(s >> 6)] >> (s & 63)) & 1ull; } - void* base_ = nullptr; - int64_t slot_bytes_ = 0; - int64_t used_ = 0; - int64_t cap_slots_ = 0; - int64_t cursor_ = 0; - std::vector bits_; -}; - /* ------------------------------------------------------------------ the policy */ class IdleTiers { public: @@ -214,12 +160,11 @@ public: int64_t entry_bytes = 0; /* one entry: sum over cached groups of bytes_per_block */ /* ---- the linear half ---- * `ckpt_bytes` is ONE SNAPSHOT, every rank's shard of it, laid out exactly like - * `entry_bytes`. `ckpt_cap_bytes` is carved out of the tier the operator sized rather than - * added to it: a snapshot store is host memory like any other and a tier that quietly - * allocated past its stated cap would be the one thing --prefix-cache-host-mib is for. Zero - * for either means snapshots do not tier, and the blocks still do. */ + * `entry_bytes`. The snapshots live in the engine's checkpoint store, `ckpt_slots` deep, + * which is reported here and not allocated: --prefix-cache-host-mib is the blocks' alone. + * `ckpt_disk_slots` zero means snapshots never reach disk, and the blocks still do. */ int64_t ckpt_bytes = 0; - int64_t ckpt_cap_bytes = 0; /* host; part of host_cap_bytes, not additional to it */ + int64_t ckpt_slots = 0; /* the checkpoint store's capacity, for the report and view */ int64_t ckpt_disk_slots = 0; /* how many the disk store was opened for */ }; @@ -262,10 +207,7 @@ public: * * The records waiting for a host copy, up to `max_entries`, as WriteBack jobs with their host * slots already allocated. Oldest first, so a conversation that went idle before another is - * copied before it. A record whose snapshot is still only on the device is included even when - * its blocks already have their copy, with `blocks` empty -- the snapshot is the half a hybrid - * session cannot resume without, and it becomes copyable later than the blocks (a checkpoint - * is committed on its own clock). + * copied before it. Blocks only: a snapshot is in host memory from the moment it is saved. * * Every record named by a returned job is `pending` until report() is called for it. An arena * too full to take the batch first gives up the host slots of the oldest entries the disk also @@ -286,32 +228,31 @@ public: bool droppable(const BlockHash& key) const; /* The cache released the blocks. The record is now a host record with its copy, on the host * tier's list like any other -- or a disk record, when its host slot was already given up. - * - * ITS SNAPSHOT STAYS WHERE IT IS. A snapshot's device slot is not memory anything else can - * use -- the expert slab borrows blocks, never checkpoint slots -- so taking it off the device - * along with the blocks would buy nothing and put the session's recurrent state at the mercy - * of a host arena a few snapshots deep, shared by every conversation. The slot goes when the - * checkpoint pool itself needs it (snapshot_backed). */ + * Its snapshot stays in its slot: the store is not the pool, and the blocks leaving frees + * nothing there. */ void drop_commit(const BlockHash& key); /* ---------------- the snapshots' own pressure ---------------- * - * The checkpoint pool is --checkpoint-slots deep for the whole server, and when it is full the - * cache retires the least recently used snapshot to make room. One whose bytes the tiers also - * hold need not be lost: the cache DETACHES it instead -- the slot goes back, the index entry - * stays, and the next restore of the session brings the state back with the blocks. True when - * this key's device snapshot has a finished copy off the card that nothing is still writing. */ + * The checkpoint store is --checkpoint-slots deep for the whole server, and when it is full + * the cache retires the least recently used snapshot to make room. One the disk also holds + * need not be lost: the cache DETACHES it instead -- the slot goes back, the index entry + * stays, and the next restore of the session reads the state back off disk (plan_fetch). + * True when this key's snapshot is in a slot and has a finished disk copy that no write is + * still producing. */ bool snapshot_backed(const BlockHash& key) const; - /* The cache gave the device slot back; the copy off the card is now the snapshot. */ + /* Is this key's snapshot in store slot `slot` by this object's record? */ + bool snapshot_in_slot(const BlockHash& key, int32_t slot) const; + /* The cache gave the slot back; the disk copy is now the snapshot. */ void snapshot_detached(const BlockHash& key); /* ---------------- the slow half ---------------- * * The host copies waiting for their disk copy, in the order they landed, as ToDisk jobs -- - * blocks and snapshot halves together where both are waiting. A ToDisk job does NOT make its - * record pending: it only reads the host slots it names, which a restore may read at the same - * time, and a slot the record gives up while the write is out is freed when the write reports - * rather than under it. With no disk tier, the copies the arena refused since the last plan + * blocks and snapshot halves together where both are waiting, and a resume point's snapshot + * ahead of everything (note_snapshot). A ToDisk job does NOT make its record pending: it only + * reads the host slots it names, which a restore may read at the same time, and a slot given + * up while the write is out is freed when the write reports rather than under it. With no disk tier, the copies the arena refused since the last plan * are made room for by dropping that many of the oldest host-only entries. `budget` bounds * one plan so the IO a pass asks for is bounded too. */ void plan(int budget, std::vector* out); @@ -340,12 +281,17 @@ public: * none of the chain is on disk, or none of what is can be given a slot -- a chain larger than * the arena comes back as far as the arena holds, and the rest is prefilled. * - * The chain's deepest snapshot that is only on disk is read with it, into the snapshot arena, - * because that is the state the hit resumes from (TierExec::issue_restore). Every record named - * is `pending` until the read reports, and what a read brought in is not given up to make - * room for anybody else until the request has had the step it needs to claim it. */ + * The chain's deepest snapshot, when it is only on disk, is read with it -- that is the state + * the hit resumes from -- into the store slot `*ck_slot` the caller allocated after asking + * snapshot_fetch_wanted. The slot is taken (and `*ck_slot` set to -1) only when the read is + * planned; otherwise it is still the caller's to free. Every record named is `pending` until + * the read reports, and what a read brought in is not given up to make room for anybody else + * until the request has had the step it needs to claim it. */ bool plan_fetch(const std::vector& chain, std::vector* out, - uint64_t now_ns); + uint64_t now_ns, int32_t* ck_slot = nullptr); + /* Would plan_fetch read this chain's deepest snapshot off disk -- is it there and nowhere + * else? Asked first, because the slot it reads into is the store's, which the caller owns. */ + bool snapshot_fetch_wanted(const std::vector& chain) const; /* A promotion, asked for by a lookup that hit off-device. Returns false when the entry is not * in host memory -- a disk entry is read in by plan_fetch first -- or already has work @@ -382,38 +328,42 @@ public: * * Told by PrefixCache::commit_checkpoint, for the same reason note_used carries the block ids: * a copy has to know what to move and the cache's index is the only place it is written down. - * `dev_slot` is a KVManager checkpoint slot and `pos` the token position the disk store - * verifies a read against. + * `slot` is a checkpoint store slot and `pos` the token position the disk store verifies a + * read against. * * A record may hear this BEFORE it hears note_used -- a checkpoint is committed mid-request * and the chain is published when the request closes -- so this creates the record if it has - * to. The snapshot is queued for a copy when the record is published, or at once when it - * already was. */ - void note_snapshot(const BlockHash& key, int32_t dev_slot, int64_t pos); - /* The cache is done with the snapshot at `key`: return whatever tier storage holds it. The - * record's BLOCKS are untouched -- the two halves are retired by different policies on - * different clocks, and a snapshot the retention policy drops says nothing about the prefix. + * to. The snapshot is queued for its disk copy when the record is published, or at once when + * it already was -- or AT ONCE AND AHEAD OF EVERYTHING when it is a resume point (`resume`): + * the deepest checkpoint its prompt gets, which the next turn resumes from. Until it is on disk + * the store can only retire it, and a burst of prefills churns the store through the whole + * decode in between. */ + void note_snapshot(const BlockHash& key, int32_t slot, int64_t pos, bool resume = false); + /* The cache is done with the snapshot at `key`, which is in store slot `slot`: return whatever + * the tiers hold for it. The record's BLOCKS are untouched -- the two halves are retired by + * different policies on different clocks, and a snapshot the retention policy drops says + * nothing about the prefix. * - * TRUE WHEN A COPY IS STILL READING THE DEVICE SLOT, and then the slot is NOT the caller's to - * free: an asynchronous copy out of a slot the pool has decommitted reads a page that is no - * longer there, which is a device fault rather than a stale byte. The tiers keep the slot and - * hand it back through `take_checkpoint_frees` once the copy has reported. */ - bool release_snapshot(const BlockHash& key); - /* Device checkpoint slots whose release waited on a copy, now safe to free. */ + * TRUE WHEN A DISK WRITE IS STILL READING THE SLOT, and then the slot is NOT the caller's to + * free: a save into it would put half of another snapshot on disk under this key. The tiers + * keep the slot and hand it back through `take_checkpoint_frees` once the write has reported. + * Decided by the slot and not by the record, which may have gone while the write was out. */ + bool release_snapshot(const BlockHash& key, int32_t slot); + /* Store slots whose release waited on a disk write, now safe to free. */ void take_checkpoint_frees(std::vector* out); - /* Is a copy reading this key's device snapshot right now? A save into that slot would tear it. */ - bool snapshot_reading(const BlockHash& key) const; - /* THE TIERS LOST A SNAPSHOT BUT KEPT THE BLOCKS. The snapshot store is far smaller than the - * block store (a snapshot is thousands of blocks' worth of bytes) so it overflows first and on - * its own, and the cache has to stop offering an index entry whose bytes nobody holds. Wired - * to PrefixCache::drop_snapshot; separate from set_drop_sink because losing half an entry and - * losing all of it are different events with different repairs. */ + /* Is a disk write reading store slot `slot` right now? A save into it would tear the write. */ + bool slot_reading(int32_t slot) const; + /* THE TIERS LOST A SNAPSHOT BUT KEPT THE BLOCKS: its only copy was on disk and the disk store + * no longer has it. The cache has to stop offering an index entry whose bytes nobody holds. + * Wired to PrefixCache::drop_snapshot; separate from set_drop_sink because losing half an + * entry and losing all of it are different events with different repairs. Never said of a + * snapshot still in its slot: that one is the cache's. */ void set_snapshot_drop_sink(std::function f) { on_ck_drop_ = std::move(f); } - bool ckpt_on() const { return ck_arena_.enabled(); } + /* Do snapshots reach disk at all? */ + bool ckpt_disk_on() const { return disk_on() && cfg_.ckpt_bytes > 0 && cfg_.ckpt_disk_slots > 0; } int64_t ckpt_bytes() const { return cfg_.ckpt_bytes; } - HostArena& ckpt_arena() { return ck_arena_; } - const HostArena& ckpt_arena() const { return ck_arena_; } - int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; } + int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; } + int64_t ckpt_slots() const { return cfg_.ckpt_slots; } /* ---------------- the session view ---------------- * @@ -440,11 +390,11 @@ public: int64_t on_device = 0, on_host = 0, on_disk = 0; /* blocks, by tier */ /* LINEAR STATE, on a hybrid model. Counted separately from blocks because it is a * different resource with a different scarcity: a snapshot is thousands of blocks' worth - * of bytes and there are only --checkpoint-slots of them on the device. A session showing + * of bytes and there are only --checkpoint-slots of them in host memory. A session showing * blocks on disk and no snapshot anywhere is one that will come back and re-run every * recurrent layer over its whole transcript, which is not what "restored" should mean. */ int64_t snapshots = 0; /* this session holds, any tier */ - int64_t snap_device = 0, snap_host = 0, snap_disk = 0; + int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */ int64_t snap_bytes = 0; /* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain, in any * tier. On a hybrid model the scheduler clamps a hit to the last linear checkpoint it can @@ -500,9 +450,17 @@ public: int64_t fetched = 0, ck_fetched = 0; /* SNAPSHOTS MOVED, counted apart from blocks. A hybrid session can move its whole chain * off the device and still replay every linear layer from zero on the way back, and no - * block counter can tell the two apart -- these are the numbers that can. */ - int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0; + * block counter can tell the two apart -- these are the numbers that can. `ck_drops` is + * snapshots whose only copy was lost. */ + int64_t ck_to_disk = 0, ck_drops = 0; + /* WHAT THE STEP THREAD SPENT ON THEM, under the scheduler's lock: restores issued at + * admission, and copies landed synchronously because pressure could not wait for them. + * Host time, not link time -- what every other request waits through. */ + int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0; }; + /* The step thread's own time on the tiers (see Stats). */ + void note_restore(int64_t ns) { std::lock_guard lk(mu_); ++stats_.restores; stats_.restore_ns += ns; } + void note_flush(int64_t ns) { std::lock_guard lk(mu_); ++stats_.flushes; stats_.flush_ns += ns; } /* A copy, taken under the lock: an HTTP thread reads these while the engine thread moves * records. */ Stats stats() const; @@ -529,30 +487,19 @@ private: bool fetching = false; /* the pending job is a read off disk (plan_fetch) */ bool doomed = false; /* forget() arrived while pending */ bool queued = false; /* in wb_q_: waiting for a copy */ + bool resume_q = false; /* in resume_q_: a resume point waiting for its disk copy */ bool clean_q = false; /* in clean_q_: a drop the cache has not been asked about */ bool listed = false; /* on host_lru_ or disk_lru_; `it` is valid */ std::vector blocks; /* ---- the linear half ---- - * `ck_dev` is the snapshot's device slot, `ck_host` its host copy and `ck_on_disk` the - * disk store's. A clean device snapshot has both of the first two; a snapshot that has - * left the device has no `ck_dev`. All clear when the record carries no snapshot, which is - * the common case -- one block in every (interval / block_size) is a checkpoint position. */ - int32_t ck_dev = -1; - int32_t ck_host = -1; + * `ck_slot` is the snapshot's checkpoint store slot and `ck_on_disk` the disk store's + * copy. A snapshot the store gave up has only the second. All clear when the record + * carries no snapshot, which is the common case -- one block in every + * (interval / block_size) is a checkpoint position. */ + int32_t ck_slot = -1; bool ck_on_disk = false; int64_t ck_pos = 0; - /* A COPY IS READING `ck_dev` RIGHT NOW: set when a write-back takes the snapshot, cleared - * when it reports. The one moment the device slot is not the cache's to free. */ - bool ck_reading = false; - /* THIS SNAPSHOT WILL NOT BE COPIED AGAIN: its copy was refused for want of room, or taken - * back to make room for another. The snapshot store is a few slots deep for the whole - * server, and a snapshot still in its device slot re-queued the moment its copy was - * evicted would evict the next one's, and so on -- every pass copying a hundred megabytes - * a rank to throw another hundred away. Cleared when a new commit replaces the state. */ - bool ck_skip = false; - /* A device slot the cache let go of while a copy was reading it. See release_snapshot. */ - int32_t ck_free_after = -1; - /* The snapshot host slot a disk write is reading, as `disk_src` is for the blocks. */ + /* The store slot a disk write is reading, as `disk_src` is for the blocks. */ int32_t ck_disk_src = -1; /* WHEN A READ OFF DISK BROUGHT THIS RECORD IN, 0 when none did or its restore has run. * Until the request that asked for it has been admitted the slots are its and not the @@ -566,24 +513,20 @@ private: std::list::iterator it; }; - /* Does this record want a copy it does not have yet? The blocks when they are in VRAM with no - * copy off the card; the snapshot when it is in a device slot with no copy off the card and - * the snapshot store exists at all. */ + /* Does this record want a host copy it does not have yet? Its blocks are in VRAM with none. */ bool wants_copy(const Rec& r) const; - /* The snapshot half of that on its own. */ - bool wants_ck_copy(const Rec& r) const; /* And a disk copy: a host copy of either half that the disk does not hold yet. */ bool wants_disk(const Rec& r) const; + bool wants_ck_disk(const Rec& r) const; void queue_copy(const BlockHash& key, Rec& r); void queue_clean(const BlockHash& key, Rec& r); void queue_disk(const BlockHash& key, Rec& r); /* GIVE UP A HOST SLOT, the record's or a finished job's. Every block-arena free goes through * `give_slot`, because a freed slot is what unblocks a write-back that found the arena full. - * `free_host` / `free_ck_host` are the record's own: a slot a disk write is reading is left + * `free_host` is the record's own: a slot a disk write is reading is left * for that write's report to free. */ void give_slot(int32_t slot); void free_host(Rec& r); - void free_ck_host(Rec& r); void set_on_disk(Rec& r, bool v); int64_t make_room_locked(int64_t n); /* May this record's host copies be given up to make room right now? Not while a read put @@ -594,12 +537,8 @@ private: void relist(const BlockHash& key, Rec& r); std::list& list_for(KVTier t) { return t == KVTier::Host ? host_lru_ : disk_lru_; } void release_storage(const BlockHash& key, Rec& r); - /* Take a snapshot arena slot from the record whose host copy is cheapest to lose, and tell the - * cache if that was the snapshot's only copy. NO SECOND LIST: the records are walked, which - * keeps the header's "one record, one tier, one list" rule intact. `lossless` takes only a - * snapshot the disk also holds. - * Returns -1 when there is none to take. */ - int32_t evict_snapshot_slot(bool lossless); + /* The chain position of the deepest snapshot no job is out on, or chain.size(). */ + size_t deepest_snapshot(const std::vector& chain) const; struct Session { int64_t n_tokens = 0; @@ -655,16 +594,21 @@ private: Config cfg_; SSDTier* disk_ = nullptr; HostArena arena_; - HostArena ck_arena_; /* snapshots; a different slot size, so a different arena */ std::unordered_map recs_; std::list host_lru_, disk_lru_; /* front = oldest */ /* THE WORK QUEUES, in the order the work arrived. Each holds a key at most once -- the Rec's * flag says whether it is in -- and a key whose record changed under it is skipped when it is * reached rather than searched for, so both stay a push and a pop. */ std::deque wb_q_; /* records wanting a host copy */ + std::deque resume_q_; /* resume points wanting a disk copy, served first */ std::deque dk_q_; /* records wanting a disk copy, in the order they landed */ std::vector clean_q_; /* records whose VRAM copy may now go */ - std::vector ck_frees_; /* device checkpoint slots a finished copy released */ + /* STORE SLOTS A DISK WRITE IS READING, and those the cache let go of meanwhile. Kept by slot + * and not on the record, because the record can be forgotten while the write is out and the + * slot is the cache's either way. A few entries at most: one write batch is out at a time. */ + std::vector ck_reading_; + std::vector ck_free_after_; + std::vector ck_frees_; /* store slots a finished write released */ /* COPIES THE ARENA REFUSED since the last maintenance plan, which is what that plan frees * room for. A count and not a list: any host-only entry makes room for any copy. */ int64_t starved_ = 0; diff --git a/core/mem/pools.cpp b/core/mem/pools.cpp index c3aeec37..b28b1d7a 100644 --- a/core/mem/pools.cpp +++ b/core/mem/pools.cpp @@ -213,7 +213,7 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity, if (cfg.vram_kv_mib <= 0) missing += " vram_kv resolved to 0 MiB\n"; if (!missing.empty()) { fit_report_ = "VRAM pool budgets are empty -- state --vram-weights-mib / --vram-kv-mib, or " - "let the card be split by --gpu-headroom-mib and --expert-vs-cache-ratio:\n" + "let the card be split from --gpu-headroom-mib and --host-pool-mib:\n" + missing; RAD_ERR("%s", fit_report_.c_str()); return RAD_E_INVAL; @@ -230,9 +230,8 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity, " total %10s\n" " card total %10s\n" " OVER BY %10s\n" - "Lower --vram-weights-mib / --vram-kv-mib, or raise --gpu-headroom-mib and let " - "--expert-vs-cache-ratio split what is left. The split is yours to make; the engine " - "will not make it for you (spec §6).\n", + "Lower --vram-weights-mib / --vram-kv-mib, or state neither and let the card be split " + "from --gpu-headroom-mib and --host-pool-mib (spec §6).\n", humanb(w).c_str(), humanb(kv).c_str(), humanb(want).c_str(), humanb(vram_capacity).c_str(), humanb(want - vram_capacity).c_str()); diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index 290a0650..4db5cd4f 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -184,7 +184,7 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ enabled_ = true; report_ = fmt("prefix cache: %zu paged group(s) at %lld-token blocks; linear checkpoints " - "every %lld tokens (%s x %s), retention '%s'\n", + "every %lld tokens (%s a rank x %s, pinned host memory), retention '%s'\n", groups_.size(), (long long)block_size_, (long long)(has_linear_ ? interval_ : 0), humanb(kv->checkpoint_bytes()).c_str(), @@ -279,26 +279,38 @@ CacheHit PrefixCache::lookup(const std::vector& tokens, /* ---- the split: how far the LINEAR state can be reused ---- * The attention blocks are reusable up to n_attn_tokens. The recurrent state is only reusable - * at a checkpoint, so walk back to the last checkpoint boundary at or below n_attn_tokens and - * look it up by the chained hash there. The gap between the two is replayed through the linear - * layers only -- the attention layers for those tokens are already in the cache. */ + * at a checkpoint: the deepest snapshot at or below n_attn_tokens on this chain, in its store + * slot. The scheduler resumes from there (Scheduler::admit_one) and recomputes the tokens + * between the two. */ if (!has_linear_) { /* No recurrent state means nothing to replay: the whole attention hit is directly usable. */ hit.n_linear_tokens = hit.n_attn_tokens; return hit; } - for (int64_t p = (hit.n_attn_tokens / interval_) * interval_; p > 0; p -= interval_) { - const BlockHash& h = hs[(size_t)(p / block_size_ - 1)]; - auto it = ck_by_prefix_.find(h); - if (it == ck_by_prefix_.end() || !it->second.valid) continue; - hit.n_linear_tokens = (int32_t)p; - hit.checkpoint_slot = it->second.slot; - it->second.used = ++clock_; - handed_.push_back(h); - ++stats_.ckpt_hits; + /* OVER THE SNAPSHOTS, NOT OVER THE POSITIONS. A checkpoint sits on the interval or at the + * tail of a prompt (Scheduler::plan_chunk), which is any block boundary, so the deepest one + * under the hit is found by asking each snapshot whether this chain passes through it: its + * key is the chained hash at its own position, which matches only on the same prefix. The + * index holds a few hundred snapshots against tens of thousands of block positions. */ + auto best = ck_by_prefix_.end(); + for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) { + const Ckpt& c = it->second; + if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > hit.n_attn_tokens || + c.pos % block_size_ != 0) + continue; + if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue; + if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue; + best = it; + } + if (best == ck_by_prefix_.end()) { + ++stats_.ckpt_misses; return hit; } - ++stats_.ckpt_misses; + hit.n_linear_tokens = (int32_t)best->second.pos; + hit.checkpoint_slot = best->second.slot; + best->second.used = ++clock_; + handed_.push_back(best->first); + ++stats_.ckpt_hits; return hit; } @@ -393,6 +405,27 @@ int PrefixCache::insert(uint64_t session, } tiers_->note_session(session, hs, n_tokens, now); } + + /* A CONVERSATION'S SNAPSHOTS BELONG TO ITS LATEST TURN. The index keys a session by REQUEST + * id, so each turn would otherwise keep its own tip forever: turn N-1's deepest snapshot stays + * a "tip" after turn N has resumed from it and written deeper ones, and the retention policy + * then guards a dozen dead tips across a long agent run while thinning the one conversation + * that is live. Every snapshot on the chain this request just published is a prefix of it, + * and is moved under this id, so the policy sees one session with one tip. */ + for (auto& kvp : ck_by_prefix_) { + Ckpt& c = kvp.second; + if (c.session == session || c.pos <= 0 || c.pos > n_full * block_size_ || + c.pos % block_size_ != 0 || hs[(size_t)(c.pos / block_size_ - 1)] != kvp.first) + continue; + auto old = ck_by_session_.find(c.session); + if (old != ck_by_session_.end()) { + old->second.erase(std::remove(old->second.begin(), old->second.end(), kvp.first), + old->second.end()); + if (old->second.empty()) ck_by_session_.erase(old); + } + c.session = session; + ck_by_session_[session].push_back(kvp.first); + } return RAD_OK; } @@ -406,7 +439,10 @@ std::vector PrefixCache::restorable_from(const std::vector& if (chain) chain->clear(); if (!enabled_ || !tiers_ || tokens.empty()) return out; - const int64_t n_full = (int64_t)tokens.size() / block_size_; + /* THE BLOCKS A HIT CAN USE: one token must remain to compute a logit from, so a prompt that + * ends on a block boundary never reuses its last block (lookup backs off by one) and neither + * restoring it nor bringing back a snapshot keyed there would be read. */ + const int64_t n_full = ((int64_t)tokens.size() - 1) / block_size_; std::vector hs = chain_all(tokens, mm, n_full); /* Walk exactly as lookup does, and keep walking past the point it stopped for as long as the @@ -447,10 +483,13 @@ void PrefixCache::drop_offdevice(const BlockHash& key) { if (it->second.in_lru) lru_.erase(it->second.lru); map_.erase(it); ++stats_.evictions; - /* AND THE SNAPSHOT KEYED BY THE SAME HASH. The tiers moved the two halves together, so they - * lose them together; leaving the index entry behind would leave a snapshot marked off-device - * whose bytes nobody holds, waiting to be promoted by something that no longer exists. */ - drop_snapshot(key); + /* AND THE SNAPSHOT KEYED BY THE SAME HASH, when the disk was all it had: its record is gone, + * and an index entry left behind would be a detached snapshot nobody can read back. One still + * in its store slot stays -- no lookup reaches it past the missing block, the slot may be + * under a disk write this sink cannot ask about, and the retention policy retires it through + * the path that does ask (retire_ckpt). */ + auto ck = ck_by_prefix_.find(key); + if (ck != ck_by_prefix_.end() && ck->second.detached) drop_snapshot(key); } int PrefixCache::rebind(const BlockHash& key, const std::vector& blocks) { @@ -474,18 +513,30 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector& blocks return RAD_OK; } +bool PrefixCache::shared_with_live(const Entry& e) const { + for (size_t g = 0; g < groups_.size(); ++g) + if (kv_->block_refcount(groups_[g], e.blocks[g]) > 1) return true; + return false; +} + int64_t PrefixCache::evict_lru(int64_t n) { int64_t done = 0; - while (done < n && !lru_.empty()) { + /* ONE PASS OVER WHAT WAS ON THE LIST WHEN THE CALL BEGAN. An entry a live sequence also holds + * goes to the back rather than being evicted: releasing the cache's reference on it frees no + * block, and an entry that had no host copy would be erased for nothing. It is in use, which is + * what the back of the list means, and moving it is what keeps a caller that asks again from + * walking the same shared run every time. */ + for (int64_t seen = (int64_t)lru_.size(); done < n && seen > 0 && !lru_.empty(); --seen) { const BlockHash h = lru_.front(); - lru_.pop_front(); auto it = map_.find(h); - if (it == map_.end()) continue; + if (it == map_.end()) { lru_.pop_front(); continue; } Entry& e = it->second; + if (shared_with_live(e)) { + lru_.splice(lru_.end(), lru_, lru_.begin()); + continue; + } + lru_.pop_front(); e.in_lru = false; - /* Every entry on the list holds its blocks, whatever the tiers are doing with it: one on - * its way to a host copy still holds the cache's references until the copy reports, and - * the report finds it forgotten and keeps nothing. */ for (size_t g = 0; g < groups_.size(); ++g) kv_->release_block(groups_[g], e.blocks[g]); if (tiers_) { @@ -505,13 +556,51 @@ int64_t PrefixCache::evict_lru(int64_t n) { return done; } +int64_t PrefixCache::trim(int64_t n_blocks) { + /* TIERS ATTACHED AND OFF are no tiers: nothing becomes droppable, and waiting for a copy that + * nobody will make would leave the reserve unkept for good. */ + const bool keep = tiers_ && tiers_->any_on(); + int64_t done = 0; + auto it = lru_.begin(); + for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_blocks && seen > 0; + --seen) { + const BlockHash h = *it; + auto m = map_.find(h); + if (m == map_.end()) { it = lru_.erase(it); continue; } + Entry& e = m->second; + if (shared_with_live(e)) { + /* In use: to the back, as evict_lru does, and the walk carries on from the next. */ + auto next = std::next(it); + lru_.splice(lru_.end(), lru_, it); + it = next; + continue; + } + if (keep && !tiers_->droppable(h)) { ++it; continue; } + it = lru_.erase(it); + e.in_lru = false; + for (size_t g = 0; g < groups_.size(); ++g) + kv_->release_block(groups_[g], e.blocks[g]); + if (keep) { + tiers_->drop_commit(h); + ++stats_.drops; + } else { + if (tiers_) tiers_->forget(h); + map_.erase(m); + ++stats_.evictions; + } + ++done; + } + return done; +} + int64_t PrefixCache::drop_clean() { if (!tiers_ || !kv_) return 0; drop_scratch_.clear(); tiers_->take_clean(&drop_scratch_); const uint64_t frees = kv_->seq_frees(); - if (frees != frees_seen_) { + if (frees != frees_seen_ || released_) { frees_seen_ = frees; + released_ = false; drop_scratch_.insert(drop_scratch_.end(), drop_wait_.begin(), drop_wait_.end()); drop_wait_.clear(); } @@ -525,7 +614,7 @@ int64_t PrefixCache::drop_clean() { /* A BLOCK A RUNNING SEQUENCE ALSO HOLDS WOULD FREE NOTHING, and its entry would then be * off-device in the index while its bytes sat in VRAM under somebody else's table -- the * next lookup would restore a second copy beside them. */ - bool shared = false; + bool shared = held_.count(h) > 0; for (size_t g = 0; g < groups_.size() && !shared; ++g) shared = kv_->block_refcount(groups_[g], e.blocks[g]) > 1; if (shared) { @@ -601,11 +690,11 @@ int64_t PrefixCache::retain(uint64_t session) { auto it = ck_by_session_.find(session); if (it == ck_by_session_.end()) return 0; - /* DEVICE-RESIDENT SNAPSHOTS ONLY. This policy exists to spend a fixed number of --checkpoint- - * slots well, and it runs when that pool is exhausted. A snapshot the idle tiers hold occupies - * none of it, so retiring one would free nothing here and would cost a session the state it - * was moved off the device precisely in order to keep. Tiered bytes are bounded by the tiers' - * own caps, oldest first, which is the right policy for the resource they actually spend. + /* SNAPSHOTS IN THE STORE ONLY. This policy exists to spend a fixed number of --checkpoint- + * slots well, and it runs when the store is exhausted. A detached snapshot occupies none of + * it, so retiring one would free nothing here and would cost a session the state it was + * written to disk precisely in order to keep. The disk store bounds its own, oldest first, + * which is the right policy for the resource it actually spends. * * It stays in `kept` rather than being skipped, or the session index would forget it. */ std::vector> all; @@ -613,7 +702,7 @@ int64_t PrefixCache::retain(uint64_t session) { for (const BlockHash& h : it->second) { auto e = ck_by_prefix_.find(h); if (e == ck_by_prefix_.end()) continue; - if (e->second.off_device) { kept.push_back(h); continue; } + if (e->second.detached) { kept.push_back(h); continue; } all.push_back({e->second.pos, h}); } std::sort(all.begin(), all.end(), @@ -628,11 +717,19 @@ int64_t PrefixCache::retain(uint64_t session) { for (const auto& a : all) { if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; } auto e = ck_by_prefix_.find(a.second); - if (e != ck_by_prefix_.end()) { - retire_ckpt(e); + if (e == ck_by_prefix_.end()) continue; + /* A SNAPSHOT THE DISK HOLDS LEAVES THE SLOT AND STAYS IN THE INDEX: the policy is about + * the slots, and that copy costs none of them. */ + if (tiers_ && tiers_->snapshot_backed(a.second)) { + (void)detach_snapshot(a.second); + tiers_->snapshot_detached(a.second); + kept.push_back(a.second); ++freed; - ++stats_.ckpt_evictions; + continue; } + retire_ckpt(e); + ++freed; + ++stats_.ckpt_evictions; } /* ERASE THE SESSION WHEN NOTHING IS LEFT OF IT, and that is not tidiness. `session` is a * REQUEST id, so without an eraser this map gains an entry for every request that ever writes @@ -648,24 +745,27 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa int32_t* slot_out) { if (!enabled_ || !has_linear_) return RAD_E_UNSUPPORTED; if (!slot_out) return RAD_E_INVAL; - if (interval_ <= 0 || pos <= 0 || pos % interval_ != 0) { - RAD_ERR("checkpoint at %lld is not on a %lld-token boundary; the scheduler splits chunks " - "at the interval precisely so this cannot happen (spec §7.3)", - (long long)pos, (long long)interval_); + /* ON A BLOCK BOUNDARY, because the key is the chained hash of whole blocks. The scheduler + * places checkpoints on the interval and at the tail of a prompt, both on its chunk quantum, + * which is a multiple of the block. */ + if (interval_ <= 0 || pos <= 0 || pos % block_size_ != 0) { + RAD_ERR("checkpoint at %lld is not on a %lld-token block boundary; the scheduler splits " + "chunks on its quantum precisely so this cannot happen (spec §7.3)", + (long long)pos, (long long)block_size_); return RAD_E_INVAL; } auto existing = ck_by_prefix_.find(prefix); if (existing != ck_by_prefix_.end()) { - /* A SNAPSHOT THE TIERS HOLD IS NOT ONE THIS CALL CAN HAND BACK. Returning its -1 slot - * would look to the scheduler exactly like a refusal (it tests `cs >= 0`) and the chunk - * would silently stop checkpointing; handing back a slot that is not in the pool would be + /* A DETACHED SNAPSHOT IS NOT ONE THIS CALL CAN HAND BACK. Returning its -1 slot would + * look to the scheduler exactly like a refusal (it tests `cs >= 0`) and the chunk would + * silently stop checkpointing; handing back a slot that is not in the store would be * worse. The state is about to be recomputed anyway -- that is what a reservation at this - * prefix means -- so the tiered copy is retired and a fresh slot allocated below. */ - /* NOR ONE A COPY IS READING. The save that follows this reservation writes the slot on - * the compute stream while the copy reads it on the transfer stream, and the host would - * keep a snapshot that is half of each. A fresh slot costs one allocation. */ - if (!existing->second.off_device && - !(tiers_ && tiers_->snapshot_reading(prefix))) { + * prefix means -- so the disk copy is retired and a fresh slot allocated below. */ + /* NOR ONE A DISK WRITE IS READING. The save that follows this reservation writes the slot + * while the write reads it, and the disk would keep a snapshot that is half of each. A + * fresh slot costs one allocation. */ + if (!existing->second.detached && + !(tiers_ && tiers_->slot_reading(existing->second.slot))) { *slot_out = existing->second.slot; return RAD_OK; } @@ -710,10 +810,13 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa const Ckpt* victim = nullptr; const Ckpt* tip_victim = nullptr; for (const auto& kvp : ck_by_prefix_) { - /* A TIERED SNAPSHOT IS NOT A CANDIDATE, because evicting it frees nothing HERE. - * Its device slot went back to the pool when the tiers took the bytes, so picking - * it as the victim would retire a usable snapshot and then fail the retry anyway. */ - if (kvp.second.off_device) continue; + /* A DETACHED SNAPSHOT IS NOT A CANDIDATE, because evicting it frees nothing HERE. + * Its slot went back to the store when it was detached, so picking it as the + * victim would retire a usable snapshot and then fail the retry anyway. */ + if (kvp.second.detached) continue; + /* NOR ONE A DISK WRITE IS READING: its slot comes back only when the write + * reports, so retiring it now loses the snapshot and frees nothing yet. */ + if (tiers_ && tiers_->slot_reading(kvp.second.slot)) continue; auto sit = ck_by_session_.find(kvp.second.session); bool is_tip = false; if (sit != ck_by_session_.end()) { @@ -731,9 +834,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa if (!victim) return RAD_E_FULL; BlockHash vh = victim->prefix; uint64_t vs = victim->session; - /* A VICTIM THE TIERS HOLD A COPY OF IS DETACHED, NOT LOST. The slot goes back all the - * same; the index entry stays, and the session's next restore brings the state back - * with its blocks instead of replaying every recurrent layer from an older point. */ + /* A VICTIM THE DISK HOLDS IS DETACHED, NOT LOST. The slot goes back all the same; the + * index entry stays, and the session's next restore reads the state back instead of + * replaying every recurrent layer from an older point. */ if (tiers_ && tiers_->snapshot_backed(vh)) { (void)detach_snapshot(vh); tiers_->snapshot_detached(vh); @@ -766,15 +869,17 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa return RAD_OK; } -void PrefixCache::commit_checkpoint(const BlockHash& prefix) { +void PrefixCache::commit_checkpoint(const BlockHash& prefix, bool resume) { auto it = ck_by_prefix_.find(prefix); if (it == ck_by_prefix_.end()) return; + /* One that lost its slot between the reservation and now holds nothing to serve. */ + if (it->second.detached || it->second.slot < 0) return; it->second.valid = true; /* THE TIERS LEARN THE SNAPSHOT HERE, for the same reason note_used tells them the block ids: * a demotion has to know what to move and this index is the only place it is written down. * Before the commit there is nothing to move -- the slot still holds the previous tenant's * state -- so this is also the earliest moment at which telling them would be true. */ - if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos); + if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos, resume); } @@ -782,16 +887,16 @@ void PrefixCache::commit_checkpoint(const BlockHash& prefix) { void PrefixCache::retire_ckpt(std::unordered_map::iterator it) { if (it == ck_by_prefix_.end()) return; - /* THE TIERS ARE ASKED FIRST, because they may be reading the slot: a copy to host memory in - * flight out of a slot the pool then decommits reads a page that is no longer mapped. When - * one is, the tiers keep the slot and hand it back once the copy has reported. */ - const bool held = tiers_ && tiers_->release_snapshot(it->first); + /* THE TIERS ARE ASKED FIRST, because a disk write may be reading the slot: a save into it + * before the write is done would put half of another snapshot on disk under this key. When + * one is, the tiers keep the slot and hand it back once the write has reported. */ + const bool held = tiers_ && tiers_->release_snapshot(it->first, it->second.slot); if (it->second.slot >= 0 && !held) kv_->free_checkpoint(it->second.slot); - /* TOLD EITHER WAY, AND NOT ONLY WHEN THE TIERS HOLD THE BYTES. They also remember a snapshot's - * DEVICE slot -- note_snapshot records it at commit, because a demotion has to know what to - * copy and this index is the only place it is written down. Freeing that slot here without - * saying so leaves the tiers naming a slot the pool has since given to another session, and - * the next demotion copies THAT session's recurrent state and restores it as this one's. The + /* TOLD EITHER WAY, AND NOT ONLY WHEN THE DISK HOLDS THE BYTES. The tiers also remember a + * snapshot's slot -- note_snapshot records it at commit, because a disk write has to know + * what to read and this index is the only place it is written down. Freeing that slot here + * without saying so leaves the tiers naming a slot the store has since given to another + * session, and the next write puts THAT session's recurrent state on disk as this one's. The * text that comes back is fluent, deterministic and about the wrong conversation, which is * the exact failure the whole tier design is arranged to make impossible. * @@ -803,10 +908,11 @@ void PrefixCache::retire_ckpt(std::unordered_map int PrefixCache::detach_snapshot(const BlockHash& key) { auto it = ck_by_prefix_.find(key); if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND; - if (it->second.off_device) return RAD_OK; /* already theirs */ + if (it->second.detached) return RAD_OK; /* already only on disk */ + /* Only ever asked of a snapshot the tiers call backed, which no write is reading. */ if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot); it->second.slot = -1; - it->second.off_device = true; + it->second.detached = true; /* NOT SERVABLE FROM HERE ON, which is the same state a reserved-but-unwritten snapshot is in * and is handled by the same branch in lookup(). A hit that reaches this position simply walks * back to an older checkpoint, or to none -- shorter, never wrong. */ @@ -818,11 +924,15 @@ int PrefixCache::reattach_snapshot(const BlockHash& key, int32_t slot) { auto it = ck_by_prefix_.find(key); if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND; if (slot < 0) return RAD_E_INVAL; - /* A SLOT THIS ENTRY DID NOT ASK FOR IS STILL ITS OWN. The promotion allocated it and filled it - * from the tier copy of THIS key's state, so the identity that matters -- which prefix the + /* AN ENTRY ALREADY IN A SLOT keeps it: taking the new one would leak the old. The caller gives + * the new slot back. */ + if (!it->second.detached && it->second.slot >= 0) return it->second.slot == slot ? RAD_OK + : RAD_E_STATE; + /* A SLOT THIS ENTRY DID NOT ASK FOR IS STILL ITS OWN. The read allocated it and filled it + * from the disk copy of THIS key's state, so the identity that matters -- which prefix the * bytes describe -- is carried by the key and not by the slot number it happened to get. */ it->second.slot = slot; - it->second.off_device = false; + it->second.detached = false; it->second.valid = true; it->second.used = ++clock_; return RAD_OK; @@ -833,7 +943,7 @@ bool PrefixCache::free_checkpoint_for_restore() { const Ckpt* victim = nullptr; for (const auto& kvp : ck_by_prefix_) { const Ckpt& c = kvp.second; - if (c.off_device || c.slot < 0 || !c.valid) continue; + if (c.detached || c.slot < 0 || !c.valid) continue; if (victim && c.used >= victim->used) continue; if (std::find(handed_.begin(), handed_.end(), kvp.first) != handed_.end()) continue; if (!tiers_->snapshot_backed(kvp.first)) continue; @@ -846,12 +956,51 @@ bool PrefixCache::free_checkpoint_for_restore() { return true; } +void PrefixCache::hold(uint64_t req, const std::vector& tokens, + const std::vector& mm) { + if (!enabled_ || !tiers_ || tokens.empty() || holds_.count(req)) return; + const int64_t n_full = ((int64_t)tokens.size() - 1) / block_size_; + const std::vector hs = chain_all(tokens, mm, n_full); + std::vector& mine = holds_[req]; + for (int64_t b = 0; b < n_full; ++b) { + auto it = map_.find(hs[(size_t)b]); + if (it == map_.end()) break; + const int32_t* src = tokens.data() + b * block_size_; + if ((int64_t)it->second.tokens.size() != block_size_ || + std::memcmp(it->second.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) != 0) + break; + mine.push_back(hs[(size_t)b]); + ++held_[hs[(size_t)b]]; + } +} + +size_t PrefixCache::resident_prefix(const std::vector& chain) const { + size_t n = 0; + for (; n < chain.size(); ++n) { + auto it = map_.find(chain[n]); + if (it == map_.end() || !it->second.in_lru) break; + } + return n; +} + +void PrefixCache::release(uint64_t req) { + auto it = holds_.find(req); + if (it == holds_.end()) return; + for (const BlockHash& h : it->second) { + auto k = held_.find(h); + if (k != held_.end() && --k->second <= 0) held_.erase(k); + } + holds_.erase(it); + released_ = true; +} + void PrefixCache::drop_snapshot(const BlockHash& key) { auto it = ck_by_prefix_.find(key); if (it == ck_by_prefix_.end()) return; const uint64_t session = it->second.session; - /* No release_snapshot on this path: the tiers are the caller and the bytes are already gone. - * Telling them to free what they just lost would double-free the arena slot. */ + /* No release_snapshot on this path: the tiers are the caller, holding their lock, and the + * bytes are already gone. They say this only of a detached snapshot, so there is normally no + * slot to give back. */ if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot); ck_by_prefix_.erase(it); ++stats_.ckpt_evictions; @@ -861,9 +1010,9 @@ void PrefixCache::drop_snapshot(const BlockHash& key) { if (sit->second.empty()) ck_by_session_.erase(sit); } -int64_t PrefixCache::snapshots_off_device() const { +int64_t PrefixCache::snapshots_detached() const { int64_t n = 0; - for (const auto& kvp : ck_by_prefix_) if (kvp.second.off_device) ++n; + for (const auto& kvp : ck_by_prefix_) if (kvp.second.detached) ++n; return n; } } /* namespace rad */ diff --git a/core/mem/prefix.h b/core/mem/prefix.h index e3e51d43..0afc0e7d 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -43,8 +43,8 @@ * is unaffected either way; the only difference is whether the prefixes still exist when the next * turn asks for them, and that difference is one to two orders of magnitude of time to first * token. Size the cache so live sessions fit with room to spare -- a context of T tokens occupies - * roughly 1.8 x T pool-tokens across the paged groups -- and keep --expert-vs-cache-ratio on the - * safe side of that. + * roughly 1.8 x T pool-tokens across the paged groups. The budget gives the cache everything the + * experts can do without (core/mem/vram_budget.h); --host-pool-mib is what moves that. * * WHAT TO WATCH: `kv_util` (/stats, or vllm:kv_cache_usage_perc) is the predictor, and * `radiance:prefix_cache_evictions_total` is the event -- the hit rate is neither, because it only @@ -203,6 +203,20 @@ public: * instead of forgetting it: the next turn restores it rather than re-prefilling it. Only an * entry with no host copy yet is lost. Either way the blocks go back to the pool. */ int64_t evict_lru(int64_t n_entries); + /* FREE UP TO `n_blocks` BLOCKS OF THE POOL for the reserve the scheduler keeps, losing nothing + * a later turn could have reused. One walk of the LRU list, oldest first, that takes only what + * gives the pool a block back without costing a conversation: + * + * - an entry a live sequence also holds is passed over. Releasing the cache's reference on + * it frees nothing, and without a host copy it erases the entry -- which, right after a + * publish, is the conversation that request just finished; + * - with the idle tiers on, an entry whose host copy has not landed is passed over too. It + * is the next turn's context with nowhere else to come from, and in a moment it is clean + * and can leave VRAM for nothing. + * + * Pressure that cannot wait -- an admission or a step that needs the blocks now -- is + * evict_lru's. Returns how many blocks went back. */ + int64_t trim(int64_t n_blocks); /* GIVE UP EVERY VRAM COPY THAT CAN GO FOR NOTHING: the entries whose host copy has landed and * that no running sequence is still reading. Called when the memory has a better use -- the * expert slab's loan -- and returns how many entries left VRAM. An entry a sequence still @@ -258,50 +272,53 @@ public: /* ---------------- the linear half of an idle session ---------------- * * ON A HYBRID MODEL THE BLOCKS ARE ONLY HALF OF WHAT A SESSION NEEDS BACK. The other half is - * the recurrent state, and it lives in a CHECKPOINT SLOT: a device-resident object of - * KVManager::checkpoint_bytes(), of which there are --checkpoint-slots IN TOTAL for the whole - * server. Eight by default, against the six or seven a single 200K session retains under - * geometric backoff -- so a second session evicts the first's snapshots, tip included. - * - * Tiering the blocks and leaving the snapshot behind therefore gets the trade backwards: it - * frees the plentiful resource and holds on to the scarce one. And what the session loses is - * not part of its hit, it is ALL of it -- the scheduler clamps reuse to the last checkpoint a - * hit can reach, because RadBatch carries one query length for every KV group and the linear + * the recurrent state, and it lives in a CHECKPOINT SLOT: a slot of the engine's snapshot + * store in pinned host memory, KVManager::checkpoint_bytes() a rank, of which there are + * --checkpoint-slots IN TOTAL for the whole server. What the session loses without it is not + * part of its hit, it is ALL of it -- the scheduler clamps reuse to the last checkpoint a hit + * can reach, because RadBatch carries one query length for every KV group and the linear * layers cannot be replayed over a longer range than the attention ones (core/sched/ * scheduler.cpp, admit_one). A restored session with no reachable snapshot reuses zero tokens - * and re-prefills its whole transcript. The blocks without the state are not a partial win; - * they are unusable. + * and re-prefills its whole transcript. * - * So a snapshot moves with the blocks whose hash it is keyed by, and these calls are the - * cache's whole part in that. The bytes are the engine's to move. */ + * A snapshot never needs to follow its blocks: it is restored straight out of its slot into + * the new sequence's state, wherever the blocks are. The only tier below the store is disk, + * and a snapshot the disk holds can give its slot up and stay in the index (DETACHED) until a + * read brings it back. */ - /* Its bytes are on another tier now: give the device slot back and stop offering it. The index - * entry STAYS, because that is what a promotion puts the snapshot back into, and an entry - * whose state is not in the pool is exactly the `valid` flag's existing meaning -- lookup - * already walks past one and falls back to an older position. */ + /* Its bytes are only on disk now: give the slot back and stop offering it. The index entry + * STAYS, because that is what a read off disk puts the snapshot back into, and an entry whose + * state is not in the store is exactly the `valid` flag's existing meaning -- lookup already + * walks past one and falls back to an older position. */ int detach_snapshot(const BlockHash& key); /* And back again, into a slot the caller has already filled. */ int reattach_snapshot(const BlockHash& key, int32_t slot); - /* A DEVICE CHECKPOINT SLOT FOR A RESTORE. The pool is --checkpoint-slots deep for the whole - * server, and it is full whenever as many sessions have run since; a session restored then - * would get its blocks back and replay every recurrent layer from an older point, because its - * state has nowhere to land. One slot is freed by detaching the least recently used snapshot - * the tiers hold a copy of -- which the next restore of THAT session brings back -- and never - * one whose only copy is the slot, and never one a lookup has handed out since the step began: - * that request reads the slot in this step's forward, and a restore writes it before the - * forward runs. True when a slot was freed. */ + /* A STORE SLOT FOR A READ OFF DISK. The store is --checkpoint-slots deep for the whole server, + * and it is full whenever as many sessions have run since; a session whose snapshot is only on + * disk would then replay every recurrent layer from an older point, because its state has + * nowhere to land. One slot is freed by detaching the least recently used snapshot the disk + * also holds -- which the next restore of THAT session reads back -- and never one whose only + * copy is the slot, and never one a lookup has handed out since the step began: that request's + * restore reads the slot ahead of its step. True when a slot was freed. */ bool free_checkpoint_for_restore(); + /* KEEP A WAITING REQUEST'S CHAIN ON THE CARD. An admission that restored a chain and was then + * refused -- no free sequence, no room in the pool -- gives its hit back, and its entries are + * clean: drop_clean would let them go at the next pass and the next attempt would restore the + * same chain again, every step for as long as the request waits. A held entry is passed over + * by drop_clean until release(); trim and evict_lru still take it under pressure, which costs + * a restore and loses nothing. Idempotent per request. */ + void hold(uint64_t req, const std::vector& tokens, const std::vector& mm); + /* How many of `chain`'s leading entries are in VRAM: as far as a lookup's hit can reach. */ + size_t resident_prefix(const std::vector& chain) const; + void release(uint64_t req); /* A step's admissions begin. The snapshots the last step's lookups handed out have been read * by its forward, which committed before this step was planned. */ void begin_step() { handed_.clear(); } - /* The tiers lost it -- a capacity drop, a failed promotion, or an entry they were told to - * forget. Erase the index entry; there is no device slot to give back. */ + /* The tiers lost it -- the disk store let it go, a failed read, or an entry they were told to + * forget. Erase the index entry and give back the slot, if it still has one. */ void drop_snapshot(const BlockHash& key); - /* How many snapshots the index holds whose bytes the tiers have. Reported rather than derived - * because it is the number that says whether hybrid tiering is doing anything at all: a - * session can move its whole chain off the device and still be re-prefilling its linear - * layers from zero on every hit, and nothing else distinguishes the two. */ - int64_t snapshots_off_device() const; + /* How many snapshots the index holds whose bytes are only on disk. */ + int64_t snapshots_detached() const; /* ---------------- linear checkpoints ---------------- */ /* The next position strictly after `pos` at which the scheduler must split a chunk so that a * checkpoint lands on a boundary (spec §7.1, §7.3). */ @@ -313,8 +330,9 @@ public: int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix, int32_t* slot_out); /* The state named by `prefix` is now IN its slot. Until this is called the reservation is only - * a promise and lookup() will not offer it -- see Ckpt::valid. */ - void commit_checkpoint(const BlockHash& prefix); + * a promise and lookup() will not offer it -- see Ckpt::valid. A `resume` point is copied off + * the card at once (IdleTiers::note_snapshot). */ + void commit_checkpoint(const BlockHash& prefix, bool resume = false); /* Every checkpoint of a session, ascending. */ std::vector checkpoints(uint64_t session) const; /* Apply the retention policy to one session now. Returns how many snapshots were released. @@ -361,21 +379,24 @@ private: * lookup between those two points would hand out a slot holding the previous tenant's * history, which is the exact failure this whole mechanism exists to prevent. */ bool valid = false; - /* ARE THE BYTES STILL IN THE POOL. The idle tiers move a snapshot along with the blocks - * it is keyed by, and `slot` is -1 for the whole time they hold it. Kept as its own flag - * rather than inferred from the slot so that the two reasons a snapshot cannot be served - * -- not written yet, and not here -- stay distinguishable in a debugger and in a report. */ - bool off_device = false; + /* ARE THE BYTES ONLY ON DISK. A detached snapshot gave its store slot up because the disk + * holds it, and `slot` is -1 until a read brings it back. Kept as its own flag rather than + * inferred from the slot so that the two reasons a snapshot cannot be served -- not written + * yet, and not here -- stay distinguishable in a debugger and in a report. */ + bool detached = false; }; std::vector chain_all(const std::vector& tokens, const std::vector& mm, int64_t n_blocks) const; void touch(const BlockHash& h) const; - /* Retire one snapshot whatever tier holds its bytes: a device slot goes back to the pool, and - * tiered bytes go back to the tiers. One place, because three call sites that each remembered - * to check `off_device` would be three places to forget. The session index is the caller's, - * since every caller is already rebuilding or erasing it. */ + /* Does a live sequence hold any of this entry's blocks as well? Then releasing the cache's + * reference frees nothing. */ + bool shared_with_live(const Entry& e) const; + /* Retire one snapshot whatever tier holds its bytes: a slot goes back to the store, and a disk + * copy goes back to the tiers. One place, because three call sites that each remembered to + * check `detached` would be three places to forget. The session index is the caller's, since + * every caller is already rebuilding or erasing it. */ void retire_ckpt(std::unordered_map::iterator it); KVManager* kv_ = nullptr; @@ -394,6 +415,11 @@ private: std::vector drop_wait_; std::vector drop_scratch_; uint64_t frees_seen_ = 0; + /* hold(): the keys each waiting request holds, and how many requests hold each key. A release + * makes drop_wait_ worth looking at again, as a freed sequence does. */ + std::unordered_map> holds_; + std::unordered_map held_; + bool released_ = false; mutable std::unordered_map ck_by_prefix_; std::unordered_map> ck_by_session_; /* Snapshots lookup handed out since begin_step: not a restore's to take (free_checkpoint_for_restore). */ diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp index 614890ec..4d0c26c5 100644 --- a/core/mem/vram_budget.cpp +++ b/core/mem/vram_budget.cpp @@ -22,6 +22,13 @@ int64_t to_mib(int64_t bytes) { return bytes > 0 ? bytes / kMiB : 0; } * footprint to the byte, and there the rounding direction decides whether it loads. The MiB this * claims comes out of the headroom, which is what the headroom is for. */ int64_t to_mib_up(int64_t bytes) { return bytes > 0 ? (bytes + kMiB - 1) / kMiB : 0; } + +/* WHAT THE DRIVER'S OWN HOLDING MOVES BY AFTER IT IS READ. `already_held` is one reading, and on + * ROCm 7.2 the same server started twice has read 4 MiB less than it later held (and once 30 MiB + * more): a budget that split the difference away came up a few MiB short of the headroom the + * first launches of kernels allocate from. Four times the drift seen, and charged before anything + * is split. */ +constexpr int64_t kDriverDrift = 16 * kMiB; } /* namespace */ /* WHAT THE CACHE BACKS, counted on its PAGED part. The ceiling is the recurrent and conv state of @@ -33,7 +40,7 @@ static double paged_share(const VramBudget& b) { return ctx > 0 ? std::max(0.0, (double)(b.kv - b.kv_fixed)) / ctx : 0.0; } -/* The resolver, with its three log lines behind `log`: vram_budget_trial asks the same question +/* The resolver, with its log lines behind `log`: vram_budget_trial asks the same question * of a configuration it may not use, and a refusal printed for a split nobody takes reads as the * startup failing. */ static int resolve(Config& cfg, const std::vector& per_rank, VramBudget* out, bool log) { @@ -46,7 +53,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg * overcommitting the smaller one on the first allocation. */ b.capacity = per_rank[0].capacity; int64_t freeb = per_rank[0].free; - int64_t layer_max = 0; + int64_t layer_max = 0, kv_one = 0; for (const VramFacts& f : per_rank) { b.capacity = std::min(b.capacity, f.capacity); freeb = std::min(freeb, f.free); @@ -62,7 +69,12 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg b.statics = std::max(b.statics, f.statics); b.expert_ceiling = std::max(b.expert_ceiling, f.experts); layer_max = std::max(layer_max, f.expert_layer_max); + /* THE RANK THAT NEEDS MOST ON THE CARD SETS THE FLOOR. */ + b.expert_floor = std::max(b.expert_floor, f.expert_floor); + kv_one = std::max(kv_one, f.kv_one); } + b.lends = true; + for (const VramFacts& f : per_rank) b.lends = b.lends && f.lends; b.headroom = std::max(cfg.gpu_headroom_mib, 0) * kMiB; int64_t host_reserve = 0; for (const VramFacts& f : per_rank) host_reserve = std::max(host_reserve, f.host_reserve); @@ -91,7 +103,8 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg b.derived_kv = want_kv; /* What is left after the terms nobody gets to spend. */ - int64_t fixed = b.already_held + b.headroom + b.arena + b.staging + b.queues; + b.drift = (want_w || want_kv) ? kDriverDrift : 0; + int64_t fixed = b.already_held + b.drift + b.headroom + b.arena + b.staging + b.queues; if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */ if (!want_kv) fixed += cfg.vram_kv_mib * kMiB; b.claimable = b.capacity - fixed; @@ -101,6 +114,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg "VRAM does not cover the fixed costs before a single pool is sized:\n" " card total %10s\n" " already held %10s (driver context, code objects, anything else on the card)\n" + " driver drift %10s (what that moves by after it is read)\n" " --gpu-headroom-mib %10s\n" " activation arena %10s (buffer plan + kernel scratch)\n" " step staging %10s (block tables, media and KV tier staging)\n" @@ -110,7 +124,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg " SHORT BY %10s\n" "Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), " "or free the card.\n", - humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), + humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(), humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(), humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n", @@ -147,39 +161,42 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg b.elastic = want_w ? b.claimable - b.statics : b.claimable; if (b.elastic < 0) b.elastic = 0; - /* ---- and only what is left is what the ratio divides ------------------------------------- */ + /* ---- and only what is left is divided --------------------------------------------------- */ if (want_w && want_kv) { - const double r = (cfg.expert_cache_ratio > 0.0 && cfg.expert_cache_ratio < 1.0) - ? cfg.expert_cache_ratio : 0.75; - int64_t kv = (int64_t)((double)b.elastic * (1.0 - r)); - int64_t exp = b.elastic - kv; - - /* BOTH SIDES ARE CAPPED AT WHAT THEY COULD USE, AND THE SLACK CROSSES OVER. A paged cache - * cannot address past max_seqs x max_ctx tokens and an expert plane that is entirely - * resident has no use for another byte -- so a share above either ceiling is memory - * nothing will ever touch. Cap, then hand the remainder to whichever side is still short, - * then stop: what neither can take is genuinely unusable and is reported as such rather - * than allocated into a pool that reports itself three quarters empty. */ - if (b.kv_ceiling > 0 && kv > b.kv_ceiling) kv = b.kv_ceiling; - /* ZERO EXPERTS IS A CEILING OF ZERO, NOT AN UNMEASURED ONE. weight_footprint() runs on - * every rank before this call, so expert_ceiling is always known -- and guarding this cap - * with `> 0` would read "dense" as "unlimited", handing a model with no experts at all a - * large expert budget against nothing to put in it while its cache goes short. - * kv_ceiling keeps its guard: that one IS genuinely unset when plan_groups fails. */ - if (exp > b.expert_ceiling) exp = b.expert_ceiling; - int64_t spare = b.elastic - kv - exp; - if (spare > 0 && b.expert_ceiling > exp) { - const int64_t take = std::min(spare, b.expert_ceiling - exp); - exp += take; spare -= take; - } - if (spare > 0 && b.kv_ceiling > kv) { - const int64_t take = std::min(spare, b.kv_ceiling - kv); - kv += take; spare -= take; + /* An unset cache ceiling (plan_groups failed) bounds nothing; zero experts is a ceiling of + * zero, which weight_footprint always measures. */ + const int64_t kv_cap = b.kv_ceiling > 0 ? b.kv_ceiling : b.elastic; + int64_t kv = 0, exp = 0; + if (kv_cap + b.expert_ceiling <= b.elastic) { + /* BOTH FIT: nothing trades. */ + kv = kv_cap; + exp = b.expert_ceiling; + } else if (b.lends) { + /* THE CACHE LENDS, so it is sized for what live requests could need and gives back + * whatever they do not. The experts keep what the host pool cannot hold. */ + exp = std::min(b.expert_floor, b.elastic); + kv = std::min(kv_cap, std::max(b.elastic - exp, kv_one)); + exp = std::min(std::max(b.expert_ceiling, b.expert_floor), b.elastic - kv); + /* THE ONE SEQUENCE WINS, and the experts it pushes off the card have no tier: the + * planner refuses them by name. Said here too, with what moves it. */ + if (log && exp < b.expert_floor) + RAD_WARN("one --max-model-len sequence's cache (%s) leaves the experts %s, short of " + "the %s the pinned host pool cannot hold: raise --host-pool-mib or lower " + "--max-model-len", + humanb(kv_one).c_str(), humanb(exp).c_str(), + humanb(b.expert_floor).c_str()); + } else { + /* NO LENDER: a block the cache does not use would sit empty, so the experts come + * first and the cache keeps one --max-model-len sequence. */ + kv = std::min(kv_cap, std::max(b.elastic - b.expert_ceiling, kv_one)); + exp = std::min(b.expert_ceiling, b.elastic - kv); } + if (kv > b.elastic) kv = b.elastic; + if (exp < 0) exp = 0; b.experts = exp; b.kv = kv; b.weights = b.statics + exp; - b.unusable = spare > 0 ? spare : 0; + b.unusable = std::max(b.elastic - kv - exp, 0); } else if (want_kv) { b.kv = b.kv_ceiling > 0 ? std::min(b.claimable, b.kv_ceiling) : b.claimable; b.unusable = b.claimable - b.kv; @@ -214,7 +231,15 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling; const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT; - if (2 * one < b.experts) { + if (b.lends && want_kv) { + /* A LENDING CACHE PAYS FOR IT: the experts are at their floor and a byte less would + * leave one with no tier, while the region is lent to the slab whenever the steps are + * small -- the same memory the cache would have lent. */ + if (b.kv - 2 * one >= kv_one) { + b.stage = 2 * one; + b.kv -= b.stage; + } + } else if (2 * one < b.experts) { b.stage = 2 * one; b.experts -= b.stage; b.weights = b.statics + b.experts; @@ -244,7 +269,8 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg "sequence's blocks stay held so the next turn can reuse them, so the demand is " "live SESSIONS and not running requests -- when they do not all fit, the cache " "evicts prefixes the next turn wanted and that turn re-prefills its whole " - "context. --expert-vs-cache-ratio moves it.", + "context. --host-pool-mib moves it: the experts the host pool cannot hold are the " + "part of the card the cache cannot have.", 100.0 * paged_share(b), (long long)cfg.max_seqs, (long long)cfg.max_ctx, (double)cfg.max_seqs * paged_share(b)); @@ -262,13 +288,14 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg * line is not padding: to_mib truncates, and what it drops is real VRAM that ends up beside * the headroom. */ const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB; - const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.staging - b.queues - b.stage - - granted; + const int64_t unclaimed = b.capacity - b.already_held - b.drift - b.arena - b.staging - b.queues - + b.stage - granted; const double ela = b.elastic > 0 ? (double)b.elastic : 1.0; b.report = fmt( "VRAM budget, per card:\n" " card total %10s\n" " already held %10s measured: driver context, code objects, anything else resident\n" + " driver drift %10s what that moves by after it is read: kept free\n" " activation arena %10s computed from the buffer plan\n" " step staging %10s the step batch's block tables and media staging, and the\n" " KV tiers' copy staging\n" @@ -278,7 +305,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg " claimable %10s\n" " static weights %10s %s\n" " ------------------------------\n" - " elastic %10s what --expert-vs-cache-ratio %.2f divides\n" + " elastic %10s %s\n" " experts %10s %.0f%% of it%s\n" " kv cache %10s %.0f%% of it%s\n" "%s" @@ -288,8 +315,8 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg " vram_kv %10s %s\n" " unclaimed %10s the headroom, the unusable above, and what MiB rounding\n" " could not place\n", - humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.arena).c_str(), - humanb(b.staging).c_str(), + humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(), + humanb(b.arena).c_str(), humanb(b.staging).c_str(), humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(), shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool " @@ -300,8 +327,10 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg b.derived_weights ? "off the top: every rank's own shard, and not a share of anything" : "(not charged here -- --vram-weights-mib was stated)", humanb(b.elastic).c_str(), - (cfg.expert_cache_ratio > 0.0 && cfg.expert_cache_ratio < 1.0) ? cfg.expert_cache_ratio - : 0.75, + b.lends ? "the experts keep what the host pool cannot hold; the cache takes the rest\n" + " and lends what no live request holds to the " + "expert slab" + : "no lender: the experts first, the cache at least one full-length sequence", humanb(b.experts).c_str(), 100.0 * (double)b.experts / ela, b.expert_ceiling == 0 ? " -- a dense model, so there is no expert plane for this share to fill and the\n" @@ -339,10 +368,11 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg "ceiling\n", humanb(b.unusable).c_str()).c_str() : "", b.stage > 0 - ? fmt(" prefill staging %10s out of the experts: two buffers of one layer's " + ? fmt(" prefill staging %10s out of the %s: two buffers of one layer's " "non-resident experts,\n" " at the arena's top and lent back to the " - "slab while steps are small\n", humanb(b.stage).c_str()).c_str() + "slab while steps are small\n", humanb(b.stage).c_str(), + b.lends ? "cache" : "experts").c_str() : "", humanb(cfg.vram_weights_mib * kMiB).c_str(), b.derived_weights ? "static + experts" : "stated by --vram-weights-mib", diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h index 4ec20ea7..efd43c17 100644 --- a/core/mem/vram_budget.h +++ b/core/mem/vram_budget.h @@ -28,20 +28,23 @@ * pinned host pool, which a lookup reads a few rows of in place; weight_footprint counts it out of * the statics then), and under tensor parallel each rank already holds its own even share of * them (declare runs per rank with every dimension divided, spec §9). They are a FLOOR, not a - * share of anything: applying a ratio to the weights as a whole would let --expert-vs-cache-ratio - * 0.3 demote the attention projections to host memory to make room for a cache nothing will fill. - * If they do not fit, that is a refusal with the shortfall named. + * share of anything: dividing the weights as a whole would let the cache's side demote the + * attention projections to host memory to make room for blocks nothing will fill. If they do not + * fit, that is a refusal with the shortfall named. * - * ONLY WHAT IS LEFT AFTER THAT IS DIVIDED, and that is the division the flag is named for: the - * expert plane against the KV cache, which is the one genuinely two-sided trade on this engine. A - * long-context low-concurrency server and a short-context high-concurrency one want opposite - * answers and neither is derivable. + * ONLY WHAT IS LEFT AFTER THAT IS DIVIDED: the expert plane against the KV cache. Where the cache + * lends its idle blocks to the expert slab, that division has nothing to guess. The experts keep + * on the card exactly what the pinned host pool cannot hold -- they have nowhere else to be -- and + * the cache takes the rest, up to what it could ever address; every block no live request holds + * is lent back to the experts in place. So the cache is as large as the work needs at the moment + * and the experts have everything else, for a long-context server and a high-concurrency one + * alike. Without a lender the cache would hold that memory empty, so there the experts come first + * and the cache keeps one --max-model-len sequence. The cache never gets less than that sequence. * - * BOTH SIDES ARE THEN CAPPED AT WHAT THEY COULD USE, and whatever one side cannot take goes to the + * BOTH SIDES ARE CAPPED AT WHAT THEY COULD USE, and whatever one side cannot take goes to the * other rather than nowhere. A cache cannot address past max_seqs x max_ctx tokens - * (KVManager::ceiling), so a share larger than that ceiling is VRAM the cache can never fill and - * the expert plane could have held. And an expert plane that fits entirely in VRAM has no use for - * more; on a model that fits, the ratio stops meaning anything and that is correct. + * (KVManager::ceiling), and an expert plane that fits entirely in VRAM has no use for more; when + * both fit, both are whole. * * A stated --vram-weights-mib or --vram-kv-mib still wins outright and turns the whole of this * off for that pool. The point is that the DEFAULT is a full card rather than a guess: VRAM left @@ -76,8 +79,18 @@ struct VramFacts { /* weight_footprint() for this rank, which under tensor parallel is already this card's even * share: declare runs per rank with every dimension already divided. */ int64_t statics = 0; /* non-expert weights -- the floor, not a share of anything */ - int64_t experts = 0; /* the elastic plane the ratio divides against the KV cache */ + int64_t experts = 0; /* the expert plane: what trades against the KV cache */ int64_t expert_layer_max = 0; /* the most expert bytes one routed layer holds */ + /* THE EXPERTS THE PINNED HOST POOL CANNOT HOLD on this rank, with the slab's spare slots + * beside them: they have nowhere to be but the card, so this is the floor under the expert + * slab when the cache lends (expert_vram_floor, core/place/planner.h). */ + int64_t expert_floor = 0; + int64_t kv_one = 0; /* the cache for ONE --max-model-len sequence: the least it may get */ + /* WILL THE CACHE LEND ITS IDLE BLOCKS TO THE EXPERT SLAB: a placement that moves units + * (expert_tiered, or auto), not --deterministic, on a device with virtual memory management. + * Decides the split: a cache that lends gives back what it does not use, so it can be sized + * for what live requests could need; one that does not would hold it empty. */ + bool lends = false; /* Integrated graphics: what of the host's memory the card leaves to the host. Its device * memory IS the host's, so an unclaimed MiB is the operating system's and every other * process's to run in, not slack. 0 on a discrete card. */ @@ -88,12 +101,15 @@ struct VramFacts { * operator stated the budgets -- the placement report and the pool report both want the totals. */ struct VramBudget { int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0; + int64_t drift = 0; /* kDriverDrift: what already_held moves by after it is read */ int64_t queues = 0; /* n_queues * queue_bytes, from the rank that needs most */ int n_queues = 0; int64_t queue_bytes = 0; int64_t claimable = 0; /* after the fixed terms above */ - int64_t statics = 0; /* off the top, before the ratio sees anything */ - int64_t elastic = 0; /* claimable - statics: what the ratio divides */ + int64_t statics = 0; /* off the top, before the split sees anything */ + int64_t elastic = 0; /* claimable - statics: what experts and cache share */ + int64_t expert_floor = 0; /* the experts the host pool cannot hold */ + bool lends = false; /* every rank's cache lends its idle blocks */ int64_t kv_ceiling = 0, expert_ceiling = 0; int64_t kv_fixed = 0; /* the state part of kv_ceiling, which no context uses */ int64_t experts = 0, kv = 0; /* the two shares, each capped at its ceiling */ diff --git a/core/place/planner.cpp b/core/place/planner.cpp index 18735ec3..15845239 100644 --- a/core/place/planner.cpp +++ b/core/place/planner.cpp @@ -20,6 +20,7 @@ #include #include #include +#include namespace rad { @@ -101,6 +102,17 @@ int64_t weight_bytes(const WeightInfo& w) { /* See planner.h. Planner::resolve_sites, Planner::build_units and Planner::pin_mapped, run over * the same program without allocating a Plan -- the budget resolver calls this before a Planner * exists. Kept adjacent to the three so a change to any of them has this in the same diff. */ +int64_t file_stage_reserve(int64_t widest, bool routed) { + return (int64_t)RAD_PLACE_FILE_STAGE_SLOTS * widest + + (routed ? (int64_t)RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES : 0); +} + +int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room) { + if (wf.experts <= 0) return 0; + const int64_t all = wf.experts + wf.expert_spare; + return std::min(all, std::max(all + 2 * wf.expert_unit_max - host_room, 0)); +} + void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding, TablePlacement ngram) { if (!out) return; @@ -166,6 +178,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement * align_up(static_need, RAD_ALIGN_UNIT)` before every unit it places. A budget that summed raw * bytes would be short by one alignment per unit, which on a 512-expert MoE is real. */ std::map layer_experts; + std::set expert_strides; bool ngram_host = true; for (const U& mu : units) if (mu.ngram && !mu.host) ngram_host = false; for (const U& mu : units) { @@ -178,9 +191,20 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement * placed in VRAM. */ if (mu.mapped || (mu.ngram && ngram != TablePlacement::Vram)) out->mapped += b; else if (mu.emb && embedding == TablePlacement::Ram) out->hosted += b; - else if (mu.expert >= 0) { out->experts += b; layer_experts[mu.layer] += b; } + else if (mu.expert >= 0) { + out->experts += b; + layer_experts[mu.layer] += b; + out->expert_unit_max = std::max(out->expert_unit_max, b); + expert_strides.insert(b); + } else out->statics += b; + if (mu.layer >= 0 && !mu.mapped) out->layer_unit_max = std::max(out->layer_unit_max, b); + if (mu.expert >= 0 && mu.layer >= 0) out->routed = true; } + /* build_classes: one expert slab class a stride. */ + for (int64_t s : expert_strides) + out->expert_spare += (int64_t)(RAD_PLACE_SHADOW_SLOTS + RAD_PLACE_STAGE_RING) * s + + RAD_ALIGN_UNIT; for (const auto& le : layer_experts) out->expert_layer_max = std::max(out->expert_layer_max, le.second); out->ngram_host = out->ngram > 0 && ngram_host; @@ -1157,7 +1181,7 @@ int Planner::plan(Plan* out) { } const int64_t windows = routed ? (int64_t)RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES : 0; - const int64_t need = (int64_t)RAD_PLACE_FILE_STAGE_SLOTS * widest + windows; + const int64_t need = file_stage_reserve(widest, routed); if (need > 0) { if (need >= out->host_budget) { RAD_ERR("placement: the file tier needs %s of pinned staging (%d slots of %s%s) " diff --git a/core/place/planner.h b/core/place/planner.h index 394fcc87..d7043215 100644 --- a/core/place/planner.h +++ b/core/place/planner.h @@ -361,9 +361,8 @@ int64_t weight_bytes(const WeightInfo& w); * order: how much room is there, and only then what goes in it. And the split matters more than * the total. A model's static weights -- everything that is not an expert -- have to be resident * for the model to run at a sensible speed at all, so they come off the top; the expert plane is - * the only thing that trades against the KV cache, and it is what --expert-vs-cache-ratio divides. - * Applying a ratio to the two together would let a 0.3 setting demote the attention projections to - * host memory to make room for a cache nothing will fill. + * the only thing that trades against the KV cache. Dividing the two together would let the cache's + * side demote the attention projections to host memory to make room for blocks nothing will fill. * * The three answers are per RANK, and under tensor parallel that is already the even split across * devices: declare runs once per rank with every dimension ALREADY DIVIDED (spec §9), so summing @@ -377,6 +376,13 @@ struct WeightFootprint { int64_t statics = 0; /* non-expert and device-readable -- the floor under any budget */ int64_t experts = 0; /* the elastic plane: what streams from host when it does not fit */ int64_t expert_layer_max = 0; /* the most expert bytes any one routed layer holds */ + int64_t expert_unit_max = 0; /* the largest expert unit's slot */ + /* THE SLAB'S SPARE SLOTS beside the residents of an expert-tiered plan, at their most: per + * expert slab class, the shadow slots and the staging ring and the tail pad + * (Planner::assign_expert_tiered). They come out of the same weight budget as the residents. */ + int64_t expert_spare = 0; + int64_t layer_unit_max = 0; /* the widest per-layer unit's slot: the file tier's staging */ + bool routed = false; /* a layer has experts: the file tier's read windows */ int64_t mapped = 0; /* no device kernel can read them; they never enter a pool at all */ int64_t hosted = 0; /* --embedding-placement ram: in the pinned host pool, off the card */ /* The tables the two placement flags move, wherever the buckets above count them: `embedding` @@ -398,6 +404,18 @@ struct WeightFootprint { void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding, TablePlacement ngram); +/* THE PINNED STAGING THE FILE TIER TAKES OUT OF --host-pool-mib before any unit is placed in it: + * RAD_PLACE_FILE_STAGE_SLOTS of the widest per-layer unit, and the read windows when a routed + * layer can stream from the container. Planner::plan spends it; the budget counts it the same. */ +int64_t file_stage_reserve(int64_t widest, bool routed); + +/* THE EXPERT BYTES THE CARD MUST HOLD when `host_room` bytes of the pinned host pool are free for + * experts: everything the pool cannot take, the slab's spare slots beside them, and one unit of + * first-fit slack on each side -- the resident fill and the pool fill each skip a unit that does + * not fit and can leave up to one unit's room unspent. At most every expert and the spare slots. + * A weight budget of the statics and this much places every expert in VRAM or the host pool. */ +int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room); + /* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight * that at least one op reads and that only `embed_lookup` reads is a token embedding table, and * one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what diff --git a/core/rad_core.h b/core/rad_core.h index bfff7331..557ad42e 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -151,8 +151,6 @@ struct WeightInfo { int n_part_spans = 0; int64_t part_lo[RAD_MAX_ROW_PARTS] = {0}, part_hi[RAD_MAX_ROW_PARTS] = {0}; int64_t part_total[RAD_MAX_ROW_PARTS] = {0}; - /* rad_weight_shard_zero: this rank reads nothing for it and the loader writes zeros. */ - bool shard_zero = false; /* WHAT IT IS A VIEW OF (RadWeightDecl::source and ::planes, spec §4.3). `enc` is the source's * encoding as the model holds it -- or, with nothing behind the builder, plain in the declared @@ -212,7 +210,6 @@ struct WeightInfo { for (int i = 0; i < RAD_MAX_ROW_PARTS; ++i) { part_lo[i] = o.part_lo[i]; part_hi[i] = o.part_hi[i]; part_total[i] = o.part_total[i]; } - shard_zero = o.shard_zero; source = o.source; enc = o.enc; enc_known = o.enc_known; n_sel = o.n_sel; for (int i = 0; i < RAD_ENC_MAX_PLANES; ++i) { sel[i] = o.sel[i]; sel_rows[i] = o.sel_rows[i]; sel_cols[i] = o.sel_cols[i]; @@ -641,7 +638,6 @@ struct Config { * a third name for the second one, and a flag whose values are not all distinct is a flag * whose log line cannot be read back. */ std::string kv_cache_dtype = "bf16"; - double expert_cache_ratio = 0.75; /* --expert-vs-cache-ratio, weights vs KV of the remainder */ /* SET BY THE RESOLVER, NOT BY A FLAG. vram_budget_resolve writes the two budgets above into * this config, which erases the only evidence of whether they were stated or derived -- and * Pools needs that to know whether unspent VRAM is a mis-stated budget worth warning about or diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp index 326788f6..11444e8e 100644 --- a/core/runtime/tierexec.cpp +++ b/core/runtime/tierexec.cpp @@ -19,7 +19,7 @@ TierExec::~TierExec() { close(); } int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk, const std::vector& groups, int max_batch, int64_t max_copy, int64_t max_chain, bool leader, int device, int64_t slot_off, - int64_t ck_slot_off, RadStream shared) { + const HostArena* ck_store, RadStream shared) { close(); if (!reg || !kv || !tiers || groups.empty() || max_batch <= 0 || max_copy <= 0 || max_chain <= 0) @@ -28,9 +28,7 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* max_batch_ = max_batch; max_copy_ = max_copy; max_chain_ = max_chain; slot_off_ = slot_off; slot_bytes_ = tiers->entry_bytes(); - ck_bytes_ = kv->checkpoint_bytes(); - ck_slot_bytes_ = tiers->ckpt_bytes(); - ck_slot_off_ = ck_slot_off; + ck_store_ = ck_store && ck_store->enabled() ? ck_store : nullptr; shared_ = shared; RAD_TRY(rad_dev_set(device_)); @@ -46,6 +44,11 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* gi.n_blocks = p->n_blocks; gi.base = p->base; gi.off = off; + if (p->zero) { + gi.zero = true; + gi_.push_back(gi); + continue; + } /* THE FRAGMENT WIDTH IS THE CONSTRAINT THE KERNEL IS PICKED ON. libr4d's byte-row pair * takes n as a multiple of 4; a geometry that does not satisfy it resolves to nothing * here rather than failing at launch inside a batch. */ @@ -66,6 +69,15 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* gi_.push_back(gi); } if (gi_.empty()) return RAD_E_UNSUPPORTED; + /* EVERY CACHED GROUP ZERO ON THIS RANK: it would hold nothing of any entry, and an empty + * entry is a zero-width copy on every path below. Said, and the tiers are off -- one rank + * that cannot take part takes them off for all. */ + if (off == 0) { + RAD_WARN("kv tiers: this rank keeps no cache for any group the prefix cache holds " + "(rad_kv_group_zero), so it has no part of an entry to move. The tiers are off."); + close(); + return RAD_E_UNSUPPORTED; + } entry_bytes_ = off; /* NOTHING IS BUILT ON THE DEVICE HERE -- see device_init(). A tier that is configured but has @@ -77,10 +89,8 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* char buf[320]; std::snprintf(buf, sizeof buf, "kv tier transfer: %zu paged group(s), %s an entry, batches of %d through " - "gather_rows/scatter_rows at u8%s%s", - gi_.size(), humanb(entry_bytes_).c_str(), max_batch_, - ck_bytes_ > 0 ? "; linear state as one contiguous copy of " : "", - ck_bytes_ > 0 ? humanb(ck_bytes_).c_str() : ""); + "gather_rows/scatter_rows at u8", + gi_.size(), humanb(entry_bytes_).c_str(), max_batch_); report_ = buf; enabled_ = true; return RAD_OK; @@ -129,7 +139,7 @@ void TierExec::close() { order_.clear(); verify_pending_.clear(); entry_bytes_ = 0; - ck_bytes_ = ck_slot_bytes_ = ck_slot_off_ = 0; + ck_store_ = nullptr; enabled_ = false; leader_ = false; reg_ = nullptr; kv_ = nullptr; tiers_ = nullptr; disk_ = nullptr; @@ -255,22 +265,20 @@ static uint64_t tier_fnv(const void* p, int64_t n) { return h; } -void TierExec::verify_note(const BlockHash& key, const void* p, int64_t n, bool snapshot) { +void TierExec::verify_note(const BlockHash& key, const void* p, int64_t n) { if (!verify_ || !leader_ || !p || n <= 0) return; - (snapshot ? out_ck_ : out_sum_)[key] = tier_fnv(p, n); + out_sum_[key] = tier_fnv(p, n); } -void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n, bool snapshot) { +void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n) { if (!verify_ || !leader_ || !p || n <= 0) return; - auto& m = snapshot ? out_ck_ : out_sum_; - auto it = m.find(key); - if (it == m.end()) return; /* never went out through this process */ + auto it = out_sum_.find(key); + if (it == out_sum_.end()) return; /* never went out through this process */ const uint64_t back = tier_fnv(p, n); if (back == it->second) return; - RAD_ERR("kv tiers: the %s for %s came back DIFFERENT (%016llx out, %016llx in). The tier is " - "moving the wrong bytes, not the engine choosing differently downstream.", - snapshot ? "linear-state snapshot" : "attention blocks", key.str().c_str(), - (unsigned long long)it->second, (unsigned long long)back); + RAD_ERR("kv tiers: the attention blocks for %s came back DIFFERENT (%016llx out, %016llx in). " + "The tier is moving the wrong bytes, not the engine choosing differently downstream.", + key.str().c_str(), (unsigned long long)it->second, (unsigned long long)back); } /* ------------------------------------------------------------------ helpers */ @@ -295,7 +303,7 @@ bool TierExec::blocks_backed(const std::vector& blocks, const char* wha for (size_t k = 0; k < gi_.size(); ++k) { if (k >= blocks.size()) continue; /* an absent group is the gather's -1 row */ const int32_t b = blocks[k]; - if (b < 0) continue; + if (b < 0 || gi_[k].zero) continue; const int64_t live = kv_->live_blocks(gi_[k].g); if (b < live) continue; if (warned_unbacked_) return false; @@ -352,7 +360,7 @@ int TierExec::enqueue_copy(std::vector& jobs, RadStream compute) { if (!blocks_backed(j->blocks, "copy to host")) return RAD_E_STATE; /* AFTER EVERYTHING THE COMPUTE STREAM HAS BEEN GIVEN, which includes the step that wrote these - * blocks and the save that wrote the snapshots. A stream wait, not a host wait. */ + * blocks. A stream wait, not a host wait. */ TIER_TRY(rad_event_record(ev_compute_, compute), "ordering the copy after the step"); TIER_TRY(rad_event_wait(stream_, ev_compute_), "ordering the copy after the step"); @@ -369,7 +377,7 @@ int TierExec::enqueue_copy(std::vector& jobs, RadStream compute) { for (int64_t s = 0; s < n; s += max_batch_) { const int64_t c = std::min(max_batch_, n - s); for (size_t gidx = 0; gidx < gi_.size(); ++gidx) - for (int64_t l = 0; l < gi_[gidx].n_layers; ++l) + for (int64_t l = 0; l < gi_[gidx].n_layers && !gi_[gidx].zero; ++l) TIER_TRY(run_rows(gi_[gidx].gather, /*scatter=*/false, gi_[gidx], l, stage_, idx_dev_ + (int64_t)gidx * n + s, c), "the gather out of the pool"); @@ -378,30 +386,13 @@ int TierExec::enqueue_copy(std::vector& jobs, RadStream compute) { st_.bytes_out += n * entry_bytes_; } - /* The linear half: one contiguous copy each, out of the device slot the snapshot sits in. */ - for (TierJob& j : jobs) { - if (j.ck_host < 0 || j.ck_dev < 0 || ck_bytes_ <= 0) continue; - if (kv_->back_checkpoint(j.ck_dev) < 0) { j.ck_ok = false; continue; } - const void* src = kv_->checkpoint_ptr(j.ck_dev); - char* dst = (char*)tiers_->ckpt_arena().at(j.ck_host); - if (!src || !dst) { j.ck_ok = false; continue; } - const int st = rad_memcpy_async(dst + ck_slot_off_, src, ck_bytes_, stream_); - if (st != RAD_OK) { - warn_once("the snapshot copy to host memory", st); - j.ck_ok = false; - continue; - } - st_.bytes_out += ck_bytes_; - } - TIER_TRY(rad_event_record(ev_copy_, stream_), "marking the copy"); copy_out_ = true; ++st_.passes; st_.jobs += (int64_t)jobs.size(); if (verify_) for (const TierJob& j : jobs) - verify_pending_.push_back({j.key, j.blocks.empty() ? -1 : j.host_slot, - j.ck_ok ? j.ck_host : -1}); + verify_pending_.push_back({j.key, j.blocks.empty() ? -1 : j.host_slot}); return RAD_OK; } @@ -415,10 +406,7 @@ int TierExec::copy_state() { for (const VerifyNote& v : verify_pending_) { if (v.host_slot >= 0) verify_note(v.key, (char*)tiers_->arena().at(v.host_slot) + slot_off_, - entry_bytes_, false); - if (v.ck_host >= 0) - verify_note(v.key, (char*)tiers_->ckpt_arena().at(v.ck_host) + ck_slot_off_, - ck_bytes_, true); + entry_bytes_); } } verify_pending_.clear(); @@ -426,8 +414,22 @@ int TierExec::copy_state() { return q > 0 ? 1 : q; } +int TierExec::wait_copy() { + if (!copy_out_) return 1; + (void)rad_dev_set(device_); + const int st = rad_event_sync(ev_copy_); + if (st != RAD_OK) warn_once("waiting for the copy to host memory", st); + return copy_state(); +} + /* ------------------------------------------------------------------ restore */ +void TierExec::quiesce() { + if (!enabled_ || !stream_) return; + if (rad_dev_set(device_) < 0) return; + (void)rad_stream_sync(stream_); +} + int TierExec::issue_restore(std::vector& jobs, RadStream compute, std::vector* ok) { ok->assign(jobs.size(), 0); @@ -486,7 +488,7 @@ int TierExec::issue_restore(std::vector& jobs, RadStream compute, for (size_t i = 0; i < m; ++i) order_.push_back(&jobs[i]); for (size_t i = 0; i < m; ++i) verify_check(jobs[i].key, (char*)tiers_->arena().at(jobs[i].host_slot) + slot_off_, - entry_bytes_, false); + entry_bytes_); /* FROM HERE ON A FAILURE LEAVES A MIXTURE, so every job about to be written is marked started * first -- report() drops a started job that failed rather than trusting its host copy to @@ -513,7 +515,7 @@ int TierExec::issue_restore(std::vector& jobs, RadStream compute, const int64_t cc = std::min(max_batch_, c - b); if ((st = copy_runs(order_, s + (size_t)b, cc, /*out=*/false)) != RAD_OK) break; for (size_t gidx = 0; gidx < ng && st == RAD_OK; ++gidx) - for (int64_t l = 0; l < gi_[gidx].n_layers && st == RAD_OK; ++l) + for (int64_t l = 0; l < gi_[gidx].n_layers && st == RAD_OK && !gi_[gidx].zero; ++l) st = run_rows(gi_[gidx].scatter, /*scatter=*/true, gi_[gidx], l, stage_, d + (int64_t)gidx * c + b, cc); } @@ -523,45 +525,6 @@ int TierExec::issue_restore(std::vector& jobs, RadStream compute, for (size_t i = 0; i < done; ++i) (*ok)[i] = 1; st_.bytes_in += (int64_t)done * entry_bytes_; - /* THE LINEAR HALF, into a slot the leader allocates. The same rule as the blocks: the id is - * rank 0's to choose, and a follower takes the id it is handed and backs its own pages. A - * snapshot that cannot be placed is not a failure of the restore -- the session keeps its - * attention hit and replays its linear layers, which is what it would have done with no - * tiers at all. - * - * THE DEEPEST ONE IS WORTH A SLOT SOMEBODY ELSE HAS. A hit resumes from the last checkpoint at - * or below its attention hit, which on a restored chain is the chain's last snapshot; the - * earlier ones take a slot only where one is free. A full pool is then made room in for that - * one snapshot by detaching another session's, which that session's own next restore brings - * back -- rather than for every snapshot on the chain, which would push out as many other - * sessions' states as this one has checkpoints. */ - size_t deepest = done; - for (size_t i = 0; i < done; ++i) - if (jobs[i].ck_want && jobs[i].ck_ok && jobs[i].ck_host >= 0) deepest = i; - for (size_t i = 0; i < done; ++i) { - TierJob& j = jobs[i]; - if (!j.ck_want || !j.ck_ok || j.ck_host < 0 || ck_bytes_ <= 0) continue; - if (leader_) { - int32_t slot = -1; - if (kv_->alloc_checkpoint(&slot) != RAD_OK || slot < 0) { - slot = -1; - if (i != deepest || !ck_room_ || !ck_room_() || - kv_->alloc_checkpoint(&slot) != RAD_OK || slot < 0) - continue; - } - j.ck_dev = slot; - } - if (j.ck_dev < 0) continue; - if (kv_->back_checkpoint(j.ck_dev) < 0) { j.ck_ok = false; continue; } - const char* src = (const char*)tiers_->ckpt_arena().at(j.ck_host); - void* dst = kv_->checkpoint_ptr(j.ck_dev); - if (!src || !dst) { j.ck_ok = false; continue; } - verify_check(j.key, src + ck_slot_off_, ck_bytes_, true); - const int cs = rad_memcpy_async(dst, src + ck_slot_off_, ck_bytes_, stream_); - if (cs != RAD_OK) { warn_once("the snapshot copy back into the pool", cs); j.ck_ok = false; continue; } - st_.bytes_in += ck_bytes_; - } - /* THE STEP THAT READS THESE WAITS FOR THEM, on the device. If even the marker cannot be * enqueued the only ordering left is the host's. */ if (rad_event_record(ev_restore_, stream_) != RAD_OK || @@ -573,13 +536,13 @@ int TierExec::issue_restore(std::vector& jobs, RadStream compute, return st; } -int TierExec::fence(RadEvent* out) { +int TierExec::fence(RadEvent* out, RadStream on) { *out = nullptr; - if (!enabled_ || !stream_) return RAD_OK; + if (!enabled_ || (!on && !stream_)) return RAD_OK; RAD_TRY(rad_dev_set(device_)); RadEvent e = nullptr; RAD_TRY(rad_event_create(&e)); - const int st = rad_event_record(e, stream_); + const int st = rad_event_record(e, on ? on : stream_); if (st != RAD_OK) { rad_event_destroy(e); return st; } *out = e; return RAD_OK; @@ -602,12 +565,13 @@ bool TierExec::run_write(TierJob& j) { const void* src = tiers_->arena().at(j.host_slot); ok = disk_ && src && disk_->put_block(j.key, nullptr, 0, src, slot_bytes_) == RAD_OK; } - if (j.ck_host >= 0) { - const void* cs = tiers_->ckpt_arena().at(j.ck_host); + if (j.ck_slot >= 0) { + const void* cs = ck_store_ ? ck_store_->at(j.ck_slot) : nullptr; /* A snapshot store that was never opened -- no room for one inside the disk cap -- refuses - * this, which is the right answer and not an error: the host copy stays the only one, as - * it was. */ - j.ck_ok = disk_ && cs && disk_->put_checkpoint(j.key, j.ck_pos, cs, ck_slot_bytes_) == RAD_OK; + * this, which is the right answer and not an error: the slot stays the only copy, as it + * was. */ + j.ck_ok = disk_ && cs && + disk_->put_checkpoint(j.key, j.ck_pos, cs, ck_store_->slot_bytes()) == RAD_OK; } return ok; } @@ -633,9 +597,10 @@ void TierExec::run_fetch(std::vector& jobs, std::vector* ok) { st_.bytes_in += (int64_t)keys.size() * slot_bytes_; } for (TierJob& j : jobs) { - if (j.ck_host < 0) continue; - void* cs = tiers_->ckpt_arena().at(j.ck_host); - j.ck_ok = disk_ && cs && disk_->get_checkpoint(j.key, j.ck_pos, cs, ck_slot_bytes_) == RAD_OK; + if (!j.ck_want || j.ck_slot < 0) continue; + void* cs = ck_store_ ? ck_store_->at(j.ck_slot) : nullptr; + j.ck_ok = disk_ && cs && + disk_->get_checkpoint(j.key, j.ck_pos, cs, ck_store_->slot_bytes()) == RAD_OK; } } @@ -644,28 +609,23 @@ void TierExec::run_fetch(std::vector& jobs, std::vector* ok) { void TierExec::report_pass(std::vector& jobs, const std::vector& ok, uint64_t now_ns) { if (!enabled_ || !leader_) return; + bool quiet = false; for (size_t i = 0; i < jobs.size(); ++i) { TierJob& j = jobs[i]; const bool good = i < ok.size() && ok[i]; - /* A SNAPSHOT IS RESTORED ONLY IF EVERY RANK RESTORED ITS SHARD, and the leader is the only - * one that can act on that. It allocates the checkpoint slot and fills its own window - * first, so a follower that then fails leaves the slot holding this rank's new state beside - * another rank's stale state -- a checkpoint the cache would go on to serve, one card - * resuming the conversation and the other resuming whatever it last held. - * - * A PROMOTION THAT FAILED AS A WHOLE gives back everything the leader took for it: report() - * drops or keeps the record, and nothing will ever name these blocks or this slot again. */ - if (j.kind == TierJob::Kind::ToDevice && j.ck_dev >= 0 && (!j.ck_ok || !good)) { - kv_->free_checkpoint(j.ck_dev); - j.ck_dev = -1; - } + /* A PROMOTION THAT FAILED AS A WHOLE gives back the blocks the leader took for it, once + * nothing queued against them can still land: report() drops or keeps the record, and + * nothing will ever name these blocks again. */ if (j.kind == TierJob::Kind::ToDevice && !good) { + if (!quiet) { quiesce(); quiet = true; } for (size_t k = 0; k < gi_.size() && k < j.blocks.size(); ++k) if (j.blocks[k] >= 0) kv_->release_block(gi_[k].g, j.blocks[k]); j.blocks.clear(); } tiers_->report(j, good, now_ns); } + /* STORE SLOTS THE TIERS HAD BEEN KEEPING: a write that read one the cache let go of, or a + * read nothing took. The disk thread is done with them -- these come only from reports. */ std::vector frees; tiers_->take_checkpoint_frees(&frees); for (int32_t s : frees) kv_->free_checkpoint(s); @@ -703,11 +663,12 @@ void TierIO::stop() { fetch_done_.clear(); } -bool TierIO::submit(std::vector&& jobs) { +bool TierIO::submit(std::vector&& jobs, std::vector&& fences) { { std::lock_guard lk(mu_); if (has_work_ || has_done_ || !th_.joinable()) return false; work_ = std::move(jobs); + work_fences_ = std::move(fences); ok_.assign(work_.size(), 1); work_at_ = 0; has_work_ = true; @@ -734,12 +695,15 @@ bool TierIO::take_fetch(Fetch* out) { return true; } -bool TierIO::take(std::vector* jobs, std::vector* ok) { +bool TierIO::take(std::vector* jobs, std::vector* ok, + std::vector* fences) { std::lock_guard lk(mu_); if (!has_done_) return false; *jobs = std::move(done_); *ok = std::move(ok_); + if (fences) *fences = std::move(done_fences_); done_.clear(); + done_fences_.clear(); ok_.clear(); has_done_ = false; return true; @@ -778,14 +742,26 @@ void TierIO::loop() { fetch_done_.push_back(std::move(f)); continue; } - /* One write at a time, so a read that arrives behind a long batch waits for one job. */ - const bool ok = i < work_.size() ? x_->run_write(work_[i]) : true; + /* NOT A BYTE UNTIL THE COPIES THAT FILLED THE SLOTS HAVE LANDED, once a batch. A fence + * that cannot be waited on fails the batch, and every record keeps what it had. */ + bool fenced = true; + if (i == 0) + for (RadEvent e : work_fences_) if (e && rad_event_sync(e) != RAD_OK) fenced = false; + bool ok = false; + if (fenced) ok = i < work_.size() ? x_->run_write(work_[i]) : true; std::lock_guard lk(mu_); - if (i < ok_.size()) ok_[i] = ok ? 1 : 0; - work_at_ = i + 1; + if (!fenced) { + ok_.assign(work_.size(), 0); + work_at_ = work_.size(); + } else { + if (i < ok_.size()) ok_[i] = ok ? 1 : 0; + work_at_ = i + 1; + } if (work_at_ >= work_.size()) { done_ = std::move(work_); + done_fences_ = std::move(work_fences_); work_.clear(); + work_fences_.clear(); has_work_ = false; has_done_ = true; } diff --git a/core/runtime/tierexec.h b/core/runtime/tierexec.h index 4b5b4afd..68112927 100644 --- a/core/runtime/tierexec.h +++ b/core/runtime/tierexec.h @@ -71,7 +71,7 @@ public: int configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk, const std::vector& groups, int max_batch, int64_t max_copy, int64_t max_chain, bool leader, int device, int64_t slot_off, - int64_t ck_slot_off, RadStream shared); + const HostArena* ck_store, RadStream shared); void close(); bool enabled() const { return enabled_; } std::string report() const { return report_; } @@ -105,6 +105,13 @@ public: * the transfer stream reported an error. Taking the answer clears it. */ int copy_state(); bool copy_out() const { return copy_out_; } + /* copy_state, after waiting for the batch to land. For a caller that cannot go on until the + * copy has a host slot to show for it -- an eviction that would otherwise lose the entry. */ + int wait_copy(); + /* EVERYTHING THIS RANK ENQUEUED HAS LANDED. For a block given back on a failure path while a + * copy into it may still be in flight: the pool would hand it to a sequence whose writes the + * late copy then overwrites. */ + void quiesce(); /* ---------------- restore ---------------- * @@ -115,36 +122,33 @@ public: * the jobs past the cut are left unstarted. `ok[i]` is whether job i was fully enqueued on * this rank. */ int issue_restore(std::vector& jobs, RadStream compute, std::vector* ok); - - /* A MARK ON THIS RANK'S TRANSFER STREAM, after everything enqueued on it so far. A restore - * reads host slots asynchronously, and a slot it is still reading may be given up and handed - * to a read off disk the moment the restore has reported; the IO thread waits for this mark - * before it writes into any slot it was handed. Null when nothing was ever enqueued here. The + /* A MARK ON THIS RANK'S TRANSFER STREAM, after everything enqueued on it so far -- or on + * `on`, the rank's compute stream, when it is given. A restore reads host slots + * asynchronously, and a slot it is still reading may be given up and handed to a read off + * disk the moment the restore has reported; the IO thread waits for this mark before it + * writes into any slot it was handed. A snapshot's store slot is read and written by copies + * on the compute stream (KVManager::checkpoint_save), so a disk write or read of one waits + * for that stream's mark. Null when nothing was ever enqueued on the transfer stream. The * caller owns the event. */ - int fence(RadEvent* out); + int fence(RadEvent* out, RadStream on = nullptr); /* ---------------- the disk store (leader only; TierIO's thread) ---------------- */ void run_disk(std::vector& jobs, std::vector* ok); /* One ToDisk job; true when it was written. */ bool run_write(TierJob& j); /* ToHost jobs: the blocks read in parallel into the host slots they were given, then the - * snapshots. `ok[i]` is the blocks' result, `ck_ok` the snapshot's. */ + * snapshots into their store slots. `ok[i]` is the blocks' result, `ck_ok` the snapshot's. */ void run_fetch(std::vector& jobs, std::vector* ok); - /* Leader only. Gives back what a failed job held -- a restore's blocks and checkpoint slot -- - * reports every job to the policy, and frees the device checkpoint slots a finished copy was - * holding on the cache's behalf. `now_ns` is when the pass ran: a promotion is a use. */ + /* Leader only. Gives back what a failed job held -- a restore's blocks -- reports every job to + * the policy, and frees the store slots a finished write or an unclaimed read was holding on + * the cache's behalf. `now_ns` is when the pass ran: a promotion is a use. */ void report_pass(std::vector& jobs, const std::vector& ok, uint64_t now_ns); /* A lookup hit off-device: the job that would bring it back, or false when the entry is not * off-device or already has work outstanding. */ bool plan_promote(const BlockHash& key, TierJob* out); /* leader only */ - /* Leader only: how a restore gets a device checkpoint slot when the pool is full. The cache - * owns the policy for which snapshot gives its slot up (PrefixCache::free_checkpoint_for_restore); - * this object only knows it needs one. True when a slot was freed. */ - void set_checkpoint_room(std::function f) { ck_room_ = std::move(f); } - struct Stats { int64_t passes = 0, jobs = 0, bytes_out = 0, bytes_in = 0; }; const Stats& stats() const { return st_; } @@ -157,6 +161,10 @@ private: int64_t n_blocks = 0; void* base = nullptr; int64_t off = 0; /* this group's start inside one entry's staging bytes */ + /* rad_kv_group_zero: no shard on this rank. Kept in its place, because a job's block ids + * are one per cached group in the same order on every rank; nothing is gathered or + * scattered for it and it is no part of this rank's entry. */ + bool zero = false; Resolved gather, scatter; }; @@ -202,16 +210,13 @@ private: KVManager* kv_ = nullptr; IdleTiers* tiers_ = nullptr; SSDTier* disk_ = nullptr; - std::function ck_room_; std::vector gi_; int64_t entry_bytes_ = 0; /* ---- the linear half ---- - * `ck_bytes_` is THIS RANK's shard of one snapshot and `ck_slot_bytes_` the whole shared slot, - * exactly as entry_bytes_ and slot_bytes_ are for blocks. Zero on a model with no recurrent - * state, which is the whole of the "off" path here. */ - int64_t ck_bytes_ = 0; - int64_t ck_slot_bytes_ = 0; - int64_t ck_slot_off_ = 0; + * The engine's snapshot store, whose slots the disk thread writes out and reads back whole -- + * every rank's shard of a snapshot together. Null on a model with no recurrent state, which + * is the whole of the "off" path here. */ + const HostArena* ck_store_ = nullptr; int max_batch_ = 0; int64_t max_copy_ = 0; int64_t max_chain_ = 0; @@ -254,17 +259,17 @@ private: * the only question worth asking first: is the tier moving the wrong bytes, or is it moving * the right ones and something downstream is choosing differently? * - * A DIAGNOSTIC, NOT A GUARD. It hashes on the host, which for a snapshot is tens of - * milliseconds an entry -- affordable when a run is being bisected and not otherwise. Off + * A DIAGNOSTIC, NOT A GUARD. It hashes on the host, which is a cost on every entry -- + * affordable when a run is being bisected and not otherwise. Off * unless the variable is set, and leader-only, because the map is keyed by an object the * followers do not own. A copy out is hashed when it has LANDED, which is when copy_state * first sees it done. */ bool verify_ = false; - std::unordered_map out_sum_, out_ck_; - struct VerifyNote { BlockHash key; int32_t host_slot = -1; int32_t ck_host = -1; }; + std::unordered_map out_sum_; + struct VerifyNote { BlockHash key; int32_t host_slot = -1; }; std::vector verify_pending_; - void verify_note(const BlockHash& key, const void* p, int64_t n, bool snapshot); - void verify_check(const BlockHash& key, const void* p, int64_t n, bool snapshot); + void verify_note(const BlockHash& key, const void* p, int64_t n); + void verify_check(const BlockHash& key, const void* p, int64_t n); std::string report_; Stats st_; @@ -288,10 +293,13 @@ public: ~TierIO(); void start(TierExec* leader); void stop(); - /* False when a batch is already out. */ - bool submit(std::vector&& jobs); + /* False when a batch is already out. `fences` are waited on before the first job is written -- + * a snapshot's store slot is filled by a copy on the compute stream (TierExec::fence) -- and + * come back with the batch from take(), still the caller's to destroy. */ + bool submit(std::vector&& jobs, std::vector&& fences = {}); /* The finished batch, when there is one. */ - bool take(std::vector* jobs, std::vector* ok); + bool take(std::vector* jobs, std::vector* ok, + std::vector* fences = nullptr); bool busy() const; /* A read off disk. `tag` is the caller's (the request waiting on it); `fences` are waited on @@ -314,6 +322,7 @@ private: mutable std::mutex mu_; std::condition_variable cv_; std::vector work_, done_; + std::vector work_fences_, done_fences_; std::vector ok_; size_t work_at_ = 0; /* the next write job; the thread's alone while has_work_ */ bool has_work_ = false, has_done_ = false, stop_ = false; diff --git a/core/sample/gbnf.cpp b/core/sample/gbnf.cpp index 4a5e6ad1..93a3039a 100644 --- a/core/sample/gbnf.cpp +++ b/core/sample/gbnf.cpp @@ -83,9 +83,17 @@ std::pair decode_utf8(const char* src) { std::pair, PartialUtf8> decode_utf8(const std::string& src, PartialUtf8 partial_start) { + std::vector cps; + const PartialUtf8 p = decode_utf8(src, partial_start, &cps); + return { std::move(cps), p }; +} + +PartialUtf8 decode_utf8(const std::string& src, PartialUtf8 partial_start, + std::vector* out) { static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 }; const char* pos = src.c_str(); - std::vector cps; + std::vector& cps = *out; + cps.clear(); cps.reserve(src.size() + 1); uint32_t value = partial_start.value; @@ -95,7 +103,7 @@ std::pair, PartialUtf8> decode_utf8(const std::string& src const uint8_t next_byte = (uint8_t)*pos; if ((next_byte >> 6) != 2) { cps.push_back(0); - return { std::move(cps), PartialUtf8{ 0, -1 } }; + return PartialUtf8{ 0, -1 }; } value = (value << 6) + (next_byte & 0x3F); ++pos; @@ -110,7 +118,7 @@ std::pair, PartialUtf8> decode_utf8(const std::string& src if (n_remain < 0) { cps.clear(); cps.push_back(0); - return { std::move(cps), PartialUtf8{ 0, n_remain } }; + return PartialUtf8{ 0, n_remain }; } const uint8_t mask = (uint8_t)((1 << (7 - n_remain)) - 1); value = first_byte & mask; @@ -123,7 +131,7 @@ std::pair, PartialUtf8> decode_utf8(const std::string& src if (n_remain == 0) cps.push_back(value); } cps.push_back(0); - return { std::move(cps), PartialUtf8{ value, n_remain } }; + return PartialUtf8{ value, n_remain }; } } /* namespace gbnf */ @@ -830,22 +838,73 @@ struct GbnfState { } }; +/* A STATE AS fill_mask HOLDS IT, NOT COPIED: the stacks through pointers, in the order the key + * sorts them into. It hashes and compares as the GbnfState it would become, so the cache is + * probed without building a key -- a copy of every stack, per mask -- and one is built only for a + * mask that is stored. */ +struct GbnfStateView { + const std::vector* stacks; + PartialUtf8 partial; + bool allow_eog; + int64_t words; +}; + struct GbnfStateHash { - size_t operator()(const GbnfState& k) const { + using is_transparent = void; + + template + static size_t hash(const Stacks& stacks, Deref deref, PartialUtf8 partial, bool allow_eog, + int64_t words) { size_t h = 1469598103934665603ull; auto mix = [&h](size_t v) { h ^= v; h *= 1099511628211ull; }; - for (const GbnfStack& s : k.stacks) { + for (const auto& x : stacks) { + const GbnfStack& s = deref(x); mix(s.size()); for (const GbnfElement* e : s) mix((size_t)e); } - mix(k.partial.value); - mix((size_t)(k.partial.n_remain + 1)); - mix(k.allow_eog ? 1u : 0u); - mix((size_t)k.words); + mix(partial.value); + mix((size_t)(partial.n_remain + 1)); + mix(allow_eog ? 1u : 0u); + mix((size_t)words); return h; } + size_t operator()(const GbnfState& k) const { + return hash(k.stacks, [](const GbnfStack& s) -> const GbnfStack& { return s; }, + k.partial, k.allow_eog, k.words); + } + size_t operator()(const GbnfStateView& k) const { + return hash(*k.stacks, [](const GbnfStack* s) -> const GbnfStack& { return *s; }, + k.partial, k.allow_eog, k.words); + } }; +struct GbnfStateEq { + using is_transparent = void; + + bool operator()(const GbnfState& a, const GbnfState& b) const { return a == b; } + bool operator()(const GbnfStateView& v, const GbnfState& k) const { + if (k.allow_eog != v.allow_eog || k.words != v.words || + k.partial.value != v.partial.value || k.partial.n_remain != v.partial.n_remain || + k.stacks.size() != v.stacks->size()) + return false; + for (size_t i = 0; i < k.stacks.size(); ++i) + if (k.stacks[i] != *(*v.stacks)[i]) return false; + return true; + } + bool operator()(const GbnfState& k, const GbnfStateView& v) const { return (*this)(v, k); } +}; + +/* The key a view becomes, for storing. */ +static GbnfState state_of(const GbnfStateView& v) { + GbnfState k; + k.stacks.reserve(v.stacks->size()); + for (const GbnfStack* s : *v.stacks) k.stacks.push_back(*s); + k.partial = v.partial; + k.allow_eog = v.allow_eog; + k.words = v.words; + return k; +} + struct GbnfProgram { GbnfRuleSet rules; GbnfStacks start; /* the root's alternates, advanced once */ @@ -864,7 +923,7 @@ struct GbnfProgram { * speculative window revisiting a state the work again. */ mutable std::mutex mu; struct Entry { std::vector mask; uint64_t used = 0; }; - mutable std::unordered_map masks; + mutable std::unordered_map masks; mutable uint64_t clock = 0; /* A tool-calling schema's working set is on the order of a hundred states; 512 is room for a @@ -873,7 +932,7 @@ struct GbnfProgram { * that was computed. */ static constexpr size_t kMaxMasks = 512; - bool lookup(const GbnfState& k, uint32_t* dst, int64_t n_words) const { + bool lookup(const GbnfStateView& k, uint32_t* dst, int64_t n_words) const { std::lock_guard lk(mu); auto it = masks.find(k); if (it == masks.end()) return false; @@ -1157,29 +1216,42 @@ int GbnfGrammar::accept_token_piece(int32_t token, const std::string& piece) { RAD_WARN("gbnf: token %d cannot be accepted: %s; the request cannot be continued", token, e.what()); stacks_.clear(); + at_ = At{}; return RAD_E_FULL; } catch (const std::bad_alloc&) { RAD_ERR("gbnf: out of memory accepting token %d; the request cannot be continued", token); stacks_.clear(); + at_ = At{}; return RAD_E_NOMEM; } } int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece) { - const auto decoded = decode_utf8(piece, partial_utf8_); - const auto& cps = decoded.first; + const PartialUtf8 partial = decode_utf8(piece, partial_utf8_, &cps_); + const size_t n_cps = cps_.size() - 1; /* the terminating 0 is not a code point */ OpWork work; GbnfStacks new_stacks; SetBuild new_set(work); - new_stacks.reserve(stacks_.size()); /* THE STACKS THAT MATCH CODE POINTS ARE ADVANCED TOGETHER, one code point at a time, as * accept_str does. Advancing each through the whole piece on its own gives the same set -- * the union of the parts is the part of the union -- but when many stacks converge on one * continuation, as every alternative of a wide rule does once it matches, each of them - * re-expands that continuation, and the token costs the square of the width. */ - GbnfStacks current; + * re-expands that continuation, and the token costs the square of the width. + * + * AND THEY ARE ADVANCED THROUGH THE MASK PLAN'S AUTOMATON (plan_step), which holds each stack + * set as a state with its successors memoised per interval of code points. The set is the + * one accept_chr builds; what changes is that a state seen before -- the same free-text + * value, token after token -- is a lookup per code point rather than every closure rebuilt, + * allocated and de-duplicated again. The set comes back sorted, which nothing reads: the + * mask cache sorts its key, and a mask is a union over the stacks. + * + * The new set is written over the one the previous token left (`spare_`) and the two are + * swapped, so a set of the same shape, token after token, allocates nothing; and when the + * automaton says the token left the set the state it was -- the steady state of a free-text + * value -- the set is not touched at all. */ + current_.clear(); for (const auto& stack : stacks_) { if (stack.empty()) continue; const GbnfElement* pos = stack.back(); @@ -1190,19 +1262,37 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece if (!is_end_of_sequence(pos + 1)) next.push_back(pos + 1); advance_stack(prog_->rules, next, new_stacks, new_set); } else { - current.push_back(stack); + current_.push_back(&stack); } } - for (auto it = cps.begin(), end = cps.end() - 1; it != end && !current.empty(); ++it) { - GbnfStacks next; - SetBuild next_set(work); - for (const auto& cs : current) accept_chr(prog_->rules, cs, *it, next, next_set); - current = std::move(next); + GbnfStacks& out = spare_; + if (n_cps > 0 && !current_.empty()) { + /* `at_` names a state only when every stack steps over code points, so with it known no + * stack matched a token terminal above and the set is the stepped stacks alone. */ + gbnf::PlanState at{ at_.gen, at_.id }; + const bool same = gbnf::plan_step(*prog_->plan, current_, &at, cps_.data(), n_cps, &out, + work); + at_ = At{ at.gen, at.id }; + if (same) { + partial_utf8_ = partial; + return RAD_OK; + } + } else { + out.resize(current_.size()); + for (size_t i = 0; i < current_.size(); ++i) out[i].assign(current_[i]->begin(), + current_[i]->end()); + at_ = At{}; } - for (auto& s : current) new_set.insert(new_stacks, std::move(s)); - - stacks_ = std::move(new_stacks); - partial_utf8_ = decoded.second; + /* What a token terminal matched goes first, then the rest without the ones it already holds; + * with nothing matched by token, `out` is the set as it stands -- a state of the automaton, + * or a subset of the set before, and either way without duplicates. */ + if (!new_stacks.empty()) { + for (auto& s : out) new_set.insert(new_stacks, std::move(s)); + out.swap(new_stacks); + at_ = At{}; + } + stacks_.swap(out); + partial_utf8_ = partial; if (stacks_.empty()) { /* NOT AN ERROR HERE, WHICH IS WHY IT LOGS AT DEBUG. This is reached as a matter of course @@ -1290,6 +1380,7 @@ int GbnfGrammar::accept_token(int32_t token) { int GbnfGrammar::accept_str(const std::string& piece) { const auto decoded = decode_utf8(piece, partial_utf8_); const auto& cps = decoded.first; + at_ = At{}; try { OpWork work; @@ -1318,7 +1409,7 @@ int GbnfGrammar::accept_str(const std::string& piece) { void GbnfGrammar::push_state() { - saved_.push_back(Snapshot{ stacks_, partial_utf8_, awaiting_trigger_, scan_, recent_ }); + saved_.push_back(Snapshot{ stacks_, partial_utf8_, awaiting_trigger_, scan_, recent_, at_ }); } int GbnfGrammar::rollback() { @@ -1332,21 +1423,11 @@ int GbnfGrammar::rollback() { awaiting_trigger_ = s.awaiting_trigger; scan_ = s.scan; recent_ = std::move(s.recent); + at_ = s.at; saved_.pop_back(); return RAD_OK; } -/* The cache key for the state the machine is in right now. */ -GbnfState GbnfGrammar::state_key(bool allow_eog, int64_t n_words) const { - GbnfState k; - k.stacks = stacks_; - k.partial = partial_utf8_; - k.allow_eog = allow_eog; - k.words = n_words; - std::sort(k.stacks.begin(), k.stacks.end()); - return k; -} - /* The mask for the current state, with no memo. */ int GbnfGrammar::mask_compute(uint32_t* bitmask, int64_t n_words) const { std::fill(bitmask, bitmask + n_words, 0u); @@ -1391,8 +1472,14 @@ int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const { * because a collision accepted on the hash alone would hand back a mask for a state the * sequence is not in and admit the wrong token set. The key sorts the stacks: two requests * that reach the same state by the same path produce the same order anyway, but the sort is - * what makes that a guarantee rather than an observation. */ - const GbnfState key = state_key(complete(), n_words); + * what makes that a guarantee rather than an observation. The probe sorts pointers to the + * stacks, in storage of the calling thread's own, and copies them only to store. */ + thread_local std::vector sorted; + sorted.clear(); + for (const GbnfStack& s : stacks_) sorted.push_back(&s); + std::sort(sorted.begin(), sorted.end(), + [](const GbnfStack* a, const GbnfStack* b) { return *a < *b; }); + const GbnfStateView key{ &sorted, partial_utf8_, complete(), n_words }; if (prog_->lookup(key, bitmask, n_words)) return RAD_OK; prog_->computed.fetch_add(1, std::memory_order_relaxed); @@ -1400,7 +1487,7 @@ int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const { if (st < 0) return st; /* Store only a mask that stands: a dead state is not worth an entry and returns above. */ - prog_->store(key, bitmask, n_words); + prog_->store(state_of(key), bitmask, n_words); return RAD_OK; } diff --git a/core/sample/gbnf.h b/core/sample/gbnf.h index e7b43deb..daa25778 100644 --- a/core/sample/gbnf.h +++ b/core/sample/gbnf.h @@ -32,6 +32,11 @@ * stacks that match code points are advanced together rather than one at a time, and a * large set is de-duplicated through an index. Each gives the same set as upstream; without * them, stacks that converge on one continuation re-expand it once each. + * - Accepting a token steps the stacks that match code points through the mask plan's + * stack-set automaton (gbnf_mask.cpp, plan_step) rather than through a closure per stack per + * code point, and the grammar remembers which automaton state its stacks are. The set is the + * one upstream's accept builds; the test oracle keeps upstream's accept and every accepted + * token is held to it. * - The token mask is not upstream's candidate walk. It is served from a plan precomputed when * the grammar is compiled (gbnf_mask.cpp): per stack suffix, the tokens it admits whatever lies * below it, and a small trie of what depends on what does. Upstream's walk survives only as @@ -239,12 +244,23 @@ private: uint64_t start; }; + /* The state of the mask plan's automaton `stacks_` is exactly, when it is one: which + * automaton (`gen`) and which state in it, or an id of -1 when that is not known. It lets + * accepting skip canonicalising the set, and skip rewriting it when a token leaves it where + * it was. Everything that sets `stacks_` other than accepting through the automaton resets + * it, or restores it with the stacks it describes. */ + struct At { + uint64_t gen = 0; + int32_t id = -1; + }; + struct Snapshot { GbnfStacks stacks; PartialUtf8 partial; bool awaiting_trigger = false; WordScanner::State scan; std::vector recent; + At at; }; const VocabView* vocab_ = nullptr; @@ -256,11 +272,10 @@ private: std::shared_ptr prog_; GbnfStacks stacks_; PartialUtf8 partial_utf8_{}; + At at_; std::vector saved_; - GbnfState state_key(bool allow_eog, int64_t n_words) const; - /* The mask itself, from the program's plan, with no memo. */ int mask_compute(uint32_t* bitmask, int64_t n_words) const; @@ -278,6 +293,13 @@ private: int accept_token_piece(int32_t token, const std::string& piece); int accept_token_piece_impl(int32_t token, const std::string& piece); + + /* Scratch for accepting, kept so a token in the steady state of a value allocates nothing: + * the piece's code points, the stacks that step over them, and the set before the last one + * accepted, whose storage the next one is written into. None of it is state. */ + std::vector cps_; + std::vector current_; + GbnfStacks spare_; }; /* COMPILE A GRAMMAR, on the calling thread, into the program every GbnfGrammar::create for the diff --git a/core/sample/gbnf_internal.h b/core/sample/gbnf_internal.h index 1f347013..db6d95b1 100644 --- a/core/sample/gbnf_internal.h +++ b/core/sample/gbnf_internal.h @@ -183,6 +183,10 @@ std::pair decode_utf8(const char* src); std::pair, PartialUtf8> decode_utf8(const std::string& src, PartialUtf8 partial_start); +/* The same into `out`, whose capacity is reused; returns the carried state. */ +PartialUtf8 decode_utf8(const std::string& src, PartialUtf8 partial_start, + std::vector* out); + /* ============================================================ elements */ inline bool is_end_of_sequence(const GbnfElement* pos) { @@ -331,5 +335,30 @@ int plan_build(const GbnfRuleSet& rules, uint32_t root, const std::shared_ptr& stacks, PlanState* at, + const uint32_t* cps, size_t n, GbnfStacks* out, OpWork& work); + } /* namespace gbnf */ } /* namespace rad */ diff --git a/core/sample/gbnf_mask.cpp b/core/sample/gbnf_mask.cpp index dd8f4855..0cbd1c25 100644 --- a/core/sample/gbnf_mask.cpp +++ b/core/sample/gbnf_mask.cpp @@ -909,6 +909,8 @@ struct MaskPlan { struct Group { int32_t key; std::vector ctx; }; mutable std::vector groups; mutable GbnfStack ctx; + mutable std::vector step_ptrs; + mutable uint64_t dfa_gen = 0; /* which automaton `dfa` is; see plan_step */ }; void MaskPlanDeleter::operator()(MaskPlan* p) const { delete p; } @@ -1841,23 +1843,85 @@ static void fill_resume(const MaskPlan& P, SetDfa& dfa, const GbnfStacks& stacks } } +/* The plan's automaton, for one operation charged to `work`. The caller holds P.mu. + * + * The automaton is a memo, so past its bound it is dropped and rebuilt rather than refused: every + * state in it can be rediscovered, and a grammar whose stacks deepen with every token would + * otherwise hold a new state per token for as long as it is cached. */ +static SetDfa& plan_dfa(const MaskPlan& P, OpWork& work) { + if (!P.dfa || P.dfa->elems() > kMaxDfaElems) { + if (P.dfa) + RAD_DEBUG("gbnf: the stack-set automaton holds %zu states, %zu stack elements; " + "rebuilding it", P.dfa->n_states(), P.dfa->elems()); + P.dfa = std::make_unique(P.rules); + ++P.dfa_gen; + } + P.dfa->begin(&work); + return *P.dfa; +} + +bool plan_step(const MaskPlan& P, const std::vector& stacks, PlanState* at, + const uint32_t* cps, size_t n, GbnfStacks* out, OpWork& work) { + std::lock_guard lk(P.mu); + SetDfa& dfa = plan_dfa(P, work); + + /* The set as a state: the one the caller names, or canonicalised through pointers -- sorted, + * without duplicates, and copied only if the automaton has not seen it. Charged as intern() + * charges a sort. */ + const bool named = at->id >= 0 && at->gen == P.dfa_gen; + int32_t s0; + if (named) { + s0 = at->id; + work.add(stacks.size() + 1); + } else { + std::vector& ps = P.step_ptrs; + ps.clear(); + size_t elems = 0; + for (const GbnfStack* k : stacks) { + ps.push_back(k); + elems += k->size() + 1; + } + work.add(elems * (1 + (uint64_t)std::bit_width(ps.size()))); + std::sort(ps.begin(), ps.end(), + [](const GbnfStack* a, const GbnfStack* b) { return *a < *b; }); + ps.erase(std::unique(ps.begin(), ps.end(), + [](const GbnfStack* a, const GbnfStack* b) { return *a == *b; }), + ps.end()); + s0 = dfa.intern_ptrs(ps); + } + int32_t s = s0; + + /* One successor per code point: the interval the code point falls in, then that interval's + * successor, each built on first use and served from the memo after. */ + for (size_t k = 0; k < n && s >= 0; ++k) { + const SetDfa::St& S = dfa.parted(s); + const size_t i = (size_t)(std::upper_bound(S.lo.begin(), S.lo.end(), cps[k]) - + S.lo.begin()) - 1; + work.add(8); + s = dfa.next(s, i); + } + if (named && s == s0) return true; + at->gen = P.dfa_gen; + if (s < 0) { + at->id = -1; + out->clear(); + return false; + } + const SetDfa::St& S = dfa.st(s); + at->id = S.has_empty || !S.ttop.empty() ? -1 : s; + out->resize(S.stacks.size()); + for (size_t i = 0; i < S.stacks.size(); ++i) + (*out)[i].assign(S.stacks[i].begin(), S.stacks[i].end()); + return false; +} + int plan_fill(const MaskPlan& P, const GbnfStacks& stacks, PartialUtf8 partial, bool allow_eog, uint32_t* bitmask, int64_t n_words) { std::lock_guard lk(P.mu); std::fill(bitmask, bitmask + n_words, 0u); OpWork work; - /* The automaton is a memo, so past its bound it is dropped and rebuilt rather than refused: - * every state in it can be rediscovered, and a grammar whose stacks deepen with every token - * would otherwise hold a new state per token for as long as it is cached. */ - if (!P.dfa || P.dfa->elems() > kMaxDfaElems) { - if (P.dfa) - RAD_DEBUG("gbnf: the stack-set automaton holds %zu states, %zu stack elements; " - "rebuilding it", P.dfa->n_states(), P.dfa->elems()); - P.dfa = std::make_unique(P.rules); - } - SetDfa& dfa = *P.dfa; - dfa.begin(&work); + SetDfa& dfa = plan_dfa(P, work); if (allow_eog) for (int32_t id : P.vx->eog) set_bit(bitmask, id); diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index b66c8c5d..cce73246 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -141,6 +141,12 @@ struct IPrefixCache { virtual Restore restore(const Request&) { return Restore::Done; } /* A step's admissions begin: what the last step's lookups handed out has been read. */ virtual void begin_step() {} + /* KEEP THIS WAITING REQUEST'S CHAIN WHERE IT IS until release(). Called when an admission is + * refused after restore(): the request gives its hit back, and without the hold the chain it + * just had restored would leave VRAM again before the next attempt restores it once more. */ + virtual void hold(const Request&) {} + /* The request is gone -- finished, failed or cancelled -- and holds nothing any more. */ + virtual void release(const Request&) {} virtual CacheHit lookup(const Request& r, std::vector>* blocks_out) const = 0; @@ -159,6 +165,11 @@ struct IPrefixCache { * blocks no live sequence needs, so this is what the scheduler tries BEFORE preempting a * running request: a cached prefix is a saving, a running request is work already done. */ virtual int64_t evict(int64_t n_entries) = 0; + /* FREE UP TO `n_blocks` FOR THE RESERVE, and nothing a later turn needs. Unlike evict(), which + * answers a shortfall that cannot wait, this passes over an entry a live sequence still holds + * (releasing it frees no block) and one whose only copy is in VRAM (it is the next turn's + * context). Returns how many blocks went back to the pool. */ + virtual int64_t trim(int64_t n_blocks) = 0; /* FORGET EVERYTHING, wherever it is. Not a loop over evict(): with idle tiers an eviction moves * an entry whose host copy has landed off the card and keeps it, so a reset built out of @@ -206,8 +217,9 @@ struct IPrefixCache { /* The state that reservation named is now IN its slot. A reservation is made when the chunk is * PLANNED and the state exists only after the step that computes it, so a lookup in between * would adopt a slot holding the previous tenant's history. Until this is called, the - * reservation is a promise and lookup will not offer it. */ - virtual void commit_checkpoint(const Request& r, int64_t pos) = 0; + * reservation is a promise and lookup will not offer it. `resume`: the deepest checkpoint this + * prompt gets, the one its next turn resumes from (Scheduler::last_checkpoint). */ + virtual void commit_checkpoint(const Request& r, int64_t pos, bool resume) = 0; }; /* ------------------------------------------------------------------ block geometry */ @@ -335,6 +347,11 @@ struct PCBinding final : IPrefixCache { return restore_fn ? restore_fn(r) : Restore::Done; } void begin_step() override { m->begin_step(); } + void hold(const Request& r) override { + media_keys(r, &mm_); + m->hold(r.id, r.prompt, mm_); + } + void release(const Request& r) override { m->release(r.id); } const std::vector& cached_groups() const override { return m->cached_groups(); } /* prompt ++ output, for the same reason reserve_checkpoint chains both: the next turn of a @@ -352,7 +369,35 @@ struct PCBinding final : IPrefixCache { media_keys(r, &mm_); return m->insert(r.id, toks, mm_, blocks, n_tokens); } - int64_t evict(int64_t n) override { return m->evict_lru(n); } + /* Installed by the engine when the idle tiers are on: lands every host copy that is waiting, + * now, and says whether any landed. Called on the step thread under the scheduler's lock. */ + std::function flush_fn; + uint64_t lost_warned_ns_ = 0; + /* PRESSURE TAKES WHAT CAN LEAVE VRAM AND STAY, FIRST. An entry whose host copy has landed is + * dropped and kept (trim); a copy still on its way is landed and that entry dropped too; only + * what the tiers then still cannot take -- an arena with no room and a disk that has not caught + * up, or no tiers at all -- is erased, and an erase with the tiers on is said, because it is + * a conversation a later turn will prefill again. */ + int64_t evict(int64_t n) override { + int64_t k = m->trim(n); + if (k < n && flush_fn && flush_fn()) k += m->trim(n - k); + if (k >= n) return k; + const int64_t before = m->stats().evictions; + k += m->evict_lru(n - k); + const int64_t lost = m->stats().evictions - before; + if (lost > 0 && flush_fn) { + const uint64_t now = rad_mono_ns(); + if (now - lost_warned_ns_ >= 60ull * 1000000000ull) { + lost_warned_ns_ = now; + RAD_WARN("prefix cache: %lld entries erased with no copy off the card -- the host " + "tier had no room for them in time (--prefix-cache-host-mib, and the disk " + "behind it); radiance:prefix_cache_evictions_total counts every one", + (long long)lost); + } + } + return k; + } + int64_t trim(int64_t n) override { return m->trim(n); } int64_t reset() override { const int64_t n = m->size(); m->clear(); @@ -378,8 +423,8 @@ struct PCBinding final : IPrefixCache { return m->reserve_checkpoint(r.id, pos, prefix_hash(r, pos), slot_out); } - void commit_checkpoint(const Request& r, int64_t pos) override { - m->commit_checkpoint(prefix_hash(r, pos)); + void commit_checkpoint(const Request& r, int64_t pos, bool resume) override { + m->commit_checkpoint(prefix_hash(r, pos), resume); } private: diff --git a/core/sched/metrics.h b/core/sched/metrics.h index 4e31f644..3bc1d1b5 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -75,6 +75,9 @@ struct SchedMetrics { /* Tokens one block covers, 0 for a stateful group. A pool measured in blocks cannot be * compared with a request measured in tokens, and every reader wants that comparison. */ int64_t block_tokens = 0; + /* A WINDOWED GROUP recycles its blocks below the window, so its carve says how far back a + * sequence keeps context and nothing about how much context fits. */ + bool window = false; /* AND THE SAME GROUP IN BYTES, which is the measure that survives being added to the next * group's. Neither blocks nor tokens does: a stateful group has no token axis, and two * paged groups share one, so a token of context takes a slot in both and summing them diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index b798d8d0..b10065a7 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -280,7 +280,16 @@ static server::Finish finish_of(ReqState st, const std::string& reason) { * So a reserve is kept free. It is a fraction of the pool rather than a token count because the * thing being protected is the ability to admit ANY sequence, and how big that is depends on the * deployment. Trimming happens after a publish, off the step path, where the blocks were just - * added -- not during admission, where the cost lands on a request that did nothing wrong. */ + * added -- not during admission, where the cost lands on a request that did nothing wrong. + * + * THE RESERVE IS NOT ALWAYS THE CACHE'S TO MEET. Live sequences count against it too, and once they + * hold more than three quarters of the pool -- five or six agent sessions at 70K tokens each -- no + * amount of trimming reaches it. Evicting in LRU order until it did would take everything on the + * list: the entries running sequences share, which frees no block, and the conversation the + * request being closed has just published, before its host copy can land -- so every agent's next + * turn would re-prefill its whole context. The trim therefore asks the cache for the blocks it is + * short and nothing more, and the cache gives only what frees a block without losing a + * conversation (PrefixCache::trim). */ /* Drop every entry, in VRAM or off it -- IPrefixCache::reset, because an eviction does not * mean "forgotten" for an entry the idle tiers hold a copy of. */ @@ -300,17 +309,12 @@ void Scheduler::trim_prefix_cache() { const int64_t total = kv_->total_blocks(g); if (total <= 0) return; const int64_t reserve = total / 4; /* a quarter of the pool stays free */ - for (int guard = 0; guard < 4096; ++guard) { - /* FREE AGAINST THE CARVE, not free_blocks(). On an elastic pool free_blocks() is bounded - * by the live mark, so a pool that has handed its unused top back reads as nearly full - * however little anything holds -- and this loop would then drain the whole cache to - * make room the pool can grow back into on demand. */ - if (total - kv_->held_blocks(g) >= reserve) return; - if (pc_->evict(256) <= 0) return; /* nothing left to give back */ - } - RAD_WARN("prefix cache: could not free %lld of %lld blocks in group %d after 4096 rounds; the " - "pool is held by live sequences rather than by the cache", - (long long)reserve, (long long)total, (int)g); + /* FREE AGAINST THE CARVE, not free_blocks(). On an elastic pool free_blocks() is bounded by + * the live mark, so a pool that has handed its unused top back reads as nearly full however + * little anything holds -- and the trim would then drain the whole cache to make room the pool + * can grow back into on demand. */ + const int64_t short_by = reserve - (total - kv_->held_blocks(g)); + if (short_by > 0) (void)pc_->trim(short_by); } void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free, @@ -341,6 +345,8 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool } } + if (cfg_.prefix_cache && pc_) pc_->release(*s.req); + if (defer_free) { if (!s.pending_free) ++n_deferred_; s.pending_free = true; @@ -665,7 +671,22 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg const int64_t I = geo_.checkpoint_interval; int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */ if (n_computed + want > next) want = next - n_computed; - if (n_computed + want == next && checkpoint_pos) *checkpoint_pos = next; + if (n_computed + want == next) { + if (checkpoint_pos) *checkpoint_pos = next; + } else if (n_computed + want == n_target) { + /* AND ONE AT THE TAIL OF THE PROMPT. The next turn of a conversation is this prompt + * with more on the end, and it resumes from the deepest snapshot under its hit -- on + * the interval alone that is up to an interval short of where this prompt ended, and + * every one of those tokens is prefilled again on every turn. The last quantum + * boundary is as far as a chunk may end short of the target, so the final chunk is + * split there and the remainder, under a quantum, runs as the next step's chunk + * (tail_checkpoint says where it is worth that step). */ + const int64_t tail = tail_checkpoint(n_target); + if (tail > n_computed) { + want = tail - n_computed; + if (checkpoint_pos) *checkpoint_pos = tail; + } + } } if (want < remaining) { @@ -688,6 +709,26 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg return want; } +/* THE DEEPEST CHECKPOINT A PROMPT OF `target` TOKENS GETS, asked of one at `pos`: no interval + * boundary is left before the target and no tail checkpoint will follow (plan_chunk's rules). It + * is the state the prompt's next turn resumes from. */ +bool Scheduler::last_checkpoint(int64_t pos, int64_t target) const { + if (!geo_.checkpoints()) return false; + const int64_t I = geo_.checkpoint_interval; + if ((pos / I + 1) * I <= target) return false; + return tail_checkpoint(target) <= pos; +} + +/* THE TAIL CHECKPOINT OF A PROMPT OF `target` TOKENS, or -1: its last quantum boundary, past the + * first interval -- a shorter prompt is cheap to prefill again -- and only where it buys a quarter + * of an interval or more over the interval checkpoint below it, which is worth the extra step. */ +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; + const int64_t tail = target / Q * Q; + return tail > I && tail - tail / I * I >= std::max(Q, I / 4) ? tail : -1; +} + /* ------------------------------------------------------------------ preemption */ void Scheduler::preempt_back() { int32_t slot = running_.back(); @@ -734,6 +775,13 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) { s.hit_owed = true; } + /* WHAT NO HIT CAN CHANGE IS ASKED FIRST: a free sequence and a budget that can take a chunk. + * A restore copies the whole context back, and an admission refused after it would give that + * hit back and copy it again on the next attempt. */ + if (s.card < 0 && free_cards_.empty()) return RAD_E_FULL; + if (budget < std::max(geo_.quantum, 1) && budget < s.seq_len() - r.n_computed) + return RAD_E_FULL; + if (r.n_computed == 0 && cfg_.prefix_cache) { /* BEFORE the lookup, because the lookup stops at the first block the tiers hold -- an * honest shorter hit, but a shorter one. This is where a cold session gets its @@ -770,9 +818,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) { /* Claim the cached blocks. Without this the hit is only an accounting entry: the sequence * would skip computing those tokens and then attend to blocks it does not own. adopt() - * takes a whole block multiple, which `reuse` is -- it is a multiple of the checkpoint - * interval, which geometry.h made a multiple of the quantum, which is a multiple of the - * block size. */ + * takes a whole block multiple, which `reuse` is -- a whole number of blocks, or a + * checkpoint position, which is on the interval or on a quantum boundary at a prompt's tail + * (plan_chunk), and geometry.h made both multiples of the block size. */ if (reuse > 0) { const std::vector& cg = pc_->cached_groups(); for (size_t i = 0; i < cg.size() && i < hit_blocks_.size(); ++i) { @@ -801,7 +849,17 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) { int rc = RAD_OK; if (want <= 0) rc = RAD_E_FULL; else if (s.card < 0 && free_cards_.empty()) rc = RAD_E_FULL; - else if (kv_->ensure(r.id, r.n_computed + want) < 0) rc = RAD_E_NOMEM; + else { + /* THE CACHE GIVES WAY TO A NEW REQUEST as it does to a running one: with nothing running, + * no other path would ever take blocks back from it, and the request would wait for good. */ + int rounds = 0; + while (kv_->ensure(r.id, r.n_computed + want) < 0) { + if (++rounds > 256 || !cfg_.prefix_cache || pc_->evict(256) <= 0) { + rc = RAD_E_NOMEM; + break; + } + } + } if (rc < 0) { /* A HIT THAT RESUMES FROM A SNAPSHOT IS NOT KEPT ACROSS A FAILED ATTEMPT. The slot is * named by id only, and until this request's first step restores from it nothing stops @@ -811,6 +869,8 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) { * a lookup; the attention-only hit of a model with no recurrent state holds only * refcounted blocks and is kept. */ if (s.ckpt_src >= 0) undo_hit(s); + /* AND WHAT THE RESTORE BROUGHT BACK STAYS for the next attempt (IPrefixCache::hold). */ + if (cfg_.prefix_cache) pc_->hold(r); return rc; } @@ -1413,8 +1473,10 @@ int Scheduler::commit(const StepResult& res) { * still holding the previous tenant's state. Stream ordering does the rest -- a later * restore is enqueued on the same stream behind this save, so validity does not have to * wait on the copy landing, only on it being issued. */ - if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && pc_) - pc_->commit_checkpoint(r, (int64_t)e.ctx_len + e.ckpt_tok + 1); + if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && pc_) { + const int64_t pos = (int64_t)e.ctx_len + e.ckpt_tok + 1; + pc_->commit_checkpoint(r, pos, last_checkpoint(pos, s.seq_len())); + } if (e.is_prefill) { r.n_computed += e.n_tokens; @@ -2172,6 +2234,7 @@ SchedMetrics Scheduler::metrics_locked() const { m.kv[i].blocks_free = fr; m.kv[i].utilisation = tot > 0 ? (float)(1.0 - (double)fr / (double)tot) : 0.0f; m.kv[i].block_tokens = kv_->block_tokens(i); + m.kv[i].window = gs[(size_t)i].decl.kind == RAD_KV_WINDOW; m.kv[i].bytes_total = kv_->pool_bytes(i); m.kv[i].bytes_used = kv_->pool_bytes_used(i); m.kv[i].bytes_carved = kv_->pool_bytes_carved(i); diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 9f59ada4..47c6aa0f 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -445,6 +445,9 @@ public: /* 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). */ + /* plan_chunk's checkpoint rules, asked after the fact (see the definitions). */ + bool last_checkpoint(int64_t pos, int64_t target) const; + int64_t tail_checkpoint(int64_t target) const; int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget, int64_t* checkpoint_pos) const; diff --git a/core/server/adapters.h b/core/server/adapters.h index 5be8b770..69745373 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -116,10 +116,11 @@ public: c.host_freed = s.host_freed; c.host_drops = s.host_drops; c.failures = s.failures; c.fetched = s.fetched; c.ck_fetched = s.ck_fetched; c.host_bytes = s.host_bytes; c.disk_bytes = s.disk_bytes; - c.ck_to_host = s.ck_to_host; c.ck_to_disk = s.ck_to_disk; c.ck_promoted = s.ck_promoted; - c.ck_drops = s.ck_drops; c.ck_starved = s.ck_starved; + c.ck_to_disk = s.ck_to_disk; c.ck_drops = s.ck_drops; + c.restores = s.restores; c.restore_ns = s.restore_ns; + c.flushes = s.flushes; c.flush_ns = s.flush_ns; c.ck_bytes = tiers_->ckpt_bytes(); - c.ck_host_slots = tiers_->ckpt_arena().capacity(); + c.ck_host_slots = tiers_->ckpt_slots(); c.ck_disk_slots = tiers_->ckpt_disk_slots(); c.host_on = tiers_->host_on(); c.disk_on = tiers_->disk_on(); @@ -150,7 +151,6 @@ public: o.on_disk = s.on_disk; o.moving = s.moving; o.snapshots = s.snapshots; - o.snap_device = s.snap_device; o.snap_host = s.snap_host; o.snap_disk = s.snap_disk; o.snap_bytes = s.snap_bytes; @@ -246,6 +246,9 @@ public: o.kv_bytes_total += m.kv[i].bytes_total; o.kv_bytes_used += m.kv[i].bytes_used; o.kv_bytes_carved += m.kv[i].bytes_carved; + if (m.kv[i].block_tokens <= 0 || m.kv[i].window) continue; + const int64_t t = m.kv[i].blocks_total * m.kv[i].block_tokens; + if (o.kv_tokens_max == 0 || t < o.kv_tokens_max) o.kv_tokens_max = t; } /* vLLM's gpu_prefix_cache_hit_rate is a single number and attention caching is what it @@ -432,9 +435,14 @@ public: m.reasoning = r.reasoning; m.tool_calls.reserve(r.calls.size()); for (const ReplyCall& c : r.calls) m.tool_calls.push_back({ std::string(), c.name, c.arguments }); + m.open_call = !r.calls.empty() && !r.calls.back().closed; return m; } + std::string content_with_open_call(std::string_view reply) const override { + return s_->content_with_open_call(reply); + } + private: void move_out(std::vector* out) { if (!out) return; diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index eae0d808..79abf0a9 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -53,7 +53,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { if (deps_.sched) deps_.sched->sessions(&v, &occ); int64_t dev = 0, host = 0, disk = 0, bytes = 0; - int64_t sdev = 0, shost = 0, sdisk = 0; + int64_t shost = 0, sdisk = 0; json a = json::array(); for (const SessionStat& s : v) { json e; @@ -69,17 +69,16 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { e["moving"] = s.moving; /* THE RECURRENT HALF. On a hybrid model a session's attention blocks are only part of * what it needs back; the rest is its linear-state snapshots, which are a different size - * of object in a different store. Counted where the BYTES are, so a snapshot that stayed - * on the device while its blocks went to disk shows as exactly that. */ + * of object in a different store. Counted where the BYTES are: in the store in host + * memory, or on disk alone. */ e["snapshots"] = s.snapshots; - e["snap_device"] = s.snap_device; e["snap_host"] = s.snap_host; e["snap_disk"] = s.snap_disk; e["snap_bytes"] = s.snap_bytes; e["resume_tokens"] = s.resume_tokens; a.push_back(std::move(e)); dev += s.on_device; host += s.on_host; disk += s.on_disk; - sdev += s.snap_device; shost += s.snap_host; sdisk += s.snap_disk; + shost += s.snap_host; sdisk += s.snap_disk; bytes += s.bytes; } o["sessions"] = std::move(a); @@ -88,7 +87,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { * a server carrying long agent transcripts by more than an order of magnitude. The field * names say so rather than pretending the sums are totals. */ o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host }, { "disk", disk } }; - o["snapshots"] = { { "device", sdev }, { "host", shost }, { "disk", sdisk } }; + o["snapshots"] = { { "host", shost }, { "disk", sdisk } }; o["bytes_sum_overlapping"] = bytes; const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{}; /* AND THE ONE FIGURE THAT IS NOT A SUM, because a view about what the conversations cost has @@ -109,15 +108,14 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { { "fetched", c.fetched } }; /* THE SNAPSHOT COUNTERS ARE NOT OPTIONAL ON A HYBRID MODEL, because a server that moves every * block it has and no snapshots at all looks identical in the block counters to one where - * tiering works -- and the difference is a full linear replay on every restored session. - * `starved` is the one to read when `to_host` stays at zero: it means the snapshot arena had - * no room, which --prefix-cache-host-mib fixes. */ - o["snapshots_moved"] = { { "to_host", c.ck_to_host }, { "to_disk", c.ck_to_disk }, - { "promoted", c.ck_promoted }, { "fetched", c.ck_fetched }, - { "drops", c.ck_drops }, - { "starved", c.ck_starved }, { "bytes_each", c.ck_bytes }, + * tiering works -- and the difference is a full linear replay on every restored session. */ + o["snapshots_moved"] = { { "to_disk", c.ck_to_disk }, { "fetched", c.ck_fetched }, + { "drops", c.ck_drops }, { "bytes_each", c.ck_bytes }, { "host_slots", c.ck_host_slots }, { "disk_slots", c.ck_disk_slots } }; + /* THE STEP THREAD'S TIME ON THE TIERS: every request waits through it. */ + o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 }, + { "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } }; /* AND WHETHER ANY OF IT IS BEING READ. Moving a snapshot and restoring it proves the bytes * travelled; this is the number that says a lookup then SERVED one. A hybrid server can move * snapshots all day and still replay from token zero if the checkpoint the restore put back @@ -170,6 +168,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) { o["kv_bytes_used"] = (double)m.kv_bytes_used; o["kv_bytes_total"] = (double)m.kv_bytes_total; o["kv_bytes_carved"] = (double)m.kv_bytes_carved; + o["kv_tokens_max"] = m.kv_tokens_max; o["prefix_hit_rate"] = m.prefix_hit_rate; /* The leading indicator beside the lagging one: past ~75% kv utilisation the cache * begins dropping prefixes the next turn wants, and the hit rate only falls once @@ -1484,6 +1483,10 @@ function meter(host, cls, title, idx, split) { const mKv = meter($("mem"), "meter", "KV cache", undefined, true); const mKvSub = el("div", "ksub"); mKv.wrap.appendChild(mKvSub); +/* AND HOW FAR IT CAN GROW: every block of the carve, the ones lent to the expert slab taken + back -- which a request that needs them does, the same step. */ +const mKvMax = el("div", "ksub"); +mKv.wrap.appendChild(mKvMax); const mPc = meter($("mem"), "meter", "Prefix hits"); /* `hot` is for a meter whose ceiling is a FAILURE -- KV utilisation near 100% preempts. A device * VRAM bar near 100% is the engine doing its job, so it passes false and stays neutral. */ @@ -1729,7 +1732,8 @@ function update(s, dt) { 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. */ $("m-kvdet").textContent = s.kv_bytes_total > 0 - ? "of " + hb(s.kv_bytes_total) + " · " + cnt3(s.kv_tokens_used) + " tok" + ? "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" : "") : ""; setMetric("accept", 100 * s.draft_accept, @@ -1769,6 +1773,10 @@ function update(s, dt) { 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" + : ""; 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 diff --git a/core/server/iface.h b/core/server/iface.h index d6d8ff39..03e9ecdb 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -67,6 +67,11 @@ struct SchedMetrics { int64_t kv_bytes_total = 0; /* What the pool was carved to address, which an elastic pool may not be holding. */ int64_t kv_bytes_carved = 0; + /* THE MOST CONTEXT THE CACHE CAN HOLD: every block of its carve, the ones lent to the expert + * slab taken back. `kv_bytes_carved` is the same figure in bytes. The paged groups share one + * token axis, so it is the smallest of theirs; a windowed group is left out, because its carve + * bounds how far back a sequence keeps context rather than how much fits. */ + int64_t kv_tokens_max = 0; double prefix_hit_rate = 0.0; /* 0..1 */ /* Cumulative prefix-cache evictions. `prefix_hit_rate` falls only AFTER a prefix that @@ -157,7 +162,7 @@ struct SessionStat { * back and re-run every recurrent layer over its whole transcript -- which the hit rate will * report as a hit. Zero everywhere on a model that has no recurrent state. */ int64_t snapshots = 0; - int64_t snap_device = 0, snap_host = 0, snap_disk = 0; + int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */ int64_t snap_bytes = 0; /* The prefix a return skips: the deepest snapshot's position (IdleTiers::SessionInfo). */ int64_t resume_tokens = 0; @@ -264,11 +269,12 @@ public: int64_t fetched = 0, ck_fetched = 0; int64_t host_bytes = 0, disk_bytes = 0; /* THE LINEAR HALF, MOVED. Separate counters because a hybrid server can move every block - * it has and no snapshots at all -- the arena too small, the device slots contended -- - * and no block counter can tell that apart from tiering working. */ - int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0; + * it has and no snapshots at all, and no block counter can tell that apart from tiering + * working. `ck_drops` is snapshots whose only copy was lost. */ + int64_t ck_to_disk = 0, ck_drops = 0; int64_t ck_bytes = 0; /* one snapshot; 0 on a model with no recurrent state */ - int64_t ck_host_slots = 0, ck_disk_slots = 0; + int64_t ck_host_slots = 0, ck_disk_slots = 0; /* the store's; the disk store's */ + int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0; /* IdleTiers::Stats */ /* WHETHER ANYTHING CAN MOVE AT ALL, which no counter above can answer: a tier that is on * and has had nothing to do reads the same as one that was never given a size, and the * two call for opposite responses from whoever is looking. */ @@ -430,6 +436,8 @@ struct ParsedMessage { std::string content; std::string reasoning; /* "" unless the template supports reasoning */ std::vector tool_calls; + /* The reply ended inside its last call: that call never closed, and is no call to run. */ + bool open_call = false; }; /* One increment of a reply that is being read as it is generated. What has been delivered is @@ -458,6 +466,10 @@ public: virtual void finish(std::vector* out) = 0; /* The whole reply, once finish() has run. */ virtual ParsedMessage message() const = 0; + /* Once finish() has run: the content with an open last call (ParsedMessage::open_call) read + * as the text it was written as -- the content before the call, then the call's own bytes + * from `reply`, the whole text fed. The content alone when no call is open. */ + virtual std::string content_with_open_call(std::string_view reply) const = 0; }; /* A request's reply format. Each choice opens its own reader, and a request that sent no tools diff --git a/core/server/json_partial.cpp b/core/server/json_partial.cpp index 1b26b5c5..d4cdefda 100644 --- a/core/server/json_partial.cpp +++ b/core/server/json_partial.cpp @@ -174,5 +174,63 @@ size_t json_stable_prefix(std::string_view s) { return n; } +bool json_quote_append(std::string& out, std::string_view s) { + static const char kHex[] = "0123456789abcdef"; + const size_t mark = out.size(); + out.reserve(mark + s.size() + 2); + out.push_back('"'); + const unsigned char* p = (const unsigned char*)s.data(); + const unsigned char* e = p + s.size(); + const unsigned char* run = p; /* [run, p) is verified and goes out as it is */ + while (p < e) { + const unsigned char c = *p; + if (c >= 0x80) { + /* Length, and the range the SECOND byte is restricted to, which is what rejects + * overlong forms, surrogates and anything past U+10FFFF without decoding. */ + size_t len; + unsigned char lo = 0x80, hi = 0xBF; + if (c >= 0xC2 && c <= 0xDF) len = 2; + else if (c == 0xE0) { len = 3; lo = 0xA0; } + else if (c >= 0xE1 && c <= 0xEC) len = 3; + else if (c == 0xED) { len = 3; hi = 0x9F; } + else if (c >= 0xEE && c <= 0xEF) len = 3; + else if (c == 0xF0) { len = 4; lo = 0x90; } + else if (c >= 0xF1 && c <= 0xF3) len = 4; + else if (c == 0xF4) { len = 4; hi = 0x8F; } + else len = 0; + bool ok = len != 0 && (size_t)(e - p) >= len && p[1] >= lo && p[1] <= hi; + for (size_t k = 2; ok && k < len; ++k) ok = p[k] >= 0x80 && p[k] <= 0xBF; + if (!ok) { + out.resize(mark); + return false; + } + p += len; + continue; + } + if (c >= 0x20 && c != '"' && c != '\\') { + ++p; + continue; + } + out.append((const char*)run, (size_t)(p - run)); + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\t': out += "\\t"; break; + case '\n': out += "\\n"; break; + case '\f': out += "\\f"; break; + case '\r': out += "\\r"; break; + default: { + const char u[6] = { '\\', 'u', '0', '0', kHex[c >> 4], kHex[c & 15] }; + out.append(u, 6); + } + } + run = ++p; + } + out.append((const char*)run, (size_t)(p - run)); + out.push_back('"'); + return true; +} + } /* namespace server */ } /* namespace rad */ diff --git a/core/server/json_partial.h b/core/server/json_partial.h index 909e709e..cdfcbdbe 100644 --- a/core/server/json_partial.h +++ b/core/server/json_partial.h @@ -12,11 +12,15 @@ * boundary: cutting a multi-byte code point in half turns one delta into mojibake and the * next into a decode error. * + * And one way to write it: `json_quote_append`, a string literal exactly as nlohmann writes one, + * for the chunks that carry a delta. + * * This is a scanner, not a parser: it allocates nothing and builds no DOM. */ #pragma once #include +#include #include namespace rad { @@ -36,5 +40,15 @@ size_t utf8_trunc(std::string_view s); * escape, and the class of bug that produces is unbisectable from the server side. */ size_t json_stable_prefix(std::string_view s); +/* Append `s` to `out` as a JSON string literal, quotes included, byte for byte as nlohmann's + * dump() writes one: `\b \t \n \f \r \" \\` as two characters, every other control character + * as `\u00xx` in lowercase hex, and everything else -- DEL and non-ASCII included -- as itself. + * Returns false, with `out` as it was, when `s` is not well-formed UTF-8 (overlong forms, + * surrogates and code points past U+10FFFF included), which nlohmann refuses rather than writes. + * + * A streamed chunk is written with this around a fixed frame instead of through a DOM: building + * and dumping a tree per token cost more than every other part of the token's host work. */ +bool json_quote_append(std::string& out, std::string_view s); + } /* namespace server */ } /* namespace rad */ diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp index 26d86f92..e4171b9f 100644 --- a/core/server/metrics.cpp +++ b/core/server/metrics.cpp @@ -130,6 +130,8 @@ void Metrics::sample(const SchedMetrics& m) { g_waiting_.set((double)m.waiting); g_preempted_.set((double)m.preempted); g_kv_util_.set(m.kv_util); + g_kv_max_tokens_.set((double)m.kv_tokens_max); + g_kv_max_bytes_.set((double)m.kv_bytes_carved); g_prefix_hit_.set(m.prefix_hit_rate); g_prefill_tps_.set(m.prefill_tps); g_decode_tps_.set(m.decode_tps); @@ -239,6 +241,12 @@ std::string Metrics::render() const { "GPU KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get()); w.gauge("vllm:kv_cache_usage_perc", "KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get()); + w.gauge("radiance:kv_cache_max_tokens", + "Tokens of context the KV cache holds with every block it lends the experts taken " + "back.", L, g_kv_max_tokens_.get()); + w.gauge("radiance:kv_cache_max_bytes", + "VRAM the KV cache holds with every block it lends the experts taken back, one card.", + L, g_kv_max_bytes_.get()); w.gauge("vllm:gpu_prefix_cache_hit_rate", "GPU prefix cache block hit rate.", L, g_prefix_hit_.get()); diff --git a/core/server/metrics.h b/core/server/metrics.h index 404dbf5b..b15e20aa 100644 --- a/core/server/metrics.h +++ b/core/server/metrics.h @@ -112,6 +112,7 @@ private: std::string labels_; /* {model_name="...",engine="0"} */ Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_; + Gauge g_kv_max_tokens_, g_kv_max_bytes_; Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_; Gauge queue_depth_; /* The per-position draft hazard, kept as plain gauges because that is what it is: a diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 083c42b7..43b8b0e7 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -1962,6 +1962,27 @@ std::string ChatDeltaStream::chunk(json delta, const char* finish_reason, const return sse_event(o.dump()); } +void ChatDeltaStream::delta_open(std::string& out) { + /* Built from nlohmann's own serialisation of each field, on first use rather than in the + * constructor, so a field nlohmann refuses throws where chunk() would have. */ + if (head_.empty()) + head_ = "data: {\"id\":" + json(id_).dump() + + ",\"object\":\"chat.completion.chunk\",\"created\":" + json(created_).dump() + + ",\"model\":" + json(model_).dump() + ",\"choices\":[{\"index\":" + + json(index_).dump() + ",\"delta\":"; + out += head_; +} + +void ChatDeltaStream::delta_close(std::string& out) const { + out += ",\"finish_reason\":null}]}\n\n"; +} + +/* Text that is not well-formed UTF-8 goes to nlohmann, which refuses it with the exception the + * tree in chunk() raises for it. */ +void ChatDeltaStream::quote(std::string& out, std::string_view s) { + if (!json_quote_append(out, s)) out += json(std::string(s)).dump(); +} + std::string ChatDeltaStream::first_chunk() { json d; d["role"] = "assistant"; @@ -1976,49 +1997,53 @@ std::string ChatDeltaStream::first_chunk() { std::string ChatDeltaStream::emit(const std::vector& ev) { std::string out; for (const ReplyDelta& d : ev) { - json delta; switch (d.kind) { case ReplyDelta::Reasoning: if (d.text.empty()) continue; last_.reasoning += d.text; - delta["reasoning_content"] = d.text; + delta_open(out); + out += "{\"reasoning_content\":"; + quote(out, d.text); + out += '}'; break; case ReplyDelta::Content: if (d.text.empty()) continue; last_.content += d.text; - delta["content"] = d.text; + delta_open(out); + out += "{\"content\":"; + quote(out, d.text); + out += '}'; break; case ReplyDelta::CallBegin: { ToolCall tc; tc.id = random_id("call_"); tc.name = d.text; - last_.tool_calls.push_back(tc); - json f; - f["name"] = tc.name; - f["arguments"] = ""; - json e; - e["index"] = (int64_t)d.call; - e["id"] = tc.id; - e["type"] = "function"; - e["function"] = std::move(f); - delta["tool_calls"] = json::array({e}); + delta_open(out); + out += "{\"tool_calls\":[{\"index\":"; + out += std::to_string((int64_t)d.call); + out += ",\"id\":"; + quote(out, tc.id); + out += ",\"type\":\"function\",\"function\":{\"name\":"; + quote(out, tc.name); + out += ",\"arguments\":\"\"}}]}"; + last_.tool_calls.push_back(std::move(tc)); break; } case ReplyDelta::CallArgs: { if (d.text.empty() || d.call >= last_.tool_calls.size()) continue; last_.tool_calls[d.call].arguments += d.text; - json f; - f["arguments"] = d.text; - json e; - e["index"] = (int64_t)d.call; - e["function"] = std::move(f); - delta["tool_calls"] = json::array({e}); + delta_open(out); + out += "{\"tool_calls\":[{\"index\":"; + out += std::to_string((int64_t)d.call); + out += ",\"function\":{\"arguments\":"; + quote(out, d.text); + out += "}}]}"; break; } case ReplyDelta::CallEnd: continue; } - out += chunk(std::move(delta), nullptr); + delta_close(out); } return out; } @@ -2030,9 +2055,11 @@ std::string ChatDeltaStream::push(std::string_view appended, bool is_final) { /* Nothing to parse: the text is the answer, as it arrives. */ if (!appended.empty()) { last_.content.append(appended); - json d; - d["content"] = std::string(appended); - out = chunk(std::move(d), nullptr); + delta_open(out); + out += "{\"content\":"; + quote(out, appended); + out += '}'; + delta_close(out); } finished_ = is_final; return out; @@ -2053,14 +2080,19 @@ std::string ChatDeltaStream::push(std::string_view appended, bool is_final) { return out; } +bool calls_complete(const ParsedMessage& m) { + if (m.tool_calls.empty() || m.open_call) return false; + for (const auto& tc : m.tool_calls) + if (tc.name.empty() || !json_complete(tc.arguments)) return false; + return true; +} + Finish ChatDeltaStream::adjusted_finish(Finish f) const { if (f != Finish::Stop && f != Finish::StopString) return f; - if (last_.tool_calls.empty()) return f; - /* Only claim tool_calls if every call's arguments actually parse. A truncated arguments - * object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h). */ - for (const auto& tc : last_.tool_calls) - if (tc.name.empty() || !json_complete(tc.arguments)) return f; - return Finish::ToolCalls; + /* Only claim tool_calls if every call closed and its arguments parse. A truncated arguments + * object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h). + * The deltas of an open call have gone out already; the finish reason says not to run it. */ + return calls_complete(last_) ? Finish::ToolCalls : f; } std::string ChatDeltaStream::final_chunk(Finish f, const TimingsOut& t) { diff --git a/core/server/oai.h b/core/server/oai.h index 498d6ab4..2441d9fa 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -290,6 +290,11 @@ std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u, /* The `timings` object, for a stream's final chunks. */ json timings_json(const TimingsOut& t); +/* Whether a parsed reply's calls are all calls a client can run: none left open, each named, + * each one's arguments one JSON value (json_partial.h). A reply is answered `tool_calls` by this + * alone, streamed or not. */ +bool calls_complete(const ParsedMessage& m); + /* ================================================================== streaming * * One of these per choice. It feeds the generated text to the choice's reply reader as it grows @@ -323,6 +328,14 @@ private: std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr); std::string emit(const std::vector& ev); + /* A delta's chunk is written, not built: the frame around the delta object is the same in + * every one, so it is serialised once, and the delta between is written with + * json_quote_append. The bytes are the ones chunk() writes for the same delta. */ + void delta_open(std::string& out); + void delta_close(std::string& out) const; + static void quote(std::string& out, std::string_view s); + std::string head_; /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */ + std::unique_ptr reader_; std::string id_, model_; int64_t created_; diff --git a/core/server/server.cpp b/core/server/server.cpp index fdc11901..44cd8705 100644 --- a/core/server/server.cpp +++ b/core/server/server.cpp @@ -644,17 +644,20 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) rd->feed(g.text, nullptr); rd->finish(nullptr); c.msg = rd->message(); - /* Only claim a tool call when the arguments actually parse (json_partial.h). */ - bool complete = r.parse_tools && !c.msg.tool_calls.empty(); - for (const auto& tc : c.msg.tool_calls) - if (tc.name.empty() || !json_complete(tc.arguments)) complete = false; + /* Only claim a tool call when every call closed and its arguments parse + * (json_partial.h) -- the streaming path's rule (calls_complete). */ + const bool complete = r.parse_tools && calls_complete(c.msg); if (complete && (c.finish == Finish::Stop || c.finish == Finish::StopString)) c.finish = Finish::ToolCalls; - else if (!c.msg.tool_calls.empty() && !complete) { - /* A half-finished call is content, not a call. The client gets what the model - * actually produced instead of a tool invocation with truncated arguments. */ - c.msg.tool_calls.clear(); - c.msg.content = g.text; + if (c.msg.open_call) { + /* A half-finished call is content, not a call: the client gets what the model + * wrote instead of a tool invocation with truncated arguments. Only that call + * -- the reply ended inside it, so it is the last -- and only its own text: + * the reasoning stays reasoning, and the calls before it, which closed, stay + * calls, as the stream announced them. The finish reason is the stream's. */ + c.msg.content = rd->content_with_open_call(g.text); + c.msg.tool_calls.pop_back(); + c.msg.open_call = false; } } else { c.msg.content = g.text; diff --git a/core/text/chatfmt.h b/core/text/chatfmt.h index 7c8b59c5..2ac85050 100644 --- a/core/text/chatfmt.h +++ b/core/text/chatfmt.h @@ -105,7 +105,8 @@ struct ChatFormat { ChatValue string_value = ChatValue::Cdata; /* a string-typed argument: Raw or Cdata */ ChatValue other_value = ChatValue::Json; /* any other type: Json */ /* One newline at each end of a value is punctuation: the template writes the value on its own - * lines, and exactly the first and last newline belong to the tags. */ + * lines, and exactly the first and last newline belong to the tags. A tag that ends with its + * newline (Qwen's `>\n`) has written the first one already, and the value starts after it. */ bool value_newlines = true; /* The literal words that start constrained decoding of a call. Empty means no lazy grammar: diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp index e2b2c9b9..ae2f9803 100644 --- a/core/text/chatparse.cpp +++ b/core/text/chatparse.cpp @@ -135,7 +135,12 @@ private: * * no whitespace before the value, any whitespace after it and inside it; * * a number may not be followed by a character that could have continued it -- `01`, `1.`, * `1-` are not numbers -- while `true` and `null` may be followed by anything; - * * a string may hold raw control characters, and any escape but the JSON ones fails it. + * * a raw control character fails a string, as the schema's string rule refuses one and JSON + * has none: a client's JSON parser rejects a raw newline in a string. Any escape but the + * JSON ones fails it too. + * + * A value accepted here is still checked whole by a JSON parser before it is written as JSON + * (json_value_done): the grammar admits a few spellings a client cannot read. * * push() answers More while the bytes are still a JSON value or its trailing whitespace, Fail at * the first byte that cannot be, and Done at the first byte after a complete value -- which is @@ -163,6 +168,7 @@ public: } if (c == '"') { st_ = key_ ? KeyAfter : After; return More; } if (c == '\\') { st_ = StrEsc; return More; } + if (c < 0x20) return Fail; if (c < 0x80) return More; if (!(c & 0x40)) return Fail; if (!(c & 0x20)) { need_ = 1; return More; } @@ -410,8 +416,22 @@ std::string_view trim_trailing_ws(std::string_view v) { * * The bytes of one value as the delimiters bound it, turned into its JSON encoding in the * arguments object. Two encodings: a STRING (quoted, escaped) and RAW JSON text, which is either - * a value that parsed as JSON or a non-string argument that did not and is passed through -- - * with a Python-style container's single quotes normalised to double ones. + * a value that parsed as JSON or a non-string argument that did not. + * + * A NON-STRING ARGUMENT THAT DID NOT PARSE IS MADE JSON, never passed through: the arguments + * object is the one thing a client parses, and a single bare token in it makes the whole call + * unreadable -- the server then cannot report it as a call at all. The grammar admits text for a + * typed argument, and what these models write there is Python: `True`, `False`, `None`, and + * single-quoted containers. A scalar is held while it could still be a Python literal -- `True` + * as true, `False`, `None` as null -- or a JSON number or literal, up to kScalar bytes, and is + * then written as that; anything else, or anything longer, streams as a JSON string of its text. + * An empty one is null. A CONTAINER -- its first byte after at most a few blanks is `[` or `{` -- + * is held whole, because whether it is JSON once its quotes are normalised to double ones and its + * Python literals to JSON's is known only at its end: a trailing comma, a bare word, an escape + * JSON has not or a missing bracket each leave it no JSON, and then it is a JSON string of its + * text. A value the reply was cut off inside is written as it arrived: it has no end to read it + * to, and the call it is in is not complete. A value the JSON reader ACCEPTED (json_value_done) + * is written as it is. * * The transforms touch only the ends of a value -- one newline at each end, the CDATA opener and * closer -- so the middle streams straight through and only a short head and tail are held: the @@ -421,12 +441,17 @@ public: enum Mode : uint8_t { String, Raw }; static constexpr size_t kHead = 16; /* a newline pair and the CDATA opener, and the tail */ static constexpr size_t kTail = 5; /* a newline pair and the CDATA closer */ + /* The longest scalar held while it could still be a literal or a number: a few blanks and + * a 64-bit integer, or a double in its shortest round-trip spelling. */ + static constexpr size_t kScalar = 28; - void begin(Mode m, bool cdata, bool newlines, std::string& out) { - mode_ = m; cdata_ = cdata; newlines_ = newlines; + /* `lead`, `trail`: a newline at that end is punctuation. `json`: the value already parsed as + * JSON, so a Raw scalar is written as it is. */ + void begin(Mode m, bool cdata, bool lead, bool trail, std::string& out, bool json = false) { + mode_ = m; cdata_ = cdata; lead_ = lead; trail_ = trail; json_ = json; str_ = false; buf_.clear(); head_ = false; opened_ = false; - raw_started_ = false; container_ = false; - in_single_ = in_double_ = bs_ = false; + container_ = false; + scalar_.clear(); cont_.clear(); if (mode_ == String) out += '"'; } @@ -436,7 +461,7 @@ public: if (buf_.size() < kHead) return; std::string_view v(buf_); size_t drop = 0; - if (newlines_) drop = v.size() - strip_leading_newline(v).size(); + if (lead_) drop = v.size() - strip_leading_newline(v).size(); if (cdata_ && v.compare(drop, kCdOpen.size(), kCdOpen) == 0) { opened_ = true; drop += kCdOpen.size(); @@ -454,10 +479,11 @@ public: void finish(bool partial, std::string& out) { std::string_view v(buf_); if (!head_) { - if (newlines_) v = strip_trailing_newline(strip_leading_newline(v)); + if (lead_) v = strip_leading_newline(v); + if (trail_) v = strip_trailing_newline(v); if (cdata_) unwrap_cdata(v, partial); } else { - if (newlines_) v = strip_trailing_newline(v); + if (trail_) v = strip_trailing_newline(v); if (opened_) { if (v.size() >= kCdClose.size() && v.compare(v.size() - kCdClose.size(), kCdClose.size(), kCdClose) == 0) { @@ -472,61 +498,164 @@ public: } } emit(v.data(), v.size(), out); - if (bs_) { out += '\\'; bs_ = false; } + if (mode_ == Raw && !json_) { + if (container_) container_out(partial, out); + else if (str_) { if (!partial) out += '"'; } + else if (partial) { out += scalar_; scalar_.clear(); } /* cut off: as it arrived */ + else scalar_out(out); + } buf_.clear(); } - size_t held() const { return buf_.size() + (bs_ ? 1 : 0); } + /* Bytes held while the value's ends are decided, and a scalar while it could be a literal. */ + size_t held() const { return buf_.size() + scalar_.size(); } + /* A container, held whole until its end. */ + size_t held_container() const { return cont_.size(); } private: void emit(const char* p, size_t n, std::string& out) { if (n == 0) return; if (mode_ == String) { json_escape_into(out, p, n); return; } - if (!raw_started_) { - raw_started_ = true; - container_ = p[0] == '[' || p[0] == '{'; - } - if (!container_) { out.append(p, n); return; } - for (size_t i = 0; i < n; ++i) normalise(p[i], out); - } - - /* Python-style quoting to JSON, one character at a time: a single-quoted string becomes a - * double-quoted one, with the quotes inside it re-escaped to match. A backslash is held until - * the character after it arrives, since the pair is read together. */ - void normalise(char c, std::string& out) { - if (bs_) { - bs_ = false; - if (in_single_) { - if (c == '\'') { out += '\''; return; } - if (c == '"') { out += "\\\""; return; } - out += '\\'; out += c; return; - } - if (in_double_) { out += '\\'; out += c; return; } - out += '\\'; - /* Outside a string the backslash stands alone and the next character is read - * normally. */ - } else if (c == '\\') { - bs_ = true; + if (json_) { out.append(p, n); return; } + if (str_) { json_escape_into(out, p, n); return; } + if (container_) { cont_.append(p, n); return; } + scalar_.append(p, n); + size_t ws = 0; + while (ws < scalar_.size() && is_ws((unsigned char)scalar_[ws])) ++ws; + if (ws <= 4 && ws < scalar_.size() && (scalar_[ws] == '[' || scalar_[ws] == '{')) { + container_ = true; + cont_.assign(scalar_, ws, std::string::npos); + scalar_.clear(); return; } - if (c == '"') { - if (in_single_) out += "\\\""; - else { in_double_ = !in_double_; out += '"'; } - } else if (c == '\'') { - if (in_double_) out += '\''; - else if (in_single_) { in_single_ = false; out += '"'; } - else { in_single_ = true; out += '"'; } - } else { - out += c; + if (scalar_.size() > kScalar || !scalar_prefix(scalar_)) { + out += '"'; + json_escape_into(out, scalar_.data(), scalar_.size()); + scalar_.clear(); + str_ = true; + } + } + + /* Could `v` still become a Python or JSON literal or a JSON number, after at most a few + * bytes of blanks on either side? */ + static bool scalar_prefix(std::string_view v) { + size_t ws = 0; + while (ws < v.size() && is_ws((unsigned char)v[ws])) ++ws; + if (ws > 4) return false; + v.remove_prefix(ws); + size_t tw = 0; + while (tw < v.size() && is_ws((unsigned char)v[v.size() - 1 - tw])) ++tw; + if (tw > 4) return false; + if (tw > 0 && tw == v.size()) return true; + v.remove_suffix(tw); + if (v.empty()) return true; + for (std::string_view l : { std::string_view("True"), std::string_view("False"), + std::string_view("None"), std::string_view("true"), + std::string_view("false"), std::string_view("null") }) + if (v.size() <= l.size() && l.compare(0, v.size(), v) == 0) return true; + return number_prefix(v); + } + + /* A prefix of -?(0|[1-9][0-9]*)(.[0-9]+)?([eE][+-]?[0-9]+)? */ + static bool number_prefix(std::string_view v) { + size_t i = 0; + if (i < v.size() && v[i] == '-') ++i; + if (i == v.size()) return true; + if (v[i] == '0') ++i; + else if (v[i] >= '1' && v[i] <= '9') while (i < v.size() && std::isdigit((unsigned char)v[i])) ++i; + else return false; + if (i < v.size() && v[i] == '.') { + ++i; + while (i < v.size() && std::isdigit((unsigned char)v[i])) ++i; + } + if (i < v.size() && (v[i] == 'e' || v[i] == 'E')) { + ++i; + if (i < v.size() && (v[i] == '+' || v[i] == '-')) ++i; + while (i < v.size() && std::isdigit((unsigned char)v[i])) ++i; + } + return i == v.size(); + } + + /* A Python literal is JSON's under another spelling; anything else is as written. */ + static const char* json_literal(std::string_view w) { + if (w == "True") return "true"; + if (w == "False") return "false"; + if (w == "None") return "null"; + return nullptr; + } + + void scalar_out(std::string& out) { + std::string_view v = trim_trailing_ws(scalar_); + while (!v.empty() && is_ws((unsigned char)v.front())) v.remove_prefix(1); + if (v.empty()) out += "null"; + else if (const char* lit = json_literal(v)) out += lit; + else if (nlohmann::json::accept(v)) out.append(v.data(), v.size()); + else out += json_quote(scalar_); + scalar_.clear(); + } + + /* The held container, normalised; JSON if that made it JSON, else a JSON string of its text. + * One the reply was cut off inside is written normalised as far as it arrived. */ + void container_out(bool partial, std::string& out) { + std::string j; + j.reserve(cont_.size() + 8); + normalise(cont_, j); + if (partial || nlohmann::json::accept(j)) out += j; + else out += json_quote(cont_); + cont_.clear(); + } + + /* Python-style quoting to JSON: a single-quoted string becomes a double-quoted one, with the + * quotes inside it re-escaped to match and its raw control characters escaped, and a bare + * Python literal outside every string is respelled as JSON's. Whatever is no JSON after that + * is left as written, for the JSON parser to refuse. */ + static void normalise(std::string_view v, std::string& out) { + bool in_single = false, in_double = false; + for (size_t i = 0; i < v.size(); ++i) { + const char c = v[i]; + if (in_single || in_double) { + if (c == '\\' && i + 1 < v.size()) { + const char d = v[++i]; + if (d == '\'') out += '\''; /* `\'` is a quote in either quoting */ + else if (in_single && d == '"') out += "\\\""; + else { out += '\\'; out += d; } + } else if (c == (in_single ? '\'' : '"')) { + in_single = in_double = false; + out += '"'; + } else if (c == '"') { + out += "\\\""; + } else if ((unsigned char)c < 0x20) { + /* A raw line break or tab inside a string, which JSON spells as an escape. */ + json_escape_into(out, &c, 1); + } else { + out += c; + } + continue; + } + if (std::isalnum((unsigned char)c) || c == '_') { + size_t e = i + 1; + while (e < v.size() && (std::isalnum((unsigned char)v[e]) || v[e] == '_')) ++e; + const std::string_view w = v.substr(i, e - i); + if (const char* lit = json_literal(w)) out += lit; + else out.append(w.data(), w.size()); + i = e - 1; + continue; + } + if (c == '\'') in_single = true; + else if (c == '"') in_double = true; + out += c == '\'' ? '"' : c; } } Mode mode_ = String; - bool cdata_ = true, newlines_ = true; + bool cdata_ = true, lead_ = true, trail_ = true; std::string buf_; bool head_ = false, opened_ = false; - bool raw_started_ = false, container_ = false; - bool in_single_ = false, in_double_ = false, bs_ = false; + bool container_ = false; + std::string scalar_; /* a scalar while it could still be a Python literal */ + std::string cont_; /* a container, held whole */ + bool json_ = false; /* the value parsed as JSON: written as it is */ + bool str_ = false; /* the scalar is no literal and streams as a JSON string */ }; /* ================================================================== the answer text @@ -562,19 +691,25 @@ public: /* The exact trim: trailing spaces and newlines, then the first terminator in the list that * ends what is left. */ void finish(std::string& full) { - while (!pend_.empty() && (pend_.back() == '\n' || pend_.back() == ' ')) pend_.pop_back(); - if (list_) - for (const std::string& t : *list_) - if (!t.empty() && pend_.size() >= t.size() && - pend_.compare(pend_.size() - t.size(), t.size(), t) == 0) { - pend_.erase(pend_.size() - t.size()); - break; - } + trim(pend_); full += pend_; pend_.clear(); } size_t held_space() const { return std::min(ws_, pend_.size()); } + /* What is held: the content after `full` so far, untrimmed. */ + const std::string& pending() const { return pend_; } + /* The same trim, on a whole text. */ + void trim(std::string& s) const { + while (!s.empty() && (s.back() == '\n' || s.back() == ' ')) s.pop_back(); + if (list_) + for (const std::string& t : *list_) + if (!t.empty() && s.size() >= t.size() && + s.compare(s.size() - t.size(), t.size(), t) == 0) { + s.erase(s.size() - t.size()); + break; + } + } size_t held_other() const { return pend_.size() - held_space(); } private: @@ -604,6 +739,9 @@ struct ReplyFormat::Impl { * model wrote it unconstrained, and its argument tags are read with the whitespace around * them optional -- as its name and its close are. */ std::string name_end_core, value_core; + /* call_close's core, when it can be told apart from what else may follow inside a call: a + * wrapped call whose own close is missing is ended by its wrapper's. */ + std::string cc_core; Dfa think, think_breaks, text, arg_name, value, junk, arg_name_loose, value_loose; size_t longest = 0; /* the longest delimiter */ }; @@ -651,7 +789,13 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr split_ws(f.arg_value_suffix, &m.value_core, &trail); m.arg_name_loose.build({ m.name_end_core }); m.value_loose.build({ m.value_core }); - m.junk.build({ f.arg_prefix, m.end_core }); + split_ws(f.call_close, &m.cc_core, &trail); + auto apart = [](const std::string& a, const std::string& b) { + return a.find(b) == std::string::npos && b.find(a) == std::string::npos; + }; + if (!apart(m.cc_core, f.arg_prefix) || !apart(m.cc_core, m.end_core)) m.cc_core.clear(); + if (m.cc_core.empty()) m.junk.build({ f.arg_prefix, m.end_core }); + else m.junk.build({ f.arg_prefix, m.end_core, m.cc_core }); } const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.call_open, &f.call_close, &f.name_prefix, &f.name_suffix, @@ -701,7 +845,7 @@ size_t ReplyParser::hold_bound() const { size_t term = 0; for (const std::string& t : impl_->terminators) term = std::max(term, t.size()); return impl_->fmt->impl().longest + std::max(term, kFenceOpen.size()) + ValueOut::kHead + 1 + - 3 * 3; + 3 * 3 + ValueOut::kScalar; } ReasoningMarkers ReplyParser::reasoning() const { @@ -740,6 +884,9 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse info.resolve_refs(params); std::vector optional; for (const auto& [pname, pschema] : properties.items()) { + /* An optional argument no value satisfies has no arm in the grammar, which reads + * it by the undeclared arm, as text (chatfmt.cpp); so does the parser. */ + if (!required.count(pname) && info.unsatisfiable(pschema)) continue; Param p; p.typed = F.f.other_value == ChatValue::Json && !info.resolves_to_string(pschema); t.has_props = true; @@ -919,9 +1066,16 @@ struct ReplyStream::Impl { size_t sent_r = 0, sent_c = 0, sent_a = 0; int cur = -1; /* the channel last published: 0 r, 1 c, 2 args */ - /* bytes to read again, ahead of the rest */ - struct Seg { const char* p; size_t n; }; + /* bytes to read again, ahead of the rest. Bytes read again are always the last ones read, + * so each segment knows where its first byte is in the stream: the generation prompt's tail, + * then the reply. */ + struct Seg { const char* p; size_t n; size_t at; }; std::vector stack; + const char* seg_p = nullptr; /* the segment being read */ + size_t seg_at = 0; /* and where its first byte is in the stream */ + size_t fed = 0; /* the bytes the stream has been given */ + size_t att_at = 0; /* where the opener being tried begins */ + size_t here(const char* p) const { return seg_at + (size_t)(p - seg_p); } std::deque owned; std::string refeed; @@ -1105,6 +1259,7 @@ struct ReplyStream::Impl { st = origin; ds = 0; hold.clear(); + lhold.clear(); if (origin == St::Think) think_out(att.data(), 1); else text_out(att.data(), 1); read_again(std::string_view(att).substr(1)); @@ -1120,6 +1275,9 @@ struct ReplyStream::Impl { 0, name.size() - F.ns_core.size())); ReplyCall c; c.name.assign(nm); + c.at = att_at >= P.tail.size() ? att_at - P.tail.size() : 0; + c.content_at = msg.content.size(); + c.content_held = content.pending(); msg.calls.push_back(std::move(c)); sent_a = 0; cur = -1; @@ -1161,6 +1319,16 @@ struct ReplyStream::Impl { else after_loose_call(); } + /* The wrapper's close inside a wrapped call, whose own close is missing: it ends the call + * and the wrapper both. Read leniently -- the grammar requires call_end first -- but as the + * close it is, or the next call's arguments would be read into this one. */ + void end_call_at_close() { + lenient(); + end_call(); + if (loose) after_loose_call(); + else st = St::AfterCall; + } + /* A loose call whose argument name runs into a tag was a call only as far as its arguments * before it: the call ends there, and the argument's opener and all after it are content. */ void end_loose_call_at_arg(bool closed_name) { @@ -1189,21 +1357,40 @@ struct ReplyStream::Impl { /* The argument name is complete. */ void begin_value() { - const std::string_view nm = trim_arg_name( + std::string_view nm = trim_arg_name( std::string_view(name).substr(0, name.size() - name_end().size())); + param = nullptr; + if (const Tool* t = cur_tool()) { + auto it = t->params.find(std::string(nm)); + const bool exact = nm.size() + name_end().size() == name.size(); + /* The grammar binds a declared name to its own arm by the raw spelling; a name that + * only trims to a declared one is read by the generic arm, as text. */ + if (it != t->params.end() && exact) { + param = &it->second; + } else if (it == t->params.end() && exact) { + /* A name that repeats its own tag's opening, ``: the + * grammar's undeclared arm takes it, and the call would reach the tool without + * the argument it names. Read as that declared argument, leniently. */ + const std::string_view rep = std::string_view(F.f.arg_prefix).substr(1); + std::string_view rest = nm; + while (!rep.empty() && rest.size() > rep.size() && + rest.compare(0, rep.size(), rep) == 0) + rest.remove_prefix(rep.size()); + if (rest.size() < nm.size()) { + auto jt = t->params.find(std::string(rest)); + if (jt != t->params.end()) { + lenient(); + nm = rest; + param = &jt->second; + } + } + } + } std::string key = argc > 0 ? "," : ""; key += json_quote(nm); key += ':'; args_out(key); ++argc; - param = nullptr; - if (const Tool* t = cur_tool()) { - auto it = t->params.find(std::string(nm)); - /* The grammar binds a declared name to its own arm by the raw spelling; a name that - * only trims to a declared one is read by the generic arm, as text. */ - if (it != t->params.end() && nm.size() + name_end().size() == name.size()) - param = &it->second; - } name.clear(); if (param && param->typed) { js.reset(); @@ -1222,9 +1409,21 @@ struct ReplyStream::Impl { /* A CDATA section is punctuation around any value the format lets carry one, typed or not. */ bool cdata() const { return F.f.string_value == ChatValue::Cdata; } + /* The newline that opens a value is punctuation unless the tag before it has written it + * already: Qwen's `\n` ends with the newline the template puts before the + * value, and a second one is the value's own. */ + bool lead_newline() const { + const std::string& ne = name_end(); + return F.f.value_newlines && (ne.empty() || ne.back() != '\n'); + } + + void begin_value_out(ValueOut::Mode m, bool json = false) { + val.begin(m, cdata(), lead_newline(), F.f.value_newlines, scratch, json); + } + void start_text_value(ValueOut::Mode m) { vmode = m; - val.begin(m, cdata(), F.f.value_newlines, scratch); + begin_value_out(m); flush_scratch(); ds = 0; hold.clear(); @@ -1232,9 +1431,19 @@ struct ReplyStream::Impl { } /* A JSON-typed value that parsed and then met its suffix: the value is the JSON text and the - * whitespace after it. */ + * whitespace after it. What a client's JSON parser takes is a little narrower than what + * JsonScan reads as the grammar's JSON -- a number past a double's range (`1e400`), an + * unpaired UTF-16 surrogate escape, a vertical tab or form feed after the value -- and such a + * value is read by the grammar's other arm, as text, so the arguments stay JSON. */ void json_value_done(std::string_view text) { - val.begin(ValueOut::Raw, cdata(), F.f.value_newlines, scratch); + if (!nlohmann::json::accept(text)) { + begin_value_out(ValueOut::Raw); + val.add(text.data(), text.size(), scratch); + val.finish(false, scratch); + flush_scratch(); + return; + } + begin_value_out(ValueOut::Raw, /*json=*/true); val.add(text.data(), text.size(), scratch); val.finish(false, scratch); flush_scratch(); @@ -1275,7 +1484,11 @@ struct ReplyStream::Impl { const Dfa& d = P.breaks ? F.think_breaks : F.think; p = scan(d, p, e, &hit, [this](const char* q, size_t n) { think_out(q, n); }); if (hit == 0) { trail = 0; st = St::ThinkCloseWs; } - else if (hit > 0) { att = d.pattern(hit); begin_attempt(St::Think); } + else if (hit > 0) { + att = d.pattern(hit); + att_at = here(p) - att.size(); + begin_attempt(St::Think); + } return p; } @@ -1291,7 +1504,10 @@ struct ReplyStream::Impl { return e; } p = scan(F.text, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); }); - if (hit >= 0) begin_text_attempt(hit); + if (hit >= 0) { + att_at = here(p) - F.openers[(size_t)hit].size(); + begin_text_attempt(hit); + } return p; case St::OpenCoTail: @@ -1422,9 +1638,12 @@ struct ReplyStream::Impl { const char c = *p; const std::string& ap = F.f.arg_prefix; const std::string& fc = F.end_core; + const std::string& cc = F.cc_core; const bool a_ok = lpos < ap.size() && ap[lpos] == c && ap.compare(0, lpos, lhold) == 0; const bool f_ok = lpos < fc.size() && fc[lpos] == c && fc.compare(0, lpos, lhold) == 0; - if (!a_ok && !f_ok) { + const bool c_ok = wrapped && lpos < cc.size() && cc[lpos] == c && + cc.compare(0, lpos, lhold) == 0; + if (!a_ok && !f_ok && !c_ok) { lenient(); st = St::Junk; ds = 0; @@ -1438,6 +1657,7 @@ struct ReplyStream::Impl { ++lpos; if (a_ok && lpos == ap.size()) { start_arg(); return p + 1; } if (f_ok && lpos == fc.size()) { finish_call_strictness(); end_core_done(); return p + 1; } + if (c_ok && lpos == cc.size()) { end_call_at_close(); return p + 1; } return p + 1; } @@ -1518,6 +1738,8 @@ struct ReplyStream::Impl { p = scan(F.junk, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); }); if (hit == 0) start_arg(); else if (hit == 1) end_core_done(); + else if (hit == 2 && wrapped) end_call_at_close(); + else if (hit == 2) text_out(F.cc_core.data(), F.cc_core.size()); return p; case St::AfterEnd: @@ -1673,20 +1895,25 @@ struct ReplyStream::Impl { /* ------------------------------------------------------------ driving */ - void run(std::string_view in) { - stack.push_back({ in.data(), in.size() }); + /* Read `in`, whose first byte is at `at` in the stream. */ + void run(std::string_view in, size_t at) { + stack.push_back({ in.data(), in.size(), at }); while (!stack.empty()) { Seg s = stack.back(); stack.pop_back(); + seg_p = s.p; + seg_at = s.at; const char* p = s.p; const char* e = s.p + s.n; while (p < e) { p = step(p, e); if (!refeed.empty()) { - if (p < e) stack.push_back({ p, (size_t)(e - p) }); + const size_t now = here(p); + if (p < e) stack.push_back({ p, (size_t)(e - p), now }); owned.push_back(std::move(refeed)); refeed.clear(); - stack.push_back({ owned.back().data(), owned.back().size() }); + const size_t n = owned.back().size(); + stack.push_back({ owned.back().data(), n, now >= n ? now - n : 0 }); break; } } @@ -1697,7 +1924,13 @@ struct ReplyStream::Impl { void feed_tail() { if (fed_tail) return; fed_tail = true; - if (!P.tail.empty()) run(P.tail); + if (!P.tail.empty()) run(P.tail, 0); + fed = P.tail.size(); + } + + void feed(std::string_view bytes) { + run(bytes, fed); + fed += bytes.size(); } /* Would the grammar still be waiting for more, rather than have failed, on what an opener @@ -1733,7 +1966,7 @@ struct ReplyStream::Impl { fail_attempt(); std::string again = std::move(refeed); refeed.clear(); - run(again); + run(again, fed >= again.size() ? fed - again.size() : 0); } switch (st) { case St::OpenWs: case St::OpenPrefix: case St::OpenName: case St::OpenTail: @@ -1757,7 +1990,7 @@ struct ReplyStream::Impl { flush_scratch(); break; case St::ValJson: - val.begin(ValueOut::Raw, cdata(), F.f.value_newlines, scratch); + begin_value_out(ValueOut::Raw); val.add(vheld.data(), vheld.size(), scratch); val.finish(true, scratch); flush_scratch(); @@ -1793,7 +2026,7 @@ void ReplyStream::feed(std::string_view bytes, std::vector* out) { if (m.finished) return; m.out = out; m.feed_tail(); - if (!bytes.empty()) m.run(bytes); + if (!bytes.empty()) m.feed(bytes); if (m.cur >= 0) m.publish(m.cur, false); m.out = nullptr; } @@ -1809,16 +2042,31 @@ void ReplyStream::finish(std::vector* out) { } const ReplyMessage& ReplyStream::message() const { return impl_->msg; } + +std::string ReplyStream::content_with_open_call(std::string_view reply) const { + const Impl& m = *impl_; + if (m.msg.calls.empty() || m.msg.calls.back().closed) return m.msg.content; + const ReplyCall& c = m.msg.calls.back(); + std::string s(m.msg.content, 0, std::min(c.content_at, m.msg.content.size())); + s += c.content_held; + if (c.at < reply.size()) s.append(reply.substr(c.at)); + m.content.trim(s); + return s; +} + bool ReplyStream::strict() const { return impl_->strict; } ReplyHeld ReplyStream::held() const { const Impl& m = *impl_; ReplyHeld h; - h.delimiter = m.hold.size() + m.lhold.size() + m.val.held() + m.content.held_other() + + /* A loose call's first argument name is read into lhold too, and is a tag name: its bytes + * are in `att` already, counted as structure. */ + const size_t lhold = m.st == St::OpenPeekArg ? 0 : m.lhold.size(); + h.delimiter = m.hold.size() + lhold + m.val.held() + m.content.held_other() + (m.msg.reasoning.size() - m.sent_r) + (m.msg.content.size() - m.sent_c) + (m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a); h.space = m.content.held_space() + m.think_pend.size(); - h.structure = m.att.size() + m.name.size() + m.vheld.size(); + h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container(); return h; } diff --git a/core/text/chatparse.h b/core/text/chatparse.h index 849706a5..4d820ea2 100644 --- a/core/text/chatparse.h +++ b/core/text/chatparse.h @@ -45,7 +45,9 @@ * * a tag's own name while it is being read, since a name is only a name once it is closed; * * a JSON-typed argument value until its closing delimiter: `30` and `30 seconds` differ from * their first byte (a number, or the string "30 seconds"), so the value is emitted whole once - * its type is known. A value that stops being JSON part-way is streamed as text from there. + * its type is known. A value that stops being JSON part-way is streamed as text from there, + * except a container (`[`, `{`), which is held to its end: only there is it known whether + * it is JSON once its Python quoting is normalised, or the JSON string of its text. * * Streaming emits in the reply's order; a call's arguments are streamed as they are parsed. */ #pragma once @@ -81,6 +83,12 @@ struct ReplyCall { std::string name; std::string arguments; /* JSON text, as the OpenAI API carries it */ bool closed = false; + /* Where the call's text begins in the reply, and the content up to it: `content_at` bytes + * of the message's content and the untrimmed whitespace held after them. What the content + * is when the call is read as text (ReplyStream::content_with_open_call). */ + size_t at = 0; + size_t content_at = 0; + std::string content_held; }; /* A reply, taken apart. After finish() it is the whole reply; before, what has been emitted. */ @@ -179,6 +187,11 @@ public: void finish(std::vector* out); const ReplyMessage& message() const; + /* After finish(): the content were the last call text, when the reply ended inside that call + * -- the content before it, then the call as `reply` (every byte fed) spells it, trimmed at + * the end as content is. A call that never closed cannot be reported as a call, and its text + * is what the model wrote. The message's content when the last call closed, or there is none. */ + std::string content_with_open_call(std::string_view reply) const; /* False once the reply left the format's grammar and was read by a recovery rule. */ bool strict() const; ReplyHeld held() const; diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp index 29b67ff8..84ba49d8 100644 --- a/core/text/tokenizer.cpp +++ b/core/text/tokenizer.cpp @@ -69,16 +69,28 @@ std::string byte_encode(std::string_view raw) { * user-defined token spelt in real text needs; it cannot be confused with a mapped one because * the mapped set is closed. */ std::string byte_decode(const std::string& enc) { + /* Unit by unit, a unit being what the lead byte says, cut short at the end. A unit is mapped + * iff it is exactly some byte's spelling in the alphabet -- one ASCII byte, or a two-byte + * sequence (lead C2..DF, a continuation byte) whose code point is below U+0144 -- so the + * code point table answers what a lookup of the unit's bytes in `from` would, without + * building a string per character. Anything else is passed through as its own bytes. */ const ByteLevelAlphabet& a = alphabet(); + const uint8_t* p = (const uint8_t*)enc.data(); + const size_t n = enc.size(); std::string out; - out.reserve(enc.size()); - for (size_t i = 0; i < enc.size(); ) { - const size_t n = std::min(unicode_len_utf8(enc[i]), enc.size() - i); - const std::string one = enc.substr(i, n); - auto it = a.from.find(one); - if (it != a.from.end()) out += (char)it->second; - else out += one; - i += n; + out.reserve(n); + for (size_t i = 0; i < n; ) { + const size_t len = std::min(unicode_len_utf8(enc[i]), n - i); + int b = -1; + if (len == 1 && p[i] < 0x80) { + b = a.byte_of_cpt[p[i]]; + } else if (len == 2 && p[i] >= 0xC2 && (p[i + 1] & 0xC0) == 0x80) { + const uint32_t c = ((uint32_t)(p[i] & 0x1F) << 6) | (p[i + 1] & 0x3F); + if (c < 0x144) b = a.byte_of_cpt[c]; + } + if (b >= 0) out += (char)b; + else out.append(enc, i, len); + i += len; } return out; } @@ -1568,14 +1580,15 @@ std::string utf8_sanitize(std::string_view s) { std::string Detokenizer::push(int32_t token) { if (!v_ || !v_->ready() || stopped_) return {}; - Tokenizer t; - /* Constructing a Tokenizer per push looks wasteful and is not: it holds a shared_ptr and - * nothing else, and piece() is a pure function of the vocab. Keeping one as a member would - * make Detokenizer non-copyable for no gain. */ - if (t.init(std::const_pointer_cast(std::const_pointer_cast(v_))) < 0) - return {}; - - std::string p = t.piece(token, render_special_ || preserved_.count(token) != 0); + /* One Tokenizer for the stream, set up on the first push: it holds the vocab's shared_ptr + * and nothing else, and piece() is a pure function of the vocab, so one built per push only + * added a reference-count round trip to every token. */ + if (!tok_ready_) { + if (tok_.init(v_) < 0) return {}; + tok_ready_ = true; + } + std::string p = tok_.piece(token, render_special_ || + (!preserved_.empty() && preserved_.count(token) != 0)); /* HuggingFace's decoders strip the leading space that Metaspace's prepend added. Only the * first piece of a stream can carry it, which is why this is a member flag and not a @@ -1613,9 +1626,10 @@ std::string Detokenizer::push(int32_t token) { const size_t cut = safe_prefix(); if (cut == 0) return {}; - std::string out = pending_.substr(0, cut); + /* Sanitised straight out of pending_, which keeps its storage for the next token. */ + std::string out = utf8_sanitize(std::string_view(pending_).substr(0, cut)); pending_.erase(0, cut); - return utf8_sanitize(out); + return out; } std::string Detokenizer::flush() { diff --git a/core/text/tokenizer.h b/core/text/tokenizer.h index 532970f7..4c00c525 100644 --- a/core/text/tokenizer.h +++ b/core/text/tokenizer.h @@ -264,6 +264,8 @@ private: std::string stop_hit_; size_t max_stop_ = 0; bool first_ = true; + Tokenizer tok_; /* over v_, set up by the first push */ + bool tok_ready_ = false; size_t safe_prefix() const; /* how much of pending_ can be released */ }; diff --git a/deploy/compose/flashnext.yaml b/deploy/compose/flashnext.yaml index d6b81cec..8e6f7a53 100644 --- a/deploy/compose/flashnext.yaml +++ b/deploy/compose/flashnext.yaml @@ -12,7 +12,7 @@ services: --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} --tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 - --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 + --kv-cache-dtype fp8 --prefix-cache-host-mib 4096 --prefix-cache-dir /data/kvcache/flashnext --prefix-cache-disk-mib 131072 --num-speculative-tokens 3 --max-num-batched-tokens 2048 diff --git a/docs/GUIDE.md b/docs/GUIDE.md index fa0cde0f..777d8437 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -409,39 +409,38 @@ outright: radiance --model m.rad --vram-weights-mib 24000 --vram-kv-mib 6000 ``` -or let the engine derive it from the card and tell it only the ratio: +or leave both unset and let the engine derive it from the card. The non-expert weights come off +the top of what is claimed. The rest — the `elastic` line of the startup receipt — is shared by +the expert slab and the KV cache, and no flag divides it: -```sh -radiance --model m.rad --expert-vs-cache-ratio 0.82 -``` +- **The cache lends** under `--placement auto` or `expert_tiered`, without `--deterministic`, on a + device with virtual memory management. The experts keep on the card exactly what the pinned host + pool (`--host-pool-mib`) cannot hold, plus one expert unit of packing slack; they have nowhere + else to be. The cache takes everything else, up to what it could ever address + (`--max-num-seqs` x `--max-model-len`), and every block no live request holds is lent back to the + expert slab in place. The prefill staging region comes out of the cache's side. +- **Without a lender** — `--deterministic`, a stated `--placement all_vram` or `layer_offload`, or + no virtual memory management — a block the cache does not use would sit empty, so the experts + come first and the cache keeps one `--max-model-len` sequence. -`--expert-vs-cache-ratio` is the **weights** share of what is claimed. 0.75 (the default) gives -three quarters to weights and a quarter to KV. +The cache never gets less than one `--max-model-len` sequence, and when both sides fit, both are +whole. With a lending cache, `--host-pool-mib` is what moves the split: a larger pool takes experts +off the card and gives the cache more. -**This flag decides whether multi-turn works, which is more than the split it names.** The KV side -is not only concurrency: prefix caching holds a finished sequence's blocks so the next turn can -reuse them. When the pool cannot hold the *live sessions*, the cache drops prefixes the next turn -wanted and that turn re-prefills its whole context. At long contexts that is two orders of magnitude -of time-to-first-token, bought back for a fraction of a percent of the decode step. - -Measured on Qwen3.8-Flash-Next at a 200K context, two ~184K-token sessions, byte-identical text: - -| ratio | turn 1 | turn 2 | prefix hit | -|---|---|---|---| -| 0.87 | 207.4 s | 173.0 s | 0.0% | -| 0.82 | 227.7 s | **3.0 s** | 99.0% | - -Same model, same prompts. The only difference is whether the pool could hold both sessions. 57x on -the second turn, paid for with ~10% on the cold first turn and ~1.4% of the decode step — experts -lose 5% of the elastic pool and the MoE GEMM is residency-bound. - -The cliff is sharp and it is worth knowing where: at this shape 0.84 is **not** enough (49.7% hit, -one of the two sessions), and watching `kv_util` finds it — between 0.75 and 0.81 of the pool the -hit rate falls from 80.7% to 49.4%. +**The cache's size decides whether multi-turn works.** The KV side is not only concurrency: prefix +caching holds a finished sequence's blocks so the next turn can reuse them. When the pool cannot +hold the *live sessions*, the cache drops prefixes the next turn wanted and that turn re-prefills +its whole context. At long contexts that is two orders of magnitude of time-to-first-token. +Measured on Qwen3.8-Flash-Next at a 200K context with two ~184K-token sessions and byte-identical +text, the second turn took 173.0 s at a 0.0% prefix hit with a pool that could not hold both +sessions, and 3.0 s at 99.0% with one that could. The fall-off is sharp, and `kv_util` shows a +pool approaching it. To size it yourself: work out what a token of context costs across **all** paged groups for your model (the startup log prints this), multiply by the context you actually serve, multiply by the -sessions you want live at once, and give the KV side at least that. +sessions you want live at once, and compare that with the cache the receipt reports. The cache +already has everything the experts can do without; a larger `--host-pool-mib` (RAM permitting) or +`--kv-cache-dtype fp8` gives it more. Worked, on Qwen3.8-Flash-Next: two paged groups share one token axis — `kv_attn` at 26.00 KiB and `kv_qsa_bkey` at 3.25 KiB per 4-token block — so a token of context costs **7.32 KiB**, and a @@ -564,8 +563,7 @@ holds at that price. ### 4.4 Long context ```sh -radiance --model m.rad --max-model-len 200000 --kv-cache-dtype fp8 \ - --expert-vs-cache-ratio 0.82 --max-num-seqs 8 +radiance --model m.rad --max-model-len 200000 --kv-cache-dtype fp8 --max-num-seqs 8 ``` `--max-model-len` does not reserve anything per request — it sets the worst case the pool is sized @@ -584,11 +582,10 @@ per sequence whether it is used or not: - **Recurrent state.** On a hybrid model every sequence owns its delta-net state, and with speculation two copies of it. Qwen3.8-Flash-Next keeps 54 MiB a copy on each card, so 32 - sequences take 3.4 GiB of the cache share before a single token is cached. At - `--expert-vs-cache-ratio 0.82` the attention cache then holds about 116K tokens, less than one - 200K request, and startup warns that a longer one would be refused; 0.78 brings it back, and the - experts it moves off the card cost single-stream decode about 15%. The 27B in bf16 lands at - 117K the same way. The 27B in FP8 holds 2.8 full-length sessions at 32, the 35B-A3B ten. + sequences take 3.4 GiB of the cache share before a single token is cached. The 27B in bf16, + with no experts to give way, then holds about 117K tokens of attention cache, less than one 200K + request, and startup warns that a longer one would be refused. The 27B in FP8 holds 2.8 + full-length sessions at 32, the 35B-A3B ten. - **Block tables.** The step batch's tables are carved for every sequence at the full context. They are charged to the VRAM budget (`step staging` in the startup receipt), so they come out of the cache share and not out of `--gpu-headroom-mib`. @@ -763,18 +760,21 @@ radiance --model m.rad \ --prefix-cache-disk-mib 65536 --prefix-cache-dir /var/cache/radiance ``` -- `--prefix-cache-host-mib N` — **this is the switch.** Without a size, nothing is copied. Part of - it goes to linear-state snapshots on a hybrid model; startup says how many. Size it for the - conversations you expect to come back: one that does not fit comes back from disk instead. +- `--prefix-cache-host-mib N` — **this is the switch.** Without a size, nothing is copied. It holds + attention blocks only; a hybrid model's linear-state snapshots are in host memory already, in the + `--checkpoint-slots` store. Size it for the conversations you expect to come back: one that does + not fit comes back from disk instead. - `--prefix-cache-disk-mib N` — the disk tier's size. Everything that reaches host memory is - written here too, so it sees the same bytes the host tier does. + written here too, snapshots included, so a full snapshot store detaches its least recently used + snapshot instead of losing it. - `--prefix-cache-dir DIR` — where the disk tier lives. **Not `--weights-disk-tier`**, which is about *weights*. The disk tier holds conversation content unencrypted. - Recovering a 200K-token turn costs a copy over PCIe; recomputing it costs minutes. -On a hybrid model this includes the recurrent state, not just the attention blocks — restoring the +On a hybrid model the recurrent state matters as much as the attention blocks — restoring the blocks alone leaves the session re-running every linear layer over its whole transcript, which -every hit-rate counter reports as a hit. `/sessions` shows what is stored, where, and whether the +every hit-rate counter reports as a hit. The snapshots never take VRAM: each is copied to host +memory after the step that produced it and back before the step that resumes from it. `/sessions` shows what is stored, where, and whether the linear half is being served. ### 4.9 What a request that leaves a field out gets @@ -891,7 +891,6 @@ one line naming each one the command line moved. | flag | default | | |---|---|---| | `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card | -| `--expert-vs-cache-ratio R` | 0.75 | weights share of what is claimed | | `--vram-weights-mib N` | derive | the resident weight slab | | `--vram-kv-mib N` | derive | the paged KV pool | | `--kv-cache-dtype T` | bf16 | `bf16` or `fp8` | @@ -915,7 +914,7 @@ one line naming each one the command line moved. | `--placement MODE` | auto | `all_vram`, `layer_offload`, `expert_tiered`, `auto` | | `--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 | -| `--checkpoint-slots N` | 8 | linear-state snapshots the server may hold at once, **in total**, not per sequence. A cap, not a charge: slots are backed as they are taken, so unused ones cost no VRAM. Raising it trades addressable context, since the range comes out of the KV pool | +| `--checkpoint-slots N` | 8 | linear-state snapshots the server may hold at once, **in total**, not per sequence. They live in pinned host memory, not VRAM: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`), allocated at startup. A snapshot is copied off the card after the step that produced it and back before the step that resumes from it. With a disk tier a full store detaches its least recently used snapshot to disk instead of losing it | | `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` | | `--no-prefix-cache` | — | disable prefix caching | @@ -1480,10 +1479,10 @@ released until it does. | What you see | What it means | What to do | |---|---|---| | `N declared op(s) resolve to libref` and the engine exits | No kernel library covers those ops on this card. Serving from the reference implementation would be orders of magnitude slow with nothing to say so | Install a library that covers them, or accept the cost with `--debug-accept-reference-kernels`. The named ops are exactly what a new library must implement | -| `did not fit` at load, naming a weight class or a KV group | The split left one side too little. A routed expert cannot be served from the file tier, so it has nowhere else to go | If **weights** did not fit: **raise** `--expert-vs-cache-ratio`, lower `--max-model-len` or `--max-num-seqs`, or add `--host-pool-mib`. If a **KV group** did not fit: lower the ratio, or `--kv-cache-dtype fp8`. The plan report names which, by class, with the shortfall | +| `did not fit` at load, naming a weight class or a KV group | The split left one side too little. A routed expert cannot be served from the file tier, so it has nowhere else to go | If **weights** did not fit: add or raise `--host-pool-mib`, or lower `--max-model-len` or `--max-num-seqs`. If a **KV group** did not fit: `--kv-cache-dtype fp8`, or a larger `--host-pool-mib` (RAM permitting), which takes experts off the card. The plan report names which, by class, with the shortfall | | `chat is 501` in the startup line | The container carries no chat template | Re-convert with `--tokenizer`, and check that a `chat_template.jinja` sits beside `tokenizer_config.json` in the checkpoint. Meanwhile use `/v1/completions` | | `does not read '' encoded ` at startup | No loaded kernel takes that weight's encoding for the op that reads it | Convert with a recipe that writes an encoding a loaded kernel reads, or load the library that reads it | -| Prefix hit rate 0% and every turn re-prefills | The KV pool cannot hold the live sessions, so the cache evicts what the next turn wanted | Lower `--expert-vs-cache-ratio` (more to KV), or `--kv-cache-dtype fp8`, or fewer/shorter sessions. See §4.3 | +| Prefix hit rate 0% and every turn re-prefills | The KV pool cannot hold the live sessions, so the cache evicts what the next turn wanted | The cache already has everything the experts can do without: a larger `--host-pool-mib` (RAM permitting), `--kv-cache-dtype fp8`, or fewer/shorter sessions. See §4.3 | | The server dies with no log line, on a request it had been serving fine | A kernel whose code object had never been loaded could not be: the card has no room left. HIP faults inside the launch rather than returning an error, so there is nothing to print | A card that never met `--gpu-headroom-mib` — see §4.3. Raise the headroom past the shortfall startup names. `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault | | KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-host-mib N` | | `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for | diff --git a/docs/MOE-W4.md b/docs/MOE-W4.md index 25efe416..354cd8ca 100644 --- a/docs/MOE-W4.md +++ b/docs/MOE-W4.md @@ -66,9 +66,8 @@ LDS lookup a byte), more protected bf16 experts (+4% bytes for 7% less error), a (13% less error energy for +13-18% on the expert GEMMs). **Further quality levers**, in order: five bits on both projections of layers -16-31 (the same +8% as the down projections, ~0.066 expected); fewer layers at five bits for a -smaller prefill cost; and `--expert-vs-cache-ratio`, which buys the residency back with KV -capacity. The formats, the kernel and a layer's own choice of form are all in the tree. +16-31 (the same +8% as the down projections, ~0.066 expected), and fewer layers at five bits for a +smaller prefill cost. The formats, the kernel and a layer's own choice of form are all in the tree. ## The stored plane @@ -244,8 +243,8 @@ its Hessians in the model's own domain; a rotated recipe's GPTQ reads them rotat Whole experts per rank, which a calibration run wants anyway. A step reads about 100 GiB a rank from the drive and grows only slowly with what it carries -- 50 s at ~32K tokens, 59 s at ~55K -- so drive it with large prefill steps: `--max-num-batched-tokens 65536 --max-num-seqs 64`, about 96 -requests in flight, and `--expert-vs-cache-ratio 0.5` so the cache share holds 64 sequences' -recurrent state. That records ~930 tokens a second, ten million tokens in three hours. +requests in flight, with a KV pool that holds 64 sequences' recurrent state (`--vram-kv-mib` +states it outright). That records ~930 tokens a second, ten million tokens in three hours. **The corpus is what the Hessian is of, so it has to look like the traffic.** A few thousand tokens of one repeated sentence gives a Gram whose energy sits in a handful of directions, and GPTQ diff --git a/docs/OPS.md b/docs/OPS.md index d7e48a9f..887081ab 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -544,11 +544,19 @@ gets a refusal, not a silent change of cost. `router_topk_scatter` over those logits. With `gate_b` [1, K] and `gate` [M, 1] present it is also the shared expert's one-column `gemm_nt` over the same `a`; the two come together or not at all. The selection needs every logit of a row, so it runs in the workgroup that finishes the GEMM -last (an arrival counter, self-resetting, one a stream and logits buffer). It is byte-identical to -the launches it stands in for: an element of the skinny bf16 GEMM depends only on its split-K -count, which this op takes from the same law at the same N, and the selection and sort are the -same code. Decode only, `M <= 64` -- past that the router is the tiled GEMM -- and bounded like the -pair. The logits stay an output. +last (an arrival counter, self-resetting, one an op instance: libr4d takes it in the row's `init`, +so it is in the VRAM budget, and refuses a launch without one). It is byte-identical to the +launches it stands in for: an element of the skinny bf16 GEMM depends only on its split-K count, +which this op takes from the same law at the same N, and the selection and sort are the same code. +Decode only, `M <= 64` -- past that the router is the tiled GEMM -- and bounded like the pair. The +logits stay an output. + +**The router GEMM inside it is NOTUNE.** It always takes the split the untuned law picks, which is +what makes it byte-identical to the unfused GEMM as an untuned install runs it. A tune-cache entry +for the unfused router's `gemm_nt` does not reach this op, so on a tuned install the two forms may +differ in the last bit; no shipped configuration tunes these GEMMs. An architecture asks for this op +wherever it declares the pair and issues the router and the pair itself where it does not resolve +or a pass is past its rows. `moe_scatter`'s output is what `rad_route_report` hands the heat engine. The histogram is read back asynchronously and consumed on the next step; nothing here blocks the compute stream diff --git a/docs/TOOLS.md b/docs/TOOLS.md index a044c36b..ad98b804 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -534,19 +534,19 @@ deliberately disconnects clients from it, which is not the same promise. | | knobs | |---|---| | `mcserve.sh` | MiniCPM5-2B + DSpark drafter (`minicpm5-2b-dspark.v2.rad`), left running. `P` `TP` `MLEN` `SEQS` `M` `KVD` `HR` `MNBT` `EXTRA` `EXTRA_ENV` | -| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. `P` `TP` `MLEN` `SEQS` `M` `RATIO` `NS` `HOSTPOOL` `KVD` `HR` `MNBT` `WIRE` `KVHOST` `KVDIR` `KVDISK` `EXTRA` `EXTRA_ENV` | +| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. `P` `TP` `MLEN` `SEQS` `M` `NS` `HOSTPOOL` `KVD` `HR` `MNBT` `WIRE` `KVHOST` `KVDIR` `KVDISK` `EXTRA` `EXTRA_ENV` | | `fnstop.sh` | stops whichever is running and **waits for the process to go** | | `convdspark.sh`, `convfn.sh` | rebuild the containers those two serve. The conversions of record. `convfn.sh` needs `CALIB=`: the production recipe's expert rule runs GPTQ against the calibration Grams there | | `hfget.sh` | fetch a checkpoint from Hugging Face with `curl` and `jq`. Resumable | ```sh -scripts/fnserve.sh # defaults: port 8100, tp 2, 200K ctx, ratio 0.82 +scripts/fnserve.sh # defaults: port 8100, tp 2, 200K ctx P=8100 MLEN=131072 SEQS=4 scripts/fnserve.sh # override scripts/fnstop.sh ``` Both print the endpoints and exit with the server still up. Read their headers — `fnserve.sh` in -particular carries the whole `--expert-vs-cache-ratio` argument with the measurements behind it. +particular records why each production flag is what it is. ### Measuring a server that is already up diff --git a/docs/TP3.md b/docs/TP3.md index f138a1c6..3effff8b 100644 --- a/docs/TP3.md +++ b/docs/TP3.md @@ -2,66 +2,60 @@ Radiance shards by dividing: `n_head`, `n_head_kv`, the delta-net head counts and the vocabulary each split across the world, and a count that does not divide is **refused at declare, by name** -(`share.cpp`, `rad_arch.h`). Four ranks got through for Qwen3.8-Flash-Next by replicating the two -KV heads in rank pairs (1.0.7); three did not: 24 query heads, 2 KV heads, 16 GDN K heads and 48 -GDN V heads have no even share in 3, and replication needs a world that is a multiple of the head -count. 1.0.12 served three ranks by **padding the checkpoint** offline (`tools/pad_tp.py`, the -regime of tcclaviger's `vllm/config/tp_padding.py`): zero heads appended so that 36 / 3 / 18 / 54 -divide, and a container converted from that. It worked, exactly, and it cost a second 115 GiB -container for every model and 1/3 of the attention and 2 of 18 delta-net heads computing zeros. +(`share.cpp`, `rad_arch.h`). Four ranks get through for Qwen3.8-Flash-Next by replicating the two +KV heads in rank pairs; three did not: 24 query heads, 2 KV heads, 16 GDN K heads and 48 GDN V +heads have no even share in 3, and replication needs a world that is a multiple of the head count. +Padding the checkpoint offline (`tools/pad_tp.py`: zero heads appended so that 36 / 3 / 18 / 54 +divide) served three ranks exactly, at the cost of a second 115 GiB container for every model and +a third of the attention and 2 of 18 delta-net heads computing zeros. This document describes what replaced it: **the shipped container serves at any world size**, with no tool and no second file. Two rules, both built from machinery the engine already had. ## 1. The attention world -`rad_arch.h` `geom_from` already handled a world *above* the KV head count by replication, when -the world is a multiple of the count. It now handles a world that is **neither a divisor nor a -multiple** of it: +`rad_arch.h` `geom_from` handles a world *above* the KV head count by replication, when the world +is a multiple of the count. For a plugin that asks for it (`attn_world_ok`; qwen4exp does) it also +handles a world that is **neither a divisor nor a multiple** of it: > attention is served on the largest multiple of the KV head count under the world -- the > **attention world** -- and the ranks past it are **attention-zero**. Three ranks over two KV heads: the attention world is 2. Ranks 0 and 1 split the heads exactly as the two-rank serve does -- 12 query heads, one KV head, gqa 12, the same kernels -- and rank 2 -declares **the same shapes** and reads **nothing** for them: `rad_weight_shard_zero` tells the -loader that this rank's share of `attn_qg`, `attn_k`, `attn_v` and `attn_output` is zeros. Its -attention computes zeros from zeros and its output projection adds exactly nothing to the reduce. -Five ranks over two: attention world 4 (two replicated pairs), rank 4 attention-zero. Six: three -pairs, no zero rank. +**computes no attention**: `rad_block_attn_gated_fp8.h` declares no projections, no attention and +no cache store on it, and writes the block's output wire to zero with one `fill` (`docs/OPS.md`). +The all-reduce and the residual after it see what they always saw, and the zero adds exactly +nothing to the reduce. Five ranks over two: attention world 4 (two replicated pairs), rank 4 +attention-zero. Six: three pairs, no zero rank. A plugin that does not ask is refused at a world +like these, by name, as before. -**The zeros are written, not assumed.** A zero share has no bytes in the container, so the sweep -over the file never reaches it; the loader hands it to the relayout workers itself, before the -sweep, and its fill writes the slot. The pool refuses to finish with any staged weight nothing -delivered. This matters because a card whose freed VRAM the driver wipes hands fresh allocations -back as zeros, and a slot nothing wrote serves correctly there by luck -- until the card has been -through a reset ("VRAM is lost") and the same slot is garbage. The test that sees it on any card: - - RADIANCE_POISON_ALLOC=255 radiance --model stock.rad --tp 3 ... - -fills every fresh device allocation with 0xFF (NaN in every float width) before it is handed out; -the serve must answer exactly as without it. `RADIANCE_POISON_RANGE=lo:hi` narrows the fill to a -thread's allocation ordinals for a bisect (`core/device/dispatch.cpp`). - -Why the same shapes rather than no attention on that rank: the scheduler sees **one program** -(`core/sched/batch.cpp` indexes `kv_groups[i]` by position), so every rank declares every op and -every KV group in the same order. An attention-zero rank's KV group is as large as its peers'; the -cost is one KV head of cache on that rank, the same bytes the padded container spent on its dummy -head, and nothing is read from disk for its projections. +**The KV groups stay in the same order on every rank.** The scheduler sees one program +(`core/sched/batch.cpp` indexes `kv_groups[i]` by position) and one block table serves every rank, +so an attention-zero rank declares its attention group like its peers and marks it +`rad_kv_group_zero`: it carves nothing for it, holds the shared table's block count, lends none of +it, and the tiers skip it when they move an entry. Every rank carves the same block count -- each +is planned, asked what it could page (`KVManager::paged_tokens`; a rank whose only paged groups are +zero limits nobody) and capped at the least before any carves. Under a smaller attention world the plain even shard over `world` is the wrong cut for every -attention projection, so `rad_block_attn_gated_fp8.h` declares **spans** (`rad_weight_shard_span`, -the same call the KV replication already used for k/v): q|gate rows and output columns -`[attn_rank * n_head, +n_head)` heads, k/v rows at `kv_off`. When the attention world is the world --- every TP2 and TP4 deployment -- no span is declared and the block declares as it always did. +attention projection, so the attention ranks declare **spans** (`rad_weight_shard_span`, the same +call the KV replication uses for k/v): q|gate rows and output columns `[attn_rank * n_head, ++n_head)` heads, k/v rows at `kv_off`. When the attention world is the world -- every TP2 and TP4 +deployment -- no span is declared and the block declares as it always did. ## 2. Uneven delta-net heads The delta net has no KV-head constraint: its kernels are bound on head *widths* (`head_k`, -`head_v`, the chunk) and take any head count. So 16 K heads over three ranks are **6, 5 and 5**, -each rank's V heads the same multiple of its K heads (48 / 16 = 3: 18, 15, 15), every rank real -heads, nothing padded. `qwen4exp` computes the split (`base + (rank < rem)`) and -`rad_block_gdn_fp8.h` declares it as spans of the container's rows. +`head_v`, the chunk) and take any head count. So 16 K heads over three ranks are **5, 5 and 6**, +each rank's V heads the same multiple of its K heads (48 / 16 = 3: 15, 15, 18), every rank real +heads, nothing padded. The extra head goes to the rank without attention (`remainder_place` in +`rad_arch.h`): it has the time, and the rank that would otherwise hold the extra head AND attention +is the step's slowest. The experts' extra block stays on the parity rotation (`qwen4exp_fp8.cpp` +says why). `qwen4exp` computes the split and `rad_block_gdn_fp8.h` declares it as spans of the +container's rows. Each rank's recurrent state is its own size, so a fresh slot is cleared, a +snapshot taken and a tier entry laid out by each rank's own plan: a slot of the snapshot store or +the tiers is the sum of the ranks' shares, each rank's where the ones before it end. That needed one thing the span call could not say. `in_proj_qkv|z` is four projections stacked along dim 0 -- q 2048, k 2048, v 6144, z 6144 rows -- and `rad_weight_shard_span` takes one @@ -73,46 +67,62 @@ columns take the same rank's heads. The even split, when the counts divide, is u ## 3. What this is built from -- `rad_weight_shard_zero(b, w)` -- this rank's share is zeros; `weight_share` returns the - declaration's extents with no rectangles, the loader stages the weight with a worker that writes - zeros (the route a checkpoint weight takes) and reads nothing. - `rad_weight_shard_span_parts(b, w, lo, hi, total, n)` -- a span per stacked part. -- `Geom::attn_world / attn_rank / attn_zero`, set by `geom_from`; `GdnFP8::Config::k_first / - v_first`, set by the plugin. -- Both exports are additive: `RAD_ABI_VERSION` does not move, and a plugin that does not call them - declares as before. `tests/share_test.cpp` holds the per-part cut and the zero share. +- `rad_kv_group_zero(b, g)` -- this rank keeps no cache for a paged group. +- the `fill` op -- libr4d's `fill_bf16`, libref's `ref_fill`. +- `Geom::attn_world / attn_rank / attn_zero`, set by `geom_from` under `attn_world_ok`; + `GdnFP8::Config::k_first / v_first`, set by the plugin. +- The exports are additive: `RAD_ABI_VERSION` does not move, and a plugin that does not call them + declares as before. `tests/share_test.cpp` holds the per-part cut, `tests/arch_test.cpp` the + three-rank declaration, `tests/mem_test.cpp` the capped carve, the zero group and a tier entry + moved across ranks with unequal shares. + +**A load check that came with it.** The relayout pool refuses to finish when any staged weight was +never delivered: a slot nothing wrote holds whatever the card had there -- zeros on a card whose +freed memory the driver wipes, garbage after a reset ("VRAM is lost"). The instrument that shows +such a read on any card: + + RADIANCE_DEBUG_POISON_ALLOC=255 radiance --model stock.rad --tp 3 ... + +fills every fresh device allocation with 0xFF (NaN in every float width) before it is handed out; +the serve must answer exactly as without it. `RADIANCE_DEBUG_POISON_RANGE=lo:hi` narrows the fill +to a thread's allocation ordinals for a bisect (`core/device/dispatch.cpp`). ## 4. Serving ```sh radiance --model qwen3.8-next-flash-fp8-iq4r-moe.rad --tp 3 --tp-wire exact --max-num-seqs 8 \ --max-model-len 262144 --placement expert_tiered --host-pool-mib 8192 \ - --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 \ + --gpu-headroom-mib 96 --kv-cache-dtype fp8 \ --num-speculative-tokens 3 --max-num-batched-tokens 2048 ``` The log says what the geometry did: ``` -radiance: world_size = 3 over n_head_kv = 2: attention on 2 rank(s), rank(s) 2..2 carry zero attention weights and the delta net and experts of a full rank -radiance: qwen4exp: rank 0 takes delta-net K heads [0, 6) of 16 and V heads [0, 18) of 48 -radiance: qwen4exp: rank 1 takes delta-net K heads [6, 11) of 16 and V heads [18, 33) of 48 -radiance: qwen4exp: rank 2 takes delta-net K heads [11, 16) of 16 and V heads [33, 48) of 48 +radiance: world_size = 3 over n_head_kv = 2: attention on 2 rank(s), rank(s) 2..2 carry no attention and take the delta net's remainder first +radiance: qwen4exp: rank 0 takes delta-net K heads [6, 11) of 16 and V heads [18, 33) of 48 +radiance: qwen4exp: rank 1 takes delta-net K heads [11, 16) of 16 and V heads [33, 48) of 48 +radiance: qwen4exp: rank 2 takes delta-net K heads [0, 6) of 16 and V heads [0, 18) of 48 ``` -Measured on three Radeon AI PRO R9700 (gfx1201, PCIe Gen5 x16, Threadripper PRO 9955WX) with the -same container served at two and three ranks -- the one comparison where only the world changes: +Measured by the contributor on three Radeon AI PRO R9700 (gfx1201, PCIe Gen5 x16) at an earlier +state of this design -- the attention-zero rank then ran its projections on zero weights, and the +extra delta-net head sat on rank 0 -- with the uncensored Flash-Next fine-tune. Hot = 1 / 4 / 8 +streams, 8 K prompt, 1 K generated, aggregate tok/s; crowd = 4 streams at 100 K context, per +stream; HumanEval 164 and a 200-question GSM8K subset at temperature 0: -| | two ranks | three ranks | -|---|---|---| -| READY from cold | | | -| 1 / 4 / 8 streams, aggregate t/s | | | -| 4 streams at 100 K context, per stream | | | -| HumanEval / GSM8K | | | +| container | `--tp` | hot c1 / c4 / c8 | crowd | HE | GSM8K | +|---|---|---|---|---|---| +| unpadded | 3 | 191 / 309 / 353 | 42.7 | 0.878 | 0.925 | +| unpadded, the same file | 2 | 177 / 308 / 377 | 33.8 | 0.884 | 0.915 | +| padded offline | 3 | 182 / 288 / 395 | 43.5 | 0.848 | 0.935 | -The three-rank text is the three-rank text of the padded container, token for token, at temperature -0 on the prompt set -- the two computations are the same arithmetic with the zeros in a different -place. +Three ranks buy the single stream and the long-context crowd, not the eight-stream aggregate. The +quality rows are within a rerun of each other (HumanEval moves by about 3 of 164 between runs of one +container); unpadded and padded at three ranks gave the same answers on 40 prompts at temperature +0, bit-identical on one -- the head regroup changes the order the all-reduce sums in, and near-ties +flip. `tools/pad_tp.py` and `tools/pad_verify.py` remain in the tree: they are how a checkpoint is padded for an engine that has no attention world, and how a pad is verified, and nothing here needs them. diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 64f48f23..5fdf8d12 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -54,6 +54,8 @@ std::vector build_cases() { add("gelu", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); add("silu", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2)); add("sigmoid", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); + add("fill", { HI("M", 6), HI("n", 645), HS("dtype", dt), HF("value", 1.3) }, + EB(6, 645, w, 1)); add("softmax", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); add("gather_rows", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2)); add("scatter_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); diff --git a/libavx/avx_elementwise.cpp b/libavx/avx_elementwise.cpp index be1b365f..13b20cdd 100644 --- a/libavx/avx_elementwise.cpp +++ b/libavx/avx_elementwise.cpp @@ -261,6 +261,25 @@ AVX_KERNEL(gelu) { return unary(a); } AVX_KERNEL(silu) { return unary(a); } AVX_KERNEL(sigmoid) { return unary(a); } +/* ------------------------------------------------------------------ fill */ +/* y = value over [M, n] at y's own row pitch, the value rounded once by the store. Nothing to + * vectorise that the store does not already do: it is a write of one number. */ +AVX_KERNEL(fill) { + if (!rad_args_have(a, 1)) return RAD_E_INVAL; + const RadTensor* y = &a->t[0]; + const int64_t n = p_int(a, "n", y->rank >= 1 ? y->shape[y->rank - 1] : 0); + if (n <= 0) return RAD_E_SHAPE; + const int64_t M = rows_of(y, n); + if (M <= 0) return RAD_E_SHAPE; + const float v = p_f32(a, "value", 0.0f); + AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < M; ++r) { + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, v); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ gather_rows */ /* y[i, :] = x[idx[i], :]. A negative index writes a ZERO ROW -- the padding rule embed_lookup * follows, and what a step with fewer sampled rows than the buffer's extent leaves behind. An diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 90304d89..f0f65ee4 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -90,7 +90,7 @@ int avx_isa_force(int level); X(mul) X(silu_mul) X(gelu) X(silu) \ X(sigmoid) X(gather_rows) X(scatter_rows) X(ngram_ids) \ X(ple_gate) X(ple_conv) X(cast) X(softmax) \ - X(scale_rows) \ + X(scale_rows) X(fill) \ /* ---- quantisation and rotation */ \ X(quant_act_i8) X(had_quant_act_i8) X(quant_act_fp8) X(had_quant_act_fp8) \ X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) X(dequant) \ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 718dda0b..15947922 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -129,6 +129,9 @@ static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") }; static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") }; static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") }; +/* `fill` has no input: `value` is the whole of what it writes. */ +static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") }; +static const RadOperandSpec oFill[] = { OUT("y") }; static const RadOperandSpec oGather[] = { OPD("x"), OPD("idx"), OUT("y") }; static const RadOperandSpec oScatterRows[] = { OPD("v"), OPD("idx"), INOUT("x") }; @@ -446,6 +449,7 @@ static const RadOpSchema kSchemas[] = { { "gelu", ARR(pMnD), ARR(oUnary), "exact erf gelu." }, { "silu", ARR(pMnD), ARR(oUnary), "silu." }, { "sigmoid", ARR(pMnD), ARR(oUnary), "logistic sigmoid." }, +{ "fill", ARR(pFill), ARR(oFill), "y = value over [M, n], rounded once to y's dtype (default 0)." }, { "ple_gate", ARR(pPleGate), ARR(oPleGate), "PLE gate: three grouped norms, a dot, a signed sqrt." }, { "ple_conv", ARR(pPleConv), ARR(oPleConv), @@ -621,6 +625,7 @@ SIMPLE("avx_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate SIMPLE("avx_gelu", "gelu", "elem", "exact erf gelu", DT_FLOAT, L(gelu)), SIMPLE("avx_silu", "silu", "elem", "silu", DT_FLOAT, L(silu)), SIMPLE("avx_sigmoid", "sigmoid", "elem", "logistic sigmoid", DT_FLOAT, L(sigmoid)), +SIMPLE("avx_fill", "fill", "elem", "constant fill", DT_FLOAT, L(fill)), SIMPLE("avx_gather_rows", "gather_rows", "elem", "y[i,:] = x[idx[i],:]", DT_ANY, L(gather_rows)), SIMPLE("avx_scatter_rows", "scatter_rows", "elem", "x[idx[i],:] = v[i,:]", DT_ANY, L(scatter_rows)), diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 2c265897..b696e12f 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -627,21 +627,15 @@ void r4d_qsa_score_pin_form(int form); // prefill form, 2 the (tile, run) decode form, 3 the uniform prefill grid. r4d_selftest --perfmoe // times each and compares it with form 1. void r4d_moe_gemm_pin_prefill(int form); -// THE DECODE FORM'S STAGED K, pinned for a test: 0 is R4D_MOE_GU_FK256's rule, 1 one 128-wide block -// a pass, 2 two wherever the shape allows it (the token-operand projection, every class's K a -// multiple of 256, a format that folds scale groups). The two are bit-identical, and r4d_selftest -// compares their bytes. +// THE DECODE FORM'S STAGED K, pinned for a test: 0 is the launcher's row limit (kMoeGuFk256Rows), +// 1 one 128-wide block a pass, 2 two wherever the shape allows it (the token-operand projection, +// every class's K a multiple of 256, a format that folds scale groups). The two are bit-identical, +// and r4d_selftest compares their bytes. void r4d_moe_gemm_pin_fk(int pin); -// THE DECODE FORM'S WEIGHT ADDRESS, pinned for a test: 0 is R4D_MOE_UWLOAD's rule, 1 the generic -// table pointer, 2 a uniform global base. Bit-identical, and r4d_selftest compares their bytes. -void r4d_moe_gemm_pin_uw(int pin); -// THE DECODE FORM'S RUN SEARCH, pinned for a test: 0 is R4D_MOE_RUNSCAN's rule, 1 the chunked -// search, 2 the one-pass search. Bit-identical, and r4d_selftest compares their bytes. -void r4d_moe_gemm_pin_rs(int pin); // THE GATED RESIDUAL READ'S PREFILL TILE, pinned for a test: 0 is the launcher's rule, 1 the decode // tiles' kernels at 128 rows (hc_down_tiled, then hc_up_tiled into `ubuf` and hc_mix), 2 the wide -// kernels (which then refuse a shape they are not built for), 3..9 the PF2 forms that -// R4D_HC_READ_PF2=1..7 puts in the rule (the same, and also refused where the band cannot hold +// kernels (which then refuse a shape they are not built for), 3 the PF2 kernels the rule takes from +// 512 rows (refused likewise, and also at a band under 512 rows, whose scratch is not sized for // their weight planes). All are bit-identical by construction, and r4d_selftest compares their // bytes. void r4d_hc_read_pin_prefill(int form); diff --git a/libr4d/r4d_hc_bf16.hip b/libr4d/r4d_hc_bf16.hip index 19de3972..aa9a093d 100644 --- a/libr4d/r4d_hc_bf16.hip +++ b/libr4d/r4d_hc_bf16.hip @@ -1291,31 +1291,20 @@ void hc_up_mix_kernel(const void* __restrict__ upv, long uld, } } -/* THE GROUP SIZE IS THE ROW COUNT, ROUNDED DOWN TO AN INSTANTIATION. RG is a template parameter - * because `acc[RG]` has to be registers; a runtime bound makes it scratch, and one private-memory - * round trip an element would cost more than the weight re-read it is here to remove. +/* THE GROUP SIZE IS THE ROW COUNT, UP TO EIGHT. RG is a template parameter because `acc[RG]` has + * to be registers; a runtime bound makes it scratch, and one private-memory round trip an element + * would cost more than the weight re-read it is here to remove. Every group from 1 to 8 is + * instantiated, so a row count up to eight is ONE group and the weight is read once: a five- or + * six-row verify (depth 4 or 5) split as 4 + 1 or 4 + 2 would read W_up twice. The output is the + * same bytes at any group, because only the loop nest over rows changes. * * The LDS cap is the real bound: RG rows of `d` are RG*lr floats beside the 4 KiB of staging - * slots, so a model with a wide low rank gets a smaller group rather than a launch failure. */ - -/* R4D_HC_RG_EXACT=1: a row count up to eight is ONE group of exactly that many rows (3, 5, 6 and 7 - * are instantiated too), so a depth-4 or depth-5 verify -- five or six rows -- still reads W_up once - * instead of twice (4 + 1, 4 + 2). Bit-identical for the reason the RG note gives: only the loop - * nest changes. Unset: the power-of-two rule. Read once, so recorded and live passes agree. */ -static bool hc_rg_exact() { - static const bool v = [] { - const char* e = std::getenv("R4D_HC_RG_EXACT"); - return e && *e && *e != '0'; - }(); - return v; -} + * slots, so a model with a wide low rank gets a smaller group rather than a launch failure -- the + * largest that fits, one row at a time, since every size below eight is an instantiation. */ static inline long hc_up_rg(long long rows, long long lr) { constexpr long kLdsCap = 60 * 1024; /* leave the 4 KiB of staging slots room */ - long rg = (rows >= 8) ? 8 : (rows >= 4) ? 4 : (rows >= 2) ? 2 : 1; - if (hc_rg_exact() && rows > 1 && rows < 8 && - (long long)rows * lr * (long long)sizeof(float) <= kLdsCap) - return (long)rows; - while (rg > 1 && (long long)rg * lr * (long long)sizeof(float) > kLdsCap) rg >>= 1; + long rg = rows < 8 ? (rows > 1 ? (long)rows : 1) : 8; + while (rg > 1 && (long long)rg * lr * (long long)sizeof(float) > kLdsCap) --rg; return rg; } @@ -1726,9 +1715,9 @@ constexpr int kWideRT = 128, kWideNT = 112, kWideCH = 16; /* THE PREFILL TILE'S FORM, pinned for a test: 0 is the launcher's rule, 1 the decode tiles' * kernels at RT 128 (hc_down_tiled, then hc_up_tiled into `ubuf` and hc_mix), 2 the wide kernels - * (which then refuse a shape they are not built for), 3..9 the PF2 forms R4D_HC_READ_PF2=1..7 - * selects (hc_pf2_launch; refused likewise, and also where the band's `u` cannot hold their - * weight planes). */ + * (which then refuse a shape they are not built for), 3 the PF2 form (hc_pf2_launch; refused + * likewise, and also at a band under kPf2MinRows, whose `u` is not sized for its weight + * planes). */ static int g_hc_prefill_form = 0; /* ==================================================== d = silu(W_down @ N / hc) at the PREFILL tile @@ -2207,8 +2196,17 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, * * THE FP8 TWIN is the arrival counter's, as in hc_up_mix_tiled_kernel: a workgroup owns 16 of a * scale group's 128 channels, and the last of the eight covering a group quantises it for the - * tile's rows. */ -template + * tile's rows. + * + * RT IS THE ROW TILE, MW = RT / 128 m-tiles a wave: 128 here (one m-tile a wave), 256 in the PF2 + * form over the mix_up its prologue decoded (two, so each B fragment read out of LDS feeds two + * WMMAs). The m-tile loops are the only difference, and at MW 1 each runs once over the same + * expressions in the same order as a body without them. The accumulators are ONE FLAT ARRAY, + * acc[mi * HC + c], because at MW 1 that is acc[c] exactly: an [MW][HC] array is the same values + * but reaches the register allocator in another shape, and gfx1201's code for the 128-row form then + * moves its zeros in another order. The rows keep their place in a 16-row tile at either RT (a + * tile starts at a multiple of RT), so both are the same bytes. */ +template __global__ __launch_bounds__(kThreads) void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, const unsigned short* __restrict__ dbuf, @@ -2216,8 +2214,9 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, const float* __restrict__ scalein, unsigned short* __restrict__ x, long rows, long n, long lr, long hrow, long xrow, float wadd) { - constexpr int RT = kWideRT, CH = kWideCH, NT = HC * CH; - static_assert(RT / 16 == kWaves, "one m-tile a wave"); + constexpr int CH = kWideCH, NT = HC * CH; + constexpr int MW = RT / 16 / kWaves; /* m-tiles a wave */ + static_assert(MW >= 1 && MW * 16 * kWaves == RT, "the waves cover the rows"); static_assert(RT * NT <= RT * kTAP, "N must fit in the A tile's LDS"); __shared__ unsigned short sA[RT * kTAP]; __shared__ unsigned short sB[NT * kTAP]; @@ -2289,9 +2288,9 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, } }; - v8f acc[HC]; + v8f acc[MW * HC]; #pragma unroll - for (int c = 0; c < HC; ++c) acc[c] = (v8f){0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + for (int c = 0; c < MW * HC; ++c) acc[c] = (v8f){0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; fetch(0); for (long k0 = 0; k0 < lr; k0 += kTKT) { @@ -2313,14 +2312,22 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, } __syncthreads(); if (k0 + kTKT < lr) fetch(k0 + kTKT); - /* A's fragment is read once a k step and taken to every n-tile. Each accumulator still - * sees its k steps in ascending order, which is all its bytes depend on. */ + /* A's fragments are read once a k step and taken to every n-tile, and B's to every m-tile. + * Each accumulator still sees its k steps in ascending order, which is all its bytes + * depend on. */ #pragma unroll for (int ks = 0; ks < kTKT / 16; ++ks) { - const v8bf af = frag(sA, kTAP, wave * 16, ks * 16, lane); + v8bf af[MW]; #pragma unroll - for (int c = 0; c < HC; ++c) - acc[c] = mma(af, frag(sB, kTAP, c * 16, ks * 16, lane), acc[c]); + for (int mi = 0; mi < MW; ++mi) + af[mi] = frag(sA, kTAP, (wave * MW + mi) * 16, ks * 16, lane); +#pragma unroll + for (int c = 0; c < HC; ++c) { + const v8bf bf = frag(sB, kTAP, c * 16, ks * 16, lane); +#pragma unroll + for (int mi = 0; mi < MW; ++mi) + acc[mi * HC + c] = mma(af[mi], bf, acc[mi * HC + c]); + } } } __syncthreads(); @@ -2345,15 +2352,17 @@ void hc_up_mix_wide_kernel(const void* __restrict__ upv, long uld, const float inv_hc = 1.0f / (float)HC; const int e0 = 8 * (lane >> 4), nn = lane & 15; #pragma unroll - for (int e = 0; e < 8; ++e) { - const int rl = wave * 16 + e0 + e; - const long r = r0 + rl; - float a = 0.0f; + for (int mi = 0; mi < MW; ++mi) #pragma unroll - for (int c = 0; c < HC; ++c) - a += bf2f(f2bf(sigmoidf_(acc[c][e]))) * bf2f(sN[(rl * HC + c) * CH + nn]); - if (r < rows) x[r * xrow + i0 + nn] = f2bf(a * inv_hc); - } + for (int e = 0; e < 8; ++e) { + const int rl = (wave * MW + mi) * 16 + e0 + e; + const long r = r0 + rl; + float a = 0.0f; +#pragma unroll + for (int c = 0; c < HC; ++c) + a += bf2f(f2bf(sigmoidf_(acc[mi * HC + c][e]))) * bf2f(sN[(rl * HC + c) * CH + nn]); + if (r < rows) x[r * xrow + i0 + nn] = f2bf(a * inv_hc); + } } /* THE FP8 CODES OF `x` AT THE PREFILL TILE, and the rotated twin: one wave a (row, 128-channel @@ -2486,9 +2495,12 @@ static inline void hc_up_mix_wide_launch(bool f8, bool i8, const void* up, long /* ==================================================== hc_read, the SECOND PREFILL FORM (PF2) * - * R4D_HC_READ_PF2=1 takes it at a prefill chunk, pinned form 3 takes it for a test. The same five - * steps as the wide form and the same bytes out of every one of them -- what moves is which - * workgroup does which part of the work, and how often: + * THE LAUNCHER'S RULE AT A PREFILL CHUNK of kPf2MinRows rows or more whose shape it is built for -- + * hc 4, n a multiple of 256, at most kPf2MaxNT n-tiles of columns -- with either dtype of mixing + * matrix; pinned form 3 takes it at any 128-row tile of such a band for a test. Every other + * prefill call is the wide form's. The same five steps as the wide form and the same bytes out of + * every one of them -- what moves is which workgroup does which part of the work, and how often + * (711 -> 611 us a call at a 2048-row chunk on gfx1201, E4M3 matrices): * * THE A OPERAND OF THE DOWN PRODUCT IS BUILT ONCE. hc_down_wide_kernel owns 112 columns, so the * three column tiles of a row tile each rebuild N from `h` -- the norm weight, the scale and the @@ -2496,13 +2508,15 @@ static inline void hc_up_mix_wide_launch(bool f8, bool i8, const void* up, long * rows and EVERY column, so `h` is read and N is built exactly once a call. * THE WEIGHT IS DECODED ONCE. Every row tile of the wide form decodes the E4M3 rows of both * mixing matrices it stages -- sixteen decodes of each matrix a call at a 2048-row chunk. A PF2 - * call decodes each matrix once, in its prologue, into scratch the wide form leaves unused. + * call decodes each matrix once, in its prologue, into the `u` scratch, which no fused form + * uses. At bf16 the prologue copies mix_down and mix_up is read where it is stored. * THE DOWN PRODUCT'S B OPERAND SKIPS LDS. With every column in one workgroup, each 16-column * n-tile belongs to exactly one wave, so nothing is shared and nothing needs staging: the * prologue writes the decoded matrix in WMMA FRAGMENT ORDER and a wave's fragment is one * 512-byte load. Only N goes through LDS, double-buffered, one barrier a slice. - * THE UP PRODUCT'S TILE IS 256 ROWS, two m-tiles a wave. Each B fragment read out of LDS feeds - * two WMMAs instead of one, and the weight is staged and read half as often. + * THE UP PRODUCT'S TILE IS 256 ROWS: hc_up_mix_wide_kernel at RT 256 over a bf16 mix_up, two + * m-tiles a wave. Each B fragment read out of LDS feeds two WMMAs instead of one, and the weight + * is staged and read half as often. * * WHAT KEEPS IT THE SAME BYTES. Every output element is the same chain of 16x16x16 WMMAs over * the same fragments in the same order: N is the same expression, the decoded weight is the bf16 @@ -2510,48 +2524,15 @@ static inline void hc_up_mix_wide_launch(bool f8, bool i8, const void* up, long * their place inside a 16x16 tile, and the down product keeps the K-split of hc_down_kchunk at * the 128-row tile, partial for partial, summed by the same reduce. The norm scales are * hc_norm_scale_kernel's sums in hc_norm_scale_kernel's order (see the prologue). r4d_selftest - * compares all three forms byte for byte. */ + * compares all three forms byte for byte, at both dtypes. + * + * THE PLANES' ROOM IS RESERVED, NOT HOPED FOR. r4d_rad_hc_read_scratch sizes `u` for both planes + * at every band that reaches kPf2MinRows (hc_u_rows), so the rule never meets a `u` too small. */ constexpr int kPf2RT = 64; // down product: rows a workgroup, four m-tiles constexpr int kPf2NW = 3; // down product: n-tiles a wave, at most constexpr int kPf2MaxNT = kWaves * kPf2NW; // ...so ceil((lr + hc) / 16) <= 24 -constexpr int kPf2WRT = 128; // the 128-row down product (PF2 form 4)... -constexpr int kPf2WThreads = 2 * kThreads; // ...is sixteen waves, two m-halves of eight -constexpr int kPf2WMaxNT = 21; // ...and holds a B slice of 21 n-tiles in LDS constexpr int kPf2UpRT = 256; // up product: rows a workgroup, two m-tiles a wave -constexpr long kPf2MinRows = 512; // the rule's floor; the pin takes any prefill tile - -/* WHAT A PF2 CALL RUNS, as bits: the 64-row down product, the up product and mix at 256 rows, the - * 128-row down product, the persistent up product and mix. A side without a bit is the wide - * form's kernel, so each half can be timed and checked alone; the prologue (norm scales, and the - * planes the chosen kernels read) runs in every PF2 call. */ -enum : int { kPf2Down = 1, kPf2Up = 2, kPf2DownW = 4, kPf2UpP = 8 }; - -/* R4D_HC_READ_PF2 (unset or 0: the wide form, as upstream): 1 both halves, 2 the down product - * alone, 3 the up product alone, 4 both with the 128-row down product, 5 the down product with - * the persistent up product, 6 the 128-row down product with it, 7 the persistent up product - * alone. Pinned forms 3..9 are the same seven. Read once, so a recorded pass and a live one take - * the same branch. */ -constexpr int kPf2Forms = 7; -static int hc_pf2_bits(int sel) { - if (sel < 1 || sel > kPf2Forms) return 0; - switch (sel) { - case 1: return kPf2Down | kPf2Up; - case 2: return kPf2Down; - case 3: return kPf2Up; - case 4: return kPf2DownW | kPf2Up; - case 5: return kPf2Down | kPf2UpP; - case 6: return kPf2DownW | kPf2UpP; - case 7: return kPf2UpP; - default: return 0; - } -} -static int hc_pf2_env() { - static const int v = [] { - const char* e = std::getenv("R4D_HC_READ_PF2"); - return hc_pf2_bits(e != nullptr ? std::atoi(e) : 0); - }(); - return v; -} +constexpr long kPf2MinRows = 512; // the rule's floor, and where `u` holds the planes /* THE PROLOGUE: the per-stream norm scales and the two weight planes, in ONE launch, because * the down product needs all three and none of them needs another. @@ -2585,7 +2566,7 @@ void hc_pf2_prep_kernel(const unsigned short* __restrict__ h, float* __restrict_ const unsigned short* __restrict__ injw, const unsigned char* __restrict__ up8, long uld, uint4* __restrict__ plane, unsigned short* __restrict__ udec, - uint4* __restrict__ uswz, long lr, long ncol, long ntt) { + long lr, long ncol, long ntt) { __shared__ float s_t[kWaves][kThreads]; const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; const long HN = (long)hc * n; @@ -2630,12 +2611,11 @@ void hc_pf2_prep_kernel(const unsigned short* __restrict__ h, float* __restrict_ return; } - const long KS = HN / 16, KSN = lr / 16; + const long KS = HN / 16; const long nswz = ntt * KS * kWave; const long nup = udec ? HN * (lr / 8) : 0; - const long nusw = uswz ? HN * (lr / 8) : 0; const long step = ((long)gridDim.x - nnb) * kThreads; - for (long v = ((long)blockIdx.x - nnb) * kThreads + tid; v < nswz + nup + nusw; v += step) { + for (long v = ((long)blockIdx.x - nnb) * kThreads + tid; v < nswz + nup; v += step) { if (v < nswz) { const long f = v / kWave; const int l = (int)(v - f * kWave); @@ -2660,40 +2640,12 @@ void hc_pf2_prep_kernel(const unsigned short* __restrict__ h, float* __restrict_ o = make_uint4(lo.x, lo.y, hi.x, hi.y); } plane[v] = o; - } else if (v < nswz + nup) { + } else { const long u = v - nswz; const long j = u / (lr / 8), k8 = (u - j * (lr / 8)) * 8; const unsigned char* row = up8 + j * uld; *(uint4*)(udec + j * lr + k8) = e4m3x8_bf16(row + k8, ((const float*)(row + lr))[k8 / r4d_hc8::up_group(lr)]); - } else { - /* mix_up in FRAGMENT ORDER for hc_up_mix_pf2p_kernel: [n/16 blocks][hc][KSN][32]. Lane - * l of block b, sub-stream c, k-step g holds row c*n + 16b + (l & 15) at k = 16g + - * 4(l >> 4) + {0..3, 8..11}; a k-step never straddles a group of lr/4 (a multiple of - * 16, which the launch checks). */ - const long u = v - nswz - nup; - const int l = (int)(u % kWave); - const long fr = u / kWave; - const long g = fr % KSN, bc = fr / KSN; - const long c = bc % hc, b = bc / hc; - const long j = c * n + 16 * b + (l & 15); - const long k = g * 16 + 4 * (l >> 4); - uint4 o; - if (f8) { - const unsigned char* row = up8 + j * uld; - const float sc = ((const float*)(row + lr))[k / r4d_hc8::up_group(lr)]; - float fv[8]; - e4m3x8(*(const uint32_t*)(row + k), *(const uint32_t*)(row + k + 8), fv); - union { uint4 v; unsigned short s[8]; } uu; -#pragma unroll - for (int e = 0; e < 8; ++e) uu.s[e] = f2bf(fv[e] * sc); - o = uu.v; - } else { - const unsigned short* src = (const unsigned short*)up8 + j * lr; - const uint2 lo = *(const uint2*)(src + k), hi = *(const uint2*)(src + k + 8); - o = make_uint4(lo.x, lo.y, hi.x, hi.y); - } - uswz[u] = o; } } } @@ -2839,388 +2791,6 @@ void hc_down_pf2_kernel(const unsigned short* __restrict__ h, const float* __res } } -/* THE SAME PRODUCT AT 128 ROWS, sixteen waves (PF2 form 4). hc_down_pf2_kernel reads the whole of - * B from L2 once per 64 rows -- 3.4 MB a workgroup at a 2048-row chunk, 220 MB a call. Here the - * waves of two m-halves share each B slice through LDS, which halves that stream for the price of - * staging it and of two barriers a slice. Which of the two the part prefers is a measurement. - * - * The B slice goes into LDS exactly as it lies in `plane` -- [n-tile][k-step][lane], 2 KB an n-tile - * -- so staging is a straight copy and a wave's fragment is one conflict-free 16-byte LDS read. - * Wave w is m-half w / 8 (four m-tiles) and n-group w % 8 (n-tiles w % 8, + 8, + 16). Same chains, - * same fragments, same places in the tile: the same bytes as every other form. */ -__global__ __launch_bounds__(kPf2WThreads) -void hc_down_pf2w_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, - const uint4* __restrict__ plane, const float* __restrict__ scalein, - unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, - float* __restrict__ part, - long rows, long n, int hc, long lr, long ncol, long ntt, long hrow, - long irow, long kc, float wadd) { - constexpr int NTH = kPf2WThreads, RT = kPf2WRT, MW = 4, NW = kPf2NW; - constexpr int kKV = kTKT / 8; /* 16-byte vectors a staged A row */ - constexpr int kRS = NTH / kKV; /* rows between a thread's A rows */ - constexpr int kAV = RT / kRS; - constexpr int KST = kTKT / 16; /* k-steps a slice */ - constexpr int kFV = KST * kWave; /* 16-byte vectors of one n-tile's slice */ - constexpr int kBV = (kPf2WMaxNT * kFV + NTH - 1) / NTH; - static_assert(RT % kRS == 0 && MW * 16 * 2 == RT && 2 * kWaves * kWave == NTH, - "two m-halves of four m-tiles, eight n-groups"); - __shared__ unsigned short sA[RT * kTAP]; - __shared__ uint4 sB[kPf2WMaxNT * kFV]; - - const int tid = threadIdx.x, lane = tid & (kWave - 1); - const int wave = __builtin_amdgcn_readfirstlane(tid / kWave); - const int mh = wave / kWaves, ng = wave % kWaves; - const long HN = (long)hc * n, KS = HN / 16; - const long r0 = (long)blockIdx.x * RT; - const long ka = (long)blockIdx.y * kc; - const long kb = (ka + kc < HN) ? ka + kc : HN; - if (r0 >= rows || ka >= HN) return; - const long nsl = (kb - ka) / kTKT; - const long nbv = ntt * kFV; - const long g0 = ka / 16; - - const int k8a = (tid % kKV) * 8, ar = tid / kKV; - long arow[kAV]; -#pragma unroll - for (int i = 0; i < kAV; ++i) { - const long r = r0 + ar + i * kRS; - arow[i] = r < rows ? r : rows - 1; - } - uint4 pa[kAV], pb[kBV]; - float psc[kAV], pw[8]; - auto fetch = [&](long t) { - const long k0 = ka + t * kTKT; - const int c = (int)(k0 / n); -#pragma unroll - for (int i = 0; i < kAV; ++i) { - pa[i] = *(const uint4*)(h + arow[i] * hrow + k0 + k8a); - psc[i] = scalein[arow[i] * kHcMax + c]; - } -#pragma unroll - for (int e = 0; e < 8; ++e) pw[e] = w[k0 + k8a + e]; -#pragma unroll - for (int b = 0; b < kBV; ++b) { - const long idx = tid + (long)b * NTH; - if (idx >= nbv) continue; - const long nt = idx / kFV, wi = idx - nt * kFV; - pb[b] = plane[(nt * KS + g0 + t * KST) * kWave + wi]; - } - }; - auto stage = [&]() { -#pragma unroll - for (int i = 0; i < kAV; ++i) { - union { uint4 v; unsigned short s[8]; } in, out; - in.v = pa[i]; -#pragma unroll - for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * psc[i] * (pw[e] + wadd)); - *(uint4*)(sA + (ar + i * kRS) * kTAP + k8a) = out.v; - } -#pragma unroll - for (int b = 0; b < kBV; ++b) { - const long idx = tid + (long)b * NTH; - if (idx < nbv) sB[idx] = pb[b]; - } - }; - - bool live[NW]; -#pragma unroll - for (int i = 0; i < NW; ++i) live[i] = ng + i * kWaves < ntt; - v8f acc[MW][NW]; -#pragma unroll - for (int m = 0; m < MW; ++m) -#pragma unroll - for (int i = 0; i < NW; ++i) acc[m][i] = (v8f){0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; - - fetch(0); - for (long t = 0; t < nsl; ++t) { - __syncthreads(); - stage(); - __syncthreads(); - fetch((t + 1 < nsl) ? t + 1 : t); /* the last slice re-reads itself: no branch */ -#pragma unroll - for (int s = 0; s < KST; ++s) { - v8bf af[MW]; -#pragma unroll - for (int m = 0; m < MW; ++m) af[m] = frag(sA, kTAP, (mh * MW + m) * 16, s * 16, lane); -#pragma unroll - for (int i = 0; i < NW; ++i) { - if (!live[i]) continue; - union { uint4 q; v8bf f; } bu; - bu.q = sB[((ng + i * kWaves) * KST + s) * kWave + lane]; -#pragma unroll - for (int m = 0; m < MW; ++m) acc[m][i] = mma(af[m], bu.f, acc[m][i]); - } - } - } - - const float inv_hc = 1.0f / (float)hc; - const int e0 = 8 * (lane >> 4), nn = lane & 15; -#pragma unroll - for (int i = 0; i < NW; ++i) { - if (!live[i]) continue; - const long col = (long)(ng + i * kWaves) * 16 + nn; - if (col >= ncol) continue; -#pragma unroll - for (int m = 0; m < MW; ++m) -#pragma unroll - for (int e = 0; e < 8; ++e) { - const long r = r0 + (mh * MW + m) * 16 + e0 + e; - if (r >= rows) continue; - const float v = acc[m][i][e]; - if (part) part[((long)blockIdx.y * rows + r) * ncol + col] = v; - else if (col < lr) dout[r * lr + col] = f2bf(siluf_(v * inv_hc)); - else inj[r * irow + (col - lr)] = f2bf(2.0f * sigmoidf_(v * inv_hc)); - } - } -} - -/* THE UP PRODUCT AND MIX WITH `d` HELD, PERSISTENT (PF2 forms 7..9). The wide form's 2560 - * workgroups each restage a [128 x 320] tile of `d` for sixteen channels, so `d` crosses L2 160 - * times a call and the A staging is a third of the kernel's LDS traffic. Here a wave loads its 16 - * rows of `d` ONCE, as the twenty WMMA fragments of K = 320 in its registers, and the workgroup - * walks a run of channel blocks: each block's B -- four sub-streams of sixteen channels, mix_up - * decoded by the prologue into FRAGMENT ORDER, 40 KB contiguous -- is a straight copy into LDS and - * a wave's fragment is one 16-byte LDS read. The next block's B and `h` are loaded while this - * block's WMMAs run. - * - * Every u is the same 20-step chain from zero over the same fragments, at the same place in its - * tile, and N, the narrowing and the mix are hc_up_mix_wide_kernel's expressions: the same bytes. */ -constexpr int kPf2PRT = 128; // rows a workgroup: one m-tile a wave -template // k-steps of lowrank, lr / 16 -__global__ __launch_bounds__(kThreads) -void hc_up_mix_pf2p_kernel(const uint4* __restrict__ uswz, const unsigned short* __restrict__ dbuf, - const unsigned short* __restrict__ h, const float* __restrict__ w, - const float* __restrict__ scalein, unsigned short* __restrict__ x, - long rows, long n, long lr, long hrow, long xrow, float wadd, - long bpw) { - constexpr int HC = 4, CH = kWideCH, NT = HC * CH; - constexpr int kBF = HC * KSN * kWave; /* 16-byte vectors of one block's B */ - constexpr int kBV = kBF / kThreads; - constexpr int kNV = kPf2PRT * HC * (CH / 8) / kThreads; - static_assert(kBF % kThreads == 0 && (kPf2PRT * HC * (CH / 8)) % kThreads == 0, - "every thread stages whole vectors"); - __shared__ uint4 sB[kBF]; - __shared__ unsigned short sN[kPf2PRT * NT]; - - const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; - const long r0 = (long)blockIdx.y * kPf2PRT; - const long nblk = n / CH; - const long b0 = (long)blockIdx.x * bpw; - const long b1 = (b0 + bpw < nblk) ? b0 + bpw : nblk; - if (r0 >= rows || b0 >= b1) return; - - /* This wave's rows of `d`, all twenty fragments: what frag() would read out of an A tile - * holding them, read from `dbuf` directly. */ - v8bf af[KSN]; - { - long r = r0 + wave * 16 + (lane & 15); - if (r >= rows) r = rows - 1; - const unsigned short* p = dbuf + r * lr + 4 * (lane >> 4); -#pragma unroll - for (int g = 0; g < KSN; ++g) af[g] = fragP(p + 16 * g); - } - - uint4 pb[kBV], pn[kNV]; - float pns[kNV]; - auto fetch = [&](long b) { - const uint4* src = uswz + b * kBF; -#pragma unroll - for (int v = 0; v < kBV; ++v) pb[v] = src[tid + v * kThreads]; - const long i0 = b * CH; -#pragma unroll - for (int i = 0; i < kNV; ++i) { - const int idx = tid + i * kThreads; - const int rl = idx / (HC * CH / 8), rem = idx % (HC * CH / 8); - const int c = rem / (CH / 8), i8 = (rem % (CH / 8)) * 8; - const long r = r0 + rl; - pn[i] = make_uint4(0u, 0u, 0u, 0u); - pns[i] = 0.0f; - if (r < rows) { - pn[i] = *(const uint4*)(h + r * hrow + (long)c * n + i0 + i8); - pns[i] = scalein[r * kHcMax + c]; - } - } - }; - - const float inv_hc = 1.0f / (float)HC; - const int e0 = 8 * (lane >> 4), nn = lane & 15; - fetch(b0); - for (long b = b0; b < b1; ++b) { - __syncthreads(); -#pragma unroll - for (int v = 0; v < kBV; ++v) sB[tid + v * kThreads] = pb[v]; - const long i0 = b * CH; -#pragma unroll - for (int i = 0; i < kNV; ++i) { - const int idx = tid + i * kThreads; - const int rl = idx / (HC * CH / 8), rem = idx % (HC * CH / 8); - const int c = rem / (CH / 8), i8 = (rem % (CH / 8)) * 8; - if (r0 + rl >= rows) continue; - const long j = (long)c * n + i0 + i8; - union { uint4 v; unsigned short s[8]; } in, out; - in.v = pn[i]; -#pragma unroll - for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * pns[i] * (w[j + e] + wadd)); - *(uint4*)(sN + (rl * HC + c) * CH + i8) = out.v; - } - __syncthreads(); - fetch((b + 1 < b1) ? b + 1 : b); /* the last block re-reads itself: no branch */ - - v8f acc[HC]; -#pragma unroll - for (int c = 0; c < HC; ++c) acc[c] = (v8f){0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; -#pragma unroll - for (int g = 0; g < KSN; ++g) -#pragma unroll - for (int c = 0; c < HC; ++c) { - union { uint4 q; v8bf f; } bu; - bu.q = sB[(c * KSN + g) * kWave + lane]; - acc[c] = mma(af[g], bu.f, acc[c]); - } - -#pragma unroll - for (int e = 0; e < 8; ++e) { - const int rl = wave * 16 + e0 + e; - const long r = r0 + rl; - float a = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) - a += bf2f(f2bf(sigmoidf_(acc[c][e]))) * bf2f(sN[(rl * HC + c) * CH + nn]); - if (r < rows) x[r * xrow + i0 + nn] = f2bf(a * inv_hc); - } - } -} - -/* hc_up_mix_wide_kernel at 256 rows, two m-tiles a wave, over a bf16 mix_up (decoded by the - * prologue, or the stored one). The (stream, channel) pairing, the prefetch, the N pass and the - * mix are that kernel's line for line; what changes is that a B fragment read out of LDS goes to - * both of a wave's m-tiles, so the weight's staging and its fragment reads are halved against - * the WMMAs they feed. The rows keep their place in a 16-row tile (the tile starts at a multiple - * of 256), so every output is the same bytes. */ -template -__global__ __launch_bounds__(kThreads) -void hc_up_mix_pf2_kernel(const unsigned short* __restrict__ ubf, - const unsigned short* __restrict__ dbuf, - const unsigned short* __restrict__ h, const float* __restrict__ w, - const float* __restrict__ scalein, - unsigned short* __restrict__ x, - long rows, long n, long lr, long hrow, long xrow, float wadd) { - constexpr int RT = kPf2UpRT, CH = kWideCH, NT = HC * CH; - constexpr int MW = RT / 16 / kWaves; /* m-tiles a wave */ - static_assert(MW * 16 * kWaves == RT, "the waves cover the rows"); - static_assert(NT <= kTAP, "N must fit in the A tile's LDS"); - __shared__ unsigned short sA[RT * kTAP]; - __shared__ unsigned short sB[NT * kTAP]; - - const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; - const long r0 = (long)blockIdx.y * RT; - const long i0 = (long)blockIdx.x * CH; - if (r0 >= rows) return; - - constexpr int kKV = kTKT / 8; - constexpr int kRS = kThreads / kKV; - constexpr int kAV = RT / kRS, kBV = NT / kRS; - constexpr int kNV = RT * HC * (CH / 8) / kThreads; - static_assert(RT % kRS == 0 && NT % kRS == 0 && (RT * HC * (CH / 8)) % kThreads == 0, - "every thread stages whole vectors"); - const int k8a = (tid % kKV) * 8, tr = tid / kKV; - - uint4 pn[kNV]; - float pns[kNV]; -#pragma unroll - for (int i = 0; i < kNV; ++i) { - const int idx = tid + i * kThreads; - const int rl = idx / (HC * CH / 8), rem = idx % (HC * CH / 8); - const int c = rem / (CH / 8), i8 = (rem % (CH / 8)) * 8; - const long r = r0 + rl; - pn[i] = make_uint4(0u, 0u, 0u, 0u); - pns[i] = 0.0f; - if (r < rows) { - pn[i] = *(const uint4*)(h + r * hrow + (long)c * n + i0 + i8); - pns[i] = scalein[r * kHcMax + c]; - } - } - - uint4 pa[kAV], pb[kBV]; - auto fetch = [&](long k0) { - const long k = k0 + k8a; - const bool in = k + 8 <= lr; -#pragma unroll - for (int i = 0; i < kAV; ++i) { - long r = r0 + tr + i * kRS; if (r >= rows) r = rows - 1; - pa[i] = in ? *(const uint4*)(dbuf + r * lr + k) : make_uint4(0u, 0u, 0u, 0u); - } -#pragma unroll - for (int i = 0; i < kBV; ++i) { - const int tt = tr + i * kRS; - const long j = (long)(tt / CH) * n + i0 + tt % CH; - pb[i] = in ? *(const uint4*)(ubf + j * lr + k) : make_uint4(0u, 0u, 0u, 0u); - } - }; - - v8f acc[MW][HC]; -#pragma unroll - for (int mi = 0; mi < MW; ++mi) -#pragma unroll - for (int c = 0; c < HC; ++c) acc[mi][c] = (v8f){0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; - - fetch(0); - for (long k0 = 0; k0 < lr; k0 += kTKT) { - __syncthreads(); -#pragma unroll - for (int i = 0; i < kAV; ++i) *(uint4*)(sA + (tr + i * kRS) * kTAP + k8a) = pa[i]; -#pragma unroll - for (int i = 0; i < kBV; ++i) *(uint4*)(sB + (tr + i * kRS) * kTAP + k8a) = pb[i]; - __syncthreads(); - if (k0 + kTKT < lr) fetch(k0 + kTKT); -#pragma unroll - for (int ks = 0; ks < kTKT / 16; ++ks) { - v8bf af[MW]; -#pragma unroll - for (int mi = 0; mi < MW; ++mi) - af[mi] = frag(sA, kTAP, (wave * MW + mi) * 16, ks * 16, lane); -#pragma unroll - for (int c = 0; c < HC; ++c) { - const v8bf bf = frag(sB, kTAP, c * 16, ks * 16, lane); -#pragma unroll - for (int mi = 0; mi < MW; ++mi) acc[mi][c] = mma(af[mi], bf, acc[mi][c]); - } - } - } - __syncthreads(); - - unsigned short* const sN = sA; -#pragma unroll - for (int i = 0; i < kNV; ++i) { - const int idx = tid + i * kThreads; - const int rl = idx / (HC * CH / 8), rem = idx % (HC * CH / 8); - const int c = rem / (CH / 8), i8 = (rem % (CH / 8)) * 8; - if (r0 + rl >= rows) continue; - const long j = (long)c * n + i0 + i8; - union { uint4 v; unsigned short s[8]; } in, out; - in.v = pn[i]; -#pragma unroll - for (int e = 0; e < 8; ++e) out.s[e] = f2bf(bf2f(in.s[e]) * pns[i] * (w[j + e] + wadd)); - *(uint4*)(sN + (rl * HC + c) * CH + i8) = out.v; - } - __syncthreads(); - - const float inv_hc = 1.0f / (float)HC; - const int e0 = 8 * (lane >> 4), nn = lane & 15; -#pragma unroll - for (int mi = 0; mi < MW; ++mi) -#pragma unroll - for (int e = 0; e < 8; ++e) { - const int rl = (wave * MW + mi) * 16 + e0 + e; - const long r = r0 + rl; - float a = 0.0f; -#pragma unroll - for (int c = 0; c < HC; ++c) - a += bf2f(f2bf(sigmoidf_(acc[mi][c][e]))) * bf2f(sN[(rl * HC + c) * CH + nn]); - if (r < rows) x[r * xrow + i0 + nn] = f2bf(a * inv_hc); - } -} - /* K per down-product workgroup: enough z-blocks that lr/kTNT * z covers the part, rounded to a * whole number of kTKT slices so a slice never straddles a sub-stream. Returns HN when one block @@ -3857,18 +3427,25 @@ static inline void hc_up_tiled_launch(int rt, bool f8, const void* up, long uld, #undef HC_UP_CASE } -/* THE PF2 FORM, start to finish: prologue, down product, reduce, up product and mix, codes. - * `bits` says which halves are PF2's (a side without its bit runs the wide form's kernel, on the - * stored weights). `wsp` is the plane space -- the `u` buffer, which no fused form uses -- and the - * caller has checked it holds pf2_plane_bytes(). Returns a RAD code. */ -static inline long long pf2_plane_bytes(int bits, long long HN, long long lr, long long ntt, - bool f8) { - const bool down = (bits & (kPf2Down | kPf2DownW)) != 0; - return (down ? ntt * 16 * HN * 2 : 0) + ((bits & kPf2Up) && f8 ? HN * lr * 2 : 0) - + ((bits & kPf2UpP) ? HN * lr * 2 : 0); +/* THE PF2 FORM'S WEIGHT PLANES in the `u` scratch, in bytes: mix_down (and the inject weights) in + * fragment order over ntt n-tiles, then -- E4M3 only -- mix_up decoded to [HN][lr] bf16. */ +static inline long long pf2_plane_bytes(long long HN, long long lr, long long ntt, bool f8) { + return ntt * 16 * HN * 2 + (f8 ? HN * lr * 2 : 0); } -static int hc_pf2_launch(int bits, bool f8, bool i8, const unsigned short* h, const float* w, +/* `u`'S ROWS IN THE SCRATCH, [rows][HN] bf16: the band's M, and at a band that reaches the PF2 rule + * at least the rows its planes take at the widest fold (ncol = lr + hc) and either dtype -- + * ceil((lr + hc) / 16) * 16 + lr. The scratch hook and the launcher both size `u` from this, so the + * offsets behind it agree, and the rule never finds the planes without room. */ +static inline long long hc_u_rows(long long M, long long lr, long long hc) { + const long long pf2 = ((lr + hc + 15) / 16) * 16 + lr; + return (M >= kPf2MinRows && pf2 > M) ? pf2 : M; +} + +/* THE PF2 FORM, start to finish: prologue, down product, reduce, up product and mix, codes. `wsp` + * is the plane space -- the `u` buffer, which no fused form uses -- and the caller has checked it + * holds pf2_plane_bytes() and that hc is 4. Returns a RAD code. */ +static int hc_pf2_launch(bool f8, bool i8, const unsigned short* h, const float* w, const void* down, long dld, const void* up, long uld, const unsigned short* injw, unsigned short* dbuf, float* scale, unsigned char* wsp, float* part, unsigned short* x, @@ -3876,43 +3453,27 @@ static int hc_pf2_launch(int bits, bool f8, bool i8, const unsigned short* h, co float* rqs, long rows, long n, int hc, long lr, long ncol, long hrow, long irow, long xrow, long qrow, long srow, long rqrow, long rsrow, long kc, int ks, float eps, float wadd, RadStream s) { - const long HN = (long)hc * n; - const bool pdown = (bits & (kPf2Down | kPf2DownW)) != 0; - const bool pup = (bits & kPf2Up) != 0; - const bool pupp = (bits & kPf2UpP) != 0; - const long ntt = pdown ? (ncol + 15) / 16 : 0; /* plane n-tiles; none unless used */ - uint4* const plane = pdown ? (uint4*)wsp : nullptr; - unsigned char* const utail = wsp + ntt * 16 * HN * 2; - unsigned short* const udec = pup && f8 ? (unsigned short*)utail : nullptr; - uint4* const uswz = pupp ? (uint4*)utail : nullptr; + const long HN = (long)hc * n; + const long ntt = (ncol + 15) / 16; /* plane n-tiles */ + uint4* const plane = (uint4*)wsp; + unsigned short* const udec = f8 ? (unsigned short*)(wsp + ntt * 16 * HN * 2) : nullptr; const unsigned short* ubf = f8 ? udec : (const unsigned short*)up; const long nnb = (rows * hc + kWaves - 1) / kWaves; - const long work = ntt * (HN / 16) * kWave + (udec ? HN * (lr / 8) : 0) - + (uswz ? HN * (lr / 8) : 0); + const long work = ntt * (HN / 16) * kWave + (udec ? HN * (lr / 8) : 0); long ndec = (work + kThreads - 1) / kThreads; if (ndec > 512) ndec = 512; hipLaunchKernelGGL(hc_pf2_prep_kernel, dim3((unsigned)(nnb + ndec)), dim3(kThreads), 0, (hipStream_t)s, h, scale, rows, n, hc, hrow, eps, nnb, down, dld, f8, injw, - (const unsigned char*)up, uld, plane, udec, uswz, lr, ncol, ntt); + (const unsigned char*)up, uld, plane, udec, lr, ncol, ntt); if (hipGetLastError() != hipSuccess) return RAD_E_DEVICE; float* const kpart = ks > 1 ? part : nullptr; - if (bits & kPf2Down) - hipLaunchKernelGGL(hc_down_pf2_kernel, - dim3((unsigned)((rows + kPf2RT - 1) / kPf2RT), (unsigned)ks), - dim3(kThreads), 0, (hipStream_t)s, h, w, (const uint4*)plane, - (const float*)scale, dbuf, inj, kpart, rows, n, hc, lr, ncol, ntt, hrow, - irow, kc, wadd); - else if (bits & kPf2DownW) - hipLaunchKernelGGL(hc_down_pf2w_kernel, - dim3((unsigned)((rows + kPf2WRT - 1) / kPf2WRT), (unsigned)ks), - dim3(kPf2WThreads), 0, (hipStream_t)s, h, w, (const uint4*)plane, - (const float*)scale, dbuf, inj, kpart, rows, n, hc, lr, ncol, ntt, hrow, - irow, kc, wadd); - else - hc_down_wide_launch(f8, h, w, down, dld, scale, injw, dbuf, inj, kpart, rows, n, hc, lr, - ncol, hrow, irow, kc, wadd, s); + hipLaunchKernelGGL(hc_down_pf2_kernel, + dim3((unsigned)((rows + kPf2RT - 1) / kPf2RT), (unsigned)ks), + dim3(kThreads), 0, (hipStream_t)s, h, w, (const uint4*)plane, + (const float*)scale, dbuf, inj, kpart, rows, n, hc, lr, ncol, ntt, hrow, + irow, kc, wadd); if (hipGetLastError() != hipSuccess) return RAD_E_DEVICE; if (ks > 1) { @@ -3924,29 +3485,15 @@ static int hc_pf2_launch(int bits, bool f8, bool i8, const unsigned short* h, co if (hipGetLastError() != hipSuccess) return RAD_E_DEVICE; } - if (pupp) { - /* Enough channel runs that the row tiles times the runs fill the part twice over. */ - const long nrt = (rows + kPf2PRT - 1) / kPf2PRT, nblk = n / kWideCH; - long runs = (64 + nrt - 1) / nrt; - if (runs > nblk) runs = nblk; - const long bpw = (nblk + runs - 1) / runs; - hipLaunchKernelGGL(hc_up_mix_pf2p_kernel<20>, - dim3((unsigned)((nblk + bpw - 1) / bpw), (unsigned)nrt), dim3(kThreads), - 0, (hipStream_t)s, (const uint4*)uswz, (const unsigned short*)dbuf, h, w, - (const float*)scale, x, rows, n, lr, hrow, xrow, wadd, bpw); - if (hipGetLastError() != hipSuccess) return RAD_E_DEVICE; - hc_quant_rows_launch(i8, x, q, qs, rq, rqs, rows, n, xrow, qrow, srow, rqrow, rsrow, s); - } else if (pup) { - hipLaunchKernelGGL(hc_up_mix_pf2_kernel<4>, - dim3((unsigned)(n / kWideCH), (unsigned)((rows + kPf2UpRT - 1) / kPf2UpRT)), - dim3(kThreads), 0, (hipStream_t)s, ubf, (const unsigned short*)dbuf, h, - w, (const float*)scale, x, rows, n, lr, hrow, xrow, wadd); - if (hipGetLastError() != hipSuccess) return RAD_E_DEVICE; - hc_quant_rows_launch(i8, x, q, qs, rq, rqs, rows, n, xrow, qrow, srow, rqrow, rsrow, s); - } else { - hc_up_mix_wide_launch(f8, i8, up, uld, dbuf, h, w, scale, x, q, qs, rq, rqs, rows, n, lr, - hrow, xrow, qrow, srow, rqrow, rsrow, wadd, s); - } + /* The up product and mix: the wide kernel at 256 rows over a bf16 mix_up, whose row pitch is + * lr -- the decoded plane, or the stored matrix at bf16. */ + hipLaunchKernelGGL((hc_up_mix_wide_kernel<4, false, kPf2UpRT>), + dim3((unsigned)(n / kWideCH), (unsigned)((rows + kPf2UpRT - 1) / kPf2UpRT)), + dim3(kThreads), 0, (hipStream_t)s, (const void*)ubf, lr, + (const unsigned short*)dbuf, h, w, (const float*)scale, x, rows, n, lr, hrow, + xrow, wadd); + if (hipGetLastError() != hipSuccess) return RAD_E_DEVICE; + hc_quant_rows_launch(i8, x, q, qs, rq, rqs, rows, n, xrow, qrow, srow, rqrow, rsrow, s); return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } @@ -4184,7 +3731,9 @@ extern "C" int64_t r4d_rad_hc_read_scratch(const RadArgs* a) { const long long hc = r4d_geti_or(a, "hc", 0); if (M <= 0 || lr <= 0 || n <= 0 || hc <= 0) return R4D_NO(RAD_E_SHAPE); /* `d` [M, lowrank] bf16, the per-stream norm scales [M, kHcMax] f32, and `u` [M, hc*n] bf16 -- - * 20 KiB a row at this model's shape, which is what buys the up-matvec its own grid. + * 20 KiB a row at this model's shape, which is what buys the up-matvec its own grid. A band + * that reaches the PF2 rule holds its weight planes in `u` as well, so `u` there has at least + * the rows they take (hc_u_rows). * * PLUS THE SPLIT-K PARTIALS. Every row count below a few thousand takes a split, so this is * not a decode-only buffer and is not bounded by kTileMinRows -- hc_part_bytes @@ -4195,7 +3744,7 @@ extern "C" int64_t r4d_rad_hc_read_scratch(const RadArgs* a) { * alone and the buffer is sized for the widest ncol a fold can produce. Deriving it from ncol * here and from lr there gives two different split counts for the same shape, and the partial * buffer then overruns. */ - return M * ((long long)lr * 2 + (long long)kHcMax * 4 + hc * n * 2) + return M * ((long long)lr * 2 + (long long)kHcMax * 4) + hc_u_rows(M, lr, hc) * HN * 2 + hc_part_bytes(M, lr, HN); } @@ -4316,7 +3865,8 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { /* `d`, the scales and `u` are all sized from the BAND, so a step wider than the band it was * planned for does not run slowly -- it writes past three buffers. */ if (rows > Mband) return R4D_NO(RAD_E_SHAPE); - const long long fixed = Mband * (lr * 2 + (long long)kHcMax * 4 + HN * 2); + const long long ubytes = hc_u_rows(Mband, lr, hc) * HN * 2; + const long long fixed = Mband * (lr * 2 + (long long)kHcMax * 4) + ubytes; if (!a->scratch || a->scratch_bytes < fixed) return R4D_NO(RAD_E_SCRATCH); unsigned short* dbuf = (unsigned short*)a->scratch; float* scale = (float*)((unsigned char*)a->scratch + Mband * lr * 2); @@ -4368,21 +3918,23 @@ static int rad_hc_read_body(const RadArgs* a, const R4dSink& sk) { return R4D_NO(RAD_E_SCRATCH); float* part = (ks > 1) ? (float*)((unsigned char*)a->scratch + fixed) : nullptr; - /* THE SECOND PREFILL FORM (hc_pf2_launch), at the 128-row tile only and for the same - * bytes. Its weight planes live in `u`, which no fused form touches, so a band too narrow - * to hold them simply keeps the wide form -- the pin refuses instead, so a test cannot - * pass on the form it did not ask for. */ - const long ntt = (ncol + 15) / 16; - const int pf2 = g_hc_prefill_form >= 3 ? hc_pf2_bits(g_hc_prefill_form - 2) - : (g_hc_prefill_form == 0 && rows >= kPf2MinRows) ? hc_pf2_env() : 0; - const bool pf2_fits = pf2 != 0 && rt == kWideRT && hc == 4 && (n % kThreads) == 0 - && ntt <= (long)((pf2 & kPf2DownW) ? kPf2WMaxNT : kPf2MaxNT) - && (!(pf2 & kPf2UpP) || lr == 20 * 16) - && Mband * HN * 2 >= pf2_plane_bytes(pf2, HN, lr, ntt, f8); - if (g_hc_prefill_form >= 3 && !pf2_fits) return R4D_NO(RAD_E_SHAPE); - if (pf2_fits) { + /* THE SECOND PREFILL FORM (hc_pf2_launch), at the 128-row tile and for the same bytes: + * the rule from kPf2MinRows rows wherever the shape is one it is built for -- hc 4, n a + * multiple of 256, at most kPf2MaxNT column n-tiles -- and the wide form's below that or + * at any other shape. Its weight planes live in `u`, which no fused form touches and which + * the scratch hook sizes for them at every band the rule reaches, so the room check below + * can only refuse the PIN, at a band under kPf2MinRows. The pin refuses a shape the form + * is not built for as well, so a test cannot pass on a form it did not ask for. */ + const long ntt = (ncol + 15) / 16; + const bool pf2_shape = rt == kWideRT && hc == 4 && (n % kThreads) == 0 + && ntt <= (long)kPf2MaxNT; + const bool pf2 = g_hc_prefill_form == 3 + || (g_hc_prefill_form == 0 && rows >= kPf2MinRows && pf2_shape); + if (pf2) { + if (!pf2_shape) return R4D_NO(RAD_E_SHAPE); + if (ubytes < pf2_plane_bytes(HN, lr, ntt, f8)) return R4D_NO(RAD_E_SCRATCH); const int prc = hc_pf2_launch( - pf2, f8, i8, (const unsigned short*)h->data, (const float*)w->data, down->data, + f8, i8, (const unsigned short*)h->data, (const float*)w->data, down->data, (long)dld, up->data, (long)uld, fold ? (const unsigned short*)injw->data : nullptr, dbuf, scale, (unsigned char*)ubuf, part, (unsigned short*)x->data, fold ? (unsigned short*)inj->data : nullptr, diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index d41e255d..c1c715d0 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -879,9 +879,9 @@ __device__ __forceinline__ uint16_t u16_load_w(const uint16_t* p) { * why the median sits near the resident cost and the upper quantiles near one and two misses. * * SO THE LEVER IS THE MISS RATE AND NOTHING ELSE. Residency is 82% of 256 experts a layer and it - * is not raisable here: --expert-vs-cache-ratio already gives the experts everything the KV pool - * does not need, and the KV pool is sized by --max-num-seqs and --max-model-len, which are the - * deployment's capability rather than a tuning knob. If every routed expert were resident this + * is not raisable here: the KV pool lends the experts every block no live request holds, and what + * live requests hold is set by --max-num-seqs and --max-model-len, which are the deployment's + * capability rather than a tuning knob. If every routed expert were resident this * kernel would run at its resident rate and its share of device time would roughly halve. That is * the size of the prize for anything that raises capacity or sharpens the ranking, and it is why * the kernel's own arithmetic is not the lever. @@ -930,8 +930,13 @@ static_assert(sizeof(MoeTab) == 16, "the code table is four words"); * its own activation scale. Same products, same sums, same order: bit-identical to FK 128. * * UW reads the weight and its scales from a uniform global base -- see the UW note at w4_load. + * The decode form always takes it. The prefill forms keep the plain loads: the waits UW removes + * were measured on the decode grid, and the prefill tiles' timing under UW is unmeasured, so + * their instructions stay as they were. * - * RS finds an ES block's run in one round trip -- see the RS note at the run search. */ + * RS finds an ES block's run in one round trip -- see the RS note at the run search. It covers + * up to kMaxExpert experts; a wider expert count takes the chunked search, which numbers the runs + * the same way. */ template @@ -1117,6 +1122,10 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel( rs_first = s_sel[1]; rs_end = s_sel[2]; } else if constexpr (ES) { + /* THE CHUNKED SEARCH SERVES THE DECODE FORM ABOVE kMaxExpert EXPERTS. RS holds a thread's + * share of the offsets in NPT registers sized for kMaxExpert, so a wider expert count is + * this loop's, which walks any count a chunk of NTHR at a time. r4d_selftest runs the + * decode form at 640 experts against the uniform prefill grid, byte for byte. */ __shared__ int32_t s_run[FM]; __shared__ uint32_t s_wc[NTHR / kWave]; uint32_t nrun = 0; @@ -2341,52 +2350,36 @@ constexpr long long kPrefillCols = 128; static inline bool r4d_moe_decode_band(long long T, long long n_expert) { return 2 * T <= 3 * n_expert; } -/* R4D_MOE_GU_FK256: the decode form of the TOKEN-operand projection (gate_up) stages two 128-wide - * K blocks a pass instead of one -- see FK at the kernel. Unset or 0: one block, as upstream. 1: - * every decode-form gate_up launch that can take it; N > 1: those of at most N routed rows. It - * can where the weight's format already folds scale groups (W4 2 to 4) and every class's K is a - * multiple of 256; anything else keeps one block. Bit-identical either way. Read once, so a - * recorded pass and a live one take the same kernel. */ -static long long moe_gu_fk256() { - static const long long v = [] { - const char* e = std::getenv("R4D_MOE_GU_FK256"); - const long long x = e ? std::atoll(e) : 0; - return x > 0 ? x : 0LL; - }(); - return v; -} -/* THE STAGED K OF THE DECODE FORM, pinned for a test: 0 is R4D_MOE_GU_FK256's rule, 1 one 128-wide - * block a pass, 2 two wherever the shape allows it, whatever the switch says. r4d_selftest - * compares the two byte for byte. */ +/* THE ROW LIMIT OF TWO 128-WIDE K BLOCKS A PASS, by weight format: the decode form of the + * TOKEN-operand projection (gate_up) stages two blocks a pass instead of one -- see FK at the + * kernel -- at most this many routed rows. Only a shape whose weight format already folds scale + * groups (W4 2 to 4) and whose every class's K is a multiple of 256 can take two; anything else + * keeps one block. The two are bit-identical. A constant, so a recorded pass and a live one take + * the same kernel. + * + * MEASURED, `r4d_selftest --perfmoe M` on gfx1201 at rank 0's tp2 width split (512 experts, top + * 10), gate_up in us, one block a pass / two: + * + * tokens (rows) 1 (10) 2 (20) 4 (40) 8 (80) 16 (160) 32 (320) + * w4nl64a8h (2) 17.9/15.6 25.6/22.4 36.4/37.3 65.6/67.8 164.6/170.2 328.7/310.8 + * w4nl32a8h (3) 19.5/17.0 26.2/24.0 40.0/40.5 71.6/77.7 177.9/177.5 337.0/321.0 + * w5nl64a8h (4) 20.3/17.6 30.0/25.5 122.3/43.1 212.9/78.6 373.2/219.8 672.3/380.5 + * + * The four-bit formats gain at one and two tokens and not in between, which is where a + * speculative decode step sits (one sequence at depth 3 is 40 rows); the five-bit format's one + * block a pass is two to three times slower from 40 rows on, and two blocks are the faster at + * every row count. */ +template +constexpr long long kMoeGuFk256Rows = W4 == 4 ? (1ll << 40) : (W4 == 2 || W4 == 3) ? 20 : 0; +/* THE STAGED K OF THE DECODE FORM, pinned for a test: 0 is kMoeGuFk256Rows's rule, 1 one 128-wide + * block a pass, 2 two wherever the shape allows it. r4d_selftest compares the two byte for byte, + * so the two-block path is held to the one-block bytes whatever the row limit is. */ static int g_moe_fk_pin = 0; +template static inline bool r4d_moe_gu_fk256(long long T, bool a_sorted) { if (a_sorted || g_moe_fk_pin == 1) return false; if (g_moe_fk_pin == 2) return true; - const long long sw = moe_gu_fk256(); - return sw == 1 || (sw > 1 && T <= sw); -} -/* R4D_MOE_UWLOAD=1: the decode form -- both projections -- reads the weight and its scales from a - * uniform global base (see UW at w4_load). Unset or 0: the generic pointer, as upstream. - * Bit-identical either way; read once, like the others. A test pin over it: 0 the switch, 1 off, - * 2 on. */ -static int g_moe_uw_pin = 0; -static bool r4d_moe_uwload() { - static const bool v = [] { - const char* e = std::getenv("R4D_MOE_UWLOAD"); - return e && std::atoll(e) > 0; - }(); - return g_moe_uw_pin ? g_moe_uw_pin == 2 : v; -} -/* R4D_MOE_RUNSCAN=1: the decode form -- both projections -- finds its block's run in one round - * trip (see RS at the run search). Unset or 0: the chunked search, as upstream. Bit-identical; - * read once. A test pin over it: 0 the switch, 1 off, 2 on. */ -static int g_moe_rs_pin = 0; -static bool r4d_moe_runscan() { - static const bool v = [] { - const char* e = std::getenv("R4D_MOE_RUNSCAN"); - return e && std::atoll(e) > 0; - }(); - return g_moe_rs_pin ? g_moe_rs_pin == 2 : v; + return T <= kMoeGuFk256Rows; } /* THE MAP'S UPPER BOUND, stated once because the scratch hook and the launcher must agree about * it exactly: a hook that answers for a different shape than the launch uses is how a kernel ends @@ -2616,23 +2609,21 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { /* THE DECODE GRID IS (tile, run) WIDE -- see the kernel's ES note. One tile of rows is all * a decode step has, so without this the whole layer runs on N/64 workgroups. */ const unsigned tiles = (unsigned)((T + 15) / 16); - /* WHICH INSTANTIATION: the weight from a uniform global base (R4D_MOE_UWLOAD), the run - * search in one round trip (R4D_MOE_RUNSCAN, up to kMaxExpert experts), and two 128-wide - * K blocks a pass (R4D_MOE_GU_FK256) where every class's K is whole passes of 256 and the - * format folds scale groups. All of them are bit-identical; the function moves with the - * choice, which a recorded pass sees as a new node. */ - const bool uw = r4d_moe_uwload(); - const bool rs = r4d_moe_runscan() && n_expert <= (long long)kMaxExpert; + /* WHICH INSTANTIATION: the weight from a uniform global base (UW) always; the run search + * in one round trip (RS) up to kMaxExpert experts and the chunked search above that; and + * two 128-wide K blocks a pass where kMoeGuFk256Rows admits the row count, every class's + * K is whole passes of 256 and the format folds scale groups. All of them are + * bit-identical; the function moves with the choice, which a recorded pass sees as a new + * node. */ + const bool rs = n_expert <= (long long)kMaxExpert; auto pick = [&](auto fk) { constexpr uint32_t F = decltype(fk)::value; - return uw ? (rs ? &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, true> - : &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true>) - : (rs ? &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, false, true> - : &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F>); + return rs ? &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, true> + : &moe_gemm_q_kernel<1, 4, 1, 4, W4, true, false, false, F, true, false>; }; auto kern = pick(std::integral_constant{}); if constexpr (W4 >= 2) { - bool fk2 = r4d_moe_gu_fk256(T, a_sorted); + bool fk2 = r4d_moe_gu_fk256(T, a_sorted); for (int q = 0; q < ncls; ++q) fk2 = fk2 && Kc[q] % (2 * (long long)kBlock) == 0; if (fk2) kern = pick(std::integral_constant{}); } @@ -2732,8 +2723,6 @@ extern "C" int64_t r4d_rad_moe_gemm_w4a8_scratch(const RadArgs* a) { return moe_ extern "C" void r4d_moe_gemm_pin_prefill(int form) { g_moe_prefill_form = form; } extern "C" void r4d_moe_gemm_pin_fk(int pin) { g_moe_fk_pin = pin; } -extern "C" void r4d_moe_gemm_pin_uw(int pin) { g_moe_uw_pin = pin; } -extern "C" void r4d_moe_gemm_pin_rs(int pin) { g_moe_rs_pin = pin; } extern "C" int r4d_rad_moe_gemm_q(const RadArgs* a, RadStream s) { return moe_gemm_launch<0>(a, r4d_stream_sink(s)); @@ -3000,8 +2989,8 @@ extern "C" int r4d_rad_scale_rows(const RadArgs* a, RadStream s) { /* ================================================================== router GEMM + router_topk_scatter * * THE ROUTER, ITS SELECTION AND ITS SORT IN ONE LAUNCH -- and, where the layer has a shared expert, - * that expert's one-column gate beside them. rad_block_moe_fp8.h declares it under - * R4D_ROUTER_FUSED; this is the kernel and its shim. + * that expert's one-column gate beside them. rad_block_moe_fp8.h asks for it wherever it declares + * router_topk_scatter and issues it up to kRgMaxM rows; this is the kernel and its shim. * * At a decode step the router is a [n_expert, n_embd] bf16 GEMM over a handful of rows, and what * follows it -- `router_topk_scatter` -- is one workgroup with almost no work in it. They are two @@ -3009,7 +2998,8 @@ extern "C" int r4d_rad_scale_rows(const RadArgs* a, RadStream s) { * gap plus a second launch, on the critical path. The selection needs every logit of a row, so it * cannot run inside a column tile; it runs in whichever workgroup finishes LAST, which an arrival * counter names. That is the device-wide pattern gemm_fp8a8's split-K finisher and hc_up_mix's - * quantiser already use, and its rule is theirs: one counter a (stream, output), self-resetting. + * quantiser already use, and its rule is theirs: self-resetting, and never shared by two launches + * that can run at once. Here it is the op instance's, taken at init -- see THE ARRIVAL COUNTER. * * The shared expert's gate is a gemm_nt at N = 1 over the SAME input, a launch of its own for one * output column. It rides along as one more workgroup of this grid (`skg` > 0), so the launch the @@ -3175,27 +3165,87 @@ __global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel( scatter_small_place(sorted, off, cnt, g.M * g.top_k, g.n_local, sl); } +/* THE ARRIVAL COUNTER IS THE OP INSTANCE'S, taken at init and not on the launch path. + * + * It has to persist between launches, zeroed: the last block of every launch resets it, and a + * launch that found it non-zero would rank before the GEMM was done. A scratch hook cannot carry + * that -- the scratch is one arena region every other op's kernel writes between two of these + * launches. The other counters in this library (gemm_fp8a8's split_ctr, hc_bf16's mix counters) + * are allocated on first use from the launch path, which leaves them out of the VRAM budget and + * puts an allocation on the describe path that must not allocate. The init hook has neither + * problem: the engine calls it once per resolved instance during declare, on the rank's device, + * and reads the free VRAM for its budget after every init has run, so what init takes is + * counted. + * + * ONE COUNTER AN INSTANCE -- one declared op, one band, one domain, one rank. Each routed layer + * declares its own op, so two layers never share one, and the launches of one instance are + * ordered: every one of them writes the same declared sort outputs, which the engine does not + * reorder or overlap. The counters are 64-byte slots of one zeroed block a device, so a model's + * few hundred instances cost one allocation; the block is freed with its last instance. */ +constexpr uint32_t kRgCtrStride = 16; /* uint32 words a slot: one 64-byte line each */ +constexpr uint32_t kRgCtrSlots = 4096; /* instances a device; a model declares hundreds */ + +struct RgCtrBlock { + unsigned int* base = nullptr; + uint32_t next = 0; /* slots handed out since the block was made */ + uint32_t live = 0; /* instances holding one */ +}; +struct RgInst { + int dev = 0; + unsigned int* ctr = nullptr; +}; +std::mutex g_rg_mu; +std::map g_rg_blocks; + } /* namespace */ -/* THE ARRIVAL COUNTER, one a (stream, logits buffer): ctx.h's rule TWO, and gemm_fp8a8's split_ctr - * says why the output is part of the key. Launches that share a logits buffer on one stream are - * ordered through it -- every routed layer writes the same plane -- so they reuse one counter. - * Zeroed once and reset by the last block of every launch. Null when it cannot be allocated; the - * op then refuses rather than computing without it. */ -static unsigned int* router_fused_ctr(RadStream s, const void* out) { - static std::mutex m; - static std::map, unsigned int*> blocks; - std::lock_guard lk(m); - const auto key = std::make_pair(s, out); - if (auto it = blocks.find(key); it != blocks.end()) return it->second; - void* p = nullptr; - if (hipMalloc(&p, 64) != hipSuccess) return nullptr; - if (hipMemset(p, 0, 64) != hipSuccess) { - (void)hipFree(p); - return nullptr; +extern "C" int r4d_rad_router_gemm_topk_scatter_init(const RadParam*, int, int, int, + void** out) { + if (!out) return RAD_E_INVAL; + *out = nullptr; + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE; + std::lock_guard lk(g_rg_mu); + RgCtrBlock& blk = g_rg_blocks[dev]; + if (!blk.base) { + const size_t bytes = (size_t)kRgCtrSlots * kRgCtrStride * sizeof(unsigned int); + void* p = nullptr; + if (hipMalloc(&p, bytes) != hipSuccess) return RAD_E_NOMEM; + /* Zero before any launch can read it: the memset is ordered on the null stream, and the + * engine's streams need not wait for that one, so it is waited for here. */ + if (hipMemset(p, 0, bytes) != hipSuccess || hipDeviceSynchronize() != hipSuccess) { + (void)hipFree(p); + return RAD_E_DEVICE; + } + blk.base = (unsigned int*)p; + blk.next = 0; } - blocks.emplace(key, (unsigned int*)p); - return (unsigned int*)p; + /* A slot is never handed out twice while its block lives: one returned by fini is not known + * to be zero if its last launch did not finish, so it is not reused. */ + if (blk.next >= kRgCtrSlots) return RAD_E_FULL; + RgInst* in = new RgInst; + in->dev = dev; + in->ctr = blk.base + (size_t)blk.next * kRgCtrStride; + ++blk.next; + ++blk.live; + *out = in; + return RAD_OK; +} + +extern "C" void r4d_rad_router_gemm_topk_scatter_fini(void* inst) { + RgInst* in = (RgInst*)inst; + if (!in) return; + std::lock_guard lk(g_rg_mu); + auto it = g_rg_blocks.find(in->dev); + if (it != g_rg_blocks.end() && it->second.live > 0 && --it->second.live == 0) { + int prev = 0; + const bool moved = hipGetDevice(&prev) == hipSuccess && prev != in->dev && + hipSetDevice(in->dev) == hipSuccess; + (void)hipFree(it->second.base); + if (moved) (void)hipSetDevice(prev); + g_rg_blocks.erase(it); + } + delete in; } /* Operands: a, b (the router), gate_b? -> logits, expert_ids, expert_w, sorted_tok, @@ -3267,8 +3317,11 @@ static int rad_router_gemm_topk_scatter_body(const RadArgs* a, const R4dSink& sk rc = cfg_for(a, K, M, 16, BR_FLAT, &cg, 1); if (rc != RAD_OK) return rc; } - unsigned int* const ctr = router_fused_ctr(sk.stream, lg->data); - if (!ctr) return R4D_NO(RAD_E_DEVICE); + /* The instance's counter (see THE ARRIVAL COUNTER). A caller that ran no init has none, and + * the op is refused: a launch without it would have no last block to rank. */ + const RgInst* const inst = (const RgInst*)a->instance; + if (!inst || !inst->ctr) return R4D_NO(RAD_E_STATE); + unsigned int* const ctr = inst->ctr; /* THE WAVE COUNT IS THE SELECTION'S, router_topk_scatter's rule: a wave a row up to 32. The * GEMM then takes as many 16-column tiles a block as fills those waves at its split. */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index bf8b160e..094659f6 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -227,7 +227,10 @@ int r4d_rad_moe_scatter (const RadArgs*, RadStream); int r4d_rad_router_topk_scatter(const RadArgs*, RadStream); int r4d_rad_router_topk_scatter_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); /* The router GEMM, the selection and the sort in one launch, the shared gate optionally beside - * them (R4D_ROUTER_FUSED in rad_block_moe_fp8.h). */ + * them. init takes the instance's arrival counter (r4d_moe.hip, THE ARRIVAL COUNTER) and fini + * gives it back; a launch with no instance is refused. */ +int r4d_rad_router_gemm_topk_scatter_init(const RadParam*, int, int rank, int world, void** out); +void r4d_rad_router_gemm_topk_scatter_fini(void*); int r4d_rad_router_gemm_topk_scatter(const RadArgs*, RadStream); int r4d_rad_router_gemm_topk_scatter_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index f57220db..927bf783 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -4405,7 +4405,8 @@ static const RadKernelInfo kKernels[] = { "sorted slots, offsets and counts out", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cRouterGemmTopkScatter), NOTUNE, - nullptr, nullptr, r4d_rad_router_gemm_topk_scatter, nullptr, nullptr, nullptr, + r4d_rad_router_gemm_topk_scatter_init, r4d_rad_router_gemm_topk_scatter_fini, + r4d_rad_router_gemm_topk_scatter, nullptr, nullptr, nullptr, r4d_shape_router_gemm_topk_scatter, nullptr, nullptr, r4d_rad_router_gemm_topk_scatter_describe }, @@ -5099,9 +5100,11 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) { * gemm_w8a8_tiled * every collective the peer flags and exchange buffers the all-reduces own * - * gemm_fp8a8_nt_m16's finisher counters are keyed on the stream AND the output, so two launches - * that could run at once never share them, and the row is concurrent. A row added with state of - * its own that the stream's order protects belongs in this list. */ + * gemm_fp8a8_nt_m16's finisher counters are keyed on the stream AND the output, and + * router_gemm_topk_scatter_bf16's arrival counter is its op instance's (taken at init, one a + * declared op and band), so two launches that could run at once never share them, and both rows + * are concurrent. A row added with state of its own that the stream's order protects belongs in + * this list. */ extern "C" int rad_kernel_concurrent(int i) { const RadKernelInfo* k = rad_kernel_at(i); if (!k) return 0; diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 303521ad..cf89aae7 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -163,8 +163,6 @@ struct Plugin { void (*pin_qsa)(int) = nullptr; void (*pin_moe)(int) = nullptr; void (*pin_fk)(int) = nullptr; - void (*pin_uw)(int) = nullptr; - void (*pin_rs)(int) = nullptr; void (*pin_hc)(int) = nullptr; void (*pin_qsel)(int) = nullptr; }; @@ -196,8 +194,6 @@ static bool load(Plugin* pl, const char* path) { okall &= sym(pl->h, "r4d_qsa_score_pin_form", &pl->pin_qsa); okall &= sym(pl->h, "r4d_moe_gemm_pin_prefill", &pl->pin_moe); okall &= sym(pl->h, "r4d_moe_gemm_pin_fk", &pl->pin_fk); - okall &= sym(pl->h, "r4d_moe_gemm_pin_uw", &pl->pin_uw); - okall &= sym(pl->h, "r4d_moe_gemm_pin_rs", &pl->pin_rs); okall &= sym(pl->h, "r4d_hc_read_pin_prefill", &pl->pin_hc); okall &= sym(pl->h, "r4d_qsa_select_pin_form", &pl->pin_qsel); return okall; @@ -672,7 +668,7 @@ static std::vector with_point(const std::vector& ps, const T * whose data is null, sizes and allocates scratch from the row's own hook, then synchronises so a * launch failure is attributed here and not to whatever runs next. */ static void run_case(const RadKernelInfo* r, std::vector& ts, - std::vector& ps, int expect = RAD_OK) { + std::vector& ps, int expect = RAD_OK, void* instance = nullptr) { for (auto& t : ts) if (!t.data && t.rank) t.data = alloc_for(t); RadArgs a; @@ -680,6 +676,7 @@ static void run_case(const RadKernelInfo* r, std::vector& ts, a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; + a.instance = instance; if (r->scratch) { const int64_t need = r->scratch(&a); @@ -1816,8 +1813,9 @@ static void topk_scatter_at(const RadKernelInfo* rf, const RadKernelInfo* rt, * * AND TWICE, BACK TO BACK, ON ONE OUTPUT. The last workgroup is named by a counter that resets * itself; a counter left behind by one launch would make the next one rank before the GEMM was - * done, or never. The configurations share one logits buffer -- and with it one counter -- in - * an order that changes the grid between consecutive launches. */ + * done, or never. The counter is the instance's, taken by the row's init as the engine takes it, + * and every launch here shares that one instance -- and with it one counter -- in an order that + * changes the grid between consecutive launches. A launch with no instance is refused. */ static void router_gemm_fused_case(const Plugin& pl) { if (!sel("router_gemm_topk_scatter_bf16")) return; const RadKernelInfo* rg = find(pl, "router_gemm_topk_scatter_bf16"); @@ -1863,6 +1861,16 @@ static void router_gemm_fused_case(const Plugin& pl) { ok("router_gemm_topk_scatter", false, "hipMalloc failed"); return; } + void* inst = nullptr; + { + std::vector ip = { PI("M", maxM), PI("K", maxK), PI("n_expert", maxNe), + PI("top_k", 10), PI("norm", 1), PS("dtype", "bf16") }; + const int irc = rg->init && rg->fini + ? rg->init(ip.data(), (int)ip.size(), 0, 1, &inst) : RAD_E_INVAL; + ok("router_gemm_topk_scatter init takes an instance", irc == RAD_OK && inst != nullptr, + "rc=" + std::to_string(irc)); + if (irc != RAD_OK || !inst) return; + } for (const RgCase& c : cfgs) { /* A trained router's logits are a few units wide; these are about that, with a tie @@ -1948,7 +1956,7 @@ static void router_gemm_fused_case(const Plugin& pl) { st_memset(d_so[1], 0xFF, (size_t)maxNS * 4); st_memset(d_of[1], 0xFF, (size_t)(maxNe + 1) * 4); } - run_case(rg, ts, ps); + run_case(rg, ts, ps, RAD_OK, inst); const std::string tag = at + (rep ? ", second launch" : ""); auto same = [&](const char* what, void* a, void* b, size_t bytes) { @@ -1990,8 +1998,26 @@ static void router_gemm_fused_case(const Plugin& pl) { T(nullptr, RAD_BF16, { M, 1 }) }; std::vector ps = { PI("M", M), PI("K", 2560), PI("n_expert", 512), PI("top_k", 10), PI("norm", 1), PS("dtype", "bf16") }; - run_case(rg, ts, ps, RAD_E_SHAPE); + run_case(rg, ts, ps, RAD_E_SHAPE, inst); } + /* A served shape with no instance is refused: there is no counter to name the last block. */ + { + const int64_t M = 4; + std::vector ts = { T(d_a, RAD_BF16, { M, 2560 }), + T(d_w, RAD_BF16, { 512, 2560 }), + T(d_wg, RAD_BF16, { 1, 2560 }), + T(d_lg[1], RAD_BF16, { M, 512 }), + T(d_id[1], RAD_I32, { M, 10 }), + T(d_ew[1], RAD_BF16, { M, 10 }), + T(d_so[1], RAD_I32, { M * 10 }), + T(d_of[1], RAD_I32, { 513 }), + T(d_cn[1], RAD_I32, { 512 }), + T(d_g[1], RAD_BF16, { M, 1 }) }; + std::vector ps = { PI("M", M), PI("K", 2560), PI("n_expert", 512), + PI("top_k", 10), PI("norm", 1), PS("dtype", "bf16") }; + run_case(rg, ts, ps, RAD_E_STATE); + } + rg->fini(inst); } /* THE PROTECTED EXPERTS ARE SORTED LAST, against a host stable sort by place. A layer that keeps a @@ -5090,7 +5116,10 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, struct Proj { const char* name; int64_t N0, K0, N1, K1, parts; bool srt; }; const Proj projs[2] = { { "gate_up", 768, 2560, 512, 2560, 2, false }, { "down", 2560, 384, 2560, 256, 1, true } }; - const int nforms = pl.pin_moe ? 3 : 1; + /* Form 4, where the plugin has the pin, is the decode form at two 128-wide K blocks a pass: + * the timing kMoeGuFk256Rows is set from. Only gate_up has it (K a multiple of 256 and a + * format that folds scale groups); elsewhere it runs as form 2. */ + const int nforms = pl.pin_moe ? (pl.pin_fk ? 4 : 3) : 1; for (const Proj& P : projs) { const int64_t N = std::max(P.N0, P.N1), K = std::max(P.K0, P.K1), kb = K / group; const int64_t Ma = P.srt ? Tr : Mtok; @@ -5225,7 +5254,8 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, const std::string pname = std::string(P.name) + (w5 ? " w5" : sub == 4 ? " g32" : g64 ? " g64" : ""); for (int f = 0; f < nforms; ++f) { - if (pl.pin_moe) pl.pin_moe(f + 1); + if (pl.pin_moe) pl.pin_moe(f == 3 ? 2 : f + 1); + if (pl.pin_fk) pl.pin_fk(f == 3 ? 2 : 1); const int rc = r->launch(&a, nullptr); if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { std::printf(" %-12s form %d rc=%d (not served)\n", pname.c_str(), f + 1, rc); @@ -5275,9 +5305,14 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, } } if (pl.pin_moe) pl.pin_moe(0); + if (pl.pin_fk) pl.pin_fk(0); } } +/* The launcher's kPf2MinRows: from this band the rule takes the PF2 form and the scratch hook + * sizes `u` for its weight planes; below it the pin to PF2 is refused. */ +static constexpr int64_t kHcPf2MinRows = 512; + /* THE GATED RESIDUAL'S READ AT INT8 CODES. The same inputs run twice, the codes plane once E4M3 * and once I8: the bf16 block input and the rotated E4M3 twin must come out byte-identical -- the * codes' format is the only thing the dtype changes -- and the int8 codes must be the bf16 input @@ -5325,12 +5360,7 @@ static void hc_read_i8(const Plugin& pl, int64_t M, bool real_stream, int form) void* d_rq = dalloc(qb); void* d_rs = dalloc(sb); static const char* const kForm[] = { "the launcher's rule", "the decode tiles' kernels", - "the wide kernels", "the PF2 kernels", - "the PF2 down product", "the PF2 up product", - "the PF2 kernels at 128 rows", - "the PF2 down and persistent up products", - "the PF2 128-row down and persistent up products", - "the PF2 persistent up product" }; + "the wide kernels", "the PF2 kernels" }; const std::string nm = fmt("hc_read_e4m3 int8 codes at M=%lld (%s, %s)", (long long)M, real_stream ? "a real stream" : "the null stream", kForm[form]); if (!d_h || !d_w || !d_dn || !d_up || !d_iw || !d_x || !d_inj || !d_q || !d_qs || !d_rq || !d_rs) { @@ -5409,13 +5439,18 @@ static void hc_read_i8(const Plugin& pl, int64_t M, bool real_stream, int form) * split. Random codes and small positive scales: what is timed is the traffic and the arithmetic. * * EVERY FORM OF THE PREFILL TILE is run -- the decode tiles' kernels at 128 rows, the wide kernels - * and, where the band can hold their weight planes, the PF2 kernels, through the - * r4d_hc_read_pin_prefill hook -- and their outputs compared BYTE FOR BYTE, which is what the wide - * and the PF2 kernels claim. `timed` times each form as well. */ -static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed) { + * and, from kHcPf2MinRows rows, the PF2 kernels, through the r4d_hc_read_pin_prefill hook -- and + * their outputs compared BYTE FOR BYTE, which is what the wide and the PF2 kernels claim. `timed` + * times each form as well. + * + * `f8` picks the row: hc_read_e4m3, or hc_read_bf16 over bf16 mixing matrices. Both enter the same + * launcher and both reach PF2, whose prologue then copies mix_down where it decodes it at E4M3 and + * whose up product reads the stored mix_up where it reads a decoded one -- a path of its own. */ +static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool f8 = true) { if (iters <= 0) iters = 20; - const RadKernelInfo* r = find(pl, "hc_read_e4m3"); - if (!r) { skip("hc_read_e4m3 prefill forms", "row absent"); return; } + const char* const rn = f8 ? "hc_read_e4m3" : "hc_read_bf16"; + const RadKernelInfo* r = find(pl, rn); + if (!r) { skip(fmt("%s prefill forms", rn).c_str(), "row absent"); return; } const int64_t n = 2560, hc = 4, lr = 320, HN = hc * n, grp = 128; const int64_t dld = r4d_hc8::row_bytes(HN, r4d_hc8::down_group(HN)); const int64_t uld = r4d_hc8::row_bytes(lr, r4d_hc8::up_group(lr)); @@ -5436,8 +5471,16 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed) { } return b; }; - std::vector down = plane(lr, HN, r4d_hc8::down_group(HN), dld); - std::vector up = plane(HN, lr, r4d_hc8::up_group(lr), uld); + /* bf16 weights of the E4M3 planes' magnitude: |w| up to 0.25. */ + auto bplane = [&](int64_t count) { + std::vector b((size_t)(count * 2)); + uint16_t* v = (uint16_t*)b.data(); + for (int64_t i = 0; i < count; ++i) + v[i] = h_to_bf16((float)((int)(rnd() % 2001) - 1000) / 4000.0f); + return b; + }; + std::vector down = f8 ? plane(lr, HN, r4d_hc8::down_group(HN), dld) : bplane(lr * HN); + std::vector up = f8 ? plane(HN, lr, r4d_hc8::up_group(lr), uld) : bplane(HN * lr); std::vector injw((size_t)(hc * HN)); for (auto& v : injw) v = h_to_bf16((float)((int)(rnd() % 201) - 100) / 50000.0f); @@ -5455,7 +5498,7 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed) { void* d_rq = dalloc(qb); void* d_rs = dalloc(sb); if (!d_h || !d_w || !d_dn || !d_up || !d_iw || !d_x || !d_inj || !d_q || !d_qs || !d_rq || !d_rs) { - ok("hc_read_e4m3 prefill forms: allocation", false); + ok(fmt("%s prefill forms: allocation", rn).c_str(), false); return; } st_memcpy(d_h, hh.data(), hh.size() * 2, hipMemcpyHostToDevice); @@ -5466,9 +5509,10 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed) { /* The mixing matrices arrive at their DECLARED shape with the stored dtype, as the engine * hands them; the launcher derives the stored row pitch itself. */ + const uint32_t mdt = f8 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16; std::vector ts = { T(d_h, RAD_BF16, { M, HN }), T(d_w, RAD_F32, { HN }), - T(d_dn, RAD_F8E4M3, { lr, HN }), T(d_up, RAD_F8E4M3, { HN, lr }), + T(d_dn, mdt, { lr, HN }), T(d_up, mdt, { HN, lr }), T(d_iw, RAD_BF16, { hc, HN }), T(d_x, RAD_BF16, { M, n }), T(d_inj, RAD_BF16, { M, hc }), T(d_q, RAD_F8E4M3, { M, n }), T(d_qs, RAD_F32, { M, n / grp }), T(d_rq, RAD_F8E4M3, { M, n }), @@ -5477,7 +5521,7 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed) { std::vector ps = { PI("M", M), PI("n", n), PI("hc", hc), PI("lowrank", lr), PF("eps", 1e-6), PS("dtype", "bf16"), PF("wadd", 1.0), PI("inject", 1), PI("group", grp), - PI("rotate", 1), PS("mix", "e4m3"), + PI("rotate", 1), PS("mix", f8 ? "e4m3" : "bf16"), }; RadArgs a; std::memset(&a, 0, sizeof(a)); @@ -5490,21 +5534,16 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed) { /* A REAL STREAM, because the op keys per-stream state on it -- the fused forms' arrival * counters -- and on the null stream it finds none and takes the unfused path. */ hipStream_t hs = nullptr; - if (hipStreamCreate(&hs) != hipSuccess) { ok("hc_read_e4m3 prefill forms: stream", false); return; } + if (hipStreamCreate(&hs) != hipSuccess) { + ok(fmt("%s prefill forms: stream", rn).c_str(), false); + return; + } const RadStream rst = (RadStream)hs; struct Out { std::vector x, inj, q, qs, rq, rs; }; - /* PF2 keeps its two weight planes in the band's `u` buffer, M * hc * n bf16: they need - * ceil((lr + hc) / 16) * 16 + lr rows of it, so a smaller M is the wide form's alone. */ - const int64_t pf2_min_m = ((lr + hc + 15) / 16) * 16 + lr; - const int f_lo = pl.pin_hc ? 1 : 0, f_hi = pl.pin_hc ? (M >= pf2_min_m ? 9 : 2) : 0; + const int f_lo = pl.pin_hc ? 1 : 0, f_hi = pl.pin_hc ? (M >= kHcPf2MinRows ? 3 : 2) : 0; static const char* const kForm[] = { "the launcher's rule", "the decode tiles' kernels", - "the wide kernels", "the PF2 kernels", - "the PF2 down product", "the PF2 up product", - "the PF2 kernels at 128 rows", - "the PF2 down and persistent up products", - "the PF2 128-row down and persistent up products", - "the PF2 persistent up product" }; + "the wide kernels", "the PF2 kernels" }; std::vector outs; for (int form = f_lo; form <= f_hi; ++form) { if (pl.pin_hc) pl.pin_hc(form); @@ -5512,7 +5551,7 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed) { st_memset(d_qs, 0, sb); st_memset(d_rq, 0, qb); st_memset(d_rs, 0, sb); const int rc = r->launch(&a, rst); if (rc != RAD_OK || st_stream_sync(hs) != hipSuccess) { - ok(fmt("hc_read_e4m3 prefill form '%s' at M=%lld is served", kForm[form], + ok(fmt("%s prefill form '%s' at M=%lld is served", rn, kForm[form], (long long)M).c_str(), false, fmt("rc=%d", rc)); if (pl.pin_hc) pl.pin_hc(0); (void)hipStreamDestroy(hs); @@ -5538,8 +5577,8 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed) { /* A zero output would pass a byte comparison between two forms that both wrote nothing. */ size_t nz = 0; for (uint8_t v : outs[f].q) nz += v != 0; - ok(fmt("hc_read_e4m3 prefill tile at M=%lld, %s: byte-identical to the decode tiles' " - "kernels", (long long)M, what).c_str(), + ok(fmt("%s prefill tile at M=%lld, %s: byte-identical to the decode tiles' kernels", rn, + (long long)M, what).c_str(), bad.empty() && nz > qb / 2, bad.empty() ? fmt("%zu of %zu codes non-zero", nz, qb) : "differs in" + bad); }; @@ -5570,8 +5609,8 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed) { st_ev_destroy(e0); st_ev_destroy(e1); const double us = (double)ms * 1000.0 / iters; const double flop = 2.0 * (double)M * (double)HN * (double)(2 * lr + hc); - std::printf("hc_read_e4m3 at M=%lld (n %lld, hc %lld, lowrank %lld, inject, fp8 twin + " - "rotated), %s: %.1f us a call, %.1f TFLOP/s\n", (long long)M, + std::printf("%s at M=%lld (n %lld, hc %lld, lowrank %lld, inject, fp8 twin + " + "rotated), %s: %.1f us a call, %.1f TFLOP/s\n", rn, (long long)M, (long long)n, (long long)hc, (long long)lr, kForm[form], us, flop / (us * 1e6)); } @@ -6072,43 +6111,30 @@ static float st_e4m3(uint8_t b) { * its part and its down projection reads a shorter K. */ struct MoeW4Shape { const char* name; int64_t N0, K0, N1, K1, parts, ne; }; -/* THE DECODE FORM'S BIT-IDENTICAL VARIANTS, each against the default, byte for byte: the weight from - * a uniform global base (R4D_MOE_UWLOAD), the run search in one round trip (R4D_MOE_RUNSCAN), two - * 128-wide K blocks a pass (R4D_MOE_GU_FK256), and every combination. Every launch is DESCRIBED - * first: a variant that named the default's kernel would match it trivially, so two pins naming - * one function is a failure, not a pass. `fk2` is whether this shape can take two blocks a pass -- - * the token operand, a format that folds scale groups, every class's K a multiple of 256; the - * other two are open to every shape. The default here is PINNED, so an R4D_MOE_* switch in the - * environment cannot make the comparison one variant against itself. +/* THE DECODE FORM'S STAGED K, BOTH WAYS, byte for byte: one 128-wide K block a pass and two. Every + * launch is DESCRIBED first: a pin that named the other's kernel would match it trivially, so two + * pins naming one function is a failure, not a pass. `fk2` is whether this shape can take two + * blocks a pass -- the token operand, a format that folds scale groups, every class's K a multiple + * of 256; a shape that cannot has one form only, which the form loop already held to the host + * decode. Both launches are PINNED, so the launcher's row limit cannot make the comparison one form + * against itself. * * A row with no describe hook -- moe_gemm_fp8a8_mod4 -- is compared on its bytes alone, and says * so in its label: that the variant ran is then not shown, only that what ran agrees. */ static void moe_dec_variants(const Plugin& pl, const RadKernelInfo* row, RadArgs& a, void* d_y, size_t elems, bool fk2, const std::string& what) { - if (!pl.pin_fk || !pl.pin_uw || !pl.pin_rs || !pl.pin_moe) return; + if (!fk2 || !pl.pin_fk || !pl.pin_moe) return; const bool described = row->describe != nullptr; - struct Var { int uw, rs, fk; const char* name; }; - static const Var kVar[] = { - { 1, 1, 1, "as upstream" }, - { 2, 1, 1, "uniform weight base" }, - { 1, 2, 1, "one-pass run search" }, - { 2, 2, 1, "uniform weight base, one-pass run search" }, - { 1, 1, 2, "two K blocks a pass" }, - { 2, 1, 2, "uniform weight base, two K blocks a pass" }, - { 1, 2, 2, "one-pass run search, two K blocks a pass" }, - { 2, 2, 2, "uniform weight base, one-pass run search, two K blocks a pass" }, - }; + struct Var { int fk; const char* name; }; + static const Var kVar[] = { { 1, "one K block a pass" }, { 2, "two K blocks a pass" } }; constexpr int kN = (int)(sizeof(kVar) / sizeof(kVar[0])); const void* fn[kN] = {}; std::vector base; for (int v = 0; v < kN; ++v) { - if (kVar[v].fk == 2 && !fk2) continue; const std::string label = what + " decode form, " + kVar[v].name + (described ? "" : " (launch not described)"); auto pin = [&](bool on) { pl.pin_moe(on ? 2 : 0); - pl.pin_uw(on ? kVar[v].uw : 0); - pl.pin_rs(on ? kVar[v].rs : 0); pl.pin_fk(on ? kVar[v].fk : 0); }; if (described) { @@ -6390,7 +6416,20 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int " elements off, worst " + std::to_string(worst) + first); two_cls[form] = got; } - /* The decode form's variants; two K blocks a pass where the switch can take this shape. */ + /* THE DECODE FORM AGAINST THE UNIFORM PREFILL GRID, byte for byte. Every form keeps each + * output element's accumulation order, so the bytes agree exactly, not within the host + * decode's tolerance. The decode form finds its runs by the one-round-trip search up to 512 + * experts and by the chunked search above that; the uniform grid walks the offsets from a + * binary search, so this holds whichever search the expert count picks to a third way of + * finding the same runs. */ + if (!two_cls[2].empty() && !two_cls[3].empty()) { + int64_t diff = 0; + for (size_t i = 0; i < two_cls[2].size(); ++i) diff += two_cls[2][i] != two_cls[3][i]; + ok((what + " decode form, byte for byte with the uniform prefill grid").c_str(), + diff == 0, std::to_string(diff) + " of " + std::to_string(Tr * N) + + " elements differ"); + } + /* The decode form's staged K both ways, where this shape can take two blocks a pass. */ const bool fk2 = g64 && sh.K0 % 256 == 0 && sh.K1 % 256 == 0; moe_dec_variants(pl, r, a, d_y, (size_t)(Tr * N), fk2, what); if (!four) return; @@ -10587,6 +10626,10 @@ static void device_phase(const Plugin& pl) { /* Three passes of 256 along K: the decode form's two-block pass then also runs its * one-ahead prefetch, which a single pass never reaches. */ { "40 experts, gate/up 2:1, K 768", 256, 768, 128, 768, 2, 40 }, + /* Past 512 experts: the decode form's chunked run search, which the one-round-trip + * search hands every wider expert count to. Runs land on experts on both sides of + * 512, and K 256 lets the two-block pass run on that search as well. */ + { "640 experts, gate/up 2:1, K 256", 256, 256, 128, 256, 2, 640 }, }; for (const MoeW4Shape& sh : kShapes) { moe_w4_gemm(pl, 24, sh); @@ -10611,6 +10654,7 @@ static void device_phase(const Plugin& pl) { { "down 2:1", 64, 256, 64, 128, 1, 10 }, { "300 experts, gate/up 2:1", 256, 128, 128, 128, 2, 300 }, { "40 experts, gate/up 2:1, K 768", 256, 768, 128, 768, 2, 40 }, + { "640 experts, gate/up 2:1, K 256", 256, 256, 128, 256, 2, 640 }, }; for (const MoeW4Shape& sh : kShapes4) for (const int64_t t : { (int64_t)24, (int64_t)200, (int64_t)600 }) { @@ -10635,22 +10679,27 @@ static void device_phase(const Plugin& pl) { } if (sel("hc_read_e4m3")) { - if (!g_case) std::printf("\nthe gated residual's read at the prefill tile, the wide " - "kernels against the decode tiles'\n"); + if (!g_case) std::printf("\nthe gated residual's read at the prefill tile, every form " + "against the decode tiles'\n"); /* 700 and 1000 put PF2's K chunks across a stream boundary and its row tiles past the * last row; 4096 is the one-chunk epilogue. */ for (int64_t m : { 65, 300, 700, 1000, 2048, 4096 }) hc_prefill(pl, m, 0, false); - for (int64_t m : { 1, 4, 33, 65, 300, 2048 }) { + /* 1 to 7 rows are one up-product row group each, every instantiation below eight. */ + for (int64_t m : { 1, 2, 3, 4, 5, 6, 7, 33, 65, 300, 2048 }) { hc_read_i8(pl, m, false, 0); hc_read_i8(pl, m, true, 0); } if (pl.pin_hc) { for (int64_t m : { 65, 2048 }) for (int form : { 1, 2 }) hc_read_i8(pl, m, true, form); - for (int64_t m : { 700, 2048 }) - for (int form = 3; form <= 9; ++form) hc_read_i8(pl, m, true, form); + for (int64_t m : { 700, 2048 }) hc_read_i8(pl, m, true, 3); } } + if (sel("hc_read_bf16")) { + if (!g_case) std::printf("\nthe gated residual's read over bf16 mixing matrices at the " + "prefill tile, every form against the decode tiles'\n"); + for (int64_t m : { 300, 700, 2048 }) hc_prefill(pl, m, 0, false, false); + } if (sel("moe_gemm_w4a8")) { if (!g_case) std::printf("\nthe arranged plane, against the stated format and its " @@ -10934,7 +10983,7 @@ static void usage(void) { " rows -- at one shape, each with its TFLOP/s.\n" " --perfw2 N K M [iters]: the int2 DFlash2 draft head at every variant it has.\n" " --perfhc M [iters]: hc_read_e4m3 at Qwen3.8-Flash-Next's shape and M rows, every\n" - " prefill-tile form (PF2 from M=656) compared byte for byte and timed\n" + " prefill-tile form (PF2 from M=512) compared byte for byte and timed\n" " as one op each;\n" " run it under libr4d/isa/trace.sh for its launches.\n" " --perfmoe M [iters] [experts] [top_k] [pooled%%]: the routed-expert w4 GEMM,\n" diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 93ef2911..23480654 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -1293,7 +1293,9 @@ extern "C" int r4d_shape_router_gemm_topk_scatter(const RadParam* p, int n_p, in const int64_t K = pi(p, n_p, "K"); const int64_t ne = pi(p, n_p, "n_expert"); const int64_t k = pi(p, n_p, "top_k"); - if (ne <= 0 || ne > 256 || k <= 0 || k > ne || K <= 0) return RAD_E_UNSUPPORTED; + /* 512 experts: the selection keeps sixteen logits a lane (kMaxExpert in r4d_moe.hip), which + * is the shim's bound and the row's constraint. */ + if (ne <= 0 || ne > 512 || k <= 0 || k > ne || K <= 0) return RAD_E_UNSUPPORTED; if (M > 64 || M * k > 1024) return RAD_E_UNSUPPORTED; const int64_t nl = pi(p, n_p, "n_local", ne); if (nl <= 0 || nl > ne) return RAD_E_UNSUPPORTED; diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index e94cf0b2..e4087203 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -307,6 +307,25 @@ int ref_silu(const RadArgs* a, RadStream) { return unary(a, 1); } * it that expert runs ungated, which is a different model and not a slower one. */ int ref_sigmoid(const RadArgs* a, RadStream) { return unary(a, 2); } +/* ------------------------------------------------------------------ fill */ +/* y = value over [M, n], at y's own row pitch. The value is rounded once, by the store. */ +int ref_fill(const RadArgs* a, RadStream) { + if (!have(a, 1)) return RAD_E_INVAL; + const RadTensor* y = &a->t[0]; + const int64_t n = p_int(a, "n", numel(y)); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n); + if (rows <= 0) return RAD_E_SHAPE; + const float v = p_f32(a, "value", 0.0f); + + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t yb = rowoff(y, r, n), ys = laststride(y); + for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, v); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ gather_rows */ /* y[i, :] = x[idx[i], :]. The op that turns "correct" into "affordable": without it a plugin runs * the lm_head GEMM over every token of a prefill chunk when the sampler wants one row per diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 16e541e0..527382d8 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -76,6 +76,7 @@ int ref_silu_mul (const RadArgs*, RadStream); int ref_gelu (const RadArgs*, RadStream); int ref_silu (const RadArgs*, RadStream); int ref_sigmoid (const RadArgs*, RadStream); +int ref_fill (const RadArgs*, RadStream); int ref_gather_rows (const RadArgs*, RadStream); int ref_scatter_rows (const RadArgs*, RadStream); int ref_ngram_ids (const RadArgs*, RadStream); @@ -192,6 +193,7 @@ REF_SHAPE_FN(ref_silu_mul); REF_SHAPE_FN(ref_gelu); REF_SHAPE_FN(ref_silu); REF_SHAPE_FN(ref_sigmoid); +REF_SHAPE_FN(ref_fill); REF_SHAPE_FN(ref_gather_rows); REF_SHAPE_FN(ref_scatter_rows); REF_SHAPE_FN(ref_ngram_ids); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 77ee84e9..918810f5 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -144,6 +144,9 @@ static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") }; static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") }; static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") }; +/* `fill` has no input: `value` is the whole of what it writes. */ +static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") }; +static const RadOperandSpec oFill[] = { OUT("y") }; static const RadOperandSpec oGather[] = { OPD("x"), OPD("idx"), OUT("y") }; static const RadOperandSpec oScatterRows[] = { OPD("v"), OPD("idx"), INOUT("x") }; @@ -594,6 +597,10 @@ static const RadOpSchema kSchemas[] = { "y = 0.5x(1 + erf(x/sqrt(2))). The exact erf form, not the tanh approximation." }, { "silu", ARR(pMnD), ARR(oUnary), "y = x * sigmoid(x)." }, { "sigmoid", ARR(pMnD), ARR(oUnary), "y = 1 / (1 + exp(-x))." }, +{ "fill", ARR(pFill), ARR(oFill), + "y = value, every element of an [M, n] extent (default 0), rounded once to y's dtype. The op a " + "rank issues where it computes nothing and a reader downstream -- an all-reduce, a residual -- " + "still expects a defined buffer." }, { "ple_gate", ARR(pPleGate), ARR(oPleGate), "Per-Layer Embedding's gate. K = grouped_rmsnorm(k) * (w_key + wadd) and Q likewise over `q`, " "one rsqrt per `n`-wide stream and one gain across all hc*n; s[c] = sum_d K[c][d]*Q[c][d] / " @@ -981,6 +988,7 @@ SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate SIMPLE("ref_gelu", "gelu", "elem", "exact erf gelu", DT_FLOAT, ref_gelu), SIMPLE("ref_silu", "silu", "elem", "silu", DT_FLOAT, ref_silu), SIMPLE("ref_sigmoid", "sigmoid", "elem", "logistic sigmoid", DT_FLOAT, ref_sigmoid), +SIMPLE("ref_fill", "fill", "elem", "constant fill", DT_FLOAT, ref_fill), SIMPLE("ref_ngram_ids", "ngram_ids", "vocab", "hashed n-gram row ids for PLE", DT_ANY, ref_ngram_ids), SIMPLE("ref_ple_gate", "ple_gate", "norm", "PLE gate: three grouped norms, a dot, a signed sqrt", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 41de9380..5885ed99 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -495,6 +495,14 @@ int ref_silu_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { int ref_sigmoid_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { return unary_shape(p, n_p, operand, "sigmoid", out); } + +int ref_fill_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + Opd o; + o.t(D, { M, n }); /* y */ + return o.finish("fill", operand, out); +} int ref_softmax_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { return unary_shape(p, n_p, operand, "softmax", out); } diff --git a/scripts/README.md b/scripts/README.md index 44582ffa..975fd399 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -17,7 +17,7 @@ header lists its own). The ones that only attach to a live server need nothing b | | | |---|---| | `mcserve.sh` | MiniCPM5-2B with its DSpark drafter (`minicpm5-2b-dspark.v2.rad`), left running on :8100. Records why `--max-model-len` is the container's `n_ctx_train` and why a dense model of this size needs no explicit VRAM split. | -| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. Records the production flags and why: the 200K context and the 0.82 expert/cache ratio that keeps the prefix cache useful at it, the 2048-token chunk, the prefix-cache tiers and the lossy `wht6` cross-rank wire. | +| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. Records the production flags and why: the 200K context and how the expert/cache split sizes the prefix cache at it, the 2048-token chunk, the prefix-cache tiers and the lossy `wht6` cross-rank wire. | | `fnstop.sh` | Stops whichever is running and waits for the process to go. | | `convdspark.sh` | Rebuilds the container `mcserve.sh` serves, with the drafter merged. The conversion of record. | | `convfn.sh` | Rebuilds the container `fnserve.sh` serves from `data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe`. Needs `CALIB=`: the recipe's expert rule runs GPTQ against the calibration Grams there (`docs/MOE-W4.md`). | diff --git a/scripts/diskstall.py b/scripts/diskstall.py index fc9513de..6b355c23 100644 --- a/scripts/diskstall.py +++ b/scripts/diskstall.py @@ -74,8 +74,8 @@ while True: print(f"diskstall: the session never left RAM and VRAM for disk: {s}", file=sys.stderr) sys.exit(1) time.sleep(1) -print(f"on disk {s['on_disk']} blocks, snapshots device/host/disk " - f"{s['snap_device']}/{s['snap_host']}/{s['snap_disk']}, after {time.time()-t0:.0f}s") +print(f"on disk {s['on_disk']} blocks, snapshots host/disk " + f"{s['snap_host']}/{s['snap_disk']}, after {time.time()-t0:.0f}s") # ---- the bystander: a stream that only decodes ---------------------------------------------------- stamps = [] diff --git a/scripts/fnserve.sh b/scripts/fnserve.sh index c1aa650c..51eb58d9 100755 --- a/scripts/fnserve.sh +++ b/scripts/fnserve.sh @@ -4,26 +4,25 @@ # production one, w4nl64-i8lm.rad, built by data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe # (scripts/convfn.sh). # -# 200K CONTEXT, AND WHY THE RATIO IS 0.82 RATHER THAN 0.75. --max-model-len reserves nothing per -# request; it sets the WORST CASE that --expert-vs-cache-ratio sizes the paged pool against. At -# 200000 x 8 sequences the default 0.75 binds: the cache takes its full quarter of the elastic pool, -# and the routed experts it displaces fit in neither VRAM nor the host pool, so without -# --weights-disk-tier the planner refuses at load ("DID NOT FIT"). +# 200K CONTEXT. --max-model-len reserves nothing per request; it sets the WORST CASE the paged +# pool is sized against. Under expert_tiered the cache lends: the routed experts keep on the card +# exactly what the host pool cannot hold, and the cache takes the rest of the elastic pool, up to +# --max-num-seqs x --max-model-len, lending every block no live request holds back to the expert +# slab. --host-pool-mib is what moves that split: a larger pool takes experts off the card and +# gives the cache more, in pinned host RAM. # # The pool is a CAPACITY, not a per-request cap. A token costs 7.31 KiB across the two paged # groups (kv_attn 26.00 KiB and kv_qsa_bkey 3.25 KiB per 4-token block), so one 200K sequence is -# 1.43 GiB. 0.87 is enough for one-shot requests (a 200K and a 120K sequence at once) but not -# for multi-turn ones: with prefix caching a finished sequence's blocks stay HELD so the next turn -# can reuse them, so the demand is the live SESSIONS, and a context of T tokens occupies about -# 1.8 x T pool tokens. At 0.87 two ~184K sessions do not fit, the cache evicts exactly what the -# next turn asks for, and every turn re-prefills its whole context (0% prefix hit; minutes per -# turn instead of seconds). 0.82 holds about two concurrent 200K sessions (99% hit on the second -# turn) for about 1.4% of decode step time, since the experts lose 5% of the elastic pool; 0.84 -# holds one. Watch kv_util: the hit rate falls off a cliff between 0.75 and 0.81 of the pool. +# 1.43 GiB. A one-shot request needs its own context; a multi-turn one needs more: with prefix +# caching a finished sequence's blocks stay HELD so the next turn can reuse them, so the demand is +# the live SESSIONS, and a context of T tokens occupies about 1.8 x T pool tokens. When the pool +# cannot hold the live sessions, the cache evicts exactly what the next turn asks for, and every +# turn re-prefills its whole context (0% prefix hit; minutes per turn instead of seconds). Watch +# kv_util: the hit rate falls off a cliff as the pool fills. # -# Defaults are the production shape (gpu-headroom-mib 96, expert-vs-cache-ratio 0.82, -# kv-cache-dtype fp8, max-num-batched-tokens 2048, tp 2, speculation depth 3), with the prefix -# cache on and --checkpoint-slots at its default, because multi-turn chat wants both. +# Defaults are the production shape (gpu-headroom-mib 96, kv-cache-dtype fp8, +# max-num-batched-tokens 2048, tp 2, speculation depth 3), with the prefix cache on and +# --checkpoint-slots at its default, because multi-turn chat wants both. # # THE CHUNK IS 2048. `--max-num-batched-tokens` is the prefill chunk when checkpoints are off, and # it sets how many routed rows the MoE GEMM sees at once. Part of the expert weight is not in @@ -98,7 +97,7 @@ nohup ./bin/radiance --model "$M" \ --host 0.0.0.0 --port "$P" \ --max-num-seqs ${SEQS:-8} --max-model-len ${MLEN:-200000} \ --tp ${TP:-2} --placement expert_tiered --host-pool-mib ${HOSTPOOL:-12288} \ - --gpu-headroom-mib ${HR:-96} --expert-vs-cache-ratio ${RATIO:-0.82} --kv-cache-dtype ${KVD:-fp8} \ + --gpu-headroom-mib ${HR:-96} --kv-cache-dtype ${KVD:-fp8} \ --prefix-cache-host-mib ${KVHOST:-4096} \ --prefix-cache-dir ${KVDIR:-$HOME/kvcache} --prefix-cache-disk-mib ${KVDISK:-131072} \ --num-speculative-tokens ${NS:-3} \ diff --git a/scripts/fntrace.sh b/scripts/fntrace.sh index cb670ad1..7118ed25 100755 --- a/scripts/fntrace.sh +++ b/scripts/fntrace.sh @@ -44,7 +44,7 @@ env GPU_MAX_ALLOC_PERCENT=100 GPU_MAX_HEAP_SIZE=100 $EXTRA_ENV \ --host 127.0.0.1 --port "$P" \ --max-num-seqs ${SEQS:-8} --max-model-len ${MLEN:-200000} \ --tp ${TP:-2} --placement expert_tiered --host-pool-mib ${HOSTPOOL:-12288} \ - --gpu-headroom-mib ${HR:-96} --expert-vs-cache-ratio ${RATIO:-0.82} --kv-cache-dtype ${KVD:-fp8} \ + --gpu-headroom-mib ${HR:-96} --kv-cache-dtype ${KVD:-fp8} \ --num-speculative-tokens ${NS:-3} \ --max-num-batched-tokens ${MNBT:-2048} \ $EXTRA > "$HOME/fntrace.log" 2>&1 & diff --git a/scripts/mcserve.sh b/scripts/mcserve.sh index 8bb0c4d6..bde94167 100755 --- a/scripts/mcserve.sh +++ b/scripts/mcserve.sh @@ -5,8 +5,8 @@ # /health, print the endpoints, exit with the server still up. Stop it with scripts/fnstop.sh. # # WHY THE VRAM FLAGS ARE ABSENT. This is a DENSE model, so every weight is static and the -# planner takes it off the top as a floor; --expert-vs-cache-ratio then divides an elastic pool -# that has no expert side to claim it, and the slack crosses over to the cache. Stating +# planner takes it off the top as a floor; the elastic pool left after it has no expert side to +# claim it, so all of it goes to the cache. Stating # --vram-weights-mib here would only cap what does not need capping. # # WHY 131072 AND NOT 200000. n_ctx_train is 131072 for this checkpoint; the 200K context diff --git a/scripts/tiercross.sh b/scripts/tiercross.sh index e6566e83..a9f34eac 100755 --- a/scripts/tiercross.sh +++ b/scripts/tiercross.sh @@ -192,7 +192,7 @@ cmp_arm "B restored from disk is still B" "$B2" "$BH" "$(hit b2)" "$(hit bh)" curl -sS --fail "http://$H:$P/sessions" > "$work/s.json" echo " moved: blocks to_host=$(jq -r .moved.to_host < "$work/s.json") to_disk=$(jq -r .moved.to_disk < "$work/s.json") promoted=$(jq -r .moved.promoted < "$work/s.json")" if [ "$CKS" != "0" ]; then - echo " state: to_host=$(jq -r .snapshots_moved.to_host < "$work/s.json") to_disk=$(jq -r .snapshots_moved.to_disk < "$work/s.json") promoted=$(jq -r .snapshots_moved.promoted < "$work/s.json") dropped=$(jq -r .snapshots_moved.drops < "$work/s.json")" + echo " state: to_disk=$(jq -r .snapshots_moved.to_disk < "$work/s.json") fetched=$(jq -r .snapshots_moved.fetched < "$work/s.json") dropped=$(jq -r .snapshots_moved.drops < "$work/s.json")" # A RUN WITH NO CONTENTION TESTED THE EASY CASE. Two stores have to run out for the paths this # script exists for to execute, and they are sized by different flags: --checkpoint-slots is # the DEVICE pool the retention policy spends, and a share of --prefix-cache-host-mib (startup diff --git a/scripts/tierident.sh b/scripts/tierident.sh index b81848f8..103bc901 100755 --- a/scripts/tierident.sh +++ b/scripts/tierident.sh @@ -122,7 +122,7 @@ where() { # where -> "vram=N ram=N disk=N [+ snapshots]" for snap w="vram=$(q .blocks_sum_overlapping.device) ram=$(q .blocks_sum_overlapping.host) disk=$(q .blocks_sum_overlapping.disk)" if [ "$(q .snapshots_moved.bytes_each)" != "0" ]; then - w="$w state: vram=$(q .snapshots.device) ram=$(q .snapshots.host) disk=$(q .snapshots.disk)" + w="$w state: ram=$(q .snapshots.host) disk=$(q .snapshots.disk)" fi echo "$w" } @@ -188,26 +188,28 @@ case "$(q .blocks_sum_overlapping.host)" in 0|null|"") false ;; *) true ;; esac (--prefix-cache-host-mib set? is the maintenance pass running?)" if [ "$HYBRID" = 1 ]; then snap - [ "$(q .snapshots_moved.to_host)" = "0" ] && \ - note "no linear-state snapshot reached RAM, so the restore below tests the blocks only - (starved: $(q .snapshots_moved.starved), dropped: $(q .snapshots_moved.drops))" + # A SNAPSHOT IS IN HOST MEMORY FROM THE MOMENT IT IS SAVED (the checkpoint store), so the + # session's state must be there or on disk -- nowhere else is a place it can be. + case "$(q .snapshots.host)/$(q .snapshots.disk)" in 0/0|null/*|*/null) false ;; *) true ;; esac || \ + note "the session holds no linear-state snapshot, so the restore below tests the blocks only + (dropped: $(q .snapshots_moved.drops))" fi snap -PROM0=$([ "$HYBRID" = 1 ] && q .snapshots_moved.promoted || echo 0) +FET0=$([ "$HYBRID" = 1 ] && q .snapshots_moved.fetched || echo 0) LIN0=$([ "$HYBRID" = 1 ] && lin || echo 0) -DEV0=$([ "$HYBRID" = 1 ] && q .snapshots.device || echo 0) +RAM0=$([ "$HYBRID" = 1 ] && q .snapshots.host || echo 0) FROMHOST=$(ask fromhost) echo " restored from RAM $FROMHOST [$(where)]" check "a session restored from RAM reproduces the cold answer" "$FROMHOST" "$COLD" if [ "$HYBRID" = 1 ]; then snap - # A SNAPSHOT STILL IN ITS DEVICE SLOT NEEDS NO PROMOTION: it stays there when the blocks go, - # and only the checkpoint pool's own pressure detaches it. Whether it was SERVED is the check - # below either way; this one only says which path served it. - if [ "$(q .snapshots_moved.promoted)" -gt "$PROM0" ]; then - echo " ok its linear state came back with it ($(( $(q .snapshots_moved.promoted) - PROM0 )) snapshot(s))" - elif [ "$DEV0" -gt 0 ]; then - echo " -- its linear state never left its device slot ($DEV0 there), so nothing was promoted" + # A SNAPSHOT IN THE STORE NEEDS NO READ: it is restored straight out of its slot, and only + # the store's own pressure sends it to disk. Whether it was SERVED is the check below either + # way; this one only says which path served it. + if [ "$(q .snapshots_moved.fetched)" -gt "$FET0" ]; then + echo " ok its linear state was read back off disk ($(( $(q .snapshots_moved.fetched) - FET0 )) snapshot(s))" + elif [ "$RAM0" -gt 0 ]; then + echo " -- its linear state stayed in the snapshot store ($RAM0 there), so nothing was read" else note "the blocks came back and the linear state did not -- the answer is right and the session will replay every recurrent layer from an older checkpoint to produce it" @@ -238,25 +240,25 @@ if [ "$HYBRID" = 1 ]; then (disk snapshot slots: $(q .snapshots_moved.disk_slots))" fi snap -PROM1=$([ "$HYBRID" = 1 ] && q .snapshots_moved.promoted || echo 0) +FET1=$([ "$HYBRID" = 1 ] && q .snapshots_moved.fetched || echo 0) LIN1=$([ "$HYBRID" = 1 ] && lin || echo 0) FROMDISK=$(ask fromdisk) echo " restored from disk $FROMDISK [$(where)]" check "a session restored from disk reproduces the cold answer" "$FROMDISK" "$COLD" if [ "$HYBRID" = 1 ]; then snap - if [ "$(q .snapshots_moved.promoted)" -gt "$PROM1" ]; then + if [ "$(q .snapshots_moved.fetched)" -gt "$FET1" ]; then echo " ok its linear state came back from disk too" else - note "nothing promoted a snapshot out of disk -- the filler's snapshots did not push the - session's out of the device pool (--checkpoint-slots 2?), so the disk path never ran" + note "no snapshot was read off disk -- the filler's snapshots did not push the session's + out of the snapshot store (--checkpoint-slots 2?), so the disk path never ran" fi if [ "$(lin)" -gt "$LIN1" ]; then echo " ok and the state restored from disk was SERVED ($(( $(lin) - LIN1 )) prompt tokens)" else note "a snapshot came back from disk and no lookup used it" fi - echo " snapshots: to_host=$(q .snapshots_moved.to_host) to_disk=$(q .snapshots_moved.to_disk) promoted=$(q .snapshots_moved.promoted) dropped=$(q .snapshots_moved.drops) starved=$(q .snapshots_moved.starved)" + echo " snapshots: to_disk=$(q .snapshots_moved.to_disk) fetched=$(q .snapshots_moved.fetched) dropped=$(q .snapshots_moved.drops)" fi # ---- and the text itself, so a failure says WHERE ---------------------------------------------- diff --git a/spec.md b/spec.md index 9326d3a9..69bd549b 100644 --- a/spec.md +++ b/spec.md @@ -953,7 +953,6 @@ utilisation fraction and no inference about what the workload will be: | | | |---|---| | `--gpu-headroom-mib` | VRAM left unclaimed on every card (default 96) | -| `--expert-vs-cache-ratio` | weights vs KV split of what is claimed (default 0.75) | | `--vram-weights-mib` | the resident weight slab; 0 derives it from the card | | `--vram-kv-mib` | the paged KV pool; 0 derives it from the card | | `--host-pool-mib` | pinned host tier | @@ -974,7 +973,8 @@ and what is left is spent in **two steps**, because only one of the two is a tra claimable 31.19 GiB static weights 3.94 GiB off the top: every rank's own shard, not a share of anything ------------------------------ - elastic 27.25 GiB what --expert-vs-cache-ratio divides + elastic 27.25 GiB the experts keep what the host pool cannot hold; the cache takes the rest + and lends what no live request holds to the expert slab experts 26.18 GiB kv cache 1.08 GiB a full cache for 8 sequences at 2048 tokens ============================== @@ -985,9 +985,21 @@ and what is left is spent in **two steps**, because only one of the two is a tra projections, the norms, the embedding, the head — has to be resident for the model to run at a sensible speed at all, and under tensor parallel each rank already holds its own even share of them (declare runs per rank with every dimension divided, §9). Dividing the weights *as a whole* -by a ratio would let `--expert-vs-cache-ratio 0.3` demote an attention projection to host memory -to make room for a cache nothing will fill. So they come out whole first, and what remains is the -one genuinely two-sided trade this engine has: the expert plane against the KV cache. +would let the cache's side demote an attention projection to host memory to make room for blocks +nothing will fill. So they come out whole first, and what remains is the one genuinely two-sided +trade this engine has: the expert plane against the KV cache. + +**Where the cache lends, that trade has nothing to guess.** Under `--placement auto` or +`expert_tiered`, without `--deterministic`, on a device with virtual memory management, the +experts keep on the card exactly what the pinned host pool (`--host-pool-mib`) cannot hold, plus +one expert unit of packing slack — they have nowhere else to be — and the cache takes the rest, up +to what it could ever address. Every block no live request holds is lent back to the expert slab +in place, so the cache is as large as the work needs at the moment and the experts have everything +else, for a long-context server and a high-concurrency one alike. `--host-pool-mib` is what moves +the split: a larger pool takes experts off the card and gives the cache more. The prefill staging +region comes out of the cache's side. Without a lender a block the cache does not use would sit +empty, so the experts come first and the cache keeps one max-length sequence. Either way the cache +never gets less than that sequence. **Both sides are then capped at what they could use, and the slack crosses over.** The ceilings are upper bounds and not targets. An expert plane that is entirely resident has no use for another @@ -1008,10 +1020,8 @@ What *is* a hard limit, and is still checked: the pool must hold **one** max-len context no single request can ever complete is a configuration error however much slack the pool has, because the API accepts that request and admission then refuses it. -The trade between KV blocks and resident weights is real and workload-dependent — a long-context -low-concurrency server and a short-context high-concurrency one want opposite splits — and stating -it is still the operator's to do: `--vram-weights-mib` and `--vram-kv-mib` win outright wherever -they are given, and nothing re-optimises a split that was stated. An engine that quietly +`--vram-weights-mib` and `--vram-kv-mib` win outright wherever they are given, and nothing +re-optimises a split that was stated. An engine that quietly re-optimises is an engine whose benchmarks do not reproduce. A fixed weight-slab budget also means dynamic re-placement (§5.4) never competes with the KV pool. The mover works inside its own slab and cannot evict a KV block to promote an expert. diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 18a04757..7fda62aa 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -45,11 +45,10 @@ struct RecWeight { * checked. A weight with no span -- every even shard -- has `span_set` false. */ bool span_set = false; int64_t span_lo = 0, span_hi = 0; - /* rad_weight_shard_span_parts and rad_weight_shard_zero, recorded the same way. */ + /* rad_weight_shard_span_parts, recorded the same way. */ int n_part_spans = 0; int64_t part_lo[RAD_MAX_ROW_PARTS] = {0}, part_hi[RAD_MAX_ROW_PARTS] = {0}; int64_t part_total[RAD_MAX_ROW_PARTS] = {0}; - bool zero = false; }; struct RecBuf { std::string name; RadBufDecl d{}; }; struct RecOp { @@ -238,13 +237,6 @@ extern "C" int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const in rw.n_part_spans = n; return RAD_OK; } -extern "C" int rad_weight_shard_zero(RadBuilder* b, rad_weight w) { - if (!b || w == 0 || w > b->weights.size()) return RAD_E_INVAL; - RecWeight& rw = b->weights[w - 1]; - if (rw.d.shard != RAD_SHARD_ROW && rw.d.shard != RAD_SHARD_COL) return RAD_E_INVAL; - rw.zero = true; - return RAD_OK; -} extern "C" int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) { if (!b || g == 0 || g > b->kv_groups.size()) return RAD_E_INVAL; b->kv_groups[g - 1].zero = true; @@ -2243,17 +2235,28 @@ TEST(flashnext_tp4_replicates_kv_heads_and_splits_expert_widths) { } } - /* A WORLD THAT CANNOT REPLICATE -- not a multiple of the KV head count -- is no longer - * refused: it serves attention on the largest multiple under it and the rest of the ranks - * carry zero attention (the tp3 case below holds the shapes). Nothing is rounded into a - * half head: the replication rule itself is unchanged and still refuses an attention world - * that is not a multiple, which cannot arise from geom_from's construction. */ + /* A WORLD THAT CANNOT REPLICATE -- not a multiple of the KV head count -- declares: qwen4exp + * asks for the attention world (geom_from's `attn_world_ok`), so attention is served on the + * largest multiple under it and the rest of the ranks compute none (the tp3 case below holds + * the shapes). Nothing is rounded into a half head: the replication rule refuses an attention + * world that is not a multiple, which geom_from's construction cannot produce. A plugin that + * does not ask is refused at this world, by geom_from itself. */ { RadBuilder b3; RadBuildCtx c3 = build_ctx(0, 3); c3.max_tok = 2048; c3.max_seqs = 8; c3.max_spec = 3; c3.max_ctx = 200000; CHECK_EQ(qwen4exp_fp8::declare(&b3, &meta, &c3), RAD_OK); } + { + rad::arch::Geom g3{}; + RadBuildCtx c3 = build_ctx(0, 3); + c3.max_tok = 2048; c3.max_seqs = 8; c3.max_spec = 3; c3.max_ctx = 200000; + CHECK_EQ(rad::arch::geom_from(g3, &meta, &c3, "bf16", RAD_BF16, /*arch_splits_ff=*/true), RAD_E_INVAL); + CHECK_EQ(rad::arch::geom_from(g3, &meta, &c3, "bf16", RAD_BF16, /*arch_splits_ff=*/true, + /*attn_world_ok=*/true), RAD_OK); + CHECK(g3.attn_zero == false); + CHECK_EQ(g3.attn_world, 2); + } /* ---- A LAYER THAT KEEPS EXPERTS PLAIN STAYS AT FOUR CLASSES. Two plain experts leave 510 * quantised ones, four leave 508; either way the layer is served by `moe_gemm_q_mod4`, the @@ -2478,11 +2481,10 @@ const RecIssue* issue_of(const RadBuilder& b, const RadCtx& c, const std::string } /* namespace */ -/* THREE RANKS OVER TWO KV HEADS: the attention world is 2 (rad_arch.h), rank 2 declares the same - * attention as its peers and reads zeros for it, and the delta net's 16 K heads go 6, 5, 5 with - * the V heads at the same multiple -- declared as spans of the container, nothing padded. On the - * tree before this, geom_from refuses world 3 ("cannot replicate n_head_kv = 2") and nothing - * below runs. */ +/* THREE RANKS OVER TWO KV HEADS: the attention world is 2 (rad_arch.h), rank 2 computes no + * attention -- a `fill` of its output wire and a zero KV group -- and the delta net's 16 K heads + * go 5, 5, 6 with the V heads at the same multiple, the extra head on the rank without attention + * -- declared as spans of the container, nothing padded. */ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenly) { RadModelMeta meta = qwen4exp_meta(); const int world = 3; @@ -2529,6 +2531,7 @@ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenl } } + std::vector> k_span((size_t)world); /* each rank's K heads, [lo, hi) */ for (int r = 0; r < world; ++r) { const bool zero = r >= attn_world; CHECK_EQ(b[r].kv_groups[0].d.n_head_kv, 1); @@ -2566,7 +2569,6 @@ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenl const int ar = zero ? attn_world - 1 : r; CHECK_EQ(w->span_lo, (int64_t)ar * head_dim); CHECK_EQ(w->span_hi, w->span_lo + head_dim); - CHECK_EQ(w->zero, zero); } if (!zero) { const RecWeight* w = find_w(b[r], qg); @@ -2576,13 +2578,11 @@ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenl CHECK_EQ(w->d.shape[0], qg_rows); CHECK(w->span_set); CHECK_EQ(w->span_lo, (int64_t)ar * qg_rows); - CHECK_EQ(w->zero, zero); const RecWeight* o = find_w(b[r], oo); REQUIRE(o != nullptr); CHECK_EQ(o->d.shard, RAD_SHARD_COL); CHECK(o->span_set); CHECK_EQ(o->span_lo, (int64_t)ar * (n_head / attn_world) * head_dim); - CHECK_EQ(o->zero, zero); } /* (3) THE DELTA NET: 5, 5, 6 K heads and 15, 15, 18 V heads, real on every rank, as * per-part spans of [q|k|v|z] and of the conv channels, a one-span of A_log. */ @@ -2605,7 +2605,7 @@ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenl CHECK_EQ(in->part_lo[3], v0 * hv); CHECK_EQ(in->part_total[0], nk * hk); CHECK_EQ(in->part_total[2], nv * hv); - CHECK(!in->zero); + k_span[(size_t)r] = { in->part_lo[0] / hk, in->part_hi[0] / hk }; const RecWeight* cv = find_w(b[r], "blk.0.ssm_conv1d.weight"); REQUIRE(cv != nullptr); REQUIRE_EQ(cv->n_part_spans, 3); @@ -2629,11 +2629,17 @@ TEST(flashnext_tp3_zeroes_the_third_ranks_attention_and_splits_gdn_heads_unevenl if (g.name == "kv_gdn_state") { seen = true; CHECK_EQ(g.d.n_head_kv, (int)my_v); } CHECK(seen); } - /* The three ranks' K heads are the container's 16, once each. */ + /* The three ranks' K heads, read back from the declared spans, are the container's 16, each + * exactly once. */ { - int64_t sum = 0; - for (int r = 0; r < world; ++r) sum += nk / world + (r < nk % world ? 1 : 0); /* a permutation of the same counts */ - CHECK_EQ(sum, nk); + std::vector owner((size_t)nk, -1); + for (int r = 0; r < world; ++r) + for (int64_t h = k_span[(size_t)r].first; h < k_span[(size_t)r].second; ++h) { + REQUIRE(h >= 0 && h < nk); + CHECK_EQ(owner[(size_t)h], -1); + owner[(size_t)h] = r; + } + for (int64_t h = 0; h < nk; ++h) CHECK(owner[(size_t)h] >= 0); } } diff --git a/tests/build_test.cpp b/tests/build_test.cpp index a718676f..ae79a6ab 100644 --- a/tests/build_test.cpp +++ b/tests/build_test.cpp @@ -1349,14 +1349,14 @@ TEST(the_gate_names_its_caller) { CHECK(has(msg, "the container's layout")); } -/* A span, per-part spans and a zero share have to SURVIVE THE WEIGHT LIST GROWING: WeightInfo's - * copy is hand-written (the atomic), so a field the copy leaves out is reset on every weight - * declared before the vector's last reallocation -- which is what the loader saw on rank 0 of a - * three-rank Flash-Next: layer 0's [a|b] with its per-part spans gone, refused as an even share. */ -TEST(shard_spans_and_zero_survive_the_weight_list_reallocating) { +/* A span and per-part spans have to SURVIVE THE WEIGHT LIST GROWING: WeightInfo's copy is + * hand-written (the atomic), so a field the copy leaves out is reset on every weight declared + * before the vector's last reallocation, and the loader then sees an uneven share as an even one + * and refuses it. */ +TEST(shard_spans_survive_the_weight_list_reallocating) { NEED_PLUGIN(reg) Builder b(reg, make_meta(), make_ctx()); - /* Three weights declared first and marked, then enough declared after them to grow the + /* Two weights declared first and marked, then enough declared after them to grow the * list several times over. */ RadWeightDecl d{}; d.dtype = RAD_BF16; d.rank = 2; d.shape[0] = 36; d.shape[1] = 64; @@ -1370,8 +1370,6 @@ TEST(shard_spans_and_zero_survive_the_weight_list_reallocating) { const rad_weight sp = decl_w(b, "span", 18, 64); CHECK_EQ(b.weight_shard_span(sp, 6, 24), RAD_OK); - const rad_weight z = decl_w(b, "zero", 18, 64); - CHECK_EQ(b.weight_shard_zero(z), RAD_OK); for (int i = 0; i < 300; ++i) { char n[32]; snprintf(n, sizeof n, "w%d", i); @@ -1387,8 +1385,6 @@ TEST(shard_spans_and_zero_survive_the_weight_list_reallocating) { w = b.program().weight(sp); CHECK_EQ((long long)w->shard_lo, 6LL); CHECK_EQ((long long)w->shard_hi, 24LL); - w = b.program().weight(z); - CHECK(w->shard_zero); CHECK_EQ((int)b.errors().size(), 0); } diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index bec9562c..d6a2f8ca 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -160,16 +160,16 @@ static Verdict run(Bench* b, const std::string& text, const char* what, size_t s * grammar, and the calls must come back as the message had them. */ /* What the template wrote for an argument, read back: a string argument is its text and any - * other one is JSON. Two exceptions, both the template's rendering rather than the parser's - * reading: a boolean or null, which Jinja renders the Python way (`True`, `None`), and -- in - * MiniCPM's template, which prints a value with a bare `{{ param_value }}` -- a list or an object, - * which this Jinja engine prints without its brackets. Those are compared by what the reply says, - * which the differential check already covers, rather than by what the message held. */ + * other one is JSON -- a boolean or null included, which Jinja renders the Python way (`True`, + * `None`) and the parser reads back as JSON's. One exception, the template's rendering rather than + * the parser's reading: MiniCPM's template prints a value with a bare `{{ param_value }}`, and a + * list or an object comes out of this Jinja engine without its brackets. Those are compared by + * what the reply says, which the differential check already covers, rather than by what the + * message held. */ static bool round_trips(const json& want, const json& got, bool containers) { if (!got.is_object() || want.size() != got.size()) return false; for (auto it = want.begin(); it != want.end(); ++it) { if (!got.contains(it.key())) return false; - if (it.value().is_boolean() || it.value().is_null()) continue; if (!containers && it.value().is_structured()) continue; if (got.at(it.key()) != it.value()) return false; } @@ -295,6 +295,71 @@ TEST(the_decided_shapes_read_as_decided) { if (!r.calls.empty()) CHECK_EQ(r.calls[0].arguments, std::string("{\"command\":\"sleep\",\"timeout\":\"30 seconds\"}")); + /* A typed argument always reads as JSON: Python's literals as JSON's, inside a container + * too, an empty value as null, and text that spells no JSON value as a string of it. + * Qwen's format reads non-string arguments as JSON; MiniCPM's reads every one as text. */ + if (q) { + r = read_adv(m, "Python literals"); + CHECK_EQ(r.calls.size(), (size_t)1); + if (!r.calls.empty()) + CHECK_EQ(r.calls[0].arguments, std::string("{\"verbose\":true,\"nothing\":null}")); + r = read_adv(m, "a Python dict with literals"); + if (!r.calls.empty()) { + const json a = json::parse(r.calls[0].arguments, nullptr, false); + CHECK(!a.is_discarded()); + if (!a.is_discarded()) { + CHECK(a["extra"]["a"] == json(true)); + CHECK(a["extra"]["b"].is_null()); + CHECK(a["extra"]["c"] == json("False")); + } + } + r = read_adv(m, "an empty typed value"); + if (!r.calls.empty()) + CHECK_EQ(r.calls[0].arguments, std::string("{\"level\":null}")); + r = read_adv(m, "a typed value that is no JSON"); + if (!r.calls.empty()) + CHECK_EQ(r.calls[0].arguments, std::string("{\"verbose\":\"yes please\"}")); + r = read_adv(m, "a number that is not one"); + if (!r.calls.empty()) + CHECK_EQ(r.calls[0].arguments, std::string("{\"path\":\"/a\",\"limit\":\"01\"}")); + /* A raw line break or tab inside a string is the escape JSON spells it as: a client's + * JSON parser refuses the raw character. */ + r = read_adv(m, "JSON strings holding a raw line break and tab"); + CHECK_EQ(r.calls.size(), (size_t)1); + if (!r.calls.empty()) { + const json a = json::parse(r.calls[0].arguments, nullptr, false); + CHECK(!a.is_discarded()); + if (!a.is_discarded()) { + CHECK(a["extra"]["a"] == json("line1\nline2")); + CHECK(a["extra"]["b"] == json("\tx")); + } + } + /* A container is JSON once normalised, or the string of its text: a trailing comma, + * a bare word or a missing bracket is no JSON, and the arguments must stay JSON. */ + r = read_adv(m, "Python containers that are no JSON"); + CHECK_EQ(r.calls.size(), (size_t)1); + if (!r.calls.empty()) + CHECK_EQ(r.calls[0].arguments, std::string("{\"extra\":\"{'a': 1, 'b': [2, 3],}\"," + "\"tags\":\"['x', nan]\"}")); + r = read_adv(m, "a container missing its close"); + if (!r.calls.empty()) + CHECK_EQ(r.calls[0].arguments, std::string("{\"extra\":\"{'a': [1, 2}\"}")); + r = read_adv(m, "an escaped quote in a double-quoted string"); + if (!r.calls.empty()) + CHECK_EQ(r.calls[0].arguments, std::string("{\"tags\":[\"it's\", \"x\"]}")); + /* The grammar's JSON admits a number past a double's range and an unpaired surrogate + * escape, which a client's JSON parser refuses: such a value is its text. */ + r = read_adv(m, "JSON a client cannot read"); + if (!r.calls.empty()) { + const json a = json::parse(r.calls[0].arguments, nullptr, false); + CHECK(!a.is_discarded()); + if (!a.is_discarded()) { + CHECK(a["level"] == json("1e400")); + CHECK(a["extra"] == json(R"({"a": "\ud800"})")); + } + } + } + /* A Python-quoted array is normalised to JSON. */ r = read_adv(m, "a Python-quoted array"); if (!r.calls.empty()) { @@ -331,6 +396,18 @@ TEST(the_decided_shapes_read_as_decided) { CHECK_EQ(r.calls[0].arguments, std::string("{\"command\":\"ls\"}")); } CHECK(r.content.empty()); + + /* A call whose own close is missing is ended by its wrapper's, and the next call is + * a call of its own rather than more arguments for this one. */ + r = read_adv(m, "a call closed by its wrapper alone"); + CHECK_EQ(r.calls.size(), (size_t)2); + if (r.calls.size() == 2) { + CHECK(r.calls[0].closed); + CHECK_EQ(r.calls[0].arguments, std::string("{\"command\":\"ls\"}")); + CHECK_EQ(r.calls[1].name, std::string("read")); + CHECK_EQ(r.calls[1].arguments, std::string("{\"path\":\"/a\"}")); + } + CHECK(r.content.empty()); } /* The terminator is not the answer, nor is trailing whitespace. */ @@ -339,6 +416,81 @@ TEST(the_decided_shapes_read_as_decided) { } } +/* AN ARGUMENT NAME THAT REPEATS ITS OWN TAG'S OPENING -- ``, which + * models write and the grammar's undeclared arm admits -- is the argument it names, read + * leniently: as the undeclared `parameter=command` the call reaches the tool without its command. + * A name the repetition does not make a declared one stays as written. */ +TEST(an_argument_name_repeating_its_tag_is_the_argument_it_names) { + for (const Model& m : models()) { + Bench* b = bench(m, ChatRequest{}); + if (!b) continue; + const std::string T = "Thinking it over.\n\n\n"; + const bool q = is_qwen(m); + const std::string rep = q ? "parameter=" : "param name=\""; + const std::string text = T + C(m, "bash", { { rep + "command", "ls -la" }, + { rep + rep + "timeout", "30" }, + { rep + "nope", "x" } }); + bool strict = true; + const ReplyMessage r = b->new_parse(text, &strict); + CHECK(!strict); + REQUIRE(r.calls.size() == 1); + const bool typed = b->format().other_value == ChatValue::Json; + CHECK_EQ(r.calls[0].arguments, "{\"command\":\"ls -la\",\"timeout\":" + + std::string(typed ? "30" : "\"30\"") + "," + + json(rep + "nope").dump() + ":\"x\"}"); + const std::string s = stream_all(b->parser(), text); + CHECK(s.empty()); + if (!s.empty()) fprintf(stderr, " %s\n", s.c_str()); + } +} + +/* A CALL THE REPLY ENDED INSIDE reads back, as content, as the text it was written as: the content + * before it, then the call's own bytes -- never the reasoning, never a call that closed before it. + * What a buffered response answers with when that call cannot be reported as a call. */ +TEST(a_call_the_reply_ended_inside_reads_back_as_its_text) { + auto trimmed = [](std::string s) { + while (!s.empty() && (s.back() == '\n' || s.back() == ' ')) s.pop_back(); + return s; + }; + for (const Model& m : models()) { + Bench* b = bench(m, ChatRequest{}); + if (!b) continue; + const std::string T = "Thinking it over.\n\n\n"; + const std::string done = C(m, "bash", { { "command", "ls" } }); + const std::string call = C(m, "write", { { "path", "/a" }, { "content", "partial fi" } }); + for (const size_t cut : { call.find("partial") + 3, call.find("") + 3 }) { + const std::string open = call.substr(0, cut); + struct Case { std::string text, content; size_t calls; }; + std::vector cases = { + { T + "Writing.\n" + open, "Writing.\n" + trimmed(open), 1 }, + { T + "Writing.\n" + done + "\n" + open, "Writing.\n" + trimmed(open), 2 }, + { T + open, trimmed(open), 1 }, + }; + /* Qwen's reasoning block ends where a call starts. */ + if (is_qwen(m)) cases.push_back({ "I will write it.\n" + open, trimmed(open), 1 }); + for (const Case& k : cases) { + std::unique_ptr s = b->parser().open(); + for (size_t i = 0; i < k.text.size(); ++i) + s->feed(std::string_view(k.text).substr(i, 1), nullptr); + s->finish(nullptr); + const ReplyMessage& r = s->message(); + CHECK_EQ(r.calls.size(), k.calls); + if (r.calls.size() != k.calls) continue; + CHECK(!r.calls.back().closed); + if (k.calls == 2) CHECK(r.calls[0].closed); + CHECK_EQ(s->content_with_open_call(k.text), k.content); + CHECK(stream_all(b->parser(), k.text).empty()); + } + } + /* With no open call the content is the content. */ + const std::string whole = T + "Writing.\n" + done; + std::unique_ptr s = b->parser().open(); + s->feed(whole, nullptr); + s->finish(nullptr); + CHECK_EQ(s->content_with_open_call(whole), std::string("Writing.")); + } +} + /* ================================================================== calls without the wrapper * * Qwen's grammar opens a call at `\n`, and the lazy grammar engages only there -- so a @@ -378,6 +530,11 @@ static std::vector bare_shapes() { { "two bare calls", T + ls + "\n" + rd, 2, false }, { "two bare calls with a sentence between", T + ls + "\nNow the file.\n" + rd, 2, false }, { "a bare call with no arguments", T + "\n", 1, false }, + /* The first argument's name is what makes the opener a call, and it is held while it is + * read: a tag name, not a delimiter, however long. */ + { "a bare call whose first argument name is long", + T + "\n\nls\n\n", + 1, false }, /* Unconstrained, the model need not write the newlines the template puts around each * tag; a loose call's tags are read with that whitespace optional. */ { "a bare call written without newlines", @@ -400,6 +557,9 @@ static std::vector bare_shapes() { /* An argument name that runs into a tag is no argument: the opener was text. */ { "a bare opener whose argument name runs into a tag", T + "\n\n", 0, true }, + { "a bare opener whose long argument name runs into a tag", + T + "\n\n", + 0, true }, { "a mangled bare opener before a wrapped call", T + "\n\n\n\n" + rd + "\n", 1, true }, @@ -950,6 +1110,16 @@ TEST(an_argument_no_value_satisfies_has_no_arm_in_either_grammar) { gq.generation_prompt = b->prompt().generation_prompt; CHECK_OK(chat_format_grammar(declared, gq, &g, &why)); CHECK_EQ(g.text, b->prompt().grammar); + + /* And the parser reads such an argument as the grammar does, by the undeclared arm: text, + * though its value spells JSON. */ + const std::string reply = "Thinking it over.\n\n\n" + + C(models()[0], "task", { { "context", "c" }, { "tasks", "[]" }, { "model", "123" } }); + const Verdict v = run(b, reply, "an argument no value satisfies"); + CHECK(v.strict); + const ReplyMessage r = b->new_parse(reply); + REQUIRE(r.calls.size() == 1); + CHECK_EQ(r.calls[0].arguments, std::string("{\"context\":\"c\",\"tasks\":[],\"model\":\"123\"}")); } /* OH-MY-PI 18.6.0's TOOLS AS AN UNMODIFIED CLIENT SENDS THEM (tests/data/chat), descriptions aside. @@ -1059,7 +1229,9 @@ TEST(a_tool_name_holding_the_format_delimiter_is_refused_at_admission) { /* ================================================================== the wire * * What a streaming client assembles from the SSE chunks -- content, reasoning, each call's id, - * name and arguments -- is the buffered answer, for every reply, cut a byte at a time. */ + * name and arguments -- is the buffered answer, for every reply, cut a byte at a time. Every + * chunk is the bytes nlohmann writes for the value it carries: the delta chunks are written + * directly rather than through a tree, and are held to it here. */ TEST(what_a_streaming_client_assembles_is_the_buffered_answer) { for (const Model& m : models()) { Bench* b = bench(m, ChatRequest{}); @@ -1096,7 +1268,9 @@ TEST(what_a_streaming_client_assembles_is_the_buffered_answer) { size_t at = 0; while ((at = sse.find("data: ", at)) != std::string::npos) { const size_t end = sse.find("\n\n", at); - const json j = json::parse(sse.substr(at + 6, end - at - 6)); + const std::string payload = sse.substr(at + 6, end - at - 6); + const json j = json::parse(payload); + CHECK_EQ(j.dump(), payload); at = end; const json& c = j["choices"][0]; if (!c["finish_reason"].is_null()) finish = c["finish_reason"].get(); @@ -1126,8 +1300,8 @@ TEST(what_a_streaming_client_assembles_is_the_buffered_answer) { CHECK_EQ(args[k], want.calls[k].arguments); CHECK_EQ(p.tool_calls[k].id, ids[k]); } - /* A call is reported as one only when its arguments parse. */ - bool complete = !want.calls.empty(); + /* A call is reported as one only when it closed and its arguments parse. */ + bool complete = !want.calls.empty() && want.calls.back().closed; for (const ReplyCall& c : want.calls) complete = complete && server::json_complete(c.arguments); CHECK_EQ(finish, std::string(complete ? "tool_calls" : "stop")); } diff --git a/tests/config_test.cpp b/tests/config_test.cpp index eded9b45..3d6dfe81 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -117,7 +117,6 @@ TEST(a_flag_missing_its_argument_is_refused_rather_than_read_past) { CHECK_EQ(parse({ "--tp" }, &c), RAD_E_INVAL); CHECK_EQ(parse({ "--port" }, &c), RAD_E_INVAL); CHECK_EQ(parse({ "--kv-cache-dtype" }, &c), RAD_E_INVAL); - CHECK_EQ(parse({ "--expert-vs-cache-ratio" }, &c), RAD_E_INVAL); Args a{ "--model" }; CHECK_EQ(config_parse(a.argc(), a.argv.data(), &c), RAD_E_INVAL); } @@ -347,30 +346,6 @@ TEST(the_table_placements_are_auto_vram_ram_or_disk) { CHECK_EQ(parse({ "--ngram-placement" }, &c), RAD_E_INVAL); } -/* THE FLAG THAT DECIDES WHETHER MULTI-TURN WORKS. It is the WEIGHTS share, strictly inside - * (0, 1): either endpoint gives one side of the split nothing at all, and the server would come - * up and then fail to place either the experts or the cache. */ -TEST(the_expert_cache_ratio_is_strictly_between_zero_and_one) { - Config c; - CHECK_EQ(parse({ "--expert-vs-cache-ratio", "0.82" }, &c), RAD_OK); - CHECK_NEAR(c.expert_cache_ratio, 0.82, 1e-9); - CHECK_EQ(parse({ "--expert-vs-cache-ratio", "0.5" }, &c), RAD_OK); - - CHECK_EQ(parse({ "--expert-vs-cache-ratio", "0" }, &c), RAD_E_INVAL); - CHECK_EQ(parse({ "--expert-vs-cache-ratio", "1" }, &c), RAD_E_INVAL); - CHECK_EQ(parse({ "--expert-vs-cache-ratio", "1.5" }, &c), RAD_E_INVAL); - CHECK_EQ(parse({ "--expert-vs-cache-ratio", "-0.5" }, &c), RAD_E_INVAL); - /* A PERCENTAGE IS THE OBVIOUS MISREADING of a flag documented as a ratio, and 82 is outside - * the range rather than clamped to it -- which is the difference between a server that says - * what is wrong and one that quietly serves a different split. */ - CHECK_EQ(parse({ "--expert-vs-cache-ratio", "82" }, &c), RAD_E_INVAL); - CHECK_EQ(parse({ "--expert-vs-cache-ratio", "high" }, &c), RAD_E_INVAL); - - Config d; - CHECK_EQ(parse({}, &d), RAD_OK); - CHECK_NEAR(d.expert_cache_ratio, 0.75, 1e-9); -} - /* A POLICY NAME THIS BUILD DOES NOT KNOW WOULD FALL THROUGH TO THE DEFAULT, and a measurement * comparing the default against itself is the failure that costs the most to notice. */ TEST(the_checkpoint_policy_is_one_of_the_three_that_exist) { @@ -814,7 +789,7 @@ TEST(usage_names_every_flag_it_documents) { fclose(f); CHECK(text.find("--model") != std::string::npos); - CHECK(text.find("--expert-vs-cache-ratio") != std::string::npos); + CHECK(text.find("--host-pool-mib") != std::string::npos); CHECK(text.find("--kv-cache-dtype") != std::string::npos); CHECK(text.find("--num-speculative-tokens") != std::string::npos); CHECK(text.find("--checkpoint-policy") != std::string::npos); diff --git a/tests/gbnf_oracle.cpp b/tests/gbnf_oracle.cpp index f0abf1d6..8b05eae7 100644 --- a/tests/gbnf_oracle.cpp +++ b/tests/gbnf_oracle.cpp @@ -150,8 +150,67 @@ int oracle_impl(const GbnfGrammar& g, uint32_t* bitmask, int64_t n_words, uint64 return RAD_E_STATE; } +void accept_chr(const GbnfRuleSet& rules, const GbnfStack& stack, uint32_t chr, + GbnfStacks& out, SetBuild& build) { + if (stack.empty()) return; + const GbnfElement* pos = stack.back(); + if (is_token_elem(pos)) return; + auto m = match_char(pos, chr); + build.work.add((size_t)(m.second - pos)); + if (!m.first) return; + GbnfStack next(stack.begin(), stack.end() - 1); + if (!is_end_of_sequence(m.second)) next.push_back(m.second); + advance_stack(rules, next, out, build); +} + +int accept_impl(const GbnfGrammar& g, int32_t token, GbnfStacks* out, PartialUtf8* partial) { + const GbnfRuleSet& rules = program_rules(g.program()); + const auto decoded = decode_utf8(g.vocab()->token_piece(token), g.partial()); + const auto& cps = decoded.first; + + OpWork work; + GbnfStacks new_stacks; + SetBuild new_set(work); + GbnfStacks current; + for (const auto& stack : g.stacks()) { + if (stack.empty()) continue; + const GbnfElement* pos = stack.back(); + if (is_token_elem(pos)) { + if (!match_token(pos, token)) continue; + GbnfStack next(stack.begin(), stack.end() - 1); + if (!is_end_of_sequence(pos + 1)) next.push_back(pos + 1); + advance_stack(rules, next, new_stacks, new_set); + } else { + current.push_back(stack); + } + } + for (auto it = cps.begin(), end = cps.end() - 1; it != end && !current.empty(); ++it) { + GbnfStacks next; + SetBuild next_set(work); + for (const auto& cs : current) accept_chr(rules, cs, *it, next, next_set); + current = std::move(next); + } + for (auto& s : current) new_set.insert(new_stacks, std::move(s)); + std::sort(new_stacks.begin(), new_stacks.end()); + *out = std::move(new_stacks); + *partial = decoded.second; + return out->empty() ? RAD_E_STATE : RAD_OK; +} + } /* namespace */ +int gbnf_oracle_accept(const GbnfGrammar& g, int32_t token, GbnfStacks* out, + PartialUtf8* partial) { + if (!out || !partial || !g.vocab()) return RAD_E_INVAL; + try { + return accept_impl(g, token, out, partial); + } catch (const gbnf::GbnfLimit&) { + return RAD_E_FULL; + } catch (const std::bad_alloc&) { + return RAD_E_NOMEM; + } +} + int gbnf_oracle_mask(const GbnfGrammar& g, uint32_t* bitmask, int64_t n_words, uint64_t work_limit) { if (!bitmask || !g.vocab()) return RAD_E_INVAL; diff --git a/tests/gbnf_oracle.h b/tests/gbnf_oracle.h index 239977a0..9716a2c1 100644 --- a/tests/gbnf_oracle.h +++ b/tests/gbnf_oracle.h @@ -26,4 +26,15 @@ namespace rad { int gbnf_oracle_mask(const GbnfGrammar& g, uint32_t* bitmask, int64_t n_words, uint64_t work_limit = 0); +/* THE STATE ACCEPTING `token` LEAVES, the way the stack machinery builds it: every stack advanced + * one code point at a time through accept_chr and the epsilon closure, as upstream's + * llama_grammar_accept_impl does. The engine steps the stacks that match code points through the + * mask plan's automaton instead, and the two must leave the same stack set and the same carried + * partial character. `*out` comes back sorted. Returns RAD_OK, RAD_E_STATE when no stack + * survives, or RAD_E_FULL / RAD_E_NOMEM past the engine's bounds. For a grammar not waiting on + * its trigger, and a token that is not end-of-generation -- accept_token answers those without + * the stacks. */ +int gbnf_oracle_accept(const GbnfGrammar& g, int32_t token, GbnfStacks* out, + PartialUtf8* partial); + } /* namespace rad */ diff --git a/tests/gbnf_test.cpp b/tests/gbnf_test.cpp index 16474401..15a3d326 100644 --- a/tests/gbnf_test.cpp +++ b/tests/gbnf_test.cpp @@ -4,7 +4,9 @@ * (core/sample/gbnf_mask.cpp); tests/gbnf_oracle.cpp computes the same mask the way llama.cpp * does, by rescanning the vocabulary. They are two implementations of one pure function of the * grammar's state, so every case here is the same assertion: at every state a walk reaches, the - * two agree bit for bit and status for status. + * two agree bit for bit and status for status. Accepting is held the same way: the engine steps a + * state through the mask plan's automaton, the oracle through the stack machinery one stack and + * one code point at a time, and every token a walk accepts must leave both in the same state. * * WHAT MAKES A STATE WORTH COMPARING is that the engine reached it the way the sampler does. The * walks below drive a grammar exactly as Sampler::build_step drives a constrained sequence under @@ -243,6 +245,7 @@ struct Tally { * rescanning one stack at a time, could still answer */ int64_t grammars = 0; int64_t mismatches = 0; + int64_t accepts = 0; /* accepted tokens whose new state was compared with the oracle's */ }; std::string show_piece(const std::string& s) { @@ -306,6 +309,32 @@ bool has(const std::vector& m, int32_t id) { return id >= 0 && ((m[(size_t)id >> 5] >> (id & 31)) & 1u); } +/* Accept `id`, holding the state it leaves to the oracle's: the same status, the same stack set + * and the same carried partial character. Returns the engine's status. A side that ran past its + * bounds is not compared, for the reason compare() gives. */ +int accept(GbnfGrammar& g, int32_t id, Tally& t) { + const bool cmp = !g.awaiting_trigger() && !g.vocab()->is_eog(id); + GbnfStacks ref; + PartialUtf8 rp; + const int rs = cmp ? gbnf_oracle_accept(g, id, &ref, &rp) : RAD_OK; + const int as = g.accept_token(id); + if (!cmp || rs == RAD_E_FULL || rs == RAD_E_NOMEM || as == RAD_E_FULL || as == RAD_E_NOMEM) + return as; + ++t.accepts; + bool same = (as >= 0) == (rs >= 0); + if (same && as >= 0) { + GbnfStacks got = g.stacks(); + std::sort(got.begin(), got.end()); + same = got == ref && g.partial().value == rp.value && g.partial().n_remain == rp.n_remain; + } + CHECK(same); + if (!same && ++t.mismatches <= 4) + std::fprintf(stderr, " accept %d '%s': engine status %d with %zu stacks, oracle %d " + "with %zu\n", id, show_piece(g.vocab()->token_piece(id)).c_str(), as, + g.stacks().size(), rs, ref.size()); + return as; +} + /* MAY THE MASK ADMIT A TOKEN THAT ACCEPTING THEN REFUSES? Upstream's mask and upstream's accept * read a piece differently in two places, and the engine reproduces the mask exactly, so an * admitted token can kill the parse: @@ -364,7 +393,7 @@ void walk_and_compare(const std::string& gbnf, const BpeVocab& bv, uint64_t seed g->push_state(); int live = 0; for (int k = 0; k < n_pos; ++k) { - if (k > 0 && g->accept_token(d[(size_t)k - 1]) < 0) { + if (k > 0 && accept(*g, d[(size_t)k - 1], t) < 0) { /* A draft the grammar refuses leaves no parse; the mask there must say so. */ compare(*g, v, m[(size_t)k], ref, t, name + " after a refused draft"); break; @@ -388,7 +417,7 @@ void walk_and_compare(const std::string& gbnf, const BpeVocab& bv, uint64_t seed bool ok = true; for (size_t k = 0; k < j && ok; ++k) { const bool quirk = accept_may_refuse(*g, gbnf, v, d[k]); - const int as = g->accept_token(d[k]); + const int as = accept(*g, d[k], t); ok = as >= 0; CHECK(ok || quirk || as == RAD_E_FULL || as == RAD_E_NOMEM); } @@ -396,7 +425,7 @@ void walk_and_compare(const std::string& gbnf, const BpeVocab& bv, uint64_t seed const int32_t bonus = pick_admitted(m[j], bv, rng); if (bonus < 0) break; const bool quirk = accept_may_refuse(*g, gbnf, v, bonus); - const int as = g->accept_token(bonus); + const int as = accept(*g, bonus, t); if (as == RAD_E_FULL || as == RAD_E_NOMEM) break; /* the parse outgrew its bounds */ CHECK(as >= 0 || quirk); if (as < 0) break; @@ -421,14 +450,14 @@ void replay_and_compare(const std::string& gbnf, const BpeVocab& bv, const int n_pos = (int)std::min(4, toks.size() - i); g->push_state(); for (int k = 0; k < n_pos; ++k) { - if (k > 0 && g->accept_token(toks[i + (size_t)k - 1]) < 0) { CHECK(false); break; } + if (k > 0 && accept(*g, toks[i + (size_t)k - 1], t) < 0) { CHECK(false); break; } const std::string where = name + " token " + std::to_string(i + (size_t)k); if (compare(*g, v, m, ref, t, where) < 0) break; CHECK(has(m, toks[i + (size_t)k])); } CHECK_OK(g->rollback()); const size_t n_acc = std::min(3, toks.size() - i); - for (size_t k = 0; k < n_acc; ++k) REQUIRE(g->accept_token(toks[i + k]) >= 0); + for (size_t k = 0; k < n_acc; ++k) REQUIRE(accept(*g, toks[i + k], t) >= 0); i += n_acc; } ++t.grammars; @@ -436,9 +465,10 @@ void replay_and_compare(const std::string& gbnf, const BpeVocab& bv, void report(const char* what, const Tally& t) { std::fprintf(stderr, " %s: %lld grammars, %lld masks compared (%lld at a split character, " - "%lld dead); %lld beyond the oracle's bound, %lld beyond the engine's\n", what, + "%lld dead), %lld accepts; %lld beyond the oracle's bound, %lld beyond the " + "engine's\n", what, (long long)t.grammars, (long long)t.masks, (long long)t.partial, (long long)t.dead, - (long long)t.skipped, (long long)t.bounded); + (long long)t.accepts, (long long)t.skipped, (long long)t.bounded); } /* ================================================================== grammars */ diff --git a/tests/legacy/chatdiff.cpp b/tests/legacy/chatdiff.cpp index b9c4932b..c86fda88 100644 --- a/tests/legacy/chatdiff.cpp +++ b/tests/legacy/chatdiff.cpp @@ -186,20 +186,50 @@ Verdict compare(const Bench& b, const std::string& text) { o.content.find(f.call_open.substr(a, e - a)) != std::string::npos; } v.same = o.content == m.content && o.reasoning == m.reasoning && o.calls.size() == m.calls.size(); + /* ARGUMENTS THE OLD READER LEFT AS NO JSON AT ALL are not a reading to agree with: it passed a + * typed value's text through bare (`"verbose":True`, `"extra":}`), which no client can parse, + * and the new reader makes every complete such value JSON (chatparse.cpp, ValueOut). So the + * arguments are compared only where the old object is JSON, and there byte for byte; the new + * reader's own reading of the rest is held by the decided shapes and the streaming checks. */ + auto args_agree = [](const std::string& old_a, const std::string& new_a) { + if (old_a == new_a || !nlohmann::json::accept(old_a)) return true; + /* NOR IS A NEWLINE THE OLD READER TOOK OFF A VALUE'S FRONT that the tag before it had + * already ended with -- Qwen's `\n` -- the newline the template writes + * when the value itself starts with one. Every other byte must agree. */ + const ojson o = ojson::parse(old_a, nullptr, false); + const ojson n = ojson::parse(new_a, nullptr, false); + if (!o.is_object() || !n.is_object() || o.size() != n.size()) return false; + for (auto it = o.begin(); it != o.end(); ++it) { + if (!n.contains(it.key())) return false; + const ojson& nv = n.at(it.key()); + if (nv == it.value()) continue; + if (!nv.is_string() || !it.value().is_string()) return false; + const std::string& ns = nv.get_ref(); + if (ns.empty() || ns[0] != '\n' || ns.compare(1, std::string::npos, + it.value().get_ref()) != 0) + return false; + } + return true; + }; for (size_t i = 0; v.same && i < o.calls.size(); ++i) - v.same = o.calls[i].name == m.calls[i].name && o.calls[i].arguments == m.calls[i].arguments; + v.same = o.calls[i].name == m.calls[i].name && + args_agree(o.calls[i].arguments, m.calls[i].arguments); + for (const legacy::ToolCall& c : o.calls) + for (char ch : c.arguments) + if ((unsigned char)ch < 0x20) v.old_raw_control = true; if (!v.same) v.detail = " old: " + show(o) + "\n new: " + show(m); return v; } std::string judge(const Verdict& v) { if (v.strict) { - if (v.old_clean && !v.same) return "both read the reply within the grammar and disagree"; + if (v.old_clean && !v.same && !v.old_raw_control) + return "both read the reply within the grammar and disagree"; if (!v.old_clean && !v.bare_lift) return "the new parser read within the grammar a reply the old grammar rejected"; return std::string(); } - if (v.old_clean && !v.old_call_syntax) + if (v.old_clean && !v.old_call_syntax && !v.old_raw_control) return "the new parser left the grammar on a reply the old grammar accepted"; return std::string(); } @@ -274,6 +304,24 @@ std::string check_stream(const ReplyParser& p, const std::string& text, if (!err.empty()) return err; if (!same(got, expect)) return "the deltas add up to\n " + show(got); if (!same(s->message(), expect)) return "the message is\n " + show(s->message()); + /* Where each call begins in the reply, which an open call's text is read back from, is a + * fact of the reply, not of how it was cut. */ + for (size_t i = 0; i < expect.calls.size(); ++i) { + const ReplyCall& a = s->message().calls[i]; + const ReplyCall& b = expect.calls[i]; + if (a.at != b.at || a.content_at != b.content_at || a.content_held != b.content_held) + return "call " + std::to_string(i) + " begins at " + std::to_string(a.at) + " cut this way, " + + std::to_string(b.at) + " read whole"; + if (b.at >= text.size() || (i > 0 && b.at <= expect.calls[i - 1].at)) + return "call " + std::to_string(i) + " begins at " + std::to_string(b.at) + ", outside the reply"; + } + /* A closed call is one a client is handed to run: its arguments are JSON, whatever the + * model wrote into them -- in a reply that is UTF-8, as every reply is once the decoder has + * sanitised it. */ + if (sanitize(text) == text) + for (const ReplyCall& c : expect.calls) + if (c.closed && !nlohmann::json::accept(c.arguments)) + return "a closed call's arguments are no JSON: " + q(c.arguments); return std::string(); } @@ -343,6 +391,7 @@ std::vector rendered_corpus() { v.push_back(message("", "", { call("write", { { "path", "/work/x.xml" }, { "content", "v\nx" } }) })); v.push_back(message("", "", { call("write", { { "path", "" }, { "content", "" } }) })); + v.push_back(message("", "", { call("write", { { "path", "/a" }, { "content", "\n\nx\n\n" } }) })); v.push_back(message("", "", { call("ping", ojson::object()) })); return v; } @@ -400,6 +449,20 @@ std::vector adversarial(const Model& m) { add("JSON then a stray character", T + C(m, "configure", { { "extra", "{\"a\": 1}x" } })); add("an unterminated JSON string", T + C(m, "configure", { { "extra", "\"abc" } })); add("a number that is not one", T + C(m, "read", { { "path", "/a" }, { "limit", "01" } })); + add("Python literals", T + C(m, "configure", { { "verbose", "True" }, { "nothing", "None" } })); + add("a Python dict with literals", T + C(m, "configure", + { { "extra", "{'a': True, 'b': None, 'c': 'False'}" } })); + add("an empty typed value", T + C(m, "configure", { { "level", "" } })); + add("a typed value that is no JSON", T + C(m, "configure", { { "verbose", "yes please" } })); + add("JSON strings holding a raw line break and tab", T + C(m, "configure", + { { "extra", "{\"a\": \"line1\nline2\",\n \"b\": \"\tx\"}" } })); + add("Python containers that are no JSON", T + C(m, "configure", + { { "extra", "{'a': 1, 'b': [2, 3],}" }, { "tags", "['x', nan]" } })); + add("a container missing its close", T + C(m, "configure", { { "extra", "{'a': [1, 2}" } })); + add("JSON a client cannot read", T + C(m, "configure", + { { "level", "1e400" }, { "extra", R"({"a": "\ud800"})" } })); + add("an escaped quote in a double-quoted string", T + C(m, "configure", + { { "tags", " [\"it\\'s\", 'x']" } })); add("unicode", T + "Größe 大小 🚀 " + C(m, "write", { { "path", "/中.txt" }, { "content", "こんにちは 🌍" } })); add("CDATA with brackets and tags", T + C(m, "write", { { "path", "/a" }, { "content", "\n indented\n]]>" } })); @@ -450,6 +513,9 @@ std::vector adversarial(const Model& m) { add("a call with no closing wrapper", T + "\n\n\nls\n\n\n" "\n\n\n/a\n\n\n"); + add("a call closed by its wrapper alone", + T + "\n\n\nls\n\n\n" + + C(m, "read", { { "path", "/a" } })); add("an argument with no newline after its name", T + "\n\nls\n\n"); } else { diff --git a/tests/legacy/chatdiff.h b/tests/legacy/chatdiff.h index 46cc4ba1..8a146d91 100644 --- a/tests/legacy/chatdiff.h +++ b/tests/legacy/chatdiff.h @@ -92,6 +92,12 @@ struct Verdict { * without its wrapper, which the legacy lifter takes only when nothing else in the reply * parses as a call, and which the streaming parser always reads as one. */ bool old_call_syntax = false; + /* A call in the legacy answer has a raw control character in its arguments: its JSON reader + * took a string holding one, which the schema grammar refuses -- the reply goes on in the + * grammar's text arm, and ends the value at its suffix, where the legacy reader kept reading + * -- or it passed a typed value's text through bare. Neither is JSON, and neither is a + * reading to hold the streaming parser to. */ + bool old_raw_control = false; std::string detail; /* both answers, when they differ */ }; Verdict compare(const Bench& b, const std::string& text); diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index 9001aea9..327da757 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -16,6 +16,7 @@ #include "device/device.h" #include "plugin/registry.h" #include "runtime/tierexec.h" +#include "sched/mem_iface.h" #include "rad_internal.h" #include @@ -85,6 +86,7 @@ static std::vector hybrid_groups(bool with_linear = true) { struct Fixture { Pools pools; + HostArena ck; /* the engine's snapshot store, in miniature */ KVManager kv; PrefixCache pc; Config cfg = small_config(); @@ -98,6 +100,11 @@ struct Fixture { if (s < 0) return s; s = kv.configure(groups, cfg, pools.kv()); if (s < 0) return s; + if (kv.checkpoint_bytes() > 0 && cfg.checkpoint_slots > 0) { + s = ck.open(kv.checkpoint_bytes(), kv.checkpoint_bytes() * cfg.checkpoint_slots); + if (s < 0) return s; + kv.set_checkpoint_store(&ck, 0); + } return pc.configure(cfg, &kv, cfg.checkpoint_interval); } }; @@ -192,11 +199,12 @@ TEST(a_refused_backing_allocation_says_it_was_refused_and_why) { /* ================================================================== the derived budget */ TEST(derived_budget_takes_the_statics_off_the_top_then_divides_the_rest) { + /* With no lender stated the experts come first; what each side gets is the subject of the + * cases below. */ Config c = small_config(); c.vram_weights_mib = 0; /* both unset: derive */ c.vram_kv_mib = 0; c.gpu_headroom_mib = 96; - c.expert_cache_ratio = 0.75; c.max_seqs = 8; c.max_ctx = 2048; @@ -207,62 +215,111 @@ TEST(derived_budget_takes_the_statics_off_the_top_then_divides_the_rest) { f.statics = 2LL << 30; /* this rank's shard of the non-expert weights */ f.experts = 200LL << 30; /* far more than fits: the plane is elastic */ f.kv_ceiling = 100LL << 30; /* far above any share, so no cap fires */ + f.kv_one = 1LL << 30; VramBudget b; CHECK_OK(vram_budget_resolve(c, { f }, &b)); - CHECK_EQ(b.claimable, f.capacity - (512LL << 20) - (96LL << 20) - (144LL << 20)); + /* Held, the driver's drift on it, the headroom and the arena. */ + CHECK_EQ(b.drift, 16LL << 20); + CHECK_EQ(b.claimable, f.capacity - (512LL << 20) - (16LL << 20) - (96LL << 20) - (144LL << 20)); CHECK(b.derived_weights && b.derived_kv); - /* THE FLOOR IS NOT A SHARE. The statics come out whole before the ratio sees anything, so - * lowering the ratio can never demote an attention projection to host memory. */ + /* THE FLOOR IS NOT A SHARE. The statics come out whole before the split sees anything, so + * nothing the cache is given can demote an attention projection to host memory. */ CHECK_EQ(b.statics, f.statics); CHECK_EQ(b.elastic, b.claimable - f.statics); CHECK_EQ(b.experts + b.kv, b.elastic); CHECK_EQ(b.weights, b.statics + b.experts); - /* Three quarters and a quarter OF THE ELASTIC PART, which is the whole point: against the - * claimable total the weights are a much larger fraction than 0.75, and that is correct. */ - const double share = (double)b.experts / (double)b.elastic; - CHECK(share > 0.74 && share < 0.76); - const int64_t MiB = 1024 * 1024; const int64_t unclaimed = f.capacity - (512LL << 20) - f.arena - c.vram_weights_mib * MiB - c.vram_kv_mib * MiB; - CHECK(unclaimed >= 96 * MiB); /* never less than the headroom asked for */ - CHECK(unclaimed < 98 * MiB); /* and never more than MiB rounding can strand */ + CHECK(unclaimed >= 112 * MiB); /* never less than the headroom and the drift */ + CHECK(unclaimed < 114 * MiB); /* and never more than MiB rounding can strand */ } -TEST(the_ratio_moves_the_elastic_part_and_only_that) { - /* The same card at two ratios. The statics are identical in both; everything that moves is - * the division of what was left. */ +static Config derive_config() { + Config c = small_config(); + c.vram_weights_mib = 0; c.vram_kv_mib = 0; c.gpu_headroom_mib = 96; + return c; +} +static VramFacts big_moe_facts() { VramFacts f{}; f.capacity = 32LL << 30; f.free = f.capacity - (512LL << 20); f.arena = 144LL << 20; f.statics = 4LL << 30; - f.experts = 200LL << 30; + f.experts = 40LL << 30; /* more than the card: some must stream */ f.kv_ceiling = 100LL << 30; + f.kv_one = 2LL << 30; + return f; +} - Config c7 = small_config(); - c7.vram_weights_mib = 0; c7.vram_kv_mib = 0; c7.gpu_headroom_mib = 96; - c7.expert_cache_ratio = 0.7; - VramBudget b7; - CHECK_OK(vram_budget_resolve(c7, { f }, &b7)); +/* A LENDING CACHE TAKES EVERYTHING THE EXPERTS CAN DO WITHOUT. The experts keep on the card what + * the host pool cannot hold (expert_vram_floor, which place_test holds to the planner) and not a + * byte more: every block the cache does not use is lent back to them. */ +TEST(a_lending_cache_takes_everything_the_experts_can_do_without) { + VramFacts f = big_moe_facts(); + f.lends = true; + f.expert_floor = 16LL << 30; /* the host pool takes 24 of the 40 */ + Config c = derive_config(); + VramBudget b; + CHECK_OK(vram_budget_resolve(c, { f }, &b)); + CHECK(b.lends); + CHECK_EQ(b.expert_floor, 16LL << 30); + CHECK_EQ(b.experts, b.expert_floor); + CHECK_EQ(b.kv, b.elastic - b.expert_floor); + CHECK_EQ(b.weights, b.statics + b.experts); - Config c3 = small_config(); - c3.vram_weights_mib = 0; c3.vram_kv_mib = 0; c3.gpu_headroom_mib = 96; - c3.expert_cache_ratio = 0.3; - VramBudget b3; - CHECK_OK(vram_budget_resolve(c3, { f }, &b3)); + /* AND THE HOST POOL IS WHAT MOVES IT: a larger pool takes experts off the card, and the cache + * gets exactly that much more. */ + VramFacts g = f; + g.expert_floor = 12LL << 30; + Config c2 = derive_config(); + VramBudget b2; + CHECK_OK(vram_budget_resolve(c2, { g }, &b2)); + CHECK_EQ(b2.experts, b.experts - (4LL << 30)); + CHECK_EQ(b2.kv, b.kv + (4LL << 30)); + CHECK_EQ(b2.statics, b.statics); +} - CHECK_EQ(b7.statics, b3.statics); /* the floor does not move */ - CHECK_EQ(b7.elastic, b3.elastic); - CHECK(b7.experts > b3.experts); /* 0.7 gives the experts more than 0.3 does */ - CHECK(b7.kv < b3.kv); - /* And even at 0.3 the weight pool still holds every static byte. */ - CHECK(b3.weights > b3.statics); - CHECK_EQ(b3.weights, b3.statics + b3.experts); +/* WITHOUT A LENDER a block the cache does not use sits empty, so the experts come first and the + * cache keeps one --max-model-len sequence. */ +TEST(without_a_lender_the_experts_come_first_and_the_cache_keeps_one_sequence) { + VramFacts f = big_moe_facts(); + f.lends = false; + f.expert_floor = 16LL << 30; + Config c = derive_config(); + VramBudget b; + CHECK_OK(vram_budget_resolve(c, { f }, &b)); + CHECK(!b.lends); + CHECK_EQ(b.kv, f.kv_one); + CHECK_EQ(b.experts, b.elastic - f.kv_one); +} + +/* THE CACHE NEVER GETS LESS THAN ONE FULL-LENGTH SEQUENCE: a context the API accepts and no pool + * can hold is a configuration error, and the experts' shortfall is the planner's to name. */ +TEST(the_cache_keeps_one_full_length_sequence_even_against_the_expert_floor) { + VramFacts f = big_moe_facts(); + f.lends = true; + f.expert_floor = f.experts; /* every expert wants the card */ + Config c = derive_config(); + VramBudget b; + CHECK_OK(vram_budget_resolve(c, { f }, &b)); + CHECK_EQ(b.kv, f.kv_one); + CHECK_EQ(b.experts, b.elastic - f.kv_one); + + /* And a cache that could never use more than its ceiling gives the rest to the experts. */ + VramFacts g = big_moe_facts(); + g.lends = true; + g.expert_floor = 1LL << 30; + g.kv_ceiling = 3LL << 30; + Config c2 = derive_config(); + VramBudget b2; + CHECK_OK(vram_budget_resolve(c2, { g }, &b2)); + CHECK_EQ(b2.kv, g.kv_ceiling); + CHECK_EQ(b2.experts, b2.elastic - g.kv_ceiling); } TEST(neither_side_is_given_more_than_it_could_use) { @@ -271,7 +328,6 @@ TEST(neither_side_is_given_more_than_it_could_use) { * allocated into a pool that would sit empty. */ Config c = small_config(); c.vram_weights_mib = 0; c.vram_kv_mib = 0; c.gpu_headroom_mib = 96; - c.expert_cache_ratio = 0.75; VramFacts f{}; f.capacity = 32LL << 30; @@ -291,13 +347,12 @@ TEST(neither_side_is_given_more_than_it_could_use) { } TEST(a_dense_model_has_no_expert_share_to_lose) { - /* A dense model in miniature: 42 dense layers and not one expert. The ratio's weight share has + /* A dense model in miniature: 42 dense layers and not one expert. An expert share would have * nothing to claim it, and a share nothing can claim is not slack -- it is memory no pool will * ever touch. Handing it to the weights anyway reserves tens of gigabytes for 0 B of experts * and leaves the cache short of the worst case it was asked to back. */ Config c = small_config(); c.vram_weights_mib = 0; c.vram_kv_mib = 0; c.gpu_headroom_mib = 96; - c.expert_cache_ratio = 0.75; c.max_seqs = 8; c.max_ctx = 131072; @@ -335,7 +390,6 @@ TEST(the_engine_s_queues_come_off_the_card_before_the_split) { c.vram_weights_mib = 0; c.vram_kv_mib = 0; c.gpu_headroom_mib = 96; - c.expert_cache_ratio = 0.75; VramFacts f{}; f.capacity = 32LL << 30; f.free = f.capacity - (512LL << 20); @@ -352,7 +406,6 @@ TEST(the_engine_s_queues_come_off_the_card_before_the_split) { c2.vram_weights_mib = 0; c2.vram_kv_mib = 0; c2.gpu_headroom_mib = 96; - c2.expert_cache_ratio = 0.75; VramFacts g = f, h = f; g.n_queues = 2; g.queue_bytes = 33LL << 20; h.n_queues = 3; h.queue_bytes = 33LL << 20; /* a rank with a second compute lane */ @@ -363,12 +416,13 @@ TEST(the_engine_s_queues_come_off_the_card_before_the_split) { CHECK_EQ(b.claimable, b0.claimable - (99LL << 20)); CHECK(b.report.find("hardware queues") != std::string::npos); - /* What is left after the pools is still the headroom, with the queues and the staging paid. */ + /* What is left after the pools is still the headroom and the drift, with the queues and the + * staging paid. */ const int64_t MiB = 1024 * 1024; const int64_t unclaimed = f.capacity - (512LL << 20) - f.arena - f.staging - b.queues - c2.vram_weights_mib * MiB - c2.vram_kv_mib * MiB; - CHECK(unclaimed >= 96 * MiB); - CHECK(unclaimed < 98 * MiB); + CHECK(unclaimed >= 112 * MiB); + CHECK(unclaimed < 114 * MiB); } TEST(a_stated_budget_still_wins_and_the_other_side_still_derives) { @@ -461,16 +515,11 @@ TEST(kv_configure_reports_and_sizes) { CHECK_EQ(f.kv.checkpoint_bytes(), 16384ll); CHECK_EQ(f.kv.checkpoint_slots(), 4ll); CHECK(full->n_blocks > 0); - /* 1 MiB minus 8 states, 4 checkpoints and TWO ALIGNMENT UNITS, all of it in pages of 2 KiB. - * The two units are the budget admitting what the pool actually spends: every reserve() - * aligns its offset up, so a carve that hands the paged groups every remaining byte overruns - * by the padding. One is the paged group's own. The other is the checkpoint region's, and it - * is an allowance rather than an exact figure -- the slots are reserved LAST, after every - * group, so where the region starts is decided by the paged split that has not run yet. - * Without it the last slot does not fit a plan the report has just called a fit, on whichever - * models happen to leave the cursor off a boundary. */ - CHECK_EQ(full->n_blocks, - ((1ll << 20) - 8 * 16384 - 4 * 16384 - 2 * RAD_ALIGN_UNIT) / 2048); + /* 1 MiB minus 8 states and ONE ALIGNMENT UNIT, all of it in pages of 2 KiB. The unit is the + * budget admitting what the pool actually spends: every reserve() aligns its offset up, so a + * carve that hands the paged groups every remaining byte overruns by the padding. The four + * snapshots cost the pool nothing -- they are in host memory. */ + CHECK_EQ(full->n_blocks, ((1ll << 20) - 8 * 16384 - RAD_ALIGN_UNIT) / 2048); } TEST(kv_ranks_with_unequal_pools_carve_the_least_ranks_blocks_under_a_cap) { @@ -508,6 +557,40 @@ TEST(kv_ranks_with_unequal_pools_carve_the_least_ranks_blocks_under_a_cap) { CHECK_EQ(c.kv.plan(G_FULL)->n_blocks, tc / 16); } +/* A RANK WHOSE ONLY PAGED GROUP IS ZERO (rad_kv_group_zero) pages nothing of its own, so its pages + * limit nobody: it reports no token count, takes the cap the ranks holding the cache set, carves + * nothing for the group and still holds the shared table's block count. Without a cap there is no + * count to hold, and the carve says so rather than leaving the group at zero blocks. */ +TEST(kv_a_rank_whose_only_paged_group_is_zero_takes_the_others_block_count) { + std::vector zg = hybrid_groups(); + zg[1].zero = true; /* the one paged group */ + Fixture a, z; + a.cfg.checkpoint_slots = z.cfg.checkpoint_slots = 0; + CHECK_OK(a.pools.configure(a.cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator())); + CHECK_OK(z.pools.configure(z.cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator())); + CHECK_OK(a.kv.plan_groups(hybrid_groups(), a.cfg)); + CHECK_OK(z.kv.plan_groups(zg, z.cfg)); + const int64_t ta = a.kv.paged_tokens(a.pools.kv().avail()); + CHECK(ta > 0); + CHECK_EQ(z.kv.paged_tokens(z.pools.kv().avail()), KVManager::kUnboundedTokens); + a.kv.cap_paged_tokens(ta); + z.kv.cap_paged_tokens(ta); + CHECK_OK(a.kv.carve(a.pools.kv())); + CHECK_OK(z.kv.carve(z.pools.kv())); + CHECK_EQ(z.kv.plan(G_FULL)->n_blocks, a.kv.plan(G_FULL)->n_blocks); + CHECK(z.kv.plan(G_FULL)->base == nullptr); + CHECK_EQ(z.kv.plan(G_FULL)->pool_bytes, (int64_t)0); + CHECK(!z.kv.lendable(G_FULL)); + /* Its recurrent state is its own and carved as on any rank. */ + CHECK(z.kv.plan(G_GDN)->base != nullptr); + + Fixture u; + u.cfg.checkpoint_slots = 0; + CHECK_OK(u.pools.configure(u.cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator())); + CHECK_OK(u.kv.plan_groups(zg, u.cfg)); + CHECK_EQ(u.kv.carve(u.pools.kv()), RAD_E_STATE); +} + TEST(kv_refuses_a_group_with_no_block_size) { /* Block size comes off the resolved attention kernel. A zero here means the attention op did * not resolve, and the manager refuses rather than inventing 16. */ @@ -529,8 +612,9 @@ TEST(kv_refuses_when_fixed_costs_do_not_fit) { CHECK_OK(f.pools.configure(f.cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator())); CHECK_EQ(f.kv.configure(hybrid_groups(), f.cfg, f.pools.kv()), RAD_E_NOMEM); - /* And the checkpoint budget is a budget: the same config fits at 8 sequences with no - * snapshots and stops fitting once --checkpoint-slots asks for more than is left. */ + /* AND THE SNAPSHOTS ARE NOT PART OF IT. The same config fits at 8 sequences whatever + * --checkpoint-slots asks for -- 64 x 16 KiB is the whole pool, and it is host memory -- and + * the paged groups get exactly what they get with none. */ Fixture g2; g2.cfg.max_seqs = 8; g2.cfg.checkpoint_slots = 0; @@ -538,9 +622,11 @@ TEST(kv_refuses_when_fixed_costs_do_not_fit) { CHECK_OK(g2.kv.configure(hybrid_groups(), g2.cfg, g2.pools.kv())); Fixture g3; g3.cfg.max_seqs = 8; - g3.cfg.checkpoint_slots = 64; /* 64 x 16 KiB = 1 MiB, on top of the state */ + g3.cfg.checkpoint_slots = 64; CHECK_OK(g3.pools.configure(g3.cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator())); - CHECK_EQ(g3.kv.configure(hybrid_groups(), g3.cfg, g3.pools.kv()), RAD_E_NOMEM); + CHECK_OK(g3.kv.configure(hybrid_groups(), g3.cfg, g3.pools.kv())); + CHECK_EQ(g3.kv.fixed_bytes(), g2.kv.fixed_bytes()); + CHECK_EQ(g3.kv.plan(G_FULL)->n_blocks, g2.kv.plan(G_FULL)->n_blocks); } @@ -920,6 +1006,11 @@ TEST(prefix_cache_lru_eviction_order) { publish(f, 2, b, 16); publish(f, 3, c, 16); CHECK_EQ(f.pc.size(), 3ll); + /* WHILE THE SEQUENCES HOLD THEM, EVICTION TAKES NOTHING: releasing the cache's reference + * would free no block and only lose the entry. */ + CHECK_EQ(f.pc.evict_lru(3), 0ll); + CHECK_EQ(f.pc.size(), 3ll); + for (uint64_t id : { 1, 2, 3 }) f.kv.free_sequence(id); /* Touch A, so the order becomes B, C, A. */ CHECK_EQ(f.pc.lookup(a, {}).n_attn_tokens, 16); @@ -931,9 +1022,6 @@ TEST(prefix_cache_lru_eviction_order) { CHECK_EQ(f.pc.lookup(b, {}).n_attn_tokens, 0); /* B was the oldest and went first */ CHECK_EQ(f.pc.lookup(c, {}).n_attn_tokens, 16); CHECK_EQ(f.pc.lookup(a, {}).n_attn_tokens, 16); - - /* Eviction releases the cache's reference; it does not free a block a sequence still holds. */ - CHECK(f.kv.block_refcount(G_FULL, f.kv.block_table(2, G_FULL)[0]) >= 1); } TEST(prefix_cache_holds_a_reference_on_every_indexed_block) { @@ -975,6 +1063,8 @@ TEST(the_cache_reports_the_context_it_is_holding) { /* And it falls when the cache gives blocks back, which is the half that makes it an answer * to "is the pool releasing anything". */ + f.kv.free_sequence(1); + f.kv.free_sequence(2); f.pc.evict_lru(1); CHECK_EQ(f.pc.size() * f.pc.block_size(), 32); f.pc.clear(); @@ -1051,6 +1141,74 @@ TEST(split_lookup_reuses_attention_between_checkpoints) { CHECK_EQ(f.pc.lookup(other, {}).n_linear_tokens, 0); } +/* The chained block hashes of `tokens`, one a block, as the cache computes them. */ +static std::vector chain_of(const std::vector& tokens, int bs) { + std::vector hs; + BlockHash parent; + for (int b = 0; b + bs <= (int)tokens.size(); b += bs) { + parent = chain_block_hash(parent, tokens.data() + b, bs, nullptr, 0, b); + hs.push_back(parent); + } + return hs; +} +static void ckpt_at(Fixture& f, uint64_t session, const std::vector& hs, int64_t pos) { + int32_t slot = -1; + CHECK_OK(f.pc.reserve_checkpoint(session, pos, hs[(size_t)(pos / 16 - 1)], &slot)); + CHECK(slot >= 0); + f.pc.commit_checkpoint(hs[(size_t)(pos / 16 - 1)]); +} + +/* A CHECKPOINT AT THE TAIL OF A PROMPT, off the interval, is one the next turn resumes from: the + * lookup takes the deepest snapshot under the hit wherever it sits on a block boundary. */ +TEST(a_checkpoint_at_the_tail_of_a_prompt_is_found_and_the_deepest_wins) { + Fixture f; + CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/4)); + const auto prompt = tok_run(7000, 336); + publish(f, 1, prompt, 320); + const std::vector hs = chain_of(prompt, 16); + ckpt_at(f, 1, hs, 128); /* on the interval */ + ckpt_at(f, 1, hs, 304); /* the tail: a block boundary, not an interval */ + CacheHit h = f.pc.lookup(prompt, {}); + CHECK_EQ(h.n_attn_tokens, 320); + CHECK_EQ(h.n_linear_tokens, 304); + + /* A prompt that shares only the first 200 tokens reaches 128 and not 304. */ + auto other = prompt; + for (size_t k = 200; k < other.size(); ++k) other[k] += 50000; + CHECK_EQ(f.pc.lookup(other, {}).n_linear_tokens, 128); + + /* Off a block boundary there is no key to hold it by. */ + int32_t slot = -1; + CHECK_EQ(f.pc.reserve_checkpoint(1, 300, hs[300 / 16 - 1], &slot), RAD_E_INVAL); +} + +/* A CONVERSATION'S SNAPSHOTS BELONG TO ITS LATEST TURN, so the retention policy sees one session + * with one tip rather than one tip a turn. What a diverging conversation shares moves with the + * prefix it shares, and only that. */ +TEST(a_turn_that_extends_a_conversation_takes_over_its_snapshots) { + Fixture f; + CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/8)); + const auto p1 = tok_run(7000, 336); + publish(f, 1, p1, 320); + const std::vector hs = chain_of(p1, 16); + ckpt_at(f, 1, hs, 128); + ckpt_at(f, 1, hs, 256); + CHECK_EQ(f.pc.checkpoints(1).size(), 2u); + + auto p2 = p1; + for (int k = 0; k < 64; ++k) p2.push_back(90000 + k); + publish(f, 2, p2, 400); + CHECK(f.pc.checkpoints(1).empty()); + CHECK(f.pc.checkpoints(2) == (std::vector{ 128, 256 })); + CHECK_EQ(f.pc.sessions_tracked(), 1ll); + + auto p3 = p1; + for (size_t k = 200; k < p3.size(); ++k) p3[k] += 50000; + publish(f, 3, p3, 320); + CHECK(f.pc.checkpoints(3) == (std::vector{ 128 })); + CHECK(f.pc.checkpoints(2) == (std::vector{ 256 })); +} + TEST(checkpoint_interval_must_be_a_block_multiple) { Fixture f; f.cfg.checkpoint_interval = 100; /* not a multiple of 16 */ @@ -1587,214 +1745,64 @@ TEST(a_follower_takes_the_leaders_mark) { * model has, and it is the only shape for which a checkpoint slot is managed elastically. The * second state dimension is solved for rather than written down, because a constant that happened * to clear a 2 MiB granule would quietly stop testing anything on a device with a larger one. */ -static std::vector big_linear_groups(int64_t want_state_bytes) { - std::vector g = hybrid_groups(/*with_linear=*/false); - KVGroupInfo k; - k.name = "gdn"; - k.decl.kind = RAD_KV_LINEAR; - k.decl.dtype = RAD_F32; - k.decl.n_head_kv = 4; - k.decl.state_dim[0] = 256; - k.layers = { 2, 3, 4, 5 }; - /* bytes = n_head_kv * d0 * d1 * sizeof(f32) * n_layers */ - const int64_t per_d1 = 4ll * 256 * 4 * (int64_t)k.layers.size(); - k.decl.state_dim[1] = (int32_t)std::max(16, (want_state_bytes + per_d1 - 1) / per_d1); - g.push_back(k); - return g; -} +/* ================================================================== the snapshot store */ -struct BigCkpt { - Pools pools; - KVManager kv; - Config cfg = small_config(); - - int build(int64_t ckpt_slots = 4) { - cfg.vram_kv_mib = 1024; - cfg.max_seqs = 2; - cfg.max_tok = 256; - cfg.checkpoint_slots = ckpt_slots; - int s = pools.configure(cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator()); - if (s < 0) return s; - return kv.configure(big_linear_groups(2 * Pool::granule()), cfg, pools.kv()); - } -}; - -TEST(a_checkpoint_slot_is_backed_when_it_is_handed_out) { - if (!VMem::supported()) { - std::fprintf(stderr, " SKIP a_checkpoint_slot_is_backed_when_it_is_handed_out: no VMM\n"); - return; - } - BigCkpt f; - CHECK_OK(f.build(/*ckpt_slots=*/4)); - REQUIRE(f.pools.kv().elastic()); - CHECK_EQ(f.kv.checkpoint_slots(), 4); - CHECK_EQ(f.kv.free_checkpoint_slots(), 4); - CHECK(f.kv.checkpoint_bytes() >= Pool::granule()); - - const int64_t idle = f.pools.kv().committed(); - int32_t a = -1, b = -1; - CHECK_OK(f.kv.alloc_checkpoint(&a)); - const int64_t one = f.pools.kv().committed(); - CHECK(one > idle); /* taking one costs the card */ - CHECK_OK(f.kv.alloc_checkpoint(&b)); - CHECK(f.pools.kv().committed() > one); - - /* AND GIVING IT BACK RELEASES IT EXACTLY, which is what the granule-aligned stride buys: an - * unaligned slot would round its release inward and leave a partial granule backed forever. */ - f.kv.free_checkpoint(b); - CHECK_EQ(f.pools.kv().committed(), one); - f.kv.free_checkpoint(a); - CHECK_EQ(f.pools.kv().committed(), idle); - - /* The slot comes back at the same address and really backed: the pointer never moved, only - * the pages under it. Asked of the pool rather than by writing to it -- an elastic range is - * DEVICE memory even here, because it comes from the driver and not from the fixture's - * allocators, so a host store to it is a fault and not a test. */ - int32_t again = -1; - CHECK_OK(f.kv.alloc_checkpoint(&again)); - void* p = f.kv.checkpoint_ptr(again); - REQUIRE(p != nullptr); - const int64_t off = (char*)p - (char*)f.pools.kv().base(); - CHECK(f.pools.kv().is_committed(off, f.kv.checkpoint_bytes())); - f.kv.free_checkpoint(again); - CHECK(!f.pools.kv().is_committed(off, f.kv.checkpoint_bytes())); -} - -/* THE OTHER HALF OF THE SAME DECISION. A snapshot smaller than a granule cannot be committed on - * its own without rounding the slot up to one, which on this fixture's 16 KiB state is 128x the - * address space to manage a charge of 64 KiB. Those slots stay in the eagerly backed region -- - * so the whole point of the test is that handing one out moves NOTHING, and the slot works - * anyway. Without this the engine would silently pick the mode and nothing would say which. */ -TEST(a_snapshot_below_a_granule_is_not_managed) { - if (!VMem::supported()) { - std::fprintf(stderr, " SKIP a_snapshot_below_a_granule_is_not_managed: no VMM\n"); - return; - } +/* A SLOT IS HOST MEMORY AND THE POOL NEVER SEES IT. Taking one, writing it and giving it back + * moves nothing the KV pool reports, and the bytes are the store's: what is written through + * checkpoint_ptr is what the store holds at that slot. */ +TEST(a_checkpoint_slot_is_host_memory_and_costs_the_pool_nothing) { Fixture f; CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/4)); - REQUIRE(f.kv.checkpoint_bytes() < Pool::granule()); - - const int64_t idle = f.pools.kv().committed(); - int32_t a = -1, b = -1; - CHECK_OK(f.kv.alloc_checkpoint(&a)); - CHECK_OK(f.kv.alloc_checkpoint(&b)); - CHECK_EQ(f.pools.kv().committed(), idle); /* nothing to back and nothing to reclaim */ - void* p = f.kv.checkpoint_ptr(a); - REQUIRE(p != nullptr); - const int64_t off = (char*)p - (char*)f.pools.kv().base(); - CHECK(f.pools.kv().is_committed(off, f.kv.checkpoint_bytes())); /* backed all along */ - f.kv.free_checkpoint(a); - f.kv.free_checkpoint(b); + CHECK_EQ(f.kv.checkpoint_slots(), 4); CHECK_EQ(f.kv.free_checkpoint_slots(), 4); -} - -/* A SIMULATED CARD: `cap` bytes, of which the pools on it have committed what they report. The - * floor tests cannot read the real device -- memory the previous test's fixtures released is still - * coming back while this one reads, so the answer moves under them -- and two ranks here share - * one device where the engine's are on two. A card per rank is what the engine has. */ -struct SimCard { - int64_t cap = 0; - std::vector pools; - int64_t used() const { - int64_t u = 0; - for (const Pool* p : pools) u += p->committed(); - return u; - } - KVManager::FreeBytes reader() const { - return [this](int64_t* free_now) -> int { *free_now = cap - used(); return RAD_OK; }; - } - /* The floor that lets `extra` more slots of `stride` fit and not one more: half a slot of - * slack either side of the boundary. */ - int64_t floor_for(int64_t extra, int64_t stride) const { - return cap - used() - extra * stride - stride / 2; - } -}; - -/* A SLOT IS BACKED ON EVERY RANK OR HANDED OUT ON NONE. If rank 0 backs a slot at allocation and - * rank 1's card refuses it at the snapshot copy, the engine stops mid-serve. So the peer is asked - * before anything is committed: its refusal is a full pool at allocation, which the prefix cache - * answers, and the leader has spent nothing on the slot it could not hand out. */ -TEST(a_checkpoint_slot_is_backed_on_every_rank_or_none) { - if (!VMem::supported()) { - std::fprintf(stderr, " SKIP a_checkpoint_slot_is_backed_on_every_rank_or_none: no VMM\n"); - return; - } - BigCkpt lead, peer; - CHECK_OK(lead.build(/*ckpt_slots=*/4)); - CHECK_OK(peer.build(/*ckpt_slots=*/4)); - lead.kv.set_checkpoint_peers({ &peer.kv }); - const int64_t stride = lead.kv.checkpoint_stride(); - REQUIRE(stride > 0); - SimCard lcard, pcard; - lcard.cap = pcard.cap = 64ll << 30; - lcard.pools = { &lead.pools.kv() }; - pcard.pools = { &peer.pools.kv() }; - - /* Room on the leader's card and none on the peer's: nothing is handed out. */ - lead.kv.set_checkpoint_floor(lcard.reader(), lcard.floor_for(4, stride)); - peer.kv.set_checkpoint_floor(pcard.reader(), pcard.floor_for(0, stride)); - const int64_t l0 = lead.pools.kv().committed(), p0 = peer.pools.kv().committed(); - int32_t s = -1; - CHECK_EQ(lead.kv.alloc_checkpoint(&s), RAD_E_FULL); - CHECK_EQ(lead.pools.kv().committed(), l0); /* asked first, so nothing was spent */ - CHECK_EQ(peer.pools.kv().committed(), p0); - CHECK_EQ(lead.kv.free_checkpoint_slots(), 4); - - /* Room for one slot on the peer's card: that one is backed on both, and the next one is - * refused by the peer and costs the leader nothing. */ - peer.kv.set_checkpoint_floor(pcard.reader(), pcard.floor_for(1, stride)); - CHECK_OK(lead.kv.alloc_checkpoint(&s)); - CHECK_EQ(lead.pools.kv().committed(), l0 + stride); - CHECK_EQ(peer.pools.kv().committed(), p0 + stride); - int32_t t = -1; - CHECK_EQ(lead.kv.alloc_checkpoint(&t), RAD_E_FULL); - CHECK_EQ(lead.pools.kv().committed(), l0 + stride); - CHECK_EQ(peer.pools.kv().committed(), p0 + stride); - - /* And a copy into the slot finds it backed on the peer without touching the card. */ - CHECK_OK(peer.kv.back_checkpoint(s)); - CHECK_EQ(peer.pools.kv().committed(), p0 + stride); - lead.kv.free_checkpoint(s); -} - -/* ON A DRIVER THAT KEEPS WHAT IT MAPS, EVERY SLOT IS BACKED AT BRINGUP, and the ones the card has - * no room for above its floor are withdrawn -- never handed out, so serving never commits. */ -TEST(back_free_checkpoints_withdraws_what_the_card_cannot_hold) { - if (!VMem::supported()) { - std::fprintf(stderr, " SKIP back_free_checkpoints_withdraws_what_the_card_cannot_hold: " - "no VMM\n"); - return; - } - BigCkpt f; - CHECK_OK(f.build(/*ckpt_slots=*/4)); - f.kv.set_release_frees_card(false); - const int64_t stride = f.kv.checkpoint_stride(); - SimCard card; - card.cap = 64ll << 30; - card.pools = { &f.pools.kv() }; - f.kv.set_checkpoint_floor(card.reader(), card.floor_for(2, stride)); - const int64_t idle = f.pools.kv().committed(); - - int64_t gone = -1; - CHECK_OK(f.kv.back_free_checkpoints(&gone)); - CHECK_EQ(gone, 2); - CHECK_EQ(f.kv.free_checkpoint_slots(), 2); - const int64_t backed = f.pools.kv().committed(); - CHECK_EQ(backed, idle + 2 * stride); - - /* Both survivors are handed out with no commit, and then the pool is full. */ - int32_t a = -1, b = -1, c = -1; + const int64_t used = f.pools.kv().used(); + int32_t a = -1, b = -1; CHECK_OK(f.kv.alloc_checkpoint(&a)); CHECK_OK(f.kv.alloc_checkpoint(&b)); CHECK(a != b); - CHECK_EQ(f.pools.kv().committed(), backed); - CHECK_EQ(f.kv.alloc_checkpoint(&c), RAD_E_FULL); - - /* A freed slot keeps its pages on this driver and is the one handed out next. */ + CHECK_EQ(f.kv.free_checkpoint_slots(), 2); + CHECK_EQ(f.pools.kv().used(), used); + char* p = (char*)f.kv.checkpoint_ptr(a); + REQUIRE(p != nullptr); + CHECK(p == (char*)f.ck.at(a)); + std::memset(p, 0x5a, (size_t)f.kv.checkpoint_bytes()); + CHECK_EQ(((unsigned char*)f.ck.at(a))[f.kv.checkpoint_bytes() - 1], 0x5a); f.kv.free_checkpoint(a); - CHECK_OK(f.kv.alloc_checkpoint(&c)); - CHECK_EQ(c, a); - CHECK_EQ(f.pools.kv().committed(), backed); + f.kv.free_checkpoint(a); /* a double free is refused, not counted */ + f.kv.free_checkpoint(b); + CHECK_EQ(f.kv.free_checkpoint_slots(), 4); +} + +/* NO STORE, NO SLOTS: a hybrid model served without one hands nothing out, rather than a pointer + * to memory nobody owns. */ +TEST(without_a_store_no_checkpoint_slot_is_handed_out) { + Fixture f; + CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/0)); + CHECK_EQ(f.kv.checkpoint_slots(), 0); + int32_t s = -1; + CHECK_EQ(f.kv.alloc_checkpoint(&s), RAD_E_FULL); + CHECK(f.kv.checkpoint_ptr(0) == nullptr); +} + +/* ONE SLOT, EVERY RANK'S SHARD. Rank 0 hands the ids out and each rank addresses its own window + * of the same slot, so the disk tier can move a slot as one payload; two ranks writing at offset + * zero would leave the last one's shard and restore it on both. */ +TEST(each_rank_addresses_its_own_window_of_a_shared_snapshot_slot) { + Fixture lead, follow; + CHECK_OK(lead.build(/*with_linear=*/true, /*ckpt_slots=*/0)); + CHECK_OK(follow.build(/*with_linear=*/true, /*ckpt_slots=*/0)); + const int64_t shard = lead.kv.checkpoint_bytes(); + HostArena store; + CHECK_OK(store.open(2 * shard, 2 * shard * 3)); + lead.kv.set_checkpoint_store(&store, 0); + follow.kv.set_checkpoint_store(&store, shard); + int32_t s = -1; + CHECK_OK(lead.kv.alloc_checkpoint(&s)); + CHECK((char*)lead.kv.checkpoint_ptr(s) == (char*)store.at(s)); + CHECK((char*)follow.kv.checkpoint_ptr(s) == (char*)store.at(s) + shard); + CHECK_EQ(follow.kv.free_checkpoint_slots(), 2); /* the follower reads the same free list */ + lead.kv.free_checkpoint(s); + CHECK_EQ(store.used_slots(), 0); } RAD_TEST_MAIN() @@ -2269,293 +2277,191 @@ TEST(tiers_stay_off_until_a_size_is_given) { /* ================================================================== the linear half * * On a hybrid model an entry's attention blocks are only part of a session. The rest is a - * recurrent-state SNAPSHOT in a checkpoint slot, of which there are --checkpoint-slots for the - * whole server, and a tier that copied the blocks and left the snapshot behind would free the - * plentiful resource and hold the scarce one -- while the session that came back would replay - * every linear layer from token zero and report a cache hit doing it. + * recurrent-state SNAPSHOT in a slot of the engine's checkpoint store -- pinned host memory, + * --checkpoint-slots of them for the whole server. A snapshot never follows its blocks through + * the tiers: it is restored straight out of its slot. The only tier below the store is disk, and + * what these tests pin is that leg -- what is written when, what the store may give up, and that + * a slot a write is reading is never handed to the next save. * * Still no bytes: every test drives the policy and reports jobs back as the engine would. */ static IdleTiers::Config ck_config(int64_t host_bytes, int64_t disk_bytes, int64_t entry, - int64_t ck_bytes, int64_t ck_cap, int64_t ck_disk_slots) { + int64_t ck_bytes, int64_t ck_slots, int64_t ck_disk_slots) { IdleTiers::Config c = tier_config(host_bytes, disk_bytes, entry); c.ckpt_bytes = ck_bytes; - c.ckpt_cap_bytes = ck_cap; + c.ckpt_slots = ck_slots; c.ckpt_disk_slots = ck_disk_slots; return c; } -TEST(a_snapshot_is_copied_with_the_blocks_it_is_keyed_by) { - TmpDisk d; - CHECK_OK(d.open(1024, 2048, 8, 4)); +/* A tier with a disk store that holds snapshots: the configuration every test below starts from + * unless it is about the absence of one. */ +struct CkTiers { + TmpDisk d; IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 1 << 20, 1024, 2048, 8192, 4), &d.disk)); - CHECK(t.ckpt_on()); - CHECK(t.disk_on()); + int open(int64_t host = 1 << 20) { + RAD_TRY(d.open(1024, 2048, 16, 16)); + return t.configure(ck_config(host, 1 << 20, 1024, 2048, 8, 16), &d.disk); + } +}; - t.note_used(bh(1), {10}, 1 * SEC); - t.note_snapshot(bh(1), /*dev_slot=*/7, /*pos=*/2048); +/* A RESUME POINT GOES TO DISK AHEAD OF EVERYTHING. It is committed mid-request, before its chain + * is published, and until the disk holds it a full store can only retire it -- so it does not + * wait for its publish, nor behind a long queue of other conversations' writes. */ +TEST(a_resume_point_is_written_to_disk_ahead_of_everything) { + CkTiers c; + CHECK_OK(c.open()); + IdleTiers& t = c.t; + for (uint64_t k = 1; k <= 64; ++k) t.note_used(bh(k), {(int32_t)k}, 1 * SEC); + copy_now(t); /* 64 host copies wanting their disk copy */ + t.note_snapshot(bh(500), /*slot=*/3, /*pos=*/4096, /*resume=*/false); + t.note_snapshot(bh(900), /*slot=*/5, /*pos=*/8192, /*resume=*/true); + CHECK(t.disk_waiting()); std::vector jobs; - t.plan_writeback(16, &jobs); - REQUIRE_EQ(jobs.size(), 1u); - /* ONE JOB, BOTH HALVES. They are stored in different places and moved by different copies, - * but they are decided together. */ - CHECK_EQ(jobs[0].blocks.size(), 1u); - CHECK_EQ(jobs[0].ck_dev, 7); - CHECK(jobs[0].ck_host >= 0); - CHECK_EQ(jobs[0].ck_pos, 2048ll); - CHECK(t.snapshot_reading(bh(1))); - t.report(jobs[0], true); - CHECK(!t.snapshot_reading(bh(1))); - CHECK_EQ(t.stats().ck_to_host, 1ll); + t.plan(4, &jobs); + REQUIRE(!jobs.empty()); + CHECK(jobs[0].key == bh(900)); + CHECK(jobs[0].kind == TierJob::Kind::ToDisk); + CHECK_EQ(jobs[0].ck_slot, 5); + CHECK_EQ(jobs[0].host_slot, -1); /* not published: the snapshot alone */ + for (const TierJob& j : jobs) CHECK(!(j.key == bh(500))); /* waits for its publish */ + CHECK(t.slot_reading(5)); + for (TierJob& j : jobs) t.report(j, true); + CHECK(!t.slot_reading(5)); + CHECK(t.snapshot_backed(bh(900))); + CHECK_EQ(t.stats().ck_to_disk, 1ll); +} - /* THE BLOCKS GO AND THE SNAPSHOT STAYS in its device slot, which nothing else could use; - * the copy is what lets the checkpoint pool take the slot later without losing the state. */ - CHECK(drop_now(t, bh(1))); - CHECK(t.resident_off_device(bh(1))); - CHECK(t.snapshot_backed(bh(1))); - CHECK(detach_now(t, bh(1))); /* the pool wanted the slot */ - - /* ...and on to disk, both halves in one write, as COPIES: the host slots stay. */ - CHECK(t.disk_waiting()); - jobs.clear(); +/* A SNAPSHOT IS WRITTEN WHEN ITS CHAIN IS PUBLISHED, with the blocks' own write where both wait, + * and once the disk holds it the store may give its slot up and read it back later. */ +TEST(a_snapshot_the_disk_holds_gives_its_slot_up_and_is_read_back) { + CkTiers c; + CHECK_OK(c.open()); + IdleTiers& t = c.t; + t.note_snapshot(bh(1), /*slot=*/7, /*pos=*/2048); + CHECK(!t.disk_waiting()); /* not published yet */ + t.note_used(bh(1), {10}, 1 * SEC); + copy_now(t); + std::vector jobs; t.plan(16, &jobs); REQUIRE_EQ(jobs.size(), 1u); - CHECK(jobs[0].kind == TierJob::Kind::ToDisk); - CHECK(jobs[0].host_slot >= 0); - CHECK(jobs[0].ck_host >= 0); + CHECK(jobs[0].host_slot >= 0); /* ONE WRITE, BOTH HALVES */ + CHECK_EQ(jobs[0].ck_slot, 7); + CHECK_EQ(jobs[0].ck_pos, 2048ll); + CHECK(!t.snapshot_backed(bh(1))); /* not while the write is out */ t.report(jobs[0], true); - CHECK_EQ(t.stats().to_disk, 1ll); - CHECK_EQ(t.stats().ck_to_disk, 1ll); - CHECK_EQ(t.arena().used_slots(), 1ll); - CHECK_EQ(t.ckpt_arena().used_slots(), 1ll); - CHECK(!t.disk_waiting()); - - /* The arena wants the slot: it goes for nothing, and the entry is a disk entry. */ - CHECK_EQ(t.make_room(1), 1ll); - CHECK_EQ(t.tier_of(bh(1)), KVTier::Disk); - CHECK_EQ(t.arena().used_slots(), 0ll); - CHECK_EQ(t.stats().host_freed, 1ll); - - /* ...and back: read into a host slot first, then promoted out of it with the device slot the - * engine allocated -- and the entry keeps both host copies, clean. */ - TierJob up; - CHECK(!t.plan_promote(bh(1), &up)); /* not out of disk: a restore reads host memory */ - const std::vector rd = fetch_now(t, {bh(1)}); - REQUIRE_EQ(rd.size(), 1u); - CHECK(rd[0].kind == TierJob::Kind::ToHost); - CHECK_EQ(rd[0].ck_host, -1); /* the snapshot's host copy never left */ - CHECK_EQ(t.tier_of(bh(1)), KVTier::Host); - CHECK(t.plan_promote(bh(1), &up)); - CHECK(up.ck_want); - CHECK_EQ(up.host_slot, rd[0].host_slot); - CHECK(up.ck_host >= 0); - up.blocks = {11}; - up.ck_dev = 3; - up.started = true; - t.report(up, true); - CHECK_EQ(t.stats().ck_promoted, 1ll); - CHECK_EQ(t.tier_of(bh(1)), KVTier::Device); - CHECK_EQ(t.arena().used_slots(), 1ll); - CHECK_EQ(t.ckpt_arena().used_slots(), 1ll); - CHECK(t.droppable(bh(1))); CHECK(t.snapshot_backed(bh(1))); - /* And the disk copies survived the promotion: nothing is written twice. */ CHECK(!t.disk_waiting()); -} -TEST(a_snapshot_that_cannot_be_placed_does_not_hold_the_blocks_in_vram) { - /* THE BLOCKS ARE WORTH MORE. They are most of the bytes and all of the attention, and a - * snapshot with nowhere to go is still sitting in its device slot -- correct, and reachable - * again the moment the blocks come back. */ - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 0, 0), nullptr)); - CHECK(t.host_on()); - CHECK(!t.ckpt_on()); /* no room was given for snapshots */ - - t.note_used(bh(1), {10}, 1 * SEC); - t.note_snapshot(bh(1), 7, 2048); - std::vector jobs = copy_now(t); - REQUIRE_EQ(jobs.size(), 1u); - CHECK_EQ(jobs[0].ck_host, -1); /* nothing carried */ - CHECK_EQ(t.stats().to_host, 1ll); - CHECK_EQ(t.stats().ck_to_host, 0ll); - - CHECK(drop_now(t, bh(1))); - CHECK(!t.snapshot_backed(bh(1))); /* the device slot is the only home it has */ - /* And the cache was NOT told to drop it: the snapshot never moved and never became wrong. */ - CHECK_EQ(t.stats().ck_drops, 0ll); -} - -TEST(the_snapshot_store_evicts_one_of_its_own_rather_than_starving) { - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 2048, 0), nullptr)); - CHECK_EQ(t.ckpt_arena().capacity(), 1ll); /* room for exactly one */ - - std::vector lost; - t.set_snapshot_drop_sink([&lost](const BlockHash& h) { lost.push_back(h); }); - - t.note_used(bh(1), {10}, 1 * SEC); - t.note_snapshot(bh(1), 7, 2048); - copy_now(t); - drop_now(t, bh(1)); - detach_now(t, bh(1)); /* its only copy of the state is on the host */ - - t.note_used(bh(2), {11}, 50 * SEC); - t.note_snapshot(bh(2), 8, 2048); - std::vector jobs = copy_now(t); - REQUIRE_EQ(jobs.size(), 1u); - CHECK(jobs[0].ck_host >= 0); /* it got the slot the first one held */ - - /* THE FIRST SNAPSHOT IS GONE AND THE CACHE WAS TOLD. An index entry left behind would be a - * checkpoint the cache goes on offering whose bytes nobody holds. */ - REQUIRE_EQ(lost.size(), 1u); - CHECK(lost[0] == bh(1)); - CHECK_EQ(t.stats().ck_drops, 1ll); - /* The first entry's BLOCKS are untouched: losing half an entry is not losing it. */ - CHECK_EQ(t.tier_of(bh(1)), KVTier::Host); -} - -/* A BACKUP EVICTED IS NOT COPIED AGAIN. Two snapshots, both still in their device slots, and room - * for one copy: each pass that re-queued the evicted one would copy it back and evict the other -- - * a hundred megabytes a rank each way, forever, enough to saturate the link. */ -TEST(two_snapshots_and_one_slot_settle_instead_of_trading_places) { - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 2048, 0), nullptr)); - REQUIRE_EQ(t.ckpt_arena().capacity(), 1ll); - t.note_used(bh(1), {10}, 1 * SEC); - t.note_snapshot(bh(1), 7, 2048); - copy_now(t); - drop_now(t, bh(1)); /* on the host list, its snapshot still on the device */ - t.note_used(bh(2), {11}, 2 * SEC); - t.note_snapshot(bh(2), 8, 4096); - copy_now(t); /* takes the one slot from bh(1)'s backup */ - int copies = 0; - for (int pass = 0; pass < 8; ++pass) copies += (int)copy_now(t).size(); - CHECK_EQ(copies, 0); - CHECK_EQ(t.stats().ck_to_host, 2ll); - CHECK_EQ(t.stats().ck_drops, 0ll); /* neither was lost: both are in their device slots */ - /* A NEW COMMIT at the key is new state, and wants a copy again. */ - t.note_snapshot(bh(1), 9, 2048); - CHECK(t.writeback_waiting()); -} - -TEST(the_snapshot_evicted_is_the_earliest_position_not_the_first_in_the_list) { - /* A SESSION'S RECORDS ALL GO IDLE AT ONCE and reach the host list in whatever order they were - * dropped, so list order is effectively arbitrary within a session. Taking the tip while - * keeping a snapshot from earlier in the same transcript is the worst available outcome: the - * tip is the one position an appending conversation asks for. Position decides. */ - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 4096, 0), nullptr)); - CHECK_EQ(t.ckpt_arena().capacity(), 2ll); - - std::vector lost; - t.set_snapshot_drop_sink([&lost](const BlockHash& h) { lost.push_back(h); }); - - /* The TIP reaches the list first -- exactly the case an oldest-first rule gets wrong. */ - t.note_used(bh(1), {10}, 1 * SEC); - t.note_snapshot(bh(1), 7, /*pos=*/8192); - t.note_used(bh(2), {11}, 1 * SEC); - t.note_snapshot(bh(2), 8, /*pos=*/2048); - CHECK_EQ(copy_now(t).size(), 2u); - for (uint64_t k : { 1, 2 }) { drop_now(t, bh(k)); detach_now(t, bh(k)); } - CHECK_EQ(t.ckpt_arena().used_slots(), 2ll); - - /* A third wants a slot and there is none. */ - t.note_used(bh(3), {12}, 50 * SEC); - t.note_snapshot(bh(3), 9, 2048); - std::vector jobs = copy_now(t); - REQUIRE_EQ(jobs.size(), 1u); - CHECK(jobs[0].ck_host >= 0); - - REQUIRE_EQ(lost.size(), 1u); - CHECK(lost[0] == bh(2)); /* position 2048, not the tip at 8192 */ -} - -TEST(a_snapshot_the_cache_retires_gives_its_tier_storage_back) { - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 8192, 0), nullptr)); - t.note_used(bh(1), {10}, 1 * SEC); - t.note_snapshot(bh(1), 7, 2048); - copy_now(t); - CHECK_EQ(t.ckpt_arena().used_slots(), 1ll); - - /* The retention policy dropped it, or a reservation at the same prefix replaced it. Either - * way the cache is the owner of that decision and the bytes come back here. Nothing was - * reading the slot, so it is the cache's to free. */ - CHECK(!t.release_snapshot(bh(1))); - CHECK_EQ(t.ckpt_arena().used_slots(), 0ll); - CHECK_EQ(t.tier_of(bh(1)), KVTier::Device); /* the blocks are still stored */ + /* The store wants the slot: the snapshot is on disk alone. Nothing about the blocks moved. */ + CHECK(detach_now(t, bh(1))); CHECK(!t.snapshot_backed(bh(1))); + CHECK_EQ(t.tier_of(bh(1)), KVTier::Device); + CHECK(t.snapshot_fetch_wanted({ bh(1) })); + + /* ...and back, into the slot the engine took for it. The disk copy stays, so the slot can go + * again for nothing. */ + int32_t slot = 4; + std::vector reads; + CHECK(t.plan_fetch({ bh(1) }, &reads, 3 * SEC, &slot)); + CHECK_EQ(slot, -1); /* taken */ + REQUIRE_EQ(reads.size(), 1u); + CHECK(reads[0].kind == TierJob::Kind::ToHost); + CHECK_EQ(reads[0].host_slot, -1); /* the blocks are in VRAM */ + CHECK(reads[0].ck_want); + CHECK_EQ(reads[0].ck_slot, 4); + reads[0].started = true; + t.report(reads[0], true); + CHECK_EQ(t.stats().ck_fetched, 1ll); + CHECK(t.snapshot_in_slot(bh(1), 4)); + CHECK(t.snapshot_backed(bh(1))); + CHECK(!t.snapshot_fetch_wanted({ bh(1) })); + std::vector frees; + t.take_checkpoint_frees(&frees); + CHECK(frees.empty()); /* the cache owns slot 4 now */ } -TEST(the_cache_retiring_an_on_device_snapshot_unregisters_its_slot) { - /* THE SLOT NUMBER IS THE HAZARD. note_snapshot records a snapshot's DEVICE slot at commit, - * because a copy has to know what to read. If the retention policy then frees that slot - * without saying so, this record still names it -- and the pool has since handed it to another - * session. The next copy reads THAT session's recurrent state into the tier and restores it - * as this one's. */ - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 8192, 0), nullptr)); +/* A SLOT THE PLAN DOES NOT READ INTO STAYS THE CALLER'S. The engine takes one before it knows, + * and it must get it back rather than lose it to a record that never wanted it. */ +TEST(a_fetch_that_reads_no_snapshot_hands_the_slot_back) { + CkTiers c; + CHECK_OK(c.open()); + IdleTiers& t = c.t; t.note_used(bh(1), {10}, 1 * SEC); - t.note_snapshot(bh(1), /*dev_slot=*/7, 2048); - - t.release_snapshot(bh(1)); /* PrefixCache::retire_ckpt */ - - std::vector jobs = copy_now(t); - REQUIRE_EQ(jobs.size(), 1u); /* the blocks are still copied */ - CHECK_EQ(jobs[0].ck_dev, -1); /* and nothing names slot 7 any more */ - CHECK_EQ(jobs[0].ck_host, -1); - CHECK_EQ(t.stats().ck_to_host, 0ll); - CHECK_EQ(t.ckpt_arena().used_slots(), 0ll); + t.note_snapshot(bh(1), 7, 2048); /* in its slot */ + CHECK(!t.snapshot_fetch_wanted({ bh(1) })); + int32_t slot = 4; + std::vector reads; + CHECK(!t.plan_fetch({ bh(1) }, &reads, 1 * SEC, &slot)); + CHECK(reads.empty()); + CHECK_EQ(slot, 4); } -TEST(a_snapshot_a_copy_is_reading_is_freed_only_after_the_copy_reports) { - /* THE SLOT MAY BE DECOMMITTED WHEN IT IS FREED, and an asynchronous copy out of an unmapped - * page is a device fault. So a release that lands while the copy is out hands the slot to the - * tiers, and they give it back once the copy has reported. */ - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 8192, 0), nullptr)); +/* A SAVE INTO A SLOT A DISK WRITE IS READING WOULD PUT HALF OF ANOTHER SNAPSHOT ON DISK UNDER THIS + * KEY. So a release that lands while the write is out leaves the slot with the tiers, and they + * give it back once the write has reported -- decided by the SLOT, because the record may be + * forgotten in between and the slot is the cache's either way. */ +TEST(a_slot_a_disk_write_reads_is_freed_only_after_the_write_reports) { + CkTiers c; + CHECK_OK(c.open()); + IdleTiers& t = c.t; t.note_used(bh(1), {10}, 1 * SEC); t.note_snapshot(bh(1), 7, 2048); std::vector jobs; - t.plan_writeback(16, &jobs); + t.plan(16, &jobs); REQUIRE_EQ(jobs.size(), 1u); - CHECK(t.snapshot_reading(bh(1))); + CHECK(t.slot_reading(7)); - CHECK(t.release_snapshot(bh(1))); /* the tiers took the slot */ + t.forget(bh(1)); /* the blocks were evicted meanwhile */ + CHECK(t.release_snapshot(bh(1), 7)); /* the tiers keep the slot */ std::vector frees; t.take_checkpoint_frees(&frees); - CHECK(frees.empty()); /* not yet: the copy is still out */ + CHECK(frees.empty()); /* not yet: the write is still out */ t.report(jobs[0], true); t.take_checkpoint_frees(&frees); REQUIRE_EQ(frees.size(), 1u); CHECK_EQ(frees[0], 7); - /* The bytes that landed describe a snapshot nobody holds, so they are not kept. */ - CHECK_EQ(t.stats().ck_to_host, 0ll); - CHECK_EQ(t.ckpt_arena().used_slots(), 0ll); - CHECK_EQ(t.stats().to_host, 1ll); /* the blocks were fine */ + CHECK(!t.slot_reading(7)); + CHECK_EQ(t.stats().ck_to_disk, 0ll); /* nobody holds what landed */ + + /* A slot nobody is reading is the caller's to free at once. */ + t.note_snapshot(bh(2), 8, 2048); + CHECK(!t.release_snapshot(bh(2), 8)); } -TEST(a_new_commit_at_a_key_replaces_the_host_copy_of_its_snapshot) { - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 8192, 0), nullptr)); +/* A NEW COMMIT AT A KEY REPLACES ITS DISK COPY, and one made while the old write is still out is + * written on its own once that write has reported -- the bytes the old write put down describe a + * state nobody holds. */ +TEST(a_new_commit_at_a_key_replaces_its_disk_copy) { + CkTiers c; + CHECK_OK(c.open()); + IdleTiers& t = c.t; t.note_used(bh(1), {10}, 1 * SEC); t.note_snapshot(bh(1), 7, 2048); - copy_now(t); - CHECK_EQ(t.ckpt_arena().used_slots(), 1ll); + disk_now(t); + CHECK(t.snapshot_backed(bh(1))); - t.note_snapshot(bh(1), 9, 2048); /* recomputed and saved into a fresh slot */ - CHECK_EQ(t.ckpt_arena().used_slots(), 0ll); - CHECK(t.writeback_waiting()); + t.note_snapshot(bh(1), 9, 2048); /* recomputed into a fresh slot */ + CHECK(!t.snapshot_backed(bh(1))); + CHECK(t.disk_waiting()); std::vector jobs; - t.plan_writeback(16, &jobs); + t.plan(16, &jobs); REQUIRE_EQ(jobs.size(), 1u); - CHECK(jobs[0].blocks.empty()); /* the blocks' copy is still good */ - CHECK_EQ(jobs[0].ck_dev, 9); + CHECK_EQ(jobs[0].ck_slot, 9); + CHECK_EQ(jobs[0].host_slot, -1); /* the blocks' copy is still good */ + + t.note_snapshot(bh(1), 11, 2048); /* and again, while that write is out */ + t.report(jobs[0], true); + CHECK(!t.snapshot_backed(bh(1))); /* slot 9's bytes are not slot 11's */ + jobs.clear(); + t.plan(16, &jobs); + REQUIRE_EQ(jobs.size(), 1u); + CHECK_EQ(jobs[0].ck_slot, 11); + t.report(jobs[0], true); + CHECK(t.snapshot_backed(bh(1))); } TEST(a_record_that_only_ever_held_a_snapshot_is_forgotten_with_it) { @@ -2563,170 +2469,94 @@ TEST(a_record_that_only_ever_held_a_snapshot_is_forgotten_with_it) { * published, which is when the request closes. A request that never publishes -- a rebased * block table, a cancel before the first whole block -- would otherwise leave a record with * no blocks, no storage and no way to be reached again, one per checkpoint, forever. */ - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 8192, 0), nullptr)); + CkTiers c; + CHECK_OK(c.open()); + IdleTiers& t = c.t; t.note_snapshot(bh(1), 7, 2048); - /* NOT COPIED UNTIL ITS CHAIN IS PUBLISHED, so a request's checkpoints are planned together - * and the deepest goes first -- and a request that never publishes costs no copy at all. */ - CHECK_EQ(copy_now(t).size(), 0u); - CHECK(!t.snapshot_backed(bh(1))); - - t.release_snapshot(bh(1)); - CHECK_EQ(t.ckpt_arena().used_slots(), 0ll); - CHECK_EQ(t.tier_of(bh(1)), KVTier::Device); /* which is what "no record" answers */ - CHECK(!t.writeback_waiting()); - - /* Published after the commit: the snapshot goes with the blocks. */ - t.note_snapshot(bh(2), 8, 2048); - t.note_used(bh(2), {12}, 1 * SEC); - std::vector jobs = copy_now(t); - REQUIRE_EQ(jobs.size(), 1u); - CHECK_EQ(jobs[0].blocks.size(), 1u); - CHECK(jobs[0].ck_host >= 0); - CHECK(t.snapshot_backed(bh(2))); + CHECK_EQ(disk_now(t).size(), 0u); /* a request that never publishes costs nothing */ + CHECK(!t.release_snapshot(bh(1), 7)); + CHECK_EQ(t.tier_of(bh(1)), KVTier::Device); /* which is what "no record" answers */ + CHECK(!t.disk_waiting()); + CHECK_EQ(t.sessions().size(), 0u); } -TEST(a_restore_that_cannot_place_the_state_keeps_its_host_copy) { - /* NO DEVICE SLOT WAS FREE for the snapshot. This turn replays its linear layers, but the host - * copy is intact, and dropping it would make one full slot pool cost the session its state - * for good. It comes back with the blocks next time. */ - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 8192, 0), nullptr)); +/* THE DISK LOSING A SNAPSHOT IS SAID ONCE, and only of one that was there alone: the cache has to + * stop offering an index entry whose bytes nobody holds. A snapshot still in its slot is the + * cache's and is never announced. */ +TEST(a_snapshot_read_that_fails_tells_the_cache_and_gives_the_slot_back) { + CkTiers c; + CHECK_OK(c.open()); + IdleTiers& t = c.t; std::vector lost; t.set_snapshot_drop_sink([&lost](const BlockHash& h) { lost.push_back(h); }); - t.note_used(bh(1), {10}, 1 * SEC); t.note_snapshot(bh(1), 7, 2048); - copy_now(t); - drop_now(t, bh(1)); - detach_now(t, bh(1)); - - TierJob up; - CHECK(t.plan_promote(bh(1), &up)); - CHECK(up.ck_want); - up.blocks = {11}; - up.ck_dev = -1; - up.started = true; - t.report(up, true); - - CHECK_EQ(t.tier_of(bh(1)), KVTier::Device); /* the attention hit survives */ - CHECK_EQ(t.stats().promoted, 1ll); - CHECK_EQ(t.stats().ck_promoted, 0ll); - CHECK(lost.empty()); - CHECK_EQ(t.ckpt_arena().used_slots(), 1ll); - - /* Out again, and back again -- and this time the state is asked for. */ - CHECK(drop_now(t, bh(1))); - TierJob next; - CHECK(t.plan_promote(bh(1), &next)); - CHECK(next.ck_want); - CHECK(next.ck_host >= 0); -} - -TEST(a_snapshot_left_behind_by_the_budget_is_copied_on_a_later_pass) { - /* A snapshot is a hundred megabytes on a production hybrid, so only a couple are copied a - * pass. The blocks do not wait for them -- and the snapshots are not forgotten either: a - * record whose state has no copy stays queued until it has one. */ - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 1 << 16, 0), nullptr)); - for (int i = 1; i <= 5; ++i) { - t.note_used(bh((uint64_t)i), {10 + i}, 1 * SEC); - t.note_snapshot(bh((uint64_t)i), 7 + i, 2048 * i); - } - std::vector jobs = copy_now(t); - CHECK_EQ(jobs.size(), 5u); - int with_ck = 0; - for (const TierJob& j : jobs) with_ck += j.ck_host >= 0; - CHECK_EQ(with_ck, 2); - - jobs = copy_now(t); - CHECK_EQ(jobs.size(), 2u); - for (const TierJob& j : jobs) { CHECK(j.blocks.empty()); CHECK(j.ck_host >= 0); } - jobs = copy_now(t); - CHECK_EQ(jobs.size(), 1u); - CHECK_EQ(copy_now(t).size(), 0u); - - CHECK_EQ(t.stats().to_host, 5ll); - CHECK_EQ(t.stats().ck_to_host, 5ll); - CHECK_EQ(t.stats().ck_starved, 0ll); -} - -TEST(the_snapshot_arena_goes_to_a_session_s_tip_before_its_older_checkpoints) { - /* A session commits its checkpoints in order, so its tip is queued last -- and the tip is the - * one its next turn resumes from. One slot, two snapshots: the deeper one gets it. */ - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 2048, 0), nullptr)); - REQUIRE_EQ(t.ckpt_arena().capacity(), 1); - t.note_used(bh(1), {11}, 1 * SEC); - t.note_used(bh(2), {12}, 1 * SEC); - t.note_snapshot(bh(1), 7, 2048); - t.note_snapshot(bh(2), 8, 4096); - const std::vector jobs = copy_now(t); - CHECK_EQ(jobs.size(), 2u); - for (const TierJob& j : jobs) CHECK_EQ(j.ck_host >= 0, j.key == bh(2)); - CHECK_EQ(t.stats().ck_to_host, 1ll); - CHECK(t.snapshot_backed(bh(2))); - CHECK(!t.snapshot_backed(bh(1))); -} - -TEST(a_snapshot_copy_can_take_the_slot_of_one_a_session_in_vram_holds) { - /* A snapshot whose session stays in VRAM must not keep the arena for as long as it stays: a - * search of only the off-device lists for a slot to take never finds it, because a live - * session is on none. Once the disk holds that copy, giving its slot up costs nothing. */ - TmpDisk d; - CHECK_OK(d.open(1024, 2048, 16, 16)); - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 1 << 20, 1024, 2048, 2048, 16), &d.disk)); - REQUIRE_EQ(t.ckpt_arena().capacity(), 1); - t.note_used(bh(1), {11}, 1 * SEC); - t.note_snapshot(bh(1), 7, 2048); - copy_now(t); disk_now(t); - CHECK_EQ(t.tier_of(bh(1)), KVTier::Device); + CHECK(detach_now(t, bh(1))); - t.note_used(bh(2), {12}, 2 * SEC); - t.note_snapshot(bh(2), 8, 4096); - copy_now(t); - CHECK_EQ(t.stats().ck_to_host, 2ll); - CHECK_EQ(t.stats().ck_starved, 0ll); - CHECK(t.snapshot_backed(bh(1))); /* through its disk copy */ - CHECK(t.snapshot_backed(bh(2))); - CHECK_EQ(t.stats().ck_drops, 0ll); + int32_t slot = 3; + std::vector reads; + CHECK(t.plan_fetch({ bh(1) }, &reads, 2 * SEC, &slot)); + REQUIRE_EQ(reads.size(), 1u); + reads[0].started = true; + reads[0].ck_ok = false; /* the store no longer had it */ + t.report(reads[0], true); + REQUIRE_EQ(lost.size(), 1u); + CHECK(lost[0] == bh(1)); + CHECK_EQ(t.stats().ck_drops, 1ll); + std::vector frees; + t.take_checkpoint_frees(&frees); + REQUIRE_EQ(frees.size(), 1u); + CHECK_EQ(frees[0], 3); + CHECK(!t.snapshot_fetch_wanted({ bh(1) })); + + /* And forgetting a record whose snapshot is in its slot announces nothing. */ + t.note_used(bh(2), {11}, 1 * SEC); + t.note_snapshot(bh(2), 8, 2048); + t.forget(bh(2)); + CHECK_EQ(lost.size(), 1u); } -TEST(the_blocks_go_to_disk_without_waiting_for_the_snapshot_budget) { - /* Only a couple of snapshots are written a plan -- one is a hundred megabytes on a production - * hybrid -- and the blocks do not wait for them: a record whose snapshot the budget left - * behind sends its blocks and goes to the back of the queue for the rest. */ - TmpDisk d; - CHECK_OK(d.open(1024, 2048, 16, 16)); +/* WITHOUT A DISK THE STORE IS THE LAST TIER: nothing is written, nothing is ever backed, and the + * cache's retention policy is the whole of the snapshot policy. */ +TEST(without_a_disk_a_snapshot_never_leaves_its_slot) { IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 1 << 20, 1024, 2048, 1 << 16, 16), &d.disk)); + CHECK_OK(t.configure(ck_config(1 << 20, 0, 1024, 2048, 8, 0), nullptr)); + CHECK(!t.ckpt_disk_on()); + t.note_used(bh(1), {10}, 1 * SEC); + t.note_snapshot(bh(1), 7, 2048, /*resume=*/true); + copy_now(t); + CHECK_EQ(disk_now(t).size(), 0u); + CHECK(!t.snapshot_backed(bh(1))); + CHECK(!t.snapshot_fetch_wanted({ bh(1) })); + CHECK(!t.disk_waiting()); +} + +TEST(only_two_snapshots_go_to_disk_a_plan_and_the_blocks_do_not_wait) { + /* A snapshot is a hundred megabytes on a production hybrid and the disk store copies it twice + * on the way out, so a plan writes two; the blocks do not wait for them, and the rest are not + * forgotten. */ + CkTiers c; + CHECK_OK(c.open()); + IdleTiers& t = c.t; for (int i = 1; i <= 4; ++i) { t.note_used(bh((uint64_t)i), {10 + i}, 1 * SEC); t.note_snapshot(bh((uint64_t)i), 7 + i, 2048); } copy_now(t); - copy_now(t); - CHECK_EQ(t.stats().ck_to_host, 4ll); - std::vector jobs; t.plan(16, &jobs); REQUIRE_EQ(jobs.size(), 4u); int with_ck = 0; - for (const TierJob& j : jobs) { CHECK(j.host_slot >= 0); with_ck += j.ck_host >= 0; } + for (const TierJob& j : jobs) { CHECK(j.host_slot >= 0); with_ck += j.ck_slot >= 0; } CHECK_EQ(with_ck, 2); for (TierJob& j : jobs) t.report(j, true); CHECK_EQ(t.stats().to_disk, 4ll); CHECK_EQ(t.stats().ck_to_disk, 2ll); - CHECK(t.disk_waiting()); - jobs.clear(); - t.plan(16, &jobs); + jobs = disk_now(t); REQUIRE_EQ(jobs.size(), 2u); - for (const TierJob& j : jobs) { CHECK_EQ(j.host_slot, -1); CHECK(j.ck_host >= 0); } - for (TierJob& j : jobs) t.report(j, true); - CHECK_EQ(t.stats().to_disk, 4ll); + for (const TierJob& j : jobs) { CHECK_EQ(j.host_slot, -1); CHECK(j.ck_slot >= 0); } CHECK_EQ(t.stats().ck_to_disk, 4ll); CHECK(!t.disk_waiting()); } @@ -2735,11 +2565,10 @@ TEST(the_blocks_go_to_disk_without_waiting_for_the_snapshot_budget) { /* ------------------------------------------------------------------ the cache's half of it */ TEST(a_detached_snapshot_is_not_offered_and_a_reattached_one_is) { - /* THE INDEX ENTRY OUTLIVES THE BYTES ON PURPOSE. A snapshot the idle tiers hold has no slot - * in the pool, so it cannot be served -- but it is exactly what a promotion puts back, and - * the position and session it stands for are not recoverable from anywhere else. The state - * it is in while tiered is the one a reserved-but-unwritten snapshot is already in, handled - * by the same branch in lookup(). */ + /* THE INDEX ENTRY OUTLIVES THE SLOT ON PURPOSE. A detached snapshot is only on disk, so it + * cannot be served -- but it is exactly what a read puts back, and the position and session + * it stands for are not recoverable from anywhere else. The state it is in meanwhile is the + * one a reserved-but-unwritten snapshot is already in, handled by the same branch in lookup(). */ Fixture f; CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/4)); @@ -2760,11 +2589,8 @@ TEST(a_detached_snapshot_is_not_offered_and_a_reattached_one_is) { const int64_t free_before = f.kv.free_checkpoint_slots(); CHECK_OK(f.pc.detach_snapshot(key)); - /* THE SLOT IS THE POINT. There are --checkpoint-slots of them for the whole server, and - * moving the bytes without giving the slot back would free the plentiful resource and keep - * the scarce one. */ CHECK_EQ(f.kv.free_checkpoint_slots(), free_before + 1); - CHECK_EQ(f.pc.snapshots_off_device(), 1ll); + CHECK_EQ(f.pc.snapshots_detached(), 1ll); CacheHit tiered = f.pc.lookup(prompt, {}); CHECK_EQ(tiered.n_attn_tokens, 320); /* the blocks are still here */ @@ -2774,18 +2600,17 @@ TEST(a_detached_snapshot_is_not_offered_and_a_reattached_one_is) { int32_t back = -1; CHECK_OK(f.kv.alloc_checkpoint(&back)); CHECK_OK(f.pc.reattach_snapshot(key, back)); - CHECK_EQ(f.pc.snapshots_off_device(), 0ll); + CHECK_EQ(f.pc.snapshots_detached(), 0ll); CacheHit restored = f.pc.lookup(prompt, {}); CHECK_EQ(restored.n_linear_tokens, 128); CHECK_EQ(restored.checkpoint_slot, back); } -TEST(a_tiered_snapshot_is_not_a_victim_and_not_a_slot_to_hand_back) { - /* Two ways the checkpoint index can go wrong once a snapshot can be somewhere else, and both - * of them are silent. Choosing a tiered snapshot as the victim when the SLOT pool is full - * frees nothing and retires a usable snapshot; handing its -1 back from reserve_checkpoint - * reads to the scheduler exactly like a refusal, and linear caching stops with nothing in - * the log. */ +TEST(a_detached_snapshot_is_not_a_victim_and_not_a_slot_to_hand_back) { + /* Two ways the checkpoint index can go wrong once a snapshot can be on disk alone, and both + * of them are silent. Choosing a detached snapshot as the victim when the store is full frees + * nothing and retires a usable snapshot; handing its -1 back from reserve_checkpoint reads to + * the scheduler exactly like a refusal, and linear caching stops with nothing in the log. */ Fixture f; CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/2)); @@ -2808,11 +2633,11 @@ TEST(a_tiered_snapshot_is_not_a_victim_and_not_a_slot_to_hand_back) { CHECK_OK(f.pc.detach_snapshot(hs[64 / 16 - 1])); CHECK_EQ(f.kv.free_checkpoint_slots(), 1ll); - /* A reservation at the tiered snapshot's own prefix gets a REAL slot, not its -1. */ + /* A reservation at the detached snapshot's own prefix gets a REAL slot, not its -1. */ int32_t again = -1; CHECK_OK(f.pc.reserve_checkpoint(1, 64, hs[64 / 16 - 1], &again)); CHECK(again >= 0); - CHECK_EQ(f.pc.snapshots_off_device(), 0ll); + CHECK_EQ(f.pc.snapshots_detached(), 0ll); } TEST(the_tiers_losing_a_snapshot_erases_the_index_entry) { @@ -2832,30 +2657,32 @@ TEST(the_tiers_losing_a_snapshot_erases_the_index_entry) { f.pc.commit_checkpoint(key); CHECK_OK(f.pc.detach_snapshot(key)); - /* The snapshot arena overflowed, or a promotion could not place the state. Either way the - * bytes are gone and an index entry that outlived them would be a checkpoint the cache goes - * on offering that nothing can ever fill. */ + /* The disk store let it go, or a read of it failed. Either way the bytes are gone and an index + * entry that outlived them would be a checkpoint the cache goes on offering that nothing can + * ever fill. */ f.pc.drop_snapshot(key); - CHECK_EQ(f.pc.snapshots_off_device(), 0ll); + CHECK_EQ(f.pc.snapshots_detached(), 0ll); CHECK_EQ(f.pc.checkpoints(1).size(), 0u); CHECK_EQ(f.pc.lookup(prompt, {}).n_linear_tokens, 0); - /* And no double free: the device slot went back at detach, not here. */ + /* And no double free: the slot went back at detach, not here. */ CHECK_EQ(f.kv.free_checkpoint_slots(), 4ll); } -/* A FULL CHECKPOINT POOL DETACHES WHAT THE TIERS HOLD, and only that. The victim's slot goes back - * either way; a victim with a finished copy off the card keeps its index entry, marked off-device, - * so the session's next restore brings the state back instead of replaying every recurrent layer. - * A victim with no copy is retired. */ -TEST(a_full_checkpoint_pool_detaches_a_snapshot_the_tiers_hold_rather_than_losing_it) { +/* A FULL STORE DETACHES WHAT THE DISK HOLDS, and only that. The victim's slot goes back either + * way; a victim the disk holds keeps its index entry, detached, so the session's next restore + * reads the state back instead of replaying every recurrent layer. A victim with no disk copy is + * retired. */ +TEST(a_full_store_detaches_a_snapshot_the_disk_holds_rather_than_losing_it) { Fixture f; CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/2)); const int64_t ck = f.kv.checkpoint_bytes(); REQUIRE(ck > 0); + const int64_t entry = f.kv.plan(G_FULL)->bytes_per_block; + TmpDisk d; + CHECK_OK(d.open(entry, ck, 64, 8)); IdleTiers t; - CHECK_OK(t.configure(ck_config(64 << 20, 0, f.kv.plan(G_FULL)->bytes_per_block, ck, 8 * ck, 0), - nullptr)); - REQUIRE(t.ckpt_on()); + CHECK_OK(t.configure(ck_config(64 << 20, 1 << 20, entry, ck, 2, 8), &d.disk)); + REQUIRE(t.ckpt_disk_on()); f.pc.set_tiers(&t); auto chain = [&](const std::vector& p) { @@ -2876,34 +2703,35 @@ TEST(a_full_checkpoint_pool_detaches_a_snapshot_the_tiers_hold_rather_than_losin CHECK_OK(f.pc.reserve_checkpoint(1, 128, ha[128 / 16 - 1], &s2)); f.pc.commit_checkpoint(ha[128 / 16 - 1]); CHECK_EQ(f.kv.free_checkpoint_slots(), 0ll); - copy_now(t); + disk_now(t); CHECK(t.snapshot_backed(ha[64 / 16 - 1])); /* Another session wants a slot; the least recently used snapshot that is not a tip is the - * one at 64, and it has a copy. */ + * one at 64, and the disk holds it. */ int32_t s3 = -1; CHECK_OK(f.pc.reserve_checkpoint(2, 64, hb[64 / 16 - 1], &s3)); CHECK(s3 >= 0); - CHECK_EQ(f.pc.snapshots_off_device(), 1ll); + CHECK_EQ(f.pc.snapshots_detached(), 1ll); CHECK_EQ(f.pc.checkpoints(1).size(), 2u); /* the session still knows both */ CHECK(!t.snapshot_backed(ha[64 / 16 - 1])); + CHECK(t.snapshot_fetch_wanted(std::vector(ha.begin(), ha.begin() + 4))); CHECK_EQ(f.pc.stats().ckpt_evictions, 0ll); /* nothing was lost */ f.pc.set_tiers(nullptr); } -/* A RESTORED SESSION'S STATE NEEDS A DEVICE SLOT, and the pool is full whenever as many sessions - * have run since. The restore takes one from the least recently used snapshot the tiers hold a - * copy of -- but never one a lookup handed out this step: that request reads the slot in the - * coming forward, and the restore writes it before the forward runs. */ -TEST(a_restore_takes_a_checkpoint_slot_only_from_a_backed_snapshot_nobody_was_handed) { +/* A READ OFF DISK NEEDS A STORE SLOT, and the store is full whenever as many sessions have run + * since. One is taken from the least recently used snapshot the disk also holds -- but never one + * a lookup handed out this step: that request's restore reads the slot ahead of its step. */ +TEST(a_read_takes_a_store_slot_only_from_a_backed_snapshot_nobody_was_handed) { Fixture f; CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/2)); const int64_t ck = f.kv.checkpoint_bytes(); REQUIRE(ck > 0); + const int64_t entry = f.kv.plan(G_FULL)->bytes_per_block; + TmpDisk d; + CHECK_OK(d.open(entry, ck, 64, 8)); IdleTiers t; - CHECK_OK(t.configure(ck_config(64 << 20, 0, f.kv.plan(G_FULL)->bytes_per_block, ck, 8 * ck, 0), - nullptr)); - REQUIRE(t.ckpt_on()); + CHECK_OK(t.configure(ck_config(64 << 20, 1 << 20, entry, ck, 2, 8), &d.disk)); f.pc.set_tiers(&t); const auto a = tok_run(7500, 336); @@ -2920,7 +2748,7 @@ TEST(a_restore_takes_a_checkpoint_slot_only_from_a_backed_snapshot_nobody_was_ha CHECK_OK(f.pc.reserve_checkpoint(1, 128, ha[128 / 16 - 1], &s2)); f.pc.commit_checkpoint(ha[128 / 16 - 1]); CHECK_EQ(f.kv.free_checkpoint_slots(), 0ll); - copy_now(t); + disk_now(t); CHECK(t.snapshot_backed(ha[128 / 16 - 1])); /* This step's admission is handed the one at 128. */ @@ -2940,11 +2768,62 @@ TEST(a_restore_takes_a_checkpoint_slot_only_from_a_backed_snapshot_nobody_was_ha CHECK(!f.pc.free_checkpoint_for_restore()); /* 128 is this step's */ f.pc.begin_step(); CHECK(f.pc.free_checkpoint_for_restore()); /* and the next step's to take */ - CHECK_EQ(f.pc.snapshots_off_device(), 2ll); + CHECK_EQ(f.pc.snapshots_detached(), 2ll); f.kv.free_checkpoint(taken); f.pc.set_tiers(nullptr); } +/* THE CACHE RETIRING A SNAPSHOT A WRITE IS READING leaves the slot with the tiers: the retention + * policy runs on its own clock, and a save into the slot before the write is done would put half + * of another snapshot on disk under this key. */ +TEST(the_cache_retiring_a_snapshot_under_a_disk_write_does_not_free_its_slot) { + Fixture f; + CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/3)); + const int64_t ck = f.kv.checkpoint_bytes(); + const int64_t entry = f.kv.plan(G_FULL)->bytes_per_block; + TmpDisk d; + CHECK_OK(d.open(entry, ck, 64, 8)); + IdleTiers t; + CHECK_OK(t.configure(ck_config(64 << 20, 1 << 20, entry, ck, 3, 8), &d.disk)); + f.pc.set_tiers(&t); + f.pc.set_policy(std::make_unique()); + + const auto a = tok_run(7600, 336); + publish(f, 1, a, 320); + std::vector ha; + BlockHash parent; + for (int b = 0; b < 21; ++b) { + parent = chain_block_hash(parent, a.data() + b * 16, 16, nullptr, 0, b * 16); + ha.push_back(parent); + } + int32_t s1 = -1, s2 = -1, s3 = -1; + CHECK_OK(f.pc.reserve_checkpoint(1, 64, ha[64 / 16 - 1], &s1)); + f.pc.commit_checkpoint(ha[64 / 16 - 1]); + CHECK_OK(f.pc.reserve_checkpoint(1, 128, ha[128 / 16 - 1], &s2)); + f.pc.commit_checkpoint(ha[128 / 16 - 1]); + std::vector writes; + t.plan(1 << 20, &writes); /* both writes out, not yet reported */ + CHECK(t.slot_reading(s1)); + CHECK(t.slot_reading(s2)); + CHECK_OK(f.pc.reserve_checkpoint(1, 192, ha[192 / 16 - 1], &s3)); + f.pc.commit_checkpoint(ha[192 / 16 - 1]); + + /* A fourth squeezes the store: tip-only retires 64 and 128, whose slots their writes are still + * reading, and the only slot that can be handed out is one no write reads. */ + int32_t s4 = -1; + CHECK_OK(f.pc.reserve_checkpoint(1, 256, ha[256 / 16 - 1], &s4)); + CHECK(s4 != s1); + CHECK(s4 != s2); + for (TierJob& j : writes) t.report(j, true); + std::vector frees; + t.take_checkpoint_frees(&frees); + REQUIRE_EQ(frees.size(), 2u); + CHECK((frees[0] == s1 && frees[1] == s2) || (frees[0] == s2 && frees[1] == s1)); + for (int32_t s : frees) f.kv.free_checkpoint(s); + CHECK_EQ(f.kv.free_checkpoint_slots(), 2ll); + f.pc.set_tiers(nullptr); +} + TEST(the_tiers_are_told_the_cache_s_block_ids_and_not_the_requests) { /* TWO REQUESTS COMPUTE THE SAME PREFIX AND ONLY ONE SET OF BLOCKS IS REFERENCED. The second * request missed -- its lookup stopped early, which is exactly what happens while the tiers @@ -3145,6 +3024,188 @@ TEST(pressure_on_the_pool_moves_a_clean_entry_and_drops_one_with_no_copy) { CHECK_EQ(x.f.pc.size(), 20ll); } +/* THE RESERVE'S TRIM LOSES NO CONVERSATION. It runs right after a publish, while the sequence that + * published still holds its blocks and before any host copy of them can have landed -- so an entry + * a sequence holds, and one with no copy yet, are exactly what it must pass over. */ +TEST(the_trim_keeps_what_a_sequence_holds_and_what_has_no_copy_yet) { + TierFixture x; + CHECK_OK(x.build()); + const auto a = tok_run(7600, 336); + const auto b = tok_run(9600, 336); + const auto c = tok_run(11600, 336); + publish(x.f, 1, a, 320); + x.f.kv.free_sequence(1); + copy_now(x.t); /* a is clean */ + publish(x.f, 2, b, 320); + x.f.kv.free_sequence(2); /* b has no copy yet */ + publish(x.f, 3, c, 320); /* c's sequence is still running */ + + CHECK_EQ(x.f.pc.trim(1000), 20); /* a, and only a */ + CHECK_EQ(x.f.pc.restorable_from(a, {}).size(), 20u); + CHECK_EQ(x.f.pc.lookup(b, {}).n_attn_tokens, 320); + CHECK_EQ(x.f.pc.lookup(c, {}).n_attn_tokens, 320); + CHECK_EQ(x.f.pc.stats().drops, 20ll); + CHECK_EQ(x.f.pc.stats().evictions, 0ll); + + copy_now(x.t); /* b and c land */ + CHECK_EQ(x.f.pc.trim(1000), 20); /* b; c is still read by its sequence */ + CHECK_EQ(x.f.pc.lookup(c, {}).n_attn_tokens, 320); + x.f.kv.free_sequence(3); + CHECK_EQ(x.f.pc.trim(5), 5); /* and no more than it was asked for */ + CHECK_EQ(x.f.pc.stats().evictions, 0ll); + CHECK_EQ(x.f.pc.size(), 60ll); /* every entry still indexed */ +} + +TEST(without_tiers_the_trim_frees_only_what_no_sequence_holds) { + Fixture f; + CHECK_OK(f.build(/*with_linear=*/false)); + const auto a = tok_run(7600, 336); + const auto b = tok_run(9600, 336); + publish(f, 1, a, 320); + f.kv.free_sequence(1); + publish(f, 2, b, 320); /* still running */ + CHECK_EQ(f.pc.trim(1000), 20); + CHECK_EQ(f.pc.lookup(a, {}).n_attn_tokens, 0); + CHECK_EQ(f.pc.lookup(b, {}).n_attn_tokens, 320); + CHECK_EQ(f.pc.stats().evictions, 20ll); + CHECK_EQ(f.pc.trim(1000), 0); +} + +/* PRESSURE LANDS A WAITING COPY INSTEAD OF ERASING. The binding drops what already has a host + * copy, then has the engine land the copies still on their way and drops those too; only what the + * tiers then still cannot take is erased. */ +TEST(pressure_lands_a_waiting_copy_instead_of_erasing_the_entry) { + TierFixture x; + CHECK_OK(x.build()); + const auto a = tok_run(7600, 336); + publish(x.f, 1, a, 320); + x.f.kv.free_sequence(1); /* finished; its copy has not landed */ + PCBinding b(&x.f.pc); + int flushes = 0; + b.flush_fn = [&]() { ++flushes; return !copy_now(x.t).empty(); }; + CHECK_EQ(b.evict(20), 20); + CHECK_EQ(flushes, 1); + CHECK_EQ(x.f.pc.stats().evictions, 0ll); + CHECK_EQ(x.f.pc.stats().drops, 20ll); + CHECK_EQ(x.f.pc.restorable_from(a, {}).size(), 20u); + + /* With nothing to land the copies, the binding has no lossless way left and erases. */ + const auto c = tok_run(9600, 336); + publish(x.f, 2, c, 320); + x.f.kv.free_sequence(2); + PCBinding bare(&x.f.pc); + CHECK_EQ(bare.evict(20), 20); + CHECK_EQ(x.f.pc.stats().evictions, 20ll); +} + +/* A hybrid cache with snapshot tiers: the linear fixture, and a disk store that holds snapshots. */ +struct CkTierFixture { + Fixture f; + TmpDisk d; + IdleTiers t; + int build(int ckpt_slots) { + int s = f.build(/*with_linear=*/true, ckpt_slots); + if (s < 0) return s; + const int64_t ck = f.kv.checkpoint_bytes(); + s = d.open(1024, ck, 64, 8); + if (s < 0) return s; + s = t.configure(ck_config(1 << 20, 1 << 20, 1024, ck, ckpt_slots, 8), &d.disk); + if (s < 0) return s; + f.pc.set_tiers(&t); + return RAD_OK; + } +}; + +TEST(the_retention_policy_detaches_a_snapshot_the_disk_holds_instead_of_retiring_it) { + CkTierFixture x; + CHECK_OK(x.build(/*ckpt_slots=*/2)); + x.f.pc.set_policy(std::make_unique()); + const auto prompt = tok_run(7000, 336); + publish(x.f, 1, prompt, 320); + const std::vector hs = chain_of(prompt, 16); + ckpt_at(x.f, 1, hs, 64); + ckpt_at(x.f, 1, hs, 128); + disk_now(x.t); /* both are on disk */ + ckpt_at(x.f, 1, hs, 192); /* the store is full: the policy runs */ + CHECK(x.f.pc.checkpoints(1) == (std::vector{ 64, 128, 192 })); + CHECK_EQ(x.f.pc.snapshots_detached(), 1ll); /* 64 left its slot and stayed indexed */ + CHECK_EQ(x.f.pc.stats().ckpt_evictions, 0ll); +} + +/* A SNAPSHOT THAT LOST ITS SLOT IS NOT SERVED, whatever else its entry says: the lookup takes the + * deepest one still in a slot, and a commit arriving after the slot went does not make it servable + * again. */ +TEST(a_lookup_takes_the_deepest_snapshot_still_in_its_slot) { + CkTierFixture x; + CHECK_OK(x.build(/*ckpt_slots=*/4)); + const auto prompt = tok_run(7000, 336); + publish(x.f, 1, prompt, 320); + const std::vector hs = chain_of(prompt, 16); + ckpt_at(x.f, 1, hs, 128); + int32_t slot = -1; + CHECK_OK(x.f.pc.reserve_checkpoint(1, 256, hs[256 / 16 - 1], &slot)); + CHECK_OK(x.f.pc.detach_snapshot(hs[256 / 16 - 1])); + x.f.pc.commit_checkpoint(hs[256 / 16 - 1]); + CacheHit h = x.f.pc.lookup(prompt, {}); + CHECK_EQ(h.n_linear_tokens, 128); + CHECK(h.checkpoint_slot >= 0); +} + +/* AN ENTRY ALREADY IN A SLOT KEEPS IT: a second slot offered for the same snapshot is refused, and + * the caller gives it back, rather than the first one leaking. */ +TEST(a_snapshot_in_its_slot_refuses_a_second_one) { + CkTierFixture x; + CHECK_OK(x.build(/*ckpt_slots=*/4)); + const auto prompt = tok_run(7000, 336); + publish(x.f, 1, prompt, 320); + const std::vector hs = chain_of(prompt, 16); + ckpt_at(x.f, 1, hs, 128); + const int32_t mine = x.f.pc.lookup(prompt, {}).checkpoint_slot; + CHECK(mine >= 0); + CHECK_OK(x.f.pc.reattach_snapshot(hs[128 / 16 - 1], mine)); + CHECK(x.f.pc.reattach_snapshot(hs[128 / 16 - 1], mine + 1) == RAD_E_STATE); + CHECK_EQ(x.f.pc.lookup(prompt, {}).checkpoint_slot, mine); +} + +/* A WAITING REQUEST'S CHAIN STAYS ON THE CARD. An admission refused after its restore gives the hit + * back, and the entries it brought back are clean; held, the eager drop passes them over until the + * request is gone, so the next attempt finds them where they are instead of copying them again. */ +TEST(a_held_chain_is_not_dropped_until_its_request_lets_go) { + TierFixture x; + CHECK_OK(x.build()); + const auto prompt = tok_run(7600, 336); + publish(x.f, 1, prompt, 320); + x.f.kv.free_sequence(1); + copy_now(x.t); + x.f.pc.hold(7, prompt, {}); + x.f.pc.hold(7, prompt, {}); /* once per request */ + CHECK_EQ(x.f.pc.drop_clean(), 0); + CHECK_EQ(x.f.pc.lookup(prompt, {}).n_attn_tokens, 320); + /* Pressure still takes it: a held entry has its copy, and trim loses nothing. */ + CHECK_EQ(x.f.pc.trim(5), 5); + x.f.pc.release(7); + CHECK_EQ(x.f.pc.drop_clean(), 15); + CHECK_EQ(x.f.kv.pool_bytes_used(G_FULL), 0ll); + CHECK_EQ(x.f.pc.stats().evictions, 0ll); +} + +/* TIERS ATTACHED AND OFF ARE NO TIERS: the engine attaches them whatever the flags say, and a trim + * that waited for a copy nobody will make would never keep the reserve. */ +TEST(with_the_tiers_attached_and_off_the_trim_still_frees) { + Fixture f; + CHECK_OK(f.build(/*with_linear=*/false)); + IdleTiers t; + CHECK_OK(t.configure(tier_config(0, 0, 1024), nullptr)); + f.pc.set_tiers(&t); + const auto a = tok_run(7600, 336); + publish(f, 1, a, 320); + f.kv.free_sequence(1); + CHECK_EQ(f.pc.trim(1000), 20); + CHECK_EQ(f.kv.pool_bytes_used(G_FULL), 0ll); + CHECK_EQ(f.pc.lookup(a, {}).n_attn_tokens, 0); + CHECK_EQ(f.pc.size(), 0ll); +} + TEST(a_prefix_computed_again_takes_the_new_blocks_as_its_device_copy) { TierFixture x; CHECK_OK(x.build()); @@ -3632,67 +3693,6 @@ TEST(a_slot_given_up_while_its_disk_write_is_out_is_freed_when_the_write_reports CHECK(t.writeback_waiting()); } -TEST(a_snapshot_the_disk_holds_gives_its_slot_up_before_one_only_the_host_holds) { - TmpDisk d; - CHECK_OK(d.open(1024, 2048, 16, 16)); - IdleTiers t; - CHECK_OK(t.configure(ck_config(1 << 20, 1 << 20, 1024, 2048, 2 * 2048, 16), &d.disk)); - REQUIRE_EQ(t.ckpt_arena().capacity(), 2); - int lost_ck = 0; - t.set_snapshot_drop_sink([&lost_ck](const BlockHash&) { ++lost_ck; }); - - t.note_used(bh(1), {11}, 1 * SEC); - t.note_used(bh(2), {12}, 2 * SEC); - t.note_snapshot(bh(1), 7, 2048); - t.note_snapshot(bh(2), 8, 4096); - copy_now(t); - CHECK_EQ(t.stats().ck_to_host, 2ll); - for (uint64_t k : {1, 2}) { CHECK(drop_now(t, bh(k))); CHECK(detach_now(t, bh(k))); } - - /* Only the second snapshot reaches disk. */ - std::vector jobs; - t.plan(16, &jobs); - for (TierJob& j : jobs) { if (j.key == bh(1)) j.ck_ok = false; t.report(j, true); } - CHECK_EQ(t.stats().ck_to_disk, 1ll); - - /* The earliest position would lose -- except that one is the only copy of its state, and the - * other costs nothing to give up. */ - t.note_used(bh(3), {13}, 3 * SEC); - t.note_snapshot(bh(3), 9, 6144); - copy_now(t); - CHECK_EQ(t.stats().ck_to_host, 3ll); - CHECK_EQ(lost_ck, 0); - CHECK_EQ(t.stats().ck_drops, 0ll); - - /* The second session's state is now only on disk, and reading it back needs a slot. A read - * never takes another session's only copy -- nor the copy that lets a snapshot still in its - * device slot be detached, until the disk holds it too. With no slot the read is not planned - * and the session is restored without it. */ - std::vector rd; - CHECK(!t.plan_fetch({bh(2)}, &rd, 1)); - CHECK(rd.empty()); - CHECK(drop_now(t, bh(3))); - CHECK(t.snapshot_backed(bh(3))); - CHECK(!t.plan_fetch({bh(2)}, &rd, 1)); - CHECK(rd.empty()); - CHECK(t.snapshot_backed(bh(3))); - disk_now(t); - CHECK(t.plan_fetch({bh(2)}, &rd, 1)); - REQUIRE_EQ(rd.size(), 1u); - CHECK_EQ(rd[0].host_slot, -1); /* its blocks are in host memory already */ - CHECK(rd[0].ck_host >= 0); - CHECK_EQ(rd[0].ck_pos, 4096ll); - CHECK(t.snapshot_backed(bh(3))); /* through its disk copy now */ - rd[0].started = true; - t.report(rd[0], true); - CHECK_EQ(t.stats().ck_fetched, 1ll); - TierJob up; - CHECK(t.plan_promote(bh(2), &up)); - CHECK(up.ck_want); - CHECK_EQ(up.ck_host, rd[0].ck_host); - CHECK_EQ(lost_ck, 0); -} - /* A RESTORE IS SIZED BEFORE IT STARTS, so it recalls the loan for the whole chain at once. One * recall a block would drain the slab a buffer at a time and stop at whatever the cache kept in * hand. */ @@ -3752,6 +3752,7 @@ static unsigned char pat(int rank, int64_t layer, int32_t block, int64_t i) { static void fill(Fixture& f, int rank) { for (int32_t g : f.pc.cached_groups()) { const KVGroupPlan* p = f.kv.plan(g); + if (p->zero) continue; const int64_t frag = p->layer_bytes_per_block(); for (int64_t l = 0; l < p->n_layers; ++l) for (int32_t b = 0; b < (int32_t)p->n_blocks; ++b) { @@ -3764,6 +3765,7 @@ static void fill(Fixture& f, int rank) { static void scribble(Fixture& f) { for (int32_t g : f.pc.cached_groups()) { const KVGroupPlan* p = f.kv.plan(g); + if (p->zero) continue; for (int64_t l = 0; l < p->n_layers; ++l) std::memset((char*)p->base + l * p->layer_stride(), 0xEE, (size_t)p->layer_stride()); } @@ -3779,6 +3781,7 @@ static int64_t same_bytes(Fixture& f, int rank, const std::vectorzero) continue; const int64_t frag = p->layer_bytes_per_block(); for (int64_t l = 0; l < p->n_layers && ok; ++l) { const unsigned char* row = @@ -3819,7 +3822,10 @@ static std::vector two_paged_groups() { return g; } -static void run_transfer(int world, bool fragment) { +/* `zero_last`: the last rank keeps no cache for the attention group (rad_kv_group_zero), as an + * attention-zero rank does. Its window of a slot is the narrower group alone, the ranks' windows + * are unequal, and every rank still takes part in every job. */ +static void run_transfer(int world, bool fragment, bool zero_last = false) { /* THE HOST BACKEND ONLY. The stand-in kernels copy rows with the CPU, which on the host backend * is where "device" memory is; on a card the staging buffer is VRAM and the production kernels * are the ones to run. */ @@ -3836,19 +3842,27 @@ static void run_transfer(int world, bool fragment) { for (int r = 0; r < world; ++r) { fx.push_back(std::make_unique()); fx.back()->cfg.checkpoint_slots = 0; - REQUIRE_EQ(fx.back()->build_groups(two_paged_groups()), RAD_OK); + std::vector groups = two_paged_groups(); + if (zero_last && r == world - 1) groups[1].zero = true; + REQUIRE_EQ(fx.back()->build_groups(groups), RAD_OK); } Fixture& f = *fx[0]; const std::vector& cg = f.pc.cached_groups(); REQUIRE_EQ(cg.size(), 2u); - int64_t entry = 0; - for (int32_t g : cg) entry += f.kv.plan(g)->bytes_per_block; + /* A slot is the sum of the ranks' entries, each rank's window where the ones before it end + * (Engine::configure_kv). */ + std::vector win_off((size_t)world, 0); + int64_t slot = 0; + for (int r = 0; r < world; ++r) { + win_off[(size_t)r] = slot; + for (int32_t g : cg) slot += fx[(size_t)r]->kv.plan(g)->bytes_per_block; + } /* FORTY SLOTS. Fragmented, every other one is taken and the copy goes out as twenty runs of * one; whole, it goes out as one run of twenty, which is the case where a rank's pitch through * a slot every rank shares decides where its rows land. */ IdleTiers t; - CHECK_OK(t.configure(tier_config(40 * entry * world, 0, entry * world), nullptr)); + CHECK_OK(t.configure(tier_config(40 * slot, 0, slot), nullptr)); REQUIRE_EQ(t.arena().capacity(), 40); if (fragment) { for (int i = 0; i < 40; ++i) CHECK_EQ(t.arena().alloc(), i); @@ -3865,7 +3879,7 @@ static void run_transfer(int world, bool fragment) { /* A three-entry staging buffer, so twenty entries cross it in seven pieces. */ REQUIRE_EQ(x.back()->configure(®, &fx[(size_t)r]->kv, &t, nullptr, cg, /*max_batch=*/3, /*max_copy=*/64, /*max_chain=*/64, /*leader=*/r == 0, - /*device=*/0, /*slot_off=*/r * entry, /*ck_slot_off=*/0, + /*device=*/0, /*slot_off=*/win_off[(size_t)r], /*ck_store=*/nullptr, /*shared=*/nullptr), RAD_OK); } @@ -3986,7 +4000,7 @@ static void run_disk_cut(int world) { x.push_back(std::make_unique()); REQUIRE_EQ(x.back()->configure(®, &fx[(size_t)r]->kv, &t, &d.disk, cg, /*max_batch=*/3, /*max_copy=*/64, /*max_chain=*/64, /*leader=*/r == 0, - /*device=*/0, /*slot_off=*/r * entry, /*ck_slot_off=*/0, + /*device=*/0, /*slot_off=*/r * entry, /*ck_store=*/nullptr, /*shared=*/nullptr), RAD_OK); } @@ -4129,6 +4143,10 @@ TEST(each_rank_restores_its_own_window_of_a_shared_slot) { run_transfer(2, /*fragment=*/false); run_transfer(2, /*fragment=*/true); } +TEST(a_rank_with_a_zero_group_moves_only_its_own_groups) { + run_transfer(3, /*fragment=*/false, /*zero_last=*/true); + run_transfer(3, /*fragment=*/true, /*zero_last=*/true); +} /* A SPECULATING DEPLOYMENT KEEPS TWO PHYSICAL SLOTS A SEQUENCE, and the free list counts logical * ones. Subtracting one from the other reads an idle pool as half full. */ diff --git a/tests/place_test.cpp b/tests/place_test.cpp index 5546d251..dced52ca 100644 --- a/tests/place_test.cpp +++ b/tests/place_test.cpp @@ -97,6 +97,7 @@ const char* rad_dev_last_error(void) { return ""; } namespace { constexpr int64_t MiB = 1024 * 1024; +constexpr int64_t KiB = 1024; /* Two kernel rows, one per domain. The planner reads Band::dom[] to learn whether a host site * exists at all, so a fixture that wants to exercise that has to resolve real rows. */ @@ -409,6 +410,57 @@ TEST(planner_spills_experts_before_dense_weights) { CHECK_EQ(zero_copy, 6); } +/* THE BUDGET'S EXPERT FLOOR PLACES EVERY EXPERT. A lending cache leaves the expert slab exactly + * expert_vram_floor, so a floor short of what the planner spends -- the residents, the slab's + * spare slots beside them, and the slack each first-fit pass can strand -- is experts with no + * tier, and a server that refuses to start. Two strides make two slab classes, each with its own + * shadow slots, which is the shape a mixed-precision container has. */ +TEST(the_expert_floor_places_every_expert) { + Fixture f; + const rad_weight m = f.weight("token_embd.weight", 1 * MiB, RAD_ACCESS_VOCAB, -1, -1); + f.op("embed", {m}, false); + for (int l = 0; l < 8; ++l) { + const int64_t gu = l < 4 ? 600 * KiB : 1 * MiB, dn = l < 4 ? 300 * KiB : 500 * KiB; + std::vector g, d; + for (int e = 0; e < 16; ++e) { + const std::string b = "blk." + std::to_string(l) + "."; + g.push_back(f.weight(b + "ffn_gate_up_exps." + std::to_string(e) + ".weight", gu, + RAD_ACCESS_CONDITIONAL, l, e)); + d.push_back(f.weight(b + "ffn_down_exps." + std::to_string(e) + ".weight", dn, + RAD_ACCESS_CONDITIONAL, l, e)); + } + f.op("moe_gemm", g, false); + f.op("moe_gemm", d, false); + } + WeightFootprint wf; + weight_footprint(f.prog, &wf, TablePlacement::Vram, TablePlacement::Disk); + CHECK(wf.expert_spare > 0); + + const int64_t host = 100 * MiB; + auto plan_with = [&](int64_t floor, Plan* p) { + Config c = base_config(); + c.placement = "expert_tiered"; + c.vram_weights_mib = (wf.statics + floor + MiB - 1) / MiB; + c.host_pool_mib = host / MiB; + PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0}; + return Planner(in).plan(p); + }; + + const int64_t floor = expert_vram_floor(wf, host); + CHECK(floor > 0 && floor < wf.experts); + Plan p; + CHECK_OK(plan_with(floor, &p)); + CHECK(p.unfit.empty()); + CHECK_EQ(count_tier(f.prog, p, Tier::SSD), 0); + CHECK(p.totals.bytes[(int)Tier::VRAM] + p.slab_overhead <= p.vram_budget); + + /* AND THE SPARE SLOTS ARE WHY: a floor that counts only the experts the pool cannot hold and + * one unit of slack strands some. */ + Plan q; + CHECK(plan_with(wf.experts - host + wf.expert_unit_max, &q) == RAD_E_NOMEM); + CHECK(!q.unfit.empty()); +} + TEST(planner_warm_starts_from_the_container_profile) { Fixture f; std::vector ex; diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index e2674310..535e5814 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -256,7 +256,7 @@ TEST(op_vocabulary) { static const char* kOps[] = { "rmsnorm", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter", "layernorm", "add", "mul", "silu_mul", "gelu", "silu", - "sigmoid", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv", + "sigmoid", "fill", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv", "embed_lookup_q", "cast", "scale_rows", "softmax", diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 135fc661..78e9dfac 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -388,10 +388,30 @@ struct FakePC : IPrefixCache { ++evict_calls; if (evict_grant <= 0) return 0; int64_t took = n < evict_grant ? n : evict_grant; + if (evict_frees) { + /* An entry is one block in every cached group: give that many back to the pool. */ + int64_t have = seeded.empty() ? 0 : (int64_t)seeded[0].size(); + took = std::min(took, have); + for (size_t i = 0; i < groups.size() && i < seeded.size(); ++i) + for (int64_t k = 0; k < took; ++k) { + kv->release(groups[i], seeded[i].back()); + seeded[i].pop_back(); + } + } evict_grant -= took; evicted += took; return took; } + bool evict_frees = false; /* evict() returns the seeded blocks to the pool */ + std::vector holds, releases; + void hold(const Request& r) override { holds.push_back(r.id); } + void release(const Request& r) override { releases.push_back(r.id); } + /* What the reserve asked for, call by call. */ + std::vector trims; + int64_t trim(int64_t n) override { + trims.push_back(n); + return 0; + } /* Cumulative, like the real cache's: the scheduler publishes it as a counter and the * server takes deltas, so a fake that reported per-call would read as a cache that * never evicts. */ @@ -402,7 +422,11 @@ struct FakePC : IPrefixCache { return ((pos / interval) + 1) * interval; } std::vector committed; - void commit_checkpoint(const Request&, int64_t pos) override { committed.push_back(pos); } + std::vector resumed; /* the commits marked as resume points */ + void commit_checkpoint(const Request&, int64_t pos, bool resume) override { + committed.push_back(pos); + if (resume) resumed.push_back(pos); + } int reserve_checkpoint(const Request&, int64_t, int32_t* slot_out) override { ++reserved; *slot_out = next_slot++; @@ -618,10 +642,23 @@ TEST(prefill_chunks_split_at_the_checkpoint_interval) { CHECK_EQ(f.sch.plan_chunk(256, 1000, 512, &ck), 256); CHECK_EQ(ck, 512); - /* The final chunk is allowed to be short -- that is the accepted cost of owning the - * boundaries -- and writes no checkpoint because it does not reach one. */ - CHECK_EQ(f.sch.plan_chunk(768, 1000, 512, &ck), 232); + /* The final chunk ends at the prompt's last quantum boundary and writes a checkpoint there: + * the next turn of a conversation resumes from it instead of from 768. The remainder, under a + * quantum, is the chunk after it and writes none -- that is the accepted cost of owning the + * boundaries. */ + CHECK_EQ(f.sch.plan_chunk(768, 1000, 512, &ck), 192); + CHECK_EQ(ck, 960); + CHECK_EQ(f.sch.plan_chunk(960, 1000, 512, &ck), 40); CHECK_EQ(ck, -1); + /* A prompt that ends less than a quantum past where the chunk starts has no boundary to + * split at, and one inside the first interval is cheap enough to prefill again. */ + CHECK_EQ(f.sch.plan_chunk(768, 830, 512, &ck), 62); + CHECK_EQ(ck, -1); + CHECK_EQ(f.sch.plan_chunk(0, 200, 512, &ck), 200); + CHECK_EQ(ck, -1); + /* And a prompt ending on a quantum boundary takes its checkpoint at the end, unsplit. */ + CHECK_EQ(f.sch.plan_chunk(768, 960, 512, &ck), 192); + CHECK_EQ(ck, 960); /* A budget short of the interval still ends on a quantum, never in the middle of a tile. */ CHECK_EQ(f.sch.plan_chunk(0, 1000, 100, &ck), 64); @@ -784,6 +821,23 @@ TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) { CHECK_EQ(f.pc.committed[0], 512); /* ctx_len 256 + ckpt_tok 255 + 1 */ } +/* THE DEEPEST CHECKPOINT A PROMPT GETS IS ITS RESUME POINT, and it alone is committed as one: it is + * the state the next turn resumes from, and the tiers copy it off the card at once rather than + * with the rest of the conversation at its publish. */ +TEST(only_a_prompt_s_deepest_checkpoint_is_its_resume_point) { + Fixture f; + f.build(); + CHECK_OK(f.start()); + const uint64_t a = f.submit(1000, 8); + for (int i = 0; i < 64 && f.sch.find(a)->n_computed < 1000; ++i) { + REQUIRE(f.sch.step() != nullptr); + f.commit_plain(); + } + REQUIRE(f.pc.committed.size() >= 2u); + REQUIRE_EQ(f.pc.resumed.size(), 1u); + CHECK_EQ(f.pc.resumed[0], f.pc.committed.back()); +} + /* A hit that skipped tokens with no snapshot to resume from is the corruption this whole mechanism * exists to prevent, so it is refused outright rather than served with a zeroed state. */ TEST(a_hit_with_no_checkpoint_slot_reuses_nothing) { @@ -2031,6 +2085,63 @@ TEST(the_cache_trim_does_not_mistake_released_vram_for_occupancy) { f.commit_plain(); /* finishes and publishes */ CHECK_EQ((int)f.pc.published.size(), 1); CHECK_EQ(f.pc.evict_calls, 0); + CHECK(f.pc.trims.empty()); +} + +/* WHEN LIVE SEQUENCES HOLD MORE THAN THE RESERVE ALLOWS, THE TRIM ASKS FOR THE SHORTFALL ONCE. + * Nothing the cache can give closes it entirely, and a loop that kept evicting until it did would + * take the conversation this close has just published along with everything else on the list. */ +TEST(the_cache_trim_asks_for_the_shortfall_and_not_for_the_whole_cache) { + Fixture f; + f.build(/*blocks=*/40, /*states=*/64); + CHECK_OK(f.start()); + f.pc.evict_grant = 1 << 20; + + f.submit(160, /*max_tokens=*/1); /* 10 blocks, finishes on the first commit */ + f.submit(176, /*max_tokens=*/64); /* 11 blocks each, still running after it */ + f.submit(176, /*max_tokens=*/64); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.kv.held_blocks(0), 32ll); /* 8 free against a reserve of 10 */ + f.commit_plain(); + CHECK_EQ((int)f.pc.published.size(), 1); + REQUIRE(f.pc.trims.size() == 1u); + CHECK_EQ(f.pc.trims[0], 2ll); + CHECK_EQ(f.pc.evict_calls, 0); +} + +/* THE CACHE GIVES WAY TO A NEW REQUEST AS IT DOES TO A RUNNING ONE. With nothing running, no + * other path takes blocks back from the cache, and a pool full of finished conversations would + * keep the request waiting for good. */ +TEST(an_admission_short_of_blocks_takes_them_from_the_cache) { + Fixture f; + f.build(/*blocks=*/20, /*states=*/64); + CHECK_OK(f.start()); + f.pc.seed(240); /* 15 of 20 held by finished conversations */ + f.pc.attn = 0; /* and none of them is this prompt */ + f.pc.evict_frees = true; + f.pc.evict_grant = 1 << 20; + const uint64_t a = f.submit(160, 8); /* 10 blocks, 5 free */ + CHECK(f.sch.step() != nullptr); + CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running); + CHECK(f.pc.evict_calls >= 1); + CHECK(f.pc.holds.empty()); +} + +/* A REFUSED ADMISSION HOLDS WHAT ITS RESTORE BROUGHT BACK, and lets go once the request is gone, + * so the next attempt finds the chain on the card instead of copying it again. */ +TEST(a_refused_admission_holds_its_chain_until_the_request_goes) { + Fixture f; + f.build(/*blocks=*/20, /*states=*/64); + CHECK_OK(f.start()); + f.pc.seed(240); + f.pc.attn = 0; + const uint64_t a = f.submit(160, 8); /* the cache gives nothing back */ + CHECK(f.sch.step() == nullptr); + CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Waiting); + REQUIRE_EQ(f.pc.holds.size(), 1u); + CHECK_EQ(f.pc.holds[0], a); + CHECK_OK(f.sch.cancel(a)); + CHECK(std::find(f.pc.releases.begin(), f.pc.releases.end(), a) != f.pc.releases.end()); } /* AN ENGINE THAT HAS STOPPED ANSWERS EVERY REQUEST IT HELD AND REFUSES NEW ONES, rather than diff --git a/tests/server_test.cpp b/tests/server_test.cpp index 458495da..9b40eebd 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -10,6 +10,7 @@ #include "mm/processor.h" #include "rad_test.h" +#include "server/adapters.h" #include "server/http.h" #include "server/json_partial.h" #include "server/liveview.h" @@ -17,6 +18,8 @@ #include "server/oai.h" #include "server/server.h" #include "server/sink.h" +#include "text/chatfmt.h" +#include "text/chatparse.h" #include @@ -33,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -123,7 +127,8 @@ struct FakeChatTemplate : IChatTemplate { } /* The parser is built per render and reads calls only for a request that sent tools -- * the contract the real bridge keeps (IReplyParser). */ - if (with_parser) out->parser = std::make_shared(!tools.empty()); + if (real_parser) out->parser = real_parser; + else if (with_parser) out->parser = std::make_shared(!tools.empty()); out->think_open = think_open; out->think_close = think_close; out->think_starts_open = think_starts_open; @@ -134,6 +139,8 @@ struct FakeChatTemplate : IChatTemplate { std::string tool_refusal() const override { return refusal; } bool with_parser = false; + /* A real reply parser to hand out instead of the fake one. */ + std::shared_ptr real_parser; std::string refusal; std::string refuse_kwarg; /* The reasoning block a render reports. FakeTokenizer makes a one-byte marker one token. */ @@ -142,15 +149,22 @@ struct FakeChatTemplate : IChatTemplate { /* Reads "TOOL::" -- everything after the second colon is the arguments, * however incomplete, and it arrives a piece at a time. That is exactly the shape the - * streaming path has to cope with. With calls off every byte is content. */ + * streaming path has to cope with. With calls off every byte is content. The call is open + * when the reply ends before its arguments are whole, and its text is then the reply. */ struct FakeReplyReader : IReplyReader { explicit FakeReplyReader(bool calls) : calls_(calls) {} void feed(std::string_view t, std::vector* out) override { text_.append(t); step(out, false); } - void finish(std::vector* out) override { step(out, true); } + void finish(std::vector* out) override { + step(out, true); + msg_.open_call = !msg_.tool_calls.empty() && !json_complete(msg_.tool_calls[0].arguments); + } ParsedMessage message() const override { return msg_; } + std::string content_with_open_call(std::string_view reply) const override { + return msg_.open_call ? std::string(reply) : msg_.content; + } private: void emit(std::vector* out, ReplyDelta::Kind k, std::string s) { if (out) out->push_back({ k, 0, std::move(s) }); @@ -239,7 +253,7 @@ struct FakeScheduler : IScheduler { /* Nonzero: every token after the first is a verify step that proposed this many drafts and * accepted one, as a speculating engine reports them. */ int32_t drafts = 0; - SchedMetrics m; + server::SchedMetrics m; std::mutex mu; std::vector submitted; @@ -302,7 +316,7 @@ struct FakeScheduler : IScheduler { cancelled.push_back(id); } - SchedMetrics metrics() const override { return m; } + server::SchedMetrics metrics() const override { return m; } bool saw_cancel() { std::lock_guard lk(mu); @@ -1511,6 +1525,88 @@ TEST(a_request_the_engine_failed_says_what_failed) { std::string("the engine failed this request: unsupported")); } +/* A REPLY THAT ENDS INSIDE ITS LAST CALL, read by the real parser in Qwen's format: that call is + * the text the model wrote, after the content before it, and nothing else moves -- the reasoning + * stays reasoning, a call that closed before it stays a call, and the finish reason is "stop", + * streamed or not. The stream has sent the open call's deltas already and cannot take them back; + * its finish reason is what says not to run it, and it is the buffered one. */ +static std::shared_ptr qwen_reply_parser(const json& tools) { + ChatFormat f; + f.reasoning_open = "\n"; + f.reasoning_close = "\n\n\n"; + f.reasoning_breaks = { "\n" }; + f.call_open = "\n"; + f.call_close = ""; + f.name_prefix = "\n" }; + std::shared_ptr rf; + std::string why; + if (ReplyFormat::compile(f, &rf, &why) < 0) return nullptr; + ReplyOptions ro; + ro.generation_prompt = "<|im_start|>assistant\n\n"; + ro.tools = &tools; + std::shared_ptr rp; + if (ReplyParser::create(rf, ro, &rp, &why) < 0) return nullptr; + return std::make_shared(rp); +} + +TEST(a_reply_ending_inside_a_call_keeps_its_reasoning_and_earlier_calls) { + const json tools = json::parse(R"([{"type":"function","function":{"name":"bash", + "parameters":{"type":"object","properties":{"command":{"type":"string"}}, + "required":["command"]}}}])"); + const std::string call1 = "\n\n\nls\n\n" + "\n\n"; + const std::string open = "\n\n\ncat /a"; + const std::string reply = "Look first.\n\n\nChecking.\n" + call1 + open; + const std::string body = R"({"messages":[{"role":"user","content":"hi"}],"max_tokens":1000, + "tools":)" + tools.dump(); + + Fixture f; + f.tmpl.real_parser = qwen_reply_parser(tools); + REQUIRE(f.tmpl.real_parser != nullptr); + f.sched.reply = reply; + HttpResponse r = f.post("/v1/chat/completions", body + "}"); + CHECK_EQ(r.status, 200); + const json c = json::parse(r.body)["choices"][0]; + CHECK_EQ(c["finish_reason"].get(), std::string("stop")); + CHECK_EQ(c["message"]["reasoning_content"].get(), std::string("Look first.\n")); + CHECK_EQ(c["message"]["content"].get(), "Checking.\n" + open); + REQUIRE(c["message"].contains("tool_calls") && c["message"]["tool_calls"].size() == 1); + CHECK_EQ(c["message"]["tool_calls"][0]["function"]["arguments"].get(), + std::string("{\"command\":\"ls\"}")); + + /* Streamed: the same reasoning, the closed call, the same finish reason. */ + HttpResponse s = f.post("/v1/chat/completions", body + R"(,"stream":true})"); + CHECK_EQ(s.status, 200); + int bad = 0; + std::string reasoning, finish; + std::vector args; + for (const std::string& p : sse_payloads(drain(s), &bad)) { + if (p == "[DONE]") continue; + const json j = json::parse(p); + if (j["choices"].empty()) continue; + const json& ch = j["choices"][0]; + if (!ch["finish_reason"].is_null()) finish = ch["finish_reason"].get(); + const json& d = ch["delta"]; + if (d.contains("reasoning_content")) reasoning += d["reasoning_content"].get(); + if (!d.contains("tool_calls")) continue; + const size_t k = d["tool_calls"][0]["index"].get(); + if (k >= args.size()) args.resize(k + 1); + if (d["tool_calls"][0]["function"].contains("arguments")) + args[k] += d["tool_calls"][0]["function"]["arguments"].get(); + } + CHECK_EQ(bad, 0); + CHECK_EQ(finish, std::string("stop")); + CHECK_EQ(reasoning, std::string("Look first.\n")); + REQUIRE(!args.empty()); + CHECK_EQ(args[0], std::string("{\"command\":\"ls\"}")); +} + TEST(a_streamed_tool_call_is_named_before_its_arguments_flow) { Fixture f; f.sched.reply = "TOOL:lookup:{\"q\":\"x\"}"; @@ -2153,7 +2249,7 @@ TEST(metrics_is_valid_prometheus_text_with_vllm_names) { * each total once: however many of them run, the counter ends at the total. */ TEST(concurrent_scrapes_count_each_total_once) { Metrics m("m", 1024); - SchedMetrics s; + server::SchedMetrics s; s.steps = 1000; s.prefill_tokens = 5000; s.draft_depth_seen = 3; @@ -2231,6 +2327,43 @@ TEST(a_stable_prefix_never_cuts_a_code_point_or_an_escape) { CHECK_EQ((long long)json_stable_prefix("x\\u0041"), 7LL); } +/* A string literal is written exactly as nlohmann writes it, and refused exactly where nlohmann + * refuses: every byte value alone and after each lead byte, and random strings drawn from the + * bytes that decide -- controls, the quote and backslash, DEL, continuation and lead bytes. */ +TEST(a_quoted_string_is_what_nlohmann_writes) { + auto agree = [](const std::string& s) { + std::string got = "x"; + const bool ok = json_quote_append(got, s); + std::string want; + bool refused = false; + try { + want = "x" + json(s).dump(); + } catch (const nlohmann::json::type_error&) { + refused = true; + } + CHECK_EQ(ok, !refused); + if (ok) CHECK_EQ(got, want); + else CHECK_EQ(got, std::string("x")); + return ok == !refused && (!ok || got == want); + }; + for (int a = 0; a < 256; ++a) { + agree(std::string(1, (char)a)); + for (int b = 0; b < 256; ++b) agree(std::string{ (char)a, (char)b, 'z' }); + } + const unsigned char pool[] = { 0x00, 0x01, 0x08, 0x09, 0x0a, 0x0c, 0x0d, 0x1f, 0x20, '"', + '\\', '/', 'a', 0x7f, 0x80, 0x8f, 0x90, 0x9f, 0xa0, 0xbf, + 0xc0, 0xc1, 0xc2, 0xdf, 0xe0, 0xed, 0xee, 0xef, 0xf0, 0xf4, + 0xf5, 0xff }; + std::mt19937 rng(7); + int bad = 0; + for (int i = 0; i < 200000 && bad < 4; ++i) { + std::string s(rng() % 12, '\0'); + for (char& c : s) c = (char)pool[rng() % sizeof pool]; + if (!agree(s)) ++bad; + } + CHECK_EQ(bad, 0); +} + /* ================================================================== the live view */ TEST(the_live_view_prints_ordinary_lines_when_it_is_not_a_terminal) { diff --git a/tests/share_test.cpp b/tests/share_test.cpp index 81d710e2..d0b9c95d 100644 --- a/tests/share_test.cpp +++ b/tests/share_test.cpp @@ -192,28 +192,6 @@ TEST(per_part_spans_cut_each_stacked_part_by_its_own_rows) { CHECK(why.find("stated rows") != std::string::npos); } -/* A ZERO SHARE has the declaration's extents and no rectangles: the loader writes zeros and reads - * nothing. At one rank there is nothing to zero. */ -TEST(a_zero_share_is_the_declared_extent_and_no_rectangles) { - const RadEncoding e = fp8_block(); - WeightInfo w = decl(e, { 0, 1 }, 1536, 128, RAD_SHARD_ROW, 3); - w.shard_zero = true; - PlaneShare s[RAD_ENC_MAX_PLANES]; - REQUIRE_EQ(share(w, 1536, 128, 3, 2, s), RAD_OK); - CHECK(s[0].zero); - CHECK_EQ(s[0].rects.size(), (size_t)0); - CHECK_EQ(s[0].rows, (int64_t)512); - CHECK_EQ(s[0].cols, (int64_t)128); - CHECK_EQ(s[0].dense_bytes(), (int64_t)(512 * 128)); - CHECK(s[1].zero); - CHECK_EQ(s[1].rows, (int64_t)4); - WeightInfo one = decl(e, { 0, 1 }, 1536, 128, RAD_SHARD_ROW, 1); - one.shard_zero = true; - REQUIRE_EQ(share(one, 1536, 128, 1, 0, s), RAD_OK); - CHECK(!s[0].zero); - CHECK_EQ(s[0].rows, (int64_t)1536); -} - /* A per-tensor scale is one value every rank carries whole, once, whatever the codes' cut. */ TEST(a_per_tensor_scale_is_carried_whole_by_every_rank) { RadEncoding e; diff --git a/tools/rad_chatparse.cpp b/tools/rad_chatparse.cpp index 3966da6e..40531172 100644 --- a/tools/rad_chatparse.cpp +++ b/tools/rad_chatparse.cpp @@ -6,6 +6,7 @@ * [--fuzz N] random replies per model and request (default 300) * [--long a,b,c] reply sizes the legacy path is timed at (default 4096,16384,65536) * [--new-long a,b] sizes only the streaming parser is timed at (default 262144,1048576) + * [--reps N] runs of the per-token breakdown (default 5) * * A folder holds the checkpoint's tokenizer.json and chat_template.jinja. The model names are * the ones tests/legacy/chatdiff.h knows -- qwen3.8, qwen3.6, minicpm5 -- which fix the BOS/EOS @@ -28,10 +29,19 @@ * against streaming ("new"), and the streaming parser alone at sizes the legacy path cannot reach * in reasonable time. * + * And the whole host cost of a streamed token, by component: the decoder, the server's text + * bookkeeping, the parser, the reader bridge, the chunk JSON, and the tool-call grammar the + * sampler drives (accept_token, and fill_mask once triggered) in prose, call structure, string + * values and typed values -- with every SSE event held to nlohmann's own serialisation of it. + * * Exit status is non-zero when any reply breaks the contract or a verdict is not allowed. */ #include "chatdiff.h" +#include "sample/grammar.h" +#include "sample/vocab_view.h" #include "server/adapters.h" +#include "server/json_partial.h" #include "server/oai.h" +#include "text/chatfmt.h" #include "text/tokenizer.h" #include @@ -275,11 +285,283 @@ Timing time_old(const Bench& b, const std::vector& pieces) { return t; } +/* ------------------------------------------------------------------ the per-token breakdown */ + +/* The sampler's view of the real vocabulary, built as core/engine_bringup.cpp builds it: pieces + * are what the decoder chain writes to the output stream, special tokens rendered. */ +class RealView final : public VocabView { +public: + int init(std::shared_ptr v) { + v_ = std::move(v); + RAD_TRY(tok_.init(v_)); + pieces_.resize((size_t)v_->n_tokens()); + for (int32_t i = 0; i < v_->n_tokens(); ++i) + pieces_[(size_t)i] = tok_.piece(i, /*render_special=*/true); + return RAD_OK; + } + int32_t n_tokens() const override { return v_ ? v_->n_tokens() : 0; } + const std::string& token_piece(int32_t id) const override { + static const std::string kEmpty; + return (id >= 0 && (size_t)id < pieces_.size()) ? pieces_[(size_t)id] : kEmpty; + } + bool is_eog(int32_t id) const override { return v_ && v_->is_eog(id); } + int tokenize(const std::string& s, std::vector* out) const override { + return out ? tok_.encode(s, *out, false, false) : RAD_E_INVAL; + } + int tokenize_special(const std::string& s, std::vector* out) const override { + return out ? tok_.encode(s, *out, false, true) : RAD_E_INVAL; + } + +private: + std::shared_ptr v_; + Tokenizer tok_; + std::vector pieces_; +}; + +double median(std::vector v) { + std::sort(v.begin(), v.end()); + return v.empty() ? 0.0 : v[v.size() / 2]; +} + +/* Median and spread over the repetitions, in nanoseconds per unit. */ +std::string per(const std::vector& secs, size_t units) { + char b[96]; + const double lo = *std::min_element(secs.begin(), secs.end()); + const double hi = *std::max_element(secs.begin(), secs.end()); + std::snprintf(b, sizeof b, "%8.1f ns (%.1f..%.1f)", median(secs) / (double)units * 1e9, + lo / (double)units * 1e9, hi / (double)units * 1e9); + return b; +} + +/* Every SSE event in `out` must be exactly what nlohmann writes for the value it carries: the + * payload parsed and dumped again gives the same bytes. A chunk writer that is not a DOM is held + * to the DOM's output this way. Returns the events that are not. */ +size_t sse_not_canonical(const std::string& out, size_t* events) { + size_t bad = 0; + for (size_t at = 0; at < out.size();) { + const size_t end = out.find("\n\n", at); + if (end == std::string::npos || out.compare(at, 6, "data: ") != 0) return bad + 1; + ++*events; + const std::string payload = out.substr(at + 6, end - at - 6); + const ojson j = ojson::parse(payload, nullptr, false); + if (j.is_discarded() || j.dump() != payload) { + if (bad++ < 3) std::fprintf(stderr, " NOT CANONICAL: %s\n", payload.c_str()); + } + at = end + 2; + } + return bad; +} + +/* THE HOST COST OF ONE STREAMED TOKEN, by component, on the real tokenizer: the decoder, the + * server's text bookkeeping, the reply reader, the chunk JSON, and the tool-call grammar the + * sampler runs (accept_token, and fill_mask once it has triggered). Each component runs over the + * whole reply on its own, `reps` times; the medians are reported, with the spread. Returns the + * contract violations it saw: chunks that are not canonical JSON, or a grammar that refused the + * reply. */ +int breakdown(const Bench& b, const Tok& tk, const RealView& view, int reps) { + const Model& m = b.model(); + /* A long write with string values, and calls with integer and boolean values. */ + std::string text = long_reply(m, 262144); + const std::string vfirst = " x = compute(a, b)"; + const size_t v0 = text.find(vfirst); + const size_t v1 = text.rfind(" \n") + 2; + std::string typed; + for (int i = 0; i < 40; ++i) + typed += C(m, "bash", { { "command", "grep -rn TODO src | head -" + std::to_string(i) }, + { "timeout", std::to_string(1000 * i) } }) + "\n" + + C(m, "configure", { { "verbose", i % 2 ? "true" : "false" }, + { "level", std::to_string(i) } }) + "\n"; + const size_t t0 = text.size(); + text += "\n" + typed; + + std::vector ids; + tk.tok.encode(text, ids, false, true); + /* Pieces as the decoder hands them over, and where each token starts in the reply. */ + std::vector pieces; + std::vector start; + { + Detokenizer d(tk.vocab, {}, false, b.prompt().preserved_tokens); + size_t at = 0; + for (int32_t id : ids) { + start.push_back(at); + std::string p = d.push(id); + at += p.size(); + pieces.push_back(std::move(p)); + } + pieces.push_back(d.flush()); + } + const size_t n = ids.size(); + std::printf(" per-token breakdown: %zu bytes, %zu tokens, %d runs, ns/token median " + "(min..max)\n", text.size(), n, reps); + + std::vector t_detok, t_text, t_parse, t_reader, t_stream; + size_t events = 0, bad = 0; + for (int r = 0; r < reps; ++r) { + auto c0 = clk::now(); + { + Detokenizer d(tk.vocab, {}, false, b.prompt().preserved_tokens); + size_t bytes = 0; + for (int32_t id : ids) bytes += d.push(id).size(); + bytes += d.flush().size(); + if (bytes != text.size()) std::fprintf(stderr, " the decoder changed the reply\n"); + } + t_detok.push_back(since(c0)); + + /* The server's side of a token: the choice's text grows, and the stable prefix -- a + * UTF-8 boundary, no half escape -- is what goes to the stream. */ + c0 = clk::now(); + { + std::string acc; + size_t emitted = 0, sent = 0; + for (const std::string& p : pieces) { + acc += p; + const size_t safe = server::json_stable_prefix(acc); + if (safe <= emitted) continue; + sent += std::string_view(acc).substr(emitted, safe - emitted).size(); + emitted = safe; + } + if (sent > acc.size()) std::fprintf(stderr, " impossible\n"); + } + t_text.push_back(since(c0)); + + c0 = clk::now(); + { + std::unique_ptr s = b.parser().open(); + std::vector ev; + for (const std::string& p : pieces) { + s->feed(p, &ev); + ev.clear(); + } + s->finish(&ev); + } + t_parse.push_back(since(c0)); + + server::ReplyParserBridge bridge(b.parser_ptr()); + c0 = clk::now(); + { + std::unique_ptr rd = bridge.open(); + std::vector ev; + for (const std::string& p : pieces) { + rd->feed(p, &ev); + ev.clear(); + } + rd->finish(&ev); + } + t_reader.push_back(since(c0)); + + server::OaiRequest req; + req.id = "chatcmpl-breakdown"; + req.model = m.name; + req.created = 1759700000; + req.parse_tools = true; + std::string all; + c0 = clk::now(); + { + server::ChatDeltaStream st(req, 0, &bridge); + std::string o = st.first_chunk(); + for (const std::string& p : pieces) { + std::string c = st.push(p, false); + if (r == 0) all += c; + } + o += st.final_chunk(server::Finish::Stop); + if (r == 0) all += o; + } + t_stream.push_back(since(c0)); + if (r == 0) bad += sse_not_canonical(all, &events); + } + std::printf(" detokenize %s\n", per(t_detok, n).c_str()); + std::printf(" server text + stable cut %s\n", per(t_text, n).c_str()); + std::printf(" parser feed %s\n", per(t_parse, n).c_str()); + std::printf(" reader bridge (w/ parser) %s\n", per(t_reader, n).c_str()); + std::printf(" ChatDeltaStream::push %s (chunk JSON + SSE: %.1f ns)\n", + per(t_stream, n).c_str(), (median(t_stream) - median(t_reader)) / (double)n * 1e9); + std::printf(" %zu SSE events, %zu not canonical\n", events, bad); + int violations = (int)bad; + + /* The grammar, as the server builds it for this request and the sampler drives it, one token + * at a time: a mask for every position once the grammar constrains, then the token. */ + ChatGrammarRequest gq; + gq.tools = &agent_tools(); + gq.generation_prompt = b.prompt().generation_prompt; + gq.parallel_tool_calls = b.request().parallel; + gq.extract_reasoning = b.request().reasoning; + ChatGrammar cg; + std::string why; + if (chat_format_grammar(b.format(), gq, &cg, &why) < 0 || cg.text.empty()) { + std::printf(" grammar: none (%s)\n", why.c_str()); + return violations; + } + GrammarSpec spec; + spec.text = cg.text; + spec.lazy = cg.lazy; + for (const std::string& w : cg.trigger_words) { + std::vector t; + view.tokenize_special(w, &t); + if (t.size() == 1) spec.trigger_tokens.push_back(t[0]); + else spec.trigger_words.push_back(w); + } + const int64_t words = grammar_mask_words(view.n_tokens()); + std::vector mask((size_t)words); + enum { Lazy, Structure, Value, Typed, NReg }; + const char* reg_name[NReg] = { "untriggered (prose)", "call structure", "string value", + "typed calls" }; + std::vector acc_s[NReg], mask_s[NReg]; + size_t cnt[NReg] = {}, masks[NReg] = {}; + for (int r = 0; r <= reps; ++r) { /* run 0 compiles the program and warms its cache */ + std::unique_ptr g; + if (grammar_create(spec, view, &g, &why) < 0) { + std::printf(" grammar: refused (%s)\n", why.c_str()); + return violations + 1; + } + double a[NReg] = {}, k[NReg] = {}; + size_t c[NReg] = {}, mk[NReg] = {}; + for (size_t i = 0; i < n; ++i) { + const int reg = !g->constrains() ? Lazy + : start[i] >= t0 ? Typed + : start[i] >= v0 && start[i] < v1 ? Value : Structure; + ++c[reg]; + if (g->constrains()) { + const auto q0 = clk::now(); + const int s = g->fill_mask(mask.data(), words); + k[reg] += since(q0); + ++mk[reg]; + if (s < 0 || !((mask[(size_t)ids[i] >> 5] >> (ids[i] & 31)) & 1u)) { + std::printf(" grammar: token %zu refused by the mask\n", i); + return violations + 1; + } + } + const auto q0 = clk::now(); + const int s = g->accept_token(ids[i]); + a[reg] += since(q0); + if (s < 0) { + std::printf(" grammar: token %zu not accepted\n", i); + return violations + 1; + } + } + if (r == 0) continue; + for (int x = 0; x < NReg; ++x) { + acc_s[x].push_back(a[x]); + mask_s[x].push_back(k[x]); + cnt[x] = c[x]; + masks[x] = mk[x]; + } + } + for (int x = 0; x < NReg; ++x) { + if (!cnt[x]) continue; + std::printf(" grammar %-20s %6zu tokens: accept %s", reg_name[x], cnt[x], + per(acc_s[x], cnt[x]).c_str()); + if (masks[x]) std::printf(", mask %s", per(mask_s[x], masks[x]).c_str()); + std::printf("\n"); + } + return violations; +} + } /* namespace */ int main(int argc, char** argv) { std::vector> want; /* model name, folder */ int fuzz = 300; + int reps = 5; std::vector old_sizes = { 4096, 16384, 65536 }; std::vector new_sizes = { 262144, 1048576 }; for (int i = 1; i < argc; ++i) { @@ -293,6 +575,8 @@ int main(int argc, char** argv) { fuzz = std::atoi(argv[++i]); } else if (a == "--long" && i + 1 < argc) { old_sizes = sizes(argv[++i]); + } else if (a == "--reps" && i + 1 < argc) { + reps = std::max(1, std::atoi(argv[++i])); } else if (a == "--new-long" && i + 1 < argc) { new_sizes = sizes(argv[++i]); } else if (a[0] != '-') { @@ -306,7 +590,7 @@ int main(int argc, char** argv) { if (is_dir(a + "/" + d)) { want.push_back({ name, a + "/" + d }); break; } } else { std::fprintf(stderr, "usage: rad-chatparse | --model name=dir ... " - "[--fuzz N] [--long a,b] [--new-long a,b]\n"); + "[--fuzz N] [--long a,b] [--new-long a,b] [--reps N]\n"); return 2; } } @@ -404,6 +688,10 @@ int main(int argc, char** argv) { text.size(), p.size(), "-", nw.sse * 1e3, "", "-", nw.parser * 1e3, nw.parser / text.size() * 1e9, nw.parser / p.size() * 1e6); } + + RealView view; + if (view.init(tk.vocab) < 0) return 1; + violations += breakdown(b, tk, view, reps); } std::printf("%s\n", violations ? "FAILED" : "ok"); return violations ? 1 : 0;