"""Validate the analytic expert-cache model against the measured OLMoE trace. Measures true LRU hit rates over the real routing sequence, compares them with Che's approximation driven by the measured popularity vector, and fits the Zipf exponent that is later used to extrapolate to a 1T-parameter expert count. """ import json, os, sys from collections import OrderedDict import numpy as np sys.path.insert(0, os.path.dirname(__file__)) from project_1t import che_hit_rate, zipf_fit, zipf_pmf, distinct_per_layer RES = os.path.join(os.path.dirname(__file__), "..", "results") def lru_hits(T, cap): """True LRU hit rate over the real interleaved (layer, expert) access order.""" L, N, K = T.shape cache = OrderedDict() hits = tot = 0 for t in range(N): for l in range(L): base = l * 1000 for e in T[l, t]: key = base + int(e) tot += 1 if key in cache: hits += 1 cache.move_to_end(key) else: if len(cache) >= cap: cache.popitem(last=False) cache[key] = True return hits / tot def static_freq_hits(T, cap, p_global): """Static frequency-pinned cache: keep the globally hottest `cap` slots.""" L = T.shape[0] E = p_global.shape[0] // L keep = np.zeros(p_global.shape[0], dtype=bool) keep[np.argsort(-p_global)[:cap]] = True flat = np.arange(L)[:, None, None] * E + T return float(keep[flat].mean()) def main(): T = np.load(os.path.join(RES, "routing_trace.npy")).astype(np.int64) L, N, K = T.shape E = int(T.max()) + 1 stats = json.load(open(os.path.join(RES, "routing_stats.json"))) freq = json.load(open(os.path.join(RES, "routing_freq.json"))) F = np.array([freq[str(l)] for l in range(L)]) # [L, E] # global popularity over all (layer, expert) slots p_global = (F / L).reshape(-1) s_layer = [zipf_fit(F[l]) for l in range(L)] s_hat = float(np.median(s_layer)) out = {"layers": L, "experts": E, "topk": K, "tokens": int(N), "zipf_s": s_hat, "zipf_s_per_layer": s_layer} print(f"trace: L={L} E={E} K={K} tokens={N}; Zipf s (median) = {s_hat:.3f}") rows = [] n_slots = L * E for frac in [0.02, 0.05, 0.10, 0.15, 0.25, 0.40, 0.60, 0.80]: cap = max(1, int(frac * n_slots)) h_meas = lru_hits(T, cap) h_che = che_hit_rate(p_global, cap) h_zipf = che_hit_rate(np.tile(zipf_pmf(E, s_hat) / L, L), cap) h_stat = static_freq_hits(T, cap, p_global) rows.append(dict(frac=frac, cap=cap, measured=h_meas, static=h_stat, che_measured_pop=h_che, che_zipf=h_zipf)) print(f" cap={frac*100:5.1f}% ({cap:5d} slots): measured LRU {h_meas:.4f} | " f"static-freq {h_stat:.4f} | Che(measured pop) {h_che:.4f} | " f"Che(Zipf s={s_hat:.2f}) {h_zipf:.4f}") out["hit_rates"] = rows err = np.array([abs(r["measured"] - r["che_measured_pop"]) for r in rows]) out["che_mae"] = float(err.mean()) out["che_zipf_mae"] = float(np.mean([abs(r["measured"] - r["che_zipf"]) for r in rows])) print(f"Che approximation MAE vs measured LRU: {out['che_mae']:.4f} " f"(Zipf-parameterised: {out['che_zipf_mae']:.4f})") # distinct experts per batch: measured vs independent-reference prediction dpb = [] rng = np.random.default_rng(0) for B in [1, 2, 4, 8, 16, 32, 64]: meas = [] for _ in range(200): ts = rng.integers(0, N, size=B) l = int(rng.integers(0, L)) meas.append(len(np.unique(T[l][ts]))) pred = distinct_per_layer(F.mean(0), K * B) pred_z = distinct_per_layer(zipf_pmf(E, s_hat), K * B) dpb.append(dict(batch=B, measured=float(np.mean(meas)), irm_measured_pop=pred, irm_zipf=pred_z)) print(f" batch {B:3d}: distinct experts/layer measured {np.mean(meas):6.2f} | " f"IRM {pred:6.2f} | IRM-Zipf {pred_z:6.2f}") out["distinct_per_batch"] = dpb out["reuse_prev_token"] = stats["reuse_prev_token"] out["working_set"] = stats["working_set"] out["mass_top25pct"] = stats["mass_top25pct"] json.dump(out, open(os.path.join(RES, "cache_validation.json"), "w"), indent=2) print("saved results/cache_validation.json") if __name__ == "__main__": main()