ling32 tiers: the compute-stream lookahead predictor is HIP-only, coverage statistics for the lookahead and for an adaptive warm tier

- The tiers' lookahead predictor runs on the compute stream only on HIP (Windows iGPU, R9700: the separate stream with its
  event pair cost 11 ms per decode token there).  On CUDA the separate lookahead stream stays (an RTX 4090, tier B, plain
  decode: 58.5 tok/s with the stream, 54.8 with the compute-stream form).  STRATA_L32_LA_INLINE=0/1 overrides.
- The compute-stream predictor writes its ranked list straight into pinned host memory (device alias of the buffer): one
  op less per layer.
- STRATA_L32_PF_COV=1 statistics: coverage of the experts outside the card prefix by the previous forward of the layer and by
  the union of the predicted lists of a batch (1 / 2-3 / 4-16 tokens); the ceiling of an adaptive warm tier (usage-counted set
  of the size of the static RAM tier, decays 0.99 / 0.998, and the share of SSD uses that were used twice within 64 / 256 /
  1024 tokens).  Demand SSD reads per layer group in the tier report.
- Opt-in adaptive warm (RAM) tier, STRATA_L32_ADAPT=1 (default off): the RAM tier is a set of exact-size slots; an often-used SSD-resident
  expert is copied from the ring into a spare slot of its size class by the worker thread, the least used resident of the class is
  demoted (slot quarantined for 80 layer steps).  Same bytes, same kernels.
This commit is contained in:
Niko1221 committed 2026-12-01 19:49:41 +01:00
1 parent 2211376e72
commit 55e42b3818
3 files changed
+308 -10

No files matched your search

