Download code/make_figs.py from mkvn/quantization-cache-amplification: direct link, hf CLI and curl.
- Browser
- Download file 8.52 kB
-
https://huggingface.co/datasets/mkvn/quantization-cache-amplification/resolve/main/code/make_figs.py
- Command line
-
hf download hf://datasets/mkvn/quantization-cache-amplification/code/make_figs.py
-
curl -L -o make_figs.py https://huggingface.co/datasets/mkvn/quantization-cache-amplification/resolve/main/code/make_figs.py
8.52 kB
| import json, os, sys | |
| import numpy as np | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| sys.path.insert(0, os.path.dirname(__file__)) | |
| RES = os.path.join(os.path.dirname(__file__), "..", "results") | |
| FIG = os.path.join(os.path.dirname(__file__), "..", "paper", "figs") | |
| plt.rcParams.update({ | |
| "font.size": 8, "axes.labelsize": 8, "axes.titlesize": 8.5, | |
| "legend.fontsize": 7, "xtick.labelsize": 7, "ytick.labelsize": 7, | |
| "figure.dpi": 200, "savefig.dpi": 200, "axes.grid": True, | |
| "grid.alpha": 0.25, "grid.linewidth": 0.5, "lines.linewidth": 1.3, | |
| "axes.spines.top": False, "axes.spines.right": False, | |
| "font.family": "serif", "mathtext.fontset": "cm", | |
| }) | |
| C = ["#1b3a6b", "#c1440e", "#2e7d32", "#6a1b9a", "#c98a00", "#00695c"] | |
| def load(n): | |
| p = os.path.join(RES, n) | |
| return json.load(open(p)) if os.path.exists(p) else None | |
| def fig_amplification(): | |
| pr = load("projection.json") | |
| if not pr: | |
| return | |
| a = pr["amplification"] | |
| bits = [x["bits"] for x in a] | |
| frac = [x["frac"] * 100 for x in a] | |
| size = [x["model_gb"] for x in a] | |
| fig, ax = plt.subplots(1, 2, figsize=(6.9, 2.35)) | |
| ax[0].plot(bits, size, "o-", color=C[0]) | |
| ax[0].axhline(294, ls="--", c=C[1], lw=1) | |
| ax[0].text(9, 320, "free NVMe (294 GB)", color=C[1], fontsize=6.5) | |
| ax[0].axhline(24, ls=":", c=C[2], lw=1) | |
| ax[0].text(9, 27, "usable DRAM (24 GB)", color=C[2], fontsize=6.5) | |
| ax[0].set_yscale("log"); ax[0].set_xlabel("weight rate (bits/parameter)") | |
| ax[0].set_ylabel("model footprint (GB)") | |
| ax[0].set_title("(a) 1.05T-parameter footprint") | |
| ax[1].plot(bits, frac, "o-", color=C[0]) | |
| ax[1].set_xlabel("weight rate (bits/parameter)") | |
| ax[1].set_ylabel("expert slots resident in 24 GB (%)") | |
| ax[1].set_title("(b) DRAM cache capacity") | |
| for b, f in zip(bits, frac): | |
| if b in (16, 1.5): | |
| ax[1].annotate(f"{f:.1f}%", (b, f), textcoords="offset points", | |
| xytext=(4, 4), fontsize=6.5) | |
| fig.tight_layout(); fig.savefig(os.path.join(FIG, "amplification.pdf")) | |
| plt.close(fig) | |
| def fig_io(): | |
| io = load("io_bench.json") | |
| if not io: | |
| return | |
| fig, ax = plt.subplots(figsize=(3.4, 2.35)) | |
| for i, t in enumerate([1, 2, 4, 8]): | |
| pts = sorted([(r["block_kb"], r["mb_s"] / 1000) for r in io["random"] | |
| if r["threads"] == t]) | |
| ax.plot([p[0] for p in pts], [p[1] for p in pts], "o-", color=C[i], | |
| label=f"{t} thread" + ("s" if t > 1 else ""), ms=3) | |
| ax.set_xscale("log", base=2) | |
| ax.set_xlabel("read block size (KiB)") | |
| ax.set_ylabel("random-read bandwidth (GB/s)") | |
| ax.axhline(io["host"]["seq_read_mb_s"] / 1000, ls="--", c="k", lw=0.9) | |
| ax.text(80, io["host"]["seq_read_mb_s"] / 1000 + 0.15, "sequential", | |
| fontsize=6.5) | |
| ax.legend(loc="lower right") | |
| fig.tight_layout(); fig.savefig(os.path.join(FIG, "io.pdf")); plt.close(fig) | |
| def fig_cache(): | |
| cp = load("cache_policy.json") | |
| cv = load("cache_validation.json") | |
| if not cp or not cv: | |
| return | |
| fr = load("routing_freq.json") | |
| fig, ax = plt.subplots(1, 3, figsize=(6.9, 2.25)) | |
| F = np.array([fr[str(l)] for l in range(cp["layers"])]) | |
| for l in range(0, cp["layers"], 3): | |
| ax[0].plot(np.arange(1, F.shape[1] + 1), np.sort(F[l])[::-1], | |
| color=C[0], alpha=0.35, lw=0.8) | |
| s = cp["zipf_s"] | |
| r = np.arange(1, F.shape[1] + 1) | |
| z = r ** (-s); z = z / z.sum() | |
| ax[0].plot(r, z, "--", color=C[1], lw=1.4, label=f"Zipf $s$={s:.2f}") | |
| ax[0].set_xscale("log"); ax[0].set_yscale("log") | |
| ax[0].set_xlabel("expert rank"); ax[0].set_ylabel("activation probability") | |
| ax[0].set_title("(a) expert popularity"); ax[0].legend() | |
| h = cp["policies"] | |
| x = [r["frac"] * 100 for r in h] | |
| ax[1].plot(x, [r["lru"] * 100 for r in h], "o-", color=C[0], | |
| label="LRU", ms=3) | |
| ax[1].plot(x, [r["static"] * 100 for r in h], "^-", color=C[2], | |
| label="popularity-pinned", ms=3) | |
| ax[1].plot(x, [r["hybrid"] * 100 for r in h], "d-", color=C[4], | |
| label="hybrid (75% pinned)", ms=3) | |
| ax[1].plot(x, [r["analytic_static"] * 100 for r in h], "s:", color=C[1], | |
| label="analytic model", ms=3) | |
| ws = cp["ws_frac"] * 100 | |
| ax[1].axvline(ws, ls="--", c=C[3], lw=1) | |
| ax[1].text(ws + 2, 72, "per-token\nworking set", color=C[3], fontsize=6) | |
| ax[1].set_xlabel("cache capacity (% of expert slots)") | |
| ax[1].set_ylabel("hit rate (%)") | |
| ax[1].set_title("(b) replacement policy"); ax[1].legend(loc="lower right") | |
| d = cv["distinct_per_batch"] | |
| ax[2].plot([r["batch"] for r in d], [r["measured"] for r in d], "o-", | |
| color=C[0], label="measured", ms=3) | |
| ax[2].plot([r["batch"] for r in d], [r["irm_measured_pop"] for r in d], | |
| "s--", color=C[1], label="IRM model", ms=3) | |
| ax[2].set_xscale("log", base=2) | |
| ax[2].set_xlabel("tokens per batch") | |
| ax[2].set_ylabel("distinct experts / layer") | |
| ax[2].set_title("(c) batch amortisation"); ax[2].legend(loc="lower right") | |
| fig.tight_layout(); fig.savefig(os.path.join(FIG, "cache.pdf")); plt.close(fig) | |
| def fig_quality(): | |
| import glob | |
| runs = [] | |
| for p in glob.glob(os.path.join(RES, "quant_*.json")): | |
| runs.append(json.load(open(p))) | |
| if not runs: | |
| return | |
| fig, ax = plt.subplots(figsize=(5.0, 3.05)) | |
| base = [r for r in runs if r["config"].get("tag", "").startswith("rtn")] | |
| ours = sorted([r for r in runs if r["config"]["tag"].startswith("main")], | |
| key=lambda r: r["avg_bits"]) | |
| abl = sorted([r for r in runs if r["config"]["tag"].startswith("northt")], | |
| key=lambda r: r["avg_bits"]) | |
| noldl = sorted([r for r in runs if r["config"]["tag"].startswith("noldlq")], | |
| key=lambda r: r["avg_bits"]) | |
| freq = sorted([r for r in runs if r["config"]["tag"].startswith("freq")], | |
| key=lambda r: r["avg_bits"]) | |
| fp = load("fp16_ppl.json") | |
| for grp, lab, st, c in [(ours, "RVQ + RHT + LDLQ (ours)", "o-", C[0]), | |
| (freq, "+ frequency-conditioned alloc.", "D-", C[4]), | |
| (noldl, "no LDLQ (data-free)", "s--", C[1]), | |
| (abl, "no incoherence processing", "^--", C[2]), | |
| (base, "RTN uniform", "v:", C[3])]: | |
| if grp: | |
| ax.plot([r["avg_bits"] for r in grp], [r["ppl"] for r in grp], st, | |
| label=lab, color=c, ms=3) | |
| if fp: | |
| ax.axhline(fp["ppl"], ls="--", c="k", lw=0.9) | |
| ax.text(3.32, fp["ppl"] * 1.12, f"bf16 = {fp['ppl']:.2f}", fontsize=6.5, | |
| ha="right", va="bottom") | |
| ax.set_yscale("log") | |
| ax.set_xlim(0.85, 3.45) | |
| ax.set_xlabel("average weight rate (bits/parameter)") | |
| ax.set_ylabel("WikiText-2 perplexity") | |
| ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.24), ncol=2, | |
| frameon=False, fontsize=7) | |
| fig.tight_layout() | |
| fig.savefig(os.path.join(FIG, "quality.pdf"), bbox_inches="tight") | |
| plt.close(fig) | |
| def fig_throughput(): | |
| pr = load("projection.json") | |
| if not pr: | |
| return | |
| fig, ax = plt.subplots(1, 2, figsize=(6.9, 2.35)) | |
| s = pr["sensitivity_1p5bit"] | |
| ax[0].plot([x["hit_rate"] * 100 for x in s], [x["tok_s"] for x in s], "-", | |
| color=C[0]) | |
| hr = pr["projection"][0]["hit_rate"] * 100 | |
| ax[0].set_xlabel("expert-cache hit rate (%)") | |
| ax[0].set_ylabel("decode throughput (tokens/s)") | |
| ax[0].set_yscale("log") | |
| ax[0].set_title("(a) sensitivity at 1.5 bit, batch 1") | |
| rows = pr["projection"] | |
| bits = sorted(set(r["rate_bits"] for r in rows)) | |
| for i, B in enumerate([1, 8, 32]): | |
| y = [next(r["tok_s"] for r in rows if r["rate_bits"] == b and r["batch"] == B) | |
| for b in bits] | |
| ax[1].plot(bits, y, "o-", color=C[i], label=f"batch {B}", ms=3) | |
| ax[1].set_xlabel("weight rate (bits/parameter)") | |
| ax[1].set_ylabel("decode throughput (tokens/s)") | |
| ax[1].set_yscale("log"); ax[1].legend() | |
| ax[1].set_title("(b) projected 1.05T throughput") | |
| fig.tight_layout(); fig.savefig(os.path.join(FIG, "throughput.pdf")) | |
| plt.close(fig) | |
| if __name__ == "__main__": | |
| os.makedirs(FIG, exist_ok=True) | |
| for f in [fig_amplification, fig_io, fig_cache, fig_quality, fig_throughput]: | |
| try: | |
| f() | |
| print("ok", f.__name__) | |
| except Exception as e: | |
| print("skip", f.__name__, type(e).__name__, e) | |