From f43929ccb8213041e8883b60c420580cecddada4 Mon Sep 17 00:00:00 2001 From: baKon Date: Tue, 27 Oct 2026 11:28:12 -0500 Subject: [PATCH] core/mem, core/sched: a prefix hit on a model whose KV groups have different block sizes, and a hybrid's window in the checkpoint slot DeepSeek-V4.1 declares its compressed attention at one KV row per r tokens: kv_index_r2 and kv_compressed_r2 at 2-token blocks, kv_index_r1 and kv_compressed_r1 at 1-token blocks, beside a 16-token sliding window (kv_window), a linear compressor state (kv_comp_tail_r2) and a conv window (kv_engram_tokens). On that model no request ever reused a token, for two reasons: - PrefixCache::configure took the first full group's block size as its granularity and left every paged group with another block size out ("block 1 != cache granularity 2: not cached"). - KVManager put a trunk's window in the checkpoint slot only on a model without linear state, and the scheduler refuses a hit that leaves a trunk group uncovered. With linear state beside the window, every hit was zeroed (HitCut::Window). Either alone leaves the hit at zero. On an agent's growing conversation that is the whole context prefilled again every turn. The cache now holds every paged group but a windowed one. An entry covers the lcm of their block sizes and holds lcm / B blocks of a group with B-token blocks (PrefixCache::entry_groups, blocks_per_entry). A lookup hands each group its own blocks for adopt(); insert, eviction, trim, rebind, restore_room, release_session and unshared_tokens count per block; trim() and trim_for() count entries. The chunk quantum is already a multiple of every paged group's block, so checkpoints and hits stay on the entry grid. With equal block sizes an entry is one block a group, as before. A trunk's window rides in the checkpoint slot whether or not linear state is beside it; the slot is the state, then the window pages, the layout KVManager::checkpoint_copy already walked. The scheduler lets a hit stand on a windowed trunk group when it resumes at a window snapshot (win_hit no longer needs a model without linear state); any other trunk group the cache does not hold refuses the hit, as before. The reserve's trim asks for entries, from the group furthest short. The idle tiers move an entry as its blocks: TierExec and the slot layout take entry_groups(), where a group appears once for each block it holds in an entry, and the VRAM estimate counts the same. No plugin on main has a window beside linear state or paged groups of different block sizes, so every model here keeps its cache and slot as they were. DeepSeek-V4.1 (#266) has both; its slot grows by the window's pages (10 blocks of kv_window, 6.25 MiB a rank at TP4). Tests: mem_test -- an entry at the lcm over block sizes 2/1, 2/4 and 16/2 (lookup blocks, adopt, refcounts, eviction and trim in entries, restore_room, unshared_tokens), a publish short of one group's blocks refused and unwound, checkpoints on the entry grid (and the binding's key), an interval off the grid refused, a hybrid with a window and mixed blocks, an entry over mixed block sizes through the host tier byte for byte (one to three ranks, replicated beside zero), and a checkpoint carrying linear state and the window together; the window-snapshot rule's test now expects the window beside linear state. sched_test -- a hit on a hybrid whose slot carries the window resumes at the snapshot, a trunk group neither cached nor in the slot refuses the hit, a hit over mixed block sizes adopts each group's own blocks, and the reserve trim asks for entries. --- core/engine.cpp | 4 +- core/engine_bringup.cpp | 27 ++- core/mem/kv.cpp | 8 +- core/mem/kv.h | 7 +- core/mem/kvtier.h | 2 +- core/mem/prefix.cpp | 132 +++++++------- core/mem/prefix.h | 62 +++++-- core/runtime/tierexec.cpp | 18 +- core/runtime/tierexec.h | 5 +- core/sched/mem_iface.h | 10 +- core/sched/scheduler.cpp | 58 +++++-- core/sched/scheduler.h | 8 +- tests/mem_test.cpp | 356 ++++++++++++++++++++++++++++++++++++-- tests/sched_test.cpp | 117 +++++++++++++ 14 files changed, 672 insertions(+), 142 deletions(-) diff --git a/core/engine.cpp b/core/engine.cpp index 6631b147..35428364 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -1818,8 +1818,8 @@ int Engine::serve(std::unique_ptr watch) { if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); ranks_[0]->tierx.report_pass(jobs, ok, rad_mono_ns()); /* Rebind every entry that came back, not only the leading run: the tiers already - * marked each resident at its new blocks. */ - const std::vector& cg = pc.cached_groups(); + * marked each resident at its new blocks. A job's blocks are one per entry slot. */ + const std::vector& cg = pc.entry_groups(); for (size_t i = 0; i < jobs.size(); ++i) { TierJob& j = jobs[i]; if (!ok[i]) { res = RestoreResult::Cut; continue; } diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 56f49386..c28fa5a8 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -37,6 +37,7 @@ #include #include +#include #include #include #include @@ -1652,16 +1653,21 @@ int Engine::plan() { int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0; /* The KV tiers' copy staging, built by TierExec::device_init on the first copy out. * The cached groups are settled later, so every paged group is counted (an upper - * bound). */ + * bound), each with the blocks an entry at the lcm of their block sizes holds + * (PrefixCache::entry_groups). */ if (cfg_.prefix_cache_mib > 0) { int64_t entry = 0, bs = 0; int ng = 0; for (size_t g = 0; g < r->program.kv_groups.size(); ++g) { const KVGroupPlan* p = probe.plan((int32_t)g); - if (!p || !p->paged() || p->bytes_per_block <= 0) continue; - entry += p->bytes_per_block; - bs = bs > 0 ? std::min(bs, p->block_size) : p->block_size; - ++ng; + if (!p || !p->paged() || p->bytes_per_block <= 0 || p->block_size <= 0) continue; + bs = bs > 0 ? std::lcm(bs, p->block_size) : p->block_size; + } + for (size_t g = 0; g < r->program.kv_groups.size() && bs > 0; ++g) { + const KVGroupPlan* p = probe.plan((int32_t)g); + if (!p || !p->paged() || p->bytes_per_block <= 0 || p->block_size <= 0) continue; + entry += p->bytes_per_block * (bs / p->block_size); + ng += (int)(bs / p->block_size); } const int64_t tier = TierExec::device_bytes(entry, ng, TierExec::sizes(entry, ctx, bs)); f.staging += tier; @@ -3232,8 +3238,11 @@ int Engine::configure_kv() { shard_off[i] = slot; slot += ranks_[i]->kv.checkpoint_bytes(); } - /* A slot holds linear state or a trunk's window, never both (KVGroupPlan::win_snap). */ - const char* what = ranks_[0]->kv.has_window_snapshot() ? "sliding-window" : "linear-state"; + /* A slot holds linear state, a trunk's window (KVGroupPlan::win_snap), or both. */ + bool linear = false; + for (const KVGroupPlan& p : ranks_[0]->kv.plans()) linear = linear || p.stateful(); + const char* what = !ranks_[0]->kv.has_window_snapshot() ? "linear-state" + : linear ? "linear-state + sliding-window" : "sliding-window"; const bool sized_auto = cfg_.checkpoint_slots < 0; if (sized_auto) RAD_TRY(size_checkpoint_store(slot, what)); const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0; @@ -3283,7 +3292,9 @@ int Engine::configure_kv() { * sessions view reads. The flags gate only the mover, below. */ { const bool tier_asked = cfg_.prefix_cache_mib > 0; - const std::vector& cg = ranks_[0]->prefix.cached_groups(); + /* An entry's blocks, one group per block: a cached group whose blocks are shorter than + * the entry appears once for each of its blocks (PrefixCache::entry_groups). */ + const std::vector& cg = ranks_[0]->prefix.entry_groups(); /* One slot holds the whole engine's entry: the groups every rank holds alike * (rad_kv_group_replicated) once, at the front, then every rank's own shard in its own * window. Shards can differ or be empty (uneven heads, rad_kv_group_zero). The layout is diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index c1a3eb7a..506e44bd 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -270,12 +270,12 @@ int KVManager::plan_groups(const std::vector& groups, const Config& checkpoint_bytes_ = 0; window_ck_bytes_ = 0; for (const auto& p : plans_) if (p.stateful()) checkpoint_bytes_ += p.bytes_per_state; - /* Then the window behind a checkpoint, after the linear state (see has_window_snapshot). */ - bool has_state = false; - for (const auto& p : plans_) has_state = has_state || p.stateful(); + /* Then the window behind a checkpoint, after the linear state (see has_window_snapshot). A + * trunk's window rides in the slot whether or not linear state is beside it: a hit resumes at + * a snapshot either way, and without the window there it could not resume at all. */ for (size_t i = 1; i < plans_.size(); ++i) { KVGroupPlan& p = plans_[i]; - p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 && + p.win_snap = p.kind == RAD_KV_WINDOW && p.window_blocks > 0 && !p.runtime_win && !groups[i].drafter; if (p.win_snap && !p.zero && p.n_layers > 0) window_ck_bytes_ += p.window_blocks * p.bytes_per_block; diff --git a/core/mem/kv.h b/core/mem/kv.h index 7786569f..2f9128d3 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -121,10 +121,9 @@ struct KVGroupPlan { return runtime_tokens > 0 && block_size > 0 ? (runtime_tokens + block_size - 1) / block_size : 0; } - /* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Set only for a - * trunk group of a model with no linear state. A drafter's window is recomputed by draft - * refill, and a model with linear state re-prefills a hit on a windowed trunk, so neither - * snapshot would be read. */ + /* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot), after any + * linear state. Set for a trunk group; a drafter's window is recomputed by draft refill, so + * its snapshot would not be read. */ bool win_snap = false; int64_t n_blocks = 0; /* paged groups: blocks the group addresses (its context) */ diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h index cdb79a5a..a42b7530 100644 --- a/core/mem/kvtier.h +++ b/core/mem/kvtier.h @@ -79,7 +79,7 @@ struct TierJob { }; Kind kind = Kind::WriteBack; BlockHash key; - /* Per cached group, in PrefixCache::cached_groups() order: the blocks to read for a + /* One per entry block, in PrefixCache::entry_groups() order: the blocks to read for a * write-back, or the blocks the engine allocated for a promotion. */ std::vector blocks; int32_t host_slot = -1; diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index da2a2c9a..d73906c7 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -5,6 +5,7 @@ #include #include +#include #include namespace rad { @@ -144,6 +145,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ block_size_ = 0; interval_ = 0; groups_.clear(); + per_.clear(); + entry_groups_.clear(); map_.clear(); lru_.clear(); ck_by_prefix_.clear(); ck_by_session_.clear(); /* set_policy() may override this afterwards. */ @@ -156,12 +159,17 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ return RAD_OK; } - /* Granularity is the first full-attention group's block size, since that is what a hit - * reuses. Paged groups with another block size are not cached and are named in the report. */ + /* Every paged group but a windowed one is cached. An entry covers the lcm of their block + * sizes, and holds that over a group's block size of the group's blocks: a hit then ends on + * a block of every group, which adopt() needs. The chunk quantum is a multiple of every paged + * group's block (core/sched/geometry.cpp), so the lcm divides every checkpoint position. */ for (const auto& p : kv->plans()) { - if (p.kind == RAD_KV_FULL && block_size_ == 0) block_size_ = p.block_size; if (p.stateful()) has_linear_ = true; + if (p.paged() && p.kind != RAD_KV_WINDOW && p.block_size > 0) + block_size_ = block_size_ > 0 ? std::lcm(block_size_, p.block_size) : p.block_size; } + /* With only windowed groups, nothing is indexed and a hit is a window snapshot alone, keyed + * on the chain at the first group's block. */ if (block_size_ == 0) { for (const auto& p : kv->plans()) if (p.paged()) { block_size_ = p.block_size; break; } } @@ -170,20 +178,25 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ RAD_WARN("%s", report_.c_str()); return RAD_OK; } - std::string skipped; + std::string skipped, split; for (const auto& p : kv->plans()) { if (!p.paged()) continue; /* A window group is not prefix-cached. Its blocks below the window are recycled, adopt() * would overfill a table capped at window_blocks, and a hit does not set first_block_pos. - * A drafter or windowed layer's cache then starts where the hit ended. */ + * A checkpoint slot can carry a trunk's window instead (KVManager::has_window_snapshot); + * a drafter or a windowed layer without one starts its cache where the hit ended. */ if (p.kind == RAD_KV_WINDOW) { - skipped += fmt(" group '%s' is windowed (%lld blocks): not cached\n", - p.name.c_str(), (long long)p.window_blocks); + skipped += fmt(" group '%s' is windowed (%lld blocks): not cached%s\n", + p.name.c_str(), (long long)p.window_blocks, + p.win_snap ? "; a checkpoint slot carries its window" : ""); continue; } - if (p.block_size == block_size_) groups_.push_back(p.index); - else skipped += fmt(" group '%s' block %lld != cache granularity %lld: not cached\n", - p.name.c_str(), (long long)p.block_size, (long long)block_size_); + groups_.push_back(p.index); + per_.push_back((int32_t)(block_size_ / p.block_size)); + for (int64_t k = 0; k < block_size_ / p.block_size; ++k) entry_groups_.push_back(p.index); + if (p.block_size != block_size_) + split += fmt(" group '%s' block %lld: %lld blocks an entry\n", p.name.c_str(), + (long long)p.block_size, (long long)(block_size_ / p.block_size)); } /* An entry can be demoted only when the host tier can hold every group in it. A streamed @@ -209,8 +222,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ /* A checkpoint is found by the chained hash at its position, which exists only on * block boundaries, so an interval off the block grid would never hit. */ RAD_ERR("the checkpoint interval resolves to %lld (from --checkpoint-interval %lld, " - "rounded up to the chunk quantum), which is not a multiple of the attention " - "block size %lld, so no checkpoint would ever hit (spec §7.3)", + "rounded up to the chunk quantum), which is not a multiple of the cache's " + "%lld-token entry, so no checkpoint would ever hit (spec §7.3)", (long long)interval_, (long long)cfg.checkpoint_interval, (long long)block_size_); return RAD_E_INVAL; @@ -218,13 +231,14 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ } enabled_ = true; - report_ = fmt("prefix cache: %zu paged group(s) at %lld-token blocks; linear checkpoints " + report_ = fmt("prefix cache: %zu paged group(s) in %lld-token entries; checkpoints " "every %lld tokens (%lld slots of %s a rank, pinned host memory), retention " "'%s'\n", groups_.size(), (long long)block_size_, (long long)(has_linear_ ? interval_ : 0), (long long)kv->checkpoint_slots(), humanb(kv->checkpoint_bytes()).c_str(), policy_->name()); + report_ += split; report_ += skipped; if (!demotable_) { /* Stated whether or not a host tier is configured. */ @@ -306,7 +320,7 @@ CacheHit PrefixCache::lookup(const std::vector& tokens, if (departed && matched > 0 && map_.find(hs[(size_t)matched - 1])->second.n_children >= 2) hit.branch_at = (int32_t)(matched * block_size_); - /* Back a full hit off by one block so one token remains to compute a logit from. */ + /* Back a full hit off by one entry so one token remains to compute a logit from. */ if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched; auto deepest = [&](int64_t limit) { return deepest_ckpt(hs, limit); }; @@ -336,8 +350,9 @@ CacheHit PrefixCache::lookup(const std::vector& tokens, if (blocks_out) for (int64_t b = 0; b < matched; ++b) { const Entry& e = map_.find(hs[(size_t)b])->second; - for (size_t g = 0; g < groups_.size(); ++g) - (*blocks_out)[g].push_back(e.blocks[g]); + for (size_t k = 0, g = 0; g < groups_.size(); ++g) + for (int32_t j = 0; j < per_[g]; ++j, ++k) + (*blocks_out)[g].push_back(e.blocks[k]); } /* A hit is a use for the tiers' idle clock too; otherwise a prefix hit every turn, or one just * promoted for this lookup, would look idle since its publish. */ @@ -368,6 +383,23 @@ CacheHit PrefixCache::lookup(const std::vector& tokens, return hit; } +bool PrefixCache::retain_entry(const std::vector>& bt, int64_t b, + std::vector* out) { + out->assign(entry_groups_.size(), -1); + size_t k = 0; + for (size_t g = 0; g < groups_.size(); ++g) + for (int32_t j = 0; j < per_[g]; ++j, ++k) { + const int32_t blk = bt[g][(size_t)(b * per_[g] + j)]; + if (kv_->retain_block(groups_[g], blk) >= 0) { (*out)[k] = blk; continue; } + /* Unwind exactly what was retained: anything else leaks a block or frees one under a + * live sequence. */ + for (size_t i = 0; i < k; ++i) kv_->release_block(entry_groups_[i], (*out)[i]); + out->clear(); + return false; + } + return true; +} + int PrefixCache::insert(uint64_t session, const std::vector& tokens, const std::vector& mm, @@ -379,7 +411,8 @@ int PrefixCache::insert(uint64_t session, const int64_t n_full = n_tokens / block_size_; if (n_full <= 0) return RAD_OK; - for (const auto& bt : blocks) if ((int64_t)bt.size() < n_full) return RAD_E_INVAL; + for (size_t g = 0; g < blocks.size(); ++g) + if ((int64_t)blocks[g].size() < n_full * per_[g]) return RAD_E_INVAL; std::vector hs = chain_all(tokens, mm, n_full); const uint64_t now = rad_mono_ns(); @@ -397,17 +430,8 @@ int PrefixCache::insert(uint64_t session, * tier copy goes (IdleTiers::rebound). An entry with a promotion in flight is left * alone. */ if (!tiers_ || !tiers_->resident_off_device(h)) continue; - std::vector mine(groups_.size(), -1); - size_t held = 0; - for (; held < groups_.size(); ++held) { - const int32_t blk = blocks[held][(size_t)b]; - if (kv_->retain_block(groups_[held], blk) < 0) break; - mine[held] = blk; - } - if (held != groups_.size()) { - for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], mine[g]); - return RAD_E_STATE; - } + std::vector mine; + if (!retain_entry(blocks, b, &mine)) return RAD_E_STATE; Entry& e = it->second; e.blocks = std::move(mine); e.used_ns = now; @@ -419,19 +443,7 @@ int PrefixCache::insert(uint64_t session, } Entry e; - e.blocks.assign(groups_.size(), -1); - size_t held = 0; - for (; held < groups_.size(); ++held) { - int32_t blk = blocks[held][(size_t)b]; - if (kv_->retain_block(groups_[held], blk) < 0) break; - e.blocks[held] = blk; - } - if (held != groups_.size()) { - /* Unwind exactly what was retained: anything else leaks a block or frees one under a - * live sequence. */ - for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], e.blocks[g]); - return RAD_E_STATE; - } + if (!retain_entry(blocks, b, &e.blocks)) return RAD_E_STATE; e.tokens.assign(tokens.begin() + b * block_size_, tokens.begin() + (b + 1) * block_size_); e.used_ns = now; @@ -534,18 +546,20 @@ std::vector PrefixCache::restorable_from(const std::vector& int64_t PrefixCache::restore_room() const { if (!kv_ || groups_.empty()) return 0; int64_t room = INT64_MAX; - for (int32_t g : groups_) room = std::min(room, kv_->total_blocks(g) - kv_->held_blocks(g)); + for (size_t i = 0; i < groups_.size(); ++i) + room = std::min(room, (kv_->total_blocks(groups_[i]) - kv_->held_blocks(groups_[i])) / + std::max(per_[i], 1)); return std::max(0, room); } int64_t PrefixCache::trim_for(const std::vector& tokens, - const std::vector& mm, int64_t n_blocks) { + const std::vector& mm, int64_t n_entries) { /* Without a host tier a trim erases, and making room for a restore must lose nothing. */ - if (!enabled_ || n_blocks <= 0 || !tiers_ || !tiers_->host_on()) return 0; + if (!enabled_ || n_entries <= 0 || !tiers_ || !tiers_->host_on()) return 0; const std::vector hs = chain_all(tokens, mm, (int64_t)tokens.size() / block_size_); std::unordered_set spare(hs.begin(), hs.end()); for (const auto& h : held_) spare.insert(h.first); - return trim_sparing(n_blocks, &spare); + return trim_sparing(n_entries, &spare); } void PrefixCache::drop_offdevice(const BlockHash& key) { @@ -563,14 +577,15 @@ void PrefixCache::drop_offdevice(const BlockHash& key) { int PrefixCache::rebind(const BlockHash& key, const std::vector& blocks) { auto it = map_.find(key); if (it == map_.end()) return RAD_E_NOTFOUND; - if (blocks.size() != groups_.size()) return RAD_E_SHAPE; + if (blocks.size() != entry_groups_.size()) return RAD_E_SHAPE; for (int32_t b : blocks) if (b < 0) return RAD_E_INVAL; /* The reservation's reference becomes the cache's: KVManager::reserve_block left each block at * refcount one with no sequence attached, and the cache's release path frees it from now on. * No extra retain. */ Entry& e = it->second; e.blocks = blocks; - for (size_t g = 0; g < groups_.size(); ++g) kv_->cache_reserved_block(groups_[g], blocks[g]); + for (size_t k = 0; k < entry_groups_.size(); ++k) + kv_->cache_reserved_block(entry_groups_[k], blocks[k]); if (!e.in_lru) { /* A restore is a use: a request is about to hit it. */ e.used_ns = rad_mono_ns(); @@ -582,8 +597,8 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector& blocks } bool PrefixCache::shared_with_live(const Entry& e) const { - for (size_t g = 0; g < groups_.size(); ++g) - if (kv_->block_refcount(groups_[g], e.blocks[g]) > 1) return true; + for (size_t k = 0; k < entry_groups_.size() && k < e.blocks.size(); ++k) + if (kv_->block_refcount(entry_groups_[k], e.blocks[k]) > 1) return true; return false; } @@ -595,7 +610,8 @@ bool PrefixCache::same_tokens(const Entry& e, const int32_t* src) const { } void PrefixCache::release_blocks(const Entry& e) { - for (size_t g = 0; g < groups_.size(); ++g) kv_->release_block(groups_[g], e.blocks[g]); + for (size_t k = 0; k < entry_groups_.size() && k < e.blocks.size(); ++k) + kv_->release_block(entry_groups_[k], e.blocks[k]); } int64_t PrefixCache::evict_lru(int64_t n) { @@ -634,16 +650,16 @@ int64_t PrefixCache::evict_lru(int64_t n) { return done; } -int64_t PrefixCache::trim(int64_t n_blocks) { return trim_sparing(n_blocks, nullptr); } +int64_t PrefixCache::trim(int64_t n_entries) { return trim_sparing(n_entries, nullptr); } -int64_t PrefixCache::trim_sparing(int64_t n_blocks, +int64_t PrefixCache::trim_sparing(int64_t n_entries, const std::unordered_set* spare) { /* Tiers attached but off count as no tiers: no copy will ever land, so do not wait for one. */ const bool keep = tiers_ && tiers_->host_on(); const uint64_t now = rad_mono_ns(); int64_t done = 0; auto it = lru_.begin(); - for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_blocks && seen > 0; + for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_entries && seen > 0; --seen) { const BlockHash h = *it; auto m = map_.find(h); @@ -714,11 +730,11 @@ int64_t PrefixCache::drop_clean() { } /* The KV manager tracks how many cache-held blocks are at refcount one. One group only: the paged - * groups share a token axis and an entry is one block in each, so summing groups would multiply - * the answer. Off-device entries hold no blocks and count for nothing. */ + * groups share a token axis and an entry is blocks_per_entry() blocks in each, so summing groups + * would multiply the answer. Off-device entries hold no blocks and count for nothing. */ int64_t PrefixCache::unshared_tokens() const { - if (!kv_ || groups_.empty() || block_size_ <= 0) return 0; - return kv_->cache_only_blocks(groups_[0]) * block_size_; + if (!kv_ || groups_.empty() || block_size_ <= 0 || per_.empty() || per_[0] <= 0) return 0; + return kv_->cache_only_blocks(groups_[0]) * (block_size_ / per_[0]); } void PrefixCache::clear() { @@ -1035,7 +1051,7 @@ int PrefixCache::release_session(const std::string& label, uint64_t id, int64_t /* A kept token keeps its whole block: the block holding it is what the next turn hits. */ const int64_t keep_blocks = (keep_tokens + block_size_ - 1) / block_size_; int64_t entry_bytes = 0; - for (int32_t g : groups_) { + for (int32_t g : entry_groups_) { const KVGroupPlan* p = kv_->plan(g); if (p) entry_bytes += p->bytes_per_block; } diff --git a/core/mem/prefix.h b/core/mem/prefix.h index b0a6016a..792dc7a3 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -23,6 +23,12 @@ * interval (next_checkpoint_after()), so a checkpoint is always written, at the cost of an * occasional short chunk. * + * Block sizes: an entry covers block_size() tokens, the lcm of the cached groups' block sizes, and + * holds block_size() / B blocks of a group whose blocks are B tokens. A model whose layers keep KV + * at different strides (a compressed group at one row per r tokens beside one per token) is cached + * in every group; a hit is then a multiple of every group's block. The chunk quantum is a multiple + * of every paged group's block (core/sched/geometry.cpp), so checkpoints land on entries. + * * Sizing: the cache holds a KV reference on every block it indexes, so pool demand scales with * live sessions, not running requests. Hit rate falls off a cliff with pool utilisation: intact * below about 75%, half gone by about 81%, and zero once the sessions no longer fit, because each @@ -207,6 +213,8 @@ public: * make reserve_checkpoint refuse every checkpoint and lookups search the wrong stride. */ int configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval); bool enabled() const { return enabled_; } + /* Tokens one entry covers: the lcm of the cached groups' block sizes. Hits, publishes and + * checkpoint keys are whole entries. */ int64_t block_size() const { return block_size_; } int64_t checkpoint_interval() const { return interval_; } const std::vector& cached_groups() const { return groups_; } @@ -214,6 +222,13 @@ public: * rows are addressed by the sequence's block ids, so entries stay in VRAM and are evicted * whole (docs/KV-STREAMING.md §4.1). */ bool demotable() const { return demotable_; } + /* Blocks of cached_groups()[i] in one entry: block_size() over that group's block size. */ + int64_t blocks_per_entry(size_t i) const { return i < per_.size() ? per_[i] : 0; } + /* The group of each block an entry holds, in the order of its block list (Entry::blocks, + * TierJob::blocks, rebind): cached_groups()[i] repeated blocks_per_entry(i) times. The idle + * tiers move an entry as these blocks, one per slot. Equal to cached_groups() when every + * cached group has the same block size. */ + const std::vector& entry_groups() const { return entry_groups_; } std::string report() const; /* Overrides the policy configure() installed from Config::checkpoint_policy (custom policies, @@ -222,12 +237,12 @@ public: const CheckpointPolicy& policy() const { return *policy_; } /* ---------------- full attention ---------------- */ - /* Longest cached prefix, in whole blocks, plus the checkpoint that covers the linear state + /* Longest cached prefix, in whole entries, plus the checkpoint that covers the linear state * for a prefix of it. `blocks_out`, when given, receives the block ids per cached group, in - * cached_groups() order, ready for KVManager::adopt(). + * cached_groups() order, ready for KVManager::adopt(): blocks_per_entry(i) of them an entry. * * Never returns the whole prompt: one token must remain to compute a logit from, so a full - * hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). `session`, + * hit is backed off by one entry. `cap`, when given, ends the hit early (HitCap). `session`, * when not 0, is the request being admitted: it takes over the snapshots on the chain it hit * (take_over). */ CacheHit lookup(const std::vector& tokens, @@ -235,7 +250,7 @@ public: std::vector>* blocks_out = nullptr, const HitCap* cap = nullptr, uint64_t session = 0) const; - /* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of + /* Publish the whole entries a sequence just filled. `blocks[i]` is the block table of * cached_groups()[i]. Takes a KV reference on every newly indexed block. */ int insert(uint64_t session, const std::vector& tokens, @@ -249,11 +264,12 @@ public: * idle tiers on, an entry whose host copy has landed moves to the host tier instead of being * forgotten; only one with no host copy is lost. */ int64_t evict_lru(int64_t n_entries); - /* Free up to `n_blocks` pool blocks for the scheduler's reserve without losing anything a - * later turn could reuse. One oldest-first walk that skips entries a live sequence also holds - * and, with the tiers on, entries whose host copy has not landed yet. Pressure that cannot - * wait goes to evict_lru. Returns how many blocks went back. */ - int64_t trim(int64_t n_blocks); + /* Give back up to `n_entries` entries' blocks for the scheduler's reserve without losing + * anything a later turn could reuse. One oldest-first walk that skips entries a live sequence + * also holds and, with the tiers on, entries whose host copy has not landed yet. Pressure + * that cannot wait goes to evict_lru. Returns how many entries went: each gave back + * blocks_per_entry(i) blocks of cached group i. */ + int64_t trim(int64_t n_entries); /* Give up every VRAM copy that costs nothing to drop: host copy landed and no running sequence * reading it. Used when the memory has a better use (the expert slab's loan). Entries still * shared are retried after a sequence frees blocks. Returns how many entries left VRAM. */ @@ -288,23 +304,25 @@ public: std::vector restorable_from(const std::vector& tokens, const std::vector& mm, int64_t fit = INT64_MAX, bool* cut = nullptr) const; - /* Entries a restore can place now: free blocks against the carve, the least over the cached - * groups. Lent blocks count, since KVManager::reserve_blocks recalls the loan for them. */ + /* Entries a restore can place now: free blocks against the carve over the blocks an entry + * takes in the group, the least over the cached groups. Lent blocks count, since + * KVManager::reserve_blocks recalls the loan for them. */ int64_t restore_room() const; /* Room for a restore of this prompt's chain: trim(), sparing the chain itself (its blocks * would only have to come back too) and every chain a waiting request holds (hold()), whose * next attempt would restore it again. Only entries whose host copy has landed leave VRAM, - * so nothing is lost; with no host tier it takes nothing. */ + * so nothing is lost; with no host tier it takes nothing. In entries, as trim(). */ int64_t trim_for(const std::vector& tokens, const std::vector& mm, - int64_t n_blocks); + int64_t n_entries); /* The tiers lost the bytes. Erases the entry without releasing blocks: an off-device entry * owns none, and its recorded ids now belong to other sequences. Installed as * IdleTiers::set_drop_sink. */ void drop_offdevice(const BlockHash& key); - /* A restore finished and the entry's blocks now live at these ids. The restore's raw - * reservations (KVManager::reserve_block) become cache-held references. */ + /* A restore finished and the entry's blocks now live at these ids, one per entry_groups() + * slot. The restore's raw reservations (KVManager::reserve_block) become cache-held + * references. */ int rebind(const BlockHash& key, const std::vector& blocks); @@ -404,7 +422,8 @@ public: private: struct Entry { - std::vector blocks; /* one per cached group, in groups_ order */ + /* blocks_per_entry(i) per cached group, in groups_ order: entry_groups_[k] owns blocks[k] */ + std::vector blocks; std::vector tokens; /* the block's token ids, compared on hit */ /* On the LRU exactly while the cache holds the blocks; `lru` is valid only then. An * off-device entry owns no block, so eviction must not reach it. */ @@ -438,14 +457,19 @@ private: int64_t n_blocks) const; void touch(const BlockHash& h, uint64_t now_ns) const; /* trim(), leaving the entries in `spare` (when given) where they are. */ - int64_t trim_sparing(int64_t n_blocks, + int64_t trim_sparing(int64_t n_entries, const std::unordered_set* spare); /* A live sequence also holds one of this entry's blocks, so releasing it frees nothing. */ bool shared_with_live(const Entry& e) const; /* Whether `e` holds the block_size_ token ids at `src`, so a hash collision is a miss. */ bool same_tokens(const Entry& e, const int32_t* src) const; - /* Gives the entry's block in every group back to the KV manager. */ + /* Gives the entry's blocks in every group back to the KV manager. */ void release_blocks(const Entry& e); + /* Takes the cache's reference on the blocks of entry `b` of a sequence's tables `bt` (one per + * cached group) into `out`, entry_groups_ order; on a refusal releases exactly what it took + * and returns false. */ + bool retain_entry(const std::vector>& bt, int64_t b, + std::vector* out); /* Retire one snapshot: free its slot and tell the tiers. The session index is left to the * caller. */ void retire_ckpt(std::unordered_map::iterator it); @@ -474,6 +498,8 @@ private: int64_t interval_ = 0; std::vector groups_; /* paged groups this cache indexes */ bool demotable_ = false; /* the host tier can hold every group in an entry */ + std::vector per_; /* blocks of groups_[i] an entry holds */ + std::vector entry_groups_; /* the group of each of an entry's blocks */ bool has_linear_ = false; mutable std::unordered_map map_; diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp index 12a38194..21d70712 100644 --- a/core/runtime/tierexec.cpp +++ b/core/runtime/tierexec.cpp @@ -87,11 +87,20 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, verify_ = std::getenv("RADIANCE_DEBUG_TIER_VERIFY") != nullptr; verify_rep_ = verify_ && !leader_ && rep_bytes_ > 0; + /* A group whose blocks are shorter than an entry is listed once per block it holds there. */ + size_t n_groups = 0; + for (size_t i = 0; i < gi_.size(); ++i) { + bool seen = false; + for (size_t j = 0; j < i && !seen; ++j) seen = gi_[j].g == gi_[i].g; + if (!seen) ++n_groups; + } + const std::string blocks = + n_groups != gi_.size() ? fmt(" in %zu blocks", gi_.size()) : std::string(); char buf[400]; std::snprintf(buf, sizeof buf, - "kv tier transfer: %zu paged group(s), %s an entry%s%s%s, batches of %d through " - "gather_rows/scatter_rows at u8", - gi_.size(), humanb(entry_bytes_).c_str(), + "kv tier transfer: %zu paged group(s), %s an entry%s%s%s%s, batches of %d " + "through gather_rows/scatter_rows at u8", + n_groups, humanb(entry_bytes_).c_str(), blocks.c_str(), rep_bytes_ > 0 ? " (" : "", rep_bytes_ > 0 ? humanb(rep_bytes_).c_str() : "", rep_bytes_ > 0 ? " of it replicated on every rank and held once a slot)" : "", @@ -143,7 +152,8 @@ int TierExec::slot_layout(const std::vector& ranks, return RAD_E_STATE; } L.rep_bytes += p0->bytes_per_block; - L.replicated.push_back(p0->name); + if (std::find(L.replicated.begin(), L.replicated.end(), p0->name) == L.replicated.end()) + L.replicated.push_back(p0->name); } int64_t slot = L.rep_bytes; for (size_t i = 0; i < ranks.size(); ++i) { diff --git a/core/runtime/tierexec.h b/core/runtime/tierexec.h index 40c2def2..37bffc21 100644 --- a/core/runtime/tierexec.h +++ b/core/runtime/tierexec.h @@ -46,8 +46,9 @@ namespace rad { class TierExec { public: ~TierExec(); - /* `groups` is PrefixCache::cached_groups(): the paged groups an entry holds a block in, in the - * order of the entry's `blocks` vector. The staging layout is derived from them here only. + /* `groups` is PrefixCache::entry_groups(): the group of each block an entry holds, in the + * order of the entry's `blocks` vector (a group with blocks shorter than the entry is listed + * once per block). The staging layout is derived from them here only. * `max_batch` is the staging buffer in entries, `max_copy` the most entries per copy out and * `max_chain` the longest restore chain; the index buffers are sized from the last two. */ int configure(Registry* reg, KVManager* kv, IdleTiers* tiers, diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index e7e329a2..fd53ac05 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -172,7 +172,7 @@ struct IPrefixCache { /* Longest cached prefix, plus the checkpoint covering the linear state for a prefix of it. * `blocks_out` receives block ids per cached group, in cached_groups() order, for - * IKVManager::adopt. `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */ + * IKVManager::adopt: n_attn_tokens over the group's own block size of them. `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */ virtual CacheHit lookup(const Request& r, std::vector>* blocks_out, const HitCap* cap) const = 0; virtual const std::vector& cached_groups() const = 0; @@ -187,10 +187,12 @@ struct IPrefixCache { /* Release the least recently used entries and their KV references. The scheduler tries this * before preempting a running request. */ virtual int64_t evict(int64_t n_entries) = 0; - /* Free up to `n_blocks` for the reserve without losing anything a later turn needs. Unlike + /* Free up to `n_entries` for the reserve without losing anything a later turn needs. Unlike * evict(), it skips entries a live sequence still holds (no block would be freed) and entries - * whose only copy is in VRAM. Returns the number of blocks freed. */ - virtual int64_t trim(int64_t n_blocks) = 0; + * whose only copy is in VRAM. An entry is one block in each cached group, or more in a group + * whose blocks are shorter than the entry (PrefixCache::blocks_per_entry). Returns the number + * of entries freed. */ + virtual int64_t trim(int64_t n_entries) = 0; /* Drop every entry in every tier. Implementations with idle tiers must override this: there, * evict() keeps an entry whose host copy has landed. Returns the number of entries dropped. */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 1664614f..960826da 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -10,6 +10,7 @@ #include #include #include +#include namespace rad { @@ -97,9 +98,9 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac if (kv->block_tokens((int32_t)i) <= 0) continue; ++n_paged; const auto& cg = pc->cached_groups(); - /* Snapshots are taken only where the trunk has a window to snapshot too - * (ChunkGeometry::window_ckpt); without them no drafter window rides in one. */ - if (cfg.prefix_cache && geo_.window_ckpt && kv->window_snapshot((int32_t)i) && + /* Snapshots are taken only on a checkpoint grid (ChunkGeometry::checkpoints()), the + * window's alone or beside linear state; without one no window rides in a slot. */ + if (cfg.prefix_cache && geo_.checkpoints() && kv->window_snapshot((int32_t)i) && std::find(cg.begin(), cg.end(), (int32_t)i) == cg.end()) ++n_snap; } @@ -110,19 +111,27 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac } /* The trunk's share: a paged group a trunk layer reads (a bound layer below the trunk's layer * count; a drafter borrows from base_layer up) that the cache does not index. Recomputing the - * tail cannot repair that hole; see scheduler.h. */ + * tail cannot repair that hole; see scheduler.h. A windowed group is restored by a hit that + * resumes at a window snapshot (a checkpoint slot carries the trunk's window, with or without + * linear state beside it); any other such group refuses every hit. */ hit_holes_trunk_ = false; + hit_needs_window_ = false; for (size_t i = 0; i < prog.kv_groups.size(); ++i) { if (kv->block_tokens((int32_t)i) <= 0) continue; bool trunk = false; for (int l : prog.kv_groups[i].layers) if (l < prog.meta.n_layers) { trunk = true; break; } if (!trunk) continue; const std::vector& cg = pc->cached_groups(); - if (std::find(cg.begin(), cg.end(), (int32_t)i) == cg.end()) { hit_holes_trunk_ = true; break; } + if (std::find(cg.begin(), cg.end(), (int32_t)i) != cg.end()) continue; + if (prog.kv_groups[i].decl.kind == RAD_KV_WINDOW) hit_needs_window_ = true; + else hit_holes_trunk_ = true; } if (hit_holes_trunk_ && cfg.prefix_cache) + RAD_INFO("prefix cache: a trunk layer's paged group is neither prefix-cached nor carried " + "by a checkpoint slot -- a hit re-prefills"); + else if (hit_needs_window_ && cfg.prefix_cache) RAD_INFO("prefix cache: a trunk layer's windowed group is not prefix-cached -- a hit " - "resumes from a window snapshot (a checkpoint slot) or re-prefills"); + "resumes from a window snapshot (a checkpoint slot)"); if (cfg.prefill_interleave > 0) RAD_INFO("scheduler: --prefill-interleave %lld: after a prefill chunk that leaves its " "prompt unfinished while other sequences decode, the next %lld steps carry " @@ -470,14 +479,26 @@ void Scheduler::trim_prefix_cache() { if (!pc_ || !cfg_.prefix_cache) return; const std::vector& cg = pc_->cached_groups(); if (cg.empty()) return; - const int32_t g = cg[0]; - const int64_t total = kv_->total_blocks(g); - if (total <= 0) return; - const int64_t reserve = total / 4; /* a quarter of the pool stays free */ - /* Free against the carve, not free_blocks(): on an elastic pool free_blocks() is bounded by - * the live mark, so a pool that returned its unused top would read as nearly full and the - * trim would drain the cache for room the pool can grow back into. */ - const int64_t short_by = reserve - (total - kv_->held_blocks(g)); + /* An entry covers the lcm of the cached groups' blocks and holds that over a group's block of + * its blocks (PrefixCache::blocks_per_entry); the trim asks for entries, as many as the group + * furthest short needs. */ + int64_t entry = 0; + for (int32_t g : cg) { + const int64_t bs = kvgeom_.g[(size_t)g].block_size; + if (bs > 0) entry = entry > 0 ? std::lcm(entry, bs) : bs; + } + int64_t short_by = 0; + for (int32_t g : cg) { + const int64_t total = kv_->total_blocks(g), bs = kvgeom_.g[(size_t)g].block_size; + if (total <= 0 || bs <= 0) continue; + const int64_t reserve = total / 4; /* a quarter of the pool stays free */ + /* Free against the carve, not free_blocks(): on an elastic pool free_blocks() is bounded + * by the live mark, so a pool that returned its unused top would read as nearly full and + * the trim would drain the cache for room the pool can grow back into. */ + const int64_t blocks = reserve - (total - kv_->held_blocks(g)); + const int64_t per = std::max(entry / bs, 1); + if (blocks > 0) short_by = std::max(short_by, (blocks + per - 1) / per); + } if (short_by > 0) (void)pc_->trim(short_by); } @@ -1158,9 +1179,10 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { (unsigned long long)r.id, (long long)h.n_attn_tokens, (long long)reuse); } /* A window snapshot covers the trunk's windowed groups at the checkpoint only. The lookup - * clamped the hit to it (a window counts as state there), so a hit with a slot is exactly - * at a snapshot; one without is no hit. */ - const bool win_hit = geo_.window_ckpt && kv_->has_window_snapshot() && reuse > 0 && + * clamped the hit to it (a window counts as state there, and linear state beside it + * resumes there too), so a hit with a slot is exactly at a snapshot; one without is no + * hit. */ + const bool win_hit = geo_.checkpoints() && kv_->has_window_snapshot() && reuse > 0 && h.checkpoint_slot >= 0 && reuse == h.n_linear_tokens; /* Windowed-group clamp: the trunk's own KV includes a paged group the cache does not @@ -1173,7 +1195,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { * * A drafter's own group (bound at base_layer and above) is not this clamp's business: * draft refill caps the hit so the recompute covers the drafter's window. */ - if (reuse > 0 && hit_holes_trunk_ && !win_hit) { + if (reuse > 0 && (hit_holes_trunk_ || (hit_needs_window_ && !win_hit))) { reuse = 0; s.hit_cut = SchedReq::HitCut::Window; RAD_DEBUG("admit %llu: prefix hit %lld zeroed -- a trunk paged group is not " diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 5efb9ee7..f33d248e 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -491,12 +491,16 @@ private: * place. */ bool hit_holes_draft_ = true; /* Does a hit leave a hole in the trunk: a paged group with a trunk layer (bound below - * meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index? - * Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */ + * meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index and + * no checkpoint slot carries? Unlike a drafter hole, recomputing the tail cannot repair it; + * every hit is refused (admit_one). */ bool hit_holes_trunk_ = false; /* The end-of-generation ids, sorted and unique (set_eog), and a lookup in them. */ std::vector eog_; bool is_eog(int32_t id) const; + /* A windowed trunk group, which the cache does not index: a hit stands only where it resumes + * at a window snapshot (IKVManager::has_window_snapshot), which restores the window. */ + bool hit_needs_window_ = false; /* R-SWA: the groups whose KV manager carries per-sequence runtime windows, with the W a * sequence is armed with (IKVManager::runtime_window_tokens). Empty for every model that does * not declare one, in which case admission and commit are exactly as before. A sequence with diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index 41df9c91..94aa2592 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -1827,21 +1828,24 @@ TEST(kv_window_snapshot_rows_and_seed) { kv.free_sequence(2); } -/* A window is snapshotted only where a hit resumes from it: the trunk's window in a model without - * linear state. With linear state a hit on a windowed trunk re-prefills, and a drafter's window is - * recomputed by draft refill, so a window section there would be copied and never read. */ +/* A window is snapshotted only where a hit resumes from it: the trunk's window, with or without + * linear state beside it. A drafter's window is recomputed by draft refill, so a window section + * there would be copied and never read. */ TEST(kv_window_snapshot_only_where_a_hit_resumes_from_it) { KVGroupInfo w = paged_group("swa", RAD_KV_WINDOW, 2, 16, { 6 }, 64); const Config cfg = small_config(); - { /* beside linear state: the slot holds only the state */ + { /* beside linear state: the slot holds the state, then the window. Without the window a + * hit could not resume on such a model at all (the scheduler refuses a trunk hole). */ std::vector g = hybrid_groups(); g.push_back(w); Pools p; CHECK_OK(configure_pools(p, cfg)); KVManager kv; CHECK_OK(kv.configure(g, cfg, p.kv())); - CHECK(!kv.has_window_snapshot()); - CHECK_EQ(kv.checkpoint_bytes(), 16384ll); + CHECK(kv.has_window_snapshot()); + const KVGroupPlan* wp = kv.plan(3); + REQUIRE(wp && wp->win_snap); + CHECK_EQ(kv.checkpoint_bytes(), 16384ll + wp->window_blocks * wp->bytes_per_block); } { /* a drafter's own window over a full-attention trunk */ std::vector g = hybrid_groups(/*with_linear=*/false); @@ -2421,6 +2425,222 @@ TEST(checkpoint_interval_must_be_a_block_multiple) { CHECK_EQ(f.pc.configure(f.cfg, &f.kv, f.cfg.checkpoint_interval), RAD_E_INVAL); } +/* ================================================================== mixed block sizes + * + * A model can keep KV at different strides: DeepSeek-V4's compressed attention stores one row per + * r tokens (a block of r) beside groups at one row a token. The cache indexes every such group at + * the lcm of their blocks, an entry holding lcm / B blocks of a B-token group, so a hit ends on a + * block of each and adopt() takes every group. Leaving the finer groups out left the trunk a hole + * the scheduler refuses every hit for. + */ +static KVGroupInfo gdn_group(std::vector layers) { + KVGroupInfo k; + k.name = "gdn"; + k.decl.kind = RAD_KV_LINEAR; + k.decl.dtype = RAD_F32; + k.decl.n_head_kv = 4; + k.decl.state_dim[0] = 16; + k.decl.state_dim[1] = 16; + k.layers = std::move(layers); + return k; +} + +/* Handles: 1 = the coarse group (`a`-token blocks), 2 = the fine one (`b`), 3 = linear state. */ +static std::vector mixed_groups(int64_t a, int64_t b, bool with_linear) { + std::vector g; + g.push_back(null_group()); + g.push_back(paged_group("coarse", RAD_KV_FULL, 2, a, { 0, 1 })); + g.push_back(paged_group("fine", RAD_KV_FULL, 1, b, { 2 })); + if (with_linear) g.push_back(gdn_group({ 3, 4 })); + return g; +} + +static std::vector head(const std::vector& v, int64_t n) { + return std::vector(v.begin(), v.begin() + std::min(n, (int64_t)v.size())); +} + +TEST(a_cache_over_mixed_block_sizes_indexes_every_group_at_their_lcm) { + for (const auto& ab : { std::pair{ 2, 1 }, { 2, 4 }, { 16, 2 } }) { + const int64_t a = ab.first, b = ab.second, L = std::lcm(a, b); + Fixture f; + REQUIRE_EQ(f.build_groups(mixed_groups(a, b, false)), RAD_OK); + REQUIRE(f.pc.enabled()); + CHECK_EQ(f.pc.block_size(), L); + CHECK(f.pc.cached_groups() == (std::vector{ 1, 2 })); + CHECK_EQ(f.pc.blocks_per_entry(0), L / a); + CHECK_EQ(f.pc.blocks_per_entry(1), L / b); + std::vector eg; + for (int64_t k = 0; k < L / a; ++k) eg.push_back(1); + for (int64_t k = 0; k < L / b; ++k) eg.push_back(2); + CHECK(f.pc.entry_groups() == eg); + /* Named once in the report, and nothing left out. */ + CHECK(f.pc.report().find("not cached") == std::string::npos); + CHECK(f.pc.report().find("blocks an entry") != std::string::npos); + const int64_t free1 = f.kv.free_blocks(1), free2 = f.kv.free_blocks(2); + + /* 101 tokens publish their whole entries: 96 or 100 of them. */ + const auto p = tok_run(300, 101); + const int64_t whole = 101 / L * L; + publish(f, 1, p, 101); + CHECK_EQ(f.pc.size(), whole / L); + const std::vector t1 = f.kv.block_table(1, 1), t2 = f.kv.block_table(1, 2); + for (int64_t k = 0; k < whole / a; ++k) CHECK_EQ(f.kv.block_refcount(1, t1[(size_t)k]), 2); + for (int64_t k = 0; k < whole / b; ++k) CHECK_EQ(f.kv.block_refcount(2, t2[(size_t)k]), 2); + /* The partial block past the last entry is the sequence's alone. */ + if ((int64_t)t2.size() > whole / b) CHECK_EQ(f.kv.block_refcount(2, t2[(size_t)(whole / b)]), 1); + + /* A longer prompt hits every published entry, with each group's own blocks. */ + auto longer = p; + for (int i = 0; i < 40; ++i) longer.push_back(900 + i); + std::vector> got; + CHECK_EQ(f.pc.lookup(longer, {}, &got).n_attn_tokens, (int32_t)whole); + REQUIRE_EQ(got.size(), 2u); + CHECK(got[0] == head(t1, whole / a)); + CHECK(got[1] == head(t2, whole / b)); + /* A full hit backs off one entry, and a divergence ends the hit on the entry below it. */ + CHECK_EQ(f.pc.lookup(head(p, whole), {}).n_attn_tokens, (int32_t)(whole - L)); + auto edited = p; + edited[37] += 5000; + CHECK_EQ(f.pc.lookup(edited, {}).n_attn_tokens, (int32_t)(37 / L * L)); + + /* The hit adopts in every group, and the blocks are shared, not copied. */ + CHECK_OK(f.kv.add_sequence(2)); + for (size_t i = 0; i < 2; ++i) + CHECK_OK(f.kv.adopt(2, f.pc.cached_groups()[i], got[i], whole)); + CHECK_OK(f.kv.ensure(2, (int64_t)longer.size())); + CHECK_EQ(f.kv.block_refcount(2, t2[0]), 3); + CHECK(head(f.kv.block_table(2, 2), whole / b) == head(t2, whole / b)); + f.kv.free_sequence(1); + f.kv.free_sequence(2); + CHECK_EQ(f.kv.block_refcount(1, t1[0]), 1); + CHECK_EQ(f.pc.unshared_tokens(), whole); + + /* Eviction takes the deepest entry: its blocks in both groups go back together. */ + const int64_t e1 = f.kv.free_blocks(1), e2 = f.kv.free_blocks(2); + CHECK_EQ(f.pc.evict_lru(1), 1ll); + CHECK_EQ(f.kv.free_blocks(1), e1 + L / a); + CHECK_EQ(f.kv.free_blocks(2), e2 + L / b); + CHECK_EQ(f.pc.lookup(longer, {}).n_attn_tokens, (int32_t)(whole - L)); + CHECK_EQ(f.pc.unshared_tokens(), whole - L); + /* trim() counts entries too. */ + CHECK_EQ(f.pc.trim(2), 2ll); + CHECK_EQ(f.kv.free_blocks(1), e1 + 3 * (L / a)); + CHECK_EQ(f.kv.free_blocks(2), e2 + 3 * (L / b)); + /* A restore's room is in entries: the group shortest of whole entries decides. */ + const int64_t room = std::min((f.kv.total_blocks(1) - f.kv.held_blocks(1)) / (L / a), + (f.kv.total_blocks(2) - f.kv.held_blocks(2)) / (L / b)); + CHECK_EQ(f.pc.restore_room(), room); + f.pc.clear(); + CHECK_EQ(f.kv.free_blocks(1), free1); + CHECK_EQ(f.kv.free_blocks(2), free2); + } +} + +/* A publish whose tables are short of an entry's blocks in one group is refused whole, and one + * that cannot take a reference in a later group gives back what it took in the earlier ones. */ +TEST(a_mixed_publish_short_of_a_groups_blocks_is_refused_and_takes_nothing) { + Fixture f; + REQUIRE_EQ(f.build_groups(mixed_groups(2, 1, false)), RAD_OK); + const auto p = tok_run(40, 32); + CHECK_OK(f.kv.add_sequence(1)); + CHECK_OK(f.kv.ensure(1, 32)); + std::vector> bt = { f.kv.block_table(1, 1), f.kv.block_table(1, 2) }; + std::vector> shorter = bt; + shorter[1].resize(31); /* 16 entries need 32 one-token blocks */ + CHECK_EQ(f.pc.insert(1, p, {}, shorter, 32), RAD_E_INVAL); + CHECK_EQ(f.pc.size(), 0ll); + /* A free block in the fine group cannot be retained: the entry is unwound. */ + std::vector> bad = bt; + int32_t loose = -1; + CHECK_OK(f.kv.reserve_block(2, &loose)); + f.kv.release_block(2, loose); /* back on the free list */ + bad[1][1] = loose; + CHECK_EQ(f.pc.insert(1, p, {}, bad, 32), RAD_E_STATE); + CHECK_EQ(f.kv.block_refcount(1, bt[0][0]), 1); + CHECK_EQ(f.kv.block_refcount(2, bt[1][0]), 1); + CHECK_OK(f.pc.insert(1, p, {}, bt, 32)); + CHECK_EQ(f.kv.block_refcount(2, bt[1][0]), 2); +} + +/* Checkpoints are keyed on the entry grid: the chain at the lcm of the blocks, as the scheduler's + * binding builds it (PCBinding::prefix_hash). A position off the grid has no key. */ +TEST(a_checkpoint_over_mixed_blocks_sits_on_the_entry_grid) { + for (const auto& ab : { std::pair{ 2, 1 }, { 2, 4 } }) { + const int64_t L = std::lcm(ab.first, ab.second); + Fixture f; + f.cfg.checkpoint_slots = 4; + REQUIRE_EQ(f.build_groups(mixed_groups(ab.first, ab.second, true)), RAD_OK); + CHECK_EQ(f.pc.checkpoint_interval(), 64ll); + const auto prompt = tok_run(7000, 202); + publish(f, 1, prompt, 202); + const std::vector hs = chain_of(prompt, (int)L); + const int64_t tail = 198 / L * L; + for (int64_t pos : { (int64_t)64, tail }) { + int32_t slot = -1; + CHECK_OK(f.pc.reserve_checkpoint(1, pos, hs[(size_t)(pos / L - 1)], &slot)); + f.pc.commit_checkpoint(hs[(size_t)(pos / L - 1)]); + } + auto longer = prompt; + for (int i = 0; i < 30; ++i) longer.push_back(80000 + i); + CacheHit h = f.pc.lookup(longer, {}); + CHECK_EQ(h.n_attn_tokens, (int32_t)(202 / L * L)); + CHECK_EQ(h.n_linear_tokens, (int32_t)tail); + CHECK(h.checkpoint_slot >= 0); + /* Diverging below the tail resumes at the interval snapshot. */ + auto edited = prompt; + edited[150] += 9; + CHECK_EQ(f.pc.lookup(edited, {}).n_linear_tokens, 64); + /* Off the grid: refused. */ + int32_t slot = -1; + CHECK_EQ(f.pc.reserve_checkpoint(1, L + 1, hs[0], &slot), RAD_E_INVAL); + + /* The scheduler's binding keys a snapshot on the same chain. */ + PCBinding bind(&f.pc); + Request r; + r.id = 5; + r.prompt = longer; + CHECK_OK(bind.reserve_checkpoint(r, 128, &slot)); + bind.commit_checkpoint(r, 128); + auto at128 = prompt; + for (size_t k = 130; k < at128.size(); ++k) at128[k] += 7; + CHECK_EQ(f.pc.lookup(at128, {}).n_linear_tokens, 128); + } +} + +/* The interval must be a multiple of an entry; the chunk quantum, which the engine rounds it to, + * is a multiple of every paged group's block and so of the lcm. */ +TEST(a_mixed_cache_refuses_an_interval_off_its_entry_grid) { + Fixture f; + f.cfg.checkpoint_interval = 66; /* a multiple of 2, not of lcm(2, 4) */ + f.cfg.checkpoint_slots = 2; + CHECK_OK(configure_pools(f.pools, f.cfg)); + CHECK_OK(f.kv.configure(mixed_groups(2, 4, true), f.cfg, f.pools.kv())); + log_set_level(Log::Error); + CHECK_EQ(f.pc.configure(f.cfg, &f.kv, f.cfg.checkpoint_interval), RAD_E_INVAL); + log_set_level(Log::Info); + CHECK_OK(f.pc.configure(f.cfg, &f.kv, 68)); + CHECK_EQ(f.pc.block_size(), 4ll); +} + +/* A model with linear state beside a trunk window and groups at two strides (DeepSeek-V4.1's + * shape): the cache indexes both full groups, and the window rides in the checkpoint slot after + * the state, so a hit resumes at a snapshot with nothing left out. */ +TEST(a_hybrid_with_a_window_and_mixed_blocks_leaves_only_the_window_to_the_slot) { + Fixture f; + f.cfg.checkpoint_slots = 4; + std::vector g = mixed_groups(2, 1, true); + g.push_back(paged_group("swa", RAD_KV_WINDOW, 2, 16, { 5 }, 64)); /* handle 4 */ + REQUIRE_EQ(f.build_groups(g), RAD_OK); + CHECK(f.kv.has_window_snapshot()); + const KVGroupPlan* w = f.kv.plan(4); + REQUIRE(w && w->win_snap); + CHECK_EQ(f.kv.checkpoint_bytes(), + f.kv.plan(3)->bytes_per_state + w->window_blocks * w->bytes_per_block); + CHECK(f.pc.cached_groups() == (std::vector{ 1, 2 })); + CHECK_EQ(f.pc.block_size(), 2ll); + CHECK(f.pc.report().find("a checkpoint slot carries its window") != std::string::npos); +} + /* ================================================================== retention */ TEST(geometric_backoff_keeps_the_tip_and_its_ancestors) { @@ -4994,24 +5214,26 @@ static void scribble(Fixture& f) { /* The number of entries whose blocks in `now` hold, in every cached group and layer, exactly what * their blocks in `was` held before the move: this rank's own bytes, and for a replicated group - * rank 0's, the one copy the slot holds. */ + * rank 0's, the one copy the slot holds. An entry is blocks_per_entry(gi) blocks of group gi. */ static int64_t same_bytes(Fixture& f, int rank, const std::vector>& was, const std::vector>& now) { const std::vector& cg = f.pc.cached_groups(); int64_t good = 0; - for (size_t k = 0; k < was[0].size(); ++k) { + const int64_t n = (int64_t)was[0].size() / f.pc.blocks_per_entry(0); + for (int64_t e = 0; e < n; ++e) { bool ok = true; for (size_t gi = 0; gi < cg.size() && ok; ++gi) { const KVGroupPlan* p = f.kv.plan(cg[gi]); if (p->zero) continue; const int r = p->replicated ? 0 : rank; - const int64_t frag = p->layer_bytes_per_block(); - for (int64_t l = 0; l < p->n_layers && ok; ++l) { - const unsigned char* row = - (const unsigned char*)p->base + l * p->layer_stride() + now[gi][k] * frag; - for (int64_t i = 0; i < frag && ok; ++i) - ok = row[i] == pat(r, cg[gi] * 16 + l, was[gi][k], i); - } + const int64_t frag = p->layer_bytes_per_block(), per = f.pc.blocks_per_entry(gi); + for (int64_t k = e * per; k < (e + 1) * per && ok; ++k) + for (int64_t l = 0; l < p->n_layers && ok; ++l) { + const unsigned char* row = (const unsigned char*)p->base + + l * p->layer_stride() + now[gi][(size_t)k] * frag; + for (int64_t i = 0; i < frag && ok; ++i) + ok = row[i] == pat(r, cg[gi] * 16 + l, was[gi][(size_t)k], i); + } } good += ok; } @@ -5059,6 +5281,9 @@ struct TransferCase { bool replicated = false; bool alike = false; bool verify = false; + /* The key cache at 8-token blocks: an entry is one attention block and two key blocks, and + * the slot, the staging entry and the jobs all go by the entry's blocks. */ + bool mixed = false; }; static void run_transfer(const TransferCase& tc) { const int world = tc.world; @@ -5085,11 +5310,14 @@ static void run_transfer(const TransferCase& tc) { * replicated attention group, which leaves that rank's own window empty. */ if (zero_last && r == world - 1) groups[tc.replicated ? 2 : 1].zero = true; if (tc.replicated) groups[1].replicated = true; + if (tc.mixed) groups[2].block_size = 8; REQUIRE_EQ(fx.back()->build_groups(groups), RAD_OK); } Fixture& f = *fx[0]; - const std::vector& cg = f.pc.cached_groups(); - REQUIRE_EQ(cg.size(), 2u); + REQUIRE_EQ(f.pc.cached_groups().size(), 2u); + /* One group per block an entry holds (PrefixCache::entry_groups), as bringup passes them. */ + const std::vector& cg = f.pc.entry_groups(); + REQUIRE_EQ(cg.size(), tc.mixed ? 3u : 2u); /* The slot as bringup lays it out: a replicated group once at the front, then each rank's own * window following the previous ones. Checked against the plain sums here. */ std::vector kvs; @@ -5146,6 +5374,7 @@ static void run_transfer(const TransferCase& tc) { REQUIRE_EQ(f.pc.lookup(prompt, {}, &hit).n_attn_tokens, 320); const std::vector> was = hit; CHECK(was[0][0] != was[1][0]); + CHECK_EQ((int64_t)was[1].size(), tc.mixed ? 40ll : 20ll); for (int r = 0; r < world; ++r) fill(*fx[(size_t)r], r, tc.alike); /* ---- out ---- */ @@ -5233,6 +5462,24 @@ TEST(each_rank_restores_its_own_window_of_a_shared_slot) { run_transfer({ 2, /*fragment=*/false }); run_transfer({ 2, /*fragment=*/true }); } +/* An entry over groups at different block sizes moves as its blocks: one attention block and two + * key-cache blocks a slot, each through its own staging window, and every byte comes back. With a + * replicated attention group beside a zero rank the windows still stay apart. */ +TEST(an_entry_over_mixed_block_sizes_moves_through_the_tiers_block_by_block) { + TransferCase tc; + tc.mixed = true; + for (int world : { 1, 2 }) + for (bool fragment : { false, true }) { + tc.world = world; + tc.fragment = fragment; + run_transfer(tc); + } + tc.world = 3; + tc.fragment = false; + tc.zero_last = true; + tc.replicated = true; + run_transfer(tc); +} TEST(a_rank_with_a_zero_group_moves_only_its_own_groups) { run_transfer({ 3, /*fragment=*/false, /*zero_last=*/true }); run_transfer({ 3, /*fragment=*/true, /*zero_last=*/true }); @@ -6413,6 +6660,81 @@ TEST(a_checkpoint_carries_the_window_page_by_page_and_skips_the_padding) { rad_stream_destroy(st); } +/* Linear state, a conv window and a trunk window in one slot, as on DeepSeek-V4.1: the state + * section first in plan order, then the window pages, and a restore puts each back where it + * belongs -- the state into the resumed sequence's slots, the pages into its seeded blocks. */ +TEST(a_checkpoint_carries_linear_state_and_the_window_together) { + if (!host_backend_or_skip("the hybrid checkpoint round trip")) return; + Fixture f; + f.cfg.checkpoint_slots = 4; + std::vector g = hybrid_conv_groups(); + g.push_back(paged_group("swa", RAD_KV_WINDOW, 2, 16, { 7, 8 }, 64)); /* handle 4 */ + REQUIRE_EQ(f.build_groups(g), RAD_OK); + const KVGroupPlan* w = f.kv.plan(4); + REQUIRE(w && w->win_snap && f.kv.has_window_snapshot()); + const int64_t state = f.kv.plan(G_GDN)->bytes_per_state + f.kv.plan(G_CV)->bytes_per_state; + const int64_t page = w->bytes_per_block, lb = w->layer_bytes_per_block(); + REQUIRE_EQ(f.kv.checkpoint_bytes(), state + w->window_blocks * page); + auto block = [&](int64_t l, int32_t b) { + return (unsigned char*)w->base + l * w->layer_stride() + b * lb; + }; + for (int64_t l = 0; l < w->n_layers; ++l) + for (int32_t b = 0; b < (int32_t)w->n_blocks; ++b) + for (int64_t i = 0; i < lb; ++i) block(l, b)[i] = pat(7, l, b, i); + + CHECK_OK(f.kv.add_sequence(1)); + CHECK_OK(f.kv.ensure(1, 400)); + const std::vector a = slots_of(f.kv, 1); + fill_states(f.kv, 0); + std::vector rows; + REQUIRE(f.kv.window_rows(1, 400, &rows)); + int32_t ck = -1; + REQUIRE_EQ(f.kv.alloc_checkpoint(&ck), RAD_OK); + unsigned char* blob = (unsigned char*)f.kv.checkpoint_ptr(ck); + std::memset(blob, 0x5A, (size_t)f.kv.checkpoint_bytes()); + RadStream st = nullptr; + REQUIRE_EQ(rad_stream_create(&st, 0), RAD_OK); + CHECK_OK(f.kv.checkpoint_save(a.data(), (int)a.size(), ck, st, &rows)); + CHECK_OK(rad_stream_sync(st)); + int64_t off = 0, wrong = 0; + for (int32_t gi : { (int32_t)G_GDN, (int32_t)G_CV }) { + const KVGroupPlan* p = f.kv.plan(gi); + const int64_t sl = p->bytes_per_state / p->n_layers; + for (int64_t l = 0; l < p->n_layers; ++l, off += sl) + for (int64_t i = 0; i < sl; ++i) wrong += blob[off + i] != pat(0, gi * 16 + l, a[(size_t)gi], i); + } + CHECK_EQ(off, state); + for (int64_t j = 0; j < w->window_blocks; ++j) + for (int64_t l = 0; l < w->n_layers; ++l) + for (int64_t i = 0; i < lb; ++i) { + const unsigned char want = rows[(size_t)j] >= 0 ? pat(7, l, rows[(size_t)j], i) : 0x5A; + wrong += blob[state + j * page + l * lb + i] != want; + } + CHECK_EQ(wrong, 0ll); + + /* Back into a fresh sequence: its state slots take A's copy 0, its seeded window the pages. */ + CHECK_OK(f.kv.add_sequence(2)); + CHECK_OK(f.kv.seed_window(2, 400)); + CHECK_OK(f.kv.ensure(2, 432, 400)); /* the chunk after the hit, as admit_one */ + const std::vector b = slots_of(f.kv, 2); + REQUIRE(b[(size_t)G_GDN] >= 0 && b[(size_t)G_CV] >= 0); + std::vector rows2; + REQUIRE(f.kv.window_rows(2, 400, &rows2)); + for (int64_t l = 0; l < w->n_layers; ++l) + for (int32_t r : rows2) if (r >= 0) std::memset(block(l, r), 0xEE, (size_t)lb); + CHECK_OK(f.kv.checkpoint_restore(b.data(), (int)b.size(), ck, st, &rows2)); + CHECK_OK(rad_stream_sync(st)); + CHECK_EQ(states_wrong(f.kv, 0, b, a), 0ll); + wrong = 0; + for (size_t j = 0; j < rows2.size(); ++j) { + if (rows2[j] < 0) continue; + for (int64_t l = 0; l < w->n_layers; ++l) + for (int64_t i = 0; i < lb; ++i) wrong += block(l, rows2[j])[i] != pat(7, l, rows[j], i); + } + CHECK_EQ(wrong, 0ll); + rad_stream_destroy(st); +} + /* ================================================================== multimodal prefix keys * * Placeholder token ids are the same for every picture, so the content key of each media span diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index caead36d..78586135 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -1117,6 +1117,123 @@ TEST(a_hit_on_a_model_with_a_windowed_group_reuses_nothing) { CHECK_EQ(m.linear_cached_tokens, 0); } +/* The same model with the trunk's window in the checkpoint slot (KVGroupPlan::win_snap beside + * linear state, as DeepSeek-V4.1's sliding layers beside its compressor state): the hit resumes at + * the snapshot, which restores the linear state and the window together, and the cached group's + * blocks are adopted. Before, a model with linear state never put its window in the slot, so this + * clamp refused every hit on it. */ +TEST(a_hit_on_a_hybrid_whose_slot_carries_the_window_resumes_at_the_snapshot) { + Fixture f; + f.build(4096, 64, 512, 4096, /*windowed=*/true); + const int32_t swa = 3; + f.kv.snap = { swa }; + f.pc.groups = { 0 }; + CHECK_OK(f.start()); + f.pc.seed(304); + f.pc.lin = 256; + f.pc.src = 3; + + const uint64_t a = f.submit(300, 8); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, 256); + CHECK_EQ(b->ctx_lens[0], 256); + CHECK_EQ(f.sch.plan().e[0].ckpt_restore, 3); + CHECK_EQ(f.kv.block_table(a, 0)[0], f.pc.seeded[0][0]); + const SchedMetrics m = f.sch.metrics(); + CHECK_EQ(m.linear_cached_tokens, 256); + CHECK_EQ(m.hit_cut_window, 0); + + /* A hit with no snapshot under it still reuses nothing: the window has nowhere to come from. */ + Fixture g; + g.build(4096, 64, 512, 4096, /*windowed=*/true); + g.kv.snap = { swa }; + g.pc.groups = { 0 }; + CHECK_OK(g.start()); + g.pc.seed(304); + g.pc.lin = 0; + g.pc.src = -1; + const uint64_t c = g.submit(300, 8); + REQUIRE(g.sch.step() != nullptr); + CHECK_EQ(g.sch.find(c)->n_computed, 0); +} + +/* A trunk group the cache does not index and no slot carries is a hole no snapshot fills: a full + * group left out (as a group at another block size was before the cache took every block size) + * refuses the hit even where the window is in the slot. */ +TEST(a_trunk_group_neither_cached_nor_in_the_slot_refuses_the_hit) { + Fixture f; + f.build(4096, 64, 512, 4096, /*windowed=*/true); + KVGroupInfo k; + k.name = "fine"; + k.decl.kind = RAD_KV_FULL; + k.block_size = 16; + k.layers = { 3 }; + f.prog.kv_groups.push_back(k); + f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64); + f.kv.snap = { 3 }; + f.pc.groups = { 0 }; + CHECK_OK(f.start()); + f.pc.seed(304); + f.pc.lin = 256; + f.pc.src = 3; + const uint64_t a = f.submit(300, 8); + REQUIRE(f.sch.step() != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, 0); + CHECK_EQ(f.sch.metrics().hit_cut_window, 1); +} + +/* Groups at two block sizes: a hit adopts each group's own blocks (the 8-token group twice as + * many), and the cache's reserve is asked for in entries, from the group furthest short. */ +TEST(a_hit_over_mixed_block_sizes_adopts_each_groups_own_blocks) { + Fixture f; + f.build(4096, 64); + KVGroupInfo k; + k.name = "fine"; + k.decl.kind = RAD_KV_FULL; + k.block_size = 8; + f.prog.kv_groups.push_back(k); + const int32_t fine = 3; + f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64); + f.pc.groups = { 0, fine }; + CHECK_OK(f.start()); + CHECK_EQ(f.sch.geometry().quantum % 16, 0ll); + f.pc.seed(304); /* 19 blocks of 16, 38 of 8 */ + f.pc.lin = 256; + f.pc.src = 3; + const uint64_t a = f.submit(1000, 8); + REQUIRE(f.sch.step() != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, 256); + const std::vector t0 = f.kv.block_table(a, 0), t1 = f.kv.block_table(a, fine); + CHECK_EQ((int)t0.size(), 32); /* 16 adopted + 16 for the 256-token chunk */ + CHECK_EQ((int)t1.size(), 64); /* 32 adopted + 32 */ + for (int i = 0; i < 16; ++i) CHECK_EQ(t0[(size_t)i], f.pc.seeded[0][(size_t)i]); + for (int i = 0; i < 32; ++i) CHECK_EQ(t1[(size_t)i], f.pc.seeded[1][(size_t)i]); +} + +TEST(the_cache_trim_over_mixed_block_sizes_asks_for_entries) { + Fixture f; + f.build(/*blocks=*/64, /*states=*/64); + KVGroupInfo k; + k.name = "fine"; + k.decl.kind = RAD_KV_FULL; + k.block_size = 8; + f.prog.kv_groups.push_back(k); + f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 64, 64); + f.pc.groups = { 0, 3 }; + CHECK_OK(f.start()); + f.pc.evict_grant = 1 << 20; + f.submit(160, /*max_tokens=*/1); /* 10 + 20 blocks, finishes on the first commit */ + f.submit(176, /*max_tokens=*/64); /* 11 + 22 each, still running after it */ + f.submit(176, /*max_tokens=*/64); + REQUIRE(f.sch.step() != nullptr); + CHECK_EQ(f.kv.held_blocks(0), 32ll); /* 32 free against a reserve of 16 */ + CHECK_EQ(f.kv.held_blocks(3), 64ll); /* none free against 16: 8 entries of 2 */ + f.commit_plain(); + REQUIRE(f.pc.trims.size() == 1u); + CHECK_EQ(f.pc.trims[0], 8ll); +} + /* A request whose media is not encoded yet waits, and only it does: it is not admitted without * its rows, and the request behind it is asked and runs. Once its items are encoded it is * admitted where it stood. */