Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
@@ -0,0 +1,627 @@
|
||||
/* heat.cpp -- the heat engine's mechanics. See heat.h for why any of it is shaped this way. */
|
||||
#include "heat.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
/* The width of one observe() block: a layer's run of positions is a whole number of these, so
|
||||
* every block has the same trip count and the compiler vectorizes it with no scalar remainder. */
|
||||
constexpr int32_t kLanes = 16;
|
||||
/* What the movable units with no layer are padded to. */
|
||||
constexpr int32_t kBlock = 64;
|
||||
} /* namespace */
|
||||
|
||||
int HeatEngine::init(const Plan& plan, const HeatParams& params) {
|
||||
params_ = params;
|
||||
stats_ = HeatStats{};
|
||||
|
||||
const size_t n = plan.units.size();
|
||||
tier_.assign(n, Tier::VRAM);
|
||||
busy_.assign(n, 0u);
|
||||
movable_.assign(n, 0u);
|
||||
layer_of_.assign(n, -1);
|
||||
bytes_.assign(n, 0);
|
||||
ever_.assign(n, 0u);
|
||||
|
||||
/* The movable units' slab classes, as dense indices -- see heat.h's `cls_`. */
|
||||
cls_.assign(n, -1);
|
||||
{
|
||||
std::vector<int32_t> dense;
|
||||
for (size_t u = 0; u < n; ++u) {
|
||||
const MoveUnit& mu = plan.units[u];
|
||||
if (!mu.movable) continue;
|
||||
const int32_t k = mu.slab_class;
|
||||
auto it = std::find(dense.begin(), dense.end(), k);
|
||||
if (it == dense.end()) { dense.push_back(k); it = dense.end() - 1; }
|
||||
cls_[u] = (int32_t)(it - dense.begin());
|
||||
}
|
||||
n_cls_ = dense.empty() ? 1 : (int32_t)dense.size();
|
||||
}
|
||||
n_hot_.assign((size_t)n_cls_, 0);
|
||||
n_cold_.assign((size_t)n_cls_, 0);
|
||||
m_of_.assign((size_t)n_cls_, 0);
|
||||
|
||||
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. */
|
||||
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;
|
||||
for (size_t u = 0; u < n; ++u) {
|
||||
const MoveUnit& mu = plan.units[u];
|
||||
tier_[u] = mu.tier;
|
||||
layer_of_[u] = mu.layer;
|
||||
bytes_[u] = mu.bytes;
|
||||
movable_[u] = mu.movable ? 1u : 0u;
|
||||
if (mu.movable) ++movable;
|
||||
if (mu.layer < 0) {
|
||||
if (mu.movable) other[(size_t)n_layer_].push_back((int32_t)u);
|
||||
continue;
|
||||
}
|
||||
if (mu.tier == Tier::VRAM) ++res_count_[(size_t)mu.layer];
|
||||
if (mu.expert >= 0) {
|
||||
auto& row = by_expert[(size_t)mu.layer];
|
||||
if ((size_t)mu.expert >= row.size()) row.resize((size_t)mu.expert + 1, -1);
|
||||
const int32_t was = row[(size_t)mu.expert];
|
||||
if (was >= 0 && movable_[(size_t)was]) other[(size_t)mu.layer].push_back(was);
|
||||
row[(size_t)mu.expert] = (int32_t)u;
|
||||
} else if (mu.movable) {
|
||||
other[(size_t)mu.layer].push_back((int32_t)u);
|
||||
}
|
||||
}
|
||||
|
||||
pos_.assign(n, -1);
|
||||
unit_at_.clear();
|
||||
unit_at_.reserve(n + (size_t)(n_layer_ + 1) * kLanes + kBlock);
|
||||
n_ex_.assign((size_t)n_layer_, 0);
|
||||
slot_lo_.assign((size_t)n_layer_ + 2, 0);
|
||||
auto place = [&](int32_t u) {
|
||||
if (u >= 0) pos_[(size_t)u] = (int32_t)unit_at_.size();
|
||||
unit_at_.push_back(u);
|
||||
};
|
||||
for (size_t s = 0; s <= (size_t)n_layer_; ++s) {
|
||||
slot_lo_[s] = (int32_t)unit_at_.size();
|
||||
if (s < (size_t)n_layer_) {
|
||||
for (int32_t u : by_expert[s]) place(u);
|
||||
n_ex_[s] = (int32_t)by_expert[s].size();
|
||||
}
|
||||
for (int32_t u : other[s]) place(u);
|
||||
const int32_t to = s < (size_t)n_layer_ ? kLanes : kBlock;
|
||||
while (unit_at_.size() % (size_t)to) place(-1);
|
||||
}
|
||||
slot_lo_[(size_t)n_layer_ + 1] = (int32_t)unit_at_.size();
|
||||
for (size_t u = 0; u < n; ++u)
|
||||
if (pos_[u] < 0) place((int32_t)u);
|
||||
|
||||
const size_t np = unit_at_.size();
|
||||
heat_.assign(np, 0.0f);
|
||||
rank_as_.assign(np, 0u);
|
||||
routed_as_.assign(np, 0u);
|
||||
miss_bytes_.assign(np, 0);
|
||||
for (size_t u = 0; u < n; ++u) set_place((int32_t)u);
|
||||
|
||||
/* Each slot's lowest movable unit index, for step()'s tie test. */
|
||||
min_unit_.assign((size_t)n_layer_ + 1, INT32_MAX);
|
||||
for (size_t sl = 0; sl <= (size_t)n_layer_; ++sl)
|
||||
for (int32_t p = slot_lo_[sl]; p < slot_lo_[sl + 1]; ++p) {
|
||||
const int32_t u = unit_at_[(size_t)p];
|
||||
if (u >= 0 && movable_[(size_t)u] && u < min_unit_[sl]) min_unit_[sl] = u;
|
||||
}
|
||||
|
||||
end_hot_.assign((size_t)n_layer_ + 1, 0.0f);
|
||||
end_cold_.assign((size_t)n_layer_ + 1, 0.0f);
|
||||
end_n_off_.assign((size_t)n_layer_ + 1, 0);
|
||||
end_n_on_.assign((size_t)n_layer_ + 1, 0);
|
||||
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. */
|
||||
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");
|
||||
return RAD_OK;
|
||||
}
|
||||
if (movable == 0) {
|
||||
enabled_ = false;
|
||||
RAD_DEBUG("heat engine: nothing movable in this plan; every weight is statically placed");
|
||||
return RAD_OK;
|
||||
}
|
||||
enabled_ = true;
|
||||
RAD_INFO("heat engine: %lld movable units, %d move%s a dispatch, "
|
||||
"decay %.3f hysteresis %.2f min-gain %.2f",
|
||||
(long long)movable, params_.moves_per_dispatch,
|
||||
params_.moves_per_dispatch == 1 ? "" : "s",
|
||||
(double)params_.decay, (double)params_.hysteresis, (double)params_.min_gain);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
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. */
|
||||
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) {
|
||||
const int32_t e = experts[i];
|
||||
if (e >= 0 && e < n_ex) dense[(size_t)e] += counts ? counts[i] : 1;
|
||||
}
|
||||
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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
prefetch(counts, n);
|
||||
|
||||
float* __restrict h = heat_.data() + lo;
|
||||
for (int32_t j = 0; j < len; ++j) h[j] *= d;
|
||||
|
||||
bool ends = end_ok_[l] != 0;
|
||||
float hot = ends && end_n_off_[l] > 0 ? end_hot_[l] * d : -INFINITY;
|
||||
const float cold = ends && end_n_on_[l] > 0 ? end_cold_[l] * d : INFINITY;
|
||||
int32_t n_cold = ends ? end_n_cold_[l] : 0;
|
||||
int32_t routed = 0, resident = 0;
|
||||
int64_t miss = 0;
|
||||
auto credit = [&](int32_t j) {
|
||||
const int32_t c = counts[j];
|
||||
const size_t q = (size_t)(lo + j);
|
||||
const float was = h[j];
|
||||
const float x = was + (float)c * weight;
|
||||
h[j] = x;
|
||||
routed += routed_as_[q] != 0;
|
||||
resident += routed_as_[q] == 2;
|
||||
miss += miss_bytes_[q];
|
||||
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. */
|
||||
int32_t j0 = 0;
|
||||
for (; j0 + kLanes <= n; j0 += kLanes) {
|
||||
uint32_t m = 0;
|
||||
for (int32_t j = 0; j < kLanes; ++j) m |= (uint32_t)(counts[j0 + j] > 0) << j;
|
||||
for (; m; m &= m - 1) credit(j0 + __builtin_ctz(m));
|
||||
}
|
||||
for (int32_t j = j0; j < n; ++j)
|
||||
if (counts[j] > 0) credit(j);
|
||||
|
||||
if (ends) {
|
||||
end_hot_[l] = end_n_off_[l] ? hot : 0.0f;
|
||||
end_cold_[l] = end_n_on_[l] ? cold : 0.0f;
|
||||
end_n_cold_[l] = n_cold;
|
||||
} else {
|
||||
end_rebuild(l);
|
||||
}
|
||||
|
||||
stats_.routed += (uint64_t)routed * passes;
|
||||
stats_.routed_resident += (uint64_t)resident * passes;
|
||||
stats_.stream_bytes += (uint64_t)miss * passes;
|
||||
++stats_.dispatches;
|
||||
}
|
||||
|
||||
void HeatEngine::set_tier(int32_t unit, Tier t) {
|
||||
if (unit < 0 || (size_t)unit >= tier_.size()) return;
|
||||
const int32_t l = layer_of_[(size_t)unit];
|
||||
const Tier was = tier_[(size_t)unit];
|
||||
if (l >= 0) {
|
||||
if (was == Tier::VRAM && t != Tier::VRAM) --res_count_[(size_t)l];
|
||||
else if (was != Tier::VRAM && t == Tier::VRAM) ++res_count_[(size_t)l];
|
||||
}
|
||||
tier_[(size_t)unit] = t;
|
||||
set_place(unit);
|
||||
end_invalidate(unit);
|
||||
|
||||
if (was != Tier::VRAM && t == Tier::VRAM) {
|
||||
++stats_.promotions;
|
||||
if (ever_[(size_t)unit] & 2u) ++stats_.readmits;
|
||||
if (!(ever_[(size_t)unit] & 1u)) { ++stats_.distinct_promoted; ever_[(size_t)unit] |= 1u; }
|
||||
} else if (was == Tier::VRAM && t != Tier::VRAM) {
|
||||
++stats_.demotions;
|
||||
ever_[(size_t)unit] |= 2u;
|
||||
}
|
||||
}
|
||||
|
||||
void HeatEngine::set_busy(int32_t unit, bool busy) {
|
||||
if (unit < 0 || (size_t)unit >= busy_.size()) return;
|
||||
busy_[(size_t)unit] = busy ? 1u : 0u;
|
||||
set_place(unit);
|
||||
end_invalidate(unit);
|
||||
}
|
||||
|
||||
void HeatEngine::set_place(int32_t unit) {
|
||||
const size_t u = (size_t)unit, p = (size_t)pos_[u];
|
||||
const bool vram = tier_[u] == Tier::VRAM;
|
||||
rank_as_[p] = (!movable_[u] || busy_[u]) ? 0u : vram ? 2u : 1u;
|
||||
routed_as_[p] = vram ? 2u : 1u;
|
||||
miss_bytes_[p] = vram ? 0 : bytes_[u];
|
||||
}
|
||||
|
||||
void HeatEngine::end_rebuild(size_t slot) {
|
||||
float hot = 0.0f, cold = 0.0f;
|
||||
int32_t n_off = 0, n_on = 0, n_cold = 0;
|
||||
for (int32_t p = slot_lo_[slot], e = slot_lo_[slot + 1]; p < e; ++p) {
|
||||
const uint8_t r = rank_as_[(size_t)p];
|
||||
if (!r) continue;
|
||||
const float h = heat_[(size_t)p];
|
||||
if (r == 2) {
|
||||
if (n_on++ == 0 || h < cold) { cold = h; n_cold = 1; }
|
||||
else if (h == cold) ++n_cold;
|
||||
} else {
|
||||
if (n_off++ == 0 || h > hot) hot = h;
|
||||
}
|
||||
}
|
||||
end_hot_[slot] = hot;
|
||||
end_cold_[slot] = cold;
|
||||
end_n_off_[slot] = n_off;
|
||||
end_n_on_[slot] = n_on;
|
||||
end_n_cold_[slot] = n_cold;
|
||||
end_ok_[slot] = 1;
|
||||
}
|
||||
|
||||
void HeatEngine::abandon(const Swap& s) {
|
||||
set_busy(s.promote, false);
|
||||
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. */
|
||||
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_`). */
|
||||
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);
|
||||
|
||||
for (size_t i = 0; i < movable_.size(); ++i) {
|
||||
if (!movable_[i] || busy_[i]) continue;
|
||||
const size_t c = (size_t)cls_[i];
|
||||
const int32_t l = layer_of_[i];
|
||||
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. */
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
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;
|
||||
if (hot_h[(size_t)c] < cold_h[(size_t)c] * params_.hysteresis + params_.min_gain) continue;
|
||||
if (best < 0 || hot_h[(size_t)c] > hot_h[(size_t)best] ||
|
||||
(hot_h[(size_t)c] == hot_h[(size_t)best] &&
|
||||
(hot_res[(size_t)c] < hot_res[(size_t)best] ||
|
||||
(hot_res[(size_t)c] == hot_res[(size_t)best] && hot[(size_t)c] < hot[(size_t)best]))))
|
||||
best = c;
|
||||
}
|
||||
if (best < 0) return false;
|
||||
|
||||
out->promote = hot[(size_t)best];
|
||||
out->demote = cold[(size_t)best];
|
||||
return true;
|
||||
}
|
||||
|
||||
/* THE WHOLE DISPATCH'S PROPOSALS FROM ONE PASS. Marking a pair busy changes neither a unit's heat
|
||||
* nor any layer's resident count, so the m-th pair repeated pick() calls would return is simply the
|
||||
* m-th entry at each end of the same ranking. One pass keeps the `moves_per_dispatch` best of each
|
||||
* end; the proposals, and the counters that say why the list stopped, are the ones the repeated
|
||||
* picks produce. This runs before every pass a rank issues -- draft passes included, where the
|
||||
* device waits for the issue -- so a scan per proposed move would be most of its cost. */
|
||||
namespace {
|
||||
using Ranked = HeatRanked;
|
||||
/* Hotter first, then the layer with fewer residents, then the lower index. */
|
||||
inline bool hotter(const Ranked& a, const Ranked& b) {
|
||||
if (a.h != b.h) return a.h > b.h;
|
||||
if (a.rc != b.rc) return a.rc < b.rc;
|
||||
return a.unit < b.unit;
|
||||
}
|
||||
/* Colder first, then the layer with more residents, then the lower index. */
|
||||
inline bool colder(const Ranked& a, const Ranked& b) {
|
||||
if (a.h != b.h) return a.h < b.h;
|
||||
if (a.rc != b.rc) return a.rc > b.rc;
|
||||
return a.unit < b.unit;
|
||||
}
|
||||
/* Insert into a sorted list of at most `k`, dropping what falls off the end. */
|
||||
template <typename Less>
|
||||
inline void keep_best(Ranked* v, int* n, int k, const Ranked& x, Less less) {
|
||||
if (*n == k && !less(x, v[k - 1])) return;
|
||||
int i = *n < k ? (*n)++ : k - 1;
|
||||
while (i > 0 && less(x, v[i - 1])) { v[i] = v[i - 1]; --i; }
|
||||
v[i] = x;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
int HeatEngine::step(std::vector<Swap>* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
out->clear();
|
||||
if (!enabled_) return RAD_OK;
|
||||
const int k = params_.moves_per_dispatch;
|
||||
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. */
|
||||
int64_t n_off = 0, n_on = 0;
|
||||
float bar = 0.0f;
|
||||
{
|
||||
float hot_h = 0.0f, cold_h = 0.0f;
|
||||
for (size_t l = 0; l < end_ok_.size(); ++l) {
|
||||
if (!end_ok_[l]) end_rebuild(l);
|
||||
if (end_n_off_[l] > 0 && (n_off == 0 || end_hot_[l] > hot_h)) hot_h = end_hot_[l];
|
||||
if (end_n_on_[l] > 0 && (n_on == 0 || end_cold_[l] < cold_h)) cold_h = end_cold_[l];
|
||||
n_off += end_n_off_[l];
|
||||
n_on += end_n_on_[l];
|
||||
}
|
||||
if (!warm() || n_off == 0 || n_on == 0 ||
|
||||
hot_h < cold_h * params_.hysteresis + params_.min_gain) {
|
||||
if (n_off > 0 && n_on > 0) ++stats_.refused; else ++stats_.no_candidate;
|
||||
return RAD_OK;
|
||||
}
|
||||
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 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.
|
||||
*
|
||||
* 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. */
|
||||
const int nc = n_cls_;
|
||||
rank_hot_.resize((size_t)(k * nc));
|
||||
rank_cold_.resize((size_t)(k * nc));
|
||||
Ranked* hot = rank_hot_.data();
|
||||
Ranked* cold = rank_cold_.data();
|
||||
int32_t* n_hot = n_hot_.data();
|
||||
int32_t* n_cold = n_cold_.data();
|
||||
for (int c = 0; c < nc; ++c) n_hot[c] = n_cold[c] = 0;
|
||||
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. */
|
||||
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);
|
||||
return std::max(t, bar);
|
||||
};
|
||||
auto cold_bar = [&]() {
|
||||
float t = -INFINITY;
|
||||
for (int c = 0; c < nc; ++c) t = std::max(t, n_cold[c] == k ? cold[c * k + k - 1].h : INFINITY);
|
||||
return t;
|
||||
};
|
||||
uint8_t pass[kLanes];
|
||||
for (int32_t sl = 0; sl <= n_layer_; ++sl) {
|
||||
const int32_t lo = slot_lo_[(size_t)sl], hi = slot_lo_[(size_t)sl + 1];
|
||||
if (lo >= hi) continue;
|
||||
const float th0 = hot_bar();
|
||||
const bool some_hot = end_n_off_[(size_t)sl] > 0 && end_hot_[(size_t)sl] >= th0;
|
||||
bool some_cold = end_n_on_[(size_t)sl] > 0;
|
||||
if (some_cold && nc == 1 && n_cold[0] == k) {
|
||||
const Ranked& last = cold[k - 1];
|
||||
const float c = end_cold_[(size_t)sl];
|
||||
const int32_t rc = sl < n_layer_ ? res_count_[(size_t)sl] : 0;
|
||||
some_cold = c < last.h ||
|
||||
(c == last.h && (rc > last.rc ||
|
||||
(rc == last.rc && min_unit_[(size_t)sl] < last.unit)));
|
||||
} else if (some_cold) {
|
||||
some_cold = end_cold_[(size_t)sl] <= cold_bar();
|
||||
}
|
||||
if (!some_hot && !some_cold) continue;
|
||||
for (int32_t b = lo; b < hi; b += kLanes) {
|
||||
const float th = hot_bar();
|
||||
const float tc = cold_bar();
|
||||
uint8_t any = 0;
|
||||
for (int32_t j = 0; j < kLanes; ++j) {
|
||||
const float h = hp[b + j];
|
||||
const uint8_t r = ra[b + j];
|
||||
pass[j] = (uint8_t)(((r == 1) & (h >= th)) | (((r == 2) & (h <= tc)) << 1));
|
||||
any |= pass[j];
|
||||
}
|
||||
if (!any) continue;
|
||||
for (int32_t j = 0; j < kLanes; ++j) {
|
||||
if (!pass[j]) continue;
|
||||
const int32_t u = unit_at_[(size_t)(b + j)];
|
||||
const int32_t l = layer_of_[(size_t)u];
|
||||
const int32_t c = cls_[(size_t)u];
|
||||
const Ranked r{ hp[b + j], l >= 0 ? res_count_[(size_t)l] : 0, u };
|
||||
if (pass[j] & 2) keep_best(cold + c * k, &n_cold[c], k, r, colder);
|
||||
else keep_best(hot + c * k, &n_hot[c], k, r, hotter);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
int32_t* m_of = m_of_.data();
|
||||
for (int c = 0; c < nc; ++c) m_of[c] = 0;
|
||||
int made = 0;
|
||||
bool short_of_budget = false;
|
||||
for (;;) {
|
||||
int best = -1;
|
||||
for (int c = 0; c < nc; ++c) {
|
||||
const int32_t m = m_of[c];
|
||||
if (m >= k) continue;
|
||||
if (m >= n_hot[c] || m >= n_cold[c]) { short_of_budget = true; continue; }
|
||||
const Ranked& h = hot[c * k + m];
|
||||
if (h.h < cold[c * k + m].h * params_.hysteresis + params_.min_gain) {
|
||||
short_of_budget = true;
|
||||
continue;
|
||||
}
|
||||
if (best < 0 || hotter(h, hot[best * k + m_of[best]])) best = c;
|
||||
}
|
||||
if (best < 0) break;
|
||||
Swap s;
|
||||
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. */
|
||||
set_busy(s.promote, true);
|
||||
set_busy(s.demote, true);
|
||||
out->push_back(s);
|
||||
++stats_.proposed;
|
||||
++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. */
|
||||
if (n_pool - made > 0 && n_vram - made > 0) ++stats_.refused; else ++stats_.no_candidate;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
std::string HeatEngine::report() const {
|
||||
if (!enabled_)
|
||||
return "heat engine: off (static placement); residency and therefore the summation "
|
||||
"order are fixed for the run\n";
|
||||
|
||||
std::string s = fmt("heat engine: %llu dispatches, %llu swaps proposed, %llu promotions, "
|
||||
"%llu demotions\n",
|
||||
(unsigned long long)stats_.dispatches,
|
||||
(unsigned long long)stats_.proposed,
|
||||
(unsigned long long)stats_.promotions,
|
||||
(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. */
|
||||
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. */
|
||||
if (!res_count_.empty()) {
|
||||
int32_t lo = res_count_[0], hi = res_count_[0];
|
||||
double sum = 0;
|
||||
for (int32_t v : res_count_) { lo = std::min(lo, v); hi = std::max(hi, v); sum += v; }
|
||||
const double mean = sum / (double)res_count_.size();
|
||||
double var = 0;
|
||||
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. */
|
||||
s += " per layer:";
|
||||
for (size_t i = 0; i < res_count_.size(); ++i) {
|
||||
if (i % 12 == 0) s += fmt("\n L%-3zu ", i);
|
||||
s += fmt("%5d", (int)res_count_[i]);
|
||||
}
|
||||
s += "\n";
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,318 @@
|
||||
/* heat.h -- the heat engine: which conditional weight should be in VRAM, decided from what the
|
||||
* router actually did.
|
||||
*
|
||||
* 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."
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* ---- WHAT IT COSTS TO BE ONE STEP BEHIND, HONESTLY -------------------------------------------
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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; LFU-with-
|
||||
* decay and LRU score the same, so the decay constant is not where the wins are and this does not
|
||||
* need to be subtle. Belady is a few points of hit rate above both -- but an oracle restricted to
|
||||
* a disjoint sample of the future keeps most of that gap, so the remainder is knowledge of the
|
||||
* realised future and is not reachable. Of what is left, no statistic of PAST USE captures any of
|
||||
* it: an expert never selected has count zero, no age and no history, and most of the space is in
|
||||
* that state. The router's own gate value does separate those cases, so a scorer built on it is
|
||||
* the one direction here that measurement has not refuted.
|
||||
*/
|
||||
#pragma once
|
||||
#include "planner.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct HeatParams {
|
||||
/* Applied to a layer's whole plane each time that layer is dispatched. Every layer is
|
||||
* dispatched exactly once per forward, so all planes decay in lockstep and heats stay
|
||||
* comparable ACROSS layers -- which the global ranking below depends on.
|
||||
*
|
||||
* 0.98 is a half-life of a few dozen dispatches: long enough to survive a paragraph, short
|
||||
* enough to follow a change of subject. Nearby values are not distinguishable from each other
|
||||
* above the run-to-run spread, which is what the offline replay predicts. */
|
||||
float decay = 0.98f;
|
||||
|
||||
/* 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. */
|
||||
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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* The exchange rate behind the value: the two link directions share one budget, so
|
||||
* a demotion costs about what a promotion does, and a swap therefore has to repay about 1.4
|
||||
* future hits rather than the 0.74 a half-price demotion would imply. */
|
||||
float min_gain = 1.5f;
|
||||
|
||||
/* A BOUNDED MOVE BUDGET PER LAYER DISPATCH. The apparent risk is that a high budget makes the
|
||||
* mover compete with the tier it is trying to shrink -- a promotion and a streamed miss are
|
||||
* the same bytes over the same link. At this scale that does not bind: a larger budget pays
|
||||
* even though it moves considerably more bytes, because converging sooner is worth more than
|
||||
* the traffic costs. The benefit then SATURATES, and this sits where the knob stops mattering
|
||||
* rather than at the largest value that still helps. Past that point the guard, not the
|
||||
* budget, is what declines the extra opportunities -- so raising this alone is worth nothing
|
||||
* until min_gain moves with it.
|
||||
*
|
||||
* IT IS A BUDGET PER SLAB CLASS. A rank holding an uneven slice of every expert has two expert
|
||||
* classes -- the wider slice of one parity's experts and the narrower slice of the other's --
|
||||
* each about half a whole expert, and a budget shared between them would move half the bytes
|
||||
* a dispatch that whole experts do: residency would converge half as fast, and a fresh server
|
||||
* would run about 2% slower for its first minute. Per class, the two together move about as
|
||||
* many whole experts as one class of whole experts does. */
|
||||
int moves_per_dispatch = 8;
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
struct Swap {
|
||||
int32_t promote = -1; /* unit index */
|
||||
int32_t demote = -1;
|
||||
};
|
||||
|
||||
/* One movable unit as step() ranks it: its heat, its layer's resident count, its index. */
|
||||
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. */
|
||||
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. */
|
||||
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.
|
||||
*/
|
||||
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
|
||||
* 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 ------------------------------------------
|
||||
*
|
||||
* `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. */
|
||||
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. */
|
||||
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 ----
|
||||
*
|
||||
* 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. */
|
||||
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]; }
|
||||
bool busy(int32_t unit) const { return busy_[(size_t)unit] != 0; }
|
||||
|
||||
/* The best swap available, or false when the guards refuse. */
|
||||
bool pick(Swap* out) const;
|
||||
|
||||
/* One layer dispatch's worth of proposals, at most `moves_per_dispatch` of them a class.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
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. */
|
||||
std::string report() const;
|
||||
|
||||
private:
|
||||
HeatParams params_;
|
||||
bool enabled_ = false;
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
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 */
|
||||
/* Per position, what step() ranks it as: 0 not a candidate (fixed, in flight, or a hole), 1 a
|
||||
* candidate off the device, 2 a candidate on it. Kept by set_tier and set_busy. */
|
||||
std::vector<uint8_t> rank_as_;
|
||||
/* Per position, what a routed read of it costs: `routed_as_` is 0 for a hole, 1 off the device
|
||||
* and 2 in VRAM, and `miss_bytes_` is the unit's bytes when it is off the device and 0 when it
|
||||
* is not. Kept by set_tier, so pricing a histogram is arithmetic on the pass that credits it. */
|
||||
std::vector<uint8_t> routed_as_;
|
||||
std::vector<int64_t> miss_bytes_;
|
||||
/* Slot s's positions are [slot_lo_[s], slot_lo_[s + 1]): layer s, and slot n_layer_ the
|
||||
* movable units with no layer. Every movable unit is below slot_lo_[n_layer_ + 1], which is a
|
||||
* whole number of screening blocks. The first n_ex_[l] positions of layer l are its experts. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
std::vector<int32_t> cls_;
|
||||
int32_t n_cls_ = 1;
|
||||
/* step()'s two ends of the ranking, `moves_per_dispatch` entries a class, kept between calls
|
||||
* so a dispatch allocates nothing. */
|
||||
std::vector<HeatRanked> rank_hot_, rank_cold_;
|
||||
std::vector<int32_t> n_hot_, n_cold_, m_of_;
|
||||
/* Per slot, its lowest movable unit index: the bound step()'s layer screen needs on a tie. */
|
||||
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.
|
||||
* 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. */
|
||||
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 */
|
||||
std::vector<uint8_t> end_ok_;
|
||||
void end_rebuild(size_t slot);
|
||||
void end_invalidate(int32_t unit) {
|
||||
if (end_ok_.empty()) return;
|
||||
const int32_t l = (size_t)unit < layer_of_.size() ? layer_of_[(size_t)unit] : -1;
|
||||
end_ok_[l >= 0 ? (size_t)l : (size_t)n_layer_] = 0;
|
||||
}
|
||||
|
||||
bool warm() const { return (int64_t)stats_.dispatches >= params_.warmup_dispatches; }
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,766 @@
|
||||
/* mover.h -- residency and the mover: the substrate every tier stands on.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* ---- THE ONE PROPERTY EVERYTHING ELSE RESTS ON -----------------------------------------------
|
||||
*
|
||||
* 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 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 -------------------------------------------------------------
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../device/directio.h"
|
||||
#include "../mem/pools.h"
|
||||
#include "heat.h"
|
||||
#include "planner.h"
|
||||
#include "residency_iface.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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.
|
||||
*
|
||||
* ---- SEGMENTS: ONE RANGE FOR THE SLAB'S OWN SLOTS, ONE FOR EACH LENDER ------------------------
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* ---- 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.
|
||||
*/
|
||||
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. */
|
||||
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;
|
||||
segs_.assign(1, Seg{ 0, n_, n_live > 0 ? n_live : 0, n_live > 0 ? n_live : 0 });
|
||||
free_.clear();
|
||||
held_.assign((size_t)(n_ > 0 ? n_ : 0), 1);
|
||||
n_usable_ = 0;
|
||||
n_held_ = n_live > 0 ? n_live : 0;
|
||||
}
|
||||
/* A segment of `n_slots` after every existing one, covering nothing and holding nothing until
|
||||
* a target reaches into it. Returns its index; slot numbers in it start at seg_lo(index). */
|
||||
int add_segment(int64_t n_slots) {
|
||||
if (n_slots < 0) n_slots = 0;
|
||||
segs_.push_back(Seg{ n_, n_ + n_slots, n_, n_ });
|
||||
held_.resize((size_t)(n_ + n_slots), 1);
|
||||
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;
|
||||
if (!held_[(size_t)slot]) return;
|
||||
held_[(size_t)slot] = 0;
|
||||
--n_held_;
|
||||
Seg& g = segs_[(size_t)seg_of(slot)];
|
||||
if (slot < g.target) push(slot);
|
||||
else settle(g);
|
||||
}
|
||||
bool empty() const { return n_usable_ == 0; }
|
||||
/* How many slots exist, over every segment. */
|
||||
int64_t size() const {
|
||||
int64_t n = 0;
|
||||
for (const Seg& g : segs_) n += g.live - g.lo;
|
||||
return n;
|
||||
}
|
||||
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. */
|
||||
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? */
|
||||
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;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
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. */
|
||||
int64_t take_at_least(int64_t lo) {
|
||||
std::vector<int64_t> keep;
|
||||
int64_t got = -1;
|
||||
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 */
|
||||
if (s < lo) { keep.push_back(s); continue; }
|
||||
held_[(size_t)s] = 1;
|
||||
++n_held_;
|
||||
--n_usable_;
|
||||
got = s;
|
||||
break;
|
||||
}
|
||||
for (int64_t s : keep) {
|
||||
free_.push_back(s);
|
||||
std::push_heap(free_.begin(), free_.end(), std::greater<int64_t>());
|
||||
}
|
||||
return got;
|
||||
}
|
||||
/* The highest slot of segment `k` something holds -- a unit, a copy in flight, a slot in
|
||||
* quarantine -- or -1. A scan down from the segment's mark. */
|
||||
int64_t top_held(int k = 0) const {
|
||||
const Seg& g = segs_[(size_t)k];
|
||||
for (int64_t s = g.live; s-- > g.lo;)
|
||||
if (held_[(size_t)s]) return s;
|
||||
return -1;
|
||||
}
|
||||
/* How many existing slots at or past `from` something holds, over every segment. */
|
||||
int64_t held_from(int64_t from) const {
|
||||
int64_t k = 0;
|
||||
for (const Seg& g : segs_)
|
||||
for (int64_t s = std::max(g.lo, from); s < g.live; ++s) k += held_[(size_t)s];
|
||||
return k;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Seg { int64_t lo, hi, target, live; };
|
||||
int seg_of(int64_t slot) const {
|
||||
for (size_t k = segs_.size(); k-- > 1;)
|
||||
if (slot >= segs_[k].lo) return (int)k;
|
||||
return 0;
|
||||
}
|
||||
void push(int64_t s) {
|
||||
free_.push_back(s);
|
||||
std::push_heap(free_.begin(), free_.end(), std::greater<int64_t>());
|
||||
++n_usable_;
|
||||
}
|
||||
void settle(Seg& g) { while (g.live > g.target && !held_[(size_t)(g.live - 1)]) --g.live; }
|
||||
/* Every covered slot that nothing holds, once each. Ascending order is already a min-heap. */
|
||||
void rebuild() {
|
||||
free_.clear();
|
||||
for (const Seg& g : segs_)
|
||||
for (int64_t s = g.lo; s < g.target; ++s)
|
||||
if (!held_[(size_t)s]) free_.push_back(s);
|
||||
n_usable_ = (int64_t)free_.size();
|
||||
}
|
||||
|
||||
int64_t stride_ = 0, n_ = 0, n_usable_ = 0, n_held_ = 0;
|
||||
std::vector<Seg> segs_;
|
||||
std::vector<int64_t> free_;
|
||||
std::vector<uint8_t> held_;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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);
|
||||
|
||||
const WeightSlot* lookup(rad_weight w) const override {
|
||||
return (size_t)w < slot_.size() ? &slot_[w] : nullptr;
|
||||
}
|
||||
uint64_t epoch() const override { return epoch_; }
|
||||
const std::vector<rad_weight>& changes() const override { return changed_; }
|
||||
void clear_changes() override {
|
||||
for (rad_weight w : changed_) noted_[w] = 0;
|
||||
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);
|
||||
void begin_transfer(rad_weight w, void* ptr, RadEvent ready);
|
||||
void settle(rad_weight w) {
|
||||
if ((size_t)w >= slot_.size()) return;
|
||||
slot_[w].ready = nullptr;
|
||||
++epoch_;
|
||||
}
|
||||
|
||||
private:
|
||||
void note(rad_weight w) {
|
||||
if (noted_[w]) return;
|
||||
noted_[w] = 1;
|
||||
changed_.push_back(w);
|
||||
}
|
||||
|
||||
std::vector<WeightSlot> slot_;
|
||||
uint64_t epoch_ = 1;
|
||||
std::vector<rad_weight> changed_;
|
||||
std::vector<uint8_t> noted_;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ configuration */
|
||||
struct MoverConfig {
|
||||
/* Shadow slots and the staging ring are NOT here. They are budgeted by the planner out of
|
||||
* --vram-weights-mib 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.
|
||||
*
|
||||
* ---- 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. */
|
||||
int max_lead_dispatches = 2;
|
||||
|
||||
/* The container, for the file tier. Empty means there is no file tier and a unit the planner
|
||||
* put there is an error rather than a slow path. */
|
||||
std::string container_path;
|
||||
/* 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. */
|
||||
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. */
|
||||
struct LoanStrip {
|
||||
char* top = nullptr; /* one past the stretch's highest byte */
|
||||
int64_t bytes = 0; /* how far below `top` it runs */
|
||||
int64_t unit_bytes = 0;
|
||||
int64_t unit_tokens = 0;
|
||||
};
|
||||
|
||||
struct MoverStats {
|
||||
uint64_t dispatches = 0;
|
||||
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. */
|
||||
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. */
|
||||
uint64_t dropped = 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. */
|
||||
uint64_t stage_layers = 0, staged_units = 0, staged_bytes = 0, stage_overflow = 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. */
|
||||
uint64_t file_layers = 0, file_units = 0, file_bytes = 0, file_preads = 0;
|
||||
uint64_t file_read_ns = 0, file_wait_ns = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the mover */
|
||||
class Mover {
|
||||
public:
|
||||
~Mover();
|
||||
Mover() = default;
|
||||
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.
|
||||
*
|
||||
* `budget` IS THE PRODUCTION PATH AND SHOULD ALWAYS BE PASSED. Pools already allocated
|
||||
* --vram-weights-mib 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. */
|
||||
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. */
|
||||
int bind_compute_stream(RadStream s);
|
||||
|
||||
/* THE MAINTENANCE STREAM, AND WHY ANYTHING ELSE MAY HAVE IT.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
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
|
||||
* 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.
|
||||
*
|
||||
* ---- A CALLER MUST DO ALL OF IT, EVERY DISPATCH -------------------------------------------
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
/* `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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
int64_t flex_used_bytes() const { return flex_used_.load(std::memory_order_relaxed); }
|
||||
int64_t flex_offered_bytes() const { return flex_offered_.load(std::memory_order_relaxed); }
|
||||
int64_t flex_capacity() const;
|
||||
/* THE 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. */
|
||||
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 is filled in
|
||||
* one call, hottest units first, and the copies run at the rate the link carries them. */
|
||||
int balance(HeatEngine* heat);
|
||||
|
||||
/* balance() for a rank with no step to ride on. Retires what has landed and fills what is
|
||||
* free, so a loan made while the server is idle is filled before the next request rather
|
||||
* than by it. Only while the rank thread is parked. */
|
||||
int idle_tick(HeatEngine* heat);
|
||||
|
||||
/* Where a unit's bytes are right now, as a device-visible address, or null for a file-tier
|
||||
* unit that has not been staged. */
|
||||
void* unit_base(int32_t unit) const;
|
||||
|
||||
/* ---- 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
int stage_units(const std::vector<int32_t>& units, char* dst, int64_t cap, RadEvent after,
|
||||
RadEvent done, std::vector<int32_t>* staged);
|
||||
void unstage_units(const std::vector<int32_t>& staged);
|
||||
|
||||
/* ---- 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 --vram-weights-mib (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.
|
||||
* 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);
|
||||
char* file_buffer(int i) const {
|
||||
return (file_vram_ && (i == 0 || i == 1)) ? file_vram_ + i * file_buf_bytes_ : nullptr;
|
||||
}
|
||||
int64_t file_buffer_bytes() const { return file_vram_ ? file_buf_bytes_ : 0; }
|
||||
|
||||
const MoverStats& stats() const { return stats_; }
|
||||
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. */
|
||||
struct Move {
|
||||
enum class State { Free, Copying, Published, Quarantine };
|
||||
/* Five kinds, one state machine. Promote and Demote are the heat engine's swaps. Stage is
|
||||
* the exact prefetch bringing an offloaded unit into a slot. Release is the same slot
|
||||
* going back once the declared order says nothing will read it again this step -- it
|
||||
* copies nothing and still needs the quarantine, because the barrier is about kernels
|
||||
* already issued and not about bytes in flight. Drop is a unit in a lent slot going back
|
||||
* to the host copy it kept: no copy either, and the same quarantine for the same reason. */
|
||||
enum class Kind { Promote, Demote, Stage, Release, Drop };
|
||||
State state = State::Free;
|
||||
Kind kind = Kind::Promote;
|
||||
int32_t unit = -1;
|
||||
int64_t slab_slot = -1;
|
||||
int64_t pool_slot = -1;
|
||||
RadEvent ev = nullptr;
|
||||
};
|
||||
|
||||
struct UnitState {
|
||||
Tier tier = Tier::VRAM;
|
||||
Site site = Site::Device;
|
||||
int64_t slab_slot = -1; /* index into class slab, or -1 */
|
||||
int64_t pool_slot = -1; /* index into class host pool, or -1 */
|
||||
int64_t static_off = -1; /* byte offset into the static VRAM region, or -1 */
|
||||
int32_t klass = -1;
|
||||
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 --vram-weights-mib 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. */
|
||||
struct ClassPools {
|
||||
SlotPool slab, pool;
|
||||
void* slab_base = nullptr;
|
||||
void* pool_base = nullptr;
|
||||
void* pool_dev = nullptr; /* the pinned pool as the device addresses it */
|
||||
int64_t stride = 0;
|
||||
int64_t n_fixed = 0; /* slots in the budgeted range; the flex ones start here */
|
||||
int64_t n_work = 0; /* shadow + staging: free slots the mover needs to move at all */
|
||||
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. */
|
||||
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. */
|
||||
bool strand_check = true;
|
||||
|
||||
char* slot_ptr(int64_t slot) const {
|
||||
return slot < n_fixed ? (char*)slab_base + slot * stride
|
||||
: flex_ptr[(size_t)(slot - n_fixed)];
|
||||
}
|
||||
bool is_flex(int64_t slot) const { return slot >= n_fixed; }
|
||||
};
|
||||
|
||||
const Program* prog_ = nullptr;
|
||||
const Plan* plan_ = nullptr;
|
||||
MoverConfig cfg_;
|
||||
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. */
|
||||
bool owns_memory_ = false;
|
||||
|
||||
RadStream mover_ = nullptr;
|
||||
RadStream compute_ = nullptr;
|
||||
RadEvent gate_ = nullptr; /* recorded on compute, waited on by the mover stream */
|
||||
int gate_dispatch_ = -1;
|
||||
|
||||
std::vector<ClassPools> pools_;
|
||||
std::vector<UnitState> unit_;
|
||||
std::vector<Move> moves_;
|
||||
|
||||
void* static_vram_ = nullptr;
|
||||
int64_t static_bytes_ = 0;
|
||||
void* pageable_ = nullptr;
|
||||
int64_t pageable_bytes_ = 0;
|
||||
|
||||
FileTier file_;
|
||||
void* stage_ = nullptr; /* pinned staging ring for file-tier reads */
|
||||
int64_t stage_stride_ = 0;
|
||||
int stage_next_ = 0;
|
||||
|
||||
/* The file stager's two VRAM buffers, one allocation, and the pinned windows it reads
|
||||
* through, each with the event behind the copies out of it. */
|
||||
char* file_vram_ = nullptr;
|
||||
int64_t file_buf_bytes_ = 0;
|
||||
char* windows_ = nullptr;
|
||||
int n_windows_ = 0;
|
||||
int win_next_ = 0;
|
||||
std::vector<RadEvent> win_ev_;
|
||||
std::vector<uint8_t> win_rec_;
|
||||
|
||||
/* The lead gate's ring: one event a dispatch, and a host wait on the one from
|
||||
* max_lead_dispatches ago. */
|
||||
std::vector<RadEvent> lead_;
|
||||
int lead_next_ = 0;
|
||||
int32_t prefetch_cursor_ = 0;
|
||||
int32_t last_op_ = -1;
|
||||
int dispatch_ = 0;
|
||||
|
||||
/* THE LOAN, in the owner's tokens, and what the dashboard reads of it. */
|
||||
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. */
|
||||
mutable size_t rec_cursor_ = 0;
|
||||
|
||||
int retire(HeatEngine* heat);
|
||||
int record_gate();
|
||||
void republish(int32_t unit);
|
||||
void* reserve(const char* what, int64_t bytes, int kind);
|
||||
int free_move_record() const;
|
||||
int start_stage(int32_t unit, int64_t slab_slot);
|
||||
void release_slot(int32_t unit);
|
||||
bool unit_in_flight(int32_t unit) const;
|
||||
/* A unit in a lent slot back to the host copy it kept. See Move::Kind::Drop. */
|
||||
int drop(int32_t unit, HeatEngine* heat);
|
||||
/* One promotion out of the unit's pool slot into `slot`, which the caller has taken. */
|
||||
int promote_to(int32_t unit, int64_t slot);
|
||||
/* Promote the hottest pooled units of one class into up to `room` free slots. */
|
||||
int fill(size_t klass, int64_t room, HeatEngine* heat);
|
||||
void count_flex();
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,372 @@
|
||||
/* 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 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. 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 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 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:
|
||||
*
|
||||
* 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
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_core.h"
|
||||
#include "rad_format.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ strategy */
|
||||
enum class Strategy { AllVram = 0, LayerOffload = 1, ExpertTiered = 2, Auto = 3 };
|
||||
|
||||
const char* strategy_name(Strategy s);
|
||||
/* RAD_E_INVAL and *out untouched if the string is not one of the four. */
|
||||
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.
|
||||
*/
|
||||
struct Budgets {
|
||||
int64_t vram_weights = 0; /* bytes; 0 = uncapped, legal only when everything fits */
|
||||
int64_t host_pool = 0; /* bytes; the pinned host tier. 0 = no host tier */
|
||||
bool ssd = false; /* --weights-disk-tier was given */
|
||||
|
||||
static Budgets from(const Config& c);
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
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 */
|
||||
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 */
|
||||
float profile_share = 0.0f; /* the container's popularity profile, or 0 */
|
||||
|
||||
Tier tier = Tier::VRAM;
|
||||
Site site = Site::Device;
|
||||
int32_t slab_slot = -1;
|
||||
bool movable = false; /* may the heat engine relocate it after load */
|
||||
const char* reason = "fits in vram"; /* a fixed string, so the report never guesses */
|
||||
|
||||
/* 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. */
|
||||
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 pool the operator sized. `bytes` is
|
||||
* still what the report attributes to the weights, because padding is not a 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. */
|
||||
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). */
|
||||
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.
|
||||
*/
|
||||
struct SlabClass {
|
||||
std::string name; /* "expert", "layer", "model" plus the byte size */
|
||||
int64_t stride = 0; /* bytes per slot, aligned */
|
||||
int64_t n_units = 0; /* units of this class in the model */
|
||||
int64_t n_slots = 0; /* resident slots the planner bought in VRAM */
|
||||
int64_t n_shadow = 0; /* spare slots for in-flight promotions; see mover.h */
|
||||
int64_t n_stage = 0; /* the staging ring; see RAD_PLACE_STAGE_RING */
|
||||
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. */
|
||||
#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. */
|
||||
#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. */
|
||||
#define RAD_PLACE_FILE_WINDOWS 4
|
||||
#define RAD_PLACE_FILE_WINDOW_BYTES ((int64_t)32 << 20)
|
||||
|
||||
/* 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 --vram-weights-mib, 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.
|
||||
*
|
||||
* 32 is far past where the knob stops mattering, and MORE is the wrong end of the problem: extra
|
||||
* shadows raise the move rate and run SLOWER, because more copies in flight contend with the
|
||||
* zero-copy tier for the same link. The quarter-of-the-slab cap only ever binds on a slab too
|
||||
* small for the number to be meaningful. */
|
||||
#define RAD_PLACE_SHADOW_SLOTS 32
|
||||
|
||||
/* ------------------------------------------------------------------ per-weight result */
|
||||
struct Placement {
|
||||
Tier tier = Tier::VRAM;
|
||||
Site site = Site::Device;
|
||||
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. */
|
||||
const char* reason = "";
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the plan */
|
||||
class Plan {
|
||||
public:
|
||||
int rank = 0, world_size = 1;
|
||||
Strategy strategy = Strategy::Auto;
|
||||
|
||||
/* 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. */
|
||||
bool dynamic = true;
|
||||
|
||||
std::vector<Placement> weight; /* by rad_weight; index 0 is the sentinel */
|
||||
std::vector<MoveUnit> units;
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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 */
|
||||
/* 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
|
||||
* --vram-weights-mib before any expert is made resident. Both 0 when nothing routed 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. */
|
||||
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). */
|
||||
std::vector<std::string> notes;
|
||||
struct Unfit {
|
||||
std::string what; /* the weight class key */
|
||||
std::string why;
|
||||
int64_t count = 0;
|
||||
int64_t bytes = 0;
|
||||
};
|
||||
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. */
|
||||
std::string report(const Program& p) const;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the planner */
|
||||
struct PlannerInput {
|
||||
const Program* program = nullptr;
|
||||
const Config* config = nullptr;
|
||||
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. */
|
||||
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). */
|
||||
bool container = true;
|
||||
};
|
||||
|
||||
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. */
|
||||
int plan(Plan* out);
|
||||
|
||||
private:
|
||||
const PlannerInput& in_;
|
||||
|
||||
/* 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. */
|
||||
bool ssd_ = false; /* --weights-disk-tier was given */
|
||||
|
||||
void resolve_sites(const Program& prog);
|
||||
void build_units(const Program& prog, Plan* p);
|
||||
void pin_mapped(const Program& prog, Plan* p);
|
||||
void build_classes(Plan* p);
|
||||
void rank_units(Plan* p, std::vector<int32_t>* order) const;
|
||||
int assign(Plan* p);
|
||||
int assign_all_vram(Plan* p);
|
||||
int assign_layer_offload(Plan* p);
|
||||
int assign_expert_tiered(Plan* p);
|
||||
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. */
|
||||
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. */
|
||||
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.
|
||||
*
|
||||
* 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, and it is what --expert-vs-cache-ratio divides.
|
||||
* Applying a ratio to the two together would let a 0.3 setting demote the attention projections to
|
||||
* host memory to make room for a cache nothing will fill.
|
||||
*
|
||||
* 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. */
|
||||
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 mapped = 0; /* no device kernel can read them; they never enter a pool at all */
|
||||
int64_t n_units = 0;
|
||||
};
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out);
|
||||
|
||||
/* "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). */
|
||||
std::string weight_class_key(const std::string& name);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,14 @@
|
||||
/* residency_iface.h -- 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "runtime/residency.h"
|
||||
@@ -0,0 +1,345 @@
|
||||
/* stager.cpp -- see stager.h. */
|
||||
#include "place/stager.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace rad {
|
||||
|
||||
PrefillStager::~PrefillStager() {
|
||||
for (int b = 0; b < 2; ++b) {
|
||||
if (done_[b]) rad_event_destroy(done_[b]);
|
||||
if (free_[b]) rad_event_destroy(free_[b]);
|
||||
}
|
||||
}
|
||||
|
||||
int PrefillStager::init(const Program& prog, const Plan& plan, Mover* mover, char* region,
|
||||
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). */
|
||||
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;
|
||||
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; });
|
||||
/* Two layers' spans must not overlap: a layer's copies are released at its last op, and the
|
||||
* next layer's buffer is the one the layer before it released. */
|
||||
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 (layers_.empty()) return RAD_OK;
|
||||
|
||||
first_of_.assign(prog.ops.size(), -1);
|
||||
last_of_.assign(prog.ops.size(), -1);
|
||||
for (size_t i = 0; i < layers_.size(); ++i) {
|
||||
if ((size_t)layers_[i].first_op < first_of_.size()) first_of_[(size_t)layers_[i].first_op] = (int32_t)i;
|
||||
if ((size_t)layers_[i].last_op < last_of_.size()) last_of_[(size_t)layers_[i].last_op] = (int32_t)i;
|
||||
}
|
||||
|
||||
mover_ = mover;
|
||||
cap_ = bytes / 2 / RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
|
||||
buf_[0] = region;
|
||||
buf_[1] = region + cap_;
|
||||
min_rows_ = min_rows;
|
||||
for (int b = 0; b < 2; ++b) {
|
||||
if (rad_event_create_local(&done_[b]) < 0 || rad_event_create_local(&free_[b]) < 0) {
|
||||
layers_.clear();
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
}
|
||||
started_.assign(layers_.size(), 0);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool PrefillStager::begin_pass(const RadBatch* b) {
|
||||
armed_ = full_ && enabled() && b && b->n_tok >= min_rows_;
|
||||
if (!armed_) return false;
|
||||
std::fill(started_.begin(), started_.end(), (uint8_t)0);
|
||||
holds_[0] = holds_[1] = -1;
|
||||
first_op_ = true;
|
||||
pass_kind_ = b->draft_pass;
|
||||
last_issued_ = -1;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool PrefillStager::will_issue(int32_t li) const {
|
||||
const auto it = pass_last_.find(pass_kind_);
|
||||
return it == pass_last_.end() || layers_[(size_t)li].first_op <= it->second;
|
||||
}
|
||||
|
||||
int PrefillStager::start(int32_t li) {
|
||||
started_[(size_t)li] = 1;
|
||||
const int b = li & 1;
|
||||
if (holds_[b] >= 0) return RAD_OK; /* the layer before still holds it: stream this one */
|
||||
const int rc = mover_->stage_units(layers_[(size_t)li].units, buf_[b], cap_,
|
||||
free_rec_[b] ? free_[b] : nullptr, done_[b], &staged_[b]);
|
||||
if (rc < 0) return rc;
|
||||
if (!staged_[b].empty()) { holds_[b] = li; read_[b] = false; }
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The host half of letting a buffer go: its units are published at their pool slots again, which
|
||||
* the next residency sync hands to the weight tables. The device half is `free_`. */
|
||||
void PrefillStager::release(int32_t b) {
|
||||
mover_->unstage_units(staged_[b]);
|
||||
staged_[b].clear();
|
||||
holds_[b] = -1;
|
||||
read_[b] = false;
|
||||
}
|
||||
|
||||
int PrefillStager::finish(int32_t b, RadStream s) {
|
||||
RAD_TRY(rad_event_record(free_[b], s));
|
||||
free_rec_[b] = true;
|
||||
release(b);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int PrefillStager::before_op(rad_op h, RadStream s, bool* resync) {
|
||||
*resync = false;
|
||||
if ((int32_t)h > last_issued_) last_issued_ = (int32_t)h;
|
||||
|
||||
/* THE PASS'S FIRST ROUTED LAYER, staged at its first op of any kind, so the copy runs behind
|
||||
* whatever the pass issues before the layer. */
|
||||
if (first_op_) {
|
||||
first_op_ = false;
|
||||
const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h,
|
||||
[](const Layer& L, int32_t op) { return L.first_op < op; });
|
||||
if (it != layers_.end()) {
|
||||
const int32_t li = (int32_t)(it - layers_.begin());
|
||||
if (!started_[(size_t)li] && will_issue(li)) {
|
||||
RAD_TRY(start(li));
|
||||
*resync = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((size_t)h >= first_of_.size()) return RAD_OK;
|
||||
const int32_t li = first_of_[(size_t)h];
|
||||
if (li < 0) return RAD_OK;
|
||||
/* This layer's copies were published a layer ago: the one wait that orders its ops behind
|
||||
* them. */
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (holds_[b] == li) RAD_TRY(rad_event_wait(s, done_[b]));
|
||||
/* The layer before is done with its buffer: every pass of rows issued its last op, the last
|
||||
* of them recorded `free_`, and a layer's ops do not interleave with the next one's. Released
|
||||
* here and not at that op, whose next run would read copies already overwritten. */
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (holds_[b] >= 0 && holds_[b] != li && read_[b]) release(b);
|
||||
/* And the next layer's copies go out now, behind it. */
|
||||
const int32_t next = li + 1;
|
||||
if ((size_t)next < layers_.size() && !started_[(size_t)next] && will_issue(next)) {
|
||||
RAD_TRY(start(next));
|
||||
*resync = true;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE LAYER'S LAST OP: `free_` goes behind it, so the copies two layers on can start as early as
|
||||
* they could before -- and goes behind it again if the block issues the op for another pass of
|
||||
* rows, which is why the copies themselves are not released until the next layer starts. */
|
||||
int PrefillStager::after_op(rad_op h, RadStream s) {
|
||||
if ((size_t)h >= last_of_.size()) return RAD_OK;
|
||||
const int32_t li = last_of_[(size_t)h];
|
||||
if (li < 0) return RAD_OK;
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (holds_[b] == li) {
|
||||
RAD_TRY(rad_event_record(free_[b], s));
|
||||
free_rec_[b] = true;
|
||||
read_[b] = true;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int PrefillStager::end_pass(RadStream s) {
|
||||
if (!armed_) return RAD_OK;
|
||||
armed_ = false;
|
||||
pass_last_[pass_kind_] = last_issued_;
|
||||
int rc = RAD_OK;
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (holds_[b] >= 0) {
|
||||
const int r = finish(b, s);
|
||||
if (r < 0 && rc >= 0) rc = r;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* ================================================================== the file stager */
|
||||
FileStager::~FileStager() {
|
||||
for (int b = 0; b < 2; ++b) {
|
||||
if (done_[b]) rad_event_destroy(done_[b]);
|
||||
if (free_[b]) rad_event_destroy(free_[b]);
|
||||
}
|
||||
}
|
||||
|
||||
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));
|
||||
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;
|
||||
}
|
||||
|
||||
buf_[0] = mover->file_buffer(0);
|
||||
buf_[1] = mover->file_buffer(1);
|
||||
cap_ = mover->file_buffer_bytes();
|
||||
if (!buf_[0] || !buf_[1] || cap_ < plan.file_layer_max) {
|
||||
RAD_ERR("file stager: the plan reads %zu routed layers from the container and the mover "
|
||||
"holds no buffers for them", layers_.size());
|
||||
layers_.clear();
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
first_of_.assign(prog.ops.size(), -1);
|
||||
for (size_t i = 0; i < layers_.size(); ++i)
|
||||
if ((size_t)layers_[i].first_op < first_of_.size())
|
||||
first_of_[(size_t)layers_[i].first_op] = (int32_t)i;
|
||||
mover_ = mover;
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (rad_event_create_local(&done_[b]) < 0 || rad_event_create_local(&free_[b]) < 0) {
|
||||
layers_.clear();
|
||||
return RAD_E_DEVICE;
|
||||
}
|
||||
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. */
|
||||
bool FileStager::begin_pass(const RadBatch* b) {
|
||||
armed_ = enabled() && b;
|
||||
if (!armed_) return false;
|
||||
holds_[0] = holds_[1] = -1;
|
||||
cur_ = -1;
|
||||
first_op_ = true;
|
||||
pass_kind_ = b->draft_pass;
|
||||
last_issued_ = -1;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FileStager::will_issue(int32_t li) const {
|
||||
const auto it = pass_last_.find(pass_kind_);
|
||||
return it == pass_last_.end() || layers_[(size_t)li].first_op <= it->second;
|
||||
}
|
||||
|
||||
int FileStager::start(int32_t li) {
|
||||
const int b = li & 1;
|
||||
if (holds_[b] >= 0) return RAD_E_STATE; /* released before the next read, by construction */
|
||||
const int rc = mover_->stage_file_units(layers_[(size_t)li].units, buf_[b], cap_,
|
||||
free_rec_[b] ? free_[b] : nullptr, done_[b],
|
||||
&staged_[b]);
|
||||
if (rc < 0) return rc;
|
||||
if (!staged_[b].empty()) holds_[b] = li;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int FileStager::finish(int32_t b, RadStream s) {
|
||||
RAD_TRY(rad_event_record(free_[b], s));
|
||||
free_rec_[b] = true;
|
||||
mover_->unstage_units(staged_[b]);
|
||||
staged_[b].clear();
|
||||
holds_[b] = -1;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
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. */
|
||||
if (first_op_) {
|
||||
first_op_ = false;
|
||||
const auto it = std::lower_bound(layers_.begin(), layers_.end(), (int32_t)h,
|
||||
[](const Layer& L, int32_t op) { return L.first_op < op; });
|
||||
if (it != layers_.end()) {
|
||||
const int32_t li = (int32_t)(it - layers_.begin());
|
||||
if (will_issue(li)) {
|
||||
RAD_TRY(start(li));
|
||||
*resync = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ((size_t)h >= first_of_.size()) return RAD_OK;
|
||||
const int32_t li = first_of_[(size_t)h];
|
||||
if (li < 0 || li == cur_) return RAD_OK;
|
||||
|
||||
/* 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
|
||||
* here rather than issued without addresses. */
|
||||
if (holds_[li & 1] != li) {
|
||||
RAD_TRY(start(li));
|
||||
*resync = true;
|
||||
}
|
||||
if (holds_[li & 1] == li) RAD_TRY(rad_event_wait(s, done_[li & 1]));
|
||||
cur_ = li;
|
||||
|
||||
const int32_t next = li + 1;
|
||||
if ((size_t)next < layers_.size() && will_issue(next)) {
|
||||
RAD_TRY(start(next));
|
||||
*resync = true;
|
||||
}
|
||||
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;
|
||||
pass_last_[pass_kind_] = last_issued_;
|
||||
int rc = RAD_OK;
|
||||
for (int b = 0; b < 2; ++b)
|
||||
if (holds_[b] >= 0) {
|
||||
const int r = finish(b, s);
|
||||
if (r < 0 && rc >= 0) rc = r;
|
||||
}
|
||||
cur_ = -1;
|
||||
return rc;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,197 @@
|
||||
/* stager.h -- the prefill stager: a routed layer's non-resident experts copied onto the card one
|
||||
* layer ahead of the layer that reads them.
|
||||
*
|
||||
* ---- WHY A 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.
|
||||
*
|
||||
* So at a step large enough, the stager copies layer L+1's pooled experts into a VRAM buffer while
|
||||
* layer L runs, publishes the copies for layer L+1's ops, and publishes the host addresses again
|
||||
* once those ops are behind it. The copy is the same bytes the GEMM would have read, so the output
|
||||
* is bit-identical; only when the link carries them moves.
|
||||
*
|
||||
* ---- WHERE THE BUFFERS ARE, AND WHEN THEY ARE ITS ---------------------------------------------
|
||||
*
|
||||
* Two buffers, each one layer's share of the experts the budget leaves off the card, at the top of
|
||||
* the activation arena (Program::arena_stage_off, sized by vram_budget_resolve). A step smaller
|
||||
* than the arena's full plan LENDS that top to the expert slab, so the buffers are the stager's
|
||||
* only in a step at the full plan -- which is exactly the steps worth staging for -- and the rest of
|
||||
* the time they hold resident experts like any other lent slot. The scheduler says which it is,
|
||||
* pass by pass (set_full_arena).
|
||||
*
|
||||
* ---- THE ORDER, AND WHAT KEEPS IT SAFE ---------------------------------------------------------
|
||||
*
|
||||
* the pass's first op stage the first routed layer the pass issues, into buffer 0 or 1
|
||||
* a layer's first op stage the NEXT layer into the other buffer; re-read the residency
|
||||
* table so this layer's ops resolve the copies made one layer ago
|
||||
* a layer's last op record "buffer free" on the op's stream; publish the host addresses
|
||||
* the pass's end the same for anything still staged: nothing outlives its pass
|
||||
*
|
||||
* A copy into a buffer waits on that buffer's "free" event, recorded behind the last op that read
|
||||
* the layer it held -- in this pass or an earlier one. The layer's ops wait on the copies' event
|
||||
* through ONE stream wait, issued before the layer's first op: the copies are published settled
|
||||
* (Mover::stage_units says why), and nothing but the layer's own ops ever resolves them.
|
||||
*
|
||||
* A LAYER IS STAGED AHEAD ONLY WHEN THE PASS WILL ISSUE IT. A step issues its routed layers across
|
||||
* more than one pass -- the trunk in one, the MTP head's in the next -- and the last layer a trunk
|
||||
* pass stages ahead would otherwise be the head's, copied for a pass that never reads it and thrown
|
||||
* away at its end. The stager learns the last op each kind of pass issues (by draft_pass) and stages
|
||||
* a layer ahead only when its first op is at or below it.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../runtime/stager.h"
|
||||
#include "mover.h"
|
||||
#include "planner.h"
|
||||
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
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 two buffers. `min_rows` is the smallest pass it arms for. Leaves it disabled --
|
||||
* enabled() false -- when the plan has no routed layer with a pooled unit to stage. */
|
||||
int init(const Program& prog, const Plan& plan, Mover* mover, char* region, int64_t bytes,
|
||||
int64_t min_rows);
|
||||
|
||||
/* Per pass, before it is released: whether the step runs at the arena's full plan, which is
|
||||
* when the buffers are not lent. */
|
||||
void set_full_arena(bool full) { full_ = full; }
|
||||
|
||||
bool enabled() const { return !layers_.empty(); }
|
||||
int64_t buffer_bytes() const { return cap_; }
|
||||
size_t n_layers() const { return layers_.size(); }
|
||||
|
||||
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;
|
||||
};
|
||||
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 */
|
||||
|
||||
Mover* mover_ = nullptr;
|
||||
char* buf_[2] = { nullptr, nullptr };
|
||||
int64_t cap_ = 0;
|
||||
int64_t min_rows_ = 0;
|
||||
RadEvent done_[2] = { nullptr, nullptr }; /* behind a buffer's copies, on the mover stream */
|
||||
RadEvent free_[2] = { nullptr, nullptr }; /* behind a buffer's last reader */
|
||||
bool free_rec_[2] = { false, false };
|
||||
std::vector<int32_t> staged_[2];
|
||||
int32_t holds_[2] = { -1, -1 }; /* the layer a buffer holds, or -1 */
|
||||
/* The holder's last op has been issued at least once, and `free_` is recorded behind it. A
|
||||
* step longer than the MoE block's pass of rows issues a layer's ops once per pass, so the
|
||||
* last op can run again: the copies are released at the NEXT layer's first op, which is past
|
||||
* every pass, while each run of the last op moves `free_` behind itself. */
|
||||
bool read_[2] = { false, false };
|
||||
|
||||
bool full_ = false;
|
||||
bool armed_ = false;
|
||||
bool first_op_ = false; /* the pass has issued nothing yet */
|
||||
std::vector<uint8_t> started_; /* by layer: staged (or tried) this pass */
|
||||
int32_t pass_kind_ = 0;
|
||||
int32_t last_issued_ = -1;
|
||||
std::map<int32_t, int32_t> pass_last_; /* by draft_pass: the last op such a pass issued */
|
||||
|
||||
bool will_issue(int32_t li) const;
|
||||
int start(int32_t li);
|
||||
int finish(int32_t b, RadStream s);
|
||||
void release(int32_t b);
|
||||
};
|
||||
|
||||
/* ---- 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.
|
||||
*
|
||||
* 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
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
int init(const Program& prog, const Plan& plan, Mover* mover);
|
||||
|
||||
bool enabled() const { return !layers_.empty(); }
|
||||
size_t n_layers() const { return layers_.size(); }
|
||||
int64_t buffer_bytes() const { return cap_; }
|
||||
|
||||
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;
|
||||
};
|
||||
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 */
|
||||
|
||||
Mover* mover_ = nullptr;
|
||||
char* buf_[2] = { nullptr, nullptr };
|
||||
int64_t cap_ = 0;
|
||||
RadEvent done_[2] = { nullptr, nullptr }; /* behind a buffer's copies, on the mover stream */
|
||||
RadEvent free_[2] = { nullptr, nullptr }; /* behind the ops that read a buffer's layer */
|
||||
bool free_rec_[2] = { false, false };
|
||||
std::vector<int32_t> staged_[2];
|
||||
int32_t holds_[2] = { -1, -1 }; /* the layer a buffer holds, or -1 */
|
||||
int32_t cur_ = -1; /* the layer whose ops are being issued */
|
||||
|
||||
bool armed_ = false;
|
||||
bool first_op_ = false;
|
||||
int32_t pass_kind_ = 0;
|
||||
int32_t last_issued_ = -1;
|
||||
std::map<int32_t, int32_t> pass_last_;
|
||||
|
||||
bool will_issue(int32_t li) const;
|
||||
int start(int32_t li);
|
||||
int finish(int32_t b, RadStream s);
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
Reference in new issue
Block a user