ling32 tiers: no lookahead work for batches nobody uses, compute-stream predictor, larger RAM tier on Windows iGPUs

- DemandSink::wants_prediction(n): the engine skips the lookahead predictor for forwards the store makes no use of
  (speculative verify batches of 2..127 tokens).  R9700 tier B with MTP: prefetch on 30.9 -> 39.7 tok/s (off: 39.6).
- Tiers: the predictor runs on the compute stream and the compute thread hands the predictions to the store after the
  next router sync (Impl::pend / flush_predictions).  The second lookahead stream with its event pair cost 11 ms per
  decode token on the R9700 although it did almost nothing (bisect with STRATA_L32_LA_DBG / STRATA_L32_LA_TIME).
  Plain tier B decode with prefetch on: 25.0 -> 29.3 tok/s (off 36.6; the remaining gap is open).
- The routing capture copies (two small D2H copies per MoE layer) are only made for the statistics and capture modes.
- Optional prefetch of the union of a verify batch (STRATA_L32_PF_VERIFY=N experts per layer, default 0: measured slower).
- Windows iGPU planner: explicit RAM budget = free RAM - 8 GiB floor, at most half of the system RAM - 0.5 GiB (GPU-visible
  pinned memory above half of the system RAM stalls the card fill); the planner's 6 GiB headroom no longer applies.
  Strix tier C: RAM tier 8.8 -> 12.5 GiB, 20.7 -> 21.8 tok/s, same greedy tokens.  Fail-fast check of the free Windows RAM
  before the warm prefix is allocated; progress lines for the start-up fill.
This commit is contained in:
Niko1221 committed 2026-12-01 18:30:22 +01:00
1 parent cf13c0df78
commit ff4b0431b0
5 files changed
+121 -21

No files matched your search

