Download code/cache_policy.py from mkvn/quantization-cache-amplification: direct link, hf CLI and curl.
- Browser
- Download file 4.46 kB
-
https://huggingface.co/datasets/mkvn/quantization-cache-amplification/resolve/main/code/cache_policy.py
- Command line
-
hf download hf://datasets/mkvn/quantization-cache-amplification/code/cache_policy.py
-
curl -L -o cache_policy.py https://huggingface.co/datasets/mkvn/quantization-cache-amplification/resolve/main/code/cache_policy.py
4.46 kB
| """Expert-cache policy comparison on the real OLMoE routing trace. | |
| Key structural fact: a single token touches k*L distinct expert slots. Under a | |
| purely recency-based policy this is a cyclic reference pattern, so any cache | |
| smaller than the per-token working set evicts every entry before it is reused | |
| and the hit rate collapses to zero. Popularity-pinned policies do not have this | |
| failure mode, and their hit rate is exactly the popularity mass of the pinned | |
| set -- which is analytically extrapolable. | |
| """ | |
| import json, os, sys | |
| from collections import OrderedDict | |
| import numpy as np | |
| sys.path.insert(0, os.path.dirname(__file__)) | |
| from project_1t import zipf_fit, zipf_pmf | |
| RES = os.path.join(os.path.dirname(__file__), "..", "results") | |
| def flat_trace(T, E): | |
| L = T.shape[0] | |
| return (np.arange(L)[:, None, None] * E + T) # [L, N, K] global ids | |
| def lru_like(F, cap, pinned=None): | |
| """LRU over the true interleaved access order, optionally with a pinned set | |
| that is never evicted. F is [L, N, K] of global slot ids.""" | |
| L, N, K = F.shape | |
| pinned = pinned if pinned is not None else np.zeros(0, dtype=np.int64) | |
| pin = set(pinned.tolist()) | |
| dyn_cap = max(0, cap - len(pin)) | |
| cache = OrderedDict() | |
| hits = tot = 0 | |
| for t in range(N): | |
| for l in range(L): | |
| for s in F[l, t]: | |
| s = int(s) | |
| tot += 1 | |
| if s in pin: | |
| hits += 1 | |
| continue | |
| if s in cache: | |
| hits += 1 | |
| cache.move_to_end(s) | |
| elif dyn_cap > 0: | |
| if len(cache) >= dyn_cap: | |
| cache.popitem(last=False) | |
| cache[s] = True | |
| return hits / tot | |
| def static_hits(F, cap, p_global): | |
| keep = np.zeros(p_global.shape[0], dtype=bool) | |
| keep[np.argsort(-p_global)[:cap]] = True | |
| return float(keep[F].mean()) | |
| def analytic_static(p, cap): | |
| """Hit rate of a popularity-pinned cache = mass of the top-`cap` slots.""" | |
| q = np.sort(np.asarray(p, dtype=np.float64))[::-1] | |
| q = q / q.sum() | |
| return float(q[:cap].sum()) | |
| 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 | |
| freq = json.load(open(os.path.join(RES, "routing_freq.json"))) | |
| Fq = np.array([freq[str(l)] for l in range(L)]) | |
| p_global = (Fq / L).reshape(-1) | |
| F = flat_trace(T, E) | |
| n_slots = L * E | |
| ws = K * L # per-token working set in slots | |
| s_hat = float(np.median([zipf_fit(Fq[l]) for l in range(L)])) | |
| out = {"layers": L, "experts": E, "topk": K, "tokens": int(N), | |
| "n_slots": n_slots, "token_working_set": ws, "zipf_s": s_hat, | |
| "ws_frac": ws / n_slots} | |
| print(f"L={L} E={E} K={K} slots={n_slots} per-token working set={ws} " | |
| f"({ws/n_slots*100:.1f}% of slots); Zipf s={s_hat:.3f}") | |
| # analytic static model validated against the trace | |
| p_zipf = np.tile(zipf_pmf(E, s_hat) / L, L) | |
| rows = [] | |
| for frac in [0.02, 0.05, 0.10, 0.125, 0.15, 0.25, 0.40, 0.60, 0.80]: | |
| cap = max(1, int(frac * n_slots)) | |
| h_lru = lru_like(F, cap) | |
| h_st = static_hits(F, cap, p_global) | |
| h_an = analytic_static(p_global, cap) | |
| h_az = analytic_static(p_zipf, cap) | |
| npin = int(0.75 * cap) | |
| pin = np.argsort(-p_global)[:npin] | |
| h_hy = lru_like(F, cap, pin) | |
| rows.append(dict(frac=frac, cap=cap, lru=h_lru, static=h_st, | |
| hybrid=h_hy, analytic_static=h_an, analytic_zipf=h_az)) | |
| print(f" cap {frac*100:5.1f}% ({cap:5d}): LRU {h_lru:.4f} | static {h_st:.4f} " | |
| f"| hybrid75 {h_hy:.4f} | analytic {h_an:.4f} | analytic-Zipf {h_az:.4f}") | |
| out["policies"] = rows | |
| out["mae_analytic_static"] = float(np.mean( | |
| [abs(r["static"] - r["analytic_static"]) for r in rows])) | |
| out["mae_analytic_zipf"] = float(np.mean( | |
| [abs(r["static"] - r["analytic_zipf"]) for r in rows])) | |
| out["best_gain_hybrid"] = float(max(r["hybrid"] - r["lru"] for r in rows)) | |
| print(f"analytic static model MAE vs measured: " | |
| f"{out['mae_analytic_static']*100:.2f} pp " | |
| f"(Zipf-parameterised: {out['mae_analytic_zipf']*100:.2f} pp)") | |
| json.dump(out, open(os.path.join(RES, "cache_policy.json"), "w"), indent=2) | |
| print("saved results/cache_policy.json") | |
| if __name__ == "__main__": | |
| main() | |