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:
Deadcode committed 2026-10-13 19:35:16 +02:00
commit b93b531f63
127 files changed
+9609 -4796

No files matched your search

+1
View File
@@ -130,6 +130,7 @@ public:
rad_op decl_op (const char* op, const RadParam* p, int n_p,
const rad_weight* w, int n_w);
int op_resolved (rad_op h) const;
int op_declared (const char* op) const;
int decl_name_map(const RadNameMap* m);
int declare_logits(rad_buf b);
int declare_pooled(rad_buf b);
+9
View File
@@ -835,6 +835,10 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
return resolved ? h : RAD_NULL_HANDLE;
}
int Builder::op_declared(const char* op) const {
return op && reg_.schema(op) ? 1 : 0;
}
int Builder::op_resolved(rad_op h) const {
if (h == 0 || h >= prog_.ops.size()) return 0;
const OpInfo& o = prog_.ops[h];
@@ -1749,6 +1753,11 @@ int rad_op_resolved(RadBuilder* b, rad_op h) {
return B(b)->op_resolved(h);
}
int rad_op_declared(RadBuilder* b, const char* op) {
if (!b) return 0;
return B(b)->op_declared(op);
}
/* Proposed additions to rad_builder.h -- defined here so the mechanism exists and core-side
* callers (rad-convert, the tests) can use it. A C plugin cannot until the declarations
* move into the frozen header. */
+49 -18
View File
@@ -72,6 +72,10 @@ static const Flag g_flags[] = {
" pins it in host memory beside --host-pool-mib, read over the\n"
" link in place; by default a model whose output head reads the\n"
" table, or a host without the memory, keeps it on the card" },
{ "--vision-tower-placement", "WHERE", "vram (default) | ram: where the encoder towers live (the\n"
" vision tower; the audio encoder too). ram pins them in host\n"
" memory beside --host-pool-mib, read over the link once an\n"
" image, and gives their VRAM to the KV cache" },
{ "--ngram-placement", "WHERE", "auto (default) | vram | ram | disk: where an n-gram\n"
" embedding table lives (Qwen3.8-Flash-Next: 47.7 GiB).\n"
" vram puts all of it on every card; ram copies it into\n"
@@ -82,16 +86,13 @@ static const Flag g_flags[] = {
{ "--weights-disk-tier", nullptr, "read weights that fit neither VRAM nor the host pool from the\n"
" container on disk (O_DIRECT); a routed expert is read a layer\n"
" at a time, so a step is paced by the drive" },
{ "--prefix-cache-host-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n"
{ "--prefix-cache-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n"
" so their VRAM can go to experts and a return restores\n"
" instead of re-prefilling. 0 is off. Part of it holds\n"
" snapshots on a hybrid or sliding-window model;\n"
" startup says how many" },
{ "--prefix-cache-dir", "DIR", "where the disk tier keeps them. Not --weights-disk-tier, which is\n"
" about WEIGHTS" },
{ "--prefix-cache-disk-mib", "N", "and copy them on to disk under --prefix-cache-dir, up to N MiB,\n"
" so a full host tier gives slots up for nothing. Holds\n"
" conversation content unencrypted. 0 is off" },
" instead of re-prefilling. A full tier drops its least\n"
" recently used entries. 0 is off" },
{ "--prefix-cache-ttl", "S", "seconds a cached conversation no request uses is kept, in VRAM\n"
" or host memory (default 3600). 0 keeps it until the memory\n"
" is wanted" },
{ "--placement", "MODE", "all_vram | layer_offload | expert_tiered | auto" },
{ "--deterministic", nullptr, "pin placement to the plan the loader made, so the resident\n"
@@ -469,7 +470,12 @@ int config_parse(int argc, char** argv, Config* c) {
* ram the default wherever it can be honoured, nothing left for auto to choose. */
if (emb && (!parse_table_placement(v, &p) ||
(p != TablePlacement::Ram && p != TablePlacement::Vram))) {
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
if (parse_table_placement(v, &p) && p == TablePlacement::Auto)
RAD_ERR("--embedding-placement auto was removed in 1.3.0: ram, the default, "
"holds the table in pinned host memory, and vram keeps it on the card. "
"Drop the flag or name one of the two");
else
RAD_ERR("--embedding-placement takes ram or vram, not '%s'", v);
return RAD_E_INVAL;
}
if (!emb && !parse_table_placement(v, &p)) {
@@ -479,10 +485,35 @@ int config_parse(int argc, char** argv, Config* c) {
(emb ? c->embedding_placement : c->ngram_placement) = p;
if (emb) c->embedding_placement_given = true;
}
else if (S("--vision-tower-placement")) {
if (!(v = need(i))) return RAD_E_INVAL;
TablePlacement p;
/* Two tiers, for the embedding's reason: an encoder writes activations the card reads. */
if (!parse_table_placement(v, &p) || (p != TablePlacement::Ram && p != TablePlacement::Vram)) {
RAD_ERR("--vision-tower-placement takes vram or ram, not '%s'", v);
return RAD_E_INVAL;
}
c->tower_placement = p;
}
else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; }
else if (S("--prefix-cache-host-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_host_mib = atoll(v); }
else if (S("--prefix-cache-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_dir = v; }
else if (S("--prefix-cache-disk-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_disk_mib = atoll(v); }
else if (S("--prefix-cache-mib")) { if (!(v = need(i)) ||
!parse_int(a.c_str(), v, 0, INT32_MAX, &c->prefix_cache_mib))
return RAD_E_INVAL; }
else if (S("--prefix-cache-ttl")) { if (!(v = need(i)) ||
!parse_int(a.c_str(), v, 0, INT32_MAX, &c->prefix_cache_ttl))
return RAD_E_INVAL; }
/* THE PREFIX CACHE KEEPS NOTHING ON A DRIVE: a tier there wore it at the rate the server
* prefills, and its copies never outlived the process. The old size flags are told what
* replaced them rather than "unknown option". */
else if (S("--prefix-cache-host-mib")) {
RAD_ERR("--prefix-cache-host-mib was renamed: use --prefix-cache-mib");
return RAD_E_INVAL;
}
else if (S("--prefix-cache-dir") || S("--prefix-cache-disk-mib")) {
RAD_ERR("%s was removed: the prefix cache is kept in VRAM and host memory only "
"(--prefix-cache-mib), and --prefix-cache-ttl says how long", a.c_str());
return RAD_E_INVAL;
}
else if (S("--placement")) { if (!(v = need(i))) return RAD_E_INVAL; c->placement = v; }
else if (S("--deterministic")) c->deterministic = true;
else if (S("--checkpoint-interval")) { if (!(v = need(i))) return RAD_E_INVAL; c->checkpoint_interval = atoll(v); }
@@ -918,12 +949,12 @@ const ShowRow kShow[] = {
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } },
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
{ "--ngram-placement", [](const Config& c) { return std::string(table_placement_name(c.ngram_placement)); } },
{ "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } },
{ "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } },
{ "--prefix-cache-host-mib", [](const Config& c) {
return c.prefix_cache_host_mib ? num(c.prefix_cache_host_mib) : std::string("0 (off)"); } },
{ "--prefix-cache-dir", [](const Config& c) { return or_none(c.prefix_cache_dir, "none"); } },
{ "--prefix-cache-disk-mib", [](const Config& c) {
return c.prefix_cache_disk_mib ? num(c.prefix_cache_disk_mib) : std::string("0 (off)"); } },
{ "--prefix-cache-mib", [](const Config& c) {
return c.prefix_cache_mib ? num(c.prefix_cache_mib) : std::string("0 (off)"); } },
{ "--prefix-cache-ttl", [](const Config& c) {
return c.prefix_cache_ttl ? num(c.prefix_cache_ttl) + " s" : std::string("0 (never)"); } },
{ "--placement", [](const Config& c) { return c.placement; } },
{ "--deterministic", [](const Config& c) { return onoff(c.deterministic); } },
{ "--checkpoint-interval", [](const Config& c) { return num(c.checkpoint_interval); } },
+1 -3
View File
@@ -181,9 +181,7 @@ int DirectFile::read_at(void* dst, int64_t off, int64_t bytes) {
/* ------------------------------------------------------------------ write */
/* The store is written to as well as read: the SSD prefix-cache tier (core/mem/sstier.cpp)
* publishes blocks, and the SSD weight tier is populated once at load. Both write whole aligned
* slots, so this has the same shape as read_at -- one fast path, and a read-modify-write for
/* The same shape as read_at -- one fast path for whole aligned blocks, and a read-modify-write for
* anything that does not cover a whole block. */
int DirectFile::write_at(const void* src, int64_t off, int64_t bytes) {
if (fd_ < 0) return RAD_E_STATE;
+5 -5
View File
@@ -30,11 +30,11 @@ enum {
/* Open buffered when the filesystem refuses O_DIRECT, instead of failing the open.
*
* Off by default, and that default is the point. The weight tier and the prefix cache are
* sized in gigabytes and read in megabyte runs; a silent buffered fallback turns both into a
* page-cache pump that is three times slower and looks like nothing at all in a profile. An
* operator who pointed --prefix-cache-dir at tmpfs wants to be told, not accommodated. The flag is
* for tests, which have to run on whatever /tmp happens to be. */
* Off by default, and that default is the point. The weight tier is sized in gigabytes and
* read in megabyte runs; a silent buffered fallback turns it into a page-cache pump that is
* three times slower and looks like nothing at all in a profile. An operator whose container
* sits on tmpfs wants to be told, not accommodated. The flag is for tests, which have to run
* on whatever /tmp happens to be. */
RAD_DIO_ALLOW_BUFFERED = 16,
};
+1 -1
View File
@@ -302,7 +302,7 @@ void check_memory(const Facts& f, const RunFacts& r, std::vector<Finding>* out)
"the page cache is what a container read in place and the n-gram rows read from disk "
"come through; with it starved every step waits on the drive, and the kernel starts "
"reclaiming and swapping",
"lower --host-pool-mib or --prefix-cache-host-mib, or stop what else holds memory");
"lower --host-pool-mib or --prefix-cache-mib, or stop what else holds memory");
if (h.swap_total > 0 && h.swap_free >= 0 && h.swap_total - h.swap_free > 256 * kMiB)
add(out, Finding::Note, "swap-in-use",
fmt("%s of swap is in use", humanb(h.swap_total - h.swap_free).c_str()),
-1
View File
@@ -167,7 +167,6 @@ struct RunFacts {
/* Why the engine turned prefix caching off itself (the KL mode, an embedding model); "" when
* it is on or the operator turned it off. */
std::string prefix_cache_off_why;
int64_t prefix_host_mib = 0, prefix_disk_mib = 0;
int64_t host_pool_mib = 0; /* a rank, as configured */
int64_t pinned_bytes = -1; /* every pinned host allocation the process made */
int64_t host_weight_bytes = 0; /* weights a rank reads from the pinned host pool */
+25 -159
View File
@@ -66,9 +66,6 @@ Engine::~Engine() {
for (float* p : kld_host_) if (p) rad_dev_free(p, RAD_MEM_HOST_PINNED);
if (pooled_host_) rad_dev_free(pooled_host_, RAD_MEM_HOST_PINNED);
for (auto& r : ranks_) if (r->score_host) rad_dev_free(r->score_host, RAD_MEM_HOST_PINNED);
/* The disk thread first: it reads the host arena and writes the store, both of which go with
* the ranks and kv_disk_ below. */
if (pump_) pump_->io.stop();
/* WHAT THE TIERING ACTUALLY DID, and it is printed here for the same reason: this is the last
* moment the plan the rows name is still alive. Only when the plan was dynamic -- a static
* one has nothing to say and a banner saying nothing is a banner people learn to skip. The
@@ -503,6 +500,7 @@ int Engine::step_loop() {
sched_.release_deferred();
}
tier_tick();
expire_tick(rad_mono_ns());
loan_tick(/*idle=*/true);
/* RADIANCE_DEBUG_IDLE_SCRUB -- a DIAGNOSTIC, not a fix, and the one question it
* answers is whether request N+1 differs from request N because of bytes request N
@@ -948,7 +946,9 @@ int Engine::step_loop() {
sched_.step_finished();
tier_tick();
loan_tick(/*idle=*/false);
arena_tick(rad_mono_ns());
const uint64_t now = rad_mono_ns();
arena_tick(now);
expire_tick(now);
drain_completed();
sched_.publish(/*idle=*/false);
@@ -1305,9 +1305,8 @@ int Engine::collect_step(const RadBatch* b, StepOut& so) {
/* EVERY ITERATION, ON BOTH PATHS. A copy to host memory is asynchronous and reported when its
* event has signalled, so the tick that collects it is simply the first one after it landed; the
* next copy is handed out on the same tick. Tying either to a slower clock would only delay the
* moment a finished conversation's VRAM can be given up. The disk half runs once a second -- its
* thresholds are measured in minutes -- and at once when the host tier has refused a copy for
* want of room, since that copy is waiting on it.
* moment a finished conversation's VRAM can be given up. Room in a full arena is made at once
* when the host tier has refused a copy for want of it, since that copy is waiting on it.
*
* THE SCHEDULER'S LOCK IS HELD FOR THE BOOKKEEPING ONLY. Planning a batch and reporting one touch
* rank 0's manager, the prefix cache and -- through the tiers' drop sinks -- the index an HTTP
@@ -1486,42 +1485,6 @@ void Engine::tier_tick() {
}
}
/* ---- reads off disk that have landed --------------------------------------------------- */
/* THEIR REQUESTS GO NEXT STEP: the records are host records now, held for them, and the
* admission that asks again restores them out of host memory. */
{
TierIO::Fetch f;
while (P.io.take_fetch(&f)) {
destroy_fences(f.fences);
const auto lk = sched_.hold();
lead.tierx.report_pass(f.jobs, f.ok, now);
/* A SNAPSHOT READ BACK INTO ITS SLOT goes to the cache's index entry, which the lookup
* then serves. One whose entry went while the read was out has nothing to land in, and
* the record must not go on naming a slot the store will hand to somebody else. */
for (const TierJob& j : f.jobs) {
if (!j.ck_want || j.ck_slot < 0 || !lead.tiers.snapshot_in_slot(j.key, j.ck_slot))
continue;
if (lead.prefix.reattach_snapshot(j.key, j.ck_slot) != RAD_OK) {
lead.tiers.snapshot_detached(j.key);
lead.kv.free_checkpoint(j.ck_slot);
}
}
P.waiting.erase(std::remove(P.waiting.begin(), P.waiting.end(), f.tag), P.waiting.end());
}
}
/* ---- the disk batch the thread finished ------------------------------------------------ */
{
std::vector<TierJob> jobs;
std::vector<char> ok;
std::vector<RadEvent> fences;
if (P.io.take(&jobs, &ok, &fences)) {
destroy_fences(fences);
const auto lk = sched_.hold();
lead.tierx.report_pass(jobs, ok, now);
}
}
/* ---- the next copy ---------------------------------------------------------------------- */
if (P.copy.empty() && lead.tiers.writeback_waiting()) {
{
@@ -1554,68 +1517,27 @@ void Engine::tier_tick() {
if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean();
}
/* ---- the slow half ---------------------------------------------------------------------- */
/* AS SOON AS A DISK COPY IS WAITING, not on the clock: until it lands, the entry's host slot
* cannot be given up for nothing, and a full arena is then a restore that cannot read through
* it. The thread takes one batch at a time, so this is also as fast as the disk takes them. */
if (!P.io.busy() && (lead.tiers.disk_waiting() || lead.tiers.starved() ||
now - tier_last_ns_ >= 1000000000ull)) {
tier_last_ns_ = now;
/* ---- capacity ---------------------------------------------------------------------------- */
/* WHEN THE ARENA HAS REFUSED A COPY: the oldest host-only entries make room for it. The drops
* move no bytes, so the plan is reported as soon as it is made. */
if (lead.tiers.starved()) {
std::vector<TierJob> jobs;
lead.tiers.plan(P.slow_budget, &jobs);
/* A SNAPSHOT'S SLOT IS FILLED BY A COPY ON THE COMPUTE STREAM, issued after the step that
* produced the state and before the cache was told of it; the write waits for that copy to
* land, and every one of its kind is behind this mark. */
bool snaps = false;
for (const TierJob& j : jobs) snaps = snaps || j.ck_slot >= 0;
int fst = RAD_OK;
std::vector<RadEvent> fences = snaps ? rank_fences(false, true, &fst)
: std::vector<RadEvent>{};
/* A mark that could not be made leaves nothing to order the write by: the batch is
* reported failed, and every record keeps what it had. */
if (fst != RAD_OK) {
destroy_fences(fences);
const std::vector<char> ok(jobs.size(), 0);
const auto lk = sched_.hold();
lead.tierx.report_pass(jobs, ok, now);
return;
}
if (!jobs.empty() && !P.io.submit(std::move(jobs), std::move(fences))) {
destroy_fences(fences);
/* The thread is not running -- no disk tier -- and a plan without one holds only drops,
* which move nothing. They are reported here. */
std::vector<char> ok(jobs.size(), 1);
if (!jobs.empty()) {
const std::vector<char> ok(jobs.size(), 1);
const auto lk = sched_.hold();
lead.tierx.report_pass(jobs, ok, now);
}
}
}
std::vector<RadEvent> Engine::rank_fences(bool transfer, bool compute, int* st) {
std::vector<RadEvent> out;
int rc = RAD_OK;
for (int pass = 0; pass < 2; ++pass) {
if ((pass == 0 && !transfer) || (pass == 1 && !compute)) continue;
for (auto& r : ranks_) {
RadEvent e = nullptr;
const int s = r->tierx.fence(&e, pass == 1 ? r->ctx.stream() : nullptr);
if (s != RAD_OK && rc == RAD_OK) rc = s;
out.push_back(e);
}
}
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
if (st) *st = rc;
return out;
}
void Engine::destroy_fences(std::vector<RadEvent>& f) {
for (size_t i = 0; i < f.size(); ++i) {
if (!f[i]) continue;
(void)rad_dev_set(ranks_[i % ranks_.size()]->device);
rad_event_destroy(f[i]);
}
f.clear();
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
void Engine::expire_tick(uint64_t now_ns) {
if (cfg_.prefix_cache_ttl <= 0 || now_ns - expire_last_ns_ < 1000000000ull) return;
expire_last_ns_ = now_ns;
PrefixCache& pc = ranks_[0]->prefix;
if (!pc.enabled()) return;
const auto lk = sched_.hold();
(void)pc.expire(now_ns, (uint64_t)cfg_.prefix_cache_ttl * 1000000000ull);
}
bool Engine::flush_copies() {
@@ -1659,34 +1581,6 @@ bool Engine::flush_copies() {
return landed;
}
/* HAND A READ OFF DISK TO THE IO THREAD, fenced on every rank's transfer stream: the slots it
* writes may have been given up by entries a restore is still copying out of. False when it could
* not be handed over, and then the reads are reported unstarted -- the records stay on disk and the
* request is admitted with what the host tier holds. */
bool Engine::submit_fetch(uint64_t tag, std::vector<TierJob>&& jobs) {
TierPump& P = *pump_;
TierIO::Fetch f;
f.tag = tag;
f.jobs = std::move(jobs);
/* THE TRANSFER STREAMS, for the restores that read block slots, and THE COMPUTE STREAMS when a
* snapshot comes in: its store slot may have been given up by a snapshot a restore on that
* stream is still copying out of. */
bool snap = false;
for (const TierJob& j : f.jobs) snap = snap || (j.ck_want && j.ck_slot >= 0);
int st = RAD_OK;
f.fences = rank_fences(true, snap, &st);
if (st == RAD_OK && P.io.submit_fetch(std::move(f))) {
P.waiting.push_back(tag);
return true;
}
RAD_ERR("kv tiers: a read off disk could not be handed to the IO thread (%s); the request is "
"admitted with what host memory holds", st < 0 ? rad_strerror(st) : "not running");
destroy_fences(f.fences);
const std::vector<char> ok(f.jobs.size(), 0);
ranks_[0]->tierx.report_pass(f.jobs, ok, rad_mono_ns());
return false;
}
void Engine::drain_completed() {
/* TAKEN, NOT READ. The list is appended to by HTTP threads' cancels, so walking it by
* reference would race them; and nothing else consumes it -- the server learns of a terminal
@@ -1788,42 +1682,13 @@ int Engine::serve() {
/* CALLED FROM INSIDE Scheduler::step(), UNDER ITS LOCK -- which is what makes it safe to
* touch the cache and rank 0's manager here, and why nothing below may call back into the
* scheduler. */
b->restore_fn = [this](const Request& req) -> IPrefixCache::Restore {
using R = IPrefixCache::Restore;
b->restore_fn = [this](const Request& req) {
const uint64_t t0 = rad_mono_ns();
PrefixCache& pc = ranks_[0]->prefix;
TierPump& P = *pump_;
if (std::find(P.waiting.begin(), P.waiting.end(), req.id) != P.waiting.end())
return R::Wait;
std::vector<BlockHash> chain;
std::vector<MMContentKey> mk;
media_keys(req, &mk);
const std::vector<BlockHash> want = pc.restorable_from(req.prompt, mk, &chain);
/* THE DISK PART IS READ FIRST, ON THE IO THREAD, while this request waits and every
* other one runs; the restore below then copies host memory and nothing else. Asked
* on every attempt, because a chain wholly in VRAM can still want a read: its deepest
* snapshot may have given its store slot up and be on disk alone.
*
* THAT SNAPSHOT NEEDS A STORE SLOT TO LAND IN, and the store's free list is rank 0's
* manager's: one is taken here -- making room by detaching a snapshot the disk also
* holds, which is the cache's choice -- and handed to the plan, which gives it back
* when it does not read the snapshot after all. */
{
std::vector<TierJob> reads;
int32_t ck = -1;
if (ranks_[0]->tiers.snapshot_fetch_wanted(chain) &&
ranks_[0]->kv.alloc_checkpoint(&ck) != RAD_OK) {
ck = -1;
if (pc.free_checkpoint_for_restore() &&
ranks_[0]->kv.alloc_checkpoint(&ck) != RAD_OK)
ck = -1;
}
const bool wait = ranks_[0]->tiers.plan_fetch(chain, &reads, rad_mono_ns(), &ck);
if (ck >= 0) ranks_[0]->kv.free_checkpoint(ck);
if (wait && (reads.empty() || submit_fetch(req.id, std::move(reads))))
return R::Wait;
}
if (want.empty()) return R::Done;
const std::vector<BlockHash> want = pc.restorable_from(req.prompt, mk);
if (want.empty()) return;
/* THE WHOLE CHAIN IN ONE RESTORE. A 4-token block makes a long conversation tens of
* thousands of entries, and one transfer an entry is tens of thousands of host round
* trips before the turn can start; as one restore it is a launch per (group, layer)
@@ -1835,7 +1700,7 @@ int Engine::serve() {
if (!ranks_[0]->tierx.plan_promote(h, &j)) break;
jobs.push_back(std::move(j));
}
if (jobs.empty()) return R::Done;
if (jobs.empty()) return;
std::vector<char> ok(jobs.size(), 1);
for (auto& r : ranks_) {
std::vector<char> mine;
@@ -1867,7 +1732,6 @@ int Engine::serve() {
}
}
ranks_[0]->tiers.note_restore((int64_t)(rad_mono_ns() - t0));
return R::Done;
};
/* AN EVICTION THAT WOULD LOSE AN ENTRY WAITS FOR ITS COPY INSTEAD. Called by the
* prefix cache binding under the scheduler's lock, on this thread, when dropping the
@@ -1992,6 +1856,8 @@ std::string Engine::engine_info() const {
{ "resolved", table_placement_name(cfg_.embedding_resolved) } };
e["ngram_placement"] = { { "asked", table_placement_name(cfg_.ngram_placement) },
{ "resolved", table_placement_name(cfg_.ngram_resolved) } };
e["vision_tower_placement"] = { { "asked", table_placement_name(cfg_.tower_placement) },
{ "resolved", table_placement_name(cfg_.tower_resolved) } };
e["prefix_cache"] = cfg_.prefix_cache;
e["checkpoint_slots"] = cfg_.checkpoint_slots;
e["deterministic"] = cfg_.deterministic;
+10 -26
View File
@@ -41,7 +41,6 @@
namespace rad {
class SSDTier;
class Kld;
struct TierPump;
struct TierJob;
@@ -92,18 +91,7 @@ private:
* shared BY POINTER rather than broadcast (spec §1). */
struct Rank;
std::vector<std::unique_ptr<Rank>> ranks_;
/* THE DISK HALF OF THE IDLE TIERS. One store for the engine, not one per rank: it is
* keyed by a chained hash of TOKENS, which every rank computes identically, and a
* per-rank store would write the same key several times over. Off unless
* --prefix-cache-disk-mib and a directory are both given; it holds conversation content
* unencrypted and says so at startup.
*
* unique_ptr because engine.h is included by main.cpp and the tools, and SSDTier
* drags in the O_DIRECT device layer that none of them want to compile against. */
std::unique_ptr<SSDTier> kv_disk_;
/* THE TIERS' WORK IN FLIGHT: the copy to host memory the transfer streams are running and the
* disk batch the IO thread is writing. Declared after kv_disk_ so it goes first -- the thread
* writes into that store. */
/* THE TIERS' WORK IN FLIGHT: the copy to host memory the transfer streams are running. */
std::unique_ptr<TierPump> pump_;
std::vector<std::thread> rank_threads_;
@@ -146,10 +134,11 @@ private:
int apply_rope_scaling();
int declare();
int plan();
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
* (engine_bringup.cpp says how auto chooses). */
/* --embedding-placement, --vision-tower-placement and --ngram-placement, resolved into Config
* before the card is split (engine_bringup.cpp says how auto chooses). */
int resolve_table_placement(const std::vector<VramFacts>& facts,
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
const std::vector<int64_t>& emb_bytes,
const std::vector<int64_t>& tower_bytes, int64_t kv_floor,
int64_t ngram_bytes, bool ngram_device, bool ngram_host);
/* --ngram-placement ram: the copy of the container's [src, src + n), file offset `foff`, made
* once and shared by every rank -- locked for the host gather, or pinned for a device kernel
@@ -352,20 +341,15 @@ private:
/* The terminal ids drain_completed() took, reused so a steady state allocates nothing. */
std::vector<uint64_t> done_;
/* THE TIERS' SIDE OF THE LOOP, every iteration: collect a copy that has landed, hand the next
* one out, collect and hand out the disk work. Nothing in it waits on the device or on a file,
* and the scheduler's lock is held only around the bookkeeping. */
* one out, and make room in a full arena. Nothing in it waits on the device, and the
* scheduler's lock is held only around the bookkeeping. */
void tier_tick();
bool submit_fetch(uint64_t tag, std::vector<TierJob>&& jobs);
/* A MARK ON EVERY RANK'S STREAMS, for the disk thread to wait on before it touches a slot:
* the transfer streams' when `transfer`, the compute streams' when `compute`, in that order,
* one a rank each; `st` is the first failure to make one. destroy_fences gives them back on
* their own cards. */
std::vector<RadEvent> rank_fences(bool transfer, bool compute, int* st = nullptr);
void destroy_fences(std::vector<RadEvent>& f);
/* --prefix-cache-ttl, once a second, with or without the tiers (PrefixCache::expire). */
void expire_tick(uint64_t now_ns);
uint64_t expire_last_ns_ = 0;
/* Every host copy that is waiting, issued and landed now. Under the scheduler's lock, from an
* eviction that would otherwise erase what the copies cover. True when any landed. */
bool flush_copies();
uint64_t tier_last_ns_ = 0;
/* THE LOAN: what the KV cache is not using, lent to every rank's expert slab at the addresses
* the cache already owns (KVManager, the loan block). Here rather than inside the scheduler
* because it spans both sides -- rank 0's cache decides how much, and every rank's mover
+111 -169
View File
@@ -220,9 +220,11 @@ static int usable_devices(std::vector<int>* out, std::string* inventory, std::st
*
* A card refusing its weights pool after its budget was measured had that memory taken in
* between, and another process on the card is the usual taker -- the budget is measured once,
* before any rank allocates. A host pool is PINNED memory, and the amdgpu driver caps what the
* whole system may pin (ttm.pages_limit, half of RAM unless raised); every rank pins its own
* --host-pool-mib, so a second rank asks for the same amount again. */
* before any rank allocates. A host pool is PINNED memory, and every rank pins its own
* --host-pool-mib, so a second rank asks for the same amount again. The pool is locked user memory,
* which the amdgpu driver counts against one system-wide cap: RAM less 1/64 and 1.5 GiB (half of
* RAM less 1/64 below 3 GiB), unless amdgpu.no_system_mem_limit lifts it. ttm.pages_limit bounds
* the driver's own allocations and not these. */
static void report_pool_refusal(int rank, int device, const Pools& pools, const Config& cfg) {
bool card = false, host = false;
for (const Shortfall& f : pools.shortfalls()) (f.pool == "host_pool" ? host : card) = true;
@@ -238,46 +240,54 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
int64_t pinned = 0, mapped = 0;
rad_dev_alloc_totals(RAD_MEM_HOST_PINNED, &pinned, nullptr);
rad_dev_alloc_totals(RAD_MEM_HOST_MAPPED, &mapped, nullptr);
int64_t cap = -1, avail = -1;
{
std::ifstream f("/sys/module/ttm/parameters/pages_limit");
long long pages = 0;
if (f >> pages && pages > 0) cap = (int64_t)pages * (int64_t)sysconf(_SC_PAGESIZE);
}
int64_t total = -1, avail = -1;
{
std::ifstream f("/proc/meminfo");
std::string line;
while (std::getline(f, line)) {
long long kb = 0;
if (std::sscanf(line.c_str(), "MemAvailable: %lld kB", &kb) == 1) {
avail = (int64_t)kb * 1024;
break;
}
if (std::sscanf(line.c_str(), "MemTotal: %lld kB", &kb) == 1) total = (int64_t)kb * 1024;
if (std::sscanf(line.c_str(), "MemAvailable: %lld kB", &kb) == 1) avail = (int64_t)kb * 1024;
}
}
bool lifted = false;
{
std::ifstream f("/sys/module/amdgpu/parameters/no_system_mem_limit");
std::string v;
lifted = (f >> v) && (v == "Y" || v == "1");
}
const int64_t reserve = (int64_t)3 << 29;
int64_t cap = -1;
if (total > 0 && !lifted) {
cap = total - (total >> 6);
cap = cap < 2 * reserve ? cap >> 1 : cap - reserve;
}
/* A refusal with room under both is not a capacity one, and advice to shrink the pool
* would send the reader after the wrong cause: the device's reason above is the answer. */
const int64_t pool = (cfg.host_pool_mib + cfg.embedding_host_mib) * 1024 * 1024;
const int64_t pool = cfg.host_pool_total_mib() * 1024 * 1024;
std::string tables, advice = "Lower --host-pool-mib";
if (cfg.embedding_host_mib) {
tables += fmt(" and the token embedding's %lld MiB", (long long)cfg.embedding_host_mib);
advice += ", keep the embedding on the card with --embedding-placement vram";
}
if (cfg.tower_host_mib) {
tables += fmt(" and the encoder towers' %lld MiB", (long long)cfg.tower_host_mib);
advice += ", keep the encoder towers on the card with --vision-tower-placement vram";
}
const int64_t want = (int64_t)cfg.tp * pool + pinned + mapped;
const bool fits = cap > 0 && avail >= 0 && want <= cap && want <= avail;
const bool fits = avail >= 0 && want <= avail && (lifted || (cap > 0 && want <= cap));
RAD_ERR("host: --host-pool-mib %lld%s is pinned once per rank, so %d rank(s) pin %s; this "
"process had taken %s of pinned host memory before rank %d's pool. The amdgpu "
"driver caps pinned memory system-wide at %s (ttm.pages_limit, half of RAM unless "
"raised), and %s of RAM is available. %s",
(long long)cfg.host_pool_mib,
cfg.embedding_host_mib
? fmt(" and the token embedding's %lld MiB", (long long)cfg.embedding_host_mib).c_str()
: "",
cfg.tp, humanb((int64_t)cfg.tp * pool).c_str(),
"driver caps what every process together pins at %s, and %s of RAM is available. %s",
(long long)cfg.host_pool_mib, tables.c_str(), cfg.tp, humanb((int64_t)cfg.tp * pool).c_str(),
humanb(pinned + mapped).c_str(), rank,
cap > 0 ? humanb(cap).c_str() : "an unreadable limit",
lifted ? "no limit (amdgpu.no_system_mem_limit)"
: cap > 0 ? fmt("%s (RAM less 1/64 and 1.5 GiB)", humanb(cap).c_str()).c_str()
: "an unknown limit (MemTotal unreadable)",
avail >= 0 ? humanb(avail).c_str() : "an unknown amount",
fits ? "The pools fit under both, so the refusal is not one of size; the reason "
"the device gave is above"
: cfg.embedding_host_mib
? "Lower --host-pool-mib, keep the embedding on the card with "
"--embedding-placement vram, or raise the cap"
: "Lower --host-pool-mib, or raise the cap");
: advice.c_str());
}
}
@@ -472,6 +482,9 @@ bool Engine::ngram_gather_to_host() {
* lookup writes the activations a card reads, which a host kernel reading the container cannot
* reach -- an architecture declares a buffer's domain, and the token embedding's is the device.
*
* THE ENCODER TOWERS: Vram by default; Ram, when named, pins them beside the pool as the embedding
* is (Config::tower_host_mib), read over the link once an image.
*
* THE N-GRAM TABLE: Vram where a device kernel gathers it and the card holds it; Ram as a copy,
* pinned for that kernel to read over the link or locked for the host gather; Disk in the
* container, read by the host gather. Each tier is refused where no kernel reads it there. Auto
@@ -480,7 +493,8 @@ bool Engine::ngram_gather_to_host() {
* the memory and every cgroup after the pools still to be allocated, and the memlock limit for a
* locked copy. */
int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
const std::vector<int64_t>& emb_bytes,
const std::vector<int64_t>& tower_bytes, int64_t kv_floor,
int64_t ngram_bytes, bool ngram_device, bool ngram_host) {
const int64_t MiB = (int64_t)1 << 20;
int64_t emb_max = 0;
@@ -494,7 +508,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
* which a pin the cards read is not charged to. */
const int64_t emb_pin = (int64_t)cfg_.tp * align_up(emb_max, (int64_t)MiB);
const int64_t pools_still = (int64_t)cfg_.tp * cfg_.host_pool_mib * MiB +
cfg_.prefix_cache_host_mib * MiB;
cfg_.prefix_cache_mib * MiB;
std::string emb_room_why;
auto emb_room = [&]() { return lockable_room(emb_pin, pools_still, false, &emb_room_why); };
if (emb_max == 0) {
@@ -528,6 +542,36 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
cfg_.embedding_resolved = emb;
cfg_.embedding_host_mib = emb == TablePlacement::Ram ? align_up(emb_max, MiB) / MiB : 0;
/* THE ENCODER TOWERS: on the card unless ram was named, and then pinned beside the pool or the
* server stops -- the flag has no default to give way to. Every rank pins a whole tower: an
* encoder is not sharded. Decided before the n-gram table, whose card test needs the statics
* as they will be and whose RAM test the pools still to be allocated. */
int64_t tower_max = 0;
for (int64_t b : tower_bytes) tower_max = std::max(tower_max, b);
const TablePlacement tw = cfg_.tower_placement;
if (tw == TablePlacement::Ram) {
if (tower_max == 0) {
if (cfg_.mm_max_patches == 0)
RAD_ERR("--vision-tower-placement ram: --mm-max-patches 0 asked for no media, so "
"this server declares no encoder tower to place");
else
RAD_ERR("--vision-tower-placement ram: this model has no encoder tower (no weight "
"its architecture reads once per request)");
return RAD_E_INVAL;
}
std::string why;
const int64_t pin = (int64_t)cfg_.tp * align_up(tower_max, (int64_t)MiB);
if (!lockable_room(pin, pools_still + (int64_t)cfg_.tp * cfg_.embedding_host_mib * MiB,
false, &why)) {
RAD_ERR("--vision-tower-placement ram: the encoder towers (%s a rank, pinned on every "
"rank) cannot be held in host memory: %s. Use vram.", humanb(tower_max).c_str(),
why.c_str());
return RAD_E_NOMEM;
}
}
cfg_.tower_resolved = tw;
cfg_.tower_host_mib = tw == TablePlacement::Ram ? align_up(tower_max, MiB) / MiB : 0;
TablePlacement ng = cfg_.ngram_placement;
std::string ng_why;
/* THE FASTEST TIER WITH THE ROOM, the card first: the table on the card, every rank holding
@@ -535,8 +579,8 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
* --max-model-len sequence beside it; then a copy in RAM -- pinned
* for a device kernel to read over the link, or locked for the host gather; then the
* container, which only the host gather reads. Each is open only where a kernel reads it. */
const int64_t still = (int64_t)cfg_.tp * (cfg_.host_pool_mib + cfg_.embedding_host_mib) * MiB +
cfg_.prefix_cache_host_mib * MiB;
const int64_t still = (int64_t)cfg_.tp * cfg_.host_pool_total_mib() * MiB +
cfg_.prefix_cache_mib * MiB;
const int64_t need = align_up(ngram_bytes, (int64_t)2 << 20);
const char* copy = ngram_device ? "a pinned copy the card reads" : "a locked copy";
auto card_holds = [&](std::string* why) {
@@ -546,6 +590,7 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
VramFacts& f = with[i];
f.statics += ngram_bytes;
if (emb == TablePlacement::Ram) f.statics -= emb_bytes[i];
if (tw == TablePlacement::Ram) f.statics -= tower_bytes[i];
fixed = std::max(fixed, f.statics);
}
/* `fixed` and not the trial's own statics: the split clamps those to what the card can give
@@ -645,6 +690,15 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
decide("--embedding-placement", table_placement_name(emb),
emb_max > 0 ? fmt("the table is %s a rank: %s", humanb(emb_max).c_str(), emb_why.c_str())
: emb_why);
if (tower_max > 0)
RAD_INFO("placement: encoder towers (%s a rank) %s%s", humanb(tower_max).c_str(),
table_placement_name(tw),
tw == TablePlacement::Ram ? ": pinned in host memory, read over the link once an "
"image, their VRAM the KV cache's"
: " (default)");
decide("--vision-tower-placement", tower_max > 0 ? table_placement_name(tw) : "n/a",
tower_max > 0 ? fmt("the towers are %s a rank", humanb(tower_max).c_str())
: std::string("this server declares no encoder tower"));
has_ngram_ = ngram_bytes > 0;
decide("--ngram-placement", ngram_bytes > 0 ? table_placement_name(ng) : "n/a",
ngram_bytes > 0 ? fmt("the table is %s: %s", humanb(ngram_bytes).c_str(), ng_why.c_str())
@@ -1223,7 +1277,7 @@ int Engine::plan() {
late_step_bytes_ = late_lazy_bytes_ = 0;
/* The placement flags' tables, per rank where they are sharded (the embedding) and once
* where they are not (the n-gram table every rank reads from the one mapping). */
std::vector<int64_t> emb_bytes;
std::vector<int64_t> emb_bytes, tower_bytes;
std::vector<WeightFootprint> wfs;
int64_t ngram_bytes = 0, kv_floor = 0;
bool ngram_device = false, ngram_host = false;
@@ -1288,6 +1342,7 @@ int Engine::plan() {
f.lends = VMem::supported() && !cfg_.deterministic &&
(cfg_.placement == "auto" || cfg_.placement == "expert_tiered");
emb_bytes.push_back(wf.embedding);
tower_bytes.push_back(wf.tower);
ngram_bytes = std::max(ngram_bytes, wf.ngram);
ngram_device = ngram_device || wf.ngram_device;
ngram_host = ngram_host || wf.ngram_host;
@@ -1333,7 +1388,7 @@ int Engine::plan() {
/* AND THE KV TIERS' COPY STAGING, which TierExec::device_init builds on the first
* copy out. Which groups the prefix cache indexes is settled after this split, so
* every paged group is counted: the entry it sizes can only be smaller. */
if (cfg_.prefix_cache_host_mib > 0 || cfg_.prefix_cache_disk_mib > 0) {
if (cfg_.prefix_cache_mib > 0) {
int64_t entry = 0, bs = 0;
int ng = 0;
for (size_t g = 0; g < r->program.kv_groups.size(); ++g) {
@@ -1359,13 +1414,15 @@ int Engine::plan() {
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
facts[i].expert_floor = expert_vram_floor(wfs[i], std::max<int64_t>(room, 0));
}
RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device,
ngram_host));
RAD_TRY(resolve_table_placement(facts, emb_bytes, tower_bytes, kv_floor, ngram_bytes,
ngram_device, ngram_host));
/* The n-gram table was counted off the card; on it, it is every rank's whole table. */
if (cfg_.ngram_resolved == TablePlacement::Vram)
for (VramFacts& f : facts) f.statics += ngram_bytes;
if (cfg_.embedding_resolved == TablePlacement::Ram)
for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i];
if (cfg_.tower_resolved == TablePlacement::Ram)
for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= tower_bytes[i];
VramBudget vb;
RAD_TRY(vram_budget_resolve(cfg_, facts, &vb));
if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str());
@@ -1535,9 +1592,10 @@ int Engine::plan() {
humanb(r->plan.totals.bytes[(int)Tier::VRAM]).c_str(), humanb(host).c_str(),
humanb(r->plan.totals.bytes[(int)Tier::SSD]).c_str(),
humanb(r->plan.totals.bytes[(int)Tier::Mapped]).c_str()),
r->plan.embedding_host_used > 0
? fmt("the host pool holds the token embedding's %s beside the weights "
"placed there", humanb(r->plan.embedding_host_used).c_str())
r->plan.forced_host_used > 0
? fmt("the host pool holds the %s the placement flags put there (the token "
"embedding, the encoder towers) beside the weights placed in it",
humanb(r->plan.forced_host_used).c_str())
: std::string());
}
/* --host-pool-mib IS ONE NUMBER FOR EVERY RANK, allocated whole by Pools::configure, so a
@@ -2933,17 +2991,16 @@ int Engine::configure_kv() {
/* ---------------- the idle session tiers (spec §7.3) ---------------- */
/* AFTER the prefix cache, because the tiers are sized in units of ONE CACHE ENTRY and only the
* configured cache knows which groups an entry covers. No memory is committed unless an
* operator gave a tier a size: a tier of zero bytes holds nothing, so the two inactivity
* thresholds are ordinary defaults rather than a commitment of memory nobody asked to spend.
* configured cache knows which groups an entry covers. No memory is committed unless the
* operator gave the host tier a size.
*
* CONFIGURED EVEN SO, because this object is also where a stored conversation is RECORDED,
* and that is not a tiering fact. A server with no --prefix-cache-host-mib holds its whole prefix
* and that is not a tiering fact. A server with no --prefix-cache-mib holds its whole prefix
* cache in VRAM and holds it for exactly as long; skipping the configure would leave the
* sessions view reading an unconfigured object and reporting an empty server, on every
* deployment that has not opted into demotion. What the flags gate is the MOVER, below. */
{
const bool tier_asked = cfg_.prefix_cache_host_mib > 0 || cfg_.prefix_cache_disk_mib > 0;
const bool tier_asked = cfg_.prefix_cache_mib > 0;
const std::vector<int32_t>& cg = ranks_[0]->prefix.cached_groups();
/* ONE SLOT HOLDS EVERY RANK'S SHARD. An entry under tensor parallelism is n_ranks
* pieces of KV that are not interchangeable, so the unit the tiers store and budget
@@ -2967,138 +3024,36 @@ int Engine::configure_kv() {
entry_bytes = std::max(entry_bytes, rank_entry[i]);
}
/* ---- how the disk tier is split between the two halves of a session ----
*
* ON THIS BUILD A RESTORED HYBRID SESSION WITH NO SNAPSHOT REUSES NOTHING AT ALL. The
* scheduler clamps its reuse to the last reachable checkpoint and says why: RadBatch
* carries one query length for every KV group, so the linear layers cannot be replayed
* over a longer range than the attention layers, and the correct answer is to recompute
* from the checkpoint (core/sched/scheduler.cpp, admit_one). A session whose blocks came
* back and whose state did not therefore gets a hit of ZERO -- the blocks are not a
* partial win, they are unusable -- and the snapshot store is not a nice-to-have beside
* the block store, it is the thing that decides whether any of this works.
*
* So the split is DERIVED, from the session the operator sized the server for. At
* --max-model-len M a session costs
*
* blocks (M / block_size) * slot_bytes
* snapshots (log2(M / interval) + 1) * ck_slot_bytes [geometric backoff]
*
* and splitting the cap in that ratio makes both halves hold the same NUMBER OF SESSIONS,
* which is the only sense in which they can be balanced. The ratio is strongly length
* dependent -- snapshots want 22% of the tier at 200K and more than half at 32K, because
* the retained set grows logarithmically while the blocks grow linearly -- which is
* exactly why a single fixed fraction is the wrong shape.
*
* Two thirds is the ceiling. Not because the arithmetic asks for one, but because the
* clamp above is a property of THIS build rather than of the design, and a tier with
* almost no room for blocks would be badly sized the day it is lifted.
*
* THE HOST TIER IS NOT SPLIT: snapshots live in the checkpoint store, which
* --checkpoint-slots sizes, and --prefix-cache-host-mib is the blocks' alone. */
/* THE SNAPSHOTS ARE NOT IN THE HOST TIER: they live in the checkpoint store, which
* --checkpoint-slots sizes, and --prefix-cache-mib is the blocks' alone. */
const int64_t ck_slot_bytes = ck_store_.enabled() ? ck_store_.slot_bytes() : 0;
int64_t ck_disk_slots = 0;
if (ck_slot_bytes > 0) {
const int64_t bs = ranks_[0]->prefix.block_size();
const int64_t iv = ranks_[0]->prefix.checkpoint_interval();
/* The session the server was sized for: --max-model-len, or the training context
* when it is unset -- the same reading the declare and the KV pool take. */
const int64_t mlen = std::max<int64_t>(
1, cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train);
int64_t retained = 1;
for (int64_t n = (iv > 0 ? mlen / iv : 0); n > 1; n >>= 1) ++retained;
const int64_t sess_blocks = bs > 0 ? (mlen / bs) * slot_bytes : slot_bytes;
const int64_t sess_snaps = retained * ck_slot_bytes;
const int64_t denom = sess_blocks + sess_snaps;
const int64_t disk_cap = cfg_.prefix_cache_disk_mib << 20;
const int64_t disk_ck = std::min(disk_cap * 2 / 3, denom > 0 ? disk_cap / denom * sess_snaps
+ disk_cap % denom * sess_snaps / denom
: 0);
ck_disk_slots = disk_ck / ck_slot_bytes;
/* One where there is room for one at all: a tier that holds a session's blocks and not
* one snapshot holds nothing usable. */
if (ck_disk_slots == 0 && disk_cap >= ck_slot_bytes * 2) ck_disk_slots = 1;
}
if (cg.empty() || entry_bytes <= 0) {
/* Said only to an operator who asked for a tier. With no flag there is nothing to
* report: a cache that indexes no paged group stores no blocks to begin with. */
if (tier_asked)
RAD_WARN("kv tiers: the prefix cache indexes no paged group, so there is nothing "
"to move. --prefix-cache-host-mib and --prefix-cache-disk-mib do nothing here.");
"to move. --prefix-cache-mib does nothing here.");
} else {
if (cfg_.prefix_cache_disk_mib > 0) {
if (cfg_.prefix_cache_dir.empty()) {
RAD_WARN("kv tiers: --prefix-cache-disk-mib needs --prefix-cache-dir to say WHERE. "
"The disk tier is off.");
} else {
SSDTierConfig sc;
sc.dir = cfg_.prefix_cache_dir;
sc.block_payload = slot_bytes;
sc.block_tokens = ranks_[0]->prefix.block_size();
sc.ckpt_payload = ck_slot_bytes;
sc.n_ckpt_slots = ck_disk_slots;
sc.n_block_slots = ((cfg_.prefix_cache_disk_mib << 20)
- ck_disk_slots * ck_slot_bytes) / slot_bytes;
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE, and it is built from
* everything a cached block's bytes actually depend on. Read back under a
* different container, layout, KV width or rotary, a block is a lossless
* function of somebody else's weights -- fluent, confident and wrong. There is
* no cheaper check than refusing the whole store, because a block carries no
* evidence of what produced it beyond the tokens it was keyed by.
*
* The rotary is the RESOLVED one, target and drafter, after --rope-scaling
* (rope_identity): a YaRN container converted from the same checkpoint has the
* same name and shapes as the stock one, and every cached key and QSA block key
* is rotated differently under it. */
{
char theta[32];
std::snprintf(theta, sizeof theta, "%.9g", (double)meta_.rope_theta);
const std::string id =
std::string(meta_.name ? meta_.name : "") + "|" +
std::string(meta_.arch_id ? meta_.arch_id : "") + "|" +
std::to_string(meta_.n_layers) + "|" +
std::to_string(ranks_[0]->prefix.block_size()) + "|" +
std::to_string(slot_bytes) + "|" + std::to_string(ck_slot_bytes) + "|" +
cfg_.kv_cache_dtype + "|" +
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION +
"|theta=" + theta + "|" + rope_identity(meta_kv_k_, meta_kv_v_);
uint64_t h = 1469598103934665603ull;
for (char c : id) { h ^= (unsigned char)c; h *= 1099511628211ull; }
sc.fingerprint = h;
}
sc.persistent = true;
kv_disk_ = std::make_unique<SSDTier>();
RAD_INFO("%s", SSDTier::disclosure(sc.dir).c_str());
if (kv_disk_->open(sc) != RAD_OK) {
RAD_WARN("kv tiers: the disk tier at %s would not open; it is off.",
sc.dir.c_str());
kv_disk_.reset();
}
}
}
IdleTiers::Config tc;
tc.host_cap_bytes = cfg_.prefix_cache_host_mib << 20;
tc.disk_cap_bytes = kv_disk_ ? (cfg_.prefix_cache_disk_mib << 20) : 0;
tc.host_cap_bytes = cfg_.prefix_cache_mib << 20;
tc.entry_bytes = slot_bytes;
tc.ckpt_bytes = ck_slot_bytes;
tc.ckpt_slots = ck_store_.capacity();
tc.ckpt_disk_slots = kv_disk_ ? ck_disk_slots : 0;
/* THE POLICY IS RANK 0'S AND THE TRANSFER IS EVERY RANK'S. A session is not sharded --
* it is a conversation -- so one decision is taken about it; but each rank holds its
* own shard of every block and gathers out of its own pool, so each rank moves its own
* bytes when that decision is taken. */
IdleTiers& T = ranks_[0]->tiers;
RAD_TRY(T.configure(tc, kv_disk_.get()));
RAD_TRY(T.configure(tc));
T.set_model(meta_.name && meta_.name[0] ? meta_.name : "(unnamed)");
if (T.any_on()) {
/* HOW MUCH A PASS MOVES, SIZED IN BYTES AND NOT IN ENTRIES. A cache entry is one
* block per cached group, and that is 29 KiB on a 4-token-block hybrid and four
* times more on a 16-token one -- so a fixed entry count means a fixed batch on
* one model and a quarter of one on another. At a fixed 64 entries a 200K session
* on a 4-token-block hybrid takes about thirteen minutes to leave VRAM, which is
* most of the way to the disk threshold: a tier that works and is too slow to be
* worth having.
* on a 4-token-block hybrid takes about thirteen minutes to leave VRAM: a tier that
* works and is too slow to be worth having.
*
* 16 MiB of device staging a rank, which is about a millisecond of PCIe a pass
* and 0.02 ms a step of the VRAM it costs. The batch is one gather per (group,
@@ -3129,12 +3084,11 @@ int Engine::configure_kv() {
* AND THE STREAM IS THE MOVER'S. See Mover::transfer_stream -- a fourth
* hardware queue costs an RDNA4 card 65% of its decode step. */
RAD_TRY(rad_dev_set(r->device));
if (r->tierx.configure(&rad_tools_registry(), &r->kv, &T, kv_disk_.get(), cg,
if (r->tierx.configure(&rad_tools_registry(), &r->kv, &T, cg,
max_batch, max_copy, max_chain,
/*leader=*/&r == &ranks_[0],
r->device,
entry_off[(size_t)(&r - &ranks_[0])],
&ck_store_,
/*shared=*/r->mover.transfer_stream())
!= RAD_OK) {
all = false;
@@ -3148,10 +3102,8 @@ int Engine::configure_kv() {
* reported size is computed from, so the object is re-configured for the
* caps it can still honour -- none. */
T.close();
kv_disk_.reset();
tc.host_cap_bytes = tc.disk_cap_bytes = 0;
tc.ckpt_disk_slots = 0;
RAD_TRY(T.configure(tc, nullptr));
tc.host_cap_bytes = 0;
RAD_TRY(T.configure(tc));
} else {
/* The tiers can lose an entry without the cache asking: a capacity drop, or a
* promotion that failed. The cache has to hear about it or it will go on
@@ -3159,21 +3111,11 @@ int Engine::configure_kv() {
T.set_drop_sink([this](const BlockHash& h) {
ranks_[0]->prefix.drop_offdevice(h);
});
/* And the linear half on its own: a snapshot whose only copy was on disk and
* that the disk store let go of. An index entry left behind would be a
* checkpoint the cache goes on offering whose bytes nobody holds, which is the
* recurrent-state form of the same corruption. */
T.set_snapshot_drop_sink([this](const BlockHash& h) {
ranks_[0]->prefix.drop_snapshot(h);
});
/* THE DISK HALF GETS A THREAD, and a plan holds about 512 MiB of it -- a
* fraction of a second of the store's write rate, so the disk copies keep up
* with the host copies in a handful of plans rather than one entry a second. */
/* A capacity plan drops up to 512 MiB of the oldest host-only entries. */
pump_ = std::make_unique<TierPump>();
pump_->max_copy = max_copy;
pump_->slow_budget = (int)std::min<int64_t>(
1 << 20, std::max<int64_t>(64, (512ll << 20) / std::max<int64_t>(1, slot_bytes)));
if (kv_disk_) pump_->io.start(&ranks_[0]->tierx);
RAD_INFO("%s", ranks_[0]->tierx.report().c_str());
}
}
+2 -4
View File
@@ -74,8 +74,6 @@ diag::RunFacts Engine::run_facts(bool failed) const {
r.tp_wire_min_kb = cfg_.tp_wire_min_kb;
r.prefix_cache = cfg_.prefix_cache;
r.prefix_cache_off_why = prefix_off_why_;
r.prefix_host_mib = cfg_.prefix_cache_host_mib;
r.prefix_disk_mib = cfg_.prefix_cache_disk_mib;
r.host_pool_mib = cfg_.host_pool_mib;
{
int64_t pinned = 0, mapped = 0, n = 0;
@@ -85,11 +83,11 @@ diag::RunFacts Engine::run_facts(bool failed) const {
}
/* THE MOST ANY RANK READS FROM THE HOST: the ranks step together, so the one that streams most
* is the one each step waits for. The embedding the placement flag put in host memory is read
* a few rows a step and is not what this counts. */
* a few rows a step, the encoder towers once an image, and neither is what this counts. */
for (const auto& rk : ranks_) {
const Plan& p = rk->plan;
const int64_t host = p.totals.bytes[(int)Tier::HostPinned] +
p.totals.bytes[(int)Tier::HostPageable] - p.embedding_host_used;
p.totals.bytes[(int)Tier::HostPageable] - p.forced_host_used;
r.host_weight_bytes = std::max(r.host_weight_bytes, std::max<int64_t>(host, 0));
r.file_weight_bytes = std::max(r.file_weight_bytes, p.totals.bytes[(int)Tier::SSD]);
}
+4 -10
View File
@@ -17,7 +17,6 @@
#include "mem/kv.h"
#include "mem/prefix.h"
#include "mem/kvtier.h"
#include "mem/sstier.h"
#include "runtime/tierexec.h"
#include "build/rad_build.h"
#include "place/heat.h"
@@ -66,9 +65,8 @@ struct Engine::Rank {
/* THE IDLE SESSION TIERS (spec 7.3). Rank 0 owns the policy and the session index,
* because they describe CONVERSATIONS and a conversation is not sharded -- but the
* transfer is per rank, since each rank holds its own shard of every KV block and
* has its own pool to gather out of. The disk store is rank 0's alone for the same
* reason the policy is: one store, keyed by a hash of tokens every rank agrees on.
* Both are inert unless the operator gave a tier a size. */
* has its own pool to gather out of. Both are inert unless --prefix-cache-mib gave the
* host tier a size. */
IdleTiers tiers;
TierExec tierx;
/* The activation arena's smaller levels, smallest step first (Engine::probe_arena_levels). */
@@ -101,16 +99,12 @@ struct Engine::Rank {
/* THE TIERS' WORK IN FLIGHT (Engine::tier_tick). One copy batch out on every rank's transfer
* stream at a time, with each rank's answer kept until all of them have one -- a rank that has
* landed must not be asked again and forget it failed -- and one disk batch out on the IO thread. */
* landed must not be asked again and forget it failed. */
struct TierPump {
std::vector<TierJob> copy;
std::vector<int> copy_st; /* per rank: 0 in flight, 1 landed, negative failed */
TierIO io;
int64_t max_copy = 0;
int slow_budget = 0;
/* The requests a read off disk is out for (IdleTiers::plan_fetch). Asked again while their
* read is out, they wait without walking their prompt; the read's collection lets them go. */
std::vector<uint64_t> waiting;
int slow_budget = 0; /* capacity drops one plan may make */
};
/* THE BUFFER PROBE (engine_probe.cpp). Declared here because three files call it: the step
+7 -1
View File
@@ -3,6 +3,7 @@
*/
#include "engine.h"
#include "hf_model.h"
#include "util/stallwatch.h"
int main(int argc, char** argv) {
rad::Config cfg;
@@ -14,7 +15,12 @@ int main(int argc, char** argv) {
rad::Engine engine(std::move(cfg));
s = engine.start();
{
/* A startup that stops printing says where it waits (util/stallwatch.h). Two minutes:
* the slowest normal step, a container read from a slow disk, logs well inside that. */
rad::StallWatch watch("startup", 120000);
s = engine.start();
}
if (s < 0) {
/* start() already said what and why; the report adds what it was running on and what it
* had decided by then, which is what a log of a server that never came up is read for. */
+2 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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;
-536
View File
@@ -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 */
-181
View File
@@ -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 */
+39 -16
View File
@@ -1115,9 +1115,10 @@ int Mover::drop(int32_t unit, HeatEngine* heat) {
* slot or back across the link (reclaim), and a loan that shrinks under it moves it the same way
* (balance). There is always somewhere for it to go -- each donor's copy went to a unit
* whose budgeted slot it left free, so the free budgeted slots and the free pool slots together
* number at least the donors. The donors are bounded by the turnover slots, and they come out of
* the KV cache's loan only: the arena takes its loan back at every prompt's first chunk, and that
* recall stays a change of address.
* number at least the donors once the quarantine has emptied (a recall drains it first). The
* donors are bounded by the turnover slots, and they come out of the KV cache's loan only: the
* arena takes its loan back at every prompt's first chunk, and that recall stays a change of
* address.
*
* THE HOTTEST UNIT GIVES ITS COPY -- of the victim's layer, when pool_slot_for asks for one --
* because a donor the engine later demotes needs a pool slot of its own where it would have been a
@@ -1458,13 +1459,28 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
RAD_TRY(flush_moves());
RAD_TRY(rad_stream_sync(mover_));
RAD_TRY(retire(heat));
/* AND NO SLOT IS STILL IN QUARANTINE. The slots the donors below are owed come back through
* it: a donation's victim leaves its budgeted slot that way, and a promotion that refilled the
* slot leaves its pool slot that way (donor_slot). Looked for before the compute stream has
* passed their barriers, the slots of the last few dispatches' swaps are not free yet, and a
* donor finds nowhere to go. Nothing goes on the compute stream from this drain to the end of
* the recall, which issues only the mover's own copies. */
RAD_TRY(rad_stream_sync(compute_));
RAD_TRY(retire(heat));
/* EVERY UNIT PAST THE LOAN GOES BACK TO ITS HOST COPY, which is a change of address -- or,
* for a donor (donor_slot), which has none, it moves: into a free budgeted slot, a copy inside
* the card, or else back across the link into a free pool slot. One of the two is free for
* every donor (donor_slot says why). Nothing is published until the copies have landed. */
* every donor once the quarantine is empty (donor_slot says why). Nothing is published until
* the copies have landed.
*
* A DONOR WITH NOWHERE TO GO STAYS WHERE IT IS, and the recall still finishes: every other
* slot is given back and every moved donor published, so the loan stops short only by that
* unit's slot, and a later recall or balance() moves it. Stopping at it instead would leave
* the slots already taken off their units held by nothing, for the life of the process. */
std::vector<std::pair<size_t, int64_t>> freed;
std::vector<int32_t> moved;
int stuck = 0;
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
UnitState& us = unit_[(size_t)u];
if (us.klass < 0 || us.slab_slot < 0) continue;
@@ -1477,16 +1493,11 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
cp.slab.add_free(to);
to = -1;
}
const int64_t g = to < 0 ? cp.pool.take() : -1;
if (to >= 0) {
RAD_TRY(rad_memcpy_async(cp.slot_ptr(to), cp.slot_ptr(from), us.bytes, mover_));
us.slab_slot = to;
} else {
const int64_t g = cp.pool.take();
if (g < 0) {
RAD_ERR("mover: unit %d gave its host copy away and neither a budgeted slot nor "
"a pool slot is free to move it to", (int)u);
return RAD_E_STATE;
}
} else if (g >= 0) {
RAD_TRY(rad_memcpy_async((char*)cp.pool_base + g * cp.stride, cp.slot_ptr(from),
us.bytes, mover_));
us.pool_slot = g;
@@ -1499,6 +1510,9 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
heat->set_tier(u, Tier::HostPinned);
heat->set_busy(u, false);
}
} else {
++stuck;
continue;
}
--cp.n_donated;
++stats_.relocated;
@@ -1525,9 +1539,9 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
}
/* AND NO KERNEL STILL NAMES ONE. The compute stream is the only reader of the slab -- the
* quarantine barrier rests on the same fact -- so once it has drained, nothing already issued
* can reach a slot past the loan, and everything issued from here reads the host copies. */
RAD_TRY(rad_stream_sync(compute_));
* quarantine barrier rests on the same fact -- and it drained above with nothing issued since,
* so nothing can reach a slot past the loan, and everything issued from here reads the host
* copies. */
for (const auto& f : freed) pools_[f.first].slab.add_free(f.second);
/* EVERY RECORD WAITING ON ONE OF THOSE SLOTS IS DONE WAITING: its barrier is behind the
@@ -1550,6 +1564,14 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
m.slab_slot = m.pool_slot = m.to_slot = -1;
}
count_flex();
if (stuck > 0) {
stats_.stranded += (uint64_t)stuck;
RAD_ERR("mover: %d unit(s) that gave their host copy away found no free slot to move to; "
"the %s loan stops at %lld instead of %lld until they move", stuck,
lender == kLendKV ? "KV" : "arena", (long long)loan_held(lender),
(long long)loan_[lender]);
return RAD_E_FULL;
}
if (loan_held(lender) > loan_[lender]) {
RAD_ERR("mover: recalled the %s loan to %lld and a slot at %lld is still held",
lender == kLendKV ? "KV" : "arena", (long long)loan_[lender],
@@ -1719,8 +1741,9 @@ std::string Mover::report() const {
(unsigned long long)stats_.starved_pool, (unsigned long long)stats_.quarantined);
if (stats_.donated)
s += fmt(" %llu host copies given by lent units to budgeted victims, %llu such units moved "
"by a recall\n",
(unsigned long long)stats_.donated, (unsigned long long)stats_.relocated);
"by a recall, %llu left past one with no free slot\n",
(unsigned long long)stats_.donated, (unsigned long long)stats_.relocated,
(unsigned long long)stats_.stranded);
if (stats_.ssd_reads)
s += fmt(" file tier: %llu demand reads (%.2f GiB), each a blocking pread in the middle "
"of a dispatch. Raise --host-pool-mib.\n",
+3 -2
View File
@@ -422,8 +422,9 @@ struct MoverStats {
uint64_t dropped = 0;
/* Host copies a unit in a lent slot gave to a budgeted victim that had no pool slot to go to
* (Mover::donor_slot), and such units moved rather than dropped when their loan was recalled
* or shrank. */
uint64_t donated = 0, relocated = 0;
* or shrank. `stranded` counts the recalls that found no free slot for one of them: it stayed
* past the loan until a later recall or balance() moved it. */
uint64_t donated = 0, relocated = 0, stranded = 0;
uint64_t ssd_reads = 0, ssd_bytes = 0;
/* The prefill stager's copies (stage_units): layers staged, units and bytes copied, and
* pooled units a buffer had no room left for -- those were read across the link in place.
+63 -5
View File
@@ -80,7 +80,7 @@ int strategy_parse(const char* s, Strategy* out) {
Budgets Budgets::from(const Config& c) {
Budgets b;
b.vram_weights = c.vram_weights_mib * 1024 * 1024;
b.host_pool = (c.host_pool_mib + c.embedding_host_mib) * 1024 * 1024;
b.host_pool = c.host_pool_total_mib() * 1024 * 1024;
b.ssd = c.weights_disk_tier;
return b;
}
@@ -146,7 +146,8 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
/* build_units: a model-level weight is its own unit, everything else groups by the declared
* (layer, expert). Ordered, for the same reason build_units is. */
struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false;
bool emb = false, ngram = false, host = true, direct = true; };
bool emb = false, ngram = false, host = true, direct = true;
int access = -1; };
std::map<std::pair<int32_t, int32_t>, size_t> by_group;
std::vector<U> units;
@@ -177,6 +178,9 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
if (w < device_ok.size() && !device_ok[w]) mu.mapped = true;
if (!weight_file_direct(wi, prog.ctx.world_size)) mu.direct = false;
if (w < host_ok.size() && !host_ok[w]) mu.host = false;
/* build_units: the group's strongest access class, which says whether it is a tower's. */
if (mu.access < 0 || access_strength(wi.decl.access) > access_strength(mu.access))
mu.access = wi.decl.access;
/* The placement flags' tables: model-level, so the unit is this one weight. */
if (layer < 0) {
mu.emb = is_embedding_table(prog, w);
@@ -198,6 +202,8 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
if (mu.emb && !mu.mapped) out->embedding += b;
if (mu.ngram) out->ngram += b;
if (mu.ngram && !mu.mapped) out->ngram_device = true;
/* pin_towers moves an encoder tower's unit out of the statics on the same test. */
if (mu.access == RAD_ACCESS_PER_REQUEST && !mu.mapped && mu.expert < 0) out->tower += b;
/* pin_mapped: an n-gram table a device kernel reads stays off the card unless it was
* placed in VRAM. */
if (mu.mapped || (mu.ngram && ngram != TablePlacement::Vram)) out->mapped += b;
@@ -1073,7 +1079,7 @@ void Planner::finish(const Program& prog, Plan* p) {
pl.reason = mu.reason;
pl.bytes = weight_bytes(prog.weights[w]);
p->totals.bytes[(int)mu.tier] += pl.bytes;
if (mu.host_forced) p->embedding_host_used += pl.bytes;
if (mu.host_forced) p->forced_host_used += pl.bytes;
}
}
}
@@ -1142,6 +1148,53 @@ int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) cons
return rc;
}
/* --vision-tower-placement ram: EVERY UNIT OF AN ENCODER TOWER goes to the pinned host pool before
* any strategy runs, as the embedding does, at the DeviceZeroCopy site: the encoder's kernels read
* the weights over the link in place, once an image or a clip, and a text-only request never
* touches them. A tower's unit is one whose every weight the architecture declared read once per
* request (RAD_ACCESS_PER_REQUEST) -- the test weight_footprint counted out of the statics with,
* so the budget the card was split by is the one spent here. The test is the access class and not
* the unit's level: a tower is model-level weights (a stem, a merger) and a layer unit a block. */
int Planner::pin_towers(const Config& cfg, Plan* p) const {
if (cfg.tower_resolved != TablePlacement::Ram) return RAD_OK;
auto tower = [](const MoveUnit& mu) {
return mu.access == RAD_ACCESS_PER_REQUEST && mu.expert < 0 && mu.tier != Tier::Mapped &&
!mu.host_forced;
};
int64_t need = 0, n = 0;
for (const MoveUnit& mu : p->units)
if (tower(mu)) { need += mu.slot_bytes; ++n; }
/* Engine::plan resolves Ram only where weight_footprint found a tower with this same test. */
if (!n) {
RAD_ERR("placement: --vision-tower-placement ram, and this rank's program has no weight it "
"reads once per request");
p->notes.push_back("--vision-tower-placement ram: no encoder tower to place");
return RAD_E_STATE;
}
if (need > p->host_budget) {
RAD_ERR("placement: --vision-tower-placement ram: the encoder towers need %s of the pinned "
"host pool and %s of it is left%s", humanb(need).c_str(),
humanb(p->host_budget).c_str(),
p->file_stage_reserve ? " after the file tier's staging" : "");
p->notes.push_back(fmt("--vision-tower-placement ram: the encoder towers (%s) do not fit "
"the host pool", humanb(need).c_str()));
return RAD_E_NOMEM;
}
for (MoveUnit& mu : p->units) {
if (!tower(mu)) continue;
p->host_budget -= mu.slot_bytes;
p->tower_host_bytes += mu.slot_bytes;
mu.tier = Tier::HostPinned;
mu.site = Site::DeviceZeroCopy;
mu.movable = false;
mu.host_forced = true;
mu.reason = "--vision-tower-placement ram; read over the link in place";
}
RAD_INFO("placement: the encoder towers, %lld units (%s), in the pinned host pool, read in place "
"(--vision-tower-placement ram)", (long long)n, humanb(need).c_str());
return RAD_OK;
}
/* ------------------------------------------------------------------ plan */
int Planner::plan(Plan* out) {
if (!out || !in_.program || !in_.config) return RAD_E_INVAL;
@@ -1216,7 +1269,9 @@ int Planner::plan(Plan* out) {
}
/* NOT a RAD_TRY: a refusal still leaves `out` filled in far enough to print. */
const int hrc = pin_embedding(prog, cfg, out);
int hrc = pin_embedding(prog, cfg, out);
const int trc = pin_towers(cfg, out);
if (hrc >= 0) hrc = trc;
int rc = assign(out);
enforce_op_site_agreement(prog, out);
@@ -1329,7 +1384,7 @@ std::string Plan::report(const Program& prog) const {
humanb(totals.bytes[(int)Tier::VRAM]).c_str());
s += fmt(" host pinned %12s %12s\n",
host_budget > 0 ? humanb(host_budget).c_str() : "none",
humanb(totals.bytes[(int)Tier::HostPinned] - embedding_host_used).c_str());
humanb(totals.bytes[(int)Tier::HostPinned] - forced_host_used).c_str());
if (totals.bytes[(int)Tier::HostPageable])
s += fmt(" host pageable %12s %12s\n", "-",
humanb(totals.bytes[(int)Tier::HostPageable]).c_str());
@@ -1354,6 +1409,9 @@ std::string Plan::report(const Program& prog) const {
if (embedding_host_bytes)
s += fmt(" embedding %12s %12s (--embedding-placement ram, pinned, read in place)\n",
"-", humanb(embedding_host_bytes).c_str());
if (tower_host_bytes)
s += fmt(" encoder tower %12s %12s (--vision-tower-placement ram, pinned, read in place)\n",
"-", humanb(tower_host_bytes).c_str());
if (ngram_copy_bytes)
s += fmt(" n-gram copy %12s %12s (--ngram-placement ram, %s, filled at load)\n",
"-", humanb(ngram_copy_bytes).c_str(),
+15 -8
View File
@@ -95,10 +95,12 @@ struct MoveUnit {
Site site = Site::Device;
int32_t slab_slot = -1;
bool movable = false; /* may the heat engine relocate it after load */
bool host_forced = false; /* --embedding-placement ram put it in the pinned pool */
bool host_forced = false; /* a placement flag put it in the pinned pool: the embedding's
* or the encoder tower's */
/* PLACED BEFORE ANY STRATEGY RAN, so every assignment pass skips it and no VRAM total counts
* it: the mapped tier (no device kernel can read it) and --embedding-placement ram. */
* it: the mapped tier (no device kernel can read it), --embedding-placement ram and
* --vision-tower-placement ram. */
bool preplaced() const { return tier == Tier::Mapped || host_forced; }
const char* reason = "fits in vram"; /* a fixed string, so the report never guesses */
@@ -274,11 +276,13 @@ public:
int64_t vram_budget = 0, host_budget = 0;
int64_t file_stage_reserve = 0;
int64_t file_windows = 0; /* the read windows' part of it */
/* --embedding-placement ram: the pool slots taken out of --host-pool-mib before any strategy
* ran, like the file staging above, and reported beside it rather than among the pooled units.
* `embedding_host_used` is the same tables' weight bytes, the unit the tier totals count in. */
/* --embedding-placement ram and --vision-tower-placement ram: the pool slots each flag's
* units took before any strategy ran, like the file staging above, and reported beside it
* rather than among the pooled units. `forced_host_used` is both flags' weight bytes, the unit
* the tier totals count in, which the pooled weights' figures leave out. */
int64_t embedding_host_bytes = 0;
int64_t embedding_host_used = 0;
int64_t tower_host_bytes = 0;
int64_t forced_host_used = 0;
/* --ngram-placement ram: the n-gram tables the load phase copies into host memory. They stay
* on the mapped tier as far as every pool is concerned; this is what the copy costs in RAM.
* `ngram_copy_card` says which copy: pinned memory a device kernel reads in place over the
@@ -379,6 +383,7 @@ private:
void build_units(const Program& prog, Plan* p);
void pin_mapped(const Program& prog, Plan* p);
int pin_embedding(const Program& prog, const Config& cfg, Plan* p) const;
int pin_towers(const Config& cfg, Plan* p) const;
void build_classes(Plan* p);
void rank_units(Plan* p, std::vector<int32_t>* order) const;
int assign(Plan* p);
@@ -430,11 +435,13 @@ struct WeightFootprint {
bool routed = false; /* a layer has experts: the file tier's read windows */
int64_t mapped = 0; /* no device kernel can read them; they never enter a pool at all */
int64_t hosted = 0; /* --embedding-placement ram: in the pinned host pool, off the card */
/* The tables the two placement flags move, wherever the buckets above count them: `embedding`
/* The tables the placement flags move, wherever the buckets above count them: `embedding`
* is inside statics or hosted, `ngram` inside statics when a device kernel reads it and it is
* placed in VRAM, inside mapped otherwise. */
* placed in VRAM, inside mapped otherwise. `tower` is the encoder towers' units, every weight
* of which the architecture declared read once per request, inside statics. */
int64_t embedding = 0;
int64_t ngram = 0;
int64_t tower = 0;
/* A device kernel reads the n-gram table, so it can be on the card or read over the link from
* pinned host memory; without one only the host gather reads it, from RAM or the container. */
bool ngram_device = false;
+19 -12
View File
@@ -800,6 +800,17 @@ struct Config {
* a rank, ON TOP OF host_pool_mib -- so the table never takes the experts' share of the pool,
* and a dense model that has no pool still has a place for it. */
int64_t embedding_host_mib = 0;
/* --vision-tower-placement: where a model's encoder towers live. A tower is every weight its
* architecture declared read once per request (RAD_ACCESS_PER_REQUEST) -- the vision tower,
* and the audio encoder where a model has one -- and Vram, the default, keeps it on the card
* with the rest. Ram pins it in host memory of its own, `tower_host_mib` a rank on top of
* host_pool_mib as the embedding's is, and the encoder's kernels read it over the link in
* place, once an image: what it held on the card goes to the KV cache. */
TablePlacement tower_placement = TablePlacement::Vram;
TablePlacement tower_resolved = TablePlacement::Vram;
int64_t tower_host_mib = 0;
/* The pinned host pool one rank allocates: --host-pool-mib and the tables placed beside it. */
int64_t host_pool_total_mib() const { return host_pool_mib + embedding_host_mib + tower_host_mib; }
bool deterministic = false;
int64_t checkpoint_interval = 2048; /* linear-state checkpoints (spec §7.3) */
/* HOW MANY LINEAR-STATE SNAPSHOTS THE SERVER MAY HOLD AT ONCE -- a CAP and not a charge.
@@ -822,23 +833,19 @@ struct Config {
* live and the least valuable thing in it once the session stops. With a host tier, a
* finished conversation is COPIED to host memory at once and its VRAM given up the moment
* something wants it -- the expert slab's loan, or a request -- so no threshold decides when
* it leaves the card: the copy makes leaving free. With a disk tier every host copy is copied
* on to disk too, so a full host tier gives the oldest slots up for nothing in the same way.
* it leaves the card: the copy makes leaving free. A full host tier drops its least recently
* used entries. Nothing is written to a drive.
*
* Moving is worth it because the alternative is a re-prefill. Recovering a 200K-token turn
* costs a copy over PCIe; recomputing it costs minutes. The two are not the same order.
*
* CAPACITY IS WHAT TURNS THEM ON. Nothing is copied until the host tier has a size: a tier of
* zero bytes holds nothing, so the feature is off until an operator says how much memory and
* how much disk it may have. */
int64_t prefix_cache_host_mib = 0; /* the host tier's size. 0 is off */
int64_t prefix_cache_disk_mib = 0; /* the disk tier's size. 0 is off */
/* WHERE THE DISK TIER LIVES, and a flag of its own rather than a second meaning for
* --weights-disk-tier. That one is the WEIGHT planner's permission to place weights on the file
* tier -- it reads the container, needs pinned staging, and refuses startup without it. The
* two have nothing in common but the word "disk", and a shared flag would make asking for a KV
* cache also ask for weight offload, which fails for want of a host pool nobody wanted. */
std::string prefix_cache_dir;
* zero bytes holds nothing, so the feature is off until an operator says how much memory it
* may have. */
int64_t prefix_cache_mib = 0; /* the host tier's size. 0 is off */
/* HOW LONG AN UNUSED CONVERSATION IS KEPT, in seconds, whichever tier holds it: VRAM, host
* memory, and its snapshots. 0 keeps everything until the memory is wanted. */
int64_t prefix_cache_ttl = 3600;
/* THE CACHE ALWAYS LENDS AND THERE IS NO FLAG FOR IT. It keeps the blocks it is using plus a
* buffer it derives, and lends the rest to the expert plane at the addresses it already owns;
+3
View File
@@ -25,6 +25,9 @@ void log_set_level(Log l);
Log log_level();
void log_emit(Log l, const char* file, int line, const char* fmt, ...)
__attribute__((format(printf, 4, 5)));
/* When the last line was written (rad_mono_ns), whatever its level: what StallWatch reads as
* progress. 0 before the first. */
uint64_t log_last_line_ns();
/* WHICH RANK IS SPEAKING.
*
+5 -212
View File
@@ -1,6 +1,5 @@
#include "runtime/tierexec.h"
#include "mem/sstier.h"
#include "rad_internal.h"
#include <algorithm>
@@ -16,19 +15,18 @@ TierExec::~TierExec() { close(); }
* maintenance path -- a selector call between steps would be affordable and is still the wrong
* shape: the kernel that serves a transfer must not be able to change underneath a half-finished
* batch. */
int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk,
int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
const std::vector<int32_t>& groups, int max_batch, int64_t max_copy,
int64_t max_chain, bool leader, int device, int64_t slot_off,
const HostArena* ck_store, RadStream shared) {
RadStream shared) {
close();
if (!reg || !kv || !tiers || groups.empty() || max_batch <= 0 || max_copy <= 0 ||
max_chain <= 0)
return RAD_E_INVAL;
reg_ = reg; kv_ = kv; tiers_ = tiers; disk_ = disk; leader_ = leader; device_ = device;
reg_ = reg; kv_ = kv; tiers_ = tiers; leader_ = leader; device_ = device;
max_batch_ = max_batch; max_copy_ = max_copy; max_chain_ = max_chain;
slot_off_ = slot_off;
slot_bytes_ = tiers->entry_bytes();
ck_store_ = ck_store && ck_store->enabled() ? ck_store : nullptr;
shared_ = shared;
RAD_TRY(rad_dev_set(device_));
@@ -139,10 +137,9 @@ void TierExec::close() {
order_.clear();
verify_pending_.clear();
entry_bytes_ = 0;
ck_store_ = nullptr;
enabled_ = false;
leader_ = false;
reg_ = nullptr; kv_ = nullptr; tiers_ = nullptr; disk_ = nullptr;
reg_ = nullptr; kv_ = nullptr; tiers_ = nullptr;
report_.clear();
}
@@ -155,7 +152,7 @@ void TierExec::close() {
* device side built at bringup, on a two-card R9700 Flash-Next server at 200K context:
*
* no tiers 20.54 ms/step collect 14.66
* tiers on, 512 MiB host arena, no disk 33.94 ms/step collect 26.78
* tiers on, 512 MiB host arena 33.94 ms/step collect 26.78
* tiers on, idle threshold a day -- NOTHING EVER MOVED 33.88 ms/step collect 26.66
*
* In the third line not one byte crosses the link, and the step is still 65% longer. The cost is
@@ -536,74 +533,6 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
return st;
}
int TierExec::fence(RadEvent* out, RadStream on) {
*out = nullptr;
if (!enabled_ || (!on && !stream_)) return RAD_OK;
RAD_TRY(rad_dev_set(device_));
RadEvent e = nullptr;
RAD_TRY(rad_event_create(&e));
const int st = rad_event_record(e, on ? on : stream_);
if (st != RAD_OK) { rad_event_destroy(e); return st; }
*out = e;
return RAD_OK;
}
/* ------------------------------------------------------------------ the disk store */
void TierExec::run_disk(std::vector<TierJob>& jobs, std::vector<char>* ok) {
ok->assign(jobs.size(), 1);
for (size_t i = 0; i < jobs.size(); ++i) (*ok)[i] = run_write(jobs[i]) ? 1 : 0;
}
bool TierExec::run_write(TierJob& j) {
if (j.kind != TierJob::Kind::ToDisk) return true; /* the drops move nothing */
bool ok = true;
/* THE WHOLE SLOT, every rank's shard of it, because a disk entry read back must be able to
* serve all of them. A job may carry only the snapshot half, when the blocks are already on
* disk or their write went out earlier. */
if (j.host_slot >= 0) {
const void* src = tiers_->arena().at(j.host_slot);
ok = disk_ && src && disk_->put_block(j.key, nullptr, 0, src, slot_bytes_) == RAD_OK;
}
if (j.ck_slot >= 0) {
const void* cs = ck_store_ ? ck_store_->at(j.ck_slot) : nullptr;
/* A snapshot store that was never opened -- no room for one inside the disk cap -- refuses
* this, which is the right answer and not an error: the slot stays the only copy, as it
* was. */
j.ck_ok = disk_ && cs &&
disk_->put_checkpoint(j.key, j.ck_pos, cs, ck_store_->slot_bytes()) == RAD_OK;
}
return ok;
}
void TierExec::run_fetch(std::vector<TierJob>& jobs, std::vector<char>* ok) {
ok->assign(jobs.size(), 1);
std::vector<BlockHash> keys;
std::vector<void*> dst;
std::vector<size_t> at;
for (size_t i = 0; i < jobs.size(); ++i) {
TierJob& j = jobs[i];
j.started = true;
if (j.host_slot < 0) continue; /* only the snapshot half */
keys.push_back(j.key);
dst.push_back(tiers_->arena().at(j.host_slot));
at.push_back(i);
}
if (!keys.empty()) {
std::vector<char> got(keys.size(), 0);
if (disk_) (void)disk_->get_blocks(keys.data(), (int64_t)keys.size(), dst.data(),
slot_bytes_, got.data());
for (size_t k = 0; k < keys.size(); ++k) (*ok)[at[k]] = got[k];
st_.bytes_in += (int64_t)keys.size() * slot_bytes_;
}
for (TierJob& j : jobs) {
if (!j.ck_want || j.ck_slot < 0) continue;
void* cs = ck_store_ ? ck_store_->at(j.ck_slot) : nullptr;
j.ck_ok = disk_ && cs &&
disk_->get_checkpoint(j.key, j.ck_pos, cs, ck_store_->slot_bytes()) == RAD_OK;
}
}
/* ------------------------------------------------------------------ the report */
void TierExec::report_pass(std::vector<TierJob>& jobs, const std::vector<char>& ok,
@@ -624,11 +553,6 @@ void TierExec::report_pass(std::vector<TierJob>& jobs, const std::vector<char>&
}
tiers_->report(j, good, now_ns);
}
/* STORE SLOTS THE TIERS HAD BEEN KEEPING: a write that read one the cache let go of, or a
* read nothing took. The disk thread is done with them -- these come only from reports. */
std::vector<int32_t> frees;
tiers_->take_checkpoint_frees(&frees);
for (int32_t s : frees) kv_->free_checkpoint(s);
}
bool TierExec::plan_promote(const BlockHash& key, TierJob* out) {
@@ -636,135 +560,4 @@ bool TierExec::plan_promote(const BlockHash& key, TierJob* out) {
return tiers_->plan_promote(key, out);
}
/* ------------------------------------------------------------------ TierIO */
TierIO::~TierIO() { stop(); }
void TierIO::start(TierExec* leader) {
stop();
x_ = leader;
stop_ = false;
th_ = std::thread([this] { loop(); });
}
void TierIO::stop() {
{
std::lock_guard<std::mutex> lk(mu_);
stop_ = true;
}
cv_.notify_all();
if (th_.joinable()) th_.join();
has_work_ = has_done_ = false;
work_.clear();
done_.clear();
ok_.clear();
work_at_ = 0;
fetch_q_.clear();
fetch_done_.clear();
}
bool TierIO::submit(std::vector<TierJob>&& jobs, std::vector<RadEvent>&& fences) {
{
std::lock_guard<std::mutex> lk(mu_);
if (has_work_ || has_done_ || !th_.joinable()) return false;
work_ = std::move(jobs);
work_fences_ = std::move(fences);
ok_.assign(work_.size(), 1);
work_at_ = 0;
has_work_ = true;
}
cv_.notify_all();
return true;
}
bool TierIO::submit_fetch(Fetch&& f) {
{
std::lock_guard<std::mutex> lk(mu_);
if (!th_.joinable()) return false;
fetch_q_.push_back(std::move(f));
}
cv_.notify_all();
return true;
}
bool TierIO::take_fetch(Fetch* out) {
std::lock_guard<std::mutex> lk(mu_);
if (fetch_done_.empty()) return false;
*out = std::move(fetch_done_.front());
fetch_done_.pop_front();
return true;
}
bool TierIO::take(std::vector<TierJob>* jobs, std::vector<char>* ok,
std::vector<RadEvent>* fences) {
std::lock_guard<std::mutex> lk(mu_);
if (!has_done_) return false;
*jobs = std::move(done_);
*ok = std::move(ok_);
if (fences) *fences = std::move(done_fences_);
done_.clear();
done_fences_.clear();
ok_.clear();
has_done_ = false;
return true;
}
bool TierIO::busy() const {
std::lock_guard<std::mutex> lk(mu_);
return has_work_ || has_done_;
}
void TierIO::loop() {
for (;;) {
Fetch f;
bool read = false;
size_t i = 0;
{
std::unique_lock<std::mutex> lk(mu_);
cv_.wait(lk, [this] { return stop_ || !fetch_q_.empty() || (has_work_ && !has_done_); });
if (stop_) return;
if (!fetch_q_.empty()) {
f = std::move(fetch_q_.front());
fetch_q_.pop_front();
read = true;
} else {
i = work_at_;
}
}
if (read) {
/* NOT A BYTE UNTIL EVERY RANK'S RESTORES THAT COULD READ THESE SLOTS HAVE RUN. A fence
* that cannot be waited on leaves the read unstarted, and the records stay on disk. */
bool fenced = true;
for (RadEvent e : f.fences) if (e && rad_event_sync(e) != RAD_OK) fenced = false;
if (fenced) x_->run_fetch(f.jobs, &f.ok);
else f.ok.assign(f.jobs.size(), 0);
std::lock_guard<std::mutex> lk(mu_);
fetch_done_.push_back(std::move(f));
continue;
}
/* NOT A BYTE UNTIL THE COPIES THAT FILLED THE SLOTS HAVE LANDED, once a batch. A fence
* that cannot be waited on fails the batch, and every record keeps what it had. */
bool fenced = true;
if (i == 0)
for (RadEvent e : work_fences_) if (e && rad_event_sync(e) != RAD_OK) fenced = false;
bool ok = false;
if (fenced) ok = i < work_.size() ? x_->run_write(work_[i]) : true;
std::lock_guard<std::mutex> lk(mu_);
if (!fenced) {
ok_.assign(work_.size(), 0);
work_at_ = work_.size();
} else {
if (i < ok_.size()) ok_[i] = ok ? 1 : 0;
work_at_ = i + 1;
}
if (work_at_ >= work_.size()) {
done_ = std::move(work_);
done_fences_ = std::move(work_fences_);
work_.clear();
work_fences_.clear();
has_work_ = false;
has_done_ = true;
}
}
}
} /* namespace rad */
+6 -96
View File
@@ -16,9 +16,6 @@
* - a restore in makes the COMPUTE stream wait for it, so the step that reads the restored
* blocks runs after they land without the host having waited for anything.
*
* The disk store is the one part that is synchronous by nature, and it runs on a thread of its own
* (TierIO below), so the engine thread never waits on a file either.
*
* ============================== THE TRANSFER, AND WHY IT IS SHAPED THIS WAY ====================
*
* A paged pool is LAYER-MAJOR: layer l of group g owns `[base + l*layer_stride, + layer_stride)`
@@ -44,20 +41,13 @@
#include "plugin/registry.h"
#include "rad_core.h"
#include <functional>
#include <condition_variable>
#include <cstdint>
#include <deque>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <vector>
namespace rad {
class SSDTier;
class TierExec {
public:
~TierExec();
@@ -68,10 +58,10 @@ public:
* `max_batch` is the staging buffer in entries, `max_copy` the most entries one copy out may
* carry, and `max_chain` the longest chain one restore brings back -- the index buffers are
* sized from the last two. */
int configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk,
int configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
const std::vector<int32_t>& groups, int max_batch, int64_t max_copy,
int64_t max_chain, bool leader, int device, int64_t slot_off,
const HostArena* ck_store, RadStream shared);
RadStream shared);
void close();
bool enabled() const { return enabled_; }
std::string report() const { return report_; }
@@ -115,34 +105,14 @@ public:
/* ---------------- restore ----------------
*
* Enqueue a chain of ToDevice jobs, in chain order, and make `compute` wait for them. Every
* job's bytes are in host memory -- a disk entry was read in first (run_fetch) -- so nothing
* here waits on a file. The leader chooses every block first, recalling the loan for the
* Enqueue a chain of ToDevice jobs, in chain order, and make `compute` wait for them. The
* leader chooses every block first, recalling the loan for the
* whole chain at once; a chain the pool cannot hold is cut where the reservation ran out, and
* the jobs past the cut are left unstarted. `ok[i]` is whether job i was fully enqueued on
* this rank. */
int issue_restore(std::vector<TierJob>& jobs, RadStream compute, std::vector<char>* ok);
/* A MARK ON THIS RANK'S TRANSFER STREAM, after everything enqueued on it so far -- or on
* `on`, the rank's compute stream, when it is given. A restore reads host slots
* asynchronously, and a slot it is still reading may be given up and handed to a read off
* disk the moment the restore has reported; the IO thread waits for this mark before it
* writes into any slot it was handed. A snapshot's store slot is read and written by copies
* on the compute stream (KVManager::checkpoint_save), so a disk write or read of one waits
* for that stream's mark. Null when nothing was ever enqueued on the transfer stream. The
* caller owns the event. */
int fence(RadEvent* out, RadStream on = nullptr);
/* ---------------- the disk store (leader only; TierIO's thread) ---------------- */
void run_disk(std::vector<TierJob>& jobs, std::vector<char>* ok);
/* One ToDisk job; true when it was written. */
bool run_write(TierJob& j);
/* ToHost jobs: the blocks read in parallel into the host slots they were given, then the
* snapshots into their store slots. `ok[i]` is the blocks' result, `ck_ok` the snapshot's. */
void run_fetch(std::vector<TierJob>& jobs, std::vector<char>* ok);
/* Leader only. Gives back what a failed job held -- a restore's blocks -- reports every job to
* the policy, and frees the store slots a finished write or an unclaimed read was holding on
* the cache's behalf. `now_ns` is when the pass ran: a promotion is a use. */
/* Leader only. Gives back what a failed job held -- a restore's blocks -- and reports every
* job to the policy. `now_ns` is when the pass ran: a promotion is a use. */
void report_pass(std::vector<TierJob>& jobs, const std::vector<char>& ok, uint64_t now_ns);
/* A lookup hit off-device: the job that would bring it back, or false when the entry is not
@@ -209,14 +179,8 @@ private:
Registry* reg_ = nullptr;
KVManager* kv_ = nullptr;
IdleTiers* tiers_ = nullptr;
SSDTier* disk_ = nullptr;
std::vector<GroupInfo> gi_;
int64_t entry_bytes_ = 0;
/* ---- the linear half ----
* The engine's snapshot store, whose slots the disk thread writes out and reads back whole --
* every rank's shard of a snapshot together. Null on a model with no recurrent state, which
* is the whole of the "off" path here. */
const HostArena* ck_store_ = nullptr;
int max_batch_ = 0;
int64_t max_copy_ = 0;
int64_t max_chain_ = 0;
@@ -275,58 +239,4 @@ private:
Stats st_;
};
/* ------------------------------------------------------------------ the disk thread */
/* THE DISK STORE ON A THREAD OF ITS OWN. A host-to-disk move is a file write of the whole slot,
* and a pass that makes room for a conversation's worth of copies is hundreds of megabytes of it
* -- the engine thread would build no step for as long as the writes took. So a batch is handed
* over and collected later. The thread touches the host arena and the disk store and nothing
* else: every decision about the records is made before the hand-over and after the collection,
* on the engine thread, under the scheduler's lock.
*
* TWO KINDS OF WORK, AND THE READS GO FIRST. A write batch is the background copy to disk: one at
* a time, and the engine does not hand over the next until it has collected the last. A read
* batch is a conversation a request is waiting on (IdleTiers::plan_fetch), so reads queue in the
* order they were asked for and each one is taken ahead of whatever write is out -- between two
* of its jobs, not after the whole batch. */
class TierIO {
public:
~TierIO();
void start(TierExec* leader);
void stop();
/* False when a batch is already out. `fences` are waited on before the first job is written --
* a snapshot's store slot is filled by a copy on the compute stream (TierExec::fence) -- and
* come back with the batch from take(), still the caller's to destroy. */
bool submit(std::vector<TierJob>&& jobs, std::vector<RadEvent>&& fences = {});
/* The finished batch, when there is one. */
bool take(std::vector<TierJob>* jobs, std::vector<char>* ok,
std::vector<RadEvent>* fences = nullptr);
bool busy() const;
/* A read off disk. `tag` is the caller's (the request waiting on it); `fences` are waited on
* before the first byte is written (TierExec::fence) and stay the caller's to destroy. */
struct Fetch {
uint64_t tag = 0;
std::vector<TierJob> jobs;
std::vector<RadEvent> fences;
std::vector<char> ok;
};
/* False when the thread is not running. */
bool submit_fetch(Fetch&& f);
/* A finished read, oldest first. */
bool take_fetch(Fetch* out);
private:
void loop();
TierExec* x_ = nullptr;
std::thread th_;
mutable std::mutex mu_;
std::condition_variable cv_;
std::vector<TierJob> work_, done_;
std::vector<RadEvent> work_fences_, done_fences_;
std::vector<char> ok_;
size_t work_at_ = 0; /* the next write job; the thread's alone while has_work_ */
bool has_work_ = false, has_done_ = false, stop_ = false;
std::deque<Fetch> fetch_q_, fetch_done_;
};
} /* namespace rad */
+19 -20
View File
@@ -146,18 +146,13 @@ struct IPrefixCache {
* `blocks_out` receives the block ids per cached group, in cached_groups() order, ready for
* IKVManager::adopt. */
/* GIVE BACK WHATEVER THE TIERS HOLD FOR THIS PROMPT, before the lookup that would otherwise
* stop at it. `Wait` when part of it is still being read off disk: the request is not
* admitted this step -- the ones behind it may be -- and is asked again on the next. Admitting
* it anyway would stop its hit at the first entry not yet read, and the hit length is what
* its prefill is chunked against, so the same prompt would run different shapes depending on
* how far a read had got.
* stop at it.
*
* The scheduler calls it and must not know what a tier is: a restore allocates blocks and
* runs a device scatter, so it is the engine's to perform and is installed as a callable
* rather than reached through this header. A failure is not an error here -- it leaves a
* shorter prefix, and a shorter prefix is always safe. */
enum class Restore { Done, Wait };
virtual Restore restore(const Request&) { return Restore::Done; }
virtual void restore(const Request&) {}
/* A step's admissions begin: what the last step's lookups handed out has been read. */
virtual void begin_step() {}
/* KEEP THIS WAITING REQUEST'S CHAIN WHERE IT IS until release(). Called when an admission is
@@ -212,6 +207,9 @@ struct IPrefixCache {
* that has happened; this count rises first. */
virtual int64_t evictions() const = 0;
virtual int64_t ckpt_evictions() const = 0;
/* And what --prefix-cache-ttl took: not memory pressure, so not evictions. */
virtual int64_t expired() const { return 0; }
virtual int64_t ckpt_expired() const { return 0; }
/* WHAT IT IS HOLDING ON ITS OWN RIGHT NOW, in tokens of context, as against the counters
* above which are cumulative. A finished turn's blocks stay held so the next turn can reuse
@@ -237,9 +235,8 @@ struct IPrefixCache {
/* The state that reservation named is now IN its slot. A reservation is made when the chunk is
* PLANNED and the state exists only after the step that computes it, so a lookup in between
* would adopt a slot holding the previous tenant's history. Until this is called, the
* reservation is a promise and lookup will not offer it. `resume`: the deepest checkpoint this
* prompt gets, the one its next turn resumes from (Scheduler::last_checkpoint). */
virtual void commit_checkpoint(const Request& r, int64_t pos, bool resume) = 0;
* reservation is a promise and lookup will not offer it. */
virtual void commit_checkpoint(const Request& r, int64_t pos) = 0;
};
/* ------------------------------------------------------------------ block geometry */
@@ -367,9 +364,9 @@ struct PCBinding final : IPrefixCache {
}
/* Installed by the engine when the idle tiers are on; empty otherwise. */
std::function<Restore(const Request&)> restore_fn;
Restore restore(const Request& r) override {
return restore_fn ? restore_fn(r) : Restore::Done;
std::function<void(const Request&)> restore_fn;
void restore(const Request& r) override {
if (restore_fn) restore_fn(r);
}
void begin_step() override { m->begin_step(); }
void hold(const Request& r) override {
@@ -400,9 +397,9 @@ struct PCBinding final : IPrefixCache {
uint64_t lost_warned_ns_ = 0;
/* PRESSURE TAKES WHAT CAN LEAVE VRAM AND STAY, FIRST. An entry whose host copy has landed is
* dropped and kept (trim); a copy still on its way is landed and that entry dropped too; only
* what the tiers then still cannot take -- an arena with no room and a disk that has not caught
* up, or no tiers at all -- is erased, and an erase with the tiers on is said, because it is
* a conversation a later turn will prefill again. */
* what the tiers then still cannot take -- an arena with no room, or no tiers at all -- is
* erased, and an erase with the tiers on is said, because it is a conversation a later turn
* will prefill again. */
int64_t evict(int64_t n) override {
int64_t k = m->trim(n);
if (k < n && flush_fn && flush_fn()) k += m->trim(n - k);
@@ -415,8 +412,8 @@ struct PCBinding final : IPrefixCache {
if (now - lost_warned_ns_ >= 60ull * 1000000000ull) {
lost_warned_ns_ = now;
RAD_WARN("prefix cache: %lld entries erased with no copy off the card -- the host "
"tier had no room for them in time (--prefix-cache-host-mib, and the disk "
"behind it); radiance:prefix_cache_evictions_total counts every one",
"tier had no room for them in time (--prefix-cache-mib); "
"radiance:prefix_cache_evictions_total counts every one",
(long long)lost);
}
}
@@ -430,6 +427,8 @@ struct PCBinding final : IPrefixCache {
}
int64_t evictions() const override { return m->stats().evictions; }
int64_t ckpt_evictions() const override { return m->stats().ckpt_evictions; }
int64_t expired() const override { return m->stats().expired; }
int64_t ckpt_expired() const override { return m->stats().ckpt_expired; }
int64_t held_tokens() const override { return m->unshared_tokens(); }
int64_t next_checkpoint_after(int64_t p) const override { return m->next_checkpoint_after(p); }
@@ -448,8 +447,8 @@ struct PCBinding final : IPrefixCache {
return m->reserve_checkpoint(r.id, pos, prefix_hash(r, pos), slot_out);
}
void commit_checkpoint(const Request& r, int64_t pos, bool resume) override {
m->commit_checkpoint(prefix_hash(r, pos), resume);
void commit_checkpoint(const Request& r, int64_t pos) override {
m->commit_checkpoint(prefix_hash(r, pos));
}
private:
+1
View File
@@ -107,6 +107,7 @@ struct SchedMetrics {
* mean the pool cannot hold the working set and turn-2 latency is about to collapse. */
int64_t prefix_evictions = 0;
int64_t prefix_ckpt_evictions = 0;
int64_t prefix_expired = 0, prefix_ckpt_expired = 0; /* --prefix-cache-ttl */
/* WHAT THE CACHE IS HOLDING ON ITS OWN NOW, in tokens of context: the part of the pool that
* an eviction would actually free, because no live sequence is reading it. The pool figure
* above counts a held block whoever holds it, and on a server serving conversations most of
+32 -35
View File
@@ -120,25 +120,34 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
DraftController::Params dp;
dp.max_depth = cfg.n_spec;
/* THE ADAPTIVE WINDOW IS THE SERIAL DRAFTER'S POLICY (draft.h): it prices a draft as one more
* round of the head. A block drafter proposes its block in one pass and prompt lookup runs no
* pass at all, so for either the window stays fixed -- decided here, once, before any step
* has counted an acceptance, and said, because a flag that changes nothing reads exactly
* like a flag that made no difference. */
/* THE ADAPTIVE WINDOW (draft.h) prices a draft by what the step it adds to costs, measured.
* For a serial head that is a round of the head and a verify row. For a BLOCK drafter the
* block is proposed in one pass whatever is verified, but each verified draft is still a
* verify row -- and on a model whose verify streams weights per row, a MoE that reads the
* experts every row routes to, a row is not free: sixteen rows read ten times the experts one
* does. So a block drafter takes the same policy with its rounds fixed: each sequence verifies
* the first min(D, its stop) of the block, its stop from its own measured acceptance, and D
* from the measured step times. Deep where the text is predictable (code, JSON, greedy), a few
* drafts where it is not (prose at temperature 1, where a point-mass draft survives a position
* with probability p(x) and a fifteen-token chain dies after one or two). Prompt lookup runs
* no pass and keeps the fixed window, decided here, once, and said, because a flag that
* changes nothing reads exactly like a flag that made no difference. */
if (cfg.draft_window == DraftWindow::Adaptive) {
const RadDrafterDecl& dd = prog.drafter;
if (cfg.n_spec <= 0)
RAD_WARN("--draft-window adaptive: this deployment does not speculate "
"(--num-speculative-tokens %d), so there is no window to adapt", cfg.n_spec);
else if (dd.kind != RAD_DRAFT_SERIAL || dd.depth <= 0)
RAD_WARN("--draft-window adaptive: the window is fixed at %d with %s -- the adaptive "
"window prices the rounds of a serial draft head, which this deployment does "
"not run", cfg.n_spec,
dd.kind == RAD_DRAFT_BLOCK ? "a block drafter, which proposes its block in one "
"pass"
: "prompt lookup only");
else
else if ((dd.kind != RAD_DRAFT_SERIAL && dd.kind != RAD_DRAFT_BLOCK) || dd.depth <= 0)
RAD_WARN("--draft-window adaptive: the window is fixed at %d with prompt lookup only "
"-- the adaptive window prices draft passes and verify rows, and prompt "
"lookup runs no pass", cfg.n_spec);
else {
dp.adapt = true;
if (dd.kind == RAD_DRAFT_BLOCK)
RAD_INFO("--draft-window adaptive with a block drafter: the block of %d is "
"proposed whole, and each sequence verifies the first min(D, its stop) "
"of it", dd.depth);
}
}
RAD_TRY(draft_.configure(dp));
draft_est_.clear();
@@ -796,17 +805,6 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
return want;
}
/* THE DEEPEST CHECKPOINT A PROMPT OF `target` TOKENS GETS, asked of one at `pos`: no interval
* boundary is left before the target and no tail checkpoint will follow (plan_chunk's rules). It
* is the state the prompt's next turn resumes from. */
bool Scheduler::last_checkpoint(int64_t pos, int64_t target) const {
if (!geo_.checkpoints()) return false;
const int64_t I = geo_.checkpoint_interval;
if (geo_.window_ckpt) { const int64_t t = tail_checkpoint(target); return t > 0 && t <= pos; }
if ((pos / I + 1) * I <= target) return false;
return tail_checkpoint(target) <= pos;
}
/* THE TAIL CHECKPOINT OF A PROMPT OF `target` TOKENS, or -1: its last quantum boundary, past the
* first interval -- a shorter prompt is cheap to prefill again -- and only where it buys a quarter
* of an interval or more over the interval checkpoint below it, which is worth the extra step. */
@@ -975,7 +973,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
* honest shorter hit, but a shorter one. This is where a cold session gets its
* context back instead of re-prefilling it: it costs a copy, and the alternative
* costs a prefill. */
if (pc_->restore(r) == IPrefixCache::Restore::Wait) return kAdmitWait;
pc_->restore(r);
HitCap cap;
if (draft_refill_ > 0) {
cap.tokens = std::max<int64_t>(0, (int64_t)r.prompt.size() - draft_refill_);
@@ -1384,9 +1382,9 @@ const RadBatch* Scheduler::step() {
* blocks, so it will refuse a new one, and the front of the queue is now the request we just
* took them from. Probing would cost a lookup per step and admit nothing. */
if (!preempted_here) {
/* `at` walks the queue and `took_` is what it admitted: a request waiting on a read off
* disk stays where it is and the one behind it is asked, so the queue is compacted after
* the walk rather than cut at its front. */
/* `at` walks the queue and `took_` is what it admitted: a request whose media is not
* encoded yet stays where it is and the one behind it is asked, so the queue is compacted
* after the walk rather than cut at its front. */
took_.clear();
size_t at = 0;
while (at < waiting_.size() &&
@@ -1410,8 +1408,8 @@ const RadBatch* Scheduler::step() {
continue;
}
/* ITS MEDIA FIRST. A request whose items are not encoded keeps its place and the one
* behind it is asked, exactly as for a context still being read off disk; the engine
* runs the encoder before the next step (encodes_pending). */
* behind it is asked; the engine runs the encoder before the next step
* (encodes_pending). */
if (s.req->media && !media_ready(s)) { ++at; continue; }
/* One share left for the next request in the queue, when there is one and a slot
* for it (busy_cap). The embed path takes a whole input or nothing, so it is not
@@ -1422,7 +1420,6 @@ const RadBatch* Scheduler::step() {
? share_tok : 0;
admit_full_ = 0;
const int as = admit_one(s, budget, areserve);
if (as == kAdmitWait) { ++at; continue; }
if (as < 0) break; /* head of line: do not admit behind it */
if (admit_full_ > s.sched_tokens && capped_at < 0) {
capped_at = (int32_t)plan_.e.size();
@@ -1886,10 +1883,8 @@ int Scheduler::commit(const StepResult& res) {
* still holding the previous tenant's state. Stream ordering does the rest -- a later
* restore is enqueued on the same stream behind this save, so validity does not have to
* wait on the copy landing, only on it being issued. */
if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && pc_) {
const int64_t pos = (int64_t)e.ctx_len + e.ckpt_tok + 1;
pc_->commit_checkpoint(r, pos, last_checkpoint(pos, s.seq_len()));
}
if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && pc_)
pc_->commit_checkpoint(r, (int64_t)e.ctx_len + e.ckpt_tok + 1);
if (e.is_prefill) {
r.n_computed += e.n_tokens;
@@ -2749,6 +2744,8 @@ SchedMetrics Scheduler::metrics_locked() const {
if (pc_) { m.prefix_evictions = pc_->evictions();
m.prefix_ckpt_evictions = pc_->ckpt_evictions();
m.prefix_expired = pc_->expired();
m.prefix_ckpt_expired = pc_->ckpt_expired();
m.prefix_held_tokens = pc_->held_tokens(); }
m.attn_hit_rate = m.prompt_tokens
? (float)((double)m.attn_cached_tokens / (double)m.prompt_tokens) : 0.0f;
+3 -6
View File
@@ -463,8 +463,7 @@ public:
SchedMetrics observed_metrics() const;
int observed_requests(ReqStat* out, int max) const;
/* plan_chunk's checkpoint rules, asked after the fact (see the definitions). */
bool last_checkpoint(int64_t pos, int64_t target) const;
/* plan_chunk's tail-checkpoint rule (see the definition). */
int64_t tail_checkpoint(int64_t target) const;
/* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a
* token budget, and the checkpoint position it will land on (-1 for none). `keep_at` is the
@@ -759,13 +758,11 @@ private:
void preempt_back();
/* Give blocks back from the prefix cache until the pool has headroom again. */
void trim_prefix_cache();
/* RAD_OK, a negative status when the request cannot be admitted now -- nothing behind it is
* either -- or kAdmitWait when its context is still being read off disk and the next request
* may go ahead of it. */
/* RAD_OK, or a negative status when the request cannot be admitted now -- nothing behind it is
* either. */
/* `reserve`: tokens of the step to leave for the requests queued behind this one
* (--busy-prefill-chunk; busy_cap). 0 plans the chunk on the whole budget, as before. */
int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0);
static constexpr int kAdmitWait = 1;
/* The queue positions one step's admission took, kept to reuse the allocation. */
std::vector<size_t> took_;
+9 -15
View File
@@ -50,7 +50,7 @@ public:
* behind it still compiles. Every rank declares the same chain against the same hierarchy, so
* whether a stage resolved is not a per-rank fact and asking one of them is asking all. */
/* `tiers` is rank 0's IdleTiers, and it is given whether or not a tier can move anything:
* the object holds the session table either way, and a server with no --prefix-cache-host-mib is
* the object holds the session table either way, and a server with no --prefix-cache-mib is
* one whose every stored session is in VRAM rather than one with no sessions. Null only when
* there is no engine behind this at all. */
explicit SchedulerBridge(Scheduler* s, const Sampler* sampler = nullptr,
@@ -111,19 +111,14 @@ public:
TierCounters c;
if (!tiers_) return c;
const IdleTiers::Stats& s = tiers_->stats();
c.to_host = s.to_host; c.dropped = s.dropped; c.to_disk = s.to_disk;
c.promoted = s.promoted;
c.host_freed = s.host_freed; c.host_drops = s.host_drops; c.failures = s.failures;
c.fetched = s.fetched; c.ck_fetched = s.ck_fetched;
c.host_bytes = s.host_bytes; c.disk_bytes = s.disk_bytes;
c.ck_to_disk = s.ck_to_disk; c.ck_drops = s.ck_drops;
c.to_host = s.to_host; c.dropped = s.dropped; c.promoted = s.promoted;
c.host_drops = s.host_drops; c.failures = s.failures;
c.host_bytes = s.host_bytes;
c.restores = s.restores; c.restore_ns = s.restore_ns;
c.flushes = s.flushes; c.flush_ns = s.flush_ns;
c.ck_bytes = tiers_->ckpt_bytes();
c.ck_host_slots = tiers_->ckpt_slots();
c.ck_disk_slots = tiers_->ckpt_disk_slots();
c.ck_slots = tiers_->ckpt_slots();
c.host_on = tiers_->host_on();
c.disk_on = tiers_->disk_on();
return c;
}
@@ -133,8 +128,8 @@ public:
IdleTiers::Occupancy held;
const std::vector<IdleTiers::SessionInfo> v = tiers_->sessions(occ ? &held : nullptr);
if (occ) {
occ->host_bytes = held.host_bytes; occ->disk_bytes = held.disk_bytes;
occ->host_cap_bytes = held.host_cap_bytes; occ->disk_cap_bytes = held.disk_cap_bytes;
occ->host_bytes = held.host_bytes;
occ->host_cap_bytes = held.host_cap_bytes;
}
const uint64_t now = rad_mono_ns();
out->reserve(v.size());
@@ -149,11 +144,8 @@ public:
o.age_s = now > s.first_seen_ns ? (double)(now - s.first_seen_ns) / 1e9 : 0.0;
o.on_device = s.on_device;
o.on_host = s.on_host;
o.on_disk = s.on_disk;
o.moving = s.moving;
o.snapshots = s.snapshots;
o.snap_host = s.snap_host;
o.snap_disk = s.snap_disk;
o.snap_bytes = s.snap_bytes;
o.resume_tokens = s.resume_tokens;
out->push_back(std::move(o));
@@ -263,6 +255,8 @@ public:
* figure above the used one would draw a negative live share. */
o.kv_tokens_cached = std::min(m.prefix_held_tokens, o.kv_tokens_used);
o.prefix_ckpt_evictions = m.prefix_ckpt_evictions;
o.prefix_expired = m.prefix_expired;
o.prefix_ckpt_expired = m.prefix_ckpt_expired;
o.prefill_tps = m.prefill_tps;
o.decode_tps = m.decode_tps;
+26 -39
View File
@@ -52,8 +52,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
SessionOccupancy occ;
if (deps_.sched) deps_.sched->sessions(&v, &occ);
int64_t dev = 0, host = 0, disk = 0, bytes = 0;
int64_t shost = 0, sdisk = 0;
int64_t dev = 0, host = 0, bytes = 0;
int64_t snaps = 0;
json a = json::array();
for (const SessionStat& s : v) {
json e;
@@ -66,20 +66,16 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
e["age_s"] = s.age_s;
e["on_device"] = s.on_device;
e["on_host"] = s.on_host;
e["on_disk"] = s.on_disk;
e["moving"] = s.moving;
/* THE RECURRENT HALF. On a hybrid model a session's attention blocks are only part of
* what it needs back; the rest is its linear-state snapshots, which are a different size
* of object in a different store. Counted where the BYTES are: in the store in host
* memory, or on disk alone. */
* of object in a different store, in host memory. */
e["snapshots"] = s.snapshots;
e["snap_host"] = s.snap_host;
e["snap_disk"] = s.snap_disk;
e["snap_bytes"] = s.snap_bytes;
e["resume_tokens"] = s.resume_tokens;
a.push_back(std::move(e));
dev += s.on_device; host += s.on_host; disk += s.on_disk;
shost += s.snap_host; sdisk += s.snap_disk;
dev += s.on_device; host += s.on_host;
snaps += s.snapshots;
bytes += s.bytes;
}
o["sessions"] = std::move(a);
@@ -87,8 +83,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
* the blocks for it, so these per-session sizes overlap and adding them up over-counts -- on
* a server carrying long agent transcripts by more than an order of magnitude. The field
* names say so rather than pretending the sums are totals. */
o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host }, { "disk", disk } };
o["snapshots"] = { { "host", shost }, { "disk", sdisk } };
o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host } };
o["snapshots_sum_overlapping"] = snaps;
o["bytes_sum_overlapping"] = bytes;
const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{};
/* AND THE ONE FIGURE THAT IS NOT A SUM, because a view about what the conversations cost has
@@ -103,17 +99,14 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
{ "bytes_total", sm.kv_bytes_total } };
const IScheduler::TierCounters c =
deps_.sched ? deps_.sched->tier_counters() : IScheduler::TierCounters{};
o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped }, { "to_disk", c.to_disk },
{ "promoted", c.promoted }, { "host_freed", c.host_freed },
{ "host_drops", c.host_drops }, { "failures", c.failures },
{ "fetched", c.fetched } };
/* THE SNAPSHOT COUNTERS ARE NOT OPTIONAL ON A HYBRID MODEL, because a server that moves every
* block it has and no snapshots at all looks identical in the block counters to one where
* tiering works -- and the difference is a full linear replay on every restored session. */
o["snapshots_moved"] = { { "to_disk", c.ck_to_disk }, { "fetched", c.ck_fetched },
{ "drops", c.ck_drops }, { "bytes_each", c.ck_bytes },
{ "host_slots", c.ck_host_slots },
{ "disk_slots", c.ck_disk_slots } };
o["moved"] = { { "to_host", c.to_host }, { "dropped", c.dropped },
{ "promoted", c.promoted }, { "host_drops", c.host_drops },
{ "failures", c.failures } };
/* THE SNAPSHOT STORE, on a hybrid model: what one snapshot costs and how many the store
* holds. `bytes_each` is 0 on a model with no recurrent state. */
o["snapshot_store"] = { { "bytes_each", c.ck_bytes }, { "slots", c.ck_slots } };
/* WHAT --prefix-cache-ttl TOOK, entries and snapshots, from whichever tier held them. */
o["expired"] = { { "entries", sm.prefix_expired }, { "snapshots", sm.prefix_ckpt_expired } };
/* THE STEP THREAD'S TIME ON THE TIERS: every request waits through it. */
o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 },
{ "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } };
@@ -127,15 +120,14 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
/* WHETHER ANYTHING MOVES, which is not whether anything is STORED. A session is recorded
* whether or not it can be demoted, so a non-empty table says only that something is held;
* these say whether a tier exists that can move it. */
o["tiers"] = { { "host", c.host_on }, { "disk", c.disk_on } };
o["tiers"] = { { "host", c.host_on } };
/* WHAT IS OFF THE CARD, counted once -- see SessionOccupancy. */
o["occupancy"] = { { "host_bytes", occ.host_bytes }, { "disk_bytes", occ.disk_bytes },
{ "host_cap_bytes", occ.host_cap_bytes },
{ "disk_cap_bytes", occ.disk_cap_bytes } };
o["occupancy"] = { { "host_bytes", occ.host_bytes },
{ "host_cap_bytes", occ.host_cap_bytes } };
/* THE ATTENTION HIT RATE, for a model with no recurrent state, where it is the whole answer
* to how much of the prompt the cache served. On a hybrid model `linear.hit_rate` is. */
o["prefix_hit_rate"] = sm.prefix_hit_rate;
o["enabled"] = c.host_on || c.disk_on;
o["enabled"] = c.host_on;
return HttpResponse::json_body(200, json_dump(o));
}
@@ -695,7 +687,6 @@ th + th, td + td { padding-left:14px; }
.tbar > i { display:block; height:100%; }
.t-dev { background:#4ade80; } .tn-dev { color:#7fe0a3; }
.t-host { background:#60a5fa; } .tn-host { color:#8dbcfb; }
.t-disk { background:#a78bfa; } .tn-disk { color:#c4b5fd; }
/* The group that starts over is folded by default: it is a count first and rows second. */
details.sgrp > summary { list-style:none; cursor:pointer; }
details.sgrp > summary::-webkit-details-marker { display:none; }
@@ -1185,9 +1176,6 @@ nav button.on { color:var(--fg); background:var(--track); }
<div class="cell" id="s-hostcell"><div class="n" id="s-host">–<u></u></div>
<span class="cap">moved to host ram</span>
<span class="det" id="s-hostdet"></span></div>
<div class="cell" id="s-diskcell"><div class="n" id="s-disk">–<u></u></div>
<span class="cap">moved to disk</span>
<span class="det" id="s-diskdet"></span></div>
</div>
<section class="panel">
@@ -2838,7 +2826,7 @@ $("tab-model").addEventListener("click", () => show("model"));
* snapshot reuses nothing however many of its blocks are kept. On a model with no recurrent state
* the blocks are the whole answer and every stored token is reused. */
const reuseOf = (r, hybrid) => hybrid ? Math.min(r.resume_tokens || 0, r.tokens) : r.tokens;
const TIERS = [["dev", "on_device", "vram"], ["host", "on_host", "host"], ["disk", "on_disk", "disk"]];
const TIERS = [["dev", "on_device", "vram"], ["host", "on_host", "host"]];
function sessCols(tr, manyModels) {
tr.textContent = "";
@@ -2874,7 +2862,7 @@ function sessRow(r, hybrid, manyModels) {
read as three equal parts. The per-tier counts are blocks, and a block is the same number of
tokens in every tier, so the proportion is the proportion of its tokens. */
const wh = tr.appendChild(el("td", "l")), bar = wh.appendChild(el("span", "tbar"));
const held = r.on_device + r.on_host + r.on_disk, parts = [];
const held = r.on_device + r.on_host, parts = [];
for (const [k, f, name] of TIERS) {
if (!(r[f] > 0)) continue;
bar.appendChild(el("i", "t-" + k)).style.width = (100 * r[f] / held).toFixed(1) + "%";
@@ -2897,7 +2885,7 @@ async function loadSessions() {
return;
}
const rows = (s.sessions || []).slice().sort((x, y) => x.idle_s - y.idle_s);
const mv = s.snapshots_moved || {}, ln = s.linear || {};
const mv = s.snapshot_store || {}, ln = s.linear || {};
const pool = s.pool || {}, occ = s.occupancy || {};
/* The model has recurrent state if its snapshots have a size. */
const hybrid = mv.bytes_each > 0;
@@ -2913,13 +2901,12 @@ async function loadSessions() {
$("s-live").firstChild.nodeValue = cnt(live.length);
$("s-liveof").textContent = "of " + cnt(rows.length);
$("s-livedet").textContent = cold.length ? cnt(cold.length) + " start over" : "";
/* VRAM IN TOKENS, THE OTHER TIERS IN BYTES. The pool's token count is the context the card can
serve without a copy; the tiers off the card are sized by --prefix-cache-host-mib and
--prefix-cache-disk-mib and are read against them. A tier that is off has no cell. */
/* VRAM IN TOKENS, HOST MEMORY IN BYTES. The pool's token count is the context the card can
serve without a copy; the host tier is sized by --prefix-cache-mib and read against it. A
tier that is off has no cell. */
$("s-vram").firstChild.nodeValue = cnt3(pool.tokens_used || 0);
$("s-vramdet").textContent = pool.tokens_total ? "of " + cnt3(pool.tokens_total) + " tok" : "";
for (const [id, used, cap] of [["s-host", occ.host_bytes, occ.host_cap_bytes],
["s-disk", occ.disk_bytes, occ.disk_cap_bytes]]) {
for (const [id, used, cap] of [["s-host", occ.host_bytes, occ.host_cap_bytes]]) {
$(id + "cell").hidden = !(cap > 0);
const x = hbs(used || 0);
$(id).firstChild.nodeValue = x.n;
+2
View File
@@ -412,6 +412,8 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
req.path = hreq.path;
req.body = std::move(body);
req.peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port);
req.t_received_ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count();
for (auto& h : hreq.headers) req.headers[h.first] = h.second;
for (auto& p : hreq.params) req.query[p.first] = p.second;
req.closed = [&hreq] { return hreq.is_connection_closed(); };
+4
View File
@@ -32,6 +32,10 @@ struct HttpRequest {
std::map<std::string, std::string> query;
std::map<std::string, std::string> params; /* from a ":name" route segment */
std::string peer; /* "addr:port"; empty in-process */
/* WHEN THE WHOLE BODY HAD ARRIVED, in steady-clock nanoseconds: where the server's own time
* for the request starts, before it is parsed, rendered or tokenised, so the time the body
* spent on the network is not in it. -1 for a request made in-process. */
int64_t t_received_ns = -1;
/* True once the peer is gone. The transport supplies it; in-process it is absent and the
* waiting paths simply never see a drop. A dropped connection is a cancellation (spec §14),
+15 -21
View File
@@ -79,6 +79,8 @@ struct SchedMetrics {
* between an alert and a post-mortem. */
int64_t prefix_evictions = 0;
int64_t prefix_ckpt_evictions = 0;
/* What --prefix-cache-ttl took, cumulative. Not evictions: nothing wanted the memory. */
int64_t prefix_expired = 0, prefix_ckpt_expired = 0;
/* PREFIX CACHING, DECOUPLED (spec §7.3). `prefix_hit_rate` above is the ATTENTION one, because
* that is what vLLM's single number has always meant. The linear side hits at a different
* granularity -- whole checkpoints, not blocks -- and averaging the two would hide exactly the
@@ -166,13 +168,12 @@ struct SessionStat {
int64_t bytes = 0;
double idle_s = 0; /* since its last turn */
double age_s = 0; /* since it was first seen */
int64_t on_device = 0, on_host = 0, on_disk = 0; /* blocks */
int64_t on_device = 0, on_host = 0; /* blocks */
/* LINEAR STATE, on a hybrid model, and counted apart from blocks because the two are not
* interchangeable. A session showing every block on disk and no snapshot anywhere will come
* interchangeable. A session showing every block in host memory and no snapshot will come
* back and re-run every recurrent layer over its whole transcript -- which the hit rate will
* report as a hit. Zero everywhere on a model that has no recurrent state. */
int64_t snapshots = 0;
int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */
int64_t snap_bytes = 0;
/* The prefix a return skips: the deepest snapshot's position (IdleTiers::SessionInfo). */
int64_t resume_tokens = 0;
@@ -182,8 +183,8 @@ struct SessionStat {
/* WHAT THE STORED CONVERSATIONS OCCUPY OFF THE CARD, blocks and snapshots each counted once --
* the one total the per-session rows cannot be summed into. Caps are 0 for a tier that is off. */
struct SessionOccupancy {
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;
};
struct RequestStat {
@@ -268,27 +269,20 @@ public:
* tiers are working, switched off, or trying and failing every pass -- three very different
* situations that all render as "everything is in VRAM". */
struct TierCounters {
/* `to_host` and `to_disk` count COPIES; `dropped` is VRAM given up after one and
* `host_freed` host slots given up after the disk copy. A conversation that returns before
* anything wants its VRAM is copied and never dropped. `host_drops` is entries lost with
* no disk tier to hold them. */
int64_t to_host = 0, dropped = 0, to_disk = 0, promoted = 0;
int64_t host_freed = 0, host_drops = 0, failures = 0;
/* Entries and snapshots read off disk into host memory ahead of the restore that wanted
* them; `promoted` counts the restore itself. */
int64_t fetched = 0, ck_fetched = 0;
int64_t host_bytes = 0, disk_bytes = 0;
/* THE LINEAR HALF, MOVED. Separate counters because a hybrid server can move every block
* it has and no snapshots at all, and no block counter can tell that apart from tiering
* working. `ck_drops` is snapshots whose only copy was lost. */
int64_t ck_to_disk = 0, ck_drops = 0;
/* `to_host` counts COPIES; `dropped` is VRAM given up after one. A conversation that
* returns before anything wants its VRAM is copied and never dropped. `host_drops` is
* entries a full host tier gave up; `promoted` counts restores. */
int64_t to_host = 0, dropped = 0, promoted = 0;
int64_t host_drops = 0, failures = 0;
int64_t host_bytes = 0;
/* THE SNAPSHOT STORE, which lives in host memory and moves nothing. */
int64_t ck_bytes = 0; /* one snapshot; 0 on a model with no recurrent state */
int64_t ck_host_slots = 0, ck_disk_slots = 0; /* the store's; the disk store's */
int64_t ck_slots = 0;
int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0; /* IdleTiers::Stats */
/* WHETHER ANYTHING CAN MOVE AT ALL, which no counter above can answer: a tier that is on
* and has had nothing to do reads the same as one that was never given a size, and the
* two call for opposite responses from whoever is looking. */
bool host_on = false, disk_on = false;
bool host_on = false;
};
virtual TierCounters tier_counters() const { return TierCounters{}; }
};
+9
View File
@@ -185,6 +185,9 @@ void Metrics::sample(const SchedMetrics& m) {
c_prefix_evict_.inc(std::max(0.0, (double)m.prefix_evictions - c_prefix_evict_.get()));
c_prefix_ckpt_evict_.inc(std::max(0.0,
(double)m.prefix_ckpt_evictions - c_prefix_ckpt_evict_.get()));
c_prefix_expired_.inc(std::max(0.0, (double)m.prefix_expired - c_prefix_expired_.get()));
c_prefix_ckpt_expired_.inc(std::max(0.0,
(double)m.prefix_ckpt_expired - c_prefix_ckpt_expired_.get()));
g_linear_hit_.set(m.linear_hit_rate);
}
@@ -394,6 +397,12 @@ std::string Metrics::render() const {
"Prefix-cache entries evicted (attention blocks).", L, c_prefix_evict_.get());
w.counter("radiance:prefix_cache_ckpt_evictions_total",
"Prefix-cache linear-state checkpoints evicted.", L, c_prefix_ckpt_evict_.get());
w.counter("radiance:prefix_cache_expired_total",
"Prefix-cache entries no request used for --prefix-cache-ttl, taken out.", L,
c_prefix_expired_.get());
w.counter("radiance:prefix_cache_ckpt_expired_total",
"Prefix-cache linear-state checkpoints taken out by --prefix-cache-ttl.", L,
c_prefix_ckpt_expired_.get());
w.gauge("radiance:draft_acceptance_ratio",
"Fraction of speculative draft tokens accepted (spec 10).", L, g_draft_accept_.get());
/* CONDITIONAL, per draft position: of the verifies that reached position j -- every earlier
+1
View File
@@ -156,6 +156,7 @@ private:
Counter c_draft_refills_, c_draft_refill_tokens_;
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
Counter c_prefix_expired_, c_prefix_ckpt_expired_;
Gauge g_linear_hit_;
Counter c_success_[(size_t)SuccessReason::N_];
Counter c_rejected_, c_disconnect_, c_overflow_;
+54 -7
View File
@@ -245,7 +245,11 @@ const char* kAcceptedChat[] = {
"functions", "function_call",
};
const char* kAcceptedCompletion[] = { "prompt", "echo" };
/* `preserved_tokens` is llama-server's: control tokens a raw completion's text keeps. On chat the
* reply format decides them (the guarded entry below); a raw completion has no format, and a
* client that renders its own template and parses its own reply -- a tool-call sidecar -- has no
* other way to see a format built of control tokens. */
const char* kAcceptedCompletion[] = { "prompt", "echo", "preserved_tokens" };
const char* kAcceptedEmbedding[] = { "model", "input", "messages", "encoding_format",
"dimensions", "image_tokens", "prompt_name" };
@@ -1233,6 +1237,15 @@ static int json_text_depth(const std::string& s) {
return most;
}
/* A STRING THAT PARSES INTO A TREE DEEPER THAN THE BOUND. Only valid JSON becomes a tree: text
* that is not JSON never becomes one (a tool result that does not parse is rendered as the
* string it is), so its brackets are not nesting, however they count. The count
* runs first and the validation (json::accept, which builds nothing and does not recurse) only
* when it is over. */
static bool json_text_too_deep(const std::string& s) {
return json_text_depth(s) > kJsonMaxDepth && json::accept(s);
}
/* STRINGS THE CHAT TEMPLATE PARSES AS JSON are bounded like the body is (parse_json_bounded). An
* assistant message's tool-call arguments and a tool message's content arrive as strings, one
* level deep in the request, and the template layer parses them into trees and serialises those
@@ -1248,7 +1261,7 @@ static int check_template_json(const json& msg, const std::string& role, ApiErro
if (fn == tc.end() || !fn->is_object()) continue;
auto args = fn->find("arguments");
if (args != fn->end() && args->is_string() &&
json_text_depth(args->get_ref<const std::string&>()) > kJsonMaxDepth) {
json_text_too_deep(args->get_ref<const std::string&>())) {
*err = err_bad("messages[].tool_calls[].function.arguments",
"nests more than " + std::to_string(kJsonMaxDepth) +
" levels deep");
@@ -1260,7 +1273,7 @@ static int check_template_json(const json& msg, const std::string& role, ApiErro
if (role == "tool") {
auto c = msg.find("content");
if (c != msg.end() && c->is_string() &&
json_text_depth(c->get_ref<const std::string&>()) > kJsonMaxDepth) {
json_text_too_deep(c->get_ref<const std::string&>())) {
*err = err_bad("messages[].content", "a tool result nests more than " +
std::to_string(kJsonMaxDepth) +
" levels deep");
@@ -1613,9 +1626,18 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit
if (!render.think_open.empty()) o = d.tok->encode(render.think_open, false, true);
n_close = c.size();
n_open = o.size();
if (c.size() == 1 && (render.think_starts_open || o.size() == 1)) {
/* AN OPENER THAT IS ONE CONTROL TOKEN AND THEN TEXT -- Gemma 4's `<|channel>thought` --
* is found by that first token: it is what a reply opening its own block writes first,
* and no text can be. The text after it counts as reasoning, as the markers do. An opener
* with a second control token in it (a channel and a message marker) is not read this
* way, since its first token may open something other than the reasoning. */
bool open_first = o.size() > 1 && d.tok->reply_bytes(o[0]).empty() &&
!d.tok->token_bytes(o[0]).empty();
for (size_t i = 1; open_first && i < o.size(); ++i)
if (d.tok->reply_bytes(o[i]).empty()) open_first = false;
if (c.size() == 1 && (render.think_starts_open || o.size() == 1 || open_first)) {
span.close = c[0];
span.open = o.size() == 1 ? o[0] : -1;
span.open = (o.size() == 1 || open_first) ? o[0] : -1;
span.starts_open = render.think_starts_open;
}
}
@@ -1654,8 +1676,8 @@ static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimit
"as one token";
else
why = "this reply has to open its own reasoning block, and the opener `" +
render.think_open + "` is " + std::to_string(n_open) + " tokens, so the block "
"cannot be found by token";
render.think_open + "` is " + std::to_string(n_open) + " tokens and does not "
"start with a lone control token, so the block cannot be found by token";
*err = err_unsupported(named, why);
return RAD_E_UNSUPPORTED;
}
@@ -2135,6 +2157,29 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa
if (!get_bool(b, "echo", &out->echo, err)) return RAD_E_INVAL;
/* The control tokens this completion's text keeps (llama-server's field): each string is
* tokenised by the decoder and every control token in it is rendered rather than dropped.
* Bounded as the stop strings are, since the decoder looks each one up per token. */
{
auto pt = b.find("preserved_tokens");
if (pt != b.end() && !pt->is_null()) {
if (!pt->is_array() || pt->size() > (size_t)lim.max_stops) {
*err = err_bad("preserved_tokens", "expected an array of at most " +
std::to_string(lim.max_stops) + " strings");
return RAD_E_INVAL;
}
for (const auto& s : *pt) {
if (!s.is_string() || s.get<std::string>().size() > (size_t)lim.max_stop_bytes) {
*err = err_bad("preserved_tokens", "expected strings of at most " +
std::to_string(lim.max_stop_bytes) +
" bytes");
return RAD_E_INVAL;
}
out->preserved_tokens.push_back(s.get<std::string>());
}
}
}
RAD_TRY(parse_logprobs(b, lim, Endpoint::Completion, out, err));
/* `echo` with logprobs asks for the PROMPT's logprobs too, which are not computed: a prompt
* position's distribution never leaves the card. */
@@ -2569,6 +2614,8 @@ json timings_json(const TimingsOut& t) {
o["predicted_ms"] = t.predicted_ms;
o["predicted_per_token_ms"] = per(t.decode_n, t.predicted_ms);
o["predicted_per_second"] = rate(t.decode_n, t.predicted_ms);
o["ttft_ms"] = t.ttft_ms >= 0.0 ? json(t.ttft_ms) : json(nullptr);
o["total_ms"] = t.total_ms >= 0.0 ? json(t.total_ms) : json(nullptr);
if (t.draft_n > 0) {
o["draft_n"] = t.draft_n;
o["draft_n_accepted"] = t.draft_n_accepted;
+7
View File
@@ -138,6 +138,7 @@ struct OaiRequest {
int n_tools = 0;
std::string last_user;
std::string peer; /* the handler sets it from the transport; "" in-process */
int64_t t_received_ns = -1; /* HttpRequest::t_received_ns, for timings' ttft and total */
bool parse_tools = false;
/* The reply parser this request's render produced. Per request and not per server: it is the
* model's format bound to the tools THIS call sent, so two concurrent requests against the
@@ -362,6 +363,11 @@ struct UsageOut {
* draft_n, draft_n_accepted
* speculative tokens proposed for this request and accepted; present when any
* were proposed, as llama.cpp does
* ttft_ms from the moment the server had the whole request body to the first token: the
* parse, the chat template, tokenisation, the wait for admission and the prefill.
* The time the body took to arrive is not in it, so a client far from the server
* reads the server's own share of what it measured
* total_ms from the same moment to the last token
*
* The rates divide the tokens by the time that produced them: prompt_n by prompt_ms, and the
* predicted_n - 1 tokens after the first by predicted_ms, since the first token is the prompt
@@ -376,6 +382,7 @@ struct TimingsOut {
int64_t decode_n = 0; /* of predicted_n, the tokens after each choice's first */
double predicted_ms = 0.0;
int64_t draft_n = 0, draft_n_accepted = 0;
double ttft_ms = -1.0, total_ms = -1.0; /* < 0: the body's arrival is not known */
};
/* `timings` is added at the top level when it is valid. */
+17 -10
View File
@@ -635,8 +635,9 @@ UsageOut Server::usage_of(const OaiRequest& r, const std::vector<Generation>& ge
/* WHERE THE REQUEST'S TIME WENT, from its sinks: one for a choice's final chunk, all of them for
* the request. Every time is moved onto one clock first -- each sink counts from its own
* construction. See TimingsOut for what each field means. */
TimingsOut Server::timings_of(const Sink* const* sinks, size_t n) {
* construction, and `received_ns` (the body's arrival, -1 when unknown) is on that clock already.
* See TimingsOut for what each field means. */
TimingsOut Server::timings_of(const Sink* const* sinks, size_t n, int64_t received_ns) {
TimingsOut t;
int64_t admit = INT64_MAX, first_lo = INT64_MAX, first_hi = INT64_MIN, last = INT64_MIN;
bool admitted = true;
@@ -662,14 +663,18 @@ TimingsOut Server::timings_of(const Sink* const* sinks, size_t n) {
if (!t.valid) return t;
if (admitted) t.prompt_ms = (double)(first_hi - admit) * 1e-6;
t.predicted_ms = (double)(last - first_lo) * 1e-6;
if (received_ns >= 0) {
t.ttft_ms = (double)(first_lo - received_ns) * 1e-6;
t.total_ms = (double)(last - received_ns) * 1e-6;
}
return t;
}
TimingsOut Server::timings_of(const std::vector<Generation>& gens) {
TimingsOut Server::timings_of(const std::vector<Generation>& gens, int64_t received_ns) {
std::vector<const Sink*> v;
v.reserve(gens.size());
for (const auto& g : gens) v.push_back(g.sink.get());
return timings_of(v.data(), v.size());
return timings_of(v.data(), v.size(), received_ns);
}
/* ------------------------------------------------------------------ metrics bookkeeping */
@@ -722,7 +727,7 @@ void Server::record(const OaiRequest& r, const std::vector<Generation>& gens, Fi
/* THE OTHER HALF OF THE REQUEST LOG. The same figures /metrics aggregates, for this one
* request: how it ended, what the prefix cache spared, the reasoning share when the parser
* knows it, time to first token, the decode rate after it, and the whole. */
const TimingsOut t = timings_of(gens);
const TimingsOut t = timings_of(gens, r.t_received_ns);
const UsageOut u = usage_of(r, gens);
const double rate = (decode > 0.0 && n_gen > 1) ? (double)(n_gen - 1) / decode : -1.0;
char reason[32] = "";
@@ -740,6 +745,7 @@ void Server::record(const OaiRequest& r, const std::vector<Generation>& gens, Fi
/* ------------------------------------------------------------------ non-streaming */
HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r) {
r.t_received_ns = req.t_received_ns;
std::vector<Generation> gens;
ApiError err;
if (submit_all(r, &gens, &err) < 0) {
@@ -846,7 +852,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
retire(gens);
release(r.n_choices());
const TimingsOut timings = timings_of(gens);
const TimingsOut timings = timings_of(gens, r.t_received_ns);
if (r.shape == ApiShape::LlamaNative) {
/* llama-server answers one result, and an array of them for several prompts. */
json res = json::array();
@@ -918,7 +924,7 @@ static const char* native_stop_type(Finish f) {
* in the chunks before it. */
json Server::native_result(const OaiRequest& r, const Generation& g, const std::string& content) {
const Sink* one = g.sink.get();
const TimingsOut t = timings_of(&one, 1);
const TimingsOut t = timings_of(&one, 1, r.t_received_ns);
const int64_t n_prompt = (int64_t)r.prompts[(size_t)g.prompt_index].tokens.size();
nlohmann::ordered_json o;
o["index"] = g.index;
@@ -1014,6 +1020,7 @@ static std::string progress_chunk(const OaiRequest& r, int index, const Sink& s)
}
HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r) {
r.t_received_ns = req.t_received_ns;
auto st = std::make_shared<StreamState>();
st->r = r;
st->peer_closed = req.closed;
@@ -1121,7 +1128,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
TimingsOut now;
if (st->r.timings_per_token) {
const Sink* one = g.sink.get();
now = timings_of(&one, 1);
now = timings_of(&one, 1, st->r.t_received_ns);
if (g.delta) g.delta->set_timings(now);
}
if (st->r.endpoint == Endpoint::Chat) {
@@ -1172,7 +1179,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
/* EACH CHOICE'S OWN TIMINGS ON ITS FINAL CHUNK, so a client that asked for no
* usage chunk still has them, as llama.cpp sends them. */
const Sink* one = g.sink.get();
const TimingsOut gt = timings_of(&one, 1);
const TimingsOut gt = timings_of(&one, 1, st->r.t_received_ns);
/* A failed generation cannot become a non-200 -- the headers left long ago -- so
* it travels as an error event in the stream. Silence would look like a normal
* end of stream and the client would use a truncated answer. */
@@ -1212,7 +1219,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
* prompt and one total, so emitting it per generation would count the prompt n times
* and interleave usage between the choices' final chunks. */
if (st->r.include_usage) {
const TimingsOut t = timings_of(st->gens);
const TimingsOut t = timings_of(st->gens, st->r.t_received_ns);
out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u, t)
: text_usage_chunk(st->r, u, t);
}
+2 -2
View File
@@ -189,8 +189,8 @@ private:
struct StreamState;
static UsageOut usage_of(const OaiRequest& r, const std::vector<Generation>& gens);
static TimingsOut timings_of(const Sink* const* sinks, size_t n);
static TimingsOut timings_of(const std::vector<Generation>& gens);
static TimingsOut timings_of(const Sink* const* sinks, size_t n, int64_t received_ns);
static TimingsOut timings_of(const std::vector<Generation>& gens, int64_t received_ns);
void register_routes();
+18
View File
@@ -605,16 +605,34 @@ int Vocab::load(VocabBuild b) {
if (b_.eos >= 0) eog_.push_back(b_.eos);
if (b_.eot >= 0 && b_.eot != b_.eos) eog_.push_back(b_.eot);
{
/* Gemma 4 ends a turn on `<turn|>` and a tool-calling turn on `<|tool_response>` -- the
* opener of the result the CALLER supplies, which the model writes after its last
* `<tool_call|>` -- and declares neither: its eos is `<eos>`. llama.cpp's loader lists
* both for it, and both are control tokens nothing else spells. */
static const char* const kEogNames[] = {
"<|endoftext|>", "<|im_end|>", "<|eot_id|>", "<|end_of_text|>", "<end_of_turn>",
"<|end|>", "<|EOT|>", "<|eom_id|>", "<|return|>", "<eos>", "</s>",
"<turn|>", "<|tool_response>",
};
/* `</s>` IS A DOCUMENT'S END, NOT A TURN'S. A vocabulary with a turn marker of its own
* ends a reply on that marker, and there `</s>` -- where it is a control token at all
* and not the declared eos -- is text a reply may write: Gemma 4 spells the HTML tag with
* it. So it joins the set only in a vocabulary that has no turn marker. */
static const char* const kTurnEnds[] = {
"<|im_end|>", "<|eot_id|>", "<end_of_turn>", "<|end|>", "<|EOT|>", "<turn|>",
};
bool has_turn_end = false;
for (int32_t id : special_) {
if (b_.types[id] != RAD_TT_CONTROL) continue;
for (const char* n : kTurnEnds) if (b_.tokens[id] == n) has_turn_end = true;
}
std::string added;
for (int32_t id : special_) {
if (b_.types[id] != RAD_TT_CONTROL) continue;
if (std::find(eog_.begin(), eog_.end(), id) != eog_.end()) continue;
bool known = false;
for (const char* n : kEogNames) if (b_.tokens[id] == n) { known = true; break; }
if (has_turn_end && b_.tokens[id] == "</s>") known = false;
if (!known) continue;
eog_.push_back(id);
added += (added.empty() ? "" : " ") + b_.tokens[id] + "=" + std::to_string(id);
+5
View File
@@ -1,6 +1,7 @@
/* rad_util.cpp -- logging, error strings, dtype arithmetic and tensor helpers. The bedrock every
* other translation unit links against.
*/
#include <atomic>
#include <chrono>
#include "../rad_internal.h"
@@ -73,6 +74,9 @@ void log_rank_tags(bool on) { g_rank_tags = on; }
LogRank::LogRank(int rank) : prev_(g_log_rank) { g_log_rank = rank; }
LogRank::~LogRank() { g_log_rank = prev_; }
static std::atomic<uint64_t> g_last_line_ns{0};
uint64_t log_last_line_ns() { return g_last_line_ns.load(std::memory_order_relaxed); }
void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
const char* base = std::strrchr(file, '/');
base = base ? base + 1 : file;
@@ -95,6 +99,7 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
fprintf(stderr, "%s%s%s%s %s:%d %s\n", col, level_tag(l), rank, rst, base, line, msg);
else
fprintf(stderr, "%s%s%s%s %s\n", col, level_tag(l), rank, rst, msg);
g_last_line_ns.store(rad_mono_ns(), std::memory_order_relaxed);
}
void fatal(const char* fmt, ...) {
+290
View File
@@ -0,0 +1,290 @@
/* stallwatch.cpp -- see stallwatch.h. */
#include "util/stallwatch.h"
#include "rad_internal.h"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <dirent.h>
#include <execinfo.h>
#include <fstream>
#include <mutex>
#include <sstream>
#include <sys/syscall.h>
#include <thread>
#include <unistd.h>
#include <vector>
namespace rad {
namespace {
std::string read_first_line(const std::string& path) {
std::ifstream f(path);
std::string s;
if (f) std::getline(f, s);
return s;
}
/* The ioctl numbers of the KFD (type 'K'), as <linux/kfd_ioctl.h> assigns them. By number rather
* than by macro, because the header a build sees can be older than the driver it runs on. */
const char* kfd_ioctl_name(unsigned nr) {
static const char* const k[] = {
nullptr, "GET_VERSION", "CREATE_QUEUE", "DESTROY_QUEUE", "SET_MEMORY_POLICY",
"GET_CLOCK_COUNTERS", "GET_PROCESS_APERTURES", "UPDATE_QUEUE", "CREATE_EVENT",
"DESTROY_EVENT", "SET_EVENT", "RESET_EVENT", "WAIT_EVENTS", "DBG_REGISTER",
"DBG_UNREGISTER", "DBG_ADDRESS_WATCH", "DBG_WAVE_CONTROL", "SET_SCRATCH_BACKING_VA",
"GET_TILE_CONFIG", "SET_TRAP_HANDLER", "GET_PROCESS_APERTURES_NEW", "ACQUIRE_VM",
"ALLOC_MEMORY_OF_GPU", "FREE_MEMORY_OF_GPU", "MAP_MEMORY_TO_GPU", "UNMAP_MEMORY_FROM_GPU",
"SET_CU_MASK", "GET_QUEUE_WAVE_STATE", "GET_DMABUF_INFO", "IMPORT_DMABUF",
"ALLOC_QUEUE_GWS", "SMI_EVENTS", "SVM", "SET_XNACK_MODE", "CRIU_OP", "AVAILABLE_MEMORY",
"EXPORT_DMABUF", "RUNTIME_ENABLE", "DBG_TRAP", "CREATE_PROCESS", "PROFILER",
};
return nr < sizeof k / sizeof k[0] ? k[nr] : nullptr;
}
/* The system calls a waiting thread is found in, by their x86-64 numbers. */
const char* syscall_name(long nr) {
#if defined(__x86_64__)
switch (nr) {
case 0: return "read"; case 1: return "write"; case 2: return "open";
case 3: return "close"; case 4: return "stat"; case 7: return "poll";
case 9: return "mmap"; case 10: return "mprotect"; case 11: return "munmap";
case 16: return "ioctl"; case 17: return "pread64"; case 18: return "pwrite64";
case 23: return "select"; case 28: return "madvise"; case 35: return "nanosleep";
case 61: return "wait4"; case 149: return "mlock"; case 202: return "futex";
case 230: return "clock_nanosleep"; case 232: return "epoll_wait";
case 237: return "mbind"; case 257: return "openat"; case 262: return "newfstatat";
case 270: return "pselect6"; case 271: return "ppoll"; case 281: return "epoll_pwait";
case 332: return "statx"; case 426: return "io_uring_enter"; case 437: return "openat2";
default: return nullptr;
}
#else
(void)nr;
return nullptr;
#endif
}
bool is_ioctl(long nr) {
#if defined(__x86_64__)
return nr == 16;
#else
(void)nr;
return false;
#endif
}
/* ---- the stack of a thread that waits in user space, taken by a signal it handles itself ---- */
constexpr int kMaxFrames = 48;
std::atomic<pid_t> g_want_tid{0};
std::atomic<int> g_have{0};
void* g_frames[kMaxFrames];
int g_n_frames = 0;
void on_stack_signal(int) {
if ((pid_t)syscall(SYS_gettid) != g_want_tid.load(std::memory_order_acquire)) return;
g_n_frames = backtrace(g_frames, kMaxFrames);
g_have.store(1, std::memory_order_release);
}
/* A real-time signal nothing else in the process uses (glibc keeps the first few for itself). */
int stack_signal() { return SIGRTMIN + 7; }
std::once_flag g_install_once;
void install_stack_handler() {
std::call_once(g_install_once, [] {
/* backtrace() loads its unwinder on first use; done here, outside any handler. */
void* prime[2];
(void)backtrace(prime, 2);
struct sigaction sa {};
sa.sa_handler = on_stack_signal;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sigaction(stack_signal(), &sa, nullptr);
});
}
std::string stack_of(pid_t tid) {
install_stack_handler();
g_have.store(0, std::memory_order_relaxed);
g_want_tid.store(tid, std::memory_order_release);
if (syscall(SYS_tgkill, getpid(), tid, stack_signal()) != 0) {
g_want_tid.store(0);
return "the thread could not be signalled";
}
for (int i = 0; i < 200 && !g_have.load(std::memory_order_acquire); ++i)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
g_want_tid.store(0, std::memory_order_release);
if (!g_have.load(std::memory_order_acquire))
return "no stack: the thread did not take the signal within 2 s";
std::string s;
/* Frame 0 and 1 are the handler and the signal trampoline. */
for (int i = 2; i < g_n_frames; ++i)
s += (s.empty() ? "" : " ") + stall_module_offset((uintptr_t)g_frames[i]);
return s;
}
} /* namespace */
std::string stall_module_offset(uintptr_t addr) {
/* RELATIVE TO WHERE THE MODULE IS LOADED, which is what addr2line takes for a position-
* independent binary or library: the start of its first mapping, less that mapping's file
* offset. The offset into the file is not the same number wherever the linker puts a segment
* at a different address than its file position, as lld does. */
struct Map { unsigned long lo, hi, off; std::string path; };
std::vector<Map> maps;
{
std::ifstream f("/proc/self/maps");
std::string line;
while (std::getline(f, line)) {
Map m{};
char path[512] = "";
if (std::sscanf(line.c_str(), "%lx-%lx %*s %lx %*s %*s %511s", &m.lo, &m.hi, &m.off,
path) < 3)
continue;
m.path = path;
maps.push_back(std::move(m));
}
}
for (const Map& m : maps) {
if (addr < m.lo || addr >= m.hi) continue;
if (m.path.empty() || m.path[0] != '/') return fmt("0x%lx", (unsigned long)addr);
unsigned long base = m.lo - m.off;
for (const Map& o : maps)
if (o.path == m.path && o.lo - o.off < base) base = o.lo - o.off;
const size_t slash = m.path.rfind('/');
return fmt("%s+0x%lx", m.path.c_str() + slash + 1, (unsigned long)(addr - base));
}
return fmt("0x%lx", (unsigned long)addr);
}
std::string stall_decode_syscall(const std::string& line) {
if (line.empty()) return "unknown";
if (line == "running") return "running";
std::istringstream in(line);
long nr = 0;
if (!(in >> nr)) return "unknown";
if (nr < 0) return "not in a system call";
std::vector<unsigned long> a;
std::string w;
while (in >> w) a.push_back(std::strtoul(w.c_str(), nullptr, 16));
/* Six arguments, then the stack pointer and the program counter. */
const unsigned long pc = a.size() >= 8 ? a[7] : 0;
std::string s;
if (is_ioctl(nr) && a.size() >= 2) {
const long fd = (long)a[0];
const unsigned long req = a[1];
char target[256] = "";
const ssize_t n = readlink(fmt("/proc/self/fd/%ld", fd).c_str(), target, sizeof target - 1);
if (n > 0) target[n] = 0; else std::snprintf(target, sizeof target, "fd %ld", fd);
const unsigned type = (unsigned)((req >> 8) & 0xff), num = (unsigned)(req & 0xff);
const char* kfd = type == 'K' ? kfd_ioctl_name(num) : nullptr;
s = kfd ? fmt("ioctl(%s, AMDKFD_IOC_%s)", target, kfd)
: fmt("ioctl(%s, request 0x%lx: type '%c' number 0x%x)", target, req,
type >= 0x20 && type < 0x7f ? (char)type : '?', num);
} else if (const char* name = syscall_name(nr)) {
s = name;
} else {
s = fmt("system call %ld", nr);
}
if (pc) s += ", called from " + stall_module_offset(pc);
return s;
}
std::string stall_describe_thread(pid_t tid, bool stack) {
const std::string dir = fmt("/proc/self/task/%d/", (int)tid);
const std::string stat = read_first_line(dir + "stat");
/* The state is the field after the parenthesised name, which may itself hold spaces. */
char state = '?';
const size_t rp = stat.rfind(')');
if (rp != std::string::npos && rp + 2 < stat.size()) state = stat[rp + 2];
const std::string wchan = read_first_line(dir + "wchan");
const std::string sc = read_first_line(dir + "syscall");
std::string s = fmt("tid %d (%s), state %c", (int)tid, read_first_line(dir + "comm").c_str(),
state);
if (!wchan.empty() && wchan != "0") s += ", waiting in the kernel at " + wchan;
s += ", " + stall_decode_syscall(sc);
long nr = -1;
std::sscanf(sc.c_str(), "%ld", &nr);
/* A thread in a driver call is not signalled: the call already says where it is, and a wait
* the signal interrupts may end the call early instead of restarting it. */
if (stack && !is_ioctl(nr) && state != 'D') s += "\n stack: " + stack_of(tid);
return s;
}
struct StallWatch::Impl {
std::string phase;
uint64_t quiet_ns = 0;
pid_t holder = 0;
std::mutex mu;
std::condition_variable cv;
bool stop = false;
std::thread th;
void report(uint64_t silent_ns) {
const pid_t me = (pid_t)syscall(SYS_gettid);
std::string others;
int n_others = 0;
if (DIR* d = opendir("/proc/self/task")) {
while (dirent* e = readdir(d)) {
const pid_t t = (pid_t)std::atoi(e->d_name);
if (t <= 0 || t == holder || t == me) continue;
long nr = -1;
std::sscanf(read_first_line(fmt("/proc/self/task/%d/syscall", (int)t)).c_str(),
"%ld", &nr);
if (!is_ioctl(nr)) continue;
if (n_others++ < 8) others += "\n also in a driver call: " +
stall_describe_thread(t, false);
}
closedir(d);
}
if (n_others > 8) others += fmt("\n and %d more threads in a driver call", n_others - 8);
RAD_WARN("%s: nothing has been logged for %.0f s since the line above. The thread doing "
"the %s is %s%s\n A report of a %s that stops here should include these lines.",
phase.c_str(), (double)silent_ns / 1e9, phase.c_str(),
stall_describe_thread(holder, true).c_str(), others.c_str(), phase.c_str());
}
void run() {
uint64_t since = rad_mono_ns(); /* the start of the current silence */
uint64_t own = 0; /* the time of this watch's own last report */
uint64_t next = quiet_ns; /* the silence that is reported next */
std::unique_lock<std::mutex> lk(mu);
while (!cv.wait_for(lk, std::chrono::seconds(1), [&] { return stop; })) {
const uint64_t last = log_last_line_ns();
if (last > since && last != own) { since = last; next = quiet_ns; }
const uint64_t now = rad_mono_ns();
if (now - since < next) continue;
lk.unlock();
report(now - since);
lk.lock();
own = log_last_line_ns();
next *= 2;
}
}
};
StallWatch::StallWatch(const char* phase, uint64_t quiet_ms) : p_(std::make_unique<Impl>()) {
p_->phase = phase ? phase : "phase";
p_->quiet_ns = quiet_ms * 1000000ull;
p_->holder = (pid_t)syscall(SYS_gettid);
install_stack_handler();
p_->th = std::thread([this] { p_->run(); });
}
StallWatch::~StallWatch() {
{
std::lock_guard<std::mutex> lk(p_->mu);
p_->stop = true;
}
p_->cv.notify_all();
if (p_->th.joinable()) p_->th.join();
}
} /* namespace rad */
+58
View File
@@ -0,0 +1,58 @@
/* stallwatch.h -- naming where a phase that has gone quiet is waiting.
*
* A startup that stops printing leaves the hardest report to act on: the log ends on the last line
* that was printed, and whatever came after it -- a driver call that never returned, a lock inside a
* runtime library -- leaves no trace. The machine it happens on is often one this project cannot
* run (a guest kernel, a card passed through to a VM), so where it waits has to come from the
* process itself.
*
* A StallWatch is held across a phase by the thread doing it. When nothing has been logged for the
* quiet interval it says what that thread is doing:
* - its scheduler state and kernel wait channel;
* - the system call it is in, an ioctl with its device and request, and the library that made
* the call;
* - when the thread waits in user space (a lock, a sleep), its stack as module+offset frames,
* which addr2line symbolises against the released binary. A thread inside an ioctl is not
* signalled: the call already names where it waits, and a signal could end a driver wait
* early;
* - the process's other threads that are inside an ioctl, since a lock in a runtime library is
* usually held by one of them.
* It says it again each time the silence doubles, so a later log shows whether the thread moved.
* The watch reads only its own process's /proc entries and costs one wake-up a second while held.
*/
#pragma once
#include <cstdint>
#include <memory>
#include <string>
#include <sys/types.h>
namespace rad {
class StallWatch {
public:
/* `phase` names what is being watched in the report ("startup"). */
explicit StallWatch(const char* phase, uint64_t quiet_ms = 60000);
~StallWatch();
StallWatch(const StallWatch&) = delete;
StallWatch& operator=(const StallWatch&) = delete;
struct Impl;
private:
std::unique_ptr<Impl> p_;
};
/* What thread `tid` of this process is doing, as the report words it: state, wait channel, system
* call. With `stack`, a thread waiting in user space is also asked for its frames. */
std::string stall_describe_thread(pid_t tid, bool stack);
/* One line of /proc/<pid>/task/<tid>/syscall in words: "running", "not in a system call", or the
* call with its arguments decoded where they name something (an ioctl's device and request). */
std::string stall_decode_syscall(const std::string& line);
/* `addr` as the module that maps it and its offset from the module's load base, "libfoo.so+0x1a2b":
* the number addr2line takes for that module. */
std::string stall_module_offset(uintptr_t addr);
} /* namespace rad */