Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
+1529
File diff suppressed because it is too large.
Load diff
+623
@@ -0,0 +1,623 @@
|
||||
/* 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.
|
||||
*
|
||||
* Hybrid models are the normal case, not an extension. Four state kinds:
|
||||
*
|
||||
* 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
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/pools.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
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) */
|
||||
int64_t stock_groups = 0;
|
||||
int64_t stock_slots = 0; /* allocated layer-slots, padding included */
|
||||
int64_t patched_group_size = 0; /* the least-waste group size for the same rule */
|
||||
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 */
|
||||
std::string report() const;
|
||||
};
|
||||
BundleComparison compare_bundling(const std::vector<int64_t>& bundles);
|
||||
|
||||
/* ------------------------------------------------------------------ per-group plan */
|
||||
struct KVGroupPlan {
|
||||
int32_t index = -1; /* position in Program::kv_groups */
|
||||
std::string name;
|
||||
int kind = RAD_KV_FULL;
|
||||
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_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 */
|
||||
|
||||
int64_t n_blocks = 0; /* paged groups: blocks carved from the pool */
|
||||
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. */
|
||||
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;
|
||||
int64_t pool_bytes = 0;
|
||||
void* base = nullptr;
|
||||
|
||||
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.
|
||||
*
|
||||
* So 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. */
|
||||
int64_t layer_bytes_per_block() const {
|
||||
return n_layers > 0 ? bytes_per_block / n_layers : bytes_per_block;
|
||||
}
|
||||
int64_t layer_bytes_per_state() const {
|
||||
return n_layers > 0 ? bytes_per_state / n_layers : bytes_per_state;
|
||||
}
|
||||
int64_t layer_stride() const {
|
||||
return paged() ? n_blocks * layer_bytes_per_block() : n_states * layer_bytes_per_state();
|
||||
}
|
||||
};
|
||||
|
||||
/* 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). */
|
||||
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).
|
||||
*
|
||||
* 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. */
|
||||
struct StateClear {
|
||||
int32_t group = -1;
|
||||
int32_t slot = -1;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
*
|
||||
* Both budgets come from the operator and neither is derived here: the byte budget is whatever
|
||||
* `kv_pool` still has (which is --vram-kv-mib), and the linear-snapshot count is
|
||||
* Config::checkpoint_slots (--checkpoint-slots). A checkpoint is ~96 MiB on a Qwen3-Next and
|
||||
* 64 of them is 6 GiB, so how many to retain is a budget decision and therefore not this
|
||||
* component's to make (spec §6, §7.3). */
|
||||
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 a derived --vram-kv-mib has to be decided from these two
|
||||
* and nothing else (core/mem/vram_budget.cpp). 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;
|
||||
int carve(Pool& kv_pool);
|
||||
|
||||
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. */
|
||||
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. */
|
||||
int ensure(uint64_t seq, int64_t n_tokens);
|
||||
|
||||
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
|
||||
* block size: a partial block is never shared, because the next token written into it would
|
||||
* 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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
int64_t cache_only_blocks(int32_t group) const;
|
||||
|
||||
const std::vector<int32_t>& block_table(uint64_t seq, int32_t group) const;
|
||||
int32_t state_slot(uint64_t seq, int32_t group) const;
|
||||
int state_index_row(uint64_t seq, int32_t group, int32_t* out, int max) const;
|
||||
int64_t state_index_width(int32_t group) const;
|
||||
|
||||
/* Slots handed to a sequence since the last drain, oldest first. The engine zeroes each on the
|
||||
* compute stream before the step that first reads it and then calls clear_state_clears(). */
|
||||
const std::vector<StateClear>& state_clears() const { return clears_; }
|
||||
void clear_state_clears() { clears_.clear(); }
|
||||
int64_t seq_tokens(uint64_t seq) const;
|
||||
|
||||
/* ---------------- 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. */
|
||||
int64_t held_blocks(int32_t g) const;
|
||||
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
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). */
|
||||
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 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.
|
||||
*
|
||||
* A BLOCK IS NOT LENT WHILE ANYTHING HOLDS IT, and a held block is a block a sequence owns OR
|
||||
* one the prefix cache still indexes. So a loan cannot evict anything: it is a claim on what
|
||||
* is free. Everything that makes a block free -- a sequence ending, an eviction, an idle-tier
|
||||
* demotion to host memory or disk -- makes it lendable, and the min-heap free list is what
|
||||
* keeps the free blocks at the top, where a loan can reach them.
|
||||
*
|
||||
* THE BUFFER IS DERIVED AND NOT STATED. It is the free blocks the cache keeps in hand so that
|
||||
* 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. */
|
||||
int64_t buffer_bytes() const;
|
||||
|
||||
/* Is this group lent from? The FULL paged groups, and only those. */
|
||||
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. */
|
||||
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. */
|
||||
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). */
|
||||
void set_reclaim(std::function<int(int64_t tokens)> f) { reclaim_ = std::move(f); }
|
||||
|
||||
/* WHETHER A DECOMMIT ACTUALLY GIVES THE CARD BACK, for the checkpoint region, which is the one
|
||||
* part of the pool still backed on demand. Measured once at bringup rather than assumed,
|
||||
* because it is a property of the driver: where it is false a freed checkpoint slot keeps its
|
||||
* pages, since unmapping them would cost driver calls and return nothing. */
|
||||
void set_release_frees_card(bool yes) { release_frees_card_ = yes; }
|
||||
|
||||
/* MATCH A LEADER'S LOAN, FOR A RANK THAT DOES NOT KNOW WHAT IT IS HOLDING.
|
||||
*
|
||||
* Block ids are SHARED ACROSS RANKS -- RadBatch carries one block table and every rank indexes
|
||||
* 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. */
|
||||
int follow(const KVManager& leader);
|
||||
|
||||
/* HOW MANY OF A GROUP'S BLOCKS THE CACHE MAY HAND OUT: the carve less what is lent. */
|
||||
int64_t live_blocks(int32_t group) const;
|
||||
int64_t committed_bytes() const;
|
||||
|
||||
/* HOW MUCH OF THE CHECKPOINT REGION MUST STAY AVAILABLE, in bytes, counting only what is not
|
||||
* committed already. The number is the HIGH WATER MARK PLUS ONE rather than the whole cap:
|
||||
* the cap is what the operator allows and the high water is what this workload takes, and
|
||||
* holding one slot past it means the allocation that would advance it always has room. */
|
||||
int64_t ck_reserve_bytes() const;
|
||||
|
||||
/* BACK THIS RANK'S COPY OF A SLOT, AND SAY SO IF THE CARD WILL NOT.
|
||||
*
|
||||
* A slot's LIFETIME is decided once: rank 0's PrefixCache owns the free list and every other
|
||||
* rank takes the id it is handed. Its BACKING is per rank, because every rank writes its own
|
||||
* shard of the snapshot into the same offset of its OWN pool. alloc_checkpoint backs the slot
|
||||
* on every rank before it hands the id out (set_checkpoint_peers), so on the paths that use a
|
||||
* slot this is a check that finds it backed. Called before EVERY access rather than once:
|
||||
* idempotence is what makes that safe, and a commit of a range already committed is a no-op.
|
||||
*
|
||||
* RAD_E_FULL when the commit would take the card under its floor (set_checkpoint_floor). */
|
||||
int back_checkpoint(int32_t slot);
|
||||
|
||||
/* THE CARD'S FLOOR FOR A CHECKPOINT SLOT'S PAGES: the card is read before a slot is backed,
|
||||
* and a slot that would leave it under `keep_free` bytes is refused as a full pool.
|
||||
*
|
||||
* The budget counts the whole checkpoint region as the cache's, but the region is backed as
|
||||
* slots are taken, and until then its bytes read as free. The allocations nobody sizes in
|
||||
* advance -- a kernel's code object and a spilling kernel's scratch, both made on the
|
||||
* kernel's first launch -- are made out of that same free memory. A slot that took the last
|
||||
* of it would leave the next first launch nothing, which is a fault inside the HIP runtime
|
||||
* and not an error. A refused slot is a snapshot fewer on the card, which the retention
|
||||
* policy answers and the host tier covers.
|
||||
*
|
||||
* `free_bytes` reads the card's free memory into its argument: the engine reads the device, a
|
||||
* test reads a simulated card, and no floor is set on a backend with no card. */
|
||||
using FreeBytes = std::function<int(int64_t*)>;
|
||||
void set_checkpoint_floor(FreeBytes free_bytes, int64_t keep_free) {
|
||||
ck_free_bytes_ = std::move(free_bytes);
|
||||
ck_keep_free_ = keep_free;
|
||||
}
|
||||
|
||||
/* THE OTHER RANKS' MANAGERS, given to the one whose free list hands the ids out. Every rank
|
||||
* writes its shard of a snapshot into the same slot of its own pool, so a slot is backed on
|
||||
* every card or handed out on none: a card that cannot back it is a full pool at allocation,
|
||||
* which the prefix cache answers by retiring a snapshot, rather than a failed copy after the
|
||||
* step that produced the state, which stops the engine. */
|
||||
void set_checkpoint_peers(std::vector<KVManager*> peers) { ck_peers_ = std::move(peers); }
|
||||
|
||||
/* BACK EVERY FREE SLOT NOW, ON EVERY RANK, and withdraw the ones the cards have no room for.
|
||||
* For a driver that never takes a mapping's pages back (set_release_frees_card(false)): a
|
||||
* slot backed later costs exactly what it costs now, and backing it now puts the region's
|
||||
* cost on the card before serving starts, where the startup reading shows it. A withdrawn
|
||||
* slot is never handed out. `withdrawn` counts them; RAD_E_FULL is not returned. */
|
||||
int back_free_checkpoints(int64_t* withdrawn);
|
||||
|
||||
int64_t checkpoint_stride() const { return ck_stride_; }
|
||||
|
||||
/* ---------------- preemption by recompute (spec §7.1, §17) ---------------- */
|
||||
/* Free the sequence's blocks and take it back to zero tokens. Its state slots are freed too: a
|
||||
* recurrent state that is not snapshotted cannot be resumed, so a preempted sequence replays
|
||||
* 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. */
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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) ---------------- */
|
||||
int64_t checkpoint_bytes() const { return checkpoint_bytes_; }
|
||||
int64_t checkpoint_slots() const { return (int64_t)ck_slot_base_.size(); }
|
||||
int64_t free_checkpoint_slots() const { return (int64_t)ck_free_.size(); }
|
||||
int alloc_checkpoint(int32_t* slot_out);
|
||||
void free_checkpoint(int32_t slot);
|
||||
void* checkpoint_ptr(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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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. RAD_E_INVAL on a bad slot or an unknown sequence. */
|
||||
int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s);
|
||||
int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s);
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
int carve_into(Pool& kv_pool);
|
||||
void forget();
|
||||
|
||||
/* One traversal serving both checkpoint directions; see checkpoint_save. */
|
||||
int checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save,
|
||||
RadStream s);
|
||||
|
||||
struct Seq {
|
||||
uint64_t id = 0;
|
||||
int64_t n_tokens = 0;
|
||||
std::vector<std::vector<int32_t>> blocks; /* per group */
|
||||
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. */
|
||||
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. */
|
||||
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);
|
||||
Seq* find(uint64_t seq);
|
||||
const Seq* find(uint64_t seq) const;
|
||||
|
||||
std::vector<KVGroupPlan> plans_;
|
||||
std::vector<std::vector<int32_t>> free_blocks_; /* per group */
|
||||
std::vector<std::vector<int32_t>> refcount_; /* per group, per block */
|
||||
/* Per group, per block: the prefix cache holds one of the references. A free block is never
|
||||
* marked. `cache_only_` is, per group, how many marked blocks are at a count of one. */
|
||||
std::vector<std::vector<uint8_t>> cached_;
|
||||
std::vector<int64_t> cache_only_;
|
||||
std::vector<std::vector<int32_t>> free_states_; /* per group */
|
||||
std::unordered_map<uint64_t, Seq> seqs_;
|
||||
std::vector<BlockCopy> pending_;
|
||||
|
||||
std::vector<int64_t> ck_slot_base_; /* pool offsets of the checkpoint slots */
|
||||
std::vector<int32_t> ck_free_;
|
||||
int64_t checkpoint_bytes_ = 0;
|
||||
std::vector<StateClear> clears_; /* grabbed slots the engine must zero */
|
||||
void* pool_base_ = nullptr;
|
||||
BundleComparison bundling_;
|
||||
std::string report_;
|
||||
int64_t max_seqs_ = 0;
|
||||
int64_t max_ctx_ = 0;
|
||||
int64_t max_tok_ = 0; /* --max-num-batched-tokens; the buffer floor is one of these */
|
||||
/* plan_groups() computes these; carve() spends against them and ceiling() reports on them. */
|
||||
int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, checkpoints, padding */
|
||||
int64_t ck_total_ = 0; /* the checkpoint part of fixed_, named for the refusal message */
|
||||
int64_t ckpts_ = 0; /* --checkpoint-slots, as plan_groups() resolved it */
|
||||
/* THE SLOT STRIDE AND WHERE THE SLOTS BEGIN. The stride is checkpoint_bytes_ rounded up to a
|
||||
* whole number of commit granules, so a slot can be backed and released without touching a
|
||||
* neighbour; the offset is where the eager startup commit stops, because everything from
|
||||
* there up is backed as it is handed out. Zero on a model with no linear state. */
|
||||
bool release_frees_card_ = true;
|
||||
bool ck_elastic_ = false;
|
||||
int64_t ck_high_water_ = 0;
|
||||
int64_t ck_backed_ = 0;
|
||||
int64_t ck_stride_ = 0;
|
||||
int64_t ck_region_off_ = 0;
|
||||
FreeBytes ck_free_bytes_; /* set_checkpoint_floor */
|
||||
int64_t ck_keep_free_ = 0;
|
||||
std::vector<KVManager*> ck_peers_;
|
||||
/* RAD_OK when this rank has the slot backed or room above the floor to back it. */
|
||||
int ck_room(int32_t slot) const;
|
||||
bool ck_backed(int32_t slot) const;
|
||||
/* The commit itself, with no floor: callers have asked ck_room on every rank first. */
|
||||
int ck_commit(int32_t slot);
|
||||
/* ck_room on every rank, then ck_commit on every rank. */
|
||||
int ck_back_everywhere(int32_t slot);
|
||||
/* What a checkpoint slot is aligned and sized to. RAD_ALIGN_UNIT on a device with no virtual
|
||||
* memory management, where nothing is released and the stride is only padding. */
|
||||
int64_t ck_align() const;
|
||||
|
||||
/* ---- the loan. See the public block for what this is and why a block that anything holds
|
||||
* is never lent. ----
|
||||
*
|
||||
* `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.
|
||||
*
|
||||
* `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.
|
||||
*
|
||||
* 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. */
|
||||
std::vector<int64_t> chunk_blocks_;
|
||||
std::vector<int64_t> short_peak_;
|
||||
Pool* pool_ = nullptr;
|
||||
int64_t loan_ = 0; /* tokens lent from the top of every lendable group */
|
||||
uint64_t seq_frees_ = 0;
|
||||
std::function<int(int64_t)> reclaim_;
|
||||
std::vector<int64_t> live_; /* per group: blocks the cache may hand out */
|
||||
std::vector<int64_t> free_usable_; /* per group: free ids below live_ */
|
||||
std::vector<int64_t> bucket_blocks_; /* per group: blocks one held_hist_ bucket covers */
|
||||
std::vector<std::vector<int32_t>> held_hist_; /* per group, per bucket: held blocks */
|
||||
|
||||
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. */
|
||||
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;
|
||||
int grow_for(int32_t g, int64_t blocks);
|
||||
void note_held(int32_t g, int32_t b, int delta);
|
||||
bool configured_ = false;
|
||||
static const std::vector<int32_t> kNoBlocks;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+1389
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,691 @@
|
||||
/* kvtier.h -- where a finished conversation's KV is kept once VRAM has a better use for it
|
||||
* (spec §7.3).
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* ============================== 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.
|
||||
*
|
||||
* published --(copy, at once)--> clean on device --(memory wanted)--> host
|
||||
* ^ |
|
||||
* +------------(a hit restores)------+
|
||||
* host copy --(copy to disk, at once)--> clean on host --(a slot wanted)--> disk
|
||||
*
|
||||
* THE DISK TIER IS A COPY TOO, by the same argument one level down. Every host copy is written to
|
||||
* the disk store in the background as soon as it lands, and keeps its host slot. Once the write
|
||||
* has landed the host slot is as free to give up as a clean entry's VRAM: when a copy or a
|
||||
* restore needs a slot and the arena is full, the oldest entries the disk also holds give theirs
|
||||
* up, which is bookkeeping and nothing else. Moving an entry to disk only when its slot is wanted
|
||||
* would put a write on the path of whatever wanted it -- a restore out of disk needs a host slot to
|
||||
* read through, and an arena full of host-only entries has no slot to give it at all.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* ============================== 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. A disk write is not
|
||||
* such a transfer -- it reads host memory and nothing else -- and holds only the slots it reads.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/kv.h"
|
||||
#include "mem/prefix.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <functional>
|
||||
#include <list>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
class SSDTier;
|
||||
|
||||
enum class KVTier : uint8_t { Device = 0, Host = 1, Disk = 2 };
|
||||
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. */
|
||||
struct TierJob {
|
||||
enum class Kind : uint8_t {
|
||||
WriteBack, /* gather_rows out of the pool into a host slot; the entry stays in VRAM */
|
||||
ToDisk, /* a host slot written to the disk store; the host copy is kept */
|
||||
ToDevice, /* allocate blocks, scatter_rows in; the host copy is kept */
|
||||
DropHost, /* no disk tier and the arena is full: this record's bytes go */
|
||||
ToHost, /* the disk store read into a host slot, ahead of the restore that wants it */
|
||||
};
|
||||
Kind kind = Kind::WriteBack;
|
||||
BlockHash key;
|
||||
/* Per cached group, in PrefixCache::cached_groups() order. For a write-back these are the
|
||||
* blocks to read -- EMPTY when only the snapshot is being copied, because the blocks already
|
||||
* have their host copy; for a promotion they are filled in by the engine with the blocks it
|
||||
* allocated. */
|
||||
std::vector<int32_t> blocks;
|
||||
int32_t host_slot = -1;
|
||||
int64_t bytes = 0;
|
||||
|
||||
/* ---- the linear half, on a hybrid model ----
|
||||
*
|
||||
* A session's recurrent state lives in a CHECKPOINT SLOT rather than in blocks: one contiguous
|
||||
* KVManager::checkpoint_bytes() extent, which is why nothing here needs a gather. The snapshot
|
||||
* belonging to this entry moves with it, so a restored hybrid session gets its attention hit
|
||||
* AND its state back, instead of an attention hit and a full linear replay from token zero.
|
||||
*
|
||||
* `ck_dev` is the device slot: where the bytes are read from on the way out, and where the
|
||||
* engine put them on the way in -- it is an OUTPUT of a promotion, exactly as `blocks` is. */
|
||||
int32_t ck_dev = -1;
|
||||
int32_t ck_host = -1; /* a slot in the snapshot arena, not the block arena */
|
||||
int64_t ck_pos = 0; /* the token position, which the disk store verifies on the way back */
|
||||
bool ck_want = false; /* a promotion should bring the snapshot back too */
|
||||
/* DID THE SNAPSHOT HALF SUCCEED. Separate from the job's own result because the two halves
|
||||
* fail for different reasons and are repaired differently: a snapshot that could not be copied
|
||||
* has not been damaged, it is still sitting correct and committed in its device slot and a
|
||||
* later pass reaches it again for free, so the blocks may as well carry on without it.
|
||||
*
|
||||
* A snapshot that is DROPPED is another matter, and it is worth being exact about the cost
|
||||
* because it is not what it looks like. On this build the scheduler clamps a hybrid session's
|
||||
* reuse to the last LINEAR CHECKPOINT it can reach, not to the attention hit -- RadBatch
|
||||
* carries one query length for every KV group, so the linear layers cannot be replayed over a
|
||||
* longer range than the attention ones (core/sched/scheduler.cpp, admit_one). A session whose
|
||||
* blocks came back and whose state did not therefore reuses NOTHING. The blocks are not a
|
||||
* partial win; they are unusable until some checkpoint under them survives. */
|
||||
int64_t ck_bytes = 0;
|
||||
bool ck_ok = true;
|
||||
/* A PROMOTION THAT WAS NEVER STARTED, as opposed to one that failed part of the way through.
|
||||
* A restore reserves every block before it moves a byte, and a chain that did not fit is cut
|
||||
* where the reservation ran out: the entries past that point were not touched, their host
|
||||
* copies are exactly what they were, and they stay on the host tier. Only an entry whose
|
||||
* scatter may have run is dropped on failure. A read off disk that never ran -- its batch
|
||||
* could not be handed to the thread -- is the same: the record stays on disk. */
|
||||
bool started = false;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the host arena */
|
||||
/* Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the
|
||||
* driver stages an async copy to pageable memory through its own buffer and, on some paths,
|
||||
* synchronises. Slot-allocated at one
|
||||
* fixed size rather than malloc'd per entry: every entry in a given model holds exactly one block
|
||||
* per cached group, so the size is a property of the geometry and a bitmap is the whole allocator.
|
||||
*
|
||||
* RUNS, BECAUSE A TRANSFER IS PER RUN. A 4-token block makes a 200K-token conversation fifty
|
||||
* thousand entries, and a copy per entry is fifty thousand driver calls on the engine thread --
|
||||
* the call rate, not the link, is then what a restore costs. Entries written together are given
|
||||
* consecutive slots wherever the arena has them, so a batch crosses the link as one strided copy
|
||||
* a run. */
|
||||
class HostArena {
|
||||
public:
|
||||
~HostArena();
|
||||
int open(int64_t slot_bytes, int64_t cap_bytes);
|
||||
void close();
|
||||
bool enabled() const { return base_ != nullptr; }
|
||||
|
||||
int64_t slot_bytes() const { return slot_bytes_; }
|
||||
/* Fixed when the arena is opened. Stored rather than counted from the bitmap, because an
|
||||
* HTTP thread reads it for the sessions view while the engine thread allocates and frees. */
|
||||
int64_t capacity() const { return cap_slots_; }
|
||||
int64_t used_slots() const { return used_; }
|
||||
int64_t cap_bytes() const { return slot_bytes_ * capacity(); }
|
||||
int64_t free_slots() const { return cap_slots_ - used_; }
|
||||
|
||||
/* -1 when the arena is full. The caller evicts and retries; this does not choose victims,
|
||||
* because the LRU that would choose them lives in IdleTiers and an allocator that reached
|
||||
* into it would give each record two owners. */
|
||||
bool full() const { return used_ >= cap_slots_; }
|
||||
int32_t alloc();
|
||||
/* UP TO `want` CONSECUTIVE SLOTS, the first free run at or after the cursor. `*got` is how
|
||||
* many; the caller asks again for the rest. -1 when the arena is full. */
|
||||
int32_t alloc_run(int32_t want, int32_t* got);
|
||||
void free(int32_t slot);
|
||||
void* at(int32_t slot) const;
|
||||
|
||||
private:
|
||||
bool is_used(int64_t s) const { return (bits_[(size_t)(s >> 6)] >> (s & 63)) & 1ull; }
|
||||
void* base_ = nullptr;
|
||||
int64_t slot_bytes_ = 0;
|
||||
int64_t used_ = 0;
|
||||
int64_t cap_slots_ = 0;
|
||||
int64_t cursor_ = 0;
|
||||
std::vector<uint64_t> bits_;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the policy */
|
||||
class IdleTiers {
|
||||
public:
|
||||
struct Config {
|
||||
int64_t host_cap_bytes = 0; /* 0 is off */
|
||||
int64_t disk_cap_bytes = 0;
|
||||
int64_t entry_bytes = 0; /* one entry: sum over cached groups of bytes_per_block */
|
||||
/* ---- the linear half ----
|
||||
* `ckpt_bytes` is ONE SNAPSHOT, every rank's shard of it, laid out exactly like
|
||||
* `entry_bytes`. `ckpt_cap_bytes` is carved out of the tier the operator sized rather than
|
||||
* added to it: a snapshot store is host memory like any other and a tier that quietly
|
||||
* allocated past its stated cap would be the one thing --prefix-cache-host-mib is for. Zero
|
||||
* for either means snapshots do not tier, and the blocks still do. */
|
||||
int64_t ckpt_bytes = 0;
|
||||
int64_t ckpt_cap_bytes = 0; /* host; part of host_cap_bytes, not additional to it */
|
||||
int64_t ckpt_disk_slots = 0; /* how many the disk store was opened for */
|
||||
};
|
||||
|
||||
int configure(const Config& c, SSDTier* disk);
|
||||
void close();
|
||||
bool host_on() const { return cfg_.host_cap_bytes > 0 && arena_.enabled(); }
|
||||
bool disk_on() const { return cfg_.disk_cap_bytes > 0 && disk_ != nullptr; }
|
||||
bool any_on() const { return host_on() || disk_on(); }
|
||||
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. */
|
||||
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. */
|
||||
void forget(const BlockHash& key);
|
||||
/* AN OFF-DEVICE ENTRY WAS RECOMPUTED. A request that could not reach the tier 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);
|
||||
|
||||
/* 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. */
|
||||
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. A record whose snapshot is still only on the device is included even when
|
||||
* its blocks already have their copy, with `blocks` empty -- the snapshot is the half a hybrid
|
||||
* session cannot resume without, and it becomes copyable later than the blocks (a checkpoint
|
||||
* is committed on its own clock).
|
||||
*
|
||||
* Every record named by a returned job is `pending` until report() is called for it. An arena
|
||||
* too full to take the batch first gives up the host slots of the oldest entries the disk also
|
||||
* holds (make_room); what is still short stays queued, and with no disk tier the next
|
||||
* maintenance plan drops that many of the oldest host-only entries. */
|
||||
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. */
|
||||
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. */
|
||||
void take_clean(std::vector<BlockHash>* out);
|
||||
/* Can this entry's blocks leave VRAM for nothing, right now: a copy off the card has landed --
|
||||
* in host memory or on disk -- and no job is out on the record. */
|
||||
bool droppable(const BlockHash& key) const;
|
||||
/* The cache released the blocks. The record is now a host record with its copy, on the host
|
||||
* tier's list like any other -- or a disk record, when its host slot was already given up.
|
||||
*
|
||||
* ITS SNAPSHOT STAYS WHERE IT IS. A snapshot's device slot is not memory anything else can
|
||||
* use -- the expert slab borrows blocks, never checkpoint slots -- so taking it off the device
|
||||
* along with the blocks would buy nothing and put the session's recurrent state at the mercy
|
||||
* of a host arena a few snapshots deep, shared by every conversation. The slot goes when the
|
||||
* checkpoint pool itself needs it (snapshot_backed). */
|
||||
void drop_commit(const BlockHash& key);
|
||||
|
||||
/* ---------------- the snapshots' own pressure ----------------
|
||||
*
|
||||
* The checkpoint pool is --checkpoint-slots deep for the whole server, and when it is full the
|
||||
* cache retires the least recently used snapshot to make room. One whose bytes the tiers also
|
||||
* hold need not be lost: the cache DETACHES it instead -- the slot goes back, the index entry
|
||||
* stays, and the next restore of the session brings the state back with the blocks. True when
|
||||
* this key's device snapshot has a finished copy off the card that nothing is still writing. */
|
||||
bool snapshot_backed(const BlockHash& key) const;
|
||||
/* The cache gave the device slot back; the copy off the card is now the snapshot. */
|
||||
void snapshot_detached(const BlockHash& key);
|
||||
|
||||
/* ---------------- the slow half ----------------
|
||||
*
|
||||
* The host copies waiting for their disk copy, in the order they landed, as ToDisk jobs --
|
||||
* blocks and snapshot halves together where both are waiting. A ToDisk job does NOT make its
|
||||
* record pending: it only reads the host slots it names, which a restore may read at the same
|
||||
* time, and a slot the record gives up while the write is out is freed when the write reports
|
||||
* rather than under it. With no disk tier, the copies the arena refused since the last plan
|
||||
* are made room for by dropping that many of the oldest host-only entries. `budget` bounds
|
||||
* one plan so the IO a pass asks for is bounded too. */
|
||||
void plan(int budget, std::vector<TierJob>* out);
|
||||
/* Is a host copy waiting for its disk copy? The slow half is then due now rather than on its
|
||||
* once-a-second clock: an entry the disk does not hold yet is one whose host slot cannot be
|
||||
* given up for nothing. */
|
||||
bool disk_waiting() const;
|
||||
|
||||
/* ROOM IN THE ARENA, FOR NOTHING. Up to `n` host slots of entries the disk also holds, given
|
||||
* up oldest first: host records first -- they become disk records -- and then the host copies
|
||||
* of clean VRAM entries, which stay clean through their disk copy. Nothing is written; an
|
||||
* entry whose disk copy has not landed is not a candidate. Returns how many were freed. */
|
||||
int64_t make_room(int64_t n);
|
||||
|
||||
/* ---------------- reading a chain back off disk, before its request runs ----------------
|
||||
*
|
||||
* A RESTORE COPIES HOST MEMORY TO THE DEVICE AND NOTHING ELSE. It runs inside the scheduler's
|
||||
* step, and a disk read there -- thousands of entries for a long conversation -- would hold
|
||||
* every other request's next token for as long as the reads take. So the disk half of a chain
|
||||
* is read into host slots on the IO thread first, as ToHost jobs, while the request that wants
|
||||
* it waits outside admission and everything else keeps running; the restore then finds the
|
||||
* chain in host memory.
|
||||
*
|
||||
* `chain` is every key a prompt's prefix matched, in order. True when the request must wait:
|
||||
* a read for one of its entries was planned now, into `out`, or is already out. False when
|
||||
* none of the chain is on disk, or none of what is can be given a slot -- a chain larger than
|
||||
* the arena comes back as far as the arena holds, and the rest is prefilled.
|
||||
*
|
||||
* The chain's deepest snapshot that is only on disk is read with it, into the snapshot arena,
|
||||
* because that is the state the hit resumes from (TierExec::issue_restore). Every record named
|
||||
* is `pending` until the read reports, and what a read brought in is not given up to make
|
||||
* room for anybody else until the request has had the step it needs to claim it. */
|
||||
bool plan_fetch(const std::vector<BlockHash>& chain, std::vector<TierJob>* out,
|
||||
uint64_t now_ns);
|
||||
|
||||
/* A promotion, asked for by a lookup that hit off-device. Returns false when the entry is not
|
||||
* in host memory -- a disk entry is read in by plan_fetch first -- or already has work
|
||||
* outstanding. */
|
||||
bool plan_promote(const BlockHash& key, TierJob* out);
|
||||
|
||||
/* The engine finished (or failed) a job. On failure the record returns to the state it was in
|
||||
* with its storage intact, EXCEPT for a failed ToDevice that had started, which cannot leave a
|
||||
* half-scattered pool behind and so drops the entry -- and a disk read that failed is marked
|
||||
* started for that reason too: the store no longer holds what the record says it does. A
|
||||
* successful ToDevice restarts the record's clock at `now_ns` when one is given: the promotion
|
||||
* happened because something is about to use it. */
|
||||
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. */
|
||||
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, or a promotion that
|
||||
* failed -- 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. */
|
||||
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, for the same reason note_used carries the block ids:
|
||||
* a copy has to know what to move and the cache's index is the only place it is written down.
|
||||
* `dev_slot` is a KVManager checkpoint slot and `pos` the token position the disk store
|
||||
* verifies a read against.
|
||||
*
|
||||
* A record may hear this BEFORE it hears note_used -- a checkpoint is committed mid-request
|
||||
* and the chain is published when the request closes -- so this creates the record if it has
|
||||
* to. The snapshot is queued for a copy when the record is published, or at once when it
|
||||
* already was. */
|
||||
void note_snapshot(const BlockHash& key, int32_t dev_slot, int64_t pos);
|
||||
/* The cache is done with the snapshot at `key`: return whatever tier storage holds it. The
|
||||
* record's BLOCKS are untouched -- the two halves are retired by different policies on
|
||||
* different clocks, and a snapshot the retention policy drops says nothing about the prefix.
|
||||
*
|
||||
* TRUE WHEN A COPY IS STILL READING THE DEVICE SLOT, and then the slot is NOT the caller's to
|
||||
* free: an asynchronous copy out of a slot the pool has decommitted reads a page that is no
|
||||
* longer there, which is a device fault rather than a stale byte. The tiers keep the slot and
|
||||
* hand it back through `take_checkpoint_frees` once the copy has reported. */
|
||||
bool release_snapshot(const BlockHash& key);
|
||||
/* Device checkpoint slots whose release waited on a copy, now safe to free. */
|
||||
void take_checkpoint_frees(std::vector<int32_t>* out);
|
||||
/* Is a copy reading this key's device snapshot right now? A save into that slot would tear it. */
|
||||
bool snapshot_reading(const BlockHash& key) const;
|
||||
/* THE TIERS LOST A SNAPSHOT BUT KEPT THE BLOCKS. The snapshot store is far smaller than the
|
||||
* block store (a snapshot is thousands of blocks' worth of bytes) so it overflows first and on
|
||||
* its own, and the cache has to stop offering an index entry whose bytes nobody holds. Wired
|
||||
* to PrefixCache::drop_snapshot; separate from set_drop_sink because losing half an entry and
|
||||
* losing all of it are different events with different repairs. */
|
||||
void set_snapshot_drop_sink(std::function<void(const BlockHash&)> f) { on_ck_drop_ = std::move(f); }
|
||||
bool ckpt_on() const { return ck_arena_.enabled(); }
|
||||
int64_t ckpt_bytes() const { return cfg_.ckpt_bytes; }
|
||||
HostArena& ckpt_arena() { return ck_arena_; }
|
||||
const HostArena& ckpt_arena() const { return ck_arena_; }
|
||||
int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; }
|
||||
|
||||
/* ---------------- 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 model name is carried rather than looked up because the disk tier outlives the process:
|
||||
* a store written by one container and read back under another is refused by fingerprint, and
|
||||
* the name is what turns that refusal into something an operator can act on. */
|
||||
struct SessionInfo {
|
||||
uint64_t id = 0;
|
||||
std::string model;
|
||||
int64_t n_tokens = 0;
|
||||
int64_t bytes = 0;
|
||||
uint64_t first_seen_ns = 0;
|
||||
uint64_t last_used_ns = 0;
|
||||
int64_t on_device = 0, on_host = 0, on_disk = 0; /* blocks, by tier */
|
||||
/* LINEAR STATE, on a hybrid model. Counted separately from blocks because it is a
|
||||
* different resource with a different scarcity: a snapshot is thousands of blocks' worth
|
||||
* of bytes and there are only --checkpoint-slots of them on the device. A session showing
|
||||
* blocks on disk and no snapshot anywhere is one that will come back and re-run every
|
||||
* recurrent layer over its whole transcript, which is not what "restored" should mean. */
|
||||
int64_t snapshots = 0; /* this session holds, any tier */
|
||||
int64_t snap_device = 0, snap_host = 0, snap_disk = 0;
|
||||
int64_t snap_bytes = 0;
|
||||
/* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain, in any
|
||||
* tier. On a hybrid model the scheduler clamps a hit to the last linear checkpoint it can
|
||||
* reach, so this -- not n_tokens and not the blocks -- is the prefix the next turn skips,
|
||||
* and n_tokens minus it is what that turn prefills. Zero with no snapshot anywhere. */
|
||||
int64_t resume_tokens = 0;
|
||||
bool moving = false; /* a job is outstanding */
|
||||
};
|
||||
/* WHAT THE TIERS OFF THE CARD ARE HOLDING, blocks and snapshots together, each counted once.
|
||||
* The per-session figures cannot be summed into this: sessions sharing a prefix share its
|
||||
* blocks and its snapshots. Caps are what the operator configured, snapshots included. A
|
||||
* clean entry's host copy is counted: it occupies the arena whether or not the VRAM copy has
|
||||
* gone yet. */
|
||||
struct Occupancy {
|
||||
int64_t host_bytes = 0, disk_bytes = 0;
|
||||
int64_t host_cap_bytes = 0, disk_cap_bytes = 0;
|
||||
};
|
||||
/* Publish one request's chain. Called from PrefixCache::insert, which is the only place that
|
||||
* knows a chain was completed rather than merely touched.
|
||||
*
|
||||
* KEPT WHETHER OR NOT ANY TIER IS ON, because what it records is not a tiering fact. A server
|
||||
* with no --prefix-cache-host-mib still stores conversations -- it stores them all in VRAM, which
|
||||
* 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. */
|
||||
void note_session(uint64_t id, const std::vector<BlockHash>& chain, int64_t n_tokens,
|
||||
uint64_t now_ns);
|
||||
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. */
|
||||
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. */
|
||||
int64_t to_host = 0, dropped = 0, to_disk = 0, promoted = 0;
|
||||
/* `host_freed` is host slots given up because the disk holds the entry -- the host tier's
|
||||
* counterpart of `dropped`; `host_drops` is entries lost with no disk tier to hold them. */
|
||||
int64_t host_freed = 0, host_drops = 0, failures = 0;
|
||||
int64_t host_bytes = 0, disk_bytes = 0;
|
||||
int64_t host_hits = 0, disk_hits = 0;
|
||||
/* Entries and snapshots read off disk into host memory ahead of a restore. */
|
||||
int64_t fetched = 0, ck_fetched = 0;
|
||||
/* SNAPSHOTS MOVED, counted apart from blocks. A hybrid session can move its whole chain
|
||||
* off the device and still replay every linear layer from zero on the way back, and no
|
||||
* block counter can tell the two apart -- these are the numbers that can. */
|
||||
int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0;
|
||||
};
|
||||
/* A copy, taken under the lock: an HTTP thread reads these while the engine thread moves
|
||||
* records. */
|
||||
Stats stats() const;
|
||||
HostArena& arena() { return arena_; }
|
||||
/* The size of ONE SLOT, which under tensor parallelism holds every rank's shard. */
|
||||
int64_t entry_bytes() const { return cfg_.entry_bytes; }
|
||||
|
||||
private:
|
||||
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. -1 on a disk record always. */
|
||||
int32_t host_slot = -1;
|
||||
/* THE DISK STORE HOLDS THESE BYTES, written from the host copy. What makes the host slot
|
||||
* free to give up, and a device record with no host copy clean. The store evicts on its own
|
||||
* and does not say so; a read that finds the entry gone drops it (report). */
|
||||
bool on_disk = false;
|
||||
/* The host slot a disk write is reading right now, -1 when none. A slot given up while
|
||||
* this names it is freed when the write reports, not under it. */
|
||||
int32_t disk_src = -1;
|
||||
bool disk_q = false; /* in dk_q_: waiting for a disk copy */
|
||||
bool pending = false;
|
||||
bool fetching = false; /* the pending job is a read off disk (plan_fetch) */
|
||||
bool doomed = false; /* forget() arrived while pending */
|
||||
bool queued = false; /* in wb_q_: waiting for a copy */
|
||||
bool clean_q = false; /* in clean_q_: a drop the cache has not been asked about */
|
||||
bool listed = false; /* on host_lru_ or disk_lru_; `it` is valid */
|
||||
std::vector<int32_t> blocks;
|
||||
/* ---- the linear half ----
|
||||
* `ck_dev` is the snapshot's device slot, `ck_host` its host copy and `ck_on_disk` the
|
||||
* disk store's. A clean device snapshot has both of the first two; a snapshot that has
|
||||
* left the device has no `ck_dev`. All clear when the record carries no snapshot, which is
|
||||
* the common case -- one block in every (interval / block_size) is a checkpoint position. */
|
||||
int32_t ck_dev = -1;
|
||||
int32_t ck_host = -1;
|
||||
bool ck_on_disk = false;
|
||||
int64_t ck_pos = 0;
|
||||
/* A COPY IS READING `ck_dev` RIGHT NOW: set when a write-back takes the snapshot, cleared
|
||||
* when it reports. The one moment the device slot is not the cache's to free. */
|
||||
bool ck_reading = false;
|
||||
/* THIS SNAPSHOT WILL NOT BE COPIED AGAIN: its copy was refused for want of room, or taken
|
||||
* back to make room for another. The snapshot store is a few slots deep for the whole
|
||||
* server, and a snapshot still in its device slot re-queued the moment its copy was
|
||||
* evicted would evict the next one's, and so on -- every pass copying a hundred megabytes
|
||||
* a rank to throw another hundred away. Cleared when a new commit replaces the state. */
|
||||
bool ck_skip = false;
|
||||
/* A device slot the cache let go of while a copy was reading it. See release_snapshot. */
|
||||
int32_t ck_free_after = -1;
|
||||
/* The snapshot host slot a disk write is reading, as `disk_src` is for the blocks. */
|
||||
int32_t ck_disk_src = -1;
|
||||
/* WHEN A READ OFF DISK BROUGHT THIS RECORD IN, 0 when none did or its restore has run.
|
||||
* Until the request that asked for it has been admitted the slots are its and not the
|
||||
* arena's to give up: two conversations waiting on reads into a full arena would
|
||||
* otherwise each evict what the other had read, and neither would ever be restored. Held
|
||||
* for kFetchHoldNs at most, which bounds what a request that went away can pin. */
|
||||
uint64_t fetched_ns = 0;
|
||||
/* Set only while plan_fetch makes room: this record is part of the chain being read, and
|
||||
* giving its slot up to read another part of the same chain would be no progress. */
|
||||
bool keep = false;
|
||||
std::list<BlockHash>::iterator it;
|
||||
};
|
||||
|
||||
/* Does this record want a copy it does not have yet? The blocks when they are in VRAM with no
|
||||
* copy off the card; the snapshot when it is in a device slot with no copy off the card and
|
||||
* the snapshot store exists at all. */
|
||||
bool wants_copy(const Rec& r) const;
|
||||
/* The snapshot half of that on its own. */
|
||||
bool wants_ck_copy(const Rec& r) const;
|
||||
/* And a disk copy: a host copy of either half that the disk does not hold yet. */
|
||||
bool wants_disk(const Rec& r) const;
|
||||
void queue_copy(const BlockHash& key, Rec& r);
|
||||
void queue_clean(const BlockHash& key, Rec& r);
|
||||
void queue_disk(const BlockHash& key, Rec& r);
|
||||
/* GIVE UP A HOST SLOT, the record's or a finished job's. Every block-arena free goes through
|
||||
* `give_slot`, because a freed slot is what unblocks a write-back that found the arena full.
|
||||
* `free_host` / `free_ck_host` are the record's own: a slot a disk write is reading is left
|
||||
* for that write's report to free. */
|
||||
void give_slot(int32_t slot);
|
||||
void free_host(Rec& r);
|
||||
void free_ck_host(Rec& r);
|
||||
void set_on_disk(Rec& r, bool v);
|
||||
int64_t make_room_locked(int64_t n);
|
||||
/* May this record's host copies be given up to make room right now? Not while a read put
|
||||
* them there for a request that has not claimed them yet, nor while the chain being read
|
||||
* includes it. */
|
||||
bool held_by_fetch(const Rec& r, uint64_t now_ns) const;
|
||||
void unlist(Rec& r);
|
||||
void relist(const BlockHash& key, Rec& r);
|
||||
std::list<BlockHash>& list_for(KVTier t) { return t == KVTier::Host ? host_lru_ : disk_lru_; }
|
||||
void release_storage(const BlockHash& key, Rec& r);
|
||||
/* Take a snapshot arena slot from the record whose host copy is cheapest to lose, and tell the
|
||||
* cache if that was the snapshot's only copy. NO SECOND LIST: the records are walked, which
|
||||
* keeps the header's "one record, one tier, one list" rule intact. `lossless` takes only a
|
||||
* snapshot the disk also holds.
|
||||
* Returns -1 when there is none to take. */
|
||||
int32_t evict_snapshot_slot(bool lossless);
|
||||
|
||||
struct Session {
|
||||
int64_t n_tokens = 0;
|
||||
uint64_t first_seen_ns = 0;
|
||||
uint64_t last_used_ns = 0;
|
||||
std::vector<BlockHash> chain;
|
||||
};
|
||||
|
||||
/* Erase one row and its root index entry together. */
|
||||
void drop_session(uint64_t id);
|
||||
/* 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.
|
||||
*
|
||||
* 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. */
|
||||
struct YieldingMutex {
|
||||
std::mutex m;
|
||||
std::atomic<int> waiting{0};
|
||||
void lock() {
|
||||
waiting.fetch_add(1, std::memory_order_relaxed);
|
||||
m.lock();
|
||||
waiting.fetch_sub(1, std::memory_order_relaxed);
|
||||
}
|
||||
void unlock() { m.unlock(); }
|
||||
/* The view's: taken only while no other taker is waiting. */
|
||||
void lock_after_others() {
|
||||
for (;;) {
|
||||
while (waiting.load(std::memory_order_relaxed) > 0) std::this_thread::yield();
|
||||
m.lock();
|
||||
if (waiting.load(std::memory_order_relaxed) == 0) return;
|
||||
m.unlock();
|
||||
}
|
||||
}
|
||||
};
|
||||
mutable YieldingMutex mu_;
|
||||
|
||||
Config cfg_;
|
||||
SSDTier* disk_ = nullptr;
|
||||
HostArena arena_;
|
||||
HostArena ck_arena_; /* snapshots; a different slot size, so a different arena */
|
||||
std::unordered_map<BlockHash, Rec, BlockHashHash> recs_;
|
||||
std::list<BlockHash> host_lru_, disk_lru_; /* front = oldest */
|
||||
/* THE WORK QUEUES, in the order the work arrived. Each holds a key at most once -- the Rec's
|
||||
* flag says whether it is in -- and a key whose record changed under it is skipped when it is
|
||||
* reached rather than searched for, so both stay a push and a pop. */
|
||||
std::deque<BlockHash> wb_q_; /* records wanting a host copy */
|
||||
std::deque<BlockHash> dk_q_; /* records wanting a disk copy, in the order they landed */
|
||||
std::vector<BlockHash> clean_q_; /* records whose VRAM copy may now go */
|
||||
std::vector<int32_t> ck_frees_; /* device checkpoint slots a finished copy released */
|
||||
/* COPIES THE ARENA REFUSED since the last maintenance plan, which is what that plan frees
|
||||
* room for. A count and not a list: any host-only entry makes room for any copy. */
|
||||
int64_t starved_ = 0;
|
||||
/* A WRITE-BACK FOUND THE ARENA FULL AND NOTHING TO GIVE UP. Waiting again changes nothing until
|
||||
* a slot is freed or an entry's disk copy lands, so the copy is not planned until one does --
|
||||
* otherwise every tick pops the queue, finds no slot and puts it back. */
|
||||
bool wb_stuck_ = false;
|
||||
std::unordered_map<uint64_t, Session> sessions_;
|
||||
/* THE DEATH SIGNAL FOR A ROW, and the reason the table is bounded. A published chain is only
|
||||
* ever reachable from position zero, so the moment the cache evicts its FIRST block the
|
||||
* conversation cannot be hit at any length and the row describes blocks that are not there.
|
||||
* The cache announces every eviction through forget(), which is the only notice this object
|
||||
* gets, so the root is indexed and the row goes with it. Several sessions share a root when
|
||||
* they share a system prompt and all of them are unreachable together, which is why the value
|
||||
* is a list. */
|
||||
std::unordered_map<BlockHash, std::vector<uint64_t>, BlockHashHash> roots_;
|
||||
std::string model_;
|
||||
std::function<void(const BlockHash&)> on_drop_;
|
||||
std::function<void(const BlockHash&)> on_ck_drop_;
|
||||
Stats stats_;
|
||||
std::string report_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,314 @@
|
||||
/* pools.cpp -- see pools.h. Every refusal in here names what did not fit and by how much. */
|
||||
#include "mem/pools.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ allocators */
|
||||
|
||||
namespace {
|
||||
|
||||
class DeviceAllocator final : public MemAllocator {
|
||||
public:
|
||||
void* alloc(int64_t bytes, int kind) override { return rad_dev_alloc(bytes, kind); }
|
||||
void free(void* p, int kind) override { rad_dev_free(p, kind); }
|
||||
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. */
|
||||
class MallocAllocator final : public MemAllocator {
|
||||
public:
|
||||
void* alloc(int64_t bytes, int kind) override {
|
||||
(void)kind;
|
||||
if (bytes <= 0) return nullptr;
|
||||
int64_t n = align_up(bytes, (int64_t)RAD_ALIGN_POOL);
|
||||
void* p = ::aligned_alloc((size_t)RAD_ALIGN_POOL, (size_t)n);
|
||||
return p;
|
||||
}
|
||||
void free(void* p, int kind) override { (void)kind; ::free(p); }
|
||||
const char* name() const override { return "malloc"; }
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
MemAllocator& rad_device_allocator() { static DeviceAllocator a; return a; }
|
||||
MemAllocator& rad_malloc_allocator() { static MallocAllocator a; return a; }
|
||||
|
||||
/* ------------------------------------------------------------------ Shortfall */
|
||||
|
||||
std::string Shortfall::str() const {
|
||||
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());
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Pool */
|
||||
|
||||
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. */
|
||||
if (elastic_) {
|
||||
vm_.release();
|
||||
elastic_ = false;
|
||||
} else if (base_ && alloc_) {
|
||||
alloc_->free(base_, kind_);
|
||||
}
|
||||
base_ = nullptr;
|
||||
bytes_ = used_ = 0;
|
||||
}
|
||||
|
||||
int Pool::init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a, bool accounting) {
|
||||
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;
|
||||
|
||||
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). */
|
||||
shortfalls_.push_back({name_, "backing allocation", bytes_, 0});
|
||||
bytes_ = 0;
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void* Pool::reserve(std::string_view what, int64_t bytes, int64_t align, int64_t* off_out) {
|
||||
if (bytes < 0 || align <= 0) return nullptr;
|
||||
int64_t off = align_up(used_, align);
|
||||
if (off + bytes > bytes_) {
|
||||
shortfalls_.push_back({name_, std::string(what), bytes, bytes_ - off});
|
||||
return nullptr;
|
||||
}
|
||||
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. */
|
||||
if (!VMem::supported() || kind != RAD_MEM_DEVICE)
|
||||
return init(nm, bytes, kind, a, /*accounting=*/false);
|
||||
|
||||
release();
|
||||
name_ = std::string(nm);
|
||||
bytes_ = bytes;
|
||||
used_ = 0;
|
||||
kind_ = kind;
|
||||
accounting_ = false;
|
||||
alloc_ = a;
|
||||
shortfalls_.clear();
|
||||
res_.clear();
|
||||
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. */
|
||||
shortfalls_.push_back({ name_, "address reservation", bytes_, 0 });
|
||||
bytes_ = 0;
|
||||
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. */
|
||||
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. */
|
||||
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 */
|
||||
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",
|
||||
name_.c_str(), humanb(bytes_).c_str(), humanb(used_).c_str(),
|
||||
humanb(avail()).c_str(), accounting_ ? " (accounted, not allocated)" : "");
|
||||
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";
|
||||
return s;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Pools */
|
||||
|
||||
int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
MemAllocator* device, MemAllocator* host) {
|
||||
configured_ = false;
|
||||
fit_report_.clear();
|
||||
|
||||
if (!device) device = &rad_device_allocator();
|
||||
if (!host) host = device;
|
||||
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
const int64_t w = cfg.vram_weights_mib * MiB;
|
||||
const int64_t kv = cfg.vram_kv_mib * MiB;
|
||||
const int64_t hp = cfg.host_pool_mib * MiB;
|
||||
|
||||
/* THE BUDGETS ARE RESOLVED BEFORE THIS RUNS AND THIS DOES NOT RE-DECIDE THEM. Either the
|
||||
* operator stated them or core/mem/vram_budget.cpp derived them from the card, the measured
|
||||
* driver residency and the computed arena -- and either way they arrive here as two numbers
|
||||
* with a report behind them. Either way 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. */
|
||||
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";
|
||||
if (!missing.empty()) {
|
||||
fit_report_ = "VRAM pool budgets are empty -- state --vram-weights-mib / --vram-kv-mib, or "
|
||||
"let the card be split by --gpu-headroom-mib and --expert-vs-cache-ratio:\n"
|
||||
+ missing;
|
||||
RAD_ERR("%s", fit_report_.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
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"
|
||||
" vram_kv %10s\n"
|
||||
" ------------------------\n"
|
||||
" total %10s\n"
|
||||
" card total %10s\n"
|
||||
" OVER BY %10s\n"
|
||||
"Lower --vram-weights-mib / --vram-kv-mib, or raise --gpu-headroom-mib and let "
|
||||
"--expert-vs-cache-ratio split what is left. The split is yours to make; the engine "
|
||||
"will not make it for you (spec §6).\n",
|
||||
humanb(w).c_str(), humanb(kv).c_str(),
|
||||
humanb(want).c_str(), humanb(vram_capacity).c_str(),
|
||||
humanb(want - vram_capacity).c_str());
|
||||
RAD_ERR("%s", fit_report_.c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
/* THE SLACK IS NAMED, because nothing else will name it -- and after the resolver ran there
|
||||
* should be almost none. `vram_capacity` is totalGlobalMem: it is not the free VRAM and it is
|
||||
* not the sum of the budgets. What is left over here is the driver's residency, the activation
|
||||
* arena, --gpu-headroom-mib, and whatever MiB rounding could not place; vram_budget.cpp's
|
||||
* report breaks that down term by term. A budget a couple of GiB under the card is that much
|
||||
* of the expert plane streaming from host memory instead, which costs real prefill throughput
|
||||
* on a model whose experts do not fit.
|
||||
*
|
||||
* THIS IS FOR A STATED BUDGET AND ONLY FOR ONE. A size threshold cannot tell the two apart: a
|
||||
* small dense model whose cache is already at the largest context it can address leaves many
|
||||
* GiB that NOTHING can spend, and warning there would tell the operator to leave unset the
|
||||
* very flags they already left unset. Where the resolver made the split it has already printed
|
||||
* every term including the unusable one, and there is nothing to add. */
|
||||
if (vram_capacity > 0 && !cfg.vram_budget_derived) {
|
||||
const int64_t slack = vram_capacity - want;
|
||||
if (slack >= 1024 * MiB)
|
||||
RAD_WARN("VRAM budgets total %s of the card's %s, so %s is neither budgeted nor "
|
||||
"accounted. The driver's context, the activation arena and "
|
||||
"--gpu-headroom-mib come out of it; anything past those is throughput on the "
|
||||
"floor. Leave --vram-weights-mib / --vram-kv-mib unset to have the card split "
|
||||
"automatically.",
|
||||
humanb(want).c_str(), humanb(vram_capacity).c_str(), humanb(slack).c_str());
|
||||
}
|
||||
|
||||
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. */
|
||||
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;
|
||||
|
||||
fit_report_ = weights_.report();
|
||||
fit_report_ += kv_.report();
|
||||
fit_report_ += host_.report();
|
||||
|
||||
if (st < 0) {
|
||||
RAD_ERR("pool allocation refused:\n%s", fit_report_.c_str());
|
||||
return st;
|
||||
}
|
||||
configured_ = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
std::vector<Shortfall> Pools::shortfalls() const {
|
||||
std::vector<Shortfall> out;
|
||||
for (const Pool* p : { &weights_, &kv_, &host_ })
|
||||
for (const auto& f : p->shortfalls()) out.push_back(f);
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,199 @@
|
||||
/* 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.
|
||||
*
|
||||
* Two properties this file exists to make STRUCTURAL rather than conventional:
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
|
||||
#include "../device/device.h"
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
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. */
|
||||
class MemAllocator {
|
||||
public:
|
||||
virtual ~MemAllocator() = default;
|
||||
virtual void* alloc(int64_t bytes, int kind) = 0; /* kind is RAD_MEM_* */
|
||||
virtual void free(void* p, int kind) = 0;
|
||||
virtual const char* name() const = 0;
|
||||
};
|
||||
|
||||
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. */
|
||||
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;
|
||||
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. */
|
||||
class Pool {
|
||||
public:
|
||||
Pool() = default;
|
||||
~Pool();
|
||||
Pool(const Pool&) = delete;
|
||||
Pool& operator=(const Pool&) = delete;
|
||||
|
||||
const char* name() const { return name_.c_str(); }
|
||||
int64_t bytes() const { return bytes_; }
|
||||
int64_t used() const { return used_; }
|
||||
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. */
|
||||
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). */
|
||||
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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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);
|
||||
void release();
|
||||
|
||||
std::string name_;
|
||||
int64_t bytes_ = 0;
|
||||
int64_t used_ = 0;
|
||||
void* base_ = nullptr;
|
||||
int kind_ = RAD_MEM_DEVICE;
|
||||
bool accounting_ = false;
|
||||
bool elastic_ = false;
|
||||
VMem vm_;
|
||||
MemAllocator* alloc_ = nullptr;
|
||||
std::vector<Shortfall> shortfalls_;
|
||||
struct Res { std::string what; int64_t off, bytes; };
|
||||
std::vector<Res> res_;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
*
|
||||
* Refuses, by name and by how much, rather than shrinking anything:
|
||||
* - if the operator did not state the weight and KV budgets at all;
|
||||
* - if weights + kv exceeds the card;
|
||||
* - if a pool's backing allocation fails.
|
||||
*/
|
||||
int configure(const Config& cfg, int64_t vram_capacity,
|
||||
MemAllocator* device = nullptr, MemAllocator* host = nullptr);
|
||||
|
||||
Pool& weights() { return weights_; }
|
||||
Pool& kv() { return kv_; }
|
||||
Pool& host_pinned() { return host_; }
|
||||
|
||||
const Pool& weights() const { return weights_; }
|
||||
const Pool& kv() const { return kv_; }
|
||||
const Pool& host_pinned() const { return host_; }
|
||||
|
||||
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). */
|
||||
const std::string& fit_report() const { return fit_report_; }
|
||||
|
||||
/* Every shortfall from every pool, gathered. */
|
||||
std::vector<Shortfall> shortfalls() const;
|
||||
|
||||
private:
|
||||
Pool weights_, kv_, host_;
|
||||
std::string fit_report_;
|
||||
bool configured_ = false;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,869 @@
|
||||
/* prefix.cpp -- see prefix.h. */
|
||||
#include "mem/prefix.h"
|
||||
|
||||
#include "mem/kvtier.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
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. The SSD tier,
|
||||
* which is such a store, carries the token ids into the slot header for the same reason
|
||||
* (sstier.h).
|
||||
*
|
||||
* 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. */
|
||||
static inline uint64_t mix64(uint64_t x) {
|
||||
x += 0x9e3779b97f4a7c15ull;
|
||||
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9ull;
|
||||
x = (x ^ (x >> 27)) * 0x94d049bb133111ebull;
|
||||
return x ^ (x >> 31);
|
||||
}
|
||||
|
||||
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. */
|
||||
BlockHash h;
|
||||
h.hi = mix64(parent.hi ^ 0x243f6a8885a308d3ull);
|
||||
h.lo = mix64(parent.lo ^ 0x13198a2e03707344ull);
|
||||
h.hi = mix64(h.hi ^ (uint64_t)block_begin);
|
||||
|
||||
for (int32_t i = 0; i < n; ++i) {
|
||||
uint64_t t = (uint64_t)(uint32_t)toks[i];
|
||||
h.lo = mix64(h.lo ^ 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). */
|
||||
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];
|
||||
if (m.tok_end <= lo_pos || m.tok_begin >= hi_pos) continue;
|
||||
h.lo = mix64(h.lo ^ m.hash);
|
||||
h.hi = mix64(h.hi ^ mix64(m.hash + (uint64_t)(m.tok_begin - lo_pos) * 1000003ull
|
||||
+ (uint64_t)(m.tok_end - lo_pos)));
|
||||
}
|
||||
/* Never let a block hash to zero: a zeroed BlockHash is the chain root and must be unique. */
|
||||
if (!h.valid()) h.lo = 1;
|
||||
return h;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ retention policies */
|
||||
|
||||
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;
|
||||
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;
|
||||
for (size_t i = 0; i < pos.size(); ++i) if (mark[i]) keep->push_back(pos[i]);
|
||||
}
|
||||
|
||||
void KeepTipOnly::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep) const {
|
||||
keep->clear();
|
||||
if (!pos.empty()) keep->push_back(pos.back());
|
||||
}
|
||||
|
||||
void KeepAll::select(const std::vector<int64_t>& pos, std::vector<int64_t>* keep) const {
|
||||
*keep = pos;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ configure */
|
||||
|
||||
int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval) {
|
||||
kv_ = kv;
|
||||
enabled_ = false;
|
||||
has_linear_ = false;
|
||||
block_size_ = 0;
|
||||
interval_ = 0;
|
||||
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. */
|
||||
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>();
|
||||
report_.clear();
|
||||
|
||||
if (!kv) return RAD_E_INVAL;
|
||||
if (!cfg.prefix_cache) {
|
||||
report_ = "prefix cache: disabled by --no-prefix-cache\n";
|
||||
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. */
|
||||
for (const auto& p : kv->plans()) {
|
||||
if (p.kind == RAD_KV_FULL && block_size_ == 0) block_size_ = p.block_size;
|
||||
if (p.stateful()) has_linear_ = true;
|
||||
}
|
||||
if (block_size_ == 0) {
|
||||
for (const auto& p : kv->plans()) if (p.paged()) { block_size_ = p.block_size; break; }
|
||||
}
|
||||
if (block_size_ <= 0) {
|
||||
report_ = "prefix cache: no paged KV group to cache; disabled\n";
|
||||
RAD_WARN("%s", report_.c_str());
|
||||
return RAD_OK;
|
||||
}
|
||||
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. */
|
||||
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",
|
||||
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",
|
||||
p.name.c_str(), (long long)p.block_size, (long long)block_size_);
|
||||
}
|
||||
|
||||
interval_ = checkpoint_interval;
|
||||
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_);
|
||||
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. */
|
||||
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).",
|
||||
(long long)interval_, (long long)cfg.checkpoint_interval,
|
||||
(long long)block_size_);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
enabled_ = true;
|
||||
report_ = fmt("prefix cache: %zu paged group(s) at %lld-token blocks; linear checkpoints "
|
||||
"every %lld tokens (%s x %s), retention '%s'\n",
|
||||
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(),
|
||||
policy_->name());
|
||||
report_ += skipped;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void PrefixCache::set_policy(std::unique_ptr<CheckpointPolicy> p) {
|
||||
if (p) policy_ = std::move(p);
|
||||
}
|
||||
|
||||
std::string PrefixCache::report() const { return report_; }
|
||||
|
||||
/* ------------------------------------------------------------------ full attention */
|
||||
|
||||
std::vector<BlockHash> PrefixCache::chain_all(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
int64_t n_blocks) const {
|
||||
std::vector<BlockHash> hs;
|
||||
hs.reserve((size_t)n_blocks);
|
||||
BlockHash parent;
|
||||
for (int64_t b = 0; b < n_blocks; ++b) {
|
||||
parent = chain_block_hash(parent, tokens.data() + b * block_size_, (int32_t)block_size_,
|
||||
mm.data(), (int32_t)mm.size(), b * block_size_);
|
||||
hs.push_back(parent);
|
||||
}
|
||||
return hs;
|
||||
}
|
||||
|
||||
void PrefixCache::touch(const BlockHash& h) const {
|
||||
auto it = map_.find(h);
|
||||
if (it == map_.end() || !it->second.in_lru) return;
|
||||
lru_.splice(lru_.end(), lru_, it->second.lru);
|
||||
}
|
||||
|
||||
CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<std::vector<int32_t>>* blocks_out) const {
|
||||
CacheHit hit;
|
||||
if (blocks_out) { blocks_out->assign(groups_.size(), {}); }
|
||||
if (!enabled_ || tokens.empty()) return hit;
|
||||
++stats_.lookups;
|
||||
|
||||
const int64_t n_full = (int64_t)tokens.size() / block_size_;
|
||||
std::vector<BlockHash> hs = chain_all(tokens, mm, n_full);
|
||||
|
||||
int64_t matched = 0;
|
||||
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. */
|
||||
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;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched;
|
||||
|
||||
for (int64_t b = 0; b < matched; ++b) {
|
||||
touch(hs[(size_t)b]);
|
||||
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. */
|
||||
if (tiers_ && matched > 0) tiers_->note_hits(hs.data(), matched, rad_mono_ns());
|
||||
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, so walk back to the last checkpoint boundary at or below n_attn_tokens and
|
||||
* look it up by the chained hash there. The gap between the two is replayed through the linear
|
||||
* layers only -- the attention layers for those tokens are already in the cache. */
|
||||
if (!has_linear_) {
|
||||
/* No recurrent state means nothing to replay: the whole attention hit is directly usable. */
|
||||
hit.n_linear_tokens = hit.n_attn_tokens;
|
||||
return hit;
|
||||
}
|
||||
for (int64_t p = (hit.n_attn_tokens / interval_) * interval_; p > 0; p -= interval_) {
|
||||
const BlockHash& h = hs[(size_t)(p / block_size_ - 1)];
|
||||
auto it = ck_by_prefix_.find(h);
|
||||
if (it == ck_by_prefix_.end() || !it->second.valid) continue;
|
||||
hit.n_linear_tokens = (int32_t)p;
|
||||
hit.checkpoint_slot = it->second.slot;
|
||||
it->second.used = ++clock_;
|
||||
handed_.push_back(h);
|
||||
++stats_.ckpt_hits;
|
||||
return hit;
|
||||
}
|
||||
++stats_.ckpt_misses;
|
||||
return hit;
|
||||
}
|
||||
|
||||
int PrefixCache::insert(uint64_t session,
|
||||
const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
const std::vector<std::vector<int32_t>>& blocks,
|
||||
int64_t n_tokens) {
|
||||
if (!enabled_) return RAD_OK;
|
||||
if (blocks.size() != groups_.size()) return RAD_E_INVAL;
|
||||
if (n_tokens > (int64_t)tokens.size()) return RAD_E_INVAL;
|
||||
|
||||
const int64_t n_full = n_tokens / block_size_;
|
||||
if (n_full <= 0) return RAD_OK;
|
||||
for (const auto& bt : blocks) if ((int64_t)bt.size() < n_full) return RAD_E_INVAL;
|
||||
|
||||
std::vector<BlockHash> hs = chain_all(tokens, mm, n_full);
|
||||
const uint64_t now = rad_mono_ns();
|
||||
for (int64_t b = 0; b < n_full; ++b) {
|
||||
const BlockHash& h = hs[(size_t)b];
|
||||
auto it = map_.find(h);
|
||||
if (it != map_.end() && it->second.in_lru) { touch(h); continue; }
|
||||
if (it != map_.end()) {
|
||||
/* 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. */
|
||||
if (!tiers_ || !tiers_->resident_off_device(h)) continue;
|
||||
std::vector<int32_t> mine(groups_.size(), -1);
|
||||
size_t held = 0;
|
||||
for (; held < groups_.size(); ++held) {
|
||||
const int32_t blk = blocks[held][(size_t)b];
|
||||
if (kv_->retain_block(groups_[held], blk) < 0) break;
|
||||
mine[held] = blk;
|
||||
}
|
||||
if (held != groups_.size()) {
|
||||
for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], mine[g]);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
Entry& e = it->second;
|
||||
e.blocks = std::move(mine);
|
||||
lru_.push_back(h);
|
||||
e.lru = std::prev(lru_.end());
|
||||
e.in_lru = true;
|
||||
tiers_->rebound(h, e.blocks, now);
|
||||
continue;
|
||||
}
|
||||
|
||||
Entry e;
|
||||
e.blocks.assign(groups_.size(), -1);
|
||||
size_t held = 0;
|
||||
for (; held < groups_.size(); ++held) {
|
||||
int32_t blk = blocks[held][(size_t)b];
|
||||
if (kv_->retain_block(groups_[held], blk) < 0) break;
|
||||
e.blocks[held] = blk;
|
||||
}
|
||||
if (held != groups_.size()) {
|
||||
/* Unwind exactly what was 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. */
|
||||
for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], e.blocks[g]);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
e.tokens.assign(tokens.begin() + b * block_size_,
|
||||
tokens.begin() + (b + 1) * block_size_);
|
||||
lru_.push_back(h);
|
||||
e.lru = std::prev(lru_.end());
|
||||
e.in_lru = true;
|
||||
map_.emplace(h, std::move(e));
|
||||
}
|
||||
|
||||
/* 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.
|
||||
*
|
||||
* 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. */
|
||||
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_session(session, hs, n_tokens, now);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ idle session tiers */
|
||||
|
||||
std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<BlockHash>* chain) const {
|
||||
std::vector<BlockHash> out;
|
||||
if (chain) chain->clear();
|
||||
if (!enabled_ || !tiers_ || tokens.empty()) return out;
|
||||
|
||||
const int64_t n_full = (int64_t)tokens.size() / 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. */
|
||||
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 (chain) chain->push_back(hs[(size_t)b]);
|
||||
if (tiers_->resident_off_device(hs[(size_t)b])) out.push_back(hs[(size_t)b]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
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. */
|
||||
if (it->second.in_lru) lru_.erase(it->second.lru);
|
||||
map_.erase(it);
|
||||
++stats_.evictions;
|
||||
/* AND THE SNAPSHOT KEYED BY THE SAME HASH. The tiers moved the two halves together, so they
|
||||
* lose them together; leaving the index entry behind would leave a snapshot marked off-device
|
||||
* whose bytes nobody holds, waiting to be promoted by something that no longer exists. */
|
||||
drop_snapshot(key);
|
||||
}
|
||||
|
||||
int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks) {
|
||||
auto it = map_.find(key);
|
||||
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. */
|
||||
Entry& e = it->second;
|
||||
e.blocks = blocks;
|
||||
for (size_t g = 0; g < groups_.size(); ++g) kv_->cache_reserved_block(groups_[g], blocks[g]);
|
||||
if (!e.in_lru) {
|
||||
lru_.push_back(key);
|
||||
e.lru = std::prev(lru_.end());
|
||||
e.in_lru = true;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
int64_t done = 0;
|
||||
while (done < n && !lru_.empty()) {
|
||||
const BlockHash h = lru_.front();
|
||||
lru_.pop_front();
|
||||
auto it = map_.find(h);
|
||||
if (it == map_.end()) continue;
|
||||
Entry& e = it->second;
|
||||
e.in_lru = false;
|
||||
/* Every entry on the list holds its blocks, whatever the tiers are doing with it: one on
|
||||
* its way to a host copy still holds the cache's references until the copy reports, and
|
||||
* the report finds it forgotten and keeps nothing. */
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
kv_->release_block(groups_[g], e.blocks[g]);
|
||||
if (tiers_) {
|
||||
/* THE HOST COPY HAS LANDED: the entry leaves VRAM and stays in the index. */
|
||||
if (tiers_->droppable(h)) {
|
||||
tiers_->drop_commit(h);
|
||||
++stats_.drops;
|
||||
++done;
|
||||
continue;
|
||||
}
|
||||
tiers_->forget(h);
|
||||
}
|
||||
map_.erase(it);
|
||||
++done;
|
||||
++stats_.evictions;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
int64_t PrefixCache::drop_clean() {
|
||||
if (!tiers_ || !kv_) return 0;
|
||||
drop_scratch_.clear();
|
||||
tiers_->take_clean(&drop_scratch_);
|
||||
const uint64_t frees = kv_->seq_frees();
|
||||
if (frees != frees_seen_) {
|
||||
frees_seen_ = frees;
|
||||
drop_scratch_.insert(drop_scratch_.end(), drop_wait_.begin(), drop_wait_.end());
|
||||
drop_wait_.clear();
|
||||
}
|
||||
int64_t n = 0;
|
||||
for (const BlockHash& h : drop_scratch_) {
|
||||
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 = false;
|
||||
for (size_t g = 0; g < groups_.size() && !shared; ++g)
|
||||
shared = kv_->block_refcount(groups_[g], e.blocks[g]) > 1;
|
||||
if (shared) {
|
||||
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]);
|
||||
lru_.erase(e.lru);
|
||||
e.in_lru = false;
|
||||
++stats_.drops;
|
||||
tiers_->drop_commit(h);
|
||||
++n;
|
||||
}
|
||||
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 on the host or on disk and it is holding none of the card. */
|
||||
int64_t PrefixCache::unshared_tokens() const {
|
||||
if (!kv_ || groups_.empty() || block_size_ <= 0) return 0;
|
||||
return kv_->cache_only_blocks(groups_[0]) * block_size_;
|
||||
}
|
||||
|
||||
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 (tiers_) tiers_->forget(kv.first);
|
||||
++stats_.evictions;
|
||||
}
|
||||
map_.clear();
|
||||
lru_.clear();
|
||||
drop_wait_.clear();
|
||||
}
|
||||
|
||||
std::vector<BlockHash> PrefixCache::lru_order() const {
|
||||
return std::vector<BlockHash>(lru_.begin(), lru_.end());
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ checkpoints */
|
||||
|
||||
int64_t PrefixCache::next_checkpoint_after(int64_t pos) const {
|
||||
if (interval_ <= 0) return -1;
|
||||
if (pos < 0) pos = 0;
|
||||
return (pos / interval_ + 1) * interval_;
|
||||
}
|
||||
|
||||
std::vector<int64_t> PrefixCache::checkpoints(uint64_t session) const {
|
||||
std::vector<int64_t> out;
|
||||
auto it = ck_by_session_.find(session);
|
||||
if (it == ck_by_session_.end()) return out;
|
||||
for (const BlockHash& h : it->second) {
|
||||
auto e = ck_by_prefix_.find(h);
|
||||
if (e != ck_by_prefix_.end()) out.push_back(e->second.pos);
|
||||
}
|
||||
std::sort(out.begin(), out.end());
|
||||
return out;
|
||||
}
|
||||
|
||||
int64_t PrefixCache::retain(uint64_t session) {
|
||||
auto it = ck_by_session_.find(session);
|
||||
if (it == ck_by_session_.end()) return 0;
|
||||
|
||||
/* DEVICE-RESIDENT SNAPSHOTS ONLY. This policy exists to spend a fixed number of --checkpoint-
|
||||
* slots well, and it runs when that pool is exhausted. A snapshot the idle tiers hold occupies
|
||||
* none of it, so retiring one would free nothing here and would cost a session the state it
|
||||
* was moved off the device precisely in order to keep. Tiered bytes are bounded by the tiers'
|
||||
* own caps, oldest first, which is the right policy for the resource they actually spend.
|
||||
*
|
||||
* It stays in `kept` rather than being skipped, or the session index would forget it. */
|
||||
std::vector<std::pair<int64_t, BlockHash>> all;
|
||||
std::vector<BlockHash> kept;
|
||||
for (const BlockHash& h : it->second) {
|
||||
auto e = ck_by_prefix_.find(h);
|
||||
if (e == ck_by_prefix_.end()) continue;
|
||||
if (e->second.off_device) { kept.push_back(h); continue; }
|
||||
all.push_back({e->second.pos, h});
|
||||
}
|
||||
std::sort(all.begin(), all.end(),
|
||||
[](const auto& a, const auto& b) { return a.first < b.first; });
|
||||
|
||||
std::vector<int64_t> pos;
|
||||
for (const auto& a : all) pos.push_back(a.first);
|
||||
std::vector<int64_t> keep;
|
||||
policy_->select(pos, &keep);
|
||||
|
||||
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; }
|
||||
auto e = ck_by_prefix_.find(a.second);
|
||||
if (e != ck_by_prefix_.end()) {
|
||||
retire_ckpt(e);
|
||||
++freed;
|
||||
++stats_.ckpt_evictions;
|
||||
}
|
||||
}
|
||||
/* ERASE THE SESSION WHEN NOTHING IS LEFT OF IT, and that is not tidiness. `session` is a
|
||||
* REQUEST id, so without an eraser this map gains an entry for every request that ever writes
|
||||
* 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. */
|
||||
if (kept.empty()) { ck_by_session_.erase(it); return freed; }
|
||||
it->second = std::move(kept);
|
||||
return freed;
|
||||
}
|
||||
|
||||
int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix,
|
||||
int32_t* slot_out) {
|
||||
if (!enabled_ || !has_linear_) return RAD_E_UNSUPPORTED;
|
||||
if (!slot_out) return RAD_E_INVAL;
|
||||
if (interval_ <= 0 || pos <= 0 || pos % interval_ != 0) {
|
||||
RAD_ERR("checkpoint at %lld is not on a %lld-token boundary; the scheduler splits chunks "
|
||||
"at the interval precisely so this cannot happen (spec §7.3)",
|
||||
(long long)pos, (long long)interval_);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto existing = ck_by_prefix_.find(prefix);
|
||||
if (existing != ck_by_prefix_.end()) {
|
||||
/* A SNAPSHOT THE TIERS HOLD IS NOT ONE THIS CALL CAN HAND BACK. Returning its -1 slot
|
||||
* would look to the scheduler exactly like a refusal (it tests `cs >= 0`) and the chunk
|
||||
* would silently stop checkpointing; handing back a slot that is not in the pool would be
|
||||
* worse. The state is about to be recomputed anyway -- that is what a reservation at this
|
||||
* prefix means -- so the tiered copy is retired and a fresh slot allocated below. */
|
||||
/* NOR ONE A COPY IS READING. The save that follows this reservation writes the slot on
|
||||
* the compute stream while the copy reads it on the transfer stream, and the host would
|
||||
* keep a snapshot that is half of each. A fresh slot costs one allocation. */
|
||||
if (!existing->second.off_device &&
|
||||
!(tiers_ && tiers_->snapshot_reading(prefix))) {
|
||||
*slot_out = existing->second.slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
const uint64_t vs = existing->second.session;
|
||||
retire_ckpt(existing);
|
||||
auto sit = ck_by_session_.find(vs);
|
||||
if (sit != ck_by_session_.end()) {
|
||||
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), prefix),
|
||||
sit->second.end());
|
||||
if (sit->second.empty()) ck_by_session_.erase(sit);
|
||||
}
|
||||
}
|
||||
|
||||
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. */
|
||||
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. */
|
||||
const Ckpt* victim = nullptr;
|
||||
const Ckpt* tip_victim = nullptr;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
/* A TIERED SNAPSHOT IS NOT A CANDIDATE, because evicting it frees nothing HERE.
|
||||
* Its device slot went back to the pool when the tiers took the bytes, so picking
|
||||
* it as the victim would retire a usable snapshot and then fail the retry anyway. */
|
||||
if (kvp.second.off_device) continue;
|
||||
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) victim = tip_victim;
|
||||
if (!victim) return RAD_E_FULL;
|
||||
BlockHash vh = victim->prefix;
|
||||
uint64_t vs = victim->session;
|
||||
/* A VICTIM THE TIERS HOLD A COPY OF IS DETACHED, NOT LOST. The slot goes back all the
|
||||
* same; the index entry stays, and the session's next restore brings the state back
|
||||
* with its blocks instead of replaying every recurrent layer from an older point. */
|
||||
if (tiers_ && tiers_->snapshot_backed(vh)) {
|
||||
(void)detach_snapshot(vh);
|
||||
tiers_->snapshot_detached(vh);
|
||||
if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL;
|
||||
Ckpt c;
|
||||
c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot;
|
||||
c.used = ++clock_;
|
||||
ck_by_prefix_.emplace(prefix, c);
|
||||
ck_by_session_[session].push_back(prefix);
|
||||
*slot_out = slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
retire_ckpt(ck_by_prefix_.find(vh));
|
||||
++stats_.ckpt_evictions;
|
||||
auto sit = ck_by_session_.find(vs);
|
||||
if (sit != ck_by_session_.end()) {
|
||||
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), vh),
|
||||
sit->second.end());
|
||||
if (sit->second.empty()) ck_by_session_.erase(sit);
|
||||
}
|
||||
if (kv_->alloc_checkpoint(&slot) < 0) return RAD_E_FULL;
|
||||
}
|
||||
}
|
||||
|
||||
Ckpt c;
|
||||
c.session = session; c.pos = pos; c.prefix = prefix; c.slot = slot; c.used = ++clock_;
|
||||
ck_by_prefix_.emplace(prefix, c);
|
||||
ck_by_session_[session].push_back(prefix);
|
||||
*slot_out = slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
|
||||
auto it = ck_by_prefix_.find(prefix);
|
||||
if (it == ck_by_prefix_.end()) return;
|
||||
it->second.valid = true;
|
||||
/* THE TIERS LEARN THE SNAPSHOT HERE, for the same reason note_used tells them the block ids:
|
||||
* a demotion has to know what to move and this index is the only place it is written down.
|
||||
* Before the commit there is nothing to move -- the slot still holds the previous tenant's
|
||||
* state -- so this is also the earliest moment at which telling them would be true. */
|
||||
if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos);
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ the linear half of a session */
|
||||
|
||||
void PrefixCache::retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it) {
|
||||
if (it == ck_by_prefix_.end()) return;
|
||||
/* THE TIERS ARE ASKED FIRST, because they may be reading the slot: a copy to host memory in
|
||||
* flight out of a slot the pool then decommits reads a page that is no longer mapped. When
|
||||
* one is, the tiers keep the slot and hand it back once the copy has reported. */
|
||||
const bool held = tiers_ && tiers_->release_snapshot(it->first);
|
||||
if (it->second.slot >= 0 && !held) kv_->free_checkpoint(it->second.slot);
|
||||
/* TOLD EITHER WAY, AND NOT ONLY WHEN THE TIERS HOLD THE BYTES. They also remember a snapshot's
|
||||
* DEVICE slot -- note_snapshot records it at commit, because a demotion has to know what to
|
||||
* copy and this index is the only place it is written down. Freeing that slot here without
|
||||
* saying so leaves the tiers naming a slot the pool has since given to another session, and
|
||||
* the next demotion copies THAT session's recurrent state and restores it as this one's. The
|
||||
* text that comes back is fluent, deterministic and about the wrong conversation, which is
|
||||
* the exact failure the whole tier design is arranged to make impossible.
|
||||
*
|
||||
* Not reachable from the tiers' own drop sink, which erases the index entry through
|
||||
* drop_snapshot instead -- so this never calls back into a record being erased. */
|
||||
ck_by_prefix_.erase(it);
|
||||
}
|
||||
|
||||
int PrefixCache::detach_snapshot(const BlockHash& key) {
|
||||
auto it = ck_by_prefix_.find(key);
|
||||
if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND;
|
||||
if (it->second.off_device) return RAD_OK; /* already theirs */
|
||||
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
|
||||
it->second.slot = -1;
|
||||
it->second.off_device = true;
|
||||
/* NOT SERVABLE FROM HERE ON, which is the same state a reserved-but-unwritten snapshot is in
|
||||
* and is handled by the same branch in lookup(). A hit that reaches this position simply walks
|
||||
* back to an older checkpoint, or to none -- shorter, never wrong. */
|
||||
it->second.valid = false;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int PrefixCache::reattach_snapshot(const BlockHash& key, int32_t slot) {
|
||||
auto it = ck_by_prefix_.find(key);
|
||||
if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND;
|
||||
if (slot < 0) return RAD_E_INVAL;
|
||||
/* A SLOT THIS ENTRY DID NOT ASK FOR IS STILL ITS OWN. The promotion allocated it and filled it
|
||||
* from the tier copy of THIS key's state, so the identity that matters -- which prefix the
|
||||
* bytes describe -- is carried by the key and not by the slot number it happened to get. */
|
||||
it->second.slot = slot;
|
||||
it->second.off_device = false;
|
||||
it->second.valid = true;
|
||||
it->second.used = ++clock_;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool PrefixCache::free_checkpoint_for_restore() {
|
||||
if (!tiers_) return false;
|
||||
const Ckpt* victim = nullptr;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
const Ckpt& c = kvp.second;
|
||||
if (c.off_device || c.slot < 0 || !c.valid) continue;
|
||||
if (victim && c.used >= victim->used) continue;
|
||||
if (std::find(handed_.begin(), handed_.end(), kvp.first) != handed_.end()) continue;
|
||||
if (!tiers_->snapshot_backed(kvp.first)) continue;
|
||||
victim = &c;
|
||||
}
|
||||
if (!victim) return false;
|
||||
const BlockHash vh = victim->prefix;
|
||||
(void)detach_snapshot(vh);
|
||||
tiers_->snapshot_detached(vh);
|
||||
return true;
|
||||
}
|
||||
|
||||
void PrefixCache::drop_snapshot(const BlockHash& key) {
|
||||
auto it = ck_by_prefix_.find(key);
|
||||
if (it == ck_by_prefix_.end()) return;
|
||||
const uint64_t session = it->second.session;
|
||||
/* No release_snapshot on this path: the tiers are the caller and the bytes are already gone.
|
||||
* Telling them to free what they just lost would double-free the arena slot. */
|
||||
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
|
||||
ck_by_prefix_.erase(it);
|
||||
++stats_.ckpt_evictions;
|
||||
auto sit = ck_by_session_.find(session);
|
||||
if (sit == ck_by_session_.end()) return;
|
||||
sit->second.erase(std::remove(sit->second.begin(), sit->second.end(), key), sit->second.end());
|
||||
if (sit->second.empty()) ck_by_session_.erase(sit);
|
||||
}
|
||||
|
||||
int64_t PrefixCache::snapshots_off_device() const {
|
||||
int64_t n = 0;
|
||||
for (const auto& kvp : ck_by_prefix_) if (kvp.second.off_device) ++n;
|
||||
return n;
|
||||
}
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,407 @@
|
||||
/* prefix.h -- prefix caching (spec §7.3). TWO mechanisms, because full attention and linear
|
||||
* attention cannot share one.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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:
|
||||
*
|
||||
* (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.
|
||||
*
|
||||
* (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.
|
||||
*
|
||||
* ============================== WHAT IT COSTS TO HOLD, AND WHEN IT STOPS WORKING ==============
|
||||
*
|
||||
* 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 -- and keep --expert-vs-cache-ratio on the
|
||||
* safe side of 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/kv.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
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. */
|
||||
struct BlockHash {
|
||||
uint64_t hi = 0, lo = 0;
|
||||
bool operator==(const BlockHash& o) const { return hi == o.hi && lo == o.lo; }
|
||||
bool operator!=(const BlockHash& o) const { return !(*this == o); }
|
||||
bool valid() const { return hi != 0 || lo != 0; }
|
||||
std::string str() const;
|
||||
};
|
||||
|
||||
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. */
|
||||
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. */
|
||||
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 split lookup */
|
||||
struct CacheHit {
|
||||
int32_t n_attn_tokens = 0; /* attention KV reused directly, always a whole block multiple */
|
||||
int32_t n_linear_tokens = 0; /* linear state reused; <= n_attn_tokens, a checkpoint multiple */
|
||||
int32_t checkpoint_slot = -1; /* the snapshot holding that state, -1 if none */
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
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. */
|
||||
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. */
|
||||
class GeometricBackoff final : public CheckpointPolicy {
|
||||
public:
|
||||
const char* name() const override { return "geometric-backoff"; }
|
||||
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
|
||||
};
|
||||
|
||||
/* The two obvious ends of the trade, kept so a measurement can be run against them. */
|
||||
class KeepTipOnly final : public CheckpointPolicy {
|
||||
public:
|
||||
const char* name() const override { return "tip-only"; }
|
||||
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
|
||||
};
|
||||
class KeepAll final : public CheckpointPolicy {
|
||||
public:
|
||||
const char* name() const override { return "keep-all"; }
|
||||
void select(const std::vector<int64_t>& positions, std::vector<int64_t>* keep) const override;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
*
|
||||
* `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. */
|
||||
int configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval);
|
||||
bool enabled() const { return enabled_; }
|
||||
int64_t block_size() const { return block_size_; }
|
||||
int64_t checkpoint_interval() const { return interval_; }
|
||||
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. */
|
||||
void set_policy(std::unique_ptr<CheckpointPolicy> p);
|
||||
const CheckpointPolicy& policy() const { return *policy_; }
|
||||
|
||||
/* ---------------- full attention ---------------- */
|
||||
/* Longest cached prefix, in whole blocks, plus the checkpoint that covers the linear state
|
||||
* for a prefix of it. `blocks_out`, when given, receives the block ids per cached group, in
|
||||
* cached_groups() order, ready for KVManager::adopt().
|
||||
*
|
||||
* 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. */
|
||||
CacheHit lookup(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<std::vector<int32_t>>* blocks_out = nullptr) const;
|
||||
|
||||
/* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of
|
||||
* cached_groups()[i]. Takes a KV reference on every newly indexed block. */
|
||||
int insert(uint64_t session,
|
||||
const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
const std::vector<std::vector<int32_t>>& blocks,
|
||||
int64_t n_tokens);
|
||||
|
||||
/* 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. */
|
||||
int64_t evict_lru(int64_t n_entries);
|
||||
/* 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. */
|
||||
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. */
|
||||
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. */
|
||||
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;
|
||||
|
||||
/* ---------------- 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. */
|
||||
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. */
|
||||
/* `chain`, when given, receives every key the walk matched, wherever it is -- what the tiers
|
||||
* need to see whether any of it is still being read off disk (IdleTiers::plan_fetch). */
|
||||
std::vector<BlockHash> restorable_from(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<BlockHash>* chain = nullptr) const;
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
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 device-resident object of
|
||||
* KVManager::checkpoint_bytes(), of which there are --checkpoint-slots IN TOTAL for the whole
|
||||
* server. Eight by default, against the six or seven a single 200K session retains under
|
||||
* geometric backoff -- so a second session evicts the first's snapshots, tip included.
|
||||
*
|
||||
* Tiering the blocks and leaving the snapshot behind therefore gets the trade backwards: it
|
||||
* frees the plentiful resource and holds on to the scarce one. And what the session loses is
|
||||
* not part of its hit, it is ALL of it -- the scheduler clamps reuse to the last checkpoint a
|
||||
* hit can reach, because RadBatch carries one query length for every KV group and the linear
|
||||
* layers cannot be replayed over a longer range than the attention ones (core/sched/
|
||||
* scheduler.cpp, admit_one). A restored session with no reachable snapshot reuses zero tokens
|
||||
* and re-prefills its whole transcript. The blocks without the state are not a partial win;
|
||||
* they are unusable.
|
||||
*
|
||||
* So a snapshot moves with the blocks whose hash it is keyed by, and these calls are the
|
||||
* cache's whole part in that. The bytes are the engine's to move. */
|
||||
|
||||
/* Its bytes are on another tier now: give the device slot back and stop offering it. The index
|
||||
* entry STAYS, because that is what a promotion puts the snapshot back into, and an entry
|
||||
* whose state is not in the pool is exactly the `valid` flag's existing meaning -- lookup
|
||||
* already walks past one and falls back to an older position. */
|
||||
int detach_snapshot(const BlockHash& key);
|
||||
/* And back again, into a slot the caller has already filled. */
|
||||
int reattach_snapshot(const BlockHash& key, int32_t slot);
|
||||
/* A DEVICE CHECKPOINT SLOT FOR A RESTORE. The pool is --checkpoint-slots deep for the whole
|
||||
* server, and it is full whenever as many sessions have run since; a session restored then
|
||||
* would get its blocks back and replay every recurrent layer from an older point, because its
|
||||
* state has nowhere to land. One slot is freed by detaching the least recently used snapshot
|
||||
* the tiers hold a copy of -- which the next restore of THAT session brings back -- and never
|
||||
* one whose only copy is the slot, and never one a lookup has handed out since the step began:
|
||||
* that request reads the slot in this step's forward, and a restore writes it before the
|
||||
* forward runs. True when a slot was freed. */
|
||||
bool free_checkpoint_for_restore();
|
||||
/* A step's admissions begin. The snapshots the last step's lookups handed out have been read
|
||||
* by its forward, which committed before this step was planned. */
|
||||
void begin_step() { handed_.clear(); }
|
||||
/* The tiers lost it -- a capacity drop, a failed promotion, or an entry they were told to
|
||||
* forget. Erase the index entry; there is no device slot to give back. */
|
||||
void drop_snapshot(const BlockHash& key);
|
||||
/* How many snapshots the index holds whose bytes the tiers have. Reported rather than derived
|
||||
* because it is the number that says whether hybrid tiering is doing anything at all: a
|
||||
* session can move its whole chain off the device and still be re-prefilling its linear
|
||||
* layers from zero on every hit, and nothing else distinguishes the two. */
|
||||
int64_t snapshots_off_device() const;
|
||||
/* ---------------- linear checkpoints ---------------- */
|
||||
/* The next position strictly after `pos` at which the scheduler must split a chunk so that a
|
||||
* checkpoint lands on a boundary (spec §7.1, §7.3). */
|
||||
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, never evicting a session tip. RAD_E_FULL when even that is not enough. */
|
||||
int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix,
|
||||
int32_t* slot_out);
|
||||
/* The state named by `prefix` is now IN its slot. Until this is called the reservation is only
|
||||
* a promise and lookup() will not offer it -- see Ckpt::valid. */
|
||||
void commit_checkpoint(const BlockHash& prefix);
|
||||
/* 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. */
|
||||
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. */
|
||||
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. */
|
||||
int64_t drops = 0;
|
||||
};
|
||||
const Stats& stats() const { return stats_; }
|
||||
|
||||
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. */
|
||||
bool in_lru = false;
|
||||
bool drop_wait = false; /* in drop_wait_: clean, but a sequence still reads it */
|
||||
std::list<BlockHash>::iterator lru;
|
||||
};
|
||||
struct Ckpt {
|
||||
uint64_t session = 0;
|
||||
int64_t pos = 0;
|
||||
BlockHash prefix;
|
||||
int32_t slot = -1;
|
||||
uint64_t used = 0;
|
||||
/* HAS THE STATE ACTUALLY BEEN WRITTEN INTO THE SLOT YET. reserve_checkpoint runs when the
|
||||
* scheduler PLANS the chunk; the copy happens after the step that computes the state. A
|
||||
* lookup between those two points would hand out a slot holding the previous tenant's
|
||||
* history, which is the exact failure this whole mechanism exists to prevent. */
|
||||
bool valid = false;
|
||||
/* ARE THE BYTES STILL IN THE POOL. The idle tiers move a snapshot along with the blocks
|
||||
* it is keyed by, and `slot` is -1 for the whole time they hold it. Kept as its own flag
|
||||
* rather than inferred from the slot so that the two reasons a snapshot cannot be served
|
||||
* -- not written yet, and not here -- stay distinguishable in a debugger and in a report. */
|
||||
bool off_device = false;
|
||||
};
|
||||
|
||||
std::vector<BlockHash> chain_all(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
int64_t n_blocks) const;
|
||||
void touch(const BlockHash& h) const;
|
||||
/* Retire one snapshot whatever tier holds its bytes: a device slot goes back to the pool, and
|
||||
* tiered bytes go back to the tiers. One place, because three call sites that each remembered
|
||||
* to check `off_device` would be three places to forget. The session index is the caller's,
|
||||
* since every caller is already rebuilding or erasing it. */
|
||||
void retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it);
|
||||
|
||||
KVManager* kv_ = nullptr;
|
||||
IdleTiers* tiers_ = nullptr;
|
||||
bool enabled_ = false;
|
||||
int64_t block_size_ = 0;
|
||||
int64_t interval_ = 0;
|
||||
std::vector<int32_t> groups_; /* paged groups this cache indexes */
|
||||
bool has_linear_ = false;
|
||||
|
||||
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. */
|
||||
std::vector<BlockHash> drop_wait_;
|
||||
std::vector<BlockHash> drop_scratch_;
|
||||
uint64_t frees_seen_ = 0;
|
||||
mutable std::unordered_map<BlockHash, Ckpt, BlockHashHash> ck_by_prefix_;
|
||||
std::unordered_map<uint64_t, std::vector<BlockHash>> ck_by_session_;
|
||||
/* Snapshots lookup handed out since begin_step: not a restore's to take (free_checkpoint_for_restore). */
|
||||
mutable std::vector<BlockHash> handed_;
|
||||
mutable uint64_t clock_ = 0;
|
||||
std::unique_ptr<CheckpointPolicy> policy_;
|
||||
mutable Stats stats_;
|
||||
std::string report_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,536 @@
|
||||
/* sstier.cpp -- see sstier.h. IT HOLDS CONVERSATION CONTENT ON DISK, UNENCRYPTED. */
|
||||
#include "mem/sstier.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <thread>
|
||||
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* The device layer's alignment, not a second opinion about it: every slot, every header region and
|
||||
* every staging buffer here is a multiple of it, which is what keeps every transfer on
|
||||
* DirectFile's aligned fast path and its bounce buffer unallocated. */
|
||||
static constexpr int64_t kAlign = DirectFile::alignment();
|
||||
|
||||
static void* alloc_aligned(int64_t bytes) {
|
||||
void* p = nullptr;
|
||||
if (posix_memalign(&p, (size_t)kAlign, (size_t)align_up(bytes, kAlign)) != 0) return nullptr;
|
||||
return p;
|
||||
}
|
||||
static constexpr uint32_t kMagicBlock = 0x4b4c4252u; /* "RBLK" */
|
||||
static constexpr uint32_t kMagicCkpt = 0x504b4352u; /* "RCKP" */
|
||||
|
||||
struct SSSlotHeader {
|
||||
uint32_t magic;
|
||||
uint32_t n_tokens;
|
||||
uint64_t fingerprint;
|
||||
uint64_t payload_bytes;
|
||||
uint64_t key_hi, key_lo;
|
||||
int64_t pos; /* checkpoint: the token position it restores to; 0 for a block */
|
||||
uint64_t reserved[3];
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ TokenBucket */
|
||||
|
||||
const char* ssd_consumer_name(SSDConsumer c) {
|
||||
switch (c) {
|
||||
case SSDConsumer::PrefixCache: return "prefix-cache";
|
||||
case SSDConsumer::WeightTier: return "weight-tier";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
|
||||
static int64_t now_ns() {
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch()).count();
|
||||
}
|
||||
|
||||
void TokenBucket::configure(int64_t bytes_per_sec, int64_t burst_bytes) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
rate_ = bytes_per_sec > 0 ? bytes_per_sec : 0;
|
||||
burst_ = burst_bytes > 0 ? burst_bytes : rate_;
|
||||
tokens_ = (double)burst_;
|
||||
last_ns_ = now_ns();
|
||||
}
|
||||
|
||||
void TokenBucket::refill_locked() {
|
||||
int64_t t = now_ns();
|
||||
double dt = (double)(t - last_ns_) * 1e-9;
|
||||
last_ns_ = t;
|
||||
tokens_ = std::min((double)burst_, tokens_ + dt * (double)rate_);
|
||||
}
|
||||
|
||||
bool TokenBucket::try_take(int64_t bytes, SSDConsumer who) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
Use& u = use_[(int)who];
|
||||
if (rate_ <= 0) { u.bytes += bytes; ++u.grants; return true; }
|
||||
refill_locked();
|
||||
if (tokens_ < (double)bytes) return false;
|
||||
tokens_ -= (double)bytes;
|
||||
u.bytes += bytes;
|
||||
++u.grants;
|
||||
return true;
|
||||
}
|
||||
|
||||
void TokenBucket::take(int64_t bytes, SSDConsumer who) {
|
||||
int64_t t0 = now_ns();
|
||||
bool waited = false;
|
||||
for (;;) {
|
||||
if (try_take(bytes, who)) break;
|
||||
waited = true;
|
||||
/* Sleep for the deficit rather than spinning. Coarse on purpose: this is a placeholder
|
||||
* and a precise scheduler for a policy nobody has measured would be effort spent on the
|
||||
* wrong thing (spec §19.5). */
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(200));
|
||||
}
|
||||
if (waited) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
++use_[(int)who].waits;
|
||||
use_[(int)who].wait_us += (now_ns() - t0) / 1000;
|
||||
}
|
||||
}
|
||||
|
||||
TokenBucket::Use TokenBucket::use(SSDConsumer c) const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return use_[(int)c];
|
||||
}
|
||||
|
||||
std::string TokenBucket::report() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
std::string s = rate_ > 0
|
||||
? fmt("SSD token bucket: %s/s, burst %s (PLACEHOLDER, spec §19.5)\n",
|
||||
humanb(rate_).c_str(), humanb(burst_).c_str())
|
||||
: std::string("SSD token bucket: off (no measured rate to enforce, spec §19.5)\n");
|
||||
for (int i = 0; i < (int)SSDConsumer::N; ++i)
|
||||
s += fmt(" %-14s %10s in %lld ops, %lld waits totalling %lld ms\n",
|
||||
ssd_consumer_name((SSDConsumer)i), humanb(use_[i].bytes).c_str(),
|
||||
(long long)use_[i].grants, (long long)use_[i].waits,
|
||||
(long long)(use_[i].wait_us / 1000));
|
||||
return s;
|
||||
}
|
||||
|
||||
TokenBucket& rad_ssd_bucket() { static TokenBucket b; return b; }
|
||||
|
||||
/* ------------------------------------------------------------------ SSDTier */
|
||||
|
||||
std::string SSDTier::disclosure(const std::string& dir) {
|
||||
return fmt("SSD prefix tier active at %s.\n"
|
||||
" It stores CONVERSATION CONTENT ON DISK, UNENCRYPTED: the cached KV blocks are a\n"
|
||||
" lossless function of the prompt, and the prompt's token ids are written beside\n"
|
||||
" them so a hit can be verified. Anything that persists across restarts says so\n"
|
||||
" (spec §7.3). Put this directory on storage you are willing to treat as holding\n"
|
||||
" the text itself.\n", dir.c_str());
|
||||
}
|
||||
|
||||
SSDTier::~SSDTier() { close(); }
|
||||
|
||||
static int64_t hdr_region_bytes(int64_t tok_bytes) {
|
||||
return align_up((int64_t)sizeof(SSSlotHeader) + tok_bytes, kAlign);
|
||||
}
|
||||
|
||||
int SSDTier::open_store(Store& s, const std::string& path, int64_t payload, int64_t n_slots,
|
||||
int64_t tok_bytes, bool allow_buffered) {
|
||||
s.payload = payload;
|
||||
s.hdr_bytes = hdr_region_bytes(tok_bytes);
|
||||
s.slot_bytes = s.hdr_bytes + align_up(payload, kAlign);
|
||||
if (n_slots <= 0) return RAD_OK;
|
||||
|
||||
int flags = RAD_DIO_READ | RAD_DIO_WRITE | RAD_DIO_CREATE;
|
||||
if (allow_buffered) flags |= RAD_DIO_ALLOW_BUFFERED;
|
||||
RAD_TRY(s.file.open(path.c_str(), flags));
|
||||
|
||||
/* Size the store up front. DirectFile does not take a size hint and does not need one -- a
|
||||
* write past the end extends the file -- but a store laid out in one ftruncate is one extent
|
||||
* rather than N, which is the difference between a slot read being one seek and being several
|
||||
* once the filesystem has interleaved somebody else's writes between ours. */
|
||||
if (::ftruncate(s.file.fd(), (off_t)(s.slot_bytes * n_slots)) != 0)
|
||||
RAD_WARN("ftruncate %s to %s: %s -- the store will be extended by its writes instead",
|
||||
path.c_str(), humanb(s.slot_bytes * n_slots).c_str(), strerror(errno));
|
||||
|
||||
s.slots.assign((size_t)n_slots, Slot{});
|
||||
s.freelist.resize((size_t)n_slots);
|
||||
for (int64_t i = 0; i < n_slots; ++i) s.freelist[(size_t)i] = (int32_t)(n_slots - 1 - i);
|
||||
s.stage = alloc_aligned(s.slot_bytes);
|
||||
if (!s.stage) return RAD_E_NOMEM;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int SSDTier::open(const SSDTierConfig& cfg) {
|
||||
close();
|
||||
cfg_ = cfg;
|
||||
if (cfg.dir.empty()) { enabled_ = false; return RAD_OK; }
|
||||
if (cfg.block_payload <= 0 && cfg.ckpt_payload <= 0) {
|
||||
RAD_ERR("--prefix-cache-dir is set but neither a block payload nor a checkpoint payload was "
|
||||
"given; there is nothing for the tier to store");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The engine says so at startup. Not behind a verbosity flag. */
|
||||
RAD_WARN("%s", disclosure(cfg.dir).c_str());
|
||||
|
||||
if (::mkdir(cfg.dir.c_str(), 0700) != 0 && errno != EEXIST) {
|
||||
RAD_ERR("cannot create %s: %s", cfg.dir.c_str(), strerror(errno));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
|
||||
RAD_TRY(open_store(blocks_, cfg.dir + "/blocks.bin", cfg.block_payload, cfg.n_block_slots,
|
||||
cfg.block_tokens * (int64_t)sizeof(uint32_t), cfg.allow_buffered));
|
||||
RAD_TRY(open_store(ckpts_, cfg.dir + "/ckpts.bin", cfg.ckpt_payload, cfg.n_ckpt_slots,
|
||||
0, cfg.allow_buffered));
|
||||
|
||||
enabled_ = true;
|
||||
|
||||
if (cfg.persistent) {
|
||||
/* Rebuild the index by scanning the slot headers rather than persisting a separate index
|
||||
* file. One sequential pass at startup, and no way for an index to disagree with the data
|
||||
* it names -- which is the failure a separate index file has and which produces exactly
|
||||
* the "serves one caller another caller's context" outcome this tier verifies against. */
|
||||
const int64_t nb = scan_store(blocks_, kMagicBlock);
|
||||
if (nb < 0) return (int)nb;
|
||||
const int64_t nc = scan_store(ckpts_, kMagicCkpt);
|
||||
if (nc < 0) return (int)nc;
|
||||
RAD_INFO("SSD tier: recovered %lld block and %lld checkpoint slots from %s",
|
||||
(long long)nb, (long long)nc, cfg.dir.c_str());
|
||||
} else {
|
||||
/* Not persistent means the store must not outlive the process, and unlinking now rather
|
||||
* than at exit means it also does not outlive a crash. The descriptors stay valid. */
|
||||
::unlink((cfg.dir + "/blocks.bin").c_str());
|
||||
::unlink((cfg.dir + "/ckpts.bin").c_str());
|
||||
}
|
||||
|
||||
report_ = fmt("SSD tier %s: %lld block slots x %s, %lld checkpoint slots x %s, %s%s\n",
|
||||
cfg.dir.c_str(),
|
||||
(long long)cfg.n_block_slots, humanb(blocks_.slot_bytes).c_str(),
|
||||
(long long)cfg.n_ckpt_slots, humanb(ckpts_.slot_bytes).c_str(),
|
||||
blocks_.file.direct() ? "O_DIRECT" : "BUFFERED",
|
||||
cfg.persistent ? ", persistent" : ", volatile");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void SSDTier::close() {
|
||||
for (Store* s : { &blocks_, &ckpts_ }) {
|
||||
s->file.close();
|
||||
if (s->stage) { ::free(s->stage); s->stage = nullptr; }
|
||||
s->slots.clear(); s->index.clear(); s->freelist.clear();
|
||||
}
|
||||
enabled_ = false;
|
||||
}
|
||||
|
||||
std::string SSDTier::report() const {
|
||||
std::string s = report_;
|
||||
s += fmt(" %lld hits, %lld misses, %lld verify misses, %lld evictions; "
|
||||
"%s read, %s written\n",
|
||||
(long long)stats_.hits, (long long)stats_.misses, (long long)stats_.verify_misses,
|
||||
(long long)stats_.evictions, humanb(stats_.bytes_read).c_str(),
|
||||
humanb(stats_.bytes_written).c_str());
|
||||
s += rad_ssd_bucket().report();
|
||||
return s;
|
||||
}
|
||||
|
||||
void SSDTier::lru_unlink(Store& s, int32_t i) {
|
||||
Slot& x = s.slots[(size_t)i];
|
||||
if (x.prev >= 0) s.slots[(size_t)x.prev].next = x.next; else s.lru_head = x.next;
|
||||
if (x.next >= 0) s.slots[(size_t)x.next].prev = x.prev; else s.lru_tail = x.prev;
|
||||
x.prev = x.next = -1;
|
||||
}
|
||||
|
||||
void SSDTier::lru_push(Store& s, int32_t i) {
|
||||
Slot& x = s.slots[(size_t)i];
|
||||
x.prev = s.lru_tail;
|
||||
x.next = -1;
|
||||
if (s.lru_tail >= 0) s.slots[(size_t)s.lru_tail].next = i; else s.lru_head = i;
|
||||
s.lru_tail = i;
|
||||
}
|
||||
|
||||
/* THE HEADERS ARE READ MANY AT A TIME. Each is one 4 KiB direct read at its own slot, so a single
|
||||
* reader waits one device round trip a slot -- some tens of microseconds, over the millions of
|
||||
* slots a store sized in hundreds of GiB holds, which is over a minute of every start. The device
|
||||
* serves dozens of such reads at once at little more latency than one, so the scan keeps
|
||||
* kScanDepth in flight: one thread each, over its own contiguous run of slots with its own staging
|
||||
* page. The threads only record each slot's verdict in the slot itself; the index, the order and
|
||||
* the free list are built afterwards in one descending pass, which is the order a single
|
||||
* sequential reader would produce. */
|
||||
static constexpr int64_t kScanDepth = 64;
|
||||
|
||||
int64_t SSDTier::scan_store(Store& s, uint32_t magic) {
|
||||
if (s.slots.empty()) return 0;
|
||||
s.index.clear();
|
||||
s.freelist.clear();
|
||||
s.lru_head = s.lru_tail = -1;
|
||||
for (Slot& x : s.slots) { x.used = 0; x.prev = x.next = -1; }
|
||||
|
||||
const int64_t n = (int64_t)s.slots.size();
|
||||
const int64_t nt = std::min(kScanDepth, n);
|
||||
std::atomic<bool> nomem{false};
|
||||
std::vector<std::thread> th;
|
||||
th.reserve((size_t)nt);
|
||||
for (int64_t t = 0; t < nt; ++t)
|
||||
th.emplace_back([&, t] {
|
||||
void* stage = alloc_aligned(s.hdr_bytes);
|
||||
if (!stage) { nomem.store(true); return; }
|
||||
for (int64_t i = n * t / nt; i < n * (t + 1) / nt; ++i) {
|
||||
if (s.file.read_at(stage, i * s.slot_bytes, s.hdr_bytes) < 0) continue;
|
||||
const SSSlotHeader* h = (const SSSlotHeader*)stage;
|
||||
if (h->magic != magic || h->fingerprint != cfg_.fingerprint
|
||||
|| h->payload_bytes != (uint64_t)s.payload) continue;
|
||||
Slot& x = s.slots[(size_t)i];
|
||||
x.key.hi = h->key_hi;
|
||||
x.key.lo = h->key_lo;
|
||||
x.pos = h->pos;
|
||||
x.used = 1;
|
||||
}
|
||||
std::free(stage);
|
||||
});
|
||||
for (std::thread& x : th) x.join();
|
||||
if (nomem.load()) {
|
||||
for (Slot& x : s.slots) x.used = 0;
|
||||
RAD_ERR("SSD tier: no staging page for the header scan");
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
int64_t live = 0;
|
||||
for (const Slot& x : s.slots) live += x.used;
|
||||
s.index.reserve((size_t)live);
|
||||
s.freelist.reserve((size_t)(n - live));
|
||||
for (int64_t i = n - 1; i >= 0; --i) {
|
||||
if (!s.slots[(size_t)i].used) { s.freelist.push_back((int32_t)i); continue; }
|
||||
lru_push(s, (int32_t)i);
|
||||
s.index[s.slots[(size_t)i].key] = (int32_t)i;
|
||||
}
|
||||
return live;
|
||||
}
|
||||
|
||||
int SSDTier::claim(Store& s, const BlockHash& key, int32_t* out) {
|
||||
auto it = s.index.find(key);
|
||||
if (it != s.index.end()) { *out = it->second; return RAD_OK; }
|
||||
if (!s.freelist.empty()) { *out = s.freelist.back(); s.freelist.pop_back(); return RAD_OK; }
|
||||
|
||||
/* LRU. Evicting the DEEPEST entry first would be better -- a deeper block chains more tokens,
|
||||
* is less shareable, and losing it only shortens the usable prefix, whereas losing a shallow
|
||||
* one strands everything above it -- but depth is not a property this tier is told. Straight
|
||||
* LRU until the caller carries depth in. */
|
||||
const int32_t victim = s.lru_head;
|
||||
if (victim < 0) return RAD_E_FULL;
|
||||
lru_unlink(s, victim);
|
||||
s.index.erase(s.slots[(size_t)victim].key);
|
||||
s.slots[(size_t)victim].used = 0;
|
||||
++stats_.evictions;
|
||||
*out = victim;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int SSDTier::put(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
|
||||
const int32_t* toks, int32_t n_toks, const void* payload, int64_t bytes) {
|
||||
if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED;
|
||||
if (bytes != s.payload) return RAD_E_SHAPE;
|
||||
if ((int64_t)sizeof(SSSlotHeader) + (int64_t)n_toks * 4 > s.hdr_bytes) return RAD_E_SHAPE;
|
||||
|
||||
int32_t slot = -1;
|
||||
RAD_TRY(claim(s, key, &slot));
|
||||
const int64_t base = (int64_t)slot * s.slot_bytes;
|
||||
|
||||
std::memset(s.stage, 0, (size_t)s.slot_bytes);
|
||||
SSSlotHeader* h = (SSSlotHeader*)s.stage;
|
||||
h->magic = magic;
|
||||
h->n_tokens = (uint32_t)n_toks;
|
||||
h->fingerprint = cfg_.fingerprint;
|
||||
h->payload_bytes = (uint64_t)bytes;
|
||||
h->key_hi = key.hi; h->key_lo = key.lo;
|
||||
h->pos = pos;
|
||||
if (n_toks > 0) std::memcpy((char*)s.stage + sizeof(SSSlotHeader), toks, (size_t)n_toks * 4);
|
||||
std::memcpy((char*)s.stage + s.hdr_bytes, payload, (size_t)bytes);
|
||||
|
||||
rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache);
|
||||
|
||||
/* Payload first, header last. Written front to back, a short write would leave the header
|
||||
* COMPLETE and the payload truncated, so the slot verifies and the engine loads whatever was
|
||||
* in the file underneath it -- which is the worst failure this tier can have.
|
||||
*
|
||||
* A WRITE THAT FAILS GIVES THE SLOT BACK. claim() took it off the free list or out of the
|
||||
* index, so returning here without that leaves a slot no list names and the store one slot
|
||||
* smaller for good. Whatever the slot held before is no longer trustworthy either -- the
|
||||
* payload may be half overwritten under a header that still verifies -- so the key comes out
|
||||
* of the index and the header is cleared on a best-effort basis, which keeps a persistent
|
||||
* store from indexing it again at the next start. */
|
||||
int wst = s.file.write_at((char*)s.stage + s.hdr_bytes, base + s.hdr_bytes,
|
||||
s.slot_bytes - s.hdr_bytes);
|
||||
if (wst >= 0) wst = s.file.write_at(s.stage, base, s.hdr_bytes);
|
||||
if (wst < 0) {
|
||||
auto it = s.index.find(key);
|
||||
if (it != s.index.end() && it->second == slot) s.index.erase(it);
|
||||
if (s.slots[(size_t)slot].used) lru_unlink(s, slot);
|
||||
s.slots[(size_t)slot].used = 0;
|
||||
s.freelist.push_back(slot);
|
||||
std::memset(s.stage, 0, (size_t)s.hdr_bytes);
|
||||
(void)s.file.write_at(s.stage, base, s.hdr_bytes);
|
||||
return wst;
|
||||
}
|
||||
|
||||
if (s.slots[(size_t)slot].used) lru_unlink(s, slot);
|
||||
s.slots[(size_t)slot].key = key;
|
||||
s.slots[(size_t)slot].used = 1;
|
||||
s.slots[(size_t)slot].pos = pos;
|
||||
lru_push(s, slot);
|
||||
s.index[key] = slot;
|
||||
++stats_.writes;
|
||||
stats_.bytes_written += s.slot_bytes;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int SSDTier::get(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
|
||||
const int32_t* toks, int32_t n_toks, void* payload, int64_t bytes) {
|
||||
if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED;
|
||||
if (bytes != s.payload) return RAD_E_SHAPE;
|
||||
auto it = s.index.find(key);
|
||||
if (it == s.index.end()) { ++stats_.misses; return RAD_E_NOTFOUND; }
|
||||
const int32_t slot = it->second;
|
||||
const int64_t base = (int64_t)slot * s.slot_bytes;
|
||||
|
||||
rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache);
|
||||
RAD_TRY(s.file.read_at(s.stage, base, s.slot_bytes));
|
||||
++stats_.reads;
|
||||
stats_.bytes_read += s.slot_bytes;
|
||||
|
||||
if (!header_ok(s, s.stage, magic, key, pos, toks, n_toks, bytes)) {
|
||||
/* Drop it rather than leaving it to fail every future probe: without this a single bad
|
||||
* slot poisons its prefix permanently. */
|
||||
forget_slot(s, slot);
|
||||
++stats_.verify_misses;
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
std::memcpy(payload, (const char*)s.stage + s.hdr_bytes, (size_t)bytes);
|
||||
lru_unlink(s, slot);
|
||||
lru_push(s, slot);
|
||||
++stats_.hits;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Belt and braces on top of the index: verify the header AND the token ids. A store that survives
|
||||
* a restart, a model change or a layout change would otherwise serve one caller another caller's
|
||||
* context, and that is not a failure anybody would ever diagnose. */
|
||||
bool SSDTier::header_ok(const Store& s, const void* stage, uint32_t magic, const BlockHash& key,
|
||||
int64_t pos, const int32_t* toks, int32_t n_toks, int64_t bytes) const {
|
||||
(void)s;
|
||||
const SSSlotHeader* h = (const SSSlotHeader*)stage;
|
||||
bool ok = h->magic == magic && h->fingerprint == cfg_.fingerprint
|
||||
&& h->key_hi == key.hi && h->key_lo == key.lo
|
||||
&& h->payload_bytes == (uint64_t)bytes && h->pos == pos
|
||||
&& h->n_tokens == (uint32_t)n_toks;
|
||||
if (ok && n_toks > 0)
|
||||
ok = std::memcmp((const char*)stage + sizeof(SSSlotHeader), toks, (size_t)n_toks * 4) == 0;
|
||||
return ok;
|
||||
}
|
||||
|
||||
void SSDTier::forget_slot(Store& s, int32_t slot) {
|
||||
auto it = s.index.find(s.slots[(size_t)slot].key);
|
||||
if (it != s.index.end() && it->second == slot) s.index.erase(it);
|
||||
if (s.slots[(size_t)slot].used) lru_unlink(s, slot);
|
||||
s.slots[(size_t)slot].used = 0;
|
||||
s.freelist.push_back(slot);
|
||||
}
|
||||
|
||||
/* READS OUTSTANDING AT ONCE. An NVMe drive reading tens-of-kilobyte extents at random reaches its
|
||||
* bandwidth only with many requests in flight; a thread each is the simplest way to have them, and
|
||||
* every thread has an aligned staging buffer of its own. */
|
||||
static constexpr int kReaders = 16;
|
||||
|
||||
int SSDTier::get_blocks(const BlockHash* keys, int64_t n, void* const* payloads, int64_t bytes,
|
||||
char* ok) {
|
||||
std::lock_guard<std::mutex> lk(io_mu_);
|
||||
Store& s = blocks_;
|
||||
for (int64_t i = 0; i < n; ++i) ok[i] = 0;
|
||||
if (!enabled_ || s.slots.empty()) return RAD_E_UNSUPPORTED;
|
||||
if (bytes != s.payload) return RAD_E_SHAPE;
|
||||
|
||||
std::vector<int32_t> slot((size_t)n, -1);
|
||||
int64_t found = 0;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
auto it = s.index.find(keys[i]);
|
||||
if (it == s.index.end()) { ++stats_.misses; continue; }
|
||||
slot[(size_t)i] = it->second;
|
||||
++found;
|
||||
}
|
||||
if (found == 0) return RAD_OK;
|
||||
|
||||
/* The reads, and nothing that touches the index or the order: those are settled after, on this
|
||||
* thread. 1 read and verified, 2 read and not the key asked for, negative a failed read. */
|
||||
std::vector<int> st((size_t)n, 0);
|
||||
std::atomic<int64_t> next{0};
|
||||
auto reader = [&](void* stage) {
|
||||
for (int64_t i; (i = next.fetch_add(1, std::memory_order_relaxed)) < n;) {
|
||||
if (slot[(size_t)i] < 0) continue;
|
||||
rad_ssd_bucket().take(s.slot_bytes, SSDConsumer::PrefixCache);
|
||||
const int r = s.file.read_at(stage, (int64_t)slot[(size_t)i] * s.slot_bytes,
|
||||
s.slot_bytes);
|
||||
if (r < 0) { st[(size_t)i] = r; continue; }
|
||||
if (!header_ok(s, stage, kMagicBlock, keys[i], 0, nullptr, 0, bytes)) {
|
||||
st[(size_t)i] = 2;
|
||||
continue;
|
||||
}
|
||||
std::memcpy(payloads[i], (const char*)stage + s.hdr_bytes, (size_t)bytes);
|
||||
st[(size_t)i] = 1;
|
||||
}
|
||||
};
|
||||
const int nt = (int)std::min<int64_t>(kReaders, found);
|
||||
std::vector<void*> stages;
|
||||
for (int t = 1; t < nt; ++t) {
|
||||
void* p = alloc_aligned(s.slot_bytes);
|
||||
if (!p) break;
|
||||
stages.push_back(p);
|
||||
}
|
||||
std::vector<std::thread> th;
|
||||
th.reserve(stages.size());
|
||||
for (void* p : stages) th.emplace_back(reader, p);
|
||||
reader(s.stage);
|
||||
for (std::thread& t : th) t.join();
|
||||
for (void* p : stages) ::free(p);
|
||||
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int32_t sl = slot[(size_t)i];
|
||||
if (sl < 0 || st[(size_t)i] < 0) continue;
|
||||
++stats_.reads;
|
||||
stats_.bytes_read += s.slot_bytes;
|
||||
if (st[(size_t)i] == 2) {
|
||||
forget_slot(s, sl);
|
||||
++stats_.verify_misses;
|
||||
continue;
|
||||
}
|
||||
lru_unlink(s, sl);
|
||||
lru_push(s, sl);
|
||||
++stats_.hits;
|
||||
ok[i] = 1;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ONE CALLER AT A TIME. Every call is the KV tiers' IO thread today, but a store is one staging
|
||||
* buffer, one slot table and one index, and nothing about the interface says who may call it. */
|
||||
int SSDTier::put_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
|
||||
const void* payload, int64_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(io_mu_);
|
||||
return put(blocks_, kMagicBlock, key, 0, toks, n_toks, payload, bytes);
|
||||
}
|
||||
int SSDTier::get_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
|
||||
void* payload, int64_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(io_mu_);
|
||||
return get(blocks_, kMagicBlock, key, 0, toks, n_toks, payload, bytes);
|
||||
}
|
||||
int SSDTier::put_checkpoint(const BlockHash& key, int64_t pos, const void* payload, int64_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(io_mu_);
|
||||
return put(ckpts_, kMagicCkpt, key, pos, nullptr, 0, payload, bytes);
|
||||
}
|
||||
int SSDTier::get_checkpoint(const BlockHash& key, int64_t pos, void* payload, int64_t bytes) {
|
||||
std::lock_guard<std::mutex> lk(io_mu_);
|
||||
return get(ckpts_, kMagicCkpt, key, pos, nullptr, 0, payload, bytes);
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,181 @@
|
||||
/* sstier.h -- the optional SSD tier for served attention state and linear checkpoints alike, so
|
||||
* an agent session does not re-prefill its whole transcript every turn (spec §7.3).
|
||||
*
|
||||
* ============================== IT HOLDS CONVERSATION CONTENT ON DISK, UNENCRYPTED ==============
|
||||
* A KV block IS the prompt: the token ids are stored beside it so a hit can be verified, and the
|
||||
* cached tensors are a lossless function of the text. Anything that persists it across restarts
|
||||
* says so, and this engine says so at startup whenever --prefix-cache-dir is set. There is no
|
||||
* encryption option, no obfuscation, and no claim of one; if the content is sensitive the
|
||||
* directory must be on storage the operator is willing to treat as sensitive.
|
||||
* ================================================================================================
|
||||
*
|
||||
* O_DIRECT, same as the weight tier. Going through the page cache would evict the weight tier's own
|
||||
* file mappings, which is paid for in decode and would never show up as a *cache* problem. O_DIRECT
|
||||
* wants offsets, lengths and buffers all on the logical block size, so every slot and every
|
||||
* sub-region here is a multiple of it and there is no unaligned tail to handle.
|
||||
*
|
||||
* Spec §19.5 records that prefix-cache and weight-tier contention on one SSD has NO PLAN. The
|
||||
* TokenBucket below is a placeholder for a measured policy, and it is labelled as one: it is a
|
||||
* shared byte budget between the two consumers, which at least makes the contention visible and
|
||||
* boundable instead of invisible. What the right split is, or whether a rate limit is even the
|
||||
* right shape of answer rather than a priority queue, is a measurement nobody has taken.
|
||||
*/
|
||||
#pragma once
|
||||
#include "device/directio.h"
|
||||
#include "mem/prefix.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* The O_DIRECT file is the device layer's rad::DirectFile (core/device/directio.h). Every extent
|
||||
* this tier reads or writes is a whole slot or a whole aligned header region, so every transfer
|
||||
* lands on its fast path and its bounce buffer is never allocated -- which is the property worth
|
||||
* stating, since the bounce exists for callers reading a header or a file tail and one on this
|
||||
* path would mean a slot geometry bug rather than a performance problem. */
|
||||
|
||||
/* ------------------------------------------------------------------ the shared rate limiter */
|
||||
enum class SSDConsumer { PrefixCache = 0, WeightTier = 1, N = 2 };
|
||||
const char* ssd_consumer_name(SSDConsumer c);
|
||||
|
||||
/* PLACEHOLDER FOR A MEASURED POLICY (spec §19.5).
|
||||
*
|
||||
* Both the prefix cache and the weight tier want O_DIRECT bandwidth and under load they fight. A
|
||||
* token bucket is the simplest thing that bounds the fight: one shared byte budget, refilled at a
|
||||
* stated rate, drawn on by both. What it does NOT do is decide who should win, and that is the
|
||||
* actual open question -- a weight-tier read blocks a layer that is about to execute, while a
|
||||
* prefix-cache read only makes a prefill shorter, so a priority scheme is probably the right shape
|
||||
* and a flat rate limit certainly is not. Replace this once there is a workload to measure
|
||||
* against; the per-consumer counters exist so that measurement has something to read. */
|
||||
class TokenBucket {
|
||||
public:
|
||||
/* 0 bytes_per_sec disables the limiter entirely, which is the default: an unmeasured rate
|
||||
* limit that throttles a machine nobody profiled is worse than none. */
|
||||
void configure(int64_t bytes_per_sec, int64_t burst_bytes);
|
||||
bool enabled() const { return rate_ > 0; }
|
||||
|
||||
bool try_take(int64_t bytes, SSDConsumer who); /* non-blocking */
|
||||
void take(int64_t bytes, SSDConsumer who); /* sleeps until the budget allows */
|
||||
|
||||
struct Use { int64_t bytes = 0; int64_t grants = 0; int64_t waits = 0; int64_t wait_us = 0; };
|
||||
Use use(SSDConsumer c) const;
|
||||
std::string report() const;
|
||||
|
||||
private:
|
||||
void refill_locked();
|
||||
|
||||
mutable std::mutex mu_;
|
||||
int64_t rate_ = 0; /* bytes per second */
|
||||
int64_t burst_ = 0;
|
||||
double tokens_ = 0;
|
||||
int64_t last_ns_ = 0;
|
||||
Use use_[(int)SSDConsumer::N];
|
||||
};
|
||||
|
||||
/* The one bucket both consumers share. The weight tier (core/place/) draws on the same object;
|
||||
* that is the entire point of it living here rather than inside either one. */
|
||||
TokenBucket& rad_ssd_bucket();
|
||||
|
||||
/* ------------------------------------------------------------------ the tier */
|
||||
struct SSDTierConfig {
|
||||
std::string dir; /* Config::prefix_cache_dir */
|
||||
int64_t block_payload = 0; /* bytes one cached attention block occupies, all groups */
|
||||
int64_t block_tokens = 0; /* the attention block size, for the verify */
|
||||
int64_t ckpt_payload = 0; /* KVManager::checkpoint_bytes() */
|
||||
/* Slot counts are STATED, not derived from statvfs. A tier that sizes itself from the free
|
||||
* space it happens to see at startup is a tier whose capacity changes when somebody untars
|
||||
* something, and §6's rule is that budgets do not move on their own. */
|
||||
int64_t n_block_slots = 0;
|
||||
int64_t n_ckpt_slots = 0;
|
||||
uint64_t fingerprint = 0; /* model + layout identity; a mismatch invalidates the store */
|
||||
bool persistent = false; /* keep the files across restarts */
|
||||
/* Passes RAD_DIO_ALLOW_BUFFERED. Off by default: the device layer REFUSES a filesystem
|
||||
* without O_DIRECT rather than downgrading it, because a silent buffered fallback costs the
|
||||
* weight tier its own page cache and shows up only as a decode regression nobody can
|
||||
* attribute. The flag is for tests, which run on whatever /tmp happens to be. */
|
||||
bool allow_buffered = false;
|
||||
};
|
||||
|
||||
class SSDTier {
|
||||
public:
|
||||
~SSDTier();
|
||||
int open(const SSDTierConfig& cfg);
|
||||
void close();
|
||||
bool enabled() const { return enabled_; }
|
||||
|
||||
/* The line the engine prints at startup when the flag is on. Not optional. */
|
||||
static std::string disclosure(const std::string& dir);
|
||||
std::string report() const;
|
||||
|
||||
/* Attention blocks. `toks` is the block's token ids: they are stored in the slot header and
|
||||
* memcmp'd on the way back in, so a hash collision is a miss and never a wrong answer. */
|
||||
int put_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
|
||||
const void* payload, int64_t bytes);
|
||||
int get_block(const BlockHash& key, const int32_t* toks, int32_t n_toks,
|
||||
void* payload, int64_t bytes);
|
||||
/* MANY BLOCKS AT ONCE, READ IN PARALLEL. A conversation coming back off disk is thousands of
|
||||
* entries of tens of kilobytes each, and read one at a time they keep the drive at a queue
|
||||
* depth of one -- a fraction of what it delivers with dozens of reads outstanding. `ok[i]` is
|
||||
* whether block i was found, read and verified into `payloads[i]`; one that was not is a miss
|
||||
* exactly as get_block's would be. Blocks stored with no token ids only. */
|
||||
int get_blocks(const BlockHash* keys, int64_t n, void* const* payloads, int64_t bytes,
|
||||
char* ok);
|
||||
|
||||
/* Linear-state checkpoints. Keyed by the chained block hash at the checkpoint position, which
|
||||
* is exactly what PrefixCache::reserve_checkpoint keys them by in VRAM. */
|
||||
int put_checkpoint(const BlockHash& key, int64_t pos, const void* payload, int64_t bytes);
|
||||
int get_checkpoint(const BlockHash& key, int64_t pos, void* payload, int64_t bytes);
|
||||
|
||||
struct Stats {
|
||||
int64_t reads = 0, writes = 0, hits = 0, misses = 0, verify_misses = 0, evictions = 0;
|
||||
int64_t bytes_read = 0, bytes_written = 0;
|
||||
};
|
||||
const Stats& stats() const { return stats_; }
|
||||
|
||||
private:
|
||||
/* `prev`/`next` link the used slots from least to most recently used, so a full store finds
|
||||
* the one to give up without a walk. A walk would be over every slot of a store sized in the
|
||||
* millions, once per write, on the thread that has to keep up with the host tier's copies. */
|
||||
struct Slot { BlockHash key; int32_t used = 0; int64_t pos = 0; int32_t prev = -1, next = -1; };
|
||||
struct Store {
|
||||
DirectFile file;
|
||||
int64_t slot_bytes = 0;
|
||||
int64_t hdr_bytes = 0; /* header + token ids, padded */
|
||||
int64_t payload = 0;
|
||||
std::vector<Slot> slots;
|
||||
std::unordered_map<BlockHash, int32_t, BlockHashHash> index;
|
||||
std::vector<int32_t> freelist;
|
||||
int32_t lru_head = -1, lru_tail = -1; /* least and most recently used */
|
||||
void* stage = nullptr;
|
||||
};
|
||||
/* A used slot leaves the order; a slot becomes the most recently used. */
|
||||
static void lru_unlink(Store& s, int32_t i);
|
||||
static void lru_push(Store& s, int32_t i);
|
||||
|
||||
int open_store(Store& s, const std::string& path, int64_t payload, int64_t n_slots,
|
||||
int64_t tok_bytes, bool allow_buffered);
|
||||
int64_t scan_store(Store& s, uint32_t magic);
|
||||
int claim(Store& s, const BlockHash& key, int32_t* out);
|
||||
int put(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
|
||||
const int32_t* toks, int32_t n_toks, const void* payload, int64_t bytes);
|
||||
int get(Store& s, uint32_t magic, const BlockHash& key, int64_t pos,
|
||||
const int32_t* toks, int32_t n_toks, void* payload, int64_t bytes);
|
||||
/* Is the slot read into `stage` the one asked for: this store, this model, this key. */
|
||||
bool header_ok(const Store& s, const void* stage, uint32_t magic, const BlockHash& key,
|
||||
int64_t pos, const int32_t* toks, int32_t n_toks, int64_t bytes) const;
|
||||
/* A slot whose bytes are not what the index says: out of the index and the order, and free. */
|
||||
static void forget_slot(Store& s, int32_t slot);
|
||||
|
||||
SSDTierConfig cfg_;
|
||||
std::mutex io_mu_;
|
||||
Store blocks_, ckpts_;
|
||||
bool enabled_ = false;
|
||||
Stats stats_;
|
||||
std::string report_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,329 @@
|
||||
/* 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. */
|
||||
#include "mem/vram_budget.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
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. */
|
||||
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. */
|
||||
int64_t to_mib_up(int64_t bytes) { return bytes > 0 ? (bytes + kMiB - 1) / kMiB : 0; }
|
||||
} /* namespace */
|
||||
|
||||
int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out) {
|
||||
VramBudget b;
|
||||
if (per_rank.empty()) { if (out) *out = b; return RAD_OK; }
|
||||
|
||||
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is applied to 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. */
|
||||
b.capacity = per_rank[0].capacity;
|
||||
int64_t freeb = per_rank[0].free;
|
||||
int64_t layer_max = 0;
|
||||
for (const VramFacts& f : per_rank) {
|
||||
b.capacity = std::min(b.capacity, f.capacity);
|
||||
freeb = std::min(freeb, f.free);
|
||||
b.arena = std::max(b.arena, f.arena);
|
||||
b.kv_ceiling = std::max(b.kv_ceiling, f.kv_ceiling);
|
||||
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);
|
||||
}
|
||||
b.headroom = std::max<int64_t>(cfg.gpu_headroom_mib, 0) * kMiB;
|
||||
int64_t host_reserve = 0;
|
||||
for (const VramFacts& f : per_rank) host_reserve = std::max(host_reserve, f.host_reserve);
|
||||
const bool shared = host_reserve > b.headroom;
|
||||
if (shared) b.headroom = host_reserve;
|
||||
|
||||
/* A host backend has no VRAM to speak of and reports none; there is nothing here to resolve
|
||||
* and inventing a capacity would be exactly the inference §6 forbids. */
|
||||
if (b.capacity <= 0) {
|
||||
b.weights = cfg.vram_weights_mib * kMiB;
|
||||
b.kv = cfg.vram_kv_mib * kMiB;
|
||||
if (out) *out = b;
|
||||
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. */
|
||||
b.already_held = std::max<int64_t>(b.capacity - freeb, 0);
|
||||
|
||||
const bool want_w = cfg.vram_weights_mib <= 0;
|
||||
const bool want_kv = cfg.vram_kv_mib <= 0;
|
||||
b.derived_weights = want_w;
|
||||
b.derived_kv = want_kv;
|
||||
|
||||
/* What is left after the terms nobody gets to spend. */
|
||||
int64_t fixed = b.already_held + b.headroom + b.arena;
|
||||
if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */
|
||||
if (!want_kv) fixed += cfg.vram_kv_mib * kMiB;
|
||||
b.claimable = b.capacity - fixed;
|
||||
|
||||
if (b.claimable < 0) {
|
||||
b.report = fmt(
|
||||
"VRAM does not cover the fixed costs before a single pool is sized:\n"
|
||||
" card total %10s\n"
|
||||
" already held %10s (driver context, code objects, anything else on the card)\n"
|
||||
" --gpu-headroom-mib %10s\n"
|
||||
" activation arena %10s (buffer plan + kernel scratch)\n"
|
||||
"%s%s"
|
||||
" ------------------------------\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.headroom).c_str(), humanb(b.arena).c_str(),
|
||||
want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str()).c_str(),
|
||||
want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n",
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str()).c_str(),
|
||||
humanb(-b.claimable).c_str());
|
||||
RAD_ERR("%s", b.report.c_str());
|
||||
if (out) *out = b;
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
b.weights = want_w ? 0 : cfg.vram_weights_mib * kMiB;
|
||||
b.kv = want_kv ? 0 : cfg.vram_kv_mib * kMiB;
|
||||
|
||||
/* ---- the static weights come off the top ------------------------------------------------
|
||||
*
|
||||
* They are a floor and not a share. Only a DERIVED weight budget pays them here: an operator
|
||||
* who stated --vram-weights-mib has already decided what the weights get, and second-guessing
|
||||
* that is the re-optimisation §6 forbids. */
|
||||
if (want_w) {
|
||||
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. */
|
||||
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());
|
||||
}
|
||||
}
|
||||
b.elastic = want_w ? b.claimable - b.statics : b.claimable;
|
||||
if (b.elastic < 0) b.elastic = 0;
|
||||
|
||||
/* ---- and only what is left is what the ratio divides ------------------------------------- */
|
||||
if (want_w && want_kv) {
|
||||
const double r = (cfg.expert_cache_ratio > 0.0 && cfg.expert_cache_ratio < 1.0)
|
||||
? cfg.expert_cache_ratio : 0.75;
|
||||
int64_t kv = (int64_t)((double)b.elastic * (1.0 - r));
|
||||
int64_t exp = b.elastic - kv;
|
||||
|
||||
/* BOTH SIDES ARE CAPPED AT WHAT THEY COULD USE, AND THE SLACK CROSSES OVER. A paged cache
|
||||
* cannot address past max_seqs x max_ctx tokens and an expert plane that is entirely
|
||||
* resident has no use for another byte -- so a share above either ceiling is memory
|
||||
* nothing will ever touch. Cap, then hand the remainder to whichever side is still short,
|
||||
* then stop: what neither can take is genuinely unusable and is reported as such rather
|
||||
* than allocated into a pool that reports itself three quarters empty. */
|
||||
if (b.kv_ceiling > 0 && kv > b.kv_ceiling) kv = b.kv_ceiling;
|
||||
/* ZERO EXPERTS IS A CEILING OF ZERO, NOT AN UNMEASURED ONE. weight_footprint() runs on
|
||||
* every rank before this call, so expert_ceiling is always known -- and guarding this cap
|
||||
* with `> 0` would read "dense" as "unlimited", handing a model with no experts at all a
|
||||
* large expert budget against nothing to put in it while its cache goes short.
|
||||
* kv_ceiling keeps its guard: that one IS genuinely unset when plan_groups fails. */
|
||||
if (exp > b.expert_ceiling) exp = b.expert_ceiling;
|
||||
int64_t spare = b.elastic - kv - exp;
|
||||
if (spare > 0 && b.expert_ceiling > exp) {
|
||||
const int64_t take = std::min(spare, b.expert_ceiling - exp);
|
||||
exp += take; spare -= take;
|
||||
}
|
||||
if (spare > 0 && b.kv_ceiling > kv) {
|
||||
const int64_t take = std::min(spare, b.kv_ceiling - kv);
|
||||
kv += take; spare -= take;
|
||||
}
|
||||
b.experts = exp;
|
||||
b.kv = kv;
|
||||
b.weights = b.statics + exp;
|
||||
b.unusable = spare > 0 ? spare : 0;
|
||||
} else if (want_kv) {
|
||||
b.kv = b.kv_ceiling > 0 ? std::min(b.claimable, b.kv_ceiling) : b.claimable;
|
||||
b.unusable = b.claimable - b.kv;
|
||||
} else if (want_w) {
|
||||
/* The KV pool was stated, so `claimable` is already net of it; the weights take the rest,
|
||||
* still capped at what the model has to put there. */
|
||||
int64_t exp = b.elastic;
|
||||
if (exp > b.expert_ceiling) {
|
||||
b.unusable = exp - b.expert_ceiling;
|
||||
exp = b.expert_ceiling;
|
||||
}
|
||||
b.experts = exp;
|
||||
b.weights = b.statics + exp;
|
||||
}
|
||||
|
||||
/* ---- THE PREFILL STAGING REGION, out of the expert share ---------------------------------
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
if (want_w && 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 (2 * one < b.experts) {
|
||||
b.stage = 2 * one;
|
||||
b.experts -= b.stage;
|
||||
b.weights = b.statics + b.experts;
|
||||
}
|
||||
}
|
||||
|
||||
/* 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). */
|
||||
if (b.derived_kv && 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. --expert-vs-cache-ratio moves it.",
|
||||
100.0 * (double)b.kv / (double)b.kv_ceiling,
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
|
||||
(double)cfg.max_seqs * (double)b.kv / (double)b.kv_ceiling);
|
||||
/* Rounding the floor up claims up to a MiB the split did not hand out. Take it back from the
|
||||
* cache where the cache is ours to size -- a paged pool a MiB smaller addresses a handful
|
||||
* fewer tokens and nothing else -- so the headroom stays whole. Where the KV budget was
|
||||
* STATED it is not ours to shave and the MiB comes out of the headroom instead. */
|
||||
cfg.vram_budget_derived = want_w || want_kv;
|
||||
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 = want_kv ? to_mib(std::max<int64_t>(b.kv - w_over, 0)) : to_mib(b.kv);
|
||||
|
||||
/* 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. */
|
||||
const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB;
|
||||
const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.stage - granted;
|
||||
const double ela = b.elastic > 0 ? (double)b.elastic : 1.0;
|
||||
b.report = fmt(
|
||||
"VRAM budget, per card:\n"
|
||||
" card total %10s\n"
|
||||
" already held %10s measured: driver context, code objects, anything else resident\n"
|
||||
" activation arena %10s computed from the buffer plan\n"
|
||||
" %-18s %10s %s\n"
|
||||
" ------------------------------\n"
|
||||
" claimable %10s\n"
|
||||
" static weights %10s %s\n"
|
||||
" ------------------------------\n"
|
||||
" elastic %10s what --expert-vs-cache-ratio %.2f divides\n"
|
||||
" experts %10s %.0f%% of it%s\n"
|
||||
" kv cache %10s %.0f%% of it%s\n"
|
||||
"%s"
|
||||
"%s"
|
||||
" ==============================\n"
|
||||
" vram_weights %10s %s\n"
|
||||
" vram_kv %10s %s\n"
|
||||
" unclaimed %10s the headroom, the unusable above, and what MiB rounding\n"
|
||||
" could not place\n",
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.arena).c_str(),
|
||||
shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(),
|
||||
shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool "
|
||||
"outright"
|
||||
: "left unclaimed on purpose",
|
||||
humanb(b.claimable).c_str(),
|
||||
humanb(b.statics).c_str(),
|
||||
b.derived_weights ? "off the top: every rank's own shard, and not a share of anything"
|
||||
: "(not charged here -- --vram-weights-mib was stated)",
|
||||
humanb(b.elastic).c_str(),
|
||||
(cfg.expert_cache_ratio > 0.0 && cfg.expert_cache_ratio < 1.0) ? cfg.expert_cache_ratio
|
||||
: 0.75,
|
||||
humanb(b.experts).c_str(), 100.0 * (double)b.experts / ela,
|
||||
b.expert_ceiling == 0
|
||||
? " -- a dense model, so there is no expert plane for this share to fill and the\n"
|
||||
" cache took everything it could address"
|
||||
: (b.experts >= b.expert_ceiling)
|
||||
? " -- the whole expert plane is resident, so more would do nothing" : "",
|
||||
humanb(b.kv).c_str(), 100.0 * (double)b.kv / ela,
|
||||
(b.kv_ceiling > 0 && b.kv >= b.kv_ceiling)
|
||||
? fmt(" -- backs %lld sequences all at %lld tokens at once, which is the worst case and\n"
|
||||
" 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). */
|
||||
? 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",
|
||||
100.0 * (double)b.kv / (double)b.kv_ceiling,
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
|
||||
(double)cfg.max_seqs * (double)b.kv / (double)b.kv_ceiling).c_str()
|
||||
: ""),
|
||||
b.unusable > 0
|
||||
? fmt(" unusable %10s neither side could take it: both are at their "
|
||||
"ceiling\n", humanb(b.unusable).c_str()).c_str()
|
||||
: "",
|
||||
b.stage > 0
|
||||
? fmt(" prefill staging %10s out of the experts: two buffers of one layer's "
|
||||
"non-resident experts,\n"
|
||||
" at the arena's top and lent back to the "
|
||||
"slab while steps are small\n", humanb(b.stage).c_str()).c_str()
|
||||
: "",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str(),
|
||||
b.derived_weights ? "static + experts" : "stated by --vram-weights-mib",
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str(),
|
||||
b.derived_kv ? "the cache's share" : "stated by --vram-kv-mib",
|
||||
humanb(unclaimed).c_str());
|
||||
|
||||
if (out) *out = b;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,103 @@
|
||||
/* 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 says the engine does not derive its budgets, and core/mem/pools.cpp still refuses to
|
||||
* re-optimise a split the operator stated. 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.
|
||||
*
|
||||
* What that argument forbids is inference. It does not forbid arithmetic on numbers that are all
|
||||
* known, all printed, and all stable:
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* What is left over is claimable, and it is spent in TWO STEPS, not one.
|
||||
*
|
||||
* 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, and under tensor parallel each rank already holds its own even share of
|
||||
* them (declare runs per rank with every dimension divided, spec §9). They are a FLOOR, not a
|
||||
* share of anything: applying a ratio to the weights as a whole would let --expert-vs-cache-ratio
|
||||
* 0.3 demote the attention projections to host memory to make room for a cache nothing will fill.
|
||||
* If they do not fit, that is a refusal with the shortfall named.
|
||||
*
|
||||
* ONLY WHAT IS LEFT AFTER THAT IS DIVIDED, and that is the division the flag is named for: the
|
||||
* expert plane against the KV cache, which is the one genuinely two-sided trade on this engine. A
|
||||
* long-context low-concurrency server and a short-context high-concurrency one want opposite
|
||||
* answers and neither is derivable.
|
||||
*
|
||||
* BOTH SIDES ARE THEN CAPPED AT WHAT THEY COULD USE, and whatever one side cannot take goes to the
|
||||
* other rather than nowhere. A cache cannot address past max_seqs x max_ctx tokens
|
||||
* (KVManager::ceiling), so a share larger than that ceiling is VRAM the cache can never fill and
|
||||
* the expert plane could have held. And an expert plane that fits entirely in VRAM has no use for
|
||||
* more; on a model that fits, the ratio stops meaning anything and that is correct.
|
||||
*
|
||||
* A stated --vram-weights-mib or --vram-kv-mib still wins outright and turns the whole of this
|
||||
* off for that pool. The point is that the DEFAULT is a full card rather than a guess: VRAM left
|
||||
* unbudgeted is VRAM no pool can use, and on a model whose experts do not fit, every unbudgeted
|
||||
* GiB costs measurable decode time.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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. */
|
||||
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 kv_ceiling = 0; /* KVManager::ceiling(max_ctx) for this rank's declared groups */
|
||||
/* weight_footprint() for this rank, which under tensor parallel is already this card's even
|
||||
* share: declare runs per rank with every dimension already divided. */
|
||||
int64_t statics = 0; /* non-expert weights -- the floor, not a share of anything */
|
||||
int64_t experts = 0; /* the elastic plane the ratio divides against the KV cache */
|
||||
int64_t expert_layer_max = 0; /* the most expert bytes one routed layer holds */
|
||||
/* 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. */
|
||||
int64_t host_reserve = 0;
|
||||
};
|
||||
|
||||
/* The resolved split, in bytes, beside every term it came from. Always filled, including when the
|
||||
* operator stated the budgets -- the placement report and the pool report both want the totals. */
|
||||
struct VramBudget {
|
||||
int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0;
|
||||
int64_t claimable = 0; /* after the four fixed terms above */
|
||||
int64_t statics = 0; /* off the top, before the ratio sees anything */
|
||||
int64_t elastic = 0; /* claimable - statics: what the ratio divides */
|
||||
int64_t kv_ceiling = 0, expert_ceiling = 0;
|
||||
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. */
|
||||
int64_t stage = 0;
|
||||
int64_t weights = 0; /* statics + experts: what vram_weights is set to */
|
||||
bool derived_weights = false, derived_kv = false;
|
||||
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.
|
||||
* 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. */
|
||||
int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
|
||||
|
||||
} /* namespace rad */
|
||||
Reference in new issue
Block a user