"""Render the Llama LR sweep figure (paper fig 8). ΔAccuracy of the restored adapter vs the quantized baseline, per learning rate. Zero line is the "no effect" reference — below zero = restoration made it worse. The figure is laid out so the story ("lower LR recovers more of the gap") reads in one pass. """ import argparse import json import os import re import sys import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) mpl.rcParams.update({ "font.family": "sans-serif", "font.sans-serif": ["Inter", "Helvetica Neue", "Arial", "DejaVu Sans"], "font.size": 9, "axes.labelsize": 10, "xtick.labelsize": 8.5, "ytick.labelsize": 8.5, "legend.fontsize": 8, "legend.frameon": False, "figure.dpi": 200, "savefig.dpi": 400, "savefig.bbox": "tight", "pdf.fonttype": 42, "ps.fonttype": 42, "axes.linewidth": 0.7, "axes.spines.top": False, "axes.spines.right": False, }) LR_PARSE = re.compile(r"^lr(.+)$") METHOD_COLOR = {"awq_w4": "#4E79A7", "gptq_w4": "#E15759", "bnb_nf4_w4": "#59A14F"} GAIN = "#2E7D32" LOSS = "#C03A2B" def _load_outcomes(jsonl): if not os.path.exists(jsonl): return None out = {} with open(jsonl) as f: for line in f: t = json.loads(line) out[t["problem_id"]] = 1.0 if t.get("is_correct_final") else 0.0 return out def paired_delta_ci(base_out, rest_out, n_boot=5000): ids = sorted(set(base_out) & set(rest_out)) if not ids: return None b = np.array([base_out[i] for i in ids]) r = np.array([rest_out[i] for i in ids]) n = len(ids) rng = np.random.default_rng(0) deltas = np.empty(n_boot) for i in range(n_boot): idx = rng.integers(0, n, size=n) deltas[i] = r[idx].mean() - b[idx].mean() obs = float(r.mean() - b.mean()) return obs * 100, float(np.percentile(deltas, 2.5)) * 100, float(np.percentile(deltas, 97.5)) * 100 def _tag_to_lr(tag: str) -> float: # lr5e_5 -> 5e-5 etc. The sweep script encodes "." as "_" and "-" as "_". s = tag.replace("__", "-").replace("_", "-") try: return float(s) except ValueError: return float("nan") def main(): parser = argparse.ArgumentParser() parser.add_argument("--sweep-root", required=True) parser.add_argument("--model", required=True) parser.add_argument("--quant", required=True) parser.add_argument("--benchmark", required=True) parser.add_argument("--metrics", required=True) parser.add_argument("--output", required=True) args = parser.parse_args() base_diag = os.path.join("results", "diagnosis", args.quant, args.model, f"{args.benchmark}_run0.jsonl") base_out = _load_outcomes(base_diag) if base_out is None: print(f" [ERROR] base diagnosed jsonl missing: {base_diag}") return rows = [] for entry in sorted(os.listdir(args.sweep_root)): m = LR_PARSE.match(entry) if not m: continue diag = os.path.join(args.sweep_root, entry, "diagnosis", f"{args.benchmark}_run0.jsonl") rest_out = _load_outcomes(diag) if rest_out is None: continue ci = paired_delta_ci(base_out, rest_out) if ci is None: continue lr_val = _tag_to_lr(m.group(1)) rows.append((lr_val, ci)) if not rows: print("No LR sweep data found.") return rows.sort(key=lambda r: r[0]) lrs = [r[0] for r in rows] deltas = [r[1][0] for r in rows] los = [r[1][1] for r in rows] his = [r[1][2] for r in rows] fig, ax = plt.subplots(figsize=(5.3, 3.2), constrained_layout=True) # Shade the "below-zero = regression" region in a faint red. ys_needed = deltas + los + his + [0] ymin, ymax = min(ys_needed) - 3, max(ys_needed) + 4 ax.axhspan(ymin, 0, color=LOSS, alpha=0.06, zorder=0) ax.axhspan(0, ymax, color=GAIN, alpha=0.06, zorder=0) # Zero reference line. ax.axhline(0, color="#555555", linewidth=0.8, zorder=1) x = np.arange(len(lrs)) for i, (d, lo, hi) in enumerate(zip(deltas, los, his)): color = GAIN if d >= 0 else LOSS ax.plot([x[i], x[i]], [lo, hi], color=color, linewidth=1.4, alpha=0.6, zorder=2, solid_capstyle="butt") ax.plot(x[i], d, "o", markersize=8, color=color, markeredgecolor="white", markeredgewidth=1.2, zorder=3) ax.annotate(f"{d:+.1f} pp", xy=(x[i], d), xytext=(0, 12 if d >= 0 else -16), textcoords="offset points", ha="center", va="bottom" if d >= 0 else "top", fontsize=9.5, color=color, fontweight="bold") # Edge-of-plot labels for the shaded regions. ax.text(-0.45, ymax * 0.92, "restoration helps", ha="left", va="top", fontsize=8, color=GAIN, style="italic") ax.text(-0.45, ymin + 0.5, "restoration hurts", ha="left", va="bottom", fontsize=8, color=LOSS, style="italic") ax.set_xticks(x) ax.set_xticklabels([f"{lr:g}" for lr in lrs]) ax.set_xlabel("QLoRA learning rate") ax.set_ylabel(r"$\Delta$Accuracy vs. quantized baseline (pp)") ax.yaxis.grid(True, linewidth=0.4, color="#DDDDDD") ax.set_axisbelow(True) ax.set_ylim(ymin, ymax) ax.set_xlim(-0.55, len(lrs) - 0.45) 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=8, color="#555") os.makedirs(os.path.dirname(args.output), exist_ok=True) fig.savefig(args.output) plt.close(fig) print(f" Paper fig 8 (Llama LR sweep) saved: {args.output}") if __name__ == "__main__": main()