Archived
radiance 1.4.0
- Qwen3.8-Flash-Next on one card: the heat engine moves 64 experts a step (was 8), its copies and the prefill's expert staging run on the card's DMA engines instead of as copy kernels, and at decode the next layer's likeliest experts are copied onto the card ahead of its GEMMs. Against 1.3.0 at --tp 1: prefill +17-20% from 8K tokens up, throughput under load +16-20% - deploy/compose/flashnext-tp1.yaml: Qwen3.8-Flash-Next on one card and 64 GB of host RAM (4096-token prefill steps, 4 sequences, a 301K-token cache) - #61: --busy-prefill-chunk (default auto): a long prefill leaves the rest of the step to the requests decoding beside it and to new arrivals, instead of taking all of it (baKon) - LiquidAI's LFM2 and LFM2-VL, and d1's /v1/systemone (after zivius's PR #50) - a startup report: every option with its value and where it came from, the hardware, and what on it costs speed with the fix; /diagnostics serves it (behind the API key; without one, only to the same machine) - #69: a GPU memory fault names the buffer and kernel argument behind it and ends the server at once (exit status 70), instead of hanging or writing a core of tens of gigabytes - #64: a card without Resizable BAR is refused at startup, naming what to turn on, instead of crashing at the first launch - the image is built with ROCm 10.1 (the host's amdgpu driver must support it), with ROCm's libLLVM rebuilt so the same source compiles to the same kernels every time; a source build takes ROCm 10.1 or 7.2 - #71: the image ships curl, jq and a CA bundle, so --model <HF repo id> works in the container, and hfget.sh runs under its busybox (baKon) - --profile-ops shows how long each op's lane sat idle before it; cardclock.py skips an integrated GPU instead of stopping
This commit is contained in:
1 parent
d5b65cddc6
commit
dc339b4cd2
153 files changed
+12956
-1067
No files matched your search
+20
-12
@@ -139,11 +139,12 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
|
||||
return RAD_OK;
|
||||
}
|
||||
enabled_ = true;
|
||||
RAD_INFO("heat engine: %lld movable units, %d move%s a dispatch, "
|
||||
"decay %.3f hysteresis %.2f min-gain %.2f",
|
||||
(long long)movable, params_.moves_per_dispatch,
|
||||
params_.moves_per_dispatch == 1 ? "" : "s",
|
||||
(double)params_.decay, (double)params_.hysteresis, (double)params_.min_gain);
|
||||
RAD_INFO("heat engine: %lld movable units, %d move%s a step, "
|
||||
"decay %.3f hysteresis %.2f min-gain %.2f credit cap %.0f",
|
||||
(long long)movable, params_.moves_per_step,
|
||||
params_.moves_per_step == 1 ? "" : "s",
|
||||
(double)params_.decay, (double)params_.hysteresis, (double)params_.min_gain,
|
||||
(double)params_.credit_cap);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -206,6 +207,13 @@ void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert,
|
||||
* (prefetch()), which makes this a no-op. */
|
||||
prefetch(counts, n);
|
||||
|
||||
/* The credit cap (HeatParams::credit_cap) scales the whole histogram, so its experts keep
|
||||
* their order. The pricing below counts every pass whatever the credit is. */
|
||||
int64_t total = 0;
|
||||
for (int32_t j = 0; j < n; ++j) total += counts[j] > 0 ? counts[j] : 0;
|
||||
const float cap = params_.credit_cap;
|
||||
const float w = cap > 0.0f && (float)total > cap ? weight * cap / (float)total : weight;
|
||||
|
||||
float* __restrict h = heat_.data() + lo;
|
||||
for (int32_t j = 0; j < len; ++j) h[j] *= d;
|
||||
|
||||
@@ -219,7 +227,7 @@ void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert,
|
||||
const int32_t c = counts[j];
|
||||
const size_t q = (size_t)(lo + j);
|
||||
const float was = h[j];
|
||||
const float x = was + (float)c * weight;
|
||||
const float x = was + (float)c * w;
|
||||
h[j] = x;
|
||||
routed += routed_as_[q] != 0;
|
||||
resident += routed_as_[q] == 2;
|
||||
@@ -380,12 +388,12 @@ bool HeatEngine::pick(Swap* out) const {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* THE WHOLE DISPATCH'S PROPOSALS FROM ONE PASS. Marking a pair busy changes neither a unit's heat
|
||||
* nor any layer's resident count, so the m-th pair repeated pick() calls would return is simply the
|
||||
* m-th entry at each end of the same ranking. One pass keeps the `moves_per_dispatch` best of each
|
||||
/* THE WHOLE STEP'S PROPOSALS FROM ONE PASS. Marking a pair busy changes neither a unit's heat nor
|
||||
* any layer's resident count, so the m-th pair repeated pick() calls would return is simply the
|
||||
* m-th entry at each end of the same ranking. One pass keeps the `moves_per_step` best of each
|
||||
* end; the proposals, and the counters that say why the list stopped, are the ones the repeated
|
||||
* picks produce. This runs before every pass a rank issues -- draft passes included, where the
|
||||
* device waits for the issue -- so a scan per proposed move would be most of its cost. */
|
||||
* picks produce. This runs once a step on the thread that issues the next one, and the budget is
|
||||
* dozens of swaps, so a scan per proposed move would be most of its cost. */
|
||||
namespace {
|
||||
using Ranked = HeatRanked;
|
||||
/* Hotter first, then the layer with fewer residents, then the lower index. */
|
||||
@@ -414,7 +422,7 @@ int HeatEngine::step(std::vector<Swap>* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
out->clear();
|
||||
if (!enabled_) return RAD_OK;
|
||||
const int k = params_.moves_per_dispatch;
|
||||
const int k = params_.moves_per_step;
|
||||
if (k <= 0) return RAD_OK;
|
||||
|
||||
/* THE BEST PAIR FROM THE LAYERS' ENDS FIRST. If it fails the guard every pair does -- the
|
||||
|
||||
+48
-33
@@ -35,14 +35,15 @@
|
||||
* ---- WHY LFU-WITH-DECAY AND NOT SOMETHING CLEVERER --------------------------------------------
|
||||
*
|
||||
* Replaying real routing traces against cache policies settles the shape of this. Runtime
|
||||
* placement beats static profile placement by a wide margin, so it is worth building; LFU-with-
|
||||
* decay and LRU score the same, so the decay constant is not where the wins are and this does not
|
||||
* need to be subtle. Belady is a few points of hit rate above both -- but an oracle restricted to
|
||||
* a disjoint sample of the future keeps most of that gap, so the remainder is knowledge of the
|
||||
* realised future and is not reachable. Of what is left, no statistic of PAST USE captures any of
|
||||
* it: an expert never selected has count zero, no age and no history, and most of the space is in
|
||||
* that state. The router's own gate value does separate those cases, so a scorer built on it is
|
||||
* the one direction here that measurement has not refuted.
|
||||
* placement beats static profile placement by a wide margin, so it is worth building. What bounds
|
||||
* it is the MOVE RATE, not the ranking: held to the same swaps a step at the same step boundaries,
|
||||
* an oracle that knows every future routing scores no better than this policy (78.0% against 78.4%
|
||||
* at 64 swaps a step, Qwen3.8-Flash-Next TP1 with 40% of the experts resident). The unrestricted
|
||||
* Belady figure is far higher -- 92% on the same trace -- because it admits every miss the moment
|
||||
* it happens, and a miss admitted here is a second copy of bytes the GEMM has just streamed. So
|
||||
* the decay constant and the guards are not where the wins are, and this does not need to be
|
||||
* subtle; the budget (RAD_PLACE_MOVES_PER_STEP), the slots behind it, and keeping a prompt's
|
||||
* routing from swamping the answer's (HeatParams::credit_cap) are.
|
||||
*/
|
||||
#pragma once
|
||||
#include "planner.h"
|
||||
@@ -53,14 +54,15 @@
|
||||
namespace rad {
|
||||
|
||||
struct HeatParams {
|
||||
/* Applied to a layer's whole plane each time that layer is dispatched. Every layer is
|
||||
* dispatched exactly once per forward, so all planes decay in lockstep and heats stay
|
||||
* comparable ACROSS layers -- which the global ranking below depends on.
|
||||
/* Applied to a layer's whole plane each time that layer's histogram is credited. Every layer is
|
||||
* credited once a step, so all planes decay in lockstep and heats stay comparable ACROSS
|
||||
* layers -- which the global ranking below depends on.
|
||||
*
|
||||
* 0.98 is a half-life of a few dozen dispatches: long enough to survive a paragraph, short
|
||||
* enough to follow a change of subject. Nearby values are not distinguishable from each other
|
||||
* above the run-to-run spread, which is what the offline replay predicts. */
|
||||
float decay = 0.98f;
|
||||
* 0.95 is a half-life of about fourteen steps. At 64 swaps a step the replay is flat from 0.8
|
||||
* to 0.95 (77.96% to 78.37%) and falls off above it -- 77.1% at 0.98, 74.2% at 0.99 -- because
|
||||
* a heat that remembers longer ranks the experts a conversation has moved past above the ones
|
||||
* it routes to now. */
|
||||
float decay = 0.95f;
|
||||
|
||||
/* Promote only when the candidate beats the victim by this ratio. Without it the two ends of
|
||||
* the ranking trade places on noise and the engine spends the whole link on churn that
|
||||
@@ -79,27 +81,40 @@ struct HeatParams {
|
||||
* MISS, and a miss is a shard streamed over the same link on the same budget. A tighter bar
|
||||
* then gives up hit rate and buys no traffic back.
|
||||
*
|
||||
* The exchange rate behind the value: the two link directions share one budget, so
|
||||
* a demotion costs about what a promotion does, and a swap therefore has to repay about 1.4
|
||||
* future hits rather than the 0.74 a half-price demotion would imply. */
|
||||
* What a swap costs is its promotion. The link is close to full duplex -- on an R9700, 28.5
|
||||
* GB/s up and 25.0 down at once, against 28.8 up alone -- so a demotion's copy rides the idle
|
||||
* direction, while a promotion shares the upstream one with every miss the GEMM streams. At
|
||||
* the default budget lower values replay within 0.2 points of hit rate and promote a fifth
|
||||
* more. */
|
||||
float min_gain = 1.5f;
|
||||
|
||||
/* A BOUNDED MOVE BUDGET PER LAYER DISPATCH. The apparent risk is that a high budget makes the
|
||||
* mover compete with the tier it is trying to shrink -- a promotion and a streamed miss are
|
||||
* the same bytes over the same link. At this scale that does not bind: a larger budget pays
|
||||
* even though it moves considerably more bytes, because converging sooner is worth more than
|
||||
* the traffic costs. The benefit then SATURATES, and this sits where the knob stops mattering
|
||||
* rather than at the largest value that still helps. Past that point the guard, not the
|
||||
* budget, is what declines the extra opportunities -- so raising this alone is worth nothing
|
||||
* until min_gain moves with it.
|
||||
/* A BOUNDED MOVE BUDGET PER STEP: step() is called once a step, after every layer's histogram
|
||||
* has been credited, and proposes at most this many swaps a slab class. The value and why it
|
||||
* is that are at RAD_PLACE_MOVES_PER_STEP, which also sizes the free slots a swap lands in
|
||||
* (the shadow and turnover slots); a budget raised here without them is spent on
|
||||
* `starved_slab`.
|
||||
*
|
||||
* The apparent risk is that a high budget makes the mover compete with the tier it is trying
|
||||
* to shrink -- a promotion and a streamed miss are the same bytes over the same link. At this
|
||||
* scale that does not bind: each swap moves an expert the ranking says will be read again
|
||||
* soon, and the misses it saves are many times its own bytes.
|
||||
*
|
||||
* IT IS A BUDGET PER SLAB CLASS. A rank holding an uneven slice of every expert has two expert
|
||||
* classes -- the wider slice of one parity's experts and the narrower slice of the other's --
|
||||
* each about half a whole expert, and a budget shared between them would move half the bytes
|
||||
* a dispatch that whole experts do: residency would converge half as fast, and a fresh server
|
||||
* would run about 2% slower for its first minute. Per class, the two together move about as
|
||||
* many whole experts as one class of whole experts does. */
|
||||
int moves_per_dispatch = 8;
|
||||
* a step that whole experts do: residency would converge half as fast. Per class, the two
|
||||
* together move about as many whole experts as one class of whole experts does. */
|
||||
int moves_per_step = RAD_PLACE_MOVES_PER_STEP;
|
||||
|
||||
/* THE MOST ONE HISTOGRAM CREDITS, in selections: a histogram that routed more is credited
|
||||
* at this total, each expert in proportion to its count. A decode step routes a few rows a
|
||||
* sequence and stays under it; a prefill chunk routes thousands, and at full weight one chunk
|
||||
* outweighs dozens of decode steps, so for that many steps after a prompt the resident set is
|
||||
* the prompt's rather than the answer's. What the resident set buys a prefill is little in
|
||||
* any case: a chunk reads nearly every expert of a layer, and the stager copies whichever are
|
||||
* not resident. Replaying a mixed workload at Qwen3.8-Flash-Next TP1, decode rows hit 77.3%
|
||||
* uncapped, 78.9% at 1024 and 79.0% at 512 or 256. */
|
||||
float credit_cap = 512.0f;
|
||||
|
||||
/* Dispatches to watch before moving anything, and it is 0 because THE GUARD ALREADY DOES THIS
|
||||
* JOB. min_gain means a promotion needs `hot >= cold*hysteresis + 1.5`, and against a
|
||||
@@ -195,7 +210,7 @@ public:
|
||||
/* The best swap available, or false when the guards refuse. */
|
||||
bool pick(Swap* out) const;
|
||||
|
||||
/* One layer dispatch's worth of proposals, at most `moves_per_dispatch` of them a class.
|
||||
/* One step's worth of proposals, at most `moves_per_step` of them a class.
|
||||
*
|
||||
* CONTRACT: every unit named in the result is marked busy on the way out. The caller must
|
||||
* either issue the transfer -- in which case set_tier() on publish and set_busy(false) after
|
||||
@@ -284,8 +299,8 @@ private:
|
||||
* unit's class as a dense index, -1 for a unit that cannot move. */
|
||||
std::vector<int32_t> cls_;
|
||||
int32_t n_cls_ = 1;
|
||||
/* step()'s two ends of the ranking, `moves_per_dispatch` entries a class, kept between calls
|
||||
* so a dispatch allocates nothing. */
|
||||
/* step()'s two ends of the ranking, `moves_per_step` entries a class, kept between calls so a
|
||||
* step allocates nothing. */
|
||||
std::vector<HeatRanked> rank_hot_, rank_cold_;
|
||||
std::vector<int32_t> n_hot_, n_cold_, m_of_;
|
||||
/* Per slot, its lowest movable unit index: the bound step()'s layer screen needs on a tie. */
|
||||
|
||||
+369
-69
@@ -90,6 +90,7 @@ Mover::~Mover() {
|
||||
* that name the events below and the copies into and out of the memory below, so each of
|
||||
* those goes only once nothing queued refers to it. */
|
||||
if (mover_) {
|
||||
(void)flush_moves();
|
||||
rad_stream_sync(mover_);
|
||||
rad_stream_destroy(mover_);
|
||||
}
|
||||
@@ -138,6 +139,11 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
"it is a test path and not a deployment.");
|
||||
|
||||
unit_.assign(plan.units.size(), UnitState{});
|
||||
copying_.assign(plan.units.size(), 0);
|
||||
pool_layer_.assign(plan.classes.size(), {});
|
||||
donors_.assign(plan.classes.size(), DonorRank{});
|
||||
n_layers_ = 0;
|
||||
for (const MoveUnit& mu : plan.units) n_layers_ = std::max(n_layers_, mu.layer + 1);
|
||||
pools_.clear();
|
||||
pools_.resize(plan.classes.size());
|
||||
|
||||
@@ -162,6 +168,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
static_need = us.static_off + mu.bytes;
|
||||
} else if (mu.tier == Tier::HostPinned) {
|
||||
us.pool_slot = n_pool[(size_t)mu.slab_class]++;
|
||||
pool_layer_[(size_t)mu.slab_class].push_back(mu.layer);
|
||||
} else if (mu.tier == Tier::HostPageable) {
|
||||
us.static_off = align_up(pageable_need, RAD_ALIGN_UNIT);
|
||||
pageable_need = us.static_off + mu.bytes;
|
||||
@@ -170,7 +177,7 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
}
|
||||
|
||||
/* ---- allocate ------------------------------------------------------------------------- */
|
||||
int64_t total_shadow = 0;
|
||||
int64_t total_shadow = 0, total_turn = 0;
|
||||
for (size_t c = 0; c < plan.classes.size(); ++c) {
|
||||
const SlabClass& sc = plan.classes[c];
|
||||
ClassPools& cp = pools_[c];
|
||||
@@ -193,6 +200,9 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
* lend_from() adds them once it is. */
|
||||
cp.n_fixed = slab_slots;
|
||||
cp.n_work = shadow + sc.n_stage;
|
||||
cp.n_turn = std::min<int64_t>(std::max(cfg.turnover_slots, 0),
|
||||
shadow * RAD_PLACE_TURNOVER_SLOTS / RAD_PLACE_SHADOW_SLOTS);
|
||||
total_turn += cp.n_turn;
|
||||
cp.slab.init(slab_slots, sc.stride);
|
||||
if (slab_slots > 0) {
|
||||
/* Tail padding: a kernel that assembles a packed code window from a wide read
|
||||
@@ -366,13 +376,13 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
lead_.assign((size_t)lead + 1, nullptr);
|
||||
for (RadEvent& e : lead_) RAD_TRY(rad_event_create_as(&e, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT));
|
||||
|
||||
/* TWO records per shadow slot, not one. A promotion holds a slab slot for its whole life, so
|
||||
* there can never be more promotions in flight than there are shadows -- but a swap is two
|
||||
* transfers, and the matching demotion needs a record of its own or the pair can never be in
|
||||
* flight together and the engine never issues a demotion at all. That failure is silent: it
|
||||
* shows up as `no_record` where the real symptom is a resident set that only ever grows.
|
||||
* The floor is what makes a one-shadow plan still able to hold a swap. */
|
||||
const int64_t n_records = std::max<int64_t>(2 * total_shadow, 4);
|
||||
/* TWO records per free slot, shadow or turnover, not one. A promotion holds a slab slot for
|
||||
* its whole life, so there can never be more promotions in flight than there are free slots --
|
||||
* but a swap is two transfers, and the matching demotion needs a record of its own or the pair
|
||||
* can never be in flight together and the engine never issues a demotion at all. That failure
|
||||
* is silent: it shows up as `no_record` where the real symptom is a resident set that only ever
|
||||
* grows. The floor is what makes a one-shadow plan still able to hold a swap. */
|
||||
const int64_t n_records = std::max<int64_t>(2 * (total_shadow + total_turn), 4);
|
||||
moves_.assign((size_t)n_records, Move{});
|
||||
for (Move& m : moves_) RAD_TRY(rad_event_create_local(&m.ev));
|
||||
|
||||
@@ -383,9 +393,10 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
republish(u);
|
||||
}
|
||||
|
||||
RAD_INFO("mover: %lld slab slots (%lld shadow), %lld pinned pool slots, %s static vram%s",
|
||||
RAD_INFO("mover: %lld slab slots (%lld shadow, %lld more kept free out of a loan), %lld pinned "
|
||||
"pool slots, %s static vram%s",
|
||||
(long long)[&] { int64_t n = 0; for (auto& c : pools_) n += c.slab.size(); return n; }(),
|
||||
(long long)total_shadow,
|
||||
(long long)total_shadow, (long long)total_turn,
|
||||
(long long)[&] { int64_t n = 0; for (auto& c : pools_) n += c.pool.size(); return n; }(),
|
||||
humanb(static_bytes_).c_str(), file_.ok() ? ", file tier open" : "");
|
||||
/* The pageable host region is allocated here and charged to no budget -- Pools has no
|
||||
@@ -436,9 +447,7 @@ void Mover::republish(int32_t unit) {
|
||||
* a record past Copying has its bytes in place, and treating it as in-flight holds the slot for
|
||||
* as long as the record takes to recycle rather than as long as the copy takes to land. */
|
||||
bool Mover::unit_in_flight(int32_t unit) const {
|
||||
for (const Move& m : moves_)
|
||||
if (m.state == Move::State::Copying && m.unit == unit) return true;
|
||||
return false;
|
||||
return unit >= 0 && (size_t)unit < copying_.size() && copying_[(size_t)unit] > 0;
|
||||
}
|
||||
|
||||
int Mover::free_move_record() const {
|
||||
@@ -577,6 +586,7 @@ int Mover::start_stage(int32_t unit, int64_t slab_slot) {
|
||||
m.state = Move::State::Copying;
|
||||
m.kind = Move::Kind::Stage;
|
||||
m.unit = unit;
|
||||
++copying_[(size_t)unit];
|
||||
m.slab_slot = slab_slot;
|
||||
m.pool_slot = -1;
|
||||
stats_.h2d_bytes += (uint64_t)us.bytes;
|
||||
@@ -602,42 +612,76 @@ int Mover::start_stage(int32_t unit, int64_t slab_slot) {
|
||||
/* ---- staging within a pass (see mover.h) ---------------------------------------------------- */
|
||||
int Mover::stage_units(const std::vector<int32_t>& units, char* dst, int64_t cap, RadEvent after,
|
||||
RadEvent done, std::vector<int32_t>* staged) {
|
||||
if (!plan_ || !dst || !staged || !done) return RAD_E_INVAL;
|
||||
const StageSpan one{dst, cap};
|
||||
return stage_units(units, &one, 1, after, done, staged);
|
||||
}
|
||||
|
||||
int Mover::stage_units(const std::vector<int32_t>& units, const StageSpan* spans, int n_spans,
|
||||
RadEvent after, RadEvent done, std::vector<int32_t>* staged) {
|
||||
if (!plan_ || !spans || n_spans < 1 || n_spans > 2 || !staged || !done) return RAD_E_INVAL;
|
||||
for (int k = 0; k < n_spans; ++k)
|
||||
if (!spans[k].dst) return RAD_E_INVAL;
|
||||
staged->clear();
|
||||
std::vector<int64_t> at;
|
||||
at.reserve(units.size());
|
||||
int64_t off = 0;
|
||||
bool waited = false;
|
||||
stage_picks_.clear();
|
||||
for (int32_t u : units) {
|
||||
if (u < 0 || (size_t)u >= unit_.size()) return RAD_E_INVAL;
|
||||
const UnitState& us = unit_[(size_t)u];
|
||||
if (us.tier != Tier::HostPinned || us.pool_slot < 0 || us.slab_slot >= 0 || us.klass < 0)
|
||||
continue;
|
||||
if (unit_in_flight(u)) continue;
|
||||
const int64_t need = align_up(us.bytes, RAD_ALIGN_UNIT);
|
||||
if (off + need > cap) { ++stats_.stage_overflow; continue; }
|
||||
if (!waited) {
|
||||
if (after) RAD_TRY(rad_event_wait(mover_, after));
|
||||
waited = true;
|
||||
}
|
||||
const ClassPools& cp = pools_[(size_t)us.klass];
|
||||
const char* src = (const char*)cp.pool_base + us.pool_slot * cp.stride;
|
||||
RAD_TRY(rad_memcpy_async(dst + off, src, us.bytes, mover_));
|
||||
staged->push_back(u);
|
||||
at.push_back(off);
|
||||
stats_.h2d_bytes += (uint64_t)us.bytes;
|
||||
stats_.staged_bytes += (uint64_t)us.bytes;
|
||||
off += need;
|
||||
stage_picks_.push_back(StagePick{src, u, us.bytes, align_up(us.bytes, RAD_ALIGN_UNIT),
|
||||
nullptr});
|
||||
}
|
||||
if (staged->empty()) return RAD_OK;
|
||||
if (stage_picks_.empty()) return RAD_OK;
|
||||
/* THE SPANS ARE FILLED IN POOL ORDER, so units on neighbouring pool slots land side by side
|
||||
* and go as one copy. A layer's pooled experts were given their slots together and mostly
|
||||
* still hold them, so a layer's ~90 units go as fewer copies -- each one a launch or a DMA
|
||||
* packet whatever its size. A class's stride is its units' aligned size, so a run's source and
|
||||
* destination advance alike, padding included. A unit the span in hand has no room left for
|
||||
* goes to the start of the next; one that no span has room for is read across the link in
|
||||
* place. */
|
||||
std::sort(stage_picks_.begin(), stage_picks_.end(),
|
||||
[](const StagePick& a, const StagePick& b) { return a.src < b.src; });
|
||||
int k = 0;
|
||||
int64_t off = 0;
|
||||
size_t taken = 0;
|
||||
for (StagePick& p : stage_picks_) {
|
||||
if (off + p.need > spans[k].cap && k + 1 < n_spans && p.need <= spans[k + 1].cap) {
|
||||
++k;
|
||||
off = 0;
|
||||
}
|
||||
if (off + p.need > spans[k].cap) { ++stats_.stage_overflow; continue; }
|
||||
p.dst = spans[k].dst + off;
|
||||
off += p.need;
|
||||
++taken;
|
||||
}
|
||||
if (taken == 0) return RAD_OK;
|
||||
if (after) RAD_TRY(rad_event_wait(mover_, after));
|
||||
stage_segs_.clear();
|
||||
for (const StagePick& p : stage_picks_) {
|
||||
if (!p.dst) continue;
|
||||
RadCopySeg* run = stage_segs_.empty() ? nullptr : &stage_segs_.back();
|
||||
if (run && p.src - (const char*)run->src == p.dst - (char*)run->dst)
|
||||
run->bytes = (int64_t)(p.dst - (char*)run->dst) + p.bytes;
|
||||
else
|
||||
stage_segs_.push_back(RadCopySeg{p.src, p.dst, p.bytes});
|
||||
staged->push_back(p.u);
|
||||
stats_.h2d_bytes += (uint64_t)p.bytes;
|
||||
stats_.staged_bytes += (uint64_t)p.bytes;
|
||||
}
|
||||
RAD_TRY(rad_memcpy_list_async(stage_segs_.data(), (int)stage_segs_.size(), RAD_COPY_YIELD,
|
||||
mover_));
|
||||
RAD_TRY(rad_event_record(done, mover_));
|
||||
for (size_t k = 0; k < staged->size(); ++k) {
|
||||
const MoveUnit& mu = plan_->units[(size_t)(*staged)[k]];
|
||||
for (size_t i = 0; i < mu.weights.size(); ++i)
|
||||
res_.publish(mu.weights[i], dst + at[k] + mu.offset[i]);
|
||||
for (const StagePick& p : stage_picks_) {
|
||||
if (!p.dst) continue;
|
||||
const MoveUnit& mu = plan_->units[(size_t)p.u];
|
||||
for (size_t i = 0; i < mu.weights.size(); ++i) res_.publish(mu.weights[i], p.dst + mu.offset[i]);
|
||||
}
|
||||
++stats_.stage_layers;
|
||||
stats_.staged_units += (uint64_t)staged->size();
|
||||
stats_.stage_copies += (uint64_t)stage_segs_.size();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -645,6 +689,23 @@ void Mover::unstage_units(const std::vector<int32_t>& staged) {
|
||||
for (int32_t u : staged) republish(u);
|
||||
}
|
||||
|
||||
/* The same choice of units as stage_units, without a cap. */
|
||||
int64_t Mover::stage_need(const std::vector<int32_t>& units, int64_t* largest) const {
|
||||
int64_t total = 0, most = 0;
|
||||
for (int32_t u : units) {
|
||||
if (u < 0 || (size_t)u >= unit_.size()) continue;
|
||||
const UnitState& us = unit_[(size_t)u];
|
||||
if (us.tier != Tier::HostPinned || us.pool_slot < 0 || us.slab_slot >= 0 || us.klass < 0)
|
||||
continue;
|
||||
if (unit_in_flight(u)) continue;
|
||||
const int64_t need = align_up(us.bytes, RAD_ALIGN_UNIT);
|
||||
total += need;
|
||||
most = std::max(most, need);
|
||||
}
|
||||
if (largest) *largest = most;
|
||||
return total;
|
||||
}
|
||||
|
||||
/* ---- a routed layer read from the container (see mover.h) ---------------------------------- */
|
||||
namespace {
|
||||
|
||||
@@ -817,7 +878,7 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
|
||||
if (record_gate() < 0) return false;
|
||||
Move& m = moves_[(size_t)rec];
|
||||
{
|
||||
const int64_t g = cp.pool.take();
|
||||
const int64_t g = pool_slot_for(unit, heat);
|
||||
if (g < 0) { ++stats_.starved_pool; return false; }
|
||||
char* dst = (char*)cp.pool_base + g * cp.stride;
|
||||
if (us.slab_slot < 0) { cp.pool.add_free(g); return false; }
|
||||
@@ -829,11 +890,10 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
|
||||
* demotion costs about what a promotion does. That is the exchange rate heat.h's
|
||||
* min_gain is tuned against. */
|
||||
if (rad_event_wait(mover_, gate_) < 0) { cp.pool.add_free(g); return false; }
|
||||
if (rad_memcpy_async(dst, src, us.bytes, mover_) < 0) {
|
||||
if (queue_move_copy(dst, src, us.bytes, (int)(&m - moves_.data())) < 0) {
|
||||
cp.pool.add_free(g);
|
||||
return false;
|
||||
}
|
||||
(void)rad_event_record(m.ev, mover_);
|
||||
m.kind = Move::Kind::Demote;
|
||||
m.slab_slot = us.slab_slot;
|
||||
m.pool_slot = g;
|
||||
@@ -841,6 +901,7 @@ int Mover::issue(const Swap& s, HeatEngine* heat) {
|
||||
}
|
||||
m.state = Move::State::Copying;
|
||||
m.unit = unit;
|
||||
++copying_[(size_t)unit];
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -1042,6 +1103,133 @@ int Mover::drop(int32_t unit, HeatEngine* heat) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE POOL IS SIZED TO THE UNITS THAT LIVE IN IT, so it has a slot free only while a promotion
|
||||
* into a budgeted slot is on its way through the quarantine -- and the budgeted range turns over
|
||||
* only as fast as those few slots come round. A budgeted unit that goes cold then stays, and the
|
||||
* engine's swap drops the coldest lent unit in its place, which is warmer: replaying a mixed
|
||||
* workload's routing at TP1, the hit rate is 72.7% that way against 76.7% with up to n_turn
|
||||
* donors a class, and 78.5% for one resident set with no regions at all.
|
||||
*
|
||||
* A unit in a lent slot keeps its host copy only so that a recall is a change of address. Giving
|
||||
* the copy to the victim costs that for this one unit: a recall moves it, into a free budgeted
|
||||
* slot or back across the link (reclaim), and a loan that shrinks under it moves it the same way
|
||||
* (balance). There is always somewhere for it to go -- each donor's copy went to a unit
|
||||
* whose budgeted slot it left free, so the free budgeted slots and the free pool slots together
|
||||
* number at least the donors. The donors are bounded by the turnover slots, and they come out of
|
||||
* the KV cache's loan only: the arena takes its loan back at every prompt's first chunk, and that
|
||||
* recall stays a change of address.
|
||||
*
|
||||
* THE HOTTEST UNIT GIVES ITS COPY -- of the victim's layer, when pool_slot_for asks for one --
|
||||
* because a donor the engine later demotes needs a pool slot of its own where it would have been a
|
||||
* drop. Its pool slot has no reader: the unit has been resident since its promotion retired, and
|
||||
* the copy into the slot waits on the gate besides. */
|
||||
int64_t Mover::donor_slot(size_t klass, int32_t layer, HeatEngine* heat) {
|
||||
ClassPools& cp = pools_[klass];
|
||||
if (cp.n_donated >= cp.n_turn) return -1;
|
||||
/* NOT WHILE THE TURNOVER SLOTS ARE HELD: through a prompt and the few steps after it
|
||||
* (Engine::tiering_dispatch). A donation lets a starved demotion go and the swap behind it
|
||||
* with it, two copies on the stream the next prompt stages on; at TP2, where the resident set
|
||||
* is nine tenths of the experts and a donor buys no decode at all, 26K-token prompts back to
|
||||
* back ran 0.3% slower with them. A decode run reaches the count in a few steps. */
|
||||
if (hold_turnover_) return -1;
|
||||
DonorRank& d = donors_[klass];
|
||||
if (d.at != dispatch_) {
|
||||
d.at = dispatch_;
|
||||
d.by_layer.assign((size_t)std::max(n_layers_, 1), {});
|
||||
for (const ClassPools::Lent& l : cp.lent) {
|
||||
if (l.lender != kLendKV) continue;
|
||||
const int64_t lo = cp.slab.seg_lo(l.seg), hi = cp.slab.target(l.seg);
|
||||
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
|
||||
const UnitState& us = unit_[(size_t)u];
|
||||
if (us.klass != (int32_t)klass || us.slab_slot < lo || us.slab_slot >= hi) continue;
|
||||
const int32_t ul = plan_->units[(size_t)u].layer;
|
||||
if (ul < 0 || ul >= n_layers_) continue;
|
||||
d.by_layer[(size_t)ul].push_back({ heat ? heat->heat(u) : 0.0f, u });
|
||||
}
|
||||
}
|
||||
for (auto& v : d.by_layer) std::sort(v.begin(), v.end());
|
||||
}
|
||||
for (;;) {
|
||||
/* The hottest candidate of the layer asked for, or of every layer. */
|
||||
std::vector<std::pair<float, int32_t>>* pick = nullptr;
|
||||
if (layer >= 0) {
|
||||
if (layer < (int32_t)d.by_layer.size() && !d.by_layer[(size_t)layer].empty())
|
||||
pick = &d.by_layer[(size_t)layer];
|
||||
} else {
|
||||
for (auto& v : d.by_layer)
|
||||
if (!v.empty() && (!pick || v.back() > pick->back())) pick = &v;
|
||||
}
|
||||
if (!pick) return -1;
|
||||
const int32_t u = pick->back().second;
|
||||
pick->pop_back();
|
||||
UnitState& us = unit_[(size_t)u];
|
||||
if (us.klass != (int32_t)klass || us.pool_slot < 0 || us.slab_slot < 0) continue;
|
||||
if (us.tier != Tier::VRAM || us.site != Site::Device || !cp.slab.covered(us.slab_slot))
|
||||
continue;
|
||||
if ((heat && heat->busy(u)) || unit_in_flight(u)) continue;
|
||||
const int64_t g = us.pool_slot;
|
||||
us.pool_slot = -1;
|
||||
++cp.n_donated;
|
||||
++stats_.donated;
|
||||
return g;
|
||||
}
|
||||
}
|
||||
|
||||
/* THE STAGER COPIES A LAYER'S POOLED UNITS IN RUNS OF NEIGHBOURING POOL SLOTS (stage_units), and
|
||||
* the pool is laid out in unit order, so a layer's pooled units start out side by side. A demotion
|
||||
* that lands in a slot another layer's unit left breaks one run in that layer and starts a run of
|
||||
* one in its own, a copy more in each, for every prompt after it. So a slot one of the unit's own
|
||||
* layer started out in comes first, then a donor of the same layer -- its slot most likely one of
|
||||
* those -- and only then any free slot, or any donor. At TP1, 26K-token prompts with 256 tokens
|
||||
* decoded between them staged a layer in 162 copies without the preference and 112 with it (95
|
||||
* when the budget was 8 swaps a step). */
|
||||
int64_t Mover::pool_slot_for(int32_t unit, HeatEngine* heat) {
|
||||
const UnitState& us = unit_[(size_t)unit];
|
||||
ClassPools& cp = pools_[(size_t)us.klass];
|
||||
const int32_t layer = plan_->units[(size_t)unit].layer;
|
||||
const std::vector<int32_t>& home = pool_layer_[(size_t)us.klass];
|
||||
int64_t g = -1;
|
||||
if (layer >= 0) {
|
||||
g = cp.pool.take_where([&](int64_t p) { return (size_t)p < home.size() && home[(size_t)p] == layer; });
|
||||
if (g < 0) g = donor_slot((size_t)us.klass, layer, heat);
|
||||
}
|
||||
if (g < 0) g = cp.pool.take();
|
||||
if (g < 0) g = donor_slot((size_t)us.klass, -1, heat);
|
||||
return g;
|
||||
}
|
||||
|
||||
bool Mover::migrate(int32_t unit, HeatEngine* heat) {
|
||||
UnitState& us = unit_[(size_t)unit];
|
||||
ClassPools& cp = pools_[(size_t)us.klass];
|
||||
const int64_t to = cp.slab.take();
|
||||
if (to < 0) return false;
|
||||
if (to >= cp.n_fixed) {
|
||||
cp.slab.add_free(to);
|
||||
return false;
|
||||
}
|
||||
const int rec = free_move_record();
|
||||
if (rec < 0 || record_gate() < 0) {
|
||||
if (rec < 0) ++stats_.no_record;
|
||||
cp.slab.add_free(to);
|
||||
return false;
|
||||
}
|
||||
Move& m = moves_[(size_t)rec];
|
||||
if (rad_event_wait(mover_, gate_) < 0 ||
|
||||
queue_move_copy(cp.slot_ptr(to), cp.slot_ptr(us.slab_slot), us.bytes, rec) < 0) {
|
||||
cp.slab.add_free(to);
|
||||
return false;
|
||||
}
|
||||
m.state = Move::State::Copying;
|
||||
m.kind = Move::Kind::Migrate;
|
||||
m.unit = unit;
|
||||
m.slab_slot = us.slab_slot;
|
||||
m.pool_slot = -1;
|
||||
m.to_slot = to;
|
||||
++copying_[(size_t)unit];
|
||||
if (heat) heat->set_busy(unit, true);
|
||||
return true;
|
||||
}
|
||||
|
||||
int Mover::promote_to(int32_t unit, int64_t slot) {
|
||||
UnitState& us = unit_[(size_t)unit];
|
||||
ClassPools& cp = pools_[(size_t)us.klass];
|
||||
@@ -1052,8 +1240,7 @@ int Mover::promote_to(int32_t unit, int64_t slot) {
|
||||
const void* src = (const char*)cp.pool_base + us.pool_slot * cp.stride;
|
||||
Move& m = moves_[(size_t)rec];
|
||||
RAD_TRY(rad_event_wait(mover_, gate_));
|
||||
RAD_TRY(rad_memcpy_async(cp.slot_ptr(slot), src, us.bytes, mover_));
|
||||
(void)rad_event_record(m.ev, mover_);
|
||||
RAD_TRY(queue_move_copy(cp.slot_ptr(slot), src, us.bytes, rec));
|
||||
m.kind = Move::Kind::Promote;
|
||||
m.slab_slot = slot;
|
||||
/* INTO A LENT SLOT, THE HOST COPY STAYS. The loan can be recalled at any time and a unit that
|
||||
@@ -1063,6 +1250,7 @@ int Mover::promote_to(int32_t unit, int64_t slot) {
|
||||
m.pool_slot = cp.is_flex(slot) ? -1 : us.pool_slot;
|
||||
m.state = Move::State::Copying;
|
||||
m.unit = unit;
|
||||
++copying_[(size_t)unit];
|
||||
stats_.h2d_bytes += (uint64_t)us.bytes;
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1125,7 +1313,7 @@ int Mover::fill(size_t klass, int64_t room, HeatEngine* heat) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Mover::balance(HeatEngine* heat) {
|
||||
int Mover::balance(HeatEngine* heat, bool turnover) {
|
||||
if (!plan_ || !plan_->dynamic) return RAD_OK;
|
||||
|
||||
for (size_t c = 0; c < pools_.size(); ++c) {
|
||||
@@ -1149,6 +1337,20 @@ int Mover::balance(HeatEngine* heat) {
|
||||
left = true;
|
||||
continue;
|
||||
}
|
||||
/* A donor has no host copy to drop to: it moves into a free budgeted slot, or
|
||||
* else back across the link, and stays past the loan until the copy lands. */
|
||||
if (us.pool_slot < 0) {
|
||||
if (migrate(u, heat)) {
|
||||
drained = true;
|
||||
} else {
|
||||
if (heat) heat->set_busy(u, true);
|
||||
Swap s;
|
||||
s.demote = u;
|
||||
if (issue(s, heat) >= 0) drained = true;
|
||||
}
|
||||
left = true;
|
||||
continue;
|
||||
}
|
||||
if (drop(u, heat) < 0) { left = true; break; }
|
||||
drained = true;
|
||||
}
|
||||
@@ -1160,36 +1362,54 @@ int Mover::balance(HeatEngine* heat) {
|
||||
* slots that were serving as the reserve leaves the slab too full by that many, and the
|
||||
* coldest lent units go -- drops, never copies. A slot already on its way back below the
|
||||
* target counts as free, because it is, a barrier from now; draining against it again is
|
||||
* how a slab empties itself. */
|
||||
* how a slab empties itself.
|
||||
*
|
||||
* THE TURNOVER SLOTS ARE REBUILT THE SAME WAY, out of the lent units alone. They are the
|
||||
* top of the lent range, which is exactly what a cache that wants memory back takes first,
|
||||
* and the loan grows back only a prefill chunk at a time: left to the fill, they would be
|
||||
* gone for as long as requests keep arriving. Dropping the coldest lent units costs
|
||||
* nothing on the link -- each still has its host copy -- and gives up the same residents
|
||||
* the slots would have cost anyway. A swap whose demotion found no pool slot is completed
|
||||
* the same way, by the coldest lent unit instead. */
|
||||
int64_t pending = 0;
|
||||
for (const Move& m : moves_) {
|
||||
if (m.state == Move::State::Free || m.unit < 0 || m.slab_slot < 0) continue;
|
||||
if (unit_[(size_t)m.unit].klass != (int32_t)c || !cp.slab.covered(m.slab_slot)) continue;
|
||||
if (m.kind == Move::Kind::Drop || m.kind == Move::Kind::Demote ||
|
||||
m.kind == Move::Kind::Release)
|
||||
m.kind == Move::Kind::Release || m.kind == Move::Kind::Migrate)
|
||||
++pending;
|
||||
}
|
||||
int64_t short_by = cp.n_work - (cp.slab.n_free() + pending);
|
||||
while (short_by > 0) {
|
||||
int32_t victim = -1;
|
||||
float coldest = 0.0f;
|
||||
const int64_t turn = turnover ? cp.n_turn : 0;
|
||||
int64_t short_by = cp.n_work + turn - (cp.slab.n_free() + pending);
|
||||
if (short_by > 0) {
|
||||
drop_cand_.clear();
|
||||
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
|
||||
const UnitState& us = unit_[(size_t)u];
|
||||
if (us.klass != (int32_t)c || us.slab_slot < 0 || !cp.is_flex(us.slab_slot)) continue;
|
||||
if (us.tier != Tier::VRAM || us.site != Site::Device || us.pool_slot < 0) continue;
|
||||
if (heat && heat->busy(u)) continue;
|
||||
const float h = heat ? heat->heat(u) : 0.0f;
|
||||
if (victim < 0 || h < coldest) { victim = u; coldest = h; }
|
||||
drop_cand_.push_back({ heat ? heat->heat(u) : 0.0f, u });
|
||||
}
|
||||
/* The coldest first, and on a tie the lower unit, so the choice is the same every run. */
|
||||
auto colder = [](const std::pair<float, int32_t>& a, const std::pair<float, int32_t>& b) {
|
||||
return a.first != b.first ? a.first < b.first : a.second < b.second;
|
||||
};
|
||||
const size_t k = std::min(drop_cand_.size(), (size_t)short_by);
|
||||
std::partial_sort(drop_cand_.begin(), drop_cand_.begin() + (ptrdiff_t)k, drop_cand_.end(),
|
||||
colder);
|
||||
for (size_t i = 0; i < k; ++i) {
|
||||
if (drop(drop_cand_[i].second, heat) < 0) break;
|
||||
drained = true;
|
||||
--short_by;
|
||||
}
|
||||
if (victim < 0 || drop(victim, heat) < 0) break;
|
||||
drained = true;
|
||||
--short_by;
|
||||
}
|
||||
/* AND WITH NO LENT UNIT LEFT TO DROP, THE COLDEST BUDGETED ONE GOES BACK TO THE POOL -- a
|
||||
* real demotion, one a call. A swap can leave the free slots in the lent range, and a loan
|
||||
* that then shrinks away takes them with it; the reserve has to be rebuilt out of the
|
||||
* real demotion, one a call, and for the working reserve only: the turnover slots are the
|
||||
* loan's to give, and a copy across the link to keep them would spend the very link they
|
||||
* exist to save. A swap can leave the free slots in the lent range, and a loan that then
|
||||
* shrinks away takes them with it; the working reserve has to be rebuilt out of the
|
||||
* budgeted slots or the mover stops turning over. */
|
||||
if (short_by > 0) {
|
||||
if (short_by > turn) {
|
||||
int32_t victim = -1;
|
||||
float coldest = 0.0f;
|
||||
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
|
||||
@@ -1212,17 +1432,17 @@ int Mover::balance(HeatEngine* heat) {
|
||||
* trying to hand back. */
|
||||
if (drained) continue;
|
||||
|
||||
/* ---- THEN FILL, every free slot past the working reserve. */
|
||||
RAD_TRY(fill(c, cp.slab.n_free() - cp.n_work, heat));
|
||||
/* ---- THEN FILL, every free slot past the working reserve and the turnover slots. */
|
||||
RAD_TRY(fill(c, cp.slab.n_free() - cp.n_work - turn, heat));
|
||||
}
|
||||
count_flex();
|
||||
return RAD_OK;
|
||||
return flush_moves();
|
||||
}
|
||||
|
||||
int Mover::idle_tick(HeatEngine* heat) {
|
||||
if (!plan_ || !plan_->dynamic) return RAD_OK;
|
||||
RAD_TRY(retire(heat));
|
||||
return balance(heat);
|
||||
return balance(heat, !hold_turnover_);
|
||||
}
|
||||
|
||||
int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
|
||||
@@ -1235,20 +1455,56 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
|
||||
}
|
||||
/* NO COPY IS STILL WRITING A SLOT: everything the mover issued has landed, and retiring it
|
||||
* publishes the promotions that landed in slots about to be taken back. */
|
||||
RAD_TRY(flush_moves());
|
||||
RAD_TRY(rad_stream_sync(mover_));
|
||||
RAD_TRY(retire(heat));
|
||||
|
||||
/* EVERY UNIT PAST THE LOAN GOES BACK TO ITS HOST COPY, which is a change of address. */
|
||||
/* EVERY UNIT PAST THE LOAN GOES BACK TO ITS HOST COPY, which is a change of address -- or,
|
||||
* for a donor (donor_slot), which has none, it moves: into a free budgeted slot, a copy inside
|
||||
* the card, or else back across the link into a free pool slot. One of the two is free for
|
||||
* every donor (donor_slot says why). Nothing is published until the copies have landed. */
|
||||
std::vector<std::pair<size_t, int64_t>> freed;
|
||||
std::vector<int32_t> moved;
|
||||
for (int32_t u = 0; u < (int32_t)unit_.size(); ++u) {
|
||||
UnitState& us = unit_[(size_t)u];
|
||||
if (us.klass < 0 || us.slab_slot < 0) continue;
|
||||
const ClassPools& cp = pools_[(size_t)us.klass];
|
||||
ClassPools& cp = pools_[(size_t)us.klass];
|
||||
if (!cp.is_flex(us.slab_slot) || cp.slab.covered(us.slab_slot)) continue;
|
||||
if (us.pool_slot < 0) {
|
||||
RAD_ERR("mover: unit %d sits in lent slot %lld with no host copy to go back to",
|
||||
(int)u, (long long)us.slab_slot);
|
||||
return RAD_E_STATE;
|
||||
const int64_t from = us.slab_slot;
|
||||
int64_t to = cp.slab.take();
|
||||
if (to >= cp.n_fixed) {
|
||||
cp.slab.add_free(to);
|
||||
to = -1;
|
||||
}
|
||||
if (to >= 0) {
|
||||
RAD_TRY(rad_memcpy_async(cp.slot_ptr(to), cp.slot_ptr(from), us.bytes, mover_));
|
||||
us.slab_slot = to;
|
||||
} else {
|
||||
const int64_t g = cp.pool.take();
|
||||
if (g < 0) {
|
||||
RAD_ERR("mover: unit %d gave its host copy away and neither a budgeted slot nor "
|
||||
"a pool slot is free to move it to", (int)u);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
RAD_TRY(rad_memcpy_async((char*)cp.pool_base + g * cp.stride, cp.slot_ptr(from),
|
||||
us.bytes, mover_));
|
||||
us.pool_slot = g;
|
||||
us.slab_slot = -1;
|
||||
us.tier = Tier::HostPinned;
|
||||
us.site = Site::DeviceZeroCopy;
|
||||
stats_.d2h_bytes += (uint64_t)us.bytes;
|
||||
++stats_.demotions;
|
||||
if (heat) {
|
||||
heat->set_tier(u, Tier::HostPinned);
|
||||
heat->set_busy(u, false);
|
||||
}
|
||||
}
|
||||
--cp.n_donated;
|
||||
++stats_.relocated;
|
||||
freed.push_back({ (size_t)us.klass, from });
|
||||
moved.push_back(u);
|
||||
continue;
|
||||
}
|
||||
freed.push_back({ (size_t)us.klass, us.slab_slot });
|
||||
us.slab_slot = -1;
|
||||
@@ -1263,6 +1519,11 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
|
||||
}
|
||||
}
|
||||
|
||||
if (!moved.empty()) {
|
||||
RAD_TRY(rad_stream_sync(mover_));
|
||||
for (int32_t u : moved) republish(u);
|
||||
}
|
||||
|
||||
/* AND NO KERNEL STILL NAMES ONE. The compute stream is the only reader of the slab -- the
|
||||
* quarantine barrier rests on the same fact -- so once it has drained, nothing already issued
|
||||
* can reach a slot past the loan, and everything issued from here reads the host copies. */
|
||||
@@ -1279,13 +1540,14 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
|
||||
ClassPools& cp = pools_[(size_t)klass];
|
||||
if (!cp.is_flex(m.slab_slot) || cp.slab.covered(m.slab_slot)) continue;
|
||||
if (m.kind == Move::Kind::Drop || m.kind == Move::Kind::Demote ||
|
||||
m.kind == Move::Kind::Release)
|
||||
m.kind == Move::Kind::Release || m.kind == Move::Kind::Migrate)
|
||||
cp.slab.add_free(m.slab_slot);
|
||||
if (heat && m.kind != Move::Kind::Stage && m.kind != Move::Kind::Release)
|
||||
heat->set_busy(m.unit, false);
|
||||
if (m.state == Move::State::Copying) --copying_[(size_t)m.unit];
|
||||
m.state = Move::State::Free;
|
||||
m.unit = -1;
|
||||
m.slab_slot = m.pool_slot = -1;
|
||||
m.slab_slot = m.pool_slot = m.to_slot = -1;
|
||||
}
|
||||
count_flex();
|
||||
if (loan_held(lender) > loan_[lender]) {
|
||||
@@ -1297,13 +1559,38 @@ int Mover::reclaim(int lender, int64_t amount, HeatEngine* heat) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Mover::queue_move_copy(void* dst, const void* src, int64_t bytes, int rec) {
|
||||
move_segs_.push_back(RadCopySeg{ src, dst, bytes });
|
||||
move_recs_.push_back((int32_t)rec);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE DMA ENGINE AND NOT COPY KERNELS. A copy kernel runs on the compute units beside the step's
|
||||
* kernels: at the heat engine's budget of 64 swaps a step, Qwen3.8-Flash-Next at one card spent 10 ms
|
||||
* a step in about 68 of them while the step took 36. The engine moves the same bytes at the link's
|
||||
* rate and takes nothing from the kernels; decode at one sequence went 34.1 -> 33.0 ms a step, and
|
||||
* two cards, prefill and the output were unchanged. A card with no DMA queue of this process's own
|
||||
* gets the list as copy kernels (rad_memcpy_list_async), as before. The list yields to the link's
|
||||
* collectives like the prefill stager's. */
|
||||
int Mover::flush_moves() {
|
||||
if (move_segs_.empty()) return RAD_OK;
|
||||
const int rc = rad_memcpy_list_async(move_segs_.data(), (int)move_segs_.size(), RAD_COPY_YIELD,
|
||||
mover_);
|
||||
for (int32_t rec : move_recs_) (void)rad_event_record(moves_[(size_t)rec].ev, mover_);
|
||||
move_segs_.clear();
|
||||
move_recs_.clear();
|
||||
return rc;
|
||||
}
|
||||
|
||||
int Mover::retire(HeatEngine* heat) {
|
||||
RAD_TRY(flush_moves());
|
||||
for (Move& m : moves_) {
|
||||
if (m.state != Move::State::Copying) continue;
|
||||
const int q = rad_event_query(m.ev);
|
||||
if (q < 0) return RAD_E_DEVICE;
|
||||
if (q == 0) continue;
|
||||
|
||||
--copying_[(size_t)m.unit];
|
||||
UnitState& us = unit_[(size_t)m.unit];
|
||||
switch (m.kind) {
|
||||
case Move::Kind::Promote:
|
||||
@@ -1317,6 +1604,9 @@ int Mover::retire(HeatEngine* heat) {
|
||||
if (heat) heat->set_tier(m.unit, Tier::VRAM);
|
||||
break;
|
||||
case Move::Kind::Demote:
|
||||
/* Out of a lent slot, the unit was a donor (donor_slot): any other unit there is
|
||||
* dropped, not demoted. */
|
||||
if (pools_[(size_t)us.klass].is_flex(m.slab_slot)) --pools_[(size_t)us.klass].n_donated;
|
||||
us.pool_slot = m.pool_slot;
|
||||
us.slab_slot = -1;
|
||||
us.tier = Tier::HostPinned;
|
||||
@@ -1348,8 +1638,13 @@ int Mover::retire(HeatEngine* heat) {
|
||||
* and the pipeline simply stops turning over. */
|
||||
m.state = Move::State::Free;
|
||||
m.unit = -1;
|
||||
m.slab_slot = m.pool_slot = -1;
|
||||
m.slab_slot = m.pool_slot = m.to_slot = -1;
|
||||
continue;
|
||||
case Move::Kind::Migrate:
|
||||
us.slab_slot = m.to_slot;
|
||||
--pools_[(size_t)us.klass].n_donated;
|
||||
++stats_.relocated;
|
||||
break;
|
||||
case Move::Kind::Release:
|
||||
case Move::Kind::Drop:
|
||||
break;
|
||||
@@ -1393,14 +1688,15 @@ int Mover::retire(HeatEngine* heat) {
|
||||
case Move::Kind::Demote: cp.slab.add_free(m.slab_slot); break;
|
||||
case Move::Kind::Release: cp.slab.add_free(m.slab_slot); break;
|
||||
case Move::Kind::Drop: cp.slab.add_free(m.slab_slot); break;
|
||||
case Move::Kind::Migrate: cp.slab.add_free(m.slab_slot); break;
|
||||
case Move::Kind::Stage: break; /* never reaches here; freed as soon as it lands */
|
||||
}
|
||||
if (heat && (m.kind == Move::Kind::Promote || m.kind == Move::Kind::Demote ||
|
||||
m.kind == Move::Kind::Drop))
|
||||
m.kind == Move::Kind::Drop || m.kind == Move::Kind::Migrate))
|
||||
heat->set_busy(m.unit, false);
|
||||
m.state = Move::State::Free;
|
||||
m.unit = -1;
|
||||
m.slab_slot = m.pool_slot = -1;
|
||||
m.slab_slot = m.pool_slot = m.to_slot = -1;
|
||||
}
|
||||
count_flex();
|
||||
return RAD_OK;
|
||||
@@ -1421,6 +1717,10 @@ std::string Mover::report() const {
|
||||
"slot; %llu slots quarantined\n",
|
||||
(unsigned long long)stats_.no_record, (unsigned long long)stats_.starved_slab,
|
||||
(unsigned long long)stats_.starved_pool, (unsigned long long)stats_.quarantined);
|
||||
if (stats_.donated)
|
||||
s += fmt(" %llu host copies given by lent units to budgeted victims, %llu such units moved "
|
||||
"by a recall\n",
|
||||
(unsigned long long)stats_.donated, (unsigned long long)stats_.relocated);
|
||||
if (stats_.ssd_reads)
|
||||
s += fmt(" file tier: %llu demand reads (%.2f GiB), each a blocking pread in the middle "
|
||||
"of a dispatch. Raise --host-pool-mib.\n",
|
||||
|
||||
+125
-8
@@ -45,6 +45,7 @@
|
||||
* the slot has retired.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../device/device.h"
|
||||
#include "../device/directio.h"
|
||||
#include "../mem/pools.h"
|
||||
#include "heat.h"
|
||||
@@ -212,6 +213,25 @@ 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. */
|
||||
template <class Want> int64_t take_where(Want want) {
|
||||
size_t best = free_.size();
|
||||
for (size_t i = 0; i < free_.size(); ++i) {
|
||||
const int64_t s = free_[i];
|
||||
if (!covered(s) || held_[(size_t)s] || !want(s)) continue;
|
||||
if (best == free_.size() || s < free_[best]) best = i;
|
||||
}
|
||||
if (best == free_.size()) return -1;
|
||||
const int64_t s = free_[best];
|
||||
free_[best] = free_.back();
|
||||
free_.pop_back();
|
||||
std::make_heap(free_.begin(), free_.end(), std::greater<int64_t>());
|
||||
held_[(size_t)s] = 1;
|
||||
++n_held_;
|
||||
--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. */
|
||||
int64_t top_held(int k = 0) const {
|
||||
@@ -356,6 +376,13 @@ struct MoverConfig {
|
||||
* layer. */
|
||||
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. */
|
||||
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. */
|
||||
std::string container_path;
|
||||
@@ -393,10 +420,16 @@ struct MoverStats {
|
||||
/* 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. */
|
||||
uint64_t dropped = 0;
|
||||
/* Host copies a unit in a lent slot gave to a budgeted victim that had no pool slot to go to
|
||||
* (Mover::donor_slot), and such units moved rather than dropped when their loan was recalled
|
||||
* or shrank. */
|
||||
uint64_t donated = 0, relocated = 0;
|
||||
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. */
|
||||
* 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. */
|
||||
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
|
||||
@@ -547,6 +580,13 @@ public:
|
||||
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;
|
||||
/* The lent slots the fill leaves free for the engine to swap into
|
||||
* (MoverConfig::turnover_slots), summed over the slab classes. */
|
||||
int64_t turnover_slots() const {
|
||||
int64_t n = 0;
|
||||
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
|
||||
@@ -556,14 +596,38 @@ public:
|
||||
/* 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 is filled in
|
||||
* one call, hottest units first, and the copies run at the rate the link carries them. */
|
||||
int balance(HeatEngine* heat);
|
||||
* 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.
|
||||
*
|
||||
* `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. */
|
||||
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. Only while the rank thread is parked. */
|
||||
* than by it -- the turnover slots too while they are held. 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
|
||||
* 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`. */
|
||||
int pool_ranges(uint64_t* lo, uint64_t* hi, uint64_t* stride, int max) const {
|
||||
int n = 0;
|
||||
for (const ClassPools& cp : pools_)
|
||||
if (cp.pool_dev && cp.stride > 0 && n < max) {
|
||||
lo[n] = (uint64_t)(uintptr_t)cp.pool_dev;
|
||||
hi[n] = lo[n] + (uint64_t)cp.pool.size() * (uint64_t)cp.stride;
|
||||
stride[n] = (uint64_t)cp.stride;
|
||||
++n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Where a unit's bytes are right now, as a device-visible address, or null for a file-tier
|
||||
* unit that has not been staged. */
|
||||
@@ -587,10 +651,20 @@ public:
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
struct StageSpan { char* dst; int64_t cap; };
|
||||
int stage_units(const std::vector<int32_t>& units, char* dst, int64_t cap, RadEvent after,
|
||||
RadEvent done, std::vector<int32_t>* staged);
|
||||
int stage_units(const std::vector<int32_t>& units, const StageSpan* spans, int n_spans,
|
||||
RadEvent after, RadEvent done, std::vector<int32_t>* staged);
|
||||
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) --------
|
||||
*
|
||||
@@ -629,18 +703,22 @@ private:
|
||||
* mid-layer, because placement would then depend on host timing and stop being reproducible. */
|
||||
struct Move {
|
||||
enum class State { Free, Copying, Published, Quarantine };
|
||||
/* Five kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is
|
||||
/* 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. */
|
||||
enum class Kind { Promote, Demote, Stage, Release, Drop };
|
||||
* 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. */
|
||||
enum class Kind { Promote, Demote, Stage, Release, Drop, Migrate };
|
||||
State state = State::Free;
|
||||
Kind kind = Kind::Promote;
|
||||
int32_t unit = -1;
|
||||
int64_t slab_slot = -1;
|
||||
int64_t pool_slot = -1;
|
||||
int64_t to_slot = -1;
|
||||
RadEvent ev = nullptr;
|
||||
};
|
||||
|
||||
@@ -672,6 +750,11 @@ private:
|
||||
int64_t stride = 0;
|
||||
int64_t n_fixed = 0; /* slots in the budgeted range; the flex ones start here */
|
||||
int64_t n_work = 0; /* shadow + staging: free slots the mover needs to move at all */
|
||||
int64_t n_turn = 0; /* lent slots kept free past those: the fill stops short
|
||||
* of them and balance() drops lent units to rebuild them
|
||||
* (MoverConfig::turnover_slots) */
|
||||
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
|
||||
@@ -703,11 +786,36 @@ private:
|
||||
RadStream mover_ = nullptr;
|
||||
RadStream compute_ = nullptr;
|
||||
RadEvent gate_ = nullptr; /* recorded on compute, waited on by the mover stream */
|
||||
std::vector<RadCopySeg> stage_segs_; /* stage_units' list, kept so a layer allocates nothing */
|
||||
struct StagePick { const char* src; int32_t u; int64_t bytes, need; char* dst; };
|
||||
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. */
|
||||
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);
|
||||
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. */
|
||||
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. */
|
||||
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). */
|
||||
std::vector<std::vector<int32_t>> pool_layer_;
|
||||
int32_t n_layers_ = 0;
|
||||
|
||||
void* static_vram_ = nullptr;
|
||||
int64_t static_bytes_ = 0;
|
||||
@@ -756,6 +864,15 @@ private:
|
||||
bool unit_in_flight(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. */
|
||||
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);
|
||||
/* One promotion out of the unit's pool slot into `slot`, which the caller has taken. */
|
||||
int promote_to(int32_t unit, int64_t slot);
|
||||
/* Promote the hottest pooled units of one class into up to `room` free slots. */
|
||||
|
||||
@@ -1243,6 +1243,17 @@ int Planner::assign(Plan* p) {
|
||||
else if (has_conditional) s = Strategy::ExpertTiered;
|
||||
else s = Strategy::LayerOffload;
|
||||
p->strategy = s;
|
||||
p->strategy_why =
|
||||
s == Strategy::AllVram
|
||||
? fmt("%s of weights fit the %s weights pool", humanb(total).c_str(),
|
||||
humanb(p->vram_budget).c_str())
|
||||
: s == Strategy::ExpertTiered
|
||||
? fmt("%s of weights against a %s weights pool: routed experts, read only when "
|
||||
"selected, are what spills to host memory", humanb(total).c_str(),
|
||||
humanb(p->vram_budget).c_str())
|
||||
: fmt("%s of weights against a %s weights pool and no routed experts to spill: "
|
||||
"whole layers are offloaded", humanb(total).c_str(),
|
||||
humanb(p->vram_budget).c_str());
|
||||
RAD_DEBUG("placement: auto chose %s (%s of weights against a %s budget)",
|
||||
strategy_name(s), humanb(total).c_str(), humanb(p->vram_budget).c_str());
|
||||
}
|
||||
|
||||
+34
-4
@@ -176,6 +176,18 @@ struct SlabClass {
|
||||
#define RAD_PLACE_FILE_WINDOWS 4
|
||||
#define RAD_PLACE_FILE_WINDOW_BYTES ((int64_t)32 << 20)
|
||||
|
||||
/* THE HEAT ENGINE'S MOVE BUDGET: swaps a STEP, a slab class. HeatParams::moves_per_step defaults
|
||||
* to it, and the free slots below are sized from it, because the two are one quantity: a swap
|
||||
* that finds no free slot does not happen.
|
||||
*
|
||||
* The engine proposes once a step (Engine::tiering_dispatch), and a step routes every layer, so
|
||||
* the budget has to cover the whole model's turnover. Replaying the routing of a mixed workload
|
||||
* through the engine's policy at Qwen3.8-Flash-Next TP1 (40% of the experts resident), the hit
|
||||
* rate on decode rows is 63.8% at 8 a step, 74.1% at 32, 77.1% at 64 and 77.8% at 128 -- and an
|
||||
* oracle that knows every future routing, held to the same 64 swaps a step, reaches 78.0%. Past
|
||||
* this the move rate, not the ranking, is what bounds the hit rate. */
|
||||
#define RAD_PLACE_MOVES_PER_STEP 64
|
||||
|
||||
/* SHADOW SLOTS: slab slots that are allocated but hold no unit, so a promotion writes into one
|
||||
* and only then publishes and never DMAs over a slot a kernel might still be reading (mover.h).
|
||||
*
|
||||
@@ -184,12 +196,28 @@ struct SlabClass {
|
||||
* explicitly and --gpu-headroom-mib is memory the engine promises NOT to touch. So dynamic
|
||||
* placement costs a few resident units, and the plan report prints exactly how many.
|
||||
*
|
||||
* 32 is far past where the knob stops mattering, and MORE is the wrong end of the problem: extra
|
||||
* shadows raise the move rate and run SLOWER, because more copies in flight contend with the
|
||||
* zero-copy tier for the same link. The quarter-of-the-slab cap only ever binds on a slab too
|
||||
* small for the number to be meaningful. */
|
||||
* THESE ARE THE SLOTS THE ENGINE CAN ALWAYS COUNT ON, and the expert floor charges for them
|
||||
* (expert_vram_floor), so every slot here is one the KV cache can never have. The rest of what the
|
||||
* move budget needs is RAD_PLACE_TURNOVER_SLOTS, taken out of the cache's loan instead. The
|
||||
* quarter-of-the-slab cap only ever binds on a slab too small for the number to be meaningful. */
|
||||
#define RAD_PLACE_SHADOW_SLOTS 32
|
||||
|
||||
/* THE TURNOVER SLOTS: free slab slots the mover keeps out of a loan (Mover::lend_from), past the
|
||||
* shadow slots, by filling the loan's slots only up to them. A swap holds a slot for about three
|
||||
* steps -- the copies go out behind the step that proposed them, the next step's retire publishes
|
||||
* them, and the slot the demotion left comes back only once the compute stream has passed the
|
||||
* quarantine recorded after that publish -- so a budget of RAD_PLACE_MOVES_PER_STEP needs three
|
||||
* times as many free slots, and with fewer the budget is smaller than it says. At 64 a step,
|
||||
* replaying the routing with 32 slots in all reaches 65.9% against 77.9% with 192.
|
||||
*
|
||||
* Out of the loan because that costs the cache nothing: a lent slot left free is one the experts
|
||||
* were borrowing anyway, and charged to the expert floor instead the same slots would come out of
|
||||
* the cache's largest size. When the cache takes memory back, the free slots at the loan's top go
|
||||
* first and the mover rebuilds them by dropping its coldest lent units, which still have their
|
||||
* host copies (Mover::balance); only once nothing is lent does the move rate fall back to what
|
||||
* the shadow slots alone allow. */
|
||||
#define RAD_PLACE_TURNOVER_SLOTS (3 * RAD_PLACE_MOVES_PER_STEP - RAD_PLACE_SHADOW_SLOTS)
|
||||
|
||||
/* ------------------------------------------------------------------ per-weight result */
|
||||
struct Placement {
|
||||
Tier tier = Tier::VRAM;
|
||||
@@ -206,6 +234,8 @@ class Plan {
|
||||
public:
|
||||
int rank = 0, world_size = 1;
|
||||
Strategy strategy = Strategy::Auto;
|
||||
/* Why `strategy` is the one it is, when `auto` chose it; empty when it was asked for. */
|
||||
std::string strategy_why;
|
||||
|
||||
/* False under Config::deterministic. Dynamic placement sets which experts are resident and
|
||||
* residency sets the summation order, so identical inputs do not give identical outputs
|
||||
|
||||
+217
-77
@@ -6,10 +6,12 @@
|
||||
namespace rad {
|
||||
|
||||
PrefillStager::~PrefillStager() {
|
||||
for (int b = 0; b < 2; ++b) {
|
||||
if (done_[b]) rad_event_destroy(done_[b]);
|
||||
if (free_[b]) rad_event_destroy(free_[b]);
|
||||
for (Place& p : place_) {
|
||||
if (p.done) rad_event_destroy(p.done);
|
||||
if (p.free) rad_event_destroy(p.free);
|
||||
}
|
||||
for (RadEvent& g : gate_)
|
||||
if (g) rad_event_destroy(g);
|
||||
}
|
||||
|
||||
int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, char* region,
|
||||
@@ -19,11 +21,16 @@ int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, cha
|
||||
|
||||
/* A ROUTED LAYER IS ITS EXPERT UNITS, and the ops that read it are the span their declared
|
||||
* uses cover: the first is the one that must find the copies, the last the one after which
|
||||
* nothing reads them again -- once the block's last pass of rows has issued it (after_op). */
|
||||
* nothing reads them again -- once the block's last pass of rows has issued it (after_op).
|
||||
* A declared draft head's layer, numbered past the trunk's, is not one (see the top of
|
||||
* stager.h). */
|
||||
const int32_t trunk = prog.drafter.kind != RAD_DRAFT_NONE && prog.meta.n_layers > 0
|
||||
? (int32_t)prog.meta.n_layers : INT32_MAX;
|
||||
std::map<int32_t, Layer> by_layer;
|
||||
for (size_t u = 0; u < plan.units.size(); ++u) {
|
||||
const MoveUnit& mu = plan.units[u];
|
||||
if (mu.expert < 0 || mu.layer < 0 || mu.first_use_op < 0 || mu.last_use_op < 0) continue;
|
||||
if (mu.layer >= trunk) continue;
|
||||
Layer& L = by_layer[mu.layer];
|
||||
L.layer = mu.layer;
|
||||
L.units.push_back((int32_t)u);
|
||||
@@ -33,8 +40,8 @@ int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, cha
|
||||
for (auto& kv : by_layer) layers_.push_back(std::move(kv.second));
|
||||
std::sort(layers_.begin(), layers_.end(),
|
||||
[](const Layer& a, const Layer& b) { return a.first_op < b.first_op; });
|
||||
/* Two layers' spans must not overlap: a layer's copies are released at its last op, and the
|
||||
* next layer's buffer is the one the layer before it released. */
|
||||
/* Two layers' spans must not overlap: a layer's copies are given back at the next layer's
|
||||
* first op, which must be past every op that reads them. */
|
||||
for (size_t i = 1; i < layers_.size(); ++i)
|
||||
if (layers_[i].first_op <= layers_[i - 1].last_op) {
|
||||
RAD_WARN("prefill staging: routed layers %d and %d are read by interleaved ops (%d..%d "
|
||||
@@ -54,130 +61,263 @@ int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, cha
|
||||
}
|
||||
|
||||
mover_ = mover;
|
||||
cap_ = bytes / 2 / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
|
||||
buf_[0] = region;
|
||||
buf_[1] = region + cap_;
|
||||
region_ = region;
|
||||
ring_ = bytes / 2 / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT * 2;
|
||||
head_ = 0;
|
||||
min_rows_ = min_rows;
|
||||
for (int b = 0; b < 2; ++b) {
|
||||
if (rad_event_create_local(&done_[b]) < 0 || rad_event_create_local(&free_[b]) < 0) {
|
||||
n_early_ = 0;
|
||||
ring_order_.clear();
|
||||
spare_.clear();
|
||||
for (int i = kPlaces - 1; i >= 0; --i) {
|
||||
Place& p = place_[i];
|
||||
if (rad_event_create_local(&p.done) < 0 || rad_event_create_local(&p.free) < 0) {
|
||||
layers_.clear();
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
spare_.push_back(i);
|
||||
}
|
||||
started_.assign(layers_.size(), 0);
|
||||
return RAD_OK;
|
||||
for (int i = 0; i < kGates; ++i) {
|
||||
if (rad_event_create_local(&gate_[i]) < 0) {
|
||||
layers_.clear();
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
gate_li_[i] = -1;
|
||||
}
|
||||
/* The backend opens what its first list needs -- the card's DMA queue -- here at bring-up, not
|
||||
* inside the first long prompt's first step. */
|
||||
return rad_memcpy_list_async(nullptr, 0, 0, mover_->transfer_stream());
|
||||
}
|
||||
|
||||
/* A TRUNK PASS AT THE FULL PLAN AND LARGE ENOUGH, and only that (see the top of stager.h). The
|
||||
* next trunk pass's first layers, staged at the end of the last one, are this pass's if it arms
|
||||
* and go back to the pool if it does not. */
|
||||
bool PrefillStager::begin_pass(const RadBatch* b) {
|
||||
armed_ = full_ && enabled() && b && b->n_tok >= min_rows_;
|
||||
if (!armed_) return false;
|
||||
std::fill(started_.begin(), started_.end(), (uint8_t)0);
|
||||
holds_[0] = holds_[1] = -1;
|
||||
if (!b || b->draft_pass != 0) return false;
|
||||
armed_ = full_ && enabled() && b->n_tok >= min_rows_;
|
||||
staged_ = armed_;
|
||||
if (!armed_) {
|
||||
withdraw_early();
|
||||
return false;
|
||||
}
|
||||
first_op_ = true;
|
||||
pass_kind_ = b->draft_pass;
|
||||
last_issued_ = -1;
|
||||
next_ = 0;
|
||||
first_li_ = -1;
|
||||
for (int32_t& g : gate_li_) g = -1;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PrefillStager::will_issue(int32_t li) const {
|
||||
const auto it = pass_last_.find(pass_kind_);
|
||||
return it == pass_last_.end() || layers_[(size_t)li].first_op <= it->second;
|
||||
/* The early layers' copies back to the pool: nothing has read them, so there is no `free` to
|
||||
* record and the next copy over their places needs no wait for them. */
|
||||
void PrefillStager::withdraw_early() {
|
||||
for (int32_t i : ring_order_) {
|
||||
Place& p = place_[i];
|
||||
if (!p.retired) retire(p);
|
||||
}
|
||||
n_early_ = 0;
|
||||
}
|
||||
|
||||
int PrefillStager::start(int32_t li) {
|
||||
started_[(size_t)li] = 1;
|
||||
const int b = li & 1;
|
||||
if (holds_[b] >= 0) return RAD_OK; /* the layer before still holds it: stream this one */
|
||||
const int rc = mover_->stage_units(layers_[(size_t)li].units, buf_[b], cap_,
|
||||
free_rec_[b] ? free_[b] : nullptr, done_[b], &staged_[b]);
|
||||
if (rc < 0) return rc;
|
||||
if (!staged_[b].empty()) { holds_[b] = li; read_[b] = false; }
|
||||
/* The host half of giving a place back: its units are published at their pool slots again, which
|
||||
* the next residency sync hands to the weight tables. The device half is `free`, which the copy
|
||||
* that laps the place waits on. */
|
||||
void PrefillStager::retire(Place& p) {
|
||||
mover_->unstage_units(p.staged);
|
||||
p.staged.clear();
|
||||
p.retired = true;
|
||||
}
|
||||
|
||||
/* The oldest place leaves the ring, and the mover's stream waits on its last reader: whatever is
|
||||
* copied there later goes out behind that wait. */
|
||||
int PrefillStager::recycle_front() {
|
||||
const int32_t i = ring_order_.front();
|
||||
Place& p = place_[i];
|
||||
if (p.free_rec) RAD_TRY(rad_event_wait(mover_->transfer_stream(), p.free));
|
||||
p.li = -1;
|
||||
p.free_rec = p.read = p.retired = false;
|
||||
ring_order_.pop_front();
|
||||
spare_.push_back(i);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The host half of letting a buffer go: its units are published at their pool slots again, which
|
||||
* the next residency sync hands to the weight tables. The device half is `free_`. */
|
||||
void PrefillStager::release(int32_t b) {
|
||||
mover_->unstage_units(staged_[b]);
|
||||
staged_[b].clear();
|
||||
holds_[b] = -1;
|
||||
read_[b] = false;
|
||||
/* A PLACE OF `want` BYTES at the head of the ring, or -- `partial` -- all the room the head can
|
||||
* reach when `want` does not fit. The head may write over retired places only: the oldest place
|
||||
* still published bounds it a whole ring ahead of where that place starts. *out is -1 when
|
||||
* nothing fits. */
|
||||
int PrefillStager::take(int64_t want, bool partial, int32_t* out) {
|
||||
*out = -1;
|
||||
int64_t limit = head_ + ring_;
|
||||
for (int32_t i : ring_order_)
|
||||
if (!place_[i].retired) { limit = place_[i].beg + ring_; break; }
|
||||
int64_t len = std::min(want, limit - head_);
|
||||
if (len < want && !partial) return RAD_OK;
|
||||
if (len < RAD_ALIGN_UNIT) return RAD_OK;
|
||||
const int64_t end = head_ + len;
|
||||
/* Every place the new one laps leaves the ring first; then, with the table full, the oldest
|
||||
* retired ones -- their waits only order the mover's stream behind reads long finished. */
|
||||
while (!ring_order_.empty() && place_[ring_order_.front()].beg + ring_ < end)
|
||||
RAD_TRY(recycle_front());
|
||||
while (spare_.empty() && !ring_order_.empty() && place_[ring_order_.front()].retired)
|
||||
RAD_TRY(recycle_front());
|
||||
if (spare_.empty()) return RAD_OK;
|
||||
const int32_t i = spare_.back();
|
||||
spare_.pop_back();
|
||||
Place& p = place_[i];
|
||||
p.beg = head_;
|
||||
p.end = end;
|
||||
*out = i;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int PrefillStager::finish(int32_t b, RadStream s) {
|
||||
RAD_TRY(rad_event_record(free_[b], s));
|
||||
free_rec_[b] = true;
|
||||
release(b);
|
||||
/* ONE LAYER INTO THE RING, behind `gate` when it is not null. `now` is the layer the run reaches
|
||||
* next, which takes whatever room there is up to all it needs; any other goes only whole and at
|
||||
* most half the ring -- so the next layer never finds less room than two buffers of half the ring
|
||||
* gave it, and a heavy layer is not cut short for having been reached early. *got is kStaged, kNone
|
||||
* when nothing of the layer is pooled, or kLater when the ring has no room for it yet. */
|
||||
int PrefillStager::stage_layer(int32_t li, bool now, RadEvent gate, int* got) {
|
||||
*got = kLater;
|
||||
const Layer& L = layers_[(size_t)li];
|
||||
int64_t unit = 0;
|
||||
const int64_t need = mover_->stage_need(L.units, &unit);
|
||||
if (need <= 0) { *got = kNone; return RAD_OK; }
|
||||
if (!now && need > ring_ / 2) return RAD_OK;
|
||||
/* A place that runs past the region's end is two stretches, and the first can end in less
|
||||
* room than a unit: it asks for one unit more than the layer needs. */
|
||||
const int64_t want = head_ % ring_ + need > ring_ ? need + unit : need;
|
||||
int32_t i = -1;
|
||||
RAD_TRY(take(want, now, &i));
|
||||
if (i < 0) return RAD_OK;
|
||||
Place& p = place_[i];
|
||||
p.li = li;
|
||||
if (gate) RAD_TRY(rad_event_wait(mover_->transfer_stream(), gate));
|
||||
/* A place that runs past the region's end goes on at its start. */
|
||||
const int64_t off = p.beg % ring_, len = p.end - p.beg;
|
||||
Mover::StageSpan sp[2] = { { region_ + off, std::min(len, ring_ - off) },
|
||||
{ region_, len - std::min(len, ring_ - off) } };
|
||||
RAD_TRY(mover_->stage_units(L.units, sp, sp[1].cap > 0 ? 2 : 1, nullptr, p.done, &p.staged));
|
||||
if (p.staged.empty()) {
|
||||
p.li = -1;
|
||||
spare_.push_back(i);
|
||||
*got = kNone;
|
||||
return RAD_OK;
|
||||
}
|
||||
head_ = p.end;
|
||||
ring_order_.push_back(i);
|
||||
*got = kStaged;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* STAGE THE LAYERS AFTER `cur` as far as the pace lets them go and the ring has room. A layer
|
||||
* nothing of which is pooled is passed over; one the ring has no room for yet, or whose pace
|
||||
* layer the run has not reached, stops the walk until a later op. */
|
||||
int PrefillStager::stage_ahead(int32_t cur, bool* resync) {
|
||||
while ((size_t)next_ < layers_.size()) {
|
||||
const int32_t g = next_ - kLead;
|
||||
RadEvent gate = nullptr;
|
||||
if (g >= first_li_) {
|
||||
if (gate_li_[g % kGates] != g) break;
|
||||
gate = gate_[g % kGates];
|
||||
}
|
||||
int got = kLater;
|
||||
RAD_TRY(stage_layer(next_, next_ <= cur + 1, gate, &got));
|
||||
if (got == kLater) break;
|
||||
*resync = *resync || got == kStaged;
|
||||
++next_;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int PrefillStager::before_op(rad_op h, RadStream s, bool* resync) {
|
||||
*resync = false;
|
||||
if ((int32_t)h > last_issued_) last_issued_ = (int32_t)h;
|
||||
|
||||
/* THE PASS'S FIRST ROUTED LAYER, staged at its first op of any kind, so the copy runs behind
|
||||
* whatever the pass issues before the layer. */
|
||||
/* THE PASS'S FIRST ROUTED LAYER, staged at its first op of any kind, so the copies run behind
|
||||
* whatever the pass issues before the layer -- and the layers after it as far as the pace and
|
||||
* the ring allow. The layers the pass before staged for it are its own from here. */
|
||||
if (first_op_) {
|
||||
first_op_ = false;
|
||||
const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h,
|
||||
[](const Layer& L, int32_t op) { return L.first_op < op; });
|
||||
if (it != layers_.end()) {
|
||||
const int32_t li = (int32_t)(it - layers_.begin());
|
||||
if (!started_[(size_t)li] && will_issue(li)) {
|
||||
RAD_TRY(start(li));
|
||||
next_ = (int32_t)(it - layers_.begin());
|
||||
first_li_ = next_;
|
||||
if (n_early_ > 0 && next_ != 0) {
|
||||
withdraw_early();
|
||||
*resync = true;
|
||||
}
|
||||
next_ = std::max(next_, n_early_);
|
||||
n_early_ = 0;
|
||||
RAD_TRY(stage_ahead(first_li_ - 1, resync));
|
||||
}
|
||||
}
|
||||
|
||||
if ((size_t)h >= first_of_.size()) return RAD_OK;
|
||||
const int32_t li = first_of_[(size_t)h];
|
||||
if (li < 0) return RAD_OK;
|
||||
/* This layer's copies were published a layer ago: the one wait that orders its ops behind
|
||||
* them. */
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (holds_[b] == li) RAD_TRY(rad_event_wait(s, done_[b]));
|
||||
/* The layer before is done with its buffer: every pass of rows issued its last op, the last
|
||||
* of them recorded `free_`, and a layer's ops do not interleave with the next one's. Released
|
||||
* here and not at that op, whose next run would read copies already overwritten. */
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (holds_[b] >= 0 && holds_[b] != li && read_[b]) release(b);
|
||||
/* And the next layer's copies go out now, behind it. */
|
||||
const int32_t next = li + 1;
|
||||
if ((size_t)next < layers_.size() && !started_[(size_t)next] && will_issue(next)) {
|
||||
RAD_TRY(start(next));
|
||||
*resync = true;
|
||||
/* The run's arrival at this layer, which the copies kLead layers on are paced by. */
|
||||
RAD_TRY(rad_event_record(gate_[li % kGates], s));
|
||||
gate_li_[li % kGates] = li;
|
||||
/* This layer's copies were published when they went out: the one wait that orders its ops
|
||||
* behind them. */
|
||||
for (int32_t i : ring_order_) {
|
||||
Place& p = place_[i];
|
||||
if (!p.retired && p.li == li) RAD_TRY(rad_event_wait(s, p.done));
|
||||
}
|
||||
/* The layers before are done with their places: every pass of rows issued their last op, the
|
||||
* last of them recorded `free`, and a layer's ops do not interleave with the next one's. Given
|
||||
* back here and not at that op, whose next run would read copies already overwritten. */
|
||||
for (int32_t i : ring_order_) {
|
||||
Place& p = place_[i];
|
||||
if (!p.retired && p.li < li && p.read) retire(p);
|
||||
}
|
||||
/* And the copies go on ahead of it into the room that gave back. */
|
||||
if (next_ <= li) next_ = li + 1;
|
||||
const bool was = *resync;
|
||||
RAD_TRY(stage_ahead(li, resync));
|
||||
*resync = *resync || was;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE LAYER'S LAST OP: `free_` goes behind it, so the copies two layers on can start as early as
|
||||
* they could before -- and goes behind it again if the block issues the op for another pass of
|
||||
* rows, which is why the copies themselves are not released until the next layer starts. */
|
||||
/* THE LAYER'S LAST OP: `free` goes behind it, so a copy that laps its place can start as early as
|
||||
* it could -- and goes behind it again if the block issues the op for another pass of rows, which
|
||||
* is why the copies themselves are not given back until the next layer starts. */
|
||||
int PrefillStager::after_op(rad_op h, RadStream s) {
|
||||
if ((size_t)h >= last_of_.size()) return RAD_OK;
|
||||
const int32_t li = last_of_[(size_t)h];
|
||||
if (li < 0) return RAD_OK;
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (holds_[b] == li) {
|
||||
RAD_TRY(rad_event_record(free_[b], s));
|
||||
free_rec_[b] = true;
|
||||
read_[b] = true;
|
||||
}
|
||||
for (int32_t i : ring_order_) {
|
||||
Place& p = place_[i];
|
||||
if (p.retired || p.li != li) continue;
|
||||
RAD_TRY(rad_event_record(p.free, s));
|
||||
p.free_rec = true;
|
||||
p.read = true;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Nothing this pass staged outlives it. Then, when the next step goes on with a prompt, its trunk
|
||||
* pass's first layers go into the ring behind this pass's last ones -- layer k paced on this
|
||||
* pass's layer n - kLead + k, as the run would pace it if the two passes were one. */
|
||||
int PrefillStager::end_pass(RadStream s) {
|
||||
if (!armed_) return RAD_OK;
|
||||
armed_ = false;
|
||||
pass_last_[pass_kind_] = last_issued_;
|
||||
int rc = RAD_OK;
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (holds_[b] >= 0) {
|
||||
const int r = finish(b, s);
|
||||
if (r < 0 && rc >= 0) rc = r;
|
||||
}
|
||||
return rc;
|
||||
for (int32_t i : ring_order_) {
|
||||
Place& p = place_[i];
|
||||
if (p.retired) continue;
|
||||
const int r = rad_event_record(p.free, s);
|
||||
if (r < 0 && rc >= 0) rc = r;
|
||||
p.free_rec = r >= 0 || p.free_rec;
|
||||
retire(p);
|
||||
}
|
||||
if (rc < 0 || !next_prefill_) return rc;
|
||||
const int32_t n = (int32_t)layers_.size();
|
||||
for (int32_t k = 0; k < kLead && k < n; ++k) {
|
||||
const int32_t g = n - kLead + k;
|
||||
if (g < first_li_ || gate_li_[g % kGates] != g) break;
|
||||
int got = kLater;
|
||||
RAD_TRY(stage_layer(k, /*now=*/false, gate_[g % kGates], &got));
|
||||
if (got == kLater) break;
|
||||
n_early_ = k + 1;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== the file stager */
|
||||
|
||||
+128
-50
@@ -1,5 +1,5 @@
|
||||
/* stager.h -- the prefill stager: a routed layer's non-resident experts copied onto the card one
|
||||
* layer ahead of the layer that reads them.
|
||||
/* stager.h -- the prefill stager: routed layers' non-resident experts copied onto the card ahead
|
||||
* of the layers that read them.
|
||||
*
|
||||
* ---- WHY A PREFILL NEEDS IT -------------------------------------------------------------------
|
||||
*
|
||||
@@ -12,44 +12,86 @@
|
||||
* work leaves the link idle. Measured with r4d_selftest --perfmoe, the gate_up GEMM of a 2048-token
|
||||
* chunk is 1.53 ms with every expert on the card and 4.34 ms with the coldest 13% in host memory.
|
||||
*
|
||||
* So at a step large enough, the stager copies layer L+1's pooled experts into a VRAM buffer while
|
||||
* layer L runs, publishes the copies for layer L+1's ops, and publishes the host addresses again
|
||||
* once those ops are behind it. The copy is the same bytes the GEMM would have read, so the output
|
||||
* So at a step large enough, the stager copies the pooled experts of the layers ahead into a VRAM
|
||||
* ring while the layers before them run, publishes the copies for each layer's ops, and publishes
|
||||
* the host addresses again once those ops are behind it. The copy is the same bytes the GEMM would have read, so the output
|
||||
* is bit-identical; only when the link carries them moves.
|
||||
*
|
||||
* ---- WHERE THE BUFFERS ARE, AND WHEN THEY ARE ITS ---------------------------------------------
|
||||
* ---- WHERE THE RING IS, AND WHEN IT IS ITS ---------------------------------------------------
|
||||
*
|
||||
* Two buffers, each one layer's share of the experts the budget leaves off the card, at the top of
|
||||
* the activation arena (Program::arena_stage_off, sized by vram_budget_resolve). A step smaller
|
||||
* than the arena's full plan LENDS that top to the expert slab, so the buffers are the stager's
|
||||
* only in a step at the full plan -- which is exactly the steps worth staging for -- and the rest of
|
||||
* the time they hold resident experts like any other lent slot. The scheduler says which it is,
|
||||
* pass by pass (set_full_arena).
|
||||
* One region, the size of two layers' share of the experts the budget leaves off the card, at the
|
||||
* top of the activation arena (Program::arena_stage_off, sized by vram_budget_resolve). A step
|
||||
* smaller than the arena's full plan LENDS that top to the expert slab, so the region is the
|
||||
* stager's only in a step at the full plan -- which is exactly the steps worth staging for -- and
|
||||
* the rest of the time it holds resident experts like any other lent slot. The scheduler says
|
||||
* which it is, pass by pass (set_full_arena).
|
||||
*
|
||||
* ---- WHY A RING AND NOT TWO BUFFERS ------------------------------------------------------------
|
||||
*
|
||||
* Layers do not leave equal parts off the card: at depth, with the KV cache's loan taken back, the
|
||||
* last third of a Qwen3.8-Flash-Next stack pools about twice the median layer. With two buffers of
|
||||
* one share each, layer L+1's copy waits for layer L-1's last op, so the engine idled once a light
|
||||
* layer's copy was done -- 60 to 80 ms of a ~280 ms step -- and a heavy layer's copy, longer than
|
||||
* the layer before it, made every layer after it wait. The ring packs each layer at its own size,
|
||||
* so the copies run as far ahead as the light layers leave room for and the heavy ones start
|
||||
* early. A layer staged further ahead than the next one takes at most half the ring, so the next
|
||||
* layer always has the room two buffers gave it; the next one takes whatever is free.
|
||||
*
|
||||
* ---- THE ORDER, AND WHAT KEEPS IT SAFE ---------------------------------------------------------
|
||||
*
|
||||
* the pass's first op stage the first routed layer the pass issues, into buffer 0 or 1
|
||||
* a layer's first op stage the NEXT layer into the other buffer; re-read the residency
|
||||
* table so this layer's ops resolve the copies made one layer ago
|
||||
* a layer's last op record "buffer free" on the op's stream; publish the host addresses
|
||||
* the pass's end the same for anything still staged: nothing outlives its pass
|
||||
* the pass's first op stage the first routed layer the pass issues, and the ones after it
|
||||
* as far as the pace and the ring allow
|
||||
* a layer's first op wait on its copies; publish the host addresses of the layers before
|
||||
* it again; stage further layers into the room that gave back
|
||||
* a layer's last op record "free" behind it on the op's stream
|
||||
* the pass's end the same for anything still staged -- and, when the next step goes on
|
||||
* with a prompt, stage the first layers of its trunk pass
|
||||
*
|
||||
* A copy into a buffer waits on that buffer's "free" event, recorded behind the last op that read
|
||||
* the layer it held -- in this pass or an earlier one. The layer's ops wait on the copies' event
|
||||
* through ONE stream wait, issued before the layer's first op: the copies are published settled
|
||||
* (Mover::stage_units says why), and nothing but the layer's own ops ever resolves them.
|
||||
* A layer's place in the ring is counted in bytes the ring has handed out since bring-up, so a
|
||||
* place laps the region and a copy finds the places it overwrites from the count alone. Before a
|
||||
* copy goes out, the mover's stream waits on the "free" event of every earlier place it laps --
|
||||
* recorded behind the last op that read it, in this pass or an earlier one. The layer's ops wait on
|
||||
* the copies' event through ONE stream wait, issued before the layer's first op: the copies are
|
||||
* published settled (Mover::stage_units says why), and nothing but the layer's own ops ever
|
||||
* resolves them.
|
||||
*
|
||||
* A LAYER IS STAGED AHEAD ONLY WHEN THE PASS WILL ISSUE IT. A step issues its routed layers across
|
||||
* more than one pass -- the trunk in one, the MTP head's in the next -- and the last layer a trunk
|
||||
* pass stages ahead would otherwise be the head's, copied for a pass that never reads it and thrown
|
||||
* away at its end. The stager learns the last op each kind of pass issues (by draft_pass) and stages
|
||||
* a layer ahead only when its first op is at or below it.
|
||||
* ---- HOW FAR AHEAD ----------------------------------------------------------------------------
|
||||
*
|
||||
* A layer's copies go out once the compute stream has reached the MoE of the layer kLead before it,
|
||||
* through an event recorded at that layer's first op. Not as soon as the ring has room: copies that
|
||||
* land long before their layer is read cost the layers they overlap more than they save. Measured at
|
||||
* TP2 on Qwen3.8-Flash-Next, released as soon as there was room, every class of op ran slower and a
|
||||
* 26K-token prompt lost 0.6%; held to one layer ahead, the heavy late layers of a 160K-token prompt
|
||||
* waited again and it lost 2.4%. Three layers ahead covered the late layers at the smallest cost
|
||||
* to the short prompt.
|
||||
*
|
||||
* ---- THE NEXT STEP'S FIRST LAYERS -------------------------------------------------------------
|
||||
*
|
||||
* A step that carries a chunk of a prompt is issued only once the step before it has been read
|
||||
* back, so the copies of its first layers would start with it and its first layer would wait for
|
||||
* all of them. When the engine says the next step goes on with a prompt (set_next_prefill), the
|
||||
* pass's end stages the first layers of the next trunk pass instead, paced on this pass's last
|
||||
* layers as if the two passes were one. They are published at once. The next trunk pass adopts them
|
||||
* when it is armed; a trunk pass that is not publishes their host addresses again in begin_pass,
|
||||
* which the run phase calls before it brings the weight tables up to date. A draft pass in between
|
||||
* reads none of the trunk's layers and leaves them be. With both, against two buffers at TP2: 160K
|
||||
* 1.0-1.4% faster, 26K unchanged; at TP1, where the link carries every pooled expert each step,
|
||||
* 26K 0.6% faster.
|
||||
*
|
||||
* ---- ONLY THE TRUNK ---------------------------------------------------------------------------
|
||||
*
|
||||
* A draft head's routed layer is not the stager's. The head runs in passes of its own -- over a
|
||||
* prefill chunk, the history pass, which needs the head's experts on a prompt's last chunk alone
|
||||
* and there only for the rows that draft, a handful however long the chunk -- so its pooled
|
||||
* experts are read in place like a decode step's. The head's layer is numbered past the
|
||||
* trunk's layers (RadModelMeta::n_layers), left out at bring-up, and a draft pass is never armed.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../runtime/stager.h"
|
||||
#include "mover.h"
|
||||
#include "planner.h"
|
||||
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
@@ -60,22 +102,29 @@ public:
|
||||
~PrefillStager() override;
|
||||
|
||||
/* The routed layers of `plan` and the ops that read them, and `bytes` of device memory at
|
||||
* `region` as two buffers. `min_rows` is the smallest pass it arms for. Leaves it disabled --
|
||||
* `region` as the ring. `min_rows` is the smallest pass it arms for. Leaves it disabled --
|
||||
* enabled() false -- when the plan has no routed layer with a pooled unit to stage. */
|
||||
int init(const Program& prog, const Plan& plan, Mover* mover, char* region, int64_t bytes,
|
||||
int64_t min_rows);
|
||||
|
||||
/* Per pass, before it is released: whether the step runs at the arena's full plan, which is
|
||||
* when the buffers are not lent. */
|
||||
* when the region is not lent. */
|
||||
void set_full_arena(bool full) { full_ = full; }
|
||||
/* Per step, before it is released: whether the step after it goes on with a prompt in a pass
|
||||
* this stager arms for, so this step's trunk pass stages that pass's first layers. */
|
||||
void set_next_prefill(bool more) { next_prefill_ = more; }
|
||||
|
||||
bool enabled() const { return !layers_.empty(); }
|
||||
int64_t buffer_bytes() const { return cap_; }
|
||||
int64_t ring_bytes() const { return ring_; }
|
||||
/* The smallest pass (in tokens) the stager arms for: a step under it reads every pooled
|
||||
* expert of a routed layer synchronously. The scheduler keeps a held-back prefill chunk at
|
||||
* or above it (Scheduler::set_stage_rows). */
|
||||
int64_t min_rows() const { return min_rows_; }
|
||||
size_t n_layers() const { return layers_.size(); }
|
||||
/* Whether the last trunk pass armed: its routed layers' pooled experts were copied onto the
|
||||
* card through the ring. A draft pass leaves it as the trunk pass set it. */
|
||||
bool staged() const { return staged_; }
|
||||
static constexpr int32_t lead() { return kLead; }
|
||||
|
||||
bool begin_pass(const RadBatch* b) override;
|
||||
int before_op(rad_op h, RadStream s, bool* resync) override;
|
||||
@@ -92,33 +141,62 @@ private:
|
||||
std::vector<int32_t> first_of_; /* by op: the layer whose first op it is, or -1 */
|
||||
std::vector<int32_t> last_of_; /* by op: the layer whose last op it is, or -1 */
|
||||
|
||||
/* ONE LAYER'S PLACE IN THE RING. [beg, end) is in bytes handed out since bring-up; the
|
||||
* offset in the region is beg modulo its size, and a place never straddles the region's end. */
|
||||
struct Place {
|
||||
int32_t li = -1; /* index into layers_ */
|
||||
int64_t beg = 0, end = 0;
|
||||
RadEvent done = nullptr; /* behind its copies, on the mover stream */
|
||||
RadEvent free = nullptr; /* behind its last reader */
|
||||
bool free_rec = false;
|
||||
/* Its last op has been issued at least once and `free` is recorded behind it. A step
|
||||
* longer than the MoE block's pass of rows issues a layer's ops once per pass, so the
|
||||
* last op can run again: the copies are published away at the NEXT layer's first op,
|
||||
* which is past every pass, while each run of the last op moves `free` behind itself. */
|
||||
bool read = false;
|
||||
bool retired = false; /* its units are published at their pool slots */
|
||||
std::vector<int32_t> staged;
|
||||
};
|
||||
/* More places than a ring of two shares can hold layers of the smallest share a pass stages;
|
||||
* a full table only stops the copies going further ahead. */
|
||||
static constexpr int kPlaces = 16;
|
||||
Place place_[kPlaces];
|
||||
std::deque<int32_t> ring_order_; /* places in the ring, oldest first; retired ones stay until lapped */
|
||||
std::vector<int32_t> spare_; /* places not in the ring */
|
||||
|
||||
Mover* mover_ = nullptr;
|
||||
char* buf_[2] = { nullptr, nullptr };
|
||||
int64_t cap_ = 0;
|
||||
char* region_ = nullptr;
|
||||
int64_t ring_ = 0;
|
||||
int64_t head_ = 0; /* bytes handed out since bring-up */
|
||||
int64_t min_rows_ = 0;
|
||||
RadEvent done_[2] = { nullptr, nullptr }; /* behind a buffer's copies, on the mover stream */
|
||||
RadEvent free_[2] = { nullptr, nullptr }; /* behind a buffer's last reader */
|
||||
bool free_rec_[2] = { false, false };
|
||||
std::vector<int32_t> staged_[2];
|
||||
int32_t holds_[2] = { -1, -1 }; /* the layer a buffer holds, or -1 */
|
||||
/* The holder's last op has been issued at least once, and `free_` is recorded behind it. A
|
||||
* step longer than the MoE block's pass of rows issues a layer's ops once per pass, so the
|
||||
* last op can run again: the copies are released at the NEXT layer's first op, which is past
|
||||
* every pass, while each run of the last op moves `free_` behind itself. */
|
||||
bool read_[2] = { false, false };
|
||||
|
||||
/* THE PACE (see the top of this file): layer k's copies wait on the event recorded at the
|
||||
* first op of layer k - kLead, on the compute stream. A layer within kLead of the pass's first
|
||||
* routed layer has no such layer in its pass and goes at once. */
|
||||
static constexpr int32_t kLead = 3;
|
||||
static constexpr int kGates = 64;
|
||||
RadEvent gate_[kGates] = {};
|
||||
int32_t gate_li_[kGates] = {}; /* the layer each gate was recorded at this pass, or -1 */
|
||||
int32_t first_li_ = -1; /* the pass's first routed layer */
|
||||
|
||||
bool full_ = false;
|
||||
bool armed_ = false;
|
||||
bool first_op_ = false; /* the pass has issued nothing yet */
|
||||
std::vector<uint8_t> started_; /* by layer: staged (or tried) this pass */
|
||||
int32_t pass_kind_ = 0;
|
||||
int32_t last_issued_ = -1;
|
||||
std::map<int32_t, int32_t> pass_last_; /* by draft_pass: the last op such a pass issued */
|
||||
/* armed_ as the last trunk pass's begin_pass set it, which end_pass leaves alone: the engine
|
||||
* asks after the pass has ended. */
|
||||
bool staged_ = false;
|
||||
bool next_prefill_ = false;
|
||||
bool first_op_ = false; /* the pass has issued nothing yet */
|
||||
int32_t next_ = 0; /* the next layer to stage this pass */
|
||||
/* The next trunk pass's first layers, staged at this pass's end: layers [0, n_early_). */
|
||||
int32_t n_early_ = 0;
|
||||
|
||||
bool will_issue(int32_t li) const;
|
||||
int start(int32_t li);
|
||||
int finish(int32_t b, RadStream s);
|
||||
void release(int32_t b);
|
||||
enum { kStaged, kNone, kLater };
|
||||
int stage_ahead(int32_t cur, bool* resync);
|
||||
int stage_layer(int32_t li, bool now, RadEvent gate, int* got);
|
||||
void withdraw_early();
|
||||
int take(int64_t want, bool partial, int32_t* out);
|
||||
int recycle_front();
|
||||
void retire(Place& p);
|
||||
};
|
||||
|
||||
/* ---- THE FILE STAGER: routed layers read from the container -------------------------------------
|
||||
|
||||
Reference in new issue
Block a user