diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 377ea096..061d8c13 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -305,6 +305,12 @@ hits, the router, the head, ...). The GPU profile times every stage with events, use it to compare, not to measure speed. This works with every pack; `--gpu-stages` (a one-token replay of per-layer graphs) refuses a native (IQ) pack, which has no such graphs. +**How good the next-layer expert prediction is (measurement only):** `STRATA_LOOKAHEAD_STATS=1` runs the router look-ahead on any expert tier and +scores it against the routing of the next layer: every 100 windows the engine log has a `strata lookahead stats:` line with the experts per layer +outside the GPU cache, the recall and precision of the top-k / k+4 / k+10 guesses and of the vote-ranked top 4 / 8 / 12, how much of the PCIe share they +would cover, and the predictor thread's time per window. It costs CPU (the predictor is a thread beside the expert pool), so use it to measure, not to +time. `tools/replay_cache_policy.py` replays a `--dump-routing` trace through the adaptive tier's swap policy offline. + Time to first token is prompt length / prompt speed: with Q2_0 about 4 s at 4K, 25 s at 32K, under 2 minutes at 128K and 4.5 minutes at 262K (engine 0.1.13 made long prompts about twice as fast, below). diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 98dae6ce..b51c8f99 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -252,6 +252,12 @@ public: /// A deeper one predicts layer + j from layer's input, which is less exact the further it looks. void set_depth(int d) { depth_ = d < 1 ? 1 : d > 4 ? 4 : d; } int depth() const { return depth_; } + /// STRATA_LOOKAHEAD_STATS=1 (measurement only): remember each prediction (top k, k+4 and k+10 per token) and let the + /// dispatch score it against the experts the next layer really routes outside the GPU cache. + void enable_stats(int64_t n_layers); + bool stats_on() const { return stats_on_; } + void stats_window_start() { gen_.fetch_add(1, std::memory_order_relaxed); } + void stats_score(int64_t layer, const int32_t* ids, int64_t n, const int32_t* host_res, int pcie_num = 0); int64_t predicted() const { return predicted_.load(std::memory_order_relaxed); } int64_t skipped() const { return skipped_.load(std::memory_order_relaxed); } double busy_ms() const { return (double) busy_us_.load(std::memory_order_relaxed) / 1000.0; } @@ -269,10 +275,23 @@ private: bool quit_ = false, pending_ = false, busy_ = false; int64_t layer_ = -1, n_tok_ = 0; const int32_t* host_res_ = nullptr; + uint64_t sub_gen_ = 0; ForesightSwap* fs_ = nullptr; ///< (under mu_) std::vector x_; std::atomic predicted_{0}, skipped_{0}; std::atomic busy_us_{0}; + // STRATA_LOOKAHEAD_STATS + bool stats_on_ = false; + int64_t words_ = 0; + std::unique_ptr[]> pmask_; // [layer][3 sizes][words] + std::unique_ptr[]> pstamp_; // [layer]: gen + 1 of the prediction (0 = none) + std::unique_ptr[]> pvote_; // [layer][kVoteN]: experts by votes, expert + 1 (0 = none) + std::atomic gen_{0}; + uint64_t st_layers_ = 0, st_nopred_ = 0, st_actual_ = 0, st_hit_[3] = {0, 0, 0}, st_pred_[3] = {0, 0, 0}, + st_predhit_[3] = {0, 0, 0}; + uint64_t st_windows_ = 0; + uint64_t st_vhit_[3] = {0, 0, 0}, st_vpred_[3] = {0, 0, 0}, st_pch_ = 0, st_pcov_[3] = {0, 0, 0}; + static constexpr int kVoteN = 16; }; /// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 8f29affc..4604eb8d 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -2083,6 +2083,12 @@ void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) { #endif } +static inline int la_pc64(uint64_t x) { // (portable: no compiler builtin) + int n = 0; + for (; x != 0; x &= x - 1) ++n; + return n; +} + RouterLookahead::~RouterLookahead() { { std::lock_guard lk(mu_); @@ -2131,11 +2137,107 @@ void RouterLookahead::submit(int64_t layer, const float* x, int64_t n_tok, const std::memcpy(x_.data(), x, (size_t) (n_tok_ * n_embd_) * sizeof(float)); layer_ = layer + 1; host_res_ = host_res; + sub_gen_ = gen_.load(std::memory_order_relaxed); pending_ = true; } cv_.notify_one(); } +void RouterLookahead::enable_stats(int64_t n_layers) { + words_ = (n_expert_ + 63) / 64; + pmask_.reset(new std::atomic[(size_t) (n_layers * 3 * words_)]); + pstamp_.reset(new std::atomic[(size_t) n_layers]); + for (int64_t i = 0; i < n_layers * 3 * words_; ++i) pmask_[(size_t) i].store(0, std::memory_order_relaxed); + for (int64_t i = 0; i < n_layers; ++i) pstamp_[(size_t) i].store(0, std::memory_order_relaxed); + pvote_.reset(new std::atomic[(size_t) (n_layers * kVoteN)]); + for (int64_t i = 0; i < n_layers * kVoteN; ++i) pvote_[(size_t) i].store(0, std::memory_order_relaxed); + stats_on_ = true; +} + +// the dispatch thread: score the prediction made for `layer` against the experts it routes outside the GPU cache +void RouterLookahead::stats_score(int64_t layer, const int32_t* ids, int64_t n, const int32_t* host_res, int pcie_num) { + if (!stats_on_ || layer < 1 || layer >= (int64_t) routers_.size()) return; + ++st_layers_; + if (pstamp_[(size_t) layer].load(std::memory_order_acquire) != gen_.load(std::memory_order_relaxed) + 1) { + ++st_nopred_; + return; + } + std::vector act((size_t) words_, 0); + for (int64_t i = 0; i < n; ++i) { + const int32_t e = ids[i]; + if (e < 0 || e >= n_expert_) continue; + if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue; + act[(size_t) (e >> 6)] |= 1ull << (e & 63); + } + uint64_t na = 0; + for (int64_t w = 0; w < words_; ++w) na += (uint64_t) la_pc64(act[(size_t) w]); + st_actual_ += na; + { // the vote-ranked top M (the experts most tokens predict) against the misses, and against the PCIe share + static const int vm[3] = {4, 8, 12}; + int32_t vt[kVoteN]; + int nv = 0; + for (int i = 0; i < kVoteN; ++i) { + const int32_t v = pvote_[(size_t) (layer * kVoteN + i)].load(std::memory_order_relaxed); + if (v == 0) break; + vt[nv++] = v - 1; + } + // the misses in routing order (first appearance), the PCIe share = the last (n_miss * pcie_num / 256) of them + std::vector order_miss; + for (int64_t i = 0; i < n; ++i) { + const int32_t e = ids[i]; + if (e < 0 || e >= n_expert_) continue; + if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue; + if (std::find(order_miss.begin(), order_miss.end(), e) == order_miss.end()) order_miss.push_back(e); + } + const int m = ((int) order_miss.size() * pcie_num) >> 8; + st_pch_ += (uint64_t) m; + for (int s = 0; s < 3; ++s) { + const int top = std::min(vm[s], nv); + st_vpred_[s] += (uint64_t) top; + for (int j = 0; j < top; ++j) { + if ((act[(size_t) (vt[j] >> 6)] >> (vt[j] & 63)) & 1ull) ++st_vhit_[s]; + const auto it = std::find(order_miss.begin(), order_miss.end(), vt[j]); + if (it != order_miss.end() && (int) (it - order_miss.begin()) >= (int) order_miss.size() - m) ++st_pcov_[s]; + } + } + } + for (int s = 0; s < 3; ++s) { + uint64_t hit = 0, np = 0; + for (int64_t w = 0; w < words_; ++w) { + const uint64_t pm = pmask_[(size_t) ((layer * 3 + s) * words_ + w)].load(std::memory_order_relaxed); + hit += (uint64_t) la_pc64(pm & act[(size_t) w]); + np += (uint64_t) la_pc64(pm); + } + st_hit_[s] += hit; + st_pred_[s] += np; + } + if (layer == (int64_t) routers_.size() - 1 && (++st_windows_ % 100) == 0) { + const uint64_t scored = st_layers_ - st_nopred_; + std::fprintf(stderr, "strata lookahead stats: %llu windows, %llu layers scored, %llu without a prediction (%.1f%%); " + "%.2f actual non-resident experts/layer;", + (unsigned long long) st_windows_, (unsigned long long) scored, (unsigned long long) st_nopred_, + st_layers_ ? 100.0 * (double) st_nopred_ / (double) st_layers_ : 0.0, + scored ? (double) st_actual_ / (double) scored : 0.0); + std::fprintf(stderr, " predictor thread %.2f ms/window;", + (double) busy_us_.load(std::memory_order_relaxed) / 1000.0 / (double) st_windows_); + static const int add[3] = {0, 4, 10}; + for (int s = 0; s < 3; ++s) + std::fprintf(stderr, " k=%d: recall %.3f precision %.3f (%.2f predicted/layer);", k_ + add[s], + st_actual_ ? (double) st_hit_[s] / (double) st_actual_ : 0.0, + st_pred_[s] ? (double) st_hit_[s] / (double) st_pred_[s] : 0.0, + scored ? (double) st_pred_[s] / (double) scored : 0.0); + static const int vm[3] = {4, 8, 12}; + for (int s = 0; s < 3; ++s) + std::fprintf(stderr, " votes top%d: %.2f/layer, covers %.3f of the misses (precision %.3f), %.3f of the PCIe share (%.2f/layer);", + vm[s], scored ? (double) st_vpred_[s] / (double) scored : 0.0, + st_actual_ ? (double) st_vhit_[s] / (double) st_actual_ : 0.0, + st_vpred_[s] ? (double) st_vhit_[s] / (double) st_vpred_[s] : 0.0, + st_pch_ ? (double) st_pcov_[s] / (double) st_pch_ : 0.0, + scored ? (double) st_pch_ / (double) scored : 0.0); + std::fprintf(stderr, "\n"); + } +} + void RouterLookahead::run() { std::vector logits((size_t) (8 * n_expert_)); std::vector order((size_t) n_expert_); @@ -2144,6 +2246,7 @@ void RouterLookahead::run() { int64_t layer, nt; const int32_t* host_res; ForesightSwap* fs; + uint64_t sgen; { std::unique_lock lk(mu_); cv_.wait(lk, [&] { return quit_ || pending_; }); @@ -2154,6 +2257,7 @@ void RouterLookahead::run() { nt = n_tok_; host_res = host_res_; fs = fs_; + sgen = sub_gen_; } const auto t0 = std::chrono::steady_clock::now(); const int64_t layer0 = layer; @@ -2189,17 +2293,48 @@ void RouterLookahead::run() { } } } + const int kmax = stats_on_ ? (int) std::min(k_ + 10, n_expert_) : k_; + const int ks[3] = {k_, (int) std::min(k_ + 4, n_expert_), kmax}; + std::vector sm; + if (stats_on_) sm.assign((size_t) (3 * words_), 0); for (int64_t t = 0; t < nt; ++t) { const float* lt = logits.data() + (size_t) (t * n_expert_); for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e; - std::partial_sort(order.begin(), order.begin() + k_, order.end(), + std::partial_sort(order.begin(), order.begin() + kmax, order.end(), [&](int32_t a, int32_t b) { return lt[(size_t) a] > lt[(size_t) b]; }); - for (int j = 0; j < k_; ++j) { + for (int j = 0; j < kmax; ++j) { const int64_t e = order[(size_t) j]; if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue; // on the GPU - if (std::find(want.begin(), want.end(), e) == want.end()) want.push_back(e); + if (j < k_ && std::find(want.begin(), want.end(), e) == want.end()) want.push_back(e); + if (stats_on_ && dj == 0) + for (int s = 0; s < 3; ++s) + if (j < ks[s]) sm[(size_t) (s * words_ + (e >> 6))] |= 1ull << (e & 63); } } + if (stats_on_ && dj == 0) { + // votes: how many tokens put each non-resident expert in their top k_ + std::vector> votes; // (sum of 64 - rank, expert) + for (int64_t t = 0; t < nt; ++t) { + const float* lt = logits.data() + (size_t) (t * n_expert_); + for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e; + std::partial_sort(order.begin(), order.begin() + k_, order.end(), + [&](int32_t a, int32_t b) { return lt[(size_t) a] > lt[(size_t) b]; }); + for (int j = 0; j < k_; ++j) { + const int32_t e = order[(size_t) j]; + if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue; + auto it = std::find_if(votes.begin(), votes.end(), [&](const auto& v) { return v.second == e; }); + if (it == votes.end()) votes.emplace_back(64 - j, e); + else it->first += 64 - j; + } + } + std::sort(votes.begin(), votes.end(), [](const auto& a, const auto& b) { return a.first > b.first; }); + for (int i = 0; i < kVoteN; ++i) + pvote_[(size_t) (layer * kVoteN + i)].store(i < (int) votes.size() ? votes[(size_t) i].second + 1 : 0, + std::memory_order_relaxed); + for (int64_t i = 0; i < 3 * words_; ++i) + pmask_[(size_t) (layer * 3 * words_ + i)].store(sm[(size_t) i], std::memory_order_relaxed); + pstamp_[(size_t) layer].store(sgen + 1, std::memory_order_release); + } src_->warm(layer, want.data(), (int64_t) want.size()); if (fs != nullptr && dj == 0) // the next layer only: a deeper guess is too often wrong to spend a copy on for (const int64_t e : want) fs->predict(src_, layer, (int32_t) e); @@ -3397,7 +3532,13 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 d.fail_layer = d.layers; return; } - if (d.lookahead != nullptr) d.lookahead->submit(d.layers, x_f, n_tok, d.host_res); // CS-T: warm layer + 1 + if (d.lookahead != nullptr) { + if (d.lookahead->stats_on()) { + if (d.layers == 0) d.lookahead->stats_window_start(); + d.lookahead->stats_score(d.layers, ids, n_tok * k, d.host_res, d.pcie_num); + } + d.lookahead->submit(d.layers, x_f, n_tok, d.host_res); // CS-T: warm layer + 1 + } if (k < 1 || n_tok * k > kMaxWindowEntries) { d.failed = true; d.fail = "a verify window routes more entries than the expert pool's window tables hold"; diff --git a/src/program/generate.cpp b/src/program/generate.cpp index d625cba8..ba904dcb 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -5335,7 +5335,9 @@ int main(int argc, char** argv) { // tiers, where there are no pages to warm, and feeds its predictions to the swap space (STRATA_FS_AHEAD=0: not) const bool fs_ahead = srcp != nullptr && [] { const char* v = std::getenv("STRATA_FS_SLOTS"); return v != nullptr && std::atoi(v) > 0; }() && [] { const char* v = std::getenv("STRATA_FS_AHEAD"); return v == nullptr || std::atoi(v) != 0; }(); - if (srcp != nullptr && ((srcp == &src && src.warms()) || fs_ahead) && + // STRATA_LOOKAHEAD_STATS=1 (measurement only): run the predictor on any tier and score it against the real routing + const bool la_stats = srcp != nullptr && [] { const char* v = std::getenv("STRATA_LOOKAHEAD_STATS"); return v != nullptr && std::atoi(v) != 0; }(); + if (srcp != nullptr && ((srcp == &src && src.warms()) || fs_ahead || la_stats) && [] { const char* v = std::getenv("STRATA_LOOKAHEAD"); return v == nullptr || std::atoi(v) != 0; }()) { std::vector> routers((size_t) g.n_layers); bool ok = true; @@ -5348,8 +5350,9 @@ int main(int argc, char** argv) { ok = cudaMemcpy(routers[(size_t) l].data(), w->data, (size_t) w->bytes, cudaMemcpyDeviceToHost) == cudaSuccess; } const char* kv = std::getenv("STRATA_LOOKAHEAD_K"); - if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, srcp, err, fs_ahead)) { + if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, srcp, err, fs_ahead || la_stats)) { drive.d.lookahead = &lookahead; + if (la_stats) lookahead.enable_stats(g.n_layers); if (const char* dv = std::getenv("STRATA_IO_PREFETCH_DEPTH"); dv != nullptr && std::atoi(dv) > 0) lookahead.set_depth(std::atoi(dv)); else if (srcp == &src && src.io_prefetch()) diff --git a/tools/replay_cache_policy.py b/tools/replay_cache_policy.py new file mode 100644 index 00000000..db010545 --- /dev/null +++ b/tools/replay_cache_policy.py @@ -0,0 +1,141 @@ +"""Offline replay of a --dump-routing trace through the expert cache policies. + + python replay_cache_policy.py TRACE.bin PROFILE.bin SLOTS [--every 4 --decay 0.7 --swaps 96 --margin 1.5 --mincand 2.0] + +Trace record = int32 layer, int32 k, k int32 ids, k float32 weights; the verify window writes one record per token and +layer, so a layer group is the run of records with one layer and a window starts when the layer does not rise. +The simulated adaptive tier is generate.cpp's adapt(): usage += 1 per routed entry, a round every `every` windows, per +layer the best non-resident (usage >= mincand) against the worst resident (needs margin), the best `swaps` over all +layers, usage *= decay. Reports the share of routed entries served by the cache (the engine's "hits / all routed"). +""" +import sys +import numpy as np + +NL, NE = 48, 512 + + +def load_trace(path): + raw = np.fromfile(path, dtype=np.int32) + k = int(raw[1]) + rec = 2 + 2 * k + raw = raw[: (len(raw) // rec) * rec].reshape(-1, rec) + layer = raw[:, 0] + ids = raw[:, 2:2 + k] + # layer groups + chg = np.flatnonzero(np.diff(layer) != 0) + 1 + starts = np.concatenate([[0], chg]) + ends = np.concatenate([chg, [len(layer)]]) + windows, cur, last = [], None, -1 + for s, e in zip(starts, ends): + l = int(layer[s]) + if cur is None or l <= last: + if cur is not None: + windows.append(cur) + cur = [] + cur.append((l, ids[s:e])) + last = l + if cur: + windows.append(cur) + # keep complete windows only + return [w for w in windows if len(w) == NL], k + + +def load_profile(path, slots): + with open(path, "rb") as f: + assert f.read(4) == b"STRP" + hdr = np.frombuffer(f.read(20), dtype=np.uint32) + n_ranked = int(hdr[4]) + pairs = np.frombuffer(f.read(4 * n_ranked), dtype=np.uint16).reshape(-1, 2) + return pairs[:slots] + + +class Policy: + def __init__(self, every=4, decay=0.7, swaps=96, margin=1.5, mincand=2.0, mode='entries', mingain=0.0, posw=1.0): + self.every, self.decay, self.swaps, self.margin, self.mincand = every, decay, swaps, margin, mincand + self.mode, self.mingain, self.posw = mode, mingain, posw + + +def adapt_round(res, usage, pol): + sw = [] + for l in range(NL): + u = usage[l] + r = res[l] + cand = np.flatnonzero(~r & (u >= pol.mincand)) + vict = np.flatnonzero(r) + if len(cand) == 0 or len(vict) == 0: + continue + cand = cand[np.argsort(-u[cand], kind="stable")] + vict = vict[np.argsort(u[vict], kind="stable")] + n = min(len(cand), len(vict)) + gain = u[cand[:n]] - u[vict[:n]] + ok = u[cand[:n]] >= u[vict[:n]] + pol.margin + # the engine stops at the first pair that does not clear the margin + bad = np.flatnonzero(~ok) + n2 = int(bad[0]) if len(bad) else n + for i in range(n2): + sw.append((gain[i], l, int(cand[i]), int(vict[i]))) + sw.sort(key=lambda t: -t[0]) + sw = [t for t in sw if t[0] >= pol.mingain][: pol.swaps] + for g, l, i, o in sw: + res[l, i] = True + res[l, o] = False + return len(sw) + + +def simulate(windows, init, pol, reset_every=0): + res = np.zeros((NL, NE), bool) + res[init[:, 0], init[:, 1]] = True + usage = np.zeros((NL, NE)) + hits = ent = swaps = 0 + miss_ent = miss_dist = 0 + for wi, w in enumerate(windows): + for l, ids in w: + r = res[l, ids] + hits += int(r.sum()) + ent += r.size + ms = ids[~r] + miss_ent += len(ms) + miss_dist += len(np.unique(ms)) + if pol.mode == 'distinct': + usage[l, np.unique(ids)] += 1.0 + elif pol.posw != 1.0: + wts = np.repeat(pol.posw ** np.arange(ids.shape[0]), ids.shape[1]) + np.add.at(usage[l], ids.ravel(), wts) + else: + np.add.at(usage[l], ids.ravel(), 1.0) + if (wi + 1) % pol.every == 0: + swaps += adapt_round(res, usage, pol) + usage *= pol.decay + return dict(share=hits / max(1, ent), swaps=swaps, windows=len(windows), entries=ent, miss_ent=miss_ent, + miss_dist=miss_dist) + + +def static_oracle(windows, slots): + cnt = np.zeros((NL, NE)) + for w in windows: + for l, ids in w: + np.add.at(cnt[l], ids.ravel(), 1.0) + flat = np.argsort(-cnt.ravel(), kind="stable")[:slots] + hit = cnt.ravel()[flat].sum() / cnt.sum() + return hit + + +if __name__ == "__main__": + tr, prof, slots = sys.argv[1], sys.argv[2], int(sys.argv[3]) + + def opt(name, default, cast=float): + return cast(sys.argv[sys.argv.index(name) + 1]) if name in sys.argv else default + + pol = Policy(every=opt("--every", 4, int), decay=opt("--decay", 0.7), swaps=opt("--swaps", 96, int), + margin=opt("--margin", 1.5), mincand=opt("--mincand", 2.0)) + windows, k = load_trace(tr) + print("windows", len(windows), "k", k, "tokens/window", np.mean([len(w[0][1]) for w in windows])) + init = load_profile(prof, slots) + print("static oracle (top-%d by this trace's own counts): %.4f" % (slots, static_oracle(windows, slots))) + base = simulate(windows, init, Policy(every=10**9)) + print("profile only, no adaptation: %.4f" % base["share"]) + cur = simulate(windows, init, pol) + print("policy every %d, swaps %d, decay %.2f: share %.4f, swaps %d (%.2f/window); miss entries %d, distinct misses %d " + "(%.1f%% fewer reads)" % (pol.every, pol.swaps, pol.decay, cur["share"], cur["swaps"], cur["swaps"] / cur["windows"], + cur["miss_ent"], cur["miss_dist"], + 100 * (1 - cur["miss_dist"] / max(1, cur["miss_ent"]))))