Download code/project_1t.py from mkvn/quantization-cache-amplification: direct link, hf CLI and curl.
- Browser
- Download file 7.57 kB
-
https://huggingface.co/datasets/mkvn/quantization-cache-amplification/resolve/main/code/project_1t.py
- Command line
-
hf download hf://datasets/mkvn/quantization-cache-amplification/code/project_1t.py
-
curl -L -o project_1t.py https://huggingface.co/datasets/mkvn/quantization-cache-amplification/resolve/main/code/project_1t.py
7.57 kB
| """Projection of a 1T-parameter sparse MoE onto the measured machine. | |
| Methodology: every hardware quantity is measured on the host; the expert-cache | |
| behaviour is modelled with the Che approximation for LRU under an | |
| independent-reference model, *validated against the real OLMoE trace at E=64* | |
| before being extrapolated to the 1T configuration's E=320. | |
| """ | |
| import json, os, sys | |
| import numpy as np | |
| RES = os.path.join(os.path.dirname(__file__), "..", "results") | |
| # ---------------------------------------------------------------- 1T config | |
| T1 = dict(name="T1-1046B", layers=64, d_model=8192, n_experts=320, topk=8, | |
| d_ff_expert=2048, n_shared=1, kv_dim=1024, vocab=129280) | |
| def config_params(c): | |
| attn = 2 * c["d_model"] ** 2 + 2 * c["d_model"] * c["kv_dim"] | |
| expert = 3 * c["d_model"] * c["d_ff_expert"] | |
| per_layer = attn + expert * (c["n_experts"] + c["n_shared"]) | |
| total = per_layer * c["layers"] + 2 * c["vocab"] * c["d_model"] | |
| active = (attn + expert * (c["topk"] + c["n_shared"])) * c["layers"] \ | |
| + c["vocab"] * c["d_model"] | |
| return dict(total=total, active=active, expert=expert, | |
| attn_total=attn * c["layers"], | |
| shared_total=expert * c["n_shared"] * c["layers"], | |
| routed_total=expert * c["n_experts"] * c["layers"], | |
| n_slots=c["n_experts"] * c["layers"]) | |
| # ---------------------------------------------------------------- cache model | |
| def che_hit_rate(p, capacity): | |
| """LRU hit rate under IRM via Che's approximation.""" | |
| p = np.asarray(p, dtype=np.float64) | |
| p = p / p.sum() | |
| if capacity >= len(p): | |
| return 1.0 | |
| if capacity <= 0: | |
| return 0.0 | |
| lo, hi = 1e-6, 1e12 | |
| for _ in range(200): | |
| t = (lo * hi) ** 0.5 | |
| occ = (1.0 - np.exp(-p * t)).sum() | |
| if occ < capacity: | |
| lo = t | |
| else: | |
| hi = t | |
| t = (lo * hi) ** 0.5 | |
| return float((p * (1.0 - np.exp(-p * t))).sum()) | |
| def zipf_fit(freq): | |
| """Least-squares Zipf exponent of a measured popularity vector.""" | |
| f = np.sort(np.asarray(freq, dtype=np.float64))[::-1] | |
| f = f[f > 0] | |
| r = np.arange(1, len(f) + 1) | |
| a, _ = np.polyfit(np.log(r), np.log(f), 1) | |
| return float(-a) | |
| def zipf_pmf(n, s): | |
| r = np.arange(1, n + 1, dtype=np.float64) | |
| p = r ** (-s) | |
| return p / p.sum() | |
| def distinct_per_layer(p, n_draws): | |
| """Expected distinct experts touched by n_draws independent selections.""" | |
| p = np.asarray(p, dtype=np.float64) | |
| p = p / p.sum() | |
| return float((1.0 - (1.0 - p) ** n_draws).sum()) | |
| # ---------------------------------------------------------------- throughput | |
| def io_bandwidth(io, block_bytes, threads=4): | |
| """Interpolate measured unbuffered random-read bandwidth at a block size.""" | |
| pts = [(r["block_kb"] * 1024, r["mb_s"]) for r in io["random"] | |
| if r["threads"] == threads] | |
| pts.sort() | |
| xs = np.log2([p[0] for p in pts]); ys = [p[1] for p in pts] | |
| return float(np.interp(np.log2(block_bytes), xs, ys)) * 1e6 | |
| def analytic_static(p, cap): | |
| """Hit rate of a popularity-pinned cache: mass of the top-`cap` slots. | |
| Exact given the popularity vector (validated to 0.00 pp on the real trace).""" | |
| q = np.sort(np.asarray(p, dtype=np.float64))[::-1] | |
| q = q / q.sum() | |
| return float(q[:min(cap, len(q))].sum()) | |
| def hit_rate_for(cfg, cap_slots, zipf_s, bias_pp=0.0): | |
| """Popularity-pinned hit rate for a configuration with E experts per layer.""" | |
| p = np.tile(zipf_pmf(cfg["n_experts"], zipf_s) / cfg["layers"], cfg["layers"]) | |
| return max(0.0, analytic_static(p, cap_slots) - bias_pp / 100.0) | |
| def project(rate_bits, hit_rate, io, cfg=T1, dram_gb=24.0, vram_gb=3.4, | |
| batch=1, zipf_s=None): | |
| P = config_params(cfg) | |
| Bpp = rate_bits / 8.0 | |
| expert_bytes = P["expert"] * Bpp | |
| total_bytes = P["total"] * Bpp | |
| resident = (P["attn_total"] + P["shared_total"]) * Bpp | |
| vram_free = max(0.0, vram_gb * 1e9 - resident) | |
| dram_slots = int(dram_gb * 1e9 // expert_bytes) | |
| vram_slots = int(vram_free // expert_bytes) | |
| bw = io_bandwidth(io, expert_bytes) | |
| if zipf_s is not None: | |
| p = zipf_pmf(cfg["n_experts"], zipf_s) | |
| u = distinct_per_layer(p, cfg["topk"] * batch) | |
| else: | |
| u = cfg["topk"] * batch | |
| fetch_per_token = cfg["layers"] * u * (1.0 - hit_rate) / batch | |
| bytes_per_token = fetch_per_token * expert_bytes | |
| t_io = bytes_per_token / bw | |
| return dict(rate_bits=rate_bits, hit_rate=hit_rate, batch=batch, | |
| total_gb=total_bytes / 1e9, expert_mb=expert_bytes / 1e6, | |
| dram_slots=dram_slots, vram_slots=vram_slots, | |
| cache_frac=dram_slots / P["n_slots"], | |
| resident_gb=resident / 1e9, | |
| io_bw_gbs=bw / 1e9, | |
| bytes_per_token_mb=bytes_per_token / 1e6, | |
| tok_s=1.0 / t_io if t_io > 0 else float("inf")) | |
| def main(): | |
| io = json.load(open(os.path.join(RES, "io_bench.json"))) | |
| P = config_params(T1) | |
| out = {"config": T1, "params": {k: float(v) for k, v in P.items()}} | |
| print(f"{T1['name']}: {P['total']/1e9:.1f}B total, {P['active']/1e9:.1f}B active/token, " | |
| f"{P['n_slots']} expert slots") | |
| # ---- cache-capacity amplification from quantisation | |
| amp = [] | |
| for r in [16, 4, 3, 2, 1.5, 1.0]: | |
| eb = P["expert"] * r / 8 | |
| amp.append(dict(bits=r, model_gb=P["total"] * r / 8 / 1e9, | |
| expert_mb=eb / 1e6, | |
| dram_experts=int(24e9 // eb), | |
| frac=int(24e9 // eb) / P["n_slots"])) | |
| out["amplification"] = amp | |
| print("\nrate model_GB expert_MB experts_in_24GB cache_frac") | |
| for a in amp: | |
| print(f"{a['bits']:>4.1f} {a['model_gb']:8.0f} {a['expert_mb']:9.2f} " | |
| f"{a['dram_experts']:15d} {a['frac']*100:9.2f}%") | |
| # ---- cache policy calibrated on the measured trace, then extrapolated | |
| cp = json.load(open(os.path.join(RES, "cache_policy.json"))) | |
| s_hat = cp["zipf_s"] | |
| bias = cp["mae_analytic_zipf"] * 100 # Zipf-fit optimism, in points | |
| out["zipf_s"] = s_hat | |
| out["zipf_bias_pp"] = bias | |
| ws = T1["topk"] * T1["layers"] # per-token working set, in slots | |
| out["token_working_set"] = ws | |
| print(f"\nper-token working set: {ws} expert slots; Zipf s={s_hat:.3f}; " | |
| f"Zipf-fit optimism {bias:.2f} pp") | |
| rows = [] | |
| for r in [1.0, 1.5, 2.0, 3.0, 4.0, 16.0]: | |
| eb = P["expert"] * r / 8 | |
| cap = int(24e9 // eb) | |
| h = hit_rate_for(T1, cap, s_hat, bias_pp=bias) | |
| for B in [1, 8, 32]: | |
| x = project(r, h, io, batch=B, zipf_s=s_hat) | |
| x["cap_slots"] = cap | |
| x["lru_viable"] = cap >= ws | |
| rows.append(x) | |
| out["projection"] = rows | |
| print("\nbits batch slots LRUok hit% model_GB expert_MB IO_GB/s MB/token tok/s") | |
| for x in rows: | |
| print(f"{x['rate_bits']:>4.1f} {x['batch']:>5d} {x['cap_slots']:>5d} " | |
| f"{str(x['lru_viable']):>5} {x['hit_rate']*100:4.1f} " | |
| f"{x['total_gb']:8.0f} {x['expert_mb']:9.2f} {x['io_bw_gbs']:7.2f} " | |
| f"{x['bytes_per_token_mb']:8.1f} {x['tok_s']:6.2f}") | |
| # ---- sensitivity: tok/s across the whole hit-rate range at 1.5 bit | |
| sens = [project(1.5, float(h), io, batch=1, zipf_s=s_hat) | |
| for h in np.arange(0.0, 0.99, 0.05)] | |
| out["sensitivity_1p5bit"] = sens | |
| json.dump(out, open(os.path.join(RES, "projection.json"), "w"), indent=2) | |
| print("\nsaved results/projection.json") | |
| if __name__ == "__main__": | |
| main() | |