| """Render the dataset-size ablation figure (paper fig 6). |
| |
| Reads restoration results produced by run_ablation.sh and plots accuracy of |
| the restored model as the silver-bullet dataset size N varies, with two |
| reference lines: |
| |
| - quantized baseline (no restoration) — from results/metrics/ |
| - FP16 upper bound (if available) — from results/segmented/fp16/ |
| |
| Style matches the other paper figures (Q1 conventions — Type-42 fonts, muted |
| Tableau palette, no inline title). |
| """ |
|
|
| import argparse |
| import json |
| import os |
| import re |
| from typing import List, Optional |
|
|
| import matplotlib as mpl |
| import matplotlib.pyplot as plt |
| import numpy as np |
|
|
|
|
| |
| |
| |
|
|
| mpl.rcParams.update({ |
| "font.family": "sans-serif", |
| "font.sans-serif": ["Inter", "Helvetica Neue", "Arial", "DejaVu Sans"], |
| "font.size": 8, |
| "axes.titlesize": 9, |
| "axes.labelsize": 9, |
| "xtick.labelsize": 7, |
| "ytick.labelsize": 7, |
| "legend.fontsize": 7, |
| "legend.frameon": False, |
| "figure.dpi": 200, |
| "savefig.dpi": 400, |
| "savefig.bbox": "tight", |
| "pdf.fonttype": 42, |
| "ps.fonttype": 42, |
| "axes.linewidth": 0.6, |
| "axes.edgecolor": "#333333", |
| "axes.spines.top": False, |
| "axes.spines.right": False, |
| "xtick.major.width": 0.6, |
| "ytick.major.width": 0.6, |
| "grid.color": "#EAEAEA", |
| "grid.linewidth": 0.5, |
| }) |
|
|
| METHOD_COLOR = { |
| "awq_w4": "#4E79A7", |
| "gptq_w4": "#E15759", |
| "bnb_nf4_w4": "#59A14F", |
| } |
| FP16_COLOR = "#333333" |
| BASE_COLOR = "#888888" |
| GREY_TEXT = "#555555" |
|
|
|
|
| |
| |
| |
|
|
| def accuracy_from_diagnosed(jsonl_path: str) -> Optional[float]: |
| if not os.path.exists(jsonl_path): |
| return None |
| n, c = 0, 0 |
| with open(jsonl_path) as f: |
| for line in f: |
| t = json.loads(line) |
| n += 1 |
| if t.get("is_correct_final"): |
| c += 1 |
| return c / n if n else None |
|
|
|
|
| def ci_from_diagnosed(jsonl_path: str, n_boot: int = 2000) -> Optional[tuple]: |
| """Return (acc, ci_lo, ci_hi) from per-problem bootstrap.""" |
| if not os.path.exists(jsonl_path): |
| return None |
| vec = [] |
| with open(jsonl_path) as f: |
| for line in f: |
| t = json.loads(line) |
| vec.append(1.0 if t.get("is_correct_final") else 0.0) |
| if not vec: |
| return None |
| vec = np.array(vec) |
| rng = np.random.default_rng(0) |
| samples = np.empty(n_boot) |
| for i in range(n_boot): |
| idx = rng.integers(0, len(vec), size=len(vec)) |
| samples[i] = vec[idx].mean() |
| lo, hi = np.percentile(samples, [2.5, 97.5]) |
| return float(vec.mean()), float(lo), float(hi) |
|
|
|
|
| def load_baseline_acc(metrics_dir, model, quant, bench): |
| path = os.path.join(metrics_dir, f"{model}_{quant}_{bench}_run0_metrics.json") |
| if not os.path.exists(path): |
| return None |
| with open(path) as f: |
| return json.load(f).get("accuracy") |
|
|
|
|
| def load_fp16_acc_from_segmented(segmented_dir, model, bench) -> Optional[float]: |
| """FP16 accuracy from segmented jsonl. |
| |
| Segment doesn't write `is_correct_final`, so we compute accuracy ourselves |
| by comparing `final_answer` to the benchmark's gold answer. Returns None |
| if anything is missing — caller treats None as "skip the FP16 reference |
| line" rather than silently plotting 0%.""" |
| path = os.path.join(segmented_dir, "fp16", model, f"{bench}_run0.jsonl") |
| if not os.path.exists(path): |
| return None |
|
|
| |
| try: |
| from datasets import load_dataset |
| if bench == "gsm8k": |
| ds = load_dataset("openai/gsm8k", "main", split="test") |
| golds = {f"gsm8k_{i}": ex["answer"].split("####")[-1].strip() |
| for i, ex in enumerate(ds)} |
| elif bench == "math500": |
| ds = load_dataset("HuggingFaceH4/MATH-500", split="test") |
| golds = {f"math500_{i}": ex["answer"] for i, ex in enumerate(ds)} |
| elif bench == "gpqa": |
| ds = load_dataset("Idavidrein/gpqa", "gpqa_diamond", split="train") |
| golds = {f"gpqa_{i}": ex.get("Correct Answer", "") for i, ex in enumerate(ds)} |
| else: |
| return None |
| except Exception: |
| return None |
|
|
| def norm(s: str) -> str: |
| s = (s or "").strip().strip("$").replace(" ", "").replace(",", "") |
| return s.lower() |
|
|
| n, c = 0, 0 |
| with open(path) as f: |
| for line in f: |
| t = json.loads(line) |
| pid = t.get("problem_id") |
| gold = golds.get(pid, "") |
| pred = t.get("final_answer", "") |
| n += 1 |
| if gold and pred and norm(gold) == norm(pred): |
| c += 1 |
| return c / n if n else None |
|
|
|
|
| |
| |
| |
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--ablation-root", required=True, |
| help="results/ablation/<model>_<quant>") |
| parser.add_argument("--model", required=True) |
| parser.add_argument("--quant", required=True) |
| parser.add_argument("--benchmark", required=True) |
| parser.add_argument("--metrics", required=True, |
| help="results/metrics — used for the quantized baseline") |
| parser.add_argument("--segmented", default="results/segmented", |
| help="results/segmented — used for FP16 upper bound (optional)") |
| parser.add_argument("--output", required=True) |
| args = parser.parse_args() |
|
|
| |
| Ns = [] |
| accs, ci_los, ci_his = [], [], [] |
| for entry in sorted(os.listdir(args.ablation_root)): |
| m = re.match(r"n(\d+)$", entry) |
| if not m: |
| continue |
| N = int(m.group(1)) |
| diag = os.path.join(args.ablation_root, entry, "diagnosis", |
| f"{args.benchmark}_run0.jsonl") |
| ci = ci_from_diagnosed(diag) |
| if ci is None: |
| print(f" [SKIP] missing diagnosed jsonl for N={N}: {diag}") |
| continue |
| Ns.append(N) |
| accs.append(ci[0]) |
| ci_los.append(ci[1]) |
| ci_his.append(ci[2]) |
|
|
| if not Ns: |
| print(f"No ablation data found in {args.ablation_root}") |
| return |
|
|
| sort_idx = np.argsort(Ns) |
| Ns = [Ns[i] for i in sort_idx] |
| accs = [accs[i] for i in sort_idx] |
| ci_los = [ci_los[i] for i in sort_idx] |
| ci_his = [ci_his[i] for i in sort_idx] |
|
|
| base_acc = load_baseline_acc(args.metrics, args.model, args.quant, args.benchmark) |
| |
| |
| |
| try: |
| from scripts.eval_accuracy import accuracy as _lv_accuracy |
| except ImportError: |
| import sys as _sys |
| _sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| from eval_accuracy import accuracy as _lv_accuracy |
| fp16_jsonl = os.path.join(args.segmented, "fp16", args.model, |
| f"{args.benchmark}_run0.jsonl") |
| fp16_acc = _lv_accuracy(fp16_jsonl, args.benchmark) |
|
|
| |
| fig, ax = plt.subplots(figsize=(4.5, 3.0), constrained_layout=True) |
|
|
| method_color = METHOD_COLOR.get(args.quant, "#4E79A7") |
|
|
| |
| acc_pp = [a * 100 for a in accs] |
| lo_pp = [a * 100 for a in ci_los] |
| hi_pp = [a * 100 for a in ci_his] |
|
|
| |
| |
| |
| for x, y, lo, hi in zip(Ns, acc_pp, lo_pp, hi_pp): |
| ax.plot([x, x], [lo, hi], color=method_color, linewidth=1.1, |
| alpha=0.55, zorder=2, solid_capstyle="butt") |
|
|
| ax.plot(Ns, acc_pp, "-", color=method_color, linewidth=1.6, |
| zorder=3, label="Restored") |
| ax.plot(Ns, acc_pp, "o", color=method_color, markersize=5.5, |
| markeredgecolor="white", markeredgewidth=1.0, zorder=4) |
|
|
| |
| if base_acc is not None: |
| ax.axhline(base_acc * 100, color=BASE_COLOR, linestyle=(0, (5, 3)), |
| linewidth=0.9, alpha=0.9, label="Quantized (no rest.)") |
|
|
| |
| if fp16_acc is not None and fp16_acc > 0: |
| ax.axhline(fp16_acc * 100, color=FP16_COLOR, linestyle=(0, (1, 2)), |
| linewidth=0.9, alpha=0.9, label="FP16") |
|
|
| |
| ax.set_xscale("log") |
| ax.set_xticks(Ns) |
| ax.set_xticklabels([str(n) for n in Ns]) |
| ax.get_xaxis().set_minor_locator(mpl.ticker.NullLocator()) |
| ax.set_xlabel("Silver-bullet dataset size (samples)") |
| ax.set_ylabel("Accuracy (%)") |
| ax.yaxis.grid(True) |
| ax.set_axisbelow(True) |
|
|
| |
| |
| |
| ys = lo_pp + hi_pp + acc_pp |
| if base_acc is not None: |
| ys.append(base_acc * 100) |
| if fp16_acc is not None and fp16_acc > 0: |
| ys.append(fp16_acc * 100) |
| ymin = min(ys) - 3.0 |
| ymax = max(ys) + 3.5 |
| ax.set_ylim(ymin, ymax) |
|
|
| |
| for x, y in zip(Ns, acc_pp): |
| ax.annotate(f"{y:.1f}", xy=(x, y), xytext=(0, -12), |
| textcoords="offset points", |
| ha="center", va="top", fontsize=7, color=method_color) |
|
|
| |
| pretty_quant = {"awq_w4": "AWQ w4", "gptq_w4": "GPTQ w4", "bnb_nf4_w4": "BnB NF4"}.get(args.quant, args.quant) |
| ax.text(1.0, 1.02, |
| f"{args.model} · {pretty_quant} · {args.benchmark}", |
| transform=ax.transAxes, ha="right", va="bottom", |
| fontsize=7.5, color=GREY_TEXT) |
|
|
| |
| |
| |
| |
| if base_acc is not None and len(acc_pp) > 0: |
| gain_at_min = acc_pp[0] - base_acc * 100 |
| ax.annotate( |
| f"+{gain_at_min:.1f} pp over\nquantized baseline\nalready at N={Ns[0]}", |
| xy=(Ns[0], acc_pp[0]), |
| xytext=(0.28, 0.78), textcoords="axes fraction", |
| ha="left", va="top", fontsize=7, color=method_color, |
| arrowprops=dict(arrowstyle="->", color=method_color, |
| linewidth=0.7, alpha=0.7, |
| shrinkA=2, shrinkB=4, |
| connectionstyle="arc3,rad=-0.25")) |
|
|
| |
| |
| ax.legend(loc="center left", bbox_to_anchor=(1.02, 0.5), |
| handlelength=2.0, handletextpad=0.5, |
| borderpad=0.3, labelspacing=0.5) |
|
|
| os.makedirs(os.path.dirname(args.output), exist_ok=True) |
| fig.savefig(args.output) |
| plt.close(fig) |
| print(f" Paper fig 6 (ablation) saved: {args.output}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|