Archived
radiance 1.1.0
- The VRAM split has no ratio: --expert-vs-cache-ratio is gone (now an unknown option). The experts keep what the pinned host pool cannot hold, the KV cache takes the rest and lends idle blocks to the experts. Flash-Next at tp2: 7.9 GiB of KV a card, up from 4.7. Startup, /stats, /metrics and the dashboard report the most the cache can hold. - Linear-state snapshots live in pinned host memory, not VRAM (--checkpoint-slots sizes the store). Prefix-cache misses on agent sessions fixed; a published conversation is no longer trimmed away. - Any world size from the shipped container (baKon): --tp 3 on Flash-Next with no padded checkpoint -- the attention world, uneven delta-net heads, the fill op. - Kernels (keptn42): moe_gemm_q decode loads and one-trip run search, hc_read's prefill form (+3.7% prefill at 18K), hc_up row groups up to eight, the fused router launch. Each is the rule where it was measured faster; no environment switches. - Tool calls: a typed argument is always JSON (Python True/None no longer leak into arguments -- Codeberg #21); nine further reply-parser fixes; the reply path inside a call is ~12x cheaper on the host. - The kernel changes: prefill +2-3% and decode -2% a step on 2x R9700 at tp2, identical text.
This commit is contained in:
1 parent
9f5feb24ee
commit
82b5835c02
101 files changed
+5105
-3767
No files matched your search
@@ -151,7 +151,6 @@ public:
|
||||
int weight_shard_span(rad_weight w, int64_t lo, int64_t hi);
|
||||
int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n);
|
||||
int weight_shard_zero(rad_weight w);
|
||||
int kv_group_zero(rad_kvgroup g);
|
||||
|
||||
/* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns
|
||||
|
||||
+10
-17
@@ -929,20 +929,18 @@ int Builder::weight_shard_span_parts(rad_weight h, const int64_t* lo, const int6
|
||||
int Builder::kv_group_zero(rad_kvgroup h) {
|
||||
if (finished_) { err(RAD_E_STATE, "kv_group_zero after declare finished"); return RAD_E_STATE; }
|
||||
if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL;
|
||||
prog_.kv_groups[h].zero = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Builder::weight_shard_zero(rad_weight h) {
|
||||
if (finished_) { err(RAD_E_STATE, "weight_shard_zero after declare finished"); return RAD_E_STATE; }
|
||||
if (h == 0 || h >= prog_.weights.size()) return RAD_E_INVAL;
|
||||
WeightInfo& w = prog_.weights[h];
|
||||
if (w.decl.shard != RAD_SHARD_ROW && w.decl.shard != RAD_SHARD_COL) {
|
||||
err(RAD_E_INVAL, "weight '%s': a zero share on a weight that is not row- or "
|
||||
"column-sharded", w.name.c_str());
|
||||
/* PAGED GROUPS ONLY. A zero group is one whose rank computes nothing that reads or writes it,
|
||||
* and a paged group's absence is invisible to the others: they index the shared block table
|
||||
* and this rank has no shard to index. A linear or conv group carries per-sequence state the
|
||||
* snapshot store saves and the step clears on every rank, and a zero-sized one would make
|
||||
* each of those copies a size mismatch. */
|
||||
const int kind = prog_.kv_groups[h].decl.kind;
|
||||
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) {
|
||||
err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group that is not paged",
|
||||
prog_.kv_groups[h].name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
w.shard_zero = true;
|
||||
prog_.kv_groups[h].zero = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1675,11 +1673,6 @@ int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo,
|
||||
return B(b)->weight_shard_span_parts(w, lo, hi, total, n);
|
||||
}
|
||||
|
||||
int rad_weight_shard_zero(RadBuilder* b, rad_weight w) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->weight_shard_zero(w);
|
||||
}
|
||||
|
||||
int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->kv_group_zero(g);
|
||||
|
||||
+4
-22
@@ -44,15 +44,6 @@ static const Flag g_flags[] = {
|
||||
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
|
||||
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
|
||||
/* THE FLAG THAT DECIDES WHETHER MULTI-TURN WORKS, which is more than the split it names.
|
||||
* The KV side is not just concurrency: prefix caching holds a finished sequence's blocks
|
||||
* so the next turn can reuse them, so when the pool cannot hold the LIVE SESSIONS the
|
||||
* cache drops prefixes the next turn wanted and that turn re-prefills its whole context.
|
||||
* At long contexts that is two orders of magnitude of time-to-first-token, bought back for
|
||||
* a fraction of a percent of the decode step. See core/mem/prefix.h. */
|
||||
{ "--expert-vs-cache-ratio", "R", "weights vs KV split of what is claimed (default "
|
||||
"0.75). The KV side also holds cached prefixes, so "
|
||||
"too little of it makes every agent turn re-prefill" },
|
||||
{ "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" },
|
||||
{ "--vram-kv-mib", "N", "the paged KV pool; 0 derives it from the card" },
|
||||
{ "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" },
|
||||
@@ -89,13 +80,14 @@ static const Flag g_flags[] = {
|
||||
" this does NOT make the engine bit-reproducible across\n"
|
||||
" batch positions -- see spec §19" },
|
||||
{ "--checkpoint-interval","N", "linear-attention state checkpoint interval, in tokens" },
|
||||
/* TOTAL, NOT PER SEQUENCE. `ck_free_` is one global free list of N slots handed out by
|
||||
* pop_back (core/mem/kv.cpp), so an operator reading "per sequence" and setting 2 gets
|
||||
/* TOTAL, NOT PER SEQUENCE. The snapshot store is one pool of N slots for the whole server
|
||||
* (KVManager::set_checkpoint_store), so an operator reading "per sequence" and setting 2 gets
|
||||
* 2 for the whole server rather than 2 x --max-num-seqs. At the default 8 slots and
|
||||
* 8 sequences that is one snapshot a sequence, which is what an append-only chat wants --
|
||||
* the next turn's hit lands at the end of the last one. */
|
||||
{ "--checkpoint-slots", "N", "linear-state snapshots retained IN TOTAL (not "
|
||||
"per sequence); compare against --max-num-seqs" },
|
||||
"per sequence), in pinned host memory; compare "
|
||||
"against --max-num-seqs" },
|
||||
{ "--no-prefix-cache", nullptr, "disable prefix caching" },
|
||||
{ "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff "
|
||||
"(default), tip-only, keep-all" },
|
||||
@@ -389,16 +381,6 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
c->kv_cache_dtype = v;
|
||||
}
|
||||
else if (S("--expert-vs-cache-ratio")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
c->expert_cache_ratio = atof(v);
|
||||
if (!(c->expert_cache_ratio > 0.0 && c->expert_cache_ratio < 1.0)) {
|
||||
RAD_ERR("--expert-vs-cache-ratio is the WEIGHTS share of what is claimed and must "
|
||||
"be strictly between 0 and 1, not '%s'. 0.75 gives three quarters to "
|
||||
"weights and a quarter to the KV cache.", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--host-pool-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->host_pool_mib = atoll(v); }
|
||||
else if (S("--embedding-placement") || S("--ngram-placement")) {
|
||||
const bool emb = S("--embedding-placement");
|
||||
|
||||
+42
-24
@@ -18,6 +18,7 @@
|
||||
#include <cstring>
|
||||
#include <atomic>
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
@@ -117,14 +118,17 @@ const char* device_backend_name() { return dev()->name; }
|
||||
* RADIANCE_TRACE_ALLOC=N logs every allocation of at least N bytes as it happens. That is the
|
||||
* instrument; the counters are the summary.
|
||||
*
|
||||
* RADIANCE_POISON_ALLOC=B fills every fresh DEVICE allocation with byte B (0..255) before it is
|
||||
* handed out, so a buffer that is read before anything wrote it shows up as garbage rather than
|
||||
* as the zeros a wiped card hands back by luck. A card that has just been through a driver reset
|
||||
* ("VRAM is lost") is that garbage for real, which is where such a read is otherwise first seen.
|
||||
* RADIANCE_POISON_RANGE=lo:hi narrows the fill to device allocations with ordinal in [lo, hi) --
|
||||
* ordinals count from 1 in allocation order ON THE ALLOCATING THREAD, the `#n on this thread` the
|
||||
* trace prints -- to bisect to the one allocation that matters. Both are debug knobs: the fill is synchronous and costs a stream a
|
||||
* call. */
|
||||
* RADIANCE_DEBUG_POISON_ALLOC=B fills every fresh DEVICE allocation with byte B (0..255) before
|
||||
* it is handed out, so a buffer that is read before anything wrote it shows up as garbage rather
|
||||
* than as the zeros a wiped card hands back by luck. A card that has just been through a driver
|
||||
* reset ("VRAM is lost") is that garbage for real, which is where such a read is otherwise first
|
||||
* seen. A correct engine serves the same output with it set. RADIANCE_DEBUG_POISON_RANGE=lo:hi
|
||||
* narrows the fill to device allocations with ordinal in [lo, hi) -- ordinals count from 1 in
|
||||
* allocation order ON THE ALLOCATING THREAD, the `#n on this thread` the trace prints -- to bisect
|
||||
* to the one allocation that matters. Both are instruments: the fill is synchronous, through one
|
||||
* stream per thread and device that lives until exit (a stream is a hardware queue, and creating
|
||||
* and destroying one per allocation is both slow and the queue churn ROCr's Trim path faults on).
|
||||
* A byte outside 0..255 or a range that does not parse is refused at the first allocation. */
|
||||
namespace rad {
|
||||
namespace {
|
||||
|
||||
@@ -152,10 +156,15 @@ int64_t trace_floor() {
|
||||
/* -1 when off; otherwise the byte. */
|
||||
int poison_byte() {
|
||||
static const int v = [] {
|
||||
const char* e = std::getenv("RADIANCE_POISON_ALLOC");
|
||||
const char* e = std::getenv("RADIANCE_DEBUG_POISON_ALLOC");
|
||||
if (!e || !*e) return -1;
|
||||
const long x = std::atol(e);
|
||||
return (x >= 0 && x <= 255) ? (int)x : 255;
|
||||
char* end = nullptr;
|
||||
const long x = std::strtol(e, &end, 0);
|
||||
if (*end || x < 0 || x > 255) {
|
||||
RAD_ERR("RADIANCE_DEBUG_POISON_ALLOC=%s is not a byte (0..255)", e);
|
||||
std::abort();
|
||||
}
|
||||
return (int)x;
|
||||
}();
|
||||
return v;
|
||||
}
|
||||
@@ -163,9 +172,12 @@ int poison_byte() {
|
||||
/* [lo, hi) over device-allocation ordinals; the whole run when unset. */
|
||||
bool poison_in_range(int64_t ordinal) {
|
||||
static const std::pair<int64_t, int64_t> r = [] {
|
||||
const char* e = std::getenv("RADIANCE_POISON_RANGE");
|
||||
const char* e = std::getenv("RADIANCE_DEBUG_POISON_RANGE");
|
||||
long long lo = 0, hi = INT64_MAX;
|
||||
if (e && *e && std::sscanf(e, "%lld:%lld", &lo, &hi) < 1) { lo = 0; hi = INT64_MAX; }
|
||||
if (e && *e && (std::sscanf(e, "%lld:%lld", &lo, &hi) != 2 || lo < 0 || hi <= lo)) {
|
||||
RAD_ERR("RADIANCE_DEBUG_POISON_RANGE=%s is not lo:hi with 0 <= lo < hi", e);
|
||||
std::abort();
|
||||
}
|
||||
return std::make_pair((int64_t)lo, (int64_t)hi);
|
||||
}();
|
||||
return ordinal >= r.first && ordinal < r.second;
|
||||
@@ -400,7 +412,14 @@ using rad::dev;
|
||||
extern "C" {
|
||||
|
||||
int rad_dev_count(void) { return dev()->count(); }
|
||||
int rad_dev_set(int device) { return dev()->set(device); }
|
||||
/* The device this thread last selected, for the poison fill's stream (rad_dev_alloc). */
|
||||
static thread_local int t_device = 0;
|
||||
static thread_local std::map<int, RadStream> t_poison_stream;
|
||||
int rad_dev_set(int device) {
|
||||
const int st = dev()->set(device);
|
||||
if (st == RAD_OK) t_device = device;
|
||||
return st;
|
||||
}
|
||||
int rad_dev_props(int device, RadDeviceProps* o) { return dev()->props(device, o); }
|
||||
int rad_dev_enable_peer(int self, int peer) { return dev()->enable_peer(self, peer); }
|
||||
|
||||
@@ -424,16 +443,15 @@ void* rad_dev_alloc(int64_t bytes, int kind) {
|
||||
* holds on both backends; synchronous, so the bytes are there before the caller sees p. */
|
||||
const int poison = rad::poison_byte();
|
||||
if (poison >= 0 && kind == RAD_MEM_DEVICE && rad::poison_in_range(ordinal)) {
|
||||
RadStream s = nullptr;
|
||||
if (dev()->stream_create(&s, 0) == RAD_OK) {
|
||||
if (dev()->memset_async(p, poison, bytes, s) != RAD_OK || dev()->stream_sync(s) != RAD_OK)
|
||||
RAD_WARN("poison: device allocation #%lld (%s) was not filled",
|
||||
(long long)ordinal, rad::humanb(bytes).c_str());
|
||||
else if (floor_ >= 0 && bytes >= floor_)
|
||||
RAD_INFO("poison: device allocation #%lld filled with 0x%02x", (long long)ordinal,
|
||||
poison);
|
||||
dev()->stream_destroy(s);
|
||||
}
|
||||
RadStream& s = t_poison_stream[t_device];
|
||||
if (!s && dev()->stream_create(&s, 0) != RAD_OK) s = nullptr;
|
||||
if (!s || dev()->memset_async(p, poison, bytes, s) != RAD_OK ||
|
||||
dev()->stream_sync(s) != RAD_OK)
|
||||
RAD_WARN("poison: device allocation #%lld (%s) was not filled",
|
||||
(long long)ordinal, rad::humanb(bytes).c_str());
|
||||
else if (floor_ >= 0 && bytes >= floor_)
|
||||
RAD_INFO("poison: device allocation #%lld filled with 0x%02x", (long long)ordinal,
|
||||
poison);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
|
||||
+170
-72
@@ -651,13 +651,13 @@ int Engine::step_loop() {
|
||||
}
|
||||
|
||||
/* THE RECURRENT HALF OF A PREFIX HIT, restored BEFORE the step that reads it. The adopted
|
||||
* blocks carry the attention layers; this carries the recurrent ones. Enqueued on each
|
||||
* rank's own stream ahead of the release, so it is ordered before the kernels without a
|
||||
* synchronisation -- the same way collect_step's readback is ordered after them.
|
||||
* blocks carry the attention layers; this carries the recurrent ones, copied out of the
|
||||
* snapshot's slot in host memory. Enqueued on each rank's own stream ahead of the
|
||||
* release, so it is ordered before the kernels without a synchronisation -- the same way
|
||||
* collect_step's readback is ordered after them.
|
||||
*
|
||||
* UNDER THE SCHEDULER'S LOCK, because it reads the sequence table and backs checkpoint
|
||||
* slots in rank 0's manager, which an HTTP thread's cancel mutates under that lock. Taken
|
||||
* only on a step that has a restore in it. */
|
||||
* UNDER THE SCHEDULER'S LOCK, because it reads the sequence table, which an HTTP thread's
|
||||
* cancel mutates under that lock. Taken only on a step that has a restore in it. */
|
||||
bool any_restore = false;
|
||||
for (const StepEntry& e : plan.e) if (e.ckpt_restore >= 0) { any_restore = true; break; }
|
||||
if (any_restore) {
|
||||
@@ -666,12 +666,7 @@ int Engine::step_loop() {
|
||||
if (e.ckpt_restore < 0) continue;
|
||||
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
|
||||
for (auto& rk : ranks_) {
|
||||
/* THIS RANK'S DEVICE, BECAUSE THE COPY MAY HAVE TO MAP MEMORY FIRST. A
|
||||
* checkpoint slot is backed by the rank that writes it
|
||||
* (KVManager::back_checkpoint), and a commit must land on the card whose pool
|
||||
* it backs -- a commit on card 0 mapped into rank 1's range succeeds, grants
|
||||
* access to the wrong card, and rank 1's next kernel faults on a page that is
|
||||
* present somewhere else. */
|
||||
/* This rank's device, for its own stream and its own state slots. */
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
|
||||
const int s = rk->kv.checkpoint_restore(ckpt_slots_.data(),
|
||||
(int)ckpt_slots_.size(),
|
||||
@@ -759,8 +754,9 @@ int Engine::step_loop() {
|
||||
|
||||
/* AND THE SNAPSHOT, taken AFTER the step that produced the state. The chunker split this
|
||||
* chunk so its last token IS the checkpoint position, so what copy 0 holds now is exactly
|
||||
* the state at that position. It is issued before collect_step's readback synchronises, so
|
||||
* the copy overlaps whatever is left of the step rather than adding to it.
|
||||
* the state at that position. It is a copy across the link into the snapshot's slot in host
|
||||
* memory, issued before collect_step's readback synchronises and ahead of any step issued
|
||||
* behind this one, which is what orders the next write of the state after it.
|
||||
*
|
||||
* Under the scheduler's lock for the reason the restore above is, and only on a step that
|
||||
* writes a checkpoint. */
|
||||
@@ -773,8 +769,6 @@ int Engine::step_loop() {
|
||||
if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue;
|
||||
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
|
||||
for (auto& rk : ranks_) {
|
||||
/* THIS RANK'S DEVICE, for the reason the restore gives: the copy may have to
|
||||
* back the slot first, and the pages belong on this rank's card. */
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
|
||||
const int s = rk->kv.checkpoint_save(ckpt_slots_.data(),
|
||||
(int)ckpt_slots_.size(),
|
||||
@@ -1147,15 +1141,8 @@ void Engine::loan_tick(bool idle) {
|
||||
const auto lk = sched_.hold();
|
||||
Rank& lead = *ranks_[0];
|
||||
|
||||
/* A FINISHED CONVERSATION'S VRAM GOES FIRST, when the slabs have a use for it. An entry whose
|
||||
* host copy has landed loses nothing by leaving -- a return restores it from host memory --
|
||||
* so while any slab has slots the loan does not yet cover, every such entry is released and
|
||||
* its blocks count toward what the cache can spare below. Past that point the VRAM would sit
|
||||
* empty in the slab, and the entries stay where a return finds them for free. */
|
||||
int64_t ceiling = 0;
|
||||
for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV));
|
||||
if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean();
|
||||
|
||||
/* A FINISHED CONVERSATION'S VRAM IS ALREADY FREE by the time this runs: tier_tick gives up
|
||||
* every entry whose host copy has landed, so what the cache can spare below counts it. */
|
||||
/* WHAT THE CACHE CAN DO WITHOUT, AND WHAT THE SLABS STILL OCCUPY. A loan grows as soon as the
|
||||
* cache can spare it -- the slots are filled on the next dispatch or the next idle tick -- but
|
||||
* only by at least a prefill chunk, so a cache breathing by a few blocks does not have its
|
||||
@@ -1296,14 +1283,20 @@ void Engine::tier_tick() {
|
||||
{
|
||||
TierIO::Fetch f;
|
||||
while (P.io.take_fetch(&f)) {
|
||||
for (size_t i = 0; i < f.fences.size() && i < ranks_.size(); ++i) {
|
||||
if (!f.fences[i]) continue;
|
||||
(void)rad_dev_set(ranks_[i]->device);
|
||||
rad_event_destroy(f.fences[i]);
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(lead.device);
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1312,7 +1305,9 @@ void Engine::tier_tick() {
|
||||
{
|
||||
std::vector<TierJob> jobs;
|
||||
std::vector<char> ok;
|
||||
if (P.io.take(&jobs, &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);
|
||||
}
|
||||
@@ -1334,6 +1329,22 @@ void Engine::tier_tick() {
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- what is not live leaves VRAM -------------------------------------------------------- */
|
||||
/* AS SOON AS ITS COPY HAS LANDED, WHILE THE EXPERT SLAB HAS A USE FOR THE BLOCKS. An entry no
|
||||
* running sequence reads and whose host copy is in place costs nothing to give up -- a later
|
||||
* turn restores it in a copy -- and its blocks are lent to the slab. With no lender, or a slab
|
||||
* whose loan already covers every slot it has, the blocks would sit empty in the pool, so the
|
||||
* entry stays where the next turn finds it for free; a request that needs the room takes it
|
||||
* through trim, which drops the same entries on demand.
|
||||
*
|
||||
* NOT THE SNAPSHOTS: they are in host memory already and hold no VRAM. */
|
||||
if (lending_) {
|
||||
int64_t ceiling = 0;
|
||||
for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV));
|
||||
const auto lk = sched_.hold();
|
||||
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
|
||||
@@ -1343,7 +1354,25 @@ void Engine::tier_tick() {
|
||||
tier_last_ns_ = now;
|
||||
std::vector<TierJob> jobs;
|
||||
lead.tiers.plan(P.slow_budget, &jobs);
|
||||
if (!jobs.empty() && !P.io.submit(std::move(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);
|
||||
@@ -1353,6 +1382,74 @@ void Engine::tier_tick() {
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
bool Engine::flush_copies() {
|
||||
if (!pump_ || !ranks_[0]->tierx.enabled()) return false;
|
||||
TierPump& P = *pump_;
|
||||
Rank& lead = *ranks_[0];
|
||||
bool landed = false;
|
||||
const uint64_t t0 = rad_mono_ns();
|
||||
/* Counted only when something was in flight or waiting: a call that found nothing to land
|
||||
* stalled nobody. */
|
||||
struct Note {
|
||||
IdleTiers& t; uint64_t t0; bool worked = false;
|
||||
~Note() { if (worked) t.note_flush((int64_t)(rad_mono_ns() - t0)); }
|
||||
} note{lead.tiers, t0};
|
||||
/* BOUNDED: each round lands one batch of P.max_copy entries, and a pool short of more than
|
||||
* that many rounds' worth is a pool the tiers cannot relieve in one step. */
|
||||
for (int round = 0; round < 64; ++round) {
|
||||
if (!P.copy.empty()) {
|
||||
note.worked = true;
|
||||
bool good = true;
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
if (P.copy_st[i] == 0) P.copy_st[i] = ranks_[i]->tierx.wait_copy();
|
||||
if (P.copy_st[i] < 0) good = false;
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(lead.device);
|
||||
const std::vector<char> ok(P.copy.size(), good ? 1 : 0);
|
||||
lead.tierx.report_pass(P.copy, ok, rad_mono_ns());
|
||||
P.copy.clear();
|
||||
landed = landed || good;
|
||||
}
|
||||
if (!lead.tiers.writeback_waiting()) break;
|
||||
lead.tiers.plan_writeback(P.max_copy, &P.copy);
|
||||
if (P.copy.empty()) break;
|
||||
P.copy_st.assign(ranks_.size(), 0);
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
const int st = ranks_[i]->tierx.issue_copy(P.copy, ranks_[i]->ctx.stream());
|
||||
if (st < 0) P.copy_st[i] = st;
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(lead.device);
|
||||
}
|
||||
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
|
||||
@@ -1362,25 +1459,20 @@ bool Engine::submit_fetch(uint64_t tag, std::vector<TierJob>&& jobs) {
|
||||
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;
|
||||
for (auto& r : ranks_) {
|
||||
RadEvent e = nullptr;
|
||||
if (st == RAD_OK) st = r->tierx.fence(&e);
|
||||
f.fences.push_back(e);
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
|
||||
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");
|
||||
for (size_t i = 0; i < f.fences.size(); ++i) {
|
||||
if (!f.fences[i]) continue;
|
||||
(void)rad_dev_set(ranks_[i]->device);
|
||||
rad_event_destroy(f.fences[i]);
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
|
||||
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;
|
||||
@@ -1408,11 +1500,12 @@ int Engine::serve() {
|
||||
}
|
||||
|
||||
/* The scheduler drives ONE block manager. Block ids are pure bookkeeping and identical on
|
||||
* every rank -- the heads divide equally, so every rank's pool has the same geometry and its
|
||||
* free list evolves identically. What differs per rank is the pool BASE, and that lives in
|
||||
* KVPoolBinding. So rank 0's manager owns the bookkeeping and the others exist to own their
|
||||
* own card's allocation. If the geometries ever disagree the block tables mean different
|
||||
* things on different cards, so it is checked rather than assumed. */
|
||||
* every rank: every rank carves the same block count (Engine::configure_kv caps each at the
|
||||
* least rank's), so its free list evolves identically even where the ranks' shares of a
|
||||
* group differ in bytes, or are zero (rad_kv_group_zero). What differs per rank is the pool
|
||||
* BASE, and that lives in KVPoolBinding. So rank 0's manager owns the bookkeeping and the
|
||||
* others exist to own their own card's allocation. If the counts ever disagree the block
|
||||
* tables mean different things on different cards, so it is checked rather than assumed. */
|
||||
for (size_t i = 1; i < ranks_.size(); ++i) {
|
||||
const auto& a = ranks_[0]->kv.plans();
|
||||
const auto& c = ranks_[i]->kv.plans();
|
||||
@@ -1452,12 +1545,9 @@ 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. */
|
||||
/* A restored session's state needs a device checkpoint slot, and which snapshot gives
|
||||
* one up is the cache's decision: it knows which ones a lookup this step handed out. */
|
||||
ranks_[0]->tierx.set_checkpoint_room(
|
||||
[this] { return ranks_[0]->prefix.free_checkpoint_for_restore(); });
|
||||
b->restore_fn = [this](const Request& req) -> IPrefixCache::Restore {
|
||||
using R = IPrefixCache::Restore;
|
||||
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())
|
||||
@@ -1468,13 +1558,27 @@ int Engine::serve() {
|
||||
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
|
||||
* only when something could be on disk or in flight: a chain wholly in VRAM is the
|
||||
* common case, and it is thousands of keys. */
|
||||
if (!want.empty() || !P.waiting.empty()) {
|
||||
* 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;
|
||||
if (ranks_[0]->tiers.plan_fetch(chain, &reads, rad_mono_ns())) {
|
||||
if (reads.empty() || submit_fetch(req.id, std::move(reads))) return R::Wait;
|
||||
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;
|
||||
/* THE WHOLE CHAIN IN ONE RESTORE. A 4-token block makes a long conversation tens of
|
||||
@@ -1513,22 +1617,20 @@ int Engine::serve() {
|
||||
* them too, and would be released later from under whoever the pool gives them
|
||||
* to. Both are let go, so the blocks return to the pool and the key is simply
|
||||
* unknown. */
|
||||
ranks_[0]->tierx.quiesce();
|
||||
for (size_t k = 0; k < cg.size() && k < j.blocks.size(); ++k)
|
||||
if (j.blocks[k] >= 0) ranks_[0]->kv.release_block(cg[k], j.blocks[k]);
|
||||
ranks_[0]->tiers.forget(j.key);
|
||||
if (j.ck_dev >= 0) ranks_[0]->kv.free_checkpoint(j.ck_dev);
|
||||
continue;
|
||||
}
|
||||
/* AND THE RECURRENT HALF, into the slot the restore allocated for it. Without this
|
||||
* the session gets its attention hit back and replays every linear layer from
|
||||
* token zero, which on a long transcript is most of a prefill. NOBODY ELSE OWNS
|
||||
* THAT SLOT UNTIL THE CACHE TAKES IT: if the index entry the snapshot belongs to
|
||||
* was retired, the slot has no path back to the free list. */
|
||||
if (j.ck_dev >= 0 && pc.reattach_snapshot(j.key, j.ck_dev) != RAD_OK)
|
||||
ranks_[0]->kv.free_checkpoint(j.ck_dev);
|
||||
}
|
||||
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
|
||||
* entries that already have a host copy did not free enough: every copy waiting is
|
||||
* planned, issued and landed now, so the entries it covers can leave VRAM and be kept. */
|
||||
b->flush_fn = [this]() -> bool { return flush_copies(); };
|
||||
}
|
||||
/* EVERY RANK'S CARD, STREAM AND ARENA. The batch is one build shared by pointer (spec §1) and
|
||||
* that is right for the host side; the DEVICE side is staged per rank, because a rank reading
|
||||
@@ -1539,10 +1641,6 @@ int Engine::serve() {
|
||||
for (auto& rk : ranks_)
|
||||
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program });
|
||||
RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_));
|
||||
/* The step staging the budget kept room for exists now, so a checkpoint slot backed from here
|
||||
* on leaves the headroom and only what is still to be built on first use. */
|
||||
set_checkpoint_floors(std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * (1ll << 20) +
|
||||
late_lazy_bytes_);
|
||||
|
||||
for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get());
|
||||
|
||||
|
||||
+18
-10
@@ -22,6 +22,7 @@
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
#include "build/startup.h"
|
||||
#include "mem/hostarena.h"
|
||||
#include "sched/mem_iface.h"
|
||||
#include "sched/scheduler.h"
|
||||
#include "sample/vocab_view.h"
|
||||
@@ -121,7 +122,8 @@ private:
|
||||
/* --embedding-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>& floor_emb_ram, 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
|
||||
@@ -306,6 +308,15 @@ private:
|
||||
* 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);
|
||||
/* 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
|
||||
@@ -327,19 +338,16 @@ private:
|
||||
int64_t arena_floor_ = 0;
|
||||
int64_t arena_last_ = 0;
|
||||
uint64_t arena_floor_ns_ = 0;
|
||||
/* WHETHER THIS DRIVER RETURNS DECOMMITTED VRAM TO THE CARD, for the checkpoint slots -- the
|
||||
* one part of the KV pool still backed on demand. Measured once at the end of bringup; it is
|
||||
* not something the API promises. */
|
||||
bool release_frees_card_ = true;
|
||||
/* WHAT THE VRAM BUDGET KEPT FOR ALLOCATIONS MADE AFTER start(), on top of --gpu-headroom-mib:
|
||||
* the step batch's staging, which serve() allocates, and what is built on first use, if
|
||||
* ever -- the KV tiers' copy staging and the second compute lane's queue. The checkpoint
|
||||
* slots backed at the end of bringup leave both free, and the bringup's closing reading is
|
||||
* checked against both. */
|
||||
* ever -- the KV tiers' copy staging and the second compute lane's queue. The bringup's
|
||||
* closing reading is checked against both. */
|
||||
int64_t late_step_bytes_ = 0;
|
||||
int64_t late_lazy_bytes_ = 0;
|
||||
/* Every rank's checkpoint floor: a slot is backed only while the card keeps `keep` free. */
|
||||
void set_checkpoint_floors(int64_t keep);
|
||||
/* THE LINEAR-STATE SNAPSHOT STORE: pinned host memory, --checkpoint-slots slots, each holding
|
||||
* every rank's shard of one snapshot (KVManager::set_checkpoint_store). Not on the card: a
|
||||
* snapshot is read by no kernel, only copied back into a sequence's state. */
|
||||
HostArena ck_store_;
|
||||
int run_server();
|
||||
/* THE KL MODE (core/kld.h), in place of run_server: the corpus's documents submitted as
|
||||
* scoring requests, and every step's scored rows copied to the host and handed to `kld_`.
|
||||
|
||||
+146
-158
@@ -438,7 +438,8 @@ bool Engine::ngram_gather_to_host() {
|
||||
* RAM's is lockable_room's -- 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>& floor_emb_ram, 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;
|
||||
@@ -501,9 +502,13 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
auto card_holds = [&](std::string* why) {
|
||||
std::vector<VramFacts> with = facts;
|
||||
int64_t fixed = 0;
|
||||
for (VramFacts& f : with) {
|
||||
for (size_t i = 0; i < with.size(); ++i) {
|
||||
VramFacts& f = with[i];
|
||||
f.statics += ngram_bytes;
|
||||
if (emb == TablePlacement::Ram) f.statics -= emb_max;
|
||||
if (emb == TablePlacement::Ram) {
|
||||
f.statics -= emb_max;
|
||||
f.expert_floor = floor_emb_ram[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
|
||||
@@ -511,12 +516,21 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
VramBudget tb;
|
||||
const int st = vram_budget_trial(cfg_, with, &tb);
|
||||
const bool over = st == RAD_OK && fixed >= tb.claimable;
|
||||
if (st == RAD_OK && !over && (!tb.derived_kv || tb.kv >= kv_floor)) return true;
|
||||
/* AND THE EXPERTS KEEP A TIER: where the cache lends, those the host pool cannot hold have
|
||||
* only the card, and a table that took their room would leave them nowhere. */
|
||||
const bool starved = st == RAD_OK && tb.lends && tb.expert_ceiling > 0 &&
|
||||
tb.experts < tb.expert_floor;
|
||||
if (st == RAD_OK && !over && !starved && (!tb.derived_kv || tb.kv >= kv_floor))
|
||||
return true;
|
||||
if (st != RAD_OK)
|
||||
*why = "the card cannot hold the other weights with it";
|
||||
else if (over)
|
||||
*why = fmt("with it the fixed weights want %s of a card that has %s to give",
|
||||
humanb(fixed).c_str(), humanb(tb.claimable).c_str());
|
||||
else if (starved)
|
||||
*why = fmt("with it on the card the experts get %s, short of the %s the pinned host "
|
||||
"pool cannot hold", humanb(tb.experts).c_str(),
|
||||
humanb(tb.expert_floor).c_str());
|
||||
else
|
||||
*why = fmt("with it on the card the KV pool is %s, short of the %s one "
|
||||
"--max-model-len sequence needs", humanb(tb.kv).c_str(),
|
||||
@@ -1064,6 +1078,7 @@ int Engine::plan() {
|
||||
/* 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<WeightFootprint> wfs;
|
||||
int64_t ngram_bytes = 0, kv_floor = 0;
|
||||
bool ngram_device = false, ngram_host = false;
|
||||
const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
@@ -1106,6 +1121,12 @@ int Engine::plan() {
|
||||
weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk);
|
||||
f.statics = wf.statics;
|
||||
f.experts = wf.experts;
|
||||
/* The expert floor waits for the tables' placement: the embedding may take its share
|
||||
* of the host pool first. */
|
||||
wfs.push_back(wf);
|
||||
/* THE CACHE LENDS where units move and the pool can give its blocks back in place. */
|
||||
f.lends = VMem::supported() && !cfg_.deterministic &&
|
||||
(cfg_.placement == "auto" || cfg_.placement == "expert_tiered");
|
||||
emb_bytes.push_back(wf.embedding);
|
||||
ngram_bytes = std::max(ngram_bytes, wf.ngram);
|
||||
ngram_device = ngram_device || wf.ngram_device;
|
||||
@@ -1118,8 +1139,10 @@ int Engine::plan() {
|
||||
Config one = cfg_;
|
||||
one.max_seqs = 1;
|
||||
KVManager single;
|
||||
if (single.plan_groups(r->program.kv_groups, one) == RAD_OK)
|
||||
if (single.plan_groups(r->program.kv_groups, one) == RAD_OK) {
|
||||
kv_floor = std::max(kv_floor, single.ceiling(ctx));
|
||||
f.kv_one = single.ceiling(ctx);
|
||||
}
|
||||
}
|
||||
/* THE STAGING REGION IS SIZED ONLY WHERE THE ARENA LENDS ITS TOP: with no smaller level
|
||||
* nothing gives the region back to the slab at decode, and a deterministic plan moves
|
||||
@@ -1167,13 +1190,28 @@ int Engine::plan() {
|
||||
late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy);
|
||||
facts.push_back(f);
|
||||
}
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device,
|
||||
ngram_host));
|
||||
/* THE PINNED HOST POOL IS THE EXPERTS' OTHER HOME, less what Planner::plan takes out of it
|
||||
* before any expert: the embedding when it is placed there, and the file tier's staging.
|
||||
* Both floors are known before the tables are placed, so placing them can ask whether the
|
||||
* experts would still have a tier. */
|
||||
std::vector<int64_t> floor_emb_ram(facts.size(), 0);
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
int64_t room = cfg_.host_pool_mib * ((int64_t)1 << 20);
|
||||
if (cfg_.weights_disk_tier)
|
||||
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));
|
||||
floor_emb_ram[i] = expert_vram_floor(wfs[i], std::max<int64_t>(room - emb_bytes[i], 0));
|
||||
}
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, floor_emb_ram, 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];
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
facts[i].statics -= emb_bytes[i];
|
||||
facts[i].expert_floor = floor_emb_ram[i];
|
||||
}
|
||||
VramBudget vb;
|
||||
RAD_TRY(vram_budget_resolve(cfg_, facts, &vb));
|
||||
if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str());
|
||||
@@ -2002,10 +2040,6 @@ static int fill_from_checkpoint(const CkptWeight& cw, const std::vector<PlaneSha
|
||||
for (size_t k = 0; k < shares.size(); ++k) {
|
||||
const PlaneShare& sh = shares[k];
|
||||
uint8_t* at = in + offs[k];
|
||||
if (sh.zero) {
|
||||
std::memset(at, 0, (size_t)sh.dense_bytes());
|
||||
continue;
|
||||
}
|
||||
const RadEncPlane& p = cw.enc.plane[sel[k]];
|
||||
int64_t pr = 0, pc = 0;
|
||||
rad_enc_plane_dims(&p, cw.rows, cw.cols, &pr, &pc);
|
||||
@@ -2322,11 +2356,8 @@ int Engine::load_weights() {
|
||||
|
||||
/* FROM A CHECKPOINT, every weight is staged and its worker reads it: there is no
|
||||
* sweep to deliver it, and the stored form is whatever the pool makes of the share --
|
||||
* as it is, widened, or relaid. A ZERO SHARE (rad_weight_shard_zero) takes the same
|
||||
* route from a container: nothing in the file is its source, so no sweep run can
|
||||
* deliver it; its worker writes zeros and the pool stores them as it would any share. */
|
||||
const bool zero_share = sh[0].zero;
|
||||
if (!e || zero_share) {
|
||||
* as it is, widened, or relaid. */
|
||||
if (!e) {
|
||||
StagedWeight sw;
|
||||
sw.prog = &r->program;
|
||||
sw.wi = i;
|
||||
@@ -2351,17 +2382,9 @@ int Engine::load_weights() {
|
||||
std::vector<int> sel(w.sel, w.sel + w.n_sel);
|
||||
std::vector<int64_t> offs(sw.plane_off, sw.plane_off + w.n_sel);
|
||||
const std::string name = w.name;
|
||||
if (zero_share) {
|
||||
const int64_t bytes = in_bytes;
|
||||
sw.fill = [bytes](uint8_t* in) -> int {
|
||||
std::memset(in, 0, (size_t)bytes);
|
||||
return RAD_OK;
|
||||
};
|
||||
} else {
|
||||
sw.fill = [cw, shares, sel, offs, name](uint8_t* in) -> int {
|
||||
return fill_from_checkpoint(*cw, shares, sel, offs, name, in);
|
||||
};
|
||||
}
|
||||
sw.fill = [cw, shares, sel, offs, name](uint8_t* in) -> int {
|
||||
return fill_from_checkpoint(*cw, shares, sel, offs, name, in);
|
||||
};
|
||||
staged.push_back(std::move(sw));
|
||||
++n_loaded;
|
||||
continue;
|
||||
@@ -2447,16 +2470,6 @@ int Engine::load_weights() {
|
||||
const auto rt0 = std::chrono::steady_clock::now();
|
||||
int sw_st = RAD_OK;
|
||||
if (file_) {
|
||||
/* A WEIGHT WITH NO BYTES IN THE FILE -- a zero share -- is one the sweep never reaches: no
|
||||
* run of the container is its source, so nothing would ever arrive for it and its worker
|
||||
* would never run. It is handed to the workers here, whole, and its own fill writes it
|
||||
* (the checkpoint branch below does the same for every weight, which is why the hole was
|
||||
* never seen there). */
|
||||
for (size_t k = 0; k < staged.size() && !pool.failed(); ++k)
|
||||
if (staged[k].fill) {
|
||||
pool.reserve((int)k);
|
||||
pool.arrived((int)k, staged[k].remaining);
|
||||
}
|
||||
sw_st = sweep_container(file_.get(), runs, devices, &pool, &read_bytes);
|
||||
} else {
|
||||
/* every weight to the workers, in declaration order, as fast as the budget lets them in */
|
||||
@@ -2542,6 +2555,7 @@ int Engine::configure_kv() {
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
|
||||
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
|
||||
if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */
|
||||
if (least < 0 || t < least) least = t;
|
||||
}
|
||||
for (auto& r : ranks_) {
|
||||
@@ -2549,7 +2563,7 @@ int Engine::configure_kv() {
|
||||
RAD_TRY(rad_dev_set(r->device)); /* allocates on the CURRENT device; see plan() */
|
||||
if (ranks_.size() > 1) {
|
||||
const int64_t own = r->kv.paged_tokens(r->pools.kv().avail());
|
||||
if (own > least)
|
||||
if (own > least && own != KVManager::kUnboundedTokens)
|
||||
RAD_INFO("kv: rank %d could page %lld tokens and carves %lld, the least rank's, so "
|
||||
"that one block table serves every rank", r->index, (long long)own,
|
||||
(long long)least);
|
||||
@@ -2559,14 +2573,52 @@ int Engine::configure_kv() {
|
||||
/* THE ONE CASE WHERE THE CACHE CANNOT GIVE ANYTHING BACK, said once and named. Every
|
||||
* caller is written against the elastic contract and runs unchanged here -- the pool
|
||||
* simply holds its whole carve -- so nothing fails, and the only symptom is an expert
|
||||
* plane that never grows and a split that stays where --expert-vs-cache-ratio put it.
|
||||
* plane that never grows and a split that stays where the budget put it.
|
||||
* That is worth a line, because it is indistinguishable from a working run in every
|
||||
* counter this engine reports. */
|
||||
if (r->index == 0 && !r->pools.kv().elastic())
|
||||
RAD_WARN("this device has no virtual memory management, so the KV cache holds its "
|
||||
"whole carve and the expert slab has nothing to grow into. The split stays "
|
||||
"where --expert-vs-cache-ratio put it.");
|
||||
"whole carve and the expert slab has nothing to grow into. The experts were "
|
||||
"given the card first and the cache one full-length sequence.");
|
||||
if (cfg_.debug_placement) fputs(r->kv.report().c_str(), stderr);
|
||||
}
|
||||
|
||||
/* ---------------- the linear-state snapshot store ---------------- */
|
||||
/* PINNED HOST MEMORY, NOT THE CARD. A snapshot is a copy of a sequence's recurrent state that
|
||||
* no kernel reads: a save copies the state out after the step that produced it and a hit
|
||||
* copies it back before the step that resumes from it, each a few milliseconds across the
|
||||
* link. Holding it in VRAM would charge the KV pool for memory the live cache could use.
|
||||
*
|
||||
* One slot holds every rank's shard, each at its own offset, so the disk tier moves a slot as
|
||||
* one payload; rank 0's manager hands the ids out. Opened only where there is something to
|
||||
* snapshot and a cache to serve it. */
|
||||
{
|
||||
/* THE SHARDS NEED NOT BE EQUAL: a rank's state holds its own heads of each group, and a
|
||||
* world the heads do not divide gives the ranks different shares. A slot is the sum of
|
||||
* the ranks' shards and a rank's starts where the ranks before it end. */
|
||||
std::vector<int64_t> shard_off(ranks_.size(), 0);
|
||||
int64_t slot = 0;
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
shard_off[i] = slot;
|
||||
slot += ranks_[i]->kv.checkpoint_bytes();
|
||||
}
|
||||
const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0;
|
||||
if (slot > 0 && n > 0 && cfg_.prefix_cache) {
|
||||
if (ck_store_.open(slot, slot * n) != RAD_OK) {
|
||||
RAD_WARN("checkpoint slots: no pinned host memory for %lld snapshot(s) of %s; a "
|
||||
"hybrid session's prefix hits replay their linear layers from zero. "
|
||||
"Lower --checkpoint-slots.", (long long)n, humanb(slot).c_str());
|
||||
} else {
|
||||
RAD_INFO("checkpoint slots: %lld linear-state snapshot(s) of %s in pinned host "
|
||||
"memory (%s), none of it on the card", (long long)n,
|
||||
humanb(slot).c_str(), humanb(ck_store_.cap_bytes()).c_str());
|
||||
}
|
||||
}
|
||||
for (auto& r : ranks_)
|
||||
r->kv.set_checkpoint_store(&ck_store_, shard_off[(size_t)(&r - &ranks_[0])]);
|
||||
}
|
||||
for (auto& r : ranks_) {
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(r->prefix.configure(cfg_, &r->kv, geo_.checkpoint_interval));
|
||||
}
|
||||
|
||||
@@ -2594,23 +2646,19 @@ int Engine::configure_kv() {
|
||||
* at offsets of one entry, as it always was. The sizing below (TierExec::sizes) takes
|
||||
* the largest rank's entry: the staging ring is a rank's own, and the ring that fits
|
||||
* the largest fits every one. */
|
||||
std::vector<int64_t> rank_entry(ranks_.size(), 0), rank_ck(ranks_.size(), 0);
|
||||
std::vector<int64_t> entry_off(ranks_.size(), 0), ck_off(ranks_.size(), 0);
|
||||
int64_t entry_bytes = 0, slot_bytes = 0, ck_slot_bytes = 0;
|
||||
std::vector<int64_t> rank_entry(ranks_.size(), 0), entry_off(ranks_.size(), 0);
|
||||
int64_t entry_bytes = 0, slot_bytes = 0;
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
for (int32_t g : cg) {
|
||||
const KVGroupPlan* p = ranks_[i]->kv.plan(g);
|
||||
if (p && p->paged()) rank_entry[i] += p->bytes_per_block;
|
||||
}
|
||||
rank_ck[i] = ranks_[i]->kv.checkpoint_bytes();
|
||||
entry_off[i] = slot_bytes;
|
||||
ck_off[i] = ck_slot_bytes;
|
||||
slot_bytes += rank_entry[i];
|
||||
ck_slot_bytes += rank_ck[i];
|
||||
slot_bytes += rank_entry[i];
|
||||
entry_bytes = std::max(entry_bytes, rank_entry[i]);
|
||||
}
|
||||
|
||||
/* ---- how the tier is split between the two halves of a session ----
|
||||
/* ---- 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
|
||||
@@ -2635,8 +2683,12 @@ int Engine::configure_kv() {
|
||||
*
|
||||
* 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. */
|
||||
int64_t ck_host_cap = 0, ck_disk_slots = 0;
|
||||
* 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. */
|
||||
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();
|
||||
@@ -2649,19 +2701,13 @@ int Engine::configure_kv() {
|
||||
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 host_cap = cfg_.prefix_cache_host_mib << 20;
|
||||
const int64_t disk_cap = cfg_.prefix_cache_disk_mib << 20;
|
||||
const int64_t host_ck = std::min(host_cap * 2 / 3, denom > 0 ? host_cap / denom * sess_snaps
|
||||
+ host_cap % denom * sess_snaps / denom
|
||||
: 0);
|
||||
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_host_cap = (host_ck / ck_slot_bytes) * ck_slot_bytes;
|
||||
ck_disk_slots = disk_ck / ck_slot_bytes;
|
||||
/* One of each 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_host_cap == 0 && host_cap >= ck_slot_bytes * 2) ck_host_cap = 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) {
|
||||
@@ -2721,7 +2767,7 @@ int Engine::configure_kv() {
|
||||
tc.disk_cap_bytes = kv_disk_ ? (cfg_.prefix_cache_disk_mib << 20) : 0;
|
||||
tc.entry_bytes = slot_bytes;
|
||||
tc.ckpt_bytes = ck_slot_bytes;
|
||||
tc.ckpt_cap_bytes = ck_host_cap;
|
||||
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 --
|
||||
@@ -2774,7 +2820,7 @@ int Engine::configure_kv() {
|
||||
/*leader=*/&r == &ranks_[0],
|
||||
r->device,
|
||||
entry_off[(size_t)(&r - &ranks_[0])],
|
||||
ck_off[(size_t)(&r - &ranks_[0])],
|
||||
&ck_store_,
|
||||
/*shared=*/r->mover.transfer_stream())
|
||||
!= RAD_OK) {
|
||||
all = false;
|
||||
@@ -2790,7 +2836,7 @@ int Engine::configure_kv() {
|
||||
T.close();
|
||||
kv_disk_.reset();
|
||||
tc.host_cap_bytes = tc.disk_cap_bytes = 0;
|
||||
tc.ckpt_cap_bytes = tc.ckpt_disk_slots = 0;
|
||||
tc.ckpt_disk_slots = 0;
|
||||
RAD_TRY(T.configure(tc, nullptr));
|
||||
} else {
|
||||
/* The tiers can lose an entry without the cache asking: a capacity drop, or a
|
||||
@@ -2799,10 +2845,10 @@ 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. The snapshot store is far smaller than the
|
||||
* block store, so it overflows first and by itself; 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. */
|
||||
/* 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);
|
||||
});
|
||||
@@ -2867,9 +2913,10 @@ int Engine::configure_kv() {
|
||||
* that request is accepted by the API and can never complete, whatever the load. */
|
||||
RAD_WARN("kv group '%s' holds %lld tokens but the context limit is %lld: ONE request "
|
||||
"longer than %lld tokens is accepted by the API and then refused as too "
|
||||
"large to ever fit -- this is a hard limit, not a backing ratio. Raise "
|
||||
"--expert-vs-cache-ratio toward the cache (about %lld MiB more for the whole "
|
||||
"context), halve the cost a token with --kv-cache-dtype fp8, or lower "
|
||||
"large to ever fit -- this is a hard limit, not a backing ratio. Give the "
|
||||
"cache more (about %lld MiB for the whole context: a larger --host-pool-mib "
|
||||
"takes experts off the card), halve the cost a token with --kv-cache-dtype fp8, "
|
||||
"or lower "
|
||||
"--max-model-len to %lld.",
|
||||
p->name.c_str(), (long long)cap, (long long)want, (long long)cap,
|
||||
(long long)(((want - cap) / p->block_size * p->bytes_per_block) >> 20),
|
||||
@@ -2938,18 +2985,6 @@ static void bind_kv_pools(const Program& p, const KVManager& kv, std::vector<KVP
|
||||
}
|
||||
|
||||
/* ================================================================== start */
|
||||
void Engine::set_checkpoint_floors(int64_t keep) {
|
||||
for (auto& r : ranks_) {
|
||||
const int dev = r->device;
|
||||
r->kv.set_checkpoint_floor([dev](int64_t* free_now) -> int {
|
||||
RadDeviceProps p{};
|
||||
RAD_TRY(rad_dev_props(dev, &p));
|
||||
*free_now = p.vram_free;
|
||||
return RAD_OK;
|
||||
}, keep);
|
||||
}
|
||||
}
|
||||
|
||||
int Engine::start() {
|
||||
std::vector<int> devs;
|
||||
std::string inventory;
|
||||
@@ -3150,6 +3185,35 @@ int Engine::start() {
|
||||
}
|
||||
(void)rad_dev_set(ranks_[0]->device);
|
||||
|
||||
/* THE MOST THE CACHE CAN HOLD, said once in one line: the whole carve, with every block it lends
|
||||
* the experts taken back -- which a request that needs them does, the same step. Tokens are the
|
||||
* paged groups' shared axis, so the smallest of theirs; a windowed group bounds how far back a
|
||||
* sequence keeps context, not how much fits, and is left out. The /stats and /metrics figures
|
||||
* (kv_tokens_max, radiance:kv_cache_max_tokens) are the same numbers. */
|
||||
{
|
||||
const KVManager& kv = ranks_[0]->kv;
|
||||
int64_t bytes = 0, state = 0, tokens = 0;
|
||||
for (const KVGroupPlan& p : kv.plans()) {
|
||||
bytes += kv.pool_bytes_carved(p.index);
|
||||
if (p.stateful()) state += kv.pool_bytes_carved(p.index);
|
||||
if (!p.paged() || p.kind == RAD_KV_WINDOW || p.block_size <= 0) continue;
|
||||
const int64_t t = p.n_blocks * p.block_size;
|
||||
if (tokens == 0 || t < tokens) tokens = t;
|
||||
}
|
||||
const int64_t mlen = cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
const int64_t lent = lending_ ? ranks_[0]->mover.flex_capacity() : 0;
|
||||
if (bytes > 0)
|
||||
RAD_INFO("kv: the cache can grow to %s a card -- %lld tokens of context, %.1f sessions at "
|
||||
"%lld -- with every block it lends the experts taken back; %s of that is "
|
||||
"per-sequence state, and %s",
|
||||
humanb(bytes).c_str(), (long long)tokens,
|
||||
mlen > 0 ? (double)tokens / (double)mlen : 0.0, (long long)mlen,
|
||||
humanb(state).c_str(),
|
||||
lent > 0 ? fmt("up to %s is lent to the experts while no request holds it",
|
||||
humanb(lent).c_str()).c_str()
|
||||
: "nothing is lent: it is all the cache's");
|
||||
}
|
||||
|
||||
/* ---- AND THE TOP OF THE ACTIVATION ARENA, lent while the steps are small ----------------
|
||||
*
|
||||
* One stretch a rank: from the end of the full plan's transients down to the end of the
|
||||
@@ -3257,83 +3321,7 @@ int Engine::start() {
|
||||
*
|
||||
* A slack of one arena is tolerated silently: MiB rounding and a kernel plugin's own
|
||||
* workspaces live in there, and naming a number this close to right would be noise. */
|
||||
/* DOES A DECOMMIT GIVE THE CARD BACK? The checkpoint slots are the one part of the KV pool
|
||||
* backed on demand, and releasing a freed slot's pages is only worth a driver call where the
|
||||
* card actually gets them back. That is a claim about the driver rather than about the API,
|
||||
* so it is measured here, once, on a range nothing else owns: commit it, read the card,
|
||||
* decommit it, read again. tools/vmemprobe.cpp asks the same question in more detail, and on
|
||||
* ROCm 7.2 / gfx1201 the answer is no -- hipMemUnmap returns nothing, and a reservation is
|
||||
* charged for its high-water commit until hipMemAddressFree.
|
||||
*
|
||||
* The expert slab does not depend on the answer. It borrows the cache's idle blocks at the
|
||||
* addresses the cache already owns, so no page ever changes hands (Engine::loan_tick). */
|
||||
if (!ranks_.empty() && VMem::supported()) {
|
||||
VMem v;
|
||||
const int64_t g = VMem::granularity();
|
||||
const int64_t n = std::max<int64_t>(64ll << 20, g > 0 ? g * 16 : 0);
|
||||
RadDeviceProps a{}, b{};
|
||||
release_frees_card_ = false;
|
||||
if (rad_dev_set(ranks_[0]->device) >= 0 && v.reserve(n) >= 0 && v.commit(0, n) >= 0 &&
|
||||
rad_dev_props(ranks_[0]->device, &a) >= 0 && v.decommit(0, n) >= 0 &&
|
||||
rad_dev_props(ranks_[0]->device, &b) >= 0)
|
||||
release_frees_card_ = (b.vram_free - a.vram_free) > n / 2;
|
||||
for (auto& r : ranks_) r->kv.set_release_frees_card(release_frees_card_);
|
||||
if (!release_frees_card_)
|
||||
RAD_INFO("this driver does not return decommitted VRAM to the card (%s unmapped, the "
|
||||
"free counter did not move), so a freed checkpoint slot keeps its pages. The "
|
||||
"expert slab is unaffected: it borrows the cache's idle blocks in place.",
|
||||
humanb(n).c_str());
|
||||
}
|
||||
|
||||
/* A CHECKPOINT SLOT IS BACKED ON EVERY CARD BEFORE ITS ID IS HANDED OUT, AND NEVER INTO THE
|
||||
* HEADROOM. Rank 0's free list hands the ids out and every rank writes its shard of a snapshot
|
||||
* into the same slot of its own pool; backing a slot on one card and meeting a refusal on the
|
||||
* other at the snapshot copy would stop the engine mid-serve. See
|
||||
* KVManager::set_checkpoint_floor for why the floor is the headroom.
|
||||
*
|
||||
* AND NOT INTO WHAT THE BUDGET KEPT FOR LATER either: the step staging serve() allocates, and
|
||||
* what is built on first use. serve() lowers the floor once the staging exists. */
|
||||
const int64_t headroom = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * (1ll << 20);
|
||||
const int64_t keep_now = headroom + late_step_bytes_ + late_lazy_bytes_;
|
||||
if (!ranks_.empty()) {
|
||||
set_checkpoint_floors(keep_now);
|
||||
std::vector<KVManager*> peers;
|
||||
for (size_t i = 1; i < ranks_.size(); ++i) peers.push_back(&ranks_[i]->kv);
|
||||
ranks_[0]->kv.set_checkpoint_peers(std::move(peers));
|
||||
}
|
||||
/* AND ON A DRIVER THAT KEEPS WHAT IT MAPS, BACKED NOW. A slot backed later would cost the card
|
||||
* exactly what it costs now and could never be given back, so waiting would only move the
|
||||
* region's cost out of the reading below and into the middle of serving -- where the budget's
|
||||
* misses (allocations made after it was resolved) may already have taken part of it. Backed
|
||||
* here, the reading includes the slots, and a slot the cards have no room for is withdrawn
|
||||
* here and said so. */
|
||||
if (!release_frees_card_ && !ranks_.empty() && ranks_[0]->kv.free_checkpoint_slots() > 0) {
|
||||
KVManager& lead = ranks_[0]->kv;
|
||||
const int64_t asked = lead.free_checkpoint_slots();
|
||||
int64_t gone = 0;
|
||||
RAD_TRY(lead.back_free_checkpoints(&gone));
|
||||
if (gone > 0) {
|
||||
const int64_t stride = lead.checkpoint_stride();
|
||||
int64_t short_by = 0;
|
||||
for (auto& r : ranks_) {
|
||||
RadDeviceProps p{};
|
||||
if (rad_dev_props(r->device, &p) < 0) continue;
|
||||
short_by = std::max(short_by, gone * stride - (p.vram_free - keep_now));
|
||||
}
|
||||
RAD_WARN("checkpoint slots: %lld of %lld backed (%s each), %lld withdrawn -- one more "
|
||||
"would take a card under the %s it has to keep free: the %s "
|
||||
"--gpu-headroom-mib, the room a kernel's first launch allocates from, and %s "
|
||||
"the budget kept for the step staging and for what is built on first use. "
|
||||
"The prefix cache holds %lld linear-state snapshots on the card and its "
|
||||
"retention policy decides which. The budget counted all %lld; the card is %s "
|
||||
"short of them, which is allocations made after the budget was resolved.",
|
||||
(long long)(asked - gone), (long long)asked, humanb(stride).c_str(),
|
||||
(long long)gone, humanb(keep_now).c_str(), humanb(headroom).c_str(),
|
||||
humanb(late_step_bytes_ + late_lazy_bytes_).c_str(), (long long)(asked - gone),
|
||||
(long long)asked, humanb(short_by).c_str());
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& r : ranks_) {
|
||||
LogRank lr(r->index);
|
||||
RadDeviceProps props{};
|
||||
|
||||
@@ -13,23 +13,6 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
|
||||
return RAD_E_SHAPE;
|
||||
};
|
||||
if (w.n_sel < 1 || w.n_sel > RAD_ENC_MAX_PLANES) return refuse("no planes selected");
|
||||
/* A ZERO SHARE: the declaration's own extents of every selected plane, and nothing to read.
|
||||
* At one rank there is no share to zero -- the weight is whole and real. */
|
||||
if (w.shard_zero && world > 1) {
|
||||
for (int k = 0; k < w.n_sel; ++k) {
|
||||
const RadEncPlane& p = enc.plane[w.sel[k]];
|
||||
PlaneShare& s = out[k];
|
||||
s = PlaneShare{};
|
||||
s.dtype = p.dtype;
|
||||
s.rows = w.sel_rows[k];
|
||||
s.cols = w.sel_cols[k];
|
||||
s.row_bytes = rad_enc_row_bytes(p.dtype, s.cols);
|
||||
s.zero = true;
|
||||
if (s.rows <= 0 || s.cols <= 0)
|
||||
return refuse(fmt("a zero share of the '%s' plane has no extent", p.role));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
int64_t R = 0, C = 0;
|
||||
rad_enc_view(rank, shape, &R, &C);
|
||||
|
||||
|
||||
@@ -27,9 +27,6 @@ struct PlaneShare {
|
||||
uint32_t dtype = RAD_DT_INVALID;
|
||||
int64_t rows = 0, cols = 0; /* the share's extents, in the plane's elements */
|
||||
int64_t row_bytes = 0;
|
||||
/* rad_weight_shard_zero: the share has its extents and no rectangles; the loader writes
|
||||
* dense_bytes() of zeros and reads nothing. */
|
||||
bool zero = false;
|
||||
int64_t dense_bytes() const; /* the share laid out dense: rows * a row of `cols` */
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/* hostarena.cpp -- see hostarena.h. */
|
||||
#include "mem/hostarena.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
HostArena::~HostArena() { close(); }
|
||||
|
||||
int HostArena::open(int64_t slot_bytes, int64_t cap_bytes) {
|
||||
close();
|
||||
if (slot_bytes <= 0 || cap_bytes < slot_bytes) return RAD_E_INVAL;
|
||||
const int64_t n = cap_bytes / slot_bytes;
|
||||
/* PINNED, and the allocation is refused rather than downgraded. A pageable host buffer on
|
||||
* this path does not fail, it just collapses -- an async copy to pageable memory serialises
|
||||
* against the stream and the whole point of moving instead of dropping is gone. Better to
|
||||
* start without the store and say so than to run it at a tenth of the rate it was budgeted
|
||||
* at. */
|
||||
base_ = rad_dev_alloc(n * slot_bytes, RAD_MEM_HOST_PINNED);
|
||||
if (!base_) return RAD_E_NOMEM;
|
||||
slot_bytes_ = slot_bytes;
|
||||
used_ = 0;
|
||||
cap_slots_ = n;
|
||||
cursor_ = 0;
|
||||
bits_.assign((size_t)((n + 63) / 64), 0ull);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void HostArena::close() {
|
||||
if (base_) rad_dev_free(base_, RAD_MEM_HOST_PINNED);
|
||||
base_ = nullptr;
|
||||
slot_bytes_ = 0;
|
||||
used_ = 0;
|
||||
cap_slots_ = 0;
|
||||
cursor_ = 0;
|
||||
bits_.clear();
|
||||
}
|
||||
|
||||
int32_t HostArena::alloc() {
|
||||
int32_t got = 0;
|
||||
return alloc_run(1, &got);
|
||||
}
|
||||
|
||||
/* THE FIRST FREE RUN AT OR AFTER THE CURSOR, wrapping once. A whole word of used slots is skipped
|
||||
* in one compare, so a nearly full arena costs a scan of its bitmap -- a few thousand words at the
|
||||
* sizes an operator gives this -- and an arena with room costs nothing. The cursor makes
|
||||
* consecutive calls hand out consecutive slots, which is what lets a batch be one copy a run. */
|
||||
int32_t HostArena::alloc_run(int32_t want, int32_t* got) {
|
||||
*got = 0;
|
||||
if (want <= 0 || !base_ || full()) return -1;
|
||||
int64_t s = -1;
|
||||
for (int pass = 0; pass < 2 && s < 0; ++pass) {
|
||||
const int64_t lo = pass == 0 ? cursor_ : 0;
|
||||
const int64_t hi = pass == 0 ? cap_slots_ : cursor_;
|
||||
for (int64_t i = lo; i < hi;) {
|
||||
const uint64_t w = bits_[(size_t)(i >> 6)];
|
||||
if ((i & 63) == 0 && w == ~0ull) { i += 64; continue; }
|
||||
if (!is_used(i)) { s = i; break; }
|
||||
++i;
|
||||
}
|
||||
}
|
||||
if (s < 0) return -1;
|
||||
int64_t n = 0;
|
||||
while (n < want && s + n < cap_slots_ && !is_used(s + n)) {
|
||||
bits_[(size_t)((s + n) >> 6)] |= 1ull << ((s + n) & 63);
|
||||
++n;
|
||||
}
|
||||
used_ += n;
|
||||
cursor_ = s + n >= cap_slots_ ? 0 : s + n;
|
||||
*got = (int32_t)n;
|
||||
return (int32_t)s;
|
||||
}
|
||||
|
||||
void HostArena::free(int32_t slot) {
|
||||
if (slot < 0 || slot >= cap_slots_) return;
|
||||
/* A slot that is already free is refused rather than counted twice: the used count is what the
|
||||
* sessions view reports and what `full` answers, and a negative one hides the next leak. */
|
||||
if (!is_used(slot)) return;
|
||||
bits_[(size_t)(slot >> 6)] &= ~(1ull << (slot & 63));
|
||||
--used_;
|
||||
}
|
||||
|
||||
void* HostArena::at(int32_t slot) const {
|
||||
if (!base_ || slot < 0 || slot >= cap_slots_) return nullptr;
|
||||
return (char*)base_ + (int64_t)slot * slot_bytes_;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,63 @@
|
||||
/* hostarena.h -- fixed-size slots of pinned host memory.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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,
|
||||
* synchronises. Slot-allocated at one fixed size rather than malloc'd per object: every object a
|
||||
* store holds is the same size for a given model, so a bitmap is the whole allocator.
|
||||
*
|
||||
* RUNS, BECAUSE A TRANSFER IS PER RUN. A 4-token block makes a 200K-token conversation fifty
|
||||
* thousand entries, and a copy per entry is fifty thousand driver calls on the engine thread --
|
||||
* the call rate, not the link, is then what a restore costs. Slots taken together are given
|
||||
* consecutive ids wherever the arena has them, so a batch crosses the link as one strided copy
|
||||
* a run. */
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
class HostArena {
|
||||
public:
|
||||
~HostArena();
|
||||
int open(int64_t slot_bytes, int64_t cap_bytes);
|
||||
void close();
|
||||
bool enabled() const { return base_ != nullptr; }
|
||||
|
||||
int64_t slot_bytes() const { return slot_bytes_; }
|
||||
/* Fixed when the arena is opened. Stored rather than counted from the bitmap, because an
|
||||
* HTTP thread reads it for the sessions view while the engine thread allocates and frees. */
|
||||
int64_t capacity() const { return cap_slots_; }
|
||||
int64_t used_slots() const { return used_; }
|
||||
int64_t cap_bytes() const { return slot_bytes_ * capacity(); }
|
||||
int64_t free_slots() const { return cap_slots_ - used_; }
|
||||
|
||||
/* -1 when the arena is full. The caller evicts and retries; this does not choose victims,
|
||||
* because the policy that would choose them lives with the store's owner and an allocator
|
||||
* that reached into it would give each object two owners. */
|
||||
bool full() const { return used_ >= cap_slots_; }
|
||||
int32_t alloc();
|
||||
/* UP TO `want` CONSECUTIVE SLOTS, the first free run at or after the cursor. `*got` is how
|
||||
* many; the caller asks again for the rest. -1 when the arena is full. */
|
||||
int32_t alloc_run(int32_t want, int32_t* got);
|
||||
void free(int32_t slot);
|
||||
bool in_use(int32_t slot) const { return slot >= 0 && slot < cap_slots_ && is_used(slot); }
|
||||
void* at(int32_t slot) const;
|
||||
|
||||
private:
|
||||
bool is_used(int64_t s) const { return (bits_[(size_t)(s >> 6)] >> (s & 63)) & 1ull; }
|
||||
void* base_ = nullptr;
|
||||
int64_t slot_bytes_ = 0;
|
||||
int64_t used_ = 0;
|
||||
int64_t cap_slots_ = 0;
|
||||
int64_t cursor_ = 0;
|
||||
std::vector<uint64_t> bits_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+80
-224
@@ -100,7 +100,8 @@ int KVManager::configure(const std::vector<KVGroupInfo>& groups, const Config& c
|
||||
}
|
||||
|
||||
int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg) {
|
||||
/* The snapshot count is the operator's, through --checkpoint-slots. Nothing here derives it. */
|
||||
/* Only to say it is ignored on a model with no recurrent state: the slots are host memory and
|
||||
* the engine opens them (set_checkpoint_store). */
|
||||
const int64_t budget_ckpts = cfg.checkpoint_slots > 0 ? cfg.checkpoint_slots : 0;
|
||||
|
||||
forget();
|
||||
@@ -285,37 +286,12 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
int64_t fixed = 0;
|
||||
for (const auto& p : plans_)
|
||||
if (p.stateful()) fixed += align_up(p.bytes_per_state * p.n_states, RAD_ALIGN_UNIT);
|
||||
/* A SLOT IS ELASTIC ONLY WHEN A SNAPSHOT IS WORTH A GRANULE, and the stride follows from
|
||||
* that. Committing and releasing a slot on its own needs the stride to be a whole number of
|
||||
* granules: a commit rounds outward and a release rounds inward, so a straddling stride
|
||||
* would leave every slot's last partial granule backed for the life of the process and let
|
||||
* one slot's commit back part of its neighbour.
|
||||
*
|
||||
* That rounding is free on a linear-attention model, where a snapshot is a sizeable fraction
|
||||
* of a gigabyte. It is not free on a small one: a 16 KiB snapshot rounded to a 2 MiB granule
|
||||
* is 128x the address space to manage a charge that was never worth managing. Below a
|
||||
* granule the slots stay in the eagerly committed region, where they cost what they say
|
||||
* they cost and nothing reclaims them because there is nothing to reclaim. */
|
||||
const int64_t granule = Pool::granule();
|
||||
ck_elastic_ = granule > 0 && checkpoint_bytes_ >= granule;
|
||||
ck_stride_ = align_up(checkpoint_bytes_, ck_align());
|
||||
/* AND THE PAD IN FRONT OF THE REGION IS PART OF ITS COST. The slots are reserved LAST, after
|
||||
* every group, and on a ck_align() boundary -- so the region starts up to one alignment unit
|
||||
* past wherever the groups happened to end. Where that is cannot be known here, because the
|
||||
* paged split below is what decides it, so the whole unit is reserved rather than the exact
|
||||
* pad: it is at most one commit granule against a pool measured in gigabytes, and the
|
||||
* alternative is a budget the LAST slot falls off the end of -- a refusal at load on some
|
||||
* models and not others, depending on where the groups happened to end. */
|
||||
const int64_t ck_pad = budget_ckpts > 0 ? ck_align() : 0;
|
||||
const int64_t ck_total = budget_ckpts * ck_stride_ + ck_pad;
|
||||
fixed += ck_total;
|
||||
/* And one unit a paged group, for the same reason: a page size that is not a multiple of the
|
||||
* alignment pads too, and the carve below hands the groups everything that is left. */
|
||||
for (const auto& p : plans_) if (p.paged()) fixed += RAD_ALIGN_UNIT;
|
||||
|
||||
fixed_ = fixed;
|
||||
ck_total_ = ck_total;
|
||||
ckpts_ = budget_ckpts;
|
||||
fixed_ = fixed;
|
||||
ckpts_ = budget_ckpts;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -361,11 +337,7 @@ void KVManager::forget() {
|
||||
chunk_blocks_.clear(); short_peak_.clear();
|
||||
pool_ = nullptr;
|
||||
clears_.clear();
|
||||
seqs_.clear(); pending_.clear(); ck_slot_base_.clear(); ck_free_.clear();
|
||||
ck_stride_ = ck_region_off_ = 0;
|
||||
ck_elastic_ = false;
|
||||
ck_high_water_ = 0;
|
||||
ck_backed_ = 0;
|
||||
seqs_.clear(); pending_.clear();
|
||||
configured_ = false;
|
||||
report_.clear();
|
||||
}
|
||||
@@ -376,8 +348,22 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
|
||||
* run out of full-attention blocks with a window pool still half empty. */
|
||||
std::vector<int64_t> out(plans_.size(), 0);
|
||||
int64_t remaining = budget_bytes - fixed_;
|
||||
std::vector<int32_t> open;
|
||||
for (const auto& p : plans_) if (p.paged()) open.push_back(p.index);
|
||||
/* A ZERO GROUP COSTS THIS RANK NOTHING, so it takes no part in the split: it holds the
|
||||
* shared table's block count, which is what the costed groups settle on (here, or under the
|
||||
* cap, on the rank that does hold the cache). */
|
||||
std::vector<int32_t> open, zeros;
|
||||
for (const auto& p : plans_)
|
||||
if (p.paged()) (p.zero ? zeros : open).push_back(p.index);
|
||||
/* Every paged group zero: nothing on this rank limits the token count. The cap is what the
|
||||
* ranks that hold the cache carve, and without one there is no figure to report. */
|
||||
if (open.empty() && !zeros.empty()) {
|
||||
const int64_t tokens = tokens_cap_ > 0 ? tokens_cap_ : kUnboundedTokens;
|
||||
if (blocks) {
|
||||
for (int32_t i : zeros) out[i] = zero_blocks(plans_[i], tokens);
|
||||
*blocks = std::move(out);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
int64_t tokens = 0;
|
||||
while (!open.empty() && remaining > 0) {
|
||||
@@ -404,34 +390,34 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
|
||||
open.erase(std::find(open.begin(), open.end(), capped));
|
||||
}
|
||||
for (int32_t i : open) out[i] = remaining > 0 ? tokens / plans_[i].block_size : 0;
|
||||
for (int32_t i : zeros) out[i] = remaining > 0 ? zero_blocks(plans_[i], tokens) : 0;
|
||||
if (blocks) *blocks = std::move(out);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
|
||||
if (tokens == kUnboundedTokens) return 0;
|
||||
const int64_t b = tokens / p.block_size;
|
||||
if (p.kind == RAD_KV_WINDOW && b > max_seqs_ * p.window_blocks) return max_seqs_ * p.window_blocks;
|
||||
return b;
|
||||
}
|
||||
|
||||
int KVManager::carve_into(Pool& kv_pool) {
|
||||
/* The pool is whatever the operator stated or the resolver derived; nothing here re-decides
|
||||
* it. What this does decide is how the groups share it, which is arithmetic, not policy. */
|
||||
const int64_t budget_bytes = kv_pool.avail();
|
||||
const int64_t budget_ckpts = ckpts_;
|
||||
const int64_t fixed = fixed_;
|
||||
const int64_t ck_total = ck_total_;
|
||||
pool_base_ = kv_pool.base();
|
||||
pool_ = &kv_pool;
|
||||
|
||||
if (fixed >= budget_bytes) {
|
||||
RAD_ERR("vram_kv does not fit its fixed costs:\n"
|
||||
" linear/conv state %10s (%lld sequences)\n"
|
||||
" checkpoints %10s (%lld x %s)\n"
|
||||
" ------------------------------\n"
|
||||
" fixed %10s\n"
|
||||
" --vram-kv-mib %10s\n"
|
||||
" SHORT BY %10s\n"
|
||||
"Lower --max-seqs or the checkpoint slot count, or raise --vram-kv-mib. "
|
||||
"The engine will not shrink one of them for you (spec §6).",
|
||||
humanb(fixed - ck_total).c_str(), (long long)max_seqs_,
|
||||
humanb(ck_total).c_str(), (long long)budget_ckpts,
|
||||
humanb(ck_stride_).c_str(),
|
||||
humanb(fixed).c_str(), humanb(budget_bytes).c_str(),
|
||||
"Lower --max-seqs or raise --vram-kv-mib. The engine will not shrink one of them "
|
||||
"for you (spec §6).",
|
||||
humanb(fixed).c_str(), (long long)max_seqs_, humanb(budget_bytes).c_str(),
|
||||
humanb(fixed - budget_bytes + 1).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
@@ -444,10 +430,16 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
|
||||
for (auto& p : plans_) {
|
||||
if (!p.paged()) continue;
|
||||
if (p.n_blocks <= 0 && p.zero) {
|
||||
RAD_ERR("KV group '%s' is zero on this rank and nothing set its block count: a zero "
|
||||
"group holds what the ranks keeping the cache carve, and no cap from them was "
|
||||
"given (cap_paged_tokens)", p.name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (p.n_blocks <= 0) {
|
||||
RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed "
|
||||
"linear/conv costs of %s. Raise --vram-kv-mib, lower --expert-vs-cache-ratio, "
|
||||
"or lower --max-seqs.",
|
||||
"linear/conv costs of %s. Raise --vram-kv-mib or --host-pool-mib, or lower "
|
||||
"--max-seqs.",
|
||||
p.name.c_str(), humanb(budget_bytes).c_str(),
|
||||
humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
@@ -456,11 +448,9 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
|
||||
/* ---- carve. Every reservation comes from the KV pool and only from the KV pool: the mover
|
||||
* works inside the weight slab and cannot reach this (spec §6). ---- */
|
||||
int64_t paged_taken = 0;
|
||||
for (auto& p : plans_) {
|
||||
int64_t bytes = p.paged() ? p.n_blocks * p.bytes_per_block
|
||||
: p.n_states * p.bytes_per_state;
|
||||
if (p.paged()) paged_taken += bytes;
|
||||
if (p.zero) {
|
||||
p.base = nullptr;
|
||||
p.pool_offset = 0;
|
||||
@@ -481,30 +471,11 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
p.pool_offset = off;
|
||||
p.pool_bytes = bytes;
|
||||
}
|
||||
/* --checkpoint-slots on a model with no recurrent state buys nothing, and allocating zero-byte
|
||||
/* --checkpoint-slots on a model with no recurrent state buys nothing, and opening zero-byte
|
||||
* slots for it would leave the operator's flag looking honoured. Ignore it and say so. */
|
||||
if (budget_ckpts > 0 && checkpoint_bytes_ <= 0)
|
||||
if (ckpts_ > 0 && checkpoint_bytes_ <= 0)
|
||||
RAD_WARN("--checkpoint-slots %lld ignored: this model declares no linear-attention state, "
|
||||
"so there is nothing to snapshot", (long long)budget_ckpts);
|
||||
for (int64_t i = 0; checkpoint_bytes_ > 0 && i < budget_ckpts; ++i) {
|
||||
int64_t off = 0;
|
||||
if (!kv_pool.reserve("linear checkpoint", ck_stride_, ck_align(), &off)
|
||||
&& !kv_pool.accounting_only()) {
|
||||
/* The arithmetic that is supposed to make this impossible, printed next to the
|
||||
* failure: `fixed` reserved budget_ckpts * checkpoint_bytes_ up front, so a checkpoint
|
||||
* that does not fit means the paged carve above spent more than `remaining`. */
|
||||
RAD_ERR("linear checkpoint slot %lld (%lld B) did not fit the KV pool: %lld B of "
|
||||
"%lld B left after the paged groups took %lld B against a %lld B share",
|
||||
(long long)i, (long long)checkpoint_bytes_,
|
||||
(long long)kv_pool.avail(), (long long)budget_bytes,
|
||||
(long long)paged_taken, (long long)(budget_bytes - fixed));
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
if (i == 0) ck_region_off_ = off;
|
||||
ck_slot_base_.push_back(off);
|
||||
ck_free_.push_back((int32_t)i);
|
||||
}
|
||||
std::reverse(ck_free_.begin(), ck_free_.end()); /* pop_back hands out slot 0 first */
|
||||
"so there is nothing to snapshot", (long long)ckpts_);
|
||||
|
||||
/* ---- free lists ---- */
|
||||
free_blocks_.resize(plans_.size());
|
||||
@@ -542,36 +513,13 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
*
|
||||
* The fixed part -- recurrent state and conv slots -- is never released. It is sized per
|
||||
* sequence rather than per token, so there is no idle fraction of it to give back, and a
|
||||
* state slot cannot be re-created on demand the way a page can.
|
||||
*
|
||||
* CHECKPOINT SLOTS ARE NOT PART OF THAT. They are a CACHE -- the retention policy creates and
|
||||
* retires them all run, and a slot nobody has taken holds nothing that has to survive -- so
|
||||
* backing them all here would make --checkpoint-slots a standing VRAM charge whether or not a
|
||||
* snapshot exists. On a linear-attention model a slot is a sizeable fraction of a gigabyte,
|
||||
* and on a card whose experts do not fit that charge is decode step time. The region is left
|
||||
* unbacked and each slot is committed as it is handed out, which makes the flag a cap. */
|
||||
* state slot cannot be re-created on demand the way a page can. */
|
||||
if (pool_ && pool_->elastic()) {
|
||||
/* EVERYTHING EXCEPT THE CHECKPOINT REGION. The slots are reserved last, so the
|
||||
* second range is empty and this is a prefix -- written as a hole anyway, because
|
||||
* "commit everything below the slots" is the rule and "the slots are at the end" is a
|
||||
* detail of the carve above that nothing here should depend on. A prefix that stopped at
|
||||
* a region in the MIDDLE would leave every group past it addressable and unbacked, and
|
||||
* the paged groups are live from the first step: a fault at a valid-looking address on
|
||||
* the first write, which is the worst shape this class of bug has.
|
||||
*
|
||||
* Both edges are granule-aligned by construction (the slot reserve asks for ck_align()
|
||||
* and the stride is a whole number of granules), so neither commit rounds outward into
|
||||
* the region. That alignment is the whole reason it can be skipped at all. */
|
||||
const int64_t used = pool_->used();
|
||||
const int64_t hole_off = ck_elastic_ && !ck_slot_base_.empty() ? ck_region_off_ : used;
|
||||
const int64_t hole_end = ck_elastic_ && !ck_slot_base_.empty()
|
||||
? ck_slot_base_.back() + ck_stride_
|
||||
: used;
|
||||
int rc = pool_->commit(0, hole_off);
|
||||
if (rc >= 0 && used > hole_end) rc = pool_->commit(hole_end, used - hole_end);
|
||||
const int64_t used = pool_->used();
|
||||
const int rc = pool_->commit(0, used);
|
||||
if (rc < 0) {
|
||||
RAD_ERR("KV pool: the carve reserved %s of address space and the card would not back "
|
||||
"it", humanb(used - (hole_end - hole_off)).c_str());
|
||||
"it", humanb(used).c_str());
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
@@ -618,19 +566,12 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
}
|
||||
/* WHERE EACH GROUP STARTS, SO A FAULT ADDRESS CAN BE PLACED. A GPU memory fault names an
|
||||
* address and nothing else, and without this the only way to tell "kv_attn layer 7" from
|
||||
* "checkpoint slot 3" is to reconstruct the carve by hand from the sizes above. One line. */
|
||||
report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld, checkpoints at +%lld\n",
|
||||
* "kv_gdn_state slot 3" is to reconstruct the carve by hand from the sizes above. One line. */
|
||||
report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld\n",
|
||||
pool_base_, humanb(pool_ ? pool_->bytes() : 0).c_str(),
|
||||
(long long)(plans_.size() > 1 ? plans_[1].pool_offset : 0),
|
||||
(long long)(plans_.empty() ? 0 : plans_.back().pool_offset +
|
||||
plans_.back().pool_bytes),
|
||||
(long long)(ck_slot_base_.empty() ? 0 : ck_slot_base_.front()));
|
||||
if (checkpoint_bytes_ > 0)
|
||||
report_ += fmt(
|
||||
" %-14s %-6s %lld slots x %s = %s%s\n", "checkpoints", "linear",
|
||||
(long long)ck_slot_base_.size(), humanb(ck_stride_).c_str(),
|
||||
humanb((int64_t)ck_slot_base_.size() * ck_stride_).c_str(),
|
||||
ck_elastic_ ? " (address space; backed as slots are taken)" : "");
|
||||
plans_.back().pool_bytes));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -781,73 +722,6 @@ int64_t KVManager::buffer_bytes() const {
|
||||
return b;
|
||||
}
|
||||
|
||||
int64_t KVManager::ck_reserve_bytes() const {
|
||||
if (!ck_elastic_ || ck_stride_ <= 0) return 0;
|
||||
/* Counted from what is BACKED and not from the free list, because a rank that is not the one
|
||||
* holding the free list still backs the slots it writes, and its reserve has to cover them. */
|
||||
const int64_t want = std::min(ckpts_, ck_high_water_ + 1);
|
||||
return want > ck_backed_ ? (want - ck_backed_) * ck_stride_ : 0;
|
||||
}
|
||||
|
||||
bool KVManager::ck_backed(int32_t slot) const {
|
||||
if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return false;
|
||||
if (!ck_elastic_ || !pool_ || !pool_->elastic() || ck_stride_ <= 0) return true;
|
||||
return pool_->is_committed(ck_slot_base_[(size_t)slot], ck_stride_);
|
||||
}
|
||||
|
||||
int KVManager::ck_room(int32_t slot) const {
|
||||
if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return RAD_E_INVAL;
|
||||
if (ck_backed(slot) || !ck_free_bytes_ || ck_keep_free_ <= 0) return RAD_OK;
|
||||
int64_t free_now = 0;
|
||||
RAD_TRY(ck_free_bytes_(&free_now));
|
||||
return free_now - ck_stride_ >= ck_keep_free_ ? RAD_OK : RAD_E_FULL;
|
||||
}
|
||||
|
||||
int KVManager::ck_commit(int32_t slot) {
|
||||
if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return RAD_E_INVAL;
|
||||
if (ck_backed(slot)) return RAD_OK;
|
||||
if (pool_->commit(ck_slot_base_[(size_t)slot], ck_stride_) < 0) return RAD_E_FULL;
|
||||
if (++ck_backed_ > ck_high_water_) ck_high_water_ = ck_backed_;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int KVManager::back_checkpoint(int32_t slot) {
|
||||
RAD_TRY(ck_room(slot));
|
||||
return ck_commit(slot);
|
||||
}
|
||||
|
||||
/* EVERY CARD'S ANSWER BEFORE ANY CARD'S PAGES. Asking first means a slot one card refuses costs
|
||||
* the others nothing: on a driver that keeps what it maps, pages committed for a slot that is then
|
||||
* not handed out would be charged to that card for the life of the process. */
|
||||
int KVManager::ck_back_everywhere(int32_t slot) {
|
||||
RAD_TRY(ck_room(slot));
|
||||
for (KVManager* p : ck_peers_) RAD_TRY(p->ck_room(slot));
|
||||
RAD_TRY(ck_commit(slot));
|
||||
for (KVManager* p : ck_peers_) RAD_TRY(p->ck_commit(slot));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int KVManager::back_free_checkpoints(int64_t* withdrawn) {
|
||||
std::vector<int32_t> keep;
|
||||
keep.reserve(ck_free_.size());
|
||||
int64_t gone = 0;
|
||||
for (const int32_t s : ck_free_) {
|
||||
const int rc = ck_back_everywhere(s);
|
||||
if (rc == RAD_E_FULL) { ++gone; continue; }
|
||||
if (rc < 0) return rc;
|
||||
keep.push_back(s);
|
||||
}
|
||||
ck_free_.swap(keep);
|
||||
if (withdrawn) *withdrawn = gone;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t KVManager::ck_align() const {
|
||||
if (!ck_elastic_) return (int64_t)RAD_ALIGN_UNIT;
|
||||
const int64_t g = Pool::granule();
|
||||
return g > (int64_t)RAD_ALIGN_UNIT ? g : (int64_t)RAD_ALIGN_UNIT;
|
||||
}
|
||||
|
||||
/* WHAT THE GROUP CAN STILL HAND OUT, WHICH IS NOT WHAT IT HAS BELOW THE MARK. A lent block is
|
||||
* still carved, still addressed and still the operator's budget -- it is one recall away, and the
|
||||
* recall happens on the path that needs it. So every admission decision is made against this
|
||||
@@ -1447,47 +1321,27 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens,
|
||||
* caller sees RAD_E_FULL, which is the answer it already handles -- the retention policy runs and
|
||||
* the allocation is retried. Anything else would turn a card that is momentarily busy into a
|
||||
* failed request. */
|
||||
void KVManager::set_checkpoint_store(HostArena* store, int64_t rank_off) {
|
||||
ck_store_ = store && store->enabled() ? store : nullptr;
|
||||
ck_rank_off_ = rank_off;
|
||||
}
|
||||
|
||||
int KVManager::alloc_checkpoint(int32_t* slot_out) {
|
||||
if (ck_free_.empty()) return RAD_E_FULL;
|
||||
/* A SLOT EVERY CARD HAS BACKED ALREADY, WHERE ONE IS FREE: it costs no commit and no reading
|
||||
* of the card, and a card at its floor still has every slot it backed before. Otherwise the
|
||||
* top of the free list, backed on every card or not handed out at all. */
|
||||
size_t at = ck_free_.size() - 1;
|
||||
for (size_t i = ck_free_.size(); i-- > 0;) {
|
||||
const int32_t s = ck_free_[i];
|
||||
bool all = ck_backed(s);
|
||||
for (const KVManager* p : ck_peers_) all = all && p->ck_backed(s);
|
||||
if (all) { at = i; break; }
|
||||
}
|
||||
const int32_t slot = ck_free_[at];
|
||||
const int rc = ck_back_everywhere(slot);
|
||||
if (rc < 0) return rc;
|
||||
ck_free_.erase(ck_free_.begin() + (std::ptrdiff_t)at);
|
||||
if (!ck_store_ || checkpoint_bytes_ <= 0) return RAD_E_FULL;
|
||||
const int32_t slot = ck_store_->alloc();
|
||||
if (slot < 0) return RAD_E_FULL;
|
||||
*slot_out = slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void KVManager::free_checkpoint(int32_t slot) {
|
||||
if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return;
|
||||
for (int32_t f : ck_free_) if (f == slot) return; /* double free: refuse, do not corrupt */
|
||||
ck_free_.push_back(slot);
|
||||
/* AFTER the free list, so a release the driver refuses still leaves the slot allocatable: the
|
||||
* next commit of the same range is idempotent and the bytes are correct either way. */
|
||||
/* AND ONLY WHERE A RELEASE IS WORTH MAKING. See set_release_frees_card: on a driver that does
|
||||
* not return decommitted VRAM, unmapping these pages buys the card nothing and costs a commit
|
||||
* on the next allocation of the slot. It is not merely wasted work: the range is unmapped
|
||||
* while the slot id goes straight back on the free list, so anything still addressing it
|
||||
* reads a page that is no longer there. */
|
||||
if (ck_elastic_ && release_frees_card_ && pool_ && pool_->elastic() && ck_stride_ > 0) {
|
||||
const int64_t off = ck_slot_base_[(size_t)slot];
|
||||
if (pool_->is_committed(off, ck_stride_) && ck_backed_ > 0) --ck_backed_;
|
||||
(void)pool_->decommit(off, ck_stride_);
|
||||
}
|
||||
if (ck_store_) ck_store_->free(slot);
|
||||
}
|
||||
|
||||
void* KVManager::checkpoint_ptr(int32_t slot) const {
|
||||
if (!pool_base_ || slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return nullptr;
|
||||
return (char*)pool_base_ + ck_slot_base_[(size_t)slot];
|
||||
if (!ck_store_) return nullptr;
|
||||
char* p = (char*)ck_store_->at(slot);
|
||||
return p ? p + ck_rank_off_ : nullptr;
|
||||
}
|
||||
|
||||
/* One walk, both directions. Keeping save and restore as a single traversal is deliberate: the
|
||||
@@ -1496,14 +1350,16 @@ void* KVManager::checkpoint_ptr(int32_t slot) const {
|
||||
* functions that could stop agreeing. */
|
||||
int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot,
|
||||
bool save, RadStream s) {
|
||||
/* THIS RANK'S PAGES, BEFORE THIS RANK'S COPY. alloc_checkpoint backed the slot on every rank
|
||||
* before it handed the id out, so this finds it backed; a refusal here is a slot that did not
|
||||
* come from there. See KVManager::back_checkpoint. */
|
||||
RAD_TRY(back_checkpoint(ck_slot));
|
||||
/* A SLOT NOBODY HOLDS IS NOT ONE TO WRITE. Rank 0 hands the ids out, so a follower checks the
|
||||
* shared store rather than a list of its own. */
|
||||
if (!ck_store_ || !ck_store_->in_use(ck_slot)) return RAD_E_INVAL;
|
||||
char* ck = (char*)checkpoint_ptr(ck_slot);
|
||||
if (!ck) return RAD_E_INVAL;
|
||||
if (!state_slots || n_slots < (int)plans_.size()) return RAD_E_INVAL;
|
||||
|
||||
/* ONE PITCHED COPY A GROUP. Within a group the state of one sequence is a row a layer, one
|
||||
* layer_stride apart in the pool and packed end to end in the slot, so a group's whole share
|
||||
* crosses the link as one launch rather than a launch a layer. */
|
||||
int64_t off = 0;
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
@@ -1511,19 +1367,19 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
|
||||
const int32_t slot = state_slots[g];
|
||||
if (slot < 0) return RAD_E_STATE; /* no state to save, or none to restore into */
|
||||
const int64_t nbytes = p.layer_bytes_per_state();
|
||||
for (int64_t l = 0; l < p.n_layers; ++l) {
|
||||
void* st = state_ptr((int32_t)g, (int32_t)l, slot);
|
||||
if (!st) return RAD_E_STATE;
|
||||
if (off + nbytes > checkpoint_bytes_) {
|
||||
RAD_ERR("checkpoint slot %d holds %lld bytes and this sequence's linear state "
|
||||
"needs more than that; configure() sized it from the same plans, so the "
|
||||
"two have gone out of step", (int)ck_slot, (long long)checkpoint_bytes_);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
RAD_TRY(save ? rad_memcpy_async(ck + off, st, nbytes, s)
|
||||
: rad_memcpy_async(st, ck + off, nbytes, s));
|
||||
off += nbytes;
|
||||
void* st = state_ptr((int32_t)g, 0, slot);
|
||||
if (!st || p.n_layers <= 0) return RAD_E_STATE;
|
||||
if (off + nbytes * p.n_layers > checkpoint_bytes_) {
|
||||
RAD_ERR("checkpoint slot %d holds %lld bytes a rank and this sequence's linear state "
|
||||
"needs more than that; the store was sized from the same plans, so the two "
|
||||
"have gone out of step", (int)ck_slot, (long long)checkpoint_bytes_);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
RAD_TRY(save ? rad_memcpy_2d_async(ck + off, nbytes, st, p.layer_stride(), nbytes,
|
||||
p.n_layers, s)
|
||||
: rad_memcpy_2d_async(st, p.layer_stride(), ck + off, nbytes, nbytes,
|
||||
p.n_layers, s));
|
||||
off += nbytes * p.n_layers;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+36
-98
@@ -18,6 +18,7 @@
|
||||
* one of the two allocators keeps handing its state slot to the next request.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/hostarena.h"
|
||||
#include "mem/pools.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
@@ -155,11 +156,10 @@ public:
|
||||
* exhaust at the same total token count, and any other split strands memory in whichever
|
||||
* group outlasts the others.
|
||||
*
|
||||
* Both budgets come from the operator and neither is derived here: the byte budget is whatever
|
||||
* `kv_pool` still has (which is --vram-kv-mib), and the linear-snapshot count is
|
||||
* Config::checkpoint_slots (--checkpoint-slots). A checkpoint is ~96 MiB on a Qwen3-Next and
|
||||
* 64 of them is 6 GiB, so how many to retain is a budget decision and therefore not this
|
||||
* component's to make (spec §6, §7.3). */
|
||||
* The byte budget comes from the operator and is not derived here: it is whatever `kv_pool`
|
||||
* still has (which is --vram-kv-mib). The linear-state snapshots take none of it -- they live
|
||||
* in pinned host memory (set_checkpoint_store) -- so the pool is the live cache and nothing
|
||||
* else (spec §6, §7.3). */
|
||||
int configure(const std::vector<KVGroupInfo>& groups, const Config& cfg, Pool& kv_pool);
|
||||
|
||||
/* configure(), split at the seam the budget resolver needs. plan_groups() sizes every group
|
||||
@@ -170,14 +170,17 @@ public:
|
||||
int plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg);
|
||||
int64_t ceiling(int64_t ctx) const;
|
||||
/* The part of every ceiling that is not context: recurrent and conv state for max_seqs
|
||||
* sequences, the checkpoint slots and the padding. Set by plan_groups(). */
|
||||
* sequences, and the padding. Set by plan_groups(). */
|
||||
int64_t fixed_bytes() const { return fixed_; }
|
||||
/* THE TOKEN COUNT THE PAGED GROUPS SETTLE ON for `budget_bytes` of pool -- carve()'s split
|
||||
* with nothing carved. One block table serves every rank, so every rank's paged groups must
|
||||
* hold the SAME number of blocks; under an uneven tensor-parallel split the ranks' pools are
|
||||
* not the same size (a rank with more delta-net heads holds more state and has less left for
|
||||
* pages, and a rank with no attention weights has more). The engine asks each rank this and
|
||||
* cap_paged_tokens() the least on all of them before carve(). 0 is no cap. */
|
||||
* cap_paged_tokens() the least on all of them before carve(). 0 is no cap.
|
||||
* kUnboundedTokens when every paged group of this rank is zero (rad_kv_group_zero): its pages
|
||||
* cost it nothing, so it takes what the ranks holding the cache carve and limits nobody. */
|
||||
static constexpr int64_t kUnboundedTokens = INT64_MAX;
|
||||
int64_t paged_tokens(int64_t budget_bytes) const { return paged_split(budget_bytes, nullptr); }
|
||||
void cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; }
|
||||
int carve(Pool& kv_pool);
|
||||
@@ -348,12 +351,6 @@ public:
|
||||
* recalled and the request is refused (RAD_E_FULL). */
|
||||
void set_reclaim(std::function<int(int64_t tokens)> f) { reclaim_ = std::move(f); }
|
||||
|
||||
/* WHETHER A DECOMMIT ACTUALLY GIVES THE CARD BACK, for the checkpoint region, which is the one
|
||||
* part of the pool still backed on demand. Measured once at bringup rather than assumed,
|
||||
* because it is a property of the driver: where it is false a freed checkpoint slot keeps its
|
||||
* pages, since unmapping them would cost driver calls and return nothing. */
|
||||
void set_release_frees_card(bool yes) { release_frees_card_ = yes; }
|
||||
|
||||
/* MATCH A LEADER'S LOAN, FOR A RANK THAT DOES NOT KNOW WHAT IT IS HOLDING.
|
||||
*
|
||||
* Block ids are SHARED ACROSS RANKS -- RadBatch carries one block table and every rank indexes
|
||||
@@ -367,59 +364,6 @@ public:
|
||||
int64_t live_blocks(int32_t group) const;
|
||||
int64_t committed_bytes() const;
|
||||
|
||||
/* HOW MUCH OF THE CHECKPOINT REGION MUST STAY AVAILABLE, in bytes, counting only what is not
|
||||
* committed already. The number is the HIGH WATER MARK PLUS ONE rather than the whole cap:
|
||||
* the cap is what the operator allows and the high water is what this workload takes, and
|
||||
* holding one slot past it means the allocation that would advance it always has room. */
|
||||
int64_t ck_reserve_bytes() const;
|
||||
|
||||
/* BACK THIS RANK'S COPY OF A SLOT, AND SAY SO IF THE CARD WILL NOT.
|
||||
*
|
||||
* A slot's LIFETIME is decided once: rank 0's PrefixCache owns the free list and every other
|
||||
* rank takes the id it is handed. Its BACKING is per rank, because every rank writes its own
|
||||
* shard of the snapshot into the same offset of its OWN pool. alloc_checkpoint backs the slot
|
||||
* on every rank before it hands the id out (set_checkpoint_peers), so on the paths that use a
|
||||
* slot this is a check that finds it backed. Called before EVERY access rather than once:
|
||||
* idempotence is what makes that safe, and a commit of a range already committed is a no-op.
|
||||
*
|
||||
* RAD_E_FULL when the commit would take the card under its floor (set_checkpoint_floor). */
|
||||
int back_checkpoint(int32_t slot);
|
||||
|
||||
/* THE CARD'S FLOOR FOR A CHECKPOINT SLOT'S PAGES: the card is read before a slot is backed,
|
||||
* and a slot that would leave it under `keep_free` bytes is refused as a full pool.
|
||||
*
|
||||
* The budget counts the whole checkpoint region as the cache's, but the region is backed as
|
||||
* slots are taken, and until then its bytes read as free. The allocations nobody sizes in
|
||||
* advance -- a kernel's code object and a spilling kernel's scratch, both made on the
|
||||
* kernel's first launch -- are made out of that same free memory. A slot that took the last
|
||||
* of it would leave the next first launch nothing, which is a fault inside the HIP runtime
|
||||
* and not an error. A refused slot is a snapshot fewer on the card, which the retention
|
||||
* policy answers and the host tier covers.
|
||||
*
|
||||
* `free_bytes` reads the card's free memory into its argument: the engine reads the device, a
|
||||
* test reads a simulated card, and no floor is set on a backend with no card. */
|
||||
using FreeBytes = std::function<int(int64_t*)>;
|
||||
void set_checkpoint_floor(FreeBytes free_bytes, int64_t keep_free) {
|
||||
ck_free_bytes_ = std::move(free_bytes);
|
||||
ck_keep_free_ = keep_free;
|
||||
}
|
||||
|
||||
/* THE OTHER RANKS' MANAGERS, given to the one whose free list hands the ids out. Every rank
|
||||
* writes its shard of a snapshot into the same slot of its own pool, so a slot is backed on
|
||||
* every card or handed out on none: a card that cannot back it is a full pool at allocation,
|
||||
* which the prefix cache answers by retiring a snapshot, rather than a failed copy after the
|
||||
* step that produced the state, which stops the engine. */
|
||||
void set_checkpoint_peers(std::vector<KVManager*> peers) { ck_peers_ = std::move(peers); }
|
||||
|
||||
/* BACK EVERY FREE SLOT NOW, ON EVERY RANK, and withdraw the ones the cards have no room for.
|
||||
* For a driver that never takes a mapping's pages back (set_release_frees_card(false)): a
|
||||
* slot backed later costs exactly what it costs now, and backing it now puts the region's
|
||||
* cost on the card before serving starts, where the startup reading shows it. A withdrawn
|
||||
* slot is never handed out. `withdrawn` counts them; RAD_E_FULL is not returned. */
|
||||
int back_free_checkpoints(int64_t* withdrawn);
|
||||
|
||||
int64_t checkpoint_stride() const { return ck_stride_; }
|
||||
|
||||
/* ---------------- preemption by recompute (spec §7.1, §17) ---------------- */
|
||||
/* Free the sequence's blocks and take it back to zero tokens. Its state slots are freed too: a
|
||||
* recurrent state that is not snapshotted cannot be resumed, so a preempted sequence replays
|
||||
@@ -470,10 +414,24 @@ public:
|
||||
const std::vector<uint64_t>& victims,
|
||||
std::vector<uint64_t>* preempted);
|
||||
|
||||
/* ---------------- linear-state checkpoints (spec §7.3) ---------------- */
|
||||
/* ---------------- linear-state checkpoints (spec §7.3) ----------------
|
||||
*
|
||||
* A SNAPSHOT LIVES IN PINNED HOST MEMORY, NOT ON THE CARD. It is a copy of a sequence's state
|
||||
* that no kernel reads -- the step reads the live state slots, and a snapshot only ever goes
|
||||
* back into one of those -- so it has no reason to hold VRAM. Saving it is one copy across the
|
||||
* link after the step that produced the state, restoring it one copy back before the step
|
||||
* 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
|
||||
* 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. */
|
||||
void set_checkpoint_store(HostArena* store, int64_t rank_off);
|
||||
int64_t checkpoint_bytes() const { return checkpoint_bytes_; }
|
||||
int64_t checkpoint_slots() const { return (int64_t)ck_slot_base_.size(); }
|
||||
int64_t free_checkpoint_slots() const { return (int64_t)ck_free_.size(); }
|
||||
int64_t checkpoint_slots() const { return ck_store_ ? ck_store_->capacity() : 0; }
|
||||
int64_t free_checkpoint_slots() const { return ck_store_ ? ck_store_->free_slots() : 0; }
|
||||
int alloc_checkpoint(int32_t* slot_out);
|
||||
void free_checkpoint(int32_t slot);
|
||||
void* checkpoint_ptr(int32_t slot) const;
|
||||
@@ -495,7 +453,8 @@ public:
|
||||
*
|
||||
* Enqueued on `s`, not synchronous: the save has to follow the step that produced the state
|
||||
* and the restore has to precede the step that consumes it, and both are ordered by the
|
||||
* stream rather than by waiting. RAD_E_INVAL on a bad slot or an unknown sequence. */
|
||||
* stream rather than by waiting. One pitched copy a stateful group between the card and the
|
||||
* store, at the link's rate. RAD_E_INVAL on a bad slot or an unknown sequence. */
|
||||
int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s);
|
||||
int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s);
|
||||
|
||||
@@ -513,6 +472,9 @@ private:
|
||||
* `budget_bytes` of pool, under tokens_cap_, and each group's block count in `blocks` (by group
|
||||
* index; a windowed group capped at its window). carve_into() spends what this says. */
|
||||
int64_t paged_split(int64_t budget_bytes, std::vector<int64_t>* blocks) const;
|
||||
/* A zero group's share of `tokens`: the block count of the shared table, capped at the window
|
||||
* for a windowed group. 0 for kUnboundedTokens, which is not a count. */
|
||||
int64_t zero_blocks(const KVGroupPlan& p, int64_t tokens) const;
|
||||
void forget();
|
||||
|
||||
/* One traversal serving both checkpoint directions; see checkpoint_save. */
|
||||
@@ -552,8 +514,8 @@ private:
|
||||
std::unordered_map<uint64_t, Seq> seqs_;
|
||||
std::vector<BlockCopy> pending_;
|
||||
|
||||
std::vector<int64_t> ck_slot_base_; /* pool offsets of the checkpoint slots */
|
||||
std::vector<int32_t> ck_free_;
|
||||
HostArena* ck_store_ = nullptr; /* set_checkpoint_store */
|
||||
int64_t ck_rank_off_ = 0;
|
||||
int64_t checkpoint_bytes_ = 0;
|
||||
std::vector<StateClear> clears_; /* grabbed slots the engine must zero */
|
||||
void* pool_base_ = nullptr;
|
||||
@@ -563,33 +525,9 @@ private:
|
||||
int64_t max_ctx_ = 0;
|
||||
int64_t max_tok_ = 0; /* --max-num-batched-tokens; the buffer floor is one of these */
|
||||
/* plan_groups() computes these; carve() spends against them and ceiling() reports on them. */
|
||||
int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, checkpoints, padding */
|
||||
int64_t ck_total_ = 0; /* the checkpoint part of fixed_, named for the refusal message */
|
||||
int64_t ckpts_ = 0; /* --checkpoint-slots, as plan_groups() resolved it */
|
||||
int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, padding */
|
||||
int64_t ckpts_ = 0; /* --checkpoint-slots, kept for the warning on a model with none */
|
||||
int64_t tokens_cap_ = 0; /* cap_paged_tokens(): the least any rank can carve; 0 is none */
|
||||
/* THE SLOT STRIDE AND WHERE THE SLOTS BEGIN. The stride is checkpoint_bytes_ rounded up to a
|
||||
* whole number of commit granules, so a slot can be backed and released without touching a
|
||||
* neighbour; the offset is where the eager startup commit stops, because everything from
|
||||
* there up is backed as it is handed out. Zero on a model with no linear state. */
|
||||
bool release_frees_card_ = true;
|
||||
bool ck_elastic_ = false;
|
||||
int64_t ck_high_water_ = 0;
|
||||
int64_t ck_backed_ = 0;
|
||||
int64_t ck_stride_ = 0;
|
||||
int64_t ck_region_off_ = 0;
|
||||
FreeBytes ck_free_bytes_; /* set_checkpoint_floor */
|
||||
int64_t ck_keep_free_ = 0;
|
||||
std::vector<KVManager*> ck_peers_;
|
||||
/* RAD_OK when this rank has the slot backed or room above the floor to back it. */
|
||||
int ck_room(int32_t slot) const;
|
||||
bool ck_backed(int32_t slot) const;
|
||||
/* The commit itself, with no floor: callers have asked ck_room on every rank first. */
|
||||
int ck_commit(int32_t slot);
|
||||
/* ck_room on every rank, then ck_commit on every rank. */
|
||||
int ck_back_everywhere(int32_t slot);
|
||||
/* What a checkpoint slot is aligned and sized to. RAD_ALIGN_UNIT on a device with no virtual
|
||||
* memory management, where nothing is released and the stride is only padding. */
|
||||
int64_t ck_align() const;
|
||||
|
||||
/* ---- the loan. See the public block for what this is and why a block that anything holds
|
||||
* is never lent. ----
|
||||
|
||||
+226
-461
File diff suppressed because it is too large.
Load diff
+105
-161
@@ -78,6 +78,7 @@
|
||||
* such a transfer -- it reads host memory and nothing else -- and holds only the slots it reads.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/hostarena.h"
|
||||
#include "mem/kv.h"
|
||||
#include "mem/prefix.h"
|
||||
#include "rad_core.h"
|
||||
@@ -123,30 +124,23 @@ struct TierJob {
|
||||
|
||||
/* ---- the linear half, on a hybrid model ----
|
||||
*
|
||||
* A session's recurrent state lives in a CHECKPOINT SLOT rather than in blocks: one contiguous
|
||||
* KVManager::checkpoint_bytes() extent, which is why nothing here needs a gather. The snapshot
|
||||
* belonging to this entry moves with it, so a restored hybrid session gets its attention hit
|
||||
* AND its state back, instead of an attention hit and a full linear replay from token zero.
|
||||
* 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_dev` is the device slot: where the bytes are read from on the way out, and where the
|
||||
* engine put them on the way in -- it is an OUTPUT of a promotion, exactly as `blocks` is. */
|
||||
int32_t ck_dev = -1;
|
||||
int32_t ck_host = -1; /* a slot in the snapshot arena, not the block arena */
|
||||
* `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 promotion should bring the snapshot back too */
|
||||
/* 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 that could not be copied
|
||||
* has not been damaged, it is still sitting correct and committed in its device slot and a
|
||||
* later pass reaches it again for free, so the blocks may as well carry on without it.
|
||||
*
|
||||
* A snapshot that is DROPPED is another matter, and it is worth being exact about the cost
|
||||
* because it is not what it looks like. On this build the scheduler clamps a hybrid session's
|
||||
* reuse to the last LINEAR CHECKPOINT it can reach, not to the attention hit -- RadBatch
|
||||
* carries one query length for every KV group, so the linear layers cannot be replayed over a
|
||||
* longer range than the attention ones (core/sched/scheduler.cpp, admit_one). A session whose
|
||||
* blocks came back and whose state did not therefore reuses NOTHING. The blocks are not a
|
||||
* partial win; they are unusable until some checkpoint under them survives. */
|
||||
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
|
||||
@@ -157,54 +151,6 @@ struct TierJob {
|
||||
bool started = false;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the host arena */
|
||||
/* 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,
|
||||
* synchronises. Slot-allocated at one
|
||||
* fixed size rather than malloc'd per entry: every entry in a given model holds exactly one block
|
||||
* per cached group, so the size is a property of the geometry and a bitmap is the whole allocator.
|
||||
*
|
||||
* RUNS, BECAUSE A TRANSFER IS PER RUN. A 4-token block makes a 200K-token conversation fifty
|
||||
* thousand entries, and a copy per entry is fifty thousand driver calls on the engine thread --
|
||||
* the call rate, not the link, is then what a restore costs. Entries written together are given
|
||||
* consecutive slots wherever the arena has them, so a batch crosses the link as one strided copy
|
||||
* a run. */
|
||||
class HostArena {
|
||||
public:
|
||||
~HostArena();
|
||||
int open(int64_t slot_bytes, int64_t cap_bytes);
|
||||
void close();
|
||||
bool enabled() const { return base_ != nullptr; }
|
||||
|
||||
int64_t slot_bytes() const { return slot_bytes_; }
|
||||
/* Fixed when the arena is opened. Stored rather than counted from the bitmap, because an
|
||||
* HTTP thread reads it for the sessions view while the engine thread allocates and frees. */
|
||||
int64_t capacity() const { return cap_slots_; }
|
||||
int64_t used_slots() const { return used_; }
|
||||
int64_t cap_bytes() const { return slot_bytes_ * capacity(); }
|
||||
int64_t free_slots() const { return cap_slots_ - used_; }
|
||||
|
||||
/* -1 when the arena is full. The caller evicts and retries; this does not choose victims,
|
||||
* because the LRU that would choose them lives in IdleTiers and an allocator that reached
|
||||
* into it would give each record two owners. */
|
||||
bool full() const { return used_ >= cap_slots_; }
|
||||
int32_t alloc();
|
||||
/* UP TO `want` CONSECUTIVE SLOTS, the first free run at or after the cursor. `*got` is how
|
||||
* many; the caller asks again for the rest. -1 when the arena is full. */
|
||||
int32_t alloc_run(int32_t want, int32_t* got);
|
||||
void free(int32_t slot);
|
||||
void* at(int32_t slot) const;
|
||||
|
||||
private:
|
||||
bool is_used(int64_t s) const { return (bits_[(size_t)(s >> 6)] >> (s & 63)) & 1ull; }
|
||||
void* base_ = nullptr;
|
||||
int64_t slot_bytes_ = 0;
|
||||
int64_t used_ = 0;
|
||||
int64_t cap_slots_ = 0;
|
||||
int64_t cursor_ = 0;
|
||||
std::vector<uint64_t> bits_;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the policy */
|
||||
class IdleTiers {
|
||||
public:
|
||||
@@ -214,12 +160,11 @@ public:
|
||||
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`. `ckpt_cap_bytes` is carved out of the tier the operator sized rather than
|
||||
* added to it: a snapshot store is host memory like any other and a tier that quietly
|
||||
* allocated past its stated cap would be the one thing --prefix-cache-host-mib is for. Zero
|
||||
* for either means snapshots do not tier, and the blocks still do. */
|
||||
* `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. */
|
||||
int64_t ckpt_bytes = 0;
|
||||
int64_t ckpt_cap_bytes = 0; /* host; part of host_cap_bytes, not additional to it */
|
||||
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 */
|
||||
};
|
||||
|
||||
@@ -262,10 +207,7 @@ public:
|
||||
*
|
||||
* The records waiting for a host copy, up to `max_entries`, as WriteBack jobs with their host
|
||||
* slots already allocated. Oldest first, so a conversation that went idle before another is
|
||||
* copied before it. A record whose snapshot is still only on the device is included even when
|
||||
* its blocks already have their copy, with `blocks` empty -- the snapshot is the half a hybrid
|
||||
* session cannot resume without, and it becomes copyable later than the blocks (a checkpoint
|
||||
* is committed on its own clock).
|
||||
* 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
|
||||
@@ -286,32 +228,31 @@ public:
|
||||
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 WHERE IT IS. A snapshot's device slot is not memory anything else can
|
||||
* use -- the expert slab borrows blocks, never checkpoint slots -- so taking it off the device
|
||||
* along with the blocks would buy nothing and put the session's recurrent state at the mercy
|
||||
* of a host arena a few snapshots deep, shared by every conversation. The slot goes when the
|
||||
* checkpoint pool itself needs it (snapshot_backed). */
|
||||
* 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 ----------------
|
||||
*
|
||||
* The checkpoint pool 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 whose bytes the tiers also
|
||||
* hold need not be lost: the cache DETACHES it instead -- the slot goes back, the index entry
|
||||
* stays, and the next restore of the session brings the state back with the blocks. True when
|
||||
* this key's device snapshot has a finished copy off the card that nothing is still writing. */
|
||||
* 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;
|
||||
/* The cache gave the device slot back; the copy off the card is now the snapshot. */
|
||||
/* 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. 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 the record gives 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
|
||||
* 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. */
|
||||
void plan(int budget, std::vector<TierJob>* out);
|
||||
@@ -340,12 +281,17 @@ public:
|
||||
* 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 that is only on disk is read with it, into the snapshot arena,
|
||||
* because that is the state the hit resumes from (TierExec::issue_restore). 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. */
|
||||
* 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);
|
||||
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;
|
||||
|
||||
/* 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
|
||||
@@ -382,38 +328,42 @@ public:
|
||||
*
|
||||
* 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.
|
||||
* `dev_slot` is a KVManager checkpoint slot and `pos` the token position the disk store
|
||||
* verifies a read against.
|
||||
* `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 a copy when the record is published, or at once when it
|
||||
* already was. */
|
||||
void note_snapshot(const BlockHash& key, int32_t dev_slot, int64_t pos);
|
||||
/* The cache is done with the snapshot at `key`: return whatever tier storage holds 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.
|
||||
* 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 COPY IS STILL READING THE DEVICE SLOT, and then the slot is NOT the caller's to
|
||||
* free: an asynchronous copy out of a slot the pool has decommitted reads a page that is no
|
||||
* longer there, which is a device fault rather than a stale byte. The tiers keep the slot and
|
||||
* hand it back through `take_checkpoint_frees` once the copy has reported. */
|
||||
bool release_snapshot(const BlockHash& key);
|
||||
/* Device checkpoint slots whose release waited on a copy, now safe to free. */
|
||||
* 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 copy reading this key's device snapshot right now? A save into that slot would tear it. */
|
||||
bool snapshot_reading(const BlockHash& key) const;
|
||||
/* THE TIERS LOST A SNAPSHOT BUT KEPT THE BLOCKS. The snapshot store is far smaller than the
|
||||
* block store (a snapshot is thousands of blocks' worth of bytes) so it overflows first and on
|
||||
* its own, and 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. */
|
||||
/* 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); }
|
||||
bool ckpt_on() const { return ck_arena_.enabled(); }
|
||||
/* Do snapshots reach disk at all? */
|
||||
bool ckpt_disk_on() const { return disk_on() && cfg_.ckpt_bytes > 0 && cfg_.ckpt_disk_slots > 0; }
|
||||
int64_t ckpt_bytes() const { return cfg_.ckpt_bytes; }
|
||||
HostArena& ckpt_arena() { return ck_arena_; }
|
||||
const HostArena& ckpt_arena() const { return ck_arena_; }
|
||||
int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; }
|
||||
int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; }
|
||||
int64_t ckpt_slots() const { return cfg_.ckpt_slots; }
|
||||
|
||||
/* ---------------- the session view ----------------
|
||||
*
|
||||
@@ -440,11 +390,11 @@ public:
|
||||
int64_t on_device = 0, on_host = 0, on_disk = 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 on the device. A session showing
|
||||
* 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
|
||||
* 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_device = 0, snap_host = 0, snap_disk = 0;
|
||||
int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */
|
||||
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
|
||||
@@ -500,9 +450,17 @@ public:
|
||||
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. */
|
||||
int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0;
|
||||
* 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;
|
||||
/* 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. */
|
||||
int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0;
|
||||
};
|
||||
/* The step thread's own time on the tiers (see Stats). */
|
||||
void note_restore(int64_t ns) { std::lock_guard lk(mu_); ++stats_.restores; stats_.restore_ns += ns; }
|
||||
void note_flush(int64_t ns) { std::lock_guard lk(mu_); ++stats_.flushes; stats_.flush_ns += ns; }
|
||||
/* A copy, taken under the lock: an HTTP thread reads these while the engine thread moves
|
||||
* records. */
|
||||
Stats stats() const;
|
||||
@@ -529,30 +487,19 @@ private:
|
||||
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 */
|
||||
std::vector<int32_t> blocks;
|
||||
/* ---- the linear half ----
|
||||
* `ck_dev` is the snapshot's device slot, `ck_host` its host copy and `ck_on_disk` the
|
||||
* disk store's. A clean device snapshot has both of the first two; a snapshot that has
|
||||
* left the device has no `ck_dev`. All clear 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_dev = -1;
|
||||
int32_t ck_host = -1;
|
||||
* `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. */
|
||||
int32_t ck_slot = -1;
|
||||
bool ck_on_disk = false;
|
||||
int64_t ck_pos = 0;
|
||||
/* A COPY IS READING `ck_dev` RIGHT NOW: set when a write-back takes the snapshot, cleared
|
||||
* when it reports. The one moment the device slot is not the cache's to free. */
|
||||
bool ck_reading = false;
|
||||
/* THIS SNAPSHOT WILL NOT BE COPIED AGAIN: its copy was refused for want of room, or taken
|
||||
* back to make room for another. The snapshot store is a few slots deep for the whole
|
||||
* server, and a snapshot still in its device slot re-queued the moment its copy was
|
||||
* evicted would evict the next one's, and so on -- every pass copying a hundred megabytes
|
||||
* a rank to throw another hundred away. Cleared when a new commit replaces the state. */
|
||||
bool ck_skip = false;
|
||||
/* A device slot the cache let go of while a copy was reading it. See release_snapshot. */
|
||||
int32_t ck_free_after = -1;
|
||||
/* The snapshot host slot a disk write is reading, as `disk_src` is for the blocks. */
|
||||
/* 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
|
||||
@@ -566,24 +513,20 @@ private:
|
||||
std::list<BlockHash>::iterator it;
|
||||
};
|
||||
|
||||
/* Does this record want a copy it does not have yet? The blocks when they are in VRAM with no
|
||||
* copy off the card; the snapshot when it is in a device slot with no copy off the card and
|
||||
* the snapshot store exists at all. */
|
||||
/* 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;
|
||||
/* The snapshot half of that on its own. */
|
||||
bool wants_ck_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` / `free_ck_host` are the record's own: a slot a disk write is reading is left
|
||||
* `free_host` is the record's own: a slot a disk write is reading is left
|
||||
* for that write's report to free. */
|
||||
void give_slot(int32_t slot);
|
||||
void free_host(Rec& r);
|
||||
void free_ck_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
|
||||
@@ -594,12 +537,8 @@ private:
|
||||
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);
|
||||
/* Take a snapshot arena slot from the record whose host copy is cheapest to lose, and tell the
|
||||
* cache if that was the snapshot's only copy. NO SECOND LIST: the records are walked, which
|
||||
* keeps the header's "one record, one tier, one list" rule intact. `lossless` takes only a
|
||||
* snapshot the disk also holds.
|
||||
* Returns -1 when there is none to take. */
|
||||
int32_t evict_snapshot_slot(bool lossless);
|
||||
/* 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;
|
||||
@@ -655,16 +594,21 @@ private:
|
||||
Config cfg_;
|
||||
SSDTier* disk_ = nullptr;
|
||||
HostArena arena_;
|
||||
HostArena ck_arena_; /* snapshots; a different slot size, so a different arena */
|
||||
std::unordered_map<BlockHash, Rec, BlockHashHash> recs_;
|
||||
std::list<BlockHash> host_lru_, disk_lru_; /* front = oldest */
|
||||
/* 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 */
|
||||
std::vector<int32_t> ck_frees_; /* device checkpoint slots a finished copy released */
|
||||
/* 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;
|
||||
|
||||
+3
-4
@@ -213,7 +213,7 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
if (cfg.vram_kv_mib <= 0) missing += " vram_kv resolved to 0 MiB\n";
|
||||
if (!missing.empty()) {
|
||||
fit_report_ = "VRAM pool budgets are empty -- state --vram-weights-mib / --vram-kv-mib, or "
|
||||
"let the card be split by --gpu-headroom-mib and --expert-vs-cache-ratio:\n"
|
||||
"let the card be split from --gpu-headroom-mib and --host-pool-mib:\n"
|
||||
+ missing;
|
||||
RAD_ERR("%s", fit_report_.c_str());
|
||||
return RAD_E_INVAL;
|
||||
@@ -230,9 +230,8 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
" total %10s\n"
|
||||
" card total %10s\n"
|
||||
" OVER BY %10s\n"
|
||||
"Lower --vram-weights-mib / --vram-kv-mib, or raise --gpu-headroom-mib and let "
|
||||
"--expert-vs-cache-ratio split what is left. The split is yours to make; the engine "
|
||||
"will not make it for you (spec §6).\n",
|
||||
"Lower --vram-weights-mib / --vram-kv-mib, or state neither and let the card be split "
|
||||
"from --gpu-headroom-mib and --host-pool-mib (spec §6).\n",
|
||||
humanb(w).c_str(), humanb(kv).c_str(),
|
||||
humanb(want).c_str(), humanb(vram_capacity).c_str(),
|
||||
humanb(want - vram_capacity).c_str());
|
||||
|
||||
+226
-77
@@ -184,7 +184,7 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
|
||||
enabled_ = true;
|
||||
report_ = fmt("prefix cache: %zu paged group(s) at %lld-token blocks; linear checkpoints "
|
||||
"every %lld tokens (%s x %s), retention '%s'\n",
|
||||
"every %lld tokens (%s a rank x %s, pinned host memory), retention '%s'\n",
|
||||
groups_.size(), (long long)block_size_,
|
||||
(long long)(has_linear_ ? interval_ : 0),
|
||||
humanb(kv->checkpoint_bytes()).c_str(),
|
||||
@@ -279,26 +279,38 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
|
||||
/* ---- the split: how far the LINEAR state can be reused ----
|
||||
* The attention blocks are reusable up to n_attn_tokens. The recurrent state is only reusable
|
||||
* at a checkpoint, so walk back to the last checkpoint boundary at or below n_attn_tokens and
|
||||
* look it up by the chained hash there. The gap between the two is replayed through the linear
|
||||
* layers only -- the attention layers for those tokens are already in the cache. */
|
||||
* at a checkpoint: the deepest snapshot at or below n_attn_tokens on this chain, in its store
|
||||
* slot. The scheduler resumes from there (Scheduler::admit_one) and recomputes the tokens
|
||||
* between the two. */
|
||||
if (!has_linear_) {
|
||||
/* No recurrent state means nothing to replay: the whole attention hit is directly usable. */
|
||||
hit.n_linear_tokens = hit.n_attn_tokens;
|
||||
return hit;
|
||||
}
|
||||
for (int64_t p = (hit.n_attn_tokens / interval_) * interval_; p > 0; p -= interval_) {
|
||||
const BlockHash& h = hs[(size_t)(p / block_size_ - 1)];
|
||||
auto it = ck_by_prefix_.find(h);
|
||||
if (it == ck_by_prefix_.end() || !it->second.valid) continue;
|
||||
hit.n_linear_tokens = (int32_t)p;
|
||||
hit.checkpoint_slot = it->second.slot;
|
||||
it->second.used = ++clock_;
|
||||
handed_.push_back(h);
|
||||
++stats_.ckpt_hits;
|
||||
/* OVER THE SNAPSHOTS, NOT OVER THE POSITIONS. A checkpoint sits on the interval or at the
|
||||
* tail of a prompt (Scheduler::plan_chunk), which is any block boundary, so the deepest one
|
||||
* under the hit is found by asking each snapshot whether this chain passes through it: its
|
||||
* key is the chained hash at its own position, which matches only on the same prefix. The
|
||||
* index holds a few hundred snapshots against tens of thousands of block positions. */
|
||||
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 > hit.n_attn_tokens ||
|
||||
c.pos % block_size_ != 0)
|
||||
continue;
|
||||
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
|
||||
if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue;
|
||||
best = it;
|
||||
}
|
||||
if (best == ck_by_prefix_.end()) {
|
||||
++stats_.ckpt_misses;
|
||||
return hit;
|
||||
}
|
||||
++stats_.ckpt_misses;
|
||||
hit.n_linear_tokens = (int32_t)best->second.pos;
|
||||
hit.checkpoint_slot = best->second.slot;
|
||||
best->second.used = ++clock_;
|
||||
handed_.push_back(best->first);
|
||||
++stats_.ckpt_hits;
|
||||
return hit;
|
||||
}
|
||||
|
||||
@@ -393,6 +405,27 @@ int PrefixCache::insert(uint64_t session,
|
||||
}
|
||||
tiers_->note_session(session, hs, n_tokens, now);
|
||||
}
|
||||
|
||||
/* A CONVERSATION'S SNAPSHOTS BELONG TO ITS LATEST TURN. The index keys a session by REQUEST
|
||||
* id, so each turn would otherwise keep its own tip forever: turn N-1's deepest snapshot stays
|
||||
* a "tip" after turn N has resumed from it and written deeper ones, and the retention policy
|
||||
* then guards a dozen dead tips across a long agent run while thinning the one conversation
|
||||
* that is live. Every snapshot on the chain this request just published is a prefix of it,
|
||||
* and is moved under this id, so the policy sees one session with one tip. */
|
||||
for (auto& kvp : ck_by_prefix_) {
|
||||
Ckpt& c = kvp.second;
|
||||
if (c.session == session || c.pos <= 0 || c.pos > n_full * block_size_ ||
|
||||
c.pos % block_size_ != 0 || hs[(size_t)(c.pos / block_size_ - 1)] != kvp.first)
|
||||
continue;
|
||||
auto old = ck_by_session_.find(c.session);
|
||||
if (old != ck_by_session_.end()) {
|
||||
old->second.erase(std::remove(old->second.begin(), old->second.end(), kvp.first),
|
||||
old->second.end());
|
||||
if (old->second.empty()) ck_by_session_.erase(old);
|
||||
}
|
||||
c.session = session;
|
||||
ck_by_session_[session].push_back(kvp.first);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -406,7 +439,10 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
|
||||
if (chain) chain->clear();
|
||||
if (!enabled_ || !tiers_ || tokens.empty()) return out;
|
||||
|
||||
const int64_t n_full = (int64_t)tokens.size() / block_size_;
|
||||
/* 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. */
|
||||
const int64_t n_full = ((int64_t)tokens.size() - 1) / block_size_;
|
||||
std::vector<BlockHash> hs = chain_all(tokens, mm, n_full);
|
||||
|
||||
/* Walk exactly as lookup does, and keep walking past the point it stopped for as long as the
|
||||
@@ -447,10 +483,13 @@ 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. The tiers moved the two halves together, so they
|
||||
* lose them together; leaving the index entry behind would leave a snapshot marked off-device
|
||||
* whose bytes nobody holds, waiting to be promoted by something that no longer exists. */
|
||||
drop_snapshot(key);
|
||||
/* 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);
|
||||
}
|
||||
|
||||
int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks) {
|
||||
@@ -474,18 +513,30 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool PrefixCache::shared_with_live(const Entry& e) const {
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
if (kv_->block_refcount(groups_[g], e.blocks[g]) > 1) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
int64_t done = 0;
|
||||
while (done < n && !lru_.empty()) {
|
||||
/* ONE PASS OVER WHAT WAS ON THE LIST WHEN THE CALL BEGAN. An entry a live sequence also holds
|
||||
* 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. */
|
||||
for (int64_t seen = (int64_t)lru_.size(); done < n && seen > 0 && !lru_.empty(); --seen) {
|
||||
const BlockHash h = lru_.front();
|
||||
lru_.pop_front();
|
||||
auto it = map_.find(h);
|
||||
if (it == map_.end()) continue;
|
||||
if (it == map_.end()) { lru_.pop_front(); continue; }
|
||||
Entry& e = it->second;
|
||||
if (shared_with_live(e)) {
|
||||
lru_.splice(lru_.end(), lru_, lru_.begin());
|
||||
continue;
|
||||
}
|
||||
lru_.pop_front();
|
||||
e.in_lru = false;
|
||||
/* Every entry on the list holds its blocks, whatever the tiers are doing with it: one on
|
||||
* its way to a host copy still holds the cache's references until the copy reports, and
|
||||
* the report finds it forgotten and keeps nothing. */
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
kv_->release_block(groups_[g], e.blocks[g]);
|
||||
if (tiers_) {
|
||||
@@ -505,13 +556,51 @@ int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
return done;
|
||||
}
|
||||
|
||||
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();
|
||||
int64_t done = 0;
|
||||
auto it = lru_.begin();
|
||||
for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_blocks && seen > 0;
|
||||
--seen) {
|
||||
const BlockHash h = *it;
|
||||
auto m = map_.find(h);
|
||||
if (m == map_.end()) { it = lru_.erase(it); continue; }
|
||||
Entry& e = m->second;
|
||||
if (shared_with_live(e)) {
|
||||
/* 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);
|
||||
it = next;
|
||||
continue;
|
||||
}
|
||||
if (keep && !tiers_->droppable(h)) { ++it; continue; }
|
||||
it = lru_.erase(it);
|
||||
e.in_lru = false;
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
kv_->release_block(groups_[g], e.blocks[g]);
|
||||
if (keep) {
|
||||
tiers_->drop_commit(h);
|
||||
++stats_.drops;
|
||||
} else {
|
||||
if (tiers_) tiers_->forget(h);
|
||||
map_.erase(m);
|
||||
++stats_.evictions;
|
||||
}
|
||||
++done;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
int64_t PrefixCache::drop_clean() {
|
||||
if (!tiers_ || !kv_) return 0;
|
||||
drop_scratch_.clear();
|
||||
tiers_->take_clean(&drop_scratch_);
|
||||
const uint64_t frees = kv_->seq_frees();
|
||||
if (frees != frees_seen_) {
|
||||
if (frees != frees_seen_ || released_) {
|
||||
frees_seen_ = frees;
|
||||
released_ = false;
|
||||
drop_scratch_.insert(drop_scratch_.end(), drop_wait_.begin(), drop_wait_.end());
|
||||
drop_wait_.clear();
|
||||
}
|
||||
@@ -525,7 +614,7 @@ int64_t PrefixCache::drop_clean() {
|
||||
/* A BLOCK A RUNNING SEQUENCE ALSO HOLDS WOULD FREE NOTHING, and its entry would then be
|
||||
* off-device in the index while its bytes sat in VRAM under somebody else's table -- the
|
||||
* next lookup would restore a second copy beside them. */
|
||||
bool shared = false;
|
||||
bool shared = held_.count(h) > 0;
|
||||
for (size_t g = 0; g < groups_.size() && !shared; ++g)
|
||||
shared = kv_->block_refcount(groups_[g], e.blocks[g]) > 1;
|
||||
if (shared) {
|
||||
@@ -601,11 +690,11 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
auto it = ck_by_session_.find(session);
|
||||
if (it == ck_by_session_.end()) return 0;
|
||||
|
||||
/* DEVICE-RESIDENT SNAPSHOTS ONLY. This policy exists to spend a fixed number of --checkpoint-
|
||||
* slots well, and it runs when that pool is exhausted. A snapshot the idle tiers hold occupies
|
||||
* none of it, so retiring one would free nothing here and would cost a session the state it
|
||||
* was moved off the device precisely in order to keep. Tiered bytes are bounded by the tiers'
|
||||
* own caps, oldest first, which is the right policy for the resource they actually spend.
|
||||
/* 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;
|
||||
@@ -613,7 +702,7 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
for (const BlockHash& h : it->second) {
|
||||
auto e = ck_by_prefix_.find(h);
|
||||
if (e == ck_by_prefix_.end()) continue;
|
||||
if (e->second.off_device) { kept.push_back(h); continue; }
|
||||
if (e->second.detached) { kept.push_back(h); continue; }
|
||||
all.push_back({e->second.pos, h});
|
||||
}
|
||||
std::sort(all.begin(), all.end(),
|
||||
@@ -628,11 +717,19 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
for (const auto& a : all) {
|
||||
if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; }
|
||||
auto e = ck_by_prefix_.find(a.second);
|
||||
if (e != ck_by_prefix_.end()) {
|
||||
retire_ckpt(e);
|
||||
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;
|
||||
++stats_.ckpt_evictions;
|
||||
continue;
|
||||
}
|
||||
retire_ckpt(e);
|
||||
++freed;
|
||||
++stats_.ckpt_evictions;
|
||||
}
|
||||
/* ERASE THE SESSION WHEN NOTHING IS LEFT OF IT, and that is not tidiness. `session` is a
|
||||
* REQUEST id, so without an eraser this map gains an entry for every request that ever writes
|
||||
@@ -648,24 +745,27 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
int32_t* slot_out) {
|
||||
if (!enabled_ || !has_linear_) return RAD_E_UNSUPPORTED;
|
||||
if (!slot_out) return RAD_E_INVAL;
|
||||
if (interval_ <= 0 || pos <= 0 || pos % interval_ != 0) {
|
||||
RAD_ERR("checkpoint at %lld is not on a %lld-token boundary; the scheduler splits chunks "
|
||||
"at the interval precisely so this cannot happen (spec §7.3)",
|
||||
(long long)pos, (long long)interval_);
|
||||
/* ON A BLOCK BOUNDARY, because the key is the chained hash of whole blocks. The scheduler
|
||||
* places checkpoints on the interval and at the tail of a prompt, both on its chunk quantum,
|
||||
* which is a multiple of the block. */
|
||||
if (interval_ <= 0 || pos <= 0 || pos % block_size_ != 0) {
|
||||
RAD_ERR("checkpoint at %lld is not on a %lld-token block boundary; the scheduler splits "
|
||||
"chunks on its quantum precisely so this cannot happen (spec §7.3)",
|
||||
(long long)pos, (long long)block_size_);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto existing = ck_by_prefix_.find(prefix);
|
||||
if (existing != ck_by_prefix_.end()) {
|
||||
/* A SNAPSHOT THE TIERS HOLD 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 pool would be
|
||||
/* 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 tiered copy is retired and a fresh slot allocated below. */
|
||||
/* NOR ONE A COPY IS READING. The save that follows this reservation writes the slot on
|
||||
* the compute stream while the copy reads it on the transfer stream, and the host would
|
||||
* keep a snapshot that is half of each. A fresh slot costs one allocation. */
|
||||
if (!existing->second.off_device &&
|
||||
!(tiers_ && tiers_->snapshot_reading(prefix))) {
|
||||
* 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;
|
||||
}
|
||||
@@ -710,10 +810,13 @@ 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 TIERED SNAPSHOT IS NOT A CANDIDATE, because evicting it frees nothing HERE.
|
||||
* Its device slot went back to the pool when the tiers took the bytes, so picking
|
||||
* it as the victim would retire a usable snapshot and then fail the retry anyway. */
|
||||
if (kvp.second.off_device) continue;
|
||||
/* 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;
|
||||
auto sit = ck_by_session_.find(kvp.second.session);
|
||||
bool is_tip = false;
|
||||
if (sit != ck_by_session_.end()) {
|
||||
@@ -731,9 +834,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
if (!victim) return RAD_E_FULL;
|
||||
BlockHash vh = victim->prefix;
|
||||
uint64_t vs = victim->session;
|
||||
/* A VICTIM THE TIERS HOLD A COPY OF IS DETACHED, NOT LOST. The slot goes back all the
|
||||
* same; the index entry stays, and the session's next restore brings the state back
|
||||
* with its blocks instead of replaying every recurrent layer from an older point. */
|
||||
/* 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);
|
||||
@@ -766,15 +869,17 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
|
||||
void PrefixCache::commit_checkpoint(const BlockHash& prefix, bool resume) {
|
||||
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;
|
||||
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);
|
||||
if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos, resume);
|
||||
}
|
||||
|
||||
|
||||
@@ -782,16 +887,16 @@ void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
|
||||
|
||||
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 they may be reading the slot: a copy to host memory in
|
||||
* flight out of a slot the pool then decommits reads a page that is no longer mapped. When
|
||||
* one is, the tiers keep the slot and hand it back once the copy has reported. */
|
||||
const bool held = tiers_ && tiers_->release_snapshot(it->first);
|
||||
/* 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 TIERS HOLD THE BYTES. They also remember a snapshot's
|
||||
* DEVICE slot -- note_snapshot records it at commit, because a demotion has to know what to
|
||||
* copy 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 pool has since given to another session, and
|
||||
* the next demotion copies THAT session's recurrent state and restores it as this one's. The
|
||||
/* 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.
|
||||
*
|
||||
@@ -803,10 +908,11 @@ void PrefixCache::retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>
|
||||
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.off_device) return RAD_OK; /* already theirs */
|
||||
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.off_device = true;
|
||||
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. */
|
||||
@@ -818,11 +924,15 @@ 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;
|
||||
/* A SLOT THIS ENTRY DID NOT ASK FOR IS STILL ITS OWN. The promotion allocated it and filled it
|
||||
* from the tier copy of THIS key's state, so the identity that matters -- which prefix the
|
||||
/* 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.off_device = false;
|
||||
it->second.detached = false;
|
||||
it->second.valid = true;
|
||||
it->second.used = ++clock_;
|
||||
return RAD_OK;
|
||||
@@ -833,7 +943,7 @@ bool PrefixCache::free_checkpoint_for_restore() {
|
||||
const Ckpt* victim = nullptr;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
const Ckpt& c = kvp.second;
|
||||
if (c.off_device || c.slot < 0 || !c.valid) continue;
|
||||
if (c.detached || c.slot < 0 || !c.valid) continue;
|
||||
if (victim && c.used >= victim->used) continue;
|
||||
if (std::find(handed_.begin(), handed_.end(), kvp.first) != handed_.end()) continue;
|
||||
if (!tiers_->snapshot_backed(kvp.first)) continue;
|
||||
@@ -846,12 +956,51 @@ bool PrefixCache::free_checkpoint_for_restore() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void PrefixCache::hold(uint64_t req, const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm) {
|
||||
if (!enabled_ || !tiers_ || tokens.empty() || holds_.count(req)) return;
|
||||
const int64_t n_full = ((int64_t)tokens.size() - 1) / block_size_;
|
||||
const std::vector<BlockHash> hs = chain_all(tokens, mm, n_full);
|
||||
std::vector<BlockHash>& mine = holds_[req];
|
||||
for (int64_t b = 0; b < n_full; ++b) {
|
||||
auto it = map_.find(hs[(size_t)b]);
|
||||
if (it == map_.end()) break;
|
||||
const int32_t* src = tokens.data() + b * block_size_;
|
||||
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;
|
||||
mine.push_back(hs[(size_t)b]);
|
||||
++held_[hs[(size_t)b]];
|
||||
}
|
||||
}
|
||||
|
||||
size_t PrefixCache::resident_prefix(const std::vector<BlockHash>& chain) const {
|
||||
size_t n = 0;
|
||||
for (; n < chain.size(); ++n) {
|
||||
auto it = map_.find(chain[n]);
|
||||
if (it == map_.end() || !it->second.in_lru) break;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
void PrefixCache::release(uint64_t req) {
|
||||
auto it = holds_.find(req);
|
||||
if (it == holds_.end()) return;
|
||||
for (const BlockHash& h : it->second) {
|
||||
auto k = held_.find(h);
|
||||
if (k != held_.end() && --k->second <= 0) held_.erase(k);
|
||||
}
|
||||
holds_.erase(it);
|
||||
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 and the bytes are already gone.
|
||||
* Telling them to free what they just lost would double-free the arena slot. */
|
||||
/* 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;
|
||||
@@ -861,9 +1010,9 @@ void PrefixCache::drop_snapshot(const BlockHash& key) {
|
||||
if (sit->second.empty()) ck_by_session_.erase(sit);
|
||||
}
|
||||
|
||||
int64_t PrefixCache::snapshots_off_device() const {
|
||||
int64_t PrefixCache::snapshots_detached() const {
|
||||
int64_t n = 0;
|
||||
for (const auto& kvp : ck_by_prefix_) if (kvp.second.off_device) ++n;
|
||||
for (const auto& kvp : ck_by_prefix_) if (kvp.second.detached) ++n;
|
||||
return n;
|
||||
}
|
||||
} /* namespace rad */
|
||||
+71
-45
@@ -43,8 +43,8 @@
|
||||
* is unaffected either way; the only difference is whether the prefixes still exist when the next
|
||||
* turn asks for them, and that difference is one to two orders of magnitude of time to first
|
||||
* token. Size the cache so live sessions fit with room to spare -- a context of T tokens occupies
|
||||
* roughly 1.8 x T pool-tokens across the paged groups -- and keep --expert-vs-cache-ratio on the
|
||||
* safe side of that.
|
||||
* roughly 1.8 x T pool-tokens across the paged groups. The budget gives the cache everything the
|
||||
* experts can do without (core/mem/vram_budget.h); --host-pool-mib is what moves that.
|
||||
*
|
||||
* WHAT TO WATCH: `kv_util` (/stats, or vllm:kv_cache_usage_perc) is the predictor, and
|
||||
* `radiance:prefix_cache_evictions_total` is the event -- the hit rate is neither, because it only
|
||||
@@ -203,6 +203,20 @@ public:
|
||||
* instead of forgetting it: the next turn restores it rather than re-prefilling it. Only an
|
||||
* entry with no host copy yet is lost. Either way the blocks go back to the pool. */
|
||||
int64_t evict_lru(int64_t n_entries);
|
||||
/* FREE UP TO `n_blocks` BLOCKS OF THE POOL for the reserve the scheduler keeps, losing nothing
|
||||
* a later turn could have reused. One walk of the LRU list, oldest first, that takes only what
|
||||
* gives the pool a block back without costing a conversation:
|
||||
*
|
||||
* - an entry a live sequence also holds is passed over. Releasing the cache's reference on
|
||||
* it frees nothing, and without a host copy it erases the entry -- which, right after a
|
||||
* publish, is the conversation that request just finished;
|
||||
* - with the idle tiers on, an entry whose host copy has not landed is passed over too. It
|
||||
* is the next turn's context with nowhere else to come from, and in a moment it is clean
|
||||
* and can leave VRAM for nothing.
|
||||
*
|
||||
* Pressure that cannot wait -- an admission or a step that needs the blocks now -- is
|
||||
* evict_lru's. Returns how many blocks went back. */
|
||||
int64_t trim(int64_t n_blocks);
|
||||
/* GIVE UP EVERY VRAM COPY THAT CAN GO FOR NOTHING: the entries whose host copy has landed and
|
||||
* that no running sequence is still reading. Called when the memory has a better use -- the
|
||||
* expert slab's loan -- and returns how many entries left VRAM. An entry a sequence still
|
||||
@@ -258,50 +272,53 @@ public:
|
||||
/* ---------------- the linear half of an idle session ----------------
|
||||
*
|
||||
* ON A HYBRID MODEL THE BLOCKS ARE ONLY HALF OF WHAT A SESSION NEEDS BACK. The other half is
|
||||
* the recurrent state, and it lives in a CHECKPOINT SLOT: a device-resident object of
|
||||
* KVManager::checkpoint_bytes(), of which there are --checkpoint-slots IN TOTAL for the whole
|
||||
* server. Eight by default, against the six or seven a single 200K session retains under
|
||||
* geometric backoff -- so a second session evicts the first's snapshots, tip included.
|
||||
*
|
||||
* Tiering the blocks and leaving the snapshot behind therefore gets the trade backwards: it
|
||||
* frees the plentiful resource and holds on to the scarce one. And what the session loses is
|
||||
* not part of its hit, it is ALL of it -- the scheduler clamps reuse to the last checkpoint a
|
||||
* hit can reach, because RadBatch carries one query length for every KV group and the linear
|
||||
* the recurrent state, and it lives in a CHECKPOINT SLOT: a slot of the engine's snapshot
|
||||
* store in pinned host memory, KVManager::checkpoint_bytes() a rank, of which there are
|
||||
* --checkpoint-slots IN TOTAL for the whole server. What the session loses without it is not
|
||||
* part of its hit, it is ALL of it -- the scheduler clamps reuse to the last checkpoint a hit
|
||||
* can reach, because RadBatch carries one query length for every KV group and the linear
|
||||
* layers cannot be replayed over a longer range than the attention ones (core/sched/
|
||||
* scheduler.cpp, admit_one). A restored session with no reachable snapshot reuses zero tokens
|
||||
* and re-prefills its whole transcript. The blocks without the state are not a partial win;
|
||||
* they are unusable.
|
||||
* and re-prefills its whole transcript.
|
||||
*
|
||||
* So a snapshot moves with the blocks whose hash it is keyed by, and these calls are the
|
||||
* cache's whole part in that. The bytes are the engine's to move. */
|
||||
* 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. */
|
||||
|
||||
/* Its bytes are on another tier now: give the device slot back and stop offering it. The index
|
||||
* entry STAYS, because that is what a promotion puts the snapshot back into, and an entry
|
||||
* whose state is not in the pool is exactly the `valid` flag's existing meaning -- lookup
|
||||
* already walks past one and falls back to an older position. */
|
||||
/* 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 DEVICE CHECKPOINT SLOT FOR A RESTORE. The pool is --checkpoint-slots deep for the whole
|
||||
* server, and it is full whenever as many sessions have run since; a session restored then
|
||||
* would get its blocks back and 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 tiers hold a copy of -- which the next restore of THAT session brings back -- and never
|
||||
* one whose only copy is the slot, and never one a lookup has handed out since the step began:
|
||||
* that request reads the slot in this step's forward, and a restore writes it before the
|
||||
* forward runs. True when a slot was freed. */
|
||||
/* 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
|
||||
* same chain again, every step for as long as the request waits. A held entry is passed over
|
||||
* by drop_clean until release(); trim and evict_lru still take it under pressure, which costs
|
||||
* a restore and loses nothing. Idempotent per request. */
|
||||
void hold(uint64_t req, const std::vector<int32_t>& tokens, const std::vector<MMContentKey>& mm);
|
||||
/* How many of `chain`'s leading entries are in VRAM: as far as a lookup's hit can reach. */
|
||||
size_t resident_prefix(const std::vector<BlockHash>& chain) const;
|
||||
void release(uint64_t req);
|
||||
/* 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. */
|
||||
void begin_step() { handed_.clear(); }
|
||||
/* The tiers lost it -- a capacity drop, a failed promotion, or an entry they were told to
|
||||
* forget. Erase the index entry; there is no device slot to give back. */
|
||||
/* 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 the tiers have. Reported rather than derived
|
||||
* because it is the number that says whether hybrid tiering is doing anything at all: a
|
||||
* session can move its whole chain off the device and still be re-prefilling its linear
|
||||
* layers from zero on every hit, and nothing else distinguishes the two. */
|
||||
int64_t snapshots_off_device() const;
|
||||
/* How many snapshots the index holds whose bytes are only on disk. */
|
||||
int64_t snapshots_detached() const;
|
||||
/* ---------------- 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). */
|
||||
@@ -313,8 +330,9 @@ 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. */
|
||||
void commit_checkpoint(const BlockHash& prefix);
|
||||
* 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);
|
||||
/* 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.
|
||||
@@ -361,21 +379,24 @@ private:
|
||||
* 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 STILL IN THE POOL. The idle tiers move a snapshot along with the blocks
|
||||
* it is keyed by, and `slot` is -1 for the whole time they hold it. 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 off_device = 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;
|
||||
/* Retire one snapshot whatever tier holds its bytes: a device slot goes back to the pool, and
|
||||
* tiered bytes go back to the tiers. One place, because three call sites that each remembered
|
||||
* to check `off_device` would be three places to forget. The session index is the caller's,
|
||||
* since every caller is already rebuilding or erasing it. */
|
||||
/* 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. */
|
||||
void retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it);
|
||||
|
||||
KVManager* kv_ = nullptr;
|
||||
@@ -394,6 +415,11 @@ private:
|
||||
std::vector<BlockHash> drop_wait_;
|
||||
std::vector<BlockHash> drop_scratch_;
|
||||
uint64_t frees_seen_ = 0;
|
||||
/* hold(): the keys each waiting request holds, and how many requests hold each key. A release
|
||||
* makes drop_wait_ worth looking at again, as a freed sequence does. */
|
||||
std::unordered_map<uint64_t, std::vector<BlockHash>> holds_;
|
||||
std::unordered_map<BlockHash, int32_t, BlockHashHash> held_;
|
||||
bool released_ = false;
|
||||
mutable std::unordered_map<BlockHash, Ckpt, BlockHashHash> ck_by_prefix_;
|
||||
std::unordered_map<uint64_t, std::vector<BlockHash>> ck_by_session_;
|
||||
/* Snapshots lookup handed out since begin_step: not a restore's to take (free_checkpoint_for_restore). */
|
||||
|
||||
+73
-43
@@ -22,6 +22,13 @@ int64_t to_mib(int64_t bytes) { return bytes > 0 ? bytes / kMiB : 0; }
|
||||
* footprint to the byte, and there the rounding direction decides whether it loads. The MiB this
|
||||
* claims comes out of the headroom, which is what the headroom is for. */
|
||||
int64_t to_mib_up(int64_t bytes) { return bytes > 0 ? (bytes + kMiB - 1) / kMiB : 0; }
|
||||
|
||||
/* WHAT THE DRIVER'S OWN HOLDING MOVES BY AFTER IT IS READ. `already_held` is one reading, and on
|
||||
* ROCm 7.2 the same server started twice has read 4 MiB less than it later held (and once 30 MiB
|
||||
* more): a budget that split the difference away came up a few MiB short of the headroom the
|
||||
* first launches of kernels allocate from. Four times the drift seen, and charged before anything
|
||||
* is split. */
|
||||
constexpr int64_t kDriverDrift = 16 * kMiB;
|
||||
} /* namespace */
|
||||
|
||||
/* WHAT THE CACHE BACKS, counted on its PAGED part. The ceiling is the recurrent and conv state of
|
||||
@@ -33,7 +40,7 @@ static double paged_share(const VramBudget& b) {
|
||||
return ctx > 0 ? std::max(0.0, (double)(b.kv - b.kv_fixed)) / ctx : 0.0;
|
||||
}
|
||||
|
||||
/* The resolver, with its three log lines behind `log`: vram_budget_trial asks the same question
|
||||
/* The resolver, with its log lines behind `log`: vram_budget_trial asks the same question
|
||||
* of a configuration it may not use, and a refusal printed for a split nobody takes reads as the
|
||||
* startup failing. */
|
||||
static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out, bool log) {
|
||||
@@ -46,7 +53,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* overcommitting the smaller one on the first allocation. */
|
||||
b.capacity = per_rank[0].capacity;
|
||||
int64_t freeb = per_rank[0].free;
|
||||
int64_t layer_max = 0;
|
||||
int64_t layer_max = 0, kv_one = 0;
|
||||
for (const VramFacts& f : per_rank) {
|
||||
b.capacity = std::min(b.capacity, f.capacity);
|
||||
freeb = std::min(freeb, f.free);
|
||||
@@ -62,7 +69,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
b.statics = std::max(b.statics, f.statics);
|
||||
b.expert_ceiling = std::max(b.expert_ceiling, f.experts);
|
||||
layer_max = std::max(layer_max, f.expert_layer_max);
|
||||
/* THE RANK THAT NEEDS MOST ON THE CARD SETS THE FLOOR. */
|
||||
b.expert_floor = std::max(b.expert_floor, f.expert_floor);
|
||||
kv_one = std::max(kv_one, f.kv_one);
|
||||
}
|
||||
b.lends = true;
|
||||
for (const VramFacts& f : per_rank) b.lends = b.lends && f.lends;
|
||||
b.headroom = std::max<int64_t>(cfg.gpu_headroom_mib, 0) * kMiB;
|
||||
int64_t host_reserve = 0;
|
||||
for (const VramFacts& f : per_rank) host_reserve = std::max(host_reserve, f.host_reserve);
|
||||
@@ -91,7 +103,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
b.derived_kv = want_kv;
|
||||
|
||||
/* What is left after the terms nobody gets to spend. */
|
||||
int64_t fixed = b.already_held + b.headroom + b.arena + b.staging + b.queues;
|
||||
b.drift = (want_w || want_kv) ? kDriverDrift : 0;
|
||||
int64_t fixed = b.already_held + b.drift + b.headroom + b.arena + b.staging + b.queues;
|
||||
if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */
|
||||
if (!want_kv) fixed += cfg.vram_kv_mib * kMiB;
|
||||
b.claimable = b.capacity - fixed;
|
||||
@@ -101,6 +114,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
"VRAM does not cover the fixed costs before a single pool is sized:\n"
|
||||
" card total %10s\n"
|
||||
" already held %10s (driver context, code objects, anything else on the card)\n"
|
||||
" driver drift %10s (what that moves by after it is read)\n"
|
||||
" --gpu-headroom-mib %10s\n"
|
||||
" activation arena %10s (buffer plan + kernel scratch)\n"
|
||||
" step staging %10s (block tables, media and KV tier staging)\n"
|
||||
@@ -110,7 +124,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" SHORT BY %10s\n"
|
||||
"Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
|
||||
"or free the card.\n",
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(),
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
|
||||
humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(),
|
||||
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
|
||||
want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n",
|
||||
@@ -147,39 +161,42 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
b.elastic = want_w ? b.claimable - b.statics : b.claimable;
|
||||
if (b.elastic < 0) b.elastic = 0;
|
||||
|
||||
/* ---- and only what is left is what the ratio divides ------------------------------------- */
|
||||
/* ---- and only what is left is divided --------------------------------------------------- */
|
||||
if (want_w && want_kv) {
|
||||
const double r = (cfg.expert_cache_ratio > 0.0 && cfg.expert_cache_ratio < 1.0)
|
||||
? cfg.expert_cache_ratio : 0.75;
|
||||
int64_t kv = (int64_t)((double)b.elastic * (1.0 - r));
|
||||
int64_t exp = b.elastic - kv;
|
||||
|
||||
/* BOTH SIDES ARE CAPPED AT WHAT THEY COULD USE, AND THE SLACK CROSSES OVER. A paged cache
|
||||
* cannot address past max_seqs x max_ctx tokens and an expert plane that is entirely
|
||||
* resident has no use for another byte -- so a share above either ceiling is memory
|
||||
* nothing will ever touch. Cap, then hand the remainder to whichever side is still short,
|
||||
* then stop: what neither can take is genuinely unusable and is reported as such rather
|
||||
* than allocated into a pool that reports itself three quarters empty. */
|
||||
if (b.kv_ceiling > 0 && kv > b.kv_ceiling) kv = b.kv_ceiling;
|
||||
/* ZERO EXPERTS IS A CEILING OF ZERO, NOT AN UNMEASURED ONE. weight_footprint() runs on
|
||||
* every rank before this call, so expert_ceiling is always known -- and guarding this cap
|
||||
* with `> 0` would read "dense" as "unlimited", handing a model with no experts at all a
|
||||
* large expert budget against nothing to put in it while its cache goes short.
|
||||
* kv_ceiling keeps its guard: that one IS genuinely unset when plan_groups fails. */
|
||||
if (exp > b.expert_ceiling) exp = b.expert_ceiling;
|
||||
int64_t spare = b.elastic - kv - exp;
|
||||
if (spare > 0 && b.expert_ceiling > exp) {
|
||||
const int64_t take = std::min(spare, b.expert_ceiling - exp);
|
||||
exp += take; spare -= take;
|
||||
}
|
||||
if (spare > 0 && b.kv_ceiling > kv) {
|
||||
const int64_t take = std::min(spare, b.kv_ceiling - kv);
|
||||
kv += take; spare -= take;
|
||||
/* An unset cache ceiling (plan_groups failed) bounds nothing; zero experts is a ceiling of
|
||||
* zero, which weight_footprint always measures. */
|
||||
const int64_t kv_cap = b.kv_ceiling > 0 ? b.kv_ceiling : b.elastic;
|
||||
int64_t kv = 0, exp = 0;
|
||||
if (kv_cap + b.expert_ceiling <= b.elastic) {
|
||||
/* BOTH FIT: nothing trades. */
|
||||
kv = kv_cap;
|
||||
exp = b.expert_ceiling;
|
||||
} else if (b.lends) {
|
||||
/* THE CACHE LENDS, so it is sized for what live requests could need and gives back
|
||||
* whatever they do not. The experts keep what the host pool cannot hold. */
|
||||
exp = std::min(b.expert_floor, b.elastic);
|
||||
kv = std::min(kv_cap, std::max(b.elastic - exp, kv_one));
|
||||
exp = std::min(std::max(b.expert_ceiling, b.expert_floor), b.elastic - kv);
|
||||
/* THE ONE SEQUENCE WINS, and the experts it pushes off the card have no tier: the
|
||||
* planner refuses them by name. Said here too, with what moves it. */
|
||||
if (log && exp < b.expert_floor)
|
||||
RAD_WARN("one --max-model-len sequence's cache (%s) leaves the experts %s, short of "
|
||||
"the %s the pinned host pool cannot hold: raise --host-pool-mib or lower "
|
||||
"--max-model-len",
|
||||
humanb(kv_one).c_str(), humanb(exp).c_str(),
|
||||
humanb(b.expert_floor).c_str());
|
||||
} else {
|
||||
/* NO LENDER: a block the cache does not use would sit empty, so the experts come
|
||||
* first and the cache keeps one --max-model-len sequence. */
|
||||
kv = std::min(kv_cap, std::max(b.elastic - b.expert_ceiling, kv_one));
|
||||
exp = std::min(b.expert_ceiling, b.elastic - kv);
|
||||
}
|
||||
if (kv > b.elastic) kv = b.elastic;
|
||||
if (exp < 0) exp = 0;
|
||||
b.experts = exp;
|
||||
b.kv = kv;
|
||||
b.weights = b.statics + exp;
|
||||
b.unusable = spare > 0 ? spare : 0;
|
||||
b.unusable = std::max<int64_t>(b.elastic - kv - exp, 0);
|
||||
} else if (want_kv) {
|
||||
b.kv = b.kv_ceiling > 0 ? std::min(b.claimable, b.kv_ceiling) : b.claimable;
|
||||
b.unusable = b.claimable - b.kv;
|
||||
@@ -214,7 +231,15 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling;
|
||||
const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) /
|
||||
RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
|
||||
if (2 * one < b.experts) {
|
||||
if (b.lends && want_kv) {
|
||||
/* A LENDING CACHE PAYS FOR IT: the experts are at their floor and a byte less would
|
||||
* leave one with no tier, while the region is lent to the slab whenever the steps are
|
||||
* small -- the same memory the cache would have lent. */
|
||||
if (b.kv - 2 * one >= kv_one) {
|
||||
b.stage = 2 * one;
|
||||
b.kv -= b.stage;
|
||||
}
|
||||
} else if (2 * one < b.experts) {
|
||||
b.stage = 2 * one;
|
||||
b.experts -= b.stage;
|
||||
b.weights = b.statics + b.experts;
|
||||
@@ -244,7 +269,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
"sequence's blocks stay held so the next turn can reuse them, so the demand is "
|
||||
"live SESSIONS and not running requests -- when they do not all fit, the cache "
|
||||
"evicts prefixes the next turn wanted and that turn re-prefills its whole "
|
||||
"context. --expert-vs-cache-ratio moves it.",
|
||||
"context. --host-pool-mib moves it: the experts the host pool cannot hold are the "
|
||||
"part of the card the cache cannot have.",
|
||||
100.0 * paged_share(b),
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
|
||||
(double)cfg.max_seqs * paged_share(b));
|
||||
@@ -262,13 +288,14 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* line is not padding: to_mib truncates, and what it drops is real VRAM that ends up beside
|
||||
* the headroom. */
|
||||
const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB;
|
||||
const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.staging - b.queues - b.stage -
|
||||
granted;
|
||||
const int64_t unclaimed = b.capacity - b.already_held - b.drift - b.arena - b.staging - b.queues -
|
||||
b.stage - granted;
|
||||
const double ela = b.elastic > 0 ? (double)b.elastic : 1.0;
|
||||
b.report = fmt(
|
||||
"VRAM budget, per card:\n"
|
||||
" card total %10s\n"
|
||||
" already held %10s measured: driver context, code objects, anything else resident\n"
|
||||
" driver drift %10s what that moves by after it is read: kept free\n"
|
||||
" activation arena %10s computed from the buffer plan\n"
|
||||
" step staging %10s the step batch's block tables and media staging, and the\n"
|
||||
" KV tiers' copy staging\n"
|
||||
@@ -278,7 +305,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" claimable %10s\n"
|
||||
" static weights %10s %s\n"
|
||||
" ------------------------------\n"
|
||||
" elastic %10s what --expert-vs-cache-ratio %.2f divides\n"
|
||||
" elastic %10s %s\n"
|
||||
" experts %10s %.0f%% of it%s\n"
|
||||
" kv cache %10s %.0f%% of it%s\n"
|
||||
"%s"
|
||||
@@ -288,8 +315,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" vram_kv %10s %s\n"
|
||||
" unclaimed %10s the headroom, the unusable above, and what MiB rounding\n"
|
||||
" could not place\n",
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.arena).c_str(),
|
||||
humanb(b.staging).c_str(),
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
|
||||
humanb(b.arena).c_str(), humanb(b.staging).c_str(),
|
||||
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
|
||||
shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(),
|
||||
shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool "
|
||||
@@ -300,8 +327,10 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
b.derived_weights ? "off the top: every rank's own shard, and not a share of anything"
|
||||
: "(not charged here -- --vram-weights-mib was stated)",
|
||||
humanb(b.elastic).c_str(),
|
||||
(cfg.expert_cache_ratio > 0.0 && cfg.expert_cache_ratio < 1.0) ? cfg.expert_cache_ratio
|
||||
: 0.75,
|
||||
b.lends ? "the experts keep what the host pool cannot hold; the cache takes the rest\n"
|
||||
" and lends what no live request holds to the "
|
||||
"expert slab"
|
||||
: "no lender: the experts first, the cache at least one full-length sequence",
|
||||
humanb(b.experts).c_str(), 100.0 * (double)b.experts / ela,
|
||||
b.expert_ceiling == 0
|
||||
? " -- a dense model, so there is no expert plane for this share to fill and the\n"
|
||||
@@ -339,10 +368,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
"ceiling\n", humanb(b.unusable).c_str()).c_str()
|
||||
: "",
|
||||
b.stage > 0
|
||||
? fmt(" prefill staging %10s out of the experts: two buffers of one layer's "
|
||||
? fmt(" prefill staging %10s out of the %s: two buffers of one layer's "
|
||||
"non-resident experts,\n"
|
||||
" at the arena's top and lent back to the "
|
||||
"slab while steps are small\n", humanb(b.stage).c_str()).c_str()
|
||||
"slab while steps are small\n", humanb(b.stage).c_str(),
|
||||
b.lends ? "cache" : "experts").c_str()
|
||||
: "",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str(),
|
||||
b.derived_weights ? "static + experts" : "stated by --vram-weights-mib",
|
||||
|
||||
+30
-14
@@ -28,20 +28,23 @@
|
||||
* pinned host pool, which a lookup reads a few rows of in place; weight_footprint counts it out of
|
||||
* the statics then), and under tensor parallel each rank already holds its own even share of
|
||||
* them (declare runs per rank with every dimension divided, spec §9). They are a FLOOR, not a
|
||||
* share of anything: applying a ratio to the weights as a whole would let --expert-vs-cache-ratio
|
||||
* 0.3 demote the attention projections to host memory to make room for a cache nothing will fill.
|
||||
* If they do not fit, that is a refusal with the shortfall named.
|
||||
* share of anything: dividing the weights as a whole would let the cache's side demote the
|
||||
* attention projections to host memory to make room for blocks nothing will fill. If they do not
|
||||
* fit, that is a refusal with the shortfall named.
|
||||
*
|
||||
* ONLY WHAT IS LEFT AFTER THAT IS DIVIDED, and that is the division the flag is named for: the
|
||||
* expert plane against the KV cache, which is the one genuinely two-sided trade on this engine. A
|
||||
* long-context low-concurrency server and a short-context high-concurrency one want opposite
|
||||
* answers and neither is derivable.
|
||||
* ONLY WHAT IS LEFT AFTER THAT IS DIVIDED: the expert plane against the KV cache. Where the cache
|
||||
* lends its idle blocks to the expert slab, that division has nothing to guess. The experts keep
|
||||
* on the card exactly what the pinned host pool cannot hold -- they have nowhere else to be -- and
|
||||
* the cache takes the rest, up to what it could ever address; every block no live request holds
|
||||
* is lent back to the experts in place. So the cache is as large as the work needs at the moment
|
||||
* and the experts have everything else, for a long-context server and a high-concurrency one
|
||||
* alike. Without a lender the cache would hold that memory empty, so there the experts come first
|
||||
* and the cache keeps one --max-model-len sequence. The cache never gets less than that sequence.
|
||||
*
|
||||
* BOTH SIDES ARE THEN CAPPED AT WHAT THEY COULD USE, and whatever one side cannot take goes to the
|
||||
* BOTH SIDES ARE CAPPED AT WHAT THEY COULD USE, and whatever one side cannot take goes to the
|
||||
* other rather than nowhere. A cache cannot address past max_seqs x max_ctx tokens
|
||||
* (KVManager::ceiling), so a share larger than that ceiling is VRAM the cache can never fill and
|
||||
* the expert plane could have held. And an expert plane that fits entirely in VRAM has no use for
|
||||
* more; on a model that fits, the ratio stops meaning anything and that is correct.
|
||||
* (KVManager::ceiling), and an expert plane that fits entirely in VRAM has no use for more; when
|
||||
* both fit, both are whole.
|
||||
*
|
||||
* A stated --vram-weights-mib or --vram-kv-mib still wins outright and turns the whole of this
|
||||
* off for that pool. The point is that the DEFAULT is a full card rather than a guess: VRAM left
|
||||
@@ -76,8 +79,18 @@ struct VramFacts {
|
||||
/* weight_footprint() for this rank, which under tensor parallel is already this card's even
|
||||
* share: declare runs per rank with every dimension already divided. */
|
||||
int64_t statics = 0; /* non-expert weights -- the floor, not a share of anything */
|
||||
int64_t experts = 0; /* the elastic plane the ratio divides against the KV cache */
|
||||
int64_t experts = 0; /* the expert plane: what trades against the KV cache */
|
||||
int64_t expert_layer_max = 0; /* the most expert bytes one routed layer holds */
|
||||
/* THE EXPERTS THE PINNED HOST POOL CANNOT HOLD on this rank, with the slab's spare slots
|
||||
* beside them: they have nowhere to be but the card, so this is the floor under the expert
|
||||
* slab when the cache lends (expert_vram_floor, core/place/planner.h). */
|
||||
int64_t expert_floor = 0;
|
||||
int64_t kv_one = 0; /* the cache for ONE --max-model-len sequence: the least it may get */
|
||||
/* WILL THE CACHE LEND ITS IDLE BLOCKS TO THE EXPERT SLAB: a placement that moves units
|
||||
* (expert_tiered, or auto), not --deterministic, on a device with virtual memory management.
|
||||
* Decides the split: a cache that lends gives back what it does not use, so it can be sized
|
||||
* for what live requests could need; one that does not would hold it empty. */
|
||||
bool lends = false;
|
||||
/* Integrated graphics: what of the host's memory the card leaves to the host. Its device
|
||||
* memory IS the host's, so an unclaimed MiB is the operating system's and every other
|
||||
* process's to run in, not slack. 0 on a discrete card. */
|
||||
@@ -88,12 +101,15 @@ struct VramFacts {
|
||||
* operator stated the budgets -- the placement report and the pool report both want the totals. */
|
||||
struct VramBudget {
|
||||
int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0;
|
||||
int64_t drift = 0; /* kDriverDrift: what already_held moves by after it is read */
|
||||
int64_t queues = 0; /* n_queues * queue_bytes, from the rank that needs most */
|
||||
int n_queues = 0;
|
||||
int64_t queue_bytes = 0;
|
||||
int64_t claimable = 0; /* after the fixed terms above */
|
||||
int64_t statics = 0; /* off the top, before the ratio sees anything */
|
||||
int64_t elastic = 0; /* claimable - statics: what the ratio divides */
|
||||
int64_t statics = 0; /* off the top, before the split sees anything */
|
||||
int64_t elastic = 0; /* claimable - statics: what experts and cache share */
|
||||
int64_t expert_floor = 0; /* the experts the host pool cannot hold */
|
||||
bool lends = false; /* every rank's cache lends its idle blocks */
|
||||
int64_t kv_ceiling = 0, expert_ceiling = 0;
|
||||
int64_t kv_fixed = 0; /* the state part of kv_ceiling, which no context uses */
|
||||
int64_t experts = 0, kv = 0; /* the two shares, each capped at its ceiling */
|
||||
|
||||
+26
-2
@@ -20,6 +20,7 @@
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -101,6 +102,17 @@ int64_t weight_bytes(const WeightInfo& w) {
|
||||
/* See planner.h. Planner::resolve_sites, Planner::build_units and Planner::pin_mapped, run over
|
||||
* the same program without allocating a Plan -- the budget resolver calls this before a Planner
|
||||
* exists. Kept adjacent to the three so a change to any of them has this in the same diff. */
|
||||
int64_t file_stage_reserve(int64_t widest, bool routed) {
|
||||
return (int64_t)RAD_PLACE_FILE_STAGE_SLOTS * widest +
|
||||
(routed ? (int64_t)RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES : 0);
|
||||
}
|
||||
|
||||
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room) {
|
||||
if (wf.experts <= 0) return 0;
|
||||
const int64_t all = wf.experts + wf.expert_spare;
|
||||
return std::min(all, std::max<int64_t>(all + 2 * wf.expert_unit_max - host_room, 0));
|
||||
}
|
||||
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram) {
|
||||
if (!out) return;
|
||||
@@ -166,6 +178,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
* align_up(static_need, RAD_ALIGN_UNIT)` before every unit it places. A budget that summed raw
|
||||
* bytes would be short by one alignment per unit, which on a 512-expert MoE is real. */
|
||||
std::map<int32_t, int64_t> layer_experts;
|
||||
std::set<int64_t> expert_strides;
|
||||
bool ngram_host = true;
|
||||
for (const U& mu : units) if (mu.ngram && !mu.host) ngram_host = false;
|
||||
for (const U& mu : units) {
|
||||
@@ -178,9 +191,20 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
* placed in VRAM. */
|
||||
if (mu.mapped || (mu.ngram && ngram != TablePlacement::Vram)) out->mapped += b;
|
||||
else if (mu.emb && embedding == TablePlacement::Ram) out->hosted += b;
|
||||
else if (mu.expert >= 0) { out->experts += b; layer_experts[mu.layer] += b; }
|
||||
else if (mu.expert >= 0) {
|
||||
out->experts += b;
|
||||
layer_experts[mu.layer] += b;
|
||||
out->expert_unit_max = std::max(out->expert_unit_max, b);
|
||||
expert_strides.insert(b);
|
||||
}
|
||||
else out->statics += b;
|
||||
if (mu.layer >= 0 && !mu.mapped) out->layer_unit_max = std::max(out->layer_unit_max, b);
|
||||
if (mu.expert >= 0 && mu.layer >= 0) out->routed = true;
|
||||
}
|
||||
/* build_classes: one expert slab class a stride. */
|
||||
for (int64_t s : expert_strides)
|
||||
out->expert_spare += (int64_t)(RAD_PLACE_SHADOW_SLOTS + RAD_PLACE_STAGE_RING) * s +
|
||||
RAD_ALIGN_UNIT;
|
||||
for (const auto& le : layer_experts)
|
||||
out->expert_layer_max = std::max(out->expert_layer_max, le.second);
|
||||
out->ngram_host = out->ngram > 0 && ngram_host;
|
||||
@@ -1157,7 +1181,7 @@ int Planner::plan(Plan* out) {
|
||||
}
|
||||
const int64_t windows = routed ? (int64_t)RAD_PLACE_FILE_WINDOWS *
|
||||
RAD_PLACE_FILE_WINDOW_BYTES : 0;
|
||||
const int64_t need = (int64_t)RAD_PLACE_FILE_STAGE_SLOTS * widest + windows;
|
||||
const int64_t need = file_stage_reserve(widest, routed);
|
||||
if (need > 0) {
|
||||
if (need >= out->host_budget) {
|
||||
RAD_ERR("placement: the file tier needs %s of pinned staging (%d slots of %s%s) "
|
||||
|
||||
+21
-3
@@ -361,9 +361,8 @@ int64_t weight_bytes(const WeightInfo& w);
|
||||
* order: how much room is there, and only then what goes in it. And the split matters more than
|
||||
* the total. A model's static weights -- everything that is not an expert -- have to be resident
|
||||
* for the model to run at a sensible speed at all, so they come off the top; the expert plane is
|
||||
* the only thing that trades against the KV cache, and it is what --expert-vs-cache-ratio divides.
|
||||
* Applying a ratio to the two together would let a 0.3 setting demote the attention projections to
|
||||
* host memory to make room for a cache nothing will fill.
|
||||
* the only thing that trades against the KV cache. Dividing the two together would let the cache's
|
||||
* side demote the attention projections to host memory to make room for blocks nothing will fill.
|
||||
*
|
||||
* The three answers are per RANK, and under tensor parallel that is already the even split across
|
||||
* devices: declare runs once per rank with every dimension ALREADY DIVIDED (spec §9), so summing
|
||||
@@ -377,6 +376,13 @@ struct WeightFootprint {
|
||||
int64_t statics = 0; /* non-expert and device-readable -- the floor under any budget */
|
||||
int64_t experts = 0; /* the elastic plane: what streams from host when it does not fit */
|
||||
int64_t expert_layer_max = 0; /* the most expert bytes any one routed layer holds */
|
||||
int64_t expert_unit_max = 0; /* the largest expert unit's slot */
|
||||
/* THE SLAB'S SPARE SLOTS beside the residents of an expert-tiered plan, at their most: per
|
||||
* expert slab class, the shadow slots and the staging ring and the tail pad
|
||||
* (Planner::assign_expert_tiered). They come out of the same weight budget as the residents. */
|
||||
int64_t expert_spare = 0;
|
||||
int64_t layer_unit_max = 0; /* the widest per-layer unit's slot: the file tier's staging */
|
||||
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`
|
||||
@@ -398,6 +404,18 @@ struct WeightFootprint {
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram);
|
||||
|
||||
/* THE PINNED STAGING THE FILE TIER TAKES OUT OF --host-pool-mib before any unit is placed in it:
|
||||
* RAD_PLACE_FILE_STAGE_SLOTS of the widest per-layer unit, and the read windows when a routed
|
||||
* layer can stream from the container. Planner::plan spends it; the budget counts it the same. */
|
||||
int64_t file_stage_reserve(int64_t widest, bool routed);
|
||||
|
||||
/* THE EXPERT BYTES THE CARD MUST HOLD when `host_room` bytes of the pinned host pool are free for
|
||||
* experts: everything the pool cannot take, the slab's spare slots beside them, and one unit of
|
||||
* first-fit slack on each side -- the resident fill and the pool fill each skip a unit that does
|
||||
* not fit and can leave up to one unit's room unspent. At most every expert and the spare slots.
|
||||
* A weight budget of the statics and this much places every expert in VRAM or the host pool. */
|
||||
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room);
|
||||
|
||||
/* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight
|
||||
* that at least one op reads and that only `embed_lookup` reads is a token embedding table, and
|
||||
* one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what
|
||||
|
||||
@@ -151,8 +151,6 @@ struct WeightInfo {
|
||||
int n_part_spans = 0;
|
||||
int64_t part_lo[RAD_MAX_ROW_PARTS] = {0}, part_hi[RAD_MAX_ROW_PARTS] = {0};
|
||||
int64_t part_total[RAD_MAX_ROW_PARTS] = {0};
|
||||
/* rad_weight_shard_zero: this rank reads nothing for it and the loader writes zeros. */
|
||||
bool shard_zero = false;
|
||||
|
||||
/* WHAT IT IS A VIEW OF (RadWeightDecl::source and ::planes, spec §4.3). `enc` is the source's
|
||||
* encoding as the model holds it -- or, with nothing behind the builder, plain in the declared
|
||||
@@ -212,7 +210,6 @@ struct WeightInfo {
|
||||
for (int i = 0; i < RAD_MAX_ROW_PARTS; ++i) {
|
||||
part_lo[i] = o.part_lo[i]; part_hi[i] = o.part_hi[i]; part_total[i] = o.part_total[i];
|
||||
}
|
||||
shard_zero = o.shard_zero;
|
||||
source = o.source; enc = o.enc; enc_known = o.enc_known; n_sel = o.n_sel;
|
||||
for (int i = 0; i < RAD_ENC_MAX_PLANES; ++i) {
|
||||
sel[i] = o.sel[i]; sel_rows[i] = o.sel_rows[i]; sel_cols[i] = o.sel_cols[i];
|
||||
@@ -641,7 +638,6 @@ struct Config {
|
||||
* a third name for the second one, and a flag whose values are not all distinct is a flag
|
||||
* whose log line cannot be read back. */
|
||||
std::string kv_cache_dtype = "bf16";
|
||||
double expert_cache_ratio = 0.75; /* --expert-vs-cache-ratio, weights vs KV of the remainder */
|
||||
/* SET BY THE RESOLVER, NOT BY A FLAG. vram_budget_resolve writes the two budgets above into
|
||||
* this config, which erases the only evidence of whether they were stated or derived -- and
|
||||
* Pools needs that to know whether unspent VRAM is a mis-stated budget worth warning about or
|
||||
|
||||
+90
-114
@@ -19,7 +19,7 @@ TierExec::~TierExec() { close(); }
|
||||
int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk,
|
||||
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,
|
||||
int64_t ck_slot_off, RadStream shared) {
|
||||
const HostArena* ck_store, RadStream shared) {
|
||||
close();
|
||||
if (!reg || !kv || !tiers || groups.empty() || max_batch <= 0 || max_copy <= 0 ||
|
||||
max_chain <= 0)
|
||||
@@ -28,9 +28,7 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier*
|
||||
max_batch_ = max_batch; max_copy_ = max_copy; max_chain_ = max_chain;
|
||||
slot_off_ = slot_off;
|
||||
slot_bytes_ = tiers->entry_bytes();
|
||||
ck_bytes_ = kv->checkpoint_bytes();
|
||||
ck_slot_bytes_ = tiers->ckpt_bytes();
|
||||
ck_slot_off_ = ck_slot_off;
|
||||
ck_store_ = ck_store && ck_store->enabled() ? ck_store : nullptr;
|
||||
shared_ = shared;
|
||||
RAD_TRY(rad_dev_set(device_));
|
||||
|
||||
@@ -46,6 +44,11 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier*
|
||||
gi.n_blocks = p->n_blocks;
|
||||
gi.base = p->base;
|
||||
gi.off = off;
|
||||
if (p->zero) {
|
||||
gi.zero = true;
|
||||
gi_.push_back(gi);
|
||||
continue;
|
||||
}
|
||||
/* THE FRAGMENT WIDTH IS THE CONSTRAINT THE KERNEL IS PICKED ON. libr4d's byte-row pair
|
||||
* takes n as a multiple of 4; a geometry that does not satisfy it resolves to nothing
|
||||
* here rather than failing at launch inside a batch. */
|
||||
@@ -66,6 +69,15 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier*
|
||||
gi_.push_back(gi);
|
||||
}
|
||||
if (gi_.empty()) return RAD_E_UNSUPPORTED;
|
||||
/* EVERY CACHED GROUP ZERO ON THIS RANK: it would hold nothing of any entry, and an empty
|
||||
* entry is a zero-width copy on every path below. Said, and the tiers are off -- one rank
|
||||
* that cannot take part takes them off for all. */
|
||||
if (off == 0) {
|
||||
RAD_WARN("kv tiers: this rank keeps no cache for any group the prefix cache holds "
|
||||
"(rad_kv_group_zero), so it has no part of an entry to move. The tiers are off.");
|
||||
close();
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
entry_bytes_ = off;
|
||||
|
||||
/* NOTHING IS BUILT ON THE DEVICE HERE -- see device_init(). A tier that is configured but has
|
||||
@@ -77,10 +89,8 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier*
|
||||
char buf[320];
|
||||
std::snprintf(buf, sizeof buf,
|
||||
"kv tier transfer: %zu paged group(s), %s an entry, batches of %d through "
|
||||
"gather_rows/scatter_rows at u8%s%s",
|
||||
gi_.size(), humanb(entry_bytes_).c_str(), max_batch_,
|
||||
ck_bytes_ > 0 ? "; linear state as one contiguous copy of " : "",
|
||||
ck_bytes_ > 0 ? humanb(ck_bytes_).c_str() : "");
|
||||
"gather_rows/scatter_rows at u8",
|
||||
gi_.size(), humanb(entry_bytes_).c_str(), max_batch_);
|
||||
report_ = buf;
|
||||
enabled_ = true;
|
||||
return RAD_OK;
|
||||
@@ -129,7 +139,7 @@ void TierExec::close() {
|
||||
order_.clear();
|
||||
verify_pending_.clear();
|
||||
entry_bytes_ = 0;
|
||||
ck_bytes_ = ck_slot_bytes_ = ck_slot_off_ = 0;
|
||||
ck_store_ = nullptr;
|
||||
enabled_ = false;
|
||||
leader_ = false;
|
||||
reg_ = nullptr; kv_ = nullptr; tiers_ = nullptr; disk_ = nullptr;
|
||||
@@ -255,22 +265,20 @@ static uint64_t tier_fnv(const void* p, int64_t n) {
|
||||
return h;
|
||||
}
|
||||
|
||||
void TierExec::verify_note(const BlockHash& key, const void* p, int64_t n, bool snapshot) {
|
||||
void TierExec::verify_note(const BlockHash& key, const void* p, int64_t n) {
|
||||
if (!verify_ || !leader_ || !p || n <= 0) return;
|
||||
(snapshot ? out_ck_ : out_sum_)[key] = tier_fnv(p, n);
|
||||
out_sum_[key] = tier_fnv(p, n);
|
||||
}
|
||||
|
||||
void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n, bool snapshot) {
|
||||
void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n) {
|
||||
if (!verify_ || !leader_ || !p || n <= 0) return;
|
||||
auto& m = snapshot ? out_ck_ : out_sum_;
|
||||
auto it = m.find(key);
|
||||
if (it == m.end()) return; /* never went out through this process */
|
||||
auto it = out_sum_.find(key);
|
||||
if (it == out_sum_.end()) return; /* never went out through this process */
|
||||
const uint64_t back = tier_fnv(p, n);
|
||||
if (back == it->second) return;
|
||||
RAD_ERR("kv tiers: the %s for %s came back DIFFERENT (%016llx out, %016llx in). The tier is "
|
||||
"moving the wrong bytes, not the engine choosing differently downstream.",
|
||||
snapshot ? "linear-state snapshot" : "attention blocks", key.str().c_str(),
|
||||
(unsigned long long)it->second, (unsigned long long)back);
|
||||
RAD_ERR("kv tiers: the attention blocks for %s came back DIFFERENT (%016llx out, %016llx in). "
|
||||
"The tier is moving the wrong bytes, not the engine choosing differently downstream.",
|
||||
key.str().c_str(), (unsigned long long)it->second, (unsigned long long)back);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ helpers */
|
||||
@@ -295,7 +303,7 @@ bool TierExec::blocks_backed(const std::vector<int32_t>& blocks, const char* wha
|
||||
for (size_t k = 0; k < gi_.size(); ++k) {
|
||||
if (k >= blocks.size()) continue; /* an absent group is the gather's -1 row */
|
||||
const int32_t b = blocks[k];
|
||||
if (b < 0) continue;
|
||||
if (b < 0 || gi_[k].zero) continue;
|
||||
const int64_t live = kv_->live_blocks(gi_[k].g);
|
||||
if (b < live) continue;
|
||||
if (warned_unbacked_) return false;
|
||||
@@ -352,7 +360,7 @@ int TierExec::enqueue_copy(std::vector<TierJob>& jobs, RadStream compute) {
|
||||
if (!blocks_backed(j->blocks, "copy to host")) return RAD_E_STATE;
|
||||
|
||||
/* AFTER EVERYTHING THE COMPUTE STREAM HAS BEEN GIVEN, which includes the step that wrote these
|
||||
* blocks and the save that wrote the snapshots. A stream wait, not a host wait. */
|
||||
* blocks. A stream wait, not a host wait. */
|
||||
TIER_TRY(rad_event_record(ev_compute_, compute), "ordering the copy after the step");
|
||||
TIER_TRY(rad_event_wait(stream_, ev_compute_), "ordering the copy after the step");
|
||||
|
||||
@@ -369,7 +377,7 @@ int TierExec::enqueue_copy(std::vector<TierJob>& jobs, RadStream compute) {
|
||||
for (int64_t s = 0; s < n; s += max_batch_) {
|
||||
const int64_t c = std::min<int64_t>(max_batch_, n - s);
|
||||
for (size_t gidx = 0; gidx < gi_.size(); ++gidx)
|
||||
for (int64_t l = 0; l < gi_[gidx].n_layers; ++l)
|
||||
for (int64_t l = 0; l < gi_[gidx].n_layers && !gi_[gidx].zero; ++l)
|
||||
TIER_TRY(run_rows(gi_[gidx].gather, /*scatter=*/false, gi_[gidx], l, stage_,
|
||||
idx_dev_ + (int64_t)gidx * n + s, c),
|
||||
"the gather out of the pool");
|
||||
@@ -378,30 +386,13 @@ int TierExec::enqueue_copy(std::vector<TierJob>& jobs, RadStream compute) {
|
||||
st_.bytes_out += n * entry_bytes_;
|
||||
}
|
||||
|
||||
/* The linear half: one contiguous copy each, out of the device slot the snapshot sits in. */
|
||||
for (TierJob& j : jobs) {
|
||||
if (j.ck_host < 0 || j.ck_dev < 0 || ck_bytes_ <= 0) continue;
|
||||
if (kv_->back_checkpoint(j.ck_dev) < 0) { j.ck_ok = false; continue; }
|
||||
const void* src = kv_->checkpoint_ptr(j.ck_dev);
|
||||
char* dst = (char*)tiers_->ckpt_arena().at(j.ck_host);
|
||||
if (!src || !dst) { j.ck_ok = false; continue; }
|
||||
const int st = rad_memcpy_async(dst + ck_slot_off_, src, ck_bytes_, stream_);
|
||||
if (st != RAD_OK) {
|
||||
warn_once("the snapshot copy to host memory", st);
|
||||
j.ck_ok = false;
|
||||
continue;
|
||||
}
|
||||
st_.bytes_out += ck_bytes_;
|
||||
}
|
||||
|
||||
TIER_TRY(rad_event_record(ev_copy_, stream_), "marking the copy");
|
||||
copy_out_ = true;
|
||||
++st_.passes;
|
||||
st_.jobs += (int64_t)jobs.size();
|
||||
if (verify_)
|
||||
for (const TierJob& j : jobs)
|
||||
verify_pending_.push_back({j.key, j.blocks.empty() ? -1 : j.host_slot,
|
||||
j.ck_ok ? j.ck_host : -1});
|
||||
verify_pending_.push_back({j.key, j.blocks.empty() ? -1 : j.host_slot});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -415,10 +406,7 @@ int TierExec::copy_state() {
|
||||
for (const VerifyNote& v : verify_pending_) {
|
||||
if (v.host_slot >= 0)
|
||||
verify_note(v.key, (char*)tiers_->arena().at(v.host_slot) + slot_off_,
|
||||
entry_bytes_, false);
|
||||
if (v.ck_host >= 0)
|
||||
verify_note(v.key, (char*)tiers_->ckpt_arena().at(v.ck_host) + ck_slot_off_,
|
||||
ck_bytes_, true);
|
||||
entry_bytes_);
|
||||
}
|
||||
}
|
||||
verify_pending_.clear();
|
||||
@@ -426,8 +414,22 @@ int TierExec::copy_state() {
|
||||
return q > 0 ? 1 : q;
|
||||
}
|
||||
|
||||
int TierExec::wait_copy() {
|
||||
if (!copy_out_) return 1;
|
||||
(void)rad_dev_set(device_);
|
||||
const int st = rad_event_sync(ev_copy_);
|
||||
if (st != RAD_OK) warn_once("waiting for the copy to host memory", st);
|
||||
return copy_state();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ restore */
|
||||
|
||||
void TierExec::quiesce() {
|
||||
if (!enabled_ || !stream_) return;
|
||||
if (rad_dev_set(device_) < 0) return;
|
||||
(void)rad_stream_sync(stream_);
|
||||
}
|
||||
|
||||
int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
std::vector<char>* ok) {
|
||||
ok->assign(jobs.size(), 0);
|
||||
@@ -486,7 +488,7 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
for (size_t i = 0; i < m; ++i) order_.push_back(&jobs[i]);
|
||||
for (size_t i = 0; i < m; ++i)
|
||||
verify_check(jobs[i].key, (char*)tiers_->arena().at(jobs[i].host_slot) + slot_off_,
|
||||
entry_bytes_, false);
|
||||
entry_bytes_);
|
||||
|
||||
/* FROM HERE ON A FAILURE LEAVES A MIXTURE, so every job about to be written is marked started
|
||||
* first -- report() drops a started job that failed rather than trusting its host copy to
|
||||
@@ -513,7 +515,7 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
const int64_t cc = std::min<int64_t>(max_batch_, c - b);
|
||||
if ((st = copy_runs(order_, s + (size_t)b, cc, /*out=*/false)) != RAD_OK) break;
|
||||
for (size_t gidx = 0; gidx < ng && st == RAD_OK; ++gidx)
|
||||
for (int64_t l = 0; l < gi_[gidx].n_layers && st == RAD_OK; ++l)
|
||||
for (int64_t l = 0; l < gi_[gidx].n_layers && st == RAD_OK && !gi_[gidx].zero; ++l)
|
||||
st = run_rows(gi_[gidx].scatter, /*scatter=*/true, gi_[gidx], l, stage_,
|
||||
d + (int64_t)gidx * c + b, cc);
|
||||
}
|
||||
@@ -523,45 +525,6 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
for (size_t i = 0; i < done; ++i) (*ok)[i] = 1;
|
||||
st_.bytes_in += (int64_t)done * entry_bytes_;
|
||||
|
||||
/* THE LINEAR HALF, into a slot the leader allocates. The same rule as the blocks: the id is
|
||||
* rank 0's to choose, and a follower takes the id it is handed and backs its own pages. A
|
||||
* snapshot that cannot be placed is not a failure of the restore -- the session keeps its
|
||||
* attention hit and replays its linear layers, which is what it would have done with no
|
||||
* tiers at all.
|
||||
*
|
||||
* THE DEEPEST ONE IS WORTH A SLOT SOMEBODY ELSE HAS. A hit resumes from the last checkpoint at
|
||||
* or below its attention hit, which on a restored chain is the chain's last snapshot; the
|
||||
* earlier ones take a slot only where one is free. A full pool is then made room in for that
|
||||
* one snapshot by detaching another session's, which that session's own next restore brings
|
||||
* back -- rather than for every snapshot on the chain, which would push out as many other
|
||||
* sessions' states as this one has checkpoints. */
|
||||
size_t deepest = done;
|
||||
for (size_t i = 0; i < done; ++i)
|
||||
if (jobs[i].ck_want && jobs[i].ck_ok && jobs[i].ck_host >= 0) deepest = i;
|
||||
for (size_t i = 0; i < done; ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
if (!j.ck_want || !j.ck_ok || j.ck_host < 0 || ck_bytes_ <= 0) continue;
|
||||
if (leader_) {
|
||||
int32_t slot = -1;
|
||||
if (kv_->alloc_checkpoint(&slot) != RAD_OK || slot < 0) {
|
||||
slot = -1;
|
||||
if (i != deepest || !ck_room_ || !ck_room_() ||
|
||||
kv_->alloc_checkpoint(&slot) != RAD_OK || slot < 0)
|
||||
continue;
|
||||
}
|
||||
j.ck_dev = slot;
|
||||
}
|
||||
if (j.ck_dev < 0) continue;
|
||||
if (kv_->back_checkpoint(j.ck_dev) < 0) { j.ck_ok = false; continue; }
|
||||
const char* src = (const char*)tiers_->ckpt_arena().at(j.ck_host);
|
||||
void* dst = kv_->checkpoint_ptr(j.ck_dev);
|
||||
if (!src || !dst) { j.ck_ok = false; continue; }
|
||||
verify_check(j.key, src + ck_slot_off_, ck_bytes_, true);
|
||||
const int cs = rad_memcpy_async(dst, src + ck_slot_off_, ck_bytes_, stream_);
|
||||
if (cs != RAD_OK) { warn_once("the snapshot copy back into the pool", cs); j.ck_ok = false; continue; }
|
||||
st_.bytes_in += ck_bytes_;
|
||||
}
|
||||
|
||||
/* THE STEP THAT READS THESE WAITS FOR THEM, on the device. If even the marker cannot be
|
||||
* enqueued the only ordering left is the host's. */
|
||||
if (rad_event_record(ev_restore_, stream_) != RAD_OK ||
|
||||
@@ -573,13 +536,13 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
return st;
|
||||
}
|
||||
|
||||
int TierExec::fence(RadEvent* out) {
|
||||
int TierExec::fence(RadEvent* out, RadStream on) {
|
||||
*out = nullptr;
|
||||
if (!enabled_ || !stream_) return RAD_OK;
|
||||
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, stream_);
|
||||
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;
|
||||
@@ -602,12 +565,13 @@ bool TierExec::run_write(TierJob& j) {
|
||||
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_host >= 0) {
|
||||
const void* cs = tiers_->ckpt_arena().at(j.ck_host);
|
||||
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 host copy stays the only one, as
|
||||
* it was. */
|
||||
j.ck_ok = disk_ && cs && disk_->put_checkpoint(j.key, j.ck_pos, cs, ck_slot_bytes_) == RAD_OK;
|
||||
* 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;
|
||||
}
|
||||
@@ -633,9 +597,10 @@ void TierExec::run_fetch(std::vector<TierJob>& jobs, std::vector<char>* ok) {
|
||||
st_.bytes_in += (int64_t)keys.size() * slot_bytes_;
|
||||
}
|
||||
for (TierJob& j : jobs) {
|
||||
if (j.ck_host < 0) continue;
|
||||
void* cs = tiers_->ckpt_arena().at(j.ck_host);
|
||||
j.ck_ok = disk_ && cs && disk_->get_checkpoint(j.key, j.ck_pos, cs, ck_slot_bytes_) == RAD_OK;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -644,28 +609,23 @@ void TierExec::run_fetch(std::vector<TierJob>& jobs, std::vector<char>* ok) {
|
||||
void TierExec::report_pass(std::vector<TierJob>& jobs, const std::vector<char>& ok,
|
||||
uint64_t now_ns) {
|
||||
if (!enabled_ || !leader_) return;
|
||||
bool quiet = false;
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
const bool good = i < ok.size() && ok[i];
|
||||
/* A SNAPSHOT IS RESTORED ONLY IF EVERY RANK RESTORED ITS SHARD, and the leader is the only
|
||||
* one that can act on that. It allocates the checkpoint slot and fills its own window
|
||||
* first, so a follower that then fails leaves the slot holding this rank's new state beside
|
||||
* another rank's stale state -- a checkpoint the cache would go on to serve, one card
|
||||
* resuming the conversation and the other resuming whatever it last held.
|
||||
*
|
||||
* A PROMOTION THAT FAILED AS A WHOLE gives back everything the leader took for it: report()
|
||||
* drops or keeps the record, and nothing will ever name these blocks or this slot again. */
|
||||
if (j.kind == TierJob::Kind::ToDevice && j.ck_dev >= 0 && (!j.ck_ok || !good)) {
|
||||
kv_->free_checkpoint(j.ck_dev);
|
||||
j.ck_dev = -1;
|
||||
}
|
||||
/* A PROMOTION THAT FAILED AS A WHOLE gives back the blocks the leader took for it, once
|
||||
* nothing queued against them can still land: report() drops or keeps the record, and
|
||||
* nothing will ever name these blocks again. */
|
||||
if (j.kind == TierJob::Kind::ToDevice && !good) {
|
||||
if (!quiet) { quiesce(); quiet = true; }
|
||||
for (size_t k = 0; k < gi_.size() && k < j.blocks.size(); ++k)
|
||||
if (j.blocks[k] >= 0) kv_->release_block(gi_[k].g, j.blocks[k]);
|
||||
j.blocks.clear();
|
||||
}
|
||||
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);
|
||||
@@ -703,11 +663,12 @@ void TierIO::stop() {
|
||||
fetch_done_.clear();
|
||||
}
|
||||
|
||||
bool TierIO::submit(std::vector<TierJob>&& jobs) {
|
||||
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;
|
||||
@@ -734,12 +695,15 @@ bool TierIO::take_fetch(Fetch* out) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TierIO::take(std::vector<TierJob>* jobs, std::vector<char>* ok) {
|
||||
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;
|
||||
@@ -778,14 +742,26 @@ void TierIO::loop() {
|
||||
fetch_done_.push_back(std::move(f));
|
||||
continue;
|
||||
}
|
||||
/* One write at a time, so a read that arrives behind a long batch waits for one job. */
|
||||
const bool ok = i < work_.size() ? x_->run_write(work_[i]) : true;
|
||||
/* 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 (i < ok_.size()) ok_[i] = ok ? 1 : 0;
|
||||
work_at_ = i + 1;
|
||||
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;
|
||||
}
|
||||
|
||||
+41
-32
@@ -71,7 +71,7 @@ public:
|
||||
int configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk,
|
||||
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,
|
||||
int64_t ck_slot_off, RadStream shared);
|
||||
const HostArena* ck_store, RadStream shared);
|
||||
void close();
|
||||
bool enabled() const { return enabled_; }
|
||||
std::string report() const { return report_; }
|
||||
@@ -105,6 +105,13 @@ public:
|
||||
* the transfer stream reported an error. Taking the answer clears it. */
|
||||
int copy_state();
|
||||
bool copy_out() const { return copy_out_; }
|
||||
/* copy_state, after waiting for the batch to land. For a caller that cannot go on until the
|
||||
* copy has a host slot to show for it -- an eviction that would otherwise lose the entry. */
|
||||
int wait_copy();
|
||||
/* EVERYTHING THIS RANK ENQUEUED HAS LANDED. For a block given back on a failure path while a
|
||||
* copy into it may still be in flight: the pool would hand it to a sequence whose writes the
|
||||
* late copy then overwrites. */
|
||||
void quiesce();
|
||||
|
||||
/* ---------------- restore ----------------
|
||||
*
|
||||
@@ -115,36 +122,33 @@ public:
|
||||
* 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. 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. Null when nothing was ever enqueued here. The
|
||||
/* 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);
|
||||
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. `ok[i]` is the blocks' result, `ck_ok` the snapshot's. */
|
||||
* 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 and checkpoint slot --
|
||||
* reports every job to the policy, and frees the device checkpoint slots a finished copy 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 -- 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. */
|
||||
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
|
||||
* off-device or already has work outstanding. */
|
||||
bool plan_promote(const BlockHash& key, TierJob* out); /* leader only */
|
||||
|
||||
/* Leader only: how a restore gets a device checkpoint slot when the pool is full. The cache
|
||||
* owns the policy for which snapshot gives its slot up (PrefixCache::free_checkpoint_for_restore);
|
||||
* this object only knows it needs one. True when a slot was freed. */
|
||||
void set_checkpoint_room(std::function<bool()> f) { ck_room_ = std::move(f); }
|
||||
|
||||
struct Stats { int64_t passes = 0, jobs = 0, bytes_out = 0, bytes_in = 0; };
|
||||
const Stats& stats() const { return st_; }
|
||||
|
||||
@@ -157,6 +161,10 @@ private:
|
||||
int64_t n_blocks = 0;
|
||||
void* base = nullptr;
|
||||
int64_t off = 0; /* this group's start inside one entry's staging bytes */
|
||||
/* rad_kv_group_zero: no shard on this rank. Kept in its place, because a job's block ids
|
||||
* are one per cached group in the same order on every rank; nothing is gathered or
|
||||
* scattered for it and it is no part of this rank's entry. */
|
||||
bool zero = false;
|
||||
Resolved gather, scatter;
|
||||
};
|
||||
|
||||
@@ -202,16 +210,13 @@ private:
|
||||
KVManager* kv_ = nullptr;
|
||||
IdleTiers* tiers_ = nullptr;
|
||||
SSDTier* disk_ = nullptr;
|
||||
std::function<bool()> ck_room_;
|
||||
std::vector<GroupInfo> gi_;
|
||||
int64_t entry_bytes_ = 0;
|
||||
/* ---- the linear half ----
|
||||
* `ck_bytes_` is THIS RANK's shard of one snapshot and `ck_slot_bytes_` the whole shared slot,
|
||||
* exactly as entry_bytes_ and slot_bytes_ are for blocks. Zero on a model with no recurrent
|
||||
* state, which is the whole of the "off" path here. */
|
||||
int64_t ck_bytes_ = 0;
|
||||
int64_t ck_slot_bytes_ = 0;
|
||||
int64_t ck_slot_off_ = 0;
|
||||
* 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;
|
||||
@@ -254,17 +259,17 @@ private:
|
||||
* the only question worth asking first: is the tier moving the wrong bytes, or is it moving
|
||||
* the right ones and something downstream is choosing differently?
|
||||
*
|
||||
* A DIAGNOSTIC, NOT A GUARD. It hashes on the host, which for a snapshot is tens of
|
||||
* milliseconds an entry -- affordable when a run is being bisected and not otherwise. Off
|
||||
* A DIAGNOSTIC, NOT A GUARD. It hashes on the host, which is a cost on every entry --
|
||||
* affordable when a run is being bisected and not otherwise. Off
|
||||
* unless the variable is set, and leader-only, because the map is keyed by an object the
|
||||
* followers do not own. A copy out is hashed when it has LANDED, which is when copy_state
|
||||
* first sees it done. */
|
||||
bool verify_ = false;
|
||||
std::unordered_map<BlockHash, uint64_t, BlockHashHash> out_sum_, out_ck_;
|
||||
struct VerifyNote { BlockHash key; int32_t host_slot = -1; int32_t ck_host = -1; };
|
||||
std::unordered_map<BlockHash, uint64_t, BlockHashHash> out_sum_;
|
||||
struct VerifyNote { BlockHash key; int32_t host_slot = -1; };
|
||||
std::vector<VerifyNote> verify_pending_;
|
||||
void verify_note(const BlockHash& key, const void* p, int64_t n, bool snapshot);
|
||||
void verify_check(const BlockHash& key, const void* p, int64_t n, bool snapshot);
|
||||
void verify_note(const BlockHash& key, const void* p, int64_t n);
|
||||
void verify_check(const BlockHash& key, const void* p, int64_t n);
|
||||
|
||||
std::string report_;
|
||||
Stats st_;
|
||||
@@ -288,10 +293,13 @@ public:
|
||||
~TierIO();
|
||||
void start(TierExec* leader);
|
||||
void stop();
|
||||
/* False when a batch is already out. */
|
||||
bool submit(std::vector<TierJob>&& jobs);
|
||||
/* 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);
|
||||
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
|
||||
@@ -314,6 +322,7 @@ private:
|
||||
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;
|
||||
|
||||
+129
-42
@@ -83,9 +83,17 @@ std::pair<uint32_t, const char*> decode_utf8(const char* src) {
|
||||
|
||||
std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src,
|
||||
PartialUtf8 partial_start) {
|
||||
std::vector<uint32_t> cps;
|
||||
const PartialUtf8 p = decode_utf8(src, partial_start, &cps);
|
||||
return { std::move(cps), p };
|
||||
}
|
||||
|
||||
PartialUtf8 decode_utf8(const std::string& src, PartialUtf8 partial_start,
|
||||
std::vector<uint32_t>* out) {
|
||||
static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
|
||||
const char* pos = src.c_str();
|
||||
std::vector<uint32_t> cps;
|
||||
std::vector<uint32_t>& cps = *out;
|
||||
cps.clear();
|
||||
cps.reserve(src.size() + 1);
|
||||
|
||||
uint32_t value = partial_start.value;
|
||||
@@ -95,7 +103,7 @@ std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src
|
||||
const uint8_t next_byte = (uint8_t)*pos;
|
||||
if ((next_byte >> 6) != 2) {
|
||||
cps.push_back(0);
|
||||
return { std::move(cps), PartialUtf8{ 0, -1 } };
|
||||
return PartialUtf8{ 0, -1 };
|
||||
}
|
||||
value = (value << 6) + (next_byte & 0x3F);
|
||||
++pos;
|
||||
@@ -110,7 +118,7 @@ std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src
|
||||
if (n_remain < 0) {
|
||||
cps.clear();
|
||||
cps.push_back(0);
|
||||
return { std::move(cps), PartialUtf8{ 0, n_remain } };
|
||||
return PartialUtf8{ 0, n_remain };
|
||||
}
|
||||
const uint8_t mask = (uint8_t)((1 << (7 - n_remain)) - 1);
|
||||
value = first_byte & mask;
|
||||
@@ -123,7 +131,7 @@ std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src
|
||||
if (n_remain == 0) cps.push_back(value);
|
||||
}
|
||||
cps.push_back(0);
|
||||
return { std::move(cps), PartialUtf8{ value, n_remain } };
|
||||
return PartialUtf8{ value, n_remain };
|
||||
}
|
||||
|
||||
} /* namespace gbnf */
|
||||
@@ -830,22 +838,73 @@ struct GbnfState {
|
||||
}
|
||||
};
|
||||
|
||||
/* A STATE AS fill_mask HOLDS IT, NOT COPIED: the stacks through pointers, in the order the key
|
||||
* sorts them into. It hashes and compares as the GbnfState it would become, so the cache is
|
||||
* probed without building a key -- a copy of every stack, per mask -- and one is built only for a
|
||||
* mask that is stored. */
|
||||
struct GbnfStateView {
|
||||
const std::vector<const GbnfStack*>* stacks;
|
||||
PartialUtf8 partial;
|
||||
bool allow_eog;
|
||||
int64_t words;
|
||||
};
|
||||
|
||||
struct GbnfStateHash {
|
||||
size_t operator()(const GbnfState& k) const {
|
||||
using is_transparent = void;
|
||||
|
||||
template <class Stacks, class Deref>
|
||||
static size_t hash(const Stacks& stacks, Deref deref, PartialUtf8 partial, bool allow_eog,
|
||||
int64_t words) {
|
||||
size_t h = 1469598103934665603ull;
|
||||
auto mix = [&h](size_t v) { h ^= v; h *= 1099511628211ull; };
|
||||
for (const GbnfStack& s : k.stacks) {
|
||||
for (const auto& x : stacks) {
|
||||
const GbnfStack& s = deref(x);
|
||||
mix(s.size());
|
||||
for (const GbnfElement* e : s) mix((size_t)e);
|
||||
}
|
||||
mix(k.partial.value);
|
||||
mix((size_t)(k.partial.n_remain + 1));
|
||||
mix(k.allow_eog ? 1u : 0u);
|
||||
mix((size_t)k.words);
|
||||
mix(partial.value);
|
||||
mix((size_t)(partial.n_remain + 1));
|
||||
mix(allow_eog ? 1u : 0u);
|
||||
mix((size_t)words);
|
||||
return h;
|
||||
}
|
||||
size_t operator()(const GbnfState& k) const {
|
||||
return hash(k.stacks, [](const GbnfStack& s) -> const GbnfStack& { return s; },
|
||||
k.partial, k.allow_eog, k.words);
|
||||
}
|
||||
size_t operator()(const GbnfStateView& k) const {
|
||||
return hash(*k.stacks, [](const GbnfStack* s) -> const GbnfStack& { return *s; },
|
||||
k.partial, k.allow_eog, k.words);
|
||||
}
|
||||
};
|
||||
|
||||
struct GbnfStateEq {
|
||||
using is_transparent = void;
|
||||
|
||||
bool operator()(const GbnfState& a, const GbnfState& b) const { return a == b; }
|
||||
bool operator()(const GbnfStateView& v, const GbnfState& k) const {
|
||||
if (k.allow_eog != v.allow_eog || k.words != v.words ||
|
||||
k.partial.value != v.partial.value || k.partial.n_remain != v.partial.n_remain ||
|
||||
k.stacks.size() != v.stacks->size())
|
||||
return false;
|
||||
for (size_t i = 0; i < k.stacks.size(); ++i)
|
||||
if (k.stacks[i] != *(*v.stacks)[i]) return false;
|
||||
return true;
|
||||
}
|
||||
bool operator()(const GbnfState& k, const GbnfStateView& v) const { return (*this)(v, k); }
|
||||
};
|
||||
|
||||
/* The key a view becomes, for storing. */
|
||||
static GbnfState state_of(const GbnfStateView& v) {
|
||||
GbnfState k;
|
||||
k.stacks.reserve(v.stacks->size());
|
||||
for (const GbnfStack* s : *v.stacks) k.stacks.push_back(*s);
|
||||
k.partial = v.partial;
|
||||
k.allow_eog = v.allow_eog;
|
||||
k.words = v.words;
|
||||
return k;
|
||||
}
|
||||
|
||||
struct GbnfProgram {
|
||||
GbnfRuleSet rules;
|
||||
GbnfStacks start; /* the root's alternates, advanced once */
|
||||
@@ -864,7 +923,7 @@ struct GbnfProgram {
|
||||
* speculative window revisiting a state the work again. */
|
||||
mutable std::mutex mu;
|
||||
struct Entry { std::vector<uint32_t> mask; uint64_t used = 0; };
|
||||
mutable std::unordered_map<GbnfState, Entry, GbnfStateHash> masks;
|
||||
mutable std::unordered_map<GbnfState, Entry, GbnfStateHash, GbnfStateEq> masks;
|
||||
mutable uint64_t clock = 0;
|
||||
|
||||
/* A tool-calling schema's working set is on the order of a hundred states; 512 is room for a
|
||||
@@ -873,7 +932,7 @@ struct GbnfProgram {
|
||||
* that was computed. */
|
||||
static constexpr size_t kMaxMasks = 512;
|
||||
|
||||
bool lookup(const GbnfState& k, uint32_t* dst, int64_t n_words) const {
|
||||
bool lookup(const GbnfStateView& k, uint32_t* dst, int64_t n_words) const {
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
auto it = masks.find(k);
|
||||
if (it == masks.end()) return false;
|
||||
@@ -1157,29 +1216,42 @@ int GbnfGrammar::accept_token_piece(int32_t token, const std::string& piece) {
|
||||
RAD_WARN("gbnf: token %d cannot be accepted: %s; the request cannot be continued",
|
||||
token, e.what());
|
||||
stacks_.clear();
|
||||
at_ = At{};
|
||||
return RAD_E_FULL;
|
||||
} catch (const std::bad_alloc&) {
|
||||
RAD_ERR("gbnf: out of memory accepting token %d; the request cannot be continued", token);
|
||||
stacks_.clear();
|
||||
at_ = At{};
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
}
|
||||
|
||||
int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece) {
|
||||
const auto decoded = decode_utf8(piece, partial_utf8_);
|
||||
const auto& cps = decoded.first;
|
||||
const PartialUtf8 partial = decode_utf8(piece, partial_utf8_, &cps_);
|
||||
const size_t n_cps = cps_.size() - 1; /* the terminating 0 is not a code point */
|
||||
|
||||
OpWork work;
|
||||
GbnfStacks new_stacks;
|
||||
SetBuild new_set(work);
|
||||
new_stacks.reserve(stacks_.size());
|
||||
|
||||
/* THE STACKS THAT MATCH CODE POINTS ARE ADVANCED TOGETHER, one code point at a time, as
|
||||
* accept_str does. Advancing each through the whole piece on its own gives the same set --
|
||||
* the union of the parts is the part of the union -- but when many stacks converge on one
|
||||
* continuation, as every alternative of a wide rule does once it matches, each of them
|
||||
* re-expands that continuation, and the token costs the square of the width. */
|
||||
GbnfStacks current;
|
||||
* re-expands that continuation, and the token costs the square of the width.
|
||||
*
|
||||
* AND THEY ARE ADVANCED THROUGH THE MASK PLAN'S AUTOMATON (plan_step), which holds each stack
|
||||
* set as a state with its successors memoised per interval of code points. The set is the
|
||||
* one accept_chr builds; what changes is that a state seen before -- the same free-text
|
||||
* value, token after token -- is a lookup per code point rather than every closure rebuilt,
|
||||
* allocated and de-duplicated again. The set comes back sorted, which nothing reads: the
|
||||
* mask cache sorts its key, and a mask is a union over the stacks.
|
||||
*
|
||||
* The new set is written over the one the previous token left (`spare_`) and the two are
|
||||
* swapped, so a set of the same shape, token after token, allocates nothing; and when the
|
||||
* automaton says the token left the set the state it was -- the steady state of a free-text
|
||||
* value -- the set is not touched at all. */
|
||||
current_.clear();
|
||||
for (const auto& stack : stacks_) {
|
||||
if (stack.empty()) continue;
|
||||
const GbnfElement* pos = stack.back();
|
||||
@@ -1190,19 +1262,37 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece
|
||||
if (!is_end_of_sequence(pos + 1)) next.push_back(pos + 1);
|
||||
advance_stack(prog_->rules, next, new_stacks, new_set);
|
||||
} else {
|
||||
current.push_back(stack);
|
||||
current_.push_back(&stack);
|
||||
}
|
||||
}
|
||||
for (auto it = cps.begin(), end = cps.end() - 1; it != end && !current.empty(); ++it) {
|
||||
GbnfStacks next;
|
||||
SetBuild next_set(work);
|
||||
for (const auto& cs : current) accept_chr(prog_->rules, cs, *it, next, next_set);
|
||||
current = std::move(next);
|
||||
GbnfStacks& out = spare_;
|
||||
if (n_cps > 0 && !current_.empty()) {
|
||||
/* `at_` names a state only when every stack steps over code points, so with it known no
|
||||
* stack matched a token terminal above and the set is the stepped stacks alone. */
|
||||
gbnf::PlanState at{ at_.gen, at_.id };
|
||||
const bool same = gbnf::plan_step(*prog_->plan, current_, &at, cps_.data(), n_cps, &out,
|
||||
work);
|
||||
at_ = At{ at.gen, at.id };
|
||||
if (same) {
|
||||
partial_utf8_ = partial;
|
||||
return RAD_OK;
|
||||
}
|
||||
} else {
|
||||
out.resize(current_.size());
|
||||
for (size_t i = 0; i < current_.size(); ++i) out[i].assign(current_[i]->begin(),
|
||||
current_[i]->end());
|
||||
at_ = At{};
|
||||
}
|
||||
for (auto& s : current) new_set.insert(new_stacks, std::move(s));
|
||||
|
||||
stacks_ = std::move(new_stacks);
|
||||
partial_utf8_ = decoded.second;
|
||||
/* What a token terminal matched goes first, then the rest without the ones it already holds;
|
||||
* with nothing matched by token, `out` is the set as it stands -- a state of the automaton,
|
||||
* or a subset of the set before, and either way without duplicates. */
|
||||
if (!new_stacks.empty()) {
|
||||
for (auto& s : out) new_set.insert(new_stacks, std::move(s));
|
||||
out.swap(new_stacks);
|
||||
at_ = At{};
|
||||
}
|
||||
stacks_.swap(out);
|
||||
partial_utf8_ = partial;
|
||||
|
||||
if (stacks_.empty()) {
|
||||
/* NOT AN ERROR HERE, WHICH IS WHY IT LOGS AT DEBUG. This is reached as a matter of course
|
||||
@@ -1290,6 +1380,7 @@ int GbnfGrammar::accept_token(int32_t token) {
|
||||
int GbnfGrammar::accept_str(const std::string& piece) {
|
||||
const auto decoded = decode_utf8(piece, partial_utf8_);
|
||||
const auto& cps = decoded.first;
|
||||
at_ = At{};
|
||||
|
||||
try {
|
||||
OpWork work;
|
||||
@@ -1318,7 +1409,7 @@ int GbnfGrammar::accept_str(const std::string& piece) {
|
||||
|
||||
|
||||
void GbnfGrammar::push_state() {
|
||||
saved_.push_back(Snapshot{ stacks_, partial_utf8_, awaiting_trigger_, scan_, recent_ });
|
||||
saved_.push_back(Snapshot{ stacks_, partial_utf8_, awaiting_trigger_, scan_, recent_, at_ });
|
||||
}
|
||||
|
||||
int GbnfGrammar::rollback() {
|
||||
@@ -1332,21 +1423,11 @@ int GbnfGrammar::rollback() {
|
||||
awaiting_trigger_ = s.awaiting_trigger;
|
||||
scan_ = s.scan;
|
||||
recent_ = std::move(s.recent);
|
||||
at_ = s.at;
|
||||
saved_.pop_back();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The cache key for the state the machine is in right now. */
|
||||
GbnfState GbnfGrammar::state_key(bool allow_eog, int64_t n_words) const {
|
||||
GbnfState k;
|
||||
k.stacks = stacks_;
|
||||
k.partial = partial_utf8_;
|
||||
k.allow_eog = allow_eog;
|
||||
k.words = n_words;
|
||||
std::sort(k.stacks.begin(), k.stacks.end());
|
||||
return k;
|
||||
}
|
||||
|
||||
/* The mask for the current state, with no memo. */
|
||||
int GbnfGrammar::mask_compute(uint32_t* bitmask, int64_t n_words) const {
|
||||
std::fill(bitmask, bitmask + n_words, 0u);
|
||||
@@ -1391,8 +1472,14 @@ int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const {
|
||||
* because a collision accepted on the hash alone would hand back a mask for a state the
|
||||
* sequence is not in and admit the wrong token set. The key sorts the stacks: two requests
|
||||
* that reach the same state by the same path produce the same order anyway, but the sort is
|
||||
* what makes that a guarantee rather than an observation. */
|
||||
const GbnfState key = state_key(complete(), n_words);
|
||||
* what makes that a guarantee rather than an observation. The probe sorts pointers to the
|
||||
* stacks, in storage of the calling thread's own, and copies them only to store. */
|
||||
thread_local std::vector<const GbnfStack*> sorted;
|
||||
sorted.clear();
|
||||
for (const GbnfStack& s : stacks_) sorted.push_back(&s);
|
||||
std::sort(sorted.begin(), sorted.end(),
|
||||
[](const GbnfStack* a, const GbnfStack* b) { return *a < *b; });
|
||||
const GbnfStateView key{ &sorted, partial_utf8_, complete(), n_words };
|
||||
if (prog_->lookup(key, bitmask, n_words)) return RAD_OK;
|
||||
|
||||
prog_->computed.fetch_add(1, std::memory_order_relaxed);
|
||||
@@ -1400,7 +1487,7 @@ int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const {
|
||||
if (st < 0) return st;
|
||||
|
||||
/* Store only a mask that stands: a dead state is not worth an entry and returns above. */
|
||||
prog_->store(key, bitmask, n_words);
|
||||
prog_->store(state_of(key), bitmask, n_words);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
+24
-2
@@ -32,6 +32,11 @@
|
||||
* stacks that match code points are advanced together rather than one at a time, and a
|
||||
* large set is de-duplicated through an index. Each gives the same set as upstream; without
|
||||
* them, stacks that converge on one continuation re-expand it once each.
|
||||
* - Accepting a token steps the stacks that match code points through the mask plan's
|
||||
* stack-set automaton (gbnf_mask.cpp, plan_step) rather than through a closure per stack per
|
||||
* code point, and the grammar remembers which automaton state its stacks are. The set is the
|
||||
* one upstream's accept builds; the test oracle keeps upstream's accept and every accepted
|
||||
* token is held to it.
|
||||
* - The token mask is not upstream's candidate walk. It is served from a plan precomputed when
|
||||
* the grammar is compiled (gbnf_mask.cpp): per stack suffix, the tokens it admits whatever lies
|
||||
* below it, and a small trie of what depends on what does. Upstream's walk survives only as
|
||||
@@ -239,12 +244,23 @@ private:
|
||||
uint64_t start;
|
||||
};
|
||||
|
||||
/* The state of the mask plan's automaton `stacks_` is exactly, when it is one: which
|
||||
* automaton (`gen`) and which state in it, or an id of -1 when that is not known. It lets
|
||||
* accepting skip canonicalising the set, and skip rewriting it when a token leaves it where
|
||||
* it was. Everything that sets `stacks_` other than accepting through the automaton resets
|
||||
* it, or restores it with the stacks it describes. */
|
||||
struct At {
|
||||
uint64_t gen = 0;
|
||||
int32_t id = -1;
|
||||
};
|
||||
|
||||
struct Snapshot {
|
||||
GbnfStacks stacks;
|
||||
PartialUtf8 partial;
|
||||
bool awaiting_trigger = false;
|
||||
WordScanner::State scan;
|
||||
std::vector<Recent> recent;
|
||||
At at;
|
||||
};
|
||||
|
||||
const VocabView* vocab_ = nullptr;
|
||||
@@ -256,11 +272,10 @@ private:
|
||||
std::shared_ptr<const GbnfProgram> prog_;
|
||||
GbnfStacks stacks_;
|
||||
PartialUtf8 partial_utf8_{};
|
||||
At at_;
|
||||
|
||||
std::vector<Snapshot> saved_;
|
||||
|
||||
GbnfState state_key(bool allow_eog, int64_t n_words) const;
|
||||
|
||||
/* The mask itself, from the program's plan, with no memo. */
|
||||
int mask_compute(uint32_t* bitmask, int64_t n_words) const;
|
||||
|
||||
@@ -278,6 +293,13 @@ private:
|
||||
|
||||
int accept_token_piece(int32_t token, const std::string& piece);
|
||||
int accept_token_piece_impl(int32_t token, const std::string& piece);
|
||||
|
||||
/* Scratch for accepting, kept so a token in the steady state of a value allocates nothing:
|
||||
* the piece's code points, the stacks that step over them, and the set before the last one
|
||||
* accepted, whose storage the next one is written into. None of it is state. */
|
||||
std::vector<uint32_t> cps_;
|
||||
std::vector<const GbnfStack*> current_;
|
||||
GbnfStacks spare_;
|
||||
};
|
||||
|
||||
/* COMPILE A GRAMMAR, on the calling thread, into the program every GbnfGrammar::create for the
|
||||
|
||||
@@ -183,6 +183,10 @@ std::pair<uint32_t, const char*> decode_utf8(const char* src);
|
||||
std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src,
|
||||
PartialUtf8 partial_start);
|
||||
|
||||
/* The same into `out`, whose capacity is reused; returns the carried state. */
|
||||
PartialUtf8 decode_utf8(const std::string& src, PartialUtf8 partial_start,
|
||||
std::vector<uint32_t>* out);
|
||||
|
||||
/* ============================================================ elements */
|
||||
|
||||
inline bool is_end_of_sequence(const GbnfElement* pos) {
|
||||
@@ -331,5 +335,30 @@ int plan_build(const GbnfRuleSet& rules, uint32_t root, const std::shared_ptr<co
|
||||
int plan_fill(const MaskPlan& plan, const GbnfStacks& stacks, PartialUtf8 partial, bool allow_eog,
|
||||
uint32_t* bitmask, int64_t n_words);
|
||||
|
||||
/* STEP A STACK SET OVER CODE POINTS through the plan's automaton: `out` is the set accepting
|
||||
* cps[0..n) one at a time leaves -- what accept_chr over every stack, code point by code point,
|
||||
* builds -- sorted, without duplicates, written over what `out` held so its capacity is reused.
|
||||
* `stacks` need not be sorted and must not point into `out`.
|
||||
*
|
||||
* `at` IS THE STATE THE CALLER'S SET IS, when it knows: on entry, a state an earlier step on this
|
||||
* plan returned, which spares canonicalising the set, or an id of -1; on return, the state
|
||||
* reached, or an id of -1 when that state holds an empty stack or a token terminal on top -- a
|
||||
* set the caller does not step whole, so not one it can name next time. Valid only while the
|
||||
* automaton that issued it lives; `gen` says which one that was. Returns true when the state
|
||||
* reached is the one `at` named on entry: the caller's set already is it, and `out` is left
|
||||
* alone. That is the steady state of a free-text value.
|
||||
*
|
||||
* The automaton memoises each state's successor per
|
||||
* interval of code points, so a state seen before costs a lookup per code point where the stack
|
||||
* machinery would rebuild every closure; inside a free-text value the state is the same one
|
||||
* token after token. Throws GbnfLimit past the per-operation bounds. Thread-safe: it takes the
|
||||
* plan's lock. */
|
||||
struct PlanState {
|
||||
uint64_t gen = 0;
|
||||
int32_t id = -1;
|
||||
};
|
||||
bool plan_step(const MaskPlan& plan, const std::vector<const GbnfStack*>& stacks, PlanState* at,
|
||||
const uint32_t* cps, size_t n, GbnfStacks* out, OpWork& work);
|
||||
|
||||
} /* namespace gbnf */
|
||||
} /* namespace rad */
|
||||
+75
-11
@@ -909,6 +909,8 @@ struct MaskPlan {
|
||||
struct Group { int32_t key; std::vector<int32_t> ctx; };
|
||||
mutable std::vector<Group> groups;
|
||||
mutable GbnfStack ctx;
|
||||
mutable std::vector<const GbnfStack*> step_ptrs;
|
||||
mutable uint64_t dfa_gen = 0; /* which automaton `dfa` is; see plan_step */
|
||||
};
|
||||
|
||||
void MaskPlanDeleter::operator()(MaskPlan* p) const { delete p; }
|
||||
@@ -1841,23 +1843,85 @@ static void fill_resume(const MaskPlan& P, SetDfa& dfa, const GbnfStacks& stacks
|
||||
}
|
||||
}
|
||||
|
||||
/* The plan's automaton, for one operation charged to `work`. The caller holds P.mu.
|
||||
*
|
||||
* The automaton is a memo, so past its bound it is dropped and rebuilt rather than refused: every
|
||||
* state in it can be rediscovered, and a grammar whose stacks deepen with every token would
|
||||
* otherwise hold a new state per token for as long as it is cached. */
|
||||
static SetDfa& plan_dfa(const MaskPlan& P, OpWork& work) {
|
||||
if (!P.dfa || P.dfa->elems() > kMaxDfaElems) {
|
||||
if (P.dfa)
|
||||
RAD_DEBUG("gbnf: the stack-set automaton holds %zu states, %zu stack elements; "
|
||||
"rebuilding it", P.dfa->n_states(), P.dfa->elems());
|
||||
P.dfa = std::make_unique<SetDfa>(P.rules);
|
||||
++P.dfa_gen;
|
||||
}
|
||||
P.dfa->begin(&work);
|
||||
return *P.dfa;
|
||||
}
|
||||
|
||||
bool plan_step(const MaskPlan& P, const std::vector<const GbnfStack*>& stacks, PlanState* at,
|
||||
const uint32_t* cps, size_t n, GbnfStacks* out, OpWork& work) {
|
||||
std::lock_guard<std::mutex> lk(P.mu);
|
||||
SetDfa& dfa = plan_dfa(P, work);
|
||||
|
||||
/* The set as a state: the one the caller names, or canonicalised through pointers -- sorted,
|
||||
* without duplicates, and copied only if the automaton has not seen it. Charged as intern()
|
||||
* charges a sort. */
|
||||
const bool named = at->id >= 0 && at->gen == P.dfa_gen;
|
||||
int32_t s0;
|
||||
if (named) {
|
||||
s0 = at->id;
|
||||
work.add(stacks.size() + 1);
|
||||
} else {
|
||||
std::vector<const GbnfStack*>& ps = P.step_ptrs;
|
||||
ps.clear();
|
||||
size_t elems = 0;
|
||||
for (const GbnfStack* k : stacks) {
|
||||
ps.push_back(k);
|
||||
elems += k->size() + 1;
|
||||
}
|
||||
work.add(elems * (1 + (uint64_t)std::bit_width(ps.size())));
|
||||
std::sort(ps.begin(), ps.end(),
|
||||
[](const GbnfStack* a, const GbnfStack* b) { return *a < *b; });
|
||||
ps.erase(std::unique(ps.begin(), ps.end(),
|
||||
[](const GbnfStack* a, const GbnfStack* b) { return *a == *b; }),
|
||||
ps.end());
|
||||
s0 = dfa.intern_ptrs(ps);
|
||||
}
|
||||
int32_t s = s0;
|
||||
|
||||
/* One successor per code point: the interval the code point falls in, then that interval's
|
||||
* successor, each built on first use and served from the memo after. */
|
||||
for (size_t k = 0; k < n && s >= 0; ++k) {
|
||||
const SetDfa::St& S = dfa.parted(s);
|
||||
const size_t i = (size_t)(std::upper_bound(S.lo.begin(), S.lo.end(), cps[k]) -
|
||||
S.lo.begin()) - 1;
|
||||
work.add(8);
|
||||
s = dfa.next(s, i);
|
||||
}
|
||||
if (named && s == s0) return true;
|
||||
at->gen = P.dfa_gen;
|
||||
if (s < 0) {
|
||||
at->id = -1;
|
||||
out->clear();
|
||||
return false;
|
||||
}
|
||||
const SetDfa::St& S = dfa.st(s);
|
||||
at->id = S.has_empty || !S.ttop.empty() ? -1 : s;
|
||||
out->resize(S.stacks.size());
|
||||
for (size_t i = 0; i < S.stacks.size(); ++i)
|
||||
(*out)[i].assign(S.stacks[i].begin(), S.stacks[i].end());
|
||||
return false;
|
||||
}
|
||||
|
||||
int plan_fill(const MaskPlan& P, const GbnfStacks& stacks, PartialUtf8 partial, bool allow_eog,
|
||||
uint32_t* bitmask, int64_t n_words) {
|
||||
std::lock_guard<std::mutex> lk(P.mu);
|
||||
std::fill(bitmask, bitmask + n_words, 0u);
|
||||
|
||||
OpWork work;
|
||||
/* The automaton is a memo, so past its bound it is dropped and rebuilt rather than refused:
|
||||
* every state in it can be rediscovered, and a grammar whose stacks deepen with every token
|
||||
* would otherwise hold a new state per token for as long as it is cached. */
|
||||
if (!P.dfa || P.dfa->elems() > kMaxDfaElems) {
|
||||
if (P.dfa)
|
||||
RAD_DEBUG("gbnf: the stack-set automaton holds %zu states, %zu stack elements; "
|
||||
"rebuilding it", P.dfa->n_states(), P.dfa->elems());
|
||||
P.dfa = std::make_unique<SetDfa>(P.rules);
|
||||
}
|
||||
SetDfa& dfa = *P.dfa;
|
||||
dfa.begin(&work);
|
||||
SetDfa& dfa = plan_dfa(P, work);
|
||||
|
||||
if (allow_eog)
|
||||
for (int32_t id : P.vx->eog) set_bit(bitmask, id);
|
||||
|
||||
+50
-5
@@ -141,6 +141,12 @@ struct IPrefixCache {
|
||||
virtual Restore restore(const Request&) { return Restore::Done; }
|
||||
/* 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
|
||||
* refused after restore(): the request gives its hit back, and without the hold the chain it
|
||||
* just had restored would leave VRAM again before the next attempt restores it once more. */
|
||||
virtual void hold(const Request&) {}
|
||||
/* The request is gone -- finished, failed or cancelled -- and holds nothing any more. */
|
||||
virtual void release(const Request&) {}
|
||||
|
||||
virtual CacheHit lookup(const Request& r,
|
||||
std::vector<std::vector<int32_t>>* blocks_out) const = 0;
|
||||
@@ -159,6 +165,11 @@ struct IPrefixCache {
|
||||
* blocks no live sequence needs, so this is what the scheduler tries BEFORE preempting a
|
||||
* running request: a cached prefix is a saving, a running request is work already done. */
|
||||
virtual int64_t evict(int64_t n_entries) = 0;
|
||||
/* FREE UP TO `n_blocks` FOR THE RESERVE, and nothing a later turn needs. Unlike evict(), which
|
||||
* answers a shortfall that cannot wait, this passes over an entry a live sequence still holds
|
||||
* (releasing it frees no block) and one whose only copy is in VRAM (it is the next turn's
|
||||
* context). Returns how many blocks went back to the pool. */
|
||||
virtual int64_t trim(int64_t n_blocks) = 0;
|
||||
|
||||
/* FORGET EVERYTHING, wherever it is. Not a loop over evict(): with idle tiers an eviction moves
|
||||
* an entry whose host copy has landed off the card and keeps it, so a reset built out of
|
||||
@@ -206,8 +217,9 @@ 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. */
|
||||
virtual void commit_checkpoint(const Request& r, int64_t pos) = 0;
|
||||
* 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;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ block geometry */
|
||||
@@ -335,6 +347,11 @@ struct PCBinding final : IPrefixCache {
|
||||
return restore_fn ? restore_fn(r) : Restore::Done;
|
||||
}
|
||||
void begin_step() override { m->begin_step(); }
|
||||
void hold(const Request& r) override {
|
||||
media_keys(r, &mm_);
|
||||
m->hold(r.id, r.prompt, mm_);
|
||||
}
|
||||
void release(const Request& r) override { m->release(r.id); }
|
||||
const std::vector<int32_t>& cached_groups() const override { return m->cached_groups(); }
|
||||
|
||||
/* prompt ++ output, for the same reason reserve_checkpoint chains both: the next turn of a
|
||||
@@ -352,7 +369,35 @@ struct PCBinding final : IPrefixCache {
|
||||
media_keys(r, &mm_);
|
||||
return m->insert(r.id, toks, mm_, blocks, n_tokens);
|
||||
}
|
||||
int64_t evict(int64_t n) override { return m->evict_lru(n); }
|
||||
/* Installed by the engine when the idle tiers are on: lands every host copy that is waiting,
|
||||
* now, and says whether any landed. Called on the step thread under the scheduler's lock. */
|
||||
std::function<bool()> flush_fn;
|
||||
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. */
|
||||
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);
|
||||
if (k >= n) return k;
|
||||
const int64_t before = m->stats().evictions;
|
||||
k += m->evict_lru(n - k);
|
||||
const int64_t lost = m->stats().evictions - before;
|
||||
if (lost > 0 && flush_fn) {
|
||||
const uint64_t now = rad_mono_ns();
|
||||
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",
|
||||
(long long)lost);
|
||||
}
|
||||
}
|
||||
return k;
|
||||
}
|
||||
int64_t trim(int64_t n) override { return m->trim(n); }
|
||||
int64_t reset() override {
|
||||
const int64_t n = m->size();
|
||||
m->clear();
|
||||
@@ -378,8 +423,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) override {
|
||||
m->commit_checkpoint(prefix_hash(r, pos));
|
||||
void commit_checkpoint(const Request& r, int64_t pos, bool resume) override {
|
||||
m->commit_checkpoint(prefix_hash(r, pos), resume);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
@@ -75,6 +75,9 @@ struct SchedMetrics {
|
||||
/* Tokens one block covers, 0 for a stateful group. A pool measured in blocks cannot be
|
||||
* compared with a request measured in tokens, and every reader wants that comparison. */
|
||||
int64_t block_tokens = 0;
|
||||
/* A WINDOWED GROUP recycles its blocks below the window, so its carve says how far back a
|
||||
* sequence keeps context and nothing about how much context fits. */
|
||||
bool window = false;
|
||||
/* AND THE SAME GROUP IN BYTES, which is the measure that survives being added to the next
|
||||
* group's. Neither blocks nor tokens does: a stateful group has no token axis, and two
|
||||
* paged groups share one, so a token of context takes a slot in both and summing them
|
||||
|
||||
+82
-19
@@ -280,7 +280,16 @@ static server::Finish finish_of(ReqState st, const std::string& reason) {
|
||||
* So a reserve is kept free. It is a fraction of the pool rather than a token count because the
|
||||
* thing being protected is the ability to admit ANY sequence, and how big that is depends on the
|
||||
* deployment. Trimming happens after a publish, off the step path, where the blocks were just
|
||||
* added -- not during admission, where the cost lands on a request that did nothing wrong. */
|
||||
* added -- not during admission, where the cost lands on a request that did nothing wrong.
|
||||
*
|
||||
* THE RESERVE IS NOT ALWAYS THE CACHE'S TO MEET. Live sequences count against it too, and once they
|
||||
* hold more than three quarters of the pool -- five or six agent sessions at 70K tokens each -- no
|
||||
* amount of trimming reaches it. Evicting in LRU order until it did would take everything on the
|
||||
* list: the entries running sequences share, which frees no block, and the conversation the
|
||||
* request being closed has just published, before its host copy can land -- so every agent's next
|
||||
* turn would re-prefill its whole context. The trim therefore asks the cache for the blocks it is
|
||||
* short and nothing more, and the cache gives only what frees a block without losing a
|
||||
* conversation (PrefixCache::trim). */
|
||||
|
||||
/* Drop every entry, in VRAM or off it -- IPrefixCache::reset, because an eviction does not
|
||||
* mean "forgotten" for an entry the idle tiers hold a copy of. */
|
||||
@@ -300,17 +309,12 @@ void Scheduler::trim_prefix_cache() {
|
||||
const int64_t total = kv_->total_blocks(g);
|
||||
if (total <= 0) return;
|
||||
const int64_t reserve = total / 4; /* a quarter of the pool stays free */
|
||||
for (int guard = 0; guard < 4096; ++guard) {
|
||||
/* FREE AGAINST THE CARVE, not free_blocks(). On an elastic pool free_blocks() is bounded
|
||||
* by the live mark, so a pool that has handed its unused top back reads as nearly full
|
||||
* however little anything holds -- and this loop would then drain the whole cache to
|
||||
* make room the pool can grow back into on demand. */
|
||||
if (total - kv_->held_blocks(g) >= reserve) return;
|
||||
if (pc_->evict(256) <= 0) return; /* nothing left to give back */
|
||||
}
|
||||
RAD_WARN("prefix cache: could not free %lld of %lld blocks in group %d after 4096 rounds; the "
|
||||
"pool is held by live sequences rather than by the cache",
|
||||
(long long)reserve, (long long)total, (int)g);
|
||||
/* FREE AGAINST THE CARVE, not free_blocks(). On an elastic pool free_blocks() is bounded by
|
||||
* the live mark, so a pool that has handed its unused top back reads as nearly full however
|
||||
* little anything holds -- and the trim would then drain the whole cache to make room the pool
|
||||
* can grow back into on demand. */
|
||||
const int64_t short_by = reserve - (total - kv_->held_blocks(g));
|
||||
if (short_by > 0) (void)pc_->trim(short_by);
|
||||
}
|
||||
|
||||
void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free,
|
||||
@@ -341,6 +345,8 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
}
|
||||
}
|
||||
|
||||
if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
|
||||
|
||||
if (defer_free) {
|
||||
if (!s.pending_free) ++n_deferred_;
|
||||
s.pending_free = true;
|
||||
@@ -665,7 +671,22 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
|
||||
const int64_t I = geo_.checkpoint_interval;
|
||||
int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */
|
||||
if (n_computed + want > next) want = next - n_computed;
|
||||
if (n_computed + want == next && checkpoint_pos) *checkpoint_pos = next;
|
||||
if (n_computed + want == next) {
|
||||
if (checkpoint_pos) *checkpoint_pos = next;
|
||||
} else if (n_computed + want == n_target) {
|
||||
/* AND ONE AT THE TAIL OF THE PROMPT. The next turn of a conversation is this prompt
|
||||
* with more on the end, and it resumes from the deepest snapshot under its hit -- on
|
||||
* the interval alone that is up to an interval short of where this prompt ended, and
|
||||
* every one of those tokens is prefilled again on every turn. The last quantum
|
||||
* boundary is as far as a chunk may end short of the target, so the final chunk is
|
||||
* split there and the remainder, under a quantum, runs as the next step's chunk
|
||||
* (tail_checkpoint says where it is worth that step). */
|
||||
const int64_t tail = tail_checkpoint(n_target);
|
||||
if (tail > n_computed) {
|
||||
want = tail - n_computed;
|
||||
if (checkpoint_pos) *checkpoint_pos = tail;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (want < remaining) {
|
||||
@@ -688,6 +709,26 @@ 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 ((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. */
|
||||
int64_t Scheduler::tail_checkpoint(int64_t target) const {
|
||||
const int64_t I = geo_.checkpoint_interval, Q = geo_.quantum;
|
||||
if (I <= 0 || Q <= 0) return -1;
|
||||
const int64_t tail = target / Q * Q;
|
||||
return tail > I && tail - tail / I * I >= std::max<int64_t>(Q, I / 4) ? tail : -1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ preemption */
|
||||
void Scheduler::preempt_back() {
|
||||
int32_t slot = running_.back();
|
||||
@@ -734,6 +775,13 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
s.hit_owed = true;
|
||||
}
|
||||
|
||||
/* WHAT NO HIT CAN CHANGE IS ASKED FIRST: a free sequence and a budget that can take a chunk.
|
||||
* A restore copies the whole context back, and an admission refused after it would give that
|
||||
* hit back and copy it again on the next attempt. */
|
||||
if (s.card < 0 && free_cards_.empty()) return RAD_E_FULL;
|
||||
if (budget < std::max<int64_t>(geo_.quantum, 1) && budget < s.seq_len() - r.n_computed)
|
||||
return RAD_E_FULL;
|
||||
|
||||
if (r.n_computed == 0 && cfg_.prefix_cache) {
|
||||
/* BEFORE the lookup, because the lookup stops at the first block the tiers hold -- an
|
||||
* honest shorter hit, but a shorter one. This is where a cold session gets its
|
||||
@@ -770,9 +818,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
|
||||
/* Claim the cached blocks. Without this the hit is only an accounting entry: the sequence
|
||||
* would skip computing those tokens and then attend to blocks it does not own. adopt()
|
||||
* takes a whole block multiple, which `reuse` is -- it is a multiple of the checkpoint
|
||||
* interval, which geometry.h made a multiple of the quantum, which is a multiple of the
|
||||
* block size. */
|
||||
* takes a whole block multiple, which `reuse` is -- a whole number of blocks, or a
|
||||
* checkpoint position, which is on the interval or on a quantum boundary at a prompt's tail
|
||||
* (plan_chunk), and geometry.h made both multiples of the block size. */
|
||||
if (reuse > 0) {
|
||||
const std::vector<int32_t>& cg = pc_->cached_groups();
|
||||
for (size_t i = 0; i < cg.size() && i < hit_blocks_.size(); ++i) {
|
||||
@@ -801,7 +849,17 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
int rc = RAD_OK;
|
||||
if (want <= 0) rc = RAD_E_FULL;
|
||||
else if (s.card < 0 && free_cards_.empty()) rc = RAD_E_FULL;
|
||||
else if (kv_->ensure(r.id, r.n_computed + want) < 0) rc = RAD_E_NOMEM;
|
||||
else {
|
||||
/* THE CACHE GIVES WAY TO A NEW REQUEST as it does to a running one: with nothing running,
|
||||
* no other path would ever take blocks back from it, and the request would wait for good. */
|
||||
int rounds = 0;
|
||||
while (kv_->ensure(r.id, r.n_computed + want) < 0) {
|
||||
if (++rounds > 256 || !cfg_.prefix_cache || pc_->evict(256) <= 0) {
|
||||
rc = RAD_E_NOMEM;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rc < 0) {
|
||||
/* A HIT THAT RESUMES FROM A SNAPSHOT IS NOT KEPT ACROSS A FAILED ATTEMPT. The slot is
|
||||
* named by id only, and until this request's first step restores from it nothing stops
|
||||
@@ -811,6 +869,8 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
* a lookup; the attention-only hit of a model with no recurrent state holds only
|
||||
* refcounted blocks and is kept. */
|
||||
if (s.ckpt_src >= 0) undo_hit(s);
|
||||
/* AND WHAT THE RESTORE BROUGHT BACK STAYS for the next attempt (IPrefixCache::hold). */
|
||||
if (cfg_.prefix_cache) pc_->hold(r);
|
||||
return rc;
|
||||
}
|
||||
|
||||
@@ -1413,8 +1473,10 @@ 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_)
|
||||
pc_->commit_checkpoint(r, (int64_t)e.ctx_len + e.ckpt_tok + 1);
|
||||
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.is_prefill) {
|
||||
r.n_computed += e.n_tokens;
|
||||
@@ -2172,6 +2234,7 @@ SchedMetrics Scheduler::metrics_locked() const {
|
||||
m.kv[i].blocks_free = fr;
|
||||
m.kv[i].utilisation = tot > 0 ? (float)(1.0 - (double)fr / (double)tot) : 0.0f;
|
||||
m.kv[i].block_tokens = kv_->block_tokens(i);
|
||||
m.kv[i].window = gs[(size_t)i].decl.kind == RAD_KV_WINDOW;
|
||||
m.kv[i].bytes_total = kv_->pool_bytes(i);
|
||||
m.kv[i].bytes_used = kv_->pool_bytes_used(i);
|
||||
m.kv[i].bytes_carved = kv_->pool_bytes_carved(i);
|
||||
|
||||
@@ -445,6 +445,9 @@ public:
|
||||
|
||||
/* 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). */
|
||||
/* plan_chunk's checkpoint rules, asked after the fact (see the definitions). */
|
||||
bool last_checkpoint(int64_t pos, int64_t target) const;
|
||||
int64_t tail_checkpoint(int64_t target) const;
|
||||
int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
|
||||
int64_t* checkpoint_pos) const;
|
||||
|
||||
|
||||
+12
-4
@@ -116,10 +116,11 @@ public:
|
||||
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_host = s.ck_to_host; c.ck_to_disk = s.ck_to_disk; c.ck_promoted = s.ck_promoted;
|
||||
c.ck_drops = s.ck_drops; c.ck_starved = s.ck_starved;
|
||||
c.ck_to_disk = s.ck_to_disk; c.ck_drops = s.ck_drops;
|
||||
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_arena().capacity();
|
||||
c.ck_host_slots = tiers_->ckpt_slots();
|
||||
c.ck_disk_slots = tiers_->ckpt_disk_slots();
|
||||
c.host_on = tiers_->host_on();
|
||||
c.disk_on = tiers_->disk_on();
|
||||
@@ -150,7 +151,6 @@ public:
|
||||
o.on_disk = s.on_disk;
|
||||
o.moving = s.moving;
|
||||
o.snapshots = s.snapshots;
|
||||
o.snap_device = s.snap_device;
|
||||
o.snap_host = s.snap_host;
|
||||
o.snap_disk = s.snap_disk;
|
||||
o.snap_bytes = s.snap_bytes;
|
||||
@@ -246,6 +246,9 @@ public:
|
||||
o.kv_bytes_total += m.kv[i].bytes_total;
|
||||
o.kv_bytes_used += m.kv[i].bytes_used;
|
||||
o.kv_bytes_carved += m.kv[i].bytes_carved;
|
||||
if (m.kv[i].block_tokens <= 0 || m.kv[i].window) continue;
|
||||
const int64_t t = m.kv[i].blocks_total * m.kv[i].block_tokens;
|
||||
if (o.kv_tokens_max == 0 || t < o.kv_tokens_max) o.kv_tokens_max = t;
|
||||
}
|
||||
|
||||
/* vLLM's gpu_prefix_cache_hit_rate is a single number and attention caching is what it
|
||||
@@ -432,9 +435,14 @@ public:
|
||||
m.reasoning = r.reasoning;
|
||||
m.tool_calls.reserve(r.calls.size());
|
||||
for (const ReplyCall& c : r.calls) m.tool_calls.push_back({ std::string(), c.name, c.arguments });
|
||||
m.open_call = !r.calls.empty() && !r.calls.back().closed;
|
||||
return m;
|
||||
}
|
||||
|
||||
std::string content_with_open_call(std::string_view reply) const override {
|
||||
return s_->content_with_open_call(reply);
|
||||
}
|
||||
|
||||
private:
|
||||
void move_out(std::vector<ReplyDelta>* out) {
|
||||
if (!out) return;
|
||||
|
||||
+22
-14
@@ -53,7 +53,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
if (deps_.sched) deps_.sched->sessions(&v, &occ);
|
||||
|
||||
int64_t dev = 0, host = 0, disk = 0, bytes = 0;
|
||||
int64_t sdev = 0, shost = 0, sdisk = 0;
|
||||
int64_t shost = 0, sdisk = 0;
|
||||
json a = json::array();
|
||||
for (const SessionStat& s : v) {
|
||||
json e;
|
||||
@@ -69,17 +69,16 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
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, so a snapshot that stayed
|
||||
* on the device while its blocks went to disk shows as exactly that. */
|
||||
* of object in a different store. Counted where the BYTES are: in the store in host
|
||||
* memory, or on disk alone. */
|
||||
e["snapshots"] = s.snapshots;
|
||||
e["snap_device"] = s.snap_device;
|
||||
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;
|
||||
sdev += s.snap_device; shost += s.snap_host; sdisk += s.snap_disk;
|
||||
shost += s.snap_host; sdisk += s.snap_disk;
|
||||
bytes += s.bytes;
|
||||
}
|
||||
o["sessions"] = std::move(a);
|
||||
@@ -88,7 +87,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
* 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"] = { { "device", sdev }, { "host", shost }, { "disk", sdisk } };
|
||||
o["snapshots"] = { { "host", shost }, { "disk", sdisk } };
|
||||
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
|
||||
@@ -109,15 +108,14 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
{ "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.
|
||||
* `starved` is the one to read when `to_host` stays at zero: it means the snapshot arena had
|
||||
* no room, which --prefix-cache-host-mib fixes. */
|
||||
o["snapshots_moved"] = { { "to_host", c.ck_to_host }, { "to_disk", c.ck_to_disk },
|
||||
{ "promoted", c.ck_promoted }, { "fetched", c.ck_fetched },
|
||||
{ "drops", c.ck_drops },
|
||||
{ "starved", c.ck_starved }, { "bytes_each", c.ck_bytes },
|
||||
* 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 } };
|
||||
/* 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 } };
|
||||
/* AND WHETHER ANY OF IT IS BEING READ. Moving a snapshot and restoring it proves the bytes
|
||||
* travelled; this is the number that says a lookup then SERVED one. A hybrid server can move
|
||||
* snapshots all day and still replay from token zero if the checkpoint the restore put back
|
||||
@@ -170,6 +168,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
o["kv_bytes_used"] = (double)m.kv_bytes_used;
|
||||
o["kv_bytes_total"] = (double)m.kv_bytes_total;
|
||||
o["kv_bytes_carved"] = (double)m.kv_bytes_carved;
|
||||
o["kv_tokens_max"] = m.kv_tokens_max;
|
||||
o["prefix_hit_rate"] = m.prefix_hit_rate;
|
||||
/* The leading indicator beside the lagging one: past ~75% kv utilisation the cache
|
||||
* begins dropping prefixes the next turn wants, and the hit rate only falls once
|
||||
@@ -1484,6 +1483,10 @@ function meter(host, cls, title, idx, split) {
|
||||
const mKv = meter($("mem"), "meter", "KV cache", undefined, true);
|
||||
const mKvSub = el("div", "ksub");
|
||||
mKv.wrap.appendChild(mKvSub);
|
||||
/* AND HOW FAR IT CAN GROW: every block of the carve, the ones lent to the expert slab taken
|
||||
back -- which a request that needs them does, the same step. */
|
||||
const mKvMax = el("div", "ksub");
|
||||
mKv.wrap.appendChild(mKvMax);
|
||||
const mPc = meter($("mem"), "meter", "Prefix hits");
|
||||
/* `hot` is for a meter whose ceiling is a FAILURE -- KV utilisation near 100% preempts. A device
|
||||
* VRAM bar near 100% is the engine doing its job, so it passes false and stays neutral. */
|
||||
@@ -1729,7 +1732,8 @@ function update(s, dt) {
|
||||
of the pool is not among them: it is the bar in the memory panel, and repeating it here cost
|
||||
the line that says how much context the bytes are actually holding. */
|
||||
$("m-kvdet").textContent = s.kv_bytes_total > 0
|
||||
? "of " + hb(s.kv_bytes_total) + " · " + cnt3(s.kv_tokens_used) + " tok"
|
||||
? "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
|
||||
+ cnt3(s.kv_tokens_used) + " tok"
|
||||
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : "")
|
||||
: "";
|
||||
setMetric("accept", 100 * s.draft_accept,
|
||||
@@ -1769,6 +1773,10 @@ function update(s, dt) {
|
||||
mKvSub.textContent = s.kv_tokens_used > 0
|
||||
? cnt3(kvLive) + " tok read by running requests · " + cnt3(kvCached) + " kept for reuse"
|
||||
: "";
|
||||
mKvMax.textContent = s.kv_tokens_max > 0
|
||||
? "can grow to " + hb(s.kv_bytes_carved || 0) + " · " + cnt3(s.kv_tokens_max)
|
||||
+ " tok, with what the experts borrowed taken back"
|
||||
: "";
|
||||
mPc.v.textContent = pct(s.prefix_hit_rate); setBar(mPc.i, s.prefix_hit_rate, false);
|
||||
|
||||
/* ---- draft. The bar is the CONDITIONAL acceptance at that position; the reach row under the
|
||||
|
||||
+17
-5
@@ -67,6 +67,11 @@ struct SchedMetrics {
|
||||
int64_t kv_bytes_total = 0;
|
||||
/* What the pool was carved to address, which an elastic pool may not be holding. */
|
||||
int64_t kv_bytes_carved = 0;
|
||||
/* THE MOST CONTEXT THE CACHE CAN HOLD: every block of its carve, the ones lent to the expert
|
||||
* slab taken back. `kv_bytes_carved` is the same figure in bytes. The paged groups share one
|
||||
* token axis, so it is the smallest of theirs; a windowed group is left out, because its carve
|
||||
* bounds how far back a sequence keeps context rather than how much fits. */
|
||||
int64_t kv_tokens_max = 0;
|
||||
|
||||
double prefix_hit_rate = 0.0; /* 0..1 */
|
||||
/* Cumulative prefix-cache evictions. `prefix_hit_rate` falls only AFTER a prefix that
|
||||
@@ -157,7 +162,7 @@ struct SessionStat {
|
||||
* 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_device = 0, snap_host = 0, snap_disk = 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;
|
||||
@@ -264,11 +269,12 @@ public:
|
||||
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 -- the arena too small, the device slots contended --
|
||||
* and no block counter can tell that apart from tiering working. */
|
||||
int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0;
|
||||
* 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;
|
||||
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;
|
||||
int64_t ck_host_slots = 0, ck_disk_slots = 0; /* the store's; the disk store's */
|
||||
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. */
|
||||
@@ -430,6 +436,8 @@ struct ParsedMessage {
|
||||
std::string content;
|
||||
std::string reasoning; /* "" unless the template supports reasoning */
|
||||
std::vector<ToolCall> tool_calls;
|
||||
/* The reply ended inside its last call: that call never closed, and is no call to run. */
|
||||
bool open_call = false;
|
||||
};
|
||||
|
||||
/* One increment of a reply that is being read as it is generated. What has been delivered is
|
||||
@@ -458,6 +466,10 @@ public:
|
||||
virtual void finish(std::vector<ReplyDelta>* out) = 0;
|
||||
/* The whole reply, once finish() has run. */
|
||||
virtual ParsedMessage message() const = 0;
|
||||
/* Once finish() has run: the content with an open last call (ParsedMessage::open_call) read
|
||||
* as the text it was written as -- the content before the call, then the call's own bytes
|
||||
* from `reply`, the whole text fed. The content alone when no call is open. */
|
||||
virtual std::string content_with_open_call(std::string_view reply) const = 0;
|
||||
};
|
||||
|
||||
/* A request's reply format. Each choice opens its own reader, and a request that sent no tools
|
||||
|
||||
@@ -174,5 +174,63 @@ size_t json_stable_prefix(std::string_view s) {
|
||||
return n;
|
||||
}
|
||||
|
||||
bool json_quote_append(std::string& out, std::string_view s) {
|
||||
static const char kHex[] = "0123456789abcdef";
|
||||
const size_t mark = out.size();
|
||||
out.reserve(mark + s.size() + 2);
|
||||
out.push_back('"');
|
||||
const unsigned char* p = (const unsigned char*)s.data();
|
||||
const unsigned char* e = p + s.size();
|
||||
const unsigned char* run = p; /* [run, p) is verified and goes out as it is */
|
||||
while (p < e) {
|
||||
const unsigned char c = *p;
|
||||
if (c >= 0x80) {
|
||||
/* Length, and the range the SECOND byte is restricted to, which is what rejects
|
||||
* overlong forms, surrogates and anything past U+10FFFF without decoding. */
|
||||
size_t len;
|
||||
unsigned char lo = 0x80, hi = 0xBF;
|
||||
if (c >= 0xC2 && c <= 0xDF) len = 2;
|
||||
else if (c == 0xE0) { len = 3; lo = 0xA0; }
|
||||
else if (c >= 0xE1 && c <= 0xEC) len = 3;
|
||||
else if (c == 0xED) { len = 3; hi = 0x9F; }
|
||||
else if (c >= 0xEE && c <= 0xEF) len = 3;
|
||||
else if (c == 0xF0) { len = 4; lo = 0x90; }
|
||||
else if (c >= 0xF1 && c <= 0xF3) len = 4;
|
||||
else if (c == 0xF4) { len = 4; hi = 0x8F; }
|
||||
else len = 0;
|
||||
bool ok = len != 0 && (size_t)(e - p) >= len && p[1] >= lo && p[1] <= hi;
|
||||
for (size_t k = 2; ok && k < len; ++k) ok = p[k] >= 0x80 && p[k] <= 0xBF;
|
||||
if (!ok) {
|
||||
out.resize(mark);
|
||||
return false;
|
||||
}
|
||||
p += len;
|
||||
continue;
|
||||
}
|
||||
if (c >= 0x20 && c != '"' && c != '\\') {
|
||||
++p;
|
||||
continue;
|
||||
}
|
||||
out.append((const char*)run, (size_t)(p - run));
|
||||
switch (c) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\b': out += "\\b"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\f': out += "\\f"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
default: {
|
||||
const char u[6] = { '\\', 'u', '0', '0', kHex[c >> 4], kHex[c & 15] };
|
||||
out.append(u, 6);
|
||||
}
|
||||
}
|
||||
run = ++p;
|
||||
}
|
||||
out.append((const char*)run, (size_t)(p - run));
|
||||
out.push_back('"');
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
@@ -12,11 +12,15 @@
|
||||
* boundary: cutting a multi-byte code point in half turns one delta into mojibake and the
|
||||
* next into a decode error.
|
||||
*
|
||||
* And one way to write it: `json_quote_append`, a string literal exactly as nlohmann writes one,
|
||||
* for the chunks that carry a delta.
|
||||
*
|
||||
* This is a scanner, not a parser: it allocates nothing and builds no DOM.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace rad {
|
||||
@@ -36,5 +40,15 @@ size_t utf8_trunc(std::string_view s);
|
||||
* escape, and the class of bug that produces is unbisectable from the server side. */
|
||||
size_t json_stable_prefix(std::string_view s);
|
||||
|
||||
/* Append `s` to `out` as a JSON string literal, quotes included, byte for byte as nlohmann's
|
||||
* dump() writes one: `\b \t \n \f \r \" \\` as two characters, every other control character
|
||||
* as `\u00xx` in lowercase hex, and everything else -- DEL and non-ASCII included -- as itself.
|
||||
* Returns false, with `out` as it was, when `s` is not well-formed UTF-8 (overlong forms,
|
||||
* surrogates and code points past U+10FFFF included), which nlohmann refuses rather than writes.
|
||||
*
|
||||
* A streamed chunk is written with this around a fixed frame instead of through a DOM: building
|
||||
* and dumping a tree per token cost more than every other part of the token's host work. */
|
||||
bool json_quote_append(std::string& out, std::string_view s);
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
@@ -130,6 +130,8 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
g_waiting_.set((double)m.waiting);
|
||||
g_preempted_.set((double)m.preempted);
|
||||
g_kv_util_.set(m.kv_util);
|
||||
g_kv_max_tokens_.set((double)m.kv_tokens_max);
|
||||
g_kv_max_bytes_.set((double)m.kv_bytes_carved);
|
||||
g_prefix_hit_.set(m.prefix_hit_rate);
|
||||
g_prefill_tps_.set(m.prefill_tps);
|
||||
g_decode_tps_.set(m.decode_tps);
|
||||
@@ -239,6 +241,12 @@ std::string Metrics::render() const {
|
||||
"GPU KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get());
|
||||
w.gauge("vllm:kv_cache_usage_perc",
|
||||
"KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get());
|
||||
w.gauge("radiance:kv_cache_max_tokens",
|
||||
"Tokens of context the KV cache holds with every block it lends the experts taken "
|
||||
"back.", L, g_kv_max_tokens_.get());
|
||||
w.gauge("radiance:kv_cache_max_bytes",
|
||||
"VRAM the KV cache holds with every block it lends the experts taken back, one card.",
|
||||
L, g_kv_max_bytes_.get());
|
||||
w.gauge("vllm:gpu_prefix_cache_hit_rate",
|
||||
"GPU prefix cache block hit rate.", L, g_prefix_hit_.get());
|
||||
|
||||
|
||||
@@ -112,6 +112,7 @@ private:
|
||||
std::string labels_; /* {model_name="...",engine="0"} */
|
||||
|
||||
Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_;
|
||||
Gauge g_kv_max_tokens_, g_kv_max_bytes_;
|
||||
Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_;
|
||||
Gauge queue_depth_;
|
||||
/* The per-position draft hazard, kept as plain gauges because that is what it is: a
|
||||
|
||||
+61
-29
@@ -1962,6 +1962,27 @@ std::string ChatDeltaStream::chunk(json delta, const char* finish_reason, const
|
||||
return sse_event(o.dump());
|
||||
}
|
||||
|
||||
void ChatDeltaStream::delta_open(std::string& out) {
|
||||
/* Built from nlohmann's own serialisation of each field, on first use rather than in the
|
||||
* constructor, so a field nlohmann refuses throws where chunk() would have. */
|
||||
if (head_.empty())
|
||||
head_ = "data: {\"id\":" + json(id_).dump() +
|
||||
",\"object\":\"chat.completion.chunk\",\"created\":" + json(created_).dump() +
|
||||
",\"model\":" + json(model_).dump() + ",\"choices\":[{\"index\":" +
|
||||
json(index_).dump() + ",\"delta\":";
|
||||
out += head_;
|
||||
}
|
||||
|
||||
void ChatDeltaStream::delta_close(std::string& out) const {
|
||||
out += ",\"finish_reason\":null}]}\n\n";
|
||||
}
|
||||
|
||||
/* Text that is not well-formed UTF-8 goes to nlohmann, which refuses it with the exception the
|
||||
* tree in chunk() raises for it. */
|
||||
void ChatDeltaStream::quote(std::string& out, std::string_view s) {
|
||||
if (!json_quote_append(out, s)) out += json(std::string(s)).dump();
|
||||
}
|
||||
|
||||
std::string ChatDeltaStream::first_chunk() {
|
||||
json d;
|
||||
d["role"] = "assistant";
|
||||
@@ -1976,49 +1997,53 @@ std::string ChatDeltaStream::first_chunk() {
|
||||
std::string ChatDeltaStream::emit(const std::vector<ReplyDelta>& ev) {
|
||||
std::string out;
|
||||
for (const ReplyDelta& d : ev) {
|
||||
json delta;
|
||||
switch (d.kind) {
|
||||
case ReplyDelta::Reasoning:
|
||||
if (d.text.empty()) continue;
|
||||
last_.reasoning += d.text;
|
||||
delta["reasoning_content"] = d.text;
|
||||
delta_open(out);
|
||||
out += "{\"reasoning_content\":";
|
||||
quote(out, d.text);
|
||||
out += '}';
|
||||
break;
|
||||
case ReplyDelta::Content:
|
||||
if (d.text.empty()) continue;
|
||||
last_.content += d.text;
|
||||
delta["content"] = d.text;
|
||||
delta_open(out);
|
||||
out += "{\"content\":";
|
||||
quote(out, d.text);
|
||||
out += '}';
|
||||
break;
|
||||
case ReplyDelta::CallBegin: {
|
||||
ToolCall tc;
|
||||
tc.id = random_id("call_");
|
||||
tc.name = d.text;
|
||||
last_.tool_calls.push_back(tc);
|
||||
json f;
|
||||
f["name"] = tc.name;
|
||||
f["arguments"] = "";
|
||||
json e;
|
||||
e["index"] = (int64_t)d.call;
|
||||
e["id"] = tc.id;
|
||||
e["type"] = "function";
|
||||
e["function"] = std::move(f);
|
||||
delta["tool_calls"] = json::array({e});
|
||||
delta_open(out);
|
||||
out += "{\"tool_calls\":[{\"index\":";
|
||||
out += std::to_string((int64_t)d.call);
|
||||
out += ",\"id\":";
|
||||
quote(out, tc.id);
|
||||
out += ",\"type\":\"function\",\"function\":{\"name\":";
|
||||
quote(out, tc.name);
|
||||
out += ",\"arguments\":\"\"}}]}";
|
||||
last_.tool_calls.push_back(std::move(tc));
|
||||
break;
|
||||
}
|
||||
case ReplyDelta::CallArgs: {
|
||||
if (d.text.empty() || d.call >= last_.tool_calls.size()) continue;
|
||||
last_.tool_calls[d.call].arguments += d.text;
|
||||
json f;
|
||||
f["arguments"] = d.text;
|
||||
json e;
|
||||
e["index"] = (int64_t)d.call;
|
||||
e["function"] = std::move(f);
|
||||
delta["tool_calls"] = json::array({e});
|
||||
delta_open(out);
|
||||
out += "{\"tool_calls\":[{\"index\":";
|
||||
out += std::to_string((int64_t)d.call);
|
||||
out += ",\"function\":{\"arguments\":";
|
||||
quote(out, d.text);
|
||||
out += "}}]}";
|
||||
break;
|
||||
}
|
||||
case ReplyDelta::CallEnd:
|
||||
continue;
|
||||
}
|
||||
out += chunk(std::move(delta), nullptr);
|
||||
delta_close(out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -2030,9 +2055,11 @@ std::string ChatDeltaStream::push(std::string_view appended, bool is_final) {
|
||||
/* Nothing to parse: the text is the answer, as it arrives. */
|
||||
if (!appended.empty()) {
|
||||
last_.content.append(appended);
|
||||
json d;
|
||||
d["content"] = std::string(appended);
|
||||
out = chunk(std::move(d), nullptr);
|
||||
delta_open(out);
|
||||
out += "{\"content\":";
|
||||
quote(out, appended);
|
||||
out += '}';
|
||||
delta_close(out);
|
||||
}
|
||||
finished_ = is_final;
|
||||
return out;
|
||||
@@ -2053,14 +2080,19 @@ std::string ChatDeltaStream::push(std::string_view appended, bool is_final) {
|
||||
return out;
|
||||
}
|
||||
|
||||
bool calls_complete(const ParsedMessage& m) {
|
||||
if (m.tool_calls.empty() || m.open_call) return false;
|
||||
for (const auto& tc : m.tool_calls)
|
||||
if (tc.name.empty() || !json_complete(tc.arguments)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
Finish ChatDeltaStream::adjusted_finish(Finish f) const {
|
||||
if (f != Finish::Stop && f != Finish::StopString) return f;
|
||||
if (last_.tool_calls.empty()) return f;
|
||||
/* Only claim tool_calls if every call's arguments actually parse. A truncated arguments
|
||||
* object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h). */
|
||||
for (const auto& tc : last_.tool_calls)
|
||||
if (tc.name.empty() || !json_complete(tc.arguments)) return f;
|
||||
return Finish::ToolCalls;
|
||||
/* Only claim tool_calls if every call closed and its arguments parse. A truncated arguments
|
||||
* object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h).
|
||||
* The deltas of an open call have gone out already; the finish reason says not to run it. */
|
||||
return calls_complete(last_) ? Finish::ToolCalls : f;
|
||||
}
|
||||
|
||||
std::string ChatDeltaStream::final_chunk(Finish f, const TimingsOut& t) {
|
||||
|
||||
@@ -290,6 +290,11 @@ std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u,
|
||||
/* The `timings` object, for a stream's final chunks. */
|
||||
json timings_json(const TimingsOut& t);
|
||||
|
||||
/* Whether a parsed reply's calls are all calls a client can run: none left open, each named,
|
||||
* each one's arguments one JSON value (json_partial.h). A reply is answered `tool_calls` by this
|
||||
* alone, streamed or not. */
|
||||
bool calls_complete(const ParsedMessage& m);
|
||||
|
||||
/* ================================================================== streaming
|
||||
*
|
||||
* One of these per choice. It feeds the generated text to the choice's reply reader as it grows
|
||||
@@ -323,6 +328,14 @@ private:
|
||||
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
|
||||
std::string emit(const std::vector<ReplyDelta>& ev);
|
||||
|
||||
/* A delta's chunk is written, not built: the frame around the delta object is the same in
|
||||
* every one, so it is serialised once, and the delta between is written with
|
||||
* json_quote_append. The bytes are the ones chunk() writes for the same delta. */
|
||||
void delta_open(std::string& out);
|
||||
void delta_close(std::string& out) const;
|
||||
static void quote(std::string& out, std::string_view s);
|
||||
std::string head_; /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */
|
||||
|
||||
std::unique_ptr<IReplyReader> reader_;
|
||||
std::string id_, model_;
|
||||
int64_t created_;
|
||||
|
||||
+12
-9
@@ -644,17 +644,20 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
rd->feed(g.text, nullptr);
|
||||
rd->finish(nullptr);
|
||||
c.msg = rd->message();
|
||||
/* Only claim a tool call when the arguments actually parse (json_partial.h). */
|
||||
bool complete = r.parse_tools && !c.msg.tool_calls.empty();
|
||||
for (const auto& tc : c.msg.tool_calls)
|
||||
if (tc.name.empty() || !json_complete(tc.arguments)) complete = false;
|
||||
/* Only claim a tool call when every call closed and its arguments parse
|
||||
* (json_partial.h) -- the streaming path's rule (calls_complete). */
|
||||
const bool complete = r.parse_tools && calls_complete(c.msg);
|
||||
if (complete && (c.finish == Finish::Stop || c.finish == Finish::StopString))
|
||||
c.finish = Finish::ToolCalls;
|
||||
else if (!c.msg.tool_calls.empty() && !complete) {
|
||||
/* A half-finished call is content, not a call. The client gets what the model
|
||||
* actually produced instead of a tool invocation with truncated arguments. */
|
||||
c.msg.tool_calls.clear();
|
||||
c.msg.content = g.text;
|
||||
if (c.msg.open_call) {
|
||||
/* A half-finished call is content, not a call: the client gets what the model
|
||||
* wrote instead of a tool invocation with truncated arguments. Only that call
|
||||
* -- the reply ended inside it, so it is the last -- and only its own text:
|
||||
* the reasoning stays reasoning, and the calls before it, which closed, stay
|
||||
* calls, as the stream announced them. The finish reason is the stream's. */
|
||||
c.msg.content = rd->content_with_open_call(g.text);
|
||||
c.msg.tool_calls.pop_back();
|
||||
c.msg.open_call = false;
|
||||
}
|
||||
} else {
|
||||
c.msg.content = g.text;
|
||||
|
||||
+2
-1
@@ -105,7 +105,8 @@ struct ChatFormat {
|
||||
ChatValue string_value = ChatValue::Cdata; /* a string-typed argument: Raw or Cdata */
|
||||
ChatValue other_value = ChatValue::Json; /* any other type: Json */
|
||||
/* One newline at each end of a value is punctuation: the template writes the value on its own
|
||||
* lines, and exactly the first and last newline belong to the tags. */
|
||||
* lines, and exactly the first and last newline belong to the tags. A tag that ends with its
|
||||
* newline (Qwen's `>\n`) has written the first one already, and the value starts after it. */
|
||||
bool value_newlines = true;
|
||||
|
||||
/* The literal words that start constrained decoding of a call. Empty means no lazy grammar:
|
||||
|
||||
+334
-86
@@ -135,7 +135,12 @@ private:
|
||||
* * no whitespace before the value, any whitespace after it and inside it;
|
||||
* * a number may not be followed by a character that could have continued it -- `01`, `1.`,
|
||||
* `1-` are not numbers -- while `true` and `null` may be followed by anything;
|
||||
* * a string may hold raw control characters, and any escape but the JSON ones fails it.
|
||||
* * a raw control character fails a string, as the schema's string rule refuses one and JSON
|
||||
* has none: a client's JSON parser rejects a raw newline in a string. Any escape but the
|
||||
* JSON ones fails it too.
|
||||
*
|
||||
* A value accepted here is still checked whole by a JSON parser before it is written as JSON
|
||||
* (json_value_done): the grammar admits a few spellings a client cannot read.
|
||||
*
|
||||
* push() answers More while the bytes are still a JSON value or its trailing whitespace, Fail at
|
||||
* the first byte that cannot be, and Done at the first byte after a complete value -- which is
|
||||
@@ -163,6 +168,7 @@ public:
|
||||
}
|
||||
if (c == '"') { st_ = key_ ? KeyAfter : After; return More; }
|
||||
if (c == '\\') { st_ = StrEsc; return More; }
|
||||
if (c < 0x20) return Fail;
|
||||
if (c < 0x80) return More;
|
||||
if (!(c & 0x40)) return Fail;
|
||||
if (!(c & 0x20)) { need_ = 1; return More; }
|
||||
@@ -410,8 +416,22 @@ std::string_view trim_trailing_ws(std::string_view v) {
|
||||
*
|
||||
* The bytes of one value as the delimiters bound it, turned into its JSON encoding in the
|
||||
* arguments object. Two encodings: a STRING (quoted, escaped) and RAW JSON text, which is either
|
||||
* a value that parsed as JSON or a non-string argument that did not and is passed through --
|
||||
* with a Python-style container's single quotes normalised to double ones.
|
||||
* a value that parsed as JSON or a non-string argument that did not.
|
||||
*
|
||||
* A NON-STRING ARGUMENT THAT DID NOT PARSE IS MADE JSON, never passed through: the arguments
|
||||
* object is the one thing a client parses, and a single bare token in it makes the whole call
|
||||
* unreadable -- the server then cannot report it as a call at all. The grammar admits text for a
|
||||
* typed argument, and what these models write there is Python: `True`, `False`, `None`, and
|
||||
* single-quoted containers. A scalar is held while it could still be a Python literal -- `True`
|
||||
* as true, `False`, `None` as null -- or a JSON number or literal, up to kScalar bytes, and is
|
||||
* then written as that; anything else, or anything longer, streams as a JSON string of its text.
|
||||
* An empty one is null. A CONTAINER -- its first byte after at most a few blanks is `[` or `{` --
|
||||
* is held whole, because whether it is JSON once its quotes are normalised to double ones and its
|
||||
* Python literals to JSON's is known only at its end: a trailing comma, a bare word, an escape
|
||||
* JSON has not or a missing bracket each leave it no JSON, and then it is a JSON string of its
|
||||
* text. A value the reply was cut off inside is written as it arrived: it has no end to read it
|
||||
* to, and the call it is in is not complete. A value the JSON reader ACCEPTED (json_value_done)
|
||||
* is written as it is.
|
||||
*
|
||||
* The transforms touch only the ends of a value -- one newline at each end, the CDATA opener and
|
||||
* closer -- so the middle streams straight through and only a short head and tail are held: the
|
||||
@@ -421,12 +441,17 @@ public:
|
||||
enum Mode : uint8_t { String, Raw };
|
||||
static constexpr size_t kHead = 16; /* a newline pair and the CDATA opener, and the tail */
|
||||
static constexpr size_t kTail = 5; /* a newline pair and the CDATA closer */
|
||||
/* The longest scalar held while it could still be a literal or a number: a few blanks and
|
||||
* a 64-bit integer, or a double in its shortest round-trip spelling. */
|
||||
static constexpr size_t kScalar = 28;
|
||||
|
||||
void begin(Mode m, bool cdata, bool newlines, std::string& out) {
|
||||
mode_ = m; cdata_ = cdata; newlines_ = newlines;
|
||||
/* `lead`, `trail`: a newline at that end is punctuation. `json`: the value already parsed as
|
||||
* JSON, so a Raw scalar is written as it is. */
|
||||
void begin(Mode m, bool cdata, bool lead, bool trail, std::string& out, bool json = false) {
|
||||
mode_ = m; cdata_ = cdata; lead_ = lead; trail_ = trail; json_ = json; str_ = false;
|
||||
buf_.clear(); head_ = false; opened_ = false;
|
||||
raw_started_ = false; container_ = false;
|
||||
in_single_ = in_double_ = bs_ = false;
|
||||
container_ = false;
|
||||
scalar_.clear(); cont_.clear();
|
||||
if (mode_ == String) out += '"';
|
||||
}
|
||||
|
||||
@@ -436,7 +461,7 @@ public:
|
||||
if (buf_.size() < kHead) return;
|
||||
std::string_view v(buf_);
|
||||
size_t drop = 0;
|
||||
if (newlines_) drop = v.size() - strip_leading_newline(v).size();
|
||||
if (lead_) drop = v.size() - strip_leading_newline(v).size();
|
||||
if (cdata_ && v.compare(drop, kCdOpen.size(), kCdOpen) == 0) {
|
||||
opened_ = true;
|
||||
drop += kCdOpen.size();
|
||||
@@ -454,10 +479,11 @@ public:
|
||||
void finish(bool partial, std::string& out) {
|
||||
std::string_view v(buf_);
|
||||
if (!head_) {
|
||||
if (newlines_) v = strip_trailing_newline(strip_leading_newline(v));
|
||||
if (lead_) v = strip_leading_newline(v);
|
||||
if (trail_) v = strip_trailing_newline(v);
|
||||
if (cdata_) unwrap_cdata(v, partial);
|
||||
} else {
|
||||
if (newlines_) v = strip_trailing_newline(v);
|
||||
if (trail_) v = strip_trailing_newline(v);
|
||||
if (opened_) {
|
||||
if (v.size() >= kCdClose.size() &&
|
||||
v.compare(v.size() - kCdClose.size(), kCdClose.size(), kCdClose) == 0) {
|
||||
@@ -472,61 +498,164 @@ public:
|
||||
}
|
||||
}
|
||||
emit(v.data(), v.size(), out);
|
||||
if (bs_) { out += '\\'; bs_ = false; }
|
||||
if (mode_ == Raw && !json_) {
|
||||
if (container_) container_out(partial, out);
|
||||
else if (str_) { if (!partial) out += '"'; }
|
||||
else if (partial) { out += scalar_; scalar_.clear(); } /* cut off: as it arrived */
|
||||
else scalar_out(out);
|
||||
}
|
||||
buf_.clear();
|
||||
}
|
||||
|
||||
size_t held() const { return buf_.size() + (bs_ ? 1 : 0); }
|
||||
/* Bytes held while the value's ends are decided, and a scalar while it could be a literal. */
|
||||
size_t held() const { return buf_.size() + scalar_.size(); }
|
||||
/* A container, held whole until its end. */
|
||||
size_t held_container() const { return cont_.size(); }
|
||||
|
||||
private:
|
||||
void emit(const char* p, size_t n, std::string& out) {
|
||||
if (n == 0) return;
|
||||
if (mode_ == String) { json_escape_into(out, p, n); return; }
|
||||
if (!raw_started_) {
|
||||
raw_started_ = true;
|
||||
container_ = p[0] == '[' || p[0] == '{';
|
||||
}
|
||||
if (!container_) { out.append(p, n); return; }
|
||||
for (size_t i = 0; i < n; ++i) normalise(p[i], out);
|
||||
}
|
||||
|
||||
/* Python-style quoting to JSON, one character at a time: a single-quoted string becomes a
|
||||
* double-quoted one, with the quotes inside it re-escaped to match. A backslash is held until
|
||||
* the character after it arrives, since the pair is read together. */
|
||||
void normalise(char c, std::string& out) {
|
||||
if (bs_) {
|
||||
bs_ = false;
|
||||
if (in_single_) {
|
||||
if (c == '\'') { out += '\''; return; }
|
||||
if (c == '"') { out += "\\\""; return; }
|
||||
out += '\\'; out += c; return;
|
||||
}
|
||||
if (in_double_) { out += '\\'; out += c; return; }
|
||||
out += '\\';
|
||||
/* Outside a string the backslash stands alone and the next character is read
|
||||
* normally. */
|
||||
} else if (c == '\\') {
|
||||
bs_ = true;
|
||||
if (json_) { out.append(p, n); return; }
|
||||
if (str_) { json_escape_into(out, p, n); return; }
|
||||
if (container_) { cont_.append(p, n); return; }
|
||||
scalar_.append(p, n);
|
||||
size_t ws = 0;
|
||||
while (ws < scalar_.size() && is_ws((unsigned char)scalar_[ws])) ++ws;
|
||||
if (ws <= 4 && ws < scalar_.size() && (scalar_[ws] == '[' || scalar_[ws] == '{')) {
|
||||
container_ = true;
|
||||
cont_.assign(scalar_, ws, std::string::npos);
|
||||
scalar_.clear();
|
||||
return;
|
||||
}
|
||||
if (c == '"') {
|
||||
if (in_single_) out += "\\\"";
|
||||
else { in_double_ = !in_double_; out += '"'; }
|
||||
} else if (c == '\'') {
|
||||
if (in_double_) out += '\'';
|
||||
else if (in_single_) { in_single_ = false; out += '"'; }
|
||||
else { in_single_ = true; out += '"'; }
|
||||
} else {
|
||||
out += c;
|
||||
if (scalar_.size() > kScalar || !scalar_prefix(scalar_)) {
|
||||
out += '"';
|
||||
json_escape_into(out, scalar_.data(), scalar_.size());
|
||||
scalar_.clear();
|
||||
str_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* Could `v` still become a Python or JSON literal or a JSON number, after at most a few
|
||||
* bytes of blanks on either side? */
|
||||
static bool scalar_prefix(std::string_view v) {
|
||||
size_t ws = 0;
|
||||
while (ws < v.size() && is_ws((unsigned char)v[ws])) ++ws;
|
||||
if (ws > 4) return false;
|
||||
v.remove_prefix(ws);
|
||||
size_t tw = 0;
|
||||
while (tw < v.size() && is_ws((unsigned char)v[v.size() - 1 - tw])) ++tw;
|
||||
if (tw > 4) return false;
|
||||
if (tw > 0 && tw == v.size()) return true;
|
||||
v.remove_suffix(tw);
|
||||
if (v.empty()) return true;
|
||||
for (std::string_view l : { std::string_view("True"), std::string_view("False"),
|
||||
std::string_view("None"), std::string_view("true"),
|
||||
std::string_view("false"), std::string_view("null") })
|
||||
if (v.size() <= l.size() && l.compare(0, v.size(), v) == 0) return true;
|
||||
return number_prefix(v);
|
||||
}
|
||||
|
||||
/* A prefix of -?(0|[1-9][0-9]*)(.[0-9]+)?([eE][+-]?[0-9]+)? */
|
||||
static bool number_prefix(std::string_view v) {
|
||||
size_t i = 0;
|
||||
if (i < v.size() && v[i] == '-') ++i;
|
||||
if (i == v.size()) return true;
|
||||
if (v[i] == '0') ++i;
|
||||
else if (v[i] >= '1' && v[i] <= '9') while (i < v.size() && std::isdigit((unsigned char)v[i])) ++i;
|
||||
else return false;
|
||||
if (i < v.size() && v[i] == '.') {
|
||||
++i;
|
||||
while (i < v.size() && std::isdigit((unsigned char)v[i])) ++i;
|
||||
}
|
||||
if (i < v.size() && (v[i] == 'e' || v[i] == 'E')) {
|
||||
++i;
|
||||
if (i < v.size() && (v[i] == '+' || v[i] == '-')) ++i;
|
||||
while (i < v.size() && std::isdigit((unsigned char)v[i])) ++i;
|
||||
}
|
||||
return i == v.size();
|
||||
}
|
||||
|
||||
/* A Python literal is JSON's under another spelling; anything else is as written. */
|
||||
static const char* json_literal(std::string_view w) {
|
||||
if (w == "True") return "true";
|
||||
if (w == "False") return "false";
|
||||
if (w == "None") return "null";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void scalar_out(std::string& out) {
|
||||
std::string_view v = trim_trailing_ws(scalar_);
|
||||
while (!v.empty() && is_ws((unsigned char)v.front())) v.remove_prefix(1);
|
||||
if (v.empty()) out += "null";
|
||||
else if (const char* lit = json_literal(v)) out += lit;
|
||||
else if (nlohmann::json::accept(v)) out.append(v.data(), v.size());
|
||||
else out += json_quote(scalar_);
|
||||
scalar_.clear();
|
||||
}
|
||||
|
||||
/* The held container, normalised; JSON if that made it JSON, else a JSON string of its text.
|
||||
* One the reply was cut off inside is written normalised as far as it arrived. */
|
||||
void container_out(bool partial, std::string& out) {
|
||||
std::string j;
|
||||
j.reserve(cont_.size() + 8);
|
||||
normalise(cont_, j);
|
||||
if (partial || nlohmann::json::accept(j)) out += j;
|
||||
else out += json_quote(cont_);
|
||||
cont_.clear();
|
||||
}
|
||||
|
||||
/* Python-style quoting to JSON: a single-quoted string becomes a double-quoted one, with the
|
||||
* quotes inside it re-escaped to match and its raw control characters escaped, and a bare
|
||||
* Python literal outside every string is respelled as JSON's. Whatever is no JSON after that
|
||||
* is left as written, for the JSON parser to refuse. */
|
||||
static void normalise(std::string_view v, std::string& out) {
|
||||
bool in_single = false, in_double = false;
|
||||
for (size_t i = 0; i < v.size(); ++i) {
|
||||
const char c = v[i];
|
||||
if (in_single || in_double) {
|
||||
if (c == '\\' && i + 1 < v.size()) {
|
||||
const char d = v[++i];
|
||||
if (d == '\'') out += '\''; /* `\'` is a quote in either quoting */
|
||||
else if (in_single && d == '"') out += "\\\"";
|
||||
else { out += '\\'; out += d; }
|
||||
} else if (c == (in_single ? '\'' : '"')) {
|
||||
in_single = in_double = false;
|
||||
out += '"';
|
||||
} else if (c == '"') {
|
||||
out += "\\\"";
|
||||
} else if ((unsigned char)c < 0x20) {
|
||||
/* A raw line break or tab inside a string, which JSON spells as an escape. */
|
||||
json_escape_into(out, &c, 1);
|
||||
} else {
|
||||
out += c;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (std::isalnum((unsigned char)c) || c == '_') {
|
||||
size_t e = i + 1;
|
||||
while (e < v.size() && (std::isalnum((unsigned char)v[e]) || v[e] == '_')) ++e;
|
||||
const std::string_view w = v.substr(i, e - i);
|
||||
if (const char* lit = json_literal(w)) out += lit;
|
||||
else out.append(w.data(), w.size());
|
||||
i = e - 1;
|
||||
continue;
|
||||
}
|
||||
if (c == '\'') in_single = true;
|
||||
else if (c == '"') in_double = true;
|
||||
out += c == '\'' ? '"' : c;
|
||||
}
|
||||
}
|
||||
|
||||
Mode mode_ = String;
|
||||
bool cdata_ = true, newlines_ = true;
|
||||
bool cdata_ = true, lead_ = true, trail_ = true;
|
||||
std::string buf_;
|
||||
bool head_ = false, opened_ = false;
|
||||
bool raw_started_ = false, container_ = false;
|
||||
bool in_single_ = false, in_double_ = false, bs_ = false;
|
||||
bool container_ = false;
|
||||
std::string scalar_; /* a scalar while it could still be a Python literal */
|
||||
std::string cont_; /* a container, held whole */
|
||||
bool json_ = false; /* the value parsed as JSON: written as it is */
|
||||
bool str_ = false; /* the scalar is no literal and streams as a JSON string */
|
||||
};
|
||||
|
||||
/* ================================================================== the answer text
|
||||
@@ -562,19 +691,25 @@ public:
|
||||
/* The exact trim: trailing spaces and newlines, then the first terminator in the list that
|
||||
* ends what is left. */
|
||||
void finish(std::string& full) {
|
||||
while (!pend_.empty() && (pend_.back() == '\n' || pend_.back() == ' ')) pend_.pop_back();
|
||||
if (list_)
|
||||
for (const std::string& t : *list_)
|
||||
if (!t.empty() && pend_.size() >= t.size() &&
|
||||
pend_.compare(pend_.size() - t.size(), t.size(), t) == 0) {
|
||||
pend_.erase(pend_.size() - t.size());
|
||||
break;
|
||||
}
|
||||
trim(pend_);
|
||||
full += pend_;
|
||||
pend_.clear();
|
||||
}
|
||||
|
||||
size_t held_space() const { return std::min(ws_, pend_.size()); }
|
||||
/* What is held: the content after `full` so far, untrimmed. */
|
||||
const std::string& pending() const { return pend_; }
|
||||
/* The same trim, on a whole text. */
|
||||
void trim(std::string& s) const {
|
||||
while (!s.empty() && (s.back() == '\n' || s.back() == ' ')) s.pop_back();
|
||||
if (list_)
|
||||
for (const std::string& t : *list_)
|
||||
if (!t.empty() && s.size() >= t.size() &&
|
||||
s.compare(s.size() - t.size(), t.size(), t) == 0) {
|
||||
s.erase(s.size() - t.size());
|
||||
break;
|
||||
}
|
||||
}
|
||||
size_t held_other() const { return pend_.size() - held_space(); }
|
||||
|
||||
private:
|
||||
@@ -604,6 +739,9 @@ struct ReplyFormat::Impl {
|
||||
* model wrote it unconstrained, and its argument tags are read with the whitespace around
|
||||
* them optional -- as its name and its close are. */
|
||||
std::string name_end_core, value_core;
|
||||
/* call_close's core, when it can be told apart from what else may follow inside a call: a
|
||||
* wrapped call whose own close is missing is ended by its wrapper's. */
|
||||
std::string cc_core;
|
||||
Dfa think, think_breaks, text, arg_name, value, junk, arg_name_loose, value_loose;
|
||||
size_t longest = 0; /* the longest delimiter */
|
||||
};
|
||||
@@ -651,7 +789,13 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
split_ws(f.arg_value_suffix, &m.value_core, &trail);
|
||||
m.arg_name_loose.build({ m.name_end_core });
|
||||
m.value_loose.build({ m.value_core });
|
||||
m.junk.build({ f.arg_prefix, m.end_core });
|
||||
split_ws(f.call_close, &m.cc_core, &trail);
|
||||
auto apart = [](const std::string& a, const std::string& b) {
|
||||
return a.find(b) == std::string::npos && b.find(a) == std::string::npos;
|
||||
};
|
||||
if (!apart(m.cc_core, f.arg_prefix) || !apart(m.cc_core, m.end_core)) m.cc_core.clear();
|
||||
if (m.cc_core.empty()) m.junk.build({ f.arg_prefix, m.end_core });
|
||||
else m.junk.build({ f.arg_prefix, m.end_core, m.cc_core });
|
||||
}
|
||||
const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.call_open,
|
||||
&f.call_close, &f.name_prefix, &f.name_suffix,
|
||||
@@ -701,7 +845,7 @@ size_t ReplyParser::hold_bound() const {
|
||||
size_t term = 0;
|
||||
for (const std::string& t : impl_->terminators) term = std::max(term, t.size());
|
||||
return impl_->fmt->impl().longest + std::max(term, kFenceOpen.size()) + ValueOut::kHead + 1 +
|
||||
3 * 3;
|
||||
3 * 3 + ValueOut::kScalar;
|
||||
}
|
||||
|
||||
ReasoningMarkers ReplyParser::reasoning() const {
|
||||
@@ -740,6 +884,9 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse
|
||||
info.resolve_refs(params);
|
||||
std::vector<std::string> optional;
|
||||
for (const auto& [pname, pschema] : properties.items()) {
|
||||
/* An optional argument no value satisfies has no arm in the grammar, which reads
|
||||
* it by the undeclared arm, as text (chatfmt.cpp); so does the parser. */
|
||||
if (!required.count(pname) && info.unsatisfiable(pschema)) continue;
|
||||
Param p;
|
||||
p.typed = F.f.other_value == ChatValue::Json && !info.resolves_to_string(pschema);
|
||||
t.has_props = true;
|
||||
@@ -919,9 +1066,16 @@ struct ReplyStream::Impl {
|
||||
size_t sent_r = 0, sent_c = 0, sent_a = 0;
|
||||
int cur = -1; /* the channel last published: 0 r, 1 c, 2 args */
|
||||
|
||||
/* bytes to read again, ahead of the rest */
|
||||
struct Seg { const char* p; size_t n; };
|
||||
/* bytes to read again, ahead of the rest. Bytes read again are always the last ones read,
|
||||
* so each segment knows where its first byte is in the stream: the generation prompt's tail,
|
||||
* then the reply. */
|
||||
struct Seg { const char* p; size_t n; size_t at; };
|
||||
std::vector<Seg> stack;
|
||||
const char* seg_p = nullptr; /* the segment being read */
|
||||
size_t seg_at = 0; /* and where its first byte is in the stream */
|
||||
size_t fed = 0; /* the bytes the stream has been given */
|
||||
size_t att_at = 0; /* where the opener being tried begins */
|
||||
size_t here(const char* p) const { return seg_at + (size_t)(p - seg_p); }
|
||||
std::deque<std::string> owned;
|
||||
std::string refeed;
|
||||
|
||||
@@ -1105,6 +1259,7 @@ struct ReplyStream::Impl {
|
||||
st = origin;
|
||||
ds = 0;
|
||||
hold.clear();
|
||||
lhold.clear();
|
||||
if (origin == St::Think) think_out(att.data(), 1);
|
||||
else text_out(att.data(), 1);
|
||||
read_again(std::string_view(att).substr(1));
|
||||
@@ -1120,6 +1275,9 @@ struct ReplyStream::Impl {
|
||||
0, name.size() - F.ns_core.size()));
|
||||
ReplyCall c;
|
||||
c.name.assign(nm);
|
||||
c.at = att_at >= P.tail.size() ? att_at - P.tail.size() : 0;
|
||||
c.content_at = msg.content.size();
|
||||
c.content_held = content.pending();
|
||||
msg.calls.push_back(std::move(c));
|
||||
sent_a = 0;
|
||||
cur = -1;
|
||||
@@ -1161,6 +1319,16 @@ struct ReplyStream::Impl {
|
||||
else after_loose_call();
|
||||
}
|
||||
|
||||
/* The wrapper's close inside a wrapped call, whose own close is missing: it ends the call
|
||||
* and the wrapper both. Read leniently -- the grammar requires call_end first -- but as the
|
||||
* close it is, or the next call's arguments would be read into this one. */
|
||||
void end_call_at_close() {
|
||||
lenient();
|
||||
end_call();
|
||||
if (loose) after_loose_call();
|
||||
else st = St::AfterCall;
|
||||
}
|
||||
|
||||
/* A loose call whose argument name runs into a tag was a call only as far as its arguments
|
||||
* before it: the call ends there, and the argument's opener and all after it are content. */
|
||||
void end_loose_call_at_arg(bool closed_name) {
|
||||
@@ -1189,21 +1357,40 @@ struct ReplyStream::Impl {
|
||||
|
||||
/* The argument name is complete. */
|
||||
void begin_value() {
|
||||
const std::string_view nm = trim_arg_name(
|
||||
std::string_view nm = trim_arg_name(
|
||||
std::string_view(name).substr(0, name.size() - name_end().size()));
|
||||
param = nullptr;
|
||||
if (const Tool* t = cur_tool()) {
|
||||
auto it = t->params.find(std::string(nm));
|
||||
const bool exact = nm.size() + name_end().size() == name.size();
|
||||
/* The grammar binds a declared name to its own arm by the raw spelling; a name that
|
||||
* only trims to a declared one is read by the generic arm, as text. */
|
||||
if (it != t->params.end() && exact) {
|
||||
param = &it->second;
|
||||
} else if (it == t->params.end() && exact) {
|
||||
/* A name that repeats its own tag's opening, `<parameter=parameter=command>`: the
|
||||
* grammar's undeclared arm takes it, and the call would reach the tool without
|
||||
* the argument it names. Read as that declared argument, leniently. */
|
||||
const std::string_view rep = std::string_view(F.f.arg_prefix).substr(1);
|
||||
std::string_view rest = nm;
|
||||
while (!rep.empty() && rest.size() > rep.size() &&
|
||||
rest.compare(0, rep.size(), rep) == 0)
|
||||
rest.remove_prefix(rep.size());
|
||||
if (rest.size() < nm.size()) {
|
||||
auto jt = t->params.find(std::string(rest));
|
||||
if (jt != t->params.end()) {
|
||||
lenient();
|
||||
nm = rest;
|
||||
param = &jt->second;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::string key = argc > 0 ? "," : "";
|
||||
key += json_quote(nm);
|
||||
key += ':';
|
||||
args_out(key);
|
||||
++argc;
|
||||
param = nullptr;
|
||||
if (const Tool* t = cur_tool()) {
|
||||
auto it = t->params.find(std::string(nm));
|
||||
/* The grammar binds a declared name to its own arm by the raw spelling; a name that
|
||||
* only trims to a declared one is read by the generic arm, as text. */
|
||||
if (it != t->params.end() && nm.size() + name_end().size() == name.size())
|
||||
param = &it->second;
|
||||
}
|
||||
name.clear();
|
||||
if (param && param->typed) {
|
||||
js.reset();
|
||||
@@ -1222,9 +1409,21 @@ struct ReplyStream::Impl {
|
||||
/* A CDATA section is punctuation around any value the format lets carry one, typed or not. */
|
||||
bool cdata() const { return F.f.string_value == ChatValue::Cdata; }
|
||||
|
||||
/* The newline that opens a value is punctuation unless the tag before it has written it
|
||||
* already: Qwen's `<parameter=NAME>\n` ends with the newline the template puts before the
|
||||
* value, and a second one is the value's own. */
|
||||
bool lead_newline() const {
|
||||
const std::string& ne = name_end();
|
||||
return F.f.value_newlines && (ne.empty() || ne.back() != '\n');
|
||||
}
|
||||
|
||||
void begin_value_out(ValueOut::Mode m, bool json = false) {
|
||||
val.begin(m, cdata(), lead_newline(), F.f.value_newlines, scratch, json);
|
||||
}
|
||||
|
||||
void start_text_value(ValueOut::Mode m) {
|
||||
vmode = m;
|
||||
val.begin(m, cdata(), F.f.value_newlines, scratch);
|
||||
begin_value_out(m);
|
||||
flush_scratch();
|
||||
ds = 0;
|
||||
hold.clear();
|
||||
@@ -1232,9 +1431,19 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
|
||||
/* A JSON-typed value that parsed and then met its suffix: the value is the JSON text and the
|
||||
* whitespace after it. */
|
||||
* whitespace after it. What a client's JSON parser takes is a little narrower than what
|
||||
* JsonScan reads as the grammar's JSON -- a number past a double's range (`1e400`), an
|
||||
* unpaired UTF-16 surrogate escape, a vertical tab or form feed after the value -- and such a
|
||||
* value is read by the grammar's other arm, as text, so the arguments stay JSON. */
|
||||
void json_value_done(std::string_view text) {
|
||||
val.begin(ValueOut::Raw, cdata(), F.f.value_newlines, scratch);
|
||||
if (!nlohmann::json::accept(text)) {
|
||||
begin_value_out(ValueOut::Raw);
|
||||
val.add(text.data(), text.size(), scratch);
|
||||
val.finish(false, scratch);
|
||||
flush_scratch();
|
||||
return;
|
||||
}
|
||||
begin_value_out(ValueOut::Raw, /*json=*/true);
|
||||
val.add(text.data(), text.size(), scratch);
|
||||
val.finish(false, scratch);
|
||||
flush_scratch();
|
||||
@@ -1275,7 +1484,11 @@ struct ReplyStream::Impl {
|
||||
const Dfa& d = P.breaks ? F.think_breaks : F.think;
|
||||
p = scan(d, p, e, &hit, [this](const char* q, size_t n) { think_out(q, n); });
|
||||
if (hit == 0) { trail = 0; st = St::ThinkCloseWs; }
|
||||
else if (hit > 0) { att = d.pattern(hit); begin_attempt(St::Think); }
|
||||
else if (hit > 0) {
|
||||
att = d.pattern(hit);
|
||||
att_at = here(p) - att.size();
|
||||
begin_attempt(St::Think);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
@@ -1291,7 +1504,10 @@ struct ReplyStream::Impl {
|
||||
return e;
|
||||
}
|
||||
p = scan(F.text, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); });
|
||||
if (hit >= 0) begin_text_attempt(hit);
|
||||
if (hit >= 0) {
|
||||
att_at = here(p) - F.openers[(size_t)hit].size();
|
||||
begin_text_attempt(hit);
|
||||
}
|
||||
return p;
|
||||
|
||||
case St::OpenCoTail:
|
||||
@@ -1422,9 +1638,12 @@ struct ReplyStream::Impl {
|
||||
const char c = *p;
|
||||
const std::string& ap = F.f.arg_prefix;
|
||||
const std::string& fc = F.end_core;
|
||||
const std::string& cc = F.cc_core;
|
||||
const bool a_ok = lpos < ap.size() && ap[lpos] == c && ap.compare(0, lpos, lhold) == 0;
|
||||
const bool f_ok = lpos < fc.size() && fc[lpos] == c && fc.compare(0, lpos, lhold) == 0;
|
||||
if (!a_ok && !f_ok) {
|
||||
const bool c_ok = wrapped && lpos < cc.size() && cc[lpos] == c &&
|
||||
cc.compare(0, lpos, lhold) == 0;
|
||||
if (!a_ok && !f_ok && !c_ok) {
|
||||
lenient();
|
||||
st = St::Junk;
|
||||
ds = 0;
|
||||
@@ -1438,6 +1657,7 @@ struct ReplyStream::Impl {
|
||||
++lpos;
|
||||
if (a_ok && lpos == ap.size()) { start_arg(); return p + 1; }
|
||||
if (f_ok && lpos == fc.size()) { finish_call_strictness(); end_core_done(); return p + 1; }
|
||||
if (c_ok && lpos == cc.size()) { end_call_at_close(); return p + 1; }
|
||||
return p + 1;
|
||||
}
|
||||
|
||||
@@ -1518,6 +1738,8 @@ struct ReplyStream::Impl {
|
||||
p = scan(F.junk, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); });
|
||||
if (hit == 0) start_arg();
|
||||
else if (hit == 1) end_core_done();
|
||||
else if (hit == 2 && wrapped) end_call_at_close();
|
||||
else if (hit == 2) text_out(F.cc_core.data(), F.cc_core.size());
|
||||
return p;
|
||||
|
||||
case St::AfterEnd:
|
||||
@@ -1673,20 +1895,25 @@ struct ReplyStream::Impl {
|
||||
|
||||
/* ------------------------------------------------------------ driving */
|
||||
|
||||
void run(std::string_view in) {
|
||||
stack.push_back({ in.data(), in.size() });
|
||||
/* Read `in`, whose first byte is at `at` in the stream. */
|
||||
void run(std::string_view in, size_t at) {
|
||||
stack.push_back({ in.data(), in.size(), at });
|
||||
while (!stack.empty()) {
|
||||
Seg s = stack.back();
|
||||
stack.pop_back();
|
||||
seg_p = s.p;
|
||||
seg_at = s.at;
|
||||
const char* p = s.p;
|
||||
const char* e = s.p + s.n;
|
||||
while (p < e) {
|
||||
p = step(p, e);
|
||||
if (!refeed.empty()) {
|
||||
if (p < e) stack.push_back({ p, (size_t)(e - p) });
|
||||
const size_t now = here(p);
|
||||
if (p < e) stack.push_back({ p, (size_t)(e - p), now });
|
||||
owned.push_back(std::move(refeed));
|
||||
refeed.clear();
|
||||
stack.push_back({ owned.back().data(), owned.back().size() });
|
||||
const size_t n = owned.back().size();
|
||||
stack.push_back({ owned.back().data(), n, now >= n ? now - n : 0 });
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1697,7 +1924,13 @@ struct ReplyStream::Impl {
|
||||
void feed_tail() {
|
||||
if (fed_tail) return;
|
||||
fed_tail = true;
|
||||
if (!P.tail.empty()) run(P.tail);
|
||||
if (!P.tail.empty()) run(P.tail, 0);
|
||||
fed = P.tail.size();
|
||||
}
|
||||
|
||||
void feed(std::string_view bytes) {
|
||||
run(bytes, fed);
|
||||
fed += bytes.size();
|
||||
}
|
||||
|
||||
/* Would the grammar still be waiting for more, rather than have failed, on what an opener
|
||||
@@ -1733,7 +1966,7 @@ struct ReplyStream::Impl {
|
||||
fail_attempt();
|
||||
std::string again = std::move(refeed);
|
||||
refeed.clear();
|
||||
run(again);
|
||||
run(again, fed >= again.size() ? fed - again.size() : 0);
|
||||
}
|
||||
switch (st) {
|
||||
case St::OpenWs: case St::OpenPrefix: case St::OpenName: case St::OpenTail:
|
||||
@@ -1757,7 +1990,7 @@ struct ReplyStream::Impl {
|
||||
flush_scratch();
|
||||
break;
|
||||
case St::ValJson:
|
||||
val.begin(ValueOut::Raw, cdata(), F.f.value_newlines, scratch);
|
||||
begin_value_out(ValueOut::Raw);
|
||||
val.add(vheld.data(), vheld.size(), scratch);
|
||||
val.finish(true, scratch);
|
||||
flush_scratch();
|
||||
@@ -1793,7 +2026,7 @@ void ReplyStream::feed(std::string_view bytes, std::vector<ReplyEvent>* out) {
|
||||
if (m.finished) return;
|
||||
m.out = out;
|
||||
m.feed_tail();
|
||||
if (!bytes.empty()) m.run(bytes);
|
||||
if (!bytes.empty()) m.feed(bytes);
|
||||
if (m.cur >= 0) m.publish(m.cur, false);
|
||||
m.out = nullptr;
|
||||
}
|
||||
@@ -1809,16 +2042,31 @@ void ReplyStream::finish(std::vector<ReplyEvent>* out) {
|
||||
}
|
||||
|
||||
const ReplyMessage& ReplyStream::message() const { return impl_->msg; }
|
||||
|
||||
std::string ReplyStream::content_with_open_call(std::string_view reply) const {
|
||||
const Impl& m = *impl_;
|
||||
if (m.msg.calls.empty() || m.msg.calls.back().closed) return m.msg.content;
|
||||
const ReplyCall& c = m.msg.calls.back();
|
||||
std::string s(m.msg.content, 0, std::min(c.content_at, m.msg.content.size()));
|
||||
s += c.content_held;
|
||||
if (c.at < reply.size()) s.append(reply.substr(c.at));
|
||||
m.content.trim(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
bool ReplyStream::strict() const { return impl_->strict; }
|
||||
|
||||
ReplyHeld ReplyStream::held() const {
|
||||
const Impl& m = *impl_;
|
||||
ReplyHeld h;
|
||||
h.delimiter = m.hold.size() + m.lhold.size() + m.val.held() + m.content.held_other() +
|
||||
/* A loose call's first argument name is read into lhold too, and is a tag name: its bytes
|
||||
* are in `att` already, counted as structure. */
|
||||
const size_t lhold = m.st == St::OpenPeekArg ? 0 : m.lhold.size();
|
||||
h.delimiter = m.hold.size() + lhold + m.val.held() + m.content.held_other() +
|
||||
(m.msg.reasoning.size() - m.sent_r) + (m.msg.content.size() - m.sent_c) +
|
||||
(m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a);
|
||||
h.space = m.content.held_space() + m.think_pend.size();
|
||||
h.structure = m.att.size() + m.name.size() + m.vheld.size();
|
||||
h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container();
|
||||
return h;
|
||||
}
|
||||
|
||||
|
||||
+14
-1
@@ -45,7 +45,9 @@
|
||||
* * a tag's own name while it is being read, since a name is only a name once it is closed;
|
||||
* * a JSON-typed argument value until its closing delimiter: `30` and `30 seconds` differ from
|
||||
* their first byte (a number, or the string "30 seconds"), so the value is emitted whole once
|
||||
* its type is known. A value that stops being JSON part-way is streamed as text from there.
|
||||
* its type is known. A value that stops being JSON part-way is streamed as text from there,
|
||||
* except a container (`[`, `{`), which is held to its end: only there is it known whether
|
||||
* it is JSON once its Python quoting is normalised, or the JSON string of its text.
|
||||
*
|
||||
* Streaming emits in the reply's order; a call's arguments are streamed as they are parsed. */
|
||||
#pragma once
|
||||
@@ -81,6 +83,12 @@ struct ReplyCall {
|
||||
std::string name;
|
||||
std::string arguments; /* JSON text, as the OpenAI API carries it */
|
||||
bool closed = false;
|
||||
/* Where the call's text begins in the reply, and the content up to it: `content_at` bytes
|
||||
* of the message's content and the untrimmed whitespace held after them. What the content
|
||||
* is when the call is read as text (ReplyStream::content_with_open_call). */
|
||||
size_t at = 0;
|
||||
size_t content_at = 0;
|
||||
std::string content_held;
|
||||
};
|
||||
|
||||
/* A reply, taken apart. After finish() it is the whole reply; before, what has been emitted. */
|
||||
@@ -179,6 +187,11 @@ public:
|
||||
void finish(std::vector<ReplyEvent>* out);
|
||||
|
||||
const ReplyMessage& message() const;
|
||||
/* After finish(): the content were the last call text, when the reply ended inside that call
|
||||
* -- the content before it, then the call as `reply` (every byte fed) spells it, trimmed at
|
||||
* the end as content is. A call that never closed cannot be reported as a call, and its text
|
||||
* is what the model wrote. The message's content when the last call closed, or there is none. */
|
||||
std::string content_with_open_call(std::string_view reply) const;
|
||||
/* False once the reply left the format's grammar and was read by a recovery rule. */
|
||||
bool strict() const;
|
||||
ReplyHeld held() const;
|
||||
|
||||
+32
-18
@@ -69,16 +69,28 @@ std::string byte_encode(std::string_view raw) {
|
||||
* user-defined token spelt in real text needs; it cannot be confused with a mapped one because
|
||||
* the mapped set is closed. */
|
||||
std::string byte_decode(const std::string& enc) {
|
||||
/* Unit by unit, a unit being what the lead byte says, cut short at the end. A unit is mapped
|
||||
* iff it is exactly some byte's spelling in the alphabet -- one ASCII byte, or a two-byte
|
||||
* sequence (lead C2..DF, a continuation byte) whose code point is below U+0144 -- so the
|
||||
* code point table answers what a lookup of the unit's bytes in `from` would, without
|
||||
* building a string per character. Anything else is passed through as its own bytes. */
|
||||
const ByteLevelAlphabet& a = alphabet();
|
||||
const uint8_t* p = (const uint8_t*)enc.data();
|
||||
const size_t n = enc.size();
|
||||
std::string out;
|
||||
out.reserve(enc.size());
|
||||
for (size_t i = 0; i < enc.size(); ) {
|
||||
const size_t n = std::min(unicode_len_utf8(enc[i]), enc.size() - i);
|
||||
const std::string one = enc.substr(i, n);
|
||||
auto it = a.from.find(one);
|
||||
if (it != a.from.end()) out += (char)it->second;
|
||||
else out += one;
|
||||
i += n;
|
||||
out.reserve(n);
|
||||
for (size_t i = 0; i < n; ) {
|
||||
const size_t len = std::min(unicode_len_utf8(enc[i]), n - i);
|
||||
int b = -1;
|
||||
if (len == 1 && p[i] < 0x80) {
|
||||
b = a.byte_of_cpt[p[i]];
|
||||
} else if (len == 2 && p[i] >= 0xC2 && (p[i + 1] & 0xC0) == 0x80) {
|
||||
const uint32_t c = ((uint32_t)(p[i] & 0x1F) << 6) | (p[i + 1] & 0x3F);
|
||||
if (c < 0x144) b = a.byte_of_cpt[c];
|
||||
}
|
||||
if (b >= 0) out += (char)b;
|
||||
else out.append(enc, i, len);
|
||||
i += len;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -1568,14 +1580,15 @@ std::string utf8_sanitize(std::string_view s) {
|
||||
std::string Detokenizer::push(int32_t token) {
|
||||
if (!v_ || !v_->ready() || stopped_) return {};
|
||||
|
||||
Tokenizer t;
|
||||
/* Constructing a Tokenizer per push looks wasteful and is not: it holds a shared_ptr and
|
||||
* nothing else, and piece() is a pure function of the vocab. Keeping one as a member would
|
||||
* make Detokenizer non-copyable for no gain. */
|
||||
if (t.init(std::const_pointer_cast<Vocab>(std::const_pointer_cast<const Vocab>(v_))) < 0)
|
||||
return {};
|
||||
|
||||
std::string p = t.piece(token, render_special_ || preserved_.count(token) != 0);
|
||||
/* One Tokenizer for the stream, set up on the first push: it holds the vocab's shared_ptr
|
||||
* and nothing else, and piece() is a pure function of the vocab, so one built per push only
|
||||
* added a reference-count round trip to every token. */
|
||||
if (!tok_ready_) {
|
||||
if (tok_.init(v_) < 0) return {};
|
||||
tok_ready_ = true;
|
||||
}
|
||||
std::string p = tok_.piece(token, render_special_ ||
|
||||
(!preserved_.empty() && preserved_.count(token) != 0));
|
||||
|
||||
/* HuggingFace's decoders strip the leading space that Metaspace's prepend added. Only the
|
||||
* first piece of a stream can carry it, which is why this is a member flag and not a
|
||||
@@ -1613,9 +1626,10 @@ std::string Detokenizer::push(int32_t token) {
|
||||
|
||||
const size_t cut = safe_prefix();
|
||||
if (cut == 0) return {};
|
||||
std::string out = pending_.substr(0, cut);
|
||||
/* Sanitised straight out of pending_, which keeps its storage for the next token. */
|
||||
std::string out = utf8_sanitize(std::string_view(pending_).substr(0, cut));
|
||||
pending_.erase(0, cut);
|
||||
return utf8_sanitize(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string Detokenizer::flush() {
|
||||
|
||||
@@ -264,6 +264,8 @@ private:
|
||||
std::string stop_hit_;
|
||||
size_t max_stop_ = 0;
|
||||
bool first_ = true;
|
||||
Tokenizer tok_; /* over v_, set up by the first push */
|
||||
bool tok_ready_ = false;
|
||||
|
||||
size_t safe_prefix() const; /* how much of pending_ can be released */
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user