diff --git a/core/config.cpp b/core/config.cpp index 20db0b2d..972b192f 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -293,6 +293,10 @@ static const Flag g_flags[] = { " implementation is an oracle and a last resort, and falling back\n" " to it is orders of magnitude of speed with nothing to say so." }, { "--profile-ops", nullptr, "per-op device timing (see the caveat it prints)" }, + { "--expert-stats", "FILE", "count the routed experts every layer selects, apart for prefill, decode,\n" + " mixed steps and draft-head passes, and write the counts to FILE as\n" + " JSON every 30 s and at shutdown. From the routing histograms the core\n" + " already copies back: no device work, no synchronisation" }, { "--live", nullptr, "the live view: cards, throughput, draft acceptance, the expert plane.\n" " Redirected it prints one greppable key=value line instead" }, { "-v", nullptr, "verbose" }, @@ -908,6 +912,7 @@ int config_parse(int argc, char** argv, Config* c) { else if (S("--debug-placement")) c->debug_placement = true; else if (S("--debug-accept-reference-kernels")) c->accept_reference_kernels = true; else if (S("--profile-ops")) c->profile_ops = true; + else if (S("--expert-stats")) { if (!(v = need(i))) return RAD_E_INVAL; c->expert_stats = v; } else if (S("--live")) c->live_view = true; else { RAD_ERR("unknown option '%s'", a.c_str()); @@ -1228,6 +1233,7 @@ const ShowRow kShow[] = { { "--debug-placement", [](const Config& c) { return onoff(c.debug_placement); } }, { "--debug-accept-reference-kernels", [](const Config& c) { return onoff(c.accept_reference_kernels); } }, { "--profile-ops", [](const Config& c) { return onoff(c.profile_ops); } }, + { "--expert-stats", [](const Config& c) { return or_none(c.expert_stats, "off"); } }, { "--live", [](const Config& c) { return onoff(c.live_view); } }, { "-v", [](const Config& c) { return onoff(c.given.count("-v") > 0); } }, { "-vv", [](const Config& c) { return onoff(c.given.count("-vv") > 0); } }, diff --git a/core/engine.cpp b/core/engine.cpp index 4dd616e6..6631b147 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -31,8 +31,10 @@ #include #include #include +#include #include #include +#include #include #include #include @@ -203,11 +205,9 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool * `heat_seen` prevents crediting a bank twice: a bank keeps its counts until the next report, so a * step where a layer did not route (a drafter pass) would re-credit the stale plane. */ -void Engine::tiering_dispatch(Rank& r, int step) { - if (!r.heat.enabled()) return; - - r.mover.begin_dispatch(step, &r.heat); - +/* Every landed histogram of a step before `before_step`, oldest first per layer, into + * `r.heat_rows`; nothing is credited yet. */ +void Engine::find_histograms(Rank& r, int before_step) { const int n_layer = r.ctx.n_route_layers(); if ((int)r.heat_seen.size() != n_layer) r.heat_seen.assign((size_t)n_layer, -1); /* Find all histograms first, then credit them in order. Each is a card-written row in host @@ -224,7 +224,7 @@ void Engine::tiering_dispatch(Rank& r, int step) { int seen = r.heat_seen[(size_t)l]; bool any = false; for (;;) { - const int bank = r.ctx.next_histogram(l, seen, step, landed); + const int bank = r.ctx.next_histogram(l, seen, before_step, landed); if (bank < 0) break; const int32_t* h = r.ctx.last_histogram(l, bank); if (!h) break; @@ -234,8 +234,46 @@ void Engine::tiering_dispatch(Rank& r, int step) { } if (!any) ++r.heat_idle; } +} + +/* --expert-stats: one found histogram into the rank's tally (place/xstats.h), from the same row + * the heat engine reads. The caller holds the tally. */ +static void xstats_credit(XsTally* xs, Ctx& ctx, int layer, int bank, const int32_t* h) { + const RadRouting* rt = ctx.last_routing(layer); + const int64_t n = rt ? std::min(rt->n_expert, ctx.route_n_expert()) : 0; + xs->credit(layer, ctx.last_histogram_step(layer, bank), h, n, + ctx.last_histogram_reports(layer, bank), rt ? rt->top_k : 0); +} + +/* The drain alone, for the tally, where the heat engine is off or the engine is stopping + * (`before_step` INT_MAX once the streams are drained). */ +void Engine::xstats_drain(Rank& r, XsTally* xs, int before_step) { + find_histograms(r, before_step); + std::lock_guard lk(xs->mutex()); + for (const Rank::HeatRow& hr : r.heat_rows) { + xstats_credit(xs, r.ctx, hr.layer, hr.bank, hr.h); + r.heat_seen[(size_t)hr.layer] = r.ctx.last_histogram_step(hr.layer, hr.bank); + r.ctx.mark_credited(hr.layer, hr.bank); + ++r.heat_credited; + } + xs->note_dropped(r.ctx.route_dropped()); +} + +void Engine::tiering_dispatch(Rank& r, int step) { + XsTally* const xs = xstats_ ? xstats_->tally(r.index) : nullptr; + if (!r.heat.enabled()) { + if (xs) xstats_drain(r, xs, step); + return; + } + + r.mover.begin_dispatch(step, &r.heat); + + find_histograms(r, step); + std::vector& rows = r.heat_rows; const int32_t n_ex = (int32_t)r.ctx.route_n_expert(); constexpr size_t kAhead = 2; + std::unique_lock xl; + if (xs) xl = std::unique_lock(xs->mutex()); for (size_t i = 0; i < rows.size() && i < kAhead; ++i) r.heat.prefetch(rows[i].h, n_ex); for (size_t i = 0; i < rows.size(); ++i) { if (i + kAhead < rows.size()) r.heat.prefetch(rows[i + kAhead].h, n_ex); @@ -244,10 +282,16 @@ void Engine::tiering_dispatch(Rank& r, int step) { * weight it by the report count, or the layer's experts are underpriced and drained. */ const int reps = r.ctx.last_histogram_reports(hr.layer, hr.bank); r.heat.observe(hr.layer, hr.h, n_ex, reps > 1 ? (float)reps : 1.0f); + /* The row is in cache now. */ + if (xs) xstats_credit(xs, r.ctx, hr.layer, hr.bank, hr.h); r.heat_seen[(size_t)hr.layer] = r.ctx.last_histogram_step(hr.layer, hr.bank); r.ctx.mark_credited(hr.layer, hr.bank); ++r.heat_credited; } + if (xs) { + xs->note_dropped(r.ctx.route_dropped()); + xl.unlock(); + } /* No swaps behind a pass the stager armed: that step is bound by its own copies on the same * transfer stream, and the turnover slots are filled for it (below). Histograms are still @@ -278,6 +322,93 @@ void Engine::tiering_dispatch(Rank& r, int step) { r.mover.hold_turnover(hold); (void)r.mover.balance(&r.heat, !hold); } + +/* ------------------------------------------------------------------ --expert-stats + * + * Which model-wide expert each index of each rank's histogram is (place/xstats.h, XsMap): index e + * is the rank's unit with group expert e, and the container's directory entry for that unit's + * weight names the expert in the model's numbering. A checkpoint served directly has no such entry + * and the map falls back to rank order. */ +int Engine::xstats_open() { + if (cfg_.expert_stats.empty()) return RAD_OK; + const int n_layer = ranks_[0]->ctx.n_route_layers(); + if (n_layer <= 0) { + RAD_WARN("--expert-stats: '%s' routes no experts; there is nothing to count and %s is not " + "written", meta_.name ? meta_.name : "the model", cfg_.expert_stats.c_str()); + return RAD_OK; + } + constexpr int32_t kUnset = INT32_MIN, kClash = -3; + std::vector>> ids(ranks_.size()); + for (size_t ri = 0; ri < ranks_.size(); ++ri) { + const Program& P = ranks_[ri]->program; + auto& layers = ids[ri]; + layers.assign((size_t)n_layer, {}); + for (size_t w = 1; w < P.weights.size(); ++w) { + const WeightInfo& wi = P.weights[w]; + const int32_t l = wi.decl.group.layer, e = wi.decl.group.expert; + if (l < 0 || l >= n_layer || e < 0) continue; + std::vector& row = layers[(size_t)l]; + if ((size_t)e >= row.size()) row.resize((size_t)e + 1, kUnset); + const RadFileEntry* fe = file_ ? file_->find(wi.source) : nullptr; + const int32_t g = fe && fe->layer == l && fe->expert >= 0 ? fe->expert : -1; + int32_t& at = row[(size_t)e]; + /* Every weight of one unit must name the same expert. */ + at = at == kUnset ? g : at == g ? at : kClash; + } + for (auto& row : layers) + for (int32_t& v : row) if (v == kUnset || v < 0) v = -1; + } + std::vector n_model((size_t)n_layer, 0); + for (int l = 0; l < n_layer && l < meta_.n_layers; ++l) n_model[(size_t)l] = (int32_t)meta_.n_expert; + XsMap map; + RAD_TRY(xs_map_build(ids, n_model, (int32_t)meta_.n_layers, &map)); + + XsSnapshot info; + info.model = meta_.name ? meta_.name : ""; + info.arch = meta_.arch_id ? meta_.arch_id : ""; + info.container = cfg_.model; + xstats_ = std::make_unique(); + if (const int st = xstats_->init(cfg_.expert_stats, map, std::move(info)); st < 0) { + RAD_ERR("--expert-stats: cannot write %s", cfg_.expert_stats.c_str()); + xstats_.reset(); + return st; + } + std::map how; + int32_t mx = 0; + for (int l = 0; l < n_layer; ++l) { + if (map.n_expert[(size_t)l] <= 0) continue; + ++how[map.how[(size_t)l]]; + mx = std::max(mx, map.n_expert[(size_t)l]); + } + std::string hs; + for (const auto& [k, v] : how) hs += fmt("%s%d by %s", hs.empty() ? "" : ", ", v, k.c_str()); + int counting = 0; + for (size_t ri = 0; ri < ranks_.size(); ++ri) counting += xstats_->tally((int)ri) != nullptr; + RAD_INFO("expert stats: %d routed layers (up to %d experts; ids %s), counted on %d of %d " + "rank%s, written to %s every 30 s and at shutdown", + n_layer, (int)mx, hs.c_str(), counting, cfg_.tp, cfg_.tp == 1 ? "" : "s", + cfg_.expert_stats.c_str()); + xstats_->start(); + return RAD_OK; +} + +void Engine::xstats_close() { + if (!xstats_) return; + xstats_->stop(); + /* The banks of the last steps are still in the ring: drain each counting rank's stream, then + * credit them. Not after a step-loop error, where a stream may never drain. */ + if (loop_status_.load(std::memory_order_acquire) >= 0) { + for (auto& r : ranks_) { + XsTally* xs = xstats_->tally(r->index); + if (!xs) continue; + if (rad_dev_set(r->device) < 0 || rad_stream_sync(r->ctx.stream()) < 0) continue; + xstats_drain(*r, xs, INT_MAX); + } + if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device); + } + (void)xstats_->write(true); +} + /* ------------------------------------------------------------------ the rank thread */ void Engine::rank_loop(int index) { Rank& r = *ranks_[(size_t)index]; @@ -303,6 +434,10 @@ void Engine::rank_loop(int index) { } b = mine; const int what = issue_what_.load(std::memory_order_acquire); + /* --expert-stats files each pass's step kind for the drain, which reads it a step or + * more later. An encoder pass is not a step of the token stream. */ + if (xstats_ && what != kIssueSampler && b->enc == 0) + if (XsTally* xs = xstats_->tally(index)) xs->issued(*b); int s = what == kIssueSampler ? RAD_OK : r.ctx.run_step(b); if (s < 0) { RAD_ERR("rank %d step %d: %s", index, b->step, r.ctx.step_error()); @@ -1775,6 +1910,8 @@ int Engine::serve(std::unique_ptr watch) { for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get()); + if (const int xs = xstats_open(); xs < 0) return xs; + barrier_ = std::make_unique(cfg_.tp + 1); stopping_.store(false, std::memory_order_release); step_status_.store(RAD_OK, std::memory_order_release); @@ -1799,6 +1936,7 @@ int Engine::serve(std::unique_ptr watch) { if (stepper.joinable()) stepper.join(); for (auto& t : rank_threads_) if (t.joinable()) t.join(); rank_threads_.clear(); + xstats_close(); /* A step-loop error takes precedence over the transport's status. */ const int ls = loop_status_.load(std::memory_order_acquire); return ls < 0 ? ls : s; @@ -1932,6 +2070,8 @@ std::string Engine::engine_info() const { sp["depth"] = drafter_.depth; } e["speculation"] = std::move(sp); + /* --expert-stats: where the counts are, for a client that reads them. */ + if (xstats_) e["expert_stats"] = { { "file", xstats_->path() }, { "interval_s", 30 } }; return e.dump(); } diff --git a/core/engine.h b/core/engine.h index 786b9870..649fc2fa 100644 --- a/core/engine.h +++ b/core/engine.h @@ -51,6 +51,8 @@ namespace gen { class Driver; class AudioDriver; class VideoDriver; struct IPass struct TierPump; struct TierJob; struct StepSlot; +class ExpertStats; /* place/xstats.h */ +class XsTally; struct VramFacts; /* mem/vram_budget.h */ struct WeightFootprint; /* place/planner.h */ @@ -145,6 +147,9 @@ private: /* The source rad_weight_encoding answers from: container entries or checkpoint tensors. */ WeightSourceFn sources() const; + /* --expert-stats FILE (place/xstats.h); null without the flag. */ + std::unique_ptr xstats_; + RadModelMeta meta_{}; LoadedPlugins plugins_; @@ -599,6 +604,14 @@ private: * what the heat engine proposes. A member because Rank is private; a no-op on a static plan. * The definition explains why a step is the unit. */ void tiering_dispatch(Rank& r, int step); + /* The routing histograms landed since the last drain (tiering_dispatch), and the drain alone + * for --expert-stats where the heat engine is off. */ + void find_histograms(Rank& r, int before_step); + void xstats_drain(Rank& r, XsTally* xs, int before_step); + /* --expert-stats: the map and the file, opened before the rank threads start; closed after they + * stop, crediting what the ring still holds once the streams are drained. */ + int xstats_open(); + void xstats_close(); void rank_loop(int rank); }; diff --git a/core/engine_priv.h b/core/engine_priv.h index b762a3a3..4a9305f6 100644 --- a/core/engine_priv.h +++ b/core/engine_priv.h @@ -22,6 +22,7 @@ #include "place/planner.h" #include "place/mover.h" #include "place/stager.h" +#include "place/xstats.h" #include "runtime/ctx.h" #include "sample/sampler.h" #include "sched/advance.h" diff --git a/core/place/xstats.cpp b/core/place/xstats.cpp new file mode 100644 index 00000000..38199713 --- /dev/null +++ b/core/place/xstats.cpp @@ -0,0 +1,482 @@ +/* xstats.cpp -- the --expert-stats tally, its merge across ranks and its file. See xstats.h. */ +#include "xstats.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rad { + +const char* xs_kind_name(int kind) { + switch (kind) { + case kXsPrefill: return "prefill"; + case kXsDecode: return "decode"; + case kXsMixed: return "mixed"; + case kXsDraft: return "draft"; + default: return "?"; + } +} + +/* ------------------------------------------------------------------ the map */ + +int xs_map_build(const std::vector>>& ids, + const std::vector& n_model, int32_t n_trunk, XsMap* out) { + if (!out || ids.empty()) return RAD_E_INVAL; + const int32_t R = (int32_t)ids.size(); + int32_t L = 0; + for (const auto& r : ids) L = std::max(L, (int32_t)r.size()); + out->n_rank = R; + out->n_layer = L; + out->n_trunk = std::max(0, std::min(n_trunk, L)); + out->n_expert.assign((size_t)L, 0); + out->how.assign((size_t)L, "none"); + out->gid.assign((size_t)R, std::vector>((size_t)L)); + constexpr int32_t kMaxId = 1 << 20; + + for (int32_t l = 0; l < L; ++l) { + std::vector n((size_t)R, 0); + bool any = false; + for (int32_t r = 0; r < R; ++r) { + n[(size_t)r] = (size_t)l < ids[(size_t)r].size() ? ids[(size_t)r][(size_t)l].size() : 0; + any = any || n[(size_t)r] > 0; + } + if (!any) continue; + for (int32_t r = 0; r < R; ++r) out->gid[(size_t)r][(size_t)l].assign(n[(size_t)r], XsMap::kUnknown); + + /* The container's ids, when every index of every rank has one, distinct within the rank. */ + bool ok = true; + int32_t mx = -1; + for (int32_t r = 0; r < R && ok; ++r) { + std::set seen; + for (size_t e = 0; e < n[(size_t)r] && ok; ++e) { + const int32_t g = ids[(size_t)r][(size_t)l][e]; + if (g < 0 || g >= kMaxId || !seen.insert(g).second) ok = false; + else mx = std::max(mx, g); + } + } + if (ok) { + /* An expert several ranks hold (a width slice each) is counted on the lowest. */ + std::vector owned((size_t)mx + 1, 0); + for (int32_t r = 0; r < R; ++r) + for (size_t e = 0; e < n[(size_t)r]; ++e) { + const int32_t g = ids[(size_t)r][(size_t)l][e]; + if (owned[(size_t)g]) { + out->gid[(size_t)r][(size_t)l][e] = XsMap::kElsewhere; + } else { + owned[(size_t)g] = 1; + out->gid[(size_t)r][(size_t)l][e] = g; + } + } + out->n_expert[(size_t)l] = mx + 1; + out->how[(size_t)l] = "container"; + continue; + } + + /* No ids: the indices are the model's on one rank, or where every rank holds the model's + * count; otherwise each rank holds a run of its own, in rank order. */ + bool same = true; + for (int32_t r = 1; r < R; ++r) same = same && n[(size_t)r] == n[0]; + const int64_t nm = (size_t)l < n_model.size() ? n_model[(size_t)l] : 0; + if (R == 1 || (same && nm > 0 && (int64_t)n[0] == nm)) { + for (int32_t r = 0; r < R; ++r) + for (size_t e = 0; e < n[(size_t)r]; ++e) + out->gid[(size_t)r][(size_t)l][e] = r == 0 ? (int32_t)e : XsMap::kElsewhere; + out->n_expert[(size_t)l] = (int32_t)n[0]; + out->how[(size_t)l] = R == 1 ? "index" : "replicated"; + } else { + int64_t base = 0; + for (int32_t r = 0; r < R; ++r) { + for (size_t e = 0; e < n[(size_t)r]; ++e) + out->gid[(size_t)r][(size_t)l][e] = (int32_t)(base + (int64_t)e); + base += (int64_t)n[(size_t)r]; + } + out->n_expert[(size_t)l] = (int32_t)base; + out->how[(size_t)l] = "rank order"; + if (nm > 0 && base != nm) + RAD_WARN("--expert-stats: layer %d's ranks hold %lld experts between them, the model " + "%lld; its counts are numbered in rank order regardless", + (int)l, (long long)base, (long long)nm); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ one rank's tally */ + +void XsTally::init(const XsMap* map, int rank) { + map_ = map; + rank_ = rank; + ring_.assign((size_t)kRing, Rec{}); + const size_t L = (size_t)map->n_layer; + off_.assign(L + 1, 0); + for (size_t l = 0; l < L; ++l) off_[l + 1] = off_[l] + (size_t)map->n_expert[l]; + for (int k = 0; k < kXsKinds; ++k) { + counts_[k].assign(off_[L], 0); + hist_[k].assign(L, 0); + passes_[k].assign(L, 0); + tok_[k].assign(L, 0); + sel_[k].assign(L, 0); + steps_[k] = tokens_[k] = 0; + } + top_k_.assign(L, 0); + mixed_decode_ = draft_passes_ = draft_rows_ = 0; + credited_ = unmapped_ = unclassified_ = dropped_ = 0; +} + +void XsTally::issued(const RadBatch& b) { + issued(b.step, b.draft_pass, b.n_seq, b.n_seq_decode, b.n_tok, b.n_tok_decode); +} + +void XsTally::issued(int step, int draft_pass, int64_t n_seq, int64_t n_seq_decode, int64_t n_tok, + int64_t n_tok_decode) { + if (step < 0) return; + std::lock_guard lk(mu_); + Rec& r = ring_[(size_t)(step % kRing)]; + if (r.step != step) { + r = Rec{}; + r.step = step; + } + if (draft_pass == 0) { + const int k = xs_trunk_kind(n_seq, n_seq_decode); + r.kind = (uint8_t)k; + r.trunk = true; + r.n_tok = n_tok; + ++steps_[k]; + tokens_[k] += (uint64_t)std::max(n_tok, 0); + if (k == kXsMixed) mixed_decode_ += (uint64_t)std::max(n_tok_decode, 0); + } else { + /* Each draft pass overwrites the head's row, so the bank holds the last pass's rows. */ + r.draft_rows = n_tok; + ++draft_passes_; + draft_rows_ += (uint64_t)std::max(n_tok, 0); + } +} + +void XsTally::credit(int layer, int step, const int32_t* counts, int64_t n, int reports, + int64_t top_k) { + if (!map_ || !counts || layer < 0 || layer >= map_->n_layer || step < 0) return; + const Rec& r = ring_[(size_t)(step % kRing)]; + const bool known = r.step == step; + int kind; + int64_t toks = 0; + if (layer >= map_->n_trunk) { + kind = kXsDraft; + if (known) toks = r.draft_rows; + else ++unclassified_; + } else if (known && r.trunk) { + kind = r.kind; + toks = r.n_tok; + } else { + kind = kXsMixed; + ++unclassified_; + } + + const std::vector& g = map_->gid[(size_t)rank_][(size_t)layer]; + const int64_t m = std::min(n, (int64_t)g.size()); + uint64_t* const plane = counts_[kind].data() + off_[(size_t)layer]; + uint64_t sel = 0; + for (int64_t e = 0; e < m; ++e) { + const int32_t c = counts[e]; + if (c <= 0) continue; + const int32_t gi = g[(size_t)e]; + if (gi >= 0) { + plane[gi] += (uint64_t)c; + sel += (uint64_t)c; + } else if (gi == XsMap::kUnknown) { + unmapped_ += (uint64_t)c; + } + } + for (int64_t e = m; e < n; ++e) + if (counts[e] > 0) unmapped_ += (uint64_t)counts[e]; + + ++hist_[kind][(size_t)layer]; + passes_[kind][(size_t)layer] += (uint64_t)std::max(reports, 1); + tok_[kind][(size_t)layer] += (uint64_t)std::max(toks, 0); + sel_[kind][(size_t)layer] += sel; + if (top_k > top_k_[(size_t)layer]) top_k_[(size_t)layer] = (int32_t)top_k; + ++credited_; +} + +void XsTally::snapshot_into(XsSnapshot* s, const std::vector& token_rank, bool issued) { + std::lock_guard lk(mu_); + const size_t L = (size_t)map_->n_layer; + for (int k = 0; k < kXsKinds; ++k) { + for (size_t l = 0; l < L; ++l) { + std::vector& row = s->counts[k][l]; + const uint64_t* src = counts_[k].data() + off_[l]; + for (size_t e = 0; e < row.size(); ++e) row[e] += src[e]; + s->selections[k][l] += sel_[k][l]; + if (l < token_rank.size() && token_rank[l] == rank_) { + s->histograms[k][l] = hist_[k][l]; + s->passes[k][l] = passes_[k][l]; + s->obs_tokens[k][l] = tok_[k][l]; + } + } + if (issued) { + s->steps[k] = steps_[k]; + s->tokens[k] = tokens_[k]; + } + } + if (issued) { + s->mixed_decode_tokens = mixed_decode_; + s->draft_passes = draft_passes_; + s->draft_rows = draft_rows_; + } + for (size_t l = 0; l < L; ++l) s->top_k[l] = std::max(s->top_k[l], top_k_[l]); + s->rank_credited[(size_t)rank_] = credited_; + s->rank_unmapped[(size_t)rank_] = unmapped_; + s->rank_unclassified[(size_t)rank_] = unclassified_; + s->rank_dropped[(size_t)rank_] = dropped_; +} + +/* ------------------------------------------------------------------ the file */ + +namespace { + +void put_u64s(std::string& o, const std::vector& v) { + o += '['; + for (size_t i = 0; i < v.size(); ++i) { + if (i) o += ','; + o += std::to_string(v[i]); + } + o += ']'; +} + +void put_i32s(std::string& o, const std::vector& v) { + o += '['; + for (size_t i = 0; i < v.size(); ++i) { + if (i) o += ','; + o += std::to_string(v[i]); + } + o += ']'; +} + +std::string jstr(const std::string& s) { return nlohmann::json(s).dump(); } + +/* {"prefill": f(0), "decode": f(1), ...} on one line. */ +template +void put_kinds(std::string& o, F f) { + o += '{'; + for (int k = 0; k < kXsKinds; ++k) { + if (k) o += ", "; + o += jstr(xs_kind_name(k)); + o += ": "; + f(o, k); + } + o += '}'; +} + +} /* namespace */ + +std::string xs_json(const XsSnapshot& s) { + std::string o; + o.reserve(4096 + (size_t)s.n_layer * (size_t)std::max(s.n_expert, 1) * kXsKinds * 4); + o += "{\n"; + o += " \"format\": \"radiance-expert-stats/1\",\n"; + o += " \"model\": " + jstr(s.model) + ",\n"; + o += " \"arch\": " + jstr(s.arch) + ",\n"; + o += " \"container\": " + jstr(s.container) + ",\n"; + o += " \"tp\": " + std::to_string(s.tp) + ",\n"; + o += std::string(" \"final\": ") + (s.final_ ? "true" : "false") + ",\n"; + o += " \"written_unix\": " + std::to_string(s.written_unix) + ",\n"; + char up[64]; + snprintf(up, sizeof up, "%.1f", s.uptime_s); + o += std::string(" \"uptime_s\": ") + up + ",\n"; + o += " \"n_layers\": " + std::to_string(s.n_layer) + ",\n"; + o += " \"n_trunk_layers\": " + std::to_string(s.n_trunk) + ",\n"; + o += " \"n_experts\": " + std::to_string(s.n_expert) + ",\n"; + o += " \"layer_experts\": "; + put_i32s(o, s.layer_experts); + o += ",\n \"top_k\": "; + put_i32s(o, s.top_k); + o += ",\n \"map\": ["; + for (size_t l = 0; l < s.how.size(); ++l) o += (l ? "," : "") + jstr(s.how[l]); + o += "],\n \"kinds\": ["; + for (int k = 0; k < kXsKinds; ++k) o += (k ? "," : "") + jstr(xs_kind_name(k)); + o += "],\n"; + /* Issued: trunk steps and tokens by kind; the draft kind's are passes and rows. */ + o += " \"steps\": "; + put_kinds(o, [&](std::string& x, int k) { + x += std::to_string(k == kXsDraft ? s.draft_passes : s.steps[k]); + }); + o += ",\n \"tokens\": "; + put_kinds(o, [&](std::string& x, int k) { + x += std::to_string(k == kXsDraft ? s.draft_rows : s.tokens[k]); + }); + o += ",\n \"mixed_decode_tokens\": " + std::to_string(s.mixed_decode_tokens); + auto per_layer = [&](const char* name, const std::vector* v) { + o += ",\n \""; + o += name; + o += "\": "; + put_kinds(o, [&](std::string& x, int k) { put_u64s(x, v[k]); }); + }; + per_layer("histograms", s.histograms); + per_layer("passes", s.passes); + per_layer("observed_tokens", s.obs_tokens); + per_layer("selections", s.selections); + o += ",\n \"ranks\": {\"credited\": "; + put_u64s(o, s.rank_credited); + o += ", \"unmapped\": "; + put_u64s(o, s.rank_unmapped); + o += ", \"unclassified\": "; + put_u64s(o, s.rank_unclassified); + o += ", \"dropped\": "; + put_u64s(o, s.rank_dropped); + o += "},\n \"counts\": {"; + for (int k = 0; k < kXsKinds; ++k) { + o += k ? ",\n " : "\n "; + o += jstr(xs_kind_name(k)); + o += ": ["; + for (size_t l = 0; l < s.counts[k].size(); ++l) { + o += l ? ",\n " : "\n "; + put_u64s(o, s.counts[k][l]); + } + o += "\n ]"; + } + o += "\n }\n}\n"; + return o; +} + +int xs_write_atomic(const std::string& path, const std::string& text) { + const std::string tmp = path + ".tmp." + std::to_string((long long)getpid()); + FILE* f = std::fopen(tmp.c_str(), "w"); + if (!f) { + RAD_WARN("--expert-stats: cannot write %s: %s", tmp.c_str(), std::strerror(errno)); + return RAD_E_IO; + } + const bool wrote = std::fwrite(text.data(), 1, text.size(), f) == text.size() && + std::fflush(f) == 0 && fsync(fileno(f)) == 0; + const int err = errno; + if (std::fclose(f) != 0 || !wrote) { + RAD_WARN("--expert-stats: writing %s failed: %s", tmp.c_str(), std::strerror(wrote ? errno : err)); + ::unlink(tmp.c_str()); + return RAD_E_IO; + } + if (std::rename(tmp.c_str(), path.c_str()) != 0) { + RAD_WARN("--expert-stats: %s -> %s: %s", tmp.c_str(), path.c_str(), std::strerror(errno)); + ::unlink(tmp.c_str()); + return RAD_E_IO; + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ the engine's side */ + +int ExpertStats::init(const std::string& path, const XsMap& map, XsSnapshot info, + double interval_s) { + if (path.empty() || map.n_rank <= 0) return RAD_E_INVAL; + path_ = path; + map_ = map; + info_ = std::move(info); + interval_s_ = interval_s > 0.0 ? interval_s : 30.0; + t0_ns_ = rad_mono_ns(); + + const size_t R = (size_t)map_.n_rank, L = (size_t)map_.n_layer; + tallies_.clear(); + counts_on_.assign(R, 0); + token_rank_.assign(L, -1); + for (size_t r = 0; r < R; ++r) { + tallies_.push_back(std::make_unique()); + tallies_.back()->init(&map_, (int)r); + for (size_t l = 0; l < L; ++l) + for (int32_t g : map_.gid[r][l]) + if (g != XsMap::kElsewhere) { + counts_on_[r] = 1; + if (token_rank_[l] < 0) token_rank_[l] = (int32_t)r; + break; + } + } + issued_rank_ = -1; + for (size_t r = 0; r < R; ++r) + if (counts_on_[r]) { issued_rank_ = (int32_t)r; break; } + /* The file appears at boot, so a path that cannot be written fails here, not 30 s in. */ + return write(false); +} + +XsSnapshot ExpertStats::snapshot() { + XsSnapshot s = info_; + const size_t R = (size_t)map_.n_rank, L = (size_t)map_.n_layer; + s.tp = map_.n_rank; + s.n_layer = map_.n_layer; + s.n_trunk = map_.n_trunk; + s.n_expert = 0; + for (int32_t n : map_.n_expert) s.n_expert = std::max(s.n_expert, n); + s.layer_experts = map_.n_expert; + s.how = map_.how; + s.top_k.assign(L, 0); + for (int k = 0; k < kXsKinds; ++k) { + s.histograms[k].assign(L, 0); + s.passes[k].assign(L, 0); + s.obs_tokens[k].assign(L, 0); + s.selections[k].assign(L, 0); + s.counts[k].assign(L, {}); + for (size_t l = 0; l < L; ++l) s.counts[k][l].assign((size_t)map_.n_expert[l], 0); + } + s.rank_credited.assign(R, 0); + s.rank_unmapped.assign(R, 0); + s.rank_unclassified.assign(R, 0); + s.rank_dropped.assign(R, 0); + for (size_t r = 0; r < R; ++r) + if (counts_on_[r]) tallies_[r]->snapshot_into(&s, token_rank_, (int32_t)r == issued_rank_); + s.uptime_s = (double)(rad_mono_ns() - t0_ns_) * 1e-9; + s.written_unix = (int64_t)std::time(nullptr); + return s; +} + +int ExpertStats::write(bool final_) { + std::lock_guard lk(file_mu_); + XsSnapshot s = snapshot(); + s.final_ = final_; + const int st = xs_write_atomic(path_, xs_json(s)); + if (final_ && st >= 0) { + uint64_t hist = 0, sel = 0; + for (uint64_t v : s.rank_credited) hist += v; + for (int k = 0; k < kXsKinds; ++k) + for (uint64_t v : s.selections[k]) sel += v; + RAD_INFO("expert stats: %llu layer histograms, %llu selections (prefill %llu, decode %llu, " + "mixed %llu tokens; %llu draft passes) written to %s", + (unsigned long long)hist, (unsigned long long)sel, + (unsigned long long)s.tokens[kXsPrefill], (unsigned long long)s.tokens[kXsDecode], + (unsigned long long)s.tokens[kXsMixed], (unsigned long long)s.draft_passes, + path_.c_str()); + } + return st; +} + +void ExpertStats::start() { + if (writer_.joinable()) return; + { + std::lock_guard lk(wmu_); + wstop_ = false; + } + writer_ = std::thread([this] { + const auto every = std::chrono::duration(interval_s_); + for (;;) { + std::unique_lock lk(wmu_); + if (wcv_.wait_for(lk, every, [this] { return wstop_; })) break; + lk.unlock(); + (void)write(false); + } + }); +} + +void ExpertStats::stop() { + { + std::lock_guard lk(wmu_); + wstop_ = true; + } + wcv_.notify_all(); + if (writer_.joinable()) writer_.join(); +} + +ExpertStats::~ExpertStats() { stop(); } + +} /* namespace rad */ diff --git a/core/place/xstats.h b/core/place/xstats.h new file mode 100644 index 00000000..ee5b5df5 --- /dev/null +++ b/core/place/xstats.h @@ -0,0 +1,213 @@ +/* xstats.h -- --expert-stats FILE: which routed experts a served model selects, per layer and per + * step kind, counted on the host from the routing histograms the core already copies back. + * + * ---- where the counts come from --------------------------------------------------------------- + * + * Every routed layer hands its per-expert counts to the core (rad_route_report), which copies the + * pass's rows to a host bank once a pass (Ctx::route_flush) whether or not anything reads them. The + * heat engine drains the landed banks once a step, one step behind (Engine::tiering_dispatch). The + * tally here is credited on that same drain from the same rows, so it adds no device work, no copy + * and no synchronisation; where the heat engine is off (every expert in VRAM, a static plan) the + * drain runs for the tally alone. At shutdown the streams are drained and the banks still in the + * ring are credited, so the file covers every step the engine ran. + * + * ---- what a histogram row is ------------------------------------------------------------------ + * + * Index e of a rank's row is the rank's own expert e: the unit it declared with group expert e, + * the contract the heat engine relies on too. Routing is replicated (every rank scores every + * expert and picks the same top-k), but under expert parallelism a rank counts only the experts it + * holds, numbered from zero (moe_scatter subtracts the rank's first expert). So a row is the + * model's histogram on a rank that holds every expert (one width slice of each), and this rank's + * slice of it otherwise. XsMap says, per rank and layer, which model-wide expert each index is: + * from the container's directory where it numbers the unit's weights (exact for any split), else + * by rank order (the contiguous runs every in-tree expert-parallel split uses). An expert several + * ranks hold is counted on the lowest of them only, since each sees the same routing. + * + * ---- step kinds ------------------------------------------------------------------------------- + * + * A bank holds one step. Trunk layers are filed under the step's kind: prefill (no decode rows), + * decode (only decode rows) or mixed (both, which one histogram cannot split). Routed layers past + * the trunk (an MTP or DSpark head, Ctx::bind_routing) are filed under draft. A head reports once a + * draft pass into the step's bank, each pass overwriting the last, so its bank holds the last pass + * of the step; `passes` counts every pass reported, `tokens` the rows of the pass the bank holds. + * Router weights are not summed: they stay on the card (RadRouting::expert_w is device memory, and + * the in-tree MoE block leaves it null), and copying them back would be new device work. + */ +#pragma once +#include "../rad_core.h" + +#include +#include +#include +#include +#include +#include +#include + +struct RadBatch; + +namespace rad { + +enum XsKind : int { kXsPrefill = 0, kXsDecode = 1, kXsMixed = 2, kXsDraft = 3 }; +constexpr int kXsKinds = 4; +const char* xs_kind_name(int kind); + +/* A trunk pass's kind from its batch shape (RadBatch::n_seq_decode). */ +inline int xs_trunk_kind(int64_t n_seq, int64_t n_seq_decode) { + return n_seq_decode <= 0 ? kXsPrefill : n_seq_decode >= n_seq ? kXsDecode : kXsMixed; +} + +/* Which model-wide expert each index of each rank's histogram row is. */ +struct XsMap { + static constexpr int32_t kElsewhere = -1; /* a lower rank holds and counts this expert */ + static constexpr int32_t kUnknown = -2; /* no model-wide id: counted as unmapped */ + + int32_t n_rank = 0; + int32_t n_layer = 0; /* routed layers, any head past the trunk included */ + int32_t n_trunk = 0; /* layers [0, n_trunk) are the trunk's, the rest draft heads */ + std::vector n_expert; /* [layer]: the model's, 0 where none */ + std::vector>> gid; /* [rank][layer][local] */ + std::vector how; /* [layer]: "container", "rank order", + * "replicated" or "none" */ +}; + +/* Builds the map from what each rank declared. + * + * ids[r][l][e] the model-wide id the container gives rank r's expert e of layer l (the + * directory entry of the unit's weight), or -1 where it gives none. Its size per + * layer is the rank's expert count there; a hole (no unit at e) is -1 too. + * n_model[l] the model's expert count where the caller knows it (the container's n_expert + * for trunk layers), 0 where not. + * + * Per layer, when every index of every rank has an id, the ids are used, each counted on the + * lowest rank that holds it. Otherwise, at one rank or when every rank holds n_model experts, the + * indices are the model's and rank 0 counts them; else the ranks' rows are concatenated in rank + * order. A layer's ids must be distinct within a rank and below 2^20, or the layer falls back. */ +int xs_map_build(const std::vector>>& ids, + const std::vector& n_model, int32_t n_trunk, XsMap* out); + +/* The merged tally a write renders. Counts are model-wide expert ids. */ +struct XsSnapshot { + std::string model, arch, container; + int32_t tp = 1; + int32_t n_layer = 0, n_trunk = 0, n_expert = 0; + std::vector layer_experts, top_k; + std::vector how; + /* Issued, from rank 0's passes: trunk steps and their tokens by kind (the mixed kind's decode + * tokens apart), draft passes and their rows. */ + uint64_t steps[kXsKinds] = {}, tokens[kXsKinds] = {}, mixed_decode_tokens = 0; + uint64_t draft_passes = 0, draft_rows = 0; + /* Observed, per kind and layer: histograms credited, passes they stand for, the tokens of the + * passes they hold (rank-0 view of the layer's lowest counting rank), and the selections, + * which are the counts' sum. */ + std::vector histograms[kXsKinds], passes[kXsKinds], obs_tokens[kXsKinds], + selections[kXsKinds]; + std::vector> counts[kXsKinds]; /* [layer][expert] */ + /* Per rank: histograms credited, selections with no model-wide id, histograms whose step had + * no record (filed as mixed), and the ring's lost histograms (Ctx::route_dropped). */ + std::vector rank_credited, rank_unmapped, rank_unclassified, rank_dropped; + double uptime_s = 0.0; + int64_t written_unix = 0; + bool final_ = false; +}; + +/* One rank's tally. Written by its rank thread (issued, credit) and read by the writer + * (snapshot_into) under the tally's lock, which the rank takes once a pass and once a drain; + * the writer holds it for a copy every 30 s, so it is never contended in practice. */ +class XsTally { +public: + void init(const XsMap* map, int rank); + + /* At every pass the rank issues, before it runs: files the step's kind, or counts a draft + * pass, for the drain to find a step or more later. Not for an encoder pass. */ + void issued(const RadBatch& b); + void issued(int step, int draft_pass, int64_t n_seq, int64_t n_seq_decode, int64_t n_tok, + int64_t n_tok_decode); + + /* Taken by the drain around its credits, and by snapshot_into. */ + std::mutex& mutex() { return mu_; } + /* One landed histogram of `layer` from step `step`: `n` counts (the layer's reported expert + * count), standing for `reports` passes. Caller holds mutex(). */ + void credit(int layer, int step, const int32_t* counts, int64_t n, int reports, int64_t top_k); + + /* The route ring's losses so far (Ctx::route_dropped), noted by the drain. Caller holds + * mutex(). */ + void note_dropped(uint64_t n) { dropped_ = n; } + + /* Adds this rank's tally into `s`, sized by the caller from the map. The per-layer token and + * histogram counts come from the layer's lowest counting rank (`token_rank`), since every rank + * counting in a layer sees the same steps, and the issued totals from the lowest counting rank + * of all (`issued`). Takes the lock. */ + void snapshot_into(XsSnapshot* s, const std::vector& token_rank, bool issued); + + uint64_t credited() const { return credited_; } + +private: + struct Rec { + int32_t step = -1; + uint8_t kind = 0; + bool trunk = false; /* the step's trunk pass was filed */ + int64_t n_tok = 0; + int64_t draft_rows = 0; /* the step's last draft pass's rows */ + }; + static constexpr int kRing = 256; /* > the route ring's 32 banks, with room for idle layers */ + + const XsMap* map_ = nullptr; + int rank_ = 0; + std::mutex mu_; + std::vector ring_; + std::vector off_; /* [layer]: offset of the layer's run in a counts plane */ + std::vector counts_[kXsKinds]; + std::vector hist_[kXsKinds], passes_[kXsKinds], tok_[kXsKinds], sel_[kXsKinds]; + std::vector top_k_; + uint64_t steps_[kXsKinds] = {}, tokens_[kXsKinds] = {}, mixed_decode_ = 0; + uint64_t draft_passes_ = 0, draft_rows_ = 0; + uint64_t credited_ = 0, unmapped_ = 0, unclassified_ = 0, dropped_ = 0; +}; + +/* Renders a snapshot as the file's JSON. */ +std::string xs_json(const XsSnapshot& s); +/* Writes `text` to `path` through `path`.tmp and a rename, so a reader never sees half a file. */ +int xs_write_atomic(const std::string& path, const std::string& text); + +/* The engine's side: the map, one tally a rank, and a thread that writes the file every + * `interval_s` seconds until stop(). */ +class ExpertStats { +public: + ~ExpertStats(); + /* Writes the file once, empty, so a path that cannot be written fails at boot. */ + int init(const std::string& path, const XsMap& map, XsSnapshot info, double interval_s = 30.0); + /* Null for a rank that counts nothing (every expert it holds a lower rank counts): its rank + * thread then neither files steps nor drains for the tally. */ + XsTally* tally(int rank) { + return rank >= 0 && (size_t)rank < tallies_.size() && counts_on_[(size_t)rank] + ? tallies_[(size_t)rank].get() : nullptr; + } + const XsMap& map() const { return map_; } + const std::string& path() const { return path_; } + + void start(); + void stop(); + /* Merges every rank's tally and writes the file. */ + int write(bool final_); + XsSnapshot snapshot(); + +private: + std::string path_; + XsMap map_; + XsSnapshot info_; + double interval_s_ = 30.0; + std::vector> tallies_; + std::vector counts_on_; /* [rank]: holds an expert it counts */ + std::vector token_rank_; /* [layer]: the lowest rank counting in it */ + int32_t issued_rank_ = -1; /* the lowest rank counting at all */ + uint64_t t0_ns_ = 0; + + std::thread writer_; + std::mutex wmu_; + std::condition_variable wcv_; + bool wstop_ = false; + std::mutex file_mu_; /* one write at a time */ +}; + +} /* namespace rad */ diff --git a/core/rad_core.h b/core/rad_core.h index 67911b80..a7cf7f5f 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -1063,6 +1063,9 @@ struct Config { bool debug_selection = false; bool debug_placement = false; bool profile_ops = false; + /* --expert-stats FILE: count the routed experts every layer selects, by step kind, and write + * the counts to FILE as JSON every 30 s and at shutdown (place/xstats.h). Empty is off. */ + std::string expert_stats; /* --live: the live view (spec §16). Off by default like everything else in that section. */ bool live_view = false; diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 7beb4407..1398644a 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -2022,6 +2022,7 @@ flags are refused on it, and so are the pixel bands. | `--debug-placement` | print the placement plan | | `--debug-accept-reference-kernels` | serve even when ops resolve to `libref`. Not a production configuration | | `--profile-ops` | per-op device timing | +| `--expert-stats FILE` | count the routed experts every layer selects, apart for prefill, decode, mixed steps and draft-head passes, and write them to `FILE` as JSON every 30 s and at shutdown (written through a temporary and a rename). Counted on the host from the routing histograms the core already copies back for the heat engine, so it adds no device work and no synchronisation; under expert parallelism each rank's slice is mapped to the model's expert ids through the container's directory | | `--live` | the live terminal view (§6.4) | | `-v` / `-vv` | verbose / very verbose | diff --git a/tests/config_test.cpp b/tests/config_test.cpp index f09e46b8..c3e91a98 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -465,6 +465,7 @@ const std::map>& legal_values() { { "--video-min-frames", { "2" } }, { "--video-max-frames", { "8" } }, { "--video-max-frame-tokens", { "70" } }, { "--image-tokens", { "280" } }, { "--max-source-pixels", { "1000000" } }, + { "--expert-stats", { "/s/experts.json" } }, { "--kld-record", { "/r", "--kld-corpus", "/c.jsonl" } }, { "--kld-ref", { "/r" } }, { "--kld-corpus", { "/c.jsonl", "--kld-record", "/r" } }, { "--kld-out", { "/o.json", "--kld-ref", "/r" } }, @@ -842,6 +843,26 @@ TEST(the_checkpoint_policy_is_one_of_the_three_that_exist) { CHECK_EQ(d.checkpoint_policy, std::string("geometric-backoff")); } +/* --expert-stats is off until it names a file, and needs one. */ +TEST(expert_stats_is_off_until_it_names_a_file) { + LogGuard lg; + auto row = [](const Config& c) { + for (const diag::ConfigRow& r : diag::config_rows(c)) + if (r.flag == "--expert-stats") return r; + return diag::ConfigRow{}; + }; + Config d; + CHECK_EQ(parse({}, &d), RAD_OK); + CHECK(d.expert_stats.empty()); + CHECK_EQ(row(d).value, std::string("off")); + Config c; + CHECK_EQ(parse({ "--expert-stats", "/s/experts.json" }, &c), RAD_OK); + CHECK_EQ(c.expert_stats, std::string("/s/experts.json")); + CHECK_EQ(row(c).value, std::string("/s/experts.json")); + CHECK_EQ(row(c).source, std::string("command line")); + CHECK(parse_fresh({ "--expert-stats" }) < 0); +} + /* --checkpoint-slots is auto by default, resolved by the engine once a snapshot's size is known; * a count is taken as given, 0 included, and the report shows which. */ TEST(the_checkpoint_slots_are_auto_or_a_count) { diff --git a/tests/xstats_test.cpp b/tests/xstats_test.cpp new file mode 100644 index 00000000..ebee267f --- /dev/null +++ b/tests/xstats_test.cpp @@ -0,0 +1,278 @@ +/* xstats_test.cpp -- --expert-stats: the expert map across ranks, the per-rank tally and its merge, + * and the file (place/xstats.h). Pure host code: the engine's drain hands the tally the same rows + * these cases hand it. */ +#include "rad_test.h" + +#include "place/xstats.h" + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace rad; + +namespace { + +using Ids = std::vector>>; /* [rank][layer][local] */ + +std::vector iota_from(int32_t base, int32_t n) { + std::vector v((size_t)n); + for (int32_t i = 0; i < n; ++i) v[(size_t)i] = base + i; + return v; +} + +/* Credits one model-wide histogram `global` of `layer` at `step` on every rank, each rank's row + * being its slice in the order its map names the experts, as moe_scatter would write it. */ +void credit_all(ExpertStats& xs, const Ids& ids, int layer, int step, + const std::vector& global, int reports, int top_k) { + for (size_t r = 0; r < ids.size(); ++r) { + XsTally* t = xs.tally((int)r); + if (!t) continue; + std::vector row; + for (int32_t g : ids[r][(size_t)layer]) row.push_back(global[(size_t)g]); + std::lock_guard lk(t->mutex()); + t->credit(layer, step, row.data(), (int64_t)row.size(), reports, top_k); + } +} + +void issued_all(ExpertStats& xs, int n_rank, int step, int draft_pass, int64_t n_seq, + int64_t n_seq_decode, int64_t n_tok, int64_t n_tok_decode) { + for (int r = 0; r < n_rank; ++r) + if (XsTally* t = xs.tally(r)) t->issued(step, draft_pass, n_seq, n_seq_decode, n_tok, n_tok_decode); +} + +std::string slurp(const std::string& path) { + std::ifstream f(path); + std::stringstream ss; + ss << f.rdbuf(); + return ss.str(); +} + +uint64_t sum(const std::vector& v) { + uint64_t s = 0; + for (uint64_t x : v) s += x; + return s; +} + +} /* namespace */ + +/* Every rank holds every expert (a width slice of each): the container gives each rank the same + * ids, so rank 0 counts them all and the other ranks count nothing. */ +TEST(experts_every_rank_holds_are_counted_on_rank_zero_only) { + Ids ids(3, { iota_from(0, 4), iota_from(0, 4) }); + XsMap m; + CHECK_OK(xs_map_build(ids, { 4, 4 }, 2, &m)); + REQUIRE_EQ(m.n_layer, 2); + CHECK_EQ(m.n_expert[0], 4); + CHECK_EQ(m.how[0], std::string("container")); + CHECK(m.gid[0][1] == iota_from(0, 4)); + for (int r = 1; r < 3; ++r) + for (int32_t g : m.gid[(size_t)r][0]) CHECK_EQ(g, XsMap::kElsewhere); +} + +/* Expert parallelism as deepseek41 declares it at TP4: the trunk's 24 experts six a rank, the + * DSpark head's 12 split 4/4/2/2 (the even floor, two more to the first ranks). Each rank's row is + * its own slice from zero; the container's ids put each index at its model-wide expert. */ +TEST(an_expert_parallel_split_maps_each_ranks_slice_to_the_models_ids) { + const int32_t head_n[4] = { 4, 4, 2, 2 }, head_base[4] = { 0, 4, 8, 10 }; + Ids ids(4); + for (int r = 0; r < 4; ++r) + ids[(size_t)r] = { iota_from(6 * r, 6), iota_from(head_base[r], head_n[r]) }; + XsMap m; + CHECK_OK(xs_map_build(ids, { 24, 0 }, 1, &m)); + CHECK_EQ(m.n_trunk, 1); + CHECK_EQ(m.n_expert[0], 24); + CHECK_EQ(m.n_expert[1], 12); + for (int r = 0; r < 4; ++r) { + CHECK(m.gid[(size_t)r][0] == iota_from(6 * r, 6)); + CHECK(m.gid[(size_t)r][1] == iota_from(head_base[r], head_n[r])); + } + + /* Any assignment the container states is taken as stated, interleaved included. */ + Ids odd = { { { 1, 3, 5 } }, { { 0, 2, 4 } } }; + CHECK_OK(xs_map_build(odd, { 6 }, 1, &m)); + CHECK(m.gid[0][0] == std::vector({ 1, 3, 5 })); + CHECK(m.gid[1][0] == std::vector({ 0, 2, 4 })); + CHECK_EQ(m.n_expert[0], 6); +} + +/* Without the container's ids (a checkpoint served directly, or ids that cannot be right), the + * map falls back: the indices themselves at one rank or where every rank holds the model's count, + * the ranks' rows in rank order otherwise. */ +TEST(without_ids_the_map_falls_back_to_the_indices_or_rank_order) { + XsMap m; + CHECK_OK(xs_map_build({ { std::vector(5, -1) } }, { 5 }, 1, &m)); + CHECK_EQ(m.how[0], std::string("index")); + CHECK(m.gid[0][0] == iota_from(0, 5)); + + CHECK_OK(xs_map_build({ { std::vector(4, -1) }, { std::vector(4, -1) } }, { 4 }, 1, &m)); + CHECK_EQ(m.how[0], std::string("replicated")); + CHECK(m.gid[0][0] == iota_from(0, 4)); + CHECK(m.gid[1][0] == std::vector(4, XsMap::kElsewhere)); + + CHECK_OK(xs_map_build({ { std::vector(3, -1) }, { std::vector(3, -1) } }, { 6 }, 1, &m)); + CHECK_EQ(m.how[0], std::string("rank order")); + CHECK(m.gid[1][0] == iota_from(3, 3)); + CHECK_EQ(m.n_expert[0], 6); + + /* One id given twice within a rank is not an assignment: the layer falls back. */ + CHECK_OK(xs_map_build({ { { 0, 1 } }, { { 2, 2 } } }, { 4 }, 1, &m)); + CHECK_EQ(m.how[0], std::string("rank order")); + CHECK(m.gid[1][0] == iota_from(2, 2)); +} + +/* The tally files each histogram under its step's kind, counts the head's under draft, and merges + * the ranks' slices into model-wide rows whose sums are the tokens times top_k. */ +TEST(the_tally_files_by_kind_and_merges_the_ranks_slices) { + /* Two ranks: layer 0 a trunk layer of 4 experts (2 a rank), layer 1 a head of 2 (1 a rank). */ + const Ids ids = { { { 0, 1 }, { 0 } }, { { 2, 3 }, { 1 } } }; + XsMap m; + CHECK_OK(xs_map_build(ids, { 4, 0 }, 1, &m)); + ExpertStats xs; + const std::string path = radtest::tmp_path("merge.json"); + XsSnapshot info; + info.model = "tiny"; + CHECK_OK(xs.init(path, m, info)); + REQUIRE(xs.tally(0) && xs.tally(1)); + + /* Step 0: a prefill of 3 tokens, top-2. */ + issued_all(xs, 2, 0, 0, 1, 0, 3, 0); + credit_all(xs, ids, 0, 0, { 3, 1, 2, 0 }, 1, 2); + /* Step 1: decode of 2 sequences, then two draft passes; the bank holds the last's 2 rows. */ + issued_all(xs, 2, 1, 0, 2, 2, 2, 2); + issued_all(xs, 2, 1, -1, 2, 2, 2, 0); + issued_all(xs, 2, 1, 2, 2, 2, 2, 0); + credit_all(xs, ids, 0, 1, { 0, 2, 1, 1 }, 1, 2); + credit_all(xs, ids, 1, 1, { 3, 1 }, 2, 2); + /* Step 2: mixed, 1 decode row and a 4-token chunk. */ + issued_all(xs, 2, 2, 0, 2, 1, 5, 1); + credit_all(xs, ids, 0, 2, { 4, 2, 3, 1 }, 1, 2); + /* A histogram of a step nothing filed (it cannot be classified): mixed, and counted apart. */ + credit_all(xs, ids, 0, 7, { 1, 1, 0, 0 }, 1, 2); + + const XsSnapshot s = xs.snapshot(); + CHECK(s.counts[kXsPrefill][0] == std::vector({ 3, 1, 2, 0 })); + CHECK(s.counts[kXsDecode][0] == std::vector({ 0, 2, 1, 1 })); + CHECK(s.counts[kXsMixed][0] == std::vector({ 5, 3, 3, 1 })); + CHECK(s.counts[kXsDraft][1] == std::vector({ 3, 1 })); + CHECK(s.counts[kXsDraft][0] == std::vector({ 0, 0, 0, 0 })); + CHECK(s.counts[kXsPrefill][1] == std::vector({ 0, 0 })); + + /* Selections are the tokens of the passes the banks hold times top_k. */ + for (int k : { kXsPrefill, kXsDecode }) + CHECK_EQ(s.selections[k][0], s.obs_tokens[k][0] * 2); + CHECK_EQ(s.obs_tokens[kXsPrefill][0], (uint64_t)3); + CHECK_EQ(s.obs_tokens[kXsDecode][0], (uint64_t)2); + CHECK_EQ(s.obs_tokens[kXsMixed][0], (uint64_t)5); /* the unclassified one adds no tokens */ + CHECK_EQ(s.selections[kXsMixed][0], (uint64_t)12); + CHECK_EQ(s.obs_tokens[kXsDraft][1], (uint64_t)2); + CHECK_EQ(s.selections[kXsDraft][1], (uint64_t)4); + CHECK_EQ(s.passes[kXsDraft][1], (uint64_t)2); + CHECK_EQ(s.histograms[kXsMixed][0], (uint64_t)2); + + /* Issued, once (not once a rank). */ + CHECK_EQ(s.steps[kXsPrefill], (uint64_t)1); + CHECK_EQ(s.tokens[kXsPrefill], (uint64_t)3); + CHECK_EQ(s.steps[kXsDecode], (uint64_t)1); + CHECK_EQ(s.tokens[kXsDecode], (uint64_t)2); + CHECK_EQ(s.tokens[kXsMixed], (uint64_t)5); + CHECK_EQ(s.mixed_decode_tokens, (uint64_t)1); + CHECK_EQ(s.draft_passes, (uint64_t)2); + CHECK_EQ(s.draft_rows, (uint64_t)4); + CHECK_EQ(s.top_k[0], 2); + CHECK_EQ(s.rank_unclassified[0], (uint64_t)1); + CHECK_EQ(s.rank_unclassified[1], (uint64_t)1); + CHECK_EQ(sum(s.rank_unmapped), (uint64_t)0); + CHECK_EQ(s.rank_credited[0], (uint64_t)5); +} + +/* A replicated layer is drained on rank 0 only: the other ranks get no tally at all. And counts + * past a rank's declared experts, or where the map has no id, are unmapped, not dropped silently. */ +TEST(ranks_that_count_nothing_have_no_tally_and_strays_are_unmapped) { + XsMap m; + CHECK_OK(xs_map_build({ { iota_from(0, 3) }, { iota_from(0, 3) } }, { 3 }, 1, &m)); + ExpertStats xs; + CHECK_OK(xs.init(radtest::tmp_path("repl.json"), m, XsSnapshot{})); + CHECK(xs.tally(0) != nullptr); + CHECK(xs.tally(1) == nullptr); + + XsTally* t = xs.tally(0); + t->issued(4, 0, 1, 1, 1, 1); + const int32_t row[5] = { 1, 0, 1, 7, -3 }; /* two past the declared three */ + { + std::lock_guard lk(t->mutex()); + t->credit(0, 4, row, 5, 1, 2); + } + const XsSnapshot s = xs.snapshot(); + CHECK(s.counts[kXsDecode][0] == std::vector({ 1, 0, 1 })); + CHECK_EQ(s.rank_unmapped[0], (uint64_t)7); + CHECK_EQ(s.selections[kXsDecode][0], (uint64_t)2); +} + +/* The file: JSON with the shape the report reads, there from boot, replaced whole through a + * rename (no temporary left behind), and rewritten by the writer thread. */ +TEST(the_file_is_json_written_at_boot_and_replaced_through_a_rename) { + const Ids ids = { { { 0, 1 } }, { { 2, 3 } } }; + XsMap m; + CHECK_OK(xs_map_build(ids, { 4 }, 1, &m)); + const std::string path = radtest::tmp_path("stats.json"); + XsSnapshot info; + info.model = "a \"quoted\" name"; + info.arch = "deepseek41"; + ExpertStats xs; + CHECK_OK(xs.init(path, m, info, 0.05)); + + nlohmann::json j = nlohmann::json::parse(slurp(path), nullptr, false); + REQUIRE(!j.is_discarded()); + CHECK_EQ(j["format"].get(), std::string("radiance-expert-stats/1")); + CHECK_EQ(j["model"].get(), info.model); + CHECK_EQ(j["final"].get(), false); + CHECK_EQ(j["n_layers"].get(), 1); + CHECK_EQ(j["n_experts"].get(), 4); + CHECK_EQ(j["tp"].get(), 2); + REQUIRE(j["counts"]["decode"].size() == 1); + CHECK_EQ(j["counts"]["decode"][0].size(), (size_t)4); + + issued_all(xs, 2, 0, 0, 1, 1, 1, 1); + credit_all(xs, ids, 0, 0, { 0, 1, 1, 0 }, 1, 2); + xs.start(); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + xs.stop(); + j = nlohmann::json::parse(slurp(path), nullptr, false); + REQUIRE(!j.is_discarded()); + CHECK(j["counts"]["decode"][0] == nlohmann::json({ 0, 1, 1, 0 })); + CHECK_EQ(j["selections"]["decode"][0].get(), (uint64_t)2); + CHECK_EQ(j["observed_tokens"]["decode"][0].get(), (uint64_t)1); + CHECK_EQ(j["tokens"]["decode"].get(), (uint64_t)1); + CHECK(j["uptime_s"].get() > 0.0); + + CHECK_OK(xs.write(true)); + j = nlohmann::json::parse(slurp(path), nullptr, false); + REQUIRE(!j.is_discarded()); + CHECK_EQ(j["final"].get(), true); + + /* Only the file itself in the directory: every temporary was renamed or removed. */ + int others = 0; + if (DIR* d = opendir(radtest::tmpdir().c_str())) { + while (dirent* e = readdir(d)) { + const std::string n = e->d_name; + if (n.find("stats.json.tmp") != std::string::npos) ++others; + } + closedir(d); + } + CHECK_EQ(others, 0); + + /* A path that cannot be written fails init. */ + ExpertStats bad; + CHECK(bad.init(radtest::tmp_path("no/such/dir/x.json"), m, XsSnapshot{}) < 0); +} + +RAD_TEST_MAIN()