radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+235 -388
View File
@@ -1,48 +1,33 @@
/* mover.h -- residency and the mover: the substrate every tier stands on.
/* mover.h -- residency and the mover: where every weight unit lives and how it moves.
*
* Three storage tiers, one address space of slots:
*
* FIXED-STRIDE VRAM SLAB SLOTS PER WEIGHT CLASS. A slot is interchangeable within its class, so
* a promotion is an integer swap and not an allocation, and a slab that never fragments is a
* slab whose hit rate does not depend on the order promotions happened to arrive in.
* VRAM slab: fixed-stride slots per weight class. Slots within a class are interchangeable, so
* a promotion is an integer swap rather than an allocation, and the slab never fragments.
*
* A PINNED HOST POOL, at the same stride. Pinned rather than pageable because the whole point of
* the host tier is that a card can DMA out of it: a device-visible pinned pool is what makes a
* non-resident expert a zero-copy read inside the GEMM instead of a bounce-buffer memcpy in
* front of it. It is also allocated and owned here rather than read through the container's
* mmap, because with an mmap the KERNEL decides what stays resident and under real memory
* pressure it decides badly for this workload -- the same reads run several times slower inside
* a decode run than in isolation, and MADV_WILLNEED makes it worse, which is the tell that the
* faults are not too small and that a hint cannot fix a policy disagreement.
* Pinned host pool, same stride. The card reads a non-resident expert from it zero-copy
* inside the GEMM. It is owned here, not read through the container's mmap, because under
* memory pressure the kernel's paging makes decode reads several times slower, and
* MADV_WILLNEED makes it worse.
*
* A FILE TIER READ WITH O_DIRECT INTO PINNED BUFFERS. Predictable latency, no page-cache
* double-copy, and the read lands where the mover can DMA from it without a bounce. A buffered
* fallback is refused rather than offered: a tier whose latency is the page cache's mood is not
* a tier you can budget against.
* File tier: O_DIRECT reads into pinned buffers, with predictable latency and no page-cache
* copy. No buffered fallback: a tier whose latency depends on the page cache cannot be budgeted.
*
* ---- THE ONE PROPERTY EVERYTHING ELSE RESTS ON -----------------------------------------------
* ---- Transfers never synchronise the host ----------------------------------------------------
*
* THE MOVER RUNS ON A DEDICATED STREAM AND THE COMPUTE STREAM WAITS ON ITS EVENTS. NO HOST
* SYNCHRONISATION IS INVOLVED IN A TRANSFER. That is what lets placement be dynamic without
* serialising the step, and it is the difference between MoE offload being unusable and being
* fast. rad_issue waits with rad_event_wait, never rad_event_sync.
* The mover runs on its own stream and the compute stream waits on its events (rad_event_wait,
* never rad_event_sync), so placement changes without serialising the step. The lead gate is a
* host wait on how far the host runs ahead, not on a transfer (MoverConfig::max_lead_dispatches).
*
* The lead gate below IS a host wait, and it is not a contradiction: it throttles how far the
* host runs ahead of the cards. It is a SUPPLY mechanism, not a transfer synchronisation, and the
* reason it exists is spelled out at MoverConfig::max_lead_dispatches.
* ---- Shadow slots and quarantine -------------------------------------------------------------
*
* ---- SHADOW SLOTS AND QUARANTINE -------------------------------------------------------------
* A promotion copies into a shadow slot (allocated, holding nothing) and only then publishes the
* new pointer, so a slot is never overwritten while a kernel may read it. Getting this order
* wrong does not crash; it produces fluent output that differs from run to run.
*
* A promotion writes into a SHADOW slot -- a slab slot that is allocated but holds nothing -- and
* only then publishes the new pointer. So a live slot is never DMA'd over while a kernel might
* still be reading it, and a promotion never invalidates a pointer the run phase is already
* holding. Getting that ordering wrong does not crash: it produces fluent output with a different
* hash every run, which is the single most expensive bug class in this design.
*
* The freed slot then goes into QUARANTINE rather than straight back to the free list, because
* kernels issued in earlier layers still name its old address. The barrier is an event recorded
* on the COMPUTE stream after the publish; when it signals, every launch that could still name
* the slot has retired.
* A freed slot goes into quarantine, because kernels issued in earlier layers still name it. The
* barrier is an event recorded on the compute stream after the publish; when it signals, every
* launch that could name the slot has retired.
*/
#pragma once
#include "../device/device.h"
@@ -61,49 +46,27 @@
namespace rad {
/* ------------------------------------------------------------------ slot bookkeeping */
/* Pure host state, no device call in it, so the whole supply half is testable without a card.
* Used for both the VRAM slab and the pinned host pool -- they are the same structure with
* different backing memory, and writing it twice is how two free lists come to disagree about
* what a slot index means.
/* Free-list bookkeeping for the VRAM slab and the pinned host pool. Pure host state, testable
* without a card.
*
* ---- SEGMENTS: ONE RANGE FOR THE SLAB'S OWN SLOTS, ONE FOR EACH LENDER ------------------------
* Slots are numbered in segments laid end to end. Segment 0 is the budgeted range; each later
* one is memory another pool lends (KV cache blocks, the arena's top). Each segment has its own
* target, below which slots may be handed out, because lenders reclaim independently.
*
* The slots are numbered in SEGMENTS laid end to end. Segment 0 is the budgeted range the pool
* was built with; every later one is a stretch of another pool's memory lent to this one -- the
* KV cache's blocks, the activation arena's top -- added once its addresses are known. Each
* segment has its own TARGET: the slots below it are the ones that may be handed out, and a
* lender moves only its own. Two lenders cannot share one target, because what one of them can
* spare says nothing about the other: the arena takes its memory back for every prefill while the
* cache is still lending, and a single mark over both would either hold the arena's slots past its
* recall or give up the cache's with it.
* The lowest free slot goes first, so occupied slots pack toward a segment's bottom and its top
* can be returned; a LIFO would keep handing out high slots. `live` is how far a segment's slots
* exist and `target` how far they should: a shrink lowers `live` only past unheld slots, so it
* never evicts.
*
* ---- WHY THE LOWEST FREE SLOT, AND WHY A LIVE MARK -------------------------------------------
*
* A lent segment is VRAM its owner can want back, and it has to be handed back when it does. That
* is only possible if the occupied slots pack toward the BOTTOM of the segment, so its top is free
* to retire. Handing out the lowest free slot is what packs them; a LIFO stack hands back the slot
* released most recently, which after a busy period is exactly the high slot the pool wants to
* give up, and the mark would never fall.
*
* A segment's `live` is how far its slots exist right now and `target` how far they should. They
* differ while a shrink waits on the units still sitting above the target: the mark stops at the
* highest slot something holds, so shrinking can never evict -- it only declines to hand a slot
* out again.
*
* THE FREE LIST IS REBUILT WHENEVER A TARGET MOVES, from the held flags, and holds exactly the
* covered slots nothing holds. Carried across a shrink and a regrow instead, it lists only some of
* the slots the shrink dropped -- a slot freed while it sat above the target is never pushed, and
* one the heap still held is discarded by the first take() that walks past it -- and a regrow
* that trusts it never hands the others out again. The rebuild is a scan of the capacity at the
* arbiter's cadence; take() and add_free, which the mover calls several times a dispatch, stay
* heap operations.
* The free list is rebuilt from the held flags whenever a target moves; one carried across a
* shrink and regrow would lose slots freed above the target. take() and add_free() stay heap
* operations.
*/
class SlotPool {
public:
/* `n_live` slots exist in segment 0 and every one of them is HELD until add_free says
* otherwise, which is what the plan's resident set is. `n_cap` is how far segment 0 may ever
* grow -- address space the caller has reserved and will back on demand -- and defaults to no
* growth at all. */
/* Segment 0 starts with `n_live` slots, all held (the plan's resident set) until add_free()
* releases them. `n_cap` is how far segment 0 may grow into address space the caller has
* reserved and backs on demand; the default is no growth. */
void init(int64_t n_live, int64_t stride, int64_t n_cap = -1) {
stride_ = stride;
n_ = n_cap > n_live ? n_cap : n_live;
@@ -122,9 +85,7 @@ public:
n_ += n_slots;
return (int)segs_.size() - 1;
}
int n_segments() const { return (int)segs_.size(); }
int64_t seg_lo(int k) const { return segs_[(size_t)k].lo; }
int64_t seg_hi(int k) const { return segs_[(size_t)k].hi; }
void add_free(int64_t slot) {
if (slot < 0 || slot >= n_) return;
@@ -145,53 +106,37 @@ public:
int64_t capacity() const { return n_; }
int64_t stride() const { return stride_; }
int64_t n_free() const { return n_usable_; }
/* Slots something is in: a resident unit, a staged one, or a copy still in flight. The
* number the fill and drain decisions are made against, because the working slots have to
* stay free whatever the target is. */
/* Slots in use: a resident unit, a staged one, or a copy in flight. Fill and drain decide
* against this, because the working slots must stay free whatever the target is. */
int64_t held() const { return n_held_; }
/* Where segment `k`'s covered slots end, as a slot number. */
int64_t target(int k = 0) const { return segs_[(size_t)k].target; }
/* May this slot be handed out -- is it below its segment's target? */
/* Whether `slot` is below its segment's target, i.e. may be handed out. */
bool covered(int64_t slot) const {
if (slot < 0 || slot >= n_) return false;
return slot < segs_[(size_t)seg_of(slot)].target;
}
/* -1 when there is none. A caller that treats that as "try again next dispatch" is right;
* one that treats it as an error is wrong -- slot starvation is the normal steady state. */
int64_t take() {
while (!free_.empty()) {
std::pop_heap(free_.begin(), free_.end(), std::greater<int64_t>());
const int64_t s = free_.back();
free_.pop_back();
if (!covered(s) || held_[(size_t)s]) continue; /* never a slot to hand out */
held_[(size_t)s] = 1;
++n_held_;
--n_usable_;
return s;
}
return -1;
}
/* The lowest free covered slot, or -1. Starvation is the normal steady state: callers retry
* on a later dispatch rather than treat -1 as an error. */
int64_t take() { return take_at_least(0); }
/* Where segment `k`'s covered slots should end, as a slot number inside it. Growing is
* immediate -- the caller has already backed the memory. Shrinking is a statement of intent:
* the mark falls as far as the slots nothing holds allow, and the rest follows as those
* retire. */
/* Sets where segment `k`'s covered slots end, as a slot number inside it. Growing is
* immediate (the caller has already backed the memory). Shrinking lowers `live` only past
* slots nothing holds; the rest follows as those are released. */
void set_target(int64_t target) { set_target(0, target); }
void set_target(int k, int64_t target) {
Seg& g = segs_[(size_t)k];
g.target = target < g.lo ? g.lo : (target > g.hi ? g.hi : target);
/* Nothing ever holds a slot at or past the mark -- take() hands out only covered slots,
* and the mark never falls past a held one -- so a set flag there only says the slot has
* never existed. */
/* Nothing holds a slot at or past `live` (take() hands out only covered slots and `live`
* never falls past a held one), so a set flag there only means the slot never existed. */
for (int64_t s = g.live; s < g.target; ++s) held_[(size_t)s] = 0;
if (g.target > g.live) g.live = g.target;
else settle(g);
rebuild();
}
/* take(), restricted to slots at or above `lo`. The slots below it that are free stay free
* and stay listed; there are at most the working slots of them, so this is a handful of heap
* operations. */
/* take(), restricted to slots >= `lo`. Free slots below `lo` stay listed; there are at most
* the working slots of them, so this is a few heap operations. */
int64_t take_at_least(int64_t lo) {
std::vector<int64_t> keep;
int64_t got = -1;
@@ -213,8 +158,8 @@ public:
}
return got;
}
/* take(), restricted to the free slots `want` accepts: the lowest of them, or -1. A scan of
* the free list, which holds the slots on their way back through a swap -- a few dozen. */
/* take(), restricted to the lowest free slot `want` accepts, or -1. A linear scan; the free
* list holds only slots passing through a swap, a few dozen. */
template <class Want> int64_t take_where(Want want) {
size_t best = free_.size();
for (size_t i = 0; i < free_.size(); ++i) {
@@ -232,8 +177,8 @@ public:
--n_usable_;
return s;
}
/* The highest slot of segment `k` something holds -- a unit, a copy in flight, a slot in
* quarantine -- or -1. A scan down from the segment's mark. */
/* The highest held slot of segment `k` (a unit, a copy in flight, a quarantined slot), or
* -1. Scans down from `live`. */
int64_t top_held(int k = 0) const {
const Seg& g = segs_[(size_t)k];
for (int64_t s = g.live; s-- > g.lo;)
@@ -277,43 +222,34 @@ private:
};
/* ------------------------------------------------------------------ the file tier */
/* A thin skin over the device layer's DirectFile, which is where the O_DIRECT mechanics live and
* where they belong: the prefix cache reads the same way for the same reasons, and two
* implementations of "align the offset, the length and the buffer" is two places for the
* alignment rule to drift. What this adds is the tier's own accounting -- a file-tier read is a
* blocking pread in the middle of a dispatch and the counter is how a run that leans on it stops
* being a mystery in the throughput. */
/* A thin wrapper over the device layer's DirectFile, which owns the O_DIRECT alignment rules
* (the prefix cache reads the same way). This adds the tier's accounting: a file-tier read is a
* blocking pread inside a dispatch, and the counters make its cost visible. */
class FileTier {
public:
/* O_DIRECT, and a refusal rather than a buffered fallback: a tier whose latency is the page
* cache's mood is not a tier you can budget against. `path` is the container. */
/* Opens the container `path` with O_DIRECT; refuses rather than fall back to buffered reads,
* whose latency cannot be budgeted. */
int open(const std::string& path);
bool ok() const { return f_.is_open(); }
void close() { f_.close(); }
/* One expert-sized read into a pinned buffer. Blocking, counted, and a cliff: a dispatch that
* meets a file-tier unit stops until the read returns. That is the price of a bet the plan
* made -- give the cold tail to disk and buy a host pool big enough to hold a working set
* that can actually move -- paid in full each time the bet is wrong. What changes in response
* is the plan, not this function. */
/* One expert-sized read into a pinned buffer. Blocking and counted: a dispatch that meets a
* file-tier unit stalls until the read returns. This is the cost the plan accepted by putting
* the cold tail on disk; frequent reads call for a different plan, not a change here. */
int read(uint64_t offset, int64_t bytes, void* pinned_dst, int64_t dst_cap);
/* Every RadFileEntry offset is RAD_ALIGN_UNIT-aligned by construction (rad_format.h) and that
* is DirectFile's alignment, so the mover's reads take the path with no bounce in it. */
/* RadFileEntry offsets are RAD_ALIGN_UNIT-aligned (rad_format.h), which is DirectFile's
* alignment, so the mover's reads need no bounce buffer. */
static int64_t direct_align(int64_t v) { return align_up(v, DirectFile::alignment()); }
uint64_t reads() const { return reads_; }
uint64_t bytes_read() const { return bytes_; }
private:
DirectFile f_;
uint64_t reads_ = 0, bytes_ = 0;
};
/* ------------------------------------------------------------------ residency */
class Residency final : public ResidencyTable {
public:
void init(const Program& prog, const Plan& plan);
void init(const Program& prog);
const WeightSlot* lookup(rad_weight w) const override {
return (size_t)w < slot_.size() ? &slot_[w] : nullptr;
@@ -325,14 +261,11 @@ public:
changed_.clear();
}
/* The only two writers, and BOTH BUMP THE GENERATION. `publish` settles a slot -- the bytes
* are there, nothing to wait on. `begin_transfer` opens one: a copy into `ptr` is in flight
* and `ready` is the event the compute stream must be ordered behind.
*
* begin_transfer bumping is the part that is easy to get wrong and expensive to debug. The
* run phase memoises the wait per generation, so installing a new event at the old generation
* makes it skip the wait entirely (residency_iface.h). */
void publish(rad_weight w, void* ptr);
/* The only two writers; both bump the generation. publish() settles a slot; begin_transfer()
* marks a copy into `ptr` in flight that the compute stream must wait on (`ready`). The run
* phase memoises its wait per generation, so a new event at an old generation would be
* skipped (residency_iface.h). */
void publish(rad_weight w, void* ptr) { begin_transfer(w, ptr, nullptr); }
void begin_transfer(rad_weight w, void* ptr, RadEvent ready);
void settle(rad_weight w) {
if ((size_t)w >= slot_.size()) return;
@@ -355,51 +288,34 @@ private:
/* ------------------------------------------------------------------ configuration */
struct MoverConfig {
/* Shadow slots and the staging ring are NOT here. They are budgeted by the planner out of
* the weights pool and reported in the plan (SlabClass::n_shadow, n_stage), and a second
* knob for the same quantity is a second number for the mover and the operator to disagree
* about -- with an overrun as the direction that disagreement goes wrong in.
/* Shadow and staging slot counts come from the plan (SlabClass::n_shadow, n_stage), which
* budgets them; a second knob here could only cause an overrun.
*
* ---- HOW FAR THE HOST MAY RUN AHEAD OF THE CARDS, IN LAYER DISPATCHES --------------------
*
* 0 is unbounded, and unbounded STARVES THE MOVER. A freed slot returns to the free list only
* after its quarantine event signals, and that event is on the COMPUTE stream -- so the
* recycle latency is however deep that stream happens to be queued, and the move rate is
* `shadow slots / recycle latency`. Let the host run and the stream carries a whole step's
* work, and almost every round finds no free slot to move into. The guard is not what binds;
* the engine simply never gets the supply to spend.
*
* Holding the host near the cards is therefore not a latency measure but a SUPPLY one. 2 is
* the smallest depth that recovers the effect while leaving the issue path a dispatch of
* margin. A coarser gate -- per step rather than per layer dispatch -- does nothing, because
* one step is already the whole model's worth of queued work; the granularity has to be the
* layer. */
* How far the host may run ahead of the cards, in layer dispatches. A freed slot recycles
* only when its quarantine event on the compute stream signals, so the move rate is shadow
* slots / compute queue depth; 0 (unbounded) queues a whole step and starves the mover. 2 is
* the smallest depth that keeps slots recycling with a dispatch of issue margin. A per-step
* gate does nothing, since one step is already the whole model's queued work. */
int max_lead_dispatches = 2;
/* Lent slots kept free for swaps to land in, a slab class (planner.h's
* RAD_PLACE_TURNOVER_SLOTS; Mover::balance keeps them). A knob here and not in the plan because the planner charges
* nothing for them: they are the KV cache's memory, free only while it lends. A class whose
* shadow slots the quarter-of-the-slab cap cut keeps at most the same multiple of them, so a
* small loan is not left emptier than it is filled. */
/* Lent slots per slab class kept free for swaps to land in (Mover::balance). A knob rather
* than a plan field because the planner charges nothing for them: they are KV cache memory,
* free only while it lends. A class whose shadow slots the quarter-of-the-slab cap reduced
* gets proportionally fewer, so a small loan is not left emptier than it is filled. */
int turnover_slots = RAD_PLACE_TURNOVER_SLOTS;
/* The container, for the file tier. Empty means there is no file tier and a unit the planner
* put there is an error rather than a slow path. */
/* The container, for the file tier. Empty means no file tier; a unit planned there is then
* an error. */
std::string container_path;
/* Pinned staging buffers for file-tier reads. Each is one class stride, and the count is the
* planner's -- RAD_PLACE_FILE_STAGE_SLOTS, which is what the operator was charged for out of
* --host-pool-mib. A separate default here would be a second number for one allocation. */
/* Pinned staging buffers for file-tier reads, one class stride each; the count the planner
* charged to --host-pool-mib. */
int stage_slots = RAD_PLACE_FILE_STAGE_SLOTS;
};
/* ------------------------------------------------------------------ the loan */
/* ONE STRETCH OF ANOTHER POOL'S VRAM THAT MAY BE LENT TO THE SLAB, described from its top down.
*
* The owner keeps it backed and lends it from the top downwards, and it states how much it has
* lent in its own measure -- tokens, for the KV cache -- so the mover can tell which slots a loan
* covers without knowing what the owner stores there. `unit_bytes` of the stretch are one unit of
* that measure and a unit is `unit_tokens` tokens: a loan of T tokens is the top
* floor(T / unit_tokens) * unit_bytes bytes of every stretch. */
/* One stretch of another pool's VRAM that may be lent to the slab. The owner keeps it backed,
* lends from the top down and states the loan in its own measure (tokens, for the KV cache). A
* loan of T tokens is the top floor(T / unit_tokens) * unit_bytes bytes of every stretch. */
struct LoanStrip {
char* top = nullptr; /* one past the stretch's highest byte */
int64_t bytes = 0; /* how far below `top` it runs */
@@ -412,29 +328,23 @@ struct MoverStats {
uint64_t promotions = 0, demotions = 0;
uint64_t h2d_bytes = 0, d2h_bytes = 0;
uint64_t prefetched = 0, prefetch_bytes = 0;
/* Why a move did not go out. `no_record` is every in-flight move record busy -- the shadow
* slots, still waiting on their copies. The two `starved` counts are the free lists empty.
* Without these a starved mover is indistinguishable from a satisfied one. */
/* Why a move did not go out: every move record busy, or a free list empty. These separate a
* starved mover from a satisfied one. */
uint64_t no_record = 0, starved_slab = 0, starved_pool = 0;
uint64_t quarantined = 0;
/* Demotions that copied nothing: the unit sat in a lent slot and kept its host copy, so going
* back to the host tier was a change of address. Counted inside `demotions` as well. */
/* Demotions out of a lent slot that copied nothing (the unit kept its host copy). Also
* counted in `demotions`. */
uint64_t dropped = 0;
/* Host copies a unit in a lent slot gave to a budgeted victim that had no pool slot to go to
* (Mover::donor_slot), and such units moved rather than dropped when their loan was recalled
* or shrank. `stranded` counts the recalls that found no free slot for one of them: it stayed
* past the loan until a later recall or balance() moved it. */
/* Host copies given to budgeted victims (Mover::donor_slot); donors moved rather than
* dropped by a recall or shrink; recalls that found no free slot for a donor. */
uint64_t donated = 0, relocated = 0, stranded = 0;
uint64_t ssd_reads = 0, ssd_bytes = 0;
/* The prefill stager's copies (stage_units): layers staged, units and bytes copied, and
* pooled units a buffer had no room left for -- those were read across the link in place.
* `stage_copies` is how many copies carried the units: neighbouring pool slots go as one. */
/* The prefill stager (stage_units). `stage_overflow`: units no buffer had room for, read in
* place. `stage_copies`: copies issued; neighbouring pool slots go as one. */
uint64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0;
uint64_t stage_copies = 0;
/* The file stager's reads (stage_file_units): routed layers read from the container, the
* units and bytes they carried, the preads that carried them, and the host time spent inside
* those reads and waiting for a window's copies to drain -- the two halves of what a step
* that reads the drive costs the thread issuing it. */
/* The file stager (stage_file_units), including the host time spent in preads and waiting
* for a window's copies to drain. */
uint64_t file_layers = 0, file_units = 0, file_bytes = 0, file_preads = 0;
uint64_t file_read_ns = 0, file_wait_ns = 0;
};
@@ -447,137 +357,97 @@ public:
Mover(const Mover&) = delete;
Mover& operator=(const Mover&) = delete;
/* Allocates every pool the plan asked for and lays every unit into a slot. Does NOT read a
* byte of the model: the load phase fills the addresses this hands it. Returns RAD_E_NOMEM
* naming the pool that failed, because "out of memory" without which pool is not a
* diagnosis.
/* Allocates every pool the plan asks for and assigns every unit a slot; the load phase fills
* the published addresses. On RAD_E_NOMEM the log names the pool.
*
* `budget` IS THE PRODUCTION PATH AND SHOULD ALWAYS BE PASSED. Pools already allocated
* the weights pool as one block; a mover that called rad_dev_alloc beside it would spend
* that budget TWICE and the overrun would surface as an out-of-memory from an unrelated
* launch much later. Reserving from Pools::weights() is also what makes it structurally
* impossible for a promotion to reach a KV block -- there is no path from the weights pool to
* the KV pool (mem/pools.h), which is the whole reason the weight slab is a fixed budget.
*
* Null is the standalone-test path and says so at Warn. It is not a supported deployment. */
* Always pass `budget`: Pools already reserved the weights pool, so allocating beside it
* spends the budget twice, and reserving from Pools::weights() keeps promotions out of KV
* blocks (mem/pools.h). Null is the standalone-test path and logs a warning. */
int init(const Program& prog, const Plan& plan, const MoverConfig& cfg, Pools* budget = nullptr);
/* The compute stream this rank issues on. The mover's transfers are ordered against it and
* the quarantine barrier is recorded on it, so without one the mover refuses to move rather
* than storing a table edit blind. */
/* The compute stream this rank issues on. Transfers are ordered against it and the
* quarantine barrier is recorded on it; without one the mover refuses to move. */
int bind_compute_stream(RadStream s);
/* THE MAINTENANCE STREAM, AND WHY ANYTHING ELSE MAY HAVE IT.
/* The mover's stream, to be shared by any subsystem moving bytes off the critical path. Each
* HIP stream costs a hardware queue, and on RDNA4 a fourth one is expensive: on two R9700s
* serving Flash-Next, an idle fourth stream takes the decode step from 20.5 to 33.9 ms
* (GPU_MAX_HW_QUEUES 1-3 are fine, 4 and 8 are not). The engine already uses three (compute,
* the second compute lane, this one).
*
* A HIP stream costs a hardware queue, and on RDNA4 a fourth concurrent queue is not a small
* cost: on a two-card R9700 Flash-Next server, a fourth stream that never carries a single
* byte takes the decode step from 20.5 ms to 33.9 (GPU_MAX_HW_QUEUES 1, 2 or 3 all run at
* full speed; 4 and 8 do not). The engine already issues on three -- compute, the second
* compute lane, and this one -- so a subsystem that wants a stream to move bytes off the
* critical path must TAKE THIS ONE rather than make a fourth.
*
* Null before init(), and null on a rank with nothing to move. A caller that gets null must
* fall back to its own stream: three streams is under the cliff either way.
*
* THE MOVER'S RUN PHASE ISSUES ON IT, so this stream is not idle: a sharer queueing a hundred
* megabytes on it will sit in front of a transfer the compute stream is waiting on. Gate the
* two -- do not answer it by making a fourth queue. */
* Null before init() and on a rank with nothing to move; the caller then uses its own stream.
* The run phase issues here too, so a sharer's large copy delays transfers the compute stream
* waits on; gate the two rather than add a queue. */
RadStream transfer_stream() const { return mover_; }
ResidencyTable* residency() { return &res_; }
/* THE ONE ADDRESS THE MOVER DOES NOT OWN. A Tier::Mapped weight lives in the container's
* mapping and the LOAD PHASE is what holds the RadFile, so it publishes the pointer and the
* mover only records it -- the residency table is the mover's, and a second table would be a
* second answer to "where is this weight". Nothing here ever moves it afterwards: a mapped
* unit has no slab class, so unit_base() has no address of its own to republish over this. */
/* For Tier::Mapped weights, which live in the container mapping the load phase holds: the
* one address the mover does not own, recorded so the residency table stays the only record
* of weight addresses. A mapped unit has no slab class, so nothing republishes over it. */
void publish_mapped(rad_weight w, void* p) { res_.publish(w, p); }
/* ---- the run phase, in the order a layer dispatch calls it -----------------------------
*
* begin_dispatch retire whatever landed, gate the host's lead, record the ordering event
* prefetch_to_op release what this op has finished with, then start everything the exact
* schedule says is due -- and keep starting, as long as slots are free
* begin_dispatch retire what landed, gate the host's lead, record the ordering event
* prefetch_to_op release what this op has finished with, then start every transfer the
* exact schedule says is due, while slots are free
* issue one heat proposal
*
* There is no end_dispatch, and the absence is deliberate. The quarantine barrier belongs
* DOWNSTREAM of the publish in stream order, and begin_dispatch's retire() is exactly that
* point: by the time it runs, every launch the previous dispatch made has been issued. A
* symmetric end-of-dispatch hook would record the barrier before those launches and the
* quarantine would be satisfied for a reason that has nothing to do with the kernels it is
* guarding.
* There is deliberately no end_dispatch: the quarantine barrier must be recorded downstream
* of the previous dispatch's launches, which begin_dispatch's retire() is.
*
* ---- A CALLER MUST DO ALL OF IT, EVERY DISPATCH -------------------------------------------
* A caller must issue as well as retire every dispatch. The pool free list starts empty, so a
* loop that only retires promotes into the shadow slots once and never demotes; on the host
* backend copies land within their dispatch, so this shows only on a real card. The compute
* stream must also carry the dispatch's real work, or the quarantine barrier and the lead
* gate are meaningless.
*
* begin_dispatch only RETIRES; it never starts anything. A loop that retires without issuing
* is not a slower engine, it is a stuck one: the pool free list starts empty, so the first
* round can only promote out of the shadow slots, and the pool slot that promotion frees
* arrives several dispatches later -- by which time, if nothing is asking, the resident set
* has grown by the shadow count and never shrinks again. The symptom is zero demotions
* forever, and it appears only on a real card: on the host backend every copy lands inside
* the dispatch that issued it, so the same mistake passes unnoticed.
*
* The compute stream must also carry the dispatch's actual work. The quarantine barrier is an
* event on that stream and its claim is "every kernel that could still name this slot has
* retired"; against an empty stream the claim is vacuous and the lead gate paces nothing.
* In production, begin_dispatch and issue run once a step from Engine::tiering_dispatch,
* since the mover relocates only between steps (Ctx::run_step syncs the residency table at
* its top). prefetch_to_op is called only by tests/place_test.cpp; the
* exact-schedule path is kept built and tested deliberately.
*/
/* `begin_dispatch` and `issue` are the engine's, once a step: Engine::tiering_dispatch is the
* seam, and it is a step and not a layer because the mover relocates BETWEEN steps and never
* during one (runtime/ctx.cpp honours `weights_dirty_` once, at the top of run_step).
*
* `prefetch_to_op` has no caller but tests/place_test.cpp, and that is DELIBERATE -- the
* exact-schedule path is kept built and tested rather than deleted and rewritten later. Do
* not read "no caller" there as the dead-surface shape it resembles elsewhere in this tree. */
int begin_dispatch(int dispatch, HeatEngine* heat);
int prefetch_to_op(int32_t op_index);
int issue(const Swap& s, HeatEngine* heat);
/* ---- the loan: VRAM another pool is not using ------------------------------------------
*
* VRAM some other pool carved and is not using is worth more here than it is there: an
* expert unit that does not fit the slab is read across the link on the critical path of
* every step that routes to it. The KV cache keeps its whole carve backed and LENDS the slab
* the part nothing holds, and the activation arena lends the part a step smaller than the
* largest one does not reach -- each at addresses it already owns, so the slab grows into
* that memory with no allocation, no mapping and no driver call, and gives it back the same
* way. The ONLY caller that may lend is the one that arbitrates the whole card: two callers
* with two opinions about how much is spare is the same memory in two pools.
* An expert that does not fit the slab is read across the link on every step that routes to
* it, so unused VRAM elsewhere is lent to the slab: the part of the KV cache's carve nothing
* holds, and the part of the activation arena that steps smaller than the largest do not
* reach. Both are addresses the lender already owns, so no allocation or mapping is involved.
* Only the caller that arbitrates the whole card may lend.
*
* EACH LENDER LENDS IN ITS OWN MEASURE, into its own segment of the slab (SlotPool): the KV
* cache in tokens, the arena in bytes. They move independently -- a prefill takes the arena's
* memory back while the cache goes on lending -- so every call names the lender it is about.
* Each lender lends in its own measure (KV cache: tokens; arena: bytes) into its own slab
* segment, and they move independently, so every call names its lender.
*
* A UNIT IN A LENT SLOT KEEPS ITS HOST COPY. Weights never change, so the pinned pool slot it
* was promoted from still holds exactly its bytes, and giving the slot back is a change of
* address rather than a copy across the link. That is what makes a loan cheap to recall:
* the cache waits for kernels to stop naming the slot, never for bytes to move. */
* A unit in a lent slot keeps its host copy (weights never change), so giving the slot back
* is a change of address: a recall waits only for kernels to stop naming the slot. */
enum Lender { kLendKV = 0, kLendArena = 1, kLenders = 2 };
/* The stretches a lender may ever lend, once per lender, after its memory is carved. Carves
* every stretch into slots of each class's stride from the top down, so the slots a small loan
* covers are the ones a large loan covers first, and the slot a loan gives back first is the
* deepest. */
/* Registers the stretches a lender may ever lend; once per lender, after its memory is
* carved. Each stretch is cut into slots of each class's stride from the top down, so a small
* loan covers a prefix of a large loan's slots and the deepest slot is given back first. */
int lend_from(int lender, const std::vector<LoanStrip>& strips);
/* HOW MUCH A LENDER LENDS, in its own measure. A TARGET, not a transaction: slots the loan
* newly covers can be filled at once, while slots it no longer covers are emptied as their
* units are dropped and their quarantine clears -- `loan_held` is how far down the lender's
* memory the slab still reaches, and the lender may not use those bytes again until it has
* fallen. */
/* How much a lender lends, in its own measure. A target, not a transaction: newly covered
* slots can be filled at once, while uncovered ones empty as their units drop and their
* quarantine clears. loan_held() is how far into the lender's memory the slab still reaches;
* the lender may not reuse those bytes until it has fallen to the loan. */
int set_loan(int lender, int64_t amount);
int64_t loan_held(int lender) const;
int64_t loan(int lender) const { return loan_[lender]; }
/* THE SAME, NOW, for a lender that cannot wait: every unit past `amount` is dropped to its
* host copy and both streams that can touch a slot are drained before this returns, so the
* memory is the lender's the moment it does. A host wait, taken only when the lender needs
* more than it kept in hand -- a request larger than the cache's buffer, a step larger than
* the arena's lent level allows. */
/* set_loan(), completed before returning: units past `amount` are dropped to their host
* copies and both streams drained. A host wait, for when the lender needs more than it kept
* in hand (a request larger than the cache's buffer, a step larger than the arena allows). */
int reclaim(int lender, int64_t amount, HeatEngine* heat);
/* What the lent slots hold and what the loan offers, in bytes, and every slot the stretches
* could ever hold. Read by the HTTP thread for the dashboard, hence stored rather than
* computed from the slot pools, which only this thread may walk. */
/* Bytes the lent slots hold, bytes the loans offer, and bytes every carved slot could hold.
* The first two are stored because the HTTP thread reads them for the dashboard and only the
* rank thread may walk the slot pools. */
int64_t flex_used_bytes() const { return flex_used_.load(std::memory_order_relaxed); }
int64_t flex_offered_bytes() const { return flex_offered_.load(std::memory_order_relaxed); }
int64_t flex_capacity() const;
@@ -588,33 +458,25 @@ public:
for (const ClassPools& cp : pools_) n += cp.n_turn;
return n;
}
/* THE LOAN PAST WHICH NOTHING MORE WOULD BE USED, in the lender's measure: the one that
* covers every slot carved from it. The slots were carved no deeper than the units the host
* pool holds, so a loan this size already has room for every unit that could move -- more VRAM
* from the lender would sit empty. Zero with nothing carved. */
/* The loan that covers every slot carved from this lender; more would sit empty. Zero when
* nothing is carved. */
int64_t loan_ceiling(int lender) const;
/* FILL EVERY SLOT THERE IS ROOM IN, AND EMPTY EVERY SLOT THE LOAN NO LONGER COVERS -- the
* half-swaps the heat engine never proposes, because its decision is a COMPARISON and a
* comparison needs a victim. Not bounded by a count: a slot left empty while a unit streams
* across the link is VRAM bought and wasted on every step, so every free slot past the
* turnover slots is filled in one call, hottest units first, and the copies run at the rate
* the link carries them. The turnover slots are left free because the engine's swaps land in
* them; filled, they would cap the move rate at what the shadow slots alone allow. When fewer
* than the working and turnover slots are free, the coldest lent units are dropped until
* enough are -- a change of address, never a copy.
/* Fills free lent slots and empties slots the loan no longer covers: the half-swaps the heat
* engine never proposes, since its decisions need a victim. Every free slot past the turnover
* slots is filled in one call, hottest units first, since an empty slot wastes VRAM every
* step. The turnover slots stay free for the engine's swaps; filled, they would cap the move
* rate at the shadow slots. When fewer than the working plus turnover slots are free, the
* coldest lent units are dropped (an address change, never a copy).
*
* `turnover` false treats the turnover slots as room, filled like any other: a step bound by
* its own staging copies swaps nothing (Engine::tiering_dispatch), and every unit resident is
* one its stager does not copy. The next call with it true drops them back out. */
* `turnover` false fills the turnover slots too, for steps bound by their own staging copies
* (Engine::tiering_dispatch); the next call with true drops them back out. */
int balance(HeatEngine* heat, bool turnover = true);
/* balance() for a rank with no step to ride on. Retires what has landed and fills what is
* free, so a loan made while the server is idle is filled before the next request rather
* than by it -- the turnover slots too while they are held. Only while the rank thread is
* parked. */
/* retire() then balance() for an idle rank, so a loan made while idle is filled before the
* next request. Call only while the rank thread is parked. */
int idle_tick(HeatEngine* heat);
/* Whether idle ticks keep the turnover slots filled: the engine holds them through a prompt
/* Whether idle ticks keep the turnover slots filled; the engine holds them through a prompt
* and the few steps after it (Engine::tiering_dispatch). */
void hold_turnover(bool held) { hold_turnover_ = held; }
/* Each class's pinned pool as the card addresses it: [lo, hi) and the unit stride. At most `max`. */
@@ -634,30 +496,23 @@ public:
* unit that has not been staged. */
void* unit_base(int32_t unit) const;
/* ---- STAGING WITHIN A PASS: the prefill stager (core/place/stager.h) ----------------------
/* ---- staging within a pass: the prefill stager (core/place/stager.h) ----------------------
*
* Everything else the mover does happens between steps, and a unit's address is fixed for the
* length of a step. These two are the exception, and they change only the PUBLISHED address,
* never where a unit lives: the unit stays in its pinned pool slot, and for one routed layer's
* ops the run phase reads a copy of it in a buffer the caller owns.
* The only calls that change a unit's address within a step, and only the published one: the
* unit stays in its pinned pool slot, and one routed layer's ops read a copy in a
* caller-owned buffer.
*
* stage_units copy every unit of `units` that lives in the pinned pool, has no slab slot and
* has no copy of its own in flight into `dst`, one after another at the allocation
* unit, until `cap` has no room for the next -- on the mover's stream, behind
* `after` when it is not null, with `done` recorded behind the last copy. Each
* copied unit's weights are then published at the copy, SETTLED: the caller
* orders the ops that read them behind `done` with one stream wait, where an
* event on every weight would cost the run phase one wait per weight -- a few
* hundred a layer. `staged` gets the units copied, in order.
* unstage_units publish those units at their pool slots again. The caller must already have
* ordered the next writer of `dst` behind every op that read the copies; this
* only moves the address the NEXT issue resolves.
* stage_need the room stage_units would fill with `units` given room for all of them, so
* a caller packing several layers into one region can size each one's share;
* `largest`, when not null, gets the room the largest of those units takes.
* stage_units copies each pooled unit of `units` with no slab slot and no copy in flight
* into `dst`, packed at the allocation unit; a unit with no room is read in
* place. Runs on the mover's stream behind `after` (if set) and records `done`.
* Copies are published settled: the caller waits on `done` once instead of
* once per weight (a few hundred per layer).
* unstage_units publishes those units at their pool slots again. The caller must already have
* ordered the next writer of `dst` behind every reader of the copies.
* stage_need the room stage_units would use with no cap, for sizing shares of a region;
* `largest`, if set, gets the largest unit's room.
*
* The span form packs into up to two stretches, the second taking what the first has no
* room left for: a ring's place that wraps past the region's end is two.
* The span form packs into up to two stretches (a ring region that wraps is two).
*/
struct StageSpan { char* dst; int64_t cap; };
int stage_units(const std::vector<int32_t>& units, char* dst, int64_t cap, RadEvent after,
@@ -667,24 +522,19 @@ public:
void unstage_units(const std::vector<int32_t>& staged);
int64_t stage_need(const std::vector<int32_t>& units, int64_t* largest = nullptr) const;
/* ---- ROUTED LAYERS READ FROM THE CONTAINER: the file stager (core/place/stager.h) --------
/* ---- routed layers read from the container: the file stager (core/place/stager.h) --------
*
* A routed unit the plan put on the file tier has no address at all (unit_base is null), and a
* grouped GEMM is handed every expert's pointer at issue -- so before a routed layer's first
* expert op, every one of its file-tier units is read into a VRAM buffer and published there,
* and after the layer it is published as null again (unstage_units does that half). The
* buffers are the two the plan charged out of the weights pool (Plan::file_stage_vram).
* A file-tier unit has no address, but a grouped GEMM takes every expert's pointer at issue.
* So before a routed layer's first expert op its file-tier units are read into a VRAM buffer
* and published there; afterwards unstage_units publishes them as null again. The plan
* charges the two buffers to the weights pool (Plan::file_stage_vram).
*
* stage_file_units read every unit of `units` that is on the file tier into `dst`, packed at
* RAD_ALIGN_UNIT in the order given, through the pinned read windows: the
* layer's weights are read in container order as long runs -- a run skips a
* gap of resident units rather than reading through it -- each window drains
* to `dst` on the mover's stream while the next fills, behind `after` when it
* is not null, with `done` recorded behind the last copy. Published SETTLED,
* for the reason stage_units gives. Refuses with RAD_E_SCRATCH when the units
* do not fit `cap`, which a buffer sized by the plan never meets. The reads
* are BLOCKING on this thread; that is the price of the tier and the stats
* above carry it.
* stage_file_units reads every file-tier unit of `units` into `dst`, packed at RAD_ALIGN_UNIT
* in the order given, through the pinned read windows: container-order
* runs, each window draining to `dst` on the mover's stream while the next
* fills, behind `after` (if set), with `done` recorded last. Published
* settled. RAD_E_SCRATCH if the units exceed `cap`. The reads block this
* thread.
* file_buffer buffer 0 or 1 of the plan's two, or null when the plan has none. */
int stage_file_units(const std::vector<int32_t>& units, char* dst, int64_t cap,
RadEvent after, RadEvent done, std::vector<int32_t>* staged);
@@ -697,22 +547,18 @@ public:
std::string report() const;
private:
/* One in-flight relocation. The state machine is Free -> Copying -> Published -> Quarantine
* -> Free, and every transition is made by the DISPATCH THREAD at a layer boundary. The
* transfers are asynchronous; the table edits are not. No mutex on the read side, because
* that side is the critical path of every layer, and no background thread mutating placement
* mid-layer, because placement would then depend on host timing and stop being reproducible. */
/* One in-flight relocation: Free -> Copying -> Published -> Quarantine -> Free. Transfers
* are asynchronous; every transition is made by the dispatch thread at a layer boundary. No
* mutex on the read side (it is on every layer's critical path) and no background thread,
* which would make placement depend on host timing. */
struct Move {
enum class State { Free, Copying, Published, Quarantine };
/* Six kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is
* the exact prefetch bringing an offloaded unit into a slot. Release is the same slot
* going back once the declared order says nothing will read it again this step -- it
* copies nothing and still needs the quarantine, because the barrier is about kernels
* already issued and not about bytes in flight. Drop is a unit in a lent slot going back
* to the host copy it kept: no copy either, and the same quarantine for the same reason.
* Migrate is a donor (Mover::donor_slot) leaving a lent slot the loan no longer covers
* for a free budgeted one, a copy inside the card; `slab_slot` is the slot it leaves and
* `to_slot` the one it lands in. */
/* Promote/Demote: the heat engine's swaps. Stage: the exact prefetch copying an offloaded
* unit into a slot; Release: that slot returned after its last use this step. Drop: a
* unit in a lent slot back to its kept host copy. Release and Drop copy nothing but still
* need the quarantine, which guards issued kernels, not bytes in flight. Migrate: a donor
* (Mover::donor_slot) from an uncovered lent slot (`slab_slot`) to a free budgeted one
* (`to_slot`). */
enum class Kind { Promote, Demote, Stage, Release, Drop, Migrate };
State state = State::Free;
Kind kind = Kind::Promote;
@@ -721,6 +567,14 @@ private:
int64_t pool_slot = -1;
int64_t to_slot = -1;
RadEvent ev = nullptr;
void clear() {
state = State::Free;
unit = -1;
slab_slot = pool_slot = to_slot = -1;
}
/* Whether the move hands `slab_slot` back once its quarantine clears. */
bool frees_slab() const { return kind != Kind::Promote && kind != Kind::Stage; }
};
struct UnitState {
@@ -733,16 +587,10 @@ private:
int64_t bytes = 0;
};
/* One weight class's memory. The slab is two kinds of slot rather than one: the BUDGETED slots
* come out of the weights pool like every other weight allocation and sit at a fixed stride
* from one base, and the FLEX slots past them are addresses inside another pool's memory --
* the KV cache's carve, the activation arena's top -- lent while that pool is not using them.
* They cannot be one range because the flex slots are scattered over every layer's stripe of
* the cache, wherever a stripe has room for one.
*
* A slot index therefore carries no information about which kind it is; slot_ptr is the only
* place that distinction exists. Each lender's flex slots are one segment of the slab, ordered
* by the loan that covers each, so a loan of any size is a prefix of its segment. */
/* One weight class's memory. Budgeted slots sit at a fixed stride from one base in the
* weights pool. Flex slots after them are lent addresses scattered over another pool's memory
* (KV cache stripes, arena top), so only slot_ptr() can resolve a slot index. Each lender's
* flex slots form one segment ordered by covering loan, so any loan covers a prefix. */
struct ClassPools {
SlotPool slab, pool;
void* slab_base = nullptr;
@@ -757,14 +605,12 @@ private:
int64_t n_donated = 0; /* units in lent slots that gave their host copy away
* (Mover::donor_slot); at most n_turn of them */
std::vector<char*> flex_ptr;
/* ONE SEGMENT OF THE SLAB PER LENDER THAT CARVED SLOTS FOR THIS CLASS. `need[i]` is the
* loan, in the lender's measure, that covers the segment's i-th slot; ascending, so a
* loan of any size covers a prefix. */
/* One slab segment per lender that carved slots for this class. `need[i]` is the loan,
* in the lender's measure, that covers the segment's i-th slot; ascending. */
struct Lent { int lender = 0; int seg = -1; int64_t first = 0; std::vector<int64_t> need; };
std::vector<Lent> lent;
/* A slot leaves coverage only when a loan shrinks, and nothing is ever placed in an
* uncovered one, so units stranded past the loan exist only after a shrink. Set there, and
* cleared by a balance() sweep that dropped every one of them. */
/* Units can sit past the loan only after a shrink, since nothing is placed in an
* uncovered slot. Set on a shrink; cleared by a balance() sweep that removed them all. */
bool strand_check = true;
char* slot_ptr(int64_t slot) const {
@@ -780,8 +626,8 @@ private:
Residency res_;
MoverStats stats_;
Pools* budget_ = nullptr;
/* True only when this object called the allocator itself, which is the test path. A Pool
* reservation is owned by the Pool and freeing it here would be a double free. */
/* True only when this object called the allocator itself (the test path). A Pool
* reservation belongs to the Pool; freeing it here would be a double free. */
bool owns_memory_ = false;
RadStream mover_ = nullptr;
@@ -792,29 +638,29 @@ private:
std::vector<StagePick> stage_picks_; /* the units stage_units may take, in pool order */
int gate_dispatch_ = -1;
/* A DISPATCH'S SWAP COPIES -- demotions, promotions and migrations -- GO TO THE CARD'S DMA ENGINE
* AS ONE LIST (flush_moves), sent at the end of balance() and before anything reads their events.
* Each move's event is recorded behind the list, so a move lands with its list. */
/* A dispatch's swap copies (demotions, promotions, migrations) go to the card's DMA engine as
* one list (flush_moves), sent at the end of balance() and before anything reads their
* events. Each move's event is recorded after the list. */
std::vector<RadCopySeg> move_segs_;
std::vector<int32_t> move_recs_;
int queue_move_copy(void* dst, const void* src, int64_t bytes, int rec);
void queue_move_copy(void* dst, const void* src, int64_t bytes, int rec);
int flush_moves();
std::vector<ClassPools> pools_;
std::vector<UnitState> unit_;
std::vector<Move> moves_;
/* Per unit, how many records are Copying it: unit_in_flight() without a walk of the records.
* The prefill stager asks for every pooled unit of every layer it stages, and the records
* number twice the slots a swap can hold, so a walk would grow with the move budget. */
/* Per unit, how many records are Copying it, so unit_in_flight() needs no walk of the
* records. The prefill stager asks about every pooled unit it stages, and the record count
* grows with the move budget. */
std::vector<uint16_t> copying_;
/* balance()'s drop candidates, (heat, unit), kept between calls so a step allocates nothing. */
std::vector<std::pair<float, int32_t>> drop_cand_;
bool hold_turnover_ = false;
/* donor_slot()'s candidates a class, by layer, each layer's coldest first so its hottest is at
* the back; ranked once a dispatch, `at` being the dispatch they were ranked for. */
/* donor_slot()'s candidates per class, by layer, each layer sorted coldest first (hottest at
* the back). Ranked once per dispatch; `at` is that dispatch. */
struct DonorRank { int at = -1; std::vector<std::vector<std::pair<float, int32_t>>> by_layer; };
std::vector<DonorRank> donors_;
/* The layer whose unit each pool slot held when the pool was laid out, a class: the pool is
* filled in unit order, so a layer's pooled units start out side by side (pool_slot_for). */
/* Per class, the layer of the unit each pool slot held at layout. The pool is filled in unit
* order, so a layer's pooled units start out adjacent (pool_slot_for). */
std::vector<std::vector<int32_t>> pool_layer_;
int32_t n_layers_ = 0;
@@ -846,13 +692,12 @@ private:
int32_t last_op_ = -1;
int dispatch_ = 0;
/* THE LOAN, in the owner's tokens, and what the dashboard reads of it. */
/* Each lender's loan in its own measure, and the totals the dashboard reads. */
int64_t loan_[kLenders] = {};
std::atomic<int64_t> flex_used_{0};
std::atomic<int64_t> flex_offered_{0};
/* Where the last free record was found. Records free up roughly in the order they were taken,
* so starting the next search there makes it a step rather than a walk of every record, which
* matters once the lent slots have put a record's worth of them in flight. */
/* Where the last free record was found. Records free up roughly in the order they were
* taken, so starting there keeps the search short when lent slots put many in flight. */
mutable size_t rec_cursor_ = 0;
int retire(HeatEngine* heat);
@@ -863,14 +708,16 @@ private:
int start_stage(int32_t unit, int64_t slab_slot);
void release_slot(int32_t unit);
bool unit_in_flight(int32_t unit) const;
/* Whether stage_units would copy `unit`: pooled, with no slab slot and no copy in flight. */
bool stageable(int32_t unit) const;
/* A unit in a lent slot back to the host copy it kept. See Move::Kind::Drop. */
int drop(int32_t unit, HeatEngine* heat);
/* The pool slot a demotion copies `unit` into: one its layer's units started out in, else a
* same-layer donor's, else any free one, else any donor's; -1 when there is none. */
int64_t pool_slot_for(int32_t unit, HeatEngine* heat);
/* A pool slot for a budgeted victim when the pool has none free: the host copy of a unit in a
* slot the KV cache lent, which keeps its place in VRAM without one -- a unit of `layer`, or
* of any layer when it is negative. -1 when no unit may give one. See the definition. */
/* A pool slot for a budgeted victim when none is free: the host copy of a unit in a KV-lent
* slot, which stays in VRAM without it. From a unit of `layer`, or of any layer when
* negative; -1 when no unit may give one. Rationale at the definition. */
int64_t donor_slot(size_t klass, int32_t layer, HeatEngine* heat);
/* A donor out of a lent slot into a free budgeted one, if one is free: false when none is. */
bool migrate(int32_t unit, HeatEngine* heat);