@@ -40,6 +40,13 @@ struct TierStats {
double lead_ms[3] = {}; // summed time between a prediction's arrival and the routing of its layer
uint64_t lead_n[3] = {};
uint64_t hint_marked = 0, pf_inflight_skips = 0;
uint64_t ssd_layer_dem[64] = {}; // demand SSD reads per layer (statistics)
uint64_t ad_promos = 0, ad_promo_bytes = 0, ad_dropped = 0; // adaptive warm tier: promotions into the RAM tier, bytes, candidates dropped
// STRATA_L32_PF_COV=1: ceiling of an ADAPTIVE warm tier: uses of experts outside the card prefix, by where the static tiers keep them and by a usage-counted tier of the same size (decay 0.99 / 0.998 per token)
uint64_t ad_uses = 0, ad_static_ram = 0, ad_adapt[2] = {}, ad_ssd_uses = 0, ad_ssd_rep[3] = {}; // ad_ssd_rep: SSD-resident uses that were used before within 64 / 256 / 1024 tokens (at least twice)
// STRATA_L32_PF_COV=1: coverage of the experts of a decode / verify layer that are NOT in the card prefix, by the previous forward of the same layer ("history") and by the top 8 / 16 / 24 / 32 of the union of the
// predicted lists of the batch rows; buckets: 0 one token, 1 two or three tokens, 2 four to sixteen
uint64_t pc_n[3] = {}, pc_true[3] = {}, pc_hist[3] = {}, pc_both[3] = {}, pc_pred[3][4] = {};
// read latency as the worker sees it (submit to the completion being processed), demand / prefetch reads, and the time the worker spends in the prefetch handler
double rd_lat_dem_s = 0, rd_lat_pf_s = 0, handle_s = 0;
uint64_t rd_n_dem = 0, rd_n_pf = 0, handle_n = 0;
+24 -3
View File
@@ -43,6 +43,19 @@ bool la_time_on() {
}();
return on;
}
// Where the tiers' lookahead predictor runs. HIP (Windows iGPU, R9700): on the compute stream, because a second stream with its events cost 11 ms per decode token there. CUDA: on the
// separate lookahead stream, which overlaps with the layer (the compute-stream form measured -6 % on an RTX 4090). STRATA_L32_LA_INLINE=0/1 overrides.
bool la_inline() {
static const bool v = [] {
if (const char* e = std::getenv("STRATA_L32_LA_INLINE")) return e[0] == '1';
#if defined(STRATA_USE_HIP)
return true;
#else
return false;
#endif
}();
return v;
}
int la_dbg() { // STRATA_L32_LA_DBG (measurements only; predictions become garbage / absent): bit 0 no host callback, bit 1 no predictor kernels
static const int v = [] { const char* e = std::getenv("STRATA_L32_LA_DBG"); return e ? std::atoi(e) : 0; }();
return v;
@@ -99,6 +112,7 @@ struct Ling32Engine::StageCtx {
std::vector<int*> d_pred[2]; // [il] -> [Nmax * kLookaheadTopN]
std::vector<int*> d_pred1, h_pred1; // the k = 1 predictor (EngineOptions::lookahead_k1): the layer own router on the residual that enters the layer
std::vector<int*> h_pred[2];
std::vector<int*> hp_dev[2]; // device-visible alias of h_pred: the compute-stream predictor writes its ranked list there directly (no D2H copy)
std::vector<char> pred_ok[2];
std::vector<std::vector<int>> la_targets[2]; // [ki][s] -> target layers
std::vector<std::unique_ptr<CbCtx>> cbs;
@@ -384,6 +398,12 @@ struct Ling32Engine::StageCtx {
for (int il = c.first_k_dense; il < c.n_layers; ++il) {
if (!alloc(d_pred[ki][il], N * kLookaheadTopN, err) || !cu(cudaMallocHost(reinterpret_cast<void**>(&h_pred[ki][il]), N * kLookaheadTopN * sizeof(int)), "pinned", err))
return false;
if (hp_dev[ki].empty()) hp_dev[ki].assign(c.n_layers, nullptr);
{
void* dp = nullptr;
hp_dev[ki][il] = cudaHostGetDevicePointer(&dp, h_pred[ki][il], 0) == cudaSuccess && dp ? static_cast<int*>(dp) : nullptr;
cudaGetLastError();
}
la_targets[ki][lookahead_source_layer(il, kLookaheadKs[ki])].push_back(il);
if (!m.layers[il].moe.look[ki]) { err = "lookahead is on but the model was loaded without the Section 2 routers"; return false; }
}
@@ -627,7 +647,7 @@ struct Ling32Engine::StageCtx {
if (!any) return;
if (la_dbg() & 4) return;
if (E.sink_ && !E.opt.lookahead_stats && !E.opt.capture && !E.sink_->wants_prediction(N)) return; // nobody uses the predictions of this forward
if (E.sink_ && E.provider_ && !E.opt.lookahead_stats && !E.opt.capture && !(la_dbg() & 64)) {
if (E.sink_ && E.provider_ && !E.opt.lookahead_stats && !E.opt.capture && !(la_dbg() & 64) && la_inline()) {
// The tiers: the predictor runs on the compute stream, right where the residual is, and its result is handed to the store by the compute thread after the next
// layer router sync (flush_predictions). No second stream, no snapshot copy, no events and no host callback: on the R9700 the second stream with its events cost
// 11 ms per decode token (a third of the step) although it did almost nothing.
@@ -639,8 +659,9 @@ struct Ling32Engine::StageCtx {
if (E.opt.act_q8) { gpu::quant_q8(la_u, la_q8, N, D, false, st); ac = {la_q8, true}; }
else ac = {la_u, false};
gpu::gemv_sk(M.look[ki].p, M.look[ki].code, M.look[ki].rows, M.look[ki].cols, ac.p, ac.q8, N, la_logits, c.n_exp, false, st);
gpu::alflb_route(la_logits, M.look_bias[ki], M.gate_bias, c.n_exp, c.n_group, E.opt.lookahead_group_mask ? c.topk_group : c.n_group, kLookaheadTopN, c.routed_scale, false, d_pred[ki][il], nullptr, N, st);
cudaMemcpyAsync(h_pred[ki][il], d_pred[ki][il], static_cast<size_t>(N) * kLookaheadTopN * sizeof(int), cudaMemcpyDeviceToHost, st);
int* dst = (!hp_dev[ki].empty() && hp_dev[ki][il]) ? hp_dev[ki][il] : nullptr; // the route kernel writes into pinned host memory directly: one op less per layer
gpu::alflb_route(la_logits, M.look_bias[ki], M.gate_bias, c.n_exp, c.n_group, E.opt.lookahead_group_mask ? c.topk_group : c.n_group, kLookaheadTopN, c.routed_scale, false, dst ? dst : d_pred[ki][il], nullptr, N, st);
if (!dst) cudaMemcpyAsync(h_pred[ki][il], d_pred[ki][il], static_cast<size_t>(N) * kLookaheadTopN * sizeof(int), cudaMemcpyDeviceToHost, st);
pend.push_back({il, kLookaheadKs[ki], N, h_pred[ki][il]});
}
return;
+277 -7
View File
@@ -16,6 +16,8 @@
#include <cstdlib>
#include <cstring>
#include <deque>
#include <map>
#include <cmath>
#include <functional>
#include <mutex>
#include <thread>
@@ -99,6 +101,7 @@ struct ExpertStore::Impl {
const uint8_t* ptr = nullptr;
int dslot = -1, rslot = -1, group = 0;
bool src_host = false;
const uint8_t* hptr = nullptr; // host address of the slab in the RAM tier (its slot)
cudaEvent_t wait_ev = nullptr;
};
// ---- CPU co-execution of cold misses (decode layers; bit-identical arithmetic, ling32_cpu_expert.hpp)
@@ -172,6 +175,26 @@ struct ExpertStore::Impl {
int pf_ssd_cap = 0; // prefetch: at most this many SSD prefetch reads unfinished (0: no limit) STRATA_L32_PF_SSD_INFLIGHT
int pf_verify = 0; // experts per layer prefetched for a speculative verify batch (2..16 tokens, from the union of the rows); 0: none STRATA_L32_PF_VERIFY
std::atomic<bool> gated{false}; // the prefetch worker waits for the compute to come within `pf_lead` layers of queued requests
bool pf_cov = false; // STRATA_L32_PF_COV=1: coverage statistics of history and of the predicted unions (also makes small batches compute predictions)
std::vector<std::vector<int>> pred_u, hist_items; // per MoE layer: the ranked union of the predicted lists of the last batch, the experts of the previous forward
std::vector<int> pred_u_fwd;
// ---- the adaptive warm (RAM) tier: the RAM tier is a set of slots of the exact size of the slabs; an SSD-resident expert that is used often is copied from the ring into a spare slot of its size class and the least used
// resident of that class is demoted (its slot quarantined for a while: the GPU may still read it). Exact by construction: the same bytes, only the location changes. STRATA_L32_ADAPT=1
struct RamSlot { uint64_t host_off = 0; uint32_t bytes = 0; int gi = -1; };
std::vector<RamSlot> rslots;
std::vector<int> ram_slot_of; // gi -> slot (-1: not in the RAM tier)
std::map<uint32_t, std::vector<int>> cls_all, cls_spare; // slab size -> slots (resident or not), spare slots
std::vector<std::pair<int, long long>> quarantine; // (slot, the step after which it is a spare again)
bool adapt_on = false;
double ad_decay = 0.99, ad_margin = 0.5, ad_min = 2.0;
std::vector<float> uc; // decayed use counts per expert
std::vector<long long> ut;
struct Promo { int gi, rs, tries; };
std::deque<Promo> promo_q;
std::vector<float> ad_c0, ad_c1; // decayed use counts per expert (statistics of the adaptive-tier ceiling)
std::vector<long long> ad_t, ad_h0, ad_h1;
double ad_thr[2] = {1e30, 1e30};
long long ad_thr_at = -1000000, ad_cap = 0;
int io_split = 1; // pieces per SSD slab read (STRATA_L32_SPLIT)
bool pf_ssdonly = false; // decode prefetch only for SSD-resident experts (the RAM tier and the card are left to the demand path) STRATA_L32_PF_SSDONLY=1
bool pf_nossd = false, pf_nopromote = false; // experiments: no SSD prefetch at all (STRATA_L32_PF_NOSSD=1) / SSD prefetch reads stay in the ring, no copy to a slot (STRATA_L32_PF_NOPROMOTE=1)
@@ -301,6 +324,11 @@ struct ExpertStore::Impl {
if (vp && !fill_vram(err)) return false;
if (!so.quiet) std::printf("tier store: hot prefix filled; reading the warm prefix (%.2f GiB)\n", rp / 1073741824.0);
if (rp && !fill_host(err)) return false;
if (const char* e = std::getenv("STRATA_L32_ADAPT")) adapt_on = e[0] == '1' && rp > 0;
if (const char* e = std::getenv("STRATA_L32_AD_DECAY")) ad_decay = std::max(0.5, std::min(0.9999, std::atof(e)));
if (const char* e = std::getenv("STRATA_L32_AD_MARGIN")) ad_margin = std::max(0.0, std::atof(e));
if (const char* e = std::getenv("STRATA_L32_AD_MIN")) ad_min = std::max(0.0, std::atof(e));
init_ram_slots();
S.load_s = now_s() - t0;
if (so.verify && !verify(err)) return false;
if (const char* sp = std::getenv("STRATA_L32_TIER_SPIN")) if (sp[0] == '1') spin_sync = true;
@@ -312,6 +340,7 @@ struct ExpertStore::Impl {
if (const char* e = std::getenv("STRATA_L32_PF_NOSSD")) pf_nossd = e[0] == '1';
if (const char* e = std::getenv("STRATA_L32_PF_SSDONLY")) pf_ssdonly = e[0] == '1';
if (const char* e = std::getenv("STRATA_L32_SPLIT")) io_split = std::max(1, std::min(std::atoi(e), 8));
if (const char* e = std::getenv("STRATA_L32_PF_COV")) pf_cov = e[0] == '1';
if (const char* e = std::getenv("STRATA_L32_PF_NOPROMOTE")) pf_nopromote = e[0] == '1';
cudaEventCreateWithFlags(&route_ev, cudaEventDisableTiming);
if (const char* ck = std::getenv("STRATA_L32_TIER_CHECK")) if (ck[0] == '1') load_mirror();
@@ -535,6 +564,7 @@ struct ExpertStore::Impl {
++S.ssd_reads;
ring[static_cast<size_t>(rs)].t_sub = now_s();
(prefetch ? S.b_ssd_prefetch : S.b_ssd_demand) += bytes;
if (!prefetch) { const int lyr = ring[static_cast<size_t>(rs)].layer; if (lyr >= 0 && lyr < 64) ++S.ssd_layer_dem[lyr]; }
int pieces = io_split > 1 ? io_split : 1;
uint64_t chunk = bytes;
if (pieces > 1) { // parallel pieces: one 4-5 MB read has a 7 ms latency on the Strix SSD (queue depth 1); several in flight finish earlier
@@ -549,6 +579,118 @@ struct ExpertStore::Impl {
return true;
}
// ------------------------------------------------------------------ the adaptive warm tier
void init_ram_slots() { // after the warm prefix is read: one slot per expert of the static RAM tier (its own place), 2 spare slots per size class when adapting
ram_slot_of.assign(static_cast<size_t>(n_gi), -1);
rslots.clear();
cls_all.clear();
cls_spare.clear();
if (rp == 0) return;
for (int g = 0; g < n_gi; ++g) {
const ExpertDesc& d = ed[static_cast<size_t>(g)];
if (d.off < vp || d.off + d.body_bytes > vp + rp) continue;
RamSlot s;
s.host_off = d.off - vp;
s.bytes = static_cast<uint32_t>(d.body_bytes);
s.gi = g;
ram_slot_of[static_cast<size_t>(g)] = static_cast<int>(rslots.size());
cls_all[s.bytes].push_back(static_cast<int>(rslots.size()));
rslots.push_back(s);
}
if (!adapt_on) return;
for (auto& kv : cls_all) { // spares: the two slots of the class that are last in the file (the coldest ranks)
std::vector<int>& v = kv.second;
if (v.size() < 8) continue;
for (int k = 0; k < 2; ++k) {
const int sid = v[v.size() - 1 - static_cast<size_t>(k)];
ram_slot_of[static_cast<size_t>(rslots[static_cast<size_t>(sid)].gi)] = -1;
rslots[static_cast<size_t>(sid)].gi = -1;
cls_spare[kv.first].push_back(sid);
}
}
uc.assign(static_cast<size_t>(n_gi), 0.f);
ut.assign(static_cast<size_t>(n_gi), 0);
if (!so.quiet) {
size_t nsp = 0;
for (auto& kv : cls_spare) nsp += kv.second.size();
std::printf("tier store: adaptive warm tier on: %zu slots in %zu size classes (%zu spare), decay %.3f, margin %.2f, admit at score >= %.1f\n", rslots.size(), cls_all.size(), nsp, ad_decay, ad_margin, ad_min);
}
}
double use_score(int gi, long long now) const {
const size_t g = static_cast<size_t>(gi);
const long long dt = now - ut[g];
return dt <= 0 ? uc[g] : (dt > 8000 ? 0.0 : static_cast<double>(uc[g]) * std::pow(ad_decay, static_cast<double>(dt)));
}
void ad_touch(int gi, long long now) { // (under mu) one more use of the expert
const size_t g = static_cast<size_t>(gi);
uc[g] = static_cast<float>(use_score(gi, now) + 1.0);
ut[g] = now;
}
void maybe_promote(int gi, int rs) { // (under mu) an SSD-resident expert that is in the ring: queue it for the RAM tier if it is used often enough
if (!adapt_on || rp == 0 || cur_tokens > 16 || promo_q.size() >= 6) return;
if (use_score(gi, static_cast<long long>(S.tokens)) < ad_min) return;
const uint32_t cls = static_cast<uint32_t>(ed[static_cast<size_t>(gi)].body_bytes);
if (!cls_all.count(cls)) return;
for (const Promo& p : promo_q) if (p.gi == gi) return;
promo_q.push_back(Promo{gi, rs, 0});
df.wake();
}
bool process_promo() { // worker thread: one promotion; true if anything was done
const size_t ssz = 0;
(void)ssz;
Promo p{-1, -1, 0};
int spare = -1, victim = -1;
uint32_t bytes = 0;
{
std::lock_guard<std::mutex> lk(mu);
for (size_t q = 0; q < quarantine.size();) {
if (quarantine[q].second < static_cast<long long>(step)) {
cls_spare[rslots[static_cast<size_t>(quarantine[q].first)].bytes].push_back(quarantine[q].first);
quarantine[q] = quarantine.back();
quarantine.pop_back();
} else ++q;
}
if (promo_q.empty()) return false;
p = promo_q.front();
promo_q.pop_front();
Ring& r = ring[static_cast<size_t>(p.rs)];
if (r.gi == p.gi && r.state == 1 && p.tries < 60) { ++p.tries; promo_q.push_back(p); return false; } // the read is still in flight: look again when it has completed
if (r.gi != p.gi || r.state != 2 || ram_slot_of[static_cast<size_t>(p.gi)] >= 0) { ++S.ad_dropped; return true; }
bytes = static_cast<uint32_t>(ed[static_cast<size_t>(p.gi)].body_bytes);
auto sp = cls_spare.find(bytes);
if (sp == cls_spare.end() || sp->second.empty()) { ++S.ad_dropped; return true; }
const long long now = static_cast<long long>(S.tokens);
const double cand = use_score(p.gi, now);
double best = 1e300;
for (int sid : cls_all[bytes]) {
const int g = rslots[static_cast<size_t>(sid)].gi;
if (g < 0) continue;
const double sc = use_score(g, now);
if (sc < best) { best = sc; victim = sid; }
}
if (victim < 0 || cand <= best + ad_margin) { ++S.ad_dropped; return true; }
spare = sp->second.back();
sp->second.pop_back();
r.state = 3; // the ring slot stays put until the copy is done
r.ev_valid = false;
}
std::memcpy(host + rslots[static_cast<size_t>(spare)].host_off, ring_ptr(p.rs), bytes);
{
std::lock_guard<std::mutex> lk(mu);
ring[static_cast<size_t>(p.rs)].state = 2;
rslots[static_cast<size_t>(spare)].gi = p.gi;
ram_slot_of[static_cast<size_t>(p.gi)] = spare;
const int vg = rslots[static_cast<size_t>(victim)].gi;
ram_slot_of[static_cast<size_t>(vg)] = -1;
rslots[static_cast<size_t>(victim)].gi = -1;
quarantine.emplace_back(victim, static_cast<long long>(step) + 80); // the GPU or a DMA may still read the demoted slab: the slot is reused after 80 layer steps
++S.ad_promos;
S.ad_promo_bytes += bytes;
}
cv.notify_all();
return true;
}
// ------------------------------------------------------------------ the compute thread
const uint8_t* const* prepare(int il, int n_tokens, const int* d_ridx, int top_k_, void* stream_v) {
cudaStream_t st = static_cast<cudaStream_t>(stream_v);
@@ -586,6 +728,79 @@ struct ExpertStore::Impl {
cnt[static_cast<size_t>(items[i].eid)] = 0;
}
S.uniq += items.size();
if (pf_cov && n_moe > 0) { // ceiling of an adaptive warm tier (see TierStats::ad_*): a usage-counted set of the same size as the static RAM tier against the static one
const size_t ngi = static_cast<size_t>(n_moe) * static_cast<size_t>(E);
if (ad_c0.size() != ngi) {
ad_c0.assign(ngi, 0.f); ad_c1.assign(ngi, 0.f); ad_t.assign(ngi, 0); ad_h0.assign(ngi, -1000000); ad_h1.assign(ngi, -1000000);
ad_cap = 0;
for (size_t g = 0; g < ngi; ++g) if (ed[g].off >= vp && ed[g].off + ed[g].body_bytes <= vp + rp) ++ad_cap;
ad_thr[0] = ad_thr[1] = 1e30; ad_thr_at = -1000000;
}
const long long now_t = static_cast<long long>(S.tokens);
auto dec = [&](size_t g, int w) -> double {
const double d = w == 0 ? 0.99 : 0.998;
return static_cast<double>(w == 0 ? ad_c0[g] : ad_c1[g]) * std::pow(d, static_cast<double>(now_t - ad_t[g]));
};
if (now_t - ad_thr_at >= 64 && ad_cap > 0) { // threshold: the ad_cap-th largest decayed count among the experts outside the card prefix
for (int w = 0; w < 2; ++w) {
std::vector<float> v;
v.reserve(ngi);
for (size_t g = 0; g < ngi; ++g) if (ed[g].off + ed[g].body_bytes > vp) v.push_back(static_cast<float>(dec(g, w)));
if (v.size() > static_cast<size_t>(ad_cap)) {
std::nth_element(v.begin(), v.begin() + static_cast<long>(ad_cap), v.end(), std::greater<float>());
ad_thr[w] = static_cast<double>(v[static_cast<size_t>(ad_cap)]);
} else ad_thr[w] = 0.0;
}
ad_thr_at = now_t;
}
const size_t abase = static_cast<size_t>(il - first_k) * static_cast<size_t>(E);
static const long long kN[3] = {64, 256, 1024};
for (const Item& it : items) {
const size_t g = abase + static_cast<size_t>(it.eid);
const bool noncard = ed[g].off + ed[g].body_bytes > vp;
if (noncard && ad_thr_at > 0) {
const bool in_ram = ed[g].off >= vp && ed[g].off + ed[g].body_bytes <= vp + rp;
++S.ad_uses;
if (in_ram) ++S.ad_static_ram;
for (int w = 0; w < 2; ++w) if (dec(g, w) >= ad_thr[w] && ad_thr[w] > 0) ++S.ad_adapt[w];
if (!in_ram) {
++S.ad_ssd_uses;
for (int q = 0; q < 3; ++q) if (now_t - ad_h1[g] <= kN[q]) ++S.ad_ssd_rep[q];
}
}
ad_c0[g] = static_cast<float>(dec(g, 0) + 1.0); ad_c1[g] = static_cast<float>(dec(g, 1) + 1.0); ad_t[g] = now_t;
ad_h1[g] = ad_h0[g]; ad_h0[g] = now_t;
}
}
if (pf_cov && n_tokens <= 16 && n_moe > 0) { // coverage of the experts outside the card prefix by the previous forward of this layer and by the predicted union
if (pred_u.empty()) { pred_u.resize(static_cast<size_t>(n_moe)); pred_u_fwd.assign(static_cast<size_t>(n_moe), -1); hist_items.resize(static_cast<size_t>(n_moe)); }
const size_t li = static_cast<size_t>(il - first_k);
const int b = n_tokens == 1 ? 0 : n_tokens <= 3 ? 1 : 2;
const int cbase2 = static_cast<int>(li) * E;
const bool have_pred = pred_u_fwd[li] == fwd_id;
const std::vector<int>& pu = pred_u[li];
const std::vector<int>& hi = hist_items[li];
static const int kW[4] = {8, 16, 24, 32};
++S.pc_n[b];
for (const Item& it : items) {
const ExpertDesc& d2 = ed[static_cast<size_t>(cbase2 + it.eid)];
if (d2.off + d2.body_bytes <= vp) continue; // on the card prefix: not interesting
++S.pc_true[b];
const bool in_hist = std::find(hi.begin(), hi.end(), it.eid) != hi.end();
if (in_hist) ++S.pc_hist[b];
bool in16 = false;
if (have_pred)
for (int wi = 0; wi < 4; ++wi) {
const size_t w = std::min<size_t>(pu.size(), static_cast<size_t>(kW[wi]));
const bool found = std::find(pu.begin(), pu.begin() + w, it.eid) != pu.begin() + w;
if (found) ++S.pc_pred[b][wi];
if (wi == 1) in16 = found;
}
if (in_hist || in16) ++S.pc_both[b];
}
hist_items[li].clear();
for (const Item& it : items) hist_items[li].push_back(it.eid);
}
if (n_tokens == 1) { // how well the predictions that had arrived in time covered the true top-8 (all experts, and the ones not on the card)
const double tnow = now_s();
const int cbase = (il - first_k) * E;
@@ -648,11 +863,13 @@ struct ExpertStore::Impl {
d.pass_used = 0;
continue;
}
const bool in_host = it.off >= vp && it.off + it.bytes <= vp + rp;
const int rsl_i = (rp > 0 && !ram_slot_of.empty()) ? ram_slot_of[static_cast<size_t>(it.gi)] : -1;
const bool in_host = rsl_i >= 0;
if (in_host) it.hptr = host + rslots[static_cast<size_t>(rsl_i)].host_off;
const bool stage_it = it.count >= 2 || !so.zero_copy;
if (in_host) {
it.src_host = true;
if (!stage_it) { it.kind = 2; it.ptr = (host_dev ? host_dev : host) + (it.off - vp); ++S.miss_zc_host; S.b_zc += it.bytes; }
if (!stage_it) { it.kind = 2; it.ptr = (host_dev ? host_dev : host) + rslots[static_cast<size_t>(rsl_i)].host_off; ++S.miss_zc_host; S.b_zc += it.bytes; }
else { it.kind = 4; stage.push_back(static_cast<int>(i)); }
continue;
}
@@ -682,6 +899,10 @@ struct ExpertStore::Impl {
it.kind = 4;
stage.push_back(static_cast<int>(i));
}
if (adapt_on) { // usage counts of the experts outside the card prefix; SSD-resident ones that are in the ring become candidates for the RAM tier
for (const Item& it : items) if (it.off + it.bytes > vp) ad_touch(it.gi, static_cast<long long>(S.tokens));
for (const Item& it : items) if (!it.src_host && it.kind >= 3 && it.rslot >= 0) maybe_promote(it.gi, it.rslot);
}
// --turbo-ssd (opt-in, NOT exact; decode layers only): the experts whose slab is on the SSD and not yet read are skipped once the routing mass of the others reaches the threshold; the
// missing ones are fetched exactly as usual, highest weight first, until it does. The weights of the executed experts are scaled so that their sum stays the layer's total, the skipped
// pairs get weight 0 and a cleared ye row.
@@ -740,7 +961,7 @@ struct ExpertStore::Impl {
if (it.kind != 4 || ncpu >= cpu_max || (phase == 0) != it.src_host) continue;
const uint8_t* src = nullptr;
if (it.src_host) {
src = host + (it.off - vp);
src = it.hptr;
} else {
int rs = it.rslot;
if (rs < 0) {
@@ -911,7 +1132,7 @@ struct ExpertStore::Impl {
it.ptr = dyn_ptr(ds);
if (it.src_host) {
++S.miss_stage_host;
srcs.push_back(host + (it.off - vp));
srcs.push_back(it.hptr);
} else {
int rs = it.rslot;
if (rs < 0) {
@@ -927,6 +1148,7 @@ struct ExpertStore::Impl {
std::string e2;
if (!submit_read(rs, it.gi, false, e2)) fatal(e2);
it.rslot = rs;
maybe_promote(it.gi, rs);
} else {
ring[static_cast<size_t>(rs)].tag = step;
ring[static_cast<size_t>(rs)].pass_used = j;
@@ -1024,7 +1246,7 @@ struct ExpertStore::Impl {
// ------------------------------------------------------------------ the prefetcher
bool wants(int n) const { // are the predictions of an n-token forward used? decode (also the hints and the coverage counters), large batches, and small ones only with PF_VERIFY
return n <= 1 || n >= so.prefill_min_batch || (pf_verify > 0 && n <= 16);
return n <= 1 || n >= so.prefill_min_batch || ((pf_verify > 0 || pf_cov) && n <= 16);
}
void on_prediction(int il, int k, const int* ranked, int n, int top_n) {
Req r;
@@ -1040,6 +1262,12 @@ struct ExpertStore::Impl {
pred_t[pi] = now_s();
}
if (k != (pf_k ? pf_k : plan.lookahead_k)) return; // the other predictors are only measured
if (pf_cov && n <= 16 && il >= first_k && n_moe > 0) { // the ranked union of this batch's lists, for the coverage statistics
if (pred_u.empty()) { pred_u.resize(static_cast<size_t>(n_moe)); pred_u_fwd.assign(static_cast<size_t>(n_moe), -1); hist_items.resize(static_cast<size_t>(n_moe)); }
const size_t li = static_cast<size_t>(il - first_k);
pred_u[li] = rank_union(ranked, n, top_n, UnionRank::ByCount, E);
pred_u_fwd[li] = fwd_id;
}
if (n == 1 && hint_rank > 0) { // residency-only lookahead: the predicted experts that are in a slot are kept there until their layer has run
const int base = (il - first_k) * E;
for (int q = 0; q < std::min(hint_rank, top_n); ++q) {
@@ -1110,6 +1338,7 @@ struct ExpertStore::Impl {
{ std::lock_guard<std::mutex> lk(mu); S.handle_s += h1 - h0; ++S.handle_n; }
had = true;
}
if (adapt_on && !had && process_promo()) had = true; // the adaptive warm tier: one copy ring -> RAM slot per round, in the idle time of the worker
if (!had && waiting) {
// lead-gated requests are queued: wait on the completion port (demand reads finishing are seen at once; a sleep here delayed them by a timer tick, a few ms on Windows)
// and be woken by the compute thread when the layer advances
@@ -1162,7 +1391,8 @@ struct ExpertStore::Impl {
const uint64_t off = ed[static_cast<size_t>(gi)].off, bytes = ed[static_cast<size_t>(gi)].body_bytes;
if (off + bytes <= vp) { ++S.pf_skipped_resident; continue; }
if (dyn_of[static_cast<size_t>(gi)] >= 0) { ++S.pf_skipped_resident; continue; }
const bool in_host = off >= vp && off + bytes <= vp + rp;
const int rsl_h = (rp > 0 && !ram_slot_of.empty()) ? ram_slot_of[static_cast<size_t>(gi)] : -1;
const bool in_host = rsl_h >= 0;
if (in_host && pf_ssdonly && r.n == 1) continue; // the RAM tier is cheap to stage on demand: spend the prefetch budget on the SSD part
if (in_host) {
const int ds = alloc_dyn(false, 0);
@@ -1171,7 +1401,7 @@ struct ExpertStore::Impl {
d.gi = gi; d.state = 1; d.pf = true; d.used = false; d.ev_valid = false; d.tag = 0; d.pass_used = 0; d.fwd = r.fwd; d.layer = r.il;
dyn_of[static_cast<size_t>(gi)] = ds;
dsts.push_back(dyn_ptr(ds));
srcs.push_back(host + (off - vp));
srcs.push_back(host + rslots[static_cast<size_t>(rsl_h)].host_off);
sizes.push_back(bytes);
slots.push_back(ds);
S.b_h2d_prefetch += bytes;
@@ -1342,6 +1572,46 @@ std::string ExpertStore::report() const {
static_cast<unsigned long long>(s.cpu_experts), static_cast<unsigned long long>(s.cpu_layers), s.cpu_experts / std::max<double>(1.0, static_cast<double>(s.cpu_layers)), s.cpu_wait_gu_s, s.cpu_wait_dn_s, s.cpu_sync_s);
out += c4;
}
{
uint64_t tot = 0;
for (int l = 0; l < 64; ++l) tot += s.ssd_layer_dem[l];
if (tot > 0) { // demand SSD reads per layer, in groups of 6 layers (the first MoE layers come first)
std::string c7 = "\n demand SSD reads by layer group (6 layers each, from layer 0):";
for (int g = 0; g < 11; ++g) {
uint64_t gs = 0;
for (int l = g * 6; l < std::min(64, g * 6 + 6); ++l) gs += s.ssd_layer_dem[l];
char b7[40];
std::snprintf(b7, sizeof b7, " %.0f%%", 100.0 * gs / static_cast<double>(tot));
c7 += b7;
}
out += c7;
}
}
if (s.ad_promos || s.ad_dropped) {
char c9[200];
std::snprintf(c9, sizeof c9, "\n adaptive warm tier: %llu promotions into the RAM tier (%.1f MB per token), %llu candidates dropped",
static_cast<unsigned long long>(s.ad_promos), s.ad_promo_bytes / 1048576.0 / std::max<double>(1.0, static_cast<double>(s.tokens)), static_cast<unsigned long long>(s.ad_dropped));
out += c9;
}
if (s.ad_uses > 0) {
char c8[620];
const double u = static_cast<double>(s.ad_uses), su = std::max<double>(1.0, static_cast<double>(s.ad_ssd_uses));
std::snprintf(c8, sizeof c8, "\n adaptive warm tier ceiling (%llu non-card uses): static RAM tier holds %.1f %%; a usage-counted tier of the same size would hold %.1f %% (decay 0.99) / %.1f %% (0.998), i.e. SSD share %.1f %% static -> %.1f %% / %.1f %%;"
" of the static SSD uses, %.1f / %.1f / %.1f %% were used twice before within 64 / 256 / 1024 tokens",
static_cast<unsigned long long>(s.ad_uses), 100.0 * s.ad_static_ram / u, 100.0 * s.ad_adapt[0] / u, 100.0 * s.ad_adapt[1] / u, 100.0 - 100.0 * s.ad_static_ram / u, 100.0 - 100.0 * s.ad_adapt[0] / u,
100.0 - 100.0 * s.ad_adapt[1] / u, 100.0 * s.ad_ssd_rep[0] / su, 100.0 * s.ad_ssd_rep[1] / su, 100.0 * s.ad_ssd_rep[2] / su);
out += c8;
}
for (int b = 0; b < 3; ++b)
if (s.pc_n[b]) {
static const char* bn[3] = {"1 token", "2-3 tokens", "4-16 tokens"};
const double t = std::max<double>(1.0, static_cast<double>(s.pc_true[b]));
char c6[420];
std::snprintf(c6, sizeof c6, "\n coverage of the non-card experts, batches of %s (%llu layers, %.2f non-card experts per layer): previous forward of the layer %.1f %%, predicted union top 8/16/24/32 = %.1f / %.1f / %.1f / %.1f %%, history or top 16 = %.1f %%",
bn[b], static_cast<unsigned long long>(s.pc_n[b]), s.pc_true[b] / std::max<double>(1.0, static_cast<double>(s.pc_n[b])), 100.0 * s.pc_hist[b] / t,
100.0 * s.pc_pred[b][0] / t, 100.0 * s.pc_pred[b][1] / t, 100.0 * s.pc_pred[b][2] / t, 100.0 * s.pc_pred[b][3] / t, 100.0 * s.pc_both[b] / t);
out += c6;
}
if (s.rd_n_dem || s.rd_n_pf) {
char c5[300];
std::snprintf(c5, sizeof c5, "\n SSD read latency seen by the worker: demand %.2f ms (%llu reads), prefetch %.2f ms (%llu reads); prefetch handler %.3f s in %llu calls",