Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+7
-16
@@ -11,11 +11,8 @@ 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. */
|
||||
/* Pinned or nothing: an async copy to pageable memory serialises against the stream, so a
|
||||
* pageable fallback would run the store at a fraction of its budgeted rate. */
|
||||
base_ = rad_dev_alloc(n * slot_bytes, RAD_MEM_HOST_PINNED);
|
||||
if (!base_) return RAD_E_NOMEM;
|
||||
slot_bytes_ = slot_bytes;
|
||||
@@ -36,15 +33,9 @@ void HostArena::close() {
|
||||
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. */
|
||||
/* First free run at or after the cursor, wrapping once. A fully used word is skipped in one
|
||||
* compare, so a nearly full arena costs one bitmap scan. The cursor makes consecutive calls hand
|
||||
* out consecutive slots, so a batch transfers as one copy per run. */
|
||||
int32_t HostArena::alloc_run(int32_t want, int32_t* got) {
|
||||
*got = 0;
|
||||
if (want <= 0 || !base_ || full()) return -1;
|
||||
@@ -73,8 +64,8 @@ int32_t HostArena::alloc_run(int32_t want, int32_t* got) {
|
||||
|
||||
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. */
|
||||
/* A double free is ignored so the used count, which `full` and the sessions view read, stays
|
||||
* correct. */
|
||||
if (!is_used(slot)) return;
|
||||
bits_[(size_t)(slot >> 6)] &= ~(1ull << (slot & 63));
|
||||
--used_;
|
||||
|
||||
+18
-23
@@ -1,21 +1,17 @@
|
||||
/* 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 one slot id -- rank 0's to hand out -- names the object
|
||||
* on every rank.
|
||||
* Backs two stores: the KV tiers' block arena (core/mem/kvtier.h, one slot per cache entry) and
|
||||
* the linear-state snapshot store (KVManager::set_checkpoint_store, one slot per snapshot). Under
|
||||
* tensor parallelism a slot holds every rank's shard of its object, each at its own offset, so
|
||||
* one slot id (handed out by rank 0) names the object on every rank.
|
||||
*
|
||||
* Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the
|
||||
* driver stages an async copy to pageable memory through its own buffer and, on some paths,
|
||||
* 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.
|
||||
* Pinned, because every byte is a PCIe transfer endpoint: the driver stages async copies to
|
||||
* pageable memory through its own buffer and may synchronise. Every object in a store has 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. */
|
||||
* Transfers are per run: with 4-token blocks a 200K-token conversation is 50K entries, and one
|
||||
* copy per entry makes the driver call rate the cost of a restore. Slots allocated together get
|
||||
* consecutive ids where possible, so a batch crosses the link as one strided copy per run. */
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
|
||||
@@ -31,21 +27,20 @@ public:
|
||||
void close();
|
||||
bool enabled() const { return base_ != nullptr; }
|
||||
|
||||
/* Not thread-safe: the owner serialises every call (IdleTiers under its mutex, the snapshot
|
||||
* store on the engine thread). */
|
||||
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 capacity() const { return cap_slots_; } /* fixed at open */
|
||||
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. */
|
||||
/* alloc: -1 when full. The caller evicts and retries; victim policy belongs to the store's
|
||||
* owner, not the allocator. */
|
||||
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() { int32_t got = 0; return alloc_run(1, &got); }
|
||||
/* Up to `want` consecutive slots: the first free run at or after the cursor. `*got` is the
|
||||
* count; the caller asks again for the rest. -1 when 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); }
|
||||
|
||||
+175
-353
File diff suppressed because it is too large.
Load diff
+231
-318
@@ -1,21 +1,19 @@
|
||||
/* kv.h -- the KV block manager (spec §7.2).
|
||||
*
|
||||
* Paged, per KV group, each group with its OWN block geometry, its own pool and its own slot
|
||||
* mapping. Block size comes from KVGroupInfo::block_size, which the build component took off the
|
||||
* resolved attention kernel's constraints -- never a core constant. A core that picked its own
|
||||
* block size would be a core that has to be edited when a kernel changes.
|
||||
* Paged per KV group; each group has its own block geometry, pool and slot mapping. Block size
|
||||
* comes from KVGroupInfo::block_size, taken from the resolved attention kernel's constraints,
|
||||
* never from a core constant, so a kernel change needs no core edit.
|
||||
*
|
||||
* Hybrid models are the normal case, not an extension. Four state kinds:
|
||||
* Four state kinds (hybrid models are the normal case):
|
||||
*
|
||||
* RAD_KV_FULL paged, per-token, growing
|
||||
* RAD_KV_WINDOW paged, per-token, bounded by the window -- blocks below the window are recycled
|
||||
* RAD_KV_LINEAR per-sequence, FIXED size: the GDN recurrent state
|
||||
* RAD_KV_CONV per-sequence, FIXED size: a rolling window of conv_width-1 + n_spec entries
|
||||
* RAD_KV_WINDOW paged, per-token, bounded by the window; blocks below the window are recycled
|
||||
* RAD_KV_LINEAR per-sequence, fixed size: the GDN recurrent state
|
||||
* RAD_KV_CONV per-sequence, fixed size: a rolling window of conv_width-1 + n_spec entries
|
||||
*
|
||||
* The last two are not paged the same way, and they are allocated, mapped and freed BY THIS
|
||||
* MANAGER anyway, because otherwise two allocators disagree about what a sequence owns. That
|
||||
* disagreement is not a memory leak, it is a correctness bug: the scheduler frees a sequence and
|
||||
* one of the two allocators keeps handing its state slot to the next request.
|
||||
* The two stateful kinds are also allocated, mapped and freed here, so one allocator decides what
|
||||
* a sequence owns. With two, a freed sequence's state slot could still be handed to the next
|
||||
* request by the other.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/hostarena.h"
|
||||
@@ -30,22 +28,14 @@
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ group sizing */
|
||||
/* vLLM slices a hybrid model's layers into equal-sized groups and PADS each bundle up to a
|
||||
* multiple of that size -- and a padding layer is allocated real memory. On a 48 linear / 16 full
|
||||
* / 5 drafter model its rule ("group size = the smallest bundle") picks 5, which divides neither
|
||||
* 48 nor 16, so it allocates 15 groups x 5 = 75 slots for 69 real layers, and rounds the
|
||||
* per-request requirement up once per group -- fifteen round-ups on every request, which is where
|
||||
* most of the loss actually is. Replacing that rule with a least-waste search recovers a
|
||||
* substantial fraction of the KV tokens at a byte-identical budget.
|
||||
/* Layer bundling compared with vLLM. vLLM splits a hybrid model's layers into equal-sized groups
|
||||
* and pads each bundle to a multiple of that size with real memory: on a 48 linear / 16 full /
|
||||
* 5 drafter model its rule picks size 5, giving 15 groups x 5 = 75 slots for 69 layers and a
|
||||
* per-request round-up per group. A least-waste search recovers part of that.
|
||||
*
|
||||
* Radiance does not need the search, because it does not have the constraint the search works
|
||||
* around. A KV group here is one state kind with one geometry and ITS OWN POOL (spec §7.2), so
|
||||
* there is no uniform page size to pad up to and no reason to subdivide a bundle: every state
|
||||
* kind is exactly one group covering exactly its own layers. Padding is structurally zero and the
|
||||
* group count is structurally minimal.
|
||||
*
|
||||
* This struct exists so `--debug-placement` can print that claim next to what vLLM would have
|
||||
* done, and so the test can assert it rather than trusting the comment. */
|
||||
* Here each state kind is one group with its own pool (spec §7.2), so there is no uniform page
|
||||
* size to pad to: padding is zero and the group count is minimal. This struct lets
|
||||
* `--debug-placement` print the comparison and lets a test assert it. */
|
||||
struct BundleComparison {
|
||||
std::vector<int64_t> bundles; /* layers per state kind, as declared */
|
||||
int64_t stock_group_size = 0; /* vLLM's rule: the smallest bundle (with the 1.5x escape) */
|
||||
@@ -55,7 +45,7 @@ struct BundleComparison {
|
||||
int64_t patched_groups = 0;
|
||||
int64_t patched_slots = 0;
|
||||
int64_t our_groups = 0; /* == bundles.size() */
|
||||
int64_t our_slots = 0; /* == sum(bundles); padding is zero by construction */
|
||||
int64_t our_slots = 0; /* == sum(bundles); no padding */
|
||||
std::string report() const;
|
||||
};
|
||||
BundleComparison compare_bundling(const std::vector<int64_t>& bundles);
|
||||
@@ -68,31 +58,28 @@ struct KVGroupPlan {
|
||||
int64_t n_layers = 0;
|
||||
|
||||
int64_t block_size = 0; /* tokens per block, from the resolved kernel */
|
||||
int64_t bytes_per_block = 0; /* covers EVERY layer bound to the group -- see the note
|
||||
* on bundling above: one page, one bundle, no padding */
|
||||
int64_t bytes_per_block = 0; /* covers every layer bound to the group */
|
||||
int64_t bytes_per_state = 0; /* LINEAR/CONV: per sequence, every layer */
|
||||
int64_t conv_slots = 0; /* CONV: conv_width - 1 + n_spec */
|
||||
int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */
|
||||
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Only a trunk
|
||||
* group of a model with no linear state: a prefix hit there resumes at a checkpoint from the
|
||||
* window behind it. A drafter's own window is recomputed by draft refill, and a model with
|
||||
* linear state re-prefills a hit on a windowed trunk, so neither snapshot would ever be read. */
|
||||
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Set only for a
|
||||
* trunk group of a model with no linear state. A drafter's window is recomputed by draft
|
||||
* refill, and a model with linear state re-prefills a hit on a windowed trunk, so neither
|
||||
* snapshot would be read. */
|
||||
bool win_snap = false;
|
||||
|
||||
int64_t n_blocks = 0; /* paged groups: blocks carved from the pool */
|
||||
/* rad_kv_group_zero: this rank keeps no cache for the group. The plan exists for its position
|
||||
* and its block count (one block table serves every rank), its costs are zero and nothing is
|
||||
* carved; no op on this rank names it (issue refuses a group with no pool bound). */
|
||||
/* rad_kv_group_zero: this rank keeps no cache for the group. The plan keeps its position and
|
||||
* block count (one block table serves every rank); its costs are zero and nothing is carved.
|
||||
* No op on this rank names it (issue refuses a group with no pool bound). */
|
||||
bool zero = false;
|
||||
int64_t n_states = 0; /* LINEAR/CONV: n_seq_states * state_copies */
|
||||
/* HOW MANY PHYSICAL SLOTS ONE LOGICAL STATE COSTS. One, normally: a sequence owns a state.
|
||||
* Under speculation a linear kernel needs somewhere to put what it cannot commit yet -- it
|
||||
* has run 1 + n_spec tokens through the recurrence before anyone knows which survive -- and
|
||||
* the scheme libr4d uses keeps the committed state in one slot and the per-token replay
|
||||
* factors in a second, then folds the accepted prefix in at the start of the next step. Two
|
||||
* slots a sequence, not 1 + n_spec: the factors are a few hundred floats a head against a
|
||||
* 128x128 state, so they fit inside a slot with room to spare and the pool grows by 2x
|
||||
* rather than by 9x. Copy k of logical slot s is the physical slot s + k * n_seq_states. */
|
||||
/* Physical slots per logical state: 1, or 2 under speculation. A verify runs 1 + n_spec
|
||||
* tokens through the recurrence before acceptance is known; libr4d keeps the committed state
|
||||
* in copy 0 and the per-token replay factors in copy 1, and folds the accepted prefix in at
|
||||
* the next step. The factors (a few hundred floats a head, against a 128x128 state) fit in
|
||||
* one slot, so the pool grows 2x rather than (1 + n_spec)x. Copy k of logical slot s is
|
||||
* physical slot s + k * n_seq_states. */
|
||||
int64_t state_copies = 1;
|
||||
int64_t n_seq_states() const { return state_copies > 0 ? n_states / state_copies : n_states; }
|
||||
int64_t pool_offset = 0;
|
||||
@@ -102,18 +89,14 @@ struct KVGroupPlan {
|
||||
bool paged() const { return kind == RAD_KV_FULL || kind == RAD_KV_WINDOW; }
|
||||
bool stateful() const { return kind == RAD_KV_LINEAR || kind == RAD_KV_CONV; }
|
||||
|
||||
/* THE POOL IS LAYER-MAJOR, and that is not a free choice -- the ABI already made it. A
|
||||
* RAD_OPK_KV operand carries the LAYER as its offset and the core resolves it as
|
||||
* `base + layer * layer_stride` (RadOperand in rad_runtime.h, KVPoolBinding in
|
||||
* core/runtime/ctx.h), because an attention kernel takes ONE base pointer for the layer it is
|
||||
* running and indexes inside it with the block table and the slot mapping. Interleaving the
|
||||
* layers inside a block would mean every kernel needed the layer count and the bundle stride
|
||||
* as well, to reach the same bytes.
|
||||
/* The pool is layer-major, as the ABI requires: a RAD_OPK_KV operand carries the layer as its
|
||||
* offset and resolves to `base + layer * layer_stride` (RadOperand in rad_runtime.h,
|
||||
* KVPoolBinding in core/runtime/ctx.h), so a kernel gets one base pointer per layer and
|
||||
* indexes it with the block table and slot mapping.
|
||||
*
|
||||
* So layer i owns [base + i*layer_stride, + layer_stride): n_blocks blocks of
|
||||
* Layer i owns [base + i*layer_stride, + layer_stride): n_blocks blocks of
|
||||
* `bytes_per_block / n_layers` for a paged group, n_states states of
|
||||
* `bytes_per_state / n_layers` for a stateful one. The totals are identical either way, which
|
||||
* is why sizing does not care and addressing does. */
|
||||
* `bytes_per_state / n_layers` for a stateful one. */
|
||||
int64_t layer_bytes_per_block() const {
|
||||
return n_layers > 0 ? bytes_per_block / n_layers : bytes_per_block;
|
||||
}
|
||||
@@ -126,28 +109,21 @@ struct KVGroupPlan {
|
||||
};
|
||||
|
||||
/* A copy the caller must execute on its copy stream before the destination block is read. The
|
||||
* manager does not issue device copies itself: it has no stream, and a memcpy on the step path is
|
||||
* a synchronisation the engine spends its whole design avoiding (spec §5.4). */
|
||||
* manager has no stream and issues no device copies, since a memcpy on the step path would
|
||||
* synchronise (spec §5.4). */
|
||||
struct BlockCopy {
|
||||
int32_t group = -1;
|
||||
int32_t src_block = -1;
|
||||
int32_t dst_block = -1;
|
||||
};
|
||||
|
||||
/* A STATE SLOT THAT STILL HOLDS THE PREVIOUS TENANT'S HISTORY. The manager names the work and the
|
||||
* engine issues it, for the same reason BlockCopy exists: no stream here, and a synchronisation on
|
||||
* the step path is what this design spends itself avoiding (spec §5.4).
|
||||
/* A state slot that still holds the previous tenant's state and must be zeroed before first use.
|
||||
* The manager names the work and the engine issues it, as with BlockCopy.
|
||||
*
|
||||
* WHY A RECURRENT SLOT HAS TO BE CLEARED AND A PAGED ONE DOES NOT. A paged sequence reads only the
|
||||
* blocks its own block table names, so a recycled block is unreachable until it is written. A
|
||||
* recurrent sequence has no table: `gdn_chunk_scan` reads `h0` out of the slot and there is no
|
||||
* operand in its schema that says "this sequence has none". An uncleared slot IS the last
|
||||
* sequence's entire compressed history, so the second request a server answers silently continues
|
||||
* the first: the same prompt gives a different distribution on a fresh process than it does after
|
||||
* another request has run.
|
||||
*
|
||||
* The conv group carries `has_init` and does not need this. It is cleared anyway: two rules about
|
||||
* one pool is how one of them rots. */
|
||||
* A paged sequence reads only the blocks its table names, so a recycled block is unreachable
|
||||
* until written. A recurrent slot has no table: `gdn_chunk_scan` reads `h0` from the slot and has
|
||||
* no operand for "no initial state", so an uncleared slot continues the previous sequence's
|
||||
* history. Conv slots carry `has_init` but are cleared too, so one rule covers the pool. */
|
||||
struct StateClear {
|
||||
int32_t group = -1;
|
||||
int32_t slot = -1;
|
||||
@@ -156,41 +132,37 @@ struct StateClear {
|
||||
/* ------------------------------------------------------------------ manager */
|
||||
class KVManager {
|
||||
public:
|
||||
/* Sizes every group out of one pool and refuses, by name and by how much, if the fixed costs
|
||||
* alone do not fit. The split between the paged groups is not a policy: they are sized to
|
||||
* exhaust at the same total token count, and any other split strands memory in whichever
|
||||
* group outlasts the others.
|
||||
/* Sizes every group out of one pool, refusing by name and shortfall if the fixed costs alone
|
||||
* do not fit. The paged groups are sized to run out at the same total token count; any other
|
||||
* split strands memory in whichever group outlasts the others.
|
||||
*
|
||||
* The byte budget is the budget resolver's and is not re-derived here: it is whatever
|
||||
* `kv_pool` still has (vram_kv). 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). */
|
||||
* The budget is whatever `kv_pool` has left (vram_kv), as the budget resolver set it.
|
||||
* Linear-state snapshots live in pinned host memory (set_checkpoint_store), so the pool holds
|
||||
* only the live cache (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
|
||||
* from the declaration and the run configuration -- no pool, no bytes -- and ceiling() then
|
||||
* says what a FULL cache for `ctx` tokens on max_seqs sequences would cost. Pools are
|
||||
* allocated before carve() runs, so the KV pool has to be decided from these two
|
||||
* and nothing else (core/mem/vram_budget.cpp). carve() spends the pool it is given. */
|
||||
/* configure() in two steps for the budget resolver. plan_groups() sizes every group from the
|
||||
* declaration and run configuration (no pool), and ceiling() gives the cost of a full cache
|
||||
* for `ctx` tokens on max_seqs sequences. Pools are allocated before carve(), so the KV pool
|
||||
* is sized and capped from these two alone (core/mem/vram_budget.cpp); VRAM above the ceiling
|
||||
* would never be addressed. carve() spends the pool it is given. */
|
||||
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, and the padding. Set by plan_groups(). */
|
||||
/* The context-independent part of every ceiling: recurrent and conv state for max_seqs
|
||||
* sequences, plus alignment 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.
|
||||
* 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. */
|
||||
/* The token count the paged groups settle on for `budget_bytes` of pool (carve()'s split,
|
||||
* without carving). One block table serves every rank, so all ranks must hold the same block
|
||||
* count, but under an uneven tensor-parallel split their pools differ. The engine asks every
|
||||
* rank and passes the least to cap_paged_tokens() before carve(); 0 is no cap.
|
||||
* kUnboundedTokens when every paged group on this rank is zero (rad_kv_group_zero): this rank
|
||||
* then limits nothing. */
|
||||
static constexpr int64_t kUnboundedTokens = INT64_MAX;
|
||||
int64_t paged_tokens(int64_t budget_bytes) const { return paged_split(budget_bytes, nullptr); }
|
||||
/* THE INVERSE OF paged_tokens: the least whole MiB of pool whose paged split reaches `tokens`,
|
||||
* searched up to max_mib; -1 when even max_mib does not. Pure arithmetic on the plan (no pool,
|
||||
* no cap), for Engine::plan sizing an uneven world's cheaper rank to the token count its
|
||||
* dearest peer sets. paged_split is monotone in the budget, so the search is exact. */
|
||||
/* Inverse of paged_tokens: the least whole MiB of pool whose paged split reaches `tokens`,
|
||||
* searched up to max_mib; -1 if max_mib does not reach it. Pure arithmetic on the plan, used
|
||||
* by Engine::plan to size a cheaper rank to the token count of its dearest peer. Exact,
|
||||
* because paged_split is monotone in the budget. */
|
||||
int64_t pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const;
|
||||
void cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; }
|
||||
int carve(Pool& kv_pool);
|
||||
@@ -198,44 +170,39 @@ public:
|
||||
const std::vector<KVGroupPlan>& plans() const { return plans_; }
|
||||
const KVGroupPlan* plan(int32_t group) const;
|
||||
int32_t n_groups() const { return (int32_t)plans_.size(); }
|
||||
const BundleComparison& bundling() const { return bundling_; }
|
||||
std::string report() const;
|
||||
|
||||
/* ---------------- sequences ---------------- */
|
||||
int add_sequence(uint64_t seq);
|
||||
bool has_sequence(uint64_t seq) const;
|
||||
void free_sequence(uint64_t seq);
|
||||
/* HOW MANY TIMES A SEQUENCE HAS LET GO OF ITS BLOCKS -- freed or preempted -- over the life of
|
||||
* the manager. A block's reference count falls for no other reason the prefix cache cannot
|
||||
* see, so this is what tells it a block it found shared may no longer be. */
|
||||
/* Count of sequence frees and preemptions over the manager's life. These are the only
|
||||
* refcount drops the prefix cache cannot see, so a change tells it a block it saw shared may
|
||||
* no longer be. */
|
||||
uint64_t seq_frees() const { return seq_frees_; }
|
||||
|
||||
/* Grow the sequence's mapping to cover `n_tokens` in every group. Unshares a shared partial
|
||||
* block first (copy-on-write) and appends the copy request to the pending list.
|
||||
* RAD_E_FULL when a group's free list is empty -- the caller preempts and retries.
|
||||
*
|
||||
* `keep_from` is the position of the FIRST query the coming step runs (the scheduler's
|
||||
* n_computed); -1 means the sequence's current end. A WINDOW group recycles only the blocks no
|
||||
* query at or past it can read -- below keep_from - window + 1 -- and NOT the blocks below the
|
||||
* window of the step's END: a prefill chunk longer than a block would otherwise lose the keys
|
||||
* its first rows attend to (a chunk of C tokens from position 0 rebased the table at
|
||||
* ceil(C/block) - window_blocks and left every position below it with no KV at all). */
|
||||
* `keep_from` is the position of the first query the coming step runs (the scheduler's
|
||||
* n_computed); -1 means the sequence's current end. A WINDOW group recycles only blocks below
|
||||
* keep_from - window + 1, not below the window of the step's end, which would drop keys the
|
||||
* first rows of a multi-block prefill chunk still read. */
|
||||
int ensure(uint64_t seq, int64_t n_tokens, int64_t keep_from = -1);
|
||||
|
||||
/* A WINDOW group's caps: a sequence holds its window behind the step's first query AND the
|
||||
* step's own tokens (window_blocks + ceil(max_tok / block) + 1 at most), and one step carries
|
||||
* at most max_tok tokens across every sequence in it, so the pool needs max_seqs windows plus
|
||||
* one step's worth on top. */
|
||||
/* A WINDOW group's caps. A sequence holds the window behind the step's first query plus the
|
||||
* step's own tokens (at most window_blocks + ceil(max_tok / block) + 1), and one step carries
|
||||
* at most max_tok tokens in total, so the pool needs max_seqs windows plus one step. */
|
||||
int64_t window_seq_cap(const KVGroupPlan& p) const;
|
||||
int64_t window_pool_cap(const KVGroupPlan& p) const;
|
||||
/* ceil(max_tok / block): the blocks one step's tokens can fill. */
|
||||
int64_t step_blocks(const KVGroupPlan& p) const;
|
||||
|
||||
/* GIVE BACK A FINISHED CHUNK'S BLOCKS once it is committed. ensure() keeps a chunk's own blocks
|
||||
* beside the window behind its first query, and only the sequence's NEXT ensure() recycles
|
||||
* them -- so a prefill waiting a step for its next chunk would sit on a whole chunk of window
|
||||
* blocks while other sequences prefill, and eight of them exhaust the pool (measured on
|
||||
* Gemma 4: "the KV pool cannot hold 12480 tokens" with eight 16K prompts). Called by the
|
||||
* scheduler when it advances n_computed: keep_from is the new n_computed, the first query any
|
||||
* later step can run. */
|
||||
/* Recycles a committed chunk's window blocks. ensure() keeps a chunk's blocks beside the
|
||||
* window and only the next ensure() recycles them, so a prefill waiting for its next chunk
|
||||
* would hold a whole chunk of blocks; several such prefills can exhaust the pool. The
|
||||
* scheduler calls this when it advances n_computed, passing the new n_computed. */
|
||||
void trim_window(uint64_t seq, int64_t keep_from);
|
||||
|
||||
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
|
||||
@@ -243,45 +210,41 @@ public:
|
||||
* corrupt the cache entry. Bumps each block's refcount. */
|
||||
int adopt(uint64_t seq, int32_t group, const std::vector<int32_t>& blocks, int64_t n_tokens);
|
||||
|
||||
/* Fork: the child shares every WHOLE block of the parent and gets its own copy of the
|
||||
* partial one on first write (copy-on-write, spec §7.3). Stateful groups cannot be shared --
|
||||
* a recurrent state is one object, not a chain -- so the child gets its own slot and the
|
||||
* caller must snapshot-restore into it. */
|
||||
/* The child shares every whole block of the parent and copies the partial one on first write
|
||||
* (spec §7.3). A recurrent state cannot be shared, so the child gets its own slot and the
|
||||
* caller must restore a snapshot into it. */
|
||||
int fork(uint64_t parent, uint64_t child);
|
||||
|
||||
std::vector<BlockCopy> take_pending_copies();
|
||||
|
||||
/* The prefix cache's handle on a block. It holds a reference on every block it indexes, and
|
||||
* that reference is the invariant that makes a hit safe: a block named by the cache is never
|
||||
* in the free list, so it can never be handed to another sequence underneath a cache entry.
|
||||
* Nothing else in the engine may call these -- the block table is the manager's property. */
|
||||
/* TAKE A FREE BLOCK, with no sequence attached to it yet. The idle-session tiers need this
|
||||
* and nothing else does: a restore has bytes to put somewhere before any sequence has asked
|
||||
* for them, and the prefix cache takes the reference afterwards. Every other caller reaches
|
||||
* blocks through a sequence, which is why grab_block itself stays private -- this is the one
|
||||
* documented way to hold a block that no Seq owns, and the holder is responsible for
|
||||
* release_block if the restore then fails. */
|
||||
/* Prefix-cache and tier access to blocks. The cache holds a reference on every block it
|
||||
* indexes, so a cached block is never in the free list and cannot be handed to another
|
||||
* sequence under a cache entry. Nothing else may call these. */
|
||||
/* Takes a free block with no sequence attached, for the idle-session tiers: a restore needs
|
||||
* somewhere to put bytes before any sequence asks for them, and the prefix cache takes the
|
||||
* reference afterwards. The holder must release_block() if the restore fails. Does not
|
||||
* recall the loan; it stops at what the cache keeps in hand. */
|
||||
int reserve_block(int32_t group, int32_t* out);
|
||||
/* THE SAME FOR A WHOLE CHAIN AT ONCE: up to `n` blocks appended to `out`, and how many. The
|
||||
* loan is recalled for all of them before the first is taken, because a restore is sized
|
||||
* before it starts and one recall a block would drain the slab a buffer at a time -- the
|
||||
* reserve above stops at whatever the cache kept in hand. */
|
||||
/* Up to `n` blocks appended to `out`; returns how many. Recalls the loan for all of them up
|
||||
* front, since a block-at-a-time recall would drain the slab one buffer at a time. */
|
||||
int64_t reserve_blocks(int32_t group, int64_t n, std::vector<int32_t>* out);
|
||||
/* The same, for a block another rank already chose. See the definition. */
|
||||
/* Takes one particular block another rank already chose. Block ids are shared across ranks
|
||||
* (RadBatch carries one table), so under tensor parallelism rank 0 picks and the others take
|
||||
* the same id. Refuses (RAD_E_STATE) a held block or one above the live mark rather than
|
||||
* substituting, since a rank restoring into a different block would corrupt only that rank's
|
||||
* output. */
|
||||
int reserve_specific_block(int32_t group, int32_t block);
|
||||
/* The cache's reference on a block a sequence already holds. The block is marked as the
|
||||
* cache's for cache_only_blocks(). */
|
||||
int retain_block(int32_t group, int32_t block);
|
||||
/* A reserved block's reference handed to the cache as it stands: marked, not counted again. */
|
||||
void cache_reserved_block(int32_t group, int32_t block);
|
||||
/* Lets go of the cache's reference on a marked block and of a reservation's on any other. */
|
||||
/* Releases the cache's reference on a marked block, or a reservation's on any other. */
|
||||
void release_block(int32_t group, int32_t block);
|
||||
int32_t block_refcount(int32_t group, int32_t block) const;
|
||||
/* BLOCKS ONLY THE CACHE HOLDS: marked, and at a reference count of one. This is what an
|
||||
* eviction would give back, and what a dashboard reports as cache rather than as context.
|
||||
* Kept current at every reference-count change so that reading it costs nothing: the figure
|
||||
* is read while the scheduler's lock is held, and a walk of the cache to compute it would
|
||||
* stall the step for as long as it ran. */
|
||||
/* Blocks only the cache holds: marked, at refcount one. This is what an eviction would free.
|
||||
* Maintained at every refcount change because it is read under the scheduler's lock, where a
|
||||
* walk of the cache would stall the step. */
|
||||
int64_t cache_only_blocks(int32_t group) const;
|
||||
|
||||
const std::vector<int32_t>& block_table(uint64_t seq, int32_t group) const;
|
||||
@@ -298,168 +261,132 @@ public:
|
||||
/* ---------------- accounting ---------------- */
|
||||
int64_t free_blocks(int32_t g) const;
|
||||
|
||||
/* HOW MANY BLOCKS OF A GROUP ANYTHING IS HOLDING. free_blocks() is what may be handed out
|
||||
* RIGHT NOW, which while the cache is lending is bounded by the live mark and not by the
|
||||
* carve, so `carve - free` counts every lent block as occupied -- an idle server reading 97%
|
||||
* full. The occupancy question wants this instead: a lent block is neither held nor
|
||||
* unavailable, because the loan is recalled on demand up to the carve. */
|
||||
/* Blocks of a group that something holds. Use this for occupancy, not `carve - free`:
|
||||
* free_blocks() is bounded by the live mark while the cache lends, so that difference would
|
||||
* count lent blocks as occupied. */
|
||||
int64_t held_blocks(int32_t g) const;
|
||||
|
||||
/* The carve: the range every block id is addressed against. live_blocks() is what the cache
|
||||
* keeps unlent. */
|
||||
int64_t total_blocks(int32_t group) const;
|
||||
int64_t free_states(int32_t group) const;
|
||||
|
||||
/* THE POOL IN BYTES, WHICH IS THE ONLY UNIT THE GROUPS CAN BE ADDED IN. Blocks cannot be:
|
||||
* a paged group and a stateful one count different objects, and two paged groups share ONE
|
||||
* token axis -- a token of context takes a slot in each of them -- so summing either measure
|
||||
* reports a pool several times the size of the one the card holds. Bytes are disjoint VRAM
|
||||
* and add up.
|
||||
/* Pool size in bytes, the only unit in which groups can be summed: paged and stateful groups
|
||||
* count different objects, and paged groups share one token axis.
|
||||
*
|
||||
* The used figure is what is HELD rather than what is reachable: a block a sequence owns and
|
||||
* a block only the prefix cache still references both count, because both are VRAM the next
|
||||
* request cannot be given. A block stops counting the moment it reaches the free list,
|
||||
* whether it got there because its sequence ended, because the cache evicted it, or because
|
||||
* the idle tiers copied it to host memory and released it. */
|
||||
* pool_bytes() excludes lent blocks, which the expert slab reports as its own. Used bytes
|
||||
* count held blocks, owned by a sequence or referenced only by the prefix cache; a block
|
||||
* stops counting when it reaches the free list. */
|
||||
int64_t pool_bytes(int32_t group) const;
|
||||
int64_t pool_bytes_used(int32_t group) const;
|
||||
/* THE CARVE, which the cache may not be keeping. pool_bytes() is what the cache keeps for
|
||||
* itself right now; this is what the operator budget gave it to address, and the difference
|
||||
* between them is what it has lent to the expert slab. */
|
||||
/* Bytes the budget carved for the group; the difference from pool_bytes() is lent to the
|
||||
* expert slab. */
|
||||
int64_t pool_bytes_carved(int32_t group) const;
|
||||
int64_t blocks_for(int32_t group, int64_t n_tokens) const;
|
||||
|
||||
/* Could a sequence of this length EVER fit, in an empty pool? If not, preempting the whole
|
||||
* server would not help and the request is failed immediately rather than the engine
|
||||
* deadlocking on it (spec §17). */
|
||||
/* Whether a sequence of this length fits an empty pool. If not, preemption cannot help and
|
||||
* the request is failed rather than deadlocking the engine (spec §17). */
|
||||
bool can_ever_fit(int64_t n_tokens) const;
|
||||
|
||||
/* ---------------- the loan ----------------
|
||||
*
|
||||
* THE PAGED GROUPS LEND THE EXPERT SLAB WHAT NOTHING HOLDS, AT THE ADDRESSES THEY ALREADY
|
||||
* OWN. The carve decides every address once and backs all of it before anything runs, and
|
||||
* nothing here ever unmaps it. What moves is only how many of a group's blocks the cache may
|
||||
* hand out: the blocks above that mark, in every layer's stripe, are where the slab keeps
|
||||
* expert units -- units the MoE GEMM would otherwise read across the link on every step that
|
||||
* routes to them. No memory is allocated or released in either direction, so no driver call
|
||||
* is made and what the card reports free never changes.
|
||||
* The paged groups lend unheld blocks to the expert slab in place. The carve fixes and backs
|
||||
* every address once and nothing here unmaps it; the loan only lowers how many of a group's
|
||||
* blocks the cache may hand out (the live mark). The slab keeps expert units in the blocks
|
||||
* above the mark in every layer's stripe, so the MoE GEMM need not read them across the link.
|
||||
* No memory is allocated or freed either way, so the loan makes no driver call.
|
||||
*
|
||||
* THE LOAN IS STATED IN TOKENS, counted down from the top of the carve. The FULL groups are
|
||||
* sized to run out at the same total token count (carve()), so one number is the same depth
|
||||
* in each of them: a loan of T tokens is the top floor(T / block_size) blocks of every FULL
|
||||
* group. A WINDOW group is sized per sequence rather than on that axis and is never lent.
|
||||
* The loan is in tokens, counted down from the top of the carve. FULL groups are sized to run
|
||||
* out at the same token count, so a loan of T tokens is the top floor(T / block_size) blocks
|
||||
* of every FULL group. WINDOW groups are sized per sequence and never lent.
|
||||
*
|
||||
* A BLOCK IS NOT LENT WHILE ANYTHING HOLDS IT, and a held block is a block a sequence owns OR
|
||||
* one the prefix cache still indexes. So a loan cannot evict anything: it is a claim on what
|
||||
* is free. Everything that makes a block free -- a sequence ending, an eviction, an idle-tier
|
||||
* demotion to host memory -- makes it lendable, and the min-heap free list is what
|
||||
* keeps the free blocks at the top, where a loan can reach them.
|
||||
* A held block (owned by a sequence or indexed by the prefix cache) is never lent, so a loan
|
||||
* evicts nothing. The min-heap free list keeps free blocks at the top, where a loan reaches
|
||||
* them.
|
||||
*
|
||||
* THE BUFFER IS DERIVED AND NOT STATED. It is the free blocks the cache keeps in hand so that
|
||||
* a request finds room without a recall, and the right size for it is a property of the
|
||||
* workload rather than a number an operator can know: one prefill chunk -- the most KV a
|
||||
* single step can consume -- or the largest recent shortfall, whichever is larger. The second
|
||||
* term decays, so an idle server settles at the floor and a ramping one has the buffer
|
||||
* leading the ramp. */
|
||||
* The buffer is the free blocks the cache keeps in hand so a request finds room without a
|
||||
* recall: the larger of one prefill chunk (the most one step consumes) and the largest recent
|
||||
* shortfall. The shortfall term decays, so an idle server settles at the floor. */
|
||||
int64_t buffer_bytes() const;
|
||||
|
||||
/* Is this group lent from? The FULL paged groups, and only those. */
|
||||
/* True for the FULL paged groups only. */
|
||||
bool lendable(int32_t group) const;
|
||||
|
||||
/* HOW MUCH THE CACHE CAN LEND RIGHT NOW, in tokens: the smallest distance, over the lendable
|
||||
* groups, from the top of the carve down to the highest block anything holds plus the buffer.
|
||||
* Rank 0 only -- a follower's held history is empty. Also where the buffer's trend term
|
||||
* decays, so it is called once per arbiter tick. */
|
||||
/* Tokens the cache can lend now: over the lendable groups, the least distance from the top of
|
||||
* the carve down to the highest held block plus the buffer. Rank 0 only (a follower tracks no
|
||||
* held blocks). Also decays the buffer's shortfall term, so call it once per arbiter tick. */
|
||||
int64_t spare_tokens();
|
||||
|
||||
/* LEND `tokens` FROM THE TOP, or take back what a smaller number no longer covers. Lending
|
||||
* past a held block is refused (RAD_E_STATE): the arbiter asked for more than spare_tokens()
|
||||
* said there was. Taking back is always allowed here, and it is the caller's to make true --
|
||||
* the slab must have left those blocks before this runs. */
|
||||
/* Lends `tokens` from the top, or takes back what a smaller number no longer covers. Lending
|
||||
* past a held block is refused (RAD_E_STATE). Taking back always succeeds here; the caller
|
||||
* must have moved the slab out of those blocks first. */
|
||||
int set_loan(int64_t tokens);
|
||||
int64_t loan_tokens() const { return loan_; }
|
||||
|
||||
/* WHO GIVES IT BACK WHEN A REQUEST CANNOT WAIT. A request that needs more blocks than the
|
||||
* cache kept in hand calls this with the loan it can still afford, and the owner of the
|
||||
* slabs drains them to it before returning -- so admission is decided against the whole
|
||||
* carve, exactly as it would be with nothing lent. Without one, what is lent is not
|
||||
* recalled and the request is refused (RAD_E_FULL). */
|
||||
/* Recall hook. A request needing more blocks than the cache has in hand calls it with the
|
||||
* loan it can still afford, and the slab owner drains to that before returning, so admission
|
||||
* is decided against the whole carve. Without a hook, lent blocks are not recalled and the
|
||||
* request gets RAD_E_FULL. */
|
||||
void set_reclaim(std::function<int(int64_t tokens)> f) { reclaim_ = std::move(f); }
|
||||
|
||||
/* 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
|
||||
* its own shard of the pool with it -- and only rank 0's KVManager tracks sequences. So a
|
||||
* follower takes its mark from the leader instead of computing one: its own slab occupies the
|
||||
* same blocks of its own pool, and an id the leader hands out below the mark has to be one the
|
||||
* follower's slab has left too. */
|
||||
/* Copies the leader's loan onto a follower rank. Block ids are shared across ranks and only
|
||||
* rank 0 tracks sequences, so a follower takes the leader's mark instead of computing one;
|
||||
* its slab occupies the same block ids of its own pool. */
|
||||
int follow(const KVManager& leader);
|
||||
|
||||
/* HOW MANY OF A GROUP'S BLOCKS THE CACHE MAY HAND OUT: the carve less what is lent. */
|
||||
/* Blocks of a group the cache may hand out: the carve less the loan. */
|
||||
int64_t live_blocks(int32_t group) const;
|
||||
int64_t committed_bytes() const;
|
||||
|
||||
/* ---------------- 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
|
||||
* from its last checkpoint or from zero.
|
||||
*
|
||||
* IT DOES NOT MARK ANYTHING, and carries no "needs re-prefill" flag. The scheduler's own
|
||||
* `r.n_computed = 0` (preempt_back) is what drives the replay, and a second piece of state
|
||||
* saying the same thing is a second thing to keep true. seq_tokens() == 0 is the reading, and
|
||||
* it cannot drift. */
|
||||
/* Frees the sequence's blocks and state slots and resets it to zero tokens. A recurrent
|
||||
* state that was not snapshotted cannot be resumed, so the sequence replays from its last
|
||||
* checkpoint or from zero. No "needs re-prefill" flag is kept: the scheduler's
|
||||
* `r.n_computed = 0` (preempt_back) drives the replay, and seq_tokens() == 0 reflects it. */
|
||||
int preempt(uint64_t seq);
|
||||
|
||||
/* ---------------- speculative rejection (spec §10) ---------------- */
|
||||
/* Bring the sequence back to `n_tokens` and return the paged blocks past it. A verify writes
|
||||
* KV for 1 + n_spec positions and the sampler accepts a prefix of them, so the rest has to go
|
||||
* back; `ensure` is monotone and cannot express it.
|
||||
/* Shrinks the sequence to `n_tokens` and frees the paged blocks past it. A verify writes KV
|
||||
* for 1 + n_spec positions and the sampler accepts a prefix; `ensure` is monotone and cannot
|
||||
* undo the rest.
|
||||
*
|
||||
* PAGED GROUPS ONLY, and that is the whole point. The linear state and the conv window have
|
||||
* already absorbed the rejected tokens and are NOT recomputed: libr4d keeps the conv cache as
|
||||
* a rolling window of conv_width-1 + n_spec entries and reads at the slot the last accepted
|
||||
* token left, so a rejection there is a change of read offset that the kernels perform
|
||||
* themselves (core/sample/accept.h). Freeing a state slot here would destroy the state that
|
||||
* offset points into.
|
||||
*
|
||||
* Rolling back is not preemption: the sequence keeps its state slots and its window base.
|
||||
* Without this the pool leaks one block per rejected block-crossing, which is a slow leak and
|
||||
* therefore the worst kind. */
|
||||
* Paged groups only. The linear state and conv window have already absorbed the rejected
|
||||
* tokens: the conv cache is a rolling window of conv_width-1 + n_spec entries, and the kernels
|
||||
* handle a rejection by moving the read offset (core/sample/accept.h). Freeing a state slot
|
||||
* here would destroy the state that offset points into. Unlike preempt, the sequence keeps
|
||||
* its state slots and window base. */
|
||||
int rollback(uint64_t seq, int64_t n_tokens);
|
||||
|
||||
/* The absolute token position that block_table(seq, group)[0] covers. Zero for a FULL group;
|
||||
* non-zero for a WINDOW group, whose blocks below the window have been recycled. The step
|
||||
* batch's slot mapping is (pos - first_block_pos) / block_size, and without the offset every
|
||||
* sliding-window sequence writes its KV to the wrong slot the moment it passes its window. */
|
||||
/* The absolute token position block_table(seq, group)[0] covers: zero for a FULL group, the
|
||||
* recycled prefix for a WINDOW group. The slot mapping is (pos - first_block_pos) /
|
||||
* block_size; without the offset a sliding-window sequence writes to the wrong slot once it
|
||||
* passes its window. */
|
||||
int64_t first_block_pos(uint64_t seq, int32_t group) const;
|
||||
|
||||
/* THE ENTRIES OF A SEQUENCE'S TABLE THAT CHANGED since the last call: every entry below the
|
||||
* returned index is what it was then, and kNoDirty says none changed. The call clears the
|
||||
* mark, so it has exactly one reader -- the batch builder, which stages only the changed tail
|
||||
* of a table the device already holds. A sequence it has not seen answers 0. */
|
||||
/* The first table entry changed since the last call; entries below it are unchanged, and
|
||||
* kNoDirty means none changed. The call clears the mark, so it has one reader: the batch
|
||||
* builder, which stages only the changed tail. An unseen sequence returns 0. */
|
||||
int64_t take_table_changes(uint64_t seq, int32_t group) const;
|
||||
static constexpr int64_t kNoDirty = INT64_MAX;
|
||||
|
||||
/* Free victims, in the order given, until `seq` can be extended to `n_tokens`.
|
||||
* RAD_OK room was made; *preempted lists who paid for it
|
||||
* RAD_E_FULL even an empty pool cannot serve it -- fail the request, do not retry
|
||||
* The caller supplies the victim order because priority is the scheduler's business, not the
|
||||
* allocator's. */
|
||||
* RAD_E_FULL even an empty pool cannot serve it; fail the request, do not retry
|
||||
* The caller supplies the victim order, since priority is the scheduler's policy. */
|
||||
int make_room(uint64_t seq, int64_t n_tokens,
|
||||
const std::vector<uint64_t>& victims,
|
||||
std::vector<uint64_t>* preempted);
|
||||
|
||||
/* ---------------- 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.
|
||||
* Snapshots live in pinned host memory: no kernel reads them, they are only copied back into
|
||||
* a live state slot. A save is one copy across the link after the step that produced the
|
||||
* state, a restore one copy back before the step that resumes from it (a few ms for 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`). 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. */
|
||||
* The store is owned by the engine and shared by every rank: a slot holds each rank's shard
|
||||
* at its own offset (`rank_off`). Rank 0 hands out slot ids and the other ranks use them.
|
||||
* Without a store no slot is 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 ck_store_ ? ck_store_->capacity() : 0; }
|
||||
@@ -470,46 +397,40 @@ public:
|
||||
/* The store holds `slot`: it was allocated and not given back since. */
|
||||
bool checkpoint_held(int32_t slot) const;
|
||||
|
||||
/* SNAPSHOT AND RESUME A SEQUENCE'S WHOLE LINEAR STATE. This is what makes a prefix hit legal
|
||||
* on a hybrid model: the attention half of a hit is carried by the adopted blocks, and the
|
||||
* recurrent half is carried by these two calls and by nothing else. Without them a hit
|
||||
* resumes every recurrent layer from whatever the slot last held -- which reads as fluent
|
||||
* text, so it is not a failure anyone notices without a determinism check.
|
||||
/* Snapshot and resume a sequence's whole linear state. On a hybrid model a prefix hit carries
|
||||
* the attention half in adopted blocks and the recurrent half only through these calls;
|
||||
* without them a hit resumes from whatever the slot last held, which still reads as fluent
|
||||
* text.
|
||||
*
|
||||
* The pool is LAYER-MAJOR and a sequence's state is therefore strided, not contiguous, so the
|
||||
* blob is a gather: for every stateful group, in `plans()` order, for every layer, its
|
||||
* `layer_bytes_per_state()` bytes. Both directions walk that identically, which is the whole
|
||||
* requirement -- a checkpoint is only ever read back by this same build.
|
||||
* The pool is layer-major, so the blob is a gather: for each stateful group in `plans()`
|
||||
* order, for each layer, `layer_bytes_per_state()` bytes. Both directions walk it the same
|
||||
* way; a checkpoint is only read back by the same build. Only copy 0 (the committed state) is
|
||||
* saved; the other copies hold replay factors for unaccepted tokens.
|
||||
*
|
||||
* COPY 0 ONLY. A speculating sequence owns `state_copies` physical slots and the committed
|
||||
* state is copy 0 (KVGroupPlan); the replay factors in the others describe tokens that have
|
||||
* not been accepted and mean nothing to a later reader.
|
||||
*
|
||||
* 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. 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. */
|
||||
* Enqueued on `s`, so stream order puts a save after the step that produced the state and a
|
||||
* restore before the step that reads it. One pitched copy per stateful group. 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,
|
||||
const std::vector<int32_t>* win = nullptr);
|
||||
int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s,
|
||||
const std::vector<int32_t>* win = nullptr);
|
||||
|
||||
/* ---------------- window snapshots (the sliding-window half of a prefix hit) ----------------
|
||||
* A WINDOW group keeps only the blocks its window can still read, so no block list from the
|
||||
* prefix cache describes it. What a later prompt that extends a cached prefix at position P
|
||||
* needs from it is exactly the window behind P: blocks [lo, P/B) with
|
||||
* lo = max(0, P/B - (window_blocks - 1)) -- the floor recycle_window keeps for a query at P.
|
||||
* A checkpoint slot therefore carries, after the linear state, window_blocks pages a WINDOW
|
||||
* group (every layer, layer-major rows), and a hit at a checkpoint restores them into fresh
|
||||
* blocks seeded at that floor.
|
||||
* A WINDOW group keeps only the blocks its window can still read, so the prefix cache's block
|
||||
* lists do not describe it. A prompt extending a cached prefix at position P needs blocks
|
||||
* [lo, P/B), lo = max(0, P/B - (window_blocks - 1)), the floor recycle_window keeps for a
|
||||
* query at P. A checkpoint slot therefore carries, after the linear state, window_blocks pages
|
||||
* per snapshot group (every layer, layer-major rows), restored into fresh blocks seeded at
|
||||
* that floor.
|
||||
*
|
||||
* has_window_snapshot(): this rank's slot carries a window section. window_rows() names, from
|
||||
* the LEADER's table, the block ids [lo, P/B) of every non-zero snapshot group (win_snap) in
|
||||
* plans() order, each group padded with -1 to window_blocks -- one vector every rank addresses
|
||||
* with its own pool, because followers keep no sequence tables. False when the sequence does
|
||||
* not hold that range (it is gone, or its floor moved past lo). seed_window() gives a sequence
|
||||
* with an empty table in each snapshot group the blocks [lo, P/B) a restore will fill, before
|
||||
* the ensure that extends it; any other WINDOW group starts at the floor that ensure sets. */
|
||||
* has_window_snapshot(): this rank's slot carries a window section.
|
||||
* window_rows(): from the leader's table, the block ids [lo, P/B) of every non-zero win_snap
|
||||
* group in plans() order, each padded with -1 to window_blocks; every rank addresses its own
|
||||
* pool with it, since followers keep no tables. False if the sequence no longer holds that
|
||||
* range.
|
||||
* seed_window(): gives a sequence with an empty table in each snapshot group the blocks
|
||||
* [lo, P/B) a restore will fill, before the ensure that extends it. Other WINDOW groups start
|
||||
* at the floor ensure sets. */
|
||||
bool has_window_snapshot() const { return window_ck_bytes_ > 0; }
|
||||
bool window_rows(uint64_t seq, int64_t pos, std::vector<int32_t>* out) const;
|
||||
int seed_window(uint64_t seq, int64_t pos);
|
||||
@@ -519,19 +440,18 @@ public:
|
||||
return b > 0 ? b : 0;
|
||||
}
|
||||
|
||||
/* Byte address of a state slot, for the slot-mapping builder. Null when the pool has no
|
||||
* host-visible base (a device pool), which is the normal case -- the offset is what the step
|
||||
* batch actually carries. */
|
||||
/* Byte address of a state slot, for the slot-mapping builder. Null when the group has no
|
||||
* base. */
|
||||
void* state_ptr(int32_t group, int32_t layer, int32_t slot) const;
|
||||
|
||||
private:
|
||||
/* carve() is the wrapper and carve_into() is the work, so that a carve which returns part way
|
||||
* through cannot leave plans_ answering guards for block state that was never sized. forget()
|
||||
* empties both together and is what plan_groups() starts from. */
|
||||
/* carve() wraps carve_into() and calls forget() on failure, so a carve that stops part way
|
||||
* cannot leave plans_ passing guards for block state that was never sized. plan_groups() also
|
||||
* starts from forget(). */
|
||||
int carve_into(Pool& kv_pool);
|
||||
/* THE PAGED SPLIT, as arithmetic: the token count the paged groups exhaust at together for
|
||||
* `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. */
|
||||
/* The token count at which the paged groups run out together for `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 returns. */
|
||||
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. */
|
||||
@@ -549,15 +469,14 @@ private:
|
||||
std::vector<int64_t> first_block_pos; /* WINDOW: token pos of blocks[0] */
|
||||
std::vector<int32_t> state; /* per group, -1 when not stateful */
|
||||
/* Per group, the lowest table entry written since the batch builder last staged this
|
||||
* sequence: everything below it is unchanged. An append or a truncation lowers it to
|
||||
* where it touched; anything that shifts or replaces entries lowers it to zero; kNoDirty
|
||||
* is nothing. Mutable because reading it is what clears it -- take_table_changes. */
|
||||
* sequence. An append or truncation lowers it to where it touched; a shift lowers it to
|
||||
* zero; kNoDirty is unchanged. Mutable because take_table_changes() clears it. */
|
||||
mutable std::vector<int64_t> dirty_from;
|
||||
};
|
||||
|
||||
int grab_block(int32_t g, int32_t* out);
|
||||
void drop_block(int32_t g, int32_t b);
|
||||
/* Every increment of a held block's reference count, so the cache-only count follows it. */
|
||||
/* Increments a held block's refcount and keeps the cache-only count in step. */
|
||||
void add_ref(size_t g, int32_t b);
|
||||
int grab_state(int32_t g, int32_t* out);
|
||||
void drop_state(int32_t g, int32_t s);
|
||||
@@ -593,31 +512,23 @@ private:
|
||||
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 loan. See the public block for what this is and why a block that anything holds
|
||||
* is never lent. ----
|
||||
/* ---- the loan (see the public block) ----
|
||||
*
|
||||
* `live_` is how many of a group's blocks the cache may hand out -- the carve less the loan --
|
||||
* and it gates the free list rather than the carve: every id the carve created is in
|
||||
* `free_blocks_`, and an id at or above live_ is simply not handed out. THAT IS WHY THE FREE
|
||||
* LIST IS A MIN-HEAP. Handing out the lowest free id keeps the held blocks packed at the
|
||||
* bottom of the pool, so the top is what drains and the top is the only part a loan can
|
||||
* reach; a stack would hand back the id freed most recently, which after a busy period is
|
||||
* exactly the high block the loan wants. The heap also makes the gate free: the smallest free
|
||||
* id is below live_ whenever any free id is, so no scan is needed to find one.
|
||||
* `live_` is the carve less the loan. Every carved id stays in `free_blocks_`; ids at or
|
||||
* above live_ are just not handed out. The free list is a min-heap so the lowest free id goes
|
||||
* out first: held blocks pack at the bottom and the top, the only part a loan reaches, drains.
|
||||
* A stack would hand out the most recently freed id, often a high one. The heap also makes the
|
||||
* gate a single check: if any free id is below live_, the smallest one is.
|
||||
*
|
||||
* `held_hist_` counts held blocks per bucket, so "what is the highest bucket anything still
|
||||
* holds" is a walk of a few thousand counters instead of a scan of every refcount. It is what
|
||||
* decides how far a loan may reach, and it is maintained on the allocation path because a
|
||||
* scan there is not affordable and a stale answer would lend a block out from under a live
|
||||
* sequence. */
|
||||
/* THE BUFFER, PER GROUP, IN BLOCKS. `chunk_blocks_` is the floor -- one prefill chunk, fixed
|
||||
* at plan time; `short_peak_` is the largest shortfall the admission path has met recently,
|
||||
* raised by grow_for and decayed by every spare_tokens() so it forgets a burst in a few
|
||||
* seconds.
|
||||
* `held_hist_` counts held blocks per bucket, so finding the highest held block is a walk of
|
||||
* a few thousand counters, not a refcount scan. It bounds how far a loan may reach, so it is
|
||||
* maintained on the allocation path; a stale value would lend a held block. */
|
||||
/* The buffer per group, in blocks. `chunk_blocks_` is the floor (one prefill chunk, fixed at
|
||||
* plan time). `short_peak_` is the largest recent admission shortfall, raised by grow_for and
|
||||
* decayed by spare_tokens().
|
||||
*
|
||||
* THE SHORTFALL IS THE SIGNAL AND THE RECALL IS NOT. grow_for recalls the shortfall PLUS the
|
||||
* buffer; feeding that back would be a buffer that sizes itself from its own last value and
|
||||
* climbs until it is the carve. What is recorded is what was asked for and not there. */
|
||||
* Only the shortfall is recorded, never the recall: grow_for recalls shortfall plus buffer,
|
||||
* and feeding that back would grow the buffer from its own value until it reached the carve. */
|
||||
std::vector<int64_t> chunk_blocks_;
|
||||
std::vector<int64_t> short_peak_;
|
||||
Pool* pool_ = nullptr;
|
||||
@@ -632,10 +543,12 @@ private:
|
||||
int64_t available_blocks(int32_t g) const;
|
||||
/* The buffer this group wants in hand, in blocks. See buffer_bytes(). */
|
||||
int64_t buf_blocks(size_t i) const;
|
||||
/* One past the highest block anything holds, to a bucket. */
|
||||
/* One past the highest held block, rounded up to a bucket. */
|
||||
int64_t held_top(size_t i) const;
|
||||
/* The blocks a loan of `tokens` takes off the top of group i. */
|
||||
int64_t lent_blocks(size_t i, int64_t tokens) const;
|
||||
/* Moves every lendable group's mark to a loan of `tokens`, unchecked (set_loan checks). */
|
||||
void apply_loan(int64_t tokens);
|
||||
int grow_for(int32_t g, int64_t blocks);
|
||||
void note_held(int32_t g, int32_t b, int delta);
|
||||
bool configured_ = false;
|
||||
|
||||
+129
-132
@@ -35,17 +35,18 @@ int IdleTiers::configure(const Config& c) {
|
||||
}
|
||||
|
||||
char buf[512];
|
||||
if (!any_on()) {
|
||||
report_ = "kv tiers: off (no --prefix-cache-mib), so a finished conversation's KV stays "
|
||||
"in VRAM until the cache evicts it under pressure -- it is never copied to host "
|
||||
"memory, and what the pool is holding is mostly cache rather than live requests";
|
||||
if (!host_on()) {
|
||||
report_ = "kv tiers: off (no --prefix-cache-mib); a finished conversation's KV stays in "
|
||||
"VRAM until the cache evicts it";
|
||||
} else {
|
||||
std::snprintf(buf, sizeof buf,
|
||||
"kv tiers: a finished conversation's KV is copied to host memory at once "
|
||||
"(%s, %lld entries) and its VRAM is given up when the expert loan or a "
|
||||
"request wants it; a full host tier drops its least recently used entries. "
|
||||
"One entry is %s",
|
||||
"(%s, %lld entries, %lld tokens of context) and its VRAM is given up when "
|
||||
"the expert loan or a request wants it; a full host tier drops its least "
|
||||
"recently used entries, the end of a conversation before its start. One "
|
||||
"entry is %s",
|
||||
humanb(arena_.cap_bytes()).c_str(), (long long)arena_.capacity(),
|
||||
(long long)(arena_.capacity() * cfg_.block_tokens),
|
||||
humanb(cfg_.entry_bytes).c_str());
|
||||
report_ = buf;
|
||||
if (cfg_.ckpt_bytes > 0) {
|
||||
@@ -65,7 +66,6 @@ void IdleTiers::close() {
|
||||
reset();
|
||||
}
|
||||
|
||||
/* The body of close(), for the caller that already holds the lock. */
|
||||
void IdleTiers::reset() {
|
||||
recs_.clear();
|
||||
sessions_.clear();
|
||||
@@ -73,7 +73,7 @@ void IdleTiers::reset() {
|
||||
host_lru_.clear();
|
||||
wb_q_.clear();
|
||||
clean_q_.clear();
|
||||
starved_ = 0;
|
||||
room_.clear();
|
||||
wb_stuck_ = false;
|
||||
arena_.close();
|
||||
cfg_ = Config{};
|
||||
@@ -88,12 +88,20 @@ void IdleTiers::unlist(Rec& r) {
|
||||
r.listed = false;
|
||||
}
|
||||
|
||||
/* ONLY A RECORD WHOSE BYTES ARE ONLY OFF THE CARD. A device record -- clean or not -- is ordered by
|
||||
* the prefix cache's own LRU, and a second ordering of the same entries is the two-owner shape the
|
||||
* header's one-record rule exists to rule out. */
|
||||
/* Host records only: device records, clean or not, are ordered by the prefix cache's LRU (see the
|
||||
* one-record rule in the header). */
|
||||
/* A use: stamps the record and moves a listed (host) one to the back of its list. */
|
||||
void IdleTiers::touch(const BlockHash& key, Rec& r, uint64_t now_ns) {
|
||||
r.used_ns = now_ns;
|
||||
if (r.listed) {
|
||||
unlist(r);
|
||||
relist(key, r);
|
||||
}
|
||||
}
|
||||
|
||||
void IdleTiers::relist(const BlockHash& key, Rec& r) {
|
||||
if (r.pending || r.tier == KVTier::Device || r.listed) return;
|
||||
r.it = host_lru_.emplace_hint(host_lru_.end(), r.used_ns, key);
|
||||
r.it = host_lru_.emplace_hint(host_lru_.end(), LruKey{ r.used_ns, r.depth }, key);
|
||||
r.listed = true;
|
||||
}
|
||||
|
||||
@@ -127,9 +135,6 @@ void IdleTiers::queue_clean(const BlockHash& key, Rec& r) {
|
||||
|
||||
/* ------------------------------------------------------------------ the linear half */
|
||||
|
||||
/* RECORDED, NOT MOVED. A snapshot is in host memory from the moment it is saved and stays in its
|
||||
* store slot until the cache retires it; the tiers keep its slot and position for the session
|
||||
* view. */
|
||||
void IdleTiers::note_snapshot(const BlockHash& key, int32_t slot, int64_t pos) {
|
||||
if (slot < 0) return;
|
||||
std::lock_guard lk(mu_);
|
||||
@@ -144,49 +149,41 @@ void IdleTiers::release_snapshot(const BlockHash& key) {
|
||||
if (it == recs_.end()) return;
|
||||
Rec& r = it->second;
|
||||
r.ck_slot = -1;
|
||||
/* A RECORD THAT ONLY EVER EXISTED FOR THE SNAPSHOT GOES WITH IT. note_snapshot creates one at
|
||||
* commit time, which is mid-request and long before the chain is published; a request that
|
||||
* never publishes -- a rebased block table, a cancel before the first whole block -- would
|
||||
* otherwise leave a record with no blocks, no storage and no way to be reached again. */
|
||||
/* A record that only existed for the snapshot goes with it. note_snapshot creates one
|
||||
* mid-request; a request that never publishes (a rebased block table, a cancel before the
|
||||
* first whole block) would otherwise leave an unreachable empty record. */
|
||||
if (!r.pending && r.tier == KVTier::Device && r.blocks.empty() && r.host_slot < 0)
|
||||
recs_.erase(it);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the cache's notices */
|
||||
|
||||
void IdleTiers::note_used(const BlockHash& key, const std::vector<int32_t>& blocks, uint64_t now_ns) {
|
||||
if (!any_on()) return;
|
||||
void IdleTiers::note_used(const BlockHash& key, const std::vector<int32_t>& blocks, uint64_t now_ns,
|
||||
int64_t depth) {
|
||||
if (!host_on()) return;
|
||||
std::lock_guard lk(mu_);
|
||||
Rec& r = recs_[key];
|
||||
r.used_ns = now_ns;
|
||||
if (r.tier == KVTier::Device && !r.pending) r.blocks = blocks;
|
||||
/* A record only moves on the host list when it is IN it. A device record is a timestamp and
|
||||
* nothing else, which is what keeps this cheap enough to sit on the publish path -- the hash
|
||||
* insert is the whole cost. */
|
||||
if (r.listed) {
|
||||
unlist(r);
|
||||
relist(key, r);
|
||||
}
|
||||
/* Before touch, which files a host record under it. */
|
||||
r.depth = depth;
|
||||
/* For a device record this is a timestamp and a hash insert, cheap enough for the publish
|
||||
* path. */
|
||||
touch(key, r, now_ns);
|
||||
queue_copy(key, r);
|
||||
}
|
||||
|
||||
void IdleTiers::note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns) {
|
||||
if (!any_on() || !keys || n <= 0) return;
|
||||
if (!host_on() || !keys || n <= 0) return;
|
||||
std::lock_guard lk(mu_);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
auto it = recs_.find(keys[i]);
|
||||
if (it == recs_.end()) continue;
|
||||
Rec& r = it->second;
|
||||
r.used_ns = now_ns;
|
||||
if (r.listed) {
|
||||
unlist(r);
|
||||
relist(keys[i], r);
|
||||
}
|
||||
if (it != recs_.end()) touch(keys[i], it->second, now_ns);
|
||||
}
|
||||
}
|
||||
|
||||
void IdleTiers::rebound(const BlockHash& key, const std::vector<int32_t>& blocks, uint64_t now_ns) {
|
||||
if (!any_on()) return;
|
||||
void IdleTiers::rebound(const BlockHash& key, const std::vector<int32_t>& blocks, uint64_t now_ns,
|
||||
int64_t depth) {
|
||||
if (!host_on()) return;
|
||||
std::lock_guard lk(mu_);
|
||||
Rec& r = recs_[key];
|
||||
if (r.pending) return;
|
||||
@@ -195,6 +192,7 @@ void IdleTiers::rebound(const BlockHash& key, const std::vector<int32_t>& blocks
|
||||
r.tier = KVTier::Device;
|
||||
r.blocks = blocks;
|
||||
r.used_ns = now_ns;
|
||||
r.depth = depth;
|
||||
queue_copy(key, r);
|
||||
}
|
||||
|
||||
@@ -207,18 +205,13 @@ bool IdleTiers::doomed(const BlockHash& key) const {
|
||||
IdleTiers::Stats IdleTiers::stats() const {
|
||||
std::lock_guard lk(mu_);
|
||||
Stats s = stats_;
|
||||
/* What the block arena holds, clean copies included: counted off the arena rather than kept
|
||||
* beside it, because every path that takes or returns a slot would otherwise have to remember
|
||||
* to move a second number. */
|
||||
/* Derived from the arena, clean copies included, so no separate counter can drift. */
|
||||
s.host_bytes = arena_.used_slots() * cfg_.entry_bytes;
|
||||
return s;
|
||||
}
|
||||
|
||||
/* AND EVERY CONVERSATION THAT STARTED HERE. A chain whose first block has gone cannot be hit at any
|
||||
* length -- a prefix hit starts at position zero. Leaving the row behind would report blocks the
|
||||
* pool has already handed to somebody else as this session's, and would hold its whole chain in
|
||||
* memory for a conversation that can never come back. Called wherever an entry goes for good: the
|
||||
* cache's forget(), and the sites here that drop an off-device entry and tell the cache. */
|
||||
/* A chain whose first block has gone can never be hit (see roots_). Called wherever an entry goes
|
||||
* for good: forget(), and the sites here that drop an off-device entry and tell the cache. */
|
||||
void IdleTiers::drop_rooted(const BlockHash& key) {
|
||||
auto ro = roots_.find(key);
|
||||
if (ro == roots_.end()) return;
|
||||
@@ -233,9 +226,7 @@ void IdleTiers::forget(const BlockHash& key) {
|
||||
if (it == recs_.end()) return;
|
||||
Rec& r = it->second;
|
||||
if (r.pending) {
|
||||
/* The engine is mid-transfer against this record. Erasing it now is exactly the
|
||||
* use-after-free the one-record rule exists to prevent, so mark it and let report()
|
||||
* finish the job and clean up. */
|
||||
/* Mid-transfer: erasing now would be a use-after-free. report() cleans up. */
|
||||
r.doomed = true;
|
||||
return;
|
||||
}
|
||||
@@ -261,16 +252,15 @@ bool IdleTiers::resident_off_device(const BlockHash& key) const {
|
||||
|
||||
bool IdleTiers::writeback_waiting() const {
|
||||
std::lock_guard lk(mu_);
|
||||
/* NOT WHILE NOTHING CAN MOVE. An arena full of the copies of entries still in VRAM has nothing
|
||||
* a capacity drop may take, so a plan would pop the queue, find no slot and put it back, every
|
||||
* tick, until a slot is freed or a VRAM copy is given up -- which is what ends the wait. */
|
||||
/* Not while nothing can move: an arena full of copies of entries still in VRAM offers nothing
|
||||
* to drop, so wait until a slot is freed or a VRAM copy is given up. */
|
||||
if (wb_stuck_ && arena_.full()) return false;
|
||||
return !wb_q_.empty() && host_on();
|
||||
}
|
||||
|
||||
bool IdleTiers::starved() const {
|
||||
std::lock_guard lk(mu_);
|
||||
return starved_ > 0;
|
||||
return !room_.empty();
|
||||
}
|
||||
|
||||
void IdleTiers::plan_writeback(int64_t max_entries, std::vector<TierJob>* out) {
|
||||
@@ -293,11 +283,8 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector<TierJob>* out) {
|
||||
out->push_back(std::move(j));
|
||||
}
|
||||
|
||||
/* THE HOST SLOTS, AS RUNS. Taken for the whole batch at once so that entries planned together
|
||||
* sit together in the arena and each run crosses the link as one copy. A batch the arena
|
||||
* cannot hold is cut where the arena ran out: the entries past that point go back to the
|
||||
* front of the queue, and the maintenance plan is told how many copies were refused so it can
|
||||
* make that much room. */
|
||||
/* Allocate host slots for the whole batch as runs, so each run crosses the link as one copy.
|
||||
* Jobs past where the arena ran out are refused; see below. */
|
||||
const int64_t want = (int64_t)(out->size() - first);
|
||||
std::vector<int32_t> slots;
|
||||
slots.reserve((size_t)want);
|
||||
@@ -316,7 +303,6 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector<TierJob>* out) {
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
++starved_;
|
||||
refused.push_back(j.key);
|
||||
out->erase(out->begin() + (long)i);
|
||||
}
|
||||
@@ -326,14 +312,56 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector<TierJob>* out) {
|
||||
unlist(r);
|
||||
r.pending = true;
|
||||
}
|
||||
/* Back where they were, at the front and in order, so the oldest conversation is still the
|
||||
* first copied once there is room. */
|
||||
if (refused.empty()) return;
|
||||
|
||||
/* A refused copy is worth making room for only by dropping a host entry worth less than it.
|
||||
* The most valuable refused copies are matched with the least valuable host entries; one
|
||||
* that finds none leaves the queue, since any room made for it would cost more than it
|
||||
* saves: it would drop a conversation's start to keep its end, or a newer conversation to
|
||||
* keep an older one. Its entry stays in VRAM only and is copied again when a turn uses it. */
|
||||
const LruOrder less;
|
||||
std::vector<std::pair<LruKey, BlockHash>> by_value;
|
||||
by_value.reserve(refused.size());
|
||||
for (const BlockHash& k : refused) {
|
||||
const Rec& r = recs_[k];
|
||||
by_value.push_back({ LruKey{ r.used_ns, r.depth }, k });
|
||||
}
|
||||
std::sort(by_value.begin(), by_value.end(),
|
||||
[&less](const auto& a, const auto& b) { return less(b.first, a.first); });
|
||||
std::unordered_set<BlockHash, BlockHashHash> keep;
|
||||
int64_t held = 0;
|
||||
auto victim = host_lru_.begin();
|
||||
for (const auto& kv : by_value) {
|
||||
if (victim != host_lru_.end() && less(victim->first, kv.first)) {
|
||||
room_.push_back(kv.first);
|
||||
keep.insert(kv.second);
|
||||
++victim;
|
||||
} else {
|
||||
++held;
|
||||
}
|
||||
}
|
||||
/* Requeue at the front, in order, so the oldest is still copied first. */
|
||||
for (auto it = refused.rbegin(); it != refused.rend(); ++it) {
|
||||
if (!keep.count(*it)) continue;
|
||||
auto ri = recs_.find(*it);
|
||||
if (ri == recs_.end() || ri->second.queued) continue;
|
||||
wb_q_.push_front(*it);
|
||||
ri->second.queued = true;
|
||||
}
|
||||
if (held == 0) return;
|
||||
stats_.held_back += held;
|
||||
const uint64_t now = rad_mono_ns();
|
||||
if (held_back_warned_ns_ == 0 || now - held_back_warned_ns_ >= 60ull * 1000000000ull) {
|
||||
held_back_warned_ns_ = now;
|
||||
RAD_WARN("kv tiers: %lld entries (%lld tokens of context) got no host copy: the host "
|
||||
"tier (--prefix-cache-mib, %s, %lld tokens) is full of context used more "
|
||||
"recently or nearer the start of its conversation. They stay in VRAM only and "
|
||||
"are prefilled again once VRAM gives them up; a larger --prefix-cache-mib holds "
|
||||
"more. Counted in /sessions moved.held_back",
|
||||
(long long)held, (long long)(held * cfg_.block_tokens),
|
||||
humanb(arena_.cap_bytes()).c_str(),
|
||||
(long long)(arena_.capacity() * cfg_.block_tokens));
|
||||
}
|
||||
}
|
||||
|
||||
void IdleTiers::take_clean(std::vector<BlockHash>* out) {
|
||||
@@ -372,13 +400,14 @@ void IdleTiers::drop_commit(const BlockHash& key) {
|
||||
void IdleTiers::plan(int budget, std::vector<TierJob>* out) {
|
||||
if (!host_on() || budget <= 0) return;
|
||||
std::lock_guard lk(mu_);
|
||||
/* HOW MANY, AND NOT "UNTIL THERE IS ROOM". A queued drop does not free its slot until the
|
||||
* engine reports it, so a loop that tested the arena would queue a drop for every entry on the
|
||||
* list and empty the whole tier to make room for one. The copies refused since the last plan
|
||||
* say how much room was wanted; this frees exactly that much, least recently used first. */
|
||||
const int64_t want = std::min<int64_t>(starved_, budget);
|
||||
starved_ = 0;
|
||||
/* Drop one entry for each copy refused, least valuable first, and only one worth less than
|
||||
* the copy it makes room for (room_ runs most valuable first, the list least valuable first,
|
||||
* so the first pair that fails ends the plan). Looping until the arena has room would empty
|
||||
* the tier, since a queued drop frees its slot only when the engine reports it. */
|
||||
const int64_t want = std::min<int64_t>((int64_t)room_.size(), budget);
|
||||
const LruOrder less;
|
||||
for (int64_t k = 0; k < want && !host_lru_.empty();) {
|
||||
if (!less(host_lru_.begin()->first, room_[(size_t)k])) break;
|
||||
auto ri = recs_.find(host_lru_.begin()->second);
|
||||
if (ri == recs_.end()) { host_lru_.erase(host_lru_.begin()); continue; }
|
||||
Rec& r = ri->second;
|
||||
@@ -392,13 +421,14 @@ void IdleTiers::plan(int budget, std::vector<TierJob>* out) {
|
||||
out->push_back(std::move(j));
|
||||
++k;
|
||||
}
|
||||
room_.clear();
|
||||
}
|
||||
|
||||
void IdleTiers::expired(uint64_t cutoff_ns, size_t max, std::vector<BlockHash>* out) const {
|
||||
std::lock_guard lk(mu_);
|
||||
/* The list holds no record with a job out (relist), so every key it yields can go now. */
|
||||
/* The list holds no pending record (relist), so every key here can go now. */
|
||||
for (auto it = host_lru_.begin();
|
||||
it != host_lru_.end() && it->first < cutoff_ns && out->size() < max; ++it)
|
||||
it != host_lru_.end() && it->first.used_ns < cutoff_ns && out->size() < max; ++it)
|
||||
out->push_back(it->second);
|
||||
}
|
||||
|
||||
@@ -424,21 +454,19 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
|
||||
std::lock_guard lk(mu_);
|
||||
auto it = recs_.find(job.key);
|
||||
if (it == recs_.end()) {
|
||||
/* Nothing names the slots a copy was handed but the job itself. */
|
||||
/* Only the job names a write-back's slot. */
|
||||
if (job.kind == TierJob::Kind::WriteBack) give_slot(job.host_slot);
|
||||
return;
|
||||
}
|
||||
Rec& r = it->second;
|
||||
r.pending = false;
|
||||
/* A promotion the chain was cut before is not a failure: nothing was tried. */
|
||||
/* An unstarted promotion is not a failure: nothing was tried. */
|
||||
if (!ok && (job.kind != TierJob::Kind::ToDevice || job.started)) ++stats_.failures;
|
||||
|
||||
/* A record that was forgotten mid-transfer is finished off here and nowhere else. Doing it at
|
||||
* the top, before the per-kind handling, means no branch below has to remember to check. */
|
||||
/* A record forgotten mid-transfer is finished off here, before the per-kind handling. */
|
||||
if (r.doomed) {
|
||||
/* THE JOB'S SLOT AND THE RECORD'S ARE NOT THE SAME SLOT on every path. A copy's host slot
|
||||
* is the job's until it reports; freeing only the record's would leak it, and freeing the
|
||||
* job's as well where it IS the record's would return one slot twice. */
|
||||
/* The job's slot may or may not be the record's: a write-back's slot belongs to the job
|
||||
* until it reports. Free each distinct slot once. */
|
||||
if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot);
|
||||
free_host(r);
|
||||
recs_.erase(it);
|
||||
@@ -467,29 +495,22 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
|
||||
if (ok) {
|
||||
r.tier = KVTier::Device;
|
||||
r.blocks = job.blocks;
|
||||
/* THE HOST COPY IS KEPT, which is what makes the entry clean the moment it lands:
|
||||
* its VRAM copy can go again at no cost, and the next copy this conversation needs
|
||||
* is only of the tokens its next turn adds. */
|
||||
/* The host copy is kept, so the entry is clean on landing. */
|
||||
r.host_slot = job.host_slot;
|
||||
/* THE CLOCK RESTARTS: the entry came back because a request is about to hit it. */
|
||||
/* A request is about to hit it. */
|
||||
if (now_ns) r.used_ns = now_ns;
|
||||
++stats_.promoted;
|
||||
queue_clean(job.key, r);
|
||||
return;
|
||||
}
|
||||
if (!job.started) {
|
||||
/* NEVER STARTED: the reservation ran out before this entry, and nothing about it
|
||||
* was touched. It stays exactly where it was. */
|
||||
/* Never started: the reservation ran out first. It stays on the host tier. */
|
||||
relist(job.key, r);
|
||||
return;
|
||||
}
|
||||
/* A FAILED PROMOTION DROPS THE ENTRY, AND THE CACHE MUST HEAR ABOUT IT. Every other
|
||||
* failure here can leave the record where it was, because nothing was consumed. This
|
||||
* one cannot: the scatter may have written some layers and not others, so the blocks
|
||||
* hold a mixture and the cached tensors are no longer a function of the tokens. A miss
|
||||
* is always safe and this is the only way to guarantee one -- but the prefix cache
|
||||
* still holds an entry naming blocks that are not ours any more, and left alone it
|
||||
* would serve them. */
|
||||
/* A started promotion that failed may have scattered some layers and not others, so
|
||||
* the entry is dropped to force a miss, and the cache is told so it stops naming the
|
||||
* blocks. */
|
||||
if (job.host_slot >= 0 && job.host_slot != r.host_slot) give_slot(job.host_slot);
|
||||
free_host(r);
|
||||
recs_.erase(it);
|
||||
@@ -510,10 +531,8 @@ void IdleTiers::report(const TierJob& job, bool ok, uint64_t now_ns) {
|
||||
|
||||
/* ------------------------------------------------------------------ the session view */
|
||||
|
||||
/* A PREFIX RELATION IS WHAT MAKES TWO CHAINS THE SAME CONVERSATION. The blocks are content
|
||||
* addressed, so turn N's chain is byte for byte turn N-1's with more on the end; anything that
|
||||
* diverges anywhere is a different transcript from that point on, however much of a system prompt
|
||||
* it shares. */
|
||||
/* Two chains are the same conversation when one is a prefix of the other: blocks are content
|
||||
* addressed, so turn N's chain is turn N-1's plus more. */
|
||||
static bool chain_extends(const std::vector<BlockHash>& shorter,
|
||||
const std::vector<BlockHash>& longer) {
|
||||
if (shorter.size() > longer.size()) return false;
|
||||
@@ -526,24 +545,15 @@ void IdleTiers::note_session(uint64_t id, const std::vector<BlockHash>& chain, i
|
||||
if (chain.empty()) return;
|
||||
std::lock_guard lk(mu_);
|
||||
|
||||
/* A SESSION IS A LEAF OF THE PREFIX TRIE, and that is what decides every case here. The turns
|
||||
* of one conversation arrive under different ids -- the id is the request's, and a
|
||||
* conversation is a new request every turn -- so without this the table grows a row a turn,
|
||||
* each holding its own copy of a chain that is a prefix of the next one's and none of them
|
||||
* ever revisited. Candidates are the sessions sharing this root, which is a handful at most.
|
||||
/* A session is a leaf of the prefix trie. Each turn arrives under a new request id, so the
|
||||
* candidates are the sessions sharing this root (a handful at most):
|
||||
*
|
||||
* A CHAIN THIS ONE EXTENDS HAS STOPPED BEING A LEAF, so it is absorbed: its blocks are the
|
||||
* first blocks of this one, byte for byte, because the chain is content addressed.
|
||||
*
|
||||
* A CHAIN THAT EXTENDS THIS ONE MEANS THIS ONE IS NOT A LEAF EITHER. That happens when a
|
||||
* preempted request re-prefills and republishes SHORTER than the conversation it belongs to;
|
||||
* recording it would shrink the row to less than the pool is holding, and there may be
|
||||
* several conversations below it -- two clients past the same system prompt -- with nothing
|
||||
* to say which of them republished. So the most recent of them is touched and no row is
|
||||
* added, which is the one answer that is wrong about nothing. */
|
||||
* - a chain this one extends is no longer a leaf and is absorbed;
|
||||
* - a chain that extends this one means this is not a leaf either (a preempted request
|
||||
* republishing shorter). Several conversations may extend it, so the most recent one is
|
||||
* touched and no row is added. */
|
||||
uint64_t first_seen = 0;
|
||||
/* A conversation's label outlives the turn that sent it: a later turn without one keeps the
|
||||
* name an earlier one gave. */
|
||||
/* A label persists across later turns that send none. */
|
||||
std::string kept_label = label;
|
||||
bool absorbed = false;
|
||||
std::vector<uint64_t>& at_root = roots_[chain[0]];
|
||||
@@ -596,20 +606,14 @@ void IdleTiers::drop_session(uint64_t id) {
|
||||
sessions_.erase(it);
|
||||
}
|
||||
|
||||
void IdleTiers::forget_session(uint64_t id) {
|
||||
std::lock_guard lk(mu_);
|
||||
drop_session(id);
|
||||
}
|
||||
|
||||
std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
/* The view's hold on the lock, a slice at a time (YieldingMutex). */
|
||||
/* One slice's hold on the lock (YieldingMutex). */
|
||||
struct Slice {
|
||||
YieldingMutex& m;
|
||||
explicit Slice(YieldingMutex& mu) : m(mu) { m.lock_after_others(); }
|
||||
~Slice() { m.unlock(); }
|
||||
};
|
||||
/* Records a slice visits: a few microseconds of hash lookups, the most an engine-side taker
|
||||
* arriving mid-slice waits. */
|
||||
/* Records per slice: a few microseconds of hash lookups, the longest an engine thread waits. */
|
||||
constexpr size_t kSliceRecords = 64;
|
||||
|
||||
std::vector<SessionInfo> out;
|
||||
@@ -628,19 +632,14 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
out.push_back(std::move(si));
|
||||
}
|
||||
}
|
||||
/* SNAPSHOTS IN THE STORE, each once. The store is the engine's and is not read from this
|
||||
* thread -- but this walk visits every record a stored conversation reaches, so it counts them
|
||||
* here. They are sparse, one per checkpoint interval, so the set stays small beside the walk
|
||||
* that fills it. */
|
||||
/* Distinct snapshots reached by the walk, for Occupancy. The store itself is the engine's and
|
||||
* is not read from this thread. One per checkpoint interval, so the set stays small. */
|
||||
std::unordered_set<BlockHash, BlockHashHash> host_snaps;
|
||||
size_t kept = 0;
|
||||
for (size_t k = 0; k < out.size(); ++k) {
|
||||
SessionInfo& si = out[k];
|
||||
/* The histogram is computed here and stored nowhere. A session's blocks move one tier at
|
||||
* a time under a bounded plan, so a second copy of this would be stale between the pass
|
||||
* that moves the first block and the pass that moves the last -- which is exactly the
|
||||
* window an operator is looking at the page during. The session is found again at every
|
||||
* slice: between slices it may have been absorbed into a longer one or dropped, and a
|
||||
/* The histogram is computed, never stored, since blocks move a few at a time. The session
|
||||
* is looked up again each slice: in between it may have been absorbed or dropped, and a
|
||||
* row that is gone is left out. */
|
||||
bool gone = false;
|
||||
for (size_t at = 0;;) {
|
||||
@@ -659,8 +658,7 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
case KVTier::Device: ++si.on_device; break;
|
||||
case KVTier::Host: ++si.on_host; break;
|
||||
}
|
||||
/* THE LINEAR HALF, which is in host memory from the moment it is saved, whatever
|
||||
* tier its blocks are on. */
|
||||
/* Snapshots are in host memory whatever tier the blocks are on. */
|
||||
if (rr.ck_slot >= 0) {
|
||||
++si.snapshots;
|
||||
if (occ) host_snaps.insert(h);
|
||||
@@ -683,8 +681,7 @@ std::vector<IdleTiers::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
Slice lk(mu_);
|
||||
occ->host_bytes = arena_.used_slots() * cfg_.entry_bytes +
|
||||
(int64_t)host_snaps.size() * cfg_.ckpt_bytes;
|
||||
/* What the operator gave the block arena and the snapshot store -- the same scope as
|
||||
* `host_bytes` above, which counts both. */
|
||||
/* Block arena plus snapshot store, the same scope as `host_bytes`. */
|
||||
occ->host_cap_bytes = (host_on() ? cfg_.host_cap_bytes : 0) +
|
||||
cfg_.ckpt_slots * cfg_.ckpt_bytes;
|
||||
}
|
||||
|
||||
+171
-254
@@ -1,79 +1,51 @@
|
||||
/* kvtier.h -- where a finished conversation's KV is kept once VRAM has a better use for it
|
||||
* (spec §7.3): VRAM, then host memory, and nowhere else.
|
||||
* (spec §7.3): VRAM, then host memory.
|
||||
*
|
||||
* The prefix cache holds a KV reference on every block it indexes, so a finished turn's context
|
||||
* survives into the next one. That is the whole value of it, and it is also the whole cost: those
|
||||
* blocks are the most valuable thing in the pool while the session is live and the least valuable
|
||||
* thing in it once the session stops -- and on a card whose experts do not fit, VRAM holding an
|
||||
* idle conversation is VRAM every decode step pays for across the link.
|
||||
* The prefix cache keeps a finished turn's blocks referenced for the next turn. They are valuable
|
||||
* while the session is live and dead weight once it stops; on a card whose experts do not fit,
|
||||
* VRAM held by an idle conversation costs every decode step link traffic.
|
||||
*
|
||||
* ============================== COPY ON IDLE, FREE ON DEMAND ====================================
|
||||
*
|
||||
* An entry is COPIED to host memory as soon as the request that published it finishes, and its
|
||||
* VRAM copy is kept. From then on the entry is CLEAN: the pool and the host hold the same bytes,
|
||||
* so giving the VRAM copy up costs nothing at all -- no transfer, no wait, only the cache's
|
||||
* reference -- and it is given up the moment something wants the memory: the expert slab's loan,
|
||||
* or an allocation the free list cannot serve. A conversation that comes back before either
|
||||
* happens resumes from VRAM for free; one that comes back after is restored from its host copy,
|
||||
* and KEEPS that copy, so the turn after it copies only the tokens that turn added.
|
||||
* Copy on idle, free on demand. An entry is copied to host memory as soon as the request that
|
||||
* published it finishes, and its VRAM copy is kept. The entry is then clean: giving up the VRAM
|
||||
* copy costs only the cache's reference, and that happens as soon as something wants the memory
|
||||
* (the expert slab's loan, or an allocation the free list cannot serve). A conversation that
|
||||
* returns earlier resumes from VRAM; one that returns later is restored from host and keeps the
|
||||
* host copy, so its next turn copies only the tokens that turn added.
|
||||
*
|
||||
* published --(copy, at once)--> clean on device --(memory wanted)--> host
|
||||
* ^ |
|
||||
* +------------(a hit restores)------+
|
||||
*
|
||||
* HOST MEMORY IS THE LAST TIER. When a copy needs a slot and the arena is full, the oldest
|
||||
* entries only the host holds are dropped, as many as the copies refused. Nothing is written to a
|
||||
* drive: a tier there wears it at the rate the server prefills -- every block and every snapshot a
|
||||
* prompt produces -- to spare a re-prefill only for what outgrows VRAM and host memory together.
|
||||
* Host memory is the last tier. When a copy needs a slot and the arena is full, the least
|
||||
* valuable host-only entries are dropped, one per copy refused, and only ones less valuable than
|
||||
* that copy: older, or as old and deeper in their chain. A copy nothing can make room for is not
|
||||
* taken and its entry stays in VRAM only. A conversation larger than the tier so keeps its start
|
||||
* on the host, the part a lookup reaches first, instead of dropping its first block for its last
|
||||
* one. Nothing goes to disk: a disk tier would be written at the prefill rate to save re-prefills
|
||||
* only for what outgrows VRAM and host memory together. Every entry also expires after
|
||||
* --prefix-cache-ttl seconds unused, from whichever tier holds it (PrefixCache::expire).
|
||||
*
|
||||
* AND EVERY ENTRY EXPIRES. One no request has used for --prefix-cache-ttl seconds leaves the cache
|
||||
* from whichever tier holds it (PrefixCache::expire); it is not moved anywhere first.
|
||||
* There is no idle threshold for leaving VRAM: a clean entry costs nothing to keep until the
|
||||
* memory is wanted and nothing to release once it is. Restoring a 200K-token prefix over PCIe
|
||||
* takes a fraction of a second; re-prefilling it takes minutes.
|
||||
*
|
||||
* THERE IS NO IDLE THRESHOLD ON THE WAY OUT OF VRAM, and that is the point of the design rather
|
||||
* than an omission. A threshold is a guess at when an entry stops being worth its VRAM, made in
|
||||
* seconds by an operator; a clean entry answers the question itself, because keeping it costs
|
||||
* nothing until the memory is wanted and releasing it costs nothing once it is.
|
||||
* This object moves no bytes. It decides what moves and hands out TierJob lists; the engine runs
|
||||
* them on its transfer stream and reports back, as with KVManager's BlockCopy and
|
||||
* take_pending_copies. core/mem has no stream, and the step path must not synchronise (spec §5.4).
|
||||
*
|
||||
* WHY MOVING BEATS DROPPING, stated once so the costs can be argued about in the right units:
|
||||
* dropping a 200K-token prefix costs a re-prefill, which is minutes. Restoring it costs a copy
|
||||
* over PCIe, which is a fraction of a second. The two are not the same order of magnitude.
|
||||
* Addressing: the pool is layer-major (core/mem/kv.h). Layer i of a paged group owns
|
||||
* `[base + i*layer_stride, + layer_stride)`, and a block within it starts at
|
||||
* `block_index * layer_bytes_per_block()`. A logical block is n_layers fragments of a few hundred
|
||||
* bytes, not one extent; `base + block * bytes_per_block` would address n_layers blocks of layer
|
||||
* zero. Such corruption yields fluent, plausible, wrong text. The unit of transfer is therefore
|
||||
* one layer of many blocks: within a layer blocks are dense rows, so packing is gather_rows and
|
||||
* restoring is scatter_rows, one launch per (group, layer) per batch.
|
||||
*
|
||||
* ============================== THIS OBJECT MOVES NO BYTES ======================================
|
||||
*
|
||||
* It decides WHAT should move and hands the work out as a list of TierJob. The engine executes
|
||||
* them on its transfer stream and reports back. That split is not decoration: `KVManager` already
|
||||
* works this way (BlockCopy, take_pending_copies) for the same reason -- core/mem has no stream,
|
||||
* and a synchronisation on the step path is what this design spends itself avoiding (spec §5.4).
|
||||
* A second mechanism for moving KV bytes would be a second place to get the pool's addressing
|
||||
* wrong.
|
||||
*
|
||||
* ============================== THE ADDRESSING, WHICH IS THE TRAP ==============================
|
||||
*
|
||||
* THE POOL IS LAYER-MAJOR (core/mem/kv.h). Layer i of a paged group owns
|
||||
* `[base + i*layer_stride, + layer_stride)`, and inside that a block is
|
||||
* `block_index * layer_bytes_per_block()`. A logical block is therefore NOT a contiguous extent:
|
||||
* it is `n_layers` fragments, one per layer, and on a production model a fragment is a few hundred
|
||||
* bytes. `base + block * bytes_per_block` addresses something else entirely -- roughly `n_layers`
|
||||
* consecutive blocks OF LAYER ZERO -- and a tier built on it moves other sequences' data and
|
||||
* restores a jumble. Corrupt KV does not read as babble; it reads as fluent, deterministic,
|
||||
* plausible, wrong text, and nothing short of a byte comparison against a known-good run finds it.
|
||||
*
|
||||
* So the unit of transfer here is not a block. It is A LAYER'S WORTH OF MANY BLOCKS, which is the
|
||||
* shape the pool is already in: within one layer the group's blocks are dense rows of
|
||||
* `layer_bytes_per_block()` each, so packing an arbitrary set of them is exactly `gather_rows`
|
||||
* and restoring them is exactly `scatter_rows`. One launch per (group, layer) per batch, however
|
||||
* many entries the batch holds.
|
||||
*
|
||||
* ============================== ONE RECORD, ONE TIER, ONE LIST ==================================
|
||||
*
|
||||
* An entry that can live in either of two tiers must not be on BOTH tiers' LRU lists: each tier's
|
||||
* eviction path then invalidates references the other holds, and every such pair is a
|
||||
* use-after-free. The rule here is that a key has exactly one Rec,
|
||||
* a Rec is in exactly one tier, and a Rec is in at most that tier's list. A CLEAN device record
|
||||
* is on no list: the copy it keeps off the card is what lets the VRAM copy go, and the tiers'
|
||||
* lists are for entries no longer in VRAM. A Rec with a transfer through the pool outstanding is
|
||||
* `pending` and is in no list either: it cannot be chosen as a victim, cannot be planned again,
|
||||
* and cannot be erased until the engine reports the job finished or failed.
|
||||
* One record, one tier, one list. If an entry sat on two tiers' LRU lists, each tier's eviction
|
||||
* would invalidate the other's references. So a key has exactly one Rec, in exactly one tier, on
|
||||
* at most that tier's list. A clean device record is on no list (the lists hold entries no longer
|
||||
* in VRAM). A Rec with a transfer outstanding is `pending` and on no list: it cannot be a victim,
|
||||
* be planned again or be erased until the engine reports the job.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/hostarena.h"
|
||||
@@ -81,11 +53,11 @@
|
||||
#include "mem/prefix.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
@@ -97,9 +69,8 @@ namespace rad {
|
||||
enum class KVTier : uint8_t { Device = 0, Host = 1 };
|
||||
const char* kv_tier_name(KVTier t);
|
||||
|
||||
/* What the engine is being asked to do. One job is one entry moving one step. The block ids are
|
||||
* carried in the job rather than looked up when it runs, because the whole point of `pending` is
|
||||
* that nothing may touch the record in between. */
|
||||
/* One entry moving one step. Block ids travel in the job because the record is `pending` and
|
||||
* must not be read until the job reports. */
|
||||
struct TierJob {
|
||||
enum class Kind : uint8_t {
|
||||
WriteBack, /* gather_rows out of the pool into a host slot; the entry stays in VRAM */
|
||||
@@ -108,18 +79,15 @@ struct TierJob {
|
||||
};
|
||||
Kind kind = Kind::WriteBack;
|
||||
BlockHash key;
|
||||
/* Per cached group, in PrefixCache::cached_groups() order. For a write-back these are the
|
||||
* blocks to read; for a promotion they are filled in by the engine with the blocks it
|
||||
* allocated. */
|
||||
/* Per cached group, in PrefixCache::cached_groups() order: the blocks to read for a
|
||||
* write-back, or the blocks the engine allocated for a promotion. */
|
||||
std::vector<int32_t> blocks;
|
||||
int32_t host_slot = -1;
|
||||
int64_t bytes = 0;
|
||||
|
||||
/* A PROMOTION THAT WAS NEVER STARTED, as opposed to one that failed part of the way through.
|
||||
* A restore reserves every block before it moves a byte, and a chain that did not fit is cut
|
||||
* where the reservation ran out: the entries past that point were not touched, their host
|
||||
* copies are exactly what they were, and they stay on the host tier. Only an entry whose
|
||||
* scatter may have run is dropped on failure. */
|
||||
/* Whether a promotion's scatter may have run. A restore reserves every block first and cuts
|
||||
* the chain where the reservation ran out; entries past the cut were never started and stay
|
||||
* on the host tier. Only a started promotion drops its entry on failure. */
|
||||
bool started = false;
|
||||
};
|
||||
|
||||
@@ -130,143 +98,117 @@ public:
|
||||
int64_t host_cap_bytes = 0; /* 0 is off */
|
||||
int64_t entry_bytes = 0; /* one entry: sum over cached groups of bytes_per_block */
|
||||
/* ---- the linear half ----
|
||||
* `ckpt_bytes` is ONE SNAPSHOT, every rank's shard of it, laid out exactly like
|
||||
* `entry_bytes`. The snapshots live in the engine's checkpoint store, `ckpt_slots` deep,
|
||||
* which is reported here and not allocated: --prefix-cache-mib is the blocks' alone. */
|
||||
* `ckpt_bytes` is one snapshot including every rank's shard, like `entry_bytes`. The
|
||||
* snapshots live in the engine's checkpoint store, `ckpt_slots` deep; reported here, not
|
||||
* allocated (--prefix-cache-mib covers blocks only). */
|
||||
int64_t ckpt_bytes = 0;
|
||||
int64_t ckpt_slots = 0; /* the checkpoint store's capacity, for the report and view */
|
||||
/* Tokens one entry covers (the cache's block size), for the report and the warning when
|
||||
* the tier cannot hold a conversation. */
|
||||
int64_t block_tokens = 0;
|
||||
};
|
||||
|
||||
int configure(const Config& c);
|
||||
void close();
|
||||
bool host_on() const { return cfg_.host_cap_bytes > 0 && arena_.enabled(); }
|
||||
bool any_on() const { return host_on(); }
|
||||
std::string report() const;
|
||||
|
||||
/* Called by PrefixCache whenever an entry is inserted. The blocks come with it because a copy
|
||||
* needs them and the map is the only place they would otherwise be read from -- at which point
|
||||
* the tiers would hold a second copy of the cache's own bookkeeping and the two could
|
||||
* disagree. A record with no host copy is queued for one here: publishing is the moment a
|
||||
* request has stopped writing the entry, which is the moment it can be copied. */
|
||||
void note_used(const BlockHash& key, const std::vector<int32_t>& blocks, uint64_t now_ns);
|
||||
/* THE HIT HALF OF THAT, for a lookup that matched `n` blocks of a chain. Only the idle clock
|
||||
* moves: a hit carries no new block ids, and it creates no record for an entry the tiers were
|
||||
* never told about. One lock for the whole chain, since a long prefix is thousands of blocks. */
|
||||
/* PrefixCache published this entry with these blocks. A record without a host copy is queued
|
||||
* for one: once published, the request has stopped writing it. `depth` is the entry's block
|
||||
* index in its chain; among entries used at the same moment the deeper one is worth less. */
|
||||
void note_used(const BlockHash& key, const std::vector<int32_t>& blocks, uint64_t now_ns,
|
||||
int64_t depth = 0);
|
||||
/* A lookup hit `n` blocks of a chain. Only the idle clock moves; no records are created. One
|
||||
* lock for the whole chain, since a long prefix is thousands of blocks. */
|
||||
void note_hits(const BlockHash* keys, int64_t n, uint64_t now_ns);
|
||||
/* The entry is gone from the cache for good -- evicted, or its blocks released. Any tier
|
||||
* storage it held is returned. A record with work outstanding is marked instead of erased and
|
||||
* is cleaned up when the job reports. */
|
||||
/* The entry left the cache for good; its tier storage is returned. A record with a job out is
|
||||
* marked `doomed` instead and erased when the job reports. */
|
||||
void forget(const BlockHash& key);
|
||||
/* AN OFF-DEVICE ENTRY WAS RECOMPUTED. A request that could not reach the host copy -- a
|
||||
* restore that did not fit, a chain past the point a promotion was cut -- computes the same
|
||||
* tokens again and publishes them, and the cache takes those blocks as the entry's device
|
||||
* copy. The tier copy goes: two copies of one entry computed by two different batches agree
|
||||
* only to the rounding the batch shape allows, and a record that called them the same bytes
|
||||
* would restore the older one over a pool that holds the newer. The record is a fresh device
|
||||
* record, queued for a copy of its own. */
|
||||
void rebound(const BlockHash& key, const std::vector<int32_t>& blocks, uint64_t now_ns);
|
||||
/* An off-device entry was recomputed by a request that could not reach the host copy, and the
|
||||
* cache took its blocks as the device copy. The tier copy is dropped (two batches' results
|
||||
* agree only to batch-shape rounding) and the record is requeued for a fresh copy. */
|
||||
void rebound(const BlockHash& key, const std::vector<int32_t>& blocks, uint64_t now_ns,
|
||||
int64_t depth = 0);
|
||||
|
||||
/* WHERE IS IT. Device for anything this object has never been told about, which is the right
|
||||
* answer: an entry the cache holds and the tiers have not touched is in the pool. */
|
||||
/* Device for keys this object has never seen: the cache holds them in the pool. */
|
||||
KVTier tier_of(const BlockHash& key) const;
|
||||
bool resident_off_device(const BlockHash& key) const;
|
||||
|
||||
/* ---------------- copy on idle ----------------
|
||||
*
|
||||
* 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. Blocks only: a snapshot is in host memory from the moment it is saved.
|
||||
* Up to `max_entries` records waiting for a host copy, oldest first, as WriteBack jobs with
|
||||
* host slots allocated. Blocks only: snapshots are already in host memory.
|
||||
*
|
||||
* Every record named by a returned job is `pending` until report() is called for it. What an
|
||||
* arena too full to take the batch cannot hold stays queued, and the next maintenance plan
|
||||
* drops that many of the oldest host-only entries. */
|
||||
* Each returned record is `pending` until report(). A job the full arena cannot take stays
|
||||
* queued when a host-only entry is worth less than it, and the next plan() drops one such
|
||||
* entry for it; otherwise it leaves the queue and its entry stays in VRAM only (Stats::
|
||||
* held_back, and a warning naming --prefix-cache-mib). */
|
||||
void plan_writeback(int64_t max_entries, std::vector<TierJob>* out);
|
||||
bool writeback_waiting() const;
|
||||
/* Has the arena refused a copy since the last maintenance plan? That plan is then due now. */
|
||||
/* The arena refused a copy since the last plan(), so a plan is due now. */
|
||||
bool starved() const;
|
||||
|
||||
/* THE VRAM COPIES THAT CAN GO, as the entries that became clean since the last call. The
|
||||
* cache decides whether each one actually goes -- a block a running sequence also holds would
|
||||
* free nothing -- and reports what it did through drop_commit. A key handed out here and not
|
||||
* dropped is the cache's to ask about again. */
|
||||
/* Entries that became clean since the last call. The cache decides whether each VRAM copy
|
||||
* actually goes (a block a running sequence holds would free nothing), reports drops through
|
||||
* drop_commit, and re-asks about the rest itself. */
|
||||
void take_clean(std::vector<BlockHash>* out);
|
||||
/* Can this entry's blocks leave VRAM for nothing, right now: its host copy has landed and no
|
||||
* job is out on the record. */
|
||||
/* Host copy landed and no job out: the blocks can leave VRAM at no cost. */
|
||||
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. Its snapshot stays in its slot: the store is not the pool, and
|
||||
* the blocks leaving frees nothing there. */
|
||||
/* The cache released the blocks; the record becomes a host record on the host list. Its
|
||||
* snapshot stays in its store slot. */
|
||||
void drop_commit(const BlockHash& key);
|
||||
|
||||
/* ---------------- capacity ----------------
|
||||
*
|
||||
* The copies the arena refused since the last plan are made room for by dropping that many of
|
||||
* the oldest host-only entries, as DropHost jobs; `budget` bounds one plan. */
|
||||
* Make room for the copies refused since the last plan, one DropHost job each, taking the
|
||||
* least valuable host-only entries and only ones worth less than the copy they make room
|
||||
* for; `budget` bounds one plan. */
|
||||
void plan(int budget, std::vector<TierJob>* out);
|
||||
|
||||
/* ---------------- expiry ----------------
|
||||
*
|
||||
* THE HOST RECORDS NO REQUEST HAS USED SINCE `cutoff_ns`, oldest first, up to `max`: what
|
||||
* --prefix-cache-ttl takes out of host memory. The cache drops each one (drop_offdevice) and
|
||||
* the record goes with it; a record with a job out is passed over and asked about again. */
|
||||
* Host records unused since `cutoff_ns`, oldest first, up to `max` (--prefix-cache-ttl). The
|
||||
* cache drops each one; records with a job out are not listed and are reconsidered later. */
|
||||
void expired(uint64_t cutoff_ns, size_t max, std::vector<BlockHash>* out) const;
|
||||
|
||||
/* A promotion, asked for by a lookup that hit off-device. Returns false when the entry is not
|
||||
* in host memory or already has work outstanding. */
|
||||
/* A promotion for a lookup that hit off-device. False when the entry is not in host memory or
|
||||
* has a job out. */
|
||||
bool plan_promote(const BlockHash& key, TierJob* out);
|
||||
|
||||
/* The engine finished (or failed) a job. On failure the record returns to the state it was in
|
||||
* with its storage intact, EXCEPT for a failed ToDevice that had started, which cannot leave a
|
||||
* half-scattered pool behind and so drops the entry. A successful ToDevice restarts the
|
||||
* record's clock at `now_ns` when one is given: the promotion happened because something is
|
||||
* about to use it. */
|
||||
/* The engine finished or failed a job. A failure restores the record's previous state with
|
||||
* its storage intact, except a started ToDevice, which may have half-scattered and so drops
|
||||
* the entry. A successful ToDevice restarts the record's clock at `now_ns` when nonzero. */
|
||||
void report(const TierJob& job, bool ok, uint64_t now_ns = 0);
|
||||
|
||||
/* WAS THIS KEY FORGOTTEN WHILE ITS JOB WAS OUT -- or is it not known at all. The engine asks
|
||||
* before acting on a finished job's blocks: an entry the cache evicted mid-transfer had its
|
||||
* references released by the eviction, and anything done in its name afterwards would be done
|
||||
* to blocks somebody else now holds. */
|
||||
/* The key was forgotten while its job was out, or is unknown. The engine checks this before
|
||||
* touching a finished job's blocks, which may now belong to another sequence. */
|
||||
bool doomed(const BlockHash& key) const;
|
||||
|
||||
/* ============================ WHEN THE BYTES ARE GONE, SO IS THE ENTRY ====================
|
||||
*
|
||||
* A record erased while its bytes are OFF-DEVICE -- a capacity drop, a promotion that failed,
|
||||
* an expiry -- leaves the prefix cache holding an entry whose block ids the pool has already
|
||||
* given to somebody else. `resident_off_device` then answers false, because there is no
|
||||
* record any more, and the cache would serve those ids as an ordinary hit: one conversation
|
||||
* gets another's context, as fluent and plausible text.
|
||||
*
|
||||
* So the tiers tell the cache, at every site that erases an off-device record, and the cache
|
||||
* drops the entry WITHOUT releasing blocks -- there are none of its own left to release. */
|
||||
/* Called at every site that erases an off-device record (capacity drop, failed promotion,
|
||||
* expiry). Without it the cache would keep the entry, resident_off_device would answer false,
|
||||
* and the stale block ids would be served as a hit. The cache drops the entry without
|
||||
* releasing blocks. */
|
||||
void set_drop_sink(std::function<void(const BlockHash&)> f) { on_drop_ = std::move(f); }
|
||||
|
||||
/* ---------------- the linear half of an idle session ----------------
|
||||
*
|
||||
* Told by PrefixCache::commit_checkpoint and PrefixCache::retire_ckpt, so the session view can
|
||||
* say which conversations hold a snapshot and where a return resumes from. A snapshot lives in
|
||||
* its checkpoint store slot, in host memory, and never moves: the tiers only record it. A
|
||||
* record may hear of a snapshot BEFORE it hears note_used -- a checkpoint is committed
|
||||
* mid-request and the chain is published when the request closes -- so this creates the
|
||||
* record if it has to. */
|
||||
* Called by PrefixCache::commit_checkpoint and retire_ckpt so the session view can show which
|
||||
* conversations hold a snapshot and where they resume. Snapshots stay in their store slots in
|
||||
* host memory; the tiers only record them. A checkpoint is committed mid-request, before the
|
||||
* chain is published, so this creates the record if needed. */
|
||||
void note_snapshot(const BlockHash& key, int32_t slot, int64_t pos);
|
||||
/* The cache is done with the snapshot at `key`. The record's BLOCKS are untouched -- the two
|
||||
* halves are retired by different policies on different clocks, and a snapshot the retention
|
||||
* policy drops says nothing about the prefix. */
|
||||
/* The cache retired the snapshot at `key`. The record's blocks are untouched: blocks and
|
||||
* snapshots are retired by different policies. */
|
||||
void release_snapshot(const BlockHash& key);
|
||||
int64_t ckpt_bytes() const { return cfg_.ckpt_bytes; }
|
||||
int64_t ckpt_slots() const { return cfg_.ckpt_slots; }
|
||||
|
||||
/* ---------------- the session view ----------------
|
||||
*
|
||||
* WHAT A SESSION IS HERE, because it is not what the cache is keyed by. The cache is keyed by
|
||||
* BLOCK, and a 200K-token conversation is twelve thousand of them -- an enumeration nobody can
|
||||
* read and not what anyone means by "session". A session is one PUBLISHED CHAIN: the blocks
|
||||
* one request inserted, named by its tip. That is exactly the leaf of the prefix trie, so two
|
||||
* conversations sharing a system prompt are two sessions and the shared blocks belong to both.
|
||||
*
|
||||
* THE SIZES THEREFORE OVERLAP AND THE TOTAL IS NOT A SUM. Sharing is the point of the cache;
|
||||
* a view that hid it would make a server look like it was storing several times what it is.
|
||||
* Anything reporting these numbers says so. */
|
||||
* The cache is keyed by block; a session is one published chain, the blocks one request
|
||||
* inserted, i.e. a leaf of the prefix trie. Two conversations sharing a system prompt are two
|
||||
* sessions that both own the shared blocks, so per-session sizes overlap and do not sum to
|
||||
* the total. Anything reporting these numbers must say so. */
|
||||
struct SessionInfo {
|
||||
uint64_t id = 0;
|
||||
std::string model;
|
||||
@@ -276,82 +218,74 @@ public:
|
||||
uint64_t first_seen_ns = 0;
|
||||
uint64_t last_used_ns = 0;
|
||||
int64_t on_device = 0, on_host = 0; /* blocks, by tier */
|
||||
/* LINEAR STATE, on a hybrid model. Counted separately from blocks because it is a
|
||||
* different resource with a different scarcity: a snapshot is thousands of blocks' worth
|
||||
* of bytes and there are only --checkpoint-slots of them in host memory. A session showing
|
||||
* blocks in host memory and no snapshot is one that will come back and re-run every
|
||||
* recurrent layer over its whole transcript, which is not what "restored" should mean. */
|
||||
/* Linear state on a hybrid model, counted apart from blocks: a snapshot is thousands of
|
||||
* blocks' worth of bytes and there are only --checkpoint-slots of them. */
|
||||
int64_t snapshots = 0; /* this session holds */
|
||||
int64_t snap_bytes = 0;
|
||||
/* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain. On a
|
||||
* hybrid model the scheduler clamps a hit to the last linear checkpoint it can
|
||||
* reach, so this -- not n_tokens and not the blocks -- is the prefix the next turn skips,
|
||||
* and n_tokens minus it is what that turn prefills. Zero with no snapshot anywhere. */
|
||||
/* Token position of the deepest snapshot on the chain, 0 if none. On a hybrid model hits
|
||||
* clamp to it, so this is what the next turn skips; n_tokens minus it gets prefilled. */
|
||||
int64_t resume_tokens = 0;
|
||||
bool moving = false; /* a job is outstanding */
|
||||
};
|
||||
/* WHAT HOST MEMORY IS HOLDING FOR THE CACHE, each block counted once. The per-session figures
|
||||
* cannot be summed into this: sessions sharing a prefix share its blocks. The cap is what the
|
||||
* operator configured. A clean entry's host copy is counted: it occupies the arena whether or
|
||||
* not the VRAM copy has gone yet. */
|
||||
/* Host memory held for the cache, each block counted once (including clean entries' copies),
|
||||
* and the configured cap. */
|
||||
struct Occupancy {
|
||||
int64_t host_bytes = 0;
|
||||
int64_t host_cap_bytes = 0;
|
||||
};
|
||||
/* Publish one request's chain. Called from PrefixCache::insert, which is the only place that
|
||||
* knows a chain was completed rather than merely touched.
|
||||
*
|
||||
* KEPT WHETHER OR NOT ANY TIER IS ON, because what it records is not a tiering fact. A server
|
||||
* with no --prefix-cache-mib still stores conversations -- it stores them all in VRAM, which
|
||||
* is the case the table most wants to show -- and gating the record on the mover would make
|
||||
* the view report an empty server to every operator who has not opted into tiering.
|
||||
*
|
||||
* ONE CONVERSATION IS ONE ROW, and the rule that makes it one is the trie: a session is a
|
||||
* LEAF, so a chain that a later turn extends has stopped being one and is absorbed into it.
|
||||
* Each turn publishes the chain it grew under its own request id, so without that the table
|
||||
* is a row per turn -- a table nobody can read, holding a copy of every prefix of the
|
||||
* transcript for as long as the newest. */
|
||||
/* Record one request's published chain (from PrefixCache::insert). Kept even with every tier
|
||||
* off, since a VRAM-only server still stores conversations. A session is a leaf, so a chain a
|
||||
* later turn extends is absorbed into it: one row per conversation, not per turn. */
|
||||
void note_session(uint64_t id, const std::vector<BlockHash>& chain, int64_t n_tokens,
|
||||
uint64_t now_ns, const std::string& label = std::string());
|
||||
void set_model(const std::string& m) { model_ = m; }
|
||||
/* Newest activity first. Recomputes each session's tier histogram from the records, so it is
|
||||
* a view and never a second copy of the truth. The walk takes the lock in slices and lets
|
||||
* every other taker go first between them (YieldingMutex), so rows read at different slices
|
||||
* may describe moments a few microseconds apart. */
|
||||
/* Newest activity first, tier histograms recomputed from the records. The walk takes the lock
|
||||
* in slices and yields between them (YieldingMutex), so rows may describe moments a few
|
||||
* microseconds apart. */
|
||||
std::vector<SessionInfo> sessions(Occupancy* occ = nullptr) const;
|
||||
void forget_session(uint64_t id);
|
||||
|
||||
struct Stats {
|
||||
/* `to_host` is entries COPIED to host memory; `dropped` is entries whose VRAM copy was
|
||||
* then given up. They are different events: a copy is link traffic and a drop is VRAM
|
||||
* handed to something else, and a conversation that returns before anything wants its
|
||||
* VRAM is copied and never dropped. */
|
||||
/* `to_host` counts copies to host memory (link traffic); `dropped` counts VRAM copies
|
||||
* then given up. An entry can be copied and never dropped. */
|
||||
int64_t to_host = 0, dropped = 0, promoted = 0;
|
||||
/* `host_drops` is entries the full arena gave up. */
|
||||
int64_t host_drops = 0, failures = 0;
|
||||
/* `host_drops` is entries the full arena gave up; `held_back` copies it did not take,
|
||||
* because every host entry was worth as much (their entries stay in VRAM only). */
|
||||
int64_t host_drops = 0, failures = 0, held_back = 0;
|
||||
int64_t host_bytes = 0;
|
||||
int64_t host_hits = 0;
|
||||
/* WHAT THE STEP THREAD SPENT ON THEM, under the scheduler's lock: restores issued at
|
||||
* admission, and copies landed synchronously because pressure could not wait for them.
|
||||
* Host time, not link time -- what every other request waits through. */
|
||||
/* Step-thread host time under the scheduler's lock: restores issued at admission, and
|
||||
* copies landed synchronously under pressure. Not link time. */
|
||||
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. */
|
||||
/* A copy taken under the lock; HTTP threads read it while the engine moves records. */
|
||||
Stats stats() const;
|
||||
HostArena& arena() { return arena_; }
|
||||
/* The size of ONE SLOT, which under tensor parallelism holds every rank's shard. */
|
||||
/* Bytes per slot; under tensor parallelism one slot holds every rank's shard. */
|
||||
int64_t entry_bytes() const { return cfg_.entry_bytes; }
|
||||
|
||||
private:
|
||||
/* The host list's order, least valuable first: least recently used, and among entries used
|
||||
* at the same moment (a chain is stamped with one clock) the deepest. */
|
||||
struct LruKey {
|
||||
uint64_t used_ns = 0;
|
||||
int64_t depth = 0;
|
||||
};
|
||||
struct LruOrder {
|
||||
bool operator()(const LruKey& a, const LruKey& b) const {
|
||||
return a.used_ns != b.used_ns ? a.used_ns < b.used_ns : a.depth > b.depth;
|
||||
}
|
||||
};
|
||||
using HostLru = std::multimap<LruKey, BlockHash, LruOrder>;
|
||||
|
||||
struct Rec {
|
||||
KVTier tier = KVTier::Device;
|
||||
uint64_t used_ns = 0;
|
||||
/* THE HOST COPY. On a device record it is a copy that makes the record clean; on a host
|
||||
* record it is where the bytes are read from. */
|
||||
int64_t depth = 0; /* block index in its chain (note_used) */
|
||||
/* Host copy: on a device record it makes the record clean; on a host record it is the
|
||||
* only copy. */
|
||||
int32_t host_slot = -1;
|
||||
bool pending = false;
|
||||
bool doomed = false; /* forget() arrived while pending */
|
||||
@@ -360,25 +294,24 @@ private:
|
||||
bool listed = false; /* on host_lru_; `it` is valid */
|
||||
std::vector<int32_t> blocks;
|
||||
/* ---- the linear half ----
|
||||
* `ck_slot` is the snapshot's checkpoint store slot and `ck_pos` its token position, for the
|
||||
* session view. -1 when the record carries no snapshot, which is the common case -- one
|
||||
* block in every (interval / block_size) is a checkpoint position. */
|
||||
* Snapshot store slot and token position, for the session view. `ck_slot` is -1 for most
|
||||
* records: one block in (interval / block_size) is a checkpoint position. */
|
||||
int32_t ck_slot = -1;
|
||||
int64_t ck_pos = 0;
|
||||
std::multimap<uint64_t, BlockHash>::iterator it;
|
||||
HostLru::iterator it;
|
||||
};
|
||||
|
||||
/* Does this record want a host copy it does not have yet? Its blocks are in VRAM with none. */
|
||||
/* Blocks in VRAM with no host copy yet. */
|
||||
bool wants_copy(const Rec& r) const;
|
||||
void queue_copy(const BlockHash& key, Rec& r);
|
||||
void queue_clean(const BlockHash& key, Rec& r);
|
||||
/* GIVE UP A HOST SLOT, the record's or a finished job's. Every block-arena free goes through
|
||||
* `give_slot`, because a freed slot is what unblocks a write-back that found the arena full.
|
||||
* `free_host` is the record's own. */
|
||||
/* Every block-arena free goes through give_slot, because a freed slot unblocks a stuck
|
||||
* write-back. free_host frees the record's own slot. */
|
||||
void give_slot(int32_t slot);
|
||||
void free_host(Rec& r);
|
||||
void unlist(Rec& r);
|
||||
void relist(const BlockHash& key, Rec& r);
|
||||
void touch(const BlockHash& key, Rec& r, uint64_t now_ns);
|
||||
|
||||
struct Session {
|
||||
int64_t n_tokens = 0;
|
||||
@@ -395,24 +328,15 @@ private:
|
||||
/* The body of close(), for a caller that already holds the lock. */
|
||||
void reset();
|
||||
|
||||
/* TWO THREADS REACH THIS OBJECT. The engine loop owns every mutation -- the cache publishes a
|
||||
* chain from the scheduler's close path, the maintenance pass moves records -- and an HTTP
|
||||
* thread drawing the sessions view walks the same containers through sessions(). An
|
||||
* unordered_map rehashed under an iterator is a crash rather than a stale number, so the
|
||||
* state the view reads is held under this and every mutator takes it.
|
||||
/* The engine loop makes every mutation; an HTTP thread walks the same containers in
|
||||
* sessions(), so every mutator takes this lock. No method calls another that takes it, so a
|
||||
* non-recursive mutex suffices; the drop sink runs under it and calls into the prefix cache,
|
||||
* which never calls back.
|
||||
*
|
||||
* NOT A BOTTLENECK, and it is worth saying where the cost lands: the per-block calls on the
|
||||
* publish path (note_used) take it once each, uncontended, against a hash insert they were
|
||||
* already paying for. No method here calls another that takes it, which is what keeps a plain
|
||||
* mutex sufficient; the drop sinks are called while it is held and reach into the prefix
|
||||
* cache, which never calls back.
|
||||
*
|
||||
* AND THE VIEW'S WALK MUST NOT DELAY THE ENGINE. It visits every block of every stored
|
||||
* conversation, which is far longer than any engine-side hold, and the engine takes this lock
|
||||
* every step. So the walk takes it for a slice of records at a time and, between slices,
|
||||
* waits until nobody else is waiting for it: an engine-side taker that arrives during a slice
|
||||
* waits for that slice and never for the walk. A plain mutex cannot promise that, because
|
||||
* the walker re-locking the moment it unlocks can win against a woken waiter every time. */
|
||||
* The view's walk is far longer than any engine-side hold, so it locks one slice of records
|
||||
* at a time and, between slices, waits until no other taker is waiting. An engine thread then
|
||||
* waits at most one slice. A plain mutex cannot promise that: the walker could re-lock ahead
|
||||
* of a woken waiter every time. */
|
||||
struct YieldingMutex {
|
||||
std::mutex m;
|
||||
std::atomic<int> waiting{0};
|
||||
@@ -437,32 +361,25 @@ private:
|
||||
Config cfg_;
|
||||
HostArena arena_;
|
||||
std::unordered_map<BlockHash, Rec, BlockHashHash> recs_;
|
||||
/* THE HOST-ONLY RECORDS BY LAST USE, begin() the least recently used. Keyed by the clock rather
|
||||
* than kept in the order records arrive, because a record arrives here when its VRAM copy is
|
||||
* given up, which says nothing about when a request last read it -- and both the capacity drop
|
||||
* and the expiry take the oldest by use. */
|
||||
std::multimap<uint64_t, BlockHash> host_lru_;
|
||||
/* THE WORK QUEUES, in the order the work arrived. Each holds a key at most once -- the Rec's
|
||||
* flag says whether it is in -- and a key whose record changed under it is skipped when it is
|
||||
* reached rather than searched for, so both stay a push and a pop. */
|
||||
/* Host-only records by value, begin() least valuable (LruOrder). Keyed by the clock, not
|
||||
* arrival order: a record arrives when its VRAM copy goes, which says nothing about its last
|
||||
* use. */
|
||||
HostLru host_lru_;
|
||||
/* Work queues in arrival order. Each key appears at most once (the Rec's flag says so); a
|
||||
* key whose record changed is skipped when reached rather than searched for. */
|
||||
std::deque<BlockHash> wb_q_; /* records wanting a host copy */
|
||||
std::vector<BlockHash> clean_q_; /* records whose VRAM copy may now go */
|
||||
/* COPIES THE ARENA REFUSED since the last maintenance plan, which is what that plan frees
|
||||
* room for. A count and not a list: any host-only entry makes room for any copy. */
|
||||
int64_t starved_ = 0;
|
||||
/* A WRITE-BACK FOUND THE ARENA FULL AND NOTHING TO GIVE UP. Waiting again changes nothing until
|
||||
* a slot is freed, so the copy is not planned until one is -- otherwise every tick pops the
|
||||
* queue, finds no slot and puts it back. */
|
||||
/* For each copy the arena refused since the last plan() that a host-only entry is worth less
|
||||
* than, its own value, most valuable first; plan() drops one entry worth less for each. */
|
||||
std::vector<LruKey> room_;
|
||||
uint64_t held_back_warned_ns_ = 0;
|
||||
/* A write-back found the arena full with nothing to drop; no copy is planned until a slot is
|
||||
* freed, so ticks do not spin on the queue. */
|
||||
bool wb_stuck_ = false;
|
||||
std::unordered_map<uint64_t, Session> sessions_;
|
||||
/* THE DEATH SIGNAL FOR A ROW, and the reason the table is bounded. A published chain is only
|
||||
* ever reachable from position zero, so the moment the cache evicts its FIRST block the
|
||||
* conversation cannot be hit at any length and the row describes blocks that are not there.
|
||||
* The cache announces its evictions and expiries through forget(), and the entries this object
|
||||
* drops itself -- a full arena's, a failed restore's -- go through drop_rooted as well, so the
|
||||
* root is indexed and the row goes with it. Several sessions share a root when
|
||||
* they share a system prompt and all of them are unreachable together, which is why the value
|
||||
* is a list. */
|
||||
/* Sessions by first block. A chain is reachable only from position zero, so once its first
|
||||
* block goes (forget(), or a drop here via drop_rooted) its rows go too; this keeps the table
|
||||
* bounded. Sessions sharing a system prompt share a root, hence a list. */
|
||||
std::unordered_map<BlockHash, std::vector<uint64_t>, BlockHashHash> roots_;
|
||||
std::string model_;
|
||||
std::function<void(const BlockHash&)> on_drop_;
|
||||
|
||||
+45
-95
@@ -1,4 +1,4 @@
|
||||
/* pools.cpp -- see pools.h. Every refusal in here names what did not fit and by how much. */
|
||||
/* pools.cpp -- see pools.h. */
|
||||
#include "mem/pools.h"
|
||||
|
||||
#include <cstdlib>
|
||||
@@ -18,10 +18,8 @@ public:
|
||||
const char* name() const override { return "device"; }
|
||||
};
|
||||
|
||||
/* aligned_alloc, at the pool alignment. Used by the no-ROCm build and by the tests. A pool's base
|
||||
* is 2 MiB-aligned either way, because the .rad's pool alignment is 2 MiB and huge-page mappable
|
||||
* (spec §4.1) and a slab whose base is not aligned makes every fixed-stride slot inside it
|
||||
* misaligned as well. */
|
||||
/* aligned_alloc at the 2 MiB pool alignment (the .rad pool alignment, huge-page mappable, spec
|
||||
* §4.2), so fixed-stride slots in a slab stay aligned. Used by the no-ROCm build and the tests. */
|
||||
class MallocAllocator final : public MemAllocator {
|
||||
public:
|
||||
void* alloc(int64_t bytes, int kind) override {
|
||||
@@ -46,7 +44,7 @@ std::string Shortfall::str() const {
|
||||
if (!refused.empty())
|
||||
return fmt("%s: %s of %s refused: %s", pool.c_str(), what.c_str(),
|
||||
humanb(wanted).c_str(), refused.c_str());
|
||||
return fmt("%s: %s wanted %s, %s available -- short by %s",
|
||||
return fmt("%s: %s wanted %s, %s available, short by %s",
|
||||
pool.c_str(), what.c_str(), humanb(wanted).c_str(),
|
||||
humanb(available).c_str(), humanb(missing()).c_str());
|
||||
}
|
||||
@@ -56,9 +54,8 @@ std::string Shortfall::str() const {
|
||||
Pool::~Pool() { release(); }
|
||||
|
||||
void Pool::release() {
|
||||
/* ELASTIC FIRST, because an elastic pool has no allocator-owned base: vm_ owns the address
|
||||
* range and the pages in it, and handing that pointer to MemAllocator::free would be a free
|
||||
* of memory the allocator never handed out. */
|
||||
/* An elastic pool's base belongs to vm_, not the allocator, so it must not reach
|
||||
* MemAllocator::free. */
|
||||
if (elastic_) {
|
||||
vm_.release();
|
||||
elastic_ = false;
|
||||
@@ -69,23 +66,23 @@ void Pool::release() {
|
||||
bytes_ = used_ = 0;
|
||||
}
|
||||
|
||||
int Pool::init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a, bool accounting) {
|
||||
void Pool::reset(std::string_view nm, int64_t bytes, int kind, MemAllocator* a) {
|
||||
release();
|
||||
name_ = std::string(nm);
|
||||
bytes_ = bytes;
|
||||
used_ = 0;
|
||||
kind_ = kind;
|
||||
accounting_ = accounting;
|
||||
alloc_ = a;
|
||||
shortfalls_.clear();
|
||||
res_.clear();
|
||||
if (accounting_ || bytes_ <= 0) return RAD_OK;
|
||||
}
|
||||
|
||||
int Pool::init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a) {
|
||||
reset(nm, bytes, kind, a);
|
||||
if (bytes_ <= 0) return RAD_OK;
|
||||
|
||||
base_ = a->alloc(bytes_, kind);
|
||||
if (!base_) {
|
||||
/* Refuse; do not retry smaller. An engine that quietly re-optimises the split is an
|
||||
* engine whose benchmarks do not reproduce (spec §6). The allocator's reason goes with
|
||||
* it: the device layer says what the driver answered. */
|
||||
/* Refuse; never retry smaller (spec §6). Record the driver's reason. */
|
||||
const char* why = a == &rad_device_allocator() ? rad_dev_last_error() : nullptr;
|
||||
shortfalls_.push_back({name_, "backing allocation", bytes_, 0,
|
||||
why && *why ? why : "the allocator returned nothing"});
|
||||
@@ -105,38 +102,24 @@ void* Pool::reserve(std::string_view what, int64_t bytes, int64_t align, int64_t
|
||||
used_ = off + bytes;
|
||||
res_.push_back({std::string(what), off, bytes});
|
||||
if (off_out) *off_out = off;
|
||||
if (accounting_) return nullptr; /* headroom: accounted, never touched */
|
||||
return (char*)base_ + off;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ elastic */
|
||||
|
||||
int64_t Pool::granule() { return VMem::granularity(); }
|
||||
|
||||
int Pool::init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocator* a) {
|
||||
/* WITHOUT VIRTUAL MEMORY MANAGEMENT THIS IS init(). The caller does not branch: it commits
|
||||
* what it wants, the commits succeed against memory that was already there, and the pool
|
||||
* holds its maximum for the whole run. That is worse than elastic and identical to a fixed
|
||||
* pool, which is the right shape for a fallback. */
|
||||
/* Without virtual memory management this is init(): commits succeed against memory that is
|
||||
* already there and the pool holds its maximum for the whole run. */
|
||||
if (!VMem::supported() || kind != RAD_MEM_DEVICE)
|
||||
return init(nm, bytes, kind, a, /*accounting=*/false);
|
||||
return init(nm, bytes, kind, a);
|
||||
|
||||
release();
|
||||
name_ = std::string(nm);
|
||||
bytes_ = bytes;
|
||||
used_ = 0;
|
||||
kind_ = kind;
|
||||
accounting_ = false;
|
||||
alloc_ = a;
|
||||
shortfalls_.clear();
|
||||
res_.clear();
|
||||
reset(nm, bytes, kind, a);
|
||||
if (bytes_ <= 0) return RAD_OK;
|
||||
|
||||
const int rc = vm_.reserve(bytes_, RAD_ALIGN_POOL);
|
||||
if (rc < 0) {
|
||||
/* Refuse; do not retry smaller. An address range is not memory -- a reservation that
|
||||
* fails on a 64-bit card is a bug and not a budget, and quietly halving it would hide the
|
||||
* bug behind a pool that cannot grow to what the operator asked for. */
|
||||
/* Refuse; never retry smaller. A failed address reservation on a 64-bit card is a bug,
|
||||
* not a budget limit. */
|
||||
const char* why = rad_dev_last_error();
|
||||
shortfalls_.push_back({ name_, "address reservation", bytes_, 0,
|
||||
*why ? why : "the device layer gave no reason" });
|
||||
@@ -144,45 +127,34 @@ int Pool::init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocato
|
||||
return rc;
|
||||
}
|
||||
base_ = vm_.base();
|
||||
/* THE RANGE ROUNDS UP AND THE BUDGET DOES NOT. vm_.size() is the reservation rounded to a
|
||||
* whole granule, which is a fact about the driver and not a licence to spend more than the
|
||||
* split allowed. Taking it as the budget lets a pool grow into the headroom by up to a
|
||||
* granule and, worse, GRANT a reservation the budget should have refused -- the same quiet
|
||||
* re-optimisation of the split that init() refuses to make when its allocation fails.
|
||||
*
|
||||
* The rounded tail stays addressable, and that is what it is for: the last reservation can
|
||||
* end mid-granule and its commit rounds outward into a range that is really reserved. */
|
||||
/* bytes_ stays the requested budget, not vm_.size() (rounded up to a granule): using the
|
||||
* rounded size would let reserve() grant more than the split allows. The rounded tail stays
|
||||
* reserved so the last reservation's commit can round outward into it. */
|
||||
elastic_ = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Pool::commit(int64_t off, int64_t bytes) {
|
||||
if (!elastic_) {
|
||||
/* A fixed pool is backed everywhere inside it and nowhere outside it, and saying so is
|
||||
* what keeps a caller written against the elastic contract correct here. */
|
||||
/* A fixed pool is backed everywhere inside its range and nowhere outside it. */
|
||||
return (off >= 0 && bytes >= 0 && off + bytes <= bytes_) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
return vm_.commit(off, bytes);
|
||||
}
|
||||
|
||||
int Pool::decommit(int64_t off, int64_t bytes) {
|
||||
if (!elastic_) return RAD_OK; /* nothing to give back, and that is not an error */
|
||||
if (!elastic_) return RAD_OK; /* nothing to give back */
|
||||
return vm_.decommit(off, bytes);
|
||||
}
|
||||
|
||||
bool Pool::is_committed(int64_t off, int64_t bytes) const {
|
||||
if (!elastic_) return off >= 0 && bytes >= 0 && off + bytes <= bytes_;
|
||||
return vm_.is_committed(off, bytes);
|
||||
}
|
||||
|
||||
std::string Pool::report() const {
|
||||
std::string s = fmt("%-14s %10s budget, %10s used, %10s free%s\n",
|
||||
std::string s = fmt("%-14s %10s budget, %10s used, %10s free\n",
|
||||
name_.c_str(), humanb(bytes_).c_str(), humanb(used_).c_str(),
|
||||
humanb(avail()).c_str(), accounting_ ? " (accounted, not allocated)" : "");
|
||||
humanb(avail()).c_str());
|
||||
for (const auto& r : res_)
|
||||
s += fmt(" %-24s %10s @ +%lld\n", r.what.c_str(), humanb(r.bytes).c_str(),
|
||||
(long long)r.off);
|
||||
for (const auto& f : shortfalls_) s += " REFUSED " + f.str() + "\n";
|
||||
for (const auto& f : shortfalls_) s += " " + f.str() + "\n";
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -201,12 +173,9 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
const int64_t kv = cfg.vram_kv_mib * MiB;
|
||||
const int64_t hp = cfg.host_pool_total_mib() * MiB;
|
||||
|
||||
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM.
|
||||
* core/mem/vram_budget.cpp derived them from the card, the measured driver residency and the
|
||||
* computed arena, and they arrive here as two numbers with a report behind them. This
|
||||
* component refuses rather than shrinking anything: an engine that quietly re-optimises a
|
||||
* split is an engine whose benchmarks do not reproduce (spec §6). A zero here means the
|
||||
* resolver was never called, which is a wiring bug and gets named as one. */
|
||||
/* The budgets were resolved by core/mem/vram_budget.cpp (from the card, the measured driver
|
||||
* residency and the computed arena); this refuses rather than re-deciding them (spec §6). A
|
||||
* zero means the resolver never ran, which is a wiring bug. */
|
||||
std::string missing;
|
||||
if (cfg.vram_weights_mib <= 0) missing += " vram_weights resolved to 0 MiB\n";
|
||||
if (cfg.vram_kv_mib <= 0) missing += " vram_kv resolved to 0 MiB\n";
|
||||
@@ -219,7 +188,6 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
|
||||
const int64_t want = w + kv;
|
||||
if (vram_capacity > 0 && want > vram_capacity) {
|
||||
/* Name every pool and the total overage. Refuse rather than shrinking any of them. */
|
||||
fit_report_ = fmt(
|
||||
"VRAM budgets do not fit:\n"
|
||||
" vram_weights %10s\n"
|
||||
@@ -227,7 +195,7 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
" ------------------------\n"
|
||||
" total %10s\n"
|
||||
" card total %10s\n"
|
||||
" OVER BY %10s\n"
|
||||
" over by %10s\n"
|
||||
"The resolved split is larger than the card, which the resolver does not produce: a "
|
||||
"wiring bug (spec §6).\n",
|
||||
humanb(w).c_str(), humanb(kv).c_str(),
|
||||
@@ -239,39 +207,21 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
|
||||
int st = RAD_OK;
|
||||
int s;
|
||||
/* Order matters only for the diagnostic: allocate the two big ones first so a failure names
|
||||
* the one that actually could not be served. */
|
||||
if ((s = weights_.init("vram_weights", w, RAD_MEM_DEVICE, device, false)) < 0) st = s;
|
||||
/* THE KV POOL IS THE ELASTIC ONE, ALWAYS, AND THERE IS NO OTHER MODE. Its budget is still the
|
||||
* budget: elasticity does not change how much of the card the cache may address, it changes
|
||||
* whether the part it is not addressing has VRAM behind it. What the cache releases is what
|
||||
* the expert plane can promote into, so the split between them stops being a guess made once
|
||||
* at startup and becomes the two pools' actual demand.
|
||||
*
|
||||
* THERE IS NO FLAG, BECAUSE A FLAG IS THE WRONG SHAPE FOR IT. A fixed pool holds every block
|
||||
* it was carved for whether or not a single token is in it, and an expert plane that does not
|
||||
* fit streams weights over the link for the whole run to pay for cache nobody is using. There
|
||||
* is no deployment that wants that. A device with no virtual memory management goes through
|
||||
* the same call -- init_elastic() allocates the range whole there, which is fixed-pool
|
||||
* behaviour under a contract the callers already meet. */
|
||||
/* Order matters only for diagnostics: the two big pools go first so a failure names the one
|
||||
* that could not be served. */
|
||||
if ((s = weights_.init("vram_weights", w, RAD_MEM_DEVICE, device)) < 0) st = s;
|
||||
/* The KV pool is always elastic. Its budget still caps what the cache may address; elasticity
|
||||
* only decides whether the unused part has VRAM behind it. What the cache releases, the
|
||||
* expert plane can promote into, so the split follows actual demand. There is no fixed-pool
|
||||
* option: it would hold every block whether used or not while experts stream over the link.
|
||||
* Without virtual memory management init_elastic() allocates the range whole. */
|
||||
if ((s = kv_.init_elastic("vram_kv", kv, RAD_MEM_DEVICE, device)) < 0) st = s;
|
||||
/* MAPPED, NOT MERELY PINNED, AND THE DIFFERENCE IS A WHOLE TIER.
|
||||
*
|
||||
* This one pool serves two jobs: the mover's staging buffers and O_DIRECT landing zone, which
|
||||
* want pinned memory so a transfer is a DMA with no driver bounce -- and the ZERO-COPY
|
||||
* execution site, row three of spec §5.1's table, where the bytes stay in host memory and the
|
||||
* kernel reads them over the link as it computes. The second needs the allocation to be
|
||||
* addressable FROM A KERNEL, and hipHostMallocDefault does not make it so.
|
||||
*
|
||||
* Getting it wrong is silent and total: Mover::init asks rad_dev_device_ptr for the pool's
|
||||
* base as the card sees it, an unmapped allocation answers null, and the fallback is the host
|
||||
* pointer -- so `assign_expert_tiered`, which routes EVERY pooled expert to
|
||||
* Site::DeviceZeroCopy, would hand a kernel a pointer it cannot dereference. There would be no
|
||||
* hybrid tier, only a plan that says there is one.
|
||||
*
|
||||
* Mapped memory is still pinned, so job one is unaffected; hipHostMallocMapped is strictly the
|
||||
* larger promise. On the host backend all four kinds are the same aligned pages. */
|
||||
if ((s = host_ .init("host_pool", hp, RAD_MEM_HOST_MAPPED, host, false)) < 0) st = s;
|
||||
/* Mapped, not merely pinned. The host pool holds the mover's staging buffers and O_DIRECT
|
||||
* landing zone, and the zero-copy execution site (spec §5.1), where kernels read weights over
|
||||
* the link and so need a kernel-addressable base: with hipHostMallocDefault,
|
||||
* rad_dev_device_ptr returns null in Mover::init and Site::DeviceZeroCopy experts get an
|
||||
* unusable pointer. On the host backend all memory kinds are the same aligned pages. */
|
||||
if ((s = host_ .init("host_pool", hp, RAD_MEM_HOST_MAPPED, host)) < 0) st = s;
|
||||
|
||||
fit_report_ = weights_.report();
|
||||
fit_report_ += kv_.report();
|
||||
|
||||
+48
-79
@@ -1,22 +1,17 @@
|
||||
/* pools.h -- explicit pool budgets (spec §6).
|
||||
*
|
||||
* Every pool is budgeted EXPLICITLY. No profiling pass, no utilisation fraction, no inference
|
||||
* about what the workload will be. The trade between KV blocks and resident weights is real and
|
||||
* workload-dependent -- a long-context low-concurrency server and a short-context high-concurrency
|
||||
* one want opposite splits -- but it is the operator's to make. An engine that quietly
|
||||
* re-optimises the split is an engine whose benchmarks do not reproduce.
|
||||
* Every pool is budgeted explicitly: no profiling pass, no utilisation fraction. The KV vs
|
||||
* weights split depends on the workload, and an engine that re-optimises it on its own does not
|
||||
* produce reproducible benchmarks.
|
||||
*
|
||||
* Two properties this file exists to make STRUCTURAL rather than conventional:
|
||||
* Two structural properties:
|
||||
*
|
||||
* 1. A Pool holds a base, a size and a cursor, and has no pointer to any other Pool. There is
|
||||
* no allocate-from-wherever call anywhere in this header. Therefore no code path exists
|
||||
* along which the mover's expert promotion (spec §5.4) can reach a KV block: the mover is
|
||||
* handed Pools::weights() and it is not possible to reach Pools::kv() from it. That is the
|
||||
* whole reason the weight slab is a fixed budget.
|
||||
* 1. A Pool holds a base, a size and a cursor, and no pointer to any other Pool. The mover is
|
||||
* handed Pools::weights() only, so expert promotion (spec §5.4) cannot reach a KV block.
|
||||
*
|
||||
* 2. A reservation that does not fit returns null and RECORDS the shortfall by name and by how
|
||||
* much. It never falls through to another pool, never shrinks an earlier reservation, and
|
||||
* never silently rounds the request down. The engine refuses to start instead.
|
||||
* 2. A reservation that does not fit returns null and records the shortfall by name and size.
|
||||
* It never falls through to another pool, shrinks an earlier reservation or rounds down;
|
||||
* the engine refuses to start instead.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
@@ -30,11 +25,9 @@
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ the allocator seam */
|
||||
/* Everything here goes through an allocator object rather than calling rad_dev_alloc directly.
|
||||
* The host backend is the primary development target and not a fallback
|
||||
* (docs/IMPLEMENTATION.md), and a pool test that cannot run without ROCm is a pool test that does
|
||||
* not run. The device allocator is the default; the malloc one is what the no-device build and
|
||||
* the tests use. */
|
||||
/* Pools allocate through this interface rather than rad_dev_alloc so they run without ROCm: the
|
||||
* host backend is a primary target (docs/IMPLEMENTATION.md). The device allocator is the default;
|
||||
* the malloc one serves the no-device build and the tests. */
|
||||
class MemAllocator {
|
||||
public:
|
||||
virtual ~MemAllocator() = default;
|
||||
@@ -47,28 +40,22 @@ MemAllocator& rad_device_allocator(); /* rad_dev_alloc / rad_dev_free */
|
||||
MemAllocator& rad_malloc_allocator(); /* aligned_alloc; host-only builds and tests */
|
||||
|
||||
/* ------------------------------------------------------------------ shortfalls */
|
||||
/* What did not fit, by name and by how much. Every refusal in this component produces one of
|
||||
* these rather than a bare RAD_E_NOMEM, because "it returned -6" is not a diagnosis. */
|
||||
/* What did not fit, by name and by how much. Every refusal here produces one, not just a bare
|
||||
* RAD_E_NOMEM. */
|
||||
struct Shortfall {
|
||||
std::string pool; /* which budget: "vram_weights", "vram_kv", ... */
|
||||
std::string what; /* what was being reserved when it ran out */
|
||||
int64_t wanted = 0;
|
||||
int64_t available = 0;
|
||||
/* A backing allocation the allocator refused: there is no "available" to report, only the
|
||||
* allocator's own sentence for why, which is what tells an out-of-memory card from a pinned-
|
||||
* memory limit from a driver that would not map the range. */
|
||||
/* Set when the allocator refused a backing allocation: its reason (out of memory, pinned
|
||||
* limit, mapping failure). `available` is meaningless then. */
|
||||
std::string refused;
|
||||
int64_t missing() const { return wanted - available; }
|
||||
std::string str() const;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ Pool */
|
||||
/* One reservation, made once, that never grows, never shrinks and never borrows.
|
||||
*
|
||||
* `accounting_only` pools hold no memory: the headroom budget is memory we promise NOT to touch,
|
||||
* for activations and the arena (spec §6). The arena owner still reserves against it, so an arena
|
||||
* that would exceed the headroom refuses at startup by name instead of succeeding here and
|
||||
* failing the first prefill on the device. */
|
||||
/* One reservation, made once, that never grows, never shrinks and never borrows. */
|
||||
class Pool {
|
||||
public:
|
||||
Pool() = default;
|
||||
@@ -82,70 +69,55 @@ public:
|
||||
int64_t avail() const { return bytes_ - used_; }
|
||||
void* base() const { return base_; }
|
||||
int kind() const { return kind_; }
|
||||
bool accounting_only() const { return accounting_; }
|
||||
|
||||
/* Carve `bytes` at `align`. Returns the pointer (null for an accounting-only pool, which
|
||||
* still tracks the cursor), or null with a recorded shortfall if it does not fit.
|
||||
* `off_out`, when given, receives the byte offset from base -- which is what a slab of
|
||||
* fixed-stride slots actually wants, since the offset survives a base that is a device
|
||||
* pointer nobody may dereference on the host. */
|
||||
/* Carve `bytes` at `align`. Returns the pointer, or null with a recorded shortfall if it does
|
||||
* not fit.
|
||||
* `off_out` receives the byte offset from base, which fixed-stride slabs use because the base
|
||||
* may be a device pointer the host cannot dereference. */
|
||||
void* reserve(std::string_view what, int64_t bytes, int64_t align, int64_t* off_out = nullptr);
|
||||
|
||||
/* True when nothing was refused. Checked once, at the end of startup, so the report names
|
||||
* every failure rather than the first one at the top (spec §3.1's rule, applied here). */
|
||||
/* True when nothing was refused. Checked once at the end of startup so the report names every
|
||||
* failure, not only the first (spec §3.1). */
|
||||
bool ok() const { return shortfalls_.empty(); }
|
||||
|
||||
/* ---- elastic pools ----------------------------------------------------------------------
|
||||
*
|
||||
* An elastic pool reserves its ADDRESS RANGE whole and backs only the part somebody has asked
|
||||
* for. Every offset reserve() hands out is final from the first call, so a slab stride or a
|
||||
* layer stride computed against the full range stays correct while the physical memory behind
|
||||
* the unused part goes back to the card for another pool to take. That is the only way two
|
||||
* pools on one card can trade: the addresses cannot move, so the pages have to.
|
||||
* An elastic pool reserves its whole address range and backs only the parts that are
|
||||
* committed. Offsets from reserve() are final, so strides computed against the full range
|
||||
* stay valid while unused pages go back to the card for another pool. Addresses cannot move
|
||||
* between pools; pages can.
|
||||
*
|
||||
* The two pools this exists for are the KV cache and the expert slab, and the trade is not
|
||||
* symmetric. A KV block holds a sequence's state and can only be given back once nothing
|
||||
* holds it; an expert slot holds a COPY of a weight that also lives in the host pool or the
|
||||
* container, so it can be given back whenever the mover can spare it. That asymmetry is the
|
||||
* policy's, not this file's -- what is here is the mechanism and the refusal.
|
||||
* Used by the KV cache and the expert slab. A KV block can be released only once nothing
|
||||
* holds it; an expert slot is a copy of a weight that also lives in host memory or the
|
||||
* container, so the mover can release it at will. That policy lives with the callers.
|
||||
*
|
||||
* A pool is elastic only where the device layer has virtual memory management (VMem in
|
||||
* core/device/device.h). Where it does not, init_elastic() allocates the whole range exactly
|
||||
* as init() does and commit()/decommit() are no-ops that succeed: a caller written for an
|
||||
* elastic pool runs unchanged against a fixed one, holding the maximum it was reserved. That
|
||||
* is the degradation spec §6 allows, because the pool is still one explicit budget -- it is
|
||||
* simply one that cannot give anything back. */
|
||||
* Without virtual memory management (VMem in core/device/device.h), init_elastic() allocates
|
||||
* the whole range like init() and commit()/decommit() succeed as no-ops, so callers run
|
||||
* unchanged against a fixed pool that holds its maximum (allowed by spec §6). */
|
||||
bool elastic() const { return elastic_; }
|
||||
int64_t committed() const { return elastic_ ? vm_.committed() : bytes_; }
|
||||
|
||||
/* Back [off, off+bytes) so a kernel may touch it. Rounds OUTWARD to the commit granule, so
|
||||
* what was asked for is certainly backed, and is idempotent: a pool growing to n asks for
|
||||
* [0, n) every time n changes and pays only for the part that is new. */
|
||||
/* Back [off, off+bytes) so a kernel may touch it. Rounds outward to the commit granule and is
|
||||
* idempotent: a pool growing to n may commit [0, n) each time and pays only for the new part. */
|
||||
int commit(int64_t off, int64_t bytes);
|
||||
|
||||
/* Hand the pages back. Rounds INWARD, so a granule holding one byte the caller still wants
|
||||
* stays -- a caller that shrinks to exactly the boundary it is holding is therefore safe, and
|
||||
* one that shrinks between boundaries simply keeps a granule it will use next time. */
|
||||
/* Release the pages. Rounds inward, so a granule with any byte still in use stays backed. */
|
||||
int decommit(int64_t off, int64_t bytes);
|
||||
|
||||
bool is_committed(int64_t off, int64_t bytes) const;
|
||||
|
||||
/* The commit quantum, so a caller can pick grow steps that do not strand a fraction of one in
|
||||
* every stripe. 0 when the pool is not elastic. */
|
||||
static int64_t granule();
|
||||
|
||||
const std::vector<Shortfall>& shortfalls() const { return shortfalls_; }
|
||||
|
||||
std::string report() const;
|
||||
|
||||
private:
|
||||
/* Reserve the address range and back nothing. `bytes` is the MAXIMUM the pool may ever hold
|
||||
* and is what reserve() carves against; what it costs the card is committed(). Falls back to
|
||||
* a whole allocation where the device layer has no virtual memory management. */
|
||||
/* Reserve the address range and back nothing. `bytes` is the maximum the pool may ever hold
|
||||
* and what reserve() carves against; committed() is what it costs the card. Falls back to a
|
||||
* whole allocation without virtual memory management. */
|
||||
int init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocator* a);
|
||||
|
||||
friend class Pools;
|
||||
int init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a, bool accounting);
|
||||
int init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a);
|
||||
/* release(), then name the pool and set its budget with nothing reserved. */
|
||||
void reset(std::string_view nm, int64_t bytes, int kind, MemAllocator* a);
|
||||
void release();
|
||||
|
||||
std::string name_;
|
||||
@@ -153,7 +125,6 @@ private:
|
||||
int64_t used_ = 0;
|
||||
void* base_ = nullptr;
|
||||
int kind_ = RAD_MEM_DEVICE;
|
||||
bool accounting_ = false;
|
||||
bool elastic_ = false;
|
||||
VMem vm_;
|
||||
MemAllocator* alloc_ = nullptr;
|
||||
@@ -165,12 +136,11 @@ private:
|
||||
/* ------------------------------------------------------------------ Pools */
|
||||
class Pools {
|
||||
public:
|
||||
/* `vram_capacity` is what the device reports free. Pass 0 to skip the capacity check, which
|
||||
* is what the host backend wants -- it has no meaningful answer and inventing one would be
|
||||
* exactly the inference §6 forbids.
|
||||
/* `vram_capacity` is what the device reports free; 0 skips the capacity check (the host
|
||||
* backend has no meaningful answer).
|
||||
*
|
||||
* Refuses, by name and by how much, rather than shrinking anything:
|
||||
* - if the operator did not state the weight and KV budgets at all;
|
||||
* Refuses, by name and size, rather than shrinking anything:
|
||||
* - if the weight or KV budget is zero (the resolver did not run);
|
||||
* - if weights + kv exceeds the card;
|
||||
* - if a pool's backing allocation fails.
|
||||
*/
|
||||
@@ -187,11 +157,10 @@ public:
|
||||
|
||||
bool configured() const { return configured_; }
|
||||
|
||||
/* The line the engine prints at startup and the reason it refuses. Always populated, even on
|
||||
* success, because the placement report wants the pool totals (spec §16). */
|
||||
/* Printed at startup and on refusal. Populated on success too, for the placement report's
|
||||
* pool totals (spec §16). */
|
||||
const std::string& fit_report() const { return fit_report_; }
|
||||
|
||||
/* Every shortfall from every pool, gathered. */
|
||||
std::vector<Shortfall> shortfalls() const;
|
||||
|
||||
private:
|
||||
|
||||
+202
-294
@@ -9,14 +9,11 @@
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ hashing */
|
||||
/* A 128-bit chained mix rather than a cryptographic hash. A prefix cache whose store is on disk,
|
||||
* shared and long-lived is usually keyed by SHA-256, because a cheap hash's collision would serve
|
||||
* one caller another caller's context. We get the same guarantee more cheaply: every entry keeps
|
||||
* its BLOCK'S TOKEN IDS and compares them on a hit, so a collision is a miss rather than a wrong
|
||||
* answer, and the hash only has to be good enough to keep the bucket chains short.
|
||||
/* A 128-bit chained mix, not a cryptographic hash: every entry stores its block's token ids and
|
||||
* compares them on a hit, so a collision is a miss, and the hash only needs to keep buckets short.
|
||||
*
|
||||
* splitmix64's finaliser, which is a full 64-bit bijection -- so folding one token cannot lose the
|
||||
* bits of the previous one, which is the failure mode of a plain multiply-xor chain. */
|
||||
* splitmix64's finaliser is a 64-bit bijection, so folding one token cannot lose the bits of the
|
||||
* previous one (the weakness of a plain multiply-xor chain). */
|
||||
static inline uint64_t mix64(uint64_t x) {
|
||||
x += 0x9e3779b97f4a7c15ull;
|
||||
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ull;
|
||||
@@ -27,24 +24,9 @@ static inline uint64_t mix64(uint64_t x) {
|
||||
std::string BlockHash::str() const { return fmt("%016llx%016llx", (unsigned long long)hi,
|
||||
(unsigned long long)lo); }
|
||||
|
||||
uint64_t mm_content_hash(const void* embedding, int64_t bytes) {
|
||||
const uint8_t* p = (const uint8_t*)embedding;
|
||||
uint64_t h = 0xcbf29ce484222325ull ^ mix64((uint64_t)bytes);
|
||||
int64_t i = 0;
|
||||
for (; i + 8 <= bytes; i += 8) {
|
||||
uint64_t w; std::memcpy(&w, p + i, 8);
|
||||
h = mix64(h ^ w);
|
||||
}
|
||||
uint64_t tail = 0;
|
||||
for (int64_t k = 0; i + k < bytes; ++k) tail |= (uint64_t)p[i + k] << (8 * k);
|
||||
return mix64(h ^ tail);
|
||||
}
|
||||
|
||||
BlockHash chain_block_hash(const BlockHash& parent, const int32_t* toks, int32_t n,
|
||||
const MMContentKey* mm, int32_t n_mm, int64_t block_begin) {
|
||||
/* The parent seeds both lanes. That is the whole chained-hash property: a block with identical
|
||||
* tokens under a different prefix lands somewhere else, so a block in the middle of another
|
||||
* conversation cannot be served here. */
|
||||
/* The parent seeds both lanes, so identical tokens under a different prefix hash differently. */
|
||||
BlockHash h;
|
||||
h.hi = mix64(parent.hi ^ 0x243f6a8885a308d3ull);
|
||||
h.lo = mix64(parent.lo ^ 0x13198a2e03707344ull);
|
||||
@@ -56,9 +38,8 @@ BlockHash chain_block_hash(const BlockHash& parent, const int32_t* toks, int32_t
|
||||
h.hi = mix64(h.hi + h.lo + t);
|
||||
}
|
||||
|
||||
/* Multimodal spans that overlap this block, folded by CONTENT plus the overlap offsets, so the
|
||||
* same image at the same position hashes the same and a different image never aliases behind
|
||||
* the identical placeholder token ids (spec §11). */
|
||||
/* Fold in overlapping multimodal spans by content hash plus offsets, so different images
|
||||
* behind identical placeholder ids never alias (spec §11). */
|
||||
const int64_t lo_pos = block_begin, hi_pos = block_begin + n;
|
||||
for (int32_t i = 0; i < n_mm; ++i) {
|
||||
const MMContentKey& m = mm[i];
|
||||
@@ -77,10 +58,18 @@ BlockHash chain_block_hash(const BlockHash& parent, const int32_t* toks, int32_t
|
||||
void GeometricBackoff::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep) const {
|
||||
keep->clear();
|
||||
if (pos.empty()) return;
|
||||
const int64_t tip = (int64_t)pos.size() - 1;
|
||||
const int64_t tip = pos.back();
|
||||
std::vector<char> mark(pos.size(), 0);
|
||||
mark[(size_t)tip] = 1; /* THE TIP IS ALWAYS KEPT */
|
||||
for (int64_t d = 1; tip - d >= 0; d *= 2) mark[(size_t)(tip - d)] = 1;
|
||||
mark.back() = 1; /* the tip is always kept */
|
||||
for (int64_t s = interval_;; s *= 2) {
|
||||
const int64_t b = tip / s;
|
||||
for (int64_t j = b > 0 ? b - 1 : 0; j <= b; ++j) {
|
||||
const auto it = std::lower_bound(pos.begin(), pos.end(), j * s);
|
||||
if (it != pos.end() && *it < (j + 1) * s) mark[(size_t)(it - pos.begin())] = 1;
|
||||
}
|
||||
/* At this scale every position is in bucket 0, and so at every larger one. */
|
||||
if (b == 0 || s > INT64_MAX / 4) break;
|
||||
}
|
||||
for (size_t i = 0; i < pos.size(); ++i) if (mark[i]) keep->push_back(pos[i]);
|
||||
}
|
||||
|
||||
@@ -104,12 +93,11 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
groups_.clear();
|
||||
map_.clear(); lru_.clear();
|
||||
ck_by_prefix_.clear(); ck_by_session_.clear();
|
||||
/* THE POLICY COMES FROM THE CONFIG, and set_policy() overrides it -- which is the order a
|
||||
* test wants and the order an operator wants. The three names are checked in config_parse, so
|
||||
* an unknown one cannot reach here and silently become the default. */
|
||||
/* config_parse rejects unknown names, so the else branch is "geometric-backoff".
|
||||
* set_policy() may override this afterwards. */
|
||||
if (cfg.checkpoint_policy == "tip-only") policy_ = std::make_unique<KeepTipOnly>();
|
||||
else if (cfg.checkpoint_policy == "keep-all") policy_ = std::make_unique<KeepAll>();
|
||||
else policy_ = std::make_unique<GeometricBackoff>();
|
||||
else policy_ = std::make_unique<GeometricBackoff>(checkpoint_interval);
|
||||
report_.clear();
|
||||
|
||||
if (!kv) return RAD_E_INVAL;
|
||||
@@ -118,11 +106,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The cache's granularity is the block size of the first FULL-attention group, because that is
|
||||
* the group whose content a prefix hit actually reuses. A paged group with a different block
|
||||
* size cannot be indexed at that granularity and is named in the report rather than silently
|
||||
* skipped -- a group that quietly stops being prefix-cached is a hit-rate regression nobody
|
||||
* can attribute. */
|
||||
/* Granularity is the first full-attention group's block size, since that is what a hit
|
||||
* reuses. Paged groups with another block size are not cached and are named in the report. */
|
||||
for (const auto& p : kv->plans()) {
|
||||
if (p.kind == RAD_KV_FULL && block_size_ == 0) block_size_ = p.block_size;
|
||||
if (p.stateful()) has_linear_ = true;
|
||||
@@ -138,45 +123,35 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
std::string skipped;
|
||||
for (const auto& p : kv->plans()) {
|
||||
if (!p.paged()) continue;
|
||||
/* A WINDOW GROUP CANNOT BE SERVED A PREFIX. Its blocks below the window are recycled, so
|
||||
* the block list a hit hands over does not describe it -- adopt() would take a prefix's
|
||||
* worth of blocks into a table the manager only ever grows to window_blocks, and the slot
|
||||
* mapping is computed against a first_block_pos that a hit does not set. The group is
|
||||
* simply not prefix-cached, which is correct and costs the sequences that hit a drafter
|
||||
* or a windowed layer whose cache starts where the hit ended. */
|
||||
/* A window group is not prefix-cached. Its blocks below the window are recycled, adopt()
|
||||
* would overfill a table capped at window_blocks, and a hit does not set first_block_pos.
|
||||
* A drafter or windowed layer's cache then starts where the hit ended. */
|
||||
if (p.kind == RAD_KV_WINDOW) {
|
||||
skipped += fmt(" group '%s' is windowed (%lld blocks) -- NOT cached, a hit's blocks "
|
||||
"do not describe a cache whose floor moves\n",
|
||||
skipped += fmt(" group '%s' is windowed (%lld blocks): not cached\n",
|
||||
p.name.c_str(), (long long)p.window_blocks);
|
||||
continue;
|
||||
}
|
||||
if (p.block_size == block_size_) groups_.push_back(p.index);
|
||||
else skipped += fmt(" group '%s' block %lld != cache granularity %lld -- NOT cached\n",
|
||||
else skipped += fmt(" group '%s' block %lld != cache granularity %lld: not cached\n",
|
||||
p.name.c_str(), (long long)p.block_size, (long long)block_size_);
|
||||
}
|
||||
|
||||
interval_ = checkpoint_interval;
|
||||
/* A WINDOW SNAPSHOT is state in the same sense: a hit is reusable at a checkpoint only, where
|
||||
* the slot carries the window behind it (KVManager::has_window_snapshot). */
|
||||
/* A window snapshot is state too: a hit is reusable only at a checkpoint, whose slot carries
|
||||
* the window behind it (KVManager::has_window_snapshot). */
|
||||
if (kv->has_window_snapshot() && interval_ > 0) has_linear_ = true;
|
||||
if (has_linear_) {
|
||||
if (interval_ <= 0) {
|
||||
RAD_ERR("checkpoint_interval is %lld but the model has linear-attention state. A "
|
||||
"0 interval means no checkpoint is ever written and every hit replays the "
|
||||
"linear layers from zero.", (long long)interval_);
|
||||
RAD_ERR("checkpoint_interval is %lld but the model has linear-attention state, which "
|
||||
"needs a checkpoint for a hit to be usable", (long long)interval_);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (interval_ % block_size_ != 0) {
|
||||
/* A checkpoint that does not land on an attention block boundary can never be found:
|
||||
* the lookup identifies a checkpoint by the chained hash at its position, and that
|
||||
* hash only exists at block boundaries. vLLM's answer is to inflate the block to the
|
||||
* interval, which is what costs it attention hit rate on every short prompt. Ours is
|
||||
* to refuse the misconfiguration by name. */
|
||||
/* A checkpoint is found by the chained hash at its position, which exists only on
|
||||
* block boundaries, so an interval off the block grid would never hit. */
|
||||
RAD_ERR("the checkpoint interval resolves to %lld (from --checkpoint-interval %lld, "
|
||||
"rounded up to the chunk quantum) and that is not a multiple of the attention "
|
||||
"block size %lld. The linear checkpoint is found by the chained block hash at "
|
||||
"its position, and that hash exists only on a block boundary, so this interval "
|
||||
"would never produce a single hit (spec §7.3).",
|
||||
"rounded up to the chunk quantum), which is not a multiple of the attention "
|
||||
"block size %lld, so no checkpoint would ever hit (spec §7.3)",
|
||||
(long long)interval_, (long long)cfg.checkpoint_interval,
|
||||
(long long)block_size_);
|
||||
return RAD_E_INVAL;
|
||||
@@ -185,11 +160,11 @@ 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 a rank x %s, pinned host memory), retention '%s'\n",
|
||||
"every %lld tokens (%lld slots of %s a rank, pinned host memory), retention "
|
||||
"'%s'\n",
|
||||
groups_.size(), (long long)block_size_,
|
||||
(long long)(has_linear_ ? interval_ : 0),
|
||||
humanb(kv->checkpoint_bytes()).c_str(),
|
||||
fmt("%lld slots", (long long)kv->checkpoint_slots()).c_str(),
|
||||
(long long)kv->checkpoint_slots(), humanb(kv->checkpoint_bytes()).c_str(),
|
||||
policy_->name());
|
||||
report_ += skipped;
|
||||
return RAD_OK;
|
||||
@@ -240,35 +215,20 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
for (; matched < n_full; ++matched) {
|
||||
auto it = map_.find(hs[(size_t)matched]);
|
||||
if (it == map_.end()) break;
|
||||
/* AN ENTRY THE TIERS HOLD IS NOT A HIT, and this is the guard that makes demotion safe at
|
||||
* all. Moving an entry off the device releases its KV blocks; the map keeps the entry so
|
||||
* the bytes can be found again, but its `blocks` now name blocks the pool has given to
|
||||
* somebody else. Serving them would hand one conversation another's context -- exactly
|
||||
* the failure the token compare below exists to rule out, arrived at from the other side.
|
||||
*
|
||||
* The prefix simply stops here. The caller may promote and ask again (see
|
||||
* restorable_from), and until it does the answer is an honest shorter hit. An entry with
|
||||
* a promotion still out on it stops the prefix too: its ids are the ones it left with. */
|
||||
/* An off-device entry is not a hit: demotion released its blocks and its recorded ids now
|
||||
* belong to other sequences. The prefix stops here (also while a promotion is in flight);
|
||||
* the caller may promote and look up again (restorable_from). */
|
||||
if (!it->second.in_lru) break;
|
||||
/* Compare the token ids, not just the hash. A 128-bit collision is improbable; serving one
|
||||
* conversation's context to another is not a failure anybody would ever diagnose, so it is
|
||||
* made impossible rather than unlikely. */
|
||||
const int32_t* src = tokens.data() + matched * 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;
|
||||
if (!same_tokens(it->second, tokens.data() + matched * block_size_)) break;
|
||||
}
|
||||
|
||||
/* At least one token must remain for the step to compute a logit from. A full hit is backed
|
||||
* off by one block rather than being handed to a caller that would then schedule a zero-token
|
||||
* forward pass. */
|
||||
/* Back a full hit off by one block so one token remains to compute a logit from. */
|
||||
if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched;
|
||||
|
||||
/* 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
|
||||
* at or below `limit` 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. */
|
||||
/* Deepest valid snapshot at or below `limit` on this chain. Checkpoints sit on the interval or
|
||||
* at a prompt's tail (Scheduler::plan_chunk), i.e. on any block boundary, so iterate the
|
||||
* snapshots (a few hundred) rather than the block positions (tens of thousands); a snapshot is
|
||||
* on this chain when its key equals the chain hash at its position. */
|
||||
auto deepest = [&](int64_t limit) {
|
||||
auto best = ck_by_prefix_.end();
|
||||
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
|
||||
@@ -282,8 +242,8 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
}
|
||||
return best;
|
||||
};
|
||||
/* What a hit of `m` blocks lets a sequence skip: all of it, or with recurrent state only up
|
||||
* to the deepest checkpoint under it (Scheduler::admit_one resumes there). */
|
||||
/* Tokens a hit of `m` blocks lets a sequence skip: all of them, or with recurrent state only
|
||||
* up to the deepest checkpoint (Scheduler::admit_one resumes there). */
|
||||
auto reusable = [&](int64_t m) -> int64_t {
|
||||
if (!has_linear_) return m * block_size_;
|
||||
const auto b = deepest(m * block_size_);
|
||||
@@ -302,29 +262,26 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
}
|
||||
|
||||
const uint64_t now = rad_mono_ns();
|
||||
for (int64_t b = 0; b < matched; ++b) {
|
||||
touch(hs[(size_t)b], now);
|
||||
if (!blocks_out) continue;
|
||||
const Entry& e = map_.find(hs[(size_t)b])->second;
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
(*blocks_out)[g].push_back(e.blocks[g]);
|
||||
}
|
||||
/* A HIT IS A USE, and the tiers' idle clock has to hear about it: it is what decides when an
|
||||
* entry leaves the device, and without this it runs from when the chain was published, so a
|
||||
* prefix hit on every turn -- or one just promoted back for this very lookup -- would read as
|
||||
* idle and be demoted from under the request using it. */
|
||||
/* Deepest first, so the chain's first block is the most recent: under pressure a conversation
|
||||
* loses its end before its start, and what is left still hits. */
|
||||
for (int64_t b = matched - 1; b >= 0; --b) touch(hs[(size_t)b], now);
|
||||
if (blocks_out)
|
||||
for (int64_t b = 0; b < matched; ++b) {
|
||||
const Entry& e = map_.find(hs[(size_t)b])->second;
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
(*blocks_out)[g].push_back(e.blocks[g]);
|
||||
}
|
||||
/* A hit is a use for the tiers' idle clock too; otherwise a prefix hit every turn, or one just
|
||||
* promoted for this lookup, would look idle since its publish. */
|
||||
if (tiers_ && matched > 0) tiers_->note_hits(hs.data(), matched, now);
|
||||
hit.n_attn_tokens = (int32_t)(matched * block_size_);
|
||||
stats_.block_hits += matched;
|
||||
stats_.block_misses += n_full - matched;
|
||||
|
||||
/* ---- 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: 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. */
|
||||
/* ---- the split: how far the linear state can be reused ----
|
||||
* Recurrent state is reusable only at the deepest snapshot at or below n_attn_tokens; the
|
||||
* scheduler resumes there (Scheduler::admit_one) and recomputes the tokens in between. */
|
||||
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;
|
||||
}
|
||||
@@ -335,7 +292,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
}
|
||||
hit.n_linear_tokens = (int32_t)best->second.pos;
|
||||
hit.checkpoint_slot = best->second.slot;
|
||||
best->second.used = ++clock_;
|
||||
best->second.used = best->second.resumed = ++clock_;
|
||||
best->second.used_ns = now;
|
||||
handed_.push_back(best->first);
|
||||
++stats_.ckpt_hits;
|
||||
@@ -360,12 +317,11 @@ int PrefixCache::insert(uint64_t session,
|
||||
for (int64_t b = 0; b < n_full; ++b) {
|
||||
const BlockHash& h = hs[(size_t)b];
|
||||
auto it = map_.find(h);
|
||||
if (it != map_.end() && it->second.in_lru) { touch(h, now); continue; }
|
||||
if (it != map_.end() && it->second.in_lru) continue; /* touched below */
|
||||
if (it != map_.end()) {
|
||||
/* AN ENTRY WHOSE ONLY COPY IS OFF THE CARD, AND THIS REQUEST JUST COMPUTED IT AGAIN --
|
||||
* a restore that did not fit, or a chain cut short. The request's blocks become the
|
||||
* entry's device copy and the tier copy is let go (IdleTiers::rebound says why). One
|
||||
* with a promotion still out on it is left alone: its record is the transfer's. */
|
||||
/* An off-device entry this request recomputed (a restore that did not fit, or a chain
|
||||
* cut short). Its blocks become the entry's device copy and the tier copy goes
|
||||
* (IdleTiers::rebound). An entry with a promotion in flight is left alone. */
|
||||
if (!tiers_ || !tiers_->resident_off_device(h)) continue;
|
||||
std::vector<int32_t> mine(groups_.size(), -1);
|
||||
size_t held = 0;
|
||||
@@ -384,7 +340,7 @@ int PrefixCache::insert(uint64_t session,
|
||||
lru_.push_back(h);
|
||||
e.lru = std::prev(lru_.end());
|
||||
e.in_lru = true;
|
||||
tiers_->rebound(h, e.blocks, now);
|
||||
tiers_->rebound(h, e.blocks, now, b);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -397,9 +353,8 @@ int PrefixCache::insert(uint64_t session,
|
||||
e.blocks[held] = blk;
|
||||
}
|
||||
if (held != groups_.size()) {
|
||||
/* Unwind exactly what was taken. A half-referenced entry leaks a block forever, and a
|
||||
* released block that was never retained frees one out from under a live sequence --
|
||||
* both are silent and neither is diagnosable later. */
|
||||
/* Unwind exactly what was retained: anything else leaks a block or frees one under a
|
||||
* live sequence. */
|
||||
for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], e.blocks[g]);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
@@ -411,37 +366,27 @@ int PrefixCache::insert(uint64_t session,
|
||||
e.in_lru = true;
|
||||
map_.emplace(h, std::move(e));
|
||||
}
|
||||
/* Deepest first, as in lookup: the first block ends most recent. */
|
||||
for (int64_t b = n_full - 1; b >= 0; --b) touch(hs[(size_t)b], now);
|
||||
|
||||
/* THE TIERS LEARN THE CHAIN HERE AND NOWHERE ELSE. insert() is the one call that knows a chain
|
||||
* was COMPLETED rather than merely touched -- which is what a session is -- and it is also the
|
||||
* only place every entry's block ids are in hand at once.
|
||||
/* The tiers learn the chain only here: insert() is the one call that knows a chain was
|
||||
* completed, and the only place every entry's block ids are in hand.
|
||||
*
|
||||
* AND THE IDS COME OUT OF THE MAP, NOT OUT OF `blocks`. The two are the same for an entry this
|
||||
* call just created and DIFFERENT for one that already existed, because the loop above keeps
|
||||
* the entry the cache already holds and lets this request's own copy of those blocks go. Both
|
||||
* block tables describe the same tokens, but only the cache's is REFERENCED: the other belongs
|
||||
* to a sequence that is about to be freed.
|
||||
*
|
||||
* Recording the wrong one is not a bookkeeping detail. The tiers demote what they were told,
|
||||
* so they would gather out of blocks the pool had already handed to somebody else -- putting a
|
||||
* stranger's KV in the tier under this prefix's key -- and then release a reference nobody
|
||||
* took. It shows as a flood of "double free of block N" in the log and, once the entry is
|
||||
* promoted back, as fluent text with one word changed. */
|
||||
* The ids come from the map, not from `blocks`. For an entry that already existed the loop
|
||||
* above kept the cache's blocks, and `blocks` belongs to a sequence about to be freed; the
|
||||
* tiers would copy from blocks reassigned to another sequence. */
|
||||
if (tiers_) {
|
||||
for (int64_t b = 0; b < n_full; ++b) {
|
||||
auto it = map_.find(hs[(size_t)b]);
|
||||
if (it == map_.end()) continue;
|
||||
tiers_->note_used(hs[(size_t)b], it->second.blocks, now);
|
||||
tiers_->note_used(hs[(size_t)b], it->second.blocks, now, b);
|
||||
}
|
||||
tiers_->note_session(session, hs, n_tokens, now, label);
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* A conversation's snapshots belong to its latest turn. Sessions are keyed by request id, so
|
||||
* without this each earlier turn's deepest snapshot would stay a protected tip. Every snapshot
|
||||
* on the chain just published moves under this id, so the policy sees one session, 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_ ||
|
||||
@@ -467,35 +412,20 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
|
||||
std::vector<BlockHash> out;
|
||||
if (!enabled_ || !tiers_ || tokens.empty()) return out;
|
||||
|
||||
/* THE BLOCKS A HIT CAN USE: one token must remain to compute a logit from, so a prompt that
|
||||
* ends on a block boundary never reuses its last block (lookup backs off by one) and neither
|
||||
* restoring it would be read. */
|
||||
/* Only blocks a hit can use: one token must remain, so a prompt ending on a block boundary
|
||||
* never reuses its last block (lookup backs off by one). */
|
||||
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
|
||||
* chain holds. EVERY off-device block in it is collected, not just the first run of them.
|
||||
*
|
||||
* STOPPING AT THE FIRST RESIDENT BLOCK PAST A GAP, on the reasoning that "the run this call is
|
||||
* about has ended", would be wrong, and the way it is wrong is worth stating because the
|
||||
* symptom does not look like a caching bug at all. A hit needs the WHOLE prefix:
|
||||
* restoring blocks 0..99 and stopping leaves block 200 off-device, so the hit ends at 200 and
|
||||
* everything above it is re-prefilled -- and WHICH blocks are off-device at the moment this
|
||||
* runs depends on how far the maintenance pass has got. The same prompt then gets a different
|
||||
* hit length on each restore.
|
||||
*
|
||||
* That is not only a lost prefix. The hit length is what the scheduler chunks the remaining
|
||||
* prefill against, so two restores that recovered different amounts run different GEMM shapes
|
||||
* over the same tokens -- and greedy decoding is tie-level sensitive to that (§19). The
|
||||
* session's answer moves between restores, intermittently, with nothing wrong in the KV at
|
||||
* all. Restoring the whole chain makes the hit length a property of the prompt. */
|
||||
/* Walk as lookup does, past where it stopped, and collect every off-device block on the
|
||||
* chain, not just the first run. Stopping at the first gap would make the hit length depend on
|
||||
* how far the maintenance pass had got; the scheduler chunks the rest of the prefill against
|
||||
* that length, and greedy output is tie-level sensitive to the GEMM shapes (§19). Restoring
|
||||
* the whole chain makes the hit length a function of the prompt. */
|
||||
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;
|
||||
if (!same_tokens(it->second, tokens.data() + b * block_size_)) break;
|
||||
if (tiers_->resident_off_device(hs[(size_t)b])) out.push_back(hs[(size_t)b]);
|
||||
}
|
||||
return out;
|
||||
@@ -504,15 +434,13 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
|
||||
void PrefixCache::drop_offdevice(const BlockHash& key) {
|
||||
auto it = map_.find(key);
|
||||
if (it == map_.end()) return;
|
||||
/* NO release_block HERE, and that is the whole point. The entry has been off-device since it
|
||||
* was demoted; the ids in it name blocks the pool reassigned long ago, so releasing them
|
||||
* would free somebody else's context and serving them would hand it over. */
|
||||
/* No release_block: the ids name blocks the pool has reassigned (see the declaration). */
|
||||
if (it->second.in_lru) lru_.erase(it->second.lru);
|
||||
map_.erase(it);
|
||||
++stats_.evictions;
|
||||
/* A SNAPSHOT KEYED BY THE SAME HASH STAYS. No lookup reaches it past the missing block, and
|
||||
* the retention policy or the expiry retires it through the path that tells the tiers
|
||||
* (retire_ckpt) -- this one is called by the tiers, holding their lock. */
|
||||
/* A snapshot under the same key stays: no lookup reaches it past the missing block, and
|
||||
* retention or expiry retires it via retire_ckpt. It cannot be retired here because the tiers
|
||||
* call this holding their lock. */
|
||||
}
|
||||
|
||||
int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks) {
|
||||
@@ -520,11 +448,9 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks
|
||||
if (it == map_.end()) return RAD_E_NOTFOUND;
|
||||
if (blocks.size() != groups_.size()) return RAD_E_SHAPE;
|
||||
for (int32_t b : blocks) if (b < 0) return RAD_E_INVAL;
|
||||
/* THE RESERVATION'S REFERENCE BECOMES THE CACHE'S. KVManager::reserve_block left each block at
|
||||
* a refcount of one with no sequence attached; assigning them here is the handover, and the
|
||||
* cache's ordinary release path frees them from now on. Retaining and then releasing to "make
|
||||
* it explicit" would be a round trip to the same number and would only obscure which reference
|
||||
* is which. */
|
||||
/* The reservation's reference becomes the cache's: KVManager::reserve_block left each block at
|
||||
* refcount one with no sequence attached, and the cache's release path frees it from now on.
|
||||
* No extra retain. */
|
||||
Entry& e = it->second;
|
||||
e.blocks = blocks;
|
||||
for (size_t g = 0; g < groups_.size(); ++g) kv_->cache_reserved_block(groups_[g], blocks[g]);
|
||||
@@ -544,14 +470,22 @@ bool PrefixCache::shared_with_live(const Entry& e) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Token ids are compared too, so a hash collision is a miss rather than another conversation's
|
||||
* context. */
|
||||
bool PrefixCache::same_tokens(const Entry& e, const int32_t* src) const {
|
||||
return (int64_t)e.tokens.size() == block_size_ &&
|
||||
std::memcmp(e.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) == 0;
|
||||
}
|
||||
|
||||
void PrefixCache::release_blocks(const Entry& e) {
|
||||
for (size_t g = 0; g < groups_.size(); ++g) kv_->release_block(groups_[g], e.blocks[g]);
|
||||
}
|
||||
|
||||
int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
int64_t done = 0;
|
||||
/* 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. It is stamped as used, which keeps the list in the
|
||||
* clock's order. */
|
||||
/* One pass over the list as it was on entry. An entry a live sequence also holds is in use:
|
||||
* it moves to the back, stamped, so the list stays in clock order and the next call does not
|
||||
* walk the same shared run. */
|
||||
const uint64_t now = rad_mono_ns();
|
||||
for (int64_t seen = (int64_t)lru_.size(); done < n && seen > 0 && !lru_.empty(); --seen) {
|
||||
const BlockHash h = lru_.front();
|
||||
@@ -565,10 +499,9 @@ int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
}
|
||||
lru_.pop_front();
|
||||
e.in_lru = false;
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
kv_->release_block(groups_[g], e.blocks[g]);
|
||||
release_blocks(e);
|
||||
if (tiers_) {
|
||||
/* THE HOST COPY HAS LANDED: the entry leaves VRAM and stays in the index. */
|
||||
/* Host copy landed: the entry leaves VRAM and stays in the index. */
|
||||
if (tiers_->droppable(h)) {
|
||||
tiers_->drop_commit(h);
|
||||
++stats_.drops;
|
||||
@@ -585,9 +518,8 @@ int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
}
|
||||
|
||||
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();
|
||||
/* Tiers attached but off count as no tiers: no copy will ever land, so do not wait for one. */
|
||||
const bool keep = tiers_ && tiers_->host_on();
|
||||
const uint64_t now = rad_mono_ns();
|
||||
int64_t done = 0;
|
||||
auto it = lru_.begin();
|
||||
@@ -598,7 +530,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) {
|
||||
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. */
|
||||
/* In use: to the back, as in evict_lru. */
|
||||
auto next = std::next(it);
|
||||
lru_.splice(lru_.end(), lru_, it);
|
||||
e.used_ns = now;
|
||||
@@ -608,8 +540,7 @@ int64_t PrefixCache::trim(int64_t n_blocks) {
|
||||
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]);
|
||||
release_blocks(e);
|
||||
if (keep) {
|
||||
tiers_->drop_commit(h);
|
||||
++stats_.drops;
|
||||
@@ -631,6 +562,10 @@ int64_t PrefixCache::drop_clean() {
|
||||
if (frees != frees_seen_ || released_) {
|
||||
frees_seen_ = frees;
|
||||
released_ = false;
|
||||
for (const BlockHash& h : drop_wait_) {
|
||||
auto it = map_.find(h);
|
||||
if (it != map_.end()) it->second.drop_wait = false;
|
||||
}
|
||||
drop_scratch_.insert(drop_scratch_.end(), drop_wait_.begin(), drop_wait_.end());
|
||||
drop_wait_.clear();
|
||||
}
|
||||
@@ -639,20 +574,14 @@ int64_t PrefixCache::drop_clean() {
|
||||
auto it = map_.find(h);
|
||||
if (it == map_.end()) continue;
|
||||
Entry& e = it->second;
|
||||
e.drop_wait = false;
|
||||
if (!e.in_lru || !tiers_->droppable(h)) continue;
|
||||
/* 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 = 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) {
|
||||
/* Skip held entries and blocks a running sequence also holds: dropping would free nothing,
|
||||
* and the next lookup would restore a second copy beside the one still in VRAM. */
|
||||
if (held_.count(h) > 0 || shared_with_live(e)) {
|
||||
if (!e.drop_wait) { e.drop_wait = true; drop_wait_.push_back(h); }
|
||||
continue;
|
||||
}
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
kv_->release_block(groups_[g], e.blocks[g]);
|
||||
release_blocks(e);
|
||||
lru_.erase(e.lru);
|
||||
e.in_lru = false;
|
||||
++stats_.drops;
|
||||
@@ -662,18 +591,9 @@ int64_t PrefixCache::drop_clean() {
|
||||
return n;
|
||||
}
|
||||
|
||||
/* THE REFCOUNT IS WHAT SEPARATES A CACHE FROM A LEAK. A block the cache indexes and a running
|
||||
* sequence is reading is not memory the cache could give back; a block only the cache references
|
||||
* is exactly what the next eviction frees. Nothing else distinguishes them -- both are `used`,
|
||||
* both are in the index -- so the count is the manager's: it marks the blocks the cache holds and
|
||||
* keeps the number of marked blocks at a reference count of one current as the counts move.
|
||||
*
|
||||
* ONE GROUP, FOR THE REASON THE POOL'S OWN TOKEN FIGURES ARE ONE GROUP'S: the paged groups share
|
||||
* a token axis and an entry is one block in each of them, so counting every group would multiply
|
||||
* the answer by the group count.
|
||||
*
|
||||
* OFF-DEVICE ENTRIES COUNT FOR NOTHING. A demoted entry released its blocks, and the mark went
|
||||
* with the release; its bytes are in host memory and it is holding none of the card. */
|
||||
/* The KV manager tracks how many cache-held blocks are at refcount one. One group only: the paged
|
||||
* groups share a token axis and an entry is one block in each, so summing groups would multiply
|
||||
* the answer. Off-device entries hold no blocks and count for nothing. */
|
||||
int64_t PrefixCache::unshared_tokens() const {
|
||||
if (!kv_ || groups_.empty() || block_size_ <= 0) return 0;
|
||||
return kv_->cache_only_blocks(groups_[0]) * block_size_;
|
||||
@@ -681,9 +601,7 @@ int64_t PrefixCache::unshared_tokens() const {
|
||||
|
||||
void PrefixCache::clear() {
|
||||
for (auto& kv : map_) {
|
||||
if (kv.second.in_lru)
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
kv_->release_block(groups_[g], kv.second.blocks[g]);
|
||||
if (kv.second.in_lru) release_blocks(kv.second);
|
||||
if (tiers_) tiers_->forget(kv.first);
|
||||
++stats_.evictions;
|
||||
}
|
||||
@@ -734,24 +652,35 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
for (const auto& a : all) pos.push_back(a.first);
|
||||
std::vector<int64_t> keep;
|
||||
policy_->select(pos, &keep);
|
||||
/* A policy may return its keep set in any order; the lookup below needs it sorted. */
|
||||
std::sort(keep.begin(), keep.end());
|
||||
const uint64_t tip_made = all.empty() ? 0 : ck_by_prefix_.find(all.back().second)->second.made;
|
||||
|
||||
int64_t freed = 0;
|
||||
for (const auto& a : all) {
|
||||
if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; }
|
||||
/* NOR ONE HANDED OUT THIS STEP, whatever the policy says of its position: the admission it
|
||||
* was handed to restores from the slot ahead of the step, and that is after this runs. */
|
||||
/* Keep one handed out this step regardless of policy: its admission restores from the
|
||||
* slot ahead of the step. */
|
||||
if (handed(a.second)) { kept.push_back(a.second); continue; }
|
||||
auto e = ck_by_prefix_.find(a.second);
|
||||
if (e == ck_by_prefix_.end()) continue;
|
||||
/* And one a lookup resumed from since the session's tip was written. The policy places
|
||||
* its ladder from the tip, but a later turn that resumed below the tip has left this
|
||||
* chain there (a rewritten last message), and its next turn most likely resumes there
|
||||
* again. */
|
||||
if (e->second.resumed > tip_made) { kept.push_back(a.second); continue; }
|
||||
RAD_DEBUG("prefix cache: snapshot at %lld of session %llu released by retention '%s' "
|
||||
"(unused for %.1f s)", (long long)e->second.pos,
|
||||
(unsigned long long)e->second.session, policy_->name(),
|
||||
idle_s(e->second.used_ns));
|
||||
retire_ckpt(e);
|
||||
++freed;
|
||||
++stats_.ckpt_evictions;
|
||||
++stats_.ckpt_retired;
|
||||
}
|
||||
/* 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
|
||||
* a checkpoint: the vector empties, here and in the eviction below, and the key stays. The
|
||||
* cost is not the bytes -- it is that the loop in reserve_checkpoint walks EVERY key on every
|
||||
* allocation failure, which is the one path this cache exists to relieve. */
|
||||
/* Erase an emptied session. Sessions are request ids, so otherwise the map grows by one key
|
||||
* per request that ever checkpointed, and reserve_checkpoint walks every key on each
|
||||
* allocation failure. */
|
||||
if (kept.empty()) { ck_by_session_.erase(it); return freed; }
|
||||
it->second = std::move(kept);
|
||||
return freed;
|
||||
@@ -761,17 +690,17 @@ 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;
|
||||
/* 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. */
|
||||
/* The key is the chained hash of whole blocks, so `pos` must be on a block boundary. The
|
||||
* scheduler places checkpoints on its chunk quantum, 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)",
|
||||
RAD_ERR("checkpoint at %lld is not on a %lld-token block boundary, which the scheduler's "
|
||||
"chunk quantum rules out (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()) {
|
||||
existing->second.used = ++clock_;
|
||||
existing->second.used_ns = rad_mono_ns();
|
||||
*slot_out = existing->second.slot;
|
||||
return RAD_OK;
|
||||
@@ -779,64 +708,48 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
|
||||
int32_t slot = -1;
|
||||
if (kv_->alloc_checkpoint(&slot) < 0) {
|
||||
/* Budgeted retention: run the policy over every session before giving up. The tip of each
|
||||
* session survives it by construction, because that is what an appending agent transcript
|
||||
* needs (spec §7.3).
|
||||
*
|
||||
* Over a SNAPSHOT of the keys, because retain() erases a session it empties and a
|
||||
* range-for over the map would be iterating a container it is erasing from. */
|
||||
/* Run retention over every session. Iterate a copy of the keys: retain() erases sessions
|
||||
* it empties. */
|
||||
std::vector<uint64_t> sessions;
|
||||
sessions.reserve(ck_by_session_.size());
|
||||
for (const auto& s : ck_by_session_) sessions.push_back(s.first);
|
||||
for (uint64_t s : sessions) retain(s);
|
||||
if (kv_->alloc_checkpoint(&slot) < 0) {
|
||||
/* Still nothing. Drop the globally least-recently-used snapshot, PREFERRING a non-tip
|
||||
* one -- but falling back to a tip rather than giving up.
|
||||
*
|
||||
* MAKING A TIP UNEVICTABLE OUTRIGHT WEDGES THE POOL PERMANENTLY. A session here is a
|
||||
* REQUEST id (PCBinding passes r.id), and a finished request's checkpoints are meant
|
||||
* to outlive it -- they are keyed by chained prefix hash, which is exactly how the
|
||||
* next turn of an agent transcript finds them. So every request that writes a
|
||||
* checkpoint leaves a tip behind and nothing ever retires one: after
|
||||
* --checkpoint-slots such requests, every slot holds a dead session's tip and this
|
||||
* would return RAD_E_FULL for the life of the process. The scheduler ignores the
|
||||
* failure (scheduler.cpp: `>= 0 && cs >= 0`), so linear prefix caching would simply
|
||||
* stop, with nothing in the log.
|
||||
*
|
||||
* Two passes rather than one comparison, because "prefer a non-tip" is a tier and not
|
||||
* a tiebreak: the oldest tip must lose to the newest non-tip. */
|
||||
/* Evict the least recently used snapshot, where a use is its reservation or a lookup
|
||||
* resuming from it, and never one handed out this step (its admission restores from
|
||||
* the slot ahead of the step). A tip gets no protection beyond its recency: sessions
|
||||
* are request ids, and a client that rewrites its last message leaves one tip per
|
||||
* turn that no later turn reaches, while the anchor every turn resumes from is used
|
||||
* each turn. */
|
||||
const Ckpt* victim = nullptr;
|
||||
const Ckpt* tip_victim = nullptr;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
/* NOT ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot
|
||||
* ahead of the step, and a slot freed under it restores nothing. */
|
||||
if (handed(kvp.first)) continue;
|
||||
auto sit = ck_by_session_.find(kvp.second.session);
|
||||
bool is_tip = false;
|
||||
if (sit != ck_by_session_.end()) {
|
||||
int64_t tip = -1;
|
||||
for (const BlockHash& h : sit->second) {
|
||||
auto e = ck_by_prefix_.find(h);
|
||||
if (e != ck_by_prefix_.end()) tip = std::max(tip, e->second.pos);
|
||||
}
|
||||
is_tip = (kvp.second.pos == tip);
|
||||
}
|
||||
const Ckpt*& best = is_tip ? tip_victim : victim;
|
||||
if (!best || kvp.second.used < best->used) best = &kvp.second;
|
||||
if (!victim || kvp.second.used < victim->used) victim = &kvp.second;
|
||||
}
|
||||
if (!victim) victim = tip_victim;
|
||||
if (!victim) return RAD_E_FULL;
|
||||
if (!victim) {
|
||||
++stats_.ckpt_refused;
|
||||
RAD_DEBUG("prefix cache: no snapshot at %lld for session %llu: every one of the "
|
||||
"%lld slots was handed out this step", (long long)pos,
|
||||
(unsigned long long)session, (long long)ck_by_prefix_.size());
|
||||
return RAD_E_FULL;
|
||||
}
|
||||
RAD_DEBUG("prefix cache: store full, snapshot at %lld of session %llu (%s) evicted "
|
||||
"as the least recently used, unused for %.1f s", (long long)victim->pos,
|
||||
(unsigned long long)victim->session,
|
||||
is_tip(*victim) ? "its tip" : "below its tip", idle_s(victim->used_ns));
|
||||
const BlockHash vh = victim->prefix;
|
||||
const uint64_t vs = victim->session;
|
||||
retire_ckpt(ck_by_prefix_.find(vh));
|
||||
++stats_.ckpt_evictions;
|
||||
++stats_.ckpt_lru;
|
||||
unindex_ckpt(vs, vh);
|
||||
if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL;
|
||||
if (kv_->alloc_checkpoint(&slot) < 0) { ++stats_.ckpt_refused; return RAD_E_FULL; }
|
||||
}
|
||||
}
|
||||
|
||||
Ckpt c;
|
||||
c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot; c.used = ++clock_;
|
||||
c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot;
|
||||
c.used = c.made = ++clock_;
|
||||
c.used_ns = rad_mono_ns();
|
||||
ck_by_prefix_.emplace(prefix, c);
|
||||
ck_by_session_[session].push_back(prefix);
|
||||
@@ -847,12 +760,10 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
|
||||
auto it = ck_by_prefix_.find(prefix);
|
||||
if (it == ck_by_prefix_.end()) return;
|
||||
/* One that lost its slot between the reservation and now holds nothing to serve. */
|
||||
/* One that lost its slot since the reservation holds nothing to serve. */
|
||||
if (it->second.slot < 0) return;
|
||||
it->second.valid = true;
|
||||
/* THE TIERS LEARN THE SNAPSHOT HERE, for the session view: before the commit the slot still
|
||||
* holds the previous tenant's state, so this is the earliest moment at which telling them
|
||||
* would be true. */
|
||||
/* Tell the tiers (for the session view) only now that the slot holds this state. */
|
||||
if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos);
|
||||
}
|
||||
|
||||
@@ -861,14 +772,27 @@ 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 TOLD, because they name the slot too: note_snapshot records it for the session
|
||||
* view, and a view that kept it would count a slot the store has since given to another
|
||||
* session as this one's resume point. */
|
||||
/* The tiers record the slot for the session view and must stop naming it before it is reused. */
|
||||
if (tiers_) tiers_->release_snapshot(it->first);
|
||||
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
|
||||
ck_by_prefix_.erase(it);
|
||||
}
|
||||
|
||||
bool PrefixCache::is_tip(const Ckpt& c) const {
|
||||
auto s = ck_by_session_.find(c.session);
|
||||
if (s == ck_by_session_.end()) return false;
|
||||
for (const BlockHash& h : s->second) {
|
||||
auto e = ck_by_prefix_.find(h);
|
||||
if (e != ck_by_prefix_.end() && e->second.pos > c.pos) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
double PrefixCache::idle_s(uint64_t used_ns) {
|
||||
const uint64_t now = rad_mono_ns();
|
||||
return now > used_ns ? (double)(now - used_ns) * 1e-9 : 0.0;
|
||||
}
|
||||
|
||||
void PrefixCache::unindex_ckpt(uint64_t session, const BlockHash& key) {
|
||||
auto sit = ck_by_session_.find(session);
|
||||
if (sit == ck_by_session_.end()) return;
|
||||
@@ -885,24 +809,12 @@ void PrefixCache::hold(uint64_t req, const std::vector<int32_t>& tokens,
|
||||
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;
|
||||
if (!same_tokens(it->second, tokens.data() + b * block_size_)) 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;
|
||||
@@ -921,9 +833,8 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
|
||||
const uint64_t cutoff = now_ns - ttl_ns;
|
||||
int64_t n = 0;
|
||||
|
||||
/* ---- in VRAM: the LRU list is in the clock's order, so the walk stops at the first entry it
|
||||
* keeps. A block a running sequence also holds stays allocated -- releasing the cache's
|
||||
* reference is not freeing the block -- and that sequence publishes it again when it ends. */
|
||||
/* ---- in VRAM: the LRU is in clock order, so stop at the first entry kept. A block a running
|
||||
* sequence also holds stays allocated; that sequence republishes it when it ends. */
|
||||
while (!lru_.empty()) {
|
||||
const BlockHash h = lru_.front();
|
||||
auto it = map_.find(h);
|
||||
@@ -932,15 +843,14 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
|
||||
if (e.used_ns >= cutoff) break;
|
||||
lru_.pop_front();
|
||||
e.in_lru = false;
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
kv_->release_block(groups_[g], e.blocks[g]);
|
||||
release_blocks(e);
|
||||
/* The host copy goes with it: an expired entry is not demoted. */
|
||||
if (tiers_) tiers_->forget(h);
|
||||
map_.erase(it);
|
||||
++n;
|
||||
}
|
||||
|
||||
/* ---- only in host memory: the tiers keep these in the clock's order too. */
|
||||
/* ---- only in host memory: the tiers keep these in clock order too. */
|
||||
if (tiers_) {
|
||||
std::vector<BlockHash> keys;
|
||||
tiers_->expired(cutoff, (size_t)-1, &keys);
|
||||
@@ -953,10 +863,8 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- snapshots, used when their prefix entry is or when a lookup hands them out. Not one
|
||||
* that is still being written (a reservation not yet committed) and not one handed out this
|
||||
* step: its admission restores from the slot ahead of the step. There are --checkpoint-slots
|
||||
* of them at most, so the whole index is walked. */
|
||||
/* ---- snapshots: skip uncommitted reservations and ones handed out this step. At most
|
||||
* --checkpoint-slots of them, so walk the whole index. */
|
||||
std::vector<BlockHash> gone;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
const Ckpt& c = kvp.second;
|
||||
|
||||
+159
-218
@@ -1,54 +1,38 @@
|
||||
/* prefix.h -- prefix caching (spec §7.3). TWO mechanisms, because full attention and linear
|
||||
* attention cannot share one.
|
||||
/* prefix.h -- prefix caching (spec §7.3). Full and linear attention need separate mechanisms.
|
||||
*
|
||||
* FULL ATTENTION: content-hashed blocks with a CHAINED hash, so a block's identity includes its
|
||||
* whole prefix. LRU eviction, copy-on-write on fork, and multimodal inputs hashed BY CONTENT --
|
||||
* an image is a cache hit, because the hash is taken over the EMBEDDING span rather than the
|
||||
* image bytes.
|
||||
* Full attention: content-hashed blocks with a chained hash, so a block's identity includes its
|
||||
* whole prefix. LRU eviction and copy-on-write on fork. Multimodal spans are keyed by their
|
||||
* processed patches, not the file bytes (MMContentKey).
|
||||
*
|
||||
* LINEAR ATTENTION: a state checkpoint. A GDN layer's recurrent state at position N depends on
|
||||
* all of 0..N and is one fixed-size object per sequence -- 32 heads of 128x128 fp32 is 2 MiB a
|
||||
* layer, roughly 96 MiB across the 48 linear layers of a Qwen3-Next. Snapshotting that per 16-token
|
||||
* block is not affordable at any block count. We take vLLM's `--mamba-cache-mode align` mechanism
|
||||
* and change two things:
|
||||
* Linear attention: state checkpoints. A GDN layer's recurrent state at position N depends on all
|
||||
* of 0..N and is one fixed-size object per sequence (on Qwen3.5-27B, 48 heads of 128x128 fp32 is
|
||||
* 3 MiB a layer, 144 MiB across its 48 linear layers), far too large to snapshot per 16-token
|
||||
* block. This follows vLLM's `--mamba-cache-mode align` with two changes:
|
||||
*
|
||||
* (a) THE CHECKPOINT INTERVAL IS DECOUPLED FROM THE ATTENTION BLOCK SIZE. vLLM inflates the
|
||||
* attention block to match the mamba page -- 528 tokens for Qwen3.5, 2240 for the 35B-A3B --
|
||||
* and since prefix caching is block-granular, every prompt shorter than that gets a 0% hit
|
||||
* rate on ATTENTION as well. We could not inflate the attention block even if we wanted to:
|
||||
* §7.2 takes it from the resolved kernel and libr4d's paged attention is compiled for 16.
|
||||
* So attention caches at 16-token granularity and Config::checkpoint_interval is a separate,
|
||||
* much larger number. A hit landing BETWEEN checkpoints reuses the attention blocks and
|
||||
* replays only the linear layers forward from the last checkpoint. That is what CacheHit's
|
||||
* two token counts are: `n_attn_tokens` is free, `[n_linear_tokens, n_attn_tokens)` costs a
|
||||
* linear-layers-only forward pass, and the rest is an ordinary prefill.
|
||||
* (a) The checkpoint interval is decoupled from the attention block size. vLLM inflates the
|
||||
* attention block to the mamba page (528 tokens for Qwen3.5, 2240 for the 35B-A3B), so
|
||||
* shorter prompts get no attention hits either. Here the attention block stays 16 (§7.2
|
||||
* takes it from the kernel; libr4d's paged attention is compiled for 16) and
|
||||
* Config::checkpoint_interval is a separate, larger number. A hit between checkpoints
|
||||
* reuses the attention blocks and replays only the linear layers from the last checkpoint:
|
||||
* in CacheHit, `n_attn_tokens` is free, `[n_linear_tokens, n_attn_tokens)` costs a
|
||||
* linear-layers-only pass, and the rest is ordinary prefill.
|
||||
*
|
||||
* (b) CHECKPOINTS ARE TAKEN DELIBERATELY, NOT OPPORTUNISTICALLY. vLLM writes one only when a
|
||||
* scheduler step happens to end on a boundary, which is why a checkpoint landing in
|
||||
* request-unique tokens silently drops caching to zero. Our scheduler owns chunk boundaries
|
||||
* (spec §7.1) and splits a chunk AT the interval, so one is always written. The cost is an
|
||||
* occasional short chunk; the benefit is that hit rate is a property of the workload rather
|
||||
* than of scheduling luck. `next_checkpoint_after()` is what the scheduler splits on.
|
||||
* (b) Checkpoints are taken deliberately. vLLM writes one only when a step happens to end on a
|
||||
* boundary. The scheduler here owns chunk boundaries (spec §7.1) and splits a chunk at the
|
||||
* interval (next_checkpoint_after()), so a checkpoint is always written, at the cost of an
|
||||
* occasional short chunk.
|
||||
*
|
||||
* ============================== WHAT IT COSTS TO HOLD, AND WHEN IT STOPS WORKING ==============
|
||||
* Sizing: the cache holds a KV reference on every block it indexes, so pool demand scales with
|
||||
* live sessions, not running requests. Hit rate falls off a cliff with pool utilisation: intact
|
||||
* below about 75%, half gone by about 81%, and zero once the sessions no longer fit, because each
|
||||
* turn evicts the prefixes the next one needs. Output is unaffected; TTFT grows 10-100x. A context
|
||||
* of T tokens occupies about 1.8 x T pool-tokens across the paged groups. The budget gives the
|
||||
* cache what the experts can spare (core/mem/vram_budget.h); --host-pool-mib moves that.
|
||||
*
|
||||
* The cache takes a KV REFERENCE on every block it indexes, so a finished sequence's blocks stay
|
||||
* held for the next turn. That is the whole point -- and it means the pool's demand is the number
|
||||
* of LIVE SESSIONS, not of running requests. Size it the other way and the failure is not graceful.
|
||||
*
|
||||
* THE THRESHOLD IS POOL UTILISATION, and it is a CLIFF rather than a slope. Below roughly 75%
|
||||
* utilisation the cache is whole; by around 81% half of it is gone; once the sessions no longer
|
||||
* fit at all the cache is not degraded but DEFEATED -- each turn evicts the prefixes the next turn
|
||||
* wants, so every turn re-prefills its whole context and the hit rate is zero. The generated text
|
||||
* 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. 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
|
||||
* falls once a prefix that would have been reused is already gone.
|
||||
* Monitoring: `kv_util` (/stats, or vllm:kv_cache_usage_perc) predicts trouble and
|
||||
* `radiance:prefix_cache_evictions_total` counts it. The hit rate lags: it falls only after a
|
||||
* reusable prefix is already gone.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/kv.h"
|
||||
@@ -67,10 +51,8 @@ namespace rad {
|
||||
class IdleTiers;
|
||||
|
||||
/* ------------------------------------------------------------------ block identity */
|
||||
/* 128 bits, chained. A block's identity includes its whole prefix, so two identical 16-token spans
|
||||
* sitting at the same offset under different prefixes are DIFFERENT blocks and cannot be served
|
||||
* for one another. That is the property; the width is only there to make an accidental collision
|
||||
* improbable, and the stored token ids below make it impossible. */
|
||||
/* 128 bits, chained: identical spans under different prefixes are different blocks. The width
|
||||
* makes a collision improbable; the token compare on lookup makes a wrong hit impossible. */
|
||||
struct BlockHash {
|
||||
uint64_t hi = 0, lo = 0;
|
||||
bool operator==(const BlockHash& o) const { return hi == o.hi && lo == o.lo; }
|
||||
@@ -83,21 +65,16 @@ struct BlockHashHash {
|
||||
size_t operator()(const BlockHash& h) const { return (size_t)(h.lo ^ (h.hi * 0x9e3779b97f4a7c15ull)); }
|
||||
};
|
||||
|
||||
/* A multimodal span, keyed BY CONTENT. The placeholder token ids inside an image span are
|
||||
* identical for every image, so hashing token ids alone would serve one request another's picture.
|
||||
* The hash is taken over the ENCODER OUTPUT for the span -- the embedding bytes -- not over the
|
||||
* image file, so a re-encode of the same picture at the same resolution hits even when the JPEG
|
||||
* differs byte-for-byte, and two different pictures never alias (spec §7.3, §11).
|
||||
*
|
||||
* The cost, stated: a non-deterministic encoder produces different embedding bytes for the same
|
||||
* image and therefore MISSES. A miss is the safe direction; the alternative -- hashing the image
|
||||
* bytes -- gets a hit and the wrong embeddings when the preprocessing changes. */
|
||||
/* A multimodal span, keyed by content. Placeholder token ids are the same for every image, so
|
||||
* `hash` is the item's content key (core/mm: its processed patches, grid and tiling) mixed with
|
||||
* the run's row offset, by media_keys in core/sched/mem_iface.h (spec §7.3, §11). The same picture
|
||||
* at the same resolution and place hits even if the file bytes differ, and different pictures
|
||||
* never alias. Hashing the file instead would hit with stale KV whenever preprocessing changes. */
|
||||
struct MMContentKey {
|
||||
int32_t tok_begin = 0; /* [begin, end) in prompt-token coordinates */
|
||||
int32_t tok_end = 0;
|
||||
uint64_t hash = 0;
|
||||
};
|
||||
uint64_t mm_content_hash(const void* embedding, int64_t bytes);
|
||||
|
||||
/* The chained hash of one block. `parent` is the previous block's hash (a zeroed BlockHash for
|
||||
* block 0), `block_begin` is the block's first token position. */
|
||||
@@ -112,42 +89,47 @@ struct CacheHit {
|
||||
int32_t given_back = 0; /* reusable tokens a HitCap took off the whole hit */
|
||||
};
|
||||
|
||||
/* A HIT ENDED EARLY ON PURPOSE. The hit ends no later than `tokens` -- at a block and, for a model
|
||||
* with recurrent state, at the deepest checkpoint at or below it -- unless that gives back more
|
||||
* than `max_give_back` of what the whole hit would reuse, in which case the whole hit stands. It
|
||||
* exists for a drafter whose own KV the cache does not hold (Scheduler::init, --draft-refill):
|
||||
* recomputing the prompt's tail gives it context, and a cap whose nearest checkpoint is far below
|
||||
* would recompute far more than that tail. */
|
||||
/* Ends a hit early on purpose: at or below `tokens`, on a block and (with recurrent state) on the
|
||||
* deepest checkpoint at or below it, unless that gives back more than `max_give_back` reusable
|
||||
* tokens, in which case the whole hit stands. For a drafter whose KV the cache does not hold
|
||||
* (Scheduler::init, --draft-refill): recomputing the prompt's tail gives it context, and the
|
||||
* give-back limit stops a far-off checkpoint from turning that into a long recompute. */
|
||||
struct HitCap {
|
||||
int64_t tokens = 0;
|
||||
int64_t max_give_back = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ retention policy */
|
||||
/* Spec §19.1 records geometric backoff as a GUESS until there is a workload to measure. It is
|
||||
* therefore a policy OBJECT and not an if-statement, so replacing it is writing a class rather
|
||||
* than rewriting the cache. Two alternatives ship alongside it for exactly that reason. */
|
||||
/* Which checkpoints a session keeps. Spec §19.1 treats geometric backoff as unmeasured, so the
|
||||
* policy is a replaceable class with two alternatives alongside it. */
|
||||
class CheckpointPolicy {
|
||||
public:
|
||||
virtual ~CheckpointPolicy() = default;
|
||||
virtual const char* name() const = 0;
|
||||
/* `positions` ascending, one entry per checkpoint the session holds. Fill `keep` with the
|
||||
* subset to retain. THE TIP -- positions.back() -- MUST ALWAYS BE KEPT, because an appending
|
||||
* agent transcript is what this cache is for and the tip is the only thing it needs. */
|
||||
/* `positions` ascending, one per checkpoint the session holds; fill `keep` with the subset to
|
||||
* retain. The tip, positions.back(), must always be kept: an appending transcript resumes
|
||||
* from it. */
|
||||
virtual void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const = 0;
|
||||
};
|
||||
|
||||
/* Keep the tip, then 1x, 2x, 4x, 8x checkpoints back. Bounds the snapshot count at log(n) and the
|
||||
* recompute at one interval-doubling, which is the trade §19.1 describes. Distances are counted in
|
||||
* CHECKPOINTS rather than in tokens: the scheduler splits chunks at the interval so the spacing is
|
||||
* uniform, and counting in checkpoints stays correct if it ever is not. */
|
||||
/* Keep the tip and, at every scale S = interval x 2^k, the shallowest checkpoint in the tip's
|
||||
* bucket [j*S, (j+1)*S) and in the bucket before it. Depths behind the tip grow geometrically, a
|
||||
* session keeps about log2(tip / interval) + 2 snapshots, and a turn that diverges d tokens behind
|
||||
* the tip resumes less than max(2d, 2 x interval) below the divergence (spec §7.3). Buckets are
|
||||
* fixed token ranges, so the rule applied again after more checkpoints keeps the same ladder, and
|
||||
* a snapshot it drops is never one it would select later. */
|
||||
class GeometricBackoff final : public CheckpointPolicy {
|
||||
public:
|
||||
/* `interval` is the resolved checkpoint interval, the smallest scale. */
|
||||
explicit GeometricBackoff(int64_t interval) : interval_(interval > 0 ? interval : 1) {}
|
||||
const char* name() const override { return "geometric-backoff"; }
|
||||
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
|
||||
|
||||
private:
|
||||
int64_t interval_;
|
||||
};
|
||||
|
||||
/* The two obvious ends of the trade, kept so a measurement can be run against them. */
|
||||
/* The two ends of the trade, for comparison. */
|
||||
class KeepTipOnly final : public CheckpointPolicy {
|
||||
public:
|
||||
const char* name() const override { return "tip-only"; }
|
||||
@@ -162,18 +144,12 @@ public:
|
||||
/* ------------------------------------------------------------------ the cache */
|
||||
class PrefixCache {
|
||||
public:
|
||||
/* `kv` must already be configured: the cache holds a KV-manager reference on every block it
|
||||
* indexes, which is the invariant that makes a hit safe -- a block in the map is never in the
|
||||
* free list, so it can never be handed to another sequence underneath a cache entry.
|
||||
/* `kv` must already be configured. The cache holds a KV reference on every block it indexes,
|
||||
* so an indexed block is never on the free list and cannot be handed to another sequence.
|
||||
*
|
||||
* `checkpoint_interval` IS THE SCHEDULER'S RESOLVED INTERVAL, NOT cfg.checkpoint_interval.
|
||||
* The two are different numbers: chunk_geometry_resolve rounds the operator's request UP to
|
||||
* the chunk quantum so that "split at the interval" is always also a legal chunk split. If
|
||||
* this cache read the raw config value while the scheduler split on the rounded one, every
|
||||
* checkpoint would be refused by reserve_checkpoint -- with an error saying the scheduler
|
||||
* splits at the interval precisely so this cannot happen -- and restore() would walk back in
|
||||
* the wrong stride looking for snapshots nothing had written. It is a parameter rather than a
|
||||
* config read so that there is one place the number comes from. */
|
||||
* `checkpoint_interval` is the scheduler's resolved interval, not cfg.checkpoint_interval:
|
||||
* chunk_geometry_resolve rounds the flag up to the chunk quantum. Using the raw value would
|
||||
* make reserve_checkpoint refuse every checkpoint and lookups search the wrong stride. */
|
||||
int configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval);
|
||||
bool enabled() const { return enabled_; }
|
||||
int64_t block_size() const { return block_size_; }
|
||||
@@ -181,9 +157,8 @@ public:
|
||||
const std::vector<int32_t>& cached_groups() const { return groups_; }
|
||||
std::string report() const;
|
||||
|
||||
/* AFTER configure(), which installs the one Config::checkpoint_policy names. This is the
|
||||
* in-process override -- a policy that is not one of the three, or one a test wants to
|
||||
* substitute -- and calling it first would be undone. */
|
||||
/* Overrides the policy configure() installed from Config::checkpoint_policy (custom policies,
|
||||
* tests). Call after configure(), which would undo it. */
|
||||
void set_policy(std::unique_ptr<CheckpointPolicy> p);
|
||||
const CheckpointPolicy& policy() const { return *policy_; }
|
||||
|
||||
@@ -192,9 +167,8 @@ public:
|
||||
* for a prefix of it. `blocks_out`, when given, receives the block ids per cached group, in
|
||||
* cached_groups() order, ready for KVManager::adopt().
|
||||
*
|
||||
* NEVER returns the whole prompt: at least one token must remain for the step to compute a
|
||||
* logit from, so a full hit is backed off by one block. That is not a subtlety the caller
|
||||
* should have to know. `cap`, when given, ends the hit early (HitCap). */
|
||||
* Never returns the whole prompt: one token must remain to compute a logit from, so a full
|
||||
* hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). */
|
||||
CacheHit lookup(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<std::vector<int32_t>>* blocks_out = nullptr,
|
||||
@@ -209,123 +183,86 @@ public:
|
||||
int64_t n_tokens,
|
||||
const std::string& label = std::string());
|
||||
|
||||
/* Drop the least recently used entries, releasing their KV references. Returns how many were
|
||||
* dropped. Blocks a live sequence still holds stay allocated -- releasing the cache's
|
||||
* reference is not freeing the block.
|
||||
*
|
||||
* A CLEAN ENTRY IS RELEASED AND KEPT. With the idle tiers on, an entry whose host copy has
|
||||
* landed loses nothing by leaving VRAM, so pressure on the pool moves it to the host tier
|
||||
* 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. */
|
||||
/* Release up to `n_entries` least recently used entries' KV references; returns how many went.
|
||||
* Entries a live sequence also holds are skipped, since releasing them frees nothing. With the
|
||||
* idle tiers on, an entry whose host copy has landed moves to the host tier instead of being
|
||||
* forgotten; only one with no host copy is lost. */
|
||||
int64_t evict_lru(int64_t n_entries);
|
||||
/* FREE UP TO `n_blocks` 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. */
|
||||
/* Free up to `n_blocks` pool blocks for the scheduler's reserve without losing anything a
|
||||
* later turn could reuse. One oldest-first walk that skips entries a live sequence also holds
|
||||
* and, with the tiers on, entries whose host copy has not landed yet. Pressure that cannot
|
||||
* wait goes to evict_lru. Returns how many blocks went back. */
|
||||
int64_t trim(int64_t n_blocks);
|
||||
/* GIVE 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
|
||||
* holds would free nothing, so it is asked about again once a sequence has let go of blocks. */
|
||||
/* Give up every VRAM copy that costs nothing to drop: host copy landed and no running sequence
|
||||
* reading it. Used when the memory has a better use (the expert slab's loan). Entries still
|
||||
* shared are retried after a sequence frees blocks. Returns how many entries left VRAM. */
|
||||
int64_t drop_clean();
|
||||
int64_t size() const { return (int64_t)map_.size(); }
|
||||
/* How many entries hold blocks in the pool, as opposed to only a copy off the card. */
|
||||
/* Entries holding blocks in the pool, as opposed to only a copy off the card. */
|
||||
int64_t resident() const { return (int64_t)lru_.size(); }
|
||||
/* HOW MUCH OF THE POOL THIS CACHE IS HOLDING ON ITS OWN, in tokens of context. The entry
|
||||
* count cannot answer that: an entry's blocks are SHARED with every live sequence that hit on
|
||||
* them, and on a server carrying long conversations that is most of the index -- so an index
|
||||
* size read as "memory the cache is keeping back" says a request reading its own context is
|
||||
* the cache refusing to release it. What an eviction would actually free is the blocks
|
||||
* nothing else references, which is what this counts. */
|
||||
/* Pool held by the cache alone, in tokens: blocks nothing else references, i.e. what an
|
||||
* eviction would actually free. The entry count overstates this, because entries share blocks
|
||||
* with every live sequence that hit them. */
|
||||
int64_t unshared_tokens() const;
|
||||
/* Forget every entry, in VRAM or off it, and give back whatever the tiers held for them. */
|
||||
void clear();
|
||||
/* Diagnostic: the LRU order, oldest first. */
|
||||
std::vector<BlockHash> lru_order() const;
|
||||
/* Diagnostic: clean entries drop_clean() is waiting to recheck, each listed once. */
|
||||
size_t drop_waiting() const { return drop_wait_.size(); }
|
||||
|
||||
/* ---------------- idle session tiers (core/mem/kvtier.h) ---------------- */
|
||||
/* Installed after configure() when the tiers are on. A null pointer is the whole of the "off"
|
||||
* path: every call site below is guarded, and with no tiers the cache is a plain VRAM-only
|
||||
* prefix cache. */
|
||||
/* Installed after configure() when the tiers are on. Null means a plain VRAM-only cache;
|
||||
* every use is guarded. */
|
||||
void set_tiers(IdleTiers* t) { tiers_ = t; }
|
||||
|
||||
/* THE CHAIN THIS PROMPT WOULD HIT IF THE TIERS GAVE IT BACK, in order, starting at the block
|
||||
* `lookup` stopped on. The caller promotes them and asks again; an empty answer means the
|
||||
* prefix stopped for an ordinary reason -- a miss, or a token compare -- and no amount of
|
||||
* restoring would lengthen it.
|
||||
*
|
||||
* It is a separate call rather than something lookup does because lookup is const and has no
|
||||
* device: a promotion allocates blocks and runs a scatter, which is the engine's to do
|
||||
* between steps and not something a cache query may trigger under the caller. */
|
||||
/* The off-device entries this prompt's chain would hit if restored, in order, from where
|
||||
* lookup stopped. The caller promotes them and looks up again; empty means the prefix ended
|
||||
* on a miss or token mismatch. Separate from lookup because lookup is const and has no
|
||||
* device; a promotion allocates blocks and runs a scatter between steps. */
|
||||
std::vector<BlockHash> restorable_from(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm) const;
|
||||
|
||||
/* THE TIERS LOST THE BYTES. Erase the entry WITHOUT releasing blocks: an off-device entry
|
||||
* owns none -- demotion released them -- and its recorded ids belong to whoever the pool gave
|
||||
* them to since. Releasing those would free another sequence's block; leaving the entry in
|
||||
* the map would serve them. Installed as IdleTiers::set_drop_sink. */
|
||||
/* The tiers lost the bytes. Erases the entry without releasing blocks: an off-device entry
|
||||
* owns none, and its recorded ids now belong to other sequences. Installed as
|
||||
* IdleTiers::set_drop_sink. */
|
||||
void drop_offdevice(const BlockHash& key);
|
||||
|
||||
/* A restore finished: the entry's blocks live at these ids now. The cache takes a reference on
|
||||
* each, because the restore holds them only as raw reservations (KVManager::reserve_block) and
|
||||
* this is where they become cache-held blocks with the usual invariant. */
|
||||
/* A restore finished and the entry's blocks now live at these ids. The restore's raw
|
||||
* reservations (KVManager::reserve_block) become cache-held references. */
|
||||
int rebind(const BlockHash& key, const std::vector<int32_t>& blocks);
|
||||
|
||||
|
||||
/* ---------------- 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 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.
|
||||
*
|
||||
* 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. There is no tier below the store: a
|
||||
* snapshot the store retires is gone, and a session that needed it replays its recurrent
|
||||
* layers from an older one. */
|
||||
* On a hybrid model a session also needs its recurrent state back, held in a checkpoint slot:
|
||||
* the engine's snapshot store in pinned host memory, KVManager::checkpoint_bytes() per rank,
|
||||
* --checkpoint-slots in total for the server. Without a reachable snapshot a session reuses
|
||||
* nothing: the scheduler clamps reuse to the last reachable checkpoint because RadBatch has
|
||||
* one query length for all KV groups (Scheduler::admit_one). A snapshot is restored straight
|
||||
* from its slot wherever the blocks are. There is no tier below the store; a retired snapshot
|
||||
* is gone and the session replays from an older one. */
|
||||
|
||||
/* 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. */
|
||||
/* Keep a waiting request's chain on the card. An admission that restored a chain and was then
|
||||
* refused gives its hit back with clean entries; without a hold, drop_clean would drop them
|
||||
* and every retry would restore the chain again. drop_clean skips held entries until
|
||||
* release(); trim and evict_lru still take them. 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. Until then a handed snapshot
|
||||
* keeps its slot through every path that would give one up: retention, the eviction in
|
||||
* reserve_checkpoint, and the expiry. */
|
||||
/* Start of a step's admissions. Snapshots the previous step's lookups handed out have been
|
||||
* read by its forward by now; until this call they keep their slots against retention,
|
||||
* reserve_checkpoint's eviction and expiry. */
|
||||
void begin_step() { handed_.clear(); }
|
||||
|
||||
/* ---------------- expiry ----------------
|
||||
*
|
||||
* TAKE OUT EVERYTHING NO REQUEST HAS USED FOR `ttl_ns`: entries in VRAM (their blocks go back
|
||||
* to the pool), entries only the host holds (their slots go back to the arena), and snapshots
|
||||
* (their store slots go back). An entry is used when a lookup hits it or a request publishes
|
||||
* it, and a snapshot when its prefix entry is or when a lookup hands it out. Nothing is moved
|
||||
* anywhere first: an expired conversation is one the operator has said is not coming back.
|
||||
* Remove everything no request has used for `ttl_ns`: VRAM entries, host-only entries and
|
||||
* snapshots, each returned to its pool. An entry is used by a hit or a publish; a snapshot by
|
||||
* a use of its prefix entry or a lookup handing it out. Nothing is demoted first.
|
||||
*
|
||||
* A PREFIX IS NEVER OLDER THAN WHAT FOLLOWS IT. A hit or a publish stamps every block of the
|
||||
* chain up to where it ends with one clock, so a conversation expires from its tip inwards and
|
||||
* a shared system prompt outlives every conversation that still reads it. Returns how many
|
||||
* entries went. */
|
||||
* A hit or publish stamps every block of the chain with one clock, so a prefix is never older
|
||||
* than what follows it: conversations expire from the tip inwards and a shared system prompt
|
||||
* outlives its readers. Returns how many entries went. */
|
||||
int64_t expire(uint64_t now_ns, uint64_t ttl_ns);
|
||||
/* ---------------- linear checkpoints ---------------- */
|
||||
/* The next position strictly after `pos` at which the scheduler must split a chunk so that a
|
||||
@@ -333,38 +270,38 @@ public:
|
||||
int64_t next_checkpoint_after(int64_t pos) const;
|
||||
bool is_checkpoint(int64_t pos) const { return interval_ > 0 && pos > 0 && pos % interval_ == 0; }
|
||||
|
||||
/* Reserve a snapshot slot for `session` at `pos`. Applies the retention policy when the slot
|
||||
* pool is exhausted, then evicts the least recently used snapshot, a session's tip last. A
|
||||
* snapshot a lookup handed out this step is never given up: the admission it was handed to
|
||||
* restores from the slot ahead of the step, after this reservation was made. RAD_E_FULL when
|
||||
* nothing else can be given up. */
|
||||
/* Reserve a snapshot slot for `session` at `pos`. When the store is full, applies the
|
||||
* retention policy, then evicts the least recently used snapshot (a use is its reservation or
|
||||
* a lookup resuming from it), a tip like any other. A snapshot handed out this step is never
|
||||
* evicted: its admission restores from the slot ahead of the step. RAD_E_FULL when nothing
|
||||
* can be given up. */
|
||||
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. */
|
||||
/* The state for `prefix` is now in its slot; lookup() offers it only after this (Ckpt::valid). */
|
||||
void commit_checkpoint(const BlockHash& prefix);
|
||||
/* Every checkpoint of a session, ascending. */
|
||||
std::vector<int64_t> checkpoints(uint64_t session) const;
|
||||
/* Apply the retention policy to one session now. Returns how many snapshots were released.
|
||||
* A session left holding nothing is forgotten -- see the note at the definition for why that
|
||||
* matters more than the bytes. */
|
||||
/* Apply the retention policy to one session now, keeping also what a lookup resumed from
|
||||
* since the session's tip was written. Returns how many snapshots were released. A session
|
||||
* left with none is erased from the index. */
|
||||
int64_t retain(uint64_t session);
|
||||
|
||||
/* How many sessions the checkpoint index still knows about. Exposed because it is an
|
||||
* INVARIANT rather than a statistic: a session is a request id, so this must track the
|
||||
* sessions holding a live snapshot and not the number of requests the process has served. */
|
||||
/* Sessions in the checkpoint index. Invariant: since a session is a request id, this tracks
|
||||
* sessions holding a live snapshot, not every request served. */
|
||||
int64_t sessions_tracked() const { return (int64_t)ck_by_session_.size(); }
|
||||
|
||||
struct Stats {
|
||||
int64_t lookups = 0, block_hits = 0, block_misses = 0;
|
||||
int64_t ckpt_hits = 0, ckpt_misses = 0;
|
||||
int64_t evictions = 0, ckpt_evictions = 0;
|
||||
/* Entries whose VRAM copy was given up with their host copy kept. Not evictions: nothing
|
||||
* was lost, and a counter that mixed the two would read a working tier as a thrashing
|
||||
* cache. */
|
||||
/* ckpt_evictions by reason: released by the retention policy, or taken as the least
|
||||
* recently used of a store retention left full. `ckpt_refused` counts reservations that
|
||||
* found every slot handed out this step and went without a snapshot. */
|
||||
int64_t ckpt_retired = 0, ckpt_lru = 0, ckpt_refused = 0;
|
||||
/* Entries whose VRAM copy was given up with the host copy kept; not evictions, since
|
||||
* nothing was lost. */
|
||||
int64_t drops = 0;
|
||||
/* Entries and snapshots --prefix-cache-ttl took, from whichever tier held them. Not
|
||||
* evictions either: nothing wanted the memory. */
|
||||
/* Entries and snapshots removed by --prefix-cache-ttl, from any tier. */
|
||||
int64_t expired = 0, ckpt_expired = 0;
|
||||
};
|
||||
const Stats& stats() const { return stats_; }
|
||||
@@ -373,15 +310,12 @@ private:
|
||||
struct Entry {
|
||||
std::vector<int32_t> blocks; /* one per cached group, in groups_ order */
|
||||
std::vector<int32_t> tokens; /* the block's token ids, compared on hit */
|
||||
/* ON THE LRU EXACTLY WHILE THE CACHE HOLDS THE BLOCKS. An entry whose bytes are only off
|
||||
* the card owns no block, so it has nothing an eviction could free, and walking past it
|
||||
* under pressure would erase the tier's copy to make room it never occupied. `lru` is
|
||||
* valid only while this is set. */
|
||||
/* On the LRU exactly while the cache holds the blocks; `lru` is valid only then. An
|
||||
* off-device entry owns no block, so eviction must not reach it. */
|
||||
bool in_lru = false;
|
||||
bool drop_wait = false; /* in drop_wait_: clean, but a sequence still reads it */
|
||||
/* LAST USE, on the monotonic clock: a hit or a publish. The LRU list is in this order --
|
||||
* every path that puts an entry at its back stamps it -- which is what lets the expiry
|
||||
* stop at the first entry it keeps. */
|
||||
/* Last hit or publish, monotonic clock. Every path that moves an entry to the LRU's back
|
||||
* stamps it, so the list is in this order and expiry stops at the first entry it keeps. */
|
||||
uint64_t used_ns = 0;
|
||||
std::list<BlockHash>::iterator lru;
|
||||
};
|
||||
@@ -390,12 +324,13 @@ private:
|
||||
int64_t pos = 0;
|
||||
BlockHash prefix;
|
||||
int32_t slot = -1;
|
||||
uint64_t used = 0;
|
||||
/* `clock_` values: the last use (reservation or hand-out, the eviction order), the
|
||||
* reservation, and the last hand-out (0 if none). */
|
||||
uint64_t used = 0, made = 0, resumed = 0;
|
||||
uint64_t used_ns = 0; /* reserved, or handed out by a lookup */
|
||||
/* HAS THE STATE ACTUALLY BEEN WRITTEN INTO THE SLOT YET. reserve_checkpoint runs when the
|
||||
* scheduler PLANS the chunk; the copy happens after the step that computes the state. A
|
||||
* lookup between those two points would hand out a slot holding the previous tenant's
|
||||
* history, which is the exact failure this whole mechanism exists to prevent. */
|
||||
/* The state has been written into the slot. Reservation happens when the chunk is
|
||||
* planned and the copy after the step that computes it; in between the slot still holds
|
||||
* the previous tenant's state and must not be handed out. */
|
||||
bool valid = false;
|
||||
};
|
||||
|
||||
@@ -403,14 +338,21 @@ private:
|
||||
const std::vector<MMContentKey>& mm,
|
||||
int64_t n_blocks) const;
|
||||
void touch(const BlockHash& h, uint64_t now_ns) const;
|
||||
/* Does a live sequence hold any of this entry's blocks as well? Then releasing the cache's
|
||||
* reference frees nothing. */
|
||||
/* A live sequence also holds one of this entry's blocks, so releasing it frees nothing. */
|
||||
bool shared_with_live(const Entry& e) const;
|
||||
/* Retire one snapshot: its slot goes back to the store and the tiers stop naming it. The
|
||||
* session index is the caller's, since every caller is already rebuilding or erasing it. */
|
||||
/* Whether `e` holds the block_size_ token ids at `src`, so a hash collision is a miss. */
|
||||
bool same_tokens(const Entry& e, const int32_t* src) const;
|
||||
/* Gives the entry's block in every group back to the KV manager. */
|
||||
void release_blocks(const Entry& e);
|
||||
/* Retire one snapshot: free its slot and tell the tiers. The session index is left to the
|
||||
* caller. */
|
||||
void retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it);
|
||||
/* Take one key out of a session's index entry, and the entry when it empties. */
|
||||
void unindex_ckpt(uint64_t session, const BlockHash& key);
|
||||
/* For the debug lines: whether `c` is its session's deepest snapshot, and seconds since a
|
||||
* monotonic stamp. */
|
||||
bool is_tip(const Ckpt& c) const;
|
||||
static double idle_s(uint64_t used_ns);
|
||||
|
||||
KVManager* kv_ = nullptr;
|
||||
IdleTiers* tiers_ = nullptr;
|
||||
@@ -422,20 +364,19 @@ private:
|
||||
|
||||
mutable std::unordered_map<BlockHash, Entry, BlockHashHash> map_;
|
||||
mutable std::list<BlockHash> lru_; /* front = oldest; resident entries only */
|
||||
/* CLEAN ENTRIES A SEQUENCE WAS STILL READING when drop_clean last looked, and the pool's count
|
||||
* of freed sequences at that moment. Only a sequence letting go of blocks can make one of them
|
||||
* droppable, so they are looked at again only when that count has moved. */
|
||||
/* Clean entries a sequence was still reading at drop_clean's last pass, and the pool's
|
||||
* sequence-free count then. They are rechecked only once that count moves. */
|
||||
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. */
|
||||
/* hold(): keys per waiting request, and holders per key. A release also triggers a recheck
|
||||
* of drop_wait_. */
|
||||
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: kept in their slots until then (begin_step). */
|
||||
/* Snapshots lookup handed out since begin_step; kept in their slots until the next one. */
|
||||
mutable std::vector<BlockHash> handed_;
|
||||
bool handed(const BlockHash& h) const {
|
||||
return std::find(handed_.begin(), handed_.end(), h) != handed_.end();
|
||||
|
||||
+83
-127
@@ -1,5 +1,5 @@
|
||||
/* vram_budget.cpp -- see vram_budget.h for why a derived budget is not the §6 violation it looks
|
||||
* like. This file is the arithmetic and the receipt. */
|
||||
/* vram_budget.cpp -- the budget arithmetic and its printed report. See vram_budget.h for why a
|
||||
* derived budget does not violate §6. */
|
||||
#include "mem/vram_budget.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -10,48 +10,38 @@ namespace rad {
|
||||
namespace {
|
||||
constexpr int64_t kMiB = 1024 * 1024;
|
||||
|
||||
/* DOWN, ALWAYS. The pools take MiB and multiply back up, so a budget rounded up is a budget that
|
||||
* asks the card for more than the arithmetic said was there -- which fails at the allocation
|
||||
* rather than here, with the driver's message instead of ours. */
|
||||
/* Rounds down: the pools multiply MiB back up, and rounding up would ask the card for more than
|
||||
* the arithmetic found, failing at allocation with the driver's message instead of ours. */
|
||||
int64_t to_mib(int64_t bytes) { return bytes > 0 ? bytes / kMiB : 0; }
|
||||
|
||||
/* UP, FOR THE ONE BUDGET THAT IS A FLOOR. The KV budget is a CAPACITY -- truncated, the cache
|
||||
* addresses a few fewer tokens and nothing else changes. The weights budget is `statics +
|
||||
* experts`, a figure the pool must COVER, and a byte short is a tensor with nowhere to land. An
|
||||
* expert share pads the number enough to hide that; a dense model is budgeted its static
|
||||
* 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. */
|
||||
/* Rounds up, for the weights budget only. The KV budget is a capacity and may be truncated; the
|
||||
* weights budget (`statics + experts`) must cover every tensor, and a dense model is budgeted its
|
||||
* static footprint to the byte. The extra MiB comes out of the headroom. */
|
||||
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. */
|
||||
/* How much the driver's own holding moves after `already_held` is read. On ROCm 7.2 the reading
|
||||
* has come in 4 MiB below what the driver later held, leaving the first kernel launches short of
|
||||
* headroom. Four times that, 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
|
||||
* max_seqs sequences plus their context, and the state is spent before a single token is cached --
|
||||
* on a hybrid model at a few dozen sequences it is gigabytes a card. A ratio over the whole
|
||||
* ceiling counts that state as context and reports full-length sessions the cache cannot hold. */
|
||||
/* The fraction of the paged (context) part of the ceiling the cache backs. The ceiling also
|
||||
* includes fixed recurrent and conv state (gigabytes per card on a hybrid model), which a ratio
|
||||
* over the whole ceiling would wrongly count as context. */
|
||||
static double paged_share(const VramBudget& b) {
|
||||
const double ctx = (double)(b.kv_ceiling - b.kv_fixed);
|
||||
return ctx > 0 ? std::max(0.0, (double)(b.kv - b.kv_fixed)) / ctx : 0.0;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* The resolver. `log` is false for vram_budget_trial, whose split may never be used, so its
|
||||
* refusals must not print as startup failures. */
|
||||
static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out, bool log) {
|
||||
VramBudget b;
|
||||
if (per_rank.empty()) { if (out) *out = b; return RAD_OK; }
|
||||
|
||||
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is derived for every rank. Ranks
|
||||
* of one deployment normally hold the same shard shapes and the same program, so these folds
|
||||
* are no-ops -- they exist so that a mixed pair degrades to the card that binds instead of
|
||||
* overcommitting the smaller one on the first allocation. An uneven world's cheaper ranks are
|
||||
* re-split from this answer afterwards (vram_budget_rank_split, called by Engine::plan). */
|
||||
/* The smallest card and the largest program, since one split serves every rank. Normally a
|
||||
* no-op; a mixed pair degrades to the card that binds. An uneven world's cheaper ranks are
|
||||
* re-split afterwards (vram_budget_rank_split, from Engine::plan). */
|
||||
b.capacity = per_rank[0].capacity;
|
||||
int64_t freeb = per_rank[0].free;
|
||||
int64_t layer_max = 0, kv_one = 0;
|
||||
@@ -71,7 +61,7 @@ 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. */
|
||||
/* 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);
|
||||
}
|
||||
@@ -83,11 +73,10 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
const bool shared = host_reserve > b.headroom;
|
||||
if (shared) b.headroom = host_reserve;
|
||||
|
||||
/* A DEVICE THAT REPORTS NO CAPACITY HAS NOTHING TO SPLIT, and inventing a capacity would be
|
||||
* exactly the inference §6 forbids. What each pool needs is still known: the weights pool
|
||||
* holds what the planner would copy out of the container -- the statics and experts
|
||||
* weight_footprint counts -- and the cache is its ceiling, every sequence at the full context.
|
||||
* (The host backend reports half the machine's memory and is split like a card.) */
|
||||
/* A device that reports no capacity has nothing to split, and inventing one is the inference
|
||||
* §6 forbids. Each pool gets what it needs: weights what the planner copies out of the
|
||||
* container (weight_footprint), the cache its ceiling. (The host backend reports half the
|
||||
* machine's memory and is split like a card.) */
|
||||
if (b.capacity <= 0) {
|
||||
b.weights = std::max<int64_t>(b.statics + b.expert_ceiling, kMiB);
|
||||
b.kv = std::max<int64_t>(b.kv_ceiling, kMiB);
|
||||
@@ -102,14 +91,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* MEASURED, NOT ASSUMED, AND IT IS THE ONLY TERM THAT IS. Everything the driver and the loaded
|
||||
* code objects already hold shows up here, including a desktop compositor on the same card --
|
||||
* which is a real configuration on a workstation and the reason this is a line in the report
|
||||
* rather than a constant folded into the headroom. Read after declare(), so every kernel
|
||||
* plugin's init has run and its code object is resident. */
|
||||
/* The only measured term: the driver, loaded code objects and anything else on the card (e.g.
|
||||
* a desktop compositor), so it is reported on its own line rather than folded into the
|
||||
* headroom. Read after declare(), once every kernel plugin's code object is resident. */
|
||||
b.already_held = std::max<int64_t>(b.capacity - freeb, 0);
|
||||
|
||||
/* What is left after the terms nobody gets to spend. */
|
||||
/* What is left after the fixed terms. */
|
||||
b.drift = kDriverDrift;
|
||||
b.claimable = b.capacity - (b.already_held + b.drift + b.headroom + b.arena + b.staging +
|
||||
b.queues + b.prefetch);
|
||||
@@ -126,7 +113,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" hardware queues %10s (%d at %s each, measured)\n"
|
||||
" expert prefetch %10s (its ring of expert units and buffers)\n"
|
||||
" ------------------------------\n"
|
||||
" SHORT BY %10s\n"
|
||||
" 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.drift).c_str(),
|
||||
@@ -138,41 +125,37 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
/* ---- the static weights come off the top ------------------------------------------------
|
||||
*
|
||||
* They are a floor and not a share. */
|
||||
/* ---- the static weights come off the top, as a floor ------------------------------------ */
|
||||
b.statics = std::min(b.statics, b.claimable);
|
||||
if (b.statics >= b.claimable && b.claimable > 0) {
|
||||
/* Not fatal: the planner will demote what does not fit and the model still serves,
|
||||
* badly. Name it, because "why is this model 8x slower than it should be" has no other
|
||||
* answer at startup. */
|
||||
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
|
||||
"give. Every expert will stream from host memory and the KV cache has "
|
||||
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
|
||||
"--max-num-batched-tokens.",
|
||||
humanb(b.statics).c_str(), humanb(b.claimable).c_str());
|
||||
/* Not fatal: the planner demotes what does not fit and the model serves slowly. Warn so
|
||||
* the slowdown is explained at startup. */
|
||||
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card can "
|
||||
"give, so every expert streams from host memory and the KV cache gets "
|
||||
"nothing; use more cards or a smaller --max-num-batched-tokens",
|
||||
humanb(b.statics).c_str(), humanb(b.claimable).c_str());
|
||||
}
|
||||
b.elastic = b.claimable - b.statics;
|
||||
if (b.elastic < 0) b.elastic = 0;
|
||||
|
||||
/* ---- and only what is left is divided --------------------------------------------------- */
|
||||
/* ---- the rest is divided ---------------------------------------------------------------- */
|
||||
{
|
||||
/* An unset cache ceiling (plan_groups failed) bounds nothing; zero experts is a ceiling of
|
||||
* zero, which weight_footprint always measures. */
|
||||
/* An unset cache ceiling (plan_groups failed) bounds nothing. An expert ceiling of zero is
|
||||
* real: weight_footprint always measures it. */
|
||||
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. */
|
||||
/* 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. */
|
||||
/* The cache lends: size it for what live requests could need; it gives back what
|
||||
* 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. */
|
||||
/* One full-length sequence wins; experts it pushes off the card have no tier and the
|
||||
* planner refuses them. Warn here too, with the flags that fix it. */
|
||||
if (log && b.expert_floor > 0 && 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 "
|
||||
@@ -180,8 +163,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
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. */
|
||||
/* No lender: an unused block would sit empty, so 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);
|
||||
}
|
||||
@@ -192,35 +175,29 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
b.weights = b.statics + exp;
|
||||
b.unusable = std::max<int64_t>(b.elastic - kv - exp, 0);
|
||||
}
|
||||
/* A POOL NOTHING IS PLACED IN STILL HAS TO EXIST. Where every weight is read where the
|
||||
* container's mapping has it -- every op on the host, on the host backend -- the statics and
|
||||
* experts are zero, and the pools refuse a zero budget as a resolver that never ran. A MiB,
|
||||
* out of the headroom as the rounding's is. */
|
||||
/* The weights pool must exist even when empty (every weight read from the container's
|
||||
* mapping on the host backend), since the pools treat a zero budget as an unresolved one. One
|
||||
* MiB, out of the headroom. */
|
||||
b.weights = std::max<int64_t>(b.weights, kMiB);
|
||||
|
||||
/* ---- THE PREFILL STAGING REGION, out of the expert share ---------------------------------
|
||||
/* ---- the prefill staging region ----------------------------------------------------------
|
||||
*
|
||||
* A prefill chunk routes to nearly every expert of every layer, so the part of each layer the
|
||||
* budget leaves off the card is read across the link by the layer's GEMM -- on the critical
|
||||
* path, at the link's rate, while the rest of the layer's work leaves the link idle. Two
|
||||
* buffers of one layer's share of that let the next layer's copy run behind the current one
|
||||
* (core/place/stager.h). They come out of the expert share because they exist only for the
|
||||
* experts that do not fit, and they sit at the top of the activation arena, which every step
|
||||
* smaller than the full plan lends back to the expert slab: a decode step keeps the residency
|
||||
* they cost.
|
||||
* Two layers' share of the experts left off the card, for the prefill stager's ring
|
||||
* (core/place/stager.h). It exists only for experts that do not fit, so it comes out of the
|
||||
* expert share (or, when the cache lends, the cache's). It sits at the top of the activation
|
||||
* arena, which steps smaller than the full plan lend back to the expert slab, so decode keeps
|
||||
* the residency.
|
||||
*
|
||||
* The share is the budget's -- what the slab alone leaves off -- which is the most a step can
|
||||
* see: the loans the KV cache and the smaller arena levels make only ever add residency. A
|
||||
* layer whose pooled part is larger than a buffer stages what fits and streams the rest. */
|
||||
* The share is what the slab alone leaves off, the most a step can see: KV and arena loans only
|
||||
* add residency. A layer larger than its share stages what fits and streams the rest. */
|
||||
if (layer_max > 0 && b.expert_ceiling > b.experts && cfg.placement != "all_vram" &&
|
||||
cfg.placement != "layer_offload") {
|
||||
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 (b.lends) {
|
||||
/* 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. */
|
||||
/* With a lending cache the cache pays: experts are at their floor, and the region is
|
||||
* lent to the slab in small steps, as the cache would have lent it. */
|
||||
if (b.kv - 2 * one >= kv_one) {
|
||||
b.stage = 2 * one;
|
||||
b.kv -= b.stage;
|
||||
@@ -232,45 +209,31 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
}
|
||||
}
|
||||
|
||||
/* HOW MUCH OF THE ADVERTISED CONTEXT THE POOL BACKS, AND IT IS A PROVISIONING CHOICE RATHER
|
||||
* THAN A SHORTFALL.
|
||||
*
|
||||
* A KV share under max_seqs x max_ctx is not a warning. The argument that it would be -- that
|
||||
* the server accepts at the door what it cannot serve -- is wrong for a PAGED cache, and the
|
||||
* difference is the whole of vLLM's block manager: a sequence holds only the blocks its tokens
|
||||
* actually occupy (KVManager::ensure grows it by ceil_div(n_tokens, block_size) as it runs,
|
||||
* drops them at completion, and returns RAD_E_FULL for the scheduler to preempt rather than
|
||||
* failing the request). Every sequence reaching max_ctx at the same moment is the worst case,
|
||||
* not the workload -- real loads run well under half backing -- and sizing for the worst case
|
||||
* spends VRAM that a model whose experts do not fit would rather have for them.
|
||||
*
|
||||
* So it is reported and not warned about. What IS still checked, and belongs in the KV manager
|
||||
* because it is a real limit rather than a ratio, is that ONE max-length sequence fits: a
|
||||
* context no single request can complete is a configuration error however much slack the pool
|
||||
* has (core/engine_bringup.cpp, configure_kv). */
|
||||
/* How much of max_seqs x max_ctx the pool backs: a provisioning choice, reported, not warned
|
||||
* about. A paged cache holds only the blocks a sequence occupies (KVManager::ensure grows it,
|
||||
* and RAD_E_FULL makes the scheduler preempt), so all sequences at max_ctx at once is the
|
||||
* worst case, not the workload, and sizing for it takes VRAM from experts that do not fit.
|
||||
* The real limit, that one max-length sequence fits, is checked in configure_kv
|
||||
* (core/engine_bringup.cpp). */
|
||||
if (log && b.kv_ceiling > 0 && cfg.max_ctx > 0)
|
||||
RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), "
|
||||
"%.1f full-length sessions. That is concurrency at length before the scheduler "
|
||||
"preempts, not a bound on any one request. WITH PREFIX CACHING a finished "
|
||||
"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. --host-pool-mib moves it: the experts the host pool cannot hold are the "
|
||||
"part of the card the cache cannot have.",
|
||||
"%.1f full-length sessions; a larger --host-pool-mib gives the cache more",
|
||||
100.0 * paged_share(b),
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
|
||||
(double)cfg.max_seqs * paged_share(b));
|
||||
/* Rounding the floor up claims up to a MiB the split did not hand out. Take it back from the
|
||||
* cache -- a paged pool a MiB smaller addresses a handful fewer tokens and nothing else -- so
|
||||
* the headroom stays whole. */
|
||||
/* Rounding the weights up claims up to a MiB the split did not hand out; take it back from
|
||||
* the cache so the headroom stays whole. */
|
||||
cfg.vram_weights_mib = to_mib_up(b.weights);
|
||||
const int64_t w_over = cfg.vram_weights_mib * kMiB - b.weights;
|
||||
cfg.vram_kv_mib = to_mib(std::max<int64_t>(b.kv - w_over, 0));
|
||||
/* A cache given its whole ceiling is rounded up to cover it, out of the headroom as the
|
||||
* weights' MiB is: truncated, a ceiling under a MiB would be an empty pool and one just over a
|
||||
* whole MiB a pool short of its own context. */
|
||||
if (b.kv_ceiling > 0 && b.kv >= b.kv_ceiling && cfg.vram_kv_mib * kMiB < b.kv_ceiling)
|
||||
cfg.vram_kv_mib = to_mib_up(b.kv_ceiling);
|
||||
|
||||
/* THE RECEIPT. Every term, in the order it was spent, so that a split anybody disagrees with
|
||||
* can be argued about against numbers instead of re-derived from sysfs by hand. The unclaimed
|
||||
* line is not padding: to_mib truncates, and what it drops is real VRAM that ends up beside
|
||||
* the headroom. */
|
||||
/* The report: every term in the order spent. `unclaimed` includes what to_mib truncated,
|
||||
* which stays 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.drift - b.arena - b.staging - b.queues -
|
||||
b.prefetch - b.stage - granted;
|
||||
@@ -326,22 +289,16 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" more would be unusable",
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx).c_str()
|
||||
: (b.kv_ceiling > 0
|
||||
/* SAID AS A SESSION COUNT, because that is the number to compare against
|
||||
* --max-num-seqs, and "28%" makes the reader do the arithmetic.
|
||||
*
|
||||
* AND IT NAMES SESSIONS, NOT RUNNING REQUESTS. "Paged blocks are held only
|
||||
* while a sequence occupies them" stops being true once prefix caching takes a
|
||||
* KV reference on every block it indexes: a finished sequence's blocks stay
|
||||
* held so the next turn can reuse them. So the demand of a multi-turn workload
|
||||
* is the number of LIVE SESSIONS, and counting running requests instead
|
||||
* under-counts by exactly the thing that makes agent turns cheap. When the pool
|
||||
* cannot hold them all, the cache evicts prefixes the next turn wants and that
|
||||
* turn re-prefills its whole context (radiance:prefix_cache_evictions_total). */
|
||||
/* Given as a session count, comparable with --max-num-seqs. Sessions, not
|
||||
* running requests: prefix caching holds a finished sequence's blocks for the
|
||||
* next turn, so multi-turn demand is live sessions. When they do not fit, the
|
||||
* cache evicts prefixes and the next turn re-prefills its whole context
|
||||
* (radiance:prefix_cache_evictions_total). */
|
||||
? fmt(" -- %.0f%% backing of the %lld x %lld worst case: %.1f full-length\n"
|
||||
" sessions. With prefix caching a "
|
||||
"finished sequence's blocks stay held\n"
|
||||
" for reuse, so the demand is LIVE "
|
||||
"SESSIONS and not running requests",
|
||||
" for reuse, so the demand is live "
|
||||
"sessions, not running requests",
|
||||
100.0 * paged_share(b),
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
|
||||
(double)cfg.max_seqs * paged_share(b)).c_str()
|
||||
@@ -381,9 +338,8 @@ RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_m
|
||||
s.kv_mib = common_kv_mib;
|
||||
if (need_kv_mib < 0 || need_kv_mib >= common_kv_mib) return s;
|
||||
const int64_t saved = common_kv_mib - need_kv_mib;
|
||||
/* NEVER LESS THAN THE COMMON WEIGHTS POOL, and never more than every weight resident: a weights
|
||||
* pool is one whole allocation, so MiB past what this rank could ever place are left unclaimed
|
||||
* rather than allocated empty. */
|
||||
/* At least the common weights pool and at most every weight resident: the weights pool is one
|
||||
* allocation, so MiB this rank could never place stay unclaimed rather than allocated empty. */
|
||||
const int64_t cap = std::max(common_weights_mib, to_mib_up(weights_cap_bytes));
|
||||
const int64_t grown = std::min(common_weights_mib + saved, cap);
|
||||
s.kv_mib = need_kv_mib;
|
||||
|
||||
+67
-96
@@ -1,62 +1,45 @@
|
||||
/* vram_budget.h -- how many bytes each VRAM pool gets, decided once and printed in full.
|
||||
*
|
||||
* ============================== WHY THIS IS NOT THE §6 VIOLATION IT LOOKS LIKE ==============================
|
||||
* Spec §6 forbids deriving budgets by inference, such as from the free VRAM at startup, which
|
||||
* moves whenever another process touches the card. This is arithmetic on known, printed, stable
|
||||
* terms instead:
|
||||
*
|
||||
* Spec §6 says the engine does not derive its budgets, and core/mem/pools.cpp still refuses to
|
||||
* re-optimise the split it is handed. The reason given there is exact and worth repeating:
|
||||
* a budget derived from the FREE VRAM at startup is a benchmark that moves when somebody opens a
|
||||
* window on the machine's desktop.
|
||||
* capacity totalGlobalMem, fixed for the part.
|
||||
* already held capacity - free VRAM, measured once after every kernel plugin has
|
||||
* initialised and its code objects are resident: the driver context and
|
||||
* loaded code. The only observed term, printed on its own line so a
|
||||
* desktop on the card shows up there instead of shrinking a pool.
|
||||
* --gpu-headroom-mib what the operator leaves alone (default 96 MiB).
|
||||
* arena activation arena plus scratch, from arena_plan_bytes() on the buffer
|
||||
* plan, the same call that later allocates it.
|
||||
*
|
||||
* What that argument forbids is inference. It does not forbid arithmetic on numbers that are all
|
||||
* known, all printed, and all stable:
|
||||
* What is left is claimable, spent in two steps:
|
||||
*
|
||||
* capacity totalGlobalMem. A fixed property of the part.
|
||||
* already held capacity - the free VRAM this process can see, MEASURED once, after every
|
||||
* kernel plugin has initialised and its code objects are resident. This is the
|
||||
* driver's context and the loaded code, and it is the one term that is observed
|
||||
* rather than computed -- so it is printed on its own line, and a machine with a
|
||||
* desktop on the card shows up in it instead of silently eating a pool.
|
||||
* --gpu-headroom-mib what the operator wants left alone. Stated, defaulted to 96 MiB.
|
||||
* arena the activation arena and the scratch beside it, computed from the buffer plan
|
||||
* by arena_plan_bytes() -- the same call that later allocates it.
|
||||
* 1. Static weights come off the top. Every non-expert weight (attention projections, norms,
|
||||
* embedding, head) must be resident; the one exception is a token embedding that
|
||||
* --embedding-placement puts in the pinned host pool, which weight_footprint then excludes.
|
||||
* Under tensor parallelism each rank's share is already divided (declare runs per rank,
|
||||
* spec §9). They are a floor, not a share, so the cache can never push attention weights to
|
||||
* host memory. If they do not fit, startup refuses with the shortfall named.
|
||||
*
|
||||
* What is left over is claimable, and it is spent in TWO STEPS, not one.
|
||||
* 2. The rest is divided between the expert plane and the KV cache. When the cache lends idle
|
||||
* blocks to the expert slab, the experts get what the pinned host pool cannot hold and the
|
||||
* cache gets the rest up to its ceiling, lending back every block no live request holds.
|
||||
* Without a lender an unused block would sit empty, so experts come first and the cache keeps
|
||||
* one --max-model-len sequence. The cache never gets less than that sequence.
|
||||
*
|
||||
* THE STATIC WEIGHTS COME OFF THE TOP. Everything that is not an expert -- the attention
|
||||
* projections, the norms, the embedding, the head -- has to be resident for the model to run at a
|
||||
* sensible speed at all (the one exception is a token embedding --embedding-placement puts in the
|
||||
* 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: 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.
|
||||
* Both sides are capped at what they can use (the cache at max_seqs x max_ctx tokens,
|
||||
* KVManager::ceiling; the experts at the whole plane) and one side's excess goes to the other.
|
||||
*
|
||||
* 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.
|
||||
* No flag states a pool size: unbudgeted VRAM is unusable, and on a model whose experts do not
|
||||
* fit every unbudgeted GiB costs decode time. Operators move the inputs instead: --gpu-headroom-mib,
|
||||
* --max-model-len and --max-num-seqs (cache bound), --host-pool-mib (which experts must stay on
|
||||
* the card).
|
||||
*
|
||||
* 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), and an expert plane that fits entirely in VRAM has no use for more; when
|
||||
* both fit, both are whole.
|
||||
*
|
||||
* THERE IS NO FLAG THAT STATES A POOL. The split is a full card rather than a guess: VRAM left
|
||||
* unbudgeted is VRAM no pool can use, and on a model whose experts do not fit, every unbudgeted
|
||||
* GiB costs measurable decode time. What an operator moves is the inputs -- --gpu-headroom-mib
|
||||
* takes card space away, --max-model-len and --max-num-seqs bound the cache, --host-pool-mib
|
||||
* decides which experts must stay on the card -- and the arithmetic follows from them.
|
||||
*
|
||||
* A HOST BACKEND HAS NO CARD, and half the machine's memory stands in for one (host_vram_bytes),
|
||||
* split as a card's is. Its weights pool is host memory and holds what a host kernel cannot read
|
||||
* where the container stores it (mapped_unit in core/place/planner.h). A device that reports no
|
||||
* capacity at all is sized at what each pool needs: the weights the planner copies, and the cache
|
||||
* at its ceiling.
|
||||
* The host backend uses half the machine's memory as its capacity (host_vram_bytes) and splits it
|
||||
* like a card; its weights pool holds what a host kernel cannot read where the container stores it
|
||||
* (mapped_unit in core/place/planner.h). A device reporting no capacity gets what each pool needs:
|
||||
* the weights the planner copies, and the cache at its ceiling.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
@@ -66,50 +49,44 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* One rank's card and program, as the resolver needs to see them. Every field is either read from
|
||||
* the device or computed from the declared program; none of it is a policy. */
|
||||
/* One rank's card and program. Every field is read from the device or computed from the declared
|
||||
* program; none is policy. */
|
||||
struct VramFacts {
|
||||
int64_t capacity = 0; /* RadDeviceProps::vram_bytes -- totalGlobalMem */
|
||||
int64_t free = 0; /* RadDeviceProps::vram_free, measured now */
|
||||
int64_t arena = 0; /* arena_plan_bytes() for this rank's program, total incl. scratch */
|
||||
int64_t staging = 0; /* BatchBuilder::device_bytes(): the step slab and the media staging,
|
||||
* and TierExec::device_bytes() when a KV tier is configured */
|
||||
/* THE HARDWARE QUEUES this rank creates after `free` was read -- its compute stream, the expert
|
||||
* mover's, and the second compute lane where the program declares one -- at `queue_bytes`
|
||||
* each. MEASURED, by making one: a queue's kernel-argument ring is the engine's, and the
|
||||
* driver backs every queue with VRAM of its own beside it (33 MiB a queue on an R9700, eight
|
||||
* times the ring). */
|
||||
/* Hardware queues this rank creates after `free` was read (compute stream, expert mover, and
|
||||
* the second compute lane if declared), at `queue_bytes` each. Measured by creating one: the
|
||||
* driver backs every queue with its own VRAM beside the engine's kernel-argument ring (33 MiB
|
||||
* per queue on an R9700, 8x the ring). */
|
||||
int n_queues = 0;
|
||||
int64_t queue_bytes = 0;
|
||||
/* THE NEXT-LAYER EXPERT PREFETCH's ring of expert units and its buffers (xprefetch.h), where it
|
||||
* will be on; its stream is one of `n_queues`. */
|
||||
/* The next-layer expert prefetch's ring and buffers (xprefetch.h), when enabled; its stream is
|
||||
* one of `n_queues`. */
|
||||
int64_t prefetch = 0;
|
||||
int64_t kv_ceiling = 0; /* KVManager::ceiling(max_ctx) for this rank's declared groups */
|
||||
int64_t kv_fixed = 0; /* KVManager::fixed_bytes(): the part of the ceiling that is state */
|
||||
/* 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. */
|
||||
/* weight_footprint() for this rank; under tensor parallelism already this card's share. */
|
||||
int64_t statics = 0; /* non-expert weights -- the floor, not a share of anything */
|
||||
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). */
|
||||
/* Experts the pinned host pool cannot hold, plus the slab's spare slots: the expert slab's
|
||||
* floor 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. */
|
||||
int64_t kv_one = 0; /* the cache for one --max-model-len sequence: the least it may get */
|
||||
/* The cache lends idle blocks to the expert slab: a placement that moves units (expert_tiered
|
||||
* or auto), not --deterministic, on a device with virtual memory management. A lending cache
|
||||
* can be sized for what live requests could need; a non-lending one 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. */
|
||||
/* Integrated graphics: host memory the card must leave to the host, since device memory is
|
||||
* host memory there. 0 on a discrete card. */
|
||||
int64_t host_reserve = 0;
|
||||
};
|
||||
|
||||
/* The resolved split, in bytes, beside every term it came from. Always filled, including for a
|
||||
* device that reports no capacity -- the placement report and the pool report both want the
|
||||
* totals. */
|
||||
/* The resolved split in bytes, with every term it came from. Always filled, including for a
|
||||
* device that reports no capacity, because the placement and pool reports 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 */
|
||||
@@ -126,36 +103,30 @@ struct VramBudget {
|
||||
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 */
|
||||
int64_t unusable = 0; /* elastic neither side could take -- both were full */
|
||||
/* THE PREFILL STAGING REGION: two buffers, each one layer's share of the experts the budget
|
||||
* leaves off the card, taken out of the expert share and appended to the top of the activation
|
||||
* arena (core/place/stager.h). Zero when every expert is resident or the placement cannot move
|
||||
* any. */
|
||||
/* Prefill staging region: two buffers, each one layer's share of the experts left off the
|
||||
* card, appended to the top of the activation arena (core/place/stager.h). Zero when every
|
||||
* expert is resident or the placement cannot move any. */
|
||||
int64_t stage = 0;
|
||||
int64_t weights = 0; /* statics + experts: what vram_weights is set to */
|
||||
std::string report; /* the block the engine prints at startup */
|
||||
};
|
||||
|
||||
/* Writes the answer into cfg.vram_weights_mib / cfg.vram_kv_mib -- ONE resolved number that every
|
||||
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree
|
||||
* (an uneven world's cheaper rank takes its own copy of it: vram_budget_rank_split below).
|
||||
* Takes the SMALLEST capacity and free across ranks and the LARGEST arena, because a split has to
|
||||
* fit on every card it is applied to.
|
||||
*
|
||||
* Refuses, by name and by how much, when the fixed terms alone exceed the card. */
|
||||
/* Writes cfg.vram_weights_mib / cfg.vram_kv_mib, the one number every downstream consumer reads
|
||||
* (an uneven world's cheaper rank re-splits it with vram_budget_rank_split). Takes the smallest
|
||||
* capacity and free VRAM across ranks and the largest arena, so the split fits every card.
|
||||
* Refuses, by name and size, when the fixed terms alone exceed the card. */
|
||||
int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
|
||||
|
||||
/* The same split worked out on a copy of `cfg`, written nowhere and printed nowhere: for a caller
|
||||
* deciding between two programs before it resolves the one it keeps (Engine::plan's table
|
||||
* placement). */
|
||||
/* The same split on a copy of `cfg`, without writing or logging anything: for choosing between
|
||||
* two programs before resolving one (Engine::plan's table placement). */
|
||||
int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
|
||||
|
||||
/* AN UNEVEN WORLD'S CHEAPER RANK. The resolver above derives one split, the dearest rank's, and one
|
||||
* block table serves every rank -- so a rank whose cache costs less per token (an attention-zero
|
||||
* rank keeps no attention cache) would reserve the common KV pool for tokens configure_kv then caps
|
||||
* away. Given the common split, the MiB that rank's pool needs to page the SAME tokens, and what
|
||||
* every one of its weights would take resident (statics + all experts + their spare slots), this
|
||||
* moves the difference to its weights pool, no further than that cap; what the cap leaves stays
|
||||
* unclaimed. Nothing changes when the need is not below the common pool. */
|
||||
/* Re-split for an uneven world's cheaper rank. The resolver derives the most expensive rank's
|
||||
* split, and one block table serves every rank, so a rank whose cache costs less per token (e.g.
|
||||
* one with no attention cache) would over-reserve KV. Given the common split, the MiB this rank
|
||||
* needs to page the same tokens, and the bytes of all its weights resident (statics + all experts
|
||||
* + spare slots), moves the difference to the weights pool up to that cap; the remainder stays
|
||||
* unclaimed. No change when the need is not below the common pool. */
|
||||
struct RankSplit {
|
||||
int64_t weights_mib = 0;
|
||||
int64_t kv_mib = 0;
|
||||
|
||||
Reference in new issue
Block a user