kv: a window group keeps the keys a prefill chunk still reads

ensure() recycled a RAD_KV_WINDOW group against the end of the step, so a
prefill chunk lost the keys its first rows read (a 2185-token prompt kept
no window KV for positions 0..1151). Recycle below the step's first query
(keep_from = n_computed), size the caps for one extra chunk, and trim the
window when a prefill chunk is committed. The old test pinned the bug.

Found while debugging #75 (Gemma 4).
This commit is contained in:
keptn42 authored and sfjes committed 2026-10-10 08:08:43 -07:00
1 parent 77c266ce8f
commit 921b02b60b
6 files changed
+145 -29

No files matched your search

+42 -14
View File
@@ -307,7 +307,7 @@ int64_t KVManager::ceiling(int64_t ctx) const {
if (!p.paged() || p.block_size <= 0) continue;
int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size);
if (p.kind == RAD_KV_WINDOW && p.window_blocks > 0)
blocks = std::min(blocks, max_seqs_ * p.window_blocks);
blocks = std::min(blocks, window_pool_cap(p));
need += blocks * p.bytes_per_block;
}
return need;
@@ -382,10 +382,10 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
for (int32_t i : open) {
const auto& p = plans_[i];
if (p.kind != RAD_KV_WINDOW) continue;
if (tokens / p.block_size > max_seqs_ * p.window_blocks) { capped = i; break; }
if (tokens / p.block_size > window_pool_cap(p)) { capped = i; break; }
}
if (capped < 0) break;
out[capped] = max_seqs_ * plans_[capped].window_blocks;
out[capped] = window_pool_cap(plans_[capped]);
remaining -= out[capped] * plans_[capped].bytes_per_block;
open.erase(std::find(open.begin(), open.end(), capped));
}
@@ -419,7 +419,7 @@ int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
if (tokens == kUnboundedTokens) return 0;
const int64_t b = tokens / p.block_size;
if (p.kind == RAD_KV_WINDOW && b > max_seqs_ * p.window_blocks) return max_seqs_ * p.window_blocks;
if (p.kind == RAD_KV_WINDOW && b > window_pool_cap(p)) return window_pool_cap(p);
return b;
}
@@ -921,7 +921,7 @@ int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const {
const KVGroupPlan* p = plan(g);
if (!p || !p->paged() || n_tokens <= 0) return 0;
int64_t n = ceil_div(n_tokens, p->block_size);
if (p->kind == RAD_KV_WINDOW) n = std::min(n, p->window_blocks);
if (p->kind == RAD_KV_WINDOW) n = std::min(n, window_seq_cap(*p));
return n;
}
@@ -1156,19 +1156,29 @@ std::vector<BlockCopy> KVManager::take_pending_copies() {
/* ------------------------------------------------------------------ ensure */
int KVManager::ensure(uint64_t id, int64_t n_tokens) {
Seq* s = find(id);
if (!s) return RAD_E_NOTFOUND;
if (n_tokens <= s->n_tokens) return RAD_OK;
int64_t KVManager::window_seq_cap(const KVGroupPlan& p) const {
return p.window_blocks + (max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0) + 1;
}
/* Pass 0: recycle whatever the window has slid past. This only frees, so it cannot fail, and
* doing it first means the availability check below sees the memory it releases. */
int64_t KVManager::window_pool_cap(const KVGroupPlan& p) const {
return max_seqs_ * p.window_blocks + (max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0) +
max_seqs_;
}
/* SLID PAST THE STEP'S FIRST QUERY, NOT ITS LAST. The query at keep_from reads keys down to
* keep_from - window + 1, which lies in block keep_from / block - (window_blocks - 1) or later
* (window_blocks - 1 >= window / block). A target taken from the END of the step --
* ceil(n_tokens / block) - window_blocks -- is the same block for a decode step and drops the keys
* every row of a longer prefill chunk still needs. Measured on Gemma 4 (#75: 50 of 60 layers
* windowed at 1024): a 2185-token prompt rebased the table at 1152, its sliding layers held no KV
* for positions 0..1151, and every prompt past ~1040 tokens came back as nonsense. */
void KVManager::recycle_window(Seq* s, int64_t keep_from) {
for (size_t g = 0; g < plans_.size(); ++g) {
const auto& p = plans_[g];
if (p.kind != RAD_KV_WINDOW) continue;
int64_t want_end = ceil_div(n_tokens, p.block_size);
int64_t first = s->first_block_pos[g] / p.block_size;
int64_t target = std::max<int64_t>(first, want_end - p.window_blocks);
int64_t target = std::max<int64_t>(first,
keep_from / p.block_size - (p.window_blocks - 1));
while (first < target && !s->blocks[g].empty()) {
drop_block((int32_t)g, s->blocks[g].front());
s->blocks[g].erase(s->blocks[g].begin());
@@ -1178,6 +1188,24 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens) {
if (s->blocks[g].empty()) first = target; /* nothing held: rebase to the window */
s->first_block_pos[g] = first * p.block_size;
}
}
void KVManager::trim_window(uint64_t id, int64_t keep_from) {
Seq* s = find(id);
if (!s || keep_from < 0) return;
if (keep_from > s->n_tokens) keep_from = s->n_tokens;
recycle_window(s, keep_from);
}
int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
Seq* s = find(id);
if (!s) return RAD_E_NOTFOUND;
if (n_tokens <= s->n_tokens) return RAD_OK;
if (keep_from < 0 || keep_from > s->n_tokens) keep_from = s->n_tokens;
/* Pass 0: recycle whatever the window has slid past. This only frees, so it cannot fail, and
* doing it first means the availability check below sees the memory it releases. */
recycle_window(s, keep_from);
/* Pass 1: can every group serve this? Check before touching anything, so a group that runs
* out does not leave the sequence half-extended and the caller unable to say what it owns. */
@@ -1316,7 +1344,7 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens,
if (p.paged()) {
int64_t first = s->first_block_pos[g] / p.block_size;
int64_t want = ceil_div(n_tokens, p.block_size) - first;
if (p.kind == RAD_KV_WINDOW) want = std::min(want, p.window_blocks);
if (p.kind == RAD_KV_WINDOW) want = std::min(want, window_seq_cap(p));
int64_t extra = want - (int64_t)s->blocks[g].size() + 1; /* +1 for a COW copy */
if (extra > available_blocks((int32_t)g)) return false;
} else if (p.stateful() && s->state[g] < 0 && free_states_[g].empty()) return false;
+27 -2
View File
@@ -207,8 +207,31 @@ public:
/* Grow the sequence's mapping to cover `n_tokens` in every group. Unshares a shared partial
* block first (copy-on-write) and appends the copy request to the pending list.
* RAD_E_FULL when a group's free list is empty -- the caller preempts and retries. */
int ensure(uint64_t seq, int64_t n_tokens);
* RAD_E_FULL when a group's free list is empty -- the caller preempts and retries.
*
* `keep_from` is the position of the FIRST query the coming step runs (the scheduler's
* n_computed); -1 means the sequence's current end. A WINDOW group recycles only the blocks no
* query at or past it can read -- below keep_from - window + 1 -- and NOT the blocks below the
* window of the step's END: a prefill chunk longer than a block would otherwise lose the keys
* its first rows attend to (a chunk of C tokens from position 0 rebased the table at
* ceil(C/block) - window_blocks and left every position below it with no KV at all). */
int ensure(uint64_t seq, int64_t n_tokens, int64_t keep_from = -1);
/* A WINDOW group's caps: a sequence holds its window behind the step's first query AND the
* step's own tokens (window_blocks + ceil(max_tok / block) + 1 at most), and one step carries
* at most max_tok tokens across every sequence in it, so the pool needs max_seqs windows plus
* one step's worth on top. */
int64_t window_seq_cap(const KVGroupPlan& p) const;
int64_t window_pool_cap(const KVGroupPlan& p) const;
/* GIVE BACK A FINISHED CHUNK'S BLOCKS once it is committed. ensure() keeps a chunk's own blocks
* beside the window behind its first query, and only the sequence's NEXT ensure() recycles
* them -- so a prefill waiting a step for its next chunk would sit on a whole chunk of window
* blocks while other sequences prefill, and eight of them exhaust the pool (measured on
* Gemma 4: "the KV pool cannot hold 12480 tokens" with eight 16K prompts). Called by the
* scheduler when it advances n_computed: keep_from is the new n_computed, the first query any
* later step can run. */
void trim_window(uint64_t seq, int64_t keep_from);
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
* block size: a partial block is never shared, because the next token written into it would
@@ -509,6 +532,8 @@ private:
void drop_state(int32_t g, int32_t s);
Seq* find(uint64_t seq);
const Seq* find(uint64_t seq) const;
/* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. */
void recycle_window(Seq* s, int64_t keep_from);
std::vector<KVGroupPlan> plans_;
std::vector<std::vector<int32_t>> free_blocks_; /* per group */
+6 -2
View File
@@ -185,8 +185,12 @@ void BatchBuilder::size_set(Set& s, const std::vector<KVGroupInfo>& groups) {
s.groups[gi].block_size = e.block_size;
int64_t mb = 1;
if (e.paged) {
int64_t span = (e.kind == RAD_KV_WINDOW && e.window > 0 && e.window < max_ctx_)
? e.window : max_ctx_;
/* A WINDOW row holds the window behind the step's first query AND the step's own
* tokens (KVManager::ensure keeps both), so it is sized for a whole chunk past the
* window -- plus the speculative lookahead, which a verify row carries on top. */
const int64_t wspan = e.window + max_tok_ + 2 * ((int64_t)std::max(cfg_.n_spec, 0) + 1);
int64_t span = (e.kind == RAD_KV_WINDOW && e.window > 0 && wspan < max_ctx_)
? wspan : max_ctx_;
mb = (span + e.block_size - 1) / e.block_size + 1;
}
s.groups[gi].max_blocks = mb;
+12
View File
@@ -46,6 +46,16 @@ struct IKVManager {
* free list is empty, which is a scheduling signal and not an error: the caller preempts a
* victim and retries. */
virtual int ensure(uint64_t seq, int64_t n_tokens) = 0;
/* The same, for a step whose first query sits at `keep_from` (the request's n_computed): a
* WINDOW group then keeps every block that query can still read, however long the step is.
* See KVManager::ensure. The default is for a manager with no windowed group. */
virtual int ensure_from(uint64_t seq, int64_t n_tokens, int64_t keep_from) {
(void)keep_from;
return ensure(seq, n_tokens);
}
/* A committed step: a WINDOW group gives back what no later query can read. A no-op for a
* manager with no windowed group. See KVManager::trim_window. */
virtual void trim_window(uint64_t seq, int64_t keep_from) { (void)seq; (void)keep_from; }
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
* block size -- a partial block is never shared, because the next token written into it would
@@ -282,6 +292,8 @@ struct KVBinding final : IKVManager {
bool has_sequence(uint64_t s) const override { return m->has_sequence(s); }
void free_sequence(uint64_t s) override { m->free_sequence(s); }
int ensure(uint64_t s, int64_t n) override { return m->ensure(s, n); }
int ensure_from(uint64_t s, int64_t n, int64_t k) override { return m->ensure(s, n, k); }
void trim_window(uint64_t s, int64_t k) override { m->trim_window(s, k); }
int adopt(uint64_t s, int32_t g, const std::vector<int32_t>& b, int64_t n) override {
return m->adopt(s, g, b, n);
}
+12 -6
View File
@@ -1048,7 +1048,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
/* THE CACHE GIVES WAY TO A NEW REQUEST as it does to a running one: with nothing running,
* no other path would ever take blocks back from it, and the request would wait for good. */
int rounds = 0;
while (kv_->ensure(r.id, r.n_computed + want) < 0) {
while (kv_->ensure_from(r.id, r.n_computed + want, r.n_computed) < 0) {
if (++rounds > 256 || !cfg_.prefix_cache || pc_->evict(256) <= 0) {
rc = RAD_E_NOMEM;
break;
@@ -1238,7 +1238,7 @@ const RadBatch* Scheduler::step() {
static const int kMaxEvictRounds = 256;
int evict_rounds = 0;
bool failed = false;
while (kv_->ensure(r.id, r.n_computed + want) < 0) {
while (kv_->ensure_from(r.id, r.n_computed + want, r.n_computed) < 0) {
/* THE CACHE GIVES ITS BLOCKS BACK BEFORE A RUNNING REQUEST DOES. Everything the prefix
* cache holds is a saving on work that has already been done once; everything a
* running request holds is work in flight. Evicting first is therefore strictly the
@@ -1450,7 +1450,7 @@ const RadBatch* Scheduler::step() {
int64_t ckpt = -1;
const int64_t grown = e.ckpt_slot < 0 && limit > had
? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt) : had;
if (grown > had && kv_->ensure(r.id, r.n_computed + grown) >= 0) {
if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) {
e.n_tokens = (int32_t)grown;
e.produces_token = (r.n_computed + grown >= s.seq_len());
if (ckpt > 0) {
@@ -1690,7 +1690,7 @@ const RadBatch* Scheduler::step_next_locked() {
const int32_t d = s.draft_next;
const int64_t want = 1 + d;
if (ctx_limit_ > 0 && ctx_up + want > ctx_limit_) return nullptr;
if (kv_->ensure(r.id, ctx_up + want) < 0) return nullptr;
if (kv_->ensure_from(r.id, ctx_up + want, r.n_computed) < 0) return nullptr;
StepEntry n;
n.req = &r;
@@ -1831,6 +1831,10 @@ int Scheduler::commit(const StepResult& res) {
if (e.is_prefill) {
r.n_computed += e.n_tokens;
/* The chunk is committed: a window group gives its blocks below the window back now,
* not at this sequence's next ensure(), which may be steps away while others
* prefill. */
kv_->trim_window(r.id, r.n_computed);
step_prefill_tok_ += e.n_tokens;
server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(),
r.n_cached);
@@ -2167,7 +2171,8 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
* unwritten in the head's layer for good. The same goes for a row too near the end of the
* context for its rounds, whose last positions do not exist. */
if (can_draft && ctx_limit_ > 0 && head_max + *rounds > ctx_limit_) can_draft = false;
if (can_draft && kv_->ensure(r.id, head_max + *rounds) < 0) can_draft = false;
if (can_draft && kv_->ensure_from(r.id, head_max + *rounds, r.n_computed) < 0)
can_draft = false;
/* THE HISTORY THIS STEP OWES, in two parts. Before the verified positions, the positions
* the step computed whose next token the host holds -- a prefill chunk's prompt -- from
@@ -2418,7 +2423,8 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block
/* The query block writes positions n_computed .. n_computed + block - 1, and none of them
* may be at or past the end of the context. */
const bool ok_ctx = ctx_limit_ <= 0 || r.n_computed + block <= ctx_limit_;
const bool ok_kv = ok_room && ok_ctx && kv_->ensure(r.id, r.n_computed + block) >= 0;
const bool ok_kv = ok_room && ok_ctx &&
kv_->ensure_from(r.id, r.n_computed + block, r.n_computed) >= 0;
static const bool dbg = [] { const char* v = std::getenv("RADIANCE_DEBUG_DRAFT");
return v && *v && *v != '0'; }();
if (dbg) {
+46 -5
View File
@@ -965,19 +965,60 @@ TEST(kv_window_group_recycles_below_the_window) {
CHECK_OK(kv.configure(g, cfg, p.kv()));
/* window 64 at block 16 is 4 blocks plus one for the straddle. */
CHECK_EQ(kv.plan(G_FULL)->window_blocks, 5ll);
/* Sized against the cap, not against the whole budget: blocks past the window are memory
* nobody will ever address. */
CHECK_EQ(kv.total_blocks(G_FULL), cfg.max_seqs * 5);
/* Sized against the cap, not against the whole budget: a window a sequence plus one step's
* worth of tokens (max_tok) and a straddle block a sequence -- a chunk's own blocks are held
* beside the window behind its first query. Past that is memory nobody will ever address. */
CHECK_EQ(kv.total_blocks(G_FULL), cfg.max_seqs * 5 + (cfg.max_tok + 15) / 16 + cfg.max_seqs);
const int64_t n0 = kv.free_blocks(G_FULL);
CHECK_OK(kv.add_sequence(1));
CHECK_OK(kv.ensure(1, 80));
CHECK_OK(kv.ensure(1, 80)); /* a chunk from 0: all of it held */
CHECK_EQ(kv.first_block_pos(1, G_FULL), 0ll);
CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 5ll);
/* A chunk from 80 to 400: its first query (80) reads back to 17, so block 1 stays and only
* block 0 goes -- NOT the window behind 400, which left rows 80..335 with no keys. */
CHECK_OK(kv.ensure(1, 400));
CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 5ll); /* recycled, not grown */
CHECK_EQ(kv.first_block_pos(1, G_FULL), 16ll);
CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 24ll);
/* A decode step from 400: back to the window, recycled rather than grown. */
CHECK_OK(kv.ensure(1, 401));
CHECK_EQ(kv.first_block_pos(1, G_FULL), 336ll);
CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 5ll);
CHECK_EQ(kv.free_blocks(G_FULL), n0 - 5);
kv.free_sequence(1);
CHECK_EQ(kv.free_blocks(G_FULL), n0);
/* THE PROMPT LONGER THAN THE WINDOW, in one chunk from 0: every position keeps its slot. The
* old rule rebased this table at ceil(400/16) - 5 = 20 blocks, and a sliding layer read no
* keys at all for positions 0..319. */
CHECK_OK(kv.add_sequence(2));
CHECK_OK(kv.ensure(2, 400));
CHECK_EQ(kv.first_block_pos(2, G_FULL), 0ll);
CHECK_EQ((long long)kv.block_table(2, G_FULL).size(), 25ll);
/* And the scheduler's form names the step's first query itself: a chunk grown in the same
* step (ensure called twice) keeps what the first call's first query reads. */
CHECK_OK(kv.ensure(2, 432, 400));
CHECK_EQ(kv.first_block_pos(2, G_FULL), 336ll);
CHECK_OK(kv.ensure(2, 464, 400));
CHECK_EQ(kv.first_block_pos(2, G_FULL), 336ll);
CHECK_EQ((long long)kv.block_table(2, G_FULL).size(), 8ll);
kv.free_sequence(2);
CHECK_EQ(kv.free_blocks(G_FULL), n0);
/* A COMMITTED CHUNK GIVES ITS BLOCKS BACK at once: trim_window to the new end keeps the window
* behind it and nothing else, so a prefill that waits a step for its next chunk holds a window
* and not a chunk. */
CHECK_OK(kv.add_sequence(3));
CHECK_OK(kv.ensure(3, 400));
CHECK_EQ((long long)kv.block_table(3, G_FULL).size(), 25ll);
kv.trim_window(3, 400);
CHECK_EQ(kv.first_block_pos(3, G_FULL), 336ll);
CHECK_EQ((long long)kv.block_table(3, G_FULL).size(), 4ll);
CHECK_EQ(kv.free_blocks(G_FULL), n0 - 4);
CHECK_OK(kv.ensure(3, 401));
CHECK_EQ((long long)kv.block_table(3, G_FULL).size(), 5ll);
kv.free_sequence(3);
CHECK_EQ(kv.free_blocks(G_FULL), n0);
}
TEST(kv_conv_slot_is_a_rolling_window) {