engine: the KV plan split, the host mirror, and --kv-resident bring-up

This commit is contained in:
C_Tamas committed 2026-10-24 19:19:19 +07:00
1 parent cce687bf2c
commit a9e627b7ca
44 files changed
+3118 -51

No files matched your search

+51 -6
View File
@@ -181,18 +181,34 @@ typedef struct RadBuildCtx {
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int kv_quant;
/* ---- appended in ABI 26 (fp8 prefill attention) */
/* ---- appended in ABI 29 (fp8 prefill attention) */
/* RAD_ATTN_FP8_* bits from --attn-prefill-fp8: the attention products the deployment accepts
* in e4m3 rather than exactly. 0 (the zero-initialised default) is exact. A plugin passes a
* nonzero value on as `attn_paged`'s `prefill_fp8` (docs/OPS.md) and omits the parameter at
* 0, so an exact declare is unchanged. The engine refuses to start when no resolved kernel
* takes it, so a plugin that ignores the field is refused rather than silently exact.
*
* Zero-defaulted and in the padding after kv_quant, so no other field moves and a plugin built
* against the older struct is unchanged. */
* Zero-defaulted and in the padding after kv_quant, so no other field moves: it fills four
* bytes the ABI 28 layout already padded before kv_resident_blocks. */
int attn_prefill_fp8;
/* ---- appended in ABI 26 (control vectors) */
/* Nonzero: the storage of a streamed group's VRAM ring, from --kv-resident, and the only switch
* that turns KV streaming on (0: nothing streams). In tokens, as the flag spells it; the ring a
* group carves is this rounded up to whole blocks and clamped to the group's context, which is
* the number its `kv_resolve` is issued with. Declaring it lets a plugin state a ring depth in
* an op's geometry rather than the context bound, so the reported geometry is the real one.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int64_t kv_resident_blocks;
/* RadArchProbe::kv_stream_ok, carried to the declare: the architecture can stream at all. A
* streamed-only op (`kv_store_streamed`, its folded form, `kv_resolve`) exists only when this
* is set AND kv_resident_blocks asks for a ring, so an architecture that cannot stream declares
* none and every `rad_op_declared` in it falls through to the path it had before streaming.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int kv_stream_ok;
/* ---- appended in ABI 27 (control vectors) */
/* A control vector loaded from a GGUF `controlvector` file found for this model, or null.
*
* The engine loads and validates it once, at bringup, and the plugin only reads it: the
@@ -428,6 +444,11 @@ typedef struct RadKVGroupDecl {
rad_kvgroup rad_decl_kv_group(RadBuilder* b, const char* name, const RadKVGroupDecl* d);
/* Valid only after the op that reads this group has been declared. 0 before that. */
int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g);
/* Bytes one block of ONE layer of a paged group occupies: the pitch of its device pool's slot and
* of its host mirror's row. Derived from the declaration and the block size the attention kernel
* supplies, the same figure KVGroupPlan::layer_bytes_per_block() carves. 0 for a group that is not
* paged, or before the block size is known. Additive export. */
int64_t rad_kv_layer_bytes(RadBuilder* b, rad_kvgroup g);
/* Bind a layer to a group, so the block manager knows how many state instances a sequence owns. */
int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g);
@@ -526,9 +547,19 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g);
* rank computes whole, an indexer's key cache every rank pools into); the engine moves bytes and
* cannot know. RADIANCE_DEBUG_TIER_VERIFY checks the claim: each follower hashes what it would
* have written and the leader compares. Paged groups only, and never a group this rank declared
* zero. No effect at one rank. Additive export; RAD_ABI_VERSION does not move. */
* zero. No effect at one rank. A replicated group is never streamed: every rank already holds
* it whole, so a streamed store would write the same bytes world times. Additive export;
* RAD_ABI_VERSION does not move. */
int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g);
/* This rank reads the group's whole live history every decode step, so it cannot be streamed
* from host memory: an indexer's block keys, which a scorer walks densely each step. While a
* sibling group streams, the carve funds this one for every sequence's full context instead of
* the split's shared token count -- the host mirror is sized for --max-num-seqs sequences, and an
* indexer funded for one would make that capacity a promise the engine cannot keep. A flag on the
* group, not a sizing hint: it does not change the group's dtype or site. Additive export. */
int rad_kv_group_dense_read(RadBuilder* b, rad_kvgroup g);
#define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \
(int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf))
@@ -1429,8 +1460,22 @@ typedef struct RadArchProbe {
* then takes them. Zero keeps them off: plain decode measured slower chained, and a plugin
* that never measured them asks for nothing. */
int32_t chain_pays;
/* Nonzero when the architecture can move a KV group between host memory and a resident VRAM
* ring: its attention is sparse and block-addressed, and it declares a streamed store
* (`kv_store_streamed` or the folded form) and `kv_resolve` for both. This is the table entry
* that makes --kv-resident automatic: the core declares the streamed-only ops only for an
* architecture that says yes here (RadBuildCtx::kv_stream_ok, core/kvstream/bringup.cpp), so a
* model that does not stream keeps the graph, arena and kernels it had before streaming
* existed, and the operator's flag is turned off at startup with one sentence naming the
* architecture rather than failing after declare.
*
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
int32_t kv_stream_ok;
/* ---- appended in ABI 29 (control vectors) */
/* Nonzero when the plugin applies RadBuildCtx::cvec for this model. --control-vector is
* refused at startup with the plugin named when this is 0. */
* refused at startup with the plugin named when this is 0.
*
* Trailing and zero-defaulted after ABI 28's kv_stream_ok. */
int32_t control_vector_ok;
/* ---- appended in ABI 27 (row-split prefill attention) */
+96
View File
@@ -663,6 +663,11 @@ struct Geom {
int64_t max_tok = 0;
int64_t max_seqs = 0;
int64_t max_ctx = 0;
/* --kv-resident, in tokens (RadBuildCtx::kv_resident_blocks), 0 when nothing streams. The
* streamed group's ring is this many tokens rounded up to whole blocks; a declaration that must
* state a ring depth states this rather than the whole context, so the geometry an op reports
* is the geometry it is issued with. */
int64_t kv_resident = 0;
int max_spec = 0;
/* Most rows the sampler can want in one step: one per sequence, or one per draft position per
* sequence at a speculative verify. Bounds the logits buffer (at a 248K vocab, 63 MiB rather
@@ -939,6 +944,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
g.max_tok = c->max_tok;
g.max_seqs = c->max_seqs;
g.max_ctx = c->max_ctx;
g.kv_resident = c->kv_resident_blocks;
g.max_spec = c->max_spec;
g.max_logit_rows = c->max_seqs * (c->max_spec > 0 ? c->max_spec + 1 : 1);
if (g.max_logit_rows > c->max_tok) g.max_logit_rows = c->max_tok;
@@ -1059,6 +1065,96 @@ inline int64_t vocab_head_rows(const Geom& g) {
* handle. */
inline RadOperand kv_cache(rad_kvgroup group, int layer) { return RAD_KV(group, layer); }
/* The row a streamed group's layer occupies in its host mirror, or null when the group does not
* stream on this rank. The mirror is layer-major over the group's BOUND layers, in the order
* KVPoolBinding::layer_slot holds them, not over absolute model layers: a group's layers need not
* be contiguous (Qwen3.8-Flash-Next's full-attention layers are every other layer, plus the MTP
* head), so `rad_kv_layer_index` makes the same lookup a RAD_KV operand does and `layer` alone
* would read another layer's bytes. */
inline const uint8_t* kv_stream_host(RadCtx* c, rad_kvgroup group, int layer,
const RadKVStream* s) {
if (!s || !s->host || s->block_bytes <= 0) return nullptr;
const int64_t li = rad_kv_layer_index(c, group, layer);
return li >= 0 ? s->host + li * s->host_layer_stride : nullptr;
}
/* Stage this layer for a streamed group's prefill pass. True when the group selected the-one-layer
* stage view: a copy was issued (or this layer was already staged for the pass), so the caller must
* not resolve and must read block ids directly. The ordering rule that makes the aliasing safe is
* in core/kvstream/stage.h; do not move this call off the compute stream or the layer's place
* between its store and its attention. */
inline bool kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer) {
return rad_kv_stage_layer(c, group, kvb, layer) != 0;
}
/* The prefill stage's two DMA seams (docs/KV-STREAMING.md §5 Phase 3). Not in the frozen ABI: they
* are what this architecture needs to keep the ordering rule in core/kvstream/stage.h, and any
* plugin that stages a group must make the same two calls.
*
* kv_stage_wait -- immediately BEFORE the layer's store, so the copy that reads the mirror lands
* before the store's newer bytes go into the stage;
* kv_stage_next -- after every attention launch of the layer, so the copy of the next layer starts
* only once the last read of the aliased stage is behind it, riding on the next
* dispatch on this stream. */
extern "C" int rad_kv_stage_wait(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer);
extern "C" int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer);
inline bool kv_stage_wait(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer) {
return rad_kv_stage_wait(c, group, kvb, layer) != 0;
}
inline void kv_stage_next(RadCtx* c, rad_kvgroup group, int layer) {
(void)rad_kv_stage_next(c, group, layer);
}
/* The `kv_resolve` a streamed group's block declares. Every architecture declares the same
* geometry, and none of it is a free parameter:
*
* blocks the block-id space a selection can name: max_seqs rows of the group's whole
* context;
* slots the ring --kv-resident carves, in whole blocks, clamped to `blocks`. NOT the
* block-id space: the resolve is issued with the pool's depth and can never address
* more, so declaring the context would size the row's scratch for slots it cannot
* reach. It is also a ceiling over the flag rather than the flag: an operator who
* asks for a ring smaller than one decode step can name has it raised to
* max_seqs x (1 + n_spec) x sel_pitch before anything is carved (kvstream_ring), and
* the declaration must cover that product or the resolve would refuse the very ring
* it was sized for. With nothing streaming the ring covers the context and `slots` is
* `blocks`;
* sel_pitch the selection row's pitch, which is what the attention op declares its own rows
* with (`qsa_topk + 1` on the sparse path, the indexer's count on GLM).
*
* The claim count the op's miss list has to hold is derived from these rather than stated
* anywhere: one claim is one distinct block a launch's selection names, so a launch makes at most
* `M * sel_pitch` of them, and those two operands are what the kernel sizes its shared claim list
* from (libr4d/r4d_kv_resolve.hip's kv_claim_cap). ctl[12] reports the largest claim count a
* launch has actually made, so a declaration that is ever wrong shows up in the engine's stream
* report.
*
* `sel` is declared read as well as written, so the arena keeps the selection live from its
* producer to the attention across this op. Returns 0 when the arch does not declare the op or the
* group has nothing to address, which is the caller's "no resolve on this path". */
inline rad_op kv_resolve_declare(RadBuilder* b, const Geom& g, rad_kvgroup kv, rad_buf sel,
rad_buf nsel, int64_t sel_pitch) {
if (!rad_op_declared(b, "kv_resolve") || !sel || !nsel || sel_pitch <= 0) return 0;
const int64_t bs = rad_kv_block_size(b, kv);
const int64_t bbytes = rad_kv_layer_bytes(b, kv);
const int64_t blocks = bs > 0 ? g.max_seqs * ((g.max_ctx + bs - 1) / bs) : 0;
if (bs <= 0 || bbytes <= 0 || blocks <= 0) return 0;
const int64_t ring = g.kv_resident > 0 ? (g.kv_resident + bs - 1) / bs : 0;
const int64_t step = g.max_seqs * (1 + (g.max_spec > 0 ? g.max_spec : 0)) * sel_pitch;
const int64_t want = ring > 0 && step > ring ? step : ring;
const int64_t slots = want > 0 && want < blocks ? want : blocks;
const rad_op op = RAD_OP(b, "kv_resolve",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("blocks", blocks),
RAD_INT("slots", slots), RAD_INT("sel_pitch", sel_pitch),
RAD_INT("block_bytes", bbytes)),
RAD_NOWEIGHTS);
if (!op) return 0;
const rad_buf rd[2] = { sel, nsel };
rad_op_reads(b, op, rd, 2);
rad_op_writes(b, op, &sel, 1);
return op;
}
/* ================================================================== step-sized operands */
/* Every operand a step issues carries the step's row count, not the buffer's.
*
+1 -1
View File
@@ -4,7 +4,7 @@
# Sources are globbed per subdirectory with CONFIGURE_DEPENDS. Re-run cmake if a new file does not
# appear.
set(RAD_CORE_DIRS util device plugin build runtime mem sched place sample text server format mm diag gen
lora)
lora kvstream)
set(RAD_CORE_SRC "")
foreach(d ${RAD_CORE_DIRS})
+2
View File
@@ -115,6 +115,7 @@ public:
rad_buf decl_buffer (const char* name, const RadBufDecl* d);
rad_kvgroup decl_kv_group(const char* name, const RadKVGroupDecl* d);
int64_t kv_block_size(rad_kvgroup g);
int64_t kv_layer_bytes(rad_kvgroup g);
int bind_layer_kv(int layer, rad_kvgroup g);
rad_op decl_op (const char* op, const RadParam* p, int n_p,
const rad_weight* w, int n_w);
@@ -146,6 +147,7 @@ public:
int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi,
const int64_t* total, int n);
int kv_group_zero(rad_kvgroup g);
int kv_group_dense_read(rad_kvgroup g);
int kv_group_replicated(rad_kvgroup g);
/* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns
+40
View File
@@ -9,6 +9,7 @@
* which makes fusion a selection rather than a compiler pass (spec §2.3).
*/
#include "rad_build.h"
#include "kvstream/bringup.h"
#include "lora/lora.h"
#include "../device/device.h"
@@ -466,6 +467,19 @@ int64_t Builder::kv_block_size(rad_kvgroup g) {
return 0;
}
/* The per-layer byte pitch of a paged group's block. finish_kv_groups() computes the same figure
* times the number of bound layers; this is the one a kernel addressing a single layer sees, and
* a streamed group's host mirror rows are this far apart. */
int64_t Builder::kv_layer_bytes(rad_kvgroup g) {
if (g == 0 || g >= prog_.kv_groups.size()) return 0;
KVGroupInfo& gi = prog_.kv_groups[g];
if (gi.decl.kind != RAD_KV_FULL && gi.decl.kind != RAD_KV_WINDOW) return 0;
const int64_t bs = kv_block_size(g);
if (bs <= 0) return 0;
const int64_t nh = gi.decl.n_head_kv > 0 ? gi.decl.n_head_kv : 1;
return rad_dtype_bytes(gi.decl.dtype, 2 * bs * nh * gi.decl.head_dim);
}
/* ================================================================== ops */
void Builder::record_tune_request(const Resolved& r) {
if (!r.row || !r.row->info || r.row->info->n_tunables <= 0) return;
@@ -803,6 +817,7 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
}
int Builder::op_declared(const char* op) const {
if (kvstream_op_gated(prog_.ctx, op)) return 0; /* no ring: a streamed op does not exist */
return op && reg_.schema(op) ? 1 : 0;
}
@@ -958,6 +973,21 @@ int Builder::kv_group_zero(rad_kvgroup h) {
return RAD_OK;
}
int Builder::kv_group_dense_read(rad_kvgroup h) {
if (finished_) { err(RAD_E_STATE, "kv_group_dense_read after declare finished"); return RAD_E_STATE; }
if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL;
/* Paged groups only: a per-sequence state slot is already sized for every sequence, and a
* window already bounds its own history. Only a full group's block count can be short. */
const KVGroupInfo& gi = prog_.kv_groups[h];
if (gi.decl.kind != RAD_KV_FULL) {
err(RAD_E_INVAL, "kv group '%s': dense_read on a group that is not a full attention group",
gi.name.c_str());
return RAD_E_INVAL;
}
prog_.kv_groups[h].dense_read = true;
return RAD_OK;
}
int Builder::kv_group_replicated(rad_kvgroup h) {
if (finished_) {
err(RAD_E_STATE, "kv_group_replicated after declare finished");
@@ -2448,6 +2478,11 @@ int64_t rad_kv_block_size(RadBuilder* b, rad_kvgroup g) {
return B(b)->kv_block_size(g);
}
int64_t rad_kv_layer_bytes(RadBuilder* b, rad_kvgroup g) {
if (!b) return 0;
return B(b)->kv_layer_bytes(g);
}
int rad_bind_layer_kv(RadBuilder* b, int layer, rad_kvgroup g) {
if (!b) return RAD_E_INVAL;
return B(b)->bind_layer_kv(layer, g);
@@ -2510,6 +2545,11 @@ int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) {
return B(b)->kv_group_zero(g);
}
int rad_kv_group_dense_read(RadBuilder* b, rad_kvgroup g) {
if (!b) return RAD_E_INVAL;
return B(b)->kv_group_dense_read(g);
}
int rad_kv_group_replicated(RadBuilder* b, rad_kvgroup g) {
if (!b) return RAD_E_INVAL;
return B(b)->kv_group_replicated(g);
+25
View File
@@ -85,6 +85,15 @@ static const Flag g_flags[] = {
{ "--attn-prefill-fp8", "MODE", "off (default) | qk | pv | both -- the prefill attention's\n"
"Q.K^T, P.V or both as e4m3 WMMA over an fp8, fp8_v4 or\n"
"k6_v4 cache: faster at long context, and lossy" },
{ "--kv-resident", "N", "tokens of the sparse attention group's KV its VRAM ring\n"
" holds; the whole switch. Absent or 0 keeps every block on\n"
" the card. At or above the group's context (sequences x\n"
" --max-model-len) nothing streams either: the group stays a\n"
" plain resident pool and the engine takes its ordinary path,\n"
" with no mirror, no stage and no resolve. Below it, the rest\n"
" of each block lives in pinned host memory and the ring must\n"
" hold one decode step's whole selection; a smaller ring is\n"
" raised to that many blocks at startup, with a warning" },
{ "--host-pool-mib", "N", "pinned host tier" },
{ "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n"
" pins its host memory at startup (default 4096)" },
@@ -531,6 +540,20 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
}
else if (S("--kv-streaming")) {
RAD_ERR("--kv-streaming was removed: --kv-resident N is the whole switch. It is the "
"tokens of the sparse attention group's KV its VRAM ring holds, and leaving it "
"off keeps every block on the card; there is no mode to choose past it");
return RAD_E_INVAL;
}
else if (S("--kv-resident")) { if (!num(0, INT64_MAX, &c->kv_resident)) return RAD_E_INVAL; }
else if (S("--kv-stream-threshold")) {
RAD_ERR("--kv-stream-threshold was removed: the streamed path is the cheap one. The "
"base path for a live set that fits the ring measured 2.6-2.9%% slower a step "
"(record §74), so --kv-resident N is the whole switch and there is no path to "
"choose");
return RAD_E_INVAL;
}
else if (S("--host-pool-mib")) { if (!num(0, INT64_MAX, &c->host_pool_mib)) return RAD_E_INVAL; }
else if (S("--embedding-placement") || S("--ngram-placement")) {
const bool emb = S("--embedding-placement");
@@ -1091,6 +1114,8 @@ const ShowRow kShow[] = {
{ "--state-cache-dtype", [](const Config& c) { return c.state_cache_dtype; } },
{ "--attn-prefill-fp8", [](const Config& c) {
return std::string(attn_prefill_fp8_name(c.attn_prefill_fp8)); } },
{ "--kv-resident", [](const Config& c) {
return c.kv_resident > 0 ? num(c.kv_resident) : std::string("0 (off: no group streams)"); } },
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } },
{ "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } },
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
+166 -2
View File
@@ -15,6 +15,7 @@
#include "device/device.h"
#include "format/radfile.h"
#include "gen_config.h"
#include "kvstream/stage.h"
#include "sample/accept.h"
#include "sched/scheduler.h"
#include "server/adapters.h"
@@ -73,6 +74,7 @@ Engine::~Engine() {
/* --profile-ops prints its final table here, the last point where the program still holds
* the op table the rows name. */
if (cfg_.profile_ops) for (auto& r : ranks_) r->ctx.dump_profile();
if (stream_ctl_p_) rad_dev_free(stream_ctl_p_, RAD_MEM_HOST_PINNED);
for (float* p : kld_host_) if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED);
if (pooled_host_) rad_dev_free(pooled_host_, RAD_MEM_HOST_PINNED);
for (auto& r : ranks_) if (r->score_host) rad_dev_free(r->score_host, RAD_MEM_HOST_PINNED);
@@ -96,6 +98,10 @@ Engine::~Engine() {
for (auto& r : ranks_)
if (RadStream s = r->mover.transfer_stream()) (void)rad_stream_sync(s);
for (auto& r : ranks_) r->ctx.shutdown();
/* A streamed group's host mirror is pinned outside every pool; the ring's maps came from the
* KV pool and go with it in ranks_.clear(). After the contexts, since a pass reads the mirror,
* and safe after a failed bring-up: a group that never got one is skipped. */
for (auto& r : ranks_) r->kv.free_stream(rad_device_allocator());
step_state_fini();
ranks_.clear();
for (TableCopy& c : table_copies_) table_copy_free(&c);
@@ -346,6 +352,12 @@ int Engine::prepare_release(const RadBatch* b) {
step_status_.store(RAD_E_NOMEM, std::memory_order_release);
}
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
/* This pass's stage bound, for every rank. Block ids are one table and rank 0's allocator is
* the only one that hands them out (the followers follow, above), so rank 0's highest held
* block bounds what any rank's staged layers can be asked to read. Read here rather than in the
* rank threads: the ranks are parked, so the next step's allocations cannot race it
* (kvstream/stage.h, "VOLUME"). */
for (auto& rk : ranks_) kvstream_bound_live(&rk->ctx, ranks_[0]->kv);
return RAD_OK;
}
@@ -690,6 +702,10 @@ int Engine::step_loop() {
st = block_drafting() ? issue_block_drafter(b->step, so)
: issue_serial_drafter(b->step, so);
if (st < 0) return fail_loop(st);
/* Behind this step's last resolve and inside the step-end event, so collect_step's wait
* proves the counters landed and the step path pays no extra synchronisation. */
st = stream_probe_issue(b);
if (st < 0) return fail_loop(st);
st = mark_step_end(b, so);
if (st < 0) return fail_loop(st);
/* Then the next step's forward pass, before this step is read back. Its rows continue from
@@ -754,6 +770,14 @@ int Engine::step_loop() {
st = sched_.commit(res);
if (t_on) phase_mark(PH_COMMIT);
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
/* The step is drained (collect_step waited on its end event), so the counters are readable.
* A chunk that produced no row did not wait, so its copy may still be in flight and is
* simply read on a later step; a prompt that completed or a request that ended always
* produced a row. */
if (so.n_rows > 0) {
st = stream_probe_take(b, res.n_prefill_done > 0, res.n_finished > 0);
if (st < 0) return fail_loop(st);
}
/* The drafter for the next step already ran on the card; what remains is to check its
* acceptance against the host's and publish its proposals. Each driver returns
@@ -824,6 +848,136 @@ int Engine::collect_issue(StepOut& so) {
return RAD_OK;
}
/* ================================================================== KV streaming's counters
*
* The resolve keeps its cumulative counters, the peak union of one launch and the overflow latch in
* each streamed group's device control block (libref/ref_kvstream.cpp, "The control block"). The
* ring's depth is decided at startup (kvstream_ring, kvstream/plan.h: one decode step's selections,
* the arch's `topk + 1` a row); these counters are what says at run time that the decision holds,
* and a launch that does not fit is failed rather than served (docs/KV-STREAMING.md §3.4, §5
* Phase 4).
*
* The step path never waits on the card, so this does not sync: the copy is enqueued on rank 0's
* compute stream *behind the step's last resolve and before the step-end event*, and the commit that
* already waits for that event reads the pinned landing area. The numbers are then this step's, at
* the cost of one 64-byte copy per streamed group per step. They are per rank; one rank's answer is
* every rank's, because the ranks resolve the same shared block ids through maps brought up
* identically.
*
* `ctl` is cumulative, so metrics are charged the deltas (KVManager::note_stream_traffic) and the log
* carries the absolute numbers. */
int Engine::stream_probe_issue(const RadBatch* b) {
if (!b || b->n_kv_groups <= 0 || ranks_.empty()) return RAD_OK;
const size_t n = (size_t)b->n_kv_groups;
if (stream_ctl_n_ < n) {
if (stream_ctl_p_) rad_dev_free(stream_ctl_p_, RAD_MEM_HOST_PINNED);
stream_ctl_p_ = static_cast<int32_t*>(
rad_dev_alloc((int64_t)n * 16 * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED));
stream_ctl_n_ = stream_ctl_p_ ? n : 0;
if (!stream_ctl_p_) {
RAD_ERR("kv streaming: no pinned host memory for the resolve's counters, so a streamed "
"step could be neither measured nor checked for overflow");
return RAD_E_NOMEM;
}
/* Zero, so a group whose first copy has not landed reads as "no calls yet" rather than as
* whatever the page held. */
std::memset(stream_ctl_p_, 0, n * 16 * sizeof(int32_t));
}
RadStream st = ranks_[0]->ctx.stream();
for (size_t i = 0; i < n; ++i) {
const RadKVStream* sv = b->kv[i].stream;
if (!sv || !sv->ctl) continue;
if (rad_memcpy_async(stream_ctl_p_ + i * 16, sv->ctl, 16 * 4, st) < 0) {
RAD_ERR("kv streaming: the resolve's counters could not be copied to the host: %s",
rad_dev_last_error());
return RAD_E_STATE;
}
}
return RAD_OK;
}
/* Read what stream_probe_issue() enqueued, at a point the step already drained. Charges the metrics
* and, when asked, logs a line for the request. A newly latched overflow is never served: every
* request that was prefilling in the step just committed is failed with the ring size and the union
* that did not fit, and the latch is cleared on the card so the next request is measured on its own
* -- the map itself is consistent again, because the resolve reverts a claim it could not place. */
int Engine::stream_probe_take(const RadBatch* b, bool prefill_done, bool request_end) {
if (!b || !stream_ctl_p_ || b->n_kv_groups <= 0) return RAD_OK;
const size_t n = (size_t)b->n_kv_groups;
if (stream_prev_.size() < n) stream_prev_.assign(n, StreamRead{});
RadStream st = ranks_[0]->ctx.stream();
bool overflowed = false;
std::string overflow_why;
for (size_t i = 0; i < n; ++i) {
const RadKVStream* sv = b->kv[i].stream;
if (!sv) continue;
const int32_t* c = stream_ctl_p_ + i * 16;
/* The counters are the three u64s from ctl[4] (libref/ref_kvstream.cpp, "The control
* block"), which is why the block is 8-byte aligned. */
const uint64_t* ctr = (const uint64_t*)(c + 4);
StreamRead r;
r.group = (int32_t)b->kv[i].group;
r.misses = (int64_t)ctr[0];
r.lookups = (int64_t)ctr[1];
r.resolves = (int64_t)ctr[2];
r.overflow = c[3] != 0;
r.max_union = c[10];
r.max_misses = c[11];
r.max_claims = c[12];
r.slots = sv->slots;
r.block_bytes = sv->block_bytes;
const StreamRead& p = stream_prev_[i];
const int64_t dm = r.misses - p.misses;
ranks_[0]->kv.note_stream_traffic(dm, dm * r.block_bytes);
if (request_end || prefill_done) stream_report(request_end ? "request end" : "prefill complete", r, p);
if (r.overflow && !p.overflow && !overflowed) {
overflowed = true;
const KVGroupPlan* gp = ranks_[0]->kv.plan(r.group);
const int64_t bs = gp && gp->block_size > 0 ? gp->block_size : 1;
/* The union is the largest one launch has selected since bring-up, which for a
* failing request is the launch that overflowed (it is at least the ring's depth). */
overflow_why = fmt(
"kv streaming overflow: group '%s' ring holds %lld blocks (%lld tokens) and one "
"resolve launch selected %lld distinct blocks, %lld of them not resident. The "
"request is failed rather than served from a selection table that no longer "
"addresses the pool; raise --kv-resident above %lld tokens and retry",
gp ? gp->name.c_str() : "?", (long long)r.slots, (long long)(r.slots * bs),
(long long)r.max_union, (long long)r.max_misses,
(long long)(r.max_union * bs));
RAD_ERR("%s", overflow_why.c_str());
}
stream_prev_[i] = r;
}
if (overflowed) {
/* Every request whose prompt the last step was still laying down read the table the failed
* sweep produced; fail it with the number, and clear the latch so the next request's
* measurement is its own (the resolve reverted the unplaced claims, so the map is legal). */
(void)sched_.fail_prefilling(overflow_why.c_str());
for (size_t i = 0; i < n; ++i) {
const RadKVStream* sv = b->kv[i].stream;
if (sv && sv->ctl) (void)rad_memset_async(sv->ctl + 3, 0, 4, st);
}
}
return RAD_OK;
}
/* One line per group: cumulative resolves, lookups and misses, and the three measured maxima, which
* are the numbers a ring -- and a resolve's claim list -- are sized from. The delta since the
* previous report is the part this interval contributed, so a single request's cost reads
* directly. `largest launch claims` is `ctl[12]`: a claim is a distinct block the launch found
* absent, one call makes at most `max_seqs * sel_pitch` of them, and a value above that says the
* derivation is wrong somewhere -- which is why it is reported rather than assumed. */
void Engine::stream_report(const char* when, const StreamRead& r, const StreamRead& prev) {
const KVGroupPlan* gp = ranks_.empty() ? nullptr : ranks_[0]->kv.plan(r.group);
RAD_INFO("kv streaming: group '%s' %s: %lld resolves, %lld lookups, %lld misses (+%lld this "
"interval); ring %lld blocks, largest launch union %lld distinct blocks, largest "
"launch misses %lld, largest launch claims %lld, overflow %s",
gp ? gp->name.c_str() : "?", when, (long long)r.resolves, (long long)r.lookups,
(long long)r.misses, (long long)(r.misses - prev.misses), (long long)r.slots,
(long long)r.max_union, (long long)r.max_misses, (long long)r.max_claims,
r.overflow ? "LATCHED" : "no");
}
int Engine::mark_step_end(const RadBatch* b, StepOut& so) {
if (embedding_) RAD_TRY(collect_pooled_issue(b, so));
else if (so.n_rows > 0 && !so.rb) RAD_TRY(collect_issue(so));
@@ -1554,8 +1708,18 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
* PCIe read and unordered against the copies that fill it (see Set in batch.h). */
std::vector<BatchBuilder::RankIO> rio;
rio.reserve(ranks_.size());
for (auto& rk : ranks_)
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program });
rank_stream_views_.assign(ranks_.size(), {});
for (size_t r = 0; r < ranks_.size(); ++r) {
const size_t ng = ranks_[r]->program.kv_groups.size();
rank_stream_views_[r].resize(ng, nullptr);
for (size_t g = 0; g < ng; ++g)
rank_stream_views_[r][g] = ranks_[r]->kv.stream_view((int32_t)g);
}
for (size_t r = 0; r < ranks_.size(); ++r) {
auto& rk = ranks_[r];
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program, rk->pools.kv().base(),
rank_stream_views_[r].data() });
}
if (video_gen) {
/* As for the image generator below; the plugin lays out each request's rows. */
std::vector<gen::VideoDriver::RankIO> gio;
+34
View File
@@ -114,6 +114,9 @@ private:
* than broadcast (spec §1). */
struct Rank;
std::vector<std::unique_ptr<Rank>> ranks_;
/* Per rank and KV group, that rank manager's stream view, or null for a resident group. The
* batch builder takes these instead of dereferencing a manager it cannot know per rank. */
std::vector<std::vector<const RadKVStream*>> rank_stream_views_;
/* The tiers' work in flight: the host-memory copies the transfer streams are running. */
std::unique_ptr<TierPump> pump_;
/* serve()'s startup stall watch, released when the server listens (run_server) or the KL
@@ -334,6 +337,33 @@ private:
int mark_step_end(const RadBatch* b, StepOut& so);
RadEvent step_end_ = nullptr;
/* ---- KV streaming's measured counters (docs/KV-STREAMING.md §3.4, §5 Phase 1) ----
*
* The resolve keeps its counters in each streamed group's device control block (`ctl[4..],
* [10], [11]`, libref/ref_kvstream.cpp). The step path must not wait on the card, so the copy
* is *enqueued* behind the step's last resolve and before the step-end event, and read at the
* commit that already waits for that event: the numbers are this step's, and no extra
* synchronisation is added. Pinned, because a device-to-host copy into pageable memory blocks
* on the stream.
*
* The reports are what one launch selects against what the ring holds, for the metrics and for
* a ring that turns out too shallow at run time. Overflow is never served -- the request is
* failed. */
struct StreamRead {
int64_t resolves = 0, lookups = 0, misses = 0;
int64_t max_union = 0, max_misses = 0, max_claims = 0;
int64_t slots = 0, block_bytes = 0;
bool overflow = false;
int32_t group = -1;
};
std::vector<StreamRead> stream_prev_; /* what metrics have already been charged */
/* Pinned landing area for the copies: [n_kv_groups][16] i32, grown on first use. */
int32_t* stream_ctl_p_ = nullptr;
size_t stream_ctl_n_ = 0;
int stream_probe_issue(const RadBatch* b);
int stream_probe_take(const RadBatch* b, bool prefill_done, bool request_end);
void stream_report(const char* when, const StreamRead& r, const StreamRead& prev);
/* The draft head as declared (rad_declare_drafter), zeroed when no speculative window was
* asked for. `kind` selects which of the two drivers below runs. `drafter_name_` owns the
* string because RadDrafterDecl::name points into the Program. */
@@ -518,6 +548,10 @@ private:
void decide(const std::string& key, const std::string& value, const std::string& why) {
diag::decide(&decisions_, key, value, why);
}
/* The architecture's capability table (RadArchProbe), asked once in declare(): a property of
* the model rather than of the deployment, so every RadBuildCtx this engine builds carries the
* one answer (RadBuildCtx::kv_stream_ok). Zeroed means nothing was asked yet. */
RadArchProbe arch_probe_{};
std::string devnote_; /* the devices usable_devices left out, and why */
int p2p_measured_ = -1; /* 1 peer to peer, 0 through host memory, -1 not asked */
std::string p2p_blocked_;
+74 -10
View File
@@ -21,6 +21,8 @@
#include "format/table_copy.h"
#include "rad_plugin.h"
#include "mem/vram_budget.h"
#include "kvstream/bringup.h"
#include "kvstream/plan.h"
#include "runtime/arena.h"
#include "runtime/kvbind.h"
#include "runtime/xprefetch.h"
@@ -329,14 +331,10 @@ static void memory_cgroups(const std::function<bool(const std::string&, int64_t)
}
}
/* Whether `need` more bytes fit in host memory after `still` more this process will allocate
* first and `margin` (--host-headroom-mib) stays free, or why not. Checks MemAvailable; every
* memory cgroup from the process's own up to the visible root (Docker's --memory, enforced by
* the OOM killer); and, for an mlock()ed copy (`mlocks`), RLIMIT_MEMLOCK unless the process has
* CAP_IPC_LOCK. Pinned memory a card reads is a driver userptr mapping, which RLIMIT_MEMLOCK
* does not count. An unreadable limit is ignored, never guessed. */
static bool lockable_room(int64_t need, int64_t still, int64_t margin, bool mlocks,
std::string* why) {
/* Declared in engine_hostmem.h, which carries the contract and the comment: the mirror of a
* streamed KV group is a second caller (kvstream/bringup.cpp). */
bool lockable_room(int64_t need, int64_t still, int64_t margin, bool mlocks,
std::string* why) {
long long locked_kb = 0;
unsigned long long caps = 0;
{
@@ -918,6 +916,12 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
/* Under --prefill-span every step but a lone prefill is planned at the shared budget
* (Scheduler::step), so a wider step is one sequence; 0 without a span. */
bc.max_mixed_tok = cfg_.prefill_span > 1 ? std::min(max_tok, prefill_shared_tok(cfg_)) : 0;
/* --kv-resident, in tokens: the ring a streamed group carves. Declared geometry states it where
* an op needs a ring depth (kv_resolve), so the report is the ring and not the context. */
bc.kv_resident_blocks = cfg_.kv_resident;
/* The probe's answer, so a streamed-only op is declared only for an architecture that serves
* one AND a deployment that asked (core/kvstream/bringup.cpp, kvstream_op_gated). */
bc.kv_stream_ok = arch_probe_.kv_stream_ok;
/* The control vector, when one is loaded: this rank's view, or null. A plugin reads it at
* declare only (the direction table never changes); the per-request switch rides the derived
* mask, not this struct. */
@@ -928,6 +932,19 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
}
int Engine::declare() {
/* KV streaming is a capability before it is a choice: an architecture that does not declare the
* streamed ops declares none even with the flag set (core/kvstream/bringup.cpp), so the probe's
* answer is taken here, once, and rides every declare. With --kv-resident on and no capability
* the flag is turned off in one sentence naming the architecture, rather than letting a ring no
* store can write be discovered after declare. */
(void)rad_tools_probe(plugins_, meta_, &arch_probe_);
if (cfg_.kv_resident > 0 && arch_probe_.kv_stream_ok == 0) {
cfg_.kv_resident = 0;
decide("--kv-resident", "0",
std::string("architecture '") + (meta_.arch_id ? meta_.arch_id : "?") +
"' cannot address a resident ring: it declares no streamed KV store or resolve, "
"so nothing streams");
}
RAD_TRY(lora_targets());
/* KL mode measures the trunk (core/kld.h): a drafter writes no scored rows and a prefix hit
* would skip positions the reference holds, so both are off, and an explicit depth is refused
@@ -1589,6 +1606,13 @@ int Engine::plan() {
if (declare_ring_windows(probe, r->program) == RAD_OK &&
probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
ck_slot += probe.checkpoint_bytes();
/* The budget must see the streamed plan before it sizes the pool: with a
* one-layer stage the group's ceiling is max(ring, one layer of its context), and
* cap_resident_tokens only runs much later (docs/KV-STREAMING.md §4.1). Without
* this the pool is still sized for the whole cache and the phase frees nothing.
* It prices the ring raised to a decode step's selection, before any weight is
* loaded. */
RAD_TRY(kvstream_cap_probe(probe, cfg_, r->program, ctx));
f.kv_ceiling = probe.ceiling(ctx);
f.kv_fixed = probe.fixed_bytes();
/* One --max-model-len sequence's pool, as the inverse of the real plan: its
@@ -3054,6 +3078,17 @@ int Engine::configure_kv() {
"block and the linear-state chunk), so a checkpoint is a legal chunk split",
(long long)geo_.quantum)
: std::string("the model keeps no linear state to checkpoint"));
/* KV streaming's policy, its refusals, the ring's ceiling and the cap on every rank's pool
* (kvstream/bringup.h). The group is chosen once, from rank 0's declarations, because a
* streamed group must be the same group on every rank. --kv-resident is the whole switch: a
* ring that covers the group's context leaves `stream.group` at -1 and the group runs the
* engine's ordinary resident path. */
KVStreamSetup stream;
if (!ranks_.empty())
RAD_TRY(kvstream_configure(cfg_, cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train,
ranks_[0]->program.kv_groups, ranks_[0]->program, &stream));
if (stream.group >= 0)
for (auto& r : ranks_) r->kv.cap_resident_tokens(stream.group, stream.ring_tokens);
/* One block table serves every rank (serve() checks it), so every rank carves the same number
* of paged blocks. Under an uneven split the pools differ (more delta-net heads, or zero
* attention weights), so each rank is planned first and all are capped at the least before
@@ -3077,6 +3112,24 @@ int Engine::configure_kv() {
if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */
if (least < 0 || t < least) least = t;
}
/* KV streaming's host tier: the mirrors are the largest host allocation in the engine after
* the experts' pool, so they are checked once, before any rank takes one, against everything
* still to be pinned after them (kvstream/bringup.h). What is still to come is the rest of the
* engine's host tiers, so it is summed here: the prefix cache's, the activation arenas and the
* checkpoint store when its size is already fixed. */
KVStreamHostUse stream_host;
for (auto& r : ranks_) kvstream_host_add(&stream_host, r->kv);
if (stream_host.sum.host_bytes > 0) {
const int64_t MiB = (int64_t)1 << 20;
int64_t still = cfg_.prefix_cache_mib * MiB;
for (auto& r : ranks_) still += arena_host_bytes(r->program);
if (cfg_.checkpoint_slots > 0) {
int64_t slot = 0;
for (auto& r : ranks_) slot += r->kv.checkpoint_bytes();
still += slot * cfg_.checkpoint_slots;
}
RAD_TRY(kvstream_host_gate(stream_host, (int)ranks_.size(), still, host_headroom_bytes()));
}
for (auto& r : ranks_) {
LogRank lr(r->index);
RAD_TRY(rad_dev_set(r->device)); /* allocates on the current device; see plan() */
@@ -3088,7 +3141,15 @@ int Engine::configure_kv() {
(long long)least);
r->kv.cap_paged_tokens(least);
}
/* Before the carve: the manager refuses a streamed plan whose mirror and map are not
* there, because an unbacked block id is written past the layer stride. The mirror is
* host memory outside every pool; the maps come out of this rank's KV pool, so the paged
* split below already has them taken and the pool report names them. */
const KVManager::StreamCost sc = r->kv.stream_cost();
if (sc.groups > 0)
RAD_TRY(r->kv.alloc_stream(rad_device_allocator(), r->pools.kv()));
RAD_TRY(r->kv.carve(r->pools.kv()));
if (sc.groups > 0) RAD_TRY(kvstream_fill(r->kv)); /* the maps, after the elastic pool */
/* Without virtual memory management the cache cannot lend: everything still works, but
* the expert slab never grows, which no counter shows, so log it once. */
if (r->index == 0 && !r->pools.kv().elastic())
@@ -3289,6 +3350,9 @@ int Engine::configure_kv() {
}
RAD_INFO("kv: %s", ranks_[0]->kv.report().c_str());
/* Which groups stream and what they took on both tiers, the stage, or which group's context
* the ring covers so that nothing streams at all (kvstream/bringup.h). */
kvstream_report(stream, stream_host, (int)ranks_.size());
/* The prefix cache's report: on or off, groups covered and skipped. It names the two things
* that silently disable caching on a hybrid model: a windowed group cannot be served a prefix,
* and a linear model with no checkpoint interval replays from zero. */
@@ -3571,8 +3635,8 @@ int Engine::start() {
const int64_t lbpb = p.layer_bytes_per_block(), stripe = p.layer_stride();
for (int64_t L = 0; L < p.n_layers; ++L) {
LoanStrip st;
st.top = (char*)p.base + L * stripe + p.n_blocks * lbpb;
st.bytes = p.n_blocks * lbpb;
st.top = (char*)p.base + L * stripe + p.pool_blocks() * lbpb;
st.bytes = p.pool_blocks() * lbpb;
st.unit_bytes = lbpb;
st.unit_tokens = p.block_size;
strips.push_back(st);
+9
View File
@@ -19,4 +19,13 @@ bool cgroup_room(const std::string& dir, bool v2, int64_t* room);
void cgroup_levels(const std::string& root, std::string path, bool v2,
const std::function<bool(const std::string& dir, int64_t room)>& visit);
/* Whether `need` more bytes fit in host memory after `still` more this process will allocate first
* and `margin` (--host-headroom-mib) stays free, or why not. Checks MemAvailable; every memory
* cgroup from the process's own up to the visible root (Docker's --memory, enforced by the OOM
* killer); and, for an mlock()ed copy (`mlocks`), RLIMIT_MEMLOCK unless the process has
* CAP_IPC_LOCK. Pinned memory a card reads is a driver userptr mapping, which RLIMIT_MEMLOCK does
* not count. An unreadable limit is ignored, never guessed. Shared with kvstream/bringup.cpp,
* which checks the streamed group's host mirror before any rank takes one. */
bool lockable_room(int64_t need, int64_t still, int64_t margin, bool mlocks, std::string* why);
} /* namespace rad */
+90
View File
@@ -0,0 +1,90 @@
/* bind.cpp -- see bind.h. */
#include "kvstream/bind.h"
#include "kvstream/plan.h"
namespace rad {
void kv_bind_views(const KVGroupPlan& p, KVPoolBinding* b) {
if (!b || !p.paged()) return;
b->base = p.base;
b->ring.layer_stride = p.layer_stride();
b->ring.bytes = kv_ring_bytes(p, p.pool_blocks());
b->ring.depth = 0;
b->ring.shape0 = p.pool_blocks();
b->has_stage = p.depth == 1;
if (b->has_stage) {
b->stage.layer_stride = p.n_blocks * p.layer_bytes_per_block();
b->stage.bytes = b->stage.layer_stride;
b->stage.depth = 1;
b->stage.shape0 = p.n_blocks;
}
kv_binding_enter(*b, KVView::Ring);
}
int64_t kv_binding_offset(const KVPoolBinding& b, int64_t layer) {
return b.depth == 1 ? 0 : layer * b.layer_stride;
}
KVView kv_pass_view(int phase, int64_t n_tok, int64_t n_seq, int n_spec) {
/* Not the phase label alone: a nominally decode pass can name more rows a sequence than a
* decode step ever does. The serial drafter's history pass (draft_pass -1) runs over the
* trunk's hidden states for a whole prefill chunk, so its rows are the chunk's tokens of every
* sequence -- a prefill-shaped read whose union is the histories it spans, not one selection a
* row. Such a pass issues one selection per row (`resolve_sel` is per query) and its union
* cannot be bounded by max_seqs x (1 + n_spec) x sel_pitch, so it must stage. A decode pass
* carries at most 1 + n_spec rows a sequence (a verify window) and takes the ring. */
if (phase != RAD_PHASE_DECODE) return KVView::Stage;
const int64_t rows = (int64_t)n_seq * (1 + (n_spec > 0 ? n_spec : 0));
return n_tok > rows ? KVView::Stage : KVView::Ring;
}
void kv_binding_enter(KVPoolBinding& b, KVView view) {
const KVViewState& v = (view == KVView::Stage && b.has_stage) ? b.stage : b.ring;
b.layer_stride = v.layer_stride;
b.bytes = v.bytes;
b.depth = v.depth;
b.shape[0] = v.shape0;
}
namespace {
template <typename T>
T* on_rank(const void* base_r, const void* base_0, T* p0) {
return p0 ? (T*)((char*)base_r + ((char*)p0 - (char*)base_0)) : nullptr;
}
} /* namespace */
uint64_t kvstream_view_key(const RadKVStream* v) {
if (!v) return 0;
uint64_t h = 0x9e3779b97f4a7c15ull;
auto mix = [&](uint64_t x) {
h ^= x + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
h *= 0xbf58476d1ce4e5b9ull;
};
auto p = [&](const void* q) { mix((uint64_t)(uintptr_t)q); };
p(v->host); p(v->res); p(v->slot_block); p(v->slot_state);
p(v->ctl);
mix((uint64_t)v->block_bytes); mix((uint64_t)v->host_layer_stride);
mix((uint64_t)v->slots); mix((uint64_t)v->host_bytes);
return h | 1;
}
const RadKVStream* kvstream_step_view(RadKVStream* out, const RadKVStream* src, bool per_rank,
const void* kv0, const void* kvr) {
if (!src) return nullptr;
*out = *src;
/* Rank 0's pointers are the basis; a follower's maps are moved into its own pool by the same
* offset its arena buffers take. Passing ring 0 through this leaves every pointer as it was. */
if (!per_rank && kv0 && kvr) {
out->res = on_rank(kvr, kv0, src->res);
out->slot_block = on_rank(kvr, kv0, src->slot_block);
out->slot_state = on_rank(kvr, kv0, src->slot_state);
out->ctl = on_rank(kvr, kv0, src->ctl);
}
return out;
}
} /* namespace rad */
+71
View File
@@ -0,0 +1,71 @@
/* bind.h -- the two views of a streamed group's one pool allocation.
*
* `layer_slot` stays the group-local position of every bound layer, because it is also the host
* mirror's row (rad_kv_layer_index -> kv_stream_host). Aliasing is a *depth*: the stage view
* reports depth 1, so every layer's operand resolves to offset 0 of the same allocation while the
* mirror keeps its per-layer addressing (docs/KV-STREAMING.md §3.5.1).
*
* A pass selects a view from its phase *and row shape*, before it is recorded or replayed. A
* one-row-a-sequence decode step (RAD_PHASE_DECODE within 1 + n_spec rows a sequence) takes the
* ring: its selection is rewritten to resident slots and misses are copied. Every other step --
* prefill, a mixed prefill+decode step (RAD_PHASE_MIXED), and a decode-classified pass with more
* rows a sequence than a decode step can have (the serial drafter's history pass over a chunk) --
* takes the stage: the stage is the group's whole context at identity addressing, so a decode row
* in a mixed chunk reads its block ids directly, exactly as a prefill row does, and no selection can
* overflow a ring. Selecting per pass is visible to the tape because `phase`, `n_tok`, `n_seq` and
* `n_spec` are already in the pass key.
*/
#pragma once
#include "mem/kv.h"
#include "runtime/ctx.h"
namespace rad {
enum class KVView { Ring, Stage };
/* Fill both fixed views from the plan and make the ring active. Call at bind time, after the
* plan's carve has set n_slots, n_blocks and depth. A non-paged group is left untouched. */
void kv_bind_views(const KVGroupPlan& p, KVPoolBinding* b);
/* The offset of a layer's cache in the active view. depth 1 aliases every layer to the pool base;
* the `off + layer_stride <= bytes` bound in issue.cpp is what makes that legal, and it is left
* exactly as it was. */
int64_t kv_binding_offset(const KVPoolBinding& b, int64_t layer);
/* The view a pass uses. `n_tok`, `n_seq` and `n_spec` are the pass's row shape, not just its
* phase: a decode-classified pass with more rows a sequence than a decode step can have (the
* serial drafter's history pass over a chunk) reads a prefill-shaped set and must take the stage.
* See bind.cpp. */
KVView kv_pass_view(int phase, int64_t n_tok, int64_t n_seq, int n_spec);
/* Make `view` the binding's active view. Stage falls back to the ring when the group has none. */
void kv_binding_enter(KVPoolBinding& b, KVView view);
/* One rank's step view of a group's ring and mirror, as the batch carries it; null when the group
* is not streamed. `src` is that rank's own manager view when the caller has per-rank views
* (`per_rank`), else rank 0's, whose map pointers are rebased from rank 0's pool (`kv0`) into this
* rank's (`kvr`).
*
* Each rank names its OWN manager's stream view. The device maps live in that rank's KV pool and
* the host mirror is that rank's pinned allocation; sharing rank 0's view made two ranks write
* different KV shards into the same mirror bytes, which a staged prefill then read back. A caller
* that gave no per-rank views (tests) still gets the old offset rebase, so a follower's maps do not
* point into its peer's pool.
*
* The addresses are fixed at bring-up, so a step's view is a copy of pointer values, not a per-step
* description; the batch outlives it with the `out` cell it is written into. */
const RadKVStream* kvstream_step_view(RadKVStream* out, const RadKVStream* src, bool per_rank,
const void* kv0, const void* kvr);
/* The identity of a step view, for a recorded pass's key (Ctx::pass_key): the memory a kernel reads,
* not the address of the struct that carries it. The batch's view is a copy in one of the builder's
* Out slots (batch.h kOut, 68 of them with speculation at its maximum), and the slot advances every
* step, so keying on `&view` made every streamed decode step a pass the tape store had never seen:
* it recorded a new tape each step, the least-recently-used 24 tapes dropped it long before its slot
* came round again, and so no streamed pass ever played: the host walked the whole issue path every
* step instead of replaying eight packets. The pointers below are fixed at bring-up
* (kvstream_step_view copies them), so this is stable across steps and still separates two groups
* that hand a kernel different memory. */
uint64_t kvstream_view_key(const RadKVStream* v);
} /* namespace rad */
+219
View File
@@ -0,0 +1,219 @@
/* bringup.cpp -- see bringup.h. */
#include "kvstream/bringup.h"
#include "device/device.h"
#include "engine_hostmem.h"
#include "kvstream/plan.h"
#include <algorithm>
#include <cstring>
namespace rad {
/* Every op whose only job is the host mirror or the ring. `kv_store` is not here -- a group that
* does not stream uses it -- and neither is the fused `qk_norm_rope_gate_kv_store`, whose streamed
* form (below) is a second variant of a fold that already exists without it. */
static const char* const kStreamOnlyOps[] = {
"kv_store_streamed",
"qk_norm_rope_gate_kv_store_streamed",
"kv_resolve",
};
bool kvstream_op_gated(const RadBuildCtx& ctx, const char* op) {
if (!op) return false;
if (ctx.kv_stream_ok != 0 && ctx.kv_resident_blocks > 0) return false; /* a ring is carved */
for (const char* s : kStreamOnlyOps)
if (std::strcmp(s, op) == 0) return true;
return false;
}
int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroupInfo>& groups,
const Program& prog, KVStreamSetup* out) {
*out = KVStreamSetup{};
/* --kv-resident is the whole switch: absent or 0 and nothing streams, which is the base
* engine's configuration and costs nothing. */
if (cfg.kv_resident <= 0) return RAD_OK;
/* One group could stream: the paged full-attention group with the largest page. On Flash-Next
* that is `kv_attn`; the indexer's `kv_qsa_bkey` is a full group too but a fraction of the
* width and `qsa_score` reads it densely over the whole history every step, so it must stay
* resident (docs/KV-STREAMING.md §2). The writer maintains the host mirror
* (`kv_store_streamed`), so a miss copies a block the engine wrote. A model whose paged groups
* are all windowed has nothing a ring could hold back, so a ring on it is not an error: the
* flag simply changes nothing. */
int32_t g = kv_stream_group(groups, &prog);
/* No group has a streamed path, so nothing will stream -- but a ring that would have streamed
* still has to name the op the architecture is missing, and the message is written against a
* group. Fall back to the old width rule for the report only; kvstream_ops below
* then refuses the path exactly as before. */
if (g < 0) g = kv_stream_group(groups);
if (g < 0) return RAD_OK;
const KVGroupInfo& gi = groups[(size_t)g];
const int64_t bs = gi.block_size > 0 ? gi.block_size : 1;
/* The ring's depth against the group's id space, without deciding anything yet: a ring that
* covers the context is not a refusal -- the group stays a plain resident pool, decided here
* from --max-num-seqs and --max-model-len, both known long before the first token. */
const KVStreamRing shape = kvstream_ring_shape(cfg, ctx, bs);
out->asked_tokens = cfg.kv_resident;
out->context_tokens = ctx * cfg.max_seqs;
out->group_name = gi.name;
out->ring_blocks = shape.ring_blocks;
out->ring_tokens = shape.ring_blocks * bs;
out->block_size = bs;
out->ctx_blocks = shape.ctx_blocks;
if (!shape.streams()) return RAD_OK;
/* Fail safe before anything is allocated: the group the plan wants to stream must have the
* ops its streamed path needs, declared by the plugin that emitted this program. Without
* kv_resolve a streamed group's `sel` still holds block ids while the attention reads them as
* ring slots -- past a ring smaller than the id space, which is a fault or silent corruption,
* not a slow path; without kv_store_streamed nothing writes the host mirror, so a miss reads
* zeros. Two paths declare both today -- the gated-fp8 attention (arch/common/
* rad_block_attn_gated_fp8.h) and GLM-5.3's MLA block (arch/common/rad_block_glm_mla.h),
* which resolves at finish after its indexer selects. Ignored with one line, then exactly the
* configuration without the flag: no cap, no mirror, no maps, no stage, a null RadKVStream. */
const KVStreamOps ops = kvstream_ops(prog, &gi);
if (!ops.streams()) {
/* Two causes, two sentences. The architecture can declare no streamed path at all (the
* gated path emits a plain kv_store and no resolve), or it can declare one the kernel
* table has no row for: a packed cache is declared to the core as plain E4M3, so the dtype
* gate below cannot see it, and the streamed store's rows are E4M3 and bf16 only. The
* second case must not say "the architecture declares no store" -- it did -- and the
* operator's answer is the cache layout, not the model. */
if ((cfg.kv_cache_dtype == "fp8_v4" || cfg.kv_cache_dtype == "k6_v4") && ops.resolve &&
!ops.store && !ops.folded)
RAD_WARN("--kv-resident %lld ignored: group '%s' has a %s cache, and the streamed store "
"has no writer for that layout (E4M3 and bf16 only), so nothing streams. "
"Serving exactly as without --kv-resident: every block of the group stays on "
"the card, with no host mirror, no residency map and no stage view",
(long long)cfg.kv_resident, gi.name.c_str(), cfg.kv_cache_dtype.c_str());
else
RAD_WARN("--kv-resident %lld ignored: architecture '%s' declares no %s for group '%s', so "
"this model has no streamed path and nothing streams. Serving exactly as without "
"--kv-resident: every block of the group stays on the card, with no host mirror, "
"no residency map and no stage view",
(long long)cfg.kv_resident,
prog.meta.arch_id && *prog.meta.arch_id ? prog.meta.arch_id : "(unnamed)",
ops.missing(), gi.name.c_str());
*out = KVStreamSetup{};
return RAD_OK;
}
/* The streamed store writes the mirror with the cache's own conversion: E4M3 for the fp8 QSA
* family, bf16 for the default cache dtype (kv_store_streamed_bf16). Streaming is
* dtype-agnostic beyond the two writers -- the mirror and the ring are byte planes of one
* paged layout whose pitch is `block_bytes` -- so a bf16 group streams. A packed fp8_v4/k6_v4
* group is declared to the core as plain E4M3 and its architecture emits no streamed store for
* the layout, so it is warned about and ignored above, never refused here. This gate is the
* last line for a group whose core dtype is neither of the two -- f32 or f16, which no
* architecture ships a full group in today. Checked only where something streams, so a
* configuration that fits is never refused for it. */
if (gi.decl.dtype != RAD_F8E4M3 && gi.decl.dtype != RAD_BF16) {
RAD_ERR("--kv-resident %lld: group '%s' has a %s cache, and the streamed store has E4M3 "
"and bf16 rows only (--kv-cache-dtype fp8 or bf16); a packed cache is a later "
"unit's row. Leave --kv-resident off to keep every block on the card",
(long long)cfg.kv_resident, out->group_name.c_str(),
rad_dtype_name(gi.decl.dtype));
return RAD_E_INVAL;
}
/* The ring's depth: a ring below what one decode step can select is raised to it, with the one
* line that says what was asked, what it became and why. */
KVStreamRing ring;
kvstream_ring(cfg, ctx, bs, ops.sel_pitch, &ring);
if (ring.raised_blocks > 0)
/* Anything under the computed amount is ignored and pulled up to it, the way Strata sizes
* this: the engine knows what a decode step names, and --kv-resident is a request for
* streaming rather than for one number. A warning, so startup proceeds -- and a different
* sentence from the ignored-flag one above, because this model does stream. */
RAD_WARN("--kv-resident %lld raised to %lld tokens: a decode step can name %lld blocks of "
"%lld blocks each (--max-num-seqs %lld x %lld for speculation x %lld), and the ring "
"must hold them all; the ring takes the raised depth and startup proceeds",
(long long)out->asked_tokens, (long long)(ring.ring_blocks * bs),
(long long)ring.raised_blocks, (long long)bs,
(long long)(cfg.max_seqs > 0 ? cfg.max_seqs : 1),
(long long)(1 + (cfg.n_spec > 0 ? cfg.n_spec : 0)), (long long)ops.sel_pitch);
/* The raised ring may be the whole context, which is not a streamed group at all: it keeps
* every block on the card and the report says which context the ring covers. */
out->ring_blocks = ring.ring_blocks;
out->ring_tokens = ring.ring_blocks * bs;
out->raised_tokens = ring.raised_blocks > 0 ? ring.ring_blocks * bs : 0;
out->group = ring.streams() ? g : -1;
/* Prefill runs on the stage and never resolves: above `qsa_exact_to` one launch's selection is
* a chunk's union, which no serving ring could hold, so the pass gets the group's context one
* layer deep, addressed by block id. A within-(1+n_spec) decode pass takes the ring and
* resolves; a decode-classified pass with more rows a sequence than that (the serial drafter's
* history pass over a chunk) is prefill-shaped and stages, because its union is the histories it
* spans. */
out->stage_blocks = ring.streams() ? ring.ctx_blocks : 0;
return RAD_OK;
}
void kvstream_host_add(KVStreamHostUse* use, const KVManager& kv) {
const KVStreamCost c = kv.stream_cost();
use->sum.groups += c.groups;
use->sum.host_bytes += c.host_bytes;
use->sum.map_bytes += c.map_bytes;
use->max_rank_bytes = std::max(use->max_rank_bytes, c.host_bytes);
}
int kvstream_host_gate(const KVStreamHostUse& use, int n_ranks, int64_t still, int64_t headroom) {
if (use.sum.host_bytes <= 0) return RAD_OK;
std::string why;
if (lockable_room(use.sum.host_bytes, still, headroom, false, &why)) return RAD_OK;
RAD_ERR("kv streaming: the host mirror for %lld streamed KV group(s) is up to %s a rank "
"(%s over %d ranks) of pinned host memory, and %s. It is sized by "
"--max-model-len and --max-num-seqs (one full context a sequence), not by "
"--kv-resident, which sizes the card's ring. Lower one of the first two, or "
"--kv-resident 0 to keep every block on the card. --host-pool-mib is the "
"experts' tier and holding less of it does not make room for this one.",
(long long)use.sum.groups, humanb(use.max_rank_bytes).c_str(),
humanb(use.sum.host_bytes).c_str(), n_ranks, why.c_str());
return RAD_E_NOMEM;
}
int kvstream_fill(KVManager& kv) {
/* After the carve, which is where an elastic pool backs its range: a fill before that
* would touch pages the card has not been given. One bring-up stream, drained before
* the first pass, since the maps are read from the first step on. */
RadStream st = nullptr;
int rc = rad_stream_create(&st, 0);
if (rc == RAD_OK) rc = kv.init_stream(st);
if (rc == RAD_OK) rc = rad_stream_sync(st);
rad_stream_destroy(st);
return rc;
}
void kvstream_report(const KVStreamSetup& s, const KVStreamHostUse& host, int n_ranks) {
/* The flag is not the ring when the ceiling raised it, and this report is what people read
* afterwards: the flag's number, the ring's, and why, before anything below quotes the ring. */
const int64_t flag = s.raised_tokens > 0 ? s.raised_tokens : s.asked_tokens;
if (s.raised_tokens > 0 && s.block_size > 0)
RAD_INFO("kv streaming: the ring is the raised one, not the flag's: --kv-resident %lld "
"became %lld tokens (%lld -> %lld blocks of %lld tokens each), the fewest blocks "
"one decode step's selection fits in; what was carved below is that ring",
(long long)s.asked_tokens, (long long)s.raised_tokens,
(long long)((s.asked_tokens + s.block_size - 1) / s.block_size),
(long long)(s.raised_tokens / s.block_size), (long long)s.block_size);
if (host.sum.groups > 0)
RAD_INFO("kv streaming: %lld group(s) stream (%s): kv_store_streamed writes the host "
"mirror and the resident ring slots, kv_resolve rewrites each selection as ring "
"slots, up to %s of pinned host mirror a rank (%s over %d), %s of ring maps in "
"the KV pools; the pool is one reservation of max(ring, stage), with the ring "
"sized by --kv-resident",
(long long)host.sum.groups, s.group_name.c_str(),
humanb(host.max_rank_bytes).c_str(), humanb(host.sum.host_bytes).c_str(), n_ranks,
humanb(host.sum.map_bytes).c_str());
if (s.stage_blocks > 0)
RAD_INFO("kv streaming: prefill staging, group '%s' ring %lld blocks, one-layer stage %lld "
"blocks (one layer of its %lld-block context): a prefill or mixed step, and a decode "
"pass with more rows a sequence than a decode step can have, stages each layer and "
"never resolves; only a within-(1+n_spec) decode pass uses the ring",
s.group_name.c_str(), (long long)s.ring_blocks,
(long long)s.stage_blocks, (long long)s.ctx_blocks);
if (s.group < 0 && s.asked_tokens > 0 && s.ctx_blocks > 0)
RAD_INFO("kv streaming: nothing streams: --kv-resident %lld covers group '%s''s "
"%lld-token context (%lld blocks), so every block keeps its own slot and the "
"group runs the engine's ordinary resident path -- no host mirror, no residency "
"map, no stage and no resolve. Lower --kv-resident below %lld to stream it",
(long long)flag, s.group_name.c_str(), (long long)s.context_tokens,
(long long)s.ctx_blocks, (long long)s.context_tokens);
}
} /* namespace rad */
+107
View File
@@ -0,0 +1,107 @@
/* bringup.h -- the engine-side bring-up of a streamed group (docs/KV-STREAMING.md §4.1, §5 Phase 4).
*
* `--kv-resident N` is the whole switch: absent or 0 and nothing streams, and a ring that covers
* the group's context streams nothing either, because such a group keeps the base engine's path
* with no overhead at all. Which group streams, the two refusals (a model with no full group, a
* cache with no streamed store row), the ring's ceiling, the cap that narrows every rank's pool,
* the host-RAM gate for the mirrors and the startup report all live here, so
* core/engine_bringup.cpp keeps one call at each seam. Nothing touches a device except fill(),
* which creates and drains the bring-up stream of the maps the carve has just placed.
*/
#pragma once
#include "mem/kv.h"
#include <string>
#include <vector>
namespace rad {
struct Config;
/* The plan --kv-resident resolves to, as Engine::configure_kv carries it to the report. `group` is
* -1 when nothing streams, which is every server without the flag and also a server whose ring
* covers the group's context; the other fields then describe what was asked for and why nothing
* streams, which is all the report needs. */
struct KVStreamSetup {
int32_t group = -1; /* the group that streams; -1 when nothing does */
std::string group_name; /* the group that would have: named by the report */
int64_t asked_tokens = 0; /* --kv-resident as given; 0 is no streaming at all */
int64_t raised_tokens = 0; /* what the flag became when the ring's ceiling raised
* it; 0 when it was not raised */
int64_t context_tokens = 0; /* --max-model-len x --max-num-seqs */
int64_t ring_tokens = 0; /* the ring that is carved, in tokens: the raised flag,
* rounded to whole blocks */
int64_t ring_blocks = 0; /* the ring's depth, in blocks */
int64_t block_size = 0; /* the group's page, in tokens: the ring's block */
int64_t ctx_blocks = 0; /* the group's id space, in blocks */
int64_t stage_blocks = 0; /* the stage view's depth, in blocks; 0 when there is none */
};
/* The host tier the mirrors take, summed over the ranks. `host_bytes` is every rank's pinned
* mirror; `max_rank_bytes` is the largest, which is the figure an operator acts on (an uneven
* tensor-parallel split gives the ranks different shard sizes). */
struct KVStreamHostUse {
KVStreamCost sum;
int64_t max_rank_bytes = 0;
};
/* Whether `op` must not be declared at all (it is not an error: the architecture takes its
* non-streaming path). The ops in kStreamOnlyOps (bringup.cpp) exist only to
* move KV between host memory and a ring, so a run that carves no ring must not have them: their
* declaration alone changes the graph, the arena and which kernels the planner may choose, and an
* operator who never asks for streaming must get exactly the build they had before it existed.
* True only when the architecture says it streams (RadArchProbe::kv_stream_ok, carried in
* RadBuildCtx::kv_stream_ok) AND --kv-resident asked for a ring. One binary serves both runs, so
* this is where the two questions meet; every architecture's `rad_op_declared` falls through to
* its non-streaming path by itself, and no model file carries the flag. */
bool kvstream_op_gated(const RadBuildCtx& ctx, const char* op);
/* Read --kv-resident, choose the group from rank 0's declarations, decide whether the ring covers
* its context (nothing streams then), refuse a cache with no streamed store row, apply the ring's
* ceiling (kvstream_ring, with `sel_pitch` read off the declared kv_resolve) and fill `out`.
* RAD_OK with group -1 when nothing streams, which is the ordinary configuration and caps nothing.
*
* The ceiling raises the ring when the flag asks for a ring smaller than one decode step's
* selection, and says so in one line: a warning, not a refusal, because the ring is a size the
* engine computes and the operator asked for streaming. `out->asked_tokens` and
* `out->raised_tokens` keep what the operator typed and what the ring became, for the report;
* `--kv-resident` itself is left as given, so nothing else re-reads a number the operator did not
* write.
*
* Fail-safe: when the architecture declares no streamed ops for the group the plan would stream
* (kvstream_ops -- no kv_resolve, or no streamed store), the flag is ignored with one warning that
* names the architecture and the missing op, and `out` is left exactly as if --kv-resident had not
* been given: group -1, so no ring is capped, no mirror or residency map is taken, no stage view is
* laid and the batch hands the arch no RadKVStream. That is not the raised ring above: an
* architecture without a streamed path cannot be fixed by the operator, while a ring under the
* ceiling is fixed here. A cache layout the streamed store has no writer for (--kv-cache-dtype
* fp8_v4 / k6_v4, whose architecture declares no streamed store for it) takes the same
* warn-and-ignore, with a sentence that names the layout rather than the architecture. Where the
* ops are there, the E4M3/bf16 gate still applies: the streamed store has rows for those two only,
* so a full group in any other core dtype would have no writer at all. */
int kvstream_configure(const Config& cfg, int64_t ctx, const std::vector<KVGroupInfo>& groups,
const Program& prog, KVStreamSetup* out);
/* Accumulate one rank's stream_cost() into the host tier's total. */
void kvstream_host_add(KVStreamHostUse* use, const KVManager& kv);
/* The host-RAM gate for the mirrors: a streamed group's mirror is `max_seqs x max_ctx` of its KV
* per rank -- on Flash-Next at 262144 tokens and 2 sequences that is 3.3 GiB a rank, the largest
* host allocation in the engine after the experts' pool. Checked once, before any rank takes it,
* against everything still to be pinned after it (`still`: the prefix cache's host tier, the
* activation arenas, the checkpoint store when its size is already fixed). The card side is the
* ring, which carve() sizes from --kv-resident; a refusal names this tier and the flag that started
* streaming, because telling an operator to lower --host-pool-mib would be about the wrong pool:
* that one holds experts, and shrinking it cannot make room here. */
int kvstream_host_gate(const KVStreamHostUse& use, int n_ranks, int64_t still, int64_t headroom);
/* After the carve: fill the maps on a bring-up stream and drain it. */
int kvstream_fill(KVManager& kv);
/* The startup lines: the raised ring when the ceiling moved it (the flag is no longer what was
* carved, and the report is what people read afterwards), which group streams and what it took on
* both tiers, the stage, and -- when the flag was given but nothing streams -- which group's
* context the ring covers. */
void kvstream_report(const KVStreamSetup& s, const KVStreamHostUse& host, int n_ranks);
} /* namespace rad */
+180
View File
@@ -0,0 +1,180 @@
/* carve.cpp -- see carve.h. */
#include "kvstream/carve.h"
#include "kvstream/mirror.h"
#include "kvstream/plan.h"
#include "mem/kv.h"
namespace rad {
int64_t kvstream_maps_charged(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs) {
/* One loop for the budget's term and the report's size: KVStreamStore::cost() is the predicate
* alloc() uses and the arithmetic kvstream_map_bytes states, so the two cannot drift. */
return st.cost(plans, max_ctx, max_seqs).map_bytes;
}
bool kvstream_dense(const KVGroupPlan& p, const std::vector<KVGroupPlan>& plans,
const KVStreamStore& st) {
if (!p.paged() || p.zero || p.kind != RAD_KV_FULL || !p.dense_read) return false;
for (const auto& q : plans)
if (!q.zero && q.paged() && st.windowed(q.index)) return true;
return false;
}
int64_t kvstream_dense_blocks(const KVGroupPlan& p, int64_t max_ctx, int64_t max_seqs) {
if (p.block_size <= 0 || max_ctx <= 0) return 0;
const int64_t seqs = max_seqs > 0 ? max_seqs : 1;
return seqs * ((max_ctx + p.block_size - 1) / p.block_size);
}
int64_t kvstream_dense_charged(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs) {
int64_t bytes = 0;
for (const auto& p : plans) {
if (!kvstream_dense(p, plans, st)) continue;
bytes += align_up(kvstream_dense_blocks(p, max_ctx, max_seqs) * p.bytes_per_block,
RAD_ALIGN_UNIT);
}
return bytes;
}
void kvstream_split_windows(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs, int64_t* remaining,
std::vector<int64_t>* out) {
for (const auto& p : plans) {
if (!p.paged() || p.zero || !st.windowed(p.index)) continue;
const int64_t slots = st.resident_blocks(p);
*remaining -= kv_pool_bytes(p, slots, st.context_blocks(p, max_ctx, max_seqs));
(*out)[p.index] = slots;
}
/* The maps are the rest of the arrangement. A probe that sizes the pool must pay them even
* though it cannot reserve them yet, or the pool it chooses is short by exactly their bytes and
* the first resident group carved against it falls short of --max-model-len. */
*remaining -= kvstream_maps_charged(plans, st, max_ctx, max_seqs);
/* A dense-read group does not take a share of the split: its requirement is every sequence's
* context, which is a floor fixed by the run configuration. Charging it here (and leaving it
* out of the shared split in paged_split) is what keeps the sibling's host mirror from
* promising max_seqs sequences that the indexer cannot address. */
for (const auto& p : plans) {
if (!kvstream_dense(p, plans, st)) continue;
const int64_t blocks = kvstream_dense_blocks(p, max_ctx, max_seqs);
*remaining -= align_up(blocks * p.bytes_per_block, RAD_ALIGN_UNIT);
(*out)[p.index] = blocks;
}
}
int kvstream_window_fit(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t fixed, int64_t budget, int64_t max_ctx, int64_t max_seqs) {
int64_t window_bytes = 0;
int64_t window_groups = 0;
for (const auto& p : plans) {
if (!p.paged() || p.zero || !st.windowed(p.index)) continue;
/* A window group already bounds its own history: the ids it allocates are its window's,
* while a streamed group's ids are its whole context. The two cannot both be true, and
* context_blocks() would size the table of the first as if it were the second. */
if (p.kind != RAD_KV_FULL) {
RAD_ERR("KV group '%s' is a %s group and streaming is set for it: only a full "
"attention group streams. A window already bounds its own history, so the ids "
"it allocates are its window's, and a streamed group's ids are its whole "
"context -- the residency map cannot be right for both. Leave this group "
"unstreamed (--kv-resident 0 for it).",
p.name.c_str(), kv_kind_name(p.kind));
return RAD_E_INVAL;
}
window_bytes += kv_pool_bytes(p, st.resident_blocks(p),
st.context_blocks(p, max_ctx, max_seqs));
++window_groups;
}
const int64_t map_bytes = kvstream_maps_charged(plans, st, max_ctx, max_seqs);
const int64_t dense_bytes = kvstream_dense_charged(plans, st, max_ctx, max_seqs);
int64_t dense_groups = 0;
for (const auto& p : plans) if (kvstream_dense(p, plans, st)) ++dense_groups;
if (fixed + window_bytes + map_bytes + dense_bytes > budget) {
RAD_ERR("the resident KV windows and dense-read groups do not fit vram_kv:\n"
" resident windows %10s (%lld group(s) streaming)\n"
" ring maps %10s (the streamed groups' residency maps)\n"
" dense-read groups %10s (%lld group(s) at %lld sequences x %lld tokens)\n"
" linear/conv state %10s (%lld sequences)\n"
" vram_kv %10s\n"
" short by %10s\n"
"Lower --kv-resident (the ring), or --max-model-len / --max-num-seqs (the one-layer "
"stage and a dense-read group's floor are sized from them), or give the cache more "
"of the card: a smaller --gpu-headroom-mib or a larger --host-pool-mib. The fixed "
"costs in this table are not what is short: it is a streamed group's ring and "
"stage, or the indexer beside it that must hold every sequence's context.",
humanb(window_bytes).c_str(), (long long)window_groups,
humanb(map_bytes).c_str(), humanb(dense_bytes).c_str(), (long long)dense_groups,
(long long)max_seqs, (long long)max_ctx, humanb(fixed).c_str(),
(long long)max_seqs, humanb(budget).c_str(),
humanb(fixed + window_bytes + map_bytes + dense_bytes - budget).c_str());
return RAD_E_NOMEM;
}
return RAD_OK;
}
int kvstream_apply(std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs) {
for (auto& p : plans) {
if (!p.paged()) continue;
if (st.windowed(p.index) && !p.zero) {
/* A streamed group's ids run over its context, which lives in host memory; the pool
* backs only its resident window. So the split above gave this group its window (the
* one number the pool may spend), and the context comes from the run configuration.
* A window wider than the context is the context: there is nothing to stream. */
p.n_blocks = st.context_blocks(p, max_ctx, max_seqs);
p.n_slots = st.resident_blocks(p);
/* Only a ring smaller than the context needs the second, one-layer view. A ring that
* covers the context streams nothing and never reaches this cap (kvstream_ring), so a
* windowed group here always has the stage. */
p.depth = p.streamed() ? 1 : 0;
} else {
/* Not streamed: it addresses exactly the blocks it carves. */
p.n_slots = p.n_blocks;
}
if (p.n_slots > p.n_blocks) p.n_slots = p.n_blocks;
/* Streaming wins over replication for one group, and the resolution is not an error
* because the two claims are about different stores. rad_kv_group_replicated says a tier
* slot holds the group once; a streamed group has no tier entry at all (kv_tier_cached) --
* its host mirror is the tier -- so the flag would only misdescribe the slot. A plugin
* declares replication because the arithmetic of the group is the same on every rank (an
* MLA latent), which stays true while it streams. */
if (p.streamed()) p.replicated = false;
/* A streamed group needs somewhere for the blocks the pool does not back. Refused here,
* not at the first attention read: an unbacked id is written past the layer stride and the
* result is fluent wrong output with no way to bisect it (docs/KV-STREAMING.md §3.1).
* RAD_E_INVAL, not RAD_E_STATE: RAD_E_STATE stringifies as "called in the wrong phase",
* and this is a caller handing the manager a cap without the backing for it. */
if (p.streamed()) {
const KVStreamStore::Map* m = st.map(p.index);
const int64_t need = p.n_blocks * p.bytes_per_block;
if (!m || !m->host || !m->res || m->host_bytes < need) {
RAD_ERR("KV group '%s' streams -- %lld of its %lld blocks resident -- but nothing "
"holds the other blocks: a streamed group needs a host copy of %s and a "
"residency map before it is carved. This is a wiring bug, not a flag: "
"--kv-resident is set only where the engine also allocates both.",
p.name.c_str(), (long long)p.n_slots, (long long)p.n_blocks,
humanb(need).c_str());
return RAD_E_INVAL;
}
}
}
return RAD_OK;
}
std::string kvstream_report_line(const KVGroupPlan& p) {
/* A streamed group's pool is smaller than its context, so the two numbers differ and the
* group's own line would read as a pool that holds the whole context. Both tiers in one line:
* the ring and where it lives (the pool, at its offset), and the host mirror the misses are
* copied from. The maps are the group's own small device allocation, taken from the same pool,
* so they are named here too rather than being invisible. */
return fmt(" %-14s %-6s streaming: %7lld blocks resident in vram_kv at "
"+%lld = %9s, %7lld blocks = %9s mirrored in pinned host memory, "
"maps %s\n", "", "", (long long)p.pool_blocks(),
(long long)p.pool_offset, humanb(p.pool_bytes).c_str(),
(long long)p.n_blocks,
humanb(p.n_blocks * p.bytes_per_block).c_str(),
humanb(kvstream_map_bytes(p.n_blocks, p.pool_blocks(), p.n_layers)).c_str());
}
} /* namespace rad */
+76
View File
@@ -0,0 +1,76 @@
/* carve.h -- what a carve does with a streamed group (docs/KV-STREAMING.md §4.1, §4.2).
*
* carve() spends a pool against the plan, and three of its steps are streaming's: the resident
* windows leave the budget before the other groups split the rest; after the split each paged
* group's n_slots (and a streamed group's context and depth) is written, with a refusal if nothing
* holds the blocks the pool does not back; and the pool report gains the line naming both tiers.
* Those three live here, so mem/kv.cpp keeps one call at each seam. Pure arithmetic on the plan:
* nothing here touches a device.
*/
#pragma once
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
struct KVGroupPlan;
class KVStreamStore;
/* Bytes a streamed group's residency maps take from the KV pool: exactly what alloc() reserves,
* as KVStreamStore::cost() states it. They are part of the group's arrangement, not a side
* allocation: the maps are reserved before carve() (KVStreamStore::alloc), so the budget that
* sizes the pool must charge them. The budget probe has no pool and cannot reserve them, while
* the carve has already taken them; charging them in paged_split() and adding them back to the
* carve's budget is what makes both paths see the same bytes (docs/KV-STREAMING.md §3.9). */
int64_t kvstream_maps_charged(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs);
/* A dense-read group (rad_kv_group_dense_read: an indexer's block keys) is walked over its whole
* live history every decode step, so it cannot stream. While any group does stream, its pool must
* hold every sequence's context: the host mirror beside it is sized for max_seqs sequences, and an
* indexer funded for one would make the advertised capacity a promise the engine cannot keep. False
* when nothing streams -- that configuration deliberately sizes the cache for one full-length
* sequence, and charging the floor there would take the experts' VRAM for capacity nothing uses. */
bool kvstream_dense(const KVGroupPlan& p, const std::vector<KVGroupPlan>& plans,
const KVStreamStore& st);
/* Blocks a dense-read group must hold: max_seqs sequences, each ceil(max_ctx / block_size)
* blocks long. 0 for a group kvstream_dense() does not select. */
int64_t kvstream_dense_blocks(const KVGroupPlan& p, int64_t max_ctx, int64_t max_seqs);
/* The bytes those blocks take from the pool, rounded as reserve() rounds them. */
int64_t kvstream_dense_charged(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs);
/* Take the streamed groups' resident windows, their maps and the dense-read groups' full contexts
* out of a paged split before the other groups compete for the pool: `remaining` loses their bytes
* and `out[group]` becomes the ring's depth (or the dense-read group's context) in blocks. A streamed group does not compete for the pool: its device share is its resident
* window, fixed by --kv-resident, and the blocks it addresses are its context, which lives in host
* memory. The caller leaves those groups out of the split and reports this as their carved blocks
* -- `carve_into` reads it as the pool's depth, while the group's context comes from the run
* configuration. */
void kvstream_split_windows(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs, int64_t* remaining,
std::vector<int64_t>* out);
/* Refuse a resident window that does not fit `budget`, before anything is split. A streamed group's
* window leaves the budget before the other groups split the rest, so a window that does not fit
* silently leaves them zero blocks and they are refused for a pool too small -- an operator told to
* raise --host-pool-mib when the term that is too large is --kv-resident, and who then tunes the
* wrong one. Refuse the window itself instead. The fixed costs are their own term and were checked
* by the caller. A window group is refused by name here too: it already bounds its own history. */
int kvstream_window_fit(const std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t fixed, int64_t budget, int64_t max_ctx, int64_t max_seqs);
/* After the split: write every paged group's n_slots, which is its carve unless it streams, and for
* a streamed group its n_blocks as the context and its depth. Refuse a streamed group whose host
* copy or residency map is missing: an unbacked id is written past the layer stride. */
int kvstream_apply(std::vector<KVGroupPlan>& plans, const KVStreamStore& st,
int64_t max_ctx, int64_t max_seqs);
/* The report continuation for a streamed group: its pool is smaller than its context, so the
* group's own line would read as a pool that holds the whole context. Both tiers in one line. */
std::string kvstream_report_line(const KVGroupPlan& p);
} /* namespace rad */
+218
View File
@@ -0,0 +1,218 @@
/* mirror.cpp -- see mirror.h. */
#include "kvstream/mirror.h"
#include <sys/mman.h>
#include "kvstream/plan.h"
#include <algorithm>
#include <cstdlib>
#include <cstring>
namespace rad {
namespace {
int64_t ceil_div(int64_t a, int64_t b) { return b > 0 ? (a + b - 1) / b : 0; }
/* Each array starts on an 8-byte boundary: the ABI's `ctl` counters are read as u64 pairs, and a
* block count or a ring depth that is odd would leave a 4-byte boundary misaligned. The pool's base
* is RAD_ALIGN_UNIT (4096) aligned, so rounding every part keeps the absolute addresses aligned. */
int64_t align8(int64_t n) { return (n + 7) & ~(int64_t)7; }
/* The reservation's one layout: the bytes of each array and its offset from the reservation's
* base. alloc() cuts the reservation from it, init() resets each part at its own length, and
* kvstream_map_bytes() is its total, so the budget, the carve and the reset cannot disagree. */
struct MapLayout {
int64_t res_bytes = 0, slot_block_bytes = 0, slot_state_bytes = 0, ctl_bytes = 0;
int64_t res = 0, slot_block = 0, slot_state = 0, ctl = 0;
int64_t bytes = 0; /* the whole reservation */
};
MapLayout map_layout(int64_t blocks, int64_t slots, int64_t layers) {
if (layers < 1) layers = 1;
MapLayout l;
l.res_bytes = layers * blocks * (int64_t)sizeof(int32_t);
l.slot_block_bytes = layers * slots * (int64_t)sizeof(int32_t);
l.slot_state_bytes = layers * slots * 2 * (int64_t)sizeof(int32_t);
l.ctl_bytes = 16 * (int64_t)sizeof(int32_t);
l.res = 0; /* res, block -> slot, one map a layer */
l.slot_block = l.res + align8(l.res_bytes); /* slot_block, slot -> block */
l.slot_state = l.slot_block + align8(l.slot_block_bytes);/* slot_state: epoch, heat */
l.ctl = l.slot_state + align8(l.slot_state_bytes);/* ctl, shared by the layers */
l.bytes = l.ctl + align8(l.ctl_bytes);
return l;
}
} /* namespace */
int64_t kvstream_map_bytes(int64_t blocks, int64_t slots, int64_t layers) {
return map_layout(blocks, slots, layers).bytes;
}
void KVStreamStore::cap(int32_t group, int64_t tokens) {
if (group < 0) return;
if ((size_t)group >= resident_tokens_.size()) resident_tokens_.resize((size_t)group + 1, 0);
resident_tokens_[(size_t)group] = tokens > 0 ? tokens : 0;
}
bool KVStreamStore::windowed(int32_t group) const {
return group >= 0 && (size_t)group < resident_tokens_.size() &&
resident_tokens_[(size_t)group] > 0;
}
int64_t KVStreamStore::resident_blocks(const KVGroupPlan& p) const {
const size_t g = (size_t)p.index;
if (g >= resident_tokens_.size() || resident_tokens_[g] <= 0 || p.block_size <= 0) return 0;
return ceil_div(resident_tokens_[g], p.block_size);
}
int64_t KVStreamStore::context_blocks(const KVGroupPlan& p, int64_t max_ctx,
int64_t max_seqs) const {
/* One spelling of the id space (kvstream/plan.h): the startup ring decision uses the same
* arithmetic, so a ring that covers ctx_blocks covers what the store sizes. */
return kv_context_blocks(p.block_size, max_ctx, max_seqs);
}
void KVStreamStore::set_map(int32_t group, const Map& m) {
if (group < 0) return;
if ((size_t)group >= maps_.size()) maps_.resize((size_t)group + 1);
maps_[(size_t)group] = m;
}
const KVStreamStore::Map* KVStreamStore::map(int32_t group) const {
if (group < 0 || (size_t)group >= maps_.size()) return nullptr;
return &maps_[(size_t)group];
}
const RadKVStream* KVStreamStore::view(const KVGroupPlan* p, int32_t group) const {
/* A group whose pool backs only a window of its context, and nothing else: a ring that covers
* the context never reaches here (kvstream_ring leaves `group` at -1 and nothing is capped), so
* such a group is not a streamed one and gets the base engine's null -- no resolve, no stage,
* no mirror read (docs/KV-STREAMING.md §5 Phase 4). */
if (!p || !p->streamed() || !windowed(group)) return nullptr;
const Map* m = map(group);
return m && m->host && m->res ? m : nullptr;
}
KVStreamCost KVStreamStore::cost(const std::vector<KVGroupPlan>& plans, int64_t max_ctx,
int64_t max_seqs) const {
KVStreamCost c;
for (const auto& p : plans) {
if (!windowed(p.index) || p.zero || p.kind != RAD_KV_FULL) continue;
const int64_t blocks = context_blocks(p, max_ctx, max_seqs);
const int64_t slots = std::min(resident_blocks(p), blocks);
if (blocks <= 0 || slots <= 0) continue;
c.host_bytes += blocks * p.bytes_per_block;
c.map_bytes += kvstream_map_bytes(blocks, slots, p.n_layers);
++c.groups;
}
return c;
}
int KVStreamStore::alloc(const std::vector<KVGroupPlan>& plans, int64_t max_ctx, int64_t max_seqs,
MemAllocator& host_alloc, Pool& kv_pool) {
for (const auto& p : plans) {
if (!windowed(p.index) || p.zero || p.kind != RAD_KV_FULL) continue;
const int64_t blocks = context_blocks(p, max_ctx, max_seqs);
const int64_t slots = std::min(resident_blocks(p), blocks);
if (blocks <= 0 || slots <= 0) continue;
Map m;
m.slots = slots;
m.block_bytes = p.layer_bytes_per_block();
m.host_layer_stride = blocks * m.block_bytes;
m.host_bytes = blocks * p.bytes_per_block;
m.host = static_cast<uint8_t*>(host_alloc.alloc(m.host_bytes, RAD_MEM_HOST_MAPPED));
if (!m.host) {
RAD_ERR("KV group '%s': the host mirror of %s (%lld blocks of %s) could not be "
"allocated", p.name.c_str(), humanb(m.host_bytes).c_str(), (long long)blocks,
humanb(p.bytes_per_block).c_str());
release(host_alloc);
return RAD_E_NOMEM;
}
/* 2 MiB pages for this mirror are already what the pinned allocator asks for
* (device/aql.cpp, pin_pieces), before the pin faults the range in; the switch that turns
* them off for the measurement is RADIANCE_NO_HUGE_PAGES there. Nothing to do here. */
/* A block the prefix cache has not written yet is read as a miss and copied to the ring
* before attention sees it, so the bytes must be defined: an uninitialised block would be
* fluent wrong output with nothing to point at. */
std::memset(m.host, 0, (size_t)m.host_bytes);
/* One reservation for the group: the resolve's arrays are a few hundred KiB and separate
* reserves would each round up to the pool's alignment. They come out of the KV pool, so
* the paged split below sees them and the pool's report names them. */
const int64_t layers = p.n_layers > 0 ? p.n_layers : 1;
const MapLayout lay = map_layout(blocks, slots, layers);
const int64_t map_bytes = lay.bytes;
std::string what = "kv_stream_maps:" + p.name;
char* at = static_cast<char*>(kv_pool.reserve(what, map_bytes, RAD_ALIGN_UNIT, nullptr));
if (!at) {
RAD_ERR("KV group '%s': its residency map and ring bookkeeping (%s) did not fit the "
"KV pool", p.name.c_str(), humanb(map_bytes).c_str());
host_alloc.free(m.host, RAD_MEM_HOST_MAPPED);
release(host_alloc);
return RAD_E_NOMEM;
}
/* The residency map is one slice a layer: a block's ring bytes are per layer, and the
* resolve copies one layer's block, so a group-wide map would call a block resident for a
* layer whose bytes were never copied (the first decode after a staged prefill). The
* control block stays shared: its counters and overflow latch are the group's. */
m.res = reinterpret_cast<int32_t*>(at + lay.res);
m.slot_block = reinterpret_cast<int32_t*>(at + lay.slot_block);
m.slot_state = reinterpret_cast<int32_t*>(at + lay.slot_state);
m.ctl = reinterpret_cast<int32_t*>(at + lay.ctl);
set_map(p.index, m);
}
return RAD_OK;
}
int KVStreamStore::init(const std::vector<KVGroupPlan>& plans, RadStream s) {
if (!s) {
RAD_ERR("KV streaming: the maps must be filled on a stream this engine owns; a null one "
"is not usable");
return RAD_E_INVAL;
}
for (const auto& p : plans) {
const Map* m = map(p.index);
if (!m || !m->host || !m->res) continue;
/* The reset a resolve launch expects (libref/ref_kvstream.cpp's contract): both maps at
* -1, the per-slot state and the control block at zero. There is no reset op because a
* residency map lives as long as the pool. */
const MapLayout lay = map_layout((int64_t)p.n_blocks, m->slots,
p.n_layers > 0 ? p.n_layers : 1);
int rc = RAD_OK;
/* Every layer has its own map slice (see alloc): a block's bytes are copied per layer, so
* residency is per layer too. A streamed group is by definition one whose pool is narrower
* than its context, so every block starts absent and the first read of it is a miss. */
rc = rad_memset_async(m->res, 0xff, lay.res_bytes, s);
if (rc == RAD_OK) rc = rad_memset_async(m->slot_block, 0xff, lay.slot_block_bytes, s);
if (rc == RAD_OK) rc = rad_memset_async(m->slot_state, 0, lay.slot_state_bytes, s);
if (rc == RAD_OK) rc = rad_memset_async(m->ctl, 0, lay.ctl_bytes, s);
if (rc != RAD_OK) {
RAD_ERR("KV group '%s': the residency map could not be initialised: %s",
p.name.c_str(), rad_dev_last_error());
return rc;
}
}
return RAD_OK;
}
void KVStreamStore::release(MemAllocator& host_alloc) {
for (auto& m : maps_) {
if (!m.host) continue;
host_alloc.free(m.host, RAD_MEM_HOST_MAPPED);
/* The device maps are carved from the KV pool and go with it. Clearing the view as well
* makes a second call, or a teardown after a failed bring-up, a no-op. */
m = Map{};
}
}
KVStreamStats KVStreamStore::stats(const std::vector<KVGroupPlan>& plans) const {
KVStreamStats st;
st.misses = misses_;
st.bytes_in = bytes_in_;
for (const auto& p : plans)
if (p.streamed()) st.resident_blocks += p.pool_blocks();
return st;
}
} /* namespace rad */
+135
View File
@@ -0,0 +1,135 @@
/* mirror.h -- the host mirror tier and the resident window (docs/KV-STREAMING.md §4.1).
*
* A streamed group's device pool backs a resident window, not its context; the blocks the pool
* does not hold live in a pinned host copy, laid out layer-major and block-indexed exactly like the
* pool, and a device residency map says which blocks are in the pool (`-1` for the ones that are
* not). This file owns that pair, the cap that narrows a group's pool to a window, and the
* arithmetic that sizes both, so mem/kv.{h,cpp} keeps one KVStreamStore member and one call per
* method. Nothing here touches a device except init(), which fills the maps on the stream it is
* given.
*/
#pragma once
#include "mem/pools.h"
#include <cstdint>
#include <vector>
namespace rad {
struct KVGroupPlan;
/* What the streamed groups need, in bytes, before anything is taken. `host_bytes` is pinned
* host memory (`blocks * bytes_per_block` per group, every rank its own shard); `map_bytes` is
* the residency map, the ring's reverse map and the control block, all device memory and all
* taken from the KV pool itself (a handful of MiB), so they are budgeted with the cache they
* describe rather than as an uncharged side allocation.
*
* Valid after plan_groups() and before carve(); the arithmetic is the one carve() uses. */
struct KVStreamCost {
int64_t groups = 0;
int64_t host_bytes = 0;
int64_t map_bytes = 0;
};
/* The resolve's cumulative counters, as metrics read them. A server that does not stream
* reports zeros; `resident_blocks` is the ring's depth from the carve. */
struct KVStreamStats {
int64_t resident_blocks = 0;
uint64_t misses = 0; /* blocks placed in the ring by resolve launches */
uint64_t bytes_in = 0; /* bytes those placements copied from the host mirror */
};
/* The bytes a streamed group needs, before anything is taken: the mirror is the context the pool
* would have held, and the maps are the residency map (one entry a logical block), the ring's
* reverse map, its per-slot state and the control block. Only a full
* attention group streams -- carve() refuses a window one by name -- so that is what is counted
* here; counting a group the carve will refuse would take its mirror first and report a size the
* operator cannot act on. */
int64_t kvstream_map_bytes(int64_t blocks, int64_t slots, int64_t layers);
/* A streamed group's storage off the card: the pinned host copy and the device residency map.
*
* The host copy must cover the group's whole context: `n_blocks * bytes_per_block`, the size the
* pool would have had. Needed before carve() for any group cap() narrowed.
*
* The manager keeps one of these per streamed group and hands it to the run phase as the ABI's
* RadKVStream (view), so the fields the plugin reads and the fields alloc() fills are one
* definition: `host_bytes` and `slots`/`block_bytes` are the mirror's and the ring's sizes.
*
* The manager's whole streaming state is here, by group handle, so the policy is in this module and
* KVManager only delegates: the resident window cap, the mirror and maps, and the resolve's
* counters. Empty vectors and zeros on a manager that does not stream. */
class KVStreamStore {
public:
using Map = RadKVStream;
/* How much of a paged group's context its device pool backs, in tokens; 0 (the default) is all
* of it, which is every group on a server that does not stream. Only the group named, because
* a streamed group is usually one whose reads a step can bound -- the sparse attention group --
* while its neighbours (an indexer's block keys, read densely over the whole history every
* step) must stay where they are (docs/KV-STREAMING.md §4). Rounded up to a whole block and
* never above the group's own carve. */
void cap(int32_t group, int64_t tokens);
/* A group whose pool is a resident window rather than its context (cap): its block ids run
* over the context and only `n_slots` of them are in device memory. */
bool windowed(int32_t group) const;
/* Blocks of the group's resident window, rounded up to a whole block. A window shorter than one
* block is one block: a pool that holds nothing is not a streamed group, it is a group that
* cannot run. */
int64_t resident_blocks(const KVGroupPlan& p) const;
/* Blocks the group's context addresses: what the pool would hold if every sequence it may run
* reached --max-model-len at once, i.e. the paged part of ceiling(). The block table is already
* pitched for this (BatchBuilder sizes it from max_ctx), so the ids exist whether the pool backs
* them or not. */
int64_t context_blocks(const KVGroupPlan& p, int64_t max_ctx, int64_t max_seqs) const;
void set_map(int32_t group, const Map& m);
const Map* map(int32_t group) const;
/* The ABI view of a streamed group's ring and mirror, or null for one that is fully resident.
* Stable from bring-up: the batch builder copies the pointer into every step's batch, and a
* recorded pass keyed by it replays only while the addresses do not move. */
const RadKVStream* view(const KVGroupPlan* p, int32_t group) const;
KVStreamCost cost(const std::vector<KVGroupPlan>& plans, int64_t max_ctx, int64_t max_seqs) const;
/* Take the mirror and the ring's maps for every streamed group and set_map() each. Call after
* plan_groups() and before carve(): the carve refuses a streamed group with no map, and the
* maps' bytes leave the pool before its paged split. The mirror is zeroed here, because a
* block the prefix cache has not written yet is read as a miss and an uninitialised block
* would be fluent wrong output. The device maps are not touched (an elastic pool backs its
* range at carve), so init() fills them after it. On failure the mirror is released again;
* release() in the engine's teardown covers a partial bring-up. */
int alloc(const std::vector<KVGroupPlan>& plans, int64_t max_ctx, int64_t max_seqs,
MemAllocator& host_alloc, Pool& kv_pool);
/* Fill the device maps: `res` and `slot_block` with -1, `slot_state` and `ctl` with zero (the
* state a resolve launch expects at bring-up). Call after carve(), with the rank's stream
* current, and sync before the first pass. */
int init(const std::vector<KVGroupPlan>& plans, RadStream s);
/* Release what alloc() took. The device maps came from the KV pool and go with it; the host
* mirror is outside every pool and is freed here. Safe to call twice and after a failed
* bring-up: a group with no mirror is skipped. */
void release(MemAllocator& host_alloc);
KVStreamStats stats(const std::vector<KVGroupPlan>& plans) const;
/* Charged by whoever reads a resolve launch's ctl: the step path never waits on the card, so
* the kernel's cumulative numbers are read where the next unit drains them. */
void note_traffic(int64_t misses, int64_t bytes) {
if (misses > 0) misses_ += (uint64_t)misses;
if (bytes > 0) bytes_in_ += (uint64_t)bytes;
}
private:
std::vector<int64_t> resident_tokens_; /* by group handle: its pool's depth in tokens */
std::vector<Map> maps_; /* set_map(), by group handle */
uint64_t misses_ = 0; /* note_traffic() */
uint64_t bytes_in_ = 0;
};
} /* namespace rad */
+209
View File
@@ -0,0 +1,209 @@
/* plan.cpp -- see plan.h. */
#include "kvstream/plan.h"
#include <algorithm>
namespace rad {
int64_t kv_pool_bytes(const KVGroupPlan& p, int64_t slots) {
return kv_pool_bytes(p, slots, p.n_blocks);
}
int64_t kv_pool_bytes(const KVGroupPlan& p, int64_t slots, int64_t context_blocks) {
if (!p.paged()) return p.n_states * p.bytes_per_state;
const int64_t ring = kv_ring_bytes(p, slots);
/* slots >= context_blocks is a ring that covers the context, which streams nothing: it is the
* group's ordinary one-view pool. A streamed group (slots < context_blocks) also needs its
* one-layer stage. The context is passed explicitly because paged_split runs before the carve
* writes p.n_blocks. */
if (slots <= 0 || slots >= context_blocks) return ring;
return std::max(ring, context_blocks * p.layer_bytes_per_block());
}
int64_t kv_pool_bytes(const KVGroupPlan& p) {
return kv_pool_bytes(p, p.pool_blocks());
}
int64_t kv_ceiling_bytes(const KVGroupPlan& p, int64_t blocks, int64_t slots) {
if (!p.paged() || p.block_size <= 0) return 0;
const int64_t ring = slots > 0 ? slots * p.bytes_per_block : 0;
if (slots <= 0 || slots >= blocks) return blocks * p.bytes_per_block;
/* The stage is context-deep and one layer wide. It and the ring are one reservation, so the
* budget pays the larger, not the sum. */
return std::max(ring, blocks * p.layer_bytes_per_block());
}
bool kv_tier_cached(const KVGroupPlan& p) {
return !p.streamed();
}
namespace {
/* The one rule both overloads state: among the groups from index 1 on, a candidate is a full group
* that owns bytes and is neither zero nor dense-read, whose declared ops stream it; the widest
* page wins. Each overload supplies only how its own container spells those fields. */
bool kv_stream_candidate(int32_t kind, bool zero, bool dense_read, int64_t bytes_per_block) {
return kind == RAD_KV_FULL && !zero && !dense_read && bytes_per_block > 0;
}
template <class Candidate>
int32_t kv_stream_widest(size_t n, const Candidate& candidate) {
int32_t best = -1;
int64_t widest = 0;
for (size_t g = 1; g < n; ++g) {
int64_t bytes = 0;
if (!candidate(g, &bytes)) continue;
if (bytes > widest) {
widest = bytes;
best = (int32_t)g;
}
}
return best;
}
} /* namespace */
int32_t kv_stream_group(const KVManager& kv, const Program* prog) {
const std::vector<KVGroupPlan>& ps = kv.plans();
return kv_stream_widest(ps.size(), [&](size_t g, int64_t* bytes) {
const KVGroupPlan& p = ps[g];
if (!kv_stream_candidate(p.kind, p.zero, p.dense_read, p.bytes_per_block)) return false;
/* Only a group the program wires: a kv_resolve stating this group's per-layer pitch and a
* streamed store stating its page. Every caller has the program (the builder's resolved
* op list), so there is no width-only fallback here. */
const KVGroupInfo* gi = g < prog->kv_groups.size() ? &prog->kv_groups[g] : nullptr;
if (!kvstream_ops(*prog, gi).streams()) return false;
*bytes = p.bytes_per_block;
return true;
});
}
int32_t kv_stream_group(const std::vector<KVGroupInfo>& gs, const Program* prog) {
return kv_stream_widest(gs.size(), [&](size_t g, int64_t* bytes) {
const KVGroupInfo& gi = gs[g];
if (!kv_stream_candidate(gi.decl.kind, gi.zero, gi.dense_read, gi.bytes_per_block))
return false;
/* The declarations exist before the plans do; a caller with no program (the width-only
* report fallback) keeps the width rule. */
if (prog && !kvstream_ops(*prog, &gi).streams()) return false;
*bytes = gi.bytes_per_block;
return true;
});
}
int64_t kvstream_ceiling_blocks(const Config& cfg, int64_t sel_pitch) {
if (sel_pitch <= 0 || cfg.max_seqs <= 0) return 0;
/* One selection per row: a sequence drafts n_spec tokens and a verify step runs them beside
* the accepted position, so under speculation a step is (1 + n_spec) rows a sequence. */
const int64_t rows = cfg.max_seqs * (1 + (cfg.n_spec > 0 ? cfg.n_spec : 0));
return rows * sel_pitch;
}
KVStreamOps kvstream_ops(const Program& prog, const KVGroupInfo* group) {
KVStreamOps ops;
/* Whether this declaration has a kernel at all. `bands` being empty does NOT mean it has none:
* the builder always leaves at least one band, and for an op no row matched it is a placeholder
* with both domains null and a miss reason (core/build/rad_builder.cpp, resolve_bands). The same
* predicate as Builder::op_resolved, read off the program a non-builder caller holds. */
const auto resolved = [](const OpInfo& o) {
for (const Band& b : o.bands)
for (int d = 0; d < RAD_N_DOMAINS; ++d)
if (b.dom[d]) return true;
return false;
};
/* The group's per-layer block pitch, the figure kv_resolve states as `block_bytes`
* (rad_kv_layer_bytes). bytes_per_block covers every bound layer. */
const int64_t n_bound = group && !group->layers.empty() ? (int64_t)group->layers.size() : 1;
const int64_t layer_bytes =
group && group->bytes_per_block > 0 ? group->bytes_per_block / n_bound : 0;
for (const OpInfo& op : prog.ops) {
/* A declaration that resolved to nothing is not a streamed path: the plugin's handle is
* null and nothing would be issued. A declared-but-unresolved store counts as no path,
* which is the packed-cache shape -- the architecture emits the op and the kernel table has
* no row for the layout -- and letting it count would stream a group whose store never
* runs, so the mirror would stay empty and a miss would copy zeros. */
if (!resolved(op)) continue;
const bool is_resolve = op.op == "kv_resolve";
const bool is_store = op.op == "kv_store_streamed" ||
op.op == "qk_norm_rope_gate_kv_store_streamed";
if (!is_resolve && !is_store) continue;
/* The declaration states the geometry it was emitted for; a resolve or a store declared
* for a narrower group must not enable streaming of this one. A declaration that states
* neither is taken at its word. */
long long stated = 0;
if (is_resolve && layer_bytes > 0 && op.base.get_i("block_bytes", &stated) &&
stated != layer_bytes)
continue;
if (is_store && group && group->block_size > 0 &&
op.base.get_i("block_size", &stated) && stated != group->block_size)
continue;
if (is_resolve) {
long long pitch = 0;
if (!op.base.get_i("sel_pitch", &pitch) || pitch <= 0) continue;
/* A resolve with no pitch cannot size the ring; the first one that states it wins, as
* every layer of the group declares the same. */
if (!ops.resolve) ops.sel_pitch = (int64_t)pitch;
ops.resolve = true;
} else if (op.op == "kv_store_streamed") {
ops.store = true;
} else {
ops.folded = true;
}
}
return ops;
}
KVStreamRing kvstream_ring_shape(const Config& cfg, int64_t ctx, int64_t block_size) {
KVStreamRing out;
const int64_t bs = block_size > 0 ? block_size : 1;
out.ctx_blocks = kv_context_blocks(bs, ctx, cfg.max_seqs);
out.ring_blocks = cfg.kv_resident > 0 ? (cfg.kv_resident + bs - 1) / bs : 0;
if (out.ring_blocks > out.ctx_blocks) out.ring_blocks = out.ctx_blocks;
return out;
}
void kvstream_ring(const Config& cfg, int64_t ctx, int64_t block_size, int64_t sel_pitch,
KVStreamRing* out) {
*out = kvstream_ring_shape(cfg, ctx, block_size);
if (!out->streams()) return; /* absent, 0, or a ring that covers the context */
/* Anything under the computed amount is ignored and pulled up to it. A ring below what one
* decode step can select is not a slower configuration, it is a request served from a
* selection table that no longer addresses the pool -- and the engine computes that floor
* itself, from --max-num-seqs, the drafter's depth and the arch's own sel_pitch. The operator
* asked for streaming, not for a number, so the ring takes the floor and `raised_blocks` says
* the flag did not ask for it: the caller prints the one line, and startup proceeds. Silent
* here because this runs once a rank on the budget probe and once in bring-up, and the raise
* is one startup fact, not three. The ceiling is always positive here: both callers reach this
* only after kvstream_ops().streams(), which requires a kv_resolve with sel_pitch > 0, and
* --max-num-seqs is parsed >= 1. */
const int64_t ceiling = kvstream_ceiling_blocks(cfg, sel_pitch);
if (out->ring_blocks < ceiling) {
out->ring_blocks = ceiling < out->ctx_blocks ? ceiling : out->ctx_blocks;
out->raised_blocks = ceiling;
}
}
int kvstream_cap_probe(KVManager& probe, Config& cfg, const Program& prog, int64_t ctx) {
cfg.kv_streams = false;
if (cfg.kv_resident <= 0) return RAD_OK;
const int32_t g = kv_stream_group(probe, &prog);
if (g < 0) return RAD_OK;
const KVGroupPlan* p = probe.plan(g);
if (!p || p->block_size <= 0) return RAD_OK;
/* This model's architecture declares no streamed path for the group the plan would stream:
* price the pool the ordinary way, exactly as without the flag. The ring's arithmetic is for a
* streamed group only, and the one warning this case deserves is printed by kvstream_configure
* (this probe runs on every rank). */
const KVStreamOps ops =
kvstream_ops(prog, g < (int32_t)prog.kv_groups.size() ? &prog.kv_groups[(size_t)g] : nullptr);
if (!ops.streams()) return RAD_OK;
KVStreamRing ring;
/* The ring this prices is the raised one (kvstream_ring), so the budget and the carve take the
* same depth. */
kvstream_ring(cfg, ctx, p->block_size, ops.sel_pitch, &ring);
if (!ring.streams()) return RAD_OK;
cfg.kv_streams = true;
probe.cap_resident_tokens(g, ring.ring_blocks * p->block_size);
return RAD_OK;
}
} /* namespace rad */
+159
View File
@@ -0,0 +1,159 @@
/* plan.h -- the KV streaming policy, as pure arithmetic on a KVGroupPlan.
*
* A streamed group has two device views over one allocation (docs/KV-STREAMING.md §4.1):
*
* ring n_slots blocks deep, `n_layers` layer stripes, addressed through the residency map;
* stage n_blocks blocks deep, ONE layer stripe, addressed by block id.
*
* The allocation is max(ring_bytes, stage_bytes), never the sum: a decode-only ring is tiny
* against one layer of the context, so the stage sets the price and the ring fits inside it.
* `depth` on the plan is the stripe count of the staged view (1); the ring view keeps the
* group's own `n_layers` stripes. Nothing here touches a device, so this file is testable
* beside mem/kv.h's arithmetic.
*
* The ceiling is the number the VRAM budget is resolved from (Engine::plan, before
* cap_resident_tokens() runs). A streamed group must contribute its stage, not its whole
* cache, or the phase frees nothing: that is why kvstream_cap_probe() is called on the
* throwaway probe before probe.ceiling() (docs/KV-STREAMING.md §4.1, point 5).
*/
#pragma once
#include "mem/kv.h"
namespace rad {
/* Bytes of the decode ring view: `slots` blocks, every layer. Inline because it is one
* multiplication on the plan and because a caller that only lays a view out (kvstream/bind.cpp)
* must not link the probe below, which names KVManager: core/sched/batch.cpp is linked by tests
* whose weak device fakes an extracted KVManager would displace. */
inline int64_t kv_ring_bytes(const KVGroupPlan& p, int64_t slots) {
return slots > 0 ? slots * p.bytes_per_block : 0;
}
/* Blocks the group's context addresses: `max_seqs` sequences at `--max-model-len`, rounded up to a
* whole block each. This is the one spelling of the id space, shared by the store's mirror/map
* sizing (KVStreamStore::context_blocks) and the startup ring decision, so the two cannot disagree
* about whether a ring covers the context. */
inline int64_t kv_context_blocks(int64_t block_size, int64_t max_ctx, int64_t max_seqs) {
if (block_size <= 0) return 0;
const int64_t seqs = max_seqs > 0 ? max_seqs : 1;
const int64_t ctx = max_ctx > 0 ? max_ctx : 0;
return seqs * ((ctx + block_size - 1) / block_size);
}
/* The one allocation: max(ring, stage). `slots <= 0` or `slots >= n_blocks` is a group that does
* not stream (no ring asked for, or one that covers the context), and it keeps its old
* single-view cost. A non-paged group is unchanged. */
int64_t kv_pool_bytes(const KVGroupPlan& p, int64_t slots);
int64_t kv_pool_bytes(const KVGroupPlan& p, int64_t slots, int64_t context_blocks);
int64_t kv_pool_bytes(const KVGroupPlan& p);
/* The pool cost of a group at `blocks` blocks of context and `slots` resident blocks. This is
* what ceiling() sums; with no streamed slot it is the old blocks * bytes_per_block. */
int64_t kv_ceiling_bytes(const KVGroupPlan& p, int64_t blocks, int64_t slots);
/* Whether the idle tiers may gather this group. A streamed group's pool holds one layer's bytes,
* so a tier gather of layer L would be the last staged layer copied n_layers times
* (core/runtime/tierexec.cpp); its mirror is the tier, and the residency map restores a block on
* the next resolve (docs/KV-STREAMING.md §4.1). */
bool kv_tier_cached(const KVGroupPlan& p);
/* The group --kv-resident streams: the widest paged FULL group whose selection the plugin has
* declared a streamed path for, as configure_kv chooses it. `prog` is the resolved program: a group
* is a candidate only if kvstream_ops states its pitch and page, so the choice is a rule rather
* than a width coincidence. dense_read groups are never candidates: a step reads them over the
* whole live history, so a ring cannot hold them back. -1 when the model has none. */
int32_t kv_stream_group(const KVManager& kv, const Program* prog);
/* The same choice from a rank's declarations, before the plans exist (Engine::configure_kv): the
* group by declaration is the one the plans will hold, so the policy is chosen once and the plan
* below follows it. */
int32_t kv_stream_group(const std::vector<KVGroupInfo>& groups, const Program* prog = nullptr);
/* What --kv-resident makes of one group: the ring's depth from the flag, the group's id space from
* --max-num-seqs and --max-model-len, and whether anything streams at all. Pure arithmetic on
* numbers the engine already has, so the budget probe and the carve decision cannot disagree. */
struct KVStreamRing {
int64_t ring_blocks = 0; /* --kv-resident, rounded up to whole blocks and raised to the
* ceiling below when the flag asks for less */
int64_t raised_blocks = 0; /* the depth the flag was raised to (kvstream_ceiling_blocks), or 0
* when it already asked for that much: the ring is not the
* operator's number when this is set */
int64_t ctx_blocks = 0; /* max_seqs x ceil(ctx / block_size): the group's whole context */
/* A ring that covers the context is not a streamed group. The pool then holds every block
* with its own id, so the group keeps the base engine's path exactly: no mirror, no residency
* maps, no stage, no resolve, and a null RadKVStream (docs/KV-STREAMING.md §5 Phase 4). */
bool streams() const { return ring_blocks > 0 && ring_blocks < ctx_blocks; }
};
/* The blocks one decode step's selections can name, which is what the ring must hold -- and the
* depth --kv-resident is raised to when it asks for less. A within-(1+n_spec) decode pass takes
* the ring (`kv_pass_view`); a decode-classified pass with more rows a sequence than that (the
* serial drafter's history pass over a prefill chunk) stages, so it is not counted here. Under
* speculation a decode step issues one selection per row, so a step is `max_seqs x (1 + n_spec)`
* rows and each names at most `sel_pitch` distinct blocks -- the arch's `topk + 1`. 0 when the
* program declares no kv_resolve: a dense model's attention reads a block id as a pool slot, so
* its ceiling is the whole context and nothing can be streamed. */
int64_t kvstream_ceiling_blocks(const Config& cfg, int64_t sel_pitch);
/* The ops a streamed group's issue path actually needs, read off the program the plugin declared
* (the builder's resolved op list, not the architecture's name). A streamed group is only safe
* when its attention rewrites `sel` from block ids into ring slots (`kv_resolve`) and its store
* writes the host mirror (`kv_store_streamed`, or the fused prologue that folds the store in).
* Without the resolve, `sel` still holds block ids while the attention reads them as pool page
* indices -- past the ring when the pool is smaller than the id space, which is a fault, not a
* slow path. Without the store nothing writes the mirror, so a miss reads zeros.
*
* `group` narrows the match to the group the plan will stream: a declaration states that group's
* geometry (`block_bytes` on the resolve, `block_size` on the store), so a resolve emitted for a
* narrower group cannot enable streaming of another. Null matches any declaration; a declaration
* that states no geometry is accepted as-is, so a plugin that names neither is never refused for
* it. A declaration the builder recorded with no kernel in any domain is not a path: the plugin's
* handle was null and nothing would be issued (the same test as Builder::op_resolved). That is how
* a packed cache reads -- the architecture emits the store and the kernel table has no row for the
* layout -- and it must not count, or the group would stream with a null writer. */
struct KVStreamOps {
bool resolve = false; /* kv_resolve, stating this group's layer bytes and sel_pitch */
bool store = false; /* kv_store_streamed: the mirror writer every streamed layer has */
bool folded = false; /* qk_norm_rope_gate_kv_store_streamed: the same store, folded */
int64_t sel_pitch = 0; /* the blocks one selection row can name, from the resolve */
/* The ops are there, so this group can stream. */
bool streams() const { return resolve && (store || folded); }
/* The first op the plugin is missing, for the one startup line that says why nothing streams;
* null when streams(). */
const char* missing() const {
if (!resolve) return "kv_resolve";
if (!store && !folded) return "kv_store_streamed";
return nullptr;
}
};
KVStreamOps kvstream_ops(const Program& prog, const KVGroupInfo* group);
/* The ring's depth and the group's id space with nothing else decided: whether a ring covers the
* context, so that the caller can tell "this model has no streamed path" (a warning) from "this
* ring is below what a decode step can select" (a raise) without one hiding the other. */
KVStreamRing kvstream_ring_shape(const Config& cfg, int64_t ctx, int64_t block_size);
/* Read --kv-resident against `group`'s context and fill `out`. A ring below what one decode step
* can select is raised to it -- `out->ring_blocks` becomes the ceiling and `out->raised_blocks`
* says the flag did not ask for that much -- not refused: the engine computes the floor and the
* operator asked for streaming, not for a number. The caller states the one warning, once, and
* startup proceeds. A ring that covers the context is not a raise either -- it is
* `out->streams() == false`, and the group stays a resident pool. `block_size` is the group's own
* page (1 for a group whose page is unknown). Never refuses: both callers reach it only after
* kvstream_ops().streams(), so the ceiling is positive, and a caller that names a pitch of its own
* on a model with no kv_resolve is a case its caller has already warned about and ignored. */
void kvstream_ring(const Config& cfg, int64_t ctx, int64_t block_size, int64_t sel_pitch,
KVStreamRing* out);
/* Teach the budget probe the streamed plan: the ring from --kv-resident and the stage from the
* context. Call before probe.ceiling(ctx); the group's ceiling then falls from n_layers of its
* context to max(ring, one layer of it), and `cfg.kv_streams` records that the pool is priced that
* way (core/mem/vram_budget.cpp). Returns RAD_OK on a model with nothing to stream, before any
* weight is loaded. The ring it prices is the raised one (kvstream_ring), so the budget and the
* carve take the same depth; the warning for it is kvstream_configure's, which runs once rather
* than once a rank. A group whose architecture declares no streamed ops (kvstream_ops) is not
* priced for streaming at all: that is the same RAD_OK, with `cfg.kv_streams` left false, so the
* configuration is exactly the one without --kv-resident. */
int kvstream_cap_probe(KVManager& probe, Config& cfg, const Program& prog, int64_t ctx);
} /* namespace rad */
+358
View File
@@ -0,0 +1,358 @@
/* stage.cpp -- see stage.h (the ordering rule lives there, beside the code that would break it). */
#include "kvstream/stage.h"
#include "device/device.h"
#include "kvstream/bind.h"
#include "runtime/wtab.h"
#include <algorithm>
#include <cstdlib>
namespace rad {
namespace {
/* The layer staged most recently on this rank thread; reset at every pass. */
thread_local int g_last_layer = -1;
/* What the pass that just closed staged, and over how many tokens: the counter is read at the next
* enter, so the numbers are the ones a request actually paid (docs/KV-STREAMING.md §3.9). */
struct PassStage {
uint64_t layers = 0, bytes = 0;
int64_t tokens = 0, ctx = 0, live_row = 0; /* live_row: the history ONE layer of this pass reads */
int64_t bound_blocks = 0; /* the manager's bound the copy was clamped to */
int phase = -1;
};
thread_local PassStage g_pass;
bool trace_stage() {
static const bool on = std::getenv("RADIANCE_KV_STAGE_TRACE") != nullptr;
return on;
}
/* One line per pass that staged: the bytes the pass moved against the bytes the history it read
* actually occupies. The ratio is the number that decides whether the stage is a bandwidth problem
* or a per-chunk tax (see the note beside kv_stage_layer). */
void report_pass() {
if (!g_pass.layers) return;
const double live = (double)g_pass.live_row * (double)g_pass.layers;
RAD_INFO("kv streaming: stage pass phase=%d tokens=%lld ctx=%lld: %llu layers, %.1f MiB moved, "
"%.1f MiB of live history (%.1fx), bound %lld blocks",
g_pass.phase, (long long)g_pass.tokens, (long long)g_pass.ctx,
(unsigned long long)g_pass.layers, (double)g_pass.bytes / (1024.0 * 1024.0),
live / (1024.0 * 1024.0), live > 0.0 ? (double)g_pass.bytes / live : 0.0,
(long long)g_pass.bound_blocks);
}
} /* namespace */
/* Forget the last staged layer. A pass visits its layers in order and `resolve_sel` may be called
* once per attention launch, so the driver stages a layer once and treats a consecutive repeat as
* already done. Called from kvstream_enter() at every pass. */
static void kvstage_begin_pass() {
report_pass();
g_last_layer = -1;
g_pass = PassStage();
}
void kvstream_enter(Ctx* c, const RadBatch* b) {
/* The stage is filled once per layer per pass; a new pass starts at the first layer again. */
kvstage_begin_pass();
if (!c || !b) return;
g_pass.tokens = b->n_tok;
g_pass.ctx = b->max_ctx_len;
g_pass.phase = b->phase;
for (int i = 0; i < b->n_kv_groups; ++i) {
if (!b->kv[i].stream) continue;
KVPoolBinding* kb = c->kv_binding(b->kv[i].group);
if (!kb || !kb->has_stage) continue;
/* A pass selects by phase and row shape (bind.h). */
kv_binding_enter(*kb, kv_pass_view(b->phase, b->n_tok, b->n_seq, b->n_spec));
/* The history one layer of this pass can read: every block up to the longest sequence's
* end, at the same block size the resolve uses. That is the useful part of the stage row
* the draw below copies in full. */
if (kb->stage.bytes > 0 && b->kv[i].block_size > 0 && b->kv[i].stream->block_bytes > 0) {
const int64_t reach = b->max_ctx_len + b->max_q_len;
const int64_t live_blocks = (reach + b->kv[i].block_size - 1) / b->kv[i].block_size;
const int64_t row = std::min(live_blocks * b->kv[i].stream->block_bytes, kb->stage.bytes);
if (row > g_pass.live_row) g_pass.live_row = row;
if (kb->stage_live_bytes > 0) {
const int64_t bound = kb->stage_live_bytes / b->kv[i].stream->block_bytes;
if (bound > g_pass.bound_blocks) g_pass.bound_blocks = bound;
}
}
}
}
/* The allocator's high-water mark, as bytes of one layer: every id a table can name is below it
* (stage.h, "VOLUME", states the argument and the failure if it is ever too small). */
void kvstream_bound_live(Ctx* c, const KVManager& kv) {
if (!c) return;
for (int g = 0; g < kv.n_groups(); ++g) {
KVPoolBinding* b = c->kv_binding(g);
if (!b || !b->has_stage) continue;
const RadKVStream* st = kv.stream_view(g);
if (!st || st->block_bytes <= 0) continue;
const int64_t blocks = kv.held_top_blocks(g);
b->stage_live_bytes = blocks > 0 ? blocks * st->block_bytes : 0;
}
}
} /* namespace rad */
namespace rad {
namespace {
/* Where a staged layer's bytes come from and how big they are: both views start at the pool base, so
* the destination is always offset 0 and the source is this layer's row in the mirror, addressed by
* the group-local position (`layer_slot`), not by the absolute model layer. */
struct StageSrc {
void* dst = nullptr;
const uint8_t* src = nullptr;
int64_t bytes = 0;
};
bool stage_src(Ctx* ctx, int group, const RadKVGroupBatch* kvb, int layer, StageSrc* o) {
const KVPoolBinding* b = ctx->kv_binding(group);
const RadKVStream* st = kvb ? kvb->stream : nullptr;
if (!b || !st) return false;
const int64_t li = ctx->kv_layer_index(group, layer);
if (!st->host || st->block_bytes <= 0 || st->host_layer_stride <= 0 || li < 0) return false;
o->dst = b->base;
o->src = st->host + li * st->host_layer_stride;
o->bytes = b->bytes;
/* Only the live prefix of the row: the block ids above the manager's highest held block cannot
* be named by any table this pass reads (stage.h, "VOLUME" -- an underestimate here is wrong
* text, not a fault, so this is the bound and not a guess). */
if (b->stage_live_bytes > 0 && b->stage_live_bytes < o->bytes) o->bytes = b->stage_live_bytes;
if (o->bytes <= 0 || o->bytes > st->host_layer_stride) o->bytes = st->host_layer_stride;
return o->bytes > 0;
}
/* The DMA path: one layer of the mirror onto the card without holding a CU slot, overlapped with the
* layer before it. `done` is an event the list completes instead of a dispatch; `mark` is the ride
* on the compute stream the list waits for, or null (copy now). */
bool dma_stage(Ctx* c) {
static const bool on = rad_xp_supported(c->device()) != 0;
return on;
}
/* One list in flight per rank thread: the layer it fills, and the ride it waits on. */
struct StagePipe {
RadEvent done = nullptr;
int inflight = -1; /* the layer the outstanding list fills */
int group = -1;
void* mark = nullptr;
int64_t bytes = 0; /* what that list was told to move, for the pass's counter */
};
thread_local StagePipe g_pipe;
thread_local bool g_warned_ride = false;
/* Arm the completion word, mark the compute stream and hand the list over.
*
* The arm is a write of 1 in stream order (the weight table's patch dispatch, runtime/wtab.h), and
* it is also the dispatch the list's ride waits on: so the list starts when the arm has executed,
* and the copy's 0 can never precede the 1 the wait is looking for. The arm is behind every
* attention launch of the layer before, which is what makes the one-layer buffer safe to refill
* (core/kvstream/stage.h). */
bool arm_and_submit(Ctx* c, int group, int layer, const StageSrc& s, void* mark) {
uint32_t* word = nullptr;
if (!g_pipe.done || rad_event_dma(g_pipe.done, c->stream(), &word) < 0) return false;
WtabPatch arm;
arm.n = 1;
arm.dst[0] = (void**)(void*)word;
arm.val[0] = (void*)(uintptr_t)1;
if (wtab_patch(arm, c->stream()) < 0) return false;
const uint64_t src = (uint64_t)(uintptr_t)s.src, dst = (uint64_t)(uintptr_t)s.dst;
const uint64_t bytes = (uint64_t)s.bytes;
/* No yield: this copy's wait is a barrier on the very stream whose link hold would release it
* (docs/KV-STREAMING.md §6.1, the deadlock the prefetch's rule names). */
if (rad_xp_list(c->device(), mark, 1, &src, &dst, &bytes, word, 0, RAD_XP_NO_YIELD) != RAD_OK)
return false;
g_pipe.inflight = layer;
g_pipe.group = group;
g_pipe.mark = mark;
g_pipe.bytes = s.bytes;
if (trace_stage())
RAD_INFO("kv streaming: handed over layer %d (%lld bytes), behind %lld", layer,
(long long)s.bytes, (long long)rad_xp_behind(c->device()));
return true;
}
/* The copy on the compute stream, for a backend with no DMA queue (the host backend, a test) and
* for a ride the engine would not lend: a list holds no CU slot, a copy does, so this is the path
* that pauses the layer rather than the one that rides behind it. */
int serial_stage(Ctx* c, const StageSrc& s) {
RadStream st = c->stream();
const int rc = (s.bytes & 15) == 0
? rad_memcpy_ranges_async(s.dst, s.src, s.bytes, nullptr, 0, st)
: rad_memcpy_async(s.dst, s.src, s.bytes, st);
return rc;
}
void count_stage(Ctx* c, int layer, int64_t bytes) {
g_last_layer = layer;
g_pass.layers += 1;
g_pass.bytes += (uint64_t)bytes;
if (trace_stage() && c->rank() == 0)
RAD_INFO("kv streaming: stage layer %d (%lld bytes)", layer, (long long)bytes);
}
/* Records the arm and the submit where a recorded pass made them: a DMA list is not a queue packet,
* so a tape that replayed without them would read an unstaged layer. */
int stage_issue_host(Ctx* c, int group, int layer, bool after) {
if (c->recording())
return c->tape_kv_stage(after, group, layer);
return kvstage_run(c, group, layer, after);
}
} /* namespace */
/* The wait and, when the pipeline has nothing for this layer, the copy: issued before the layer's
* store, so the store's newer bytes are the last writer of this chunk's positions (the copy reads a
* mirror the store has not written yet). 1 when the layer is staged, 0 when the group has no stage
* view -- the caller then resolves as usual. A failure is reported with rad_step_fail and returns
* 1, so the caller stops rather than reading an unstaged layer. Internal: every caller is the
* extern "C" seam below. */
static int kvstage_wait(Ctx* c, int group, const RadKVGroupBatch* kvb, int layer) {
if (!c || !kvb || !kvb->stream) return 0;
const KVPoolBinding* b = c->kv_binding(group);
if (!b || !b->has_stage || b->depth != 1) return 0;
if (layer == g_last_layer) return 1;
return stage_issue_host(c, group, layer, false);
}
/* After a layer's attention has been issued and has finished reading the stage: start the next
* bound layer's copy. The ride is completed by the next dispatch on the compute stream, which is
* behind every attention launch of `layer`; nothing may read the stage again until the wait that
* precedes the next layer's store. 0 always: it reports nothing to the arch, and the exported
* rad_kv_stage_next keeps the int for the ABI (every caller (void)s it). Internal: the extern "C"
* seam below is its only caller. */
static int kvstage_next(Ctx* c, int group, int layer) {
if (!c) return 0;
const KVPoolBinding* b = c->kv_binding(group);
if (!b || !b->has_stage || b->depth != 1) return 0;
return stage_issue_host(c, group, layer, true);
}
int kvstage_run(Ctx* c, int group, int layer, bool after) {
if (!c) return 0;
const RadBatch* b = c->batch();
const RadKVGroupBatch* kvb = nullptr;
if (b)
for (int i = 0; i < b->n_kv_groups; ++i)
if ((int)b->kv[i].group == group) { kvb = &b->kv[i]; break; }
if (!kvb || !kvb->stream) return 0;
const KVPoolBinding* kb = c->kv_binding(group);
if (!kb || !kb->has_stage || kb->depth != 1) return 0;
if (!after) {
/* Make `layer`'s stage row whole. Pipelined: the list was handed over at the layer before,
* so this is a barrier on the compute stream that the engine's done word releases. */
if (g_pipe.inflight >= 0 && (g_pipe.inflight != layer || g_pipe.group != group)) {
/* A list is filling the stage for a layer this pass does not read (a pass that ended
* before it). Nothing may rewrite the buffer until it lands. */
(void)rad_event_wait(c->stream(), g_pipe.done);
g_pipe.inflight = -1;
g_pipe.bytes = 0;
rad_ride_release(g_pipe.mark, nullptr, 0);
g_pipe.mark = nullptr;
}
if (g_pipe.inflight == layer && g_pipe.group == group) {
if (rad_event_wait(c->stream(), g_pipe.done) < 0) {
rad_step_fail(c, "kv streaming: the compute stream could not wait for the stage copy "
"the DMA engine is filling; the layer's attention would read the "
"previous layer's bytes");
return 1;
}
/* What the list was handed, not the row's whole size: the counter is what the pass
* paid, and the clamp is the whole point of the pass's bound. */
const int64_t moved = g_pipe.bytes;
g_pipe.inflight = -1;
g_pipe.bytes = 0;
/* The signal the list polled is nobody's until it goes back to the pool. */
rad_ride_release(g_pipe.mark, nullptr, 0);
g_pipe.mark = nullptr;
count_stage(c, layer, moved);
return 1;
}
StageSrc s;
if (!stage_src(c, group, kvb, layer, &s)) {
rad_step_fail(c, "kv streaming: a layer needs its prefill stage but the group has no host "
"mirror row for it, so the attention would read an unstaged layer");
return 1;
}
/* Nothing was pipelined for this layer (the pass's first, or a group the pipeline has not
* seen): copy it on the engine now and wait for it, so it costs the layer's prologue. */
if (dma_stage(c)) {
if (!g_pipe.done && rad_event_create_local(&g_pipe.done) < 0) g_pipe.done = nullptr;
/* The arm dispatch is what the ride below is completed by; it is issued after this
* layer's projections, so the copy has that much of a head start. */
void* mark = nullptr;
if (g_pipe.done && rad_ride(c->stream(), &mark) == RAD_OK) {
if (arm_and_submit(c, group, layer, s, mark)) {
const bool ok = rad_event_wait(c->stream(), g_pipe.done) >= 0;
g_pipe.inflight = -1;
rad_ride_release(mark, nullptr, 0);
if (ok) {
count_stage(c, layer, s.bytes);
return 1;
}
} else {
rad_ride_release(mark, nullptr, 0);
}
}
}
if (serial_stage(c, s) < 0) {
rad_step_fail(c, "kv streaming: the prefill stage copy failed; the layer's attention "
"would read the previous layer's bytes");
return 1;
}
count_stage(c, layer, s.bytes);
return 1;
}
/* The layer after this one in this group's binding, if it has one. */
int next = -1;
const auto& ls = kb->layer_slot;
for (int l = layer + 1; l < (int)ls.size(); ++l)
if (c->kv_layer_index(group, l) >= 0) { next = l; break; }
if (next < 0 || !dma_stage(c)) return 0;
if (!g_pipe.done && rad_event_create_local(&g_pipe.done) < 0) g_pipe.done = nullptr;
if (!g_pipe.done) return 0;
StageSrc s;
if (!stage_src(c, group, kvb, next, &s)) return 0;
/* No spare ride: the next layer's wait copies it on the compute stream instead. */
void* mark = nullptr;
if (rad_ride(c->stream(), &mark) != RAD_OK) {
if (!g_warned_ride) {
g_warned_ride = true;
RAD_INFO("rank %d: kv streaming: no spare ride for the stage's DMA list, so its layer "
"copies serially", c->rank());
}
return 0;
}
if (!arm_and_submit(c, group, next, s, mark)) {
rad_ride_release(mark, nullptr, 0);
return 0;
}
return 0;
}
} /* namespace rad */
extern "C" int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb,
int layer) {
using namespace rad;
if (!c || !kvb || !kvb->stream) return 0;
return kvstage_wait(static_cast<Ctx*>(c), group, kvb, layer);
}
/* The two exported names are the same question ("is this layer staged?"); the frozen ABI keeps
* both signatures, but only one body. */
extern "C" int rad_kv_stage_wait(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb,
int layer) {
return rad_kv_stage_layer(c, group, kvb, layer);
}
extern "C" int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer) {
using namespace rad;
if (!c) return 0;
return kvstage_next(static_cast<Ctx*>(c), group, layer);
}
+116
View File
@@ -0,0 +1,116 @@
/* stage.h -- the one-layer prefill stage: per pass, per layer, copy the live part of the layer's
* mirror row into the stage view of the group's pool, on the card's DMA engine, one layer ahead.
*
* ORDERING RULE -- a correctness invariant, not a preference.
*
* Aliasing every layer to offset 0 is safe only because, for each layer L, these four happen in
* this order:
*
* 1. the stage copy of L has landed;
* 2. L's store writes this chunk's tokens into the stage (the stage copy reads the mirror, which
* the store has not written yet, so a copy landing after the store would put the mirror's
* older bytes back over them);
* 3. L's attention reads the stage;
* 4. the stage copy of L+1 starts, and nothing reads the stage until its wait.
*
* The copy is a list on the card's DMA engine, which holds no CU slot, so the order does not rest
* on one stream's issue order alone:
*
* - 1 before 2 is a barrier the compute stream takes on an event the *list itself* completes
* (rad_event_dma hands the list the event's completion word as its `done`), issued immediately
* before the layer's store. `rad_event_wait` is a barrier packet, so the wait is device-side and
* in issue order: nothing between it and the store can slip in front of it;
* - 4 after 3 is a ride (`rad_ride`) taken on the compute stream once every attention launch of
* layer L has been issued, so the signal it completes is behind all of L's reads. The list polls
* that signal, so it starts when L's attention is done, and crosses the link under L's MLP and
* L+1's projections.
*
* What breaks it, in the order it is likely to happen:
*
* - taking the ride *before* all of L's attention launches. A prefill layer's attention is issued
* in `qsa_gq_rows`-wide chunks, so a ride taken at the first chunk starts the copy of L+1 while
* the second chunk still reads the stage. That is why the seam is after the loop
* (`rad_kv_stage_next`), not in `resolve_sel`;
* - waiting for the copy *after* the layer's store instead of before it. The store's bytes are the
* newest ones and the copy's are older ones from the same mirror row;
* - arming the completion event on the host instead of on the compute stream. An older 0 from the
* previous layer's list would then release this layer's wait early, and a fresh 1 would cut the
* previous wait short -- one signal, two uses, no order between them. The record packet puts the
* arm in stream order, behind the previous wait;
* - the copy on lane 1, or on a bare second stream with no recorded event pair (see §3.5.1);
* - re-issuing the copy host-side without `tape_host`. The list is not a queue packet, so a
* recorded pass must re-run the arm and the submit where it made them; `Ctx::tape_kv_stage`
* does that with the tape paused, as `xprefetch.cpp` does for the prefetch.
*
* `haz_mark` sees the KV operand as the same byte range for every aliased layer, so a stage and the
* previous layer's attention are never marked overlap. That is a relaxation check, not the
* protection; do not weaken it (core/runtime/issue.cpp, "haz_mark"). The DMA copy is not a dispatch
* at all, so the hazard pass cannot see it: the barriers above are its whole ordering.
*
* VOLUME -- and the one way this file can be silently wrong.
*
* The copy moves the mirror row up to the highest block id the coming attention can read, not the
* whole row: `n_blocks * block_bytes` is the context allocation, and a 17k-token request was
* paying 24 GiB of PCIe to stage 102 MiB of live KV (docs/KV-STREAMING.md §3.5, §5 Phase 3).
*
* `stage_live_bytes` (kvstream_bound_live, called once per released batch from the engine) is an
* UPPER bound on the block ids the pass can name, and an UNDERESTIMATE IS NOT A CRASH: the attention
* would read bytes the copy never moved -- whatever the previous layer left there -- and produce
* fluent wrong text. It cannot be too small because:
*
* - every id a block table can hold came out of the group's allocator and is held, and
* `KVManager::held_top_blocks` is one bucket past the highest held block it has counted. The
* histogram is updated on every acquisition (grab_block, reserve_specific_block) and on the last
* release, so it counts sequence blocks and cache-retained blocks alike;
* - the stage view is identity-addressed from block 0 for every layer, so copying [0, bound)
* covers every id below it, whether or not the ids are dense;
* - it is re-evaluated every step, so the chunk that appends a block raises it before the pass
* that reads it. A partial tail block and a speculative token live in blocks `ensure` took
* before the step was built, so they are held and inside the bound; the bound is in blocks, so
* a partial block is copied whole and its unwritten tail is the mirror's zeros.
*
* Ascending allocation is NOT assumed. The free list is a min-heap, so a fresh sequence usually
* takes 0,1,2..., but a prefix-cache-retained block or a restore's `reserve_specific_block` can
* leave a live block above a free one, and a reused id need not be the sequence's next. That is
* why the bound is the allocator's high-water mark and not `ceil(end / block_size)`.
*
* What the bound costs: it is the whole group's held set, including blocks another sequence or the
* prefix cache holds, so a server with a long cached conversation behind it stages more than the
* request reads. It is never less, and a group with nothing held (0) stages the whole row as before.
*
* A backend with no DMA queue (the host backend, a test) copies on the compute stream exactly as
* before, in the same four-step order.
*/
#pragma once
#include "mem/kv.h"
#include "runtime/ctx.h"
namespace rad {
/* Select the view of every streamed group a pass names, and reset the stage's per-pass state.
* Called once before the pass loop (seams in core/runtime/ctx.cpp). Here rather than in bind.h
* because it is the pass's opening move -- the driver's, not the layout's -- and because a caller
* that only builds a step's view must not link the driver (core/sched/batch.cpp). */
void kvstream_enter(Ctx* c, const RadBatch* b);
/* Carry the block manager's upper bound on live block ids into every streamed group's stage view,
* for the step about to run. Called for every rank from Engine::prepare_release, with the ranks
* parked, after the step's blocks are ensured and before its layers are staged; rank 0's manager is
* the one that hands the ids out. A group with nothing held leaves the view at 0, which copies the
* whole row (stage.h, "VOLUME"). */
void kvstream_bound_live(Ctx* c, const KVManager& kv);
/* The driver, as a tape step re-runs it (Ctx::tape_kv_stage). `after` is the seam between the
* layer's store and the next layer's copy. */
int kvstage_run(Ctx* c, int group, int layer, bool after);
} /* namespace rad */
extern "C" {
/* Is this layer staged? 1: its row is whole for this pass (the caller must not resolve it). 0: the
* group has no stage view, so the caller proceeds normally. Called from `resolve_sel`, which is the
* pass's later seam: the wait itself happens before the layer's store, so this only reports. */
int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, int layer);
/* Issue the next bound layer's stage copy, after this layer's attention has been issued. */
int rad_kv_stage_next(RadCtx* c, rad_kvgroup group, int layer);
}
+56 -12
View File
@@ -1,6 +1,9 @@
/* kv.cpp -- see kv.h. */
#include "mem/kv.h"
#include "kvstream/carve.h"
#include "kvstream/plan.h"
#include <algorithm>
#include <cassert>
#include <cstring>
@@ -71,7 +74,7 @@ std::string BundleComparison::report() const {
/* ------------------------------------------------------------------ configure */
static const char* kv_kind_name(int k) {
const char* kv_kind_name(int k) {
switch (k) {
case RAD_KV_FULL: return "full";
case RAD_KV_WINDOW: return "window";
@@ -133,6 +136,7 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
* other plan-path code has to know the kind. */
p.kind = g.decl.kind == RAD_KV_RING ? RAD_KV_WINDOW : g.decl.kind;
p.n_layers = (int64_t)g.layers.size();
p.dense_read = g.dense_read;
if (p.n_layers <= 0) {
RAD_ERR("KV group '%s': no layers are bound to it, so its page size is unknown "
@@ -309,8 +313,11 @@ int64_t KVManager::ceiling(int64_t ctx) const {
int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size);
if (p.kind == RAD_KV_WINDOW && !p.runtime_win && p.window_blocks > 0)
blocks = std::min(blocks, window_pool_cap(p));
need += blocks * p.bytes_per_block;
need += kv_ceiling_bytes(p, blocks, stream_.resident_blocks(p));
}
/* The streamed groups' residency maps are reserved from this same pool; leaving them out makes
* a pool given its whole ceiling short by their bytes (kvstream/carve.h). */
need += kvstream_maps_charged(plans_, stream_, ctx, max_seqs_);
return need;
}
@@ -415,9 +422,15 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
/* Zero groups take no part in the split; they get the shared table's block count, which is
* what the costed groups settle on here or, under the cap, on the ranks holding the cache. */
std::vector<int32_t> open, zeros;
for (const auto& p : plans_)
if (p.paged()) (p.zero ? zeros : open).push_back(p.index);
/* Every paged group zero: this rank limits nothing, so take the cap, or report unbounded. */
bool dense = false;
for (const auto& p : plans_) {
if (!p.paged()) continue;
if (p.zero) zeros.push_back(p.index);
else if (kvstream_dense(p, plans_, stream_)) dense = true; /* its carve is a floor */
else if (!stream_.windowed(p.index)) open.push_back(p.index);
}
kvstream_split_windows(plans_, stream_, max_ctx_, max_seqs_, &remaining, &out);
/* Every paged group is zero: this rank limits nothing, so take the cap, or report unbounded. */
if (open.empty() && !zeros.empty()) {
const int64_t tokens = tokens_cap_ > 0 ? tokens_cap_ : kUnboundedTokens;
if (blocks) {
@@ -453,6 +466,10 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
}
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;
/* A dense-read group's floor is already paid and has no share of the split, so a pool with no
* other open group still pages one full-length sequence: that is the count the report and the
* admission cap must see, even though the group addresses max_seqs of them. */
if (dense && open.empty() && remaining > 0) tokens = max_ctx_;
if (blocks) *blocks = std::move(out);
return tokens;
}
@@ -486,8 +503,13 @@ int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
}
int KVManager::carve_into(Pool& kv_pool) {
/* The pool size is the resolver's; this only splits it between the groups. */
const int64_t budget_bytes = kv_pool.avail();
/* The pool size is the resolver's; this only splits it between the groups. The streamed
* groups' maps were reserved from this pool before the carve (KVStreamStore::alloc), so add
* them back: paged_split() charges them as part of those groups' windows (kvstream/carve.h),
* and a budget that already excludes them would be charged twice and leave the resident
* groups one map short. */
const int64_t budget_bytes = kv_pool.avail() +
kvstream_maps_charged(plans_, stream_, max_ctx_, max_seqs_);
const int64_t fixed = fixed_;
pool_base_ = kv_pool.base();
pool_ = &kv_pool;
@@ -505,11 +527,21 @@ int KVManager::carve_into(Pool& kv_pool) {
return RAD_E_NOMEM;
}
/* ---- the resident windows, before anything is split (kvstream/carve.h) ---- */
RAD_TRY(kvstream_window_fit(plans_, stream_, fixed, budget_bytes, max_ctx_, max_seqs_));
/* ---- the paged split; under a cap, the least rank's ---- */
std::vector<int64_t> blocks;
(void)paged_split(budget_bytes, &blocks);
for (auto& p : plans_) if (p.paged()) p.n_blocks = blocks[p.index];
/* How much of that the device pool backs, and the refusal of a streamed plan with nothing to
* back the rest (kvstream/carve.h). */
RAD_TRY(kvstream_apply(plans_, stream_, max_ctx_, max_seqs_));
/* A streamed group's `n_blocks` is its context, not the window the split gave it, so this asks
* the right question of it -- can the group address anything at all -- and its window (which is
* what `blocks[p.index]` holds) never decides whether the carve goes ahead. */
for (auto& p : plans_) {
if (!p.paged()) continue;
if (p.n_blocks <= 0 && p.zero) {
@@ -531,7 +563,7 @@ int KVManager::carve_into(Pool& kv_pool) {
/* ---- carve. Every reservation comes from the KV pool only; the mover works inside the
* weight slab and cannot reach it (spec §6). ---- */
for (auto& p : plans_) {
int64_t bytes = p.paged() ? p.n_blocks * p.bytes_per_block
int64_t bytes = p.paged() ? kv_pool_bytes(p)
: p.n_states * p.bytes_per_state;
if (p.zero) {
p.base = nullptr;
@@ -625,14 +657,19 @@ int KVManager::carve_into(Pool& kv_pool) {
return p.runtime_win ? "ring" : kv_kind_name(p.kind);
};
for (const auto& p : plans_) {
if (p.paged())
if (p.paged()) {
report_ += fmt(" %-14s %-6s %3lld layers block %4lld tok page %8s "
"%7lld blocks = %9s (%lld tokens)\n",
p.name.c_str(), kind_of(p), (long long)p.n_layers,
(long long)p.block_size, humanb(p.bytes_per_block).c_str(),
(long long)p.n_blocks, humanb(p.pool_bytes).c_str(),
(long long)(p.n_blocks * p.block_size));
else
/* Both tiers of a streamed group in one line (kvstream/carve.h): its pool is smaller
* than its context, so the line above would read as a pool that holds the whole
* context. */
if (p.streamed())
report_ += kvstream_report_line(p);
} else
report_ += fmt(" %-14s %-6s %3lld layers state %8s %7lld slots = %9s\n",
p.name.c_str(), kind_of(p), (long long)p.n_layers,
humanb(p.bytes_per_state).c_str(),
@@ -758,6 +795,9 @@ int64_t KVManager::total_blocks(int32_t g) const {
int64_t KVManager::live_blocks(int32_t g) const {
return (g >= 0 && g < (int32_t)live_.size()) ? live_[(size_t)g] : 0;
}
int64_t KVManager::held_top_blocks(int32_t g) const {
return (g >= 0 && g < (int32_t)plans_.size()) ? held_top((size_t)g) : 0;
}
/* The larger of one prefill chunk and the recent shortfall peak (see buffer_bytes in kv.h). */
int64_t KVManager::buf_blocks(size_t i) const {
@@ -786,8 +826,12 @@ int64_t KVManager::available_blocks(int32_t g) const {
bool KVManager::lendable(int32_t g) const {
const KVGroupPlan* p = plan(g);
/* A streamed group never lends. Its pool is the resident window off which a residency map
* reads, so a block lent to the expert slab is one the attention has nowhere to put; the
* whole point of the group is that the pool is small, and taking part of it away would leave
* fewer slots than one launch's selection needs. */
return p && p->kind == RAD_KV_FULL && p->n_blocks > 0 && p->block_size > 0 &&
p->bytes_per_block > 0;
p->bytes_per_block > 0 && !p->streamed();
}
int64_t KVManager::lent_blocks(size_t i, int64_t tokens) const {
@@ -905,7 +949,7 @@ int64_t KVManager::pool_bytes(int32_t g) const {
int64_t KVManager::pool_bytes_carved(int32_t g) const {
const KVGroupPlan* p = plan(g);
if (!p) return 0;
if (p->paged()) return p->n_blocks * p->bytes_per_block;
if (p->paged()) return kv_pool_bytes(*p);
if (p->stateful()) return p->n_states * p->bytes_per_state;
return 0;
}
+77 -3
View File
@@ -20,6 +20,7 @@
* request by the other.
*/
#pragma once
#include "kvstream/mirror.h"
#include "mem/hostarena.h"
#include "mem/pools.h"
#include "rad_core.h"
@@ -54,6 +55,10 @@ struct BundleComparison {
};
BundleComparison compare_bundling(const std::vector<int64_t>& bundles);
/* The name a refusal or a report uses for a RAD_KV_* kind (kvstream/carve.cpp names the kind it
* refuses; KVManager::report() the one it carved). */
const char* kv_kind_name(int kind);
/* ------------------------------------------------------------------ the runtime window */
/* A sequence's per-sequence window on a RAD_KV_WINDOW group, set at runtime (R-SWA, the
* "reference + ring" attention of Unlimited-OCR: a full causal prefill over the prompt and image
@@ -123,11 +128,31 @@ struct KVGroupPlan {
* snapshot would be read. */
bool win_snap = false;
int64_t n_blocks = 0; /* paged groups: blocks carved from the pool */
int64_t n_blocks = 0; /* paged groups: blocks the group addresses (its context) */
/* Paged groups: blocks the device pool actually backs, which may be fewer than `n_blocks`
* when the group's KV streams (docs/KV-STREAMING.md). Block ids stay dense over `n_blocks` --
* the manager, the refcounts, the block table, the prefix cache and every `id < n_blocks`
* guard count in the group's context, because the table a sequence holds names logical blocks.
* Only *addressing* uses this: the pool is carved `n_slots` blocks deep and the stride between
* layers is `n_slots` blocks long, so a residency map (block -> resident slot) is what turns a
* logical block into an address. Equal to `n_blocks` in every other case, so no existing
* layout moves. */
int64_t n_slots = 0;
/* Layer stripes the pool's *staged* view presents: 0 means `n_layers` (the ring, and every
* group that does not stream), 1 means one layer and every layer aliases offset 0. It is a
* depth, not a rewritten layer table: `layer_slot` is also the host mirror's row
* (rad_kv_layer_index), so collapsing it would write every layer into one mirror row
* (docs/KV-STREAMING.md §3.5.1). Set by carve() when the group's ring is smaller than its
* context. */
int64_t depth = 0;
/* rad_kv_group_zero: this rank keeps no cache for the group. The plan keeps its position and
* block count (one block table serves every rank); its costs are zero and nothing is carved.
* No op on this rank names it (issue refuses a group with no pool bound). */
bool zero = false;
/* An indexer-style group a decode step reads over the whole live history, so it cannot
* stream (kvstream/carve.h). When a sibling streams, its carve is a floor of max_seqs full
* contexts, not the split's shared token count. */
bool dense_read = false;
/* rad_kv_group_replicated: every rank holds the same bytes, so a tier slot carries this
* group once, in a window at its front that rank 0 writes and every rank reads
* (TierExec::slot_layout). The pool is carved as for any group. */
@@ -147,13 +172,21 @@ struct KVGroupPlan {
bool paged() const { return kind == RAD_KV_FULL || kind == RAD_KV_WINDOW; }
bool stateful() const { return kind == RAD_KV_LINEAR || kind == RAD_KV_CONV; }
/* Blocks of device pool this group owns: `n_slots` for a paged group, which is `n_blocks`
* unless the group streams. The one place the two meanings may be confused is addressing, so
* every carve and every stride goes through here and every allocation and every guard uses
* `n_blocks`. */
int64_t pool_blocks() const { return n_slots > 0 ? n_slots : n_blocks; }
/* The pool holds less than the group addresses: blocks beyond `n_slots` live off the card and
* a residency map decides which are here. */
bool streamed() const { return paged() && n_slots > 0 && n_slots < n_blocks; }
/* The pool is layer-major, as the ABI requires: a RAD_OPK_KV operand carries the layer as its
* offset and resolves to `base + layer * layer_stride` (RadOperand in rad_runtime.h,
* KVPoolBinding in core/runtime/ctx.h), so a kernel gets one base pointer per layer and
* indexes it with the block table and slot mapping.
*
* Layer i owns [base + i*layer_stride, + layer_stride): n_blocks blocks of
* Layer i owns [base + i*layer_stride, + layer_stride): pool_blocks() blocks of
* `bytes_per_block / n_layers` for a paged group, n_states states of
* `bytes_per_state / n_layers` for a stateful one. */
int64_t layer_bytes_per_block() const {
@@ -163,7 +196,8 @@ struct KVGroupPlan {
return n_layers > 0 ? bytes_per_state / n_layers : bytes_per_state;
}
int64_t layer_stride() const {
return paged() ? n_blocks * layer_bytes_per_block() : n_states * layer_bytes_per_state();
return paged() ? pool_blocks() * layer_bytes_per_block()
: n_states * layer_bytes_per_state();
}
};
@@ -224,6 +258,33 @@ public:
* because paged_split is monotone in the budget. */
int64_t pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const;
void cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; }
/* ---------------- KV streaming (kvstream/mirror.h, kvstream/carve.h) ----------------
*
* A streamed group's device pool is a resident window and its blocks' authority is a pinned
* host copy plus a device residency map. The state, the cap and the mirror's life cycle are
* KVStreamStore's, one member of it below; these are the manager's own names for them, so a
* caller (the engine, the tests, core/sched/mem_iface.h) does not need the module's header.
* See kvstream/mirror.h for what each one promises. */
using StreamMap = RadKVStream; /* the ABI's view: the mirror and the ring's maps */
using StreamCost = KVStreamCost;
using StreamStats = KVStreamStats;
void cap_resident_tokens(int32_t group, int64_t tokens) { stream_.cap(group, tokens); }
void set_stream_map(int32_t group, const StreamMap& m) { stream_.set_map(group, m); }
const StreamMap* stream_map(int32_t group) const { return stream_.map(group); }
const RadKVStream* stream_view(int32_t group) const {
return stream_.view(plan(group), group);
}
StreamCost stream_cost() const { return stream_.cost(plans_, max_ctx_, max_seqs_); }
int alloc_stream(MemAllocator& host_alloc, Pool& kv_pool) {
return stream_.alloc(plans_, max_ctx_, max_seqs_, host_alloc, kv_pool);
}
int init_stream(RadStream s) { return stream_.init(plans_, s); }
void free_stream(MemAllocator& host_alloc) { stream_.release(host_alloc); }
StreamStats stream_stats() const { return stream_.stats(plans_); }
void note_stream_traffic(int64_t misses, int64_t bytes) {
stream_.note_traffic(misses, bytes);
}
int carve(Pool& kv_pool);
const std::vector<KVGroupPlan>& plans() const { return plans_; }
@@ -368,6 +429,13 @@ public:
/* The carve: the range every block id is addressed against. live_blocks() is what the cache
* keeps unlent. */
int64_t total_blocks(int32_t group) const;
/* One past the highest held block, rounded up to a `held_hist_` bucket (0 on a group with
* nothing held). Every id a sequence's block table can name is held, so this is an UPPER bound
* on those ids -- what a streamed group's prefill stage copies its mirror row up to
* (kvstream/stage.h). It counts blocks the prefix cache or another sequence holds too, so it
* is exact only while one request is live; the alternative, a scan of the block tables per
* layer, is the one thing the stage cannot afford. */
int64_t held_top_blocks(int32_t group) const;
int64_t free_states(int32_t group) const;
/* Pool size in bytes, the only unit in which groups can be summed: paged and stateful groups
@@ -622,6 +690,12 @@ private:
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 */
/* KV streaming's state, by group handle: the resident window cap, the mirror and the ring's
* maps, and the resolve's counters (kvstream/mirror.h). Empty and zero on a manager that does
* not stream, which is every group on a server without --kv-resident and also a group whose
* ring covers its context. */
KVStreamStore stream_;
/* declare_runtime_window(): group -> W. Survives forget(), which plan_groups() calls at its
* start: it is a declaration about the program, not about a plan. */
std::unordered_map<int32_t, int64_t> runtime_decl_;
+9
View File
@@ -239,6 +239,15 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
cfg.vram_weights_mib = to_mib_up(b.weights);
const int64_t w_over = cfg.vram_weights_mib * kMiB - b.weights;
cfg.vram_kv_mib = to_mib(std::max<int64_t>(b.kv - w_over, 0));
/* A streamed plan's maps are charged inside kv_one but reserved outside the paged split, so
* the MiB truncation here leaves the pool a whole map short of the one conversation kv_one was
* sized for -- the target shape's indexer then caps at 47 185 of its 51 200 blocks. kv_one is a
* requirement in that case, not a target: round it back up. Only the streamed arms are held to
* it; without streaming this is the pre-existing 1 MiB truncation (204 648 for 204 800), which
* is a separate issue and not this feature's. */
if (cfg.kv_streams && kv_one > 0 &&
b.kv >= kv_one && cfg.vram_kv_mib * kMiB < kv_one)
cfg.vram_kv_mib = to_mib_up(kv_one);
/* A cache given its whole ceiling is rounded up to cover it, out of the headroom as the
* weights' MiB is: truncated, a ceiling under a MiB would be an empty pool and one just over a
* whole MiB a pool short of its own context. */
+17
View File
@@ -289,6 +289,10 @@ struct KVGroupInfo {
int64_t bytes_per_state = 0; /* linear/conv: per sequence */
std::vector<int> layers;
bool zero = false; /* rad_kv_group_zero: declared for position, nothing carved */
/* rad_kv_group_dense_read: read over the whole live history every step (an indexer's block
* keys), so it cannot stream and its pool must hold every sequence's context while a group
* does stream. False on every other group. */
bool dense_read = false;
bool replicated = false; /* rad_kv_group_replicated: the same bytes on every rank */
/* Bound only at meta.n_layers and above: the drafter's own cache, which no trunk layer reads.
* Set at declare (Builder::finish_kv_groups). */
@@ -819,6 +823,19 @@ struct Config {
* accepted in e4m3 (RadBuildCtx::attn_prefill_fp8). Lossy, so off is the default.
* attn_prefill_fp8_name() spells it as the flag does. */
int attn_prefill_fp8 = 0;
/* --kv-resident N: the whole switch (docs/KV-STREAMING.md §5 Phase 4). It is the tokens of
* the sparse attention group's context its VRAM ring holds; absent or 0 and nothing streams,
* which is the base engine. A ring that covers the group's context (`max_seqs x max_ctx`)
* streams nothing either -- the group stays a plain resident pool, no mirror, no maps, no
* stage, no resolve -- so a configuration that fits pays nothing. Below the context, the ring
* must hold one decode step's whole selection, and anything smaller is refused at startup. */
int64_t kv_resident = 0;
/* Derived, never a flag: whether this run configuration streams a group at all. Set where the
* budget probe is capped (kvstream_cap_probe), before the pool is sized, because a streamed
* plan's ceiling is its ring and its one-layer stage rather than the whole cache; the cache's
* MiB rounding reads it. Engine::configure_kv asks the same question of the same numbers and
* must land on the same answer. */
bool kv_streams = false;
int64_t host_pool_mib = 0;
int64_t host_headroom_mib = 4096; /* --host-headroom-mib: RAM left free for the system at startup */
/* File tier for weights: what fits in neither the VRAM slab nor the pinned host pool is read
+8
View File
@@ -4,6 +4,7 @@
#include "mm/processor.h"
#include "derive.h"
#include "device/device.h"
#include "kvstream/bind.h"
#include <algorithm>
#include <cassert>
@@ -233,6 +234,7 @@ int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
for (Out& o : out_) {
o.kv.assign(ranks_.size(), std::vector<RadKVGroupBatch>(s.groups.size()));
o.stream.assign(ranks_.size(), std::vector<RadKVStream>(s.groups.size()));
o.batch.assign(ranks_.size(), RadBatch{});
}
pitch_.assign(s.groups.size(), 1);
@@ -821,6 +823,8 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
a.tlen_off = (const char*)s.d_tlen - d0;
}
/* Each rank's own view of the group's ring and mirror (kvstream/bind.h). */
const RadKVStream* sv = kv.stream_view((int32_t)gi);
for (size_t r = 0; r < ranks_.size(); ++r) {
void* base = s.dev[r];
RadKVGroupBatch& b = o.kv[r][gi];
@@ -833,6 +837,10 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
b.state_index_pitch = g.sidx_pitch;
b.block_size = L.block_size;
b.max_blocks = pitch;
b.stream = kvstream_step_view(&o.stream[r][gi],
ranks_[r].kv_streams ? ranks_[r].kv_streams[gi] : sv,
ranks_[r].kv_streams != nullptr,
ranks_[0].kv_base, ranks_[r].kv_base);
/* The group's arrays are uploaded with the rest of the slab in build(). */
}
+14
View File
@@ -105,6 +105,16 @@ public:
int device = 0;
RadStream stream = nullptr;
Program* prog = nullptr;
/* This rank's KV pool base, the origin the streamed group's device maps are rebased
* from (see build_groups). Rank 0's is the basis the manager's stream_view names. */
void* kv_base = nullptr;
/* This rank's block manager. A streamed group's view must come from it, not from rank
* 0's: the device maps live in that rank's pool and the host mirror is that rank's pinned
* allocation. Sharing rank 0's host mirror let two ranks write different KV shards into
* the same bytes. The array is per group and owned by the engine; it is a pointer array,
* not the manager, so a test that drives the builder without a device does not link the
* real manager and its backend. */
const RadKVStream* const* kv_streams = nullptr;
};
/* `prog` is non-const because derived buffers are written into its arena, whose pointer lands
@@ -242,6 +252,10 @@ private:
static constexpr int kOut = RAD_SCHED_MAX_SPEC + 4;
struct Out {
std::vector<std::vector<RadKVGroupBatch>> kv;
/* Per rank and group, the RadKVStream a batch names. The view is not in the slab: its
* device pointers are rebased into that rank's KV pool, and its host mirror is shared,
* so each rank needs its own copy of the struct to point at. */
std::vector<std::vector<RadKVStream>> stream;
std::vector<RadBatch> batch;
};
+22
View File
@@ -94,6 +94,10 @@ struct IKVManager {
/* Blocks held by anything, as opposed to free_blocks (what can be handed out now). On an
* elastic pool they differ by what the cache released (KVManager::held_blocks). */
virtual int64_t held_blocks(int32_t group) const = 0;
/* One past the highest block id any held table can name (KVManager::held_top_blocks), the
* sound bound for the stage's live-row copy (kvstream/stage.h). A manager that cannot answer
* says "the whole row". */
virtual int64_t held_top_blocks(int32_t group) const { (void)group; return INT64_MAX; }
/* The pool in bytes, the only unit that sums across groups. Asked of the manager because its
* plan knows whether a group counts blocks or states. */
@@ -102,6 +106,17 @@ struct IKVManager {
/* What the carve gave the group; an elastic pool may have released part of it. */
virtual int64_t pool_bytes_carved(int32_t group) const = 0;
/* A streamed group's ring, residency map and host mirror as the step batch hands them to a
* plugin (RadKVStream), or null for a group that is fully resident. The addresses are fixed at
* bring-up, so the batch builder copies the pointer into every step's batch and a recorded
* pass keyed by it replays. The default is null: a manager with no streaming has none. */
virtual const RadKVStream* stream_view(int32_t group) const { (void)group; return nullptr; }
/* The resolve's cumulative traffic and the ring's depth, for the metrics. Zero and empty on a
* server that does not stream. */
virtual int64_t stream_misses() const { return 0; }
virtual int64_t stream_bytes_in() const { return 0; }
virtual int64_t stream_resident_blocks() const { return 0; }
/* Tokens one block covers, or 0 for a stateful group. */
virtual int64_t block_tokens(int32_t group) const = 0;
@@ -326,9 +341,16 @@ struct KVBinding final : IKVManager {
int64_t free_blocks(int32_t g) const override { return m->free_blocks(g); }
int64_t total_blocks(int32_t g) const override { return m->total_blocks(g); }
int64_t held_blocks(int32_t g) const override { return m->held_blocks(g); }
int64_t held_top_blocks(int32_t g) const override { return m->held_top_blocks(g); }
int64_t pool_bytes(int32_t g) const override { return m->pool_bytes(g); }
int64_t pool_bytes_used(int32_t g) const override { return m->pool_bytes_used(g); }
int64_t pool_bytes_carved(int32_t g) const override { return m->pool_bytes_carved(g); }
const RadKVStream* stream_view(int32_t g) const override { return m->stream_view(g); }
int64_t stream_misses() const override { return (int64_t)m->stream_stats().misses; }
int64_t stream_bytes_in() const override { return (int64_t)m->stream_stats().bytes_in; }
int64_t stream_resident_blocks() const override {
return m->stream_stats().resident_blocks;
}
int64_t block_tokens(int32_t g) const override {
const KVGroupPlan* p = m->plan(g);
return p && p->paged() ? p->block_size : 0;
+6
View File
@@ -77,6 +77,12 @@ struct SchedMetrics {
* difference is the VRAM the elastic pool released behind unheld blocks. */
int64_t bytes_carved = 0;
} kv[RAD_SCHED_MAX_KV_GROUPS];
/* KV streaming (docs/KV-STREAMING.md §4.2): the ring's depth over every streamed group, and
* the resolve's cumulative misses and bytes copied in from the pinned host mirror. All zero
* unless a group's pool is a resident window rather than its whole context. */
int64_t kv_resident_blocks = 0;
int64_t kv_stream_misses = 0;
int64_t kv_stream_bytes_in = 0;
/* Prefix caching (§7.3). Attention and linear are reported separately because they hit at
* different granularities. */
+64 -2
View File
@@ -474,6 +474,7 @@ void Scheduler::trim_prefix_cache() {
void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free,
bool publish, int status, const char* why) {
++step_finished_;
/* Publish before freeing: this is the only moment the whole prefix is both computed and still
* owned. insert() takes its own KV references, so the blocks survive the free below. Cancelled
* and failed requests are published too; their prompts were computed, and a client that hangs
@@ -554,6 +555,47 @@ void Scheduler::reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_
++m_.checkpoints_written;
}
int Scheduler::fail_prefilling(const char* why) {
std::lock_guard<std::mutex> lk(mu_);
/* Stable for the client: the sink keeps this pointer past the call (Sink::why_). */
stream_why_ = why ? why : "kv streaming overflow";
why = stream_why_.c_str();
int n = 0;
/* The step just committed named these; when it produced no token row (a middle prefill chunk
* issues none) no list was filled, and every request still laying down its prompt is the set
* whose next chunk would read the failed table. */
const bool by_step = !last_prefill_ids_.empty();
auto fail = [&](SchedReq& s) {
if (s.req->state != ReqState::Running && s.req->state != ReqState::Preempted &&
s.req->state != ReqState::Waiting)
return;
/* The next step may already be issued (a decode row of a request whose prompt just
* finished), so its blocks stay until that step's commit frees them -- the same rule
* cancel() uses for a request in flight. */
const bool in_flight = in_step(s) || block_holds(s.req->id);
/* RAD_E_FULL, not RAD_E_STATE: the ring is a pool that ran out, and RAD_E_STATE
* stringifies as "called in the wrong phase", which would follow the real message. */
close_request(s, ReqState::Failed, "kv_stream_overflow", in_flight,
/*publish=*/false, RAD_E_FULL, why);
++n;
};
if (by_step) {
for (uint64_t id : last_prefill_ids_) {
auto it = by_id_.find(id);
if (it != by_id_.end()) fail(*reqs_[(size_t)it->second]);
}
} else {
std::vector<int32_t> live(running_);
live.insert(live.end(), waiting_.begin(), waiting_.end());
for (int32_t slot : live) {
if (slot < 0 || (size_t)slot >= reqs_.size() || !reqs_[(size_t)slot]) continue;
SchedReq& s = *reqs_[(size_t)slot];
if ((int64_t)s.req->n_computed < (int64_t)s.req->prompt.size()) fail(s);
}
}
return n;
}
int Scheduler::cancel(uint64_t id) {
std::lock_guard<std::mutex> lk(mu_);
auto it = by_id_.find(id);
@@ -1927,9 +1969,12 @@ void Scheduler::promote_next() {
}
/* ------------------------------------------------------------------ commit */
int Scheduler::commit(const StepResult& res) {
int Scheduler::commit(StepResult& res) {
std::lock_guard<std::mutex> lk(mu_);
if (!step_open_) return RAD_E_STATE;
/* The engine's reports describe this step only (StepResult::n_prefill_done, n_finished). */
step_finished_ = 0;
last_prefill_ids_.clear();
if (res.n_seq != (int)plan_.e.size()) {
RAD_ERR("commit of %d sequences against a step of %d", res.n_seq, (int)plan_.e.size());
return RAD_E_INVAL;
@@ -1992,8 +2037,12 @@ int Scheduler::commit(const StepResult& res) {
r.n_cached);
/* Once, when the prompt is fully placed: the usage block's admission accounting.
* `n_cached` is what the prefix cache supplied. */
if (r.n_computed >= (int64_t)r.prompt.size())
if (r.n_computed >= (int64_t)r.prompt.size()) {
server::sink_prompt_stats(r.sink, (int32_t)r.prompt.size(), r.n_cached);
/* The prompt is fully placed: the point past which a decode step reads the ring,
* and the point at which the engine checks a streamed resolve's overflow. */
last_prefill_ids_.push_back(r.id);
}
if (e.produces_token && res.token && r.embed) {
/* The answer is the pooled vector the engine already put in the sink; there is
* no token to emit, and `eos` ends the request below. */
@@ -2130,6 +2179,8 @@ int Scheduler::commit(const StepResult& res) {
* block_end() / serial_end() has since cleared, can be released: every pass naming them was
* issued before this step's readback, which waited for the compute stream. */
sweep_deferred();
res.n_prefill_done = (int)last_prefill_ids_.size();
res.n_finished = step_finished_;
return RAD_OK;
}
@@ -2344,6 +2395,11 @@ const RadBatch* Scheduler::serial_batch(int round, int step) {
serial_plan_.reset();
serial_plan_.phase = RAD_PHASE_DECODE;
/* The deployment's speculative window, though no entry of a draft pass verifies: the history
* pass redoes up to 1 + n_spec verified positions a sequence, and a prefill chunk's history is
* wider. Its KV view is chosen from that shape (kvstream/bind.cpp), so the batch must carry the
* window the ceiling was built from. */
serial_plan_.n_spec = cfg_.n_spec > 0 ? cfg_.n_spec : 0;
/* Negative is the history pass; positive is draft round r. The sign is what the plugin reads
* to decide whether the pass ends in the lm_head (rad_runtime.h). */
serial_plan_.draft_pass = round == 0 ? -1 : round;
@@ -2778,6 +2834,12 @@ SchedMetrics Scheduler::metrics_locked() const {
m.kv[i].bytes_used = kv_->pool_bytes_used(i);
m.kv[i].bytes_carved = kv_->pool_bytes_carved(i);
}
/* Streaming's totals beside the per-group rows: the ring's depth is geometry, the misses and
* bytes are what resolve launches have moved, so all three read zero on a server whose groups
* are fully resident. */
m.kv_resident_blocks = kv_->stream_resident_blocks();
m.kv_stream_misses = kv_->stream_misses();
m.kv_stream_bytes_in = kv_->stream_bytes_in();
if (pc_) { m.prefix_evictions = pc_->evictions();
m.prefix_ckpt_evictions = pc_->ckpt_evictions();
+25 -2
View File
@@ -128,11 +128,18 @@ class Scheduler {
public:
/* What the sampler hands back after a step: per sequence, how many drafts survived, the token
* sampled at the accepted position, and whether the sequence ended. No logits. */
/* The step's outcome, for the engine's reports. Both count what this step did, so a report
* line can say "the prompt completed here" or "a request ended here" without reading internal
* queues: `n_prefill_done` counts entries whose prompt was fully placed in this step (the
* point after which a decode step reads the ring), `n_finished` counts requests that reached a
* terminal state during it. */
struct StepResult {
int n_seq = 0;
const int32_t* n_accepted = nullptr; /* [n_seq] drafted tokens accepted, 0..n_spec */
const int32_t* token = nullptr; /* [n_seq] token sampled at the accepted position */
const uint8_t* eos = nullptr; /* [n_seq] 1 when the sequence ended */
int n_prefill_done = 0;
int n_finished = 0;
/* Logprobs, null on a step where no request asked: entry i's j-th emitted token (its
* accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */
const TokenLogprobs* lp = nullptr;
@@ -176,6 +183,12 @@ public:
* under exactly the load that cancels. */
int cancel(uint64_t id);
Request* find(uint64_t id);
/* Fail every request that was prefilling in the step just committed, with `why` reaching the
* client. The engine calls this when a streamed group's resolve latched overflow: those
* requests' selections are the ones whose ring placement failed, so their attention reads from
* a table that no longer addresses the pool. Failing them is the only honest outcome; it never
* serves a step from a half-resident selection (docs/KV-STREAMING.md §3.4). */
int fail_prefilling(const char* why);
/* Whether the request is still admitted and Running, read under the lock. */
bool running(uint64_t id) const;
/* What the step just committed left for `seq`, copied by commit under the lock. False when
@@ -309,8 +322,9 @@ public:
const RadBatch* step_next_locked();
void promote_next();
/* Fold the step's outcome back in: append tokens, roll back rejected speculation, retire
* finished requests, feed the draft controller. */
int commit(const StepResult& r);
* finished requests, feed the draft controller, and fill `r`'s report counts
* (n_prefill_done, n_finished). */
int commit(StepResult& r);
/* Ends the step for timing; call once per loop iteration that ran a step, after the drafter,
* so the draft rounds are charged to the step (see the definition). Without it the counters
* stay correct but there is no timing. */
@@ -553,6 +567,11 @@ private:
std::vector<int32_t> running_;
std::vector<int32_t> waiting_;
std::vector<uint64_t> completed_;
/* What the step being committed did for the engine's reports (StepResult::n_prefill_done,
* n_finished): the prefill entries' request ids, and the terminal count. Reset at the start of
* every commit, so nothing is carried across steps. */
std::vector<uint64_t> last_prefill_ids_;
int step_finished_ = 0;
/* Requests whose release waits on something that still refers to them (a deferred reap or a
* deferred free). A count, so the sweeps cost nothing on the steps where there are none. */
@@ -577,6 +596,10 @@ private:
* lives here). See add_locked. */
int64_t pool_tokens_ = -1;
std::string pool_refusal_;
/* The message fail_prefilling() sends to a streamed request's client. A sink keeps the pointer
* until the HTTP thread writes the error, so it cannot be a temporary (Sink::why_); the same
* reason pool_refusal_ lives here. */
std::string stream_why_;
/* Scratch for a prefix-cache hit's block ids, one row per cached group. Reserved at init so
* an admission does not reach the allocator. */
+6
View File
@@ -87,6 +87,12 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) {
if (o.kv_tokens_max == 0 || t < o.kv_tokens_max) o.kv_tokens_max = t;
}
/* KV streaming's totals pass through unchanged: none of them is a per-group figure the
* binding rule above applies to. */
o.kv_resident_blocks = m.kv_resident_blocks;
o.kv_stream_misses = m.kv_stream_misses;
o.kv_stream_bytes_in = m.kv_stream_bytes_in;
/* vLLM's gpu_prefix_cache_hit_rate means attention caching. The linear-checkpoint hit
* rate has a different granularity (spec §7.3) and is reported separately, not averaged
* in. */
+6
View File
@@ -60,6 +60,12 @@ struct SchedMetrics {
* expert slab (`kv_bytes_carved` in bytes). The smallest over the paged groups, which share
* one token axis; windowed groups are excluded, since their carve bounds lookback, not fit. */
int64_t kv_tokens_max = 0;
/* KV streaming (docs/KV-STREAMING.md §4.2): the ring's depth over every streamed group, and
* the resolve's cumulative misses and bytes copied in from the host mirror. All zero unless a
* group's pool is a resident window rather than its whole context. */
int64_t kv_resident_blocks = 0;
int64_t kv_stream_misses = 0;
int64_t kv_stream_bytes_in = 0;
double prefix_hit_rate = 0.0; /* 0..1 */
/* Cumulative prefix-cache evictions. They rise as reusable prefixes are dropped, while
+21
View File
@@ -136,6 +136,7 @@ void Metrics::sample(const SchedMetrics& m) {
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_kv_resident_blocks_.set((double)m.kv_resident_blocks);
g_prefix_hit_.set(m.prefix_hit_rate);
g_prefill_tps_.set(m.prefill_tps);
g_decode_tps_.set(m.decode_tps);
@@ -200,6 +201,8 @@ void Metrics::sample(const SchedMetrics& m) {
c_cut_resumed_below_.advance_to(m.hit_cut_resumed_below);
c_restore_cuts_.advance_to(m.prefix_restore_cuts);
c_cut_tokens_.advance_to(m.hit_cut_tokens);
c_kv_stream_misses_.advance_to((double)m.kv_stream_misses);
c_kv_stream_bytes_.advance_to((double)m.kv_stream_bytes_in);
g_linear_hit_.set(m.linear_hit_rate);
}
@@ -281,6 +284,24 @@ std::string Metrics::render() const {
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());
/* KV streaming (docs/KV-STREAMING.md §4.2): the ring's depth over every streamed group, and
* what the resolve has moved into it. All zero on a server whose groups are fully resident. */
w.gauge("radiance:kv_resident_blocks",
"Blocks of every streamed KV group the device ring holds; 0 when no group streams.",
L, g_kv_resident_blocks_.get());
w.counter("radiance:kv_stream_misses_total",
"Blocks copied into a streamed KV group's ring from the host mirror.",
L, c_kv_stream_misses_.get());
/* Split by direction, as the host tier may later gain a write-back: only `in` exists today,
* the misses' copy from the mirror into the ring. The label is spelled the way the design
* note does so a dashboard can ask for both from the start. */
w.help("radiance:kv_stream_bytes_total",
"Bytes a streamed KV group's resolve moved, by direction.", "counter");
w.out += "radiance:kv_stream_bytes_total";
w.out += L.substr(0, L.size() - 1);
w.out += ",dir=\"in\"} ";
w.out += num(c_kv_stream_bytes_.get());
w.out += '\n';
w.gauge("vllm:gpu_prefix_cache_hit_rate",
"GPU prefix cache block hit rate.", L, g_prefix_hit_.get());
+4 -1
View File
@@ -111,7 +111,10 @@ 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_kv_max_tokens_, g_kv_max_bytes_, g_kv_resident_blocks_;
/* KV streaming: blocks copied into a streamed group's ring, and the bytes they carried, both
* cumulative and both zero unless a group's pool is a resident window. */
Counter c_kv_stream_misses_, c_kv_stream_bytes_;
Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_;
/* The decode floor in seconds: the fastest and the most recent single-sequence window. 0
* until a window completes, and render() omits a 0. */
+14
View File
@@ -18,6 +18,7 @@ ABI_FIELD(RadArchProbe, gen_ctx)
ABI_FIELD(RadArchProbe, gen_video)
ABI_FIELD(RadArchProbe, kv_quant_ok)
ABI_FIELD(RadArchProbe, chain_pays)
ABI_FIELD(RadArchProbe, kv_stream_ok)
ABI_FIELD(RadArchProbe, control_vector_ok)
ABI_FIELD(RadArchProbe, tp_attn_rows_ok)
ABI_FIELD(RadArchProbe, state_f16_ok)
@@ -109,6 +110,8 @@ ABI_FIELD(RadBuildCtx, max_audio_frames)
ABI_FIELD(RadBuildCtx, max_mixed_tok)
ABI_FIELD(RadBuildCtx, kv_quant)
ABI_FIELD(RadBuildCtx, attn_prefill_fp8)
ABI_FIELD(RadBuildCtx, kv_resident_blocks)
ABI_FIELD(RadBuildCtx, kv_stream_ok)
ABI_FIELD(RadBuildCtx, cvec)
ABI_FIELD(RadBuildCtx, tp_attn_rows)
ABI_FIELD(RadBuildCtx, state_dtype)
@@ -476,6 +479,7 @@ ABI_FIELD(RadKVGroupBatch, state_index)
ABI_FIELD(RadKVGroupBatch, state_index_pitch)
ABI_FIELD(RadKVGroupBatch, block_size)
ABI_FIELD(RadKVGroupBatch, max_blocks)
ABI_FIELD(RadKVGroupBatch, stream)
ABI_STRUCT(RadKVGroupDecl)
ABI_FIELD(RadKVGroupDecl, kind)
ABI_FIELD(RadKVGroupDecl, dtype)
@@ -484,6 +488,16 @@ ABI_FIELD(RadKVGroupDecl, n_head_kv)
ABI_FIELD(RadKVGroupDecl, head_dim)
ABI_FIELD(RadKVGroupDecl, state_dim)
ABI_FIELD(RadKVGroupDecl, conv_width)
ABI_STRUCT(RadKVStream)
ABI_FIELD(RadKVStream, host)
ABI_FIELD(RadKVStream, res)
ABI_FIELD(RadKVStream, slot_block)
ABI_FIELD(RadKVStream, slot_state)
ABI_FIELD(RadKVStream, ctl)
ABI_FIELD(RadKVStream, block_bytes)
ABI_FIELD(RadKVStream, host_layer_stride)
ABI_FIELD(RadKVStream, slots)
ABI_FIELD(RadKVStream, host_bytes)
ABI_STRUCT(RadKernelInfo)
ABI_FIELD(RadKernelInfo, name)
ABI_FIELD(RadKernelInfo, op)
+23 -9
View File
@@ -1,4 +1,4 @@
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 27 and
/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 30 and
* RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot
* of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it
* from the test's printout only together with a version bump. */
@@ -15,9 +15,10 @@
{ "RadArchProbe", "gen_video", 64, 4 },
{ "RadArchProbe", "kv_quant_ok", 68, 4 },
{ "RadArchProbe", "chain_pays", 72, 4 },
{ "RadArchProbe", "control_vector_ok", 76, 4 },
{ "RadArchProbe", "tp_attn_rows_ok", 80, 4 },
{ "RadArchProbe", "state_f16_ok", 84, 4 },
{ "RadArchProbe", "kv_stream_ok", 76, 4 },
{ "RadArchProbe", "control_vector_ok", 80, 4 },
{ "RadArchProbe", "tp_attn_rows_ok", 84, 4 },
{ "RadArchProbe", "state_f16_ok", 88, 4 },
{ "RadArgs", "", 0, 64 },
{ "RadArgs", "t", 0, 8 },
{ "RadArgs", "n_t", 8, 4 },
@@ -106,10 +107,12 @@
{ "RadBuildCtx", "max_mixed_tok", 96, 8 },
{ "RadBuildCtx", "kv_quant", 104, 4 },
{ "RadBuildCtx", "attn_prefill_fp8", 108, 4 },
{ "RadBuildCtx", "cvec", 112, 8 },
{ "RadBuildCtx", "tp_attn_rows", 120, 4 },
{ "RadBuildCtx", "state_dtype", 124, 4 },
{ "RadBuildCtx", "draft_coupling", 128, 4 },
{ "RadBuildCtx", "kv_resident_blocks", 112, 8 },
{ "RadBuildCtx", "kv_stream_ok", 120, 4 },
{ "RadBuildCtx", "cvec", 128, 8 },
{ "RadBuildCtx", "tp_attn_rows", 136, 4 },
{ "RadBuildCtx", "state_dtype", 140, 4 },
{ "RadBuildCtx", "draft_coupling", 144, 4 },
{ "RadAudioGenBatch", "", 0, 344 },
{ "RadAudioGenBatch", "n_lane", 0, 8 },
{ "RadAudioGenBatch", "lane", 8, 8 },
@@ -463,7 +466,7 @@
{ "RadGeneratorDecl", "chunk_bos", 364, 4 },
{ "RadGeneratorDecl", "chunk_eos", 368, 4 },
{ "RadGeneratorDecl", "cond_opts", 372, 4 },
{ "RadKVGroupBatch", "", 0, 72 },
{ "RadKVGroupBatch", "", 0, 80 },
{ "RadKVGroupBatch", "group", 0, 4 },
{ "RadKVGroupBatch", "slot_mapping", 8, 8 },
{ "RadKVGroupBatch", "block_table", 16, 8 },
@@ -473,6 +476,7 @@
{ "RadKVGroupBatch", "state_index_pitch", 48, 8 },
{ "RadKVGroupBatch", "block_size", 56, 8 },
{ "RadKVGroupBatch", "max_blocks", 64, 8 },
{ "RadKVGroupBatch", "stream", 72, 8 },
{ "RadKVGroupDecl", "", 0, 56 },
{ "RadKVGroupDecl", "kind", 0, 4 },
{ "RadKVGroupDecl", "dtype", 4, 4 },
@@ -481,6 +485,16 @@
{ "RadKVGroupDecl", "head_dim", 24, 8 },
{ "RadKVGroupDecl", "state_dim", 32, 16 },
{ "RadKVGroupDecl", "conv_width", 48, 8 },
{ "RadKVStream", "", 0, 72 },
{ "RadKVStream", "host", 0, 8 },
{ "RadKVStream", "res", 8, 8 },
{ "RadKVStream", "slot_block", 16, 8 },
{ "RadKVStream", "slot_state", 24, 8 },
{ "RadKVStream", "ctl", 32, 8 },
{ "RadKVStream", "block_bytes", 40, 8 },
{ "RadKVStream", "host_layer_stride", 48, 8 },
{ "RadKVStream", "slots", 56, 8 },
{ "RadKVStream", "host_bytes", 64, 8 },
{ "RadKernelInfo", "", 0, 168 },
{ "RadKernelInfo", "name", 0, 8 },
{ "RadKernelInfo", "op", 8, 8 },
+3 -3
View File
@@ -8,7 +8,7 @@
*
* Checked: a C translation unit (abi_c_test.c, strict C11) lays every struct out as C++ does; every
* struct's listed fields account for its size, so the list in abi_layout_rows.h is complete; and
* the layout agrees with the table below, taken at RAD_ABI_VERSION 27 and RAD_FORMAT_VER 2. Under
* the layout agrees with the table below, taken at RAD_ABI_VERSION 30 and RAD_FORMAT_VER 2. Under
* those versions a listed field may not move or change size, an ABI struct may only grow by fields
* past its old end, and an on-disk struct may not change at all. The table is a snapshot of the
* headers: nothing else states the layout. When it disagrees the test prints the live table.
@@ -58,8 +58,8 @@ std::vector<Row> cpp_rows() {
};
}
/* The layout at RAD_ABI_VERSION 27 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 27, kTableFormat = 2;
/* The layout at RAD_ABI_VERSION 30 / RAD_FORMAT_VER 2 (see the file header). */
constexpr uint32_t kTableAbi = 30, kTableFormat = 2;
const AbiRow kTable[] = {
#include "abi_layout_table.h"
};
+24
View File
@@ -429,6 +429,7 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
{ "--max-model-len", { "4096" } }, { "--rope-scaling", { "yarn:4" } },
{ "--gpu-headroom-mib", { "128" } }, { "--kv-cache-dtype", { "fp8" } },
{ "--state-cache-dtype", { "f16" } }, { "--attn-prefill-fp8", { "both" } },
{ "--kv-resident", { "65536" } },
{ "--host-pool-mib", { "1024" } }, { "--host-headroom-mib", { "2048" } },
{ "--embedding-placement", { "vram" } },
{ "--vision-tower-placement", { "ram" } }, { "--ngram-placement", { "disk" } },
@@ -726,6 +727,29 @@ TEST(the_kv_cache_dtype_is_one_of_four_names) {
CHECK_EQ(d.kv_cache_dtype, std::string("bf16"));
}
/* --kv-resident is the whole switch: absent or 0 and nothing streams, and it is whole tokens
* rounded up to the group's page at startup. The mode flag is gone, and a launch line that still
* passes it is refused by name rather than silently served without streaming. */
TEST(kv_resident_is_the_whole_switch_and_its_ring_is_whole_tokens) {
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK_EQ(d.kv_resident, 0ll); /* nothing streams */
CHECK(!d.kv_streams); /* derived: no group streams either */
for (const char* old : { "auto", "on", "off", "measure" }) {
Config c;
int st = RAD_OK;
const std::string log = stderr_of([&] { st = parse({ "--kv-streaming", old }, &c); });
CHECK_EQ(st, (int)RAD_E_INVAL);
CHECK(has(log, "--kv-resident")); /* the message names the replacement */
}
Config c;
CHECK_EQ(parse({ "--kv-resident", "262144" }, &c), RAD_OK);
CHECK_EQ(c.kv_resident, 262144ll);
CHECK_EQ(parse({ "--kv-resident", "0" }, &c), RAD_OK);
CHECK_EQ(c.kv_resident, 0ll);
CHECK_EQ(parse({ "--kv-resident", "-1" }, &c), RAD_E_INVAL);
}
/* The embedding takes ram (default) or vram; the n-gram table takes auto (default), vram, ram or
* disk. The parser records whether the embedding placement was named and leaves resolution to
* Engine::plan, which can refuse a placement with the model in hand. */
+194
View File
@@ -18,6 +18,9 @@
#include "runtime/ctx.h"
#include "runtime/kvbind.h"
#include "mem/kv.h"
#include "kvstream/bind.h"
#include "kvstream/plan.h"
#include "kvstream/stage.h"
#include "runtime/rank_barrier.h"
#include "runtime/residency.h"
#include "runtime/wtab.h"
@@ -1676,6 +1679,9 @@ TEST(too_many_operands_or_an_unknown_handle_is_refused) {
/* ================================================================== KV operands */
namespace {
alignas(64) uint16_t g_kv_pool[4 * 2048];
/* One layer of a 13-layer group's context: [8 blocks, 2 heads, 4 tokens, 2*4] fp8 = 512 B. A
* prefill pool for a streamed group is this deep, not 13 of these. */
alignas(64) uint8_t g_alias_pool[8 * 2 * 4 * 2 * 4];
/* Group 1: full attention over layers 3, 7 and 11, rank 4. Group 2: a conv state, rank 3, over
* layer 0. Group 0 is the sentinel every handle table carries, with no pool. */
@@ -1782,6 +1788,133 @@ TEST(kv_pools_bind_each_layer_to_its_place_in_the_group) {
CHECK_EQ(b[3].layer_slot[2], 0);
}
/* A streamed group's prefill pool is ONE layer deep and every layer of the group addresses it.
*
* Above `qsa_exact_to` one prefill launch selects 70-100% of the live history (docs/KV-STREAMING.md
* §3.5), so a decode-sized ring overflows and the prefill path stages one layer's history into an
* identity-layout buffer instead. Layer L is staged into that buffer, read, and then overwritten by
* layer L+1, so the buffer is one layer deep rather than `n_layers` deep: 128 MiB at 262K fp8 on
* two ranks, against 1.66 GiB.
*
* The operand resolution accepts it, and the depth is the whole arithmetic: `layer_slot` is a
* lookup and the only bound is `off + layer_stride <= bytes` (runtime/issue.cpp:781-789), which a
* one-layer-deep pool satisfies at `off == 0` for every layer. This case pins that, pins that an
* identity table over the same pool is refused (so the depth is not silently tolerated), and pins
* the two facts that make aliasing a *binding* change rather than a hand-built layer table: the
* same table is the host mirror's row (`rad_kv_layer_index`, arch/common/rad_arch.h:1028-1032), so
* mapping every layer to 0 collapses the mirror; and bind_kv_pools derives the table from each
* layer's position in the group, so an aliased table cannot come from it. */
TEST(a_streamed_groups_layers_may_all_alias_one_pool_slot) {
const int64_t n_blocks = 8, heads = 2, block = 4, hd = 4;
const int64_t lbpb = heads * block * 2 * hd; /* one block of ONE layer */
const int64_t stride = n_blocks * lbpb; /* one whole layer: the stage's depth */
const int64_t shape[4] = { n_blocks, heads, block, 2 * hd };
const int64_t st[4] = { heads * block * 2 * hd, block * 2 * hd, 2 * hd, 1 };
Fixture f;
f.kv.assign(2, rad::KVPoolBinding{});
rad::KVPoolBinding& alias = f.kv[1];
alias.base = g_alias_pool;
alias.layer_stride = stride;
alias.bytes = stride; /* 13 layers share these bytes */
alias.depth = 1; /* every layer resolves to offset 0 */
alias.dtype = RAD_F8E4M3;
alias.layer_slot.assign(13, 0);
for (int l = 0; l < 13; ++l) alias.layer_slot[(size_t)l] = l; /* the MIRROR row */
alias.rank = 4;
for (int d = 0; d < 4; ++d) alias.shape[d] = shape[d];
rad_op op = loose_op(f, "attn_paged");
CHECK_OK(f.start());
/* The recorder keeps eight operands, so the 13 layers go in two issues. Every layer reads the
* same pool base because `depth` is 1, and the operand's shape follows the stage view. */
for (int first = 0; first < 13; first += 8) {
const int last = first + 8 < 13 ? first + 8 : 13;
std::vector<RadOperand> some;
for (int l = first; l < last; ++l) some.push_back(RAD_KV(1, l));
CHECK_OK(issue_once(f, first, op, some));
REQUIRE_EQ(g_rec.size(), (size_t)1);
REQUIRE_EQ(g_rec[0].n_t, last - first);
for (int l = first; l < last; ++l) {
const RadTensor& t = g_rec[0].t[l - first];
CHECK(t.data == (void*)g_alias_pool);
CHECK_EQ((int)t.rank, 4);
CHECK_EQ((int)t.dtype, (int)RAD_F8E4M3);
for (int d = 0; d < 4; ++d) {
CHECK_EQ(t.shape[d], shape[d]);
CHECK_EQ(t.stride[d], st[d]);
}
}
}
/* The mirror's row comes from the same lookup, which is why aliasing has to be a depth of the
* binding and not a rewritten layer_slot: with depth 1 every layer would read layer 0's mirror
* row. The lookup itself is untouched and still positional. */
for (int l = 0; l < 13; ++l) CHECK_EQ(f.ctx.kv_layer_index(1, l), (int64_t)l);
/* The same one-layer-deep pool with depth 0 is a positional table, and `bytes` is the only
* bound: it serves exactly layer 0 and refuses the rest. This is what makes the aliasing a
* deliberate depth rather than something issue.cpp silently tolerates. */
Fixture g;
g.kv.assign(2, rad::KVPoolBinding{});
g.kv[1] = alias;
g.kv[1].depth = 0;
for (int l = 0; l < 13; ++l) g.kv[1].layer_slot[(size_t)l] = l;
rad_op op_g = loose_op(g, "attn_paged");
CHECK_OK(g.start());
refused(g, issue_once(g, 0, op_g, { RAD_KV(1, 1) }), RAD_E_INVAL, "outside the");
next_step_clean(g, 1, op_g, { RAD_KV(1, 0) });
/* The plan's arithmetic: the ring is n_slots blocks of every layer, the stage is the context
* one layer deep, and the carve is their maximum, never their sum. */
rad::KVGroupPlan p;
p.kind = RAD_KV_FULL;
p.n_layers = 13;
p.n_blocks = n_blocks;
p.n_slots = 2; /* a decode-sized ring, smaller than the context */
p.depth = 1;
p.block_size = block;
p.bytes_per_block = 13 * lbpb;
CHECK_EQ(p.layer_stride(), 2 * lbpb);
CHECK_EQ(p.streamed(), true);
CHECK_EQ(p.n_blocks * p.layer_bytes_per_block(), stride); /* one layer, not 13 */
CHECK_EQ(rad::kv_ring_bytes(p, 2), 2 * 13 * lbpb);
CHECK_EQ(rad::kv_pool_bytes(p), 2 * 13 * lbpb); /* ring wins here */
CHECK_EQ(rad::kv_ceiling_bytes(p, 200, 2), 200 * lbpb); /* stage wins at context */
CHECK_EQ(rad::kv_tier_cached(p), false);
/* The engine's own builder places each bound layer at its position in the group and keeps the
* pool alias a view, so both views are fixed from bring-up and the ring is active first. */
Program P;
P.kv_groups.resize(2);
P.kv_groups[1].decl.kind = RAD_KV_FULL;
P.kv_groups[1].decl.n_head_kv = heads;
P.kv_groups[1].decl.head_dim = hd;
for (int l = 0; l < 13; ++l) P.kv_groups[1].layers.push_back(l);
std::vector<rad::KVGroupPlan> plans(2);
plans[1] = p;
plans[1].base = g_alias_pool;
plans[1].pool_bytes = rad::kv_pool_bytes(p);
std::vector<rad::KVPoolBinding> b;
rad::bind_kv_pools(P, [&](int32_t x) -> const rad::KVGroupPlan* {
return x == 0 ? nullptr : &plans[(size_t)x];
}, &b);
REQUIRE_EQ(b.size(), (size_t)2);
REQUIRE_EQ(b[1].layer_slot.size(), (size_t)13);
for (int l = 0; l < 13; ++l) CHECK_EQ(b[1].layer_slot[(size_t)l], l);
REQUIRE(b[1].has_stage);
CHECK_EQ(b[1].depth, 0); /* the ring is the active view */
CHECK_EQ(b[1].layer_stride, 2 * lbpb);
CHECK_EQ(b[1].shape[0], 2);
CHECK_EQ(b[1].stage.layer_stride, stride);
CHECK_EQ(b[1].stage.shape0, n_blocks);
rad::kv_binding_enter(b[1], rad::KVView::Stage);
CHECK_EQ(b[1].depth, 1);
CHECK_EQ(b[1].layer_stride, stride);
CHECK_EQ(b[1].shape[0], n_blocks);
for (int l = 0; l < 13; ++l) CHECK_EQ(rad::kv_binding_offset(b[1], l), 0);
}
/* ================================================================== arena levels */
/* A level packs the transient buffers for smaller steps at new offsets with smaller shapes; the
* active level decides every buffer's address and the extent an operand is checked against, so a
@@ -2199,6 +2332,67 @@ TEST(the_pass_key_changes_with_the_arena_level) {
CHECK_EQ(f.ctx.pass_key(&b), k0);
}
/* A streamed pass's key names the memory its view reads, not the address of the struct that carries
* it: the batch's view is a copy in a rotating builder Out slot, so keying on `&view` made every
* streamed decode step a pass the tape had never seen, no tape survived the 24-slot LRU, and the
* host walked the whole issue path every step (record §55: 25 ms/step, §56 the fix). Two views
* with the same bytes must agree, a view that hands a kernel different memory must not, and on a
* card the same streamed pass twice must play. The host backend records no tape, so only the key
* is checked there. */
TEST(a_streamed_pass_is_keyed_by_its_view_and_replays) {
Fixture f;
rad_buf x = f.add_buffer("x", RAD_BF16, 64, 4, 0);
rad_op op = loose_op(f);
CHECK_OK(f.start(nullptr, false, /*record=*/true));
std::vector<int32_t> res(64, -1), sblk(64, -1), sst(128, 0), ctl(16, 0);
std::vector<uint8_t> host(1024, 0);
RadKVStream view{};
view.host = host.data(); view.res = res.data(); view.slot_block = sblk.data();
view.slot_state = sst.data(); view.ctl = ctl.data();
view.block_bytes = 16; view.host_layer_stride = 1024; view.slots = 64;
view.host_bytes = 2048;
RadKVGroupBatch kg[1]{};
f.batch.kv = kg;
f.batch.n_kv_groups = 1;
f.batch.phase = RAD_PHASE_DECODE;
f.batch.n_tok = 1; f.batch.n_seq = 1;
kg[0].stream = &view;
const uint64_t k0 = f.ctx.pass_key(&f.batch);
CHECK(k0 != 0);
/* The Out slot moves; the bytes a kernel reads do not. */
RadKVStream copy = view;
kg[0].stream = &copy;
CHECK_EQ(f.ctx.pass_key(&f.batch), k0);
/* A different ring or a different map is a different pass. */
copy.slots = view.slots + 1;
CHECK(f.ctx.pass_key(&f.batch) != k0);
copy = view;
copy.res = res.data() + 1;
CHECK(f.ctx.pass_key(&f.batch) != k0);
kg[0].stream = &view;
const auto body = [&](Ctx& c) {
const RadOperand o[1] = { RAD_B(x) };
CHECK_OK(c.issue(op, o, 1, RAD_N_BATCH));
};
/* First sighting records, the second is the audit every recording gets before its first play,
* the third is the play. A key that moved each step would never get past the first. */
/* The first pass settles the runtime state the key also names (the host-touch and scratch
* flags a pass leaves behind), then: one sighting records, the next is the audit every
* recording gets before its first play, the third is the play. A key that moved with the view
* slot would never get past the first. */
for (int i = 0; i < 4; ++i) CHECK_OK(f.step(1, i, body));
if (f.ctx.records_passes()) {
const Ctx::PassCounts pc = f.ctx.pass_counts();
CHECK(pc.recorded > 0);
CHECK(pc.audited > 0);
CHECK(pc.played > 0); /* the streamed pass replayed, not reissued */
}
}
/* ================================================================== the op oracle */
namespace {
std::string radiance_home() {
+8
View File
@@ -339,6 +339,14 @@ struct FakeKV : IKVManager {
const KVGeom::G& gg = geom.g[(size_t)g];
return gg.paged ? gg.block_size : 0;
}
/* A streamed group's view, as KVManager::stream_view returns it. Tests install fake
* addresses to check that the builder rebases them into each rank's pool; with `streams`
* false the fake has none, which is every other scheduler test. */
RadKVStream stream{};
bool streams = false;
const RadKVStream* stream_view(int32_t g) const override {
return streams && g == 0 ? &stream : nullptr;
}
};
struct FakePC : IPrefixCache {
+72
View File
@@ -3336,6 +3336,78 @@ TEST(the_cards_block_tables_match_the_manager_after_every_build) {
CHECK(checked > 100);
}
/* A streamed group's residency map and ring bookkeeping live in each rank's KV pool,
* but the manager the builder is given is rank 0's, so its pointers are rank 0's addresses. A
* two-rank batch must name rank r's own copies or device r resolves through device 0's memory
* (a page-not-present fault at --tp 2). The host mirror is the exception: RAD_MEM_HOST_MAPPED's
* device view is its host address on every card, so it is the same pointer on both ranks.
*
* The bases are fake and no map is dereferenced: what is under test is the rebasing arithmetic,
* not two cards. Both ranks use device 0 so the test runs on the host backend. */
TEST(a_two_rank_batch_rebases_stream_maps_into_each_ranks_pool_and_shares_the_mirror) {
Fixture f;
f.build();
ChunkGeometry geo;
CHECK_OK(chunk_geometry_resolve(f.prog, f.cfg, &geo));
KVGeom kvg = KVGeom::of(f.prog.kv_groups);
for (size_t i = 0; i < kvg.g.size(); ++i) {
const int64_t w = f.kv.state_index_width((int32_t)i);
if (w > 0) kvg.g[i].sidx_width = w;
}
/* Two pools' worth of address space, only ever differenced, never dereferenced. */
alignas(16) char pool0[0x200], pool1[0x200];
char* const base[2] = { pool0, pool1 };
const int64_t res_off = 0x40, sblk_off = 0x80, sst_off = 0xc0, ctl_off = 0x100;
alignas(16) uint8_t mirror[0x100];
f.kv.streams = true;
f.kv.stream.host = mirror;
f.kv.stream.res = (int32_t*)(base[0] + res_off);
f.kv.stream.slot_block = (int32_t*)(base[0] + sblk_off);
f.kv.stream.slot_state = (int32_t*)(base[0] + sst_off);
f.kv.stream.ctl = (int32_t*)(base[0] + ctl_off);
f.kv.stream.block_bytes = 64;
f.kv.stream.slots = 8;
BatchBuilder bb;
std::vector<BatchBuilder::RankIO> rio;
rio.push_back({ 0, nullptr, &f.prog, base[0] });
rio.push_back({ 0, nullptr, &f.prog, base[1] });
CHECK_OK(bb.init(f.prog, f.cfg, geo, kvg, rio));
CHECK_OK(f.kv.add_sequence(1));
CHECK_OK(f.kv.ensure(1, 80));
StepPlan p;
p.reset();
StepEntry e;
e.seq = 1;
e.card = 0;
e.n_tokens = 1;
e.ctx_len = 79;
p.e.push_back(e);
p.n_tok = 1;
REQUIRE(bb.build(p, f.kv, 0) != nullptr);
for (int r = 0; r < 2; ++r) {
const RadBatch* b = bb.batch_for(r);
REQUIRE(b != nullptr);
const RadKVStream* s = b->kv[0].stream;
REQUIRE(s != nullptr);
CHECK_EQ((void*)s->res, (void*)(base[r] + res_off));
CHECK_EQ((void*)s->slot_block, (void*)(base[r] + sblk_off));
CHECK_EQ((void*)s->slot_state, (void*)(base[r] + sst_off));
CHECK_EQ((void*)s->ctl, (void*)(base[r] + ctl_off));
/* Same mirror address, and the geometry is rank-independent. */
CHECK_EQ((void*)s->host, (void*)mirror);
CHECK_EQ(s->block_bytes, (int64_t)64);
CHECK_EQ(s->slots, (int64_t)8);
/* Groups that do not stream keep a null view. */
for (int gi = 1; gi < b->n_kv_groups; ++gi)
CHECK(b->kv[gi].stream == nullptr);
}
bb.fini();
}
/* A sequence that leaves a row and returns to it is restaged whole. Its change marks are taken
* wherever it is written, so the old row's copy goes stale; restaging only later changes would
* keep entries a rollback replaced earlier. The scheduler's own passes reorder rows, so this
+9
View File
@@ -2271,6 +2271,11 @@ TEST(metrics_is_valid_prometheus_text_with_vllm_names) {
CHECK_EQ(d.type["radiance:draft_acceptance_ratio"], std::string("gauge"));
CHECK_EQ(d.type["radiance:decode_tokens_per_second"], std::string("gauge"));
CHECK_EQ(d.type["radiance:http_admission_rejected_total"], std::string("counter"));
/* KV streaming (docs/KV-STREAMING.md §4.2), present even when no group streams so a dashboard
* can query the names before the feature is turned on. The bytes counter carries `dir`. */
CHECK_EQ(d.type["radiance:kv_resident_blocks"], std::string("gauge"));
CHECK_EQ(d.type["radiance:kv_stream_misses_total"], std::string("counter"));
CHECK_EQ(d.type["radiance:kv_stream_bytes_total"], std::string("counter"));
/* The scheduler's numbers reached the gauges. */
auto find_one = [&](const std::string& prefix) -> double {
@@ -2283,6 +2288,10 @@ TEST(metrics_is_valid_prometheus_text_with_vllm_names) {
CHECK_NEAR(find_one("vllm:gpu_cache_usage_perc{"), 0.42, 1e-9);
CHECK_NEAR(find_one("radiance:draft_acceptance_ratio{"), 0.61, 1e-9);
CHECK_NEAR(find_one("vllm:generation_tokens_total{"), 5.0, 1e-9);
/* This server streams nothing, so every streaming number is zero. */
CHECK_NEAR(find_one("radiance:kv_resident_blocks{"), 0.0, 1e-9);
CHECK_NEAR(find_one("radiance:kv_stream_misses_total{"), 0.0, 1e-9);
CHECK_NEAR(find_one("radiance:kv_stream_bytes_total{"), 0.0, 1e-9);
/* An unmeasured decode floor is absent, not 0, which a scrape would plot as the fastest step
* ever. This fixture completes no single-stream window, so neither series appears. */