From 2bf10961318e36a2d2980d3649fa16634ce6bfc6 Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Sun, 25 Oct 2026 07:03:03 +0700 Subject: [PATCH 1/2] prefix cache: the host tier cannot hold a streamed entry, so it is off The prefix cache's host tier and --kv-resident are exclusive, and the engine used to find that out at the first restore. An entry covers every cached group; a streamed group's rows are addressed by the block id its sequence used, in that group's own pinned mirror, so a slot cannot stand in for them and their ids cannot be given up in exchange for one. Three defects came from ignoring that: * the write-back gathered the resident sibling with the streamed group's block id, so the host slot held another group's row (TierExec indexes its block vector by gi_, the entry's ids are in groups_ order); * demotion released the streamed group's ids too (PrefixCache:: release_blocks walks every group), handing the mirror rows the entry lives in back to the allocator; * a restore reserved one group's ids against an entry that has two, so rebind returned RAD_E_SHAPE and the record was dropped -- and engine.cpp's failure path then released those ids against the wrong pools. Measured on 2x16GB tp2, three 44220-token conversations and a replay of the first after the third displaced it, streaming on: 20247 entries demoted, 8588 restored, replay 0 cached tokens / 16.5s against streaming off's 44160 cached / 0.4s. The copies were pure waste. Two rules now: * PrefixCache::demotable() is false when any cached group streams: the tiers are never told about such an entry (insert), and trim_sparing no longer skips it as though its copy were in flight, so it is evicted whole with every group's ids. * kvstream_prefix_host_off() turns --prefix-cache-mib off at bring-up, before anything is sized from it, when cfg.kv_streams is set -- the flag asked, the architecture streams and the ring is under the context. A flag with no streaming behind it (0, a ring that covers the context, a model with no kv_resolve) keeps the tier exactly as configured. On the cards: --kv-resident 32768 reports "no host cache ... so it is off" and 0 (off); --kv-resident 131072 keeps 2.00 GiB / 38836 entries. The tests live in the mem test file's own commit; the docs in the docs commit. --- core/config.cpp | 4 +++- core/engine_bringup.cpp | 13 +++++++++++++ core/kvstream/plan.cpp | 18 ++++++++++++++++-- core/kvstream/plan.h | 5 +++++ core/mem/prefix.cpp | 38 ++++++++++++++++++++++++++++++++++---- core/mem/prefix.h | 11 +++++++++++ 6 files changed, 82 insertions(+), 7 deletions(-) diff --git a/core/config.cpp b/core/config.cpp index 5fa32122..fbe57afa 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -118,7 +118,9 @@ static const Flag g_flags[] = { { "--prefix-cache-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n" " so their VRAM can go to experts and a return restores\n" " instead of re-prefilling. A full tier drops its least\n" - " recently used entries. 0 is off" }, + " recently used entries. 0 is off. Ignored, and not\n" + " reserved, when a group streams (--kv-resident): such an\n" + " entry cannot be demoted, its mirror is its cold copy" }, { "--prefix-cache-ttl", "S", "seconds a cached conversation no request uses is kept, in VRAM\n" " or host memory (default 3600). 0 keeps it until the memory\n" " is wanted" }, diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 44fc3059..7baa152b 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -1613,6 +1613,19 @@ int Engine::plan() { * 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)); + /* A streamed group's rows are addressed by block id, so the prefix cache cannot + * demote an entry that contains one (PrefixCache::demotable): its mirror is the only + * cold copy that group has. The host tier would only be pinned and never used, so it + * is turned off here -- once, before the tables and the checkpoint store are sized, + * so its memory is not reserved either. Only when streaming is really on: the flag + * asks, the architecture serves it and the ring is under the context (kv_streams). + */ + if (const int64_t off = kvstream_prefix_host_off(cfg_)) { + RAD_INFO("a streamed KV group has no host cache: --prefix-cache-mib %lld would " + "hold nothing (its entries could never be demoted), so it is off; the " + "%lld MiB go to the host pool and the page cache instead", + (long long)off, (long long)off); + } 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 diff --git a/core/kvstream/plan.cpp b/core/kvstream/plan.cpp index e43804a9..4cec79fc 100644 --- a/core/kvstream/plan.cpp +++ b/core/kvstream/plan.cpp @@ -182,8 +182,22 @@ void kvstream_ring(const Config& cfg, int64_t ctx, int64_t block_size, int64_t s } } -int kvstream_cap_probe(KVManager& probe, Config& cfg, const Program& prog, int64_t ctx) { - cfg.kv_streams = false; +/* The prefix cache's host tier cannot hold an entry that contains a streamed group: its rows are + * addressed by the block id a sequence used, so they cannot be copied into a slot and their ids + * cannot be given up for one (PrefixCache::demotable, docs/KV-STREAMING.md §4.1). A host tier + * configured beside a streamed group would only be pinned and never used, so it is turned off + * before anything is sized. `cfg.kv_streams` is what kvstream_cap_probe sets when the flag asks, + * the architecture serves it and the ring is under the context -- a flag alone, a model with no + * streamed path and a ring that covers the context all leave it false, and the tier stays on. + * Returns the MiB taken off, for the caller's one line; 0 when nothing changed. */ +int64_t kvstream_prefix_host_off(Config& cfg) { + if (!cfg.kv_streams || cfg.prefix_cache_mib <= 0) return 0; + const int64_t was = cfg.prefix_cache_mib; + cfg.prefix_cache_mib = 0; + return was; +} + +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; diff --git a/core/kvstream/plan.h b/core/kvstream/plan.h index fbda98f0..ff4805bc 100644 --- a/core/kvstream/plan.h +++ b/core/kvstream/plan.h @@ -154,6 +154,11 @@ void kvstream_ring(const Config& cfg, int64_t ctx, int64_t block_size, int64_t s * 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. */ +/* Turn the host tier off when a streamed group means no entry can be demoted to it. Returns the + * MiB it turned off (0 if the tier was not on, or nothing streams), so the caller states it once. + * Call after kvstream_cap_probe, before anything is sized from --prefix-cache-mib. */ +int64_t kvstream_prefix_host_off(Config& cfg); + int kvstream_cap_probe(KVManager& probe, Config& cfg, const Program& prog, int64_t ctx); } /* namespace rad */ diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index d90f6fe1..603377c1 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -1,6 +1,7 @@ /* prefix.cpp -- see prefix.h. */ #include "mem/prefix.h" +#include "kvstream/plan.h" #include "mem/kvtier.h" #include @@ -186,6 +187,25 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ p.name.c_str(), (long long)p.block_size, (long long)block_size_); } + /* An entry is only demotable when the host tier can hold every group in it. A streamed group + * cannot be gathered: its VRAM pool is one layer of its context, so a copy per layer would move + * the last staged layer N times, and its pinned host mirror is already its cold tier + * (docs/KV-STREAMING.md §4.1). Its rows are addressed by the block id the sequence used, so the + * entry cannot hand the mirror to a slot and drop its ids either: the ids are the bytes. Such an + * entry stays a VRAM entry and is evicted whole, exactly as with no host tier. + * + * The subset is also the block-id order of a tier job and of TierExec's slot, which is what + * rebind() takes; see "the host tier cannot hold a streamed group" in prefix.h. */ + tier_groups_.clear(); + tier_at_.clear(); + for (size_t g = 0; g < groups_.size(); ++g) { + const KVGroupPlan* p = kv->plan(groups_[g]); + if (p && !kv_tier_cached(*p)) continue; + tier_at_.push_back(g); + tier_groups_.push_back(groups_[g]); + } + demotable_ = tier_at_.size() == groups_.size(); + interval_ = checkpoint_interval; /* A window snapshot is state too: a hit is reusable only at a checkpoint, whose slot carries * the window behind it (KVManager::has_window_snapshot). */ @@ -217,6 +237,12 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ (long long)kv->checkpoint_slots(), humanb(kv->checkpoint_bytes()).c_str(), policy_->name()); report_ += skipped; + if (!demotable_) { + /* A fact about the model, not about the tiers, so it is stated here whether or not a host + * tier is configured: with one, these entries are still never demoted. */ + report_ += " a streamed group is cached, so no entry can be demoted to the host tier: a " + "streamed group's rows are its pinned mirror, addressed by block id\n"; + } return RAD_OK; } @@ -431,14 +457,16 @@ int PrefixCache::insert(uint64_t session, * The ids come from the map, not from `blocks`. For an entry that already existed the loop * above kept the cache's blocks, and `blocks` belongs to a sequence about to be freed; the * tiers would copy from blocks reassigned to another sequence. */ - if (tiers_) { + if (tiers_ && demotable_) { for (int64_t b = 0; b < n_full; ++b) { auto it = map_.find(hs[(size_t)b]); if (it == map_.end()) continue; tiers_->note_used(hs[(size_t)b], it->second.blocks, now, b); } - tiers_->note_session(session, hs, n_tokens, now, label); } + /* The session index names no blocks: it is what /v1/sessions release cuts, and it stays useful + * with or without a host copy. */ + if (tiers_) tiers_->note_session(session, hs, n_tokens, now, label); take_over(session, hs, n_full * block_size_); return RAD_OK; @@ -635,11 +663,13 @@ int64_t PrefixCache::trim_sparing(int64_t n_blocks, it = next; continue; } - if (keep && !tiers_->droppable(h)) { ++it; continue; } + /* Skip a copy still in flight, but never an entry this tier cannot hold: that one never + * gets a copy, so waiting for one would keep it out of reach of the trim forever. */ + if (keep && demotable_ && !tiers_->droppable(h)) { ++it; continue; } it = lru_.erase(it); e.in_lru = false; release_blocks(e); - if (keep) { + if (keep && demotable_) { tiers_->drop_commit(h); ++stats_.drops; } else { diff --git a/core/mem/prefix.h b/core/mem/prefix.h index b60eec9e..06155322 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -205,6 +205,11 @@ public: int64_t block_size() const { return block_size_; } int64_t checkpoint_interval() const { return interval_; } const std::vector& cached_groups() const { return groups_; } + /* Whether the host tier can hold this cache's entries. False when any cached group streams: a + * streamed group's rows are addressed by the block id the sequence used, so they cannot be + * copied into a slot and their ids cannot be given up. With it false the cache is a VRAM cache + * and evicts whole entries, exactly as with no host tier (docs/KV-STREAMING.md §4.1). */ + bool demotable() const { return demotable_; } std::string report() const; /* Overrides the policy configure() installed from Config::checkpoint_policy (custom policies, @@ -461,6 +466,12 @@ private: int64_t block_size_ = 0; int64_t interval_ = 0; std::vector groups_; /* paged groups this cache indexes */ + /* groups_ less the streamed ones, in the same order, and where each sits in groups_. A tier + * job's block ids and a host slot are in this order; an entry that is not demotable_ never + * reaches the tiers at all. */ + std::vector tier_groups_; + std::vector tier_at_; + bool demotable_ = false; /* the host tier can hold every group in an entry */ bool has_linear_ = false; mutable std::unordered_map map_; From 4134b700884d752df9ddde62083050d48414aea3 Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Sun, 25 Oct 2026 07:03:19 +0700 Subject: [PATCH 2/2] mem_test: the host tier never takes an entry with a streamed group Two pins on the rule in core/mem/prefix.cpp: * an_entry_with_a_streamed_group_is_never_demoted -- demotable() is false, the tiers are never told about the entry (plan_writeback yields nothing), drop_clean takes nothing, and trim_sparing evicts it whole: every group's block comes back, the streamed one included; * the_prefix_cache_host_tier_is_off_only_when_streaming_is_really_on -- kvstream_prefix_host_off() turns --prefix-cache-mib off only when cfg.kv_streams is set, i.e. the ring is under the context and the architecture streams; the flag absent, a ring that covers the context and a model with no streamed path all keep the tier. Runs through kvstream_cap_probe, so the three cases are the ones an operator hits. --- tests/mem_test.cpp | 96 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index 780a93c5..c46a9fdc 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -1319,6 +1319,47 @@ TEST(a_ring_that_covers_the_context_streams_nothing_and_the_engine_pays_nothing) } } +/* The prefix cache's host tier is turned off when --kv-resident really streams, and only then. + * The three cases that must leave it on are the ones an operator hits without meaning to: the flag + * absent or 0, a ring that covers the group's context (nothing streams), and a flag on a model the + * tier does not stream. `cfg.kv_streams` is the one answer to all three (kvstream_cap_probe). */ +TEST(the_prefix_cache_host_tier_is_off_only_when_streaming_is_really_on) { + std::vector groups = hybrid_groups(); + groups[G_FULL].bytes_per_block = 2048; /* 16 tokens x 128 B, as declare sets it */ + /* A pitch of 513 blocks is this fixture's resolve; the ceiling is max_seqs x (1 + n_spec) x + * pitch, so a ring under a 128-block context needs a small pitch: 8 x 2 = 16 blocks. */ + const Program wide = stream_program(groups[G_FULL], 513); + const Program narrow = stream_program(groups[G_FULL], 8); + + struct Case { + const char* what; + int64_t resident; /* --kv-resident */ + bool streams; + int64_t tier_after; /* --prefix-cache-mib once bring-up has had its say */ + }; + const Case cases[] = { + { "the flag absent", 0, false, 2048 }, + { "a ring covering the ctx", 2 * 1024, false, 2048 }, + { "a ring under the ctx", 256, true, 0 }, + }; + for (const Case& c : cases) { + Fixture f; + f.cfg.checkpoint_slots = 0; + f.cfg.max_ctx = 1024; + f.cfg.max_seqs = 2; + f.cfg.kv_resident = c.resident; + f.cfg.prefix_cache_mib = 2048; + CHECK_OK(f.kv.plan_groups(groups, f.cfg)); + CHECK_OK(kvstream_cap_probe(f.kv, f.cfg, c.streams ? narrow : wide, 1024)); + CHECK_EQ(f.cfg.kv_streams, c.streams); + const int64_t off = kvstream_prefix_host_off(f.cfg); + CHECK_EQ(f.cfg.prefix_cache_mib, c.tier_after); + CHECK_EQ(off, c.streams ? 2048ll : 0ll); + CHECK_EQ(kvstream_prefix_host_off(f.cfg), 0ll); /* idempotent: a second rank says nothing */ + f.kv.free_stream(rad_malloc_allocator()); + } +} + TEST(a_decode_pass_wider_than_a_verify_stages_instead_of_resolving_the_ring) { /* The serial drafter's history pass is RAD_PHASE_DECODE, but after a prefill chunk it carries * the chunk's tokens of every sequence: more rows a sequence than a decode step can select for @@ -7474,6 +7515,61 @@ TEST(a_dense_read_groups_floor_holds_every_sequence_while_a_sibling_streams) { CHECK_EQ(bkey->n_slots, bkey->n_blocks); } +/* A prefix entry covers every cached group, the streamed one included: a hit re-adopts its block + * ids, and the mirror behind them is the tier for that group. A host-tier entry cannot: a slot + * holds only the groups whose bytes the tier copies (kv_tier_cached), and a streamed group's rows + * are addressed by the block id the sequence used, so its ids can never be given up in exchange + * for a slot. An entry that contains one is therefore a VRAM entry: the tiers are never told about + * it, and an eviction takes every group's ids with it. */ +TEST(an_entry_with_a_streamed_group_is_never_demoted) { + if (!host_backend_or_skip("the tier restore")) return; + Fixture f; + f.cfg.checkpoint_slots = 0; + f.cfg.max_seqs = 1; + f.cfg.max_ctx = 1024; + std::vector groups = hybrid_groups(); + groups.push_back(paged_group("bkey", RAD_KV_FULL, 2, 16, { 6, 7 })); + CHECK_OK(f.kv.plan_groups(groups, f.cfg)); + f.kv.cap_resident_tokens(G_FULL, 64); /* four blocks of 16 tokens */ + const int64_t need = f.kv.pool_mib_for_tokens(f.cfg.max_ctx, 256); + REQUIRE(need > 0); + f.cfg.vram_kv_mib = need; + CHECK_OK(configure_pools(f.pools, f.cfg)); + CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv())); + CHECK_OK(f.kv.carve(f.pools.kv())); + + const std::vector& cg = f.pc.cached_groups(); + IdleTiers t; + REQUIRE_EQ(t.configure(tier_config(4096 * 1024, 4096 * 1024)), RAD_OK); + f.pc.set_tiers(&t); + REQUIRE_EQ(f.pc.configure(f.cfg, &f.kv, f.cfg.checkpoint_interval), RAD_OK); + REQUIRE_EQ(cg.size(), 2u); + CHECK(f.kv.plan(cg[0])->streamed()); + /* The one fact the tier path depends on: a slot cannot hold this cache's entries, so no + * write-back is planned, nothing is queued, and nothing can be dropped to the host. */ + CHECK(!f.pc.demotable()); + + const auto tokens = tok_run(5000, 64); + publish(f, 1, tokens, 64); + f.kv.free_sequence(1); + const std::vector hs = chain_of(tokens); + REQUIRE_EQ(hs.size(), 4u); + + std::vector wb; + t.plan_writeback(64, &wb); + CHECK_EQ(wb.size(), 0u); /* the streamed entry is never copied */ + CHECK_EQ(f.pc.drop_clean(), 0ll); /* so it is never demoted */ + CHECK(!t.droppable(hs[0])); + + /* The trim still frees it: an entry the tier cannot hold must not be skipped as though its + * copy were in flight. All four blocks are at refcount one and the trim takes them. */ + CHECK_EQ(f.pc.trim(4), 4ll); + CHECK_EQ(f.pc.size(), 0ll); + CHECK_EQ(f.kv.block_refcount(cg[0], 0), 0); + CHECK_EQ(f.kv.block_refcount(cg[1], 0), 0); + f.pc.set_tiers(nullptr); +} + RAD_TEST_MAIN() /* A streamed-only op exists only when the architecture's capability table says it can stream AND