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

+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. */