Archived
radiance 1.5.0
- Gemma 4 31B (PRs #74, #75, #81, #86; sfjes, keptn42): sliding and global attention with their own kernels, the assistant head as a drafter that reads the trunk's cache, the vision tower, a fused w4a8 decode step, bf16 and compressed-tensors int4 checkpoints, and window snapshots so a prefix hit on a sliding-window model resumes instead of prefilling again. deploy/compose/gemma4-31b-w4a8.yaml serves keptn42's container on two cards - ParoQuant (PRs #65, #66, #67; malic): Qwen3.8-27B checkpoints with learned Givens rotations, as int4, int5 and MXFP4, imported without re-quantising, the prefill's rotations on the matrix cores. deploy/compose/qwen3.8-27b-paro.yaml serves them on one card. A ParoQuant container made with the PR builds is refused: convert it again with --reuse <old container> - Gemma 4 26B-A4B with z-lab's DFlash drafter (PR #88; Perire): arch/gemma4 serves Google's bf16 checkpoint with the routed experts in block fp8 or bf16 (data/recipes/gemma4-26b-a4b-df*.recipe), and libr4d gains its windowed paged attention, the fused sandwich-norm joins, expert_scale and the sharded draft head's pair_argmax. A prefill chunk runs as two slices with its all-reduces beside the compute, bit-exact with the whole step. The 31B's global layers take the windowed attention too: an 11.5K-token prefill on two R9700s in 3.1 s instead of 4.9 - a startup that logs nothing for two minutes says where it waits (#89): the system call (a KFD request by name), the library that made it, and its stack, which addr2line resolves against the binary - the prefix cache is kept in VRAM and host memory only (#70): the disk tier wrote every block and snapshot a prompt produced, and its copies never outlived the process. --prefix-cache-host-mib is renamed --prefix-cache-mib; --prefix-cache-dir and --prefix-cache-disk-mib are removed, and startup refuses all three with what replaced them. The compose files no longer mount /data, and .env no longer needs RADIANCE_STATE - --prefix-cache-ttl S (default 3600, 0 never): a conversation no request has used for that long leaves the cache, whichever tier holds it; radiance:prefix_cache_expired_total counts them. A full host tier now drops its least recently used conversations - --vision-tower-placement vram|ram (#84): ram keeps an encoder tower in pinned host memory and gives its VRAM to the KV cache, read over the link once an image - timings carry ttft_ms and total_ms (#85): the server's own time from the request body's arrival to the first and the last token, queueing and tokenisation included - a KV-cache recall that found a moved expert with nowhere to go stopped halfway and leaked the slots it had already freed: after it every recall failed, the cache stayed short until a restart, and requests failed with HTTP 500. A recall now waits for the slots it is owed and always finishes - a tool result or tool-call arguments that are not JSON are no longer refused as nesting past 1024 levels for their unmatched brackets (#90): only text that parses as JSON is held to the bound, since nothing else is parsed into a tree - the host-pool refusal names the limit that applies to pinned memory (RAM less 1/64 and 1.5 GiB), not ttm.pages_limit - --embedding-placement auto, removed in 1.3.0, is refused with what replaced it - for out-of-tree kernel libraries: gemm_nt_q gains two operands (pb1, pb2, the part bounds), and the loader requires identical op schemas, so a library built against 1.4.0 must be rebuilt. For architecture plugins, rad_op_declared(b, op) asks whether an op is in the loaded vocabulary without declaring it
This commit is contained in:
commit
b93b531f63
127 files changed
+9609
-4796
No files matched your search
@@ -3,7 +3,8 @@
|
||||
* Two stores are built from it: the KV tiers' block arena (core/mem/kvtier.h), where one slot is
|
||||
* one cache entry, and the linear-state snapshot store (KVManager::set_checkpoint_store), where
|
||||
* one slot is one snapshot. Under tensor parallelism a slot holds EVERY rank's shard of its
|
||||
* object, each rank at its own offset, so the disk store can read and write it as one payload.
|
||||
* object, each rank at its own offset, so one slot id -- rank 0's to hand out -- names the object
|
||||
* on every rank.
|
||||
*
|
||||
* Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the
|
||||
* driver stages an async copy to pageable memory through its own buffer and, on some paths,
|
||||
|
||||
+2
-3
@@ -350,7 +350,7 @@ public:
|
||||
* A BLOCK IS NOT LENT WHILE ANYTHING HOLDS IT, and a held block is a block a sequence owns OR
|
||||
* one the prefix cache still indexes. So a loan cannot evict anything: it is a claim on what
|
||||
* is free. Everything that makes a block free -- a sequence ending, an eviction, an idle-tier
|
||||
* demotion to host memory or disk -- makes it lendable, and the min-heap free list is what
|
||||
* demotion to host memory -- makes it lendable, and the min-heap free list is what
|
||||
* keeps the free blocks at the top, where a loan can reach them.
|
||||
*
|
||||
* THE BUFFER IS DERIVED AND NOT STATED. It is the free blocks the cache keeps in hand so that
|
||||
@@ -456,8 +456,7 @@ public:
|
||||
* that resumes from it, each a few milliseconds on a 50-100 MiB snapshot.
|
||||
*
|
||||
* THE STORE IS SHARED BY EVERY RANK and owned by the engine: a slot holds every rank's shard
|
||||
* of one snapshot, each at its own offset (`rank_off`), so the disk tier reads and writes a
|
||||
* slot as one payload. The slot ids are rank 0's -- its manager hands them out and the others
|
||||
* of one snapshot, each at its own offset (`rank_off`). The slot ids are rank 0's -- its manager hands them out and the others
|
||||
* address the id they are given. Without a store no slot is ever handed out and a hybrid
|
||||
* model's prefix hits replay their linear layers from zero. `checkpoint_bytes()` is THIS
|
||||
* rank's shard. */
|
||||
|
||||
+84
-555
@@ -1,6 +1,5 @@
|
||||
#include "mem/kvtier.h"
|
||||
|
||||
#include "mem/sstier.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -13,18 +12,16 @@ const char* kv_tier_name(KVTier t) {
|
||||
switch (t) {
|
||||
case KVTier::Device: return "device";
|
||||
case KVTier::Host: return "host";
|
||||
case KVTier::Disk: return "disk";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ IdleTiers */
|
||||
|
||||
int IdleTiers::configure(const Config& c, SSDTier* disk) {
|
||||
int IdleTiers::configure(const Config& c) {
|
||||
std::lock_guard lk(mu_);
|
||||
reset();
|
||||
cfg_ = c;
|
||||
disk_ = disk;
|
||||
|
||||
if (cfg_.host_cap_bytes > 0 && cfg_.entry_bytes > 0) {
|
||||
const int st = arena_.open(cfg_.entry_bytes, cfg_.host_cap_bytes);
|
||||
@@ -36,46 +33,27 @@ int IdleTiers::configure(const Config& c, SSDTier* disk) {
|
||||
} else {
|
||||
cfg_.host_cap_bytes = 0;
|
||||
}
|
||||
if (!disk_ || !disk_->enabled()) cfg_.disk_cap_bytes = 0;
|
||||
|
||||
/* A disk tier under no host tier is legal and it is not a mistake: the blocks' path to disk
|
||||
* runs through host memory, so with no host tier no block ever reaches disk, and saying so at
|
||||
* startup is cheaper than an operator reading a disk tier's zero counters for an afternoon. */
|
||||
if (!host_on() && disk_on())
|
||||
RAD_WARN("kv tiers: --prefix-cache-disk-mib is set but --prefix-cache-host-mib is not, and the "
|
||||
"blocks' path to disk runs through host memory -- only snapshots will be written");
|
||||
|
||||
char buf[512];
|
||||
if (!any_on()) {
|
||||
report_ = "kv tiers: off (no --prefix-cache-host-mib), so a finished conversation's KV stays "
|
||||
report_ = "kv tiers: off (no --prefix-cache-mib), so a finished conversation's KV stays "
|
||||
"in VRAM until the cache evicts it under pressure -- it is never copied to host "
|
||||
"memory, and what the pool is holding is mostly cache rather than live requests";
|
||||
} else {
|
||||
std::snprintf(buf, sizeof buf,
|
||||
"kv tiers: a finished conversation's KV is copied to host memory at once "
|
||||
"(%s, %lld entries) and its VRAM is given up when the expert loan or a "
|
||||
"request wants it; %s. One entry is %s",
|
||||
"request wants it; a full host tier drops its least recently used entries. "
|
||||
"One entry is %s",
|
||||
humanb(arena_.cap_bytes()).c_str(), (long long)arena_.capacity(),
|
||||
disk_on() ? ("every host copy is written on to disk (" +
|
||||
humanb(cfg_.disk_cap_bytes) + ") and its slot is given up "
|
||||
"when another entry needs it").c_str()
|
||||
: "no disk tier, so a full host tier drops its oldest entries",
|
||||
humanb(cfg_.entry_bytes).c_str());
|
||||
report_ = buf;
|
||||
/* SAID EVEN WHEN IT IS ZERO, on a model that has recurrent state. A hybrid server whose
|
||||
* snapshots do not reach disk looks identical from every block counter there is, and the
|
||||
* difference it makes is a full linear replay of the transcript on what the hit rate will
|
||||
* happily report as a hit. */
|
||||
if (cfg_.ckpt_bytes > 0) {
|
||||
std::snprintf(buf, sizeof buf,
|
||||
"\nkv tiers: a session's linear state is saved to host memory -- %lld "
|
||||
"snapshot slot(s) of %s -- and %s",
|
||||
(long long)cfg_.ckpt_slots, humanb(cfg_.ckpt_bytes).c_str(),
|
||||
ckpt_disk_on()
|
||||
? fmt("written on to disk (%lld slots), so a full store detaches "
|
||||
"the least recently used instead of losing it",
|
||||
(long long)cfg_.ckpt_disk_slots).c_str()
|
||||
: "with no disk copy a full store retires the least recently used");
|
||||
"snapshot slot(s) of %s -- and a full store retires the least recently "
|
||||
"used",
|
||||
(long long)cfg_.ckpt_slots, humanb(cfg_.ckpt_bytes).c_str());
|
||||
report_ += buf;
|
||||
}
|
||||
}
|
||||
@@ -93,18 +71,11 @@ void IdleTiers::reset() {
|
||||
sessions_.clear();
|
||||
roots_.clear();
|
||||
host_lru_.clear();
|
||||
disk_lru_.clear();
|
||||
wb_q_.clear();
|
||||
resume_q_.clear();
|
||||
dk_q_.clear();
|
||||
clean_q_.clear();
|
||||
ck_reading_.clear();
|
||||
ck_free_after_.clear();
|
||||
ck_frees_.clear();
|
||||
starved_ = 0;
|
||||
wb_stuck_ = false;
|
||||
arena_.close();
|
||||
disk_ = nullptr;
|
||||
cfg_ = Config{};
|
||||
report_.clear();
|
||||
}
|
||||
@@ -113,7 +84,7 @@ std::string IdleTiers::report() const { return report_; }
|
||||
|
||||
void IdleTiers::unlist(Rec& r) {
|
||||
if (!r.listed) return;
|
||||
list_for(r.tier).erase(r.it);
|
||||
host_lru_.erase(r.it);
|
||||
r.listed = false;
|
||||
}
|
||||
|
||||
@@ -122,25 +93,13 @@ void IdleTiers::unlist(Rec& r) {
|
||||
* header's one-record rule exists to rule out. */
|
||||
void IdleTiers::relist(const BlockHash& key, Rec& r) {
|
||||
if (r.pending || r.tier == KVTier::Device || r.listed) return;
|
||||
std::list<BlockHash>& l = list_for(r.tier);
|
||||
l.push_back(key);
|
||||
r.it = std::prev(l.end());
|
||||
r.it = host_lru_.emplace_hint(host_lru_.end(), r.used_ns, key);
|
||||
r.listed = true;
|
||||
}
|
||||
|
||||
bool IdleTiers::wants_copy(const Rec& r) const {
|
||||
if (r.pending || r.doomed) return false;
|
||||
return host_on() && r.tier == KVTier::Device && r.host_slot < 0 && !r.on_disk &&
|
||||
!r.blocks.empty();
|
||||
}
|
||||
|
||||
bool IdleTiers::wants_ck_disk(const Rec& r) const {
|
||||
return ckpt_disk_on() && !r.doomed && r.ck_slot >= 0 && !r.ck_on_disk && r.ck_disk_src < 0;
|
||||
}
|
||||
|
||||
bool IdleTiers::wants_disk(const Rec& r) const {
|
||||
if (!disk_on() || r.doomed) return false;
|
||||
return (r.host_slot >= 0 && !r.on_disk && r.disk_src < 0) || wants_ck_disk(r);
|
||||
return host_on() && r.tier == KVTier::Device && r.host_slot < 0 && !r.blocks.empty();
|
||||
}
|
||||
|
||||
void IdleTiers::queue_copy(const BlockHash& key, Rec& r) {
|
||||
@@ -149,12 +108,6 @@ void IdleTiers::queue_copy(const BlockHash& key, Rec& r) {
|
||||
r.queued = true;
|
||||
}
|
||||
|
||||
void IdleTiers::queue_disk(const BlockHash& key, Rec& r) {
|
||||
if (r.disk_q || !wants_disk(r)) return;
|
||||
dk_q_.push_back(key);
|
||||
r.disk_q = true;
|
||||
}
|
||||
|
||||
void IdleTiers::give_slot(int32_t slot) {
|
||||
if (slot < 0) return;
|
||||
arena_.free(slot);
|
||||
@@ -162,106 +115,41 @@ void IdleTiers::give_slot(int32_t slot) {
|
||||
}
|
||||
|
||||
void IdleTiers::free_host(Rec& r) {
|
||||
if (r.host_slot < 0) return;
|
||||
if (r.host_slot != r.disk_src) give_slot(r.host_slot);
|
||||
give_slot(r.host_slot);
|
||||
r.host_slot = -1;
|
||||
}
|
||||
|
||||
/* THE ONE PLACE `on_disk` CHANGES, because the disk figure in the occupancy view is kept beside it
|
||||
* rather than counted, and an entry landing on disk is also what unblocks a stuck write-back. */
|
||||
void IdleTiers::set_on_disk(Rec& r, bool v) {
|
||||
if (r.on_disk == v) return;
|
||||
r.on_disk = v;
|
||||
stats_.disk_bytes += v ? cfg_.entry_bytes : -cfg_.entry_bytes;
|
||||
if (v) wb_stuck_ = false;
|
||||
}
|
||||
|
||||
void IdleTiers::queue_clean(const BlockHash& key, Rec& r) {
|
||||
if (r.clean_q) return;
|
||||
clean_q_.push_back(key);
|
||||
r.clean_q = true;
|
||||
}
|
||||
|
||||
/* EVERYTHING THIS RECORD HOLDS OFF THE CARD. The blocks' arena slot is the tiers'; SSDTier owns
|
||||
* its own slots and reclaims them by LRU, so there is nothing to give back for a disk-resident
|
||||
* copy of either half.
|
||||
*
|
||||
* A snapshot in its store slot is the CACHE'S, not this object's: the cache retires snapshots by
|
||||
* its own retention policy and the slot is still correct and indexed. Only a snapshot that exists
|
||||
* nowhere but on disk is lost with the record, and only that loss is announced -- the cache
|
||||
* learns about a lost ENTRY from set_drop_sink at the sites that erase one, and this is also
|
||||
* called from forget(), where the cache is the caller and already knows. */
|
||||
void IdleTiers::release_storage(const BlockHash& key, Rec& r) {
|
||||
free_host(r);
|
||||
set_on_disk(r, false);
|
||||
const bool lost_ck = r.ck_slot < 0 && r.ck_on_disk;
|
||||
r.ck_on_disk = false;
|
||||
if (lost_ck) { ++stats_.ck_drops; if (on_ck_drop_) on_ck_drop_(key); }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the linear half */
|
||||
|
||||
void IdleTiers::note_snapshot(const BlockHash& key, int32_t slot, int64_t pos, bool resume) {
|
||||
/* RECORDED, NOT MOVED. A snapshot is in host memory from the moment it is saved and stays in its
|
||||
* store slot until the cache retires it; the tiers keep its slot and position for the session
|
||||
* view. */
|
||||
void IdleTiers::note_snapshot(const BlockHash& key, int32_t slot, int64_t pos) {
|
||||
if (slot < 0) return;
|
||||
std::lock_guard lk(mu_);
|
||||
Rec& r = recs_[key];
|
||||
/* A FRESH SNAPSHOT REPLACES WHATEVER DISK COPY THERE WAS, never joins it. The disk copy
|
||||
* described the state as it was last written; the slot now holds it as it was just written,
|
||||
* and a record that called the two the same bytes would read the older one back. */
|
||||
r.ck_on_disk = false;
|
||||
r.ck_slot = slot;
|
||||
r.ck_pos = pos;
|
||||
/* WRITTEN TO DISK ONCE ITS RECORD IS PUBLISHED, like the blocks: note_used queues it then. A
|
||||
* request commits its checkpoints as its prefill passes them and the store's retention policy
|
||||
* thins them as it goes, so writing each at commit would send most of them to disk to be
|
||||
* retired a moment later. A record the request had already published takes a new commit at
|
||||
* once. A RESUME POINT does not wait: it is the snapshot the next turn needs, and until it is
|
||||
* on disk a full store can only retire it. */
|
||||
if (r.tier != KVTier::Device || !r.blocks.empty()) queue_disk(key, r);
|
||||
if (resume && !r.resume_q && wants_ck_disk(r)) {
|
||||
resume_q_.push_back(key);
|
||||
r.resume_q = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool IdleTiers::release_snapshot(const BlockHash& key, int32_t slot) {
|
||||
void IdleTiers::release_snapshot(const BlockHash& key) {
|
||||
std::lock_guard lk(mu_);
|
||||
bool held = false;
|
||||
if (slot >= 0 &&
|
||||
std::find(ck_reading_.begin(), ck_reading_.end(), slot) != ck_reading_.end()) {
|
||||
ck_free_after_.push_back(slot);
|
||||
held = true;
|
||||
}
|
||||
auto it = recs_.find(key);
|
||||
if (it == recs_.end()) return held;
|
||||
if (it == recs_.end()) return;
|
||||
Rec& r = it->second;
|
||||
r.ck_slot = -1;
|
||||
r.ck_on_disk = false;
|
||||
/* A RECORD THAT ONLY EVER EXISTED FOR THE SNAPSHOT GOES WITH IT. note_snapshot creates one at
|
||||
* commit time, which is mid-request and long before the chain is published; a request that
|
||||
* never publishes -- a rebased block table, a cancel before the first whole block -- would
|
||||
* otherwise leave a record with no blocks, no storage and no way to be reached again. */
|
||||
if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0 &&
|
||||
r.ck_disk_src < 0 && !r.disk_q)
|
||||
if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0)
|
||||
recs_.erase(it);
|
||||
return held;
|
||||
}
|
||||
|
||||
void IdleTiers::take_checkpoint_frees(std::vector<int32_t>* out) {
|
||||
std::lock_guard lk(mu_);
|
||||
out->insert(out->end(), ck_frees_.begin(), ck_frees_.end());
|
||||
ck_frees_.clear();
|
||||
}
|
||||
|
||||
bool IdleTiers::slot_reading(int32_t slot) const {
|
||||
std::lock_guard lk(mu_);
|
||||
return slot >= 0 && std::find(ck_reading_.begin(), ck_reading_.end(), slot) != ck_reading_.end();
|
||||
}
|
||||
|
||||
bool IdleTiers::snapshot_in_slot(const BlockHash& key, int32_t slot) const {
|
||||
std::lock_guard lk(mu_);
|
||||
auto it = recs_.find(key);
|
||||
return it != recs_.end() && slot >= 0 && it->second.ck_slot == slot;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the cache's notices */
|
||||
@@ -272,17 +160,14 @@ void IdleTiers::note_used(const BlockHash& key, const std::vector<int32_t>& bloc
|
||||
Rec& r = recs_[key];
|
||||
r.used_ns = now_ns;
|
||||
if (r.tier == KVTier::Device && !r.pending) r.blocks = blocks;
|
||||
/* A record only moves to the back of its list when it is IN one. A device record is a
|
||||
* timestamp and nothing else, which is what keeps this cheap enough to sit on the publish
|
||||
* path -- the hash insert is the whole cost. */
|
||||
/* A record only moves on the host list when it is IN it. A device record is a timestamp and
|
||||
* nothing else, which is what keeps this cheap enough to sit on the publish path -- the hash
|
||||
* insert is the whole cost. */
|
||||
if (r.listed) {
|
||||
list_for(r.tier).erase(r.it);
|
||||
r.listed = false;
|
||||
unlist(r);
|
||||
relist(key, r);
|
||||
}
|
||||
queue_copy(key, r);
|
||||
/* A snapshot the request committed under this key goes to disk now that its chain is out. */
|
||||
if (wants_ck_disk(r)) queue_disk(key, r);
|
||||
}
|
||||
|
||||
void IdleTiers::note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns) {
|
||||
@@ -294,8 +179,7 @@ void IdleTiers::note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns) {
|
||||
Rec& r = it->second;
|
||||
r.used_ns = now_ns;
|
||||
if (r.listed) {
|
||||
list_for(r.tier).erase(r.it);
|
||||
r.listed = false;
|
||||
unlist(r);
|
||||
relist(keys[i], r);
|
||||
}
|
||||
}
|
||||
@@ -307,7 +191,7 @@ void IdleTiers::rebound(const BlockHash& key, const std::vector<int32_t>& blocks
|
||||
Rec& r = recs_[key];
|
||||
if (r.pending) return;
|
||||
unlist(r);
|
||||
release_storage(key, r);
|
||||
free_host(r);
|
||||
r.tier = KVTier::Device;
|
||||
r.blocks = blocks;
|
||||
r.used_ns = now_ns;
|
||||
@@ -330,18 +214,21 @@ IdleTiers::Stats IdleTiers::stats() const {
|
||||
return s;
|
||||
}
|
||||
|
||||
/* AND EVERY CONVERSATION THAT STARTED HERE. A chain whose first block has gone cannot be hit at any
|
||||
* length -- a prefix hit starts at position zero. Leaving the row behind would report blocks the
|
||||
* pool has already handed to somebody else as this session's, and would hold its whole chain in
|
||||
* memory for a conversation that can never come back. Called wherever an entry goes for good: the
|
||||
* cache's forget(), and the sites here that drop an off-device entry and tell the cache. */
|
||||
void IdleTiers::drop_rooted(const BlockHash& key) {
|
||||
auto ro = roots_.find(key);
|
||||
if (ro == roots_.end()) return;
|
||||
const std::vector<uint64_t> ids = ro->second; /* drop_session rewrites the list */
|
||||
for (uint64_t id : ids) drop_session(id);
|
||||
}
|
||||
|
||||
void IdleTiers::forget(const BlockHash& key) {
|
||||
std::lock_guard lk(mu_);
|
||||
/* AND EVERY CONVERSATION THAT STARTED HERE. This is the only notice the cache gives that an
|
||||
* entry is gone for good, and a chain whose first block has gone cannot be hit at any length
|
||||
* -- a prefix hit starts at position zero. Leaving the row behind would report blocks the
|
||||
* pool has already handed to somebody else as this session's, and would hold its whole chain
|
||||
* in memory for a conversation that can never come back. */
|
||||
auto ro = roots_.find(key);
|
||||
if (ro != roots_.end()) {
|
||||
const std::vector<uint64_t> ids = ro->second; /* drop_session rewrites the list */
|
||||
for (uint64_t id : ids) drop_session(id);
|
||||
}
|
||||
drop_rooted(key);
|
||||
auto it = recs_.find(key);
|
||||
if (it == recs_.end()) return;
|
||||
Rec& r = it->second;
|
||||
@@ -353,7 +240,7 @@ void IdleTiers::forget(const BlockHash& key) {
|
||||
return;
|
||||
}
|
||||
unlist(r);
|
||||
release_storage(key, r);
|
||||
free_host(r);
|
||||
recs_.erase(it);
|
||||
}
|
||||
|
||||
@@ -374,74 +261,13 @@ bool IdleTiers::resident_off_device(const BlockHash& key) const {
|
||||
|
||||
bool IdleTiers::writeback_waiting() const {
|
||||
std::lock_guard lk(mu_);
|
||||
/* NOT WHILE NOTHING CAN MOVE. An arena full of copies the disk does not hold yet has nothing
|
||||
* to give up, so a plan would pop the queue, find no slot and put it back, every tick, until
|
||||
* a slot is freed or a disk copy lands -- which is what ends the wait. */
|
||||
/* NOT WHILE NOTHING CAN MOVE. An arena full of the copies of entries still in VRAM has nothing
|
||||
* a capacity drop may take, so a plan would pop the queue, find no slot and put it back, every
|
||||
* tick, until a slot is freed or a VRAM copy is given up -- which is what ends the wait. */
|
||||
if (wb_stuck_ && arena_.full()) return false;
|
||||
return !wb_q_.empty() && host_on();
|
||||
}
|
||||
|
||||
bool IdleTiers::disk_waiting() const {
|
||||
std::lock_guard lk(mu_);
|
||||
return !dk_q_.empty() || !resume_q_.empty();
|
||||
}
|
||||
|
||||
int64_t IdleTiers::make_room(int64_t n) {
|
||||
std::lock_guard lk(mu_);
|
||||
return make_room_locked(n);
|
||||
}
|
||||
|
||||
/* A READ NO REQUEST CLAIMS IS HELD THIS LONG. A request is admitted on the step after its read lands,
|
||||
* which is milliseconds; this only bounds what one that went away -- cancelled while it waited --
|
||||
* keeps out of reach of everybody else. */
|
||||
static constexpr uint64_t kFetchHoldNs = 10ull * 1000000000ull;
|
||||
|
||||
bool IdleTiers::held_by_fetch(const Rec& r, uint64_t now_ns) const {
|
||||
return r.keep || (r.fetched_ns != 0 && now_ns - r.fetched_ns < kFetchHoldNs);
|
||||
}
|
||||
|
||||
int64_t IdleTiers::make_room_locked(int64_t n) {
|
||||
if (!disk_on() || n <= 0) return 0;
|
||||
const uint64_t now = rad_mono_ns();
|
||||
int64_t freed = 0;
|
||||
/* HOST RECORDS FIRST, oldest first: nothing is in VRAM to use them, and they become disk
|
||||
* records. The walk skips the ones whose disk copy has not landed, which are the newest --
|
||||
* the writes go out in the order the copies landed -- so it stops close to the front. */
|
||||
for (auto it = host_lru_.begin(); it != host_lru_.end() && freed < n;) {
|
||||
const BlockHash key = *it;
|
||||
++it;
|
||||
auto ri = recs_.find(key);
|
||||
if (ri == recs_.end()) continue;
|
||||
Rec& r = ri->second;
|
||||
if (r.pending || !r.on_disk || r.host_slot < 0 || r.host_slot == r.disk_src ||
|
||||
held_by_fetch(r, now))
|
||||
continue;
|
||||
unlist(r);
|
||||
free_host(r);
|
||||
r.tier = KVTier::Disk;
|
||||
relist(key, r);
|
||||
++freed;
|
||||
}
|
||||
/* THEN THE HOST COPIES OF CLEAN VRAM ENTRIES, oldest first. The VRAM copy stays and stays
|
||||
* clean -- its disk copy is what lets it go now. These are on no list (a device record is
|
||||
* ordered by the cache), so they are found by a walk, which only a full arena of them pays. */
|
||||
if (freed < n) {
|
||||
std::vector<std::pair<uint64_t, Rec*>> c;
|
||||
for (auto& kv : recs_) {
|
||||
Rec& r = kv.second;
|
||||
if (r.tier == KVTier::Device && !r.pending && r.on_disk && r.host_slot >= 0 &&
|
||||
r.host_slot != r.disk_src && !held_by_fetch(r, now))
|
||||
c.emplace_back(r.used_ns, &r);
|
||||
}
|
||||
const size_t k = std::min(c.size(), (size_t)(n - freed));
|
||||
std::partial_sort(c.begin(), c.begin() + (long)k, c.end(),
|
||||
[](const auto& a, const auto& b) { return a.first < b.first; });
|
||||
for (size_t i = 0; i < k; ++i) { free_host(*c[i].second); ++freed; }
|
||||
}
|
||||
stats_.host_freed += freed;
|
||||
return freed;
|
||||
}
|
||||
|
||||
bool IdleTiers::starved() const {
|
||||
std::lock_guard lk(mu_);
|
||||
return starved_ > 0;
|
||||
@@ -473,7 +299,6 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector<TierJob>* out) {
|
||||
* front of the queue, and the maintenance plan is told how many copies were refused so it can
|
||||
* make that much room. */
|
||||
const int64_t want = (int64_t)(out->size() - first);
|
||||
if (want > arena_.free_slots()) make_room_locked(want - arena_.free_slots());
|
||||
std::vector<int32_t> slots;
|
||||
slots.reserve((size_t)want);
|
||||
while ((int64_t)slots.size() < want) {
|
||||
@@ -527,7 +352,7 @@ bool IdleTiers::droppable(const BlockHash& key) const {
|
||||
auto it = recs_.find(key);
|
||||
if (it == recs_.end()) return false;
|
||||
const Rec& r = it->second;
|
||||
return !r.pending && !r.doomed && r.tier == KVTier::Device && (r.host_slot >= 0 || r.on_disk);
|
||||
return !r.pending && !r.doomed && r.tier == KVTier::Device && r.host_slot >= 0;
|
||||
}
|
||||
|
||||
void IdleTiers::drop_commit(const BlockHash& key) {
|
||||
@@ -536,113 +361,26 @@ void IdleTiers::drop_commit(const BlockHash& key) {
|
||||
if (it == recs_.end()) return;
|
||||
Rec& r = it->second;
|
||||
if (r.tier != KVTier::Device) return;
|
||||
r.tier = r.host_slot >= 0 ? KVTier::Host : KVTier::Disk;
|
||||
r.tier = KVTier::Host;
|
||||
++stats_.dropped;
|
||||
wb_stuck_ = false; /* with no disk tier, a host record is what a capacity drop takes */
|
||||
wb_stuck_ = false; /* a host record is what a capacity drop takes */
|
||||
relist(key, r);
|
||||
}
|
||||
|
||||
bool IdleTiers::snapshot_backed(const BlockHash& key) const {
|
||||
std::lock_guard lk(mu_);
|
||||
auto it = recs_.find(key);
|
||||
if (it == recs_.end()) return false;
|
||||
const Rec& r = it->second;
|
||||
return !r.doomed && r.ck_slot >= 0 && r.ck_on_disk && r.ck_disk_src < 0;
|
||||
}
|
||||
|
||||
void IdleTiers::snapshot_detached(const BlockHash& key) {
|
||||
std::lock_guard lk(mu_);
|
||||
auto it = recs_.find(key);
|
||||
if (it == recs_.end()) return;
|
||||
it->second.ck_slot = -1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the slow half */
|
||||
/* ------------------------------------------------------------------ capacity and expiry */
|
||||
|
||||
void IdleTiers::plan(int budget, std::vector<TierJob>* out) {
|
||||
if (!any_on() || budget <= 0) return;
|
||||
if (!host_on() || budget <= 0) return;
|
||||
std::lock_guard lk(mu_);
|
||||
/* ---- disk copies: the resume points first, then in the order the host copies landed --- */
|
||||
/* ONE SNAPSHOT BUDGET FOR THE WAY TO DISK, apart from the blocks'. A snapshot is a hundred
|
||||
* megabytes or more and the disk store copies it twice on the way out (an aligned bounce, then
|
||||
* the write), so a plan that sent a session's whole retained set at once would hold the IO
|
||||
* thread for most of a second. A record whose snapshot the budget left behind still sends its
|
||||
* blocks, and goes to the back of the queue for the rest. */
|
||||
int ck_disk_budget = 2;
|
||||
int n = 0;
|
||||
auto take_ck = [&](const BlockHash& key, Rec& r, TierJob& j) {
|
||||
j.ck_slot = r.ck_slot;
|
||||
j.ck_pos = r.ck_pos;
|
||||
j.ck_bytes = cfg_.ckpt_bytes;
|
||||
r.ck_disk_src = r.ck_slot;
|
||||
ck_reading_.push_back(r.ck_slot);
|
||||
--ck_disk_budget;
|
||||
(void)key;
|
||||
};
|
||||
/* A RESUME POINT IS THE SNAPSHOT THE NEXT TURN NEEDS, and the store can only retire it until
|
||||
* the disk holds it. Its record's blocks are not waited for: they go through the host tier on
|
||||
* their own clock. */
|
||||
while (ckpt_disk_on() && ck_disk_budget > 0 && !resume_q_.empty() && n < budget) {
|
||||
const BlockHash key = resume_q_.front();
|
||||
resume_q_.pop_front();
|
||||
auto ri = recs_.find(key);
|
||||
if (ri == recs_.end()) continue;
|
||||
Rec& r = ri->second;
|
||||
r.resume_q = false;
|
||||
if (!wants_ck_disk(r)) continue;
|
||||
TierJob j;
|
||||
j.kind = TierJob::Kind::ToDisk;
|
||||
j.key = key;
|
||||
j.bytes = cfg_.entry_bytes;
|
||||
take_ck(key, r, j);
|
||||
out->push_back(std::move(j));
|
||||
++n;
|
||||
}
|
||||
std::vector<BlockHash> later;
|
||||
while (disk_on() && !dk_q_.empty() && n < budget) {
|
||||
const BlockHash key = dk_q_.front();
|
||||
dk_q_.pop_front();
|
||||
auto ri = recs_.find(key);
|
||||
if (ri == recs_.end()) continue;
|
||||
Rec& r = ri->second;
|
||||
if (!r.disk_q) continue;
|
||||
r.disk_q = false;
|
||||
if (!wants_disk(r)) continue;
|
||||
TierJob j;
|
||||
j.kind = TierJob::Kind::ToDisk;
|
||||
j.key = key;
|
||||
j.bytes = cfg_.entry_bytes;
|
||||
if (r.host_slot >= 0 && !r.on_disk && r.disk_src < 0) {
|
||||
j.host_slot = r.host_slot;
|
||||
r.disk_src = r.host_slot;
|
||||
}
|
||||
if (wants_ck_disk(r)) {
|
||||
if (ck_disk_budget > 0) take_ck(key, r, j);
|
||||
else later.push_back(key);
|
||||
}
|
||||
if (j.host_slot < 0 && j.ck_slot < 0) continue;
|
||||
out->push_back(std::move(j));
|
||||
++n;
|
||||
}
|
||||
for (const BlockHash& k : later) {
|
||||
auto ri = recs_.find(k);
|
||||
if (ri != recs_.end()) queue_disk(k, ri->second);
|
||||
}
|
||||
|
||||
/* ---- capacity, with no disk tier: oldest first ----------------------------------------- */
|
||||
/* HOW MANY, AND NOT "UNTIL THERE IS ROOM". A queued drop does not free its slot until the
|
||||
* engine reports it, so a loop that tested the arena would queue a drop for every entry on the
|
||||
* list and empty the whole tier to make room for one. The copies refused since the last plan
|
||||
* say how much room was wanted; this frees exactly that much. With a disk tier the room comes
|
||||
* from make_room instead, for nothing, once the disk copies above have landed. */
|
||||
const int64_t want = starved_;
|
||||
* say how much room was wanted; this frees exactly that much, least recently used first. */
|
||||
const int64_t want = std::min<int64_t>(starved_, budget);
|
||||
starved_ = 0;
|
||||
if (disk_on()) return;
|
||||
int n_cap = 0;
|
||||
for (int64_t k = 0; k < want && n_cap < budget; ) {
|
||||
if (host_lru_.empty()) break;
|
||||
auto ri = recs_.find(host_lru_.front());
|
||||
if (ri == recs_.end()) { host_lru_.pop_front(); continue; }
|
||||
for (int64_t k = 0; k < want && !host_lru_.empty();) {
|
||||
auto ri = recs_.find(host_lru_.begin()->second);
|
||||
if (ri == recs_.end()) { host_lru_.erase(host_lru_.begin()); continue; }
|
||||
Rec& r = ri->second;
|
||||
TierJob j;
|
||||
j.kind = TierJob::Kind::DropHost;
|
||||
@@ -653,10 +391,17 @@ void IdleTiers::plan(int budget, std::vector<TierJob>* out) {
|
||||
r.pending = true;
|
||||
out->push_back(std::move(j));
|
||||
++k;
|
||||
++n_cap;
|
||||
}
|
||||
}
|
||||
|
||||
void IdleTiers::expired(uint64_t cutoff_ns, size_t max, std::vector<BlockHash>* out) const {
|
||||
std::lock_guard lk(mu_);
|
||||
/* The list holds no record with a job out (relist), so every key it yields can go now. */
|
||||
for (auto it = host_lru_.begin();
|
||||
it != host_lru_.end() && it->first < cutoff_ns && out->size() < max; ++it)
|
||||
out->push_back(it->second);
|
||||
}
|
||||
|
||||
bool IdleTiers::plan_promote(const BlockHash& key, TierJob* out) {
|
||||
std::lock_guard lk(mu_);
|
||||
auto it = recs_.find(key);
|
||||
@@ -669,189 +414,33 @@ bool IdleTiers::plan_promote(const BlockHash& key, TierJob* out) {
|
||||
out->key = key;
|
||||
out->host_slot = r.host_slot;
|
||||
out->bytes = cfg_.entry_bytes;
|
||||
if (r.fetched_ns) ++stats_.disk_hits; else ++stats_.host_hits;
|
||||
++stats_.host_hits;
|
||||
unlist(r);
|
||||
r.pending = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* THE DEEPEST SNAPSHOT ON THE CHAIN, wherever it is and whatever tier its blocks are on: that is
|
||||
* the one the hit resumes from, and it is read off disk only when the disk is the one place it
|
||||
* is. Its record may be in VRAM -- a snapshot can leave its slot while its blocks stay -- and then
|
||||
* the read is of the snapshot alone. A record with a job out is passed over. */
|
||||
size_t IdleTiers::deepest_snapshot(const std::vector<BlockHash>& chain) const {
|
||||
size_t deep = chain.size();
|
||||
for (size_t i = 0; i < chain.size(); ++i) {
|
||||
auto it = recs_.find(chain[i]);
|
||||
if (it == recs_.end()) continue;
|
||||
const Rec& r = it->second;
|
||||
if (r.pending || r.doomed) continue;
|
||||
if (r.ck_slot >= 0 || r.ck_on_disk) deep = i;
|
||||
}
|
||||
return deep;
|
||||
}
|
||||
|
||||
bool IdleTiers::snapshot_fetch_wanted(const std::vector<BlockHash>& chain) const {
|
||||
if (!ckpt_disk_on() || chain.empty()) return false;
|
||||
std::lock_guard lk(mu_);
|
||||
const size_t deep = deepest_snapshot(chain);
|
||||
if (deep >= chain.size()) return false;
|
||||
const Rec& r = recs_.find(chain[deep])->second;
|
||||
return r.ck_slot < 0 && r.ck_on_disk;
|
||||
}
|
||||
|
||||
bool IdleTiers::plan_fetch(const std::vector<BlockHash>& chain, std::vector<TierJob>* out,
|
||||
uint64_t now_ns, int32_t* ck_slot) {
|
||||
if (!disk_on() || chain.empty()) return false;
|
||||
std::lock_guard lk(mu_);
|
||||
bool wait = false;
|
||||
std::vector<Rec*> recs(chain.size(), nullptr);
|
||||
std::vector<size_t> need; /* chain positions whose blocks are only on disk */
|
||||
for (size_t i = 0; i < chain.size(); ++i) {
|
||||
auto it = recs_.find(chain[i]);
|
||||
if (it == recs_.end()) continue;
|
||||
Rec& r = it->second;
|
||||
if (r.fetching) { wait = true; continue; }
|
||||
if (r.pending || r.doomed || r.tier == KVTier::Device) continue;
|
||||
recs[i] = &r;
|
||||
if (r.tier == KVTier::Disk) need.push_back(i);
|
||||
}
|
||||
const size_t deep = deepest_snapshot(chain);
|
||||
Rec* deep_rec = deep < chain.size() ? &recs_.find(chain[deep])->second : nullptr;
|
||||
const bool ck_read = deep_rec && deep_rec->ck_slot < 0 && deep_rec->ck_on_disk &&
|
||||
ckpt_disk_on() && ck_slot && *ck_slot >= 0;
|
||||
if (need.empty() && !ck_read) return wait;
|
||||
|
||||
/* THE ROOM, OUT OF EVERYTHING BUT THIS CHAIN. What the disk also holds goes for nothing
|
||||
* (make_room); the chain's own host copies are what the restore is about to read, and giving
|
||||
* one up to read another would only move the gap. */
|
||||
for (Rec* r : recs) if (r) r->keep = true;
|
||||
if (deep_rec) deep_rec->keep = true;
|
||||
std::vector<int32_t> slots;
|
||||
if (!need.empty()) {
|
||||
const int64_t want = (int64_t)need.size();
|
||||
if (want > arena_.free_slots()) make_room_locked(want - arena_.free_slots());
|
||||
slots.reserve((size_t)want);
|
||||
while ((int64_t)slots.size() < want) {
|
||||
int32_t got = 0;
|
||||
const int32_t s = arena_.alloc_run((int32_t)(want - (int64_t)slots.size()), &got);
|
||||
if (s < 0) break;
|
||||
for (int32_t k = 0; k < got; ++k) slots.push_back(s + k);
|
||||
}
|
||||
}
|
||||
for (Rec* r : recs) if (r) r->keep = false;
|
||||
if (deep_rec) deep_rec->keep = false;
|
||||
|
||||
/* IN CHAIN ORDER, AND CUT WHERE THE SLOTS RAN OUT: a hit needs a contiguous prefix, so an entry
|
||||
* read past a gap would be read for nothing. */
|
||||
const size_t first = out->size();
|
||||
for (size_t k = 0; k < slots.size(); ++k) {
|
||||
TierJob j;
|
||||
j.kind = TierJob::Kind::ToHost;
|
||||
j.key = chain[need[k]];
|
||||
j.host_slot = slots[k];
|
||||
j.bytes = cfg_.entry_bytes;
|
||||
out->push_back(std::move(j));
|
||||
}
|
||||
/* ONLY A SNAPSHOT THE RESTORE WILL REACH: every disk entry at or before it has a slot.
|
||||
* Otherwise the store slot stays the caller's. */
|
||||
if (ck_read && (slots.size() == need.size() || need[slots.size()] > deep)) {
|
||||
TierJob* j = nullptr;
|
||||
for (size_t k = first; k < out->size(); ++k)
|
||||
if ((*out)[k].key == chain[deep]) { j = &(*out)[k]; break; }
|
||||
if (!j) {
|
||||
out->push_back(TierJob{});
|
||||
j = &out->back();
|
||||
j->kind = TierJob::Kind::ToHost;
|
||||
j->key = chain[deep];
|
||||
j->bytes = cfg_.entry_bytes;
|
||||
}
|
||||
j->ck_want = true;
|
||||
j->ck_slot = *ck_slot;
|
||||
j->ck_pos = deep_rec->ck_pos;
|
||||
j->ck_bytes = cfg_.ckpt_bytes;
|
||||
*ck_slot = -1;
|
||||
}
|
||||
for (size_t k = first; k < out->size(); ++k) {
|
||||
Rec& r = recs_[(*out)[k].key];
|
||||
unlist(r);
|
||||
r.pending = true;
|
||||
r.fetching = true;
|
||||
r.used_ns = now_ns;
|
||||
}
|
||||
return wait || out->size() > first;
|
||||
}
|
||||
|
||||
void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
|
||||
std::lock_guard lk(mu_);
|
||||
auto it = recs_.find(job.key);
|
||||
|
||||
/* A DISK WRITE IS NOT A PENDING JOB, so it is settled before anything below touches the
|
||||
* record's pending state -- which may belong to a restore running beside it. The slots it
|
||||
* read are the record's, unless the record gave them up (or went) while the write was out:
|
||||
* then the write's report is what frees them. */
|
||||
if (job.kind == TierJob::Kind::ToDisk) {
|
||||
if (!ok) ++stats_.failures;
|
||||
Rec* r = it == recs_.end() ? nullptr : &it->second;
|
||||
if (job.host_slot >= 0) {
|
||||
if (r && r->disk_src == job.host_slot) r->disk_src = -1;
|
||||
if (!r || r->host_slot != job.host_slot) give_slot(job.host_slot);
|
||||
else if (ok) { set_on_disk(*r, true); ++stats_.to_disk; }
|
||||
}
|
||||
if (job.ck_slot >= 0) {
|
||||
/* THE STORE SLOT IS FREE TO WRITE AGAIN, and one the cache let go of meanwhile goes
|
||||
* back now. */
|
||||
auto rd = std::find(ck_reading_.begin(), ck_reading_.end(), job.ck_slot);
|
||||
if (rd != ck_reading_.end()) ck_reading_.erase(rd);
|
||||
auto fa = std::find(ck_free_after_.begin(), ck_free_after_.end(), job.ck_slot);
|
||||
if (fa != ck_free_after_.end()) {
|
||||
ck_free_after_.erase(fa);
|
||||
ck_frees_.push_back(job.ck_slot);
|
||||
}
|
||||
/* ON DISK ONLY IF THE RECORD STILL NAMES THE SLOT THE WRITE READ. A new commit at this
|
||||
* key, or a release by the cache, moved it while the write ran, and the bytes that
|
||||
* landed describe a state nobody holds any more; a new commit is written on its own. */
|
||||
if (r && r->ck_disk_src == job.ck_slot) {
|
||||
r->ck_disk_src = -1;
|
||||
if (ok && job.ck_ok && r->ck_slot == job.ck_slot) {
|
||||
r->ck_on_disk = true;
|
||||
++stats_.ck_to_disk;
|
||||
}
|
||||
}
|
||||
if (r) queue_disk(job.key, *r);
|
||||
}
|
||||
/* A write that failed is not tried again: a store that refused it once will refuse the
|
||||
* next, and the entry stays host-only, which is what it was before. */
|
||||
return;
|
||||
}
|
||||
|
||||
/* A store slot a read was given and nothing took goes back to the store. */
|
||||
auto ck_back = [&] { if (job.ck_want && job.ck_slot >= 0) ck_frees_.push_back(job.ck_slot); };
|
||||
|
||||
if (it == recs_.end()) {
|
||||
/* Nothing names the slots a job was handed but the job itself. */
|
||||
/* Nothing names the slots a copy was handed but the job itself. */
|
||||
if (job.kind == TierJob::Kind::WriteBack) give_slot(job.host_slot);
|
||||
ck_back();
|
||||
return;
|
||||
}
|
||||
Rec& r = it->second;
|
||||
r.pending = false;
|
||||
r.fetching = false;
|
||||
/* A promotion the chain was cut before, or a read that never ran, is not a failure: nothing
|
||||
* was tried. */
|
||||
const bool may_skip = job.kind == TierJob::Kind::ToDevice || job.kind == TierJob::Kind::ToHost;
|
||||
if (!ok && (!may_skip || job.started)) ++stats_.failures;
|
||||
/* A promotion the chain was cut before is not a failure: nothing was tried. */
|
||||
if (!ok && (job.kind != TierJob::Kind::ToDevice || job.started)) ++stats_.failures;
|
||||
|
||||
/* A record that was forgotten mid-transfer is finished off here and nowhere else. Doing it at
|
||||
* the top, before the per-kind handling, means no branch below has to remember to check. */
|
||||
if (r.doomed) {
|
||||
/* THE JOB'S SLOTS AND THE RECORD'S ARE NOT THE SAME SLOTS on every path. A copy's host
|
||||
* slots were the job's until it reported, and a promotion out of disk ran through a join
|
||||
* slot the record never owned; freeing only the record's would leak those, and freeing
|
||||
* the job's as well where they ARE the record's would return one slot twice. */
|
||||
/* THE JOB'S SLOT AND THE RECORD'S ARE NOT THE SAME SLOT on every path. A copy's host slot
|
||||
* is the job's until it reports; freeing only the record's would leak it, and freeing the
|
||||
* job's as well where it IS the record's would return one slot twice. */
|
||||
if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot);
|
||||
ck_back();
|
||||
release_storage(job.key, r);
|
||||
free_host(r);
|
||||
recs_.erase(it);
|
||||
return;
|
||||
}
|
||||
@@ -871,8 +460,6 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
|
||||
if (r.tier == KVTier::Device && r.host_slot >= 0) queue_clean(job.key, r);
|
||||
/* A copy that failed is tried again. */
|
||||
queue_copy(job.key, r);
|
||||
/* And what landed goes on to disk. */
|
||||
queue_disk(job.key, r);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -882,16 +469,12 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
|
||||
r.blocks = job.blocks;
|
||||
/* THE HOST COPY IS KEPT, which is what makes the entry clean the moment it lands:
|
||||
* its VRAM copy can go again at no cost, and the next copy this conversation needs
|
||||
* is only of the tokens its next turn adds. A disk entry keeps the slot it was
|
||||
* read into for the same reason -- it holds exactly the entry's bytes -- and keeps
|
||||
* its disk copy, which is what lets that slot go again for nothing. */
|
||||
* is only of the tokens its next turn adds. */
|
||||
r.host_slot = job.host_slot;
|
||||
/* THE CLOCK RESTARTS: the entry came back because a request is about to hit it. */
|
||||
if (now_ns) r.used_ns = now_ns;
|
||||
r.fetched_ns = 0;
|
||||
++stats_.promoted;
|
||||
queue_clean(job.key, r);
|
||||
queue_disk(job.key, r);
|
||||
return;
|
||||
}
|
||||
if (!job.started) {
|
||||
@@ -908,68 +491,19 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
|
||||
* still holds an entry naming blocks that are not ours any more, and left alone it
|
||||
* would serve them. */
|
||||
if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot);
|
||||
release_storage(job.key, r);
|
||||
free_host(r);
|
||||
recs_.erase(it);
|
||||
drop_rooted(job.key);
|
||||
if (on_drop_) on_drop_(job.key);
|
||||
return;
|
||||
|
||||
case TierJob::Kind::DropHost:
|
||||
give_slot(job.host_slot);
|
||||
free_host(r);
|
||||
++stats_.host_drops;
|
||||
r.host_slot = -1;
|
||||
release_storage(job.key, r);
|
||||
recs_.erase(it);
|
||||
drop_rooted(job.key);
|
||||
if (on_drop_) on_drop_(job.key);
|
||||
return;
|
||||
|
||||
case TierJob::Kind::ToHost: {
|
||||
if (!job.started) {
|
||||
/* NEVER READ: the slots go back and the record is where it was, on disk. */
|
||||
give_slot(job.host_slot);
|
||||
ck_back();
|
||||
relist(job.key, r);
|
||||
return;
|
||||
}
|
||||
if (!ok) {
|
||||
/* THE STORE NO LONGER HOLDS WHAT THE RECORD SAYS IT DOES -- its own eviction does
|
||||
* not tell the tiers, and a slot that fails its verify is dropped by the read. The
|
||||
* record claims bytes nobody has, so it goes, and the cache has to hear so. */
|
||||
give_slot(job.host_slot);
|
||||
ck_back();
|
||||
release_storage(job.key, r);
|
||||
recs_.erase(it);
|
||||
if (on_drop_) on_drop_(job.key);
|
||||
return;
|
||||
}
|
||||
if (job.host_slot >= 0) {
|
||||
r.host_slot = job.host_slot;
|
||||
r.tier = KVTier::Host;
|
||||
++stats_.fetched;
|
||||
}
|
||||
if (job.ck_want && job.ck_slot >= 0) {
|
||||
/* THE SNAPSHOT IS IN ITS STORE SLOT AGAIN, and keeps its disk copy -- which is what
|
||||
* lets the slot go again for nothing. The engine hands the slot to the cache's
|
||||
* index entry (PrefixCache::reattach_snapshot). */
|
||||
if (job.ck_ok && r.ck_slot < 0) {
|
||||
r.ck_slot = job.ck_slot;
|
||||
++stats_.ck_fetched;
|
||||
} else {
|
||||
ck_back();
|
||||
if (!job.ck_ok && r.ck_slot < 0 && r.ck_on_disk) {
|
||||
/* The disk store lost it; the blocks are still good. */
|
||||
r.ck_on_disk = false;
|
||||
++stats_.ck_drops;
|
||||
if (on_ck_drop_) on_ck_drop_(job.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
r.fetched_ns = now_ns ? now_ns : rad_mono_ns();
|
||||
relist(job.key, r);
|
||||
return;
|
||||
}
|
||||
|
||||
case TierJob::Kind::ToDisk:
|
||||
return; /* settled above */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1094,11 +628,11 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
out.push_back(std::move(si));
|
||||
}
|
||||
}
|
||||
/* SNAPSHOTS IN THE STORE AND ON DISK, each once. The store is the engine's and is not read
|
||||
* from this thread, and a disk snapshot has only a flag on its record -- but this walk visits
|
||||
* every record a stored conversation reaches, so it counts them here. They are sparse, one
|
||||
* per checkpoint interval, so the sets stay small beside the walk that fills them. */
|
||||
std::unordered_set<BlockHash, BlockHashHash> disk_snaps, host_snaps;
|
||||
/* SNAPSHOTS IN THE STORE, each once. The store is the engine's and is not read from this
|
||||
* thread -- but this walk visits every record a stored conversation reaches, so it counts them
|
||||
* here. They are sparse, one per checkpoint interval, so the set stays small beside the walk
|
||||
* that fills it. */
|
||||
std::unordered_set<BlockHash, BlockHashHash> host_snaps;
|
||||
size_t kept = 0;
|
||||
for (size_t k = 0; k < out.size(); ++k) {
|
||||
SessionInfo& si = out[k];
|
||||
@@ -1124,17 +658,14 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
switch (rr.tier) {
|
||||
case KVTier::Device: ++si.on_device; break;
|
||||
case KVTier::Host: ++si.on_host; break;
|
||||
case KVTier::Disk: ++si.on_disk; break;
|
||||
}
|
||||
/* THE LINEAR HALF, COUNTED WHERE ITS BYTES ACTUALLY ARE and not where the blocks
|
||||
* are: a snapshot is in host memory from the moment it is saved, whatever tier
|
||||
* its blocks are on, and on disk alone once the store has given its slot up. */
|
||||
const bool ck = rr.ck_slot >= 0 || rr.ck_on_disk;
|
||||
if (rr.ck_slot >= 0) { ++si.snapshots; ++si.snap_host; }
|
||||
else if (rr.ck_on_disk) { ++si.snapshots; ++si.snap_disk; }
|
||||
if (rr.ck_on_disk && occ) disk_snaps.insert(h);
|
||||
if (rr.ck_slot >= 0 && occ) host_snaps.insert(h);
|
||||
if (ck && rr.ck_pos > si.resume_tokens) si.resume_tokens = rr.ck_pos;
|
||||
/* THE LINEAR HALF, which is in host memory from the moment it is saved, whatever
|
||||
* tier its blocks are on. */
|
||||
if (rr.ck_slot >= 0) {
|
||||
++si.snapshots;
|
||||
if (occ) host_snaps.insert(h);
|
||||
if (rr.ck_pos > si.resume_tokens) si.resume_tokens = rr.ck_pos;
|
||||
}
|
||||
}
|
||||
if (at >= chain.size()) break;
|
||||
}
|
||||
@@ -1152,12 +683,10 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
Slice lk(mu_);
|
||||
occ->host_bytes = arena_.used_slots() * cfg_.entry_bytes +
|
||||
(int64_t)host_snaps.size() * cfg_.ckpt_bytes;
|
||||
occ->disk_bytes = stats_.disk_bytes + (int64_t)disk_snaps.size() * cfg_.ckpt_bytes;
|
||||
/* What the operator gave the block arena and the snapshot store -- the same scope as
|
||||
* `host_bytes` above, which counts both. */
|
||||
occ->host_cap_bytes = (host_on() ? cfg_.host_cap_bytes : 0) +
|
||||
cfg_.ckpt_slots * cfg_.ckpt_bytes;
|
||||
occ->disk_cap_bytes = disk_on() ? cfg_.disk_cap_bytes : 0;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
+87
-251
@@ -1,5 +1,5 @@
|
||||
/* kvtier.h -- where a finished conversation's KV is kept once VRAM has a better use for it
|
||||
* (spec §7.3).
|
||||
* (spec §7.3): VRAM, then host memory, and nowhere else.
|
||||
*
|
||||
* The prefix cache holds a KV reference on every block it indexes, so a finished turn's context
|
||||
* survives into the next one. That is the whole value of it, and it is also the whole cost: those
|
||||
@@ -20,15 +20,14 @@
|
||||
* published --(copy, at once)--> clean on device --(memory wanted)--> host
|
||||
* ^ |
|
||||
* +------------(a hit restores)------+
|
||||
* host copy --(copy to disk, at once)--> clean on host --(a slot wanted)--> disk
|
||||
*
|
||||
* THE DISK TIER IS A COPY TOO, by the same argument one level down. Every host copy is written to
|
||||
* the disk store in the background as soon as it lands, and keeps its host slot. Once the write
|
||||
* has landed the host slot is as free to give up as a clean entry's VRAM: when a copy or a
|
||||
* restore needs a slot and the arena is full, the oldest entries the disk also holds give theirs
|
||||
* up, which is bookkeeping and nothing else. Moving an entry to disk only when its slot is wanted
|
||||
* would put a write on the path of whatever wanted it -- a restore out of disk needs a host slot to
|
||||
* read through, and an arena full of host-only entries has no slot to give it at all.
|
||||
* HOST MEMORY IS THE LAST TIER. When a copy needs a slot and the arena is full, the oldest
|
||||
* entries only the host holds are dropped, as many as the copies refused. Nothing is written to a
|
||||
* drive: a tier there wears it at the rate the server prefills -- every block and every snapshot a
|
||||
* prompt produces -- to spare a re-prefill only for what outgrows VRAM and host memory together.
|
||||
*
|
||||
* AND EVERY ENTRY EXPIRES. One no request has used for --prefix-cache-ttl seconds leaves the cache
|
||||
* from whichever tier holds it (PrefixCache::expire); it is not moved anywhere first.
|
||||
*
|
||||
* THERE IS NO IDLE THRESHOLD ON THE WAY OUT OF VRAM, and that is the point of the design rather
|
||||
* than an omission. A threshold is a guess at when an entry stops being worth its VRAM, made in
|
||||
@@ -74,8 +73,7 @@
|
||||
* is on no list: the copy it keeps off the card is what lets the VRAM copy go, and the tiers'
|
||||
* lists are for entries no longer in VRAM. A Rec with a transfer through the pool outstanding is
|
||||
* `pending` and is in no list either: it cannot be chosen as a victim, cannot be planned again,
|
||||
* and cannot be erased until the engine reports the job finished or failed. A disk write is not
|
||||
* such a transfer -- it reads host memory and nothing else -- and holds only the slots it reads.
|
||||
* and cannot be erased until the engine reports the job finished or failed.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/hostarena.h"
|
||||
@@ -86,7 +84,7 @@
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <map>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
@@ -96,9 +94,7 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
class SSDTier;
|
||||
|
||||
enum class KVTier : uint8_t { Device = 0, Host = 1, Disk = 2 };
|
||||
enum class KVTier : uint8_t { Device = 0, Host = 1 };
|
||||
const char* kv_tier_name(KVTier t);
|
||||
|
||||
/* What the engine is being asked to do. One job is one entry moving one step. The block ids are
|
||||
@@ -107,47 +103,23 @@ const char* kv_tier_name(KVTier t);
|
||||
struct TierJob {
|
||||
enum class Kind : uint8_t {
|
||||
WriteBack, /* gather_rows out of the pool into a host slot; the entry stays in VRAM */
|
||||
ToDisk, /* a host slot written to the disk store; the host copy is kept */
|
||||
ToDevice, /* allocate blocks, scatter_rows in; the host copy is kept */
|
||||
DropHost, /* no disk tier and the arena is full: this record's bytes go */
|
||||
ToHost, /* the disk store read into a host slot, ahead of the restore that wants it */
|
||||
DropHost, /* the arena is full: this record's bytes go */
|
||||
};
|
||||
Kind kind = Kind::WriteBack;
|
||||
BlockHash key;
|
||||
/* Per cached group, in PrefixCache::cached_groups() order. For a write-back these are the
|
||||
* blocks to read -- EMPTY when only the snapshot is being copied, because the blocks already
|
||||
* have their host copy; for a promotion they are filled in by the engine with the blocks it
|
||||
* blocks to read; for a promotion they are filled in by the engine with the blocks it
|
||||
* allocated. */
|
||||
std::vector<int32_t> blocks;
|
||||
int32_t host_slot = -1;
|
||||
int64_t bytes = 0;
|
||||
|
||||
/* ---- the linear half, on a hybrid model ----
|
||||
*
|
||||
* A session's recurrent state lives in a SNAPSHOT SLOT of the checkpoint store -- pinned host
|
||||
* memory, one contiguous KVManager::checkpoint_bytes() shard a rank -- rather than in blocks,
|
||||
* so it never crosses the link with them: a lookup restores it straight out of its slot. The
|
||||
* tiers only move it between that slot and the disk store, on the disk thread: a ToDisk job
|
||||
* reads `ck_slot`, a ToHost job writes it.
|
||||
*
|
||||
* `ck_slot` is an INPUT to both. A read off disk is planned with `ck_want` and the engine
|
||||
* allocates the slot before the job leaves its hands (it holds the store's free list); a
|
||||
* write names the slot the snapshot is in. */
|
||||
int32_t ck_slot = -1;
|
||||
int64_t ck_pos = 0; /* the token position, which the disk store verifies on the way back */
|
||||
bool ck_want = false; /* a read off disk should bring the snapshot in too */
|
||||
int64_t ck_bytes = 0;
|
||||
/* DID THE SNAPSHOT HALF SUCCEED. Separate from the job's own result because the two halves
|
||||
* fail for different reasons and are repaired differently: a snapshot whose disk write failed
|
||||
* is still correct in its slot, and one whose read failed costs the session a replay of its
|
||||
* linear layers, not its blocks. */
|
||||
bool ck_ok = true;
|
||||
/* A PROMOTION THAT WAS NEVER STARTED, as opposed to one that failed part of the way through.
|
||||
* A restore reserves every block before it moves a byte, and a chain that did not fit is cut
|
||||
* where the reservation ran out: the entries past that point were not touched, their host
|
||||
* copies are exactly what they were, and they stay on the host tier. Only an entry whose
|
||||
* scatter may have run is dropped on failure. A read off disk that never ran -- its batch
|
||||
* could not be handed to the thread -- is the same: the record stays on disk. */
|
||||
* scatter may have run is dropped on failure. */
|
||||
bool started = false;
|
||||
};
|
||||
|
||||
@@ -156,23 +128,19 @@ class IdleTiers {
|
||||
public:
|
||||
struct Config {
|
||||
int64_t host_cap_bytes = 0; /* 0 is off */
|
||||
int64_t disk_cap_bytes = 0;
|
||||
int64_t entry_bytes = 0; /* one entry: sum over cached groups of bytes_per_block */
|
||||
/* ---- the linear half ----
|
||||
* `ckpt_bytes` is ONE SNAPSHOT, every rank's shard of it, laid out exactly like
|
||||
* `entry_bytes`. The snapshots live in the engine's checkpoint store, `ckpt_slots` deep,
|
||||
* which is reported here and not allocated: --prefix-cache-host-mib is the blocks' alone.
|
||||
* `ckpt_disk_slots` zero means snapshots never reach disk, and the blocks still do. */
|
||||
* which is reported here and not allocated: --prefix-cache-mib is the blocks' alone. */
|
||||
int64_t ckpt_bytes = 0;
|
||||
int64_t ckpt_slots = 0; /* the checkpoint store's capacity, for the report and view */
|
||||
int64_t ckpt_disk_slots = 0; /* how many the disk store was opened for */
|
||||
};
|
||||
|
||||
int configure(const Config& c, SSDTier* disk);
|
||||
int configure(const Config& c);
|
||||
void close();
|
||||
bool host_on() const { return cfg_.host_cap_bytes > 0 && arena_.enabled(); }
|
||||
bool disk_on() const { return cfg_.disk_cap_bytes > 0 && disk_ != nullptr; }
|
||||
bool any_on() const { return host_on() || disk_on(); }
|
||||
bool any_on() const { return host_on(); }
|
||||
std::string report() const;
|
||||
|
||||
/* Called by PrefixCache whenever an entry is inserted. The blocks come with it because a copy
|
||||
@@ -189,7 +157,7 @@ public:
|
||||
* storage it held is returned. A record with work outstanding is marked instead of erased and
|
||||
* is cleaned up when the job reports. */
|
||||
void forget(const BlockHash& key);
|
||||
/* AN OFF-DEVICE ENTRY WAS RECOMPUTED. A request that could not reach the tier copy -- a
|
||||
/* AN OFF-DEVICE ENTRY WAS RECOMPUTED. A request that could not reach the host copy -- a
|
||||
* restore that did not fit, a chain past the point a promotion was cut -- computes the same
|
||||
* tokens again and publishes them, and the cache takes those blocks as the entry's device
|
||||
* copy. The tier copy goes: two copies of one entry computed by two different batches agree
|
||||
@@ -209,10 +177,9 @@ public:
|
||||
* slots already allocated. Oldest first, so a conversation that went idle before another is
|
||||
* copied before it. Blocks only: a snapshot is in host memory from the moment it is saved.
|
||||
*
|
||||
* Every record named by a returned job is `pending` until report() is called for it. An arena
|
||||
* too full to take the batch first gives up the host slots of the oldest entries the disk also
|
||||
* holds (make_room); what is still short stays queued, and with no disk tier the next
|
||||
* maintenance plan drops that many of the oldest host-only entries. */
|
||||
* Every record named by a returned job is `pending` until report() is called for it. What an
|
||||
* arena too full to take the batch cannot hold stays queued, and the next maintenance plan
|
||||
* drops that many of the oldest host-only entries. */
|
||||
void plan_writeback(int64_t max_entries, std::vector<TierJob>* out);
|
||||
bool writeback_waiting() const;
|
||||
/* Has the arena refused a copy since the last maintenance plan? That plan is then due now. */
|
||||
@@ -223,87 +190,36 @@ public:
|
||||
* free nothing -- and reports what it did through drop_commit. A key handed out here and not
|
||||
* dropped is the cache's to ask about again. */
|
||||
void take_clean(std::vector<BlockHash>* out);
|
||||
/* Can this entry's blocks leave VRAM for nothing, right now: a copy off the card has landed --
|
||||
* in host memory or on disk -- and no job is out on the record. */
|
||||
/* Can this entry's blocks leave VRAM for nothing, right now: its host copy has landed and no
|
||||
* job is out on the record. */
|
||||
bool droppable(const BlockHash& key) const;
|
||||
/* The cache released the blocks. The record is now a host record with its copy, on the host
|
||||
* tier's list like any other -- or a disk record, when its host slot was already given up.
|
||||
* Its snapshot stays in its slot: the store is not the pool, and the blocks leaving frees
|
||||
* nothing there. */
|
||||
* tier's list like any other. Its snapshot stays in its slot: the store is not the pool, and
|
||||
* the blocks leaving frees nothing there. */
|
||||
void drop_commit(const BlockHash& key);
|
||||
|
||||
/* ---------------- the snapshots' own pressure ----------------
|
||||
/* ---------------- capacity ----------------
|
||||
*
|
||||
* The checkpoint store is --checkpoint-slots deep for the whole server, and when it is full
|
||||
* the cache retires the least recently used snapshot to make room. One the disk also holds
|
||||
* need not be lost: the cache DETACHES it instead -- the slot goes back, the index entry
|
||||
* stays, and the next restore of the session reads the state back off disk (plan_fetch).
|
||||
* True when this key's snapshot is in a slot and has a finished disk copy that no write is
|
||||
* still producing. */
|
||||
bool snapshot_backed(const BlockHash& key) const;
|
||||
/* Is this key's snapshot in store slot `slot` by this object's record? */
|
||||
bool snapshot_in_slot(const BlockHash& key, int32_t slot) const;
|
||||
/* The cache gave the slot back; the disk copy is now the snapshot. */
|
||||
void snapshot_detached(const BlockHash& key);
|
||||
|
||||
/* ---------------- the slow half ----------------
|
||||
*
|
||||
* The host copies waiting for their disk copy, in the order they landed, as ToDisk jobs --
|
||||
* blocks and snapshot halves together where both are waiting, and a resume point's snapshot
|
||||
* ahead of everything (note_snapshot). A ToDisk job does NOT make its record pending: it only
|
||||
* reads the host slots it names, which a restore may read at the same time, and a slot given
|
||||
* up while the write is out is freed when the write reports rather than under it. With no disk tier, the copies the arena refused since the last plan
|
||||
* are made room for by dropping that many of the oldest host-only entries. `budget` bounds
|
||||
* one plan so the IO a pass asks for is bounded too. */
|
||||
* The copies the arena refused since the last plan are made room for by dropping that many of
|
||||
* the oldest host-only entries, as DropHost jobs; `budget` bounds one plan. */
|
||||
void plan(int budget, std::vector<TierJob>* out);
|
||||
/* Is a host copy waiting for its disk copy? The slow half is then due now rather than on its
|
||||
* once-a-second clock: an entry the disk does not hold yet is one whose host slot cannot be
|
||||
* given up for nothing. */
|
||||
bool disk_waiting() const;
|
||||
|
||||
/* ROOM IN THE ARENA, FOR NOTHING. Up to `n` host slots of entries the disk also holds, given
|
||||
* up oldest first: host records first -- they become disk records -- and then the host copies
|
||||
* of clean VRAM entries, which stay clean through their disk copy. Nothing is written; an
|
||||
* entry whose disk copy has not landed is not a candidate. Returns how many were freed. */
|
||||
int64_t make_room(int64_t n);
|
||||
|
||||
/* ---------------- reading a chain back off disk, before its request runs ----------------
|
||||
/* ---------------- expiry ----------------
|
||||
*
|
||||
* A RESTORE COPIES HOST MEMORY TO THE DEVICE AND NOTHING ELSE. It runs inside the scheduler's
|
||||
* step, and a disk read there -- thousands of entries for a long conversation -- would hold
|
||||
* every other request's next token for as long as the reads take. So the disk half of a chain
|
||||
* is read into host slots on the IO thread first, as ToHost jobs, while the request that wants
|
||||
* it waits outside admission and everything else keeps running; the restore then finds the
|
||||
* chain in host memory.
|
||||
*
|
||||
* `chain` is every key a prompt's prefix matched, in order. True when the request must wait:
|
||||
* a read for one of its entries was planned now, into `out`, or is already out. False when
|
||||
* none of the chain is on disk, or none of what is can be given a slot -- a chain larger than
|
||||
* the arena comes back as far as the arena holds, and the rest is prefilled.
|
||||
*
|
||||
* The chain's deepest snapshot, when it is only on disk, is read with it -- that is the state
|
||||
* the hit resumes from -- into the store slot `*ck_slot` the caller allocated after asking
|
||||
* snapshot_fetch_wanted. The slot is taken (and `*ck_slot` set to -1) only when the read is
|
||||
* planned; otherwise it is still the caller's to free. Every record named is `pending` until
|
||||
* the read reports, and what a read brought in is not given up to make room for anybody else
|
||||
* until the request has had the step it needs to claim it. */
|
||||
bool plan_fetch(const std::vector<BlockHash>& chain, std::vector<TierJob>* out,
|
||||
uint64_t now_ns, int32_t* ck_slot = nullptr);
|
||||
/* Would plan_fetch read this chain's deepest snapshot off disk -- is it there and nowhere
|
||||
* else? Asked first, because the slot it reads into is the store's, which the caller owns. */
|
||||
bool snapshot_fetch_wanted(const std::vector<BlockHash>& chain) const;
|
||||
* THE HOST RECORDS NO REQUEST HAS USED SINCE `cutoff_ns`, oldest first, up to `max`: what
|
||||
* --prefix-cache-ttl takes out of host memory. The cache drops each one (drop_offdevice) and
|
||||
* the record goes with it; a record with a job out is passed over and asked about again. */
|
||||
void expired(uint64_t cutoff_ns, size_t max, std::vector<BlockHash>* out) const;
|
||||
|
||||
/* A promotion, asked for by a lookup that hit off-device. Returns false when the entry is not
|
||||
* in host memory -- a disk entry is read in by plan_fetch first -- or already has work
|
||||
* outstanding. */
|
||||
* in host memory or already has work outstanding. */
|
||||
bool plan_promote(const BlockHash& key, TierJob* out);
|
||||
|
||||
/* The engine finished (or failed) a job. On failure the record returns to the state it was in
|
||||
* with its storage intact, EXCEPT for a failed ToDevice that had started, which cannot leave a
|
||||
* half-scattered pool behind and so drops the entry -- and a disk read that failed is marked
|
||||
* started for that reason too: the store no longer holds what the record says it does. A
|
||||
* successful ToDevice restarts the record's clock at `now_ns` when one is given: the promotion
|
||||
* happened because something is about to use it. */
|
||||
* half-scattered pool behind and so drops the entry. A successful ToDevice restarts the
|
||||
* record's clock at `now_ns` when one is given: the promotion happened because something is
|
||||
* about to use it. */
|
||||
void report(const TierJob& job, bool ok, uint64_t now_ns = 0);
|
||||
|
||||
/* WAS THIS KEY FORGOTTEN WHILE ITS JOB WAS OUT -- or is it not known at all. The engine asks
|
||||
@@ -314,8 +230,8 @@ public:
|
||||
|
||||
/* ============================ WHEN THE BYTES ARE GONE, SO IS THE ENTRY ====================
|
||||
*
|
||||
* A record erased while its bytes are OFF-DEVICE -- a capacity drop, or a promotion that
|
||||
* failed -- leaves the prefix cache holding an entry whose block ids the pool has already
|
||||
* A record erased while its bytes are OFF-DEVICE -- a capacity drop, a promotion that failed,
|
||||
* an expiry -- leaves the prefix cache holding an entry whose block ids the pool has already
|
||||
* given to somebody else. `resident_off_device` then answers false, because there is no
|
||||
* record any more, and the cache would serve those ids as an ordinary hit: one conversation
|
||||
* gets another's context, as fluent and plausible text.
|
||||
@@ -326,43 +242,18 @@ public:
|
||||
|
||||
/* ---------------- the linear half of an idle session ----------------
|
||||
*
|
||||
* Told by PrefixCache::commit_checkpoint, for the same reason note_used carries the block ids:
|
||||
* a copy has to know what to move and the cache's index is the only place it is written down.
|
||||
* `slot` is a checkpoint store slot and `pos` the token position the disk store verifies a
|
||||
* read against.
|
||||
*
|
||||
* A record may hear this BEFORE it hears note_used -- a checkpoint is committed mid-request
|
||||
* and the chain is published when the request closes -- so this creates the record if it has
|
||||
* to. The snapshot is queued for its disk copy when the record is published, or at once when
|
||||
* it already was -- or AT ONCE AND AHEAD OF EVERYTHING when it is a resume point (`resume`):
|
||||
* the deepest checkpoint its prompt gets, which the next turn resumes from. Until it is on disk
|
||||
* the store can only retire it, and a burst of prefills churns the store through the whole
|
||||
* decode in between. */
|
||||
void note_snapshot(const BlockHash& key, int32_t slot, int64_t pos, bool resume = false);
|
||||
/* The cache is done with the snapshot at `key`, which is in store slot `slot`: return whatever
|
||||
* the tiers hold for it. The record's BLOCKS are untouched -- the two halves are retired by
|
||||
* different policies on different clocks, and a snapshot the retention policy drops says
|
||||
* nothing about the prefix.
|
||||
*
|
||||
* TRUE WHEN A DISK WRITE IS STILL READING THE SLOT, and then the slot is NOT the caller's to
|
||||
* free: a save into it would put half of another snapshot on disk under this key. The tiers
|
||||
* keep the slot and hand it back through `take_checkpoint_frees` once the write has reported.
|
||||
* Decided by the slot and not by the record, which may have gone while the write was out. */
|
||||
bool release_snapshot(const BlockHash& key, int32_t slot);
|
||||
/* Store slots whose release waited on a disk write, now safe to free. */
|
||||
void take_checkpoint_frees(std::vector<int32_t>* out);
|
||||
/* Is a disk write reading store slot `slot` right now? A save into it would tear the write. */
|
||||
bool slot_reading(int32_t slot) const;
|
||||
/* THE TIERS LOST A SNAPSHOT BUT KEPT THE BLOCKS: its only copy was on disk and the disk store
|
||||
* no longer has it. The cache has to stop offering an index entry whose bytes nobody holds.
|
||||
* Wired to PrefixCache::drop_snapshot; separate from set_drop_sink because losing half an
|
||||
* entry and losing all of it are different events with different repairs. Never said of a
|
||||
* snapshot still in its slot: that one is the cache's. */
|
||||
void set_snapshot_drop_sink(std::function<void(const BlockHash&)> f) { on_ck_drop_ = std::move(f); }
|
||||
/* Do snapshots reach disk at all? */
|
||||
bool ckpt_disk_on() const { return disk_on() && cfg_.ckpt_bytes > 0 && cfg_.ckpt_disk_slots > 0; }
|
||||
* Told by PrefixCache::commit_checkpoint and PrefixCache::retire_ckpt, so the session view can
|
||||
* say which conversations hold a snapshot and where a return resumes from. A snapshot lives in
|
||||
* its checkpoint store slot, in host memory, and never moves: the tiers only record it. A
|
||||
* record may hear of a snapshot BEFORE it hears note_used -- a checkpoint is committed
|
||||
* mid-request and the chain is published when the request closes -- so this creates the
|
||||
* record if it has to. */
|
||||
void note_snapshot(const BlockHash& key, int32_t slot, int64_t pos);
|
||||
/* The cache is done with the snapshot at `key`. The record's BLOCKS are untouched -- the two
|
||||
* halves are retired by different policies on different clocks, and a snapshot the retention
|
||||
* policy drops says nothing about the prefix. */
|
||||
void release_snapshot(const BlockHash& key);
|
||||
int64_t ckpt_bytes() const { return cfg_.ckpt_bytes; }
|
||||
int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; }
|
||||
int64_t ckpt_slots() const { return cfg_.ckpt_slots; }
|
||||
|
||||
/* ---------------- the session view ----------------
|
||||
@@ -375,11 +266,7 @@ public:
|
||||
*
|
||||
* THE SIZES THEREFORE OVERLAP AND THE TOTAL IS NOT A SUM. Sharing is the point of the cache;
|
||||
* a view that hid it would make a server look like it was storing several times what it is.
|
||||
* Anything reporting these numbers says so.
|
||||
*
|
||||
* The model name is carried rather than looked up because the disk tier outlives the process:
|
||||
* a store written by one container and read back under another is refused by fingerprint, and
|
||||
* the name is what turns that refusal into something an operator can act on. */
|
||||
* Anything reporting these numbers says so. */
|
||||
struct SessionInfo {
|
||||
uint64_t id = 0;
|
||||
std::string model;
|
||||
@@ -388,36 +275,34 @@ public:
|
||||
int64_t bytes = 0;
|
||||
uint64_t first_seen_ns = 0;
|
||||
uint64_t last_used_ns = 0;
|
||||
int64_t on_device = 0, on_host = 0, on_disk = 0; /* blocks, by tier */
|
||||
int64_t on_device = 0, on_host = 0; /* blocks, by tier */
|
||||
/* LINEAR STATE, on a hybrid model. Counted separately from blocks because it is a
|
||||
* different resource with a different scarcity: a snapshot is thousands of blocks' worth
|
||||
* of bytes and there are only --checkpoint-slots of them in host memory. A session showing
|
||||
* blocks on disk and no snapshot anywhere is one that will come back and re-run every
|
||||
* blocks in host memory and no snapshot is one that will come back and re-run every
|
||||
* recurrent layer over its whole transcript, which is not what "restored" should mean. */
|
||||
int64_t snapshots = 0; /* this session holds, any tier */
|
||||
int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */
|
||||
int64_t snapshots = 0; /* this session holds */
|
||||
int64_t snap_bytes = 0;
|
||||
/* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain, in any
|
||||
* tier. On a hybrid model the scheduler clamps a hit to the last linear checkpoint it can
|
||||
/* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain. On a
|
||||
* hybrid model the scheduler clamps a hit to the last linear checkpoint it can
|
||||
* reach, so this -- not n_tokens and not the blocks -- is the prefix the next turn skips,
|
||||
* and n_tokens minus it is what that turn prefills. Zero with no snapshot anywhere. */
|
||||
int64_t resume_tokens = 0;
|
||||
bool moving = false; /* a job is outstanding */
|
||||
};
|
||||
/* WHAT THE TIERS OFF THE CARD ARE HOLDING, blocks and snapshots together, each counted once.
|
||||
* The per-session figures cannot be summed into this: sessions sharing a prefix share its
|
||||
* blocks and its snapshots. Caps are what the operator configured, snapshots included. A
|
||||
* clean entry's host copy is counted: it occupies the arena whether or not the VRAM copy has
|
||||
* gone yet. */
|
||||
/* WHAT HOST MEMORY IS HOLDING FOR THE CACHE, each block counted once. The per-session figures
|
||||
* cannot be summed into this: sessions sharing a prefix share its blocks. The cap is what the
|
||||
* operator configured. A clean entry's host copy is counted: it occupies the arena whether or
|
||||
* not the VRAM copy has gone yet. */
|
||||
struct Occupancy {
|
||||
int64_t host_bytes = 0, disk_bytes = 0;
|
||||
int64_t host_cap_bytes = 0, disk_cap_bytes = 0;
|
||||
int64_t host_bytes = 0;
|
||||
int64_t host_cap_bytes = 0;
|
||||
};
|
||||
/* Publish one request's chain. Called from PrefixCache::insert, which is the only place that
|
||||
* knows a chain was completed rather than merely touched.
|
||||
*
|
||||
* KEPT WHETHER OR NOT ANY TIER IS ON, because what it records is not a tiering fact. A server
|
||||
* with no --prefix-cache-host-mib still stores conversations -- it stores them all in VRAM, which
|
||||
* with no --prefix-cache-mib still stores conversations -- it stores them all in VRAM, which
|
||||
* is the case the table most wants to show -- and gating the record on the mover would make
|
||||
* the view report an empty server to every operator who has not opted into tiering.
|
||||
*
|
||||
@@ -441,19 +326,11 @@ public:
|
||||
* then given up. They are different events: a copy is link traffic and a drop is VRAM
|
||||
* handed to something else, and a conversation that returns before anything wants its
|
||||
* VRAM is copied and never dropped. */
|
||||
int64_t to_host = 0, dropped = 0, to_disk = 0, promoted = 0;
|
||||
/* `host_freed` is host slots given up because the disk holds the entry -- the host tier's
|
||||
* counterpart of `dropped`; `host_drops` is entries lost with no disk tier to hold them. */
|
||||
int64_t host_freed = 0, host_drops = 0, failures = 0;
|
||||
int64_t host_bytes = 0, disk_bytes = 0;
|
||||
int64_t host_hits = 0, disk_hits = 0;
|
||||
/* Entries and snapshots read off disk into host memory ahead of a restore. */
|
||||
int64_t fetched = 0, ck_fetched = 0;
|
||||
/* SNAPSHOTS MOVED, counted apart from blocks. A hybrid session can move its whole chain
|
||||
* off the device and still replay every linear layer from zero on the way back, and no
|
||||
* block counter can tell the two apart -- these are the numbers that can. `ck_drops` is
|
||||
* snapshots whose only copy was lost. */
|
||||
int64_t ck_to_disk = 0, ck_drops = 0;
|
||||
int64_t to_host = 0, dropped = 0, promoted = 0;
|
||||
/* `host_drops` is entries the full arena gave up. */
|
||||
int64_t host_drops = 0, failures = 0;
|
||||
int64_t host_bytes = 0;
|
||||
int64_t host_hits = 0;
|
||||
/* WHAT THE STEP THREAD SPENT ON THEM, under the scheduler's lock: restores issued at
|
||||
* admission, and copies landed synchronously because pressure could not wait for them.
|
||||
* Host time, not link time -- what every other request waits through. */
|
||||
@@ -474,72 +351,34 @@ private:
|
||||
KVTier tier = KVTier::Device;
|
||||
uint64_t used_ns = 0;
|
||||
/* THE HOST COPY. On a device record it is a copy that makes the record clean; on a host
|
||||
* record it is where the bytes are read from. -1 on a disk record always. */
|
||||
* record it is where the bytes are read from. */
|
||||
int32_t host_slot = -1;
|
||||
/* THE DISK STORE HOLDS THESE BYTES, written from the host copy. What makes the host slot
|
||||
* free to give up, and a device record with no host copy clean. The store evicts on its own
|
||||
* and does not say so; a read that finds the entry gone drops it (report). */
|
||||
bool on_disk = false;
|
||||
/* The host slot a disk write is reading right now, -1 when none. A slot given up while
|
||||
* this names it is freed when the write reports, not under it. */
|
||||
int32_t disk_src = -1;
|
||||
bool disk_q = false; /* in dk_q_: waiting for a disk copy */
|
||||
bool pending = false;
|
||||
bool fetching = false; /* the pending job is a read off disk (plan_fetch) */
|
||||
bool doomed = false; /* forget() arrived while pending */
|
||||
bool queued = false; /* in wb_q_: waiting for a copy */
|
||||
bool resume_q = false; /* in resume_q_: a resume point waiting for its disk copy */
|
||||
bool clean_q = false; /* in clean_q_: a drop the cache has not been asked about */
|
||||
bool listed = false; /* on host_lru_ or disk_lru_; `it` is valid */
|
||||
bool listed = false; /* on host_lru_; `it` is valid */
|
||||
std::vector<int32_t> blocks;
|
||||
/* ---- the linear half ----
|
||||
* `ck_slot` is the snapshot's checkpoint store slot and `ck_on_disk` the disk store's
|
||||
* copy. A snapshot the store gave up has only the second. All clear when the record
|
||||
* carries no snapshot, which is the common case -- one block in every
|
||||
* (interval / block_size) is a checkpoint position. */
|
||||
* `ck_slot` is the snapshot's checkpoint store slot and `ck_pos` its token position, for the
|
||||
* session view. -1 when the record carries no snapshot, which is the common case -- one
|
||||
* block in every (interval / block_size) is a checkpoint position. */
|
||||
int32_t ck_slot = -1;
|
||||
bool ck_on_disk = false;
|
||||
int64_t ck_pos = 0;
|
||||
/* The store slot a disk write is reading, as `disk_src` is for the blocks. */
|
||||
int32_t ck_disk_src = -1;
|
||||
/* WHEN A READ OFF DISK BROUGHT THIS RECORD IN, 0 when none did or its restore has run.
|
||||
* Until the request that asked for it has been admitted the slots are its and not the
|
||||
* arena's to give up: two conversations waiting on reads into a full arena would
|
||||
* otherwise each evict what the other had read, and neither would ever be restored. Held
|
||||
* for kFetchHoldNs at most, which bounds what a request that went away can pin. */
|
||||
uint64_t fetched_ns = 0;
|
||||
/* Set only while plan_fetch makes room: this record is part of the chain being read, and
|
||||
* giving its slot up to read another part of the same chain would be no progress. */
|
||||
bool keep = false;
|
||||
std::list<BlockHash>::iterator it;
|
||||
std::multimap<uint64_t, BlockHash>::iterator it;
|
||||
};
|
||||
|
||||
/* Does this record want a host copy it does not have yet? Its blocks are in VRAM with none. */
|
||||
bool wants_copy(const Rec& r) const;
|
||||
/* And a disk copy: a host copy of either half that the disk does not hold yet. */
|
||||
bool wants_disk(const Rec& r) const;
|
||||
bool wants_ck_disk(const Rec& r) const;
|
||||
void queue_copy(const BlockHash& key, Rec& r);
|
||||
void queue_clean(const BlockHash& key, Rec& r);
|
||||
void queue_disk(const BlockHash& key, Rec& r);
|
||||
/* GIVE UP A HOST SLOT, the record's or a finished job's. Every block-arena free goes through
|
||||
* `give_slot`, because a freed slot is what unblocks a write-back that found the arena full.
|
||||
* `free_host` is the record's own: a slot a disk write is reading is left
|
||||
* for that write's report to free. */
|
||||
* `free_host` is the record's own. */
|
||||
void give_slot(int32_t slot);
|
||||
void free_host(Rec& r);
|
||||
void set_on_disk(Rec& r, bool v);
|
||||
int64_t make_room_locked(int64_t n);
|
||||
/* May this record's host copies be given up to make room right now? Not while a read put
|
||||
* them there for a request that has not claimed them yet, nor while the chain being read
|
||||
* includes it. */
|
||||
bool held_by_fetch(const Rec& r, uint64_t now_ns) const;
|
||||
void unlist(Rec& r);
|
||||
void relist(const BlockHash& key, Rec& r);
|
||||
std::list<BlockHash>& list_for(KVTier t) { return t == KVTier::Host ? host_lru_ : disk_lru_; }
|
||||
void release_storage(const BlockHash& key, Rec& r);
|
||||
/* The chain position of the deepest snapshot no job is out on, or chain.size(). */
|
||||
size_t deepest_snapshot(const std::vector<BlockHash>& chain) const;
|
||||
|
||||
struct Session {
|
||||
int64_t n_tokens = 0;
|
||||
@@ -551,6 +390,8 @@ private:
|
||||
|
||||
/* Erase one row and its root index entry together. */
|
||||
void drop_session(uint64_t id);
|
||||
/* Every row whose chain starts at `key`, which has gone for good. */
|
||||
void drop_rooted(const BlockHash& key);
|
||||
/* The body of close(), for a caller that already holds the lock. */
|
||||
void reset();
|
||||
|
||||
@@ -594,42 +435,37 @@ private:
|
||||
mutable YieldingMutex mu_;
|
||||
|
||||
Config cfg_;
|
||||
SSDTier* disk_ = nullptr;
|
||||
HostArena arena_;
|
||||
std::unordered_map<BlockHash, Rec, BlockHashHash> recs_;
|
||||
std::list<BlockHash> host_lru_, disk_lru_; /* front = oldest */
|
||||
/* THE HOST-ONLY RECORDS BY LAST USE, begin() the least recently used. Keyed by the clock rather
|
||||
* than kept in the order records arrive, because a record arrives here when its VRAM copy is
|
||||
* given up, which says nothing about when a request last read it -- and both the capacity drop
|
||||
* and the expiry take the oldest by use. */
|
||||
std::multimap<uint64_t, BlockHash> host_lru_;
|
||||
/* THE WORK QUEUES, in the order the work arrived. Each holds a key at most once -- the Rec's
|
||||
* flag says whether it is in -- and a key whose record changed under it is skipped when it is
|
||||
* reached rather than searched for, so both stay a push and a pop. */
|
||||
std::deque<BlockHash> wb_q_; /* records wanting a host copy */
|
||||
std::deque<BlockHash> resume_q_; /* resume points wanting a disk copy, served first */
|
||||
std::deque<BlockHash> dk_q_; /* records wanting a disk copy, in the order they landed */
|
||||
std::vector<BlockHash> clean_q_; /* records whose VRAM copy may now go */
|
||||
/* STORE SLOTS A DISK WRITE IS READING, and those the cache let go of meanwhile. Kept by slot
|
||||
* and not on the record, because the record can be forgotten while the write is out and the
|
||||
* slot is the cache's either way. A few entries at most: one write batch is out at a time. */
|
||||
std::vector<int32_t> ck_reading_;
|
||||
std::vector<int32_t> ck_free_after_;
|
||||
std::vector<int32_t> ck_frees_; /* store slots a finished write released */
|
||||
/* COPIES THE ARENA REFUSED since the last maintenance plan, which is what that plan frees
|
||||
* room for. A count and not a list: any host-only entry makes room for any copy. */
|
||||
int64_t starved_ = 0;
|
||||
/* A WRITE-BACK FOUND THE ARENA FULL AND NOTHING TO GIVE UP. Waiting again changes nothing until
|
||||
* a slot is freed or an entry's disk copy lands, so the copy is not planned until one does --
|
||||
* otherwise every tick pops the queue, finds no slot and puts it back. */
|
||||
* a slot is freed, so the copy is not planned until one is -- otherwise every tick pops the
|
||||
* queue, finds no slot and puts it back. */
|
||||
bool wb_stuck_ = false;
|
||||
std::unordered_map<uint64_t, Session> sessions_;
|
||||
/* THE DEATH SIGNAL FOR A ROW, and the reason the table is bounded. A published chain is only
|
||||
* ever reachable from position zero, so the moment the cache evicts its FIRST block the
|
||||
* conversation cannot be hit at any length and the row describes blocks that are not there.
|
||||
* The cache announces every eviction through forget(), which is the only notice this object
|
||||
* gets, so the root is indexed and the row goes with it. Several sessions share a root when
|
||||
* The cache announces its evictions and expiries through forget(), and the entries this object
|
||||
* drops itself -- a full arena's, a failed restore's -- go through drop_rooted as well, so the
|
||||
* root is indexed and the row goes with it. Several sessions share a root when
|
||||
* they share a system prompt and all of them are unreachable together, which is why the value
|
||||
* is a list. */
|
||||
std::unordered_map<BlockHash, std::vector<uint64_t>, BlockHashHash> roots_;
|
||||
std::string model_;
|
||||
std::function<void(const BlockHash&)> on_drop_;
|
||||
std::function<void(const BlockHash&)> on_ck_drop_;
|
||||
Stats stats_;
|
||||
std::string report_;
|
||||
};
|
||||
|
||||
+1
-1
@@ -199,7 +199,7 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
const int64_t w = cfg.vram_weights_mib * MiB;
|
||||
const int64_t kv = cfg.vram_kv_mib * MiB;
|
||||
const int64_t hp = (cfg.host_pool_mib + cfg.embedding_host_mib) * MiB;
|
||||
const int64_t hp = cfg.host_pool_total_mib() * MiB;
|
||||
|
||||
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM.
|
||||
* core/mem/vram_budget.cpp derived them from the card, the measured driver residency and the
|
||||
|
||||
+106
-182
@@ -13,9 +13,7 @@ namespace rad {
|
||||
* shared and long-lived is usually keyed by SHA-256, because a cheap hash's collision would serve
|
||||
* one caller another caller's context. We get the same guarantee more cheaply: every entry keeps
|
||||
* its BLOCK'S TOKEN IDS and compares them on a hit, so a collision is a miss rather than a wrong
|
||||
* answer, and the hash only has to be good enough to keep the bucket chains short. The SSD tier,
|
||||
* which is such a store, carries the token ids into the slot header for the same reason
|
||||
* (sstier.h).
|
||||
* answer, and the hash only has to be good enough to keep the bucket chains short.
|
||||
*
|
||||
* splitmix64's finaliser, which is a full 64-bit bijection -- so folding one token cannot lose the
|
||||
* bits of the previous one, which is the failure mode of a plain multiply-xor chain. */
|
||||
@@ -219,10 +217,11 @@ std::vector<BlockHash> PrefixCache::chain_all(const std::vector<int32_t>& tokens
|
||||
return hs;
|
||||
}
|
||||
|
||||
void PrefixCache::touch(const BlockHash& h) const {
|
||||
void PrefixCache::touch(const BlockHash& h, uint64_t now_ns) const {
|
||||
auto it = map_.find(h);
|
||||
if (it == map_.end() || !it->second.in_lru) return;
|
||||
lru_.splice(lru_.end(), lru_, it->second.lru);
|
||||
it->second.used_ns = now_ns;
|
||||
}
|
||||
|
||||
CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
@@ -274,7 +273,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
auto best = ck_by_prefix_.end();
|
||||
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
|
||||
const Ckpt& c = it->second;
|
||||
if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > limit ||
|
||||
if (!c.valid || c.slot < 0 || c.pos <= 0 || c.pos > limit ||
|
||||
c.pos % block_size_ != 0)
|
||||
continue;
|
||||
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
|
||||
@@ -302,8 +301,9 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
}
|
||||
}
|
||||
|
||||
const uint64_t now = rad_mono_ns();
|
||||
for (int64_t b = 0; b < matched; ++b) {
|
||||
touch(hs[(size_t)b]);
|
||||
touch(hs[(size_t)b], now);
|
||||
if (!blocks_out) continue;
|
||||
const Entry& e = map_.find(hs[(size_t)b])->second;
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
@@ -313,7 +313,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
* entry leaves the device, and without this it runs from when the chain was published, so a
|
||||
* prefix hit on every turn -- or one just promoted back for this very lookup -- would read as
|
||||
* idle and be demoted from under the request using it. */
|
||||
if (tiers_ && matched > 0) tiers_->note_hits(hs.data(), matched, rad_mono_ns());
|
||||
if (tiers_ && matched > 0) tiers_->note_hits(hs.data(), matched, now);
|
||||
hit.n_attn_tokens = (int32_t)(matched * block_size_);
|
||||
stats_.block_hits += matched;
|
||||
stats_.block_misses += n_full - matched;
|
||||
@@ -336,6 +336,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
hit.n_linear_tokens = (int32_t)best->second.pos;
|
||||
hit.checkpoint_slot = best->second.slot;
|
||||
best->second.used = ++clock_;
|
||||
best->second.used_ns = now;
|
||||
handed_.push_back(best->first);
|
||||
++stats_.ckpt_hits;
|
||||
return hit;
|
||||
@@ -359,7 +360,7 @@ int PrefixCache::insert(uint64_t session,
|
||||
for (int64_t b = 0; b < n_full; ++b) {
|
||||
const BlockHash& h = hs[(size_t)b];
|
||||
auto it = map_.find(h);
|
||||
if (it != map_.end() && it->second.in_lru) { touch(h); continue; }
|
||||
if (it != map_.end() && it->second.in_lru) { touch(h, now); continue; }
|
||||
if (it != map_.end()) {
|
||||
/* AN ENTRY WHOSE ONLY COPY IS OFF THE CARD, AND THIS REQUEST JUST COMPUTED IT AGAIN --
|
||||
* a restore that did not fit, or a chain cut short. The request's blocks become the
|
||||
@@ -379,6 +380,7 @@ int PrefixCache::insert(uint64_t session,
|
||||
}
|
||||
Entry& e = it->second;
|
||||
e.blocks = std::move(mine);
|
||||
e.used_ns = now;
|
||||
lru_.push_back(h);
|
||||
e.lru = std::prev(lru_.end());
|
||||
e.in_lru = true;
|
||||
@@ -403,6 +405,7 @@ int PrefixCache::insert(uint64_t session,
|
||||
}
|
||||
e.tokens.assign(tokens.begin() + b * block_size_,
|
||||
tokens.begin() + (b + 1) * block_size_);
|
||||
e.used_ns = now;
|
||||
lru_.push_back(h);
|
||||
e.lru = std::prev(lru_.end());
|
||||
e.in_lru = true;
|
||||
@@ -460,15 +463,13 @@ int PrefixCache::insert(uint64_t session,
|
||||
/* ------------------------------------------------------------------ idle session tiers */
|
||||
|
||||
std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<BlockHash>* chain) const {
|
||||
const std::vector<MMContentKey>& mm) const {
|
||||
std::vector<BlockHash> out;
|
||||
if (chain) chain->clear();
|
||||
if (!enabled_ || !tiers_ || tokens.empty()) return out;
|
||||
|
||||
/* THE BLOCKS A HIT CAN USE: one token must remain to compute a logit from, so a prompt that
|
||||
* ends on a block boundary never reuses its last block (lookup backs off by one) and neither
|
||||
* restoring it nor bringing back a snapshot keyed there would be read. */
|
||||
* restoring it would be read. */
|
||||
const int64_t n_full = ((int64_t)tokens.size() - 1) / block_size_;
|
||||
std::vector<BlockHash> hs = chain_all(tokens, mm, n_full);
|
||||
|
||||
@@ -495,7 +496,6 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
|
||||
if ((int64_t)it->second.tokens.size() != block_size_ ||
|
||||
std::memcmp(it->second.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) != 0)
|
||||
break;
|
||||
if (chain) chain->push_back(hs[(size_t)b]);
|
||||
if (tiers_->resident_off_device(hs[(size_t)b])) out.push_back(hs[(size_t)b]);
|
||||
}
|
||||
return out;
|
||||
@@ -510,13 +510,9 @@ void PrefixCache::drop_offdevice(const BlockHash& key) {
|
||||
if (it->second.in_lru) lru_.erase(it->second.lru);
|
||||
map_.erase(it);
|
||||
++stats_.evictions;
|
||||
/* AND THE SNAPSHOT KEYED BY THE SAME HASH, when the disk was all it had: its record is gone,
|
||||
* and an index entry left behind would be a detached snapshot nobody can read back. One still
|
||||
* in its store slot stays -- no lookup reaches it past the missing block, the slot may be
|
||||
* under a disk write this sink cannot ask about, and the retention policy retires it through
|
||||
* the path that does ask (retire_ckpt). */
|
||||
auto ck = ck_by_prefix_.find(key);
|
||||
if (ck != ck_by_prefix_.end() && ck->second.detached) drop_snapshot(key);
|
||||
/* A SNAPSHOT KEYED BY THE SAME HASH STAYS. No lookup reaches it past the missing block, and
|
||||
* the retention policy or the expiry retires it through the path that tells the tiers
|
||||
* (retire_ckpt) -- this one is called by the tiers, holding their lock. */
|
||||
}
|
||||
|
||||
int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks) {
|
||||
@@ -533,6 +529,8 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks
|
||||
e.blocks = blocks;
|
||||
for (size_t g = 0; g < groups_.size(); ++g) kv_->cache_reserved_block(groups_[g], blocks[g]);
|
||||
if (!e.in_lru) {
|
||||
/* A restore is a use: a request is about to hit it. */
|
||||
e.used_ns = rad_mono_ns();
|
||||
lru_.push_back(key);
|
||||
e.lru = std::prev(lru_.end());
|
||||
e.in_lru = true;
|
||||
@@ -552,7 +550,9 @@ int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
* goes to the back rather than being evicted: releasing the cache's reference on it frees no
|
||||
* block, and an entry that had no host copy would be erased for nothing. It is in use, which is
|
||||
* what the back of the list means, and moving it is what keeps a caller that asks again from
|
||||
* walking the same shared run every time. */
|
||||
* walking the same shared run every time. It is stamped as used, which keeps the list in the
|
||||
* clock's order. */
|
||||
const uint64_t now = rad_mono_ns();
|
||||
for (int64_t seen = (int64_t)lru_.size(); done < n && seen > 0 && !lru_.empty(); --seen) {
|
||||
const BlockHash h = lru_.front();
|
||||
auto it = map_.find(h);
|
||||
@@ -560,6 +560,7 @@ int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
Entry& e = it->second;
|
||||
if (shared_with_live(e)) {
|
||||
lru_.splice(lru_.end(), lru_, lru_.begin());
|
||||
e.used_ns = now;
|
||||
continue;
|
||||
}
|
||||
lru_.pop_front();
|
||||
@@ -587,6 +588,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) {
|
||||
/* TIERS ATTACHED AND OFF are no tiers: nothing becomes droppable, and waiting for a copy that
|
||||
* nobody will make would leave the reserve unkept for good. */
|
||||
const bool keep = tiers_ && tiers_->any_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;
|
||||
@@ -599,6 +601,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) {
|
||||
/* In use: to the back, as evict_lru does, and the walk carries on from the next. */
|
||||
auto next = std::next(it);
|
||||
lru_.splice(lru_.end(), lru_, it);
|
||||
e.used_ns = now;
|
||||
it = next;
|
||||
continue;
|
||||
}
|
||||
@@ -670,7 +673,7 @@ int64_t PrefixCache::drop_clean() {
|
||||
* the answer by the group count.
|
||||
*
|
||||
* OFF-DEVICE ENTRIES COUNT FOR NOTHING. A demoted entry released its blocks, and the mark went
|
||||
* with the release; its bytes are on the host or on disk and it is holding none of the card. */
|
||||
* with the release; its bytes are in host memory and it is holding none of the card. */
|
||||
int64_t PrefixCache::unshared_tokens() const {
|
||||
if (!kv_ || groups_.empty() || block_size_ <= 0) return 0;
|
||||
return kv_->cache_only_blocks(groups_[0]) * block_size_;
|
||||
@@ -717,19 +720,11 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
auto it = ck_by_session_.find(session);
|
||||
if (it == ck_by_session_.end()) return 0;
|
||||
|
||||
/* SNAPSHOTS IN THE STORE ONLY. This policy exists to spend a fixed number of --checkpoint-
|
||||
* slots well, and it runs when the store is exhausted. A detached snapshot occupies none of
|
||||
* it, so retiring one would free nothing here and would cost a session the state it was
|
||||
* written to disk precisely in order to keep. The disk store bounds its own, oldest first,
|
||||
* which is the right policy for the resource it actually spends.
|
||||
*
|
||||
* It stays in `kept` rather than being skipped, or the session index would forget it. */
|
||||
std::vector<std::pair<int64_t, BlockHash>> all;
|
||||
std::vector<BlockHash> kept;
|
||||
for (const BlockHash& h : it->second) {
|
||||
auto e = ck_by_prefix_.find(h);
|
||||
if (e == ck_by_prefix_.end()) continue;
|
||||
if (e->second.detached) { kept.push_back(h); continue; }
|
||||
all.push_back({e->second.pos, h});
|
||||
}
|
||||
std::sort(all.begin(), all.end(),
|
||||
@@ -748,15 +743,6 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
if (handed(a.second)) { kept.push_back(a.second); continue; }
|
||||
auto e = ck_by_prefix_.find(a.second);
|
||||
if (e == ck_by_prefix_.end()) continue;
|
||||
/* A SNAPSHOT THE DISK HOLDS LEAVES THE SLOT AND STAYS IN THE INDEX: the policy is about
|
||||
* the slots, and that copy costs none of them. */
|
||||
if (tiers_ && tiers_->snapshot_backed(a.second)) {
|
||||
(void)detach_snapshot(a.second);
|
||||
tiers_->snapshot_detached(a.second);
|
||||
kept.push_back(a.second);
|
||||
++freed;
|
||||
continue;
|
||||
}
|
||||
retire_ckpt(e);
|
||||
++freed;
|
||||
++stats_.ckpt_evictions;
|
||||
@@ -786,30 +772,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
}
|
||||
auto existing = ck_by_prefix_.find(prefix);
|
||||
if (existing != ck_by_prefix_.end()) {
|
||||
/* A DETACHED SNAPSHOT IS NOT ONE THIS CALL CAN HAND BACK. Returning its -1 slot would
|
||||
* look to the scheduler exactly like a refusal (it tests `cs >= 0`) and the chunk would
|
||||
* silently stop checkpointing; handing back a slot that is not in the store would be
|
||||
* worse. The state is about to be recomputed anyway -- that is what a reservation at this
|
||||
* prefix means -- so the disk copy is retired and a fresh slot allocated below. */
|
||||
/* NOR ONE A DISK WRITE IS READING. The save that follows this reservation writes the slot
|
||||
* while the write reads it, and the disk would keep a snapshot that is half of each. A
|
||||
* fresh slot costs one allocation. */
|
||||
if (!existing->second.detached &&
|
||||
!(tiers_ && tiers_->slot_reading(existing->second.slot))) {
|
||||
*slot_out = existing->second.slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
/* ONE HANDED OUT THIS STEP IS NOT RETIRED either: an admission restores from it ahead of
|
||||
* the step. This chunk goes without a checkpoint, which costs a later hit some replay. */
|
||||
if (handed(prefix)) return RAD_E_FULL;
|
||||
const uint64_t vs = existing->second.session;
|
||||
retire_ckpt(existing);
|
||||
auto sit = ck_by_session_.find(vs);
|
||||
if (sit != ck_by_session_.end()) {
|
||||
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), prefix),
|
||||
sit->second.end());
|
||||
if (sit->second.empty()) ck_by_session_.erase(sit);
|
||||
}
|
||||
existing->second.used_ns = rad_mono_ns();
|
||||
*slot_out = existing->second.slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int32_t slot = -1;
|
||||
@@ -843,14 +808,7 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
const Ckpt* victim = nullptr;
|
||||
const Ckpt* tip_victim = nullptr;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
/* A DETACHED SNAPSHOT IS NOT A CANDIDATE, because evicting it frees nothing HERE.
|
||||
* Its slot went back to the store when it was detached, so picking it as the
|
||||
* victim would retire a usable snapshot and then fail the retry anyway. */
|
||||
if (kvp.second.detached) continue;
|
||||
/* NOR ONE A DISK WRITE IS READING: its slot comes back only when the write
|
||||
* reports, so retiring it now loses the snapshot and frees nothing yet. */
|
||||
if (tiers_ && tiers_->slot_reading(kvp.second.slot)) continue;
|
||||
/* NOR ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot
|
||||
/* NOT ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot
|
||||
* ahead of the step, and a slot freed under it restores nothing. */
|
||||
if (handed(kvp.first)) continue;
|
||||
auto sit = ck_by_session_.find(kvp.second.session);
|
||||
@@ -868,54 +826,34 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
}
|
||||
if (!victim) victim = tip_victim;
|
||||
if (!victim) return RAD_E_FULL;
|
||||
BlockHash vh = victim->prefix;
|
||||
uint64_t vs = victim->session;
|
||||
/* A VICTIM THE DISK HOLDS IS DETACHED, NOT LOST. The slot goes back all the same; the
|
||||
* index entry stays, and the session's next restore reads the state back instead of
|
||||
* replaying every recurrent layer from an older point. */
|
||||
if (tiers_ && tiers_->snapshot_backed(vh)) {
|
||||
(void)detach_snapshot(vh);
|
||||
tiers_->snapshot_detached(vh);
|
||||
if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL;
|
||||
Ckpt c;
|
||||
c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot;
|
||||
c.used = ++clock_;
|
||||
ck_by_prefix_.emplace(prefix, c);
|
||||
ck_by_session_[session].push_back(prefix);
|
||||
*slot_out = slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
const BlockHash vh = victim->prefix;
|
||||
const uint64_t vs = victim->session;
|
||||
retire_ckpt(ck_by_prefix_.find(vh));
|
||||
++stats_.ckpt_evictions;
|
||||
auto sit = ck_by_session_.find(vs);
|
||||
if (sit != ck_by_session_.end()) {
|
||||
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), vh),
|
||||
sit->second.end());
|
||||
if (sit->second.empty()) ck_by_session_.erase(sit);
|
||||
}
|
||||
unindex_ckpt(vs, vh);
|
||||
if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL;
|
||||
}
|
||||
}
|
||||
|
||||
Ckpt c;
|
||||
c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot; c.used = ++clock_;
|
||||
c.used_ns = rad_mono_ns();
|
||||
ck_by_prefix_.emplace(prefix, c);
|
||||
ck_by_session_[session].push_back(prefix);
|
||||
*slot_out = slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void PrefixCache::commit_checkpoint(const BlockHash& prefix, bool resume) {
|
||||
void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
|
||||
auto it = ck_by_prefix_.find(prefix);
|
||||
if (it == ck_by_prefix_.end()) return;
|
||||
/* One that lost its slot between the reservation and now holds nothing to serve. */
|
||||
if (it->second.detached || it->second.slot < 0) return;
|
||||
if (it->second.slot < 0) return;
|
||||
it->second.valid = true;
|
||||
/* THE TIERS LEARN THE SNAPSHOT HERE, for the same reason note_used tells them the block ids:
|
||||
* a demotion has to know what to move and this index is the only place it is written down.
|
||||
* Before the commit there is nothing to move -- the slot still holds the previous tenant's
|
||||
* state -- so this is also the earliest moment at which telling them would be true. */
|
||||
if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos, resume);
|
||||
/* THE TIERS LEARN THE SNAPSHOT HERE, for the session view: before the commit the slot still
|
||||
* holds the previous tenant's state, so this is the earliest moment at which telling them
|
||||
* would be true. */
|
||||
if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos);
|
||||
}
|
||||
|
||||
|
||||
@@ -923,73 +861,19 @@ void PrefixCache::commit_checkpoint(const BlockHash& prefix, bool resume) {
|
||||
|
||||
void PrefixCache::retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it) {
|
||||
if (it == ck_by_prefix_.end()) return;
|
||||
/* THE TIERS ARE ASKED FIRST, because a disk write may be reading the slot: a save into it
|
||||
* before the write is done would put half of another snapshot on disk under this key. When
|
||||
* one is, the tiers keep the slot and hand it back once the write has reported. */
|
||||
const bool held = tiers_ && tiers_->release_snapshot(it->first, it->second.slot);
|
||||
if (it->second.slot >= 0 && !held) kv_->free_checkpoint(it->second.slot);
|
||||
/* TOLD EITHER WAY, AND NOT ONLY WHEN THE DISK HOLDS THE BYTES. The tiers also remember a
|
||||
* snapshot's slot -- note_snapshot records it at commit, because a disk write has to know
|
||||
* what to read and this index is the only place it is written down. Freeing that slot here
|
||||
* without saying so leaves the tiers naming a slot the store has since given to another
|
||||
* session, and the next write puts THAT session's recurrent state on disk as this one's. The
|
||||
* text that comes back is fluent, deterministic and about the wrong conversation, which is
|
||||
* the exact failure the whole tier design is arranged to make impossible.
|
||||
*
|
||||
* Not reachable from the tiers' own drop sink, which erases the index entry through
|
||||
* drop_snapshot instead -- so this never calls back into a record being erased. */
|
||||
/* THE TIERS ARE TOLD, because they name the slot too: note_snapshot records it for the session
|
||||
* view, and a view that kept it would count a slot the store has since given to another
|
||||
* session as this one's resume point. */
|
||||
if (tiers_) tiers_->release_snapshot(it->first);
|
||||
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
|
||||
ck_by_prefix_.erase(it);
|
||||
}
|
||||
|
||||
int PrefixCache::detach_snapshot(const BlockHash& key) {
|
||||
auto it = ck_by_prefix_.find(key);
|
||||
if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND;
|
||||
if (it->second.detached) return RAD_OK; /* already only on disk */
|
||||
/* Only ever asked of a snapshot the tiers call backed, which no write is reading. */
|
||||
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
|
||||
it->second.slot = -1;
|
||||
it->second.detached = true;
|
||||
/* NOT SERVABLE FROM HERE ON, which is the same state a reserved-but-unwritten snapshot is in
|
||||
* and is handled by the same branch in lookup(). A hit that reaches this position simply walks
|
||||
* back to an older checkpoint, or to none -- shorter, never wrong. */
|
||||
it->second.valid = false;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int PrefixCache::reattach_snapshot(const BlockHash& key, int32_t slot) {
|
||||
auto it = ck_by_prefix_.find(key);
|
||||
if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND;
|
||||
if (slot < 0) return RAD_E_INVAL;
|
||||
/* AN ENTRY ALREADY IN A SLOT keeps it: taking the new one would leak the old. The caller gives
|
||||
* the new slot back. */
|
||||
if (!it->second.detached && it->second.slot >= 0) return it->second.slot == slot ? RAD_OK
|
||||
: RAD_E_STATE;
|
||||
/* A SLOT THIS ENTRY DID NOT ASK FOR IS STILL ITS OWN. The read allocated it and filled it
|
||||
* from the disk copy of THIS key's state, so the identity that matters -- which prefix the
|
||||
* bytes describe -- is carried by the key and not by the slot number it happened to get. */
|
||||
it->second.slot = slot;
|
||||
it->second.detached = false;
|
||||
it->second.valid = true;
|
||||
it->second.used = ++clock_;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool PrefixCache::free_checkpoint_for_restore() {
|
||||
if (!tiers_) return false;
|
||||
const Ckpt* victim = nullptr;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
const Ckpt& c = kvp.second;
|
||||
if (c.detached || c.slot < 0 || !c.valid) continue;
|
||||
if (victim && c.used >= victim->used) continue;
|
||||
if (handed(kvp.first)) continue;
|
||||
if (!tiers_->snapshot_backed(kvp.first)) continue;
|
||||
victim = &c;
|
||||
}
|
||||
if (!victim) return false;
|
||||
const BlockHash vh = victim->prefix;
|
||||
(void)detach_snapshot(vh);
|
||||
tiers_->snapshot_detached(vh);
|
||||
return true;
|
||||
void PrefixCache::unindex_ckpt(uint64_t session, const BlockHash& key) {
|
||||
auto sit = ck_by_session_.find(session);
|
||||
if (sit == ck_by_session_.end()) return;
|
||||
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), key), sit->second.end());
|
||||
if (sit->second.empty()) ck_by_session_.erase(sit);
|
||||
}
|
||||
|
||||
void PrefixCache::hold(uint64_t req, const std::vector<int32_t>& tokens,
|
||||
@@ -1030,25 +914,65 @@ void PrefixCache::release(uint64_t req) {
|
||||
released_ = true;
|
||||
}
|
||||
|
||||
void PrefixCache::drop_snapshot(const BlockHash& key) {
|
||||
auto it = ck_by_prefix_.find(key);
|
||||
if (it == ck_by_prefix_.end()) return;
|
||||
const uint64_t session = it->second.session;
|
||||
/* No release_snapshot on this path: the tiers are the caller, holding their lock, and the
|
||||
* bytes are already gone. They say this only of a detached snapshot, so there is normally no
|
||||
* slot to give back. */
|
||||
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
|
||||
ck_by_prefix_.erase(it);
|
||||
++stats_.ckpt_evictions;
|
||||
auto sit = ck_by_session_.find(session);
|
||||
if (sit == ck_by_session_.end()) return;
|
||||
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), key), sit->second.end());
|
||||
if (sit->second.empty()) ck_by_session_.erase(sit);
|
||||
}
|
||||
/* ------------------------------------------------------------------ expiry */
|
||||
|
||||
int64_t PrefixCache::snapshots_detached() const {
|
||||
int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
|
||||
if (!enabled_ || ttl_ns == 0 || now_ns <= ttl_ns) return 0;
|
||||
const uint64_t cutoff = now_ns - ttl_ns;
|
||||
int64_t n = 0;
|
||||
for (const auto& kvp : ck_by_prefix_) if (kvp.second.detached) ++n;
|
||||
|
||||
/* ---- in VRAM: the LRU list is in the clock's order, so the walk stops at the first entry it
|
||||
* keeps. A block a running sequence also holds stays allocated -- releasing the cache's
|
||||
* reference is not freeing the block -- and that sequence publishes it again when it ends. */
|
||||
while (!lru_.empty()) {
|
||||
const BlockHash h = lru_.front();
|
||||
auto it = map_.find(h);
|
||||
if (it == map_.end()) { lru_.pop_front(); continue; }
|
||||
Entry& e = it->second;
|
||||
if (e.used_ns >= cutoff) break;
|
||||
lru_.pop_front();
|
||||
e.in_lru = false;
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
kv_->release_block(groups_[g], e.blocks[g]);
|
||||
/* The host copy goes with it: an expired entry is not demoted. */
|
||||
if (tiers_) tiers_->forget(h);
|
||||
map_.erase(it);
|
||||
++n;
|
||||
}
|
||||
|
||||
/* ---- only in host memory: the tiers keep these in the clock's order too. */
|
||||
if (tiers_) {
|
||||
std::vector<BlockHash> keys;
|
||||
tiers_->expired(cutoff, (size_t)-1, &keys);
|
||||
for (const BlockHash& h : keys) {
|
||||
tiers_->forget(h);
|
||||
auto it = map_.find(h);
|
||||
if (it == map_.end() || it->second.in_lru) continue;
|
||||
map_.erase(it);
|
||||
++n;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- snapshots, used when their prefix entry is or when a lookup hands them out. Not one
|
||||
* that is still being written (a reservation not yet committed) and not one handed out this
|
||||
* step: its admission restores from the slot ahead of the step. There are --checkpoint-slots
|
||||
* of them at most, so the whole index is walked. */
|
||||
std::vector<BlockHash> gone;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
const Ckpt& c = kvp.second;
|
||||
if (!c.valid || handed(kvp.first)) continue;
|
||||
auto e = map_.find(kvp.first);
|
||||
const uint64_t used = std::max(c.used_ns, e == map_.end() ? 0 : e->second.used_ns);
|
||||
if (used < cutoff) gone.push_back(kvp.first);
|
||||
}
|
||||
for (const BlockHash& h : gone) {
|
||||
auto it = ck_by_prefix_.find(h);
|
||||
const uint64_t session = it->second.session;
|
||||
retire_ckpt(it);
|
||||
unindex_ckpt(session, h);
|
||||
}
|
||||
stats_.expired += n;
|
||||
stats_.ckpt_expired += (int64_t)gone.size();
|
||||
return n;
|
||||
}
|
||||
} /* namespace rad */
|
||||
+34
-41
@@ -266,11 +266,8 @@ public:
|
||||
* It is a separate call rather than something lookup does because lookup is const and has no
|
||||
* device: a promotion allocates blocks and runs a scatter, which is the engine's to do
|
||||
* between steps and not something a cache query may trigger under the caller. */
|
||||
/* `chain`, when given, receives every key the walk matched, wherever it is -- what the tiers
|
||||
* need to see whether any of it is still being read off disk (IdleTiers::plan_fetch). */
|
||||
std::vector<BlockHash> restorable_from(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<BlockHash>* chain = nullptr) const;
|
||||
const std::vector<MMContentKey>& mm) const;
|
||||
|
||||
/* THE TIERS LOST THE BYTES. Erase the entry WITHOUT releasing blocks: an off-device entry
|
||||
* owns none -- demotion released them -- and its recorded ids belong to whoever the pool gave
|
||||
@@ -297,25 +294,10 @@ public:
|
||||
* and re-prefills its whole transcript.
|
||||
*
|
||||
* A snapshot never needs to follow its blocks: it is restored straight out of its slot into
|
||||
* the new sequence's state, wherever the blocks are. The only tier below the store is disk,
|
||||
* and a snapshot the disk holds can give its slot up and stay in the index (DETACHED) until a
|
||||
* read brings it back. */
|
||||
* the new sequence's state, wherever the blocks are. There is no tier below the store: a
|
||||
* snapshot the store retires is gone, and a session that needed it replays its recurrent
|
||||
* layers from an older one. */
|
||||
|
||||
/* Its bytes are only on disk now: give the slot back and stop offering it. The index entry
|
||||
* STAYS, because that is what a read off disk puts the snapshot back into, and an entry whose
|
||||
* state is not in the store is exactly the `valid` flag's existing meaning -- lookup already
|
||||
* walks past one and falls back to an older position. */
|
||||
int detach_snapshot(const BlockHash& key);
|
||||
/* And back again, into a slot the caller has already filled. */
|
||||
int reattach_snapshot(const BlockHash& key, int32_t slot);
|
||||
/* A STORE SLOT FOR A READ OFF DISK. The store is --checkpoint-slots deep for the whole server,
|
||||
* and it is full whenever as many sessions have run since; a session whose snapshot is only on
|
||||
* disk would then replay every recurrent layer from an older point, because its state has
|
||||
* nowhere to land. One slot is freed by detaching the least recently used snapshot the disk
|
||||
* also holds -- which the next restore of THAT session reads back -- and never one whose only
|
||||
* copy is the slot, and never one a lookup has handed out since the step began: that request's
|
||||
* restore reads the slot ahead of its step. True when a slot was freed. */
|
||||
bool free_checkpoint_for_restore();
|
||||
/* KEEP A WAITING REQUEST'S CHAIN ON THE CARD. An admission that restored a chain and was then
|
||||
* refused -- no free sequence, no room in the pool -- gives its hit back, and its entries are
|
||||
* clean: drop_clean would let them go at the next pass and the next attempt would restore the
|
||||
@@ -329,13 +311,22 @@ public:
|
||||
/* A step's admissions begin. The snapshots the last step's lookups handed out have been read
|
||||
* by its forward, which committed before this step was planned. Until then a handed snapshot
|
||||
* keeps its slot through every path that would give one up: retention, the eviction in
|
||||
* reserve_checkpoint, and free_checkpoint_for_restore. */
|
||||
* reserve_checkpoint, and the expiry. */
|
||||
void begin_step() { handed_.clear(); }
|
||||
/* The tiers lost it -- the disk store let it go, a failed read, or an entry they were told to
|
||||
* forget. Erase the index entry and give back the slot, if it still has one. */
|
||||
void drop_snapshot(const BlockHash& key);
|
||||
/* How many snapshots the index holds whose bytes are only on disk. */
|
||||
int64_t snapshots_detached() const;
|
||||
|
||||
/* ---------------- expiry ----------------
|
||||
*
|
||||
* TAKE OUT EVERYTHING NO REQUEST HAS USED FOR `ttl_ns`: entries in VRAM (their blocks go back
|
||||
* to the pool), entries only the host holds (their slots go back to the arena), and snapshots
|
||||
* (their store slots go back). An entry is used when a lookup hits it or a request publishes
|
||||
* it, and a snapshot when its prefix entry is or when a lookup hands it out. Nothing is moved
|
||||
* anywhere first: an expired conversation is one the operator has said is not coming back.
|
||||
*
|
||||
* A PREFIX IS NEVER OLDER THAN WHAT FOLLOWS IT. A hit or a publish stamps every block of the
|
||||
* chain up to where it ends with one clock, so a conversation expires from its tip inwards and
|
||||
* a shared system prompt outlives every conversation that still reads it. Returns how many
|
||||
* entries went. */
|
||||
int64_t expire(uint64_t now_ns, uint64_t ttl_ns);
|
||||
/* ---------------- linear checkpoints ---------------- */
|
||||
/* The next position strictly after `pos` at which the scheduler must split a chunk so that a
|
||||
* checkpoint lands on a boundary (spec §7.1, §7.3). */
|
||||
@@ -350,9 +341,8 @@ public:
|
||||
int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix,
|
||||
int32_t* slot_out);
|
||||
/* The state named by `prefix` is now IN its slot. Until this is called the reservation is only
|
||||
* a promise and lookup() will not offer it -- see Ckpt::valid. A `resume` point is copied off
|
||||
* the card at once (IdleTiers::note_snapshot). */
|
||||
void commit_checkpoint(const BlockHash& prefix, bool resume = false);
|
||||
* a promise and lookup() will not offer it -- see Ckpt::valid. */
|
||||
void commit_checkpoint(const BlockHash& prefix);
|
||||
/* Every checkpoint of a session, ascending. */
|
||||
std::vector<int64_t> checkpoints(uint64_t session) const;
|
||||
/* Apply the retention policy to one session now. Returns how many snapshots were released.
|
||||
@@ -373,6 +363,9 @@ public:
|
||||
* was lost, and a counter that mixed the two would read a working tier as a thrashing
|
||||
* cache. */
|
||||
int64_t drops = 0;
|
||||
/* Entries and snapshots --prefix-cache-ttl took, from whichever tier held them. Not
|
||||
* evictions either: nothing wanted the memory. */
|
||||
int64_t expired = 0, ckpt_expired = 0;
|
||||
};
|
||||
const Stats& stats() const { return stats_; }
|
||||
|
||||
@@ -386,6 +379,10 @@ private:
|
||||
* valid only while this is set. */
|
||||
bool in_lru = false;
|
||||
bool drop_wait = false; /* in drop_wait_: clean, but a sequence still reads it */
|
||||
/* LAST USE, on the monotonic clock: a hit or a publish. The LRU list is in this order --
|
||||
* every path that puts an entry at its back stamps it -- which is what lets the expiry
|
||||
* stop at the first entry it keeps. */
|
||||
uint64_t used_ns = 0;
|
||||
std::list<BlockHash>::iterator lru;
|
||||
};
|
||||
struct Ckpt {
|
||||
@@ -394,30 +391,26 @@ private:
|
||||
BlockHash prefix;
|
||||
int32_t slot = -1;
|
||||
uint64_t used = 0;
|
||||
uint64_t used_ns = 0; /* reserved, or handed out by a lookup */
|
||||
/* HAS THE STATE ACTUALLY BEEN WRITTEN INTO THE SLOT YET. reserve_checkpoint runs when the
|
||||
* scheduler PLANS the chunk; the copy happens after the step that computes the state. A
|
||||
* lookup between those two points would hand out a slot holding the previous tenant's
|
||||
* history, which is the exact failure this whole mechanism exists to prevent. */
|
||||
bool valid = false;
|
||||
/* ARE THE BYTES ONLY ON DISK. A detached snapshot gave its store slot up because the disk
|
||||
* holds it, and `slot` is -1 until a read brings it back. Kept as its own flag rather than
|
||||
* inferred from the slot so that the two reasons a snapshot cannot be served -- not written
|
||||
* yet, and not here -- stay distinguishable in a debugger and in a report. */
|
||||
bool detached = false;
|
||||
};
|
||||
|
||||
std::vector<BlockHash> chain_all(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
int64_t n_blocks) const;
|
||||
void touch(const BlockHash& h) const;
|
||||
void touch(const BlockHash& h, uint64_t now_ns) const;
|
||||
/* Does a live sequence hold any of this entry's blocks as well? Then releasing the cache's
|
||||
* reference frees nothing. */
|
||||
bool shared_with_live(const Entry& e) const;
|
||||
/* Retire one snapshot whatever tier holds its bytes: a slot goes back to the store, and a disk
|
||||
* copy goes back to the tiers. One place, because three call sites that each remembered to
|
||||
* check `detached` would be three places to forget. The session index is the caller's, since
|
||||
* every caller is already rebuilding or erasing it. */
|
||||
/* Retire one snapshot: its slot goes back to the store and the tiers stop naming it. The
|
||||
* session index is the caller's, since every caller is already rebuilding or erasing it. */
|
||||
void retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it);
|
||||
/* Take one key out of a session's index entry, and the entry when it empties. */
|
||||
void unindex_ckpt(uint64_t session, const BlockHash& key);
|
||||
|
||||
KVManager* kv_ = nullptr;
|
||||
IdleTiers* tiers_ = nullptr;
|
||||
|
||||
@@ -1,536 +0,0 @@
|
||||
/* sstier.cpp -- see sstier.h. IT HOLDS CONVERSATION CONTENT ON DISK, UNENCRYPTED. */
|
||||
#include "mem/sstier.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <thread>
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* The device layer's alignment, not a second opinion about it: every slot, every header region and
|
||||
* every staging buffer here is a multiple of it, which is what keeps every transfer on
|
||||
* DirectFile's aligned fast path and its bounce buffer unallocated. */
|
||||
static constexpr int64_t kAlign = DirectFile::alignment();
|
||||
|
||||
static void* alloc_aligned(int64_t bytes) {
|
||||
void* p = nullptr;
|
||||
if (posix_memalign(&p, (size_t)kAlign, (size_t)align_up(bytes, kAlign)) != 0) return nullptr;
|
||||
return p;
|
||||
}
|
||||
static constexpr uint32_t kMagicBlock = 0x4b4c4252u; /* "RBLK" */
|
||||
static constexpr uint32_t kMagicCkpt = 0x504b4352u; /* "RCKP" */
|
||||
|
||||
struct SSSlotHeader {
|
||||
uint32_t magic;
|
||||
uint32_t n_tokens;
|
||||
uint64_t fingerprint;
|
||||
uint64_t payload_bytes;
|
||||
uint64_t key_hi, key_lo;
|
||||
int64_t pos; /* checkpoint: the token position it restores to; 0 for a block */
|
||||
uint64_t reserved[3];
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ TokenBucket */
|
||||
|
||||
const char* ssd_consumer_name(SSDConsumer c) {
|
||||
switch (c) {
|
||||
case SSDConsumer::PrefixCache: return "prefix-cache";
|
||||
case SSDConsumer::WeightTier: return "weight-tier";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
|
||||
static int64_t now_ns() {
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
void TokenBucket::configure(int64_t bytes_per_sec, int64_t burst_bytes) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
rate_ = bytes_per_sec > 0 ? bytes_per_sec : 0;
|
||||
burst_ = burst_bytes > 0 ? burst_bytes : rate_;
|
||||
tokens_ = (double)burst_;
|
||||
last_ns_ = now_ns();
|
||||
}
|
||||
|
||||
void TokenBucket::refill_locked() {
|
||||
int64_t t = now_ns();
|
||||
double dt = (double)(t - last_ns_) * 1e-9;
|
||||
last_ns_ = t;
|
||||
tokens_ = std::min((double)burst_, tokens_ + dt * (double)rate_);
|
||||
}
|
||||
|
||||
bool TokenBucket::try_take(int64_t bytes, SSDConsumer who) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
Use& u = use_[(int)who];
|
||||
if (rate_ <= 0) { u.bytes += bytes; ++u.grants; return true; }
|
||||
refill_locked();
|
||||
if (tokens_ < (double)bytes) return false;
|
||||
tokens_ -= (double)bytes;
|
||||
u.bytes += bytes;
|
||||
++u.grants;
|
||||
return true;
|
||||
}
|
||||
|
||||
void TokenBucket::take(int64_t bytes, SSDConsumer who) {
|
||||
int64_t t0 = now_ns();
|
||||
bool waited = false;
|
||||
for (;;) {
|
||||
if (try_take(bytes, who)) break;
|
||||
waited = true;
|
||||
/* Sleep for the deficit rather than spinning. Coarse on purpose: this is a placeholder
|
||||
* and a precise scheduler for a policy nobody has measured would be effort spent on the
|
||||
* wrong thing (spec §19.5). */
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(200));
|
||||
}
|
||||
if (waited) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
++use_[(int)who].waits;
|
||||
use_[(int)who].wait_us += (now_ns() - t0) / 1000;
|
||||
}
|
||||
}
|
||||
|
||||
TokenBucket::Use TokenBucket::use(SSDConsumer c) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return use_[(int)c];
|
||||
}
|
||||
|
||||
std::string TokenBucket::report() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
std::string s = rate_ > 0
|
||||
? fmt("SSD token bucket: %s/s, burst %s (PLACEHOLDER, spec §19.5)\n",
|
||||
humanb(rate_).c_str(), humanb(burst_).c_str())
|
||||
: std::string("SSD token bucket: off (no measured rate to enforce, spec §19.5)\n");
|
||||
for (int i = 0; i < (int)SSDConsumer::N; ++i)
|
||||
s += fmt(" %-14s %10s in %lld ops, %lld waits totalling %lld ms\n",
|
||||
ssd_consumer_name((SSDConsumer)i), humanb(use_[i].bytes).c_str(),
|
||||
(long long)use_[i].grants, (long long)use_[i].waits,
|
||||
(long long)(use_[i].wait_us / 1000));
|
||||
return s;
|
||||
}
|
||||
|
||||
TokenBucket& rad_ssd_bucket() { static TokenBucket b; return b; }
|
||||
|
||||
/* ------------------------------------------------------------------ SSDTier */
|
||||
|
||||
std::string SSDTier::disclosure(const std::string& dir) {
|
||||
return fmt("SSD prefix tier active at %s.\n"
|
||||
" It stores CONVERSATION CONTENT ON DISK, UNENCRYPTED: the cached KV blocks are a\n"
|
||||
" lossless function of the prompt, and the prompt's token ids are written beside\n"
|
||||
" them so a hit can be verified. Anything that persists across restarts says so\n"
|
||||
" (spec §7.3). Put this directory on storage you are willing to treat as holding\n"
|
||||
" the text itself.\n", dir.c_str());
|
||||
}
|
||||
|
||||
SSDTier::~SSDTier() { close(); }
|
||||
|
||||
static int64_t hdr_region_bytes(int64_t tok_bytes) {
|
||||
return align_up((int64_t)sizeof(SSSlotHeader) + tok_bytes, kAlign);
|
||||
}
|
||||
|
||||
int SSDTier::open_store(Store& s, const std::string& path, int64_t payload, int64_t n_slots,
|
||||
int64_t tok_bytes, bool allow_buffered) {
|
||||
s.payload = payload;
|
||||
s.hdr_bytes = hdr_region_bytes(tok_bytes);
|
||||
s.slot_bytes = s.hdr_bytes + align_up(payload, kAlign);
|
||||
if (n_slots <= 0) return RAD_OK;
|
||||
|
||||
int flags = RAD_DIO_READ | RAD_DIO_WRITE | RAD_DIO_CREATE;
|
||||
if (allow_buffered) flags |= RAD_DIO_ALLOW_BUFFERED;
|
||||
RAD_TRY(s.file.open(path.c_str(), flags));
|
||||
|
||||
/* Size the store up front. DirectFile does not take a size hint and does not need one -- a
|
||||
* write past the end extends the file -- but a store laid out in one ftruncate is one extent
|
||||
* rather than N, which is the difference between a slot read being one seek and being several
|
||||
* once the filesystem has interleaved somebody else's writes between ours. */
|
||||
if (::ftruncate(s.file.fd(), (off_t)(s.slot_bytes * n_slots)) != 0)
|
||||
RAD_WARN("ftruncate %s to %s: %s -- the store will be extended by its writes instead",
|
||||
path.c_str(), humanb(s.slot_bytes * n_slots).c_str(), strerror(errno));
|
||||
|
||||
s.slots.assign((size_t)n_slots, Slot{});
|
||||
s.freelist.resize((size_t)n_slots);
|
||||
for (int64_t i = 0; i < n_slots; ++i) s.freelist[(size_t)i] = (int32_t)(n_slots - 1 - i);
|
||||
s.stage = alloc_aligned(s.slot_bytes);
|
||||
if (!s.stage) return RAD_E_NOMEM;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int SSDTier::open(const SSDTierConfig& cfg) {
|
||||
close();
|
||||
cfg_ = cfg;
|
||||
if (cfg.dir.empty()) { enabled_ = false; return RAD_OK; }
|
||||
if (cfg.block_payload <= 0 && cfg.ckpt_payload <= 0) {
|
||||
RAD_ERR("--prefix-cache-dir is set but neither a block payload nor a checkpoint payload was "
|
||||
"given; there is nothing for the tier to store");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The engine says so at startup. Not behind a verbosity flag. */
|
||||
RAD_WARN("%s", disclosure(cfg.dir).c_str());
|
||||
|
||||
if (::mkdir(cfg.dir.c_str(), 0700) != 0 && errno != EEXIST) {
|
||||
RAD_ERR("cannot create %s: %s", cfg.dir.c_str(), strerror(errno));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
|
||||
RAD_TRY(open_store(blocks_, cfg.dir + "/blocks.bin", cfg.block_payload, cfg.n_block_slots,
|
||||
cfg.block_tokens * (int64_t)sizeof(uint32_t), cfg.allow_buffered));
|
||||
RAD_TRY(open_store(ckpts_, cfg.dir + "/ckpts.bin", cfg.ckpt_payload, cfg.n_ckpt_slots,
|
||||
0, cfg.allow_buffered));
|
||||
|
||||
enabled_ = true;
|
||||
|
||||
if (cfg.persistent) {
|
||||
/* Rebuild the index by scanning the slot headers rather than persisting a separate index
|
||||
* file. One sequential pass at startup, and no way for an index to disagree with the data
|
||||
* it names -- which is the failure a separate index file has and which produces exactly
|
||||
* the "serves one caller another caller's context" outcome this tier verifies against. */
|
||||
const int64_t nb = scan_store(blocks_, kMagicBlock);
|
||||
if (nb < 0) return (int)nb;
|
||||
const int64_t nc = scan_store(ckpts_, kMagicCkpt);
|
||||
if (nc < 0) return (int)nc;
|
||||
RAD_INFO("SSD tier: recovered %lld block and %lld checkpoint slots from %s",
|
||||
(long long)nb, (long long)nc, cfg.dir.c_str());
|
||||
} else {
|
||||
/* Not persistent means the store must not outlive the process, and unlinking now rather
|
||||
* than at exit means it also does not outlive a crash. The descriptors stay valid. */
|
||||
::unlink((cfg.dir + "/blocks.bin").c_str());
|
||||
::unlink((cfg.dir + "/ckpts.bin").c_str());
|
||||
}
|
||||
|
||||
report_ = fmt("SSD tier %s: %lld block slots x %s, %lld checkpoint slots x %s, %s%s\n",
|
||||
cfg.dir.c_str(),
|
||||
(long long)cfg.n_block_slots, humanb(blocks_.slot_bytes).c_str(),
|
||||
(long long)cfg.n_ckpt_slots, humanb(ckpts_.slot_bytes).c_str(),
|
||||
blocks_.file.direct() ? "O_DIRECT" : "BUFFERED",
|
||||
cfg.persistent ? ", persistent" : ", volatile");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void SSDTier::close() {
|
||||
for (Store* s : { &blocks_, &ckpts_ }) {
|
||||
s->file.close();
|
||||
if (s->stage) { ::free(s->stage); s->stage = nullptr; }
|
||||
s->slots.clear(); s->index.clear(); s->freelist.clear();
|
||||
}
|
||||
enabled_ = false;
|
||||
}
|
||||
|
||||
std::string SSDTier::report() const {
|
||||
std::string s = report_;
|
||||
s += fmt(" %lld hits, %lld misses, %lld verify misses, %lld evictions; "
|
||||
"%s read, %s written\n",
|
||||
(long long)stats_.hits, (long long)stats_.misses, (long long)stats_.verify_misses,
|
||||
(long long)stats_.evictions, humanb(stats_.bytes_read).c_str(),
|
||||
humanb(stats_.bytes_written).c_str());
|
||||
s += rad_ssd_bucket().report();
|
||||
return s;
|
||||
}
|
||||
|
||||
void SSDTier::lru_unlink(Store& s, int32_t i) {
|
||||
Slot& x = s.slots[(size_t)i];
|
||||
if (x.prev >= 0) s.slots[(size_t)x.prev].next = x.next; else s.lru_head = x.next;
|
||||
if (x.next >= 0) s.slots[(size_t)x.next].prev = x.prev; else s.lru_tail = x.prev;
|
||||
x.prev = x.next = -1;
|
||||
}
|
||||
|
||||
void SSDTier::lru_push(Store& s, int32_t i) {
|
||||
Slot& x = s.slots[(size_t)i];
|
||||
x.prev = s.lru_tail;
|
||||
x.next = -1;
|
||||
if (s.lru_tail >= 0) s.slots[(size_t)s.lru_tail].next = i; else s.lru_head = i;
|
||||
s.lru_tail = i;
|
||||
}
|
||||
|
||||
/* THE HEADERS ARE READ MANY AT A TIME. Each is one 4 KiB direct read at its own slot, so a single
|
||||
* reader waits one device round trip a slot -- some tens of microseconds, over the millions of
|
||||
* slots a store sized in hundreds of GiB holds, which is over a minute of every start. The device
|
||||
* serves dozens of such reads at once at little more latency than one, so the scan keeps
|
||||
* kScanDepth in flight: one thread each, over its own contiguous run of slots with its own staging
|
||||
* page. The threads only record each slot's verdict in the slot itself; the index, the order and
|
||||
* the free list are built afterwards in one descending pass, which is the order a single
|
||||
* sequential reader would produce. */
|
||||
static constexpr int64_t kScanDepth = 64;
|
||||
|
||||
int64_t SSDTier::scan_store(Store& s, uint32_t magic) {
|
||||
if (s.slots.empty()) return 0;
|
||||
s.index.clear();
|
||||
s.freelist.clear();
|
||||
s.lru_head = s.lru_tail = -1;
|
||||
for (Slot& x : s.slots) { x.used = 0; x.prev = x.next = -1; }
|
||||
|
||||
const int64_t n = (int64_t)s.slots.size();
|
||||
const int64_t nt = std::min(kScanDepth, n);
|
||||
std::atomic<bool> nomem{false};
|
||||
std::vector<std::thread> th;
|
||||
th.reserve((size_t)nt);
|
||||
for (int64_t t = 0; t < nt; ++t)
|
||||
th.emplace_back([&, t] {
|
||||
void* stage = alloc_aligned(s.hdr_bytes);
|
||||
if (!stage) { nomem.store(true); return; }
|
||||
for (int64_t i = n * t / nt; i < n * (t + 1) / nt; ++i) {
|
||||
if (s.file.read_at(stage, i * s.slot_bytes, s.hdr_bytes) < 0) continue;
|
||||
const SSSlotHeader* h = (const SSSlotHeader*)stage;
|
||||
if (h->magic != magic || h->fingerprint != cfg_.fingerprint
|
||||
|| h->payload_bytes != (uint64_t)s.payload) continue;
|
||||
Slot& x = s.slots[(size_t)i];
|
||||
x.key.hi = h->key_hi;
|
||||
x.key.lo = h->key_lo;
|
||||
x.pos = h->pos;
|
||||
x.used = 1;
|
||||
}
|
||||
std::free(stage);
|
||||
});
|
||||
for (std::thread& x : th) x.join();
|
||||
if (nomem.load()) {
|
||||
for (Slot& x : s.slots) x.used = 0;
|
||||
RAD_ERR("SSD tier: no staging page for the header scan");
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
int64_t live = 0;
|
||||
for (const Slot& x : s.slots) live += x.used;
|
||||
s.index.reserve((size_t)live);
|
||||
s.freelist.reserve((size_t)(n - live));
|
||||
for (int64_t i = n - 1; i >= 0; --i) {
|
||||
if (!s.slots[(size_t)i].used) { s.freelist.push_back((int32_t)i); continue; }
|
||||
lru_push(s, (int32_t)i);
|
||||
s.index[s.slots[(size_t)i].key] = (int32_t)i;
|
||||
}
|
||||
return live;
|
||||
}
|
||||
|
||||
int SSDTier::claim(Store& s, const BlockHash& key, int32_t* out) {
|
||||
auto it = s.index.find(key);
|
||||
if (it != s.index.end()) { *out = it->second; return RAD_OK; }
|
||||
if (!s.freelist.empty()) { *out = s.freelist.back(); s.freelist.pop_back(); return RAD_OK; }
|
||||
|
||||
/* LRU. Evicting the DEEPEST entry first would be better -- a deeper block chains more tokens,
|
||||
* is less shareable, and losing it only shortens the usable prefix, whereas losing a shallow
|
||||
* one strands everything above it -- but depth is not a property this tier is told. Straight
|
||||
* LRU until the caller carries depth in. */
|
||||
const int32_t victim = s.lru_head;
|
||||
if (victim < 0) return RAD_E_FULL;
|
||||
lru_unlink(s, victim);
|
||||
s.index.erase(s.slots[(size_t)victim].key);
|
||||
s.slots[(size_t)victim].used = 0;
|
||||
++stats_.evictions;
|
||||
*out = victim;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int SSDTier::put(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
|
||||
const int32_t* toks, int32_t n_toks, const void* payload, int64_t bytes) {
|
||||
if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED;
|
||||
if (bytes != s.payload) return RAD_E_SHAPE;
|
||||
if ((int64_t)sizeof(SSSlotHeader) + (int64_t)n_toks * 4 > s.hdr_bytes) return RAD_E_SHAPE;
|
||||
|
||||
int32_t slot = -1;
|
||||
RAD_TRY(claim(s, key, &slot));
|
||||
const int64_t base = (int64_t)slot * s.slot_bytes;
|
||||
|
||||
std::memset(s.stage, 0, (size_t)s.slot_bytes);
|
||||
SSSlotHeader* h = (SSSlotHeader*)s.stage;
|
||||
h->magic = magic;
|
||||
h->n_tokens = (uint32_t)n_toks;
|
||||
h->fingerprint = cfg_.fingerprint;
|
||||
h->payload_bytes = (uint64_t)bytes;
|
||||
h->key_hi = key.hi; h->key_lo = key.lo;
|
||||
h->pos = pos;
|
||||
if (n_toks > 0) std::memcpy((char*)s.stage + sizeof(SSSlotHeader), toks, (size_t)n_toks * 4);
|
||||
std::memcpy((char*)s.stage + s.hdr_bytes, payload, (size_t)bytes);
|
||||
|
||||
rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache);
|
||||
|
||||
/* Payload first, header last. Written front to back, a short write would leave the header
|
||||
* COMPLETE and the payload truncated, so the slot verifies and the engine loads whatever was
|
||||
* in the file underneath it -- which is the worst failure this tier can have.
|
||||
*
|
||||
* A WRITE THAT FAILS GIVES THE SLOT BACK. claim() took it off the free list or out of the
|
||||
* index, so returning here without that leaves a slot no list names and the store one slot
|
||||
* smaller for good. Whatever the slot held before is no longer trustworthy either -- the
|
||||
* payload may be half overwritten under a header that still verifies -- so the key comes out
|
||||
* of the index and the header is cleared on a best-effort basis, which keeps a persistent
|
||||
* store from indexing it again at the next start. */
|
||||
int wst = s.file.write_at((char*)s.stage + s.hdr_bytes, base + s.hdr_bytes,
|
||||
s.slot_bytes - s.hdr_bytes);
|
||||
if (wst >= 0) wst = s.file.write_at(s.stage, base, s.hdr_bytes);
|
||||
if (wst < 0) {
|
||||
auto it = s.index.find(key);
|
||||
if (it != s.index.end() && it->second == slot) s.index.erase(it);
|
||||
if (s.slots[(size_t)slot].used) lru_unlink(s, slot);
|
||||
s.slots[(size_t)slot].used = 0;
|
||||
s.freelist.push_back(slot);
|
||||
std::memset(s.stage, 0, (size_t)s.hdr_bytes);
|
||||
(void)s.file.write_at(s.stage, base, s.hdr_bytes);
|
||||
return wst;
|
||||
}
|
||||
|
||||
if (s.slots[(size_t)slot].used) lru_unlink(s, slot);
|
||||
s.slots[(size_t)slot].key = key;
|
||||
s.slots[(size_t)slot].used = 1;
|
||||
s.slots[(size_t)slot].pos = pos;
|
||||
lru_push(s, slot);
|
||||
s.index[key] = slot;
|
||||
++stats_.writes;
|
||||
stats_.bytes_written += s.slot_bytes;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int SSDTier::get(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
|
||||
const int32_t* toks, int32_t n_toks, void* payload, int64_t bytes) {
|
||||
if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED;
|
||||
if (bytes != s.payload) return RAD_E_SHAPE;
|
||||
auto it = s.index.find(key);
|
||||
if (it == s.index.end()) { ++stats_.misses; return RAD_E_NOTFOUND; }
|
||||
const int32_t slot = it->second;
|
||||
const int64_t base = (int64_t)slot * s.slot_bytes;
|
||||
|
||||
rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache);
|
||||
RAD_TRY(s.file.read_at(s.stage, base, s.slot_bytes));
|
||||
++stats_.reads;
|
||||
stats_.bytes_read += s.slot_bytes;
|
||||
|
||||
if (!header_ok(s, s.stage, magic, key, pos, toks, n_toks, bytes)) {
|
||||
/* Drop it rather than leaving it to fail every future probe: without this a single bad
|
||||
* slot poisons its prefix permanently. */
|
||||
forget_slot(s, slot);
|
||||
++stats_.verify_misses;
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
std::memcpy(payload, (const char*)s.stage + s.hdr_bytes, (size_t)bytes);
|
||||
lru_unlink(s, slot);
|
||||
lru_push(s, slot);
|
||||
++stats_.hits;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Belt and braces on top of the index: verify the header AND the token ids. A store that survives
|
||||
* a restart, a model change or a layout change would otherwise serve one caller another caller's
|
||||
* context, and that is not a failure anybody would ever diagnose. */
|
||||
bool SSDTier::header_ok(const Store& s, const void* stage, uint32_t magic, const BlockHash& key,
|
||||
int64_t pos, const int32_t* toks, int32_t n_toks, int64_t bytes) const {
|
||||
(void)s;
|
||||
const SSSlotHeader* h = (const SSSlotHeader*)stage;
|
||||
bool ok = h->magic == magic && h->fingerprint == cfg_.fingerprint
|
||||
&& h->key_hi == key.hi && h->key_lo == key.lo
|
||||
&& h->payload_bytes == (uint64_t)bytes && h->pos == pos
|
||||
&& h->n_tokens == (uint32_t)n_toks;
|
||||
if (ok && n_toks > 0)
|
||||
ok = std::memcmp((const char*)stage + sizeof(SSSlotHeader), toks, (size_t)n_toks * 4) == 0;
|
||||
return ok;
|
||||
}
|
||||
|
||||
void SSDTier::forget_slot(Store& s, int32_t slot) {
|
||||
auto it = s.index.find(s.slots[(size_t)slot].key);
|
||||
if (it != s.index.end() && it->second == slot) s.index.erase(it);
|
||||
if (s.slots[(size_t)slot].used) lru_unlink(s, slot);
|
||||
s.slots[(size_t)slot].used = 0;
|
||||
s.freelist.push_back(slot);
|
||||
}
|
||||
|
||||
/* READS OUTSTANDING AT ONCE. An NVMe drive reading tens-of-kilobyte extents at random reaches its
|
||||
* bandwidth only with many requests in flight; a thread each is the simplest way to have them, and
|
||||
* every thread has an aligned staging buffer of its own. */
|
||||
static constexpr int kReaders = 16;
|
||||
|
||||
int SSDTier::get_blocks(const BlockHash* keys, int64_t n, void* const* payloads, int64_t bytes,
|
||||
char* ok) {
|
||||
std::lock_guard<std::mutex> lk(io_mu_);
|
||||
Store& s = blocks_;
|
||||
for (int64_t i = 0; i < n; ++i) ok[i] = 0;
|
||||
if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED;
|
||||
if (bytes != s.payload) return RAD_E_SHAPE;
|
||||
|
||||
std::vector<int32_t> slot((size_t)n, -1);
|
||||
int64_t found = 0;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
auto it = s.index.find(keys[i]);
|
||||
if (it == s.index.end()) { ++stats_.misses; continue; }
|
||||
slot[(size_t)i] = it->second;
|
||||
++found;
|
||||
}
|
||||
if (found == 0) return RAD_OK;
|
||||
|
||||
/* The reads, and nothing that touches the index or the order: those are settled after, on this
|
||||
* thread. 1 read and verified, 2 read and not the key asked for, negative a failed read. */
|
||||
std::vector<int> st((size_t)n, 0);
|
||||
std::atomic<int64_t> next{0};
|
||||
auto reader = [&](void* stage) {
|
||||
for (int64_t i; (i = next.fetch_add(1, std::memory_order_relaxed)) < n;) {
|
||||
if (slot[(size_t)i] < 0) continue;
|
||||
rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache);
|
||||
const int r = s.file.read_at(stage, (int64_t)slot[(size_t)i] * s.slot_bytes,
|
||||
s.slot_bytes);
|
||||
if (r < 0) { st[(size_t)i] = r; continue; }
|
||||
if (!header_ok(s, stage, kMagicBlock, keys[i], 0, nullptr, 0, bytes)) {
|
||||
st[(size_t)i] = 2;
|
||||
continue;
|
||||
}
|
||||
std::memcpy(payloads[i], (const char*)stage + s.hdr_bytes, (size_t)bytes);
|
||||
st[(size_t)i] = 1;
|
||||
}
|
||||
};
|
||||
const int nt = (int)std::min<int64_t>(kReaders, found);
|
||||
std::vector<void*> stages;
|
||||
for (int t = 1; t < nt; ++t) {
|
||||
void* p = alloc_aligned(s.slot_bytes);
|
||||
if (!p) break;
|
||||
stages.push_back(p);
|
||||
}
|
||||
std::vector<std::thread> th;
|
||||
th.reserve(stages.size());
|
||||
for (void* p : stages) th.emplace_back(reader, p);
|
||||
reader(s.stage);
|
||||
for (std::thread& t : th) t.join();
|
||||
for (void* p : stages) ::free(p);
|
||||
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int32_t sl = slot[(size_t)i];
|
||||
if (sl < 0 || st[(size_t)i] < 0) continue;
|
||||
++stats_.reads;
|
||||
stats_.bytes_read += s.slot_bytes;
|
||||
if (st[(size_t)i] == 2) {
|
||||
forget_slot(s, sl);
|
||||
++stats_.verify_misses;
|
||||
continue;
|
||||
}
|
||||
lru_unlink(s, sl);
|
||||
lru_push(s, sl);
|
||||
++stats_.hits;
|
||||
ok[i] = 1;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ONE CALLER AT A TIME. Every call is the KV tiers' IO thread today, but a store is one staging
|
||||
* buffer, one slot table and one index, and nothing about the interface says who may call it. */
|
||||
int SSDTier::put_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
|
||||
const void* payload, int64_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(io_mu_);
|
||||
return put(blocks_, kMagicBlock, key, 0, toks, n_toks, payload, bytes);
|
||||
}
|
||||
int SSDTier::get_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
|
||||
void* payload, int64_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(io_mu_);
|
||||
return get(blocks_, kMagicBlock, key, 0, toks, n_toks, payload, bytes);
|
||||
}
|
||||
int SSDTier::put_checkpoint(const BlockHash& key, int64_t pos, const void* payload, int64_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(io_mu_);
|
||||
return put(ckpts_, kMagicCkpt, key, pos, nullptr, 0, payload, bytes);
|
||||
}
|
||||
int SSDTier::get_checkpoint(const BlockHash& key, int64_t pos, void* payload, int64_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(io_mu_);
|
||||
return get(ckpts_, kMagicCkpt, key, pos, nullptr, 0, payload, bytes);
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -1,181 +0,0 @@
|
||||
/* sstier.h -- the optional SSD tier for served attention state and linear checkpoints alike, so
|
||||
* an agent session does not re-prefill its whole transcript every turn (spec §7.3).
|
||||
*
|
||||
* ============================== IT HOLDS CONVERSATION CONTENT ON DISK, UNENCRYPTED ==============
|
||||
* A KV block IS the prompt: the token ids are stored beside it so a hit can be verified, and the
|
||||
* cached tensors are a lossless function of the text. Anything that persists it across restarts
|
||||
* says so, and this engine says so at startup whenever --prefix-cache-dir is set. There is no
|
||||
* encryption option, no obfuscation, and no claim of one; if the content is sensitive the
|
||||
* directory must be on storage the operator is willing to treat as sensitive.
|
||||
* ================================================================================================
|
||||
*
|
||||
* O_DIRECT, same as the weight tier. Going through the page cache would evict the weight tier's own
|
||||
* file mappings, which is paid for in decode and would never show up as a *cache* problem. O_DIRECT
|
||||
* wants offsets, lengths and buffers all on the logical block size, so every slot and every
|
||||
* sub-region here is a multiple of it and there is no unaligned tail to handle.
|
||||
*
|
||||
* Spec §19.5 records that prefix-cache and weight-tier contention on one SSD has NO PLAN. The
|
||||
* TokenBucket below is a placeholder for a measured policy, and it is labelled as one: it is a
|
||||
* shared byte budget between the two consumers, which at least makes the contention visible and
|
||||
* boundable instead of invisible. What the right split is, or whether a rate limit is even the
|
||||
* right shape of answer rather than a priority queue, is a measurement nobody has taken.
|
||||
*/
|
||||
#pragma once
|
||||
#include "device/directio.h"
|
||||
#include "mem/prefix.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* The O_DIRECT file is the device layer's rad::DirectFile (core/device/directio.h). Every extent
|
||||
* this tier reads or writes is a whole slot or a whole aligned header region, so every transfer
|
||||
* lands on its fast path and its bounce buffer is never allocated -- which is the property worth
|
||||
* stating, since the bounce exists for callers reading a header or a file tail and one on this
|
||||
* path would mean a slot geometry bug rather than a performance problem. */
|
||||
|
||||
/* ------------------------------------------------------------------ the shared rate limiter */
|
||||
enum class SSDConsumer { PrefixCache = 0, WeightTier = 1, N = 2 };
|
||||
const char* ssd_consumer_name(SSDConsumer c);
|
||||
|
||||
/* PLACEHOLDER FOR A MEASURED POLICY (spec §19.5).
|
||||
*
|
||||
* Both the prefix cache and the weight tier want O_DIRECT bandwidth and under load they fight. A
|
||||
* token bucket is the simplest thing that bounds the fight: one shared byte budget, refilled at a
|
||||
* stated rate, drawn on by both. What it does NOT do is decide who should win, and that is the
|
||||
* actual open question -- a weight-tier read blocks a layer that is about to execute, while a
|
||||
* prefix-cache read only makes a prefill shorter, so a priority scheme is probably the right shape
|
||||
* and a flat rate limit certainly is not. Replace this once there is a workload to measure
|
||||
* against; the per-consumer counters exist so that measurement has something to read. */
|
||||
class TokenBucket {
|
||||
public:
|
||||
/* 0 bytes_per_sec disables the limiter entirely, which is the default: an unmeasured rate
|
||||
* limit that throttles a machine nobody profiled is worse than none. */
|
||||
void configure(int64_t bytes_per_sec, int64_t burst_bytes);
|
||||
bool enabled() const { return rate_ > 0; }
|
||||
|
||||
bool try_take(int64_t bytes, SSDConsumer who); /* non-blocking */
|
||||
void take(int64_t bytes, SSDConsumer who); /* sleeps until the budget allows */
|
||||
|
||||
struct Use { int64_t bytes = 0; int64_t grants = 0; int64_t waits = 0; int64_t wait_us = 0; };
|
||||
Use use(SSDConsumer c) const;
|
||||
std::string report() const;
|
||||
|
||||
private:
|
||||
void refill_locked();
|
||||
|
||||
mutable std::mutex mu_;
|
||||
int64_t rate_ = 0; /* bytes per second */
|
||||
int64_t burst_ = 0;
|
||||
double tokens_ = 0;
|
||||
int64_t last_ns_ = 0;
|
||||
Use use_[(int)SSDConsumer::N];
|
||||
};
|
||||
|
||||
/* The one bucket both consumers share. The weight tier (core/place/) draws on the same object;
|
||||
* that is the entire point of it living here rather than inside either one. */
|
||||
TokenBucket& rad_ssd_bucket();
|
||||
|
||||
/* ------------------------------------------------------------------ the tier */
|
||||
struct SSDTierConfig {
|
||||
std::string dir; /* Config::prefix_cache_dir */
|
||||
int64_t block_payload = 0; /* bytes one cached attention block occupies, all groups */
|
||||
int64_t block_tokens = 0; /* the attention block size, for the verify */
|
||||
int64_t ckpt_payload = 0; /* KVManager::checkpoint_bytes() */
|
||||
/* Slot counts are STATED, not derived from statvfs. A tier that sizes itself from the free
|
||||
* space it happens to see at startup is a tier whose capacity changes when somebody untars
|
||||
* something, and §6's rule is that budgets do not move on their own. */
|
||||
int64_t n_block_slots = 0;
|
||||
int64_t n_ckpt_slots = 0;
|
||||
uint64_t fingerprint = 0; /* model + layout identity; a mismatch invalidates the store */
|
||||
bool persistent = false; /* keep the files across restarts */
|
||||
/* Passes RAD_DIO_ALLOW_BUFFERED. Off by default: the device layer REFUSES a filesystem
|
||||
* without O_DIRECT rather than downgrading it, because a silent buffered fallback costs the
|
||||
* weight tier its own page cache and shows up only as a decode regression nobody can
|
||||
* attribute. The flag is for tests, which run on whatever /tmp happens to be. */
|
||||
bool allow_buffered = false;
|
||||
};
|
||||
|
||||
class SSDTier {
|
||||
public:
|
||||
~SSDTier();
|
||||
int open(const SSDTierConfig& cfg);
|
||||
void close();
|
||||
bool enabled() const { return enabled_; }
|
||||
|
||||
/* The line the engine prints at startup when the flag is on. Not optional. */
|
||||
static std::string disclosure(const std::string& dir);
|
||||
std::string report() const;
|
||||
|
||||
/* Attention blocks. `toks` is the block's token ids: they are stored in the slot header and
|
||||
* memcmp'd on the way back in, so a hash collision is a miss and never a wrong answer. */
|
||||
int put_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
|
||||
const void* payload, int64_t bytes);
|
||||
int get_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
|
||||
void* payload, int64_t bytes);
|
||||
/* MANY BLOCKS AT ONCE, READ IN PARALLEL. A conversation coming back off disk is thousands of
|
||||
* entries of tens of kilobytes each, and read one at a time they keep the drive at a queue
|
||||
* depth of one -- a fraction of what it delivers with dozens of reads outstanding. `ok[i]` is
|
||||
* whether block i was found, read and verified into `payloads[i]`; one that was not is a miss
|
||||
* exactly as get_block's would be. Blocks stored with no token ids only. */
|
||||
int get_blocks(const BlockHash* keys, int64_t n, void* const* payloads, int64_t bytes,
|
||||
char* ok);
|
||||
|
||||
/* Linear-state checkpoints. Keyed by the chained block hash at the checkpoint position, which
|
||||
* is exactly what PrefixCache::reserve_checkpoint keys them by in VRAM. */
|
||||
int put_checkpoint(const BlockHash& key, int64_t pos, const void* payload, int64_t bytes);
|
||||
int get_checkpoint(const BlockHash& key, int64_t pos, void* payload, int64_t bytes);
|
||||
|
||||
struct Stats {
|
||||
int64_t reads = 0, writes = 0, hits = 0, misses = 0, verify_misses = 0, evictions = 0;
|
||||
int64_t bytes_read = 0, bytes_written = 0;
|
||||
};
|
||||
const Stats& stats() const { return stats_; }
|
||||
|
||||
private:
|
||||
/* `prev`/`next` link the used slots from least to most recently used, so a full store finds
|
||||
* the one to give up without a walk. A walk would be over every slot of a store sized in the
|
||||
* millions, once per write, on the thread that has to keep up with the host tier's copies. */
|
||||
struct Slot { BlockHash key; int32_t used = 0; int64_t pos = 0; int32_t prev = -1, next = -1; };
|
||||
struct Store {
|
||||
DirectFile file;
|
||||
int64_t slot_bytes = 0;
|
||||
int64_t hdr_bytes = 0; /* header + token ids, padded */
|
||||
int64_t payload = 0;
|
||||
std::vector<Slot> slots;
|
||||
std::unordered_map<BlockHash, int32_t, BlockHashHash> index;
|
||||
std::vector<int32_t> freelist;
|
||||
int32_t lru_head = -1, lru_tail = -1; /* least and most recently used */
|
||||
void* stage = nullptr;
|
||||
};
|
||||
/* A used slot leaves the order; a slot becomes the most recently used. */
|
||||
static void lru_unlink(Store& s, int32_t i);
|
||||
static void lru_push(Store& s, int32_t i);
|
||||
|
||||
int open_store(Store& s, const std::string& path, int64_t payload, int64_t n_slots,
|
||||
int64_t tok_bytes, bool allow_buffered);
|
||||
int64_t scan_store(Store& s, uint32_t magic);
|
||||
int claim(Store& s, const BlockHash& key, int32_t* out);
|
||||
int put(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
|
||||
const int32_t* toks, int32_t n_toks, const void* payload, int64_t bytes);
|
||||
int get(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
|
||||
const int32_t* toks, int32_t n_toks, void* payload, int64_t bytes);
|
||||
/* Is the slot read into `stage` the one asked for: this store, this model, this key. */
|
||||
bool header_ok(const Store& s, const void* stage, uint32_t magic, const BlockHash& key,
|
||||
int64_t pos, const int32_t* toks, int32_t n_toks, int64_t bytes) const;
|
||||
/* A slot whose bytes are not what the index says: out of the index and the order, and free. */
|
||||
static void forget_slot(Store& s, int32_t slot);
|
||||
|
||||
SSDTierConfig cfg_;
|
||||
std::mutex io_mu_;
|
||||
Store blocks_, ckpts_;
|
||||
bool enabled_ = false;
|
||||
Stats stats_;
|
||||
std::string report_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
Reference in new issue
Block a user