@@ -62,6 +62,9 @@ class DemandSink {
public:
virtual ~DemandSink() = default;
virtual void on_prediction(int target_layer, int k, const int* ranked, int n_tokens, int top_n) = 0;
// false: a forward of n_tokens makes no use of the predictions, so the engine does not compute them (the predictor GEMV, router and host callback of every layer cost
// decode time). The statistics and capture modes ignore this and always compute them.
virtual bool wants_prediction(int n_tokens) const { (void)n_tokens; return true; }
};
// Prediction against truth, per layer and per predictor: top-K hit rate and routing-mass coverage, per token and for the union over a batch.
+70 -13
View File
@@ -2,6 +2,8 @@
#include "ling32_engine.hpp"
#include <algorithm>
#include <atomic>
#include <cstdlib>
#include <chrono>
#include <cmath>
#include <cstdio>
@@ -27,9 +29,29 @@ struct CbCtx {
int il, k, n;
const int* host;
};
// STRATA_L32_LA_TIME=1: what the lookahead costs the compute thread (printed at exit)
std::atomic<long long> g_la_cpu_ns{0}, g_la_sync_ns{0}, g_la_cb_ns{0}, g_la_calls{0}, g_la_cbs{0};
bool la_time_on() {
static const bool on = [] {
const char* e = std::getenv("STRATA_L32_LA_TIME");
if (!e || e[0] != '1') return false;
std::atexit([] {
std::fprintf(stderr, "lookahead cost: %lld lookahead_at calls, %.3f s of compute-thread time in them (%.3f s waiting for a snapshot slot), %lld host callbacks %.3f s\n",
g_la_calls.load(), g_la_cpu_ns.load() * 1e-9, g_la_sync_ns.load() * 1e-9, g_la_cbs.load(), g_la_cb_ns.load() * 1e-9);
});
return true;
}();
return on;
}
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;
}
void CUDART_CB la_callback(void* u) {
const CbCtx* c = static_cast<const CbCtx*>(u);
const auto t0 = std::chrono::steady_clock::now();
if (c->sink) c->sink->on_prediction(c->il, c->k, c->host, c->n, kLookaheadTopN);
if (la_time_on()) { g_la_cb_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - t0).count(); ++g_la_cbs; }
}
} // namespace
@@ -80,6 +102,12 @@ struct Ling32Engine::StageCtx {
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;
struct PendingPred { int il, k, n; const int* host; };
std::vector<PendingPred> pend; // predictions enqueued on the compute stream, delivered to the store after the next router sync
void flush_predictions() {
for (const PendingPred& p : pend) E.sink_->on_prediction(p.il, p.k, p.host, p.n, kLookaheadTopN);
pend.clear();
}
std::vector<int*> h_ridx;
std::vector<float*> h_rw;
gpu::MoeTcWork tcw;
@@ -361,7 +389,7 @@ struct Ling32Engine::StageCtx {
}
}
}
if (o.lookahead || o.capture)
if (o.lookahead_stats || o.capture) // the routing capture is only read by the statistics and the capture mode: two small D2H copies per MoE layer are not free
for (int il = c.first_k_dense; il < c.n_layers; ++il) {
if (!cu(cudaMallocHost(reinterpret_cast<void**>(&h_ridx[il]), N * c.top_k * sizeof(int)), "pinned", err) ||
!cu(cudaMallocHost(reinterpret_cast<void**>(&h_rw[il]), N * c.top_k * sizeof(float)), "pinned", err))
@@ -550,6 +578,7 @@ struct Ling32Engine::StageCtx {
const ExpertDesc* edesc = mt ? m.mtp.d_experts : m.d_experts;
if (E.provider_ && !mt) E.provider_->set_route_buffers(rw, ye); // the layer router weights and the pair rows of ye (the tiers read / rewrite them: --turbo-ssd)
const uint8_t* const* slabs = mt ? m.mtp.d_slab_ptrs : (E.provider_ ? E.provider_->prepare(il, N, ridx, c.top_k, st) : m.d_slab_ptrs);
if (!pend.empty() && !mt && E.sink_) flush_predictions(); // prepare() has synchronized the stream: the predictions enqueued before this layer are on the host
const int base = mt ? 0 : (il - c.first_k_dense) * c.n_exp;
// CPU co-execution of cold misses (tiers): float activations and the plain kernels only
const bool cpux = !mt && E.provider_ && E.provider_->cpu_pending();
@@ -596,30 +625,56 @@ struct Ling32Engine::StageCtx {
void lookahead_at(int s, int N) {
bool any = !la_targets[0][s].empty() || !la_targets[1][s].empty();
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)) {
// 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.
for (int ki = 0; ki < 2; ++ki)
for (int il : la_targets[ki][s]) {
const MoeLayer& M = m.layers[il].moe;
gpu::rmsnorm(x, nullptr, 1e-6f, la_u, N, D, st);
Act ac;
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);
pend.push_back({il, kLookaheadKs[ki], N, h_pred[ki][il]});
}
return;
}
const bool timed = la_time_on();
const auto lt0 = std::chrono::steady_clock::now();
const int r = ring_next;
ring_next = (ring_next + 1) % kRing;
if (snap_used[r]) cudaEventSynchronize(snap_done[r]);
cudaMemcpyAsync(snap[r], x, static_cast<size_t>(N) * D * sizeof(float), cudaMemcpyDeviceToDevice, st);
cudaEventRecord(snap_ready[r], st);
cudaStreamWaitEvent(la, snap_ready[r], 0);
if (snap_used[r]) {
cudaEventSynchronize(snap_done[r]);
if (timed) g_la_sync_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - lt0).count();
}
if (!(la_dbg() & 16)) cudaMemcpyAsync(snap[r], x, static_cast<size_t>(N) * D * sizeof(float), cudaMemcpyDeviceToDevice, st);
if (!(la_dbg() & 16)) cudaEventRecord(snap_ready[r], st);
if (!(la_dbg() & 16)) cudaStreamWaitEvent(la, snap_ready[r], 0);
for (int ki = 0; ki < 2; ++ki)
for (int il : la_targets[ki][s]) {
const MoeLayer& M = m.layers[il].moe;
gpu::rmsnorm(snap[r], nullptr, 1e-6f, la_u, N, D, la);
if (!(la_dbg() & 2)) gpu::rmsnorm(snap[r], nullptr, 1e-6f, la_u, N, D, la);
Act ac;
if (E.opt.act_q8) { gpu::quant_q8(la_u, la_q8, N, D, false, la); ac = {la_q8, true}; }
if (la_dbg() & 2) ac = {la_u, false}; else if (E.opt.act_q8) { gpu::quant_q8(la_u, la_q8, N, D, false, la); 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, la);
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, la);
cudaMemcpyAsync(h_pred[ki][il], d_pred[ki][il], static_cast<size_t>(N) * kLookaheadTopN * sizeof(int), cudaMemcpyDeviceToHost, la);
if (!(la_dbg() & 2)) 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, la);
if (!(la_dbg() & 2)) 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, la);
if (!(la_dbg() & 32)) cudaMemcpyAsync(h_pred[ki][il], d_pred[ki][il], static_cast<size_t>(N) * kLookaheadTopN * sizeof(int), cudaMemcpyDeviceToHost, la);
pred_ok[ki][il] = 1;
if (E.sink_) {
if (E.sink_ && !(la_dbg() & 1)) {
cbs.push_back(std::unique_ptr<CbCtx>(new CbCtx{E.sink_, il, kLookaheadKs[ki], N, h_pred[ki][il]}));
cudaLaunchHostFunc(la, la_callback, cbs.back().get());
}
}
cudaEventRecord(snap_done[r], la);
snap_used[r] = true;
if (timed) { g_la_cpu_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - lt0).count(); ++g_la_calls; }
}
// the whole step after the ids are on the device: embedding, 42 layers, final norm, lm_head
@@ -802,6 +857,7 @@ bool Ling32Engine::forward_mm(const int* ids, int N, int n_logits, std::vector<f
const auto t0 = std::chrono::steady_clock::now();
if (provider_) provider_->begin_forward(N);
I.la_enabled = true;
I.pend.clear();
(void)cudaGetLastError(); // HIP has one sticky last-error for all calls: drop what an earlier handled failure (a refused attribute, a not-ready query) left, the checks below look at launches only
I.set_pos(pos_);
cudaMemcpyAsync(I.ids, ids, static_cast<size_t>(N) * sizeof(int), cudaMemcpyHostToDevice, I.st);
@@ -856,7 +912,7 @@ bool Ling32Engine::forward_mm(const int* ids, int N, int n_logits, std::vector<f
if (e != cudaSuccess) { err = std::string("forward: ") + cudaGetErrorString(e); return false; }
I.la_enabled = false;
I.mm_embed_on = I.mm_mpos_on = false;
if (opt.lookahead) I.finish_lookahead(N);
if (opt.lookahead && !(la_dbg() & 8)) I.finish_lookahead(N);
if (provider_) provider_->end_forward();
pos_ += N;
last_forward_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
@@ -1129,6 +1185,7 @@ bool Ling32Engine::spec_cycle(std::vector<int>& committed, std::string& err) {
I.set_pos(pos_);
if (provider_) provider_->begin_forward(N);
I.la_enabled = opt.lookahead;
I.pend.clear();
const bool use_graph = opt.cuda_graph && !opt.lookahead && !provider_;
bool done = false;
if (use_graph) {
@@ -1154,7 +1211,7 @@ bool Ling32Engine::spec_cycle(std::vector<int>& committed, std::string& err) {
if (!done) I.enqueue_cycle(N, Knext);
const cudaError_t e = cudaStreamSynchronize(I.st);
I.la_enabled = false;
if (opt.lookahead && e == cudaSuccess) I.finish_lookahead(N);
if (opt.lookahead && e == cudaSuccess && !(la_dbg() & 8)) I.finish_lookahead(N);
if (provider_) provider_->end_forward();
if (e != cudaSuccess) { err = std::string("spec_cycle: ") + cudaGetErrorString(e); return false; }
const cudaError_t e2 = cudaGetLastError();
+19 -2
View File
@@ -578,7 +578,7 @@ int cmd_run(const RunOpts& o) {
#if defined(STRATA_USE_HIP) && defined(_WIN32)
win_igpu = integrated;
#endif
uint64_t plan_vram = fr, plan_ram = host_ram_available();
uint64_t plan_vram = fr, plan_ram = host_ram_available(), win_ram_budget = 0;
if (win_igpu && o.tier != "vram") {
constexpr uint64_t kGiBu = 1ull << 30;
const uint64_t cap = probe_gpu_alloc_cap(o.device);
@@ -586,11 +586,28 @@ int cmd_run(const RunOpts& o) {
const uint64_t floor_ram = 8 * kGiBu + kGiBu * 3 / 2; // 8 GiB of Windows RAM stay free (+ the ring, staging and the process itself)
plan_vram = std::min<uint64_t>(fr, cap > reserve ? cap - reserve : 0);
plan_ram = plan_ram > floor_ram ? plan_ram - floor_ram : 0;
#if defined(_WIN32)
{ // The RAM tier is Windows memory registered with the GPU: the driver keeps GPU-visible pinned memory (this tier + the ring + the staging buffers) below half of the system RAM;
// above that the card fill stalls (measured on the Strix: 31.6 GiB of Windows RAM, 15.3 GiB pinned fine, 15.8 GiB stalls). Planner RAM budget: the RAM that is free
// minus the 8 GiB floor, at most half of the system RAM minus 0.5 GiB; it is explicit, so the planner's own 6 GiB headroom (for page cache on Linux) does not apply.
MEMORYSTATUSEX ms;
ms.dwLength = sizeof ms;
if (GlobalMemoryStatusEx(&ms)) {
const uint64_t avail = ms.ullAvailPhys;
uint64_t b = avail > 8 * kGiBu ? avail - 8 * kGiBu : 0;
b = std::min<uint64_t>(b, ms.ullTotalPhys / 2 > kGiBu / 2 ? ms.ullTotalPhys / 2 - kGiBu / 2 : 0);
win_ram_budget = b;
plan_ram = std::min<uint64_t>(std::max<uint64_t>(plan_ram, b), avail);
}
}
#endif
std::printf("Windows integrated GPU: GPU allocation cap probed %.1f GiB (device + pinned host draw from it): card budget %.1f GiB, RAM tier budget %.1f GiB (registered pages, 8 GiB of RAM stay free)\n", cap / double(kGiBu), plan_vram / double(kGiBu), plan_ram / double(kGiBu));
}
if (!o.map_experts && (!integrated || asked || (win_igpu && o.tier != "vram"))) {
std::string perr;
if (!make_plan(f, o, plan_vram, plan_ram, plan, rt, perr)) { std::fprintf(stderr, "strata-ling32: %s\n", perr.c_str()); return 1; }
RunOpts plan_opts = o;
if (win_igpu && o.tier != "vram" && o.ram_budget_gib <= 0 && win_ram_budget > 0) plan_opts.ram_budget_gib = win_ram_budget / double(1ull << 30);
if (!make_plan(f, plan_opts, plan_vram, plan_ram, plan, rt, perr)) { std::fprintf(stderr, "strata-ling32: %s\n", perr.c_str()); return 1; }
std::printf("%s\n", plan.describe().c_str());
for (const auto& n : plan.notes) std::printf(" note: %s\n", n.c_str());
tiered = plan.mode != TierMode::A;
+28 -6
View File
@@ -167,7 +167,8 @@ struct ExpertStore::Impl {
int n_moe = 0, pf_scan = 8, hint_rank = 0; // prefetch: rank cut-off of the predicted list, how many predicted ranks protect a resident expert from eviction
uint64_t inflight_cap = 8ull << 20; // prefetch: at most this many bytes of prefetch copies unfinished (0: no limit)
int pf_ssd_cap = 0; // prefetch: at most this many SSD prefetch reads unfinished (0: no limit) STRATA_L32_PF_SSD_INFLIGHT
std::atomic<bool> gated{false}; // the prefetch worker waits for the compute to come within `pf_lead` layers of queued requests
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_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)
bool pf_ssd_idle = false; // prefetch: no SSD prefetch while a demand read is unfinished STRATA_L32_PF_SSD_IDLE=1
std::vector<int> pred_buf, pred_fwd; // the last decode prediction per (predictor, layer): ranked ids, forward id
@@ -244,11 +245,23 @@ struct ExpertStore::Impl {
// Windows iGPU: hipHostMalloc memory draws from the same ~63 GiB per-process cap as device memory; ordinary pages registered with the driver do not (and the GPU reads them at the
// same speed), so the warm prefix is VirtualAlloc'ed and registered as one range. The slabs are always staged by DMA from this CPU address (miss_stage), never read in place.
if (rp) {
constexpr uint64_t kGiBw = 1ull << 30;
MEMORYSTATUSEX ms;
ms.dwLength = sizeof ms;
const bool have_ms = GlobalMemoryStatusEx(&ms) != 0;
const uint64_t ring_need = static_cast<uint64_t>(std::max(0, plan.ring_slots)) * slot_bytes;
if (!so.quiet) std::printf("tier store: Windows RAM %.1f GiB free of %.1f GiB; warm prefix %.2f GiB, ring %.2f GiB\n", have_ms ? ms.ullAvailPhys / double(kGiBw) : -1.0, have_ms ? ms.ullTotalPhys / double(kGiBw) : -1.0, rp / double(kGiBw), ring_need / double(kGiBw));
if (have_ms && ms.ullAvailPhys < rp + ring_need + 8 * kGiBw) { // the owner rule: 8 GiB of Windows RAM stay free; fail fast instead of paging the box to death
err = "tier store: not enough free Windows RAM for the warm prefix (" + std::to_string(ms.ullAvailPhys / kGiBw) + " GiB free, " + std::to_string((rp + ring_need) / kGiBw) + " GiB needed plus the 8 GiB floor)";
return false;
}
const double tw0 = now_s();
host = static_cast<uint8_t*>(VirtualAlloc(nullptr, rp, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
if (!host) { err = "tier store: VirtualAlloc failed for the warm prefix"; return false; }
host_registered = true;
// ONE registration of the whole range: a DMA copy of a slab that straddles two separate registrations fails with "invalid argument"
if (!cu(cudaHostRegister(host, rp, cudaHostRegisterPortable), "cudaHostRegister (warm prefix in RAM)", err)) return false;
if (!so.quiet) std::printf("tier store: warm prefix allocated and registered in %.2f s\n", now_s() - tw0);
}
#else
if (rp && !cu(cudaHostAlloc(reinterpret_cast<void**>(&host), rp, cudaHostAllocPortable), "cudaHostAlloc (warm prefix in RAM)", err)) return false;
@@ -268,7 +281,9 @@ struct ExpertStore::Impl {
const size_t max_pairs = static_cast<size_t>(so.max_tokens) * top_k;
if (!cu(cudaHostAlloc(reinterpret_cast<void**>(&h_ridx), max_pairs * sizeof(int), cudaHostAllocPortable), "cudaHostAlloc", err)) return false;
// window tables per pass: grown on demand
if (!so.quiet) std::printf("tier store: filling the hot prefix on the card (%.2f GiB)\n", vp / 1073741824.0);
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;
S.load_s = now_s() - t0;
if (so.verify && !verify(err)) return false;
@@ -277,6 +292,7 @@ struct ExpertStore::Impl {
if (const char* e = std::getenv("STRATA_L32_PF_SCAN")) pf_scan = std::max(1, std::min(std::atoi(e), 32));
if (const char* e = std::getenv("STRATA_L32_PF_SSD_INFLIGHT")) pf_ssd_cap = std::max(0, std::atoi(e));
if (const char* e = std::getenv("STRATA_L32_PF_SSD_IDLE")) pf_ssd_idle = e[0] == '1';
if (const char* e = std::getenv("STRATA_L32_PF_VERIFY")) pf_verify = std::max(0, std::min(std::atoi(e), 64));
if (const char* e = std::getenv("STRATA_L32_PF_NOSSD")) pf_nossd = e[0] == '1';
if (const char* e = std::getenv("STRATA_L32_PF_NOPROMOTE")) pf_nopromote = e[0] == '1';
cudaEventCreateWithFlags(&route_ev, cudaEventDisableTiming);
@@ -363,6 +379,7 @@ struct ExpertStore::Impl {
if (!cs[i].ok || cs[i].bytes != len) { err = "tier store: a read of the warm prefix failed"; return false; }
++finished;
last_progress = now_s();
if (!so.quiet && finished % 128 == 0) std::printf("tier store: warm prefix read %.1f of %.1f GiB\n", finished * double(kPiece) / 1073741824.0, rp / 1073741824.0);
}
if (now_s() - last_progress > 300) { err = "tier store: the warm-prefix read stalled"; return false; }
}
@@ -976,6 +993,9 @@ 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);
}
void on_prediction(int il, int k, const int* ranked, int n, int top_n) {
Req r;
{
@@ -1000,7 +1020,7 @@ struct ExpertStore::Impl {
}
}
if (n == 1 && plan.prefetch_width <= 0) return; // decode prefetch off
if (n > 1 && n < so.prefill_min_batch) return; // too small a batch for a union prefetch to pay
if (n > 1 && n < so.prefill_min_batch && !(pf_verify > 0 && n <= 16)) return; // too small a batch for a union prefetch to pay
}
r.il = il;
r.k = k;
@@ -1092,21 +1112,22 @@ struct ExpertStore::Impl {
std::lock_guard<std::mutex> lk(mu);
if (r.fwd != fwd_id || r.il <= cur_layer) { ++S.pf_stale; return; }
const int base = (r.il - first_k) * E;
const int limit = r.n == 1 ? plan.prefetch_width : so.prefill_budget;
const bool decodeish = r.n == 1 || r.n < so.prefill_min_batch; // a decode token or a speculative verify batch (small): decode-style limits
const int limit = r.n == 1 ? plan.prefetch_width : (decodeish ? pf_verify : so.prefill_budget);
int issued = 0;
uint64_t inflight = 0; // bytes of prefetch copies that have not finished: demand copies must not queue behind a long prefetch queue
if (inflight_cap)
for (const Dyn& d : dyn)
if (d.state == 2 && d.pf && !d.used && d.ev_valid && cudaEventQuery(d.ev) != cudaSuccess) inflight += ed[static_cast<size_t>(d.gi)].body_bytes;
int rd_pf = 0, rd_dem = 0; // SSD reads not finished: prefetch ones, demand ones (a demand read queues behind everything issued before it)
if (r.n == 1 && (pf_ssd_cap || pf_ssd_idle))
if (decodeish && (pf_ssd_cap || pf_ssd_idle))
for (const Ring& rg : ring) if (rg.state == 1) { if (rg.promote) ++rd_pf; else ++rd_dem; }
const size_t scan_n = r.n == 1 ? std::min<size_t>(r.ranked.size(), static_cast<size_t>(std::max(1, pf_scan))) : r.ranked.size(); // the rank cut-off is the confidence gate
for (size_t qi = 0; qi < scan_n; ++qi) {
const int e = r.ranked[qi];
if (e < 0 || e >= E) continue;
if (issued >= limit) break;
if (inflight_cap && inflight + ed[static_cast<size_t>(base + e)].body_bytes > inflight_cap && r.n == 1) { ++S.pf_inflight_skips; break; }
if (inflight_cap && inflight + ed[static_cast<size_t>(base + e)].body_bytes > inflight_cap && decodeish) { ++S.pf_inflight_skips; break; }
const int gi = base + e;
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; }
@@ -1129,7 +1150,7 @@ struct ExpertStore::Impl {
} else {
if (ring_of[static_cast<size_t>(gi)] >= 0) { ++S.pf_skipped_resident; continue; }
if (ring.empty() || pf_nossd) continue;
if (r.n == 1 && ((pf_ssd_cap && rd_pf >= pf_ssd_cap) || (pf_ssd_idle && rd_dem > 0))) { ++S.pf_inflight_skips; break; }
if (decodeish && ((pf_ssd_cap && rd_pf >= pf_ssd_cap) || (pf_ssd_idle && rd_dem > 0))) { ++S.pf_inflight_skips; break; }
const int rs = alloc_ring(false, 0);
if (rs < 0) { ++S.pf_no_slot; break; }
Ring& rg = ring[static_cast<size_t>(rs)];
@@ -1232,6 +1253,7 @@ const uint8_t* const* ExpertStore::next_pass(int j, void* stream) { return p_->n
void ExpertStore::begin_forward(int n) { p_->begin_forward(n); }
void ExpertStore::end_forward() { p_->end_forward(); }
void ExpertStore::on_prediction(int il, int k, const int* ranked, int n, int top_n) { p_->on_prediction(il, k, ranked, n, top_n); }
bool ExpertStore::wants_prediction(int n) const { return p_->wants(n); }
TierStats ExpertStore::stats() const { return p_->snapshot(); }
void ExpertStore::reset_stats() { p_->reset_stats(); }
void ExpertStore::set_prefetch_width(int w) { std::lock_guard<std::mutex> lk(p_->mu); p_->plan.prefetch_width = std::max(0, w); }
+1
View File
@@ -51,6 +51,7 @@ public:
void end_forward() override;
// DemandSink
void on_prediction(int target_layer, int k, const int* ranked, int n_tokens, int top_n) override;
bool wants_prediction(int n_tokens) const override;
TierStats stats() const;
void reset_stats();