Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+82
-127
@@ -1,4 +1,4 @@
|
||||
/* heat.cpp -- the heat engine's mechanics. See heat.h for why any of it is shaped this way. */
|
||||
/* heat.cpp -- the heat engine's mechanics. See heat.h for the policy and data layout. */
|
||||
#include "heat.h"
|
||||
|
||||
#include <algorithm>
|
||||
@@ -26,7 +26,7 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
|
||||
bytes_.assign(n, 0);
|
||||
ever_.assign(n, 0u);
|
||||
|
||||
/* The movable units' slab classes, as dense indices -- see heat.h's `cls_`. */
|
||||
/* The movable units' slab classes as dense indices (heat.h: `cls_`). */
|
||||
cls_.assign(n, -1);
|
||||
{
|
||||
std::vector<int32_t> dense;
|
||||
@@ -46,13 +46,12 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
|
||||
|
||||
n_layer_ = 0;
|
||||
for (const MoveUnit& mu : plan.units) n_layer_ = std::max(n_layer_, mu.layer + 1);
|
||||
if (n_layer_ < 0) n_layer_ = 0;
|
||||
res_count_.assign((size_t)n_layer_, 0);
|
||||
|
||||
/* Each layer's units by expert id, and each slot's other movable units in plan order: a
|
||||
* layer's, then (slot n_layer_) those with no layer. Two units naming one (layer, expert)
|
||||
* leave the later one indexed by the expert -- the one a histogram credits -- and the
|
||||
* earlier, if it can move, among the layer's others. */
|
||||
/* Each layer's units by expert id, and each slot's other movable units in plan order (slot
|
||||
* n_layer_ holds those with no layer). If two units name one (layer, expert), the later one
|
||||
* is indexed by the expert (and credited by histograms); the earlier, if movable, goes among
|
||||
* the layer's others. */
|
||||
std::vector<std::vector<int32_t>> by_expert((size_t)n_layer_);
|
||||
std::vector<std::vector<int32_t>> other((size_t)n_layer_ + 1);
|
||||
int64_t movable = 0;
|
||||
@@ -124,13 +123,12 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
|
||||
end_n_cold_.assign((size_t)n_layer_ + 1, 0);
|
||||
end_ok_.assign((size_t)n_layer_ + 1, 0);
|
||||
|
||||
/* Two ways to be off, and they are different facts worth different lines. A static plan is a
|
||||
* mode the operator asked for; a plan with nothing movable is a model that does not need this
|
||||
* engine -- the all-in-VRAM degenerate case, where the mover never runs either. */
|
||||
/* Two distinct ways to be off: a static plan (an operator choice), or nothing movable (every
|
||||
* weight fits in VRAM; the mover never runs either). */
|
||||
if (!plan.dynamic) {
|
||||
enabled_ = false;
|
||||
RAD_INFO("placement is static (--deterministic): the heat engine will not run, so "
|
||||
"residency -- and therefore the summation order -- is fixed for the run");
|
||||
RAD_INFO("placement is static (--deterministic): residency and summation order are "
|
||||
"fixed for the run");
|
||||
return RAD_OK;
|
||||
}
|
||||
if (movable == 0) {
|
||||
@@ -152,7 +150,7 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
|
||||
void HeatEngine::observe_ids(int32_t layer, const int32_t* experts, const int32_t* counts,
|
||||
int32_t n) {
|
||||
if (!enabled_ || layer < 0 || layer >= n_layer_) return;
|
||||
/* The histogram these name, dense, so both entry points are the one pass. */
|
||||
/* Densify so both entry points share observe(). */
|
||||
const int32_t n_ex = n_ex_[(size_t)layer];
|
||||
std::vector<int32_t> dense((size_t)n_ex, 0);
|
||||
for (int32_t i = 0; i < n; ++i) {
|
||||
@@ -162,53 +160,43 @@ void HeatEngine::observe_ids(int32_t layer, const int32_t* experts, const int32_
|
||||
observe(layer, dense.data(), n_ex, 1.0f);
|
||||
}
|
||||
|
||||
/* DECAY EVERY POSITION, THEN CREDIT THE ROUTED ONES. Decay first, then credit: the other order
|
||||
* gives THIS dispatch's experts a decayed count, which makes min_gain = 1.0 mean 1/decay
|
||||
* activations rather than one -- the kind of off-by-a-constant that only ever shows up as a
|
||||
* threshold that does not do what it says.
|
||||
/* Decay every position, then credit the routed ones. Decay comes first so this dispatch's
|
||||
* credit is not decayed; otherwise min_gain = 1.0 would mean 1/decay activations.
|
||||
*
|
||||
* THE DECAY IS THE ONLY WORK EVERY POSITION NEEDS, so it is the only dense pass: one multiply a
|
||||
* float, vector code at any instruction set. A dispatch routes to a few dozen of a layer's
|
||||
* hundreds of experts, and everything else -- the credit, the pricing, the layer's ends -- is a
|
||||
* property of those, so it is done for those alone. `h * d` and then `+ c * w` round exactly as
|
||||
* the one expression `h * d + c * w` does, so the heats are the same bits either way.
|
||||
* The decay is the only dense pass (one vector multiply per float). A dispatch routes to a few
|
||||
* dozen of a layer's hundreds of experts, so crediting, pricing and the layer's ends touch only
|
||||
* those. `h * d` then `+ c * w` rounds exactly as `h * d + c * w`, so heats are bit-identical.
|
||||
*
|
||||
* A ROUTED EXPERT IS PRICED HERE TOO. A unit not in VRAM is not a stall -- the GEMM reads it
|
||||
* where it lies -- but for every tier above VRAM that read crosses the link, and those are the
|
||||
* bytes the mover exists to stop paying. Pricing them on the pass that credits the heat puts the
|
||||
* hit rate and the streamed bytes beside the policy's decisions.
|
||||
* Routed experts are priced here too: a unit off the device is read in place across the link,
|
||||
* and those are the bytes the mover exists to save. Pricing on the crediting pass puts hit rate
|
||||
* and streamed bytes beside the policy's decisions.
|
||||
*
|
||||
* THE LAYER'S ENDS FOLLOW FROM THE CREDITED EXPERTS WHEN THEY WERE VALID. A positive scale keeps
|
||||
* every order, and rounding is monotone, so the hottest unit off the device decays to exactly
|
||||
* `hot * d` and nothing uncredited passes it: the new hot end is that or a credited unit, whichever
|
||||
* is larger. The coldest units on the device decay to exactly `cold * d` likewise, and a credit
|
||||
* only raises a unit, so the cold end stands while any unit is left at it. The ends count the
|
||||
* units AT the cold value -- equal heats decay to equal heats -- because the common cold end is
|
||||
* a crowd: every resident unit no token has routed to yet sits at exactly zero. Only when the
|
||||
* last of them is credited is the next coldest unknown here, and the layer is rebuilt from its
|
||||
* positions. A tie decay creates is not counted, which can only rebuild a layer that did not need
|
||||
* it. */
|
||||
* The layer's ends are updated from the credited experts when they were valid. Decay by a positive
|
||||
* scale with monotone rounding keeps every order, so the hot end becomes `hot * d` or a credited
|
||||
* unit, whichever is larger; the cold end becomes `cold * d` and stands while any unit remains at
|
||||
* it, since credit only raises. The cold end counts units at exactly that value, because it is
|
||||
* usually a crowd (every resident unit not routed to lately sits at zero). When the last is
|
||||
* credited the layer is rebuilt from its positions. Ties created by decay are not counted, which
|
||||
* can only cause an unneeded rebuild. */
|
||||
void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert, float weight) {
|
||||
if (!enabled_ || layer < 0 || layer >= n_layer_ || !counts) return;
|
||||
if (!(weight > 0.0f)) weight = 1.0f;
|
||||
/* Passes this histogram stands for -- see observe()'s contract. At least one, so a caller
|
||||
* that does not set it still prices its reads. */
|
||||
/* Routing passes this histogram stands for (see heat.h: observe); at least one. */
|
||||
const uint64_t passes = weight >= 1.0f ? (uint64_t)(weight + 0.5f) : 1u;
|
||||
|
||||
const size_t l = (size_t)layer;
|
||||
const int32_t lo = slot_lo_[l], len = slot_lo_[l + 1] - lo;
|
||||
/* Past the histogram's last expert, and past the layer's, a position is credited nothing. */
|
||||
/* Positions past the histogram's or the layer's last expert get no credit. */
|
||||
const int32_t n = std::max(0, std::min(n_expert, n_ex_[l]));
|
||||
const float d = params_.decay;
|
||||
|
||||
/* THE HISTOGRAM ARRIVES BY DMA, so none of it is in the cache: every line is a miss, and a
|
||||
* scan that meets them one at a time pays one latency a line. Asked for all at once they
|
||||
* overlap each other and the decay below -- and a caller sweeping layers asks earlier still
|
||||
* (prefetch()), which makes this a no-op. */
|
||||
/* The histogram arrives by DMA and is not in cache. Prefetching every line at once overlaps
|
||||
* the misses with each other and with the decay; a caller sweeping layers may prefetch
|
||||
* earlier still. */
|
||||
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. */
|
||||
/* The credit cap (HeatParams::credit_cap) scales the whole histogram, preserving order.
|
||||
* Pricing ignores the cap. */
|
||||
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;
|
||||
@@ -235,9 +223,8 @@ void HeatEngine::observe(int32_t layer, const int32_t* counts, int32_t n_expert,
|
||||
if (rank_as_[q] == 1) hot = std::max(hot, x);
|
||||
else if (rank_as_[q] == 2 && was <= cold && --n_cold <= 0) ends = false;
|
||||
};
|
||||
/* A dispatch routes to a few dozen of the layer's experts, so the credited ones are found a
|
||||
* block at a time -- a mask of the positive counts is vector code -- and only its set bits are
|
||||
* visited, in increasing order as a scan would meet them. */
|
||||
/* Find credited experts a block at a time via a vectorisable mask of positive counts, then
|
||||
* visit only the set bits, in increasing order. */
|
||||
int32_t j0 = 0;
|
||||
for (; j0 + kLanes <= n; j0 += kLanes) {
|
||||
uint32_t m = 0;
|
||||
@@ -325,15 +312,13 @@ void HeatEngine::abandon(const Swap& s) {
|
||||
set_busy(s.demote, false);
|
||||
}
|
||||
|
||||
/* THE ONE-PAIR PICK, kept as the definition of the ranking: the hottest movable unit off the device
|
||||
* against the coldest one on it, ties broken toward the layer that most needs the slot, and the
|
||||
* first unit in index order on a full tie. step() proposes exactly the pairs repeated calls to
|
||||
* this would, from one pass. */
|
||||
/* The one-pair pick, kept as the reference definition of the ranking: the hottest movable unit
|
||||
* off the device against the coldest on it, ties broken toward the layer that most needs the
|
||||
* slot, then by lowest index. step() proposes exactly the pairs repeated calls to this would. */
|
||||
bool HeatEngine::pick(Swap* out) const {
|
||||
if (!enabled_ || !warm() || !out) return false;
|
||||
|
||||
/* Each class's hottest unit off the device and coldest one on it: a swap stays in its class
|
||||
* (heat.h's `cls_`). */
|
||||
/* Per class, since a swap stays in its class (heat.h: `cls_`). */
|
||||
std::vector<int32_t> hot((size_t)n_cls_, -1), cold((size_t)n_cls_, -1);
|
||||
std::vector<float> hot_h((size_t)n_cls_, 0.0f), cold_h((size_t)n_cls_, 0.0f);
|
||||
std::vector<int32_t> hot_res((size_t)n_cls_, 0), cold_res((size_t)n_cls_, 0);
|
||||
@@ -345,32 +330,27 @@ bool HeatEngine::pick(Swap* out) const {
|
||||
const int32_t rc = l >= 0 ? res_count_[(size_t)l] : 0;
|
||||
const float h = heat_[(size_t)pos_[i]];
|
||||
if (tier_[i] == Tier::VRAM) {
|
||||
/* Colder wins; on an exact tie take from the layer holding the MOST resident units,
|
||||
* which is the layer that can spare it. */
|
||||
/* Colder wins; on a tie, take from the layer holding the most resident units. */
|
||||
if (cold[c] < 0 || h < cold_h[c] || (h == cold_h[c] && rc > cold_res[c])) {
|
||||
cold[c] = (int32_t)i; cold_h[c] = h; cold_res[c] = rc;
|
||||
}
|
||||
} else {
|
||||
/* Hotter wins; on an exact tie the layer with the FEWEST resident units wins, because
|
||||
* that is the layer whose tokens are missing most often. Both halves of this are the
|
||||
* same statement about where capacity should sit.
|
||||
/* Hotter wins; on a tie, the layer with the fewest resident units, whose tokens miss
|
||||
* most often.
|
||||
*
|
||||
* Tier::SSD is a candidate here and Tier::HostPinned is too, deliberately: this
|
||||
* engine promotes UP from wherever the unit is, and the mover knows which source that
|
||||
* means. What it never does is push a unit DOWN to the file tier -- banishing
|
||||
* something to disk is a bet that it will not be needed, paid at a full read every
|
||||
* time the bet is wrong, and a frequency counter has no forward-looking confidence to
|
||||
* justify one. Demotion targets the host pool, and only the planner assigns SSD. */
|
||||
* Both Tier::SSD and Tier::HostPinned units are candidates: promotion is from wherever
|
||||
* the unit is, and the mover knows the source. Demotion never targets the file tier,
|
||||
* since a frequency counter cannot justify a bet that a unit will not be needed; it
|
||||
* targets the host pool, and only the planner assigns SSD. */
|
||||
if (hot[c] < 0 || h > hot_h[c] || (h == hot_h[c] && rc < hot_res[c])) {
|
||||
hot[c] = (int32_t)i; hot_h[c] = h; hot_res[c] = rc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* BOTH guards, and they answer different failures. The ratio stops a swap that trades one
|
||||
* warm unit for another; the additive floor stops the degenerate case where the victim's heat
|
||||
* is zero, which every ratio passes trivially and which describes most of the resident set
|
||||
* right after warmup. Of the classes whose pair passes, the one with the hotter candidate. */
|
||||
/* Both guards: the ratio stops trading one warm unit for another, and the additive floor
|
||||
* stops swaps against a zero-heat victim, which any ratio passes. Of the classes whose pair
|
||||
* passes, take the one with the hotter candidate. */
|
||||
int32_t best = -1;
|
||||
for (int32_t c = 0; c < n_cls_; ++c) {
|
||||
if (hot[(size_t)c] < 0 || cold[(size_t)c] < 0) continue;
|
||||
@@ -388,12 +368,10 @@ bool HeatEngine::pick(Swap* out) const {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* 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 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. */
|
||||
/* A whole step's proposals from one pass. Marking a pair busy changes no heat or resident
|
||||
* count, so the m-th pair repeated pick() calls would return is the m-th entry at each end of the
|
||||
* same ranking. One pass keeps the `moves_per_step` best of each end and yields the same
|
||||
* proposals and stop counters as repeated picks, without a scan per move on the issuing thread. */
|
||||
namespace {
|
||||
using Ranked = HeatRanked;
|
||||
/* Hotter first, then the layer with fewer residents, then the lower index. */
|
||||
@@ -425,10 +403,9 @@ int HeatEngine::step(std::vector<Swap>* out) {
|
||||
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
|
||||
* ranking only gets colder at one end and warmer at the other -- and the dispatch proposes
|
||||
* nothing, which is the verdict the full ranking below reaches, from one entry a layer. The
|
||||
* ends also count the candidates at each end, which is all the stop reasons below need. */
|
||||
/* Test the best pair from the layers' ends first. If it fails the guard, every pair does,
|
||||
* and the dispatch proposes nothing after one entry per layer. The ends' counts also give the
|
||||
* stop reasons. */
|
||||
int64_t n_off = 0, n_on = 0;
|
||||
float bar = 0.0f;
|
||||
{
|
||||
@@ -448,31 +425,21 @@ int HeatEngine::step(std::vector<Swap>* out) {
|
||||
bar = cold_h * params_.hysteresis + params_.min_gain;
|
||||
}
|
||||
|
||||
/* THE RANKING, over every movable position. A unit can only enter a full list by reaching
|
||||
* its last entry's heat, so each block of positions is first screened against the two lists'
|
||||
* last heats -- one compare a position, over contiguous floats -- and only what passes the
|
||||
* screen meets the exact comparison, ties and all. The screen passes a tie, so it never drops
|
||||
* a unit the comparison would keep; and the lists are a strict order's best k, so meeting the
|
||||
* units in position order rather than unit order ends in the same lists.
|
||||
/* The ranking over every movable position. Each kLanes block is screened against the two
|
||||
* lists' last heats (one vector compare per position); only what passes meets the exact
|
||||
* comparison. The screen passes ties, so it never drops a unit the comparison would keep, and
|
||||
* since the lists hold a strict order's best k, visiting in position order gives the same
|
||||
* lists. The hot end is also screened against the guard bar: a unit below it cannot be
|
||||
* proposed against any victim.
|
||||
*
|
||||
* The hot end is screened against the guard as well. A unit colder than the coldest resident
|
||||
* unit's bar fails the guard against every victim the cold list can hold, so it cannot be
|
||||
* proposed, and the list it is kept out of only ever ends at the pair that fails. A layer's
|
||||
* run is a whole number of kLanes blocks, so every block has the same trip count and the
|
||||
* screen is vector code.
|
||||
* Each layer is first screened by its ends. Most resident units sit exactly at the cold end
|
||||
* (zero), which the position screen passes, so without this nearly every resident unit would
|
||||
* reach the exact comparison. A layer whose hot end is below the hot bar and whose cold end
|
||||
* cannot beat the cold list's last entry is skipped; on a heat tie the comparison falls to the
|
||||
* layer's shared resident count, then to the unit index, bounded by the layer's lowest.
|
||||
*
|
||||
* A WHOLE LAYER IS SCREENED FIRST, BY ITS ENDS. Most resident units sit at exactly the cold
|
||||
* end's heat -- zero, for every one no token has routed to lately -- and the position screen
|
||||
* passes a tie, so it would send nearly every resident unit to the exact comparison only for
|
||||
* the tie break to refuse it. The ends are that layer's hottest candidate off the device and
|
||||
* coldest on it, so a layer whose hot end is below the hot list's bar and whose cold end
|
||||
* cannot beat the cold list's last entry holds no unit either list would keep. On a tie the
|
||||
* comparison falls to the layer's resident count, which every unit of the layer shares, and
|
||||
* then to the unit index, which the layer's lowest bounds. */
|
||||
/* ONE PAIR OF LISTS A CLASS, because a swap stays inside its class (heat.h's `cls_`). The
|
||||
* screens below take the loosest of the classes' thresholds, so a unit any class's list would
|
||||
* keep still reaches the exact comparison; with one class they are that class's thresholds
|
||||
* and the screen is exact. */
|
||||
* One pair of lists per class (heat.h: `cls_`). The screens use the loosest threshold across
|
||||
* classes, so they stay conservative; with one class they are exact. */
|
||||
const int nc = n_cls_;
|
||||
rank_hot_.resize((size_t)(k * nc));
|
||||
rank_cold_.resize((size_t)(k * nc));
|
||||
@@ -484,8 +451,8 @@ int HeatEngine::step(std::vector<Swap>* out) {
|
||||
const int64_t n_pool = n_off, n_vram = n_on;
|
||||
const float* hp = heat_.data();
|
||||
const uint8_t* ra = rank_as_.data();
|
||||
/* A hot unit reaches a list at the lowest last entry of a full list, and none below the guard;
|
||||
* a cold one at the highest last entry, and any heat while some list is not full. */
|
||||
/* Hot threshold: the lowest last entry of any full list, never below the guard. Cold
|
||||
* threshold: the highest last entry, or any heat while some list is not full. */
|
||||
auto hot_bar = [&]() {
|
||||
float t = INFINITY;
|
||||
for (int c = 0; c < nc; ++c) t = std::min(t, n_hot[c] == k ? hot[c * k + k - 1].h : -INFINITY);
|
||||
@@ -537,10 +504,9 @@ int HeatEngine::step(std::vector<Swap>* out) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The proposals: each class's m-th hottest against its m-th coldest, for as long as that
|
||||
* passes the guard -- the ranking only gets colder at one end and warmer at the other, so the
|
||||
* first pair that fails ends the class -- and at most `k` of them a class, taken across the
|
||||
* classes hottest first, which is the order repeated pick() calls would return them in. */
|
||||
/* Each class's m-th hottest against its m-th coldest while that passes the guard (the first
|
||||
* failure ends the class), at most `k` per class, taken across classes hottest first: the
|
||||
* order repeated pick() calls would return. */
|
||||
int32_t* m_of = m_of_.data();
|
||||
for (int c = 0; c < nc; ++c) m_of[c] = 0;
|
||||
int made = 0;
|
||||
@@ -563,7 +529,7 @@ int HeatEngine::step(std::vector<Swap>* out) {
|
||||
s.promote = hot[best * k + m_of[best]].unit;
|
||||
s.demote = cold[best * k + m_of[best]].unit;
|
||||
++m_of[best];
|
||||
/* Marked busy on the way out: the caller owns the pair until it publishes or abandons. */
|
||||
/* The caller owns the pair until it publishes or abandons it. */
|
||||
set_busy(s.promote, true);
|
||||
set_busy(s.demote, true);
|
||||
out->push_back(s);
|
||||
@@ -571,11 +537,8 @@ int HeatEngine::step(std::vector<Swap>* out) {
|
||||
++made;
|
||||
}
|
||||
if (short_of_budget) {
|
||||
/* Two ways to propose nothing more and they are different diagnoses. `refused` is the
|
||||
* guard declining -- the healthy steady state. `no_candidate` is one end of the ranking
|
||||
* being empty, which means either everything movable is resident or nothing is, and is a
|
||||
* budget question rather than a policy one. The pairs already proposed are busy by now,
|
||||
* so they are not counted at either end. */
|
||||
/* See HeatStats for `refused` vs `no_candidate`. Pairs already proposed are busy and not
|
||||
* counted at either end. */
|
||||
if (n_pool - made > 0 && n_vram - made > 0) ++stats_.refused; else ++stats_.no_candidate;
|
||||
}
|
||||
return RAD_OK;
|
||||
@@ -595,20 +558,15 @@ std::string HeatEngine::report() const {
|
||||
(unsigned long long)stats_.demotions);
|
||||
s += fmt(" %llu dispatches declined on hysteresis, %llu found no candidate at one end\n",
|
||||
(unsigned long long)stats_.refused, (unsigned long long)stats_.no_candidate);
|
||||
/* The one line that says whether the traffic above was worth paying. A readmit is a unit this
|
||||
* engine demoted and then fetched back: both directions of the link spent to return to where
|
||||
* it started, on the link the zero-copy tier needs. High here means the guards are too
|
||||
* loose -- and note that TIGHTENING min_gain to fix it costs more bytes, not fewer. */
|
||||
/* A readmit is a unit demoted and then fetched back: link traffic both ways for nothing. A high
|
||||
* rate means the guards are too loose, though raising min_gain costs more bytes (heat.h). */
|
||||
s += fmt(" %llu distinct units promoted, %llu readmits (%.0f%% of promotions were of "
|
||||
"something already demoted)\n",
|
||||
(unsigned long long)stats_.distinct_promoted, (unsigned long long)stats_.readmits,
|
||||
stats_.promotions ? 100.0 * (double)stats_.readmits / (double)stats_.promotions : 0.0);
|
||||
|
||||
/* The histogram this engine exists for. A global profile ranking leaves the per-layer
|
||||
* resident count wherever it happens to fall; a layer starved of slots misses on nearly every
|
||||
* token however good the ranking inside it is, which is how a hit rate lands below what
|
||||
* choosing at random would give. Whether the engine repaired that is a question about this
|
||||
* DISTRIBUTION, not about the mean. */
|
||||
/* The per-layer resident distribution: a layer starved of slots misses on nearly every token
|
||||
* however good its internal ranking, so the spread matters more than the mean. */
|
||||
if (!res_count_.empty()) {
|
||||
int32_t lo = res_count_[0], hi = res_count_[0];
|
||||
double sum = 0;
|
||||
@@ -618,10 +576,7 @@ std::string HeatEngine::report() const {
|
||||
for (int32_t v : res_count_) var += (v - mean) * (v - mean);
|
||||
s += fmt(" resident units a layer: min %d max %d mean %.1f sd %.1f\n", (int)lo, (int)hi,
|
||||
mean, std::sqrt(var / (double)res_count_.size()));
|
||||
/* AND WHICH LAYERS, because min/max/sd cannot be joined to anything. A kernel trace can
|
||||
* say which layers run longer than their neighbours; only this line can say whether those
|
||||
* are the starved ones, and without it the two measurements sit in different files saying
|
||||
* nothing to each other. One line, one number a layer, printed once at exit. */
|
||||
/* Per-layer counts, so slow layers in a kernel trace can be matched to starved ones. */
|
||||
s += " per layer:";
|
||||
for (size_t i = 0; i < res_count_.size(); ++i) {
|
||||
if (i % 12 == 0) s += fmt("\n L%-3zu ", i);
|
||||
|
||||
+116
-191
@@ -1,49 +1,31 @@
|
||||
/* heat.h -- the heat engine: which conditional weight should be in VRAM, decided from what the
|
||||
* router actually did.
|
||||
/* heat.h -- the heat engine: which conditional weights should be in VRAM, decided from the
|
||||
* router's observed choices.
|
||||
*
|
||||
* EXPERT OFFLOAD IS A PREDICTION PROBLEM. Layer offload is not -- declare enumerated the whole
|
||||
* access sequence and the planner emits an exact prefetch schedule off it. Routing is
|
||||
* data-dependent, so for RAD_ACCESS_CONDITIONAL weights there is no schedule to emit and the only
|
||||
* thing left is a policy. This file is that policy and nothing else: it sees a tier per unit, a
|
||||
* heat per unit and a dispatch count, and it answers one question -- "swap these two."
|
||||
* Layer offload gets an exact prefetch schedule, because declare enumerates the access sequence.
|
||||
* Routing (RAD_ACCESS_CONDITIONAL) is data-dependent, so expert offload needs a policy instead.
|
||||
* This file is that policy: from a tier and a heat per unit and a dispatch count, it proposes
|
||||
* swaps. It is pure host code with no device calls and no knowledge of slabs, streams or events
|
||||
* (that is mover.cpp), so the decision half, hysteresis included, is testable without a card.
|
||||
*
|
||||
* Deliberately pure host code with no device call in it and no knowledge of slabs, streams or
|
||||
* events. Everything about how the bytes get there is mover.cpp. That split is what lets the
|
||||
* entire decision half be tested on a machine with no card, which is the only reason the
|
||||
* hysteresis behaviour below is checkable at all.
|
||||
* ---- one step behind ---------------------------------------------------------------------------
|
||||
*
|
||||
* ---- WHAT IT COSTS TO BE ONE STEP BEHIND, HONESTLY -------------------------------------------
|
||||
* Routing runs on device and never blocks the compute stream. The histogram is copied back
|
||||
* asynchronously and consumed on the next step (spec §5.5), so every decision is one step stale.
|
||||
* Ranking is unaffected, since a hot expert stays hot across many steps. But an expert that is not
|
||||
* resident this step cannot be fetched in time: it is served from where it lies, streamed from the
|
||||
* pinned pool or staged off the file tier. A last-moment fetch would have to fit between the
|
||||
* router's output and the expert GEMM's first block, which is microseconds. Hit rate is therefore
|
||||
* a property of the placement policy, and the run phase has no device round-trip.
|
||||
*
|
||||
* Routing is computed on device and never blocks the compute stream. The histogram is copied back
|
||||
* asynchronously and this engine consumes it on the NEXT step (spec §5.5), so every placement
|
||||
* decision is one step stale.
|
||||
* ---- why LFU with decay ------------------------------------------------------------------------
|
||||
*
|
||||
* For heat-based promotion that is irrelevant: a hot expert is hot across many steps, and a
|
||||
* ranking built from the step before ranks almost exactly the same as one built from this step.
|
||||
* The real cost is different and it is worth being blunt about, because it is what people expect
|
||||
* this file to do and it does not:
|
||||
*
|
||||
* AN EXPERT THAT IS NOT RESIDENT THIS STEP CANNOT BE FETCHED IN TIME. It is served from
|
||||
* wherever it is -- streamed out of the pinned pool over the link, or staged off the file tier.
|
||||
* There is no last-moment rescue and there is no point adding one: the fetch would have to
|
||||
* finish inside the gap between the router's output and the expert GEMM's first block, which
|
||||
* is microseconds.
|
||||
*
|
||||
* Hit rate is therefore a property of the PLACEMENT POLICY, not of a rescue path. That is the
|
||||
* trade, and what it buys is a run phase with no device round-trip in it.
|
||||
*
|
||||
* ---- 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. 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.
|
||||
* In routing-trace replays, runtime placement beats static profile placement by a wide margin, and
|
||||
* the move rate bounds it, not the ranking: at the same swaps a step, an oracle that knows every
|
||||
* future routing scores no better (78.0% vs 78.4% at 64 swaps a step, Qwen3.8-Flash-Next TP1, 40%
|
||||
* of experts resident). Unrestricted Belady reaches 92% only by admitting every miss at once, which
|
||||
* here would copy again bytes the GEMM just streamed. The levers are the move budget
|
||||
* (RAD_PLACE_MOVES_PER_STEP), the slots behind it, and keeping a prompt's routing from swamping the
|
||||
* answer's (HeatParams::credit_cap), not the decay constant or the guards.
|
||||
*/
|
||||
#pragma once
|
||||
#include "planner.h"
|
||||
@@ -54,78 +36,54 @@
|
||||
namespace rad {
|
||||
|
||||
struct HeatParams {
|
||||
/* 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.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. */
|
||||
/* Applied to a layer's whole plane each time its histogram is credited. Every layer is
|
||||
* credited once a step, so planes decay in lockstep and heats stay comparable across layers,
|
||||
* which the global ranking needs. 0.95 is a half-life of about 14 steps. In replay at 64 swaps
|
||||
* a step, hit rate is flat from 0.8 to 0.95 and falls above it (77.1% at 0.98, 74.2% at 0.99):
|
||||
* a longer memory ranks experts the conversation has moved past above the current ones. */
|
||||
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
|
||||
* changes nothing. */
|
||||
/* Promote only when the candidate beats the victim by this ratio, so the two ends of the
|
||||
* ranking do not trade places on noise. */
|
||||
float hysteresis = 1.25f;
|
||||
|
||||
/* ...and the additive half of the same guard, in units of one activation. It is what stops a
|
||||
* swap when the victim's heat is ZERO, where any ratio test passes trivially -- and right
|
||||
* after warmup that describes most of the resident set, so without this the first dispatch
|
||||
* would try to swap the entire cache.
|
||||
/* The additive half of the guard, in activations. It stops a swap against a zero-heat victim,
|
||||
* where any ratio passes; right after warmup that is most of the resident set.
|
||||
*
|
||||
* LINK TRAFFIC IS U-SHAPED IN THIS THRESHOLD. PAST THE BOTTOM OF THE CURVE, RAISING IT MOVES
|
||||
* MORE BYTES, NOT FEWER -- so do not "fix" it by tightening the bar to save traffic. The
|
||||
* economics look one-directional -- a promotion costs an H2D plus a D2H and only pays if the
|
||||
* expert is selected again -- and they are not, because A PROMOTION DECLINED COMES BACK AS A
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
* Do not raise it to save link traffic: traffic is U-shaped in this threshold. A declined
|
||||
* promotion comes back as a miss, streamed over the same link, so past the minimum a tighter
|
||||
* bar loses hit rate and saves no bytes. A swap costs its promotion: the link is near full
|
||||
* duplex (R9700: 28.5 GB/s up and 25.0 down at once, 28.8 up alone), so a demotion rides the
|
||||
* idle direction while a promotion shares the upstream with every miss. 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 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`.
|
||||
/* Swaps step() may propose per slab class each step, after every layer is credited. The value
|
||||
* and its reason are at RAD_PLACE_MOVES_PER_STEP, which also sizes the free slots a swap lands
|
||||
* in (shadow and turnover slots); a budget raised here without them is spent on
|
||||
* `starved_slab`. Promotions share the link with streamed misses, but each swap saves many
|
||||
* times its own bytes in misses.
|
||||
*
|
||||
* 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 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. */
|
||||
* Per class because a rank holding an uneven slice of every expert has two classes of about
|
||||
* half an expert each; a shared budget would make residency converge half as fast. */
|
||||
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. */
|
||||
/* The most one histogram credits, in selections; a larger histogram is scaled to this total.
|
||||
* Decode routes a few rows a sequence and stays under it. A prefill chunk routes thousands
|
||||
* and would otherwise make the resident set the prompt's for dozens of steps, while prefill
|
||||
* gains little from residency (a chunk reads nearly every expert; the stager copies the rest).
|
||||
* Mixed-workload replay, Qwen3.8-Flash-Next TP1: decode hit rate 77.3% uncapped, 78.9% at
|
||||
* 1024, 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
|
||||
* zero-heat victim that is two tokens agreeing in one dispatch -- evidence, not noise,
|
||||
* whatever the dispatch count is. A warmup only postpones convergence. */
|
||||
/* Dispatches to watch before moving anything. 0, because min_gain already requires
|
||||
* `hot >= cold*hysteresis + 1.5`, which against a zero-heat victim is two tokens agreeing in
|
||||
* one dispatch; a warmup only delays convergence. */
|
||||
int warmup_dispatches = 0;
|
||||
};
|
||||
|
||||
/* A swap is returned as a PAIR even though the mover issues two independent transfers, because
|
||||
* the DECISION is a comparison between them: promoting without the matching demotion would grow
|
||||
* the resident set past the slab. */
|
||||
/* A promotion and its matching demotion. The mover issues two transfers, but they are decided
|
||||
* together: a promotion without its demotion would grow the resident set past the slab. */
|
||||
struct Swap {
|
||||
int32_t promote = -1; /* unit index */
|
||||
int32_t demote = -1;
|
||||
@@ -137,71 +95,53 @@ struct HeatRanked { float h; int32_t rc; int32_t unit; };
|
||||
struct HeatStats {
|
||||
uint64_t dispatches = 0;
|
||||
uint64_t proposed = 0, promotions = 0, demotions = 0;
|
||||
/* Why a dispatch did NOT move anything, which is the diagnostic that matters once the engine
|
||||
* looks idle. `refused` is the guard declining -- the healthy steady state, and the number
|
||||
* that should dominate once the hot set has settled. */
|
||||
/* Why a dispatch moved nothing. `refused` is the guard declining, the healthy steady state.
|
||||
* `no_candidate` is an empty end of the ranking (everything movable is resident, or nothing
|
||||
* is), a budget question rather than a policy one. */
|
||||
uint64_t refused = 0, no_candidate = 0;
|
||||
/* Is the churn PROGRESS or THRASH? The same total move count means two opposite things. If
|
||||
* every promotion is of a unit never promoted before, the engine is still discovering the
|
||||
* working set and the traffic is an investment. If it keeps re-admitting units it demoted a
|
||||
* moment ago, the traffic is pure loss: both directions of the link spent to arrive back
|
||||
* where it started. `readmits` is the second case counted directly, and it is the number that
|
||||
* decides whether the guards are set right. */
|
||||
/* Progress or thrash. `distinct_promoted` counts first-time promotions (still discovering the
|
||||
* working set); `readmits` counts promotions of units demoted earlier, link traffic spent to
|
||||
* return to where it started. Readmits say whether the guards are set right. */
|
||||
uint64_t distinct_promoted = 0, readmits = 0;
|
||||
/* WHAT THE ROUTER ASKED FOR, AND WHETHER IT WAS THERE. Counted on the histogram this engine
|
||||
* already walks, so it is one compare per routed expert and no second pass.
|
||||
*
|
||||
* A miss is not an error and nothing stalls on it: the GEMM reads that expert's weights from
|
||||
* whatever tier holds them, which for a host-pinned unit means pulling them across the link
|
||||
* on the critical path of the step. So `stream_bytes` is the OTHER traffic the mover's
|
||||
* promotions were hiding -- a promotion is bytes spent once to stop paying this, and without
|
||||
* both numbers beside each other there is no way to say whether the policy is winning.
|
||||
*
|
||||
* Weighted by the histogram's `weight`, because a draft head's histogram stands for several
|
||||
* routing passes and each of them really did read its experts. The hit RATE is unaffected --
|
||||
* both counters scale together -- and the byte figure is right.
|
||||
*/
|
||||
/* Routed experts and how many were resident, counted on the histogram pass observe() already
|
||||
* makes. A miss does not stall: the GEMM reads the expert from its tier, which for a
|
||||
* host-pinned unit crosses the link on the step's critical path. `stream_bytes` is that
|
||||
* traffic, the cost promotions exist to avoid. Weighted by the histogram's `weight`, since a
|
||||
* draft head's histogram stands for several routing passes; the hit rate is unaffected. */
|
||||
uint64_t routed = 0, routed_resident = 0, stream_bytes = 0;
|
||||
};
|
||||
|
||||
class HeatEngine {
|
||||
public:
|
||||
/* Binds to the plan. Returns RAD_OK even when the plan is static -- that is a mode, not a
|
||||
* failure, and every caller would otherwise have to special-case it. `enabled()` says which.
|
||||
* Under Config::deterministic the plan is static, this stays off, and step() proposes
|
||||
/* Binds to the plan. A static plan is a mode, not a failure: init returns RAD_OK and
|
||||
* enabled() is false. Under Config::deterministic the plan is static and step() proposes
|
||||
* nothing for the whole run (spec §17). */
|
||||
int init(const Plan& plan, const HeatParams& params);
|
||||
bool enabled() const { return enabled_; }
|
||||
|
||||
/* ---- the input: last step's routing histogram ------------------------------------------
|
||||
/* ---- input: last step's routing histogram ------------------------------------------------
|
||||
*
|
||||
* `counts[e]` is how many of the step's tokens routed to expert e of this layer. The credit
|
||||
* is that count and not a flat 1.0: cost is per DISTINCT expert -- a dispatch reads an
|
||||
* expert's weights once however many tokens chose it -- but the probability of needing it
|
||||
* again is not. An expert several tokens chose is far likelier to be chosen again soon than
|
||||
* one a single token chose, and most selections are single-token. Weighting by it moves no
|
||||
* extra bytes; it only ranks better. */
|
||||
/* `weight` is how many of that layer's routing passes this histogram stands for -- see
|
||||
* Ctx::last_histogram_reports. It is 1 for every layer of a non-speculative step and n_spec
|
||||
* for a draft head, and it belongs on the CREDIT rather than the decay: the caller sweeps
|
||||
* every layer exactly once a step, so the planes decay in lockstep and heats stay comparable
|
||||
* across layers. Without it a single histogram silently stands for several passes' worth of
|
||||
* activations and under-credits the experts a draft head routed to. */
|
||||
* is the count, not 1: a dispatch reads an expert once however many tokens chose it, but an
|
||||
* expert several tokens chose is far likelier to be chosen again soon.
|
||||
*
|
||||
* `weight` is how many of the layer's routing passes this histogram stands for (see
|
||||
* Ctx::last_histogram_reports): 1 for a non-speculative step, n_spec for a draft head. It
|
||||
* scales the credit, not the decay, because every layer still decays exactly once a step. */
|
||||
void observe(int32_t layer, const int32_t* counts, int32_t n_expert, float weight = 1.0f);
|
||||
/* The same, sparse: distinct expert ids and their counts. `counts` may be null for one each. */
|
||||
void observe_ids(int32_t layer, const int32_t* experts, const int32_t* counts, int32_t n);
|
||||
/* Starts the fetch of a histogram observe() will read: a row the card copied into host
|
||||
* memory is a miss on every line, so a caller that knows its next rows asks for them early. */
|
||||
/* Starts fetching a histogram observe() will read. A row the card copied into host memory
|
||||
* misses on every line, so a caller that knows its next rows asks early. */
|
||||
static void prefetch(const int32_t* counts, int32_t n_expert) {
|
||||
for (int32_t j = 0; j < n_expert; j += 64 / (int32_t)sizeof(int32_t))
|
||||
__builtin_prefetch(counts + j);
|
||||
}
|
||||
|
||||
/* ---- the tier map, written by the MOVER when a move PUBLISHES, not when it is issued ----
|
||||
/* ---- tier map, written by the mover when a move publishes, not when it is issued ---------
|
||||
*
|
||||
* Between issue and publish both copies of the bytes are valid and the dispatch still reads
|
||||
* the old one, so this engine must agree with dispatch about where a unit is or it will pick
|
||||
* the same one twice. `set_busy` is what excludes an in-flight unit instead. */
|
||||
* Until publish both copies are valid and dispatch reads the old one, so the tier here must
|
||||
* match dispatch's view. `set_busy` is what keeps an in-flight unit from being picked again. */
|
||||
void set_tier(int32_t unit, Tier t);
|
||||
void set_busy(int32_t unit, bool busy);
|
||||
Tier tier(int32_t unit) const { return tier_[(size_t)unit]; }
|
||||
@@ -210,30 +150,25 @@ public:
|
||||
/* The best swap available, or false when the guards refuse. */
|
||||
bool pick(Swap* out) const;
|
||||
|
||||
/* One step's worth of proposals, at most `moves_per_step` of them a class.
|
||||
/* One step's proposals, at most `moves_per_step` per 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
|
||||
* the quarantine -- or call abandon() for both halves. A proposal that is silently dropped
|
||||
* leaves the pair busy forever and the engine goes quiet with no counter to say why. */
|
||||
* Every unit in the result is marked busy. The caller must either issue the transfer
|
||||
* (set_tier() on publish, set_busy(false) after the quarantine) or abandon() the pair. A
|
||||
* dropped proposal leaves both units busy forever, with no counter to show it. */
|
||||
int step(std::vector<Swap>* out);
|
||||
void abandon(const Swap& s);
|
||||
|
||||
float heat(int32_t unit) const { return heat_[(size_t)pos_[(size_t)unit]]; }
|
||||
/* How many units of THIS unit's layer are resident. The tiebreak every residency decision
|
||||
* needs: a global ranking with no layer term leaves some layers holding far more than others,
|
||||
* and a layer starved of slots misses on nearly every token however good the ranking inside
|
||||
* it is. `pick` uses it on an exact heat tie and so must anything else that chooses. */
|
||||
/* Resident units in this unit's layer: the tie-break every residency decision needs (see
|
||||
* `res_count_`). `pick` uses it on an exact heat tie, and so must anything else that chooses. */
|
||||
int32_t layer_residents(int32_t unit) const {
|
||||
const int32_t l = (size_t)unit < layer_of_.size() ? layer_of_[(size_t)unit] : -1;
|
||||
return l >= 0 && (size_t)l < res_count_.size() ? res_count_[(size_t)l] : 0;
|
||||
}
|
||||
const HeatStats& stats() const { return stats_; }
|
||||
|
||||
/* The exit banner. The per-layer residency histogram at the end of it is the one number that
|
||||
* says whether the engine did the thing it exists for: a global profile ranking leaves layers
|
||||
* with wildly different resident counts, and a layer starved of slots misses on nearly every
|
||||
* token however good the ranking inside it is. */
|
||||
/* Exit banner, ending with the per-layer resident counts, which show whether every layer kept
|
||||
* its share of slots. */
|
||||
std::string report() const;
|
||||
|
||||
private:
|
||||
@@ -242,20 +177,17 @@ private:
|
||||
int32_t n_layer_ = 0;
|
||||
HeatStats stats_;
|
||||
|
||||
/* THE HEAT, BY POSITION RATHER THAN BY UNIT. Each layer owns one run of positions, and the
|
||||
* front of that run is indexed by EXPERT: expert e of layer l sits at slot_lo_[l] + e, whether
|
||||
* or not the plan has a unit for it and whether or not that unit may move. Then the layer's
|
||||
* other movable units, then padding to a whole number of lanes. After the layers come the
|
||||
* movable units with no layer, padded to a whole screening block, and after them everything
|
||||
* else.
|
||||
/* Heat by position, not by unit. Each layer owns a run of positions whose front is indexed by
|
||||
* expert: expert e of layer l is at slot_lo_[l] + e, whether or not the plan has a unit for it
|
||||
* or that unit may move. Then come the layer's other movable units, then padding to a multiple
|
||||
* of kLanes. After the layers: the movable units with no layer, padded to a screening block,
|
||||
* then everything else.
|
||||
*
|
||||
* That lines a histogram up with the positions it credits. observe() walks counts[e] and the
|
||||
* heat at slot_lo_[l] + e side by side, in fixed-width blocks the compiler turns into vector
|
||||
* code, with no unit number looked up and no branch taken per expert. A position with no unit
|
||||
* behind it is a hole: never a candidate, never priced, and its heat is read by nothing.
|
||||
* `pos_` and `unit_at_` translate (-1 for a hole); everything outside the position arrays
|
||||
* stays indexed by MoveUnit index so this file and the plan cannot disagree about what a
|
||||
* number means. */
|
||||
* This lines a histogram up with the positions it credits, so observe() walks counts[e] and
|
||||
* the heat side by side in fixed-width vector blocks, with no unit lookup or per-expert branch.
|
||||
* A position with no unit is a hole: never a candidate, never priced. `pos_` and `unit_at_`
|
||||
* translate (-1 for a hole); everything outside the position arrays is indexed by MoveUnit
|
||||
* index, as in the plan. */
|
||||
std::vector<float> heat_; /* by position */
|
||||
std::vector<int32_t> pos_; /* unit -> position */
|
||||
std::vector<int32_t> unit_at_; /* position -> unit, -1 for a hole */
|
||||
@@ -273,30 +205,26 @@ private:
|
||||
std::vector<int32_t> slot_lo_;
|
||||
std::vector<int32_t> n_ex_;
|
||||
void set_place(int32_t unit);
|
||||
/* Unit bytes, from the plan. Here so a miss can be priced where it is detected rather than
|
||||
* joined back to the plan by every reader. */
|
||||
/* Unit bytes from the plan, so a miss is priced where it is detected. */
|
||||
std::vector<int64_t> bytes_;
|
||||
std::vector<Tier> tier_;
|
||||
std::vector<uint8_t> busy_;
|
||||
std::vector<uint8_t> movable_;
|
||||
std::vector<int32_t> layer_of_;
|
||||
/* Bit 0: promoted before. Bit 1: demoted before. Two bits a unit, so the thrash question
|
||||
* costs nothing on the dispatch path. */
|
||||
/* Bit 0: promoted before. Bit 1: demoted before. Feeds the readmit counters. */
|
||||
std::vector<uint8_t> ever_;
|
||||
|
||||
/* How many of each layer's units are resident. THE TIE-BREAK IS NOT COSMETIC: most resident
|
||||
* units are cold, so `heat == 0.0f` exactly is the common case at both ends of the ranking,
|
||||
* and whatever breaks that tie IS the policy for most of a run. Breaking it by index order
|
||||
* strips the low-numbered layers first, which replaces the skew this engine exists to fix
|
||||
* with a different one. So ties go to the layer that can most afford it: take the victim from
|
||||
* the layer holding the MOST, promote into the one holding the FEWEST. */
|
||||
/* Resident units per layer. A layer starved of slots misses on nearly every token however
|
||||
* good the ranking inside it is. Most resident units are cold, so exact `heat == 0.0f` ties
|
||||
* are common at both ends and the tie-break is effectively the policy; breaking it by index
|
||||
* would strip low-numbered layers first. Ties take the victim from the layer holding the most
|
||||
* and promote into the layer holding the fewest. */
|
||||
std::vector<int32_t> res_count_;
|
||||
/* A SWAP STAYS INSIDE ONE SLAB CLASS. The promoted unit takes a slot of its own class and the
|
||||
* demoted one frees a slot of its own, so a pair across two classes would drain one class's
|
||||
* spare slots into the other's until promotions starve. A model has one expert class when
|
||||
* every expert is the same size on a rank, and two when a rank holds an uneven slice of each
|
||||
* expert's width (three 128-column blocks of one parity, two of the other). `cls_` is the
|
||||
* unit's class as a dense index, -1 for a unit that cannot move. */
|
||||
/* A swap stays inside one slab class: each half uses a slot of its own class, so a pair across
|
||||
* classes would drain one class's spare slots into the other's until promotions starve. A rank
|
||||
* has one expert class when every expert is the same size, two when it holds an uneven slice
|
||||
* of each expert's width (three 128-column blocks of one parity, two of the other). `cls_` is
|
||||
* the dense class 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_step` entries a class, kept between calls so a
|
||||
@@ -306,16 +234,13 @@ private:
|
||||
/* Per slot, its lowest movable unit index: the bound step()'s layer screen needs on a tie. */
|
||||
std::vector<int32_t> min_unit_;
|
||||
|
||||
/* EACH LAYER'S TWO ENDS, so a dispatch that proposes nothing -- the guard declining the best
|
||||
* pair, which is nearly every dispatch once the resident set has settled -- is decided from
|
||||
* one entry a layer rather than a scan of every unit. Over the movable units not in flight:
|
||||
* the hottest one off the device and the coldest one on it, and how many there are of each.
|
||||
/* Each slot's two ends, over movable units not in flight: the hottest off the device and the
|
||||
* coldest on it, and how many of each. A dispatch that proposes nothing (nearly all of them
|
||||
* once residency settles) is then decided from one entry a layer, not a scan of every unit.
|
||||
* Slot n_layer_ is the movable units with no layer.
|
||||
*
|
||||
* observe() recomputes a layer's ends on the pass that decays and credits it, where each is
|
||||
* one more compare on a value already in a register. A change of tier or of being in flight
|
||||
* invalidates the unit's layer, and an invalid entry is rebuilt from its positions when step()
|
||||
* next reads it. */
|
||||
* observe() updates a layer's ends on the pass that credits it. A tier or busy change
|
||||
* invalidates the unit's slot, which step() rebuilds from its positions on its next read. */
|
||||
std::vector<float> end_hot_, end_cold_;
|
||||
std::vector<int32_t> end_n_off_, end_n_on_;
|
||||
std::vector<int32_t> end_n_cold_; /* units on the device at exactly the cold end's heat */
|
||||
|
||||
+286
-426
File diff suppressed because it is too large.
Load diff
+235
-388
@@ -1,48 +1,33 @@
|
||||
/* mover.h -- residency and the mover: the substrate every tier stands on.
|
||||
/* mover.h -- residency and the mover: where every weight unit lives and how it moves.
|
||||
*
|
||||
* Three storage tiers, one address space of slots:
|
||||
*
|
||||
* FIXED-STRIDE VRAM SLAB SLOTS PER WEIGHT CLASS. A slot is interchangeable within its class, so
|
||||
* a promotion is an integer swap and not an allocation, and a slab that never fragments is a
|
||||
* slab whose hit rate does not depend on the order promotions happened to arrive in.
|
||||
* VRAM slab: fixed-stride slots per weight class. Slots within a class are interchangeable, so
|
||||
* a promotion is an integer swap rather than an allocation, and the slab never fragments.
|
||||
*
|
||||
* A PINNED HOST POOL, at the same stride. Pinned rather than pageable because the whole point of
|
||||
* the host tier is that a card can DMA out of it: a device-visible pinned pool is what makes a
|
||||
* non-resident expert a zero-copy read inside the GEMM instead of a bounce-buffer memcpy in
|
||||
* front of it. It is also allocated and owned here rather than read through the container's
|
||||
* mmap, because with an mmap the KERNEL decides what stays resident and under real memory
|
||||
* pressure it decides badly for this workload -- the same reads run several times slower inside
|
||||
* a decode run than in isolation, and MADV_WILLNEED makes it worse, which is the tell that the
|
||||
* faults are not too small and that a hint cannot fix a policy disagreement.
|
||||
* Pinned host pool, same stride. The card reads a non-resident expert from it zero-copy
|
||||
* inside the GEMM. It is owned here, not read through the container's mmap, because under
|
||||
* memory pressure the kernel's paging makes decode reads several times slower, and
|
||||
* MADV_WILLNEED makes it worse.
|
||||
*
|
||||
* A FILE TIER READ WITH O_DIRECT INTO PINNED BUFFERS. Predictable latency, no page-cache
|
||||
* double-copy, and the read lands where the mover can DMA from it without a bounce. A buffered
|
||||
* fallback is refused rather than offered: a tier whose latency is the page cache's mood is not
|
||||
* a tier you can budget against.
|
||||
* File tier: O_DIRECT reads into pinned buffers, with predictable latency and no page-cache
|
||||
* copy. No buffered fallback: a tier whose latency depends on the page cache cannot be budgeted.
|
||||
*
|
||||
* ---- THE ONE PROPERTY EVERYTHING ELSE RESTS ON -----------------------------------------------
|
||||
* ---- Transfers never synchronise the host ----------------------------------------------------
|
||||
*
|
||||
* THE MOVER RUNS ON A DEDICATED STREAM AND THE COMPUTE STREAM WAITS ON ITS EVENTS. NO HOST
|
||||
* SYNCHRONISATION IS INVOLVED IN A TRANSFER. That is what lets placement be dynamic without
|
||||
* serialising the step, and it is the difference between MoE offload being unusable and being
|
||||
* fast. rad_issue waits with rad_event_wait, never rad_event_sync.
|
||||
* The mover runs on its own stream and the compute stream waits on its events (rad_event_wait,
|
||||
* never rad_event_sync), so placement changes without serialising the step. The lead gate is a
|
||||
* host wait on how far the host runs ahead, not on a transfer (MoverConfig::max_lead_dispatches).
|
||||
*
|
||||
* The lead gate below IS a host wait, and it is not a contradiction: it throttles how far the
|
||||
* host runs ahead of the cards. It is a SUPPLY mechanism, not a transfer synchronisation, and the
|
||||
* reason it exists is spelled out at MoverConfig::max_lead_dispatches.
|
||||
* ---- Shadow slots and quarantine -------------------------------------------------------------
|
||||
*
|
||||
* ---- SHADOW SLOTS AND QUARANTINE -------------------------------------------------------------
|
||||
* A promotion copies into a shadow slot (allocated, holding nothing) and only then publishes the
|
||||
* new pointer, so a slot is never overwritten while a kernel may read it. Getting this order
|
||||
* wrong does not crash; it produces fluent output that differs from run to run.
|
||||
*
|
||||
* A promotion writes into a SHADOW slot -- a slab slot that is allocated but holds nothing -- and
|
||||
* only then publishes the new pointer. So a live slot is never DMA'd over while a kernel might
|
||||
* still be reading it, and a promotion never invalidates a pointer the run phase is already
|
||||
* holding. Getting that ordering wrong does not crash: it produces fluent output with a different
|
||||
* hash every run, which is the single most expensive bug class in this design.
|
||||
*
|
||||
* The freed slot then goes into QUARANTINE rather than straight back to the free list, because
|
||||
* kernels issued in earlier layers still name its old address. The barrier is an event recorded
|
||||
* on the COMPUTE stream after the publish; when it signals, every launch that could still name
|
||||
* the slot has retired.
|
||||
* A freed slot goes into quarantine, because kernels issued in earlier layers still name it. The
|
||||
* barrier is an event recorded on the compute stream after the publish; when it signals, every
|
||||
* launch that could name the slot has retired.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../device/device.h"
|
||||
@@ -61,49 +46,27 @@
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ slot bookkeeping */
|
||||
/* Pure host state, no device call in it, so the whole supply half is testable without a card.
|
||||
* Used for both the VRAM slab and the pinned host pool -- they are the same structure with
|
||||
* different backing memory, and writing it twice is how two free lists come to disagree about
|
||||
* what a slot index means.
|
||||
/* Free-list bookkeeping for the VRAM slab and the pinned host pool. Pure host state, testable
|
||||
* without a card.
|
||||
*
|
||||
* ---- SEGMENTS: ONE RANGE FOR THE SLAB'S OWN SLOTS, ONE FOR EACH LENDER ------------------------
|
||||
* Slots are numbered in segments laid end to end. Segment 0 is the budgeted range; each later
|
||||
* one is memory another pool lends (KV cache blocks, the arena's top). Each segment has its own
|
||||
* target, below which slots may be handed out, because lenders reclaim independently.
|
||||
*
|
||||
* The slots are numbered in SEGMENTS laid end to end. Segment 0 is the budgeted range the pool
|
||||
* was built with; every later one is a stretch of another pool's memory lent to this one -- the
|
||||
* KV cache's blocks, the activation arena's top -- added once its addresses are known. Each
|
||||
* segment has its own TARGET: the slots below it are the ones that may be handed out, and a
|
||||
* lender moves only its own. Two lenders cannot share one target, because what one of them can
|
||||
* spare says nothing about the other: the arena takes its memory back for every prefill while the
|
||||
* cache is still lending, and a single mark over both would either hold the arena's slots past its
|
||||
* recall or give up the cache's with it.
|
||||
* The lowest free slot goes first, so occupied slots pack toward a segment's bottom and its top
|
||||
* can be returned; a LIFO would keep handing out high slots. `live` is how far a segment's slots
|
||||
* exist and `target` how far they should: a shrink lowers `live` only past unheld slots, so it
|
||||
* never evicts.
|
||||
*
|
||||
* ---- WHY THE LOWEST FREE SLOT, AND WHY A LIVE MARK -------------------------------------------
|
||||
*
|
||||
* A lent segment is VRAM its owner can want back, and it has to be handed back when it does. That
|
||||
* is only possible if the occupied slots pack toward the BOTTOM of the segment, so its top is free
|
||||
* to retire. Handing out the lowest free slot is what packs them; a LIFO stack hands back the slot
|
||||
* released most recently, which after a busy period is exactly the high slot the pool wants to
|
||||
* give up, and the mark would never fall.
|
||||
*
|
||||
* A segment's `live` is how far its slots exist right now and `target` how far they should. They
|
||||
* differ while a shrink waits on the units still sitting above the target: the mark stops at the
|
||||
* highest slot something holds, so shrinking can never evict -- it only declines to hand a slot
|
||||
* out again.
|
||||
*
|
||||
* THE FREE LIST IS REBUILT WHENEVER A TARGET MOVES, from the held flags, and holds exactly the
|
||||
* covered slots nothing holds. Carried across a shrink and a regrow instead, it lists only some of
|
||||
* the slots the shrink dropped -- a slot freed while it sat above the target is never pushed, and
|
||||
* one the heap still held is discarded by the first take() that walks past it -- and a regrow
|
||||
* that trusts it never hands the others out again. The rebuild is a scan of the capacity at the
|
||||
* arbiter's cadence; take() and add_free, which the mover calls several times a dispatch, stay
|
||||
* heap operations.
|
||||
* The free list is rebuilt from the held flags whenever a target moves; one carried across a
|
||||
* shrink and regrow would lose slots freed above the target. take() and add_free() stay heap
|
||||
* operations.
|
||||
*/
|
||||
class SlotPool {
|
||||
public:
|
||||
/* `n_live` slots exist in segment 0 and every one of them is HELD until add_free says
|
||||
* otherwise, which is what the plan's resident set is. `n_cap` is how far segment 0 may ever
|
||||
* grow -- address space the caller has reserved and will back on demand -- and defaults to no
|
||||
* growth at all. */
|
||||
/* Segment 0 starts with `n_live` slots, all held (the plan's resident set) until add_free()
|
||||
* releases them. `n_cap` is how far segment 0 may grow into address space the caller has
|
||||
* reserved and backs on demand; the default is no growth. */
|
||||
void init(int64_t n_live, int64_t stride, int64_t n_cap = -1) {
|
||||
stride_ = stride;
|
||||
n_ = n_cap > n_live ? n_cap : n_live;
|
||||
@@ -122,9 +85,7 @@ public:
|
||||
n_ += n_slots;
|
||||
return (int)segs_.size() - 1;
|
||||
}
|
||||
int n_segments() const { return (int)segs_.size(); }
|
||||
int64_t seg_lo(int k) const { return segs_[(size_t)k].lo; }
|
||||
int64_t seg_hi(int k) const { return segs_[(size_t)k].hi; }
|
||||
|
||||
void add_free(int64_t slot) {
|
||||
if (slot < 0 || slot >= n_) return;
|
||||
@@ -145,53 +106,37 @@ public:
|
||||
int64_t capacity() const { return n_; }
|
||||
int64_t stride() const { return stride_; }
|
||||
int64_t n_free() const { return n_usable_; }
|
||||
/* Slots something is in: a resident unit, a staged one, or a copy still in flight. The
|
||||
* number the fill and drain decisions are made against, because the working slots have to
|
||||
* stay free whatever the target is. */
|
||||
/* Slots in use: a resident unit, a staged one, or a copy in flight. Fill and drain decide
|
||||
* against this, because the working slots must stay free whatever the target is. */
|
||||
int64_t held() const { return n_held_; }
|
||||
/* Where segment `k`'s covered slots end, as a slot number. */
|
||||
int64_t target(int k = 0) const { return segs_[(size_t)k].target; }
|
||||
/* May this slot be handed out -- is it below its segment's target? */
|
||||
/* Whether `slot` is below its segment's target, i.e. may be handed out. */
|
||||
bool covered(int64_t slot) const {
|
||||
if (slot < 0 || slot >= n_) return false;
|
||||
return slot < segs_[(size_t)seg_of(slot)].target;
|
||||
}
|
||||
/* -1 when there is none. A caller that treats that as "try again next dispatch" is right;
|
||||
* one that treats it as an error is wrong -- slot starvation is the normal steady state. */
|
||||
int64_t take() {
|
||||
while (!free_.empty()) {
|
||||
std::pop_heap(free_.begin(), free_.end(), std::greater<int64_t>());
|
||||
const int64_t s = free_.back();
|
||||
free_.pop_back();
|
||||
if (!covered(s) || held_[(size_t)s]) continue; /* never a slot to hand out */
|
||||
held_[(size_t)s] = 1;
|
||||
++n_held_;
|
||||
--n_usable_;
|
||||
return s;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
/* The lowest free covered slot, or -1. Starvation is the normal steady state: callers retry
|
||||
* on a later dispatch rather than treat -1 as an error. */
|
||||
int64_t take() { return take_at_least(0); }
|
||||
|
||||
/* Where segment `k`'s covered slots should end, as a slot number inside it. Growing is
|
||||
* immediate -- the caller has already backed the memory. Shrinking is a statement of intent:
|
||||
* the mark falls as far as the slots nothing holds allow, and the rest follows as those
|
||||
* retire. */
|
||||
/* Sets where segment `k`'s covered slots end, as a slot number inside it. Growing is
|
||||
* immediate (the caller has already backed the memory). Shrinking lowers `live` only past
|
||||
* slots nothing holds; the rest follows as those are released. */
|
||||
void set_target(int64_t target) { set_target(0, target); }
|
||||
void set_target(int k, int64_t target) {
|
||||
Seg& g = segs_[(size_t)k];
|
||||
g.target = target < g.lo ? g.lo : (target > g.hi ? g.hi : target);
|
||||
/* Nothing ever holds a slot at or past the mark -- take() hands out only covered slots,
|
||||
* and the mark never falls past a held one -- so a set flag there only says the slot has
|
||||
* never existed. */
|
||||
/* Nothing holds a slot at or past `live` (take() hands out only covered slots and `live`
|
||||
* never falls past a held one), so a set flag there only means the slot never existed. */
|
||||
for (int64_t s = g.live; s < g.target; ++s) held_[(size_t)s] = 0;
|
||||
if (g.target > g.live) g.live = g.target;
|
||||
else settle(g);
|
||||
rebuild();
|
||||
}
|
||||
|
||||
/* take(), restricted to slots at or above `lo`. The slots below it that are free stay free
|
||||
* and stay listed; there are at most the working slots of them, so this is a handful of heap
|
||||
* operations. */
|
||||
/* take(), restricted to slots >= `lo`. Free slots below `lo` stay listed; there are at most
|
||||
* the working slots of them, so this is a few heap operations. */
|
||||
int64_t take_at_least(int64_t lo) {
|
||||
std::vector<int64_t> keep;
|
||||
int64_t got = -1;
|
||||
@@ -213,8 +158,8 @@ public:
|
||||
}
|
||||
return got;
|
||||
}
|
||||
/* take(), restricted to the free slots `want` accepts: the lowest of them, or -1. A scan of
|
||||
* the free list, which holds the slots on their way back through a swap -- a few dozen. */
|
||||
/* take(), restricted to the lowest free slot `want` accepts, or -1. A linear scan; the free
|
||||
* list holds only slots passing through a swap, a few dozen. */
|
||||
template <class Want> int64_t take_where(Want want) {
|
||||
size_t best = free_.size();
|
||||
for (size_t i = 0; i < free_.size(); ++i) {
|
||||
@@ -232,8 +177,8 @@ public:
|
||||
--n_usable_;
|
||||
return s;
|
||||
}
|
||||
/* The highest slot of segment `k` something holds -- a unit, a copy in flight, a slot in
|
||||
* quarantine -- or -1. A scan down from the segment's mark. */
|
||||
/* The highest held slot of segment `k` (a unit, a copy in flight, a quarantined slot), or
|
||||
* -1. Scans down from `live`. */
|
||||
int64_t top_held(int k = 0) const {
|
||||
const Seg& g = segs_[(size_t)k];
|
||||
for (int64_t s = g.live; s-- > g.lo;)
|
||||
@@ -277,43 +222,34 @@ private:
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the file tier */
|
||||
/* A thin skin over the device layer's DirectFile, which is where the O_DIRECT mechanics live and
|
||||
* where they belong: the prefix cache reads the same way for the same reasons, and two
|
||||
* implementations of "align the offset, the length and the buffer" is two places for the
|
||||
* alignment rule to drift. What this adds is the tier's own accounting -- a file-tier read is a
|
||||
* blocking pread in the middle of a dispatch and the counter is how a run that leans on it stops
|
||||
* being a mystery in the throughput. */
|
||||
/* A thin wrapper over the device layer's DirectFile, which owns the O_DIRECT alignment rules
|
||||
* (the prefix cache reads the same way). This adds the tier's accounting: a file-tier read is a
|
||||
* blocking pread inside a dispatch, and the counters make its cost visible. */
|
||||
class FileTier {
|
||||
public:
|
||||
/* O_DIRECT, and a refusal rather than a buffered fallback: a tier whose latency is the page
|
||||
* cache's mood is not a tier you can budget against. `path` is the container. */
|
||||
/* Opens the container `path` with O_DIRECT; refuses rather than fall back to buffered reads,
|
||||
* whose latency cannot be budgeted. */
|
||||
int open(const std::string& path);
|
||||
bool ok() const { return f_.is_open(); }
|
||||
void close() { f_.close(); }
|
||||
|
||||
/* One expert-sized read into a pinned buffer. Blocking, counted, and a cliff: a dispatch that
|
||||
* meets a file-tier unit stops until the read returns. That is the price of a bet the plan
|
||||
* made -- give the cold tail to disk and buy a host pool big enough to hold a working set
|
||||
* that can actually move -- paid in full each time the bet is wrong. What changes in response
|
||||
* is the plan, not this function. */
|
||||
/* One expert-sized read into a pinned buffer. Blocking and counted: a dispatch that meets a
|
||||
* file-tier unit stalls until the read returns. This is the cost the plan accepted by putting
|
||||
* the cold tail on disk; frequent reads call for a different plan, not a change here. */
|
||||
int read(uint64_t offset, int64_t bytes, void* pinned_dst, int64_t dst_cap);
|
||||
|
||||
/* Every RadFileEntry offset is RAD_ALIGN_UNIT-aligned by construction (rad_format.h) and that
|
||||
* is DirectFile's alignment, so the mover's reads take the path with no bounce in it. */
|
||||
/* RadFileEntry offsets are RAD_ALIGN_UNIT-aligned (rad_format.h), which is DirectFile's
|
||||
* alignment, so the mover's reads need no bounce buffer. */
|
||||
static int64_t direct_align(int64_t v) { return align_up(v, DirectFile::alignment()); }
|
||||
|
||||
uint64_t reads() const { return reads_; }
|
||||
uint64_t bytes_read() const { return bytes_; }
|
||||
|
||||
private:
|
||||
DirectFile f_;
|
||||
uint64_t reads_ = 0, bytes_ = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ residency */
|
||||
class Residency final : public ResidencyTable {
|
||||
public:
|
||||
void init(const Program& prog, const Plan& plan);
|
||||
void init(const Program& prog);
|
||||
|
||||
const WeightSlot* lookup(rad_weight w) const override {
|
||||
return (size_t)w < slot_.size() ? &slot_[w] : nullptr;
|
||||
@@ -325,14 +261,11 @@ public:
|
||||
changed_.clear();
|
||||
}
|
||||
|
||||
/* The only two writers, and BOTH BUMP THE GENERATION. `publish` settles a slot -- the bytes
|
||||
* are there, nothing to wait on. `begin_transfer` opens one: a copy into `ptr` is in flight
|
||||
* and `ready` is the event the compute stream must be ordered behind.
|
||||
*
|
||||
* begin_transfer bumping is the part that is easy to get wrong and expensive to debug. The
|
||||
* run phase memoises the wait per generation, so installing a new event at the old generation
|
||||
* makes it skip the wait entirely (residency_iface.h). */
|
||||
void publish(rad_weight w, void* ptr);
|
||||
/* The only two writers; both bump the generation. publish() settles a slot; begin_transfer()
|
||||
* marks a copy into `ptr` in flight that the compute stream must wait on (`ready`). The run
|
||||
* phase memoises its wait per generation, so a new event at an old generation would be
|
||||
* skipped (residency_iface.h). */
|
||||
void publish(rad_weight w, void* ptr) { begin_transfer(w, ptr, nullptr); }
|
||||
void begin_transfer(rad_weight w, void* ptr, RadEvent ready);
|
||||
void settle(rad_weight w) {
|
||||
if ((size_t)w >= slot_.size()) return;
|
||||
@@ -355,51 +288,34 @@ private:
|
||||
|
||||
/* ------------------------------------------------------------------ configuration */
|
||||
struct MoverConfig {
|
||||
/* Shadow slots and the staging ring are NOT here. They are budgeted by the planner out of
|
||||
* the weights pool and reported in the plan (SlabClass::n_shadow, n_stage), and a second
|
||||
* knob for the same quantity is a second number for the mover and the operator to disagree
|
||||
* about -- with an overrun as the direction that disagreement goes wrong in.
|
||||
/* Shadow and staging slot counts come from the plan (SlabClass::n_shadow, n_stage), which
|
||||
* budgets them; a second knob here could only cause an overrun.
|
||||
*
|
||||
* ---- HOW FAR THE HOST MAY RUN AHEAD OF THE CARDS, IN LAYER DISPATCHES --------------------
|
||||
*
|
||||
* 0 is unbounded, and unbounded STARVES THE MOVER. A freed slot returns to the free list only
|
||||
* after its quarantine event signals, and that event is on the COMPUTE stream -- so the
|
||||
* recycle latency is however deep that stream happens to be queued, and the move rate is
|
||||
* `shadow slots / recycle latency`. Let the host run and the stream carries a whole step's
|
||||
* work, and almost every round finds no free slot to move into. The guard is not what binds;
|
||||
* the engine simply never gets the supply to spend.
|
||||
*
|
||||
* Holding the host near the cards is therefore not a latency measure but a SUPPLY one. 2 is
|
||||
* the smallest depth that recovers the effect while leaving the issue path a dispatch of
|
||||
* margin. A coarser gate -- per step rather than per layer dispatch -- does nothing, because
|
||||
* one step is already the whole model's worth of queued work; the granularity has to be the
|
||||
* layer. */
|
||||
* How far the host may run ahead of the cards, in layer dispatches. A freed slot recycles
|
||||
* only when its quarantine event on the compute stream signals, so the move rate is shadow
|
||||
* slots / compute queue depth; 0 (unbounded) queues a whole step and starves the mover. 2 is
|
||||
* the smallest depth that keeps slots recycling with a dispatch of issue margin. A per-step
|
||||
* gate does nothing, since one step is already the whole model's queued work. */
|
||||
int max_lead_dispatches = 2;
|
||||
|
||||
/* Lent slots kept free for swaps to land in, a slab class (planner.h's
|
||||
* RAD_PLACE_TURNOVER_SLOTS; Mover::balance keeps them). A knob here and not in the plan because the planner charges
|
||||
* nothing for them: they are the KV cache's memory, free only while it lends. A class whose
|
||||
* shadow slots the quarter-of-the-slab cap cut keeps at most the same multiple of them, so a
|
||||
* small loan is not left emptier than it is filled. */
|
||||
/* Lent slots per slab class kept free for swaps to land in (Mover::balance). A knob rather
|
||||
* than a plan field because the planner charges nothing for them: they are KV cache memory,
|
||||
* free only while it lends. A class whose shadow slots the quarter-of-the-slab cap reduced
|
||||
* gets proportionally fewer, so a small loan is not left emptier than it is filled. */
|
||||
int turnover_slots = RAD_PLACE_TURNOVER_SLOTS;
|
||||
|
||||
/* The container, for the file tier. Empty means there is no file tier and a unit the planner
|
||||
* put there is an error rather than a slow path. */
|
||||
/* The container, for the file tier. Empty means no file tier; a unit planned there is then
|
||||
* an error. */
|
||||
std::string container_path;
|
||||
/* Pinned staging buffers for file-tier reads. Each is one class stride, and the count is the
|
||||
* planner's -- RAD_PLACE_FILE_STAGE_SLOTS, which is what the operator was charged for out of
|
||||
* --host-pool-mib. A separate default here would be a second number for one allocation. */
|
||||
/* Pinned staging buffers for file-tier reads, one class stride each; the count the planner
|
||||
* charged to --host-pool-mib. */
|
||||
int stage_slots = RAD_PLACE_FILE_STAGE_SLOTS;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the loan */
|
||||
/* ONE STRETCH OF ANOTHER POOL'S VRAM THAT MAY BE LENT TO THE SLAB, described from its top down.
|
||||
*
|
||||
* The owner keeps it backed and lends it from the top downwards, and it states how much it has
|
||||
* lent in its own measure -- tokens, for the KV cache -- so the mover can tell which slots a loan
|
||||
* covers without knowing what the owner stores there. `unit_bytes` of the stretch are one unit of
|
||||
* that measure and a unit is `unit_tokens` tokens: a loan of T tokens is the top
|
||||
* floor(T / unit_tokens) * unit_bytes bytes of every stretch. */
|
||||
/* One stretch of another pool's VRAM that may be lent to the slab. The owner keeps it backed,
|
||||
* lends from the top down and states the loan in its own measure (tokens, for the KV cache). A
|
||||
* loan of T tokens is the top floor(T / unit_tokens) * unit_bytes bytes of every stretch. */
|
||||
struct LoanStrip {
|
||||
char* top = nullptr; /* one past the stretch's highest byte */
|
||||
int64_t bytes = 0; /* how far below `top` it runs */
|
||||
@@ -412,29 +328,23 @@ struct MoverStats {
|
||||
uint64_t promotions = 0, demotions = 0;
|
||||
uint64_t h2d_bytes = 0, d2h_bytes = 0;
|
||||
uint64_t prefetched = 0, prefetch_bytes = 0;
|
||||
/* Why a move did not go out. `no_record` is every in-flight move record busy -- the shadow
|
||||
* slots, still waiting on their copies. The two `starved` counts are the free lists empty.
|
||||
* Without these a starved mover is indistinguishable from a satisfied one. */
|
||||
/* Why a move did not go out: every move record busy, or a free list empty. These separate a
|
||||
* starved mover from a satisfied one. */
|
||||
uint64_t no_record = 0, starved_slab = 0, starved_pool = 0;
|
||||
uint64_t quarantined = 0;
|
||||
/* Demotions that copied nothing: the unit sat in a lent slot and kept its host copy, so going
|
||||
* back to the host tier was a change of address. Counted inside `demotions` as well. */
|
||||
/* Demotions out of a lent slot that copied nothing (the unit kept its host copy). Also
|
||||
* counted in `demotions`. */
|
||||
uint64_t dropped = 0;
|
||||
/* Host copies a unit in a lent slot gave to a budgeted victim that had no pool slot to go to
|
||||
* (Mover::donor_slot), and such units moved rather than dropped when their loan was recalled
|
||||
* or shrank. `stranded` counts the recalls that found no free slot for one of them: it stayed
|
||||
* past the loan until a later recall or balance() moved it. */
|
||||
/* Host copies given to budgeted victims (Mover::donor_slot); donors moved rather than
|
||||
* dropped by a recall or shrink; recalls that found no free slot for a donor. */
|
||||
uint64_t donated = 0, relocated = 0, stranded = 0;
|
||||
uint64_t ssd_reads = 0, ssd_bytes = 0;
|
||||
/* The prefill stager's copies (stage_units): layers staged, units and bytes copied, and
|
||||
* pooled units a buffer had no room left for -- those were read across the link in place.
|
||||
* `stage_copies` is how many copies carried the units: neighbouring pool slots go as one. */
|
||||
/* The prefill stager (stage_units). `stage_overflow`: units no buffer had room for, read in
|
||||
* place. `stage_copies`: copies issued; neighbouring pool slots go as one. */
|
||||
uint64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 0;
|
||||
uint64_t stage_copies = 0;
|
||||
/* The file stager's reads (stage_file_units): routed layers read from the container, the
|
||||
* units and bytes they carried, the preads that carried them, and the host time spent inside
|
||||
* those reads and waiting for a window's copies to drain -- the two halves of what a step
|
||||
* that reads the drive costs the thread issuing it. */
|
||||
/* The file stager (stage_file_units), including the host time spent in preads and waiting
|
||||
* for a window's copies to drain. */
|
||||
uint64_t file_layers = 0, file_units = 0, file_bytes = 0, file_preads = 0;
|
||||
uint64_t file_read_ns = 0, file_wait_ns = 0;
|
||||
};
|
||||
@@ -447,137 +357,97 @@ public:
|
||||
Mover(const Mover&) = delete;
|
||||
Mover& operator=(const Mover&) = delete;
|
||||
|
||||
/* Allocates every pool the plan asked for and lays every unit into a slot. Does NOT read a
|
||||
* byte of the model: the load phase fills the addresses this hands it. Returns RAD_E_NOMEM
|
||||
* naming the pool that failed, because "out of memory" without which pool is not a
|
||||
* diagnosis.
|
||||
/* Allocates every pool the plan asks for and assigns every unit a slot; the load phase fills
|
||||
* the published addresses. On RAD_E_NOMEM the log names the pool.
|
||||
*
|
||||
* `budget` IS THE PRODUCTION PATH AND SHOULD ALWAYS BE PASSED. Pools already allocated
|
||||
* the weights pool as one block; a mover that called rad_dev_alloc beside it would spend
|
||||
* that budget TWICE and the overrun would surface as an out-of-memory from an unrelated
|
||||
* launch much later. Reserving from Pools::weights() is also what makes it structurally
|
||||
* impossible for a promotion to reach a KV block -- there is no path from the weights pool to
|
||||
* the KV pool (mem/pools.h), which is the whole reason the weight slab is a fixed budget.
|
||||
*
|
||||
* Null is the standalone-test path and says so at Warn. It is not a supported deployment. */
|
||||
* Always pass `budget`: Pools already reserved the weights pool, so allocating beside it
|
||||
* spends the budget twice, and reserving from Pools::weights() keeps promotions out of KV
|
||||
* blocks (mem/pools.h). Null is the standalone-test path and logs a warning. */
|
||||
int init(const Program& prog, const Plan& plan, const MoverConfig& cfg, Pools* budget = nullptr);
|
||||
|
||||
/* The compute stream this rank issues on. The mover's transfers are ordered against it and
|
||||
* the quarantine barrier is recorded on it, so without one the mover refuses to move rather
|
||||
* than storing a table edit blind. */
|
||||
/* The compute stream this rank issues on. Transfers are ordered against it and the
|
||||
* quarantine barrier is recorded on it; without one the mover refuses to move. */
|
||||
int bind_compute_stream(RadStream s);
|
||||
|
||||
/* THE MAINTENANCE STREAM, AND WHY ANYTHING ELSE MAY HAVE IT.
|
||||
/* The mover's stream, to be shared by any subsystem moving bytes off the critical path. Each
|
||||
* HIP stream costs a hardware queue, and on RDNA4 a fourth one is expensive: on two R9700s
|
||||
* serving Flash-Next, an idle fourth stream takes the decode step from 20.5 to 33.9 ms
|
||||
* (GPU_MAX_HW_QUEUES 1-3 are fine, 4 and 8 are not). The engine already uses three (compute,
|
||||
* the second compute lane, this one).
|
||||
*
|
||||
* A HIP stream costs a hardware queue, and on RDNA4 a fourth concurrent queue is not a small
|
||||
* cost: on a two-card R9700 Flash-Next server, a fourth stream that never carries a single
|
||||
* byte takes the decode step from 20.5 ms to 33.9 (GPU_MAX_HW_QUEUES 1, 2 or 3 all run at
|
||||
* full speed; 4 and 8 do not). The engine already issues on three -- compute, the second
|
||||
* compute lane, and this one -- so a subsystem that wants a stream to move bytes off the
|
||||
* critical path must TAKE THIS ONE rather than make a fourth.
|
||||
*
|
||||
* Null before init(), and null on a rank with nothing to move. A caller that gets null must
|
||||
* fall back to its own stream: three streams is under the cliff either way.
|
||||
*
|
||||
* THE MOVER'S RUN PHASE ISSUES ON IT, so this stream is not idle: a sharer queueing a hundred
|
||||
* megabytes on it will sit in front of a transfer the compute stream is waiting on. Gate the
|
||||
* two -- do not answer it by making a fourth queue. */
|
||||
* Null before init() and on a rank with nothing to move; the caller then uses its own stream.
|
||||
* The run phase issues here too, so a sharer's large copy delays transfers the compute stream
|
||||
* waits on; gate the two rather than add a queue. */
|
||||
RadStream transfer_stream() const { return mover_; }
|
||||
|
||||
ResidencyTable* residency() { return &res_; }
|
||||
/* THE ONE ADDRESS THE MOVER DOES NOT OWN. A Tier::Mapped weight lives in the container's
|
||||
* mapping and the LOAD PHASE is what holds the RadFile, so it publishes the pointer and the
|
||||
* mover only records it -- the residency table is the mover's, and a second table would be a
|
||||
* second answer to "where is this weight". Nothing here ever moves it afterwards: a mapped
|
||||
* unit has no slab class, so unit_base() has no address of its own to republish over this. */
|
||||
/* For Tier::Mapped weights, which live in the container mapping the load phase holds: the
|
||||
* one address the mover does not own, recorded so the residency table stays the only record
|
||||
* of weight addresses. A mapped unit has no slab class, so nothing republishes over it. */
|
||||
void publish_mapped(rad_weight w, void* p) { res_.publish(w, p); }
|
||||
|
||||
/* ---- the run phase, in the order a layer dispatch calls it -----------------------------
|
||||
*
|
||||
* begin_dispatch retire whatever landed, gate the host's lead, record the ordering event
|
||||
* prefetch_to_op release what this op has finished with, then start everything the exact
|
||||
* schedule says is due -- and keep starting, as long as slots are free
|
||||
* begin_dispatch retire what landed, gate the host's lead, record the ordering event
|
||||
* prefetch_to_op release what this op has finished with, then start every transfer the
|
||||
* exact schedule says is due, while slots are free
|
||||
* issue one heat proposal
|
||||
*
|
||||
* There is no end_dispatch, and the absence is deliberate. The quarantine barrier belongs
|
||||
* DOWNSTREAM of the publish in stream order, and begin_dispatch's retire() is exactly that
|
||||
* point: by the time it runs, every launch the previous dispatch made has been issued. A
|
||||
* symmetric end-of-dispatch hook would record the barrier before those launches and the
|
||||
* quarantine would be satisfied for a reason that has nothing to do with the kernels it is
|
||||
* guarding.
|
||||
* There is deliberately no end_dispatch: the quarantine barrier must be recorded downstream
|
||||
* of the previous dispatch's launches, which begin_dispatch's retire() is.
|
||||
*
|
||||
* ---- A CALLER MUST DO ALL OF IT, EVERY DISPATCH -------------------------------------------
|
||||
* A caller must issue as well as retire every dispatch. The pool free list starts empty, so a
|
||||
* loop that only retires promotes into the shadow slots once and never demotes; on the host
|
||||
* backend copies land within their dispatch, so this shows only on a real card. The compute
|
||||
* stream must also carry the dispatch's real work, or the quarantine barrier and the lead
|
||||
* gate are meaningless.
|
||||
*
|
||||
* begin_dispatch only RETIRES; it never starts anything. A loop that retires without issuing
|
||||
* is not a slower engine, it is a stuck one: the pool free list starts empty, so the first
|
||||
* round can only promote out of the shadow slots, and the pool slot that promotion frees
|
||||
* arrives several dispatches later -- by which time, if nothing is asking, the resident set
|
||||
* has grown by the shadow count and never shrinks again. The symptom is zero demotions
|
||||
* forever, and it appears only on a real card: on the host backend every copy lands inside
|
||||
* the dispatch that issued it, so the same mistake passes unnoticed.
|
||||
*
|
||||
* The compute stream must also carry the dispatch's actual work. The quarantine barrier is an
|
||||
* event on that stream and its claim is "every kernel that could still name this slot has
|
||||
* retired"; against an empty stream the claim is vacuous and the lead gate paces nothing.
|
||||
* In production, begin_dispatch and issue run once a step from Engine::tiering_dispatch,
|
||||
* since the mover relocates only between steps (Ctx::run_step syncs the residency table at
|
||||
* its top). prefetch_to_op is called only by tests/place_test.cpp; the
|
||||
* exact-schedule path is kept built and tested deliberately.
|
||||
*/
|
||||
/* `begin_dispatch` and `issue` are the engine's, once a step: Engine::tiering_dispatch is the
|
||||
* seam, and it is a step and not a layer because the mover relocates BETWEEN steps and never
|
||||
* during one (runtime/ctx.cpp honours `weights_dirty_` once, at the top of run_step).
|
||||
*
|
||||
* `prefetch_to_op` has no caller but tests/place_test.cpp, and that is DELIBERATE -- the
|
||||
* exact-schedule path is kept built and tested rather than deleted and rewritten later. Do
|
||||
* not read "no caller" there as the dead-surface shape it resembles elsewhere in this tree. */
|
||||
int begin_dispatch(int dispatch, HeatEngine* heat);
|
||||
int prefetch_to_op(int32_t op_index);
|
||||
int issue(const Swap& s, HeatEngine* heat);
|
||||
|
||||
/* ---- the loan: VRAM another pool is not using ------------------------------------------
|
||||
*
|
||||
* VRAM some other pool carved and is not using is worth more here than it is there: an
|
||||
* expert unit that does not fit the slab is read across the link on the critical path of
|
||||
* every step that routes to it. The KV cache keeps its whole carve backed and LENDS the slab
|
||||
* the part nothing holds, and the activation arena lends the part a step smaller than the
|
||||
* largest one does not reach -- each at addresses it already owns, so the slab grows into
|
||||
* that memory with no allocation, no mapping and no driver call, and gives it back the same
|
||||
* way. The ONLY caller that may lend is the one that arbitrates the whole card: two callers
|
||||
* with two opinions about how much is spare is the same memory in two pools.
|
||||
* An expert that does not fit the slab is read across the link on every step that routes to
|
||||
* it, so unused VRAM elsewhere is lent to the slab: the part of the KV cache's carve nothing
|
||||
* holds, and the part of the activation arena that steps smaller than the largest do not
|
||||
* reach. Both are addresses the lender already owns, so no allocation or mapping is involved.
|
||||
* Only the caller that arbitrates the whole card may lend.
|
||||
*
|
||||
* EACH LENDER LENDS IN ITS OWN MEASURE, into its own segment of the slab (SlotPool): the KV
|
||||
* cache in tokens, the arena in bytes. They move independently -- a prefill takes the arena's
|
||||
* memory back while the cache goes on lending -- so every call names the lender it is about.
|
||||
* Each lender lends in its own measure (KV cache: tokens; arena: bytes) into its own slab
|
||||
* segment, and they move independently, so every call names its lender.
|
||||
*
|
||||
* A UNIT IN A LENT SLOT KEEPS ITS HOST COPY. Weights never change, so the pinned pool slot it
|
||||
* was promoted from still holds exactly its bytes, and giving the slot back is a change of
|
||||
* address rather than a copy across the link. That is what makes a loan cheap to recall:
|
||||
* the cache waits for kernels to stop naming the slot, never for bytes to move. */
|
||||
* A unit in a lent slot keeps its host copy (weights never change), so giving the slot back
|
||||
* is a change of address: a recall waits only for kernels to stop naming the slot. */
|
||||
|
||||
enum Lender { kLendKV = 0, kLendArena = 1, kLenders = 2 };
|
||||
|
||||
/* The stretches a lender may ever lend, once per lender, after its memory is carved. Carves
|
||||
* every stretch into slots of each class's stride from the top down, so the slots a small loan
|
||||
* covers are the ones a large loan covers first, and the slot a loan gives back first is the
|
||||
* deepest. */
|
||||
/* Registers the stretches a lender may ever lend; once per lender, after its memory is
|
||||
* carved. Each stretch is cut into slots of each class's stride from the top down, so a small
|
||||
* loan covers a prefix of a large loan's slots and the deepest slot is given back first. */
|
||||
int lend_from(int lender, const std::vector<LoanStrip>& strips);
|
||||
|
||||
/* HOW MUCH A LENDER LENDS, in its own measure. A TARGET, not a transaction: slots the loan
|
||||
* newly covers can be filled at once, while slots it no longer covers are emptied as their
|
||||
* units are dropped and their quarantine clears -- `loan_held` is how far down the lender's
|
||||
* memory the slab still reaches, and the lender may not use those bytes again until it has
|
||||
* fallen. */
|
||||
/* How much a lender lends, in its own measure. A target, not a transaction: newly covered
|
||||
* slots can be filled at once, while uncovered ones empty as their units drop and their
|
||||
* quarantine clears. loan_held() is how far into the lender's memory the slab still reaches;
|
||||
* the lender may not reuse those bytes until it has fallen to the loan. */
|
||||
int set_loan(int lender, int64_t amount);
|
||||
int64_t loan_held(int lender) const;
|
||||
int64_t loan(int lender) const { return loan_[lender]; }
|
||||
|
||||
/* THE SAME, NOW, for a lender that cannot wait: every unit past `amount` is dropped to its
|
||||
* host copy and both streams that can touch a slot are drained before this returns, so the
|
||||
* memory is the lender's the moment it does. A host wait, taken only when the lender needs
|
||||
* more than it kept in hand -- a request larger than the cache's buffer, a step larger than
|
||||
* the arena's lent level allows. */
|
||||
/* set_loan(), completed before returning: units past `amount` are dropped to their host
|
||||
* copies and both streams drained. A host wait, for when the lender needs more than it kept
|
||||
* in hand (a request larger than the cache's buffer, a step larger than the arena allows). */
|
||||
int reclaim(int lender, int64_t amount, HeatEngine* heat);
|
||||
|
||||
/* What the lent slots hold and what the loan offers, in bytes, and every slot the stretches
|
||||
* could ever hold. Read by the HTTP thread for the dashboard, hence stored rather than
|
||||
* computed from the slot pools, which only this thread may walk. */
|
||||
/* Bytes the lent slots hold, bytes the loans offer, and bytes every carved slot could hold.
|
||||
* The first two are stored because the HTTP thread reads them for the dashboard and only the
|
||||
* rank thread may walk the slot pools. */
|
||||
int64_t flex_used_bytes() const { return flex_used_.load(std::memory_order_relaxed); }
|
||||
int64_t flex_offered_bytes() const { return flex_offered_.load(std::memory_order_relaxed); }
|
||||
int64_t flex_capacity() const;
|
||||
@@ -588,33 +458,25 @@ public:
|
||||
for (const ClassPools& cp : pools_) n += cp.n_turn;
|
||||
return n;
|
||||
}
|
||||
/* THE LOAN PAST WHICH NOTHING MORE WOULD BE USED, in the lender's measure: the one that
|
||||
* covers every slot carved from it. The slots were carved no deeper than the units the host
|
||||
* pool holds, so a loan this size already has room for every unit that could move -- more VRAM
|
||||
* from the lender would sit empty. Zero with nothing carved. */
|
||||
/* The loan that covers every slot carved from this lender; more would sit empty. Zero when
|
||||
* nothing is carved. */
|
||||
int64_t loan_ceiling(int lender) const;
|
||||
|
||||
/* FILL EVERY SLOT THERE IS ROOM IN, AND EMPTY EVERY SLOT THE LOAN NO LONGER COVERS -- the
|
||||
* half-swaps the heat engine never proposes, because its decision is a COMPARISON and a
|
||||
* comparison needs a victim. Not bounded by a count: a slot left empty while a unit streams
|
||||
* across the link is VRAM bought and wasted on every step, so every free slot past the
|
||||
* turnover slots is filled in one call, hottest units first, and the copies run at the rate
|
||||
* the link carries them. The turnover slots are left free because the engine's swaps land in
|
||||
* them; filled, they would cap the move rate at what the shadow slots alone allow. When fewer
|
||||
* than the working and turnover slots are free, the coldest lent units are dropped until
|
||||
* enough are -- a change of address, never a copy.
|
||||
/* Fills free lent slots and empties slots the loan no longer covers: the half-swaps the heat
|
||||
* engine never proposes, since its decisions need a victim. Every free slot past the turnover
|
||||
* slots is filled in one call, hottest units first, since an empty slot wastes VRAM every
|
||||
* step. The turnover slots stay free for the engine's swaps; filled, they would cap the move
|
||||
* rate at the shadow slots. When fewer than the working plus turnover slots are free, the
|
||||
* coldest lent units are dropped (an address change, never a copy).
|
||||
*
|
||||
* `turnover` false treats the turnover slots as room, filled like any other: a step bound by
|
||||
* its own staging copies swaps nothing (Engine::tiering_dispatch), and every unit resident is
|
||||
* one its stager does not copy. The next call with it true drops them back out. */
|
||||
* `turnover` false fills the turnover slots too, for steps bound by their own staging copies
|
||||
* (Engine::tiering_dispatch); the next call with true drops them back out. */
|
||||
int balance(HeatEngine* heat, bool turnover = true);
|
||||
|
||||
/* balance() for a rank with no step to ride on. Retires what has landed and fills what is
|
||||
* free, so a loan made while the server is idle is filled before the next request rather
|
||||
* than by it -- the turnover slots too while they are held. Only while the rank thread is
|
||||
* parked. */
|
||||
/* retire() then balance() for an idle rank, so a loan made while idle is filled before the
|
||||
* next request. Call only while the rank thread is parked. */
|
||||
int idle_tick(HeatEngine* heat);
|
||||
/* Whether idle ticks keep the turnover slots filled: the engine holds them through a prompt
|
||||
/* Whether idle ticks keep the turnover slots filled; the engine holds them through a prompt
|
||||
* and the few steps after it (Engine::tiering_dispatch). */
|
||||
void hold_turnover(bool held) { hold_turnover_ = held; }
|
||||
/* Each class's pinned pool as the card addresses it: [lo, hi) and the unit stride. At most `max`. */
|
||||
@@ -634,30 +496,23 @@ public:
|
||||
* unit that has not been staged. */
|
||||
void* unit_base(int32_t unit) const;
|
||||
|
||||
/* ---- STAGING WITHIN A PASS: the prefill stager (core/place/stager.h) ----------------------
|
||||
/* ---- staging within a pass: the prefill stager (core/place/stager.h) ----------------------
|
||||
*
|
||||
* Everything else the mover does happens between steps, and a unit's address is fixed for the
|
||||
* length of a step. These two are the exception, and they change only the PUBLISHED address,
|
||||
* never where a unit lives: the unit stays in its pinned pool slot, and for one routed layer's
|
||||
* ops the run phase reads a copy of it in a buffer the caller owns.
|
||||
* The only calls that change a unit's address within a step, and only the published one: the
|
||||
* unit stays in its pinned pool slot, and one routed layer's ops read a copy in a
|
||||
* caller-owned buffer.
|
||||
*
|
||||
* stage_units copy every unit of `units` that lives in the pinned pool, has no slab slot and
|
||||
* has no copy of its own in flight into `dst`, one after another at the allocation
|
||||
* unit, until `cap` has no room for the next -- on the mover's stream, behind
|
||||
* `after` when it is not null, with `done` recorded behind the last copy. Each
|
||||
* copied unit's weights are then published at the copy, SETTLED: the caller
|
||||
* orders the ops that read them behind `done` with one stream wait, where an
|
||||
* event on every weight would cost the run phase one wait per weight -- a few
|
||||
* hundred a layer. `staged` gets the units copied, in order.
|
||||
* unstage_units publish those units at their pool slots again. The caller must already have
|
||||
* ordered the next writer of `dst` behind every op that read the copies; this
|
||||
* only moves the address the NEXT issue resolves.
|
||||
* stage_need the room stage_units would fill with `units` given room for all of them, so
|
||||
* a caller packing several layers into one region can size each one's share;
|
||||
* `largest`, when not null, gets the room the largest of those units takes.
|
||||
* stage_units copies each pooled unit of `units` with no slab slot and no copy in flight
|
||||
* into `dst`, packed at the allocation unit; a unit with no room is read in
|
||||
* place. Runs on the mover's stream behind `after` (if set) and records `done`.
|
||||
* Copies are published settled: the caller waits on `done` once instead of
|
||||
* once per weight (a few hundred per layer).
|
||||
* unstage_units publishes those units at their pool slots again. The caller must already have
|
||||
* ordered the next writer of `dst` behind every reader of the copies.
|
||||
* stage_need the room stage_units would use with no cap, for sizing shares of a region;
|
||||
* `largest`, if set, gets the largest unit's room.
|
||||
*
|
||||
* The span form packs into up to two stretches, the second taking what the first has no
|
||||
* room left for: a ring's place that wraps past the region's end is two.
|
||||
* The span form packs into up to two stretches (a ring region that wraps is two).
|
||||
*/
|
||||
struct StageSpan { char* dst; int64_t cap; };
|
||||
int stage_units(const std::vector<int32_t>& units, char* dst, int64_t cap, RadEvent after,
|
||||
@@ -667,24 +522,19 @@ public:
|
||||
void unstage_units(const std::vector<int32_t>& staged);
|
||||
int64_t stage_need(const std::vector<int32_t>& units, int64_t* largest = nullptr) const;
|
||||
|
||||
/* ---- ROUTED LAYERS READ FROM THE CONTAINER: the file stager (core/place/stager.h) --------
|
||||
/* ---- routed layers read from the container: the file stager (core/place/stager.h) --------
|
||||
*
|
||||
* A routed unit the plan put on the file tier has no address at all (unit_base is null), and a
|
||||
* grouped GEMM is handed every expert's pointer at issue -- so before a routed layer's first
|
||||
* expert op, every one of its file-tier units is read into a VRAM buffer and published there,
|
||||
* and after the layer it is published as null again (unstage_units does that half). The
|
||||
* buffers are the two the plan charged out of the weights pool (Plan::file_stage_vram).
|
||||
* A file-tier unit has no address, but a grouped GEMM takes every expert's pointer at issue.
|
||||
* So before a routed layer's first expert op its file-tier units are read into a VRAM buffer
|
||||
* and published there; afterwards unstage_units publishes them as null again. The plan
|
||||
* charges the two buffers to the weights pool (Plan::file_stage_vram).
|
||||
*
|
||||
* stage_file_units read every unit of `units` that is on the file tier into `dst`, packed at
|
||||
* RAD_ALIGN_UNIT in the order given, through the pinned read windows: the
|
||||
* layer's weights are read in container order as long runs -- a run skips a
|
||||
* gap of resident units rather than reading through it -- each window drains
|
||||
* to `dst` on the mover's stream while the next fills, behind `after` when it
|
||||
* is not null, with `done` recorded behind the last copy. Published SETTLED,
|
||||
* for the reason stage_units gives. Refuses with RAD_E_SCRATCH when the units
|
||||
* do not fit `cap`, which a buffer sized by the plan never meets. The reads
|
||||
* are BLOCKING on this thread; that is the price of the tier and the stats
|
||||
* above carry it.
|
||||
* stage_file_units reads every file-tier unit of `units` into `dst`, packed at RAD_ALIGN_UNIT
|
||||
* in the order given, through the pinned read windows: container-order
|
||||
* runs, each window draining to `dst` on the mover's stream while the next
|
||||
* fills, behind `after` (if set), with `done` recorded last. Published
|
||||
* settled. RAD_E_SCRATCH if the units exceed `cap`. The reads block this
|
||||
* thread.
|
||||
* file_buffer buffer 0 or 1 of the plan's two, or null when the plan has none. */
|
||||
int stage_file_units(const std::vector<int32_t>& units, char* dst, int64_t cap,
|
||||
RadEvent after, RadEvent done, std::vector<int32_t>* staged);
|
||||
@@ -697,22 +547,18 @@ public:
|
||||
std::string report() const;
|
||||
|
||||
private:
|
||||
/* One in-flight relocation. The state machine is Free -> Copying -> Published -> Quarantine
|
||||
* -> Free, and every transition is made by the DISPATCH THREAD at a layer boundary. The
|
||||
* transfers are asynchronous; the table edits are not. No mutex on the read side, because
|
||||
* that side is the critical path of every layer, and no background thread mutating placement
|
||||
* mid-layer, because placement would then depend on host timing and stop being reproducible. */
|
||||
/* One in-flight relocation: Free -> Copying -> Published -> Quarantine -> Free. Transfers
|
||||
* are asynchronous; every transition is made by the dispatch thread at a layer boundary. No
|
||||
* mutex on the read side (it is on every layer's critical path) and no background thread,
|
||||
* which would make placement depend on host timing. */
|
||||
struct Move {
|
||||
enum class State { Free, Copying, Published, Quarantine };
|
||||
/* Six kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is
|
||||
* the exact prefetch bringing an offloaded unit into a slot. Release is the same slot
|
||||
* going back once the declared order says nothing will read it again this step -- it
|
||||
* copies nothing and still needs the quarantine, because the barrier is about kernels
|
||||
* already issued and not about bytes in flight. Drop is a unit in a lent slot going back
|
||||
* to the host copy it kept: no copy either, and the same quarantine for the same reason.
|
||||
* Migrate is a donor (Mover::donor_slot) leaving a lent slot the loan no longer covers
|
||||
* for a free budgeted one, a copy inside the card; `slab_slot` is the slot it leaves and
|
||||
* `to_slot` the one it lands in. */
|
||||
/* Promote/Demote: the heat engine's swaps. Stage: the exact prefetch copying an offloaded
|
||||
* unit into a slot; Release: that slot returned after its last use this step. Drop: a
|
||||
* unit in a lent slot back to its kept host copy. Release and Drop copy nothing but still
|
||||
* need the quarantine, which guards issued kernels, not bytes in flight. Migrate: a donor
|
||||
* (Mover::donor_slot) from an uncovered lent slot (`slab_slot`) to a free budgeted one
|
||||
* (`to_slot`). */
|
||||
enum class Kind { Promote, Demote, Stage, Release, Drop, Migrate };
|
||||
State state = State::Free;
|
||||
Kind kind = Kind::Promote;
|
||||
@@ -721,6 +567,14 @@ private:
|
||||
int64_t pool_slot = -1;
|
||||
int64_t to_slot = -1;
|
||||
RadEvent ev = nullptr;
|
||||
|
||||
void clear() {
|
||||
state = State::Free;
|
||||
unit = -1;
|
||||
slab_slot = pool_slot = to_slot = -1;
|
||||
}
|
||||
/* Whether the move hands `slab_slot` back once its quarantine clears. */
|
||||
bool frees_slab() const { return kind != Kind::Promote && kind != Kind::Stage; }
|
||||
};
|
||||
|
||||
struct UnitState {
|
||||
@@ -733,16 +587,10 @@ private:
|
||||
int64_t bytes = 0;
|
||||
};
|
||||
|
||||
/* One weight class's memory. The slab is two kinds of slot rather than one: the BUDGETED slots
|
||||
* come out of the weights pool like every other weight allocation and sit at a fixed stride
|
||||
* from one base, and the FLEX slots past them are addresses inside another pool's memory --
|
||||
* the KV cache's carve, the activation arena's top -- lent while that pool is not using them.
|
||||
* They cannot be one range because the flex slots are scattered over every layer's stripe of
|
||||
* the cache, wherever a stripe has room for one.
|
||||
*
|
||||
* A slot index therefore carries no information about which kind it is; slot_ptr is the only
|
||||
* place that distinction exists. Each lender's flex slots are one segment of the slab, ordered
|
||||
* by the loan that covers each, so a loan of any size is a prefix of its segment. */
|
||||
/* One weight class's memory. Budgeted slots sit at a fixed stride from one base in the
|
||||
* weights pool. Flex slots after them are lent addresses scattered over another pool's memory
|
||||
* (KV cache stripes, arena top), so only slot_ptr() can resolve a slot index. Each lender's
|
||||
* flex slots form one segment ordered by covering loan, so any loan covers a prefix. */
|
||||
struct ClassPools {
|
||||
SlotPool slab, pool;
|
||||
void* slab_base = nullptr;
|
||||
@@ -757,14 +605,12 @@ private:
|
||||
int64_t n_donated = 0; /* units in lent slots that gave their host copy away
|
||||
* (Mover::donor_slot); at most n_turn of them */
|
||||
std::vector<char*> flex_ptr;
|
||||
/* ONE SEGMENT OF THE SLAB PER LENDER THAT CARVED SLOTS FOR THIS CLASS. `need[i]` is the
|
||||
* loan, in the lender's measure, that covers the segment's i-th slot; ascending, so a
|
||||
* loan of any size covers a prefix. */
|
||||
/* One slab segment per lender that carved slots for this class. `need[i]` is the loan,
|
||||
* in the lender's measure, that covers the segment's i-th slot; ascending. */
|
||||
struct Lent { int lender = 0; int seg = -1; int64_t first = 0; std::vector<int64_t> need; };
|
||||
std::vector<Lent> lent;
|
||||
/* A slot leaves coverage only when a loan shrinks, and nothing is ever placed in an
|
||||
* uncovered one, so units stranded past the loan exist only after a shrink. Set there, and
|
||||
* cleared by a balance() sweep that dropped every one of them. */
|
||||
/* Units can sit past the loan only after a shrink, since nothing is placed in an
|
||||
* uncovered slot. Set on a shrink; cleared by a balance() sweep that removed them all. */
|
||||
bool strand_check = true;
|
||||
|
||||
char* slot_ptr(int64_t slot) const {
|
||||
@@ -780,8 +626,8 @@ private:
|
||||
Residency res_;
|
||||
MoverStats stats_;
|
||||
Pools* budget_ = nullptr;
|
||||
/* True only when this object called the allocator itself, which is the test path. A Pool
|
||||
* reservation is owned by the Pool and freeing it here would be a double free. */
|
||||
/* True only when this object called the allocator itself (the test path). A Pool
|
||||
* reservation belongs to the Pool; freeing it here would be a double free. */
|
||||
bool owns_memory_ = false;
|
||||
|
||||
RadStream mover_ = nullptr;
|
||||
@@ -792,29 +638,29 @@ private:
|
||||
std::vector<StagePick> stage_picks_; /* the units stage_units may take, in pool order */
|
||||
int gate_dispatch_ = -1;
|
||||
|
||||
/* A DISPATCH'S SWAP COPIES -- demotions, promotions and migrations -- GO TO THE CARD'S DMA ENGINE
|
||||
* AS ONE LIST (flush_moves), sent at the end of balance() and before anything reads their events.
|
||||
* Each move's event is recorded behind the list, so a move lands with its list. */
|
||||
/* A dispatch's swap copies (demotions, promotions, migrations) go to the card's DMA engine as
|
||||
* one list (flush_moves), sent at the end of balance() and before anything reads their
|
||||
* events. Each move's event is recorded after the list. */
|
||||
std::vector<RadCopySeg> move_segs_;
|
||||
std::vector<int32_t> move_recs_;
|
||||
int queue_move_copy(void* dst, const void* src, int64_t bytes, int rec);
|
||||
void queue_move_copy(void* dst, const void* src, int64_t bytes, int rec);
|
||||
int flush_moves();
|
||||
std::vector<ClassPools> pools_;
|
||||
std::vector<UnitState> unit_;
|
||||
std::vector<Move> moves_;
|
||||
/* Per unit, how many records are Copying it: unit_in_flight() without a walk of the records.
|
||||
* The prefill stager asks for every pooled unit of every layer it stages, and the records
|
||||
* number twice the slots a swap can hold, so a walk would grow with the move budget. */
|
||||
/* Per unit, how many records are Copying it, so unit_in_flight() needs no walk of the
|
||||
* records. The prefill stager asks about every pooled unit it stages, and the record count
|
||||
* grows with the move budget. */
|
||||
std::vector<uint16_t> copying_;
|
||||
/* balance()'s drop candidates, (heat, unit), kept between calls so a step allocates nothing. */
|
||||
std::vector<std::pair<float, int32_t>> drop_cand_;
|
||||
bool hold_turnover_ = false;
|
||||
/* donor_slot()'s candidates a class, by layer, each layer's coldest first so its hottest is at
|
||||
* the back; ranked once a dispatch, `at` being the dispatch they were ranked for. */
|
||||
/* donor_slot()'s candidates per class, by layer, each layer sorted coldest first (hottest at
|
||||
* the back). Ranked once per dispatch; `at` is that dispatch. */
|
||||
struct DonorRank { int at = -1; std::vector<std::vector<std::pair<float, int32_t>>> by_layer; };
|
||||
std::vector<DonorRank> donors_;
|
||||
/* The layer whose unit each pool slot held when the pool was laid out, a class: the pool is
|
||||
* filled in unit order, so a layer's pooled units start out side by side (pool_slot_for). */
|
||||
/* Per class, the layer of the unit each pool slot held at layout. The pool is filled in unit
|
||||
* order, so a layer's pooled units start out adjacent (pool_slot_for). */
|
||||
std::vector<std::vector<int32_t>> pool_layer_;
|
||||
int32_t n_layers_ = 0;
|
||||
|
||||
@@ -846,13 +692,12 @@ private:
|
||||
int32_t last_op_ = -1;
|
||||
int dispatch_ = 0;
|
||||
|
||||
/* THE LOAN, in the owner's tokens, and what the dashboard reads of it. */
|
||||
/* Each lender's loan in its own measure, and the totals the dashboard reads. */
|
||||
int64_t loan_[kLenders] = {};
|
||||
std::atomic<int64_t> flex_used_{0};
|
||||
std::atomic<int64_t> flex_offered_{0};
|
||||
/* Where the last free record was found. Records free up roughly in the order they were taken,
|
||||
* so starting the next search there makes it a step rather than a walk of every record, which
|
||||
* matters once the lent slots have put a record's worth of them in flight. */
|
||||
/* Where the last free record was found. Records free up roughly in the order they were
|
||||
* taken, so starting there keeps the search short when lent slots put many in flight. */
|
||||
mutable size_t rec_cursor_ = 0;
|
||||
|
||||
int retire(HeatEngine* heat);
|
||||
@@ -863,14 +708,16 @@ private:
|
||||
int start_stage(int32_t unit, int64_t slab_slot);
|
||||
void release_slot(int32_t unit);
|
||||
bool unit_in_flight(int32_t unit) const;
|
||||
/* Whether stage_units would copy `unit`: pooled, with no slab slot and no copy in flight. */
|
||||
bool stageable(int32_t unit) const;
|
||||
/* A unit in a lent slot back to the host copy it kept. See Move::Kind::Drop. */
|
||||
int drop(int32_t unit, HeatEngine* heat);
|
||||
/* The pool slot a demotion copies `unit` into: one its layer's units started out in, else a
|
||||
* same-layer donor's, else any free one, else any donor's; -1 when there is none. */
|
||||
int64_t pool_slot_for(int32_t unit, HeatEngine* heat);
|
||||
/* A pool slot for a budgeted victim when the pool has none free: the host copy of a unit in a
|
||||
* slot the KV cache lent, which keeps its place in VRAM without one -- a unit of `layer`, or
|
||||
* of any layer when it is negative. -1 when no unit may give one. See the definition. */
|
||||
/* A pool slot for a budgeted victim when none is free: the host copy of a unit in a KV-lent
|
||||
* slot, which stays in VRAM without it. From a unit of `layer`, or of any layer when
|
||||
* negative; -1 when no unit may give one. Rationale at the definition. */
|
||||
int64_t donor_slot(size_t klass, int32_t layer, HeatEngine* heat);
|
||||
/* A donor out of a lent slot into a free budgeted one, if one is free: false when none is. */
|
||||
bool migrate(int32_t unit, HeatEngine* heat);
|
||||
|
||||
+253
-447
File diff suppressed because it is too large.
Load diff
+174
-247
@@ -1,38 +1,28 @@
|
||||
/* planner.h -- the placement planner. Runs ONCE, after declare and before load, and assigns every
|
||||
/* planner.h -- the placement planner. Runs once, after declare and before load, and assigns every
|
||||
* weight a tier and an execution site against explicit pool budgets (spec §5.3).
|
||||
*
|
||||
* ---- THE ONE IDEA IN THIS DIRECTORY ------------------------------------------------------------
|
||||
* All-in-VRAM, layer offload and expert offload are one mechanism at three granularities, over
|
||||
* the same tiers. They differ in whether the access is predictable:
|
||||
*
|
||||
* All-in-VRAM, layer offload to RAM/SSD, and expert offload to RAM/SSD are ONE MECHANISM AT THREE
|
||||
* GRANULARITIES. What separates them is not the tiering -- the tiers are the same four -- but
|
||||
* whether the access is PREDICTABLE, and that distinction is the shape of this code:
|
||||
* Layer offload is a scheduling problem. WeightInfo::first_use_op is the full access sequence,
|
||||
* known statically from declare, so Plan::prefetch is an exact schedule with no predictor.
|
||||
*
|
||||
* LAYER OFFLOAD IS A SCHEDULING PROBLEM. Declare already enumerated every op with its weight
|
||||
* operands in order, so WeightInfo::first_use_op is the entire future access sequence, known
|
||||
* statically. The planner emits an exact prefetch schedule off it (Plan::prefetch). No policy,
|
||||
* no predictor, nothing to be wrong about.
|
||||
* Expert offload is a prediction problem. Routing is data-dependent, so the planner only ranks
|
||||
* an initial residency and heat.h re-ranks from real routing.
|
||||
*
|
||||
* EXPERT OFFLOAD IS A PREDICTION PROBLEM. Routing is data-dependent, so the only thing the
|
||||
* planner can do is rank an initial residency and hand the rest to heat.h. This is why expert
|
||||
* offload needs a heat engine and layer offload (llama.cpp's) does not.
|
||||
* All-in-VRAM is the degenerate case: every weight on tier 0 and the mover never runs.
|
||||
*
|
||||
* ALL-IN-VRAM IS THE DEGENERATE CASE where every weight lands on tier 0 and the mover never
|
||||
* runs. It is not a separate path; it is this one with a budget that fits.
|
||||
*
|
||||
* ---- TIER AND SITE ARE INDEPENDENT AXES (spec §5.1) --------------------------------------------
|
||||
*
|
||||
* Tier is where the bytes live. Site is where the arithmetic happens. All four combinations are
|
||||
* core behaviour:
|
||||
* Tier (where the bytes live) and site (where the arithmetic runs) are independent axes
|
||||
* (spec §5.1):
|
||||
*
|
||||
* VRAM + Device vLLM
|
||||
* host/SSD + DeviceStaged staged into a slab slot, exact or predicted
|
||||
* host + DeviceZeroCopy the GEMM streams the weight over the link as it computes; no
|
||||
* slab slot, so a read-once weight costs no residency at all
|
||||
* slab slot, so a read-once weight costs no residency
|
||||
* host + Host llama.cpp -ngl
|
||||
*
|
||||
* Host-site execution needs a RAD_DOMAIN_HOST kernel. Where declare resolved none, that site is
|
||||
* UNAVAILABLE for that op, and the planner is told so by reading Band::dom[RAD_DOMAIN_HOST]
|
||||
* rather than by being passed a flag -- the resolution is the fact.
|
||||
* The host site needs a RAD_DOMAIN_HOST kernel; the planner reads its availability from
|
||||
* Band::dom[RAD_DOMAIN_HOST] rather than from a flag.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
@@ -51,10 +41,9 @@ const char* strategy_name(Strategy s);
|
||||
int strategy_parse(const char* s, Strategy* out);
|
||||
|
||||
/* ------------------------------------------------------------------ budgets */
|
||||
/* Every pool is budgeted explicitly. No profiling pass, no utilisation fraction, no inference
|
||||
* about what the workload will be (spec §6). The one thing a zero means is stated here rather
|
||||
* than guessed at each use: zero vram_weights is "no cap", which is answerable only under
|
||||
* all_vram -- any offload strategy needs a number to spill against and says so by name.
|
||||
/* Every pool is budgeted explicitly: no profiling pass, no utilisation fraction (spec §6). Zero
|
||||
* vram_weights means "no cap", which only all_vram accepts; an offload strategy needs a number
|
||||
* to spill against.
|
||||
*/
|
||||
struct Budgets {
|
||||
int64_t vram_weights = 0; /* bytes; 0 = uncapped, legal only when everything fits */
|
||||
@@ -65,27 +54,22 @@ struct Budgets {
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the movement unit */
|
||||
/* THE UNIT OF PLACEMENT IS A GROUP, NOT A TENSOR. An expert's gate/up/down share one
|
||||
* RadWeightGroup because a dispatch holding two of the three has nothing it can compute; a
|
||||
* layer's weights share one because layer offload is a contiguous run rather than a scatter
|
||||
* (spec §4.1). Everything below -- the slab's fixed stride, the mover's copy, heat's ranking --
|
||||
* is per unit, and a weight's placement is its unit's placement.
|
||||
/* The unit of placement is a weight group, not a tensor. An expert's gate/up/down share one
|
||||
* RadWeightGroup because a dispatch missing one of them cannot compute; a layer's weights share one
|
||||
* because layer offload moves contiguous runs (spec §5.3). Slab stride, mover copies and heat
|
||||
* ranking are all per unit, and a weight's placement is its unit's placement.
|
||||
*
|
||||
* UNDER TENSOR PARALLEL A UNIT IS THIS RANK'S SHARD OF THE GROUP. The plugin declares dimensions
|
||||
* already divided (spec §9), so `bytes` is already per-rank and the planner budgets against this
|
||||
* card. What the planner still owes TP is the harder half, and it is an invariant rather than an
|
||||
* arithmetic: THE RESIDENT SET MUST BE IDENTICAL ON EVERY RANK. Each rank holds its own half of
|
||||
* every resident expert, so a slab slot only means the same thing everywhere if every rank
|
||||
* decided the same experts were in it. That is why the ranking below is keyed on the container's
|
||||
* profile and the unit's identity and on nothing rank-local -- no free-VRAM query, no timing, no
|
||||
* device enumeration. The invariant is a property of how the ranking is computed rather than a
|
||||
* condition checked before placement may run.
|
||||
* Under tensor parallel a unit is this rank's shard: dimensions are declared already divided
|
||||
* (spec §9), so `bytes` is per rank. Invariant: the resident set must be identical on every rank,
|
||||
* or a slab slot holds different experts on different cards. The ranking therefore uses only the
|
||||
* container's profile and the unit's identity -- no free-VRAM query, no timing, no device
|
||||
* enumeration.
|
||||
*/
|
||||
struct MoveUnit {
|
||||
int32_t layer = -1; /* RadWeightGroup::layer; -1 for a model-level weight */
|
||||
int32_t expert = -1; /* RadWeightGroup::expert; -1 for a non-expert group */
|
||||
int32_t slab_class = -1; /* index into Plan::classes */
|
||||
int64_t bytes = 0; /* THIS RANK's shard of the whole group */
|
||||
int64_t bytes = 0; /* this rank's shard of the whole group */
|
||||
int32_t first_use_op = -1; /* min over the group; the prefetch schedule keys on it */
|
||||
int32_t last_use_op = -1;
|
||||
int access = RAD_ACCESS_PER_TOKEN; /* the group's strongest access class */
|
||||
@@ -98,43 +82,38 @@ struct MoveUnit {
|
||||
bool host_forced = false; /* a placement flag put it in the pinned pool: the embedding's
|
||||
* or the encoder tower's */
|
||||
|
||||
/* PLACED BEFORE ANY STRATEGY RAN, so every assignment pass skips it and no VRAM total counts
|
||||
* it: the mapped tier (no device kernel can read it), --embedding-placement ram and
|
||||
* --vision-tower-placement ram. */
|
||||
/* Placed before any strategy runs, so every assignment pass skips it and no VRAM total counts
|
||||
* it: the mapped tier, --embedding-placement ram and --vision-tower-placement ram. */
|
||||
bool preplaced() const { return tier == Tier::Mapped || host_forced; }
|
||||
const char* reason = "fits in vram"; /* a fixed string, so the report never guesses */
|
||||
const char* reason = "fits in vram"; /* a fixed string for the report */
|
||||
|
||||
/* The group's INTERNAL LAYOUT, computed once here so the mover never has to. `offset[i]` is
|
||||
* where weights[i] sits inside the unit, honouring that weight's declared alignment, and
|
||||
* `bytes` is the padded total. One definition, because the mover's copy size, the pool offset
|
||||
* it reads and the pointer it publishes must agree and they are written in three places. */
|
||||
/* The group's internal layout, computed once here: `offset[i]` is where weights[i] sits in the
|
||||
* unit at its declared alignment, and `bytes` is the padded total. The mover's copy size, pool
|
||||
* offset and published pointer all derive from it. */
|
||||
std::vector<rad_weight> weights;
|
||||
std::vector<int64_t> offset;
|
||||
|
||||
/* WHAT THE UNIT ACTUALLY COSTS A POOL, which is its class's slot stride and not `bytes`. The
|
||||
* planner budgets against this and the mover allocates this, so the two cannot drift -- and
|
||||
* the direction they would drift in is an overrun of the weights pool. `bytes` is
|
||||
* still what the report attributes to the weights, because padding is not a weight. */
|
||||
/* What the unit costs a pool: its class's slot stride, not `bytes`. The planner budgets and
|
||||
* the mover allocates this same number, so they cannot drift into a weights-pool overrun. The
|
||||
* report still attributes `bytes`, since padding is not weight. */
|
||||
int64_t slot_bytes = 0;
|
||||
|
||||
/* Every weight of it lies in the container exactly as its kernel reads it (weight_file_direct),
|
||||
* so the file tier can stage it with a read. A unit that is not is never placed there. */
|
||||
/* Every weight lies in the container exactly as its kernel reads it (weight_file_direct), so
|
||||
* the file tier can stage it with a read. A unit that is not never goes to the file tier. */
|
||||
bool file_direct = true;
|
||||
};
|
||||
|
||||
/* The strongest access class in a group decides the group's. Strongest means "read most surely":
|
||||
* a group holding one PER_TOKEN weight is read on every forward pass whatever the rest of it is,
|
||||
* and calling it conditional would let the heat engine demote something the next token needs.
|
||||
* VOCAB ranks with PER_TOKEN -- lm_head and the embedding table are read every token; what makes
|
||||
* them their own class is their size and the gather, not their certainty (spec §19.2). */
|
||||
/* The strongest access class in a group, "read most surely", decides the group's: a group with
|
||||
* one PER_TOKEN weight is read every forward pass, and calling it conditional would let heat
|
||||
* demote something the next token needs. VOCAB ranks with PER_TOKEN; lm_head and the embedding
|
||||
* are read every token and differ only in size and the gather (spec §5.2). */
|
||||
int access_strength(int access);
|
||||
|
||||
/* ------------------------------------------------------------------ the slab class */
|
||||
/* Fixed-stride VRAM slab slots per weight class (spec §5.4). One stride per class, so a slot is
|
||||
* interchangeable within its class and the mover's bookkeeping is an integer rather than an
|
||||
* allocator. The stride is the class's largest unit rounded to the movement-unit alignment; the
|
||||
* padding that costs is the price of never fragmenting, and a fragmenting slab is a slab whose
|
||||
* hit rate depends on the order promotions happened to arrive in.
|
||||
/* Fixed-stride VRAM slab slots per weight class (spec §5.4). Slots are interchangeable within a
|
||||
* class, so the mover's bookkeeping is an integer, not an allocator. A class is keyed on the unit
|
||||
* kind and the unit size rounded to the movement-unit alignment, so every unit of a class has
|
||||
* the class's stride and the slab never fragments.
|
||||
*/
|
||||
struct SlabClass {
|
||||
std::string name; /* "expert", "layer", "model" plus the byte size */
|
||||
@@ -146,78 +125,52 @@ struct SlabClass {
|
||||
bool movable = false;
|
||||
};
|
||||
|
||||
/* THE STAGING RING. A DeviceStaged unit lives off the device and is copied into a slab slot
|
||||
* before its op runs, so a class holding staged units needs slots that belong to no unit. Two is
|
||||
* double buffering -- one slot being read by the op that is running, one landing for the op
|
||||
* after it -- and it is the minimum depth that overlaps anything at all.
|
||||
*
|
||||
* More is better hiding at more VRAM, and where the curve flattens is a measurement rather than a
|
||||
* principle; it is not a Config field because Config is frozen and this is the honest
|
||||
* default rather than a tuned one. If it becomes worth tuning it wants a --stage-ring flag beside
|
||||
* the other explicit budgets in spec §6, NOT a heuristic derived from free VRAM. */
|
||||
/* Staging ring: slab slots that belong to no unit, which a DeviceStaged unit is copied into
|
||||
* before its op runs. Two is double buffering (one slot read by the running op, one landing for
|
||||
* the next), the minimum that overlaps anything. Deeper hides more at more VRAM; if it needs
|
||||
* tuning it should become an explicit budget flag (spec §6), not a heuristic from free VRAM. */
|
||||
#define RAD_PLACE_STAGE_RING 2
|
||||
|
||||
/* THE FILE TIER'S STAGING POOL, IN PINNED HOST SLOTS. A unit read from the container lands in a
|
||||
* pinned buffer the mover can DMA out of without a bounce (spec §5.4), and those buffers come out
|
||||
* of --host-pool-mib like everything else on the host side.
|
||||
*
|
||||
* It is defined HERE, beside the VRAM ring, because the planner has to charge the operator for it
|
||||
* and the mover has to allocate exactly what was charged. Were it a mover-side default instead,
|
||||
* the planner would fill the host pool with pinned units and the mover would then ask the
|
||||
* exhausted pool for these slots and refuse the plan -- the same shape as the slab overhead on
|
||||
* the VRAM side, and the same rule: whoever budgets a thing owns its number. */
|
||||
/* The file tier's staging pool, in pinned host slots: a unit read from the container lands in a
|
||||
* pinned buffer the mover can DMA out of without a bounce (spec §5.4). Defined here because the
|
||||
* planner charges it to --host-pool-mib and the mover must allocate exactly that; a mover-side
|
||||
* default would let the planner fill the pool first and the mover then refuse the plan. */
|
||||
#define RAD_PLACE_FILE_STAGE_SLOTS 4
|
||||
|
||||
/* THE WINDOWS A ROUTED LAYER IS READ THROUGH, when routed experts land on the file tier. A layer's
|
||||
* file-tier experts are read as long sequential runs of the container -- a few gigabytes a layer
|
||||
* for a bf16 model -- so the read does not go a unit at a time into the slots above: it fills one
|
||||
* pinned window while the window before it drains to the card, and the host waits on a window
|
||||
* only when it comes round again. Four of 32 MiB keep a drive at its sequential rate (a pread of
|
||||
* this size is ~5 ms at 7 GB/s, the copy out of it under 2) for 128 MiB of pinned memory, charged
|
||||
* out of --host-pool-mib like the slots. */
|
||||
/* Pinned read windows for routed experts on the file tier. A layer's file-tier experts are read
|
||||
* as long sequential runs of the container: one window fills while the previous one drains to the
|
||||
* card. Four of 32 MiB keep a drive at its sequential rate (a 32 MiB pread is ~5 ms at 7 GB/s,
|
||||
* the copy out under 2 ms) for 128 MiB pinned, charged to --host-pool-mib. */
|
||||
#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. */
|
||||
/* Heat engine move budget: swaps per step per slab class. HeatParams::moves_per_step defaults to
|
||||
* it and the free slots below are sized from it, since a swap without a free slot does not happen.
|
||||
* The engine proposes once a step (Engine::tiering_dispatch) for every layer. Replaying a mixed
|
||||
* workload on Qwen3.8-Flash-Next TP1 with 40% of experts resident, the decode hit rate is 63.8% at
|
||||
* 8, 74.1% at 32, 77.1% at 64 and 77.8% at 128; an oracle held to 64 reaches 78.0%, so past 64
|
||||
* the move rate, not the ranking, 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).
|
||||
*
|
||||
* THEY COME OUT OF THE WEIGHTS POOL, like everything else in the slab. Taking them from
|
||||
* whatever VRAM is left over after the slabs is not an option: spec §6 budgets every pool
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
/* Shadow slots: allocated slab slots holding no unit. A promotion writes into one and only then
|
||||
* publishes, so it never DMAs over a slot a kernel may still be reading (mover.h). They come out
|
||||
* of the weights pool, not leftover VRAM: every pool is budgeted (spec §6) and --gpu-headroom-mib
|
||||
* is untouchable. The expert floor charges for them (expert_vram_floor), so the KV cache never
|
||||
* gets them; the rest of the move budget is RAD_PLACE_TURNOVER_SLOTS. The quarter-of-the-slab cap
|
||||
* binds only on very small slabs. */
|
||||
#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.
|
||||
/* Turnover slots: free slab slots the mover keeps out of a loan (Mover::lend_from) beyond the
|
||||
* shadow slots. A swap holds a slot for about three steps (copy behind the proposing step,
|
||||
* publish at the next step's retire, then the demoted slot's quarantine), so
|
||||
* RAD_PLACE_MOVES_PER_STEP needs three times as many free slots. At 64 a step, 32 slots in all
|
||||
* give a 65.9% hit rate 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. */
|
||||
* They come out of the loan because a lent slot left free costs the cache nothing; charged to the
|
||||
* expert floor they would shrink the cache's largest size. When the cache reclaims memory, the
|
||||
* free slots at the loan's top go first and the mover rebuilds them by dropping its coldest lent
|
||||
* units, which keep host copies (Mover::balance). With nothing lent, only the shadow slots
|
||||
* remain. */
|
||||
#define RAD_PLACE_TURNOVER_SLOTS (3 * RAD_PLACE_MOVES_PER_STEP - RAD_PLACE_SHADOW_SLOTS)
|
||||
|
||||
/* ------------------------------------------------------------------ per-weight result */
|
||||
@@ -227,7 +180,7 @@ struct Placement {
|
||||
int32_t slab_slot = -1;
|
||||
int32_t unit = -1;
|
||||
int64_t bytes = 0;
|
||||
/* Why this and not VRAM/device, as a fixed string so the report never has to guess. */
|
||||
/* Why this and not VRAM/device, as a fixed string for the report. */
|
||||
const char* reason = "";
|
||||
};
|
||||
|
||||
@@ -239,11 +192,9 @@ public:
|
||||
/* 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
|
||||
* (spec §17). This is that mode as a real property of the plan -- the heat engine reads it
|
||||
* and stays off, and the mover reads it and allocates no shadow slots -- rather than a flag
|
||||
* that is checked nowhere. */
|
||||
/* False under Config::deterministic: residency sets the summation order, so dynamic placement
|
||||
* breaks bitwise reproducibility (spec §17). The heat engine stays off and the mover allocates
|
||||
* no shadow slots when it is false. */
|
||||
bool dynamic = true;
|
||||
|
||||
std::vector<Placement> weight; /* by rad_weight; index 0 is the sentinel */
|
||||
@@ -251,63 +202,52 @@ public:
|
||||
std::vector<int32_t> unit_of_weight; /* by rad_weight; -1 for the sentinel */
|
||||
std::vector<SlabClass> classes;
|
||||
|
||||
/* Host-site work, in EXECUTION ORDER, as runs. A host-site op leaves its activation in host
|
||||
* memory, so a host layer between two device layers costs two link crossings; a few hundred
|
||||
* KB is nothing and alternating per layer is not. llama.cpp gets this free because -ngl
|
||||
* assigns a contiguous suffix. Here it is an explicit objective, and this vector is the
|
||||
* evidence: one entry means one run, and `link_crossings` is what the plan costs a step. */
|
||||
/* Host-site layers in execution order, as runs. A host-site op leaves its activation in host
|
||||
* memory, so every run costs two link crossings and alternating per layer is expensive.
|
||||
* Contiguity is an explicit objective; `link_crossings` is the per-step cost. */
|
||||
struct HostRun { int32_t first_layer = 0, last_layer = 0; int64_t bytes = 0; };
|
||||
std::vector<HostRun> host_runs;
|
||||
int32_t link_crossings = 0;
|
||||
|
||||
/* THE EXACT PREFETCH SCHEDULE. Layer offload is a scheduling problem: this is the whole of
|
||||
* the policy, and it is a sorted list rather than a predictor. `at_op` is the op index by
|
||||
* which the unit's bytes must have landed, already backed off by the configured lead. */
|
||||
/* The exact prefetch schedule for staged, non-routed units, sorted by `at_op`: the op index by
|
||||
* which the unit's bytes must have landed. */
|
||||
struct Prefetch { int32_t at_op = 0; int32_t unit = 0; };
|
||||
std::vector<Prefetch> prefetch;
|
||||
|
||||
struct Totals { int64_t bytes[kTierCount] = {0}; }; /* indexed by Tier */
|
||||
Totals totals;
|
||||
/* `host_budget` is what is left for WEIGHTS after the file tier's staging pool is taken out of
|
||||
* --host-pool-mib, so the number the placement passes spend against is the number they may
|
||||
* actually have. `file_stage_reserve` is what was taken, reported so the operator can see
|
||||
* where the difference went: the unit slots, plus the read windows when a routed expert can
|
||||
* land on the file tier. */
|
||||
/* `host_budget` is what --host-pool-mib leaves for weights after the file tier's staging pool.
|
||||
* `file_stage_reserve` is that pool, reported so the difference is visible: the unit slots,
|
||||
* plus the read windows when a routed expert can land on the file tier. */
|
||||
int64_t vram_budget = 0, host_budget = 0;
|
||||
int64_t file_stage_reserve = 0;
|
||||
int64_t file_windows = 0; /* the read windows' part of it */
|
||||
/* --embedding-placement ram and --vision-tower-placement ram: the pool slots each flag's
|
||||
* units took before any strategy ran, like the file staging above, and reported beside it
|
||||
* rather than among the pooled units. `forced_host_used` is both flags' weight bytes, the unit
|
||||
* the tier totals count in, which the pooled weights' figures leave out. */
|
||||
/* --embedding-placement ram and --vision-tower-placement ram: host-pool bytes each flag's units
|
||||
* took before any strategy ran, reported apart from the pooled units. `forced_host_used` is
|
||||
* both flags' weight bytes, as the tier totals count them; the pooled figures exclude it. */
|
||||
int64_t embedding_host_bytes = 0;
|
||||
int64_t tower_host_bytes = 0;
|
||||
int64_t forced_host_used = 0;
|
||||
/* --ngram-placement ram: the n-gram tables the load phase copies into host memory. They stay
|
||||
* on the mapped tier as far as every pool is concerned; this is what the copy costs in RAM.
|
||||
* `ngram_copy_card` says which copy: pinned memory a device kernel reads in place over the
|
||||
* link, or locked memory the host gather reads. */
|
||||
/* --ngram-placement ram: RAM for the n-gram tables the load phase copies out of the mapping.
|
||||
* Every pool still sees them on the mapped tier. `ngram_copy_card` selects pinned memory a
|
||||
* device kernel reads over the link; otherwise locked memory the host gather reads. */
|
||||
int64_t ngram_copy_bytes = 0;
|
||||
bool ngram_copy_card = false;
|
||||
/* ROUTED EXPERTS ON THE FILE TIER have no address of their own: a routed layer's are read into
|
||||
* one of two VRAM buffers before the layer's first expert op and published there until the next
|
||||
* routed layer starts (place/stager.h, FileStager). `file_layer_max` is the most one layer's
|
||||
* file-tier units take in a buffer, each at its own size rounded to RAD_ALIGN_UNIT, which is
|
||||
* how the stager packs them; `file_stage_vram` is the two buffers, taken out of
|
||||
* the weights pool before any expert is made resident. Both 0 when nothing routed is on the
|
||||
/* Routed experts on the file tier have no address of their own: a routed layer's are read into
|
||||
* one of two VRAM buffers before its first expert op and stay published until the next routed
|
||||
* layer starts (place/stager.h, FileStager). `file_layer_max` is the largest layer's share,
|
||||
* each unit rounded to RAD_ALIGN_UNIT as the stager packs them; `file_stage_vram` is both
|
||||
* buffers, taken from the weights pool before residents. Both 0 when no routed unit is on the
|
||||
* file tier. */
|
||||
int64_t file_layer_max = 0;
|
||||
int64_t file_stage_vram = 0;
|
||||
/* VRAM the slab holds that no weight occupies: the shadow slots and the staging ring. It is
|
||||
* reported rather than folded into the tier total because it is the price of dynamic
|
||||
* placement and of offload respectively, and an operator comparing two runs needs to see
|
||||
* which of the two changed. */
|
||||
/* Slab VRAM no weight occupies: shadow slots (the cost of dynamic placement) and the staging
|
||||
* ring (the cost of offload). Reported separately from the tier totals. */
|
||||
int64_t slab_overhead = 0;
|
||||
|
||||
/* What did not fit. Two lists because there are two kinds of failure and they read
|
||||
* differently: `notes` is a whole-plan statement ("the budget is 3 GiB short"), and `unfit`
|
||||
* is per unit -- aggregated by class and reason, because a plan that strands nine hundred
|
||||
* experts must print one line about it and not nine hundred (spec §16). */
|
||||
/* What did not fit. `notes` holds whole-plan statements ("the budget is 3 GiB short");
|
||||
* `unfit` holds per-unit misfits aggregated by class and reason, so hundreds of stranded
|
||||
* experts print as one line (spec §16). */
|
||||
std::vector<std::string> notes;
|
||||
struct Unfit {
|
||||
std::string what; /* the weight class key */
|
||||
@@ -318,14 +258,8 @@ public:
|
||||
std::vector<Unfit> unfit;
|
||||
bool fits() const { return notes.empty() && unfit.empty(); }
|
||||
|
||||
const MoveUnit* unit_for(rad_weight w) const {
|
||||
if (w >= unit_of_weight.size() || unit_of_weight[w] < 0) return nullptr;
|
||||
return &units[(size_t)unit_of_weight[w]];
|
||||
}
|
||||
|
||||
/* THE PLACEMENT PLAN REPORT (spec §16): every weight's tier and site, the pool totals, and
|
||||
* what did not fit. One line per weight CLASS rather than per weight, because a model with
|
||||
* eleven thousand experts has eleven thousand weights and three interesting lines. */
|
||||
/* The placement plan report (spec §16): tier and site per weight class (not per weight), the
|
||||
* pool totals, and what did not fit. */
|
||||
std::string report(const Program& p) const;
|
||||
};
|
||||
|
||||
@@ -336,27 +270,23 @@ struct PlannerInput {
|
||||
int rank = 0;
|
||||
int world_size = 1;
|
||||
|
||||
/* The container's expert-popularity profile, derived from the imatrix's activation counts.
|
||||
* Null is fine and costs about a point of hit rate. See Planner::rank_units. */
|
||||
/* The container's expert-popularity profile, from the imatrix's activation counts. Null is
|
||||
* fine and costs about a point of hit rate. See Planner::rank_units. */
|
||||
const RadFileProfile* profile = nullptr;
|
||||
int64_t n_profile = 0;
|
||||
/* The weights are in a container, which the file and mapped tiers read in place. A checkpoint
|
||||
* served directly is neither grouped by movement unit nor aligned for O_DIRECT, so with this
|
||||
* false no unit is file-direct and both tiers are closed (spec §4.3). */
|
||||
* false both tiers are closed (spec §4.3). */
|
||||
bool container = true;
|
||||
/* No card is visible and the device backend is the host's own memory (device_is_host()), so a
|
||||
* host kernel can read the weights pool as well as the container's mapping. See
|
||||
* mapped_unit(). */
|
||||
/* No card is visible and the device backend is host memory (device_is_host()), so a host
|
||||
* kernel can read the weights pool as well as the mapping. See mapped_unit(). */
|
||||
bool host_backend = false;
|
||||
};
|
||||
|
||||
/* DOES A UNIT STAY IN THE CONTAINER'S MAPPING because only a host kernel can read it? On a card,
|
||||
* always: a host kernel cannot read VRAM, and the mapping is the one host address its bytes
|
||||
* already have. On the host backend the weights pool is host memory too, and a unit whose stored
|
||||
* form is not the container's (a widening or a relayout its host kernel asked for at load, or a
|
||||
* checkpoint served directly) has no place in the mapping that looks the way its kernel reads it,
|
||||
* so there it takes a converted copy in the weights pool like any other weight. One rule, for the
|
||||
* planner and the budget alike. */
|
||||
/* Whether a host-only unit stays in the container's mapping. On a card, always: a host kernel
|
||||
* cannot read VRAM. On the host backend the weights pool is host memory, so a unit whose stored
|
||||
* form differs from the container's (a load-time widening or relayout, or a checkpoint served
|
||||
* directly) takes a converted copy in the pool instead. Shared by the planner and the budget. */
|
||||
inline bool mapped_unit(bool host_only, bool direct, bool host_backend) {
|
||||
return host_only && (direct || !host_backend);
|
||||
}
|
||||
@@ -365,8 +295,8 @@ class Planner {
|
||||
public:
|
||||
explicit Planner(const PlannerInput& in) : in_(in) {}
|
||||
|
||||
/* Runs the whole plan. Returns RAD_OK, or a negative status with `out` still filled in far
|
||||
* enough to print -- a plan that does not fit is a plan the operator has to read. */
|
||||
/* Returns RAD_OK, or a negative status with `out` still filled in far enough to print the
|
||||
* report. */
|
||||
int plan(Plan* out);
|
||||
|
||||
private:
|
||||
@@ -375,11 +305,11 @@ private:
|
||||
/* Per-weight facts derived from declare, indexed by rad_weight. */
|
||||
std::vector<uint8_t> host_ok_; /* every op reading it resolved a RAD_DOMAIN_HOST kernel */
|
||||
std::vector<uint8_t> device_ok_; /* ...and a RAD_DOMAIN_DEVICE one. Cleared means the weight
|
||||
* can ONLY be read on the host, which is a decision and
|
||||
* not a preference -- see pin_mapped. */
|
||||
* can only be read on the host; see pin_mapped. */
|
||||
bool ssd_ = false; /* --weights-disk-tier was given */
|
||||
|
||||
void resolve_sites(const Program& prog);
|
||||
/* Whether every weight of the unit has a host kernel. */
|
||||
bool host_kernel(const MoveUnit& mu) const;
|
||||
void build_units(const Program& prog, Plan* p);
|
||||
void pin_mapped(const Program& prog, Plan* p);
|
||||
int pin_embedding(const Program& prog, const Config& cfg, Plan* p) const;
|
||||
@@ -393,55 +323,49 @@ private:
|
||||
void enforce_op_site_agreement(const Program& prog, Plan* p);
|
||||
void schedule_prefetch(Plan* p);
|
||||
void finish(const Program& prog, Plan* p);
|
||||
/* Fold one stranded unit into the aggregated list. Found-or-appended by (class, reason), so
|
||||
* the cost of reporting nine hundred stranded experts is one line and one counter. */
|
||||
/* Folds one stranded unit into the list aggregated by (class, reason). */
|
||||
void note_unfit(Plan* p, const MoveUnit& mu, const char* why) const;
|
||||
};
|
||||
|
||||
/* Bytes of a declared weight as THIS RANK will hold them: the stored size once the layout pass
|
||||
* has run, the logical size before it. Exposed because the mover and the report both need the
|
||||
* same answer and two spellings of it is how two components disagree about a budget. */
|
||||
/* Bytes of a declared weight as this rank holds them: the stored size once the layout pass has
|
||||
* run, the logical size before it. Shared so the mover and the report agree on budgets. */
|
||||
int64_t weight_bytes(const WeightInfo& w);
|
||||
|
||||
/* ------------------------------------------------------------------ what the weights would cost
|
||||
*
|
||||
* ONE RANK'S DECLARED WEIGHTS, SPLIT INTO THE PART THAT IS NOT NEGOTIABLE AND THE PART THAT IS.
|
||||
* One rank's declared weights, split into the fixed part and the elastic part. The VRAM budget
|
||||
* needs this before the planner runs. Static (non-expert) weights must be resident for the model
|
||||
* to run at a sensible speed, so they come off the top; only the expert plane trades against the
|
||||
* KV cache. A single combined total would let the cache demote attention projections to host.
|
||||
*
|
||||
* The VRAM budget needs this BEFORE the planner runs, because the two questions are asked in that
|
||||
* order: how much room is there, and only then what goes in it. And the split matters more than
|
||||
* the total. A model's static weights -- everything that is not an expert -- have to be resident
|
||||
* for the model to run at a sensible speed at all, so they come off the top; the expert plane is
|
||||
* the only thing that trades against the KV cache. Dividing the two together would let the cache's
|
||||
* side demote the attention projections to host memory to make room for blocks nothing will fill.
|
||||
* Values are per rank, which under tensor parallel is the shard: declare divides every dimension
|
||||
* per rank (spec §9).
|
||||
*
|
||||
* The three answers are per RANK, and under tensor parallel that is already the even split across
|
||||
* devices: declare runs once per rank with every dimension ALREADY DIVIDED (spec §9), so summing
|
||||
* this rank's declared weights is summing its shard.
|
||||
*
|
||||
* IT MUST AGREE WITH THE PLANNER AND THAT IS WHY IT LIVES HERE. The unit grouping, the alignment
|
||||
* accumulation and the mapped-tier rule are Planner::build_units', Planner::resolve_sites' and
|
||||
* Planner::pin_mapped's respectively; a second copy of any of them somewhere else would drift and
|
||||
* the failure would be a budget that overcommits the card by exactly the difference. */
|
||||
* It must agree with the planner, which is why it lives here: it shares the planner's site test
|
||||
* and repeats the unit grouping and alignment of Planner::build_units and the mapped-tier rule of
|
||||
* Planner::pin_mapped. Any drift overcommits the card by the difference. */
|
||||
struct WeightFootprint {
|
||||
int64_t statics = 0; /* non-expert and device-readable -- the floor under any budget */
|
||||
int64_t experts = 0; /* the elastic plane: what streams from host when it does not fit */
|
||||
int64_t expert_layer_max = 0; /* the most expert bytes any one routed layer holds */
|
||||
int64_t expert_unit_max = 0; /* the largest expert unit's slot */
|
||||
/* THE SLAB'S SPARE SLOTS beside the residents of an expert-tiered plan, at their most: per
|
||||
* expert slab class, the shadow slots and the staging ring and the tail pad
|
||||
* (Planner::assign_expert_tiered). They come out of the same weight budget as the residents. */
|
||||
/* Upper bound on an expert-tiered plan's spare slab: per expert slab class, the shadow slots,
|
||||
* staging ring and tail pad (Planner::assign_expert_tiered). Same weight budget as residents. */
|
||||
int64_t expert_spare = 0;
|
||||
int64_t layer_unit_max = 0; /* the widest per-layer unit's slot: the file tier's staging */
|
||||
bool routed = false; /* a layer has experts: the file tier's read windows */
|
||||
int64_t mapped = 0; /* no device kernel can read them; they never enter a pool at all */
|
||||
int64_t hosted = 0; /* --embedding-placement ram: in the pinned host pool, off the card */
|
||||
/* The tables the placement flags move, wherever the buckets above count them: `embedding`
|
||||
* is inside statics or hosted, `ngram` inside statics when a device kernel reads it and it is
|
||||
* placed in VRAM, inside mapped otherwise. `tower` is the encoder towers' units, every weight
|
||||
* of which the architecture declared read once per request, inside statics. */
|
||||
/* The tables the placement flags move, already counted in a bucket above: `embedding` in
|
||||
* statics or hosted; `ngram` in statics when a device kernel reads it and it is placed in
|
||||
* VRAM, else in mapped; `tower` (units the architecture declared read once per request) in
|
||||
* statics. */
|
||||
int64_t embedding = 0;
|
||||
int64_t ngram = 0;
|
||||
int64_t tower = 0;
|
||||
/* The part of `tower` that is also `embedding`: a tower's model-level table read once a
|
||||
* request and only by embed_lookup (Gemma 4's patch-position tables). See tower_pin_bytes. */
|
||||
int64_t tower_lookup = 0;
|
||||
/* A device kernel reads the n-gram table, so it can be on the card or read over the link from
|
||||
* pinned host memory; without one only the host gather reads it, from RAM or the container. */
|
||||
bool ngram_device = false;
|
||||
@@ -449,40 +373,43 @@ struct WeightFootprint {
|
||||
bool ngram_host = false;
|
||||
int64_t n_units = 0;
|
||||
};
|
||||
/* `embedding` is what the token embedding's placement resolved to; only Ram moves it out of the
|
||||
* statics. `ngram` is the n-gram table's; only Vram puts it among them, and only where a device
|
||||
* kernel reads it. `host_backend` and `container` are PlannerInput's: whether a host kernel can
|
||||
* read the weights pool, and whether the weights lie in a container at all (a checkpoint served
|
||||
* directly has no mapping a unit could stay in). Stated by every caller, so the budget and the
|
||||
* planner cannot count it differently. */
|
||||
/* `embedding` is the token embedding's resolved placement; only Ram moves it out of the statics.
|
||||
* `ngram` is the n-gram table's; only Vram puts it in the statics, and only where a device kernel
|
||||
* reads it. `host_backend` and `container` mean what they do in PlannerInput; every caller passes
|
||||
* them so the budget and the planner count alike. */
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram, bool host_backend, bool container);
|
||||
|
||||
/* THE PINNED STAGING THE FILE TIER TAKES OUT OF --host-pool-mib before any unit is placed in it:
|
||||
* RAD_PLACE_FILE_STAGE_SLOTS of the widest per-layer unit, and the read windows when a routed
|
||||
* layer can stream from the container. Planner::plan spends it; the budget counts it the same. */
|
||||
/* The bytes --vision-tower-placement ram moves off one rank's card. With the embedding in RAM,
|
||||
* pin_embedding pins the towers' lookup tables first and pin_towers skips them, so they count
|
||||
* once, with the embedding; a split that takes both `embedding` and `tower` out of the statics
|
||||
* comes up short by those tables. */
|
||||
inline int64_t tower_pin_bytes(const WeightFootprint& wf, TablePlacement embedding) {
|
||||
return embedding == TablePlacement::Ram ? wf.tower - wf.tower_lookup : wf.tower;
|
||||
}
|
||||
|
||||
/* Pinned staging the file tier takes out of --host-pool-mib before any unit is placed:
|
||||
* RAD_PLACE_FILE_STAGE_SLOTS of the widest per-layer unit, plus the read windows when a routed
|
||||
* layer can stream from the container. Shared by Planner::plan and the budget. */
|
||||
int64_t file_stage_reserve(int64_t widest, bool routed);
|
||||
|
||||
/* THE EXPERT BYTES THE CARD MUST HOLD when `host_room` bytes of the pinned host pool are free for
|
||||
* experts: everything the pool cannot take, the slab's spare slots beside them, and one unit of
|
||||
* first-fit slack on each side -- the resident fill and the pool fill each skip a unit that does
|
||||
* not fit and can leave up to one unit's room unspent. At most every expert and the spare slots.
|
||||
* A weight budget of the statics and this much places every expert in VRAM or the host pool. */
|
||||
/* Expert bytes the card must hold when `host_room` bytes of the pinned pool are free for experts:
|
||||
* what the pool cannot take, the spare slab slots, and one unit of first-fit slack on each side
|
||||
* (the resident fill and the pool fill can each leave up to one unit's room unspent). Capped at
|
||||
* all experts plus spares. A weight budget of statics plus this places every expert in VRAM or
|
||||
* the host pool. */
|
||||
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room);
|
||||
|
||||
/* THE PLAN AND ITS RANK'S WEIGHTS POOL READ ONE SPLIT. The planner places against
|
||||
* Plan::vram_budget and the mover fills the pool Pools::configure allocated, each from the Config
|
||||
* it was handed; a rank given two different Configs plans a slab the pool does not have, or leaves
|
||||
* part of the pool unplanned and empty, and nothing downstream would say so. RAD_E_STATE, naming
|
||||
* the rank and both sizes, when they differ. */
|
||||
/* Checks that the plan and this rank's weights pool used the same split: Plan::vram_budget must
|
||||
* equal the pool Pools::configure allocated, or the slab and the pool disagree silently. Returns
|
||||
* RAD_E_STATE, logging the rank and both sizes, when they differ. */
|
||||
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes);
|
||||
|
||||
/* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight
|
||||
* that at least one op reads and that only `embed_lookup` reads is a token embedding table, and
|
||||
* one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what
|
||||
* makes a tier below the card usable for it at all; a weight a GEMM also reads -- an output head
|
||||
* tied to the embedding -- would stream whole over the link every step, and is neither. One
|
||||
* definition, because the budget resolver and the planner must pick the same weights. */
|
||||
/* The tables the placement flags move, identified by their readers rather than by name: a
|
||||
* model-level weight read by at least one op, and only by `embed_lookup`, is a token embedding;
|
||||
* only by `embed_lookup_q`, an n-gram table. A lookup reads M rows a step, so a tier below the
|
||||
* card is usable; a weight a GEMM also reads (an output head tied to the embedding) would stream
|
||||
* whole every step and is neither. Shared by the budget resolver and the planner. */
|
||||
bool read_only_by(const Program& prog, rad_weight w, const char* op);
|
||||
inline bool is_embedding_table(const Program& prog, rad_weight w) {
|
||||
return read_only_by(prog, w, "embed_lookup");
|
||||
@@ -491,8 +418,8 @@ inline bool is_ngram_table(const Program& prog, rad_weight w) {
|
||||
return read_only_by(prog, w, "embed_lookup_q");
|
||||
}
|
||||
|
||||
/* "blk.12.ffn_gate_exps.3.weight" -> "blk.*.ffn_gate_exps.*.weight". The report's grouping key:
|
||||
* one line per weight class rather than per weight (spec §16). */
|
||||
/* "blk.12.ffn_gate_exps.3.weight" -> "blk.*.ffn_gate_exps.*.weight": the report's per-class
|
||||
* grouping key (spec §16). */
|
||||
std::string weight_class_key(const std::string& name);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -1,14 +1,10 @@
|
||||
/* residency_iface.h -- THE SEAM between placement and the run phase.
|
||||
/* residency_iface.h -- forwards the seam between placement and the run phase.
|
||||
*
|
||||
* core/runtime/ owns the declaration and this file only forwards to it. Placement does not keep a
|
||||
* copy: two declarations of a struct that crosses a component boundary is an ODR violation waiting
|
||||
* for the first translation unit that includes both, and the symptom would be a WeightSlot whose
|
||||
* fields the two components disagree about.
|
||||
*
|
||||
* The contract itself is documented where it is declared. Read core/runtime/residency.h -- in
|
||||
* particular the rule that begin_transfer and publish are the ONLY writers and that BOTH must bump
|
||||
* the generation, because the run phase memoises the stream wait per generation and installing a
|
||||
* new event at the old generation makes it skip the wait entirely.
|
||||
* core/runtime/residency.h owns the declarations; placement keeps no copy, since two definitions
|
||||
* of a struct that crosses a component boundary are an ODR violation. The contract is documented
|
||||
* there, notably: begin_transfer and publish are the only writers and both must bump the
|
||||
* generation, because the run phase memoises the stream wait per generation and a new event at
|
||||
* the old generation would skip the wait.
|
||||
*/
|
||||
#pragma once
|
||||
#include "runtime/residency.h"
|
||||
+141
-113
@@ -5,6 +5,34 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
/* The units `take` accepts, grouped by layer, in first-op order. Sets `*clash` to the first layer
|
||||
* whose span starts inside the one before it, or 0 when no spans interleave. */
|
||||
template <class Take>
|
||||
std::vector<StagedLayer> routed_layers(const Plan& plan, Take take, size_t* clash) {
|
||||
std::map<int32_t, StagedLayer> by_layer;
|
||||
for (size_t u = 0; u < plan.units.size(); ++u) {
|
||||
const MoveUnit& mu = plan.units[u];
|
||||
if (mu.layer < 0 || mu.first_use_op < 0 || mu.last_use_op < 0 || !take(mu)) continue;
|
||||
StagedLayer& L = by_layer[mu.layer];
|
||||
L.layer = mu.layer;
|
||||
L.units.push_back((int32_t)u);
|
||||
L.first_op = L.first_op < 0 ? mu.first_use_op : std::min(L.first_op, mu.first_use_op);
|
||||
L.last_op = std::max(L.last_op, mu.last_use_op);
|
||||
}
|
||||
std::vector<StagedLayer> out;
|
||||
for (auto& kv : by_layer) out.push_back(std::move(kv.second));
|
||||
std::sort(out.begin(), out.end(),
|
||||
[](const StagedLayer& a, const StagedLayer& b) { return a.first_op < b.first_op; });
|
||||
*clash = 0;
|
||||
for (size_t i = 1; i < out.size() && *clash == 0; ++i)
|
||||
if (out[i].first_op <= out[i - 1].last_op) *clash = i;
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
PrefillStager::~PrefillStager() {
|
||||
for (Place& p : place_) {
|
||||
if (p.done) rad_event_destroy(p.done);
|
||||
@@ -12,45 +40,33 @@ PrefillStager::~PrefillStager() {
|
||||
}
|
||||
for (RadEvent& g : gate_)
|
||||
if (g) rad_event_destroy(g);
|
||||
if (moved_t_) rad_event_destroy(moved_t_);
|
||||
if (moved_c_) rad_event_destroy(moved_c_);
|
||||
}
|
||||
|
||||
int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, char* region,
|
||||
int64_t bytes, int64_t min_rows) {
|
||||
char* low, int64_t bytes, int64_t min_rows) {
|
||||
layers_.clear();
|
||||
if (!mover || !region || bytes <= 0) return RAD_OK;
|
||||
|
||||
/* 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).
|
||||
* A declared draft head's layer, numbered past the trunk's, is not one (see the top of
|
||||
* stager.h). */
|
||||
/* A routed layer is its expert units; its op span is their declared uses. The first op must
|
||||
* find the copies; after the last (once the block's last pass of rows issued it) nothing reads
|
||||
* them. A draft head's layer, numbered past the trunk's, is excluded (see 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);
|
||||
L.first_op = L.first_op < 0 ? mu.first_use_op : std::min(L.first_op, mu.first_use_op);
|
||||
L.last_op = std::max(L.last_op, mu.last_use_op);
|
||||
}
|
||||
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; });
|
||||
size_t c = 0;
|
||||
layers_ = routed_layers(
|
||||
plan, [&](const MoveUnit& mu) { return mu.expert >= 0 && mu.layer < trunk; }, &c);
|
||||
/* 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 "
|
||||
"and %d..%d); staging is off", layers_[i - 1].layer, layers_[i].layer,
|
||||
layers_[i - 1].first_op, layers_[i - 1].last_op, layers_[i].first_op,
|
||||
layers_[i].last_op);
|
||||
layers_.clear();
|
||||
return RAD_OK;
|
||||
}
|
||||
if (c > 0) {
|
||||
RAD_WARN("prefill staging: routed layers %d and %d are read by interleaved ops (%d..%d "
|
||||
"and %d..%d); staging is off", layers_[c - 1].layer, layers_[c].layer,
|
||||
layers_[c - 1].first_op, layers_[c - 1].last_op, layers_[c].first_op,
|
||||
layers_[c].last_op);
|
||||
layers_.clear();
|
||||
return RAD_OK;
|
||||
}
|
||||
if (layers_.empty()) return RAD_OK;
|
||||
|
||||
first_of_.assign(prog.ops.size(), -1);
|
||||
@@ -62,6 +78,10 @@ int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, cha
|
||||
|
||||
mover_ = mover;
|
||||
region_ = region;
|
||||
low_ = low ? low : region;
|
||||
base_ = region;
|
||||
want_ = nullptr;
|
||||
rebase_ = false;
|
||||
ring_ = bytes / 2 / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT * 2;
|
||||
head_ = 0;
|
||||
min_rows_ = min_rows;
|
||||
@@ -83,22 +103,33 @@ int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, cha
|
||||
}
|
||||
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. */
|
||||
/* The move's two waits, only where the ring has a second place to move to (rebase). */
|
||||
if (low_ != region_ &&
|
||||
((!moved_t_ && rad_event_create_local(&moved_t_) < 0) ||
|
||||
(!moved_c_ && rad_event_create_local(&moved_c_) < 0))) {
|
||||
layers_.clear();
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
/* An empty list makes the backend open the card's DMA queue now, at bring-up, rather than in
|
||||
* 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. */
|
||||
/* Arms only for a trunk pass whose level has a ring and with at least min_rows tokens (see
|
||||
* stager.h). Layers the previous pass staged early are kept if it arms with the ring where they
|
||||
* are, and withdrawn if not. */
|
||||
bool PrefillStager::begin_pass(const RadBatch* b) {
|
||||
if (!b || b->draft_pass != 0) return false;
|
||||
armed_ = full_ && enabled() && b->n_tok >= min_rows_;
|
||||
armed_ = want_ != nullptr && enabled() && b->n_tok >= min_rows_;
|
||||
staged_ = armed_;
|
||||
if (!armed_) {
|
||||
withdraw_early();
|
||||
return false;
|
||||
}
|
||||
if (want_ != base_) {
|
||||
withdraw_early();
|
||||
rebase_ = true;
|
||||
}
|
||||
first_op_ = true;
|
||||
next_ = 0;
|
||||
first_li_ = -1;
|
||||
@@ -106,8 +137,7 @@ bool PrefillStager::begin_pass(const RadBatch* b) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* Withdraw the early layers' copies. Nothing has read them, so there is no `free` to record. */
|
||||
void PrefillStager::withdraw_early() {
|
||||
for (int32_t i : ring_order_) {
|
||||
Place& p = place_[i];
|
||||
@@ -116,17 +146,17 @@ void PrefillStager::withdraw_early() {
|
||||
n_early_ = 0;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* The host half of giving a place back: its units are published at their pool slots again, for
|
||||
* the next residency sync. 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. */
|
||||
/* The oldest place leaves the ring; the mover's stream waits on its last reader, so later copies
|
||||
* into it are ordered behind that read. */
|
||||
int PrefillStager::recycle_front() {
|
||||
const int32_t i = ring_order_.front();
|
||||
Place& p = place_[i];
|
||||
@@ -138,10 +168,27 @@ int PrefillStager::recycle_front() {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* Moves the ring (see stager.h) at the first op of a pass whose ring is not where the last armed
|
||||
* pass left it. Nothing in it is published any more (begin_pass withdrew it), so it starts over,
|
||||
* empty, at its new place. Either place is the other level's buffers, hence two waits: the compute
|
||||
* stream does not reach the new step before the copies still going into the old place land, and
|
||||
* the first copy into the new place waits for the compute work already queued, which used it. */
|
||||
int PrefillStager::rebase(RadStream s) {
|
||||
rebase_ = false;
|
||||
const RadStream t = mover_->transfer_stream();
|
||||
RAD_TRY(rad_event_record(moved_t_, t));
|
||||
RAD_TRY(rad_event_wait(s, moved_t_));
|
||||
RAD_TRY(rad_event_record(moved_c_, s));
|
||||
RAD_TRY(rad_event_wait(t, moved_c_));
|
||||
while (!ring_order_.empty()) RAD_TRY(recycle_front());
|
||||
head_ = 0;
|
||||
base_ = want_;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A place of `want` bytes at the head of the ring or, with `partial`, all the room the head can
|
||||
* reach when `want` does not fit. The head may only overwrite retired places: it stays within one
|
||||
* ring of the oldest place still published. *out is -1 when nothing fits. */
|
||||
int PrefillStager::take(int64_t want, bool partial, int32_t* out) {
|
||||
*out = -1;
|
||||
int64_t limit = head_ + ring_;
|
||||
@@ -151,8 +198,8 @@ int PrefillStager::take(int64_t want, bool partial, int32_t* out) {
|
||||
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. */
|
||||
/* Every place the new one laps leaves the ring first; then, if the table is full, the oldest
|
||||
* retired ones (their waits are on 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)
|
||||
@@ -167,11 +214,10 @@ int PrefillStager::take(int64_t want, bool partial, int32_t* out) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* Stage one layer into the ring, behind `gate` when not null. The layer the run reaches next
|
||||
* (`now`) takes whatever room there is up to its need; any other goes only whole and within half
|
||||
* the ring, so the next layer always has at least half the ring. *got is kStaged, kNone when
|
||||
* nothing of the layer is pooled, or kLater when the ring has no room yet. */
|
||||
int PrefillStager::stage_layer(int32_t li, bool now, RadEvent gate, int* got) {
|
||||
*got = kLater;
|
||||
const Layer& L = layers_[(size_t)li];
|
||||
@@ -179,8 +225,8 @@ int PrefillStager::stage_layer(int32_t li, bool now, RadEvent gate, int* got) {
|
||||
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. */
|
||||
/* A place that wraps past the region's end is two stretches, and the first may end with less
|
||||
* room than a unit, so it asks for one unit extra. */
|
||||
const int64_t want = head_ % ring_ + need > ring_ ? need + unit : need;
|
||||
int32_t i = -1;
|
||||
RAD_TRY(take(want, now, &i));
|
||||
@@ -188,10 +234,10 @@ int PrefillStager::stage_layer(int32_t li, bool now, RadEvent gate, int* got) {
|
||||
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. */
|
||||
/* A wrapping place continues at the region's 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) } };
|
||||
Mover::StageSpan sp[2] = { { base_ + off, std::min(len, ring_ - off) },
|
||||
{ base_, 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;
|
||||
@@ -205,9 +251,9 @@ int PrefillStager::stage_layer(int32_t li, bool now, RadEvent gate, int* got) {
|
||||
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. */
|
||||
/* Stage the layers after `cur` as far as the pace and the ring allow. A layer with nothing pooled
|
||||
* is skipped; one without room 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;
|
||||
@@ -228,11 +274,11 @@ int PrefillStager::stage_ahead(int32_t cur, bool* resync) {
|
||||
int PrefillStager::before_op(rad_op h, RadStream s, bool* resync) {
|
||||
*resync = false;
|
||||
|
||||
/* 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. */
|
||||
/* At the pass's first op of any kind, stage its first routed layer and the ones after it as
|
||||
* far as the pace and ring allow. Layers the previous pass staged early are adopted here. */
|
||||
if (first_op_) {
|
||||
first_op_ = false;
|
||||
if (rebase_) RAD_TRY(rebase(s));
|
||||
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()) {
|
||||
@@ -251,23 +297,22 @@ int PrefillStager::before_op(rad_op h, RadStream s, bool* 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;
|
||||
/* The run's arrival at this layer, which the copies kLead layers on are paced by. */
|
||||
/* The run's arrival at this layer paces the copies kLead layers on. */
|
||||
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. */
|
||||
/* This layer's copies were published when issued; this one wait 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. */
|
||||
/* Earlier layers are done: every pass of rows issued their last op and recorded `free`, and
|
||||
* layers do not interleave. They are retired here, not at their last op, which may repeat for
|
||||
* another pass of rows. */
|
||||
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. */
|
||||
/* Stage further ahead into the freed room. */
|
||||
if (next_ <= li) next_ = li + 1;
|
||||
const bool was = *resync;
|
||||
RAD_TRY(stage_ahead(li, resync));
|
||||
@@ -275,9 +320,9 @@ int PrefillStager::before_op(rad_op h, RadStream s, bool* resync) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
/* A layer's last op: record `free` behind it so a lapping copy can start as early as possible.
|
||||
* The op may repeat for another pass of rows, moving `free` again, which is why the copies are
|
||||
* retired only when 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];
|
||||
@@ -292,9 +337,9 @@ int PrefillStager::after_op(rad_op h, RadStream s) {
|
||||
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. */
|
||||
/* Retire everything this pass staged. Then, when the next step continues a prompt, stage its
|
||||
* trunk pass's first layers, layer k paced on this pass's layer n - kLead + k, as if the two
|
||||
* passes were one. */
|
||||
int PrefillStager::end_pass(RadStream s) {
|
||||
if (!armed_) return RAD_OK;
|
||||
armed_ = false;
|
||||
@@ -332,33 +377,22 @@ int FileStager::init(const Program& prog, const Plan& plan, Mover* mover) {
|
||||
layers_.clear();
|
||||
if (!mover) return RAD_OK;
|
||||
|
||||
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.tier != Tier::SSD || mu.access != RAD_ACCESS_CONDITIONAL || mu.layer < 0) continue;
|
||||
if (mu.first_use_op < 0 || mu.last_use_op < 0) continue; /* declared and never read */
|
||||
Layer& L = by_layer[mu.layer];
|
||||
L.layer = mu.layer;
|
||||
L.units.push_back((int32_t)u);
|
||||
L.first_op = L.first_op < 0 ? mu.first_use_op : std::min(L.first_op, mu.first_use_op);
|
||||
L.last_op = std::max(L.last_op, mu.last_use_op);
|
||||
}
|
||||
for (auto& kv : by_layer) layers_.push_back(std::move(kv.second));
|
||||
/* A unit declared and never read has no op span and is left out. */
|
||||
size_t c = 0;
|
||||
layers_ = routed_layers(plan, [](const MoveUnit& mu) {
|
||||
return mu.tier == Tier::SSD && mu.access == RAD_ACCESS_CONDITIONAL;
|
||||
}, &c);
|
||||
if (layers_.empty()) return RAD_OK;
|
||||
std::sort(layers_.begin(), layers_.end(),
|
||||
[](const Layer& a, const Layer& b) { return a.first_op < b.first_op; });
|
||||
/* A layer's copies stay published until the next one starts, so two layers whose ops
|
||||
* interleave would need both buffers at once and a third for the read ahead. That is a plugin
|
||||
* shape this tier cannot serve, and a file-tier unit has no address to fall back on. */
|
||||
for (size_t i = 1; i < layers_.size(); ++i)
|
||||
if (layers_[i].first_op <= layers_[i - 1].last_op) {
|
||||
RAD_ERR("file stager: routed layers %d and %d are read by interleaved ops (%d..%d and "
|
||||
"%d..%d), and a routed layer read from the container is published one layer "
|
||||
"at a time", layers_[i - 1].layer, layers_[i].layer, layers_[i - 1].first_op,
|
||||
layers_[i - 1].last_op, layers_[i].first_op, layers_[i].last_op);
|
||||
layers_.clear();
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* A layer's copies stay published until the next one starts, so interleaved layers would need
|
||||
* a third buffer for the read-ahead; with no fallback address, such a plan is refused. */
|
||||
if (c > 0) {
|
||||
RAD_ERR("file stager: routed layers %d and %d are read by interleaved ops (%d..%d and "
|
||||
"%d..%d), and a routed layer read from the container is published one layer at a "
|
||||
"time", layers_[c - 1].layer, layers_[c].layer, layers_[c - 1].first_op,
|
||||
layers_[c - 1].last_op, layers_[c].first_op, layers_[c].last_op);
|
||||
layers_.clear();
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
buf_[0] = mover->file_buffer(0);
|
||||
buf_[1] = mover->file_buffer(1);
|
||||
@@ -382,8 +416,8 @@ int FileStager::init(const Program& prog, const Plan& plan, Mover* mover) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* EVERY PASS: there is no other address for a file-tier unit, so a pass the stager sat out would
|
||||
* reach its first routed layer with null expert pointers. */
|
||||
/* Arms for every pass: a file-tier unit has no other address, so an unarmed pass would reach its
|
||||
* first routed layer with null expert pointers. */
|
||||
bool FileStager::begin_pass(const RadBatch* b) {
|
||||
armed_ = enabled() && b;
|
||||
if (!armed_) return false;
|
||||
@@ -424,7 +458,7 @@ int FileStager::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, read at its first op of any kind. */
|
||||
/* Read the pass's first routed layer at its first op of any kind. */
|
||||
if (first_op_) {
|
||||
first_op_ = false;
|
||||
const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h,
|
||||
@@ -445,7 +479,7 @@ int FileStager::before_op(rad_op h, RadStream s, bool* resync) {
|
||||
/* Entering layer `li`: the layer before is behind every op issued so far on this stream. */
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (holds_[b] >= 0 && holds_[b] != li) { RAD_TRY(finish(b, s)); *resync = true; }
|
||||
/* A layer the read-ahead skipped -- the learned bound said this pass ends before it -- is read
|
||||
/* A layer the read-ahead skipped (the learned bound said the pass ends before it) is read
|
||||
* here rather than issued without addresses. */
|
||||
if (holds_[li & 1] != li) {
|
||||
RAD_TRY(start(li));
|
||||
@@ -462,12 +496,6 @@ int FileStager::before_op(rad_op h, RadStream s, bool* resync) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int FileStager::after_op(rad_op h, RadStream s) {
|
||||
(void)h;
|
||||
(void)s;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int FileStager::end_pass(RadStream s) {
|
||||
if (!armed_) return RAD_OK;
|
||||
armed_ = false;
|
||||
|
||||
+129
-127
@@ -1,90 +1,85 @@
|
||||
/* 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 -------------------------------------------------------------------
|
||||
* ---- why prefill needs it ---------------------------------------------------------------------
|
||||
*
|
||||
* An expert the slab has no room for lives in the pinned host pool, and a GEMM that routes to it
|
||||
* reads it across the link in place (Site::DeviceZeroCopy). At decode that is the right trade: a
|
||||
* step routes a few dozen rows to a few dozen experts and reads a few of them from the host. A
|
||||
* prefill chunk routes tens of thousands of rows to nearly EVERY expert of every layer, so the
|
||||
* whole pooled part of each layer -- ~85 MB a card on Qwen3.8-Flash-Next -- crosses the link inside
|
||||
* the layer's two GEMMs, at the link's rate and on the critical path, while the rest of the layer's
|
||||
* 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.
|
||||
* reads it across the link in place (Site::DeviceZeroCopy). That suits decode, which reads a few
|
||||
* experts per step from the host. A prefill chunk routes to nearly every expert of every layer, so
|
||||
* each layer's whole pooled part (~85 MB per card on Qwen3.8-Flash-Next) crosses the link inside
|
||||
* its two GEMMs, on the critical path, while the rest of the layer leaves the link idle. With
|
||||
* r4d_selftest --perfmoe, a 2048-token gate_up GEMM takes 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 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.
|
||||
* So for large enough steps the stager copies the pooled experts of the layers ahead into a VRAM
|
||||
* ring while earlier layers run, publishes the copies for each layer's ops, and publishes the host
|
||||
* addresses again once those ops are issued. The bytes are the same, so output is bit-identical.
|
||||
*
|
||||
* ---- WHERE THE RING IS, AND WHEN IT IS ITS ---------------------------------------------------
|
||||
* ---- the region --------------------------------------------------------------------------------
|
||||
*
|
||||
* 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).
|
||||
* One region, 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 belongs to the stager
|
||||
* only in full-plan steps (the ones worth staging for). The scheduler says which, per pass
|
||||
* (set_ring).
|
||||
*
|
||||
* ---- WHY A RING AND NOT TWO BUFFERS ------------------------------------------------------------
|
||||
* Under --prefill-span the ring has a second place. The full plan is sized for a spanned step,
|
||||
* and a step of one interval (a chunk that shares its step, a short prompt) runs at the level of
|
||||
* that size (Engine::probe_arena_levels). That level keeps the ring right above its own buffers,
|
||||
* so everything over it, the span's extra rows included, is lent to the slab while such steps
|
||||
* run, and the step is still staged. A pass whose ring is in the other place than the last one's
|
||||
* moves it first (rebase).
|
||||
*
|
||||
* 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.
|
||||
* ---- why a ring, not two buffers ---------------------------------------------------------------
|
||||
*
|
||||
* ---- THE ORDER, AND WHAT KEEPS IT SAFE ---------------------------------------------------------
|
||||
* Layers leave unequal 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 fixed buffers,
|
||||
* a light layer's copy finishes early and the engine idles, and a heavy layer's copy delays every
|
||||
* layer after it. The ring packs each layer at its own size, so copies run ahead through light
|
||||
* layers and heavy ones start early. A layer staged beyond the next one takes at most half the
|
||||
* ring, so the next layer always has the room two buffers would give it.
|
||||
*
|
||||
* ---- order and safety --------------------------------------------------------------------------
|
||||
*
|
||||
* 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 first op wait on its copies; publish the host addresses of earlier layers
|
||||
* again; stage further layers into the freed room
|
||||
* 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
|
||||
* the pass's end the same for anything still staged; and, when the next step continues
|
||||
* a prompt, stage the first layers of its trunk pass
|
||||
*
|
||||
* 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's place in the ring is counted in bytes handed out since bring-up, so a copy finds the
|
||||
* places it overwrites from the count alone. Before a copy is issued, the mover's stream waits on
|
||||
* the "free" event of every earlier place it laps (recorded behind that place's last reader, in
|
||||
* this pass or an earlier one). The layer's ops wait on the copies' event through one stream wait
|
||||
* before its first op: copies are published settled (see Mover::stage_units), and only the
|
||||
* layer's own ops resolve them.
|
||||
*
|
||||
* ---- HOW FAR AHEAD ----------------------------------------------------------------------------
|
||||
* ---- 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.
|
||||
* A layer's copies are released once the compute stream reaches the MoE of the layer kLead before
|
||||
* it (an event recorded at that layer's first op), not as soon as the ring has room: copies that
|
||||
* land long before use slow the layers they overlap. On Qwen3.8-Flash-Next TP2, unpaced copies
|
||||
* cost a 26K-token prompt 0.6% and one layer ahead cost a 160K-token prompt 2.4% (its heavy late
|
||||
* layers waited); three ahead covered the late layers at the least cost to short prompts.
|
||||
*
|
||||
* ---- THE NEXT STEP'S FIRST LAYERS -------------------------------------------------------------
|
||||
* ---- 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.
|
||||
* A step carrying a prompt chunk is issued only after the previous step is read back, so its first
|
||||
* layer would otherwise wait for all its own copies. When the next step continues a prompt
|
||||
* (set_next_prefill), this pass's end stages the next trunk pass's first layers, paced on this
|
||||
* pass's last layers as if the passes were one, and publishes them at once. The next trunk pass
|
||||
* adopts them when armed; an unarmed trunk pass publishes their host addresses again in
|
||||
* begin_pass, which the run phase calls before updating the weight tables. A draft pass in
|
||||
* between reads none of the trunk's layers and leaves them.
|
||||
*
|
||||
* ---- ONLY THE TRUNK ---------------------------------------------------------------------------
|
||||
* ---- trunk only --------------------------------------------------------------------------------
|
||||
*
|
||||
* 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.
|
||||
* A draft head's routed layer is not staged. The head runs in its own passes; over a prefill chunk
|
||||
* (the history pass) it needs its experts only on a prompt's last chunk, for the few rows that
|
||||
* draft, so its pooled experts are read in place as at decode. The head's layer is numbered past
|
||||
* the trunk's (RadModelMeta::n_layers) and left out at bring-up; a draft pass is never armed.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../runtime/stager.h"
|
||||
@@ -97,32 +92,44 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* One routed layer a stager serves: its units and the span of ops that read them. */
|
||||
struct StagedLayer {
|
||||
int32_t layer = -1;
|
||||
std::vector<int32_t> units;
|
||||
int32_t first_op = -1, last_op = -1;
|
||||
};
|
||||
|
||||
class PrefillStager final : public OpStager {
|
||||
public:
|
||||
~PrefillStager() override;
|
||||
|
||||
/* The routed layers of `plan` and the ops that read them, and `bytes` of device memory at
|
||||
* `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);
|
||||
/* Binds the routed layers of `plan` and the ops that read them, with `bytes` of device memory
|
||||
* at `region` as the ring -- or at `low`, the ring's place under the span's shared level, when
|
||||
* there is one (null otherwise). `min_rows` is the smallest pass it arms for. Leaves enabled()
|
||||
* false when no routed layer has a pooled unit to stage. */
|
||||
int init(const Program& prog, const Plan& plan, Mover* mover, char* region, char* low,
|
||||
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 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. */
|
||||
/* Per pass, before release: where the ring is for the step -- the region at the full plan,
|
||||
* `low` at the span's shared level -- or null when the step's level lends both. */
|
||||
void set_ring(char* base) { want_ = base; }
|
||||
/* The ring's two places: at the full plan, and at the span's shared level (the same one when
|
||||
* there is no such level). */
|
||||
char* ring_full() const { return region_; }
|
||||
char* ring_low() const { return low_; }
|
||||
/* Per step, before release: whether the next step continues 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 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). */
|
||||
/* The smallest pass, in tokens, the stager arms for; smaller steps read pooled experts in
|
||||
* place. 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. */
|
||||
/* Whether the last trunk pass armed (copied its pooled experts through the ring). A draft
|
||||
* pass leaves it unchanged. */
|
||||
bool staged() const { return staged_; }
|
||||
static constexpr int32_t lead() { return kLead; }
|
||||
|
||||
@@ -132,17 +139,13 @@ public:
|
||||
int end_pass(RadStream s) override;
|
||||
|
||||
private:
|
||||
struct Layer {
|
||||
int32_t layer = -1;
|
||||
std::vector<int32_t> units;
|
||||
int32_t first_op = -1, last_op = -1;
|
||||
};
|
||||
using Layer = StagedLayer;
|
||||
std::vector<Layer> layers_; /* the routed layers, in first-op order */
|
||||
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. */
|
||||
/* One layer's place in the ring. [beg, end) is in bytes handed out since bring-up; the region
|
||||
* offset 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;
|
||||
@@ -150,15 +153,15 @@ private:
|
||||
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. */
|
||||
* longer than the MoE block's pass of rows issues a layer's ops once per pass, so the last
|
||||
* op can repeat: each repeat moves `free` behind itself, and the copies are published away
|
||||
* only at the next layer's first op. */
|
||||
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. */
|
||||
/* More places than a two-share ring can hold at the smallest per-layer share; a full table
|
||||
* only stops copies running 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 */
|
||||
@@ -166,22 +169,27 @@ private:
|
||||
|
||||
Mover* mover_ = nullptr;
|
||||
char* region_ = nullptr;
|
||||
char* low_ = nullptr; /* the ring's place at the span's shared level, or null */
|
||||
char* base_ = nullptr; /* where the places in the ring are */
|
||||
char* want_ = nullptr; /* where this pass wants it (set_ring) */
|
||||
bool rebase_ = false; /* the pass moves the ring before its first copy */
|
||||
RadEvent moved_t_ = nullptr; /* the move's two waits: behind the mover's stream, */
|
||||
RadEvent moved_c_ = nullptr; /* and behind the compute stream */
|
||||
int64_t ring_ = 0;
|
||||
int64_t head_ = 0; /* bytes handed out since bring-up */
|
||||
int64_t min_rows_ = 0;
|
||||
|
||||
/* 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. */
|
||||
/* The pace (see the file header): layer k's copies wait on the compute-stream event recorded
|
||||
* at the first op of layer k - kLead. A layer within kLead of the pass's first routed layer
|
||||
* 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;
|
||||
/* armed_ as the last trunk pass's begin_pass set it, which end_pass leaves alone: the engine
|
||||
/* armed_ as the last trunk pass's begin_pass set it; end_pass leaves it, since the engine
|
||||
* asks after the pass has ended. */
|
||||
bool staged_ = false;
|
||||
bool next_prefill_ = false;
|
||||
@@ -196,45 +204,44 @@ private:
|
||||
void withdraw_early();
|
||||
int take(int64_t want, bool partial, int32_t* out);
|
||||
int recycle_front();
|
||||
int rebase(RadStream s);
|
||||
void retire(Place& p);
|
||||
};
|
||||
|
||||
/* ---- THE FILE STAGER: routed layers read from the container -------------------------------------
|
||||
/* ---- the file stager: routed layers read from the container -------------------------------------
|
||||
*
|
||||
* A routed unit the plan put on the file tier (--weights-disk-tier) has no address of its own, and
|
||||
* a grouped GEMM is handed every expert's pointer at issue. So on EVERY pass -- a decode step as
|
||||
* much as a prefill chunk -- each routed layer's file-tier units are read into one of the mover's
|
||||
* two file buffers before the layer's first expert op and published there, and published as null
|
||||
* again when the next routed layer starts. Which experts the router picks cannot be known on the
|
||||
* host without a round trip, so the whole layer's file-tier part is read; a prefill chunk routes to
|
||||
* nearly all of it anyway, and a decode step is paced by the drive -- the trade the flag names.
|
||||
* A routed unit on the file tier (--weights-disk-tier) has no address of its own, and a grouped
|
||||
* GEMM is handed every expert's pointer at issue. So on every pass, decode included, each routed
|
||||
* layer's file-tier units are read into one of the mover's two file buffers before the layer's
|
||||
* first expert op and published there, then published as null when the next routed layer starts.
|
||||
* The router's picks are not known on the host without a round trip, so the layer's whole
|
||||
* file-tier part is read; decode is then paced by the drive, which is the trade the flag makes.
|
||||
*
|
||||
* the pass's first op read the first routed layer the pass issues
|
||||
* a layer's first op release the layer before (record its buffer free on the stream, publish
|
||||
* null), wait on this layer's copies, and read the NEXT layer into the
|
||||
* null), wait on this layer's copies, and read the next layer into the
|
||||
* buffer just released -- its copies queue behind that free event
|
||||
* the pass's end release whatever is still held
|
||||
*
|
||||
* A LAYER IS RELEASED WHEN THE NEXT ONE STARTS, not at its own last op: a routed block that slices a
|
||||
* large step into passes of `rows` tokens issues its expert ops once a slice, so the last declared
|
||||
* op of the layer comes round again, and a release there would leave the second slice reading null.
|
||||
* Repeats of the current layer's first op do nothing.
|
||||
* A layer is released when the next one starts, not at its own last op: a routed block that slices
|
||||
* a large step into passes of `rows` tokens issues its expert ops once per slice, so a release at
|
||||
* the last op would leave the next slice reading null. Repeats of the current layer's first op do
|
||||
* nothing.
|
||||
*
|
||||
* THE READ IS ON THE ISSUING THREAD and blocks it; the card meanwhile runs whatever was issued
|
||||
* before it. A routed layer's file-tier part is gigabytes and its compute milliseconds, so the step
|
||||
* is the drive's either way, and a reader thread would buy the few percent the layer's own compute
|
||||
* is worth at the cost of a second writer of the residency table.
|
||||
* The read blocks the issuing thread while the card runs what was issued before it. A layer's
|
||||
* file-tier part is gigabytes against milliseconds of compute, so the step is drive-bound either
|
||||
* way; a reader thread would gain little and add a second writer of the residency table.
|
||||
*
|
||||
* A layer is read ahead only when the pass will issue it -- the same learned bound PrefillStager
|
||||
* keeps (by draft_pass), so a trunk pass does not read the MTP head's layer for nothing. */
|
||||
* A layer is read ahead only when the pass will issue it (a bound learned per draft_pass from the
|
||||
* last pass of that kind), so a trunk pass does not read the MTP head's layer. */
|
||||
class FileStager final : public OpStager {
|
||||
public:
|
||||
~FileStager() override;
|
||||
|
||||
/* The routed layers of `plan` that hold a unit on the file tier and the ops that read them,
|
||||
* over the mover's two file buffers. Leaves it disabled -- enabled() false -- when the plan
|
||||
* puts no routed unit there; refuses a plan whose routed layers are read by interleaved ops,
|
||||
* because a file-tier unit has no other address to fall back on. */
|
||||
/* Binds the routed layers with file-tier units and the ops that read them, over the mover's
|
||||
* two file buffers. Leaves enabled() false when no routed unit is on the file tier. Refuses a
|
||||
* plan whose routed layers are read by interleaved ops, since a file-tier unit has no other
|
||||
* address to fall back on. */
|
||||
int init(const Program& prog, const Plan& plan, Mover* mover);
|
||||
|
||||
bool enabled() const { return !layers_.empty(); }
|
||||
@@ -243,15 +250,10 @@ public:
|
||||
|
||||
bool begin_pass(const RadBatch* b) override;
|
||||
int before_op(rad_op h, RadStream s, bool* resync) override;
|
||||
int after_op(rad_op h, RadStream s) override;
|
||||
int end_pass(RadStream s) override;
|
||||
|
||||
private:
|
||||
struct Layer {
|
||||
int32_t layer = -1;
|
||||
std::vector<int32_t> units;
|
||||
int32_t first_op = -1, last_op = -1;
|
||||
};
|
||||
using Layer = StagedLayer;
|
||||
std::vector<Layer> layers_; /* the routed layers with file-tier units, in first-op order */
|
||||
std::vector<int32_t> first_of_; /* by op: the layer whose first op it is, or -1 */
|
||||
|
||||
@@ -269,7 +271,7 @@ private:
|
||||
bool first_op_ = false;
|
||||
int32_t pass_kind_ = 0;
|
||||
int32_t last_issued_ = -1;
|
||||
std::map<int32_t, int32_t> pass_last_;
|
||||
std::map<int32_t, int32_t> pass_last_; /* by draft_pass: the last op such a pass issued */
|
||||
|
||||
bool will_issue(int32_t li) const;
|
||||
int start(int32_t li);
|
||||
|
||||
Reference in new issue
Block